From 0bedcdeb370ef1970bdaf2abe482c549e537c170 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 27 Sep 2026 20:55:49 +0200 Subject: [PATCH 01/64] Add TypeScript Idunn runtime presence publisher --- .../cultnet-ts/src/idunn-runtime-authority.ts | 717 ++++++++++++++++++ packages/cultnet-ts/src/index.ts | 14 + .../test/idunn-runtime-authority.test.ts | 140 ++++ 3 files changed, 871 insertions(+) create mode 100644 packages/cultnet-ts/src/idunn-runtime-authority.ts create mode 100644 packages/cultnet-ts/test/idunn-runtime-authority.test.ts diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts new file mode 100644 index 00000000..28e61e97 --- /dev/null +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -0,0 +1,717 @@ +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { decode, encode } from "@msgpack/msgpack"; + +import { + GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, + GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME, + IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, + runtimePresenceActivationSigningMessage, + runtimePresenceProofPayload, + runtimePresenceProviderSigningMessage, + encodeRuntimePresenceHealth, + type RuntimePresenceHealth, +} from "./runtime-presence-health"; +import { encodeCultNetMessageForWire } from "./contracts"; +import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; +import type { CultNetRudpPacket } from "./rudp"; +import dgram from "node:dgram"; + +export const IDUNN_EXPECTED_INCARNATION_SCHEMA = "idunn.expected_incarnation.v2"; +export const IDUNN_RUNTIME_ACTIVATION_SCHEMA = "idunn.runtime_activation.v2"; +export const IDUNN_PROCESS_WRITE_LEASE_SCHEMA = "idunn.process_write_lease.v1"; +export const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE"; +export const IDUNN_RUNTIME_BUNDLE_ENVIRONMENT = "GAMECULT_IDUNN_RUNTIME_BUNDLE"; +export const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT = "GAMECULT_IDUNN_CANDIDATE_BIND"; + +const PROVIDER_ID_DOMAIN = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8"); +const PROVIDER_PROTECTOR_CONTEXT = "gamecult-provider-health-identity-v1"; +const ACTIVATION_ID_DOMAIN = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8"); +const CULTCACHE_STORE_FORMAT = "cultcache.store.v1"; +const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex"); +const MAX_RECENT_WARMING_PROOFS = 64; +const authorityKeys = new WeakMap(); + +type ExpectedIncarnation = { + schemaVersion: string; + target: string; + planId: string; + incarnationId: string; + sealedReleaseId: string; + sourceRepository: string; + sourceRevision: string; + recipeSha256: string; + runtimeId: string; + expectedSignerIdentityId: string; + healthContract: string; + artifactSha256: string; + stateSchemaGeneration: string | null; + stateContractSha256: string | null; + writeLeaseRequired: boolean; + route: { routeId: string; transport: string; stableEndpoint: string; candidateEndpoint: string } | null; + capabilities: Array<{ capability: string; schema: string; compatibility: string; minimumCapacity: number }>; + dependencies: Array<{ kind: string; capability: string; schema: string; compatibility: string; providerEndpoint: string | null }>; + canonicalBytes: Buffer; + canonicalSha256: string; +}; + +type RuntimeActivation = { + schemaVersion: string; + expectedProjectionSha256: string; + runtimeId: string; + runtimeInstanceId: string; + activationSignerIdentityId: string; + activationSignerPublicKey: Buffer; + canonicalSha256: string; +}; + +export type IdunnRuntimeAuthority = { + expected: ExpectedIncarnation; + activation: RuntimeActivation; + providerSignerIdentityId: string; + activationSignerIdentityId: string; + boundEndpoint: string; + processWriteLeasePath?: string; +}; + +export type IdunnRuntimePresencePublisher = { + readonly runtimeId: string; + readonly runtimeInstanceId: string; + readonly requiresWriteLease: boolean; + publish(state: RuntimePresenceHealth["state"], detail: string): Promise; + waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; + assertWriteLease(): Promise; +}; + +export type IdunnRuntimePresencePublisherOptions = { + authority: IdunnRuntimeAuthority; + endpoint: string; + healthContract: string; + capabilities: RuntimePresenceHealth["capabilities"]; +}; + +/** + * Loads the root-provisioned Idunn bundle and parent-only signing descriptors. + * The expected record and activation witness are accepted only when their + * exact positional contracts and mutual incarnation binding agree. + */ +export function loadIdunnRuntimeAuthorityFromEnvironment( + target: string, + healthContract: string, + odinEndpoint: string, +): IdunnRuntimeAuthority { + const bundle = requiredEnvironment(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT); + const expected = readAuthorityRecord(path.join(bundle, "expected.cc"), "idunn.expected_incarnation", IDUNN_EXPECTED_INCARNATION_SCHEMA); + const activation = readAuthorityRecord(path.join(bundle, "activation.cc"), "idunn.runtime_activation", IDUNN_RUNTIME_ACTIVATION_SCHEMA); + const expectedValue = decodeExpected(expected.payload); + const activationValue = decodeActivation(activation.payload); + if (expectedValue.target !== target || expectedValue.healthContract !== healthContract) { + throw new Error("Idunn Expected target or health contract does not match this runtime."); + } + const odinDependency = expectedValue.dependencies.find((dependency) => dependency.kind === "shared-infrastructure" + && dependency.capability === "odin.verse-rendezvous"); + if (!odinDependency || normalizeRudpEndpoint(odinDependency.providerEndpoint ?? "") !== normalizeRudpEndpoint(odinEndpoint)) { + throw new Error("Configured Odin endpoint does not match Idunn Expected dependency authority."); + } + if (activationValue.expectedProjectionSha256 !== expectedValue.canonicalSha256 + || activationValue.runtimeId !== expectedValue.runtimeId) { + throw new Error("Idunn Activation does not bind this exact Expected incarnation."); + } + + const descriptors = inheritedDescriptorMap(); + const providerCredential = descriptors.get(GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME); + const activationCredential = descriptors.get(IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME); + if (providerCredential === undefined || activationCredential === undefined) { + throw new Error("Idunn runtime-presence signing descriptors are missing."); + } + + const providerPrivateKey = openProviderHealthIdentity(readDescriptor(providerCredential)); + const activationSeed = readDescriptor(activationCredential); + if (activationSeed.length !== 32) throw new Error("Idunn activation credential must be exactly 32 bytes."); + const activationPrivateKey = privateKeyFromSeed(activationSeed); + activationSeed.fill(0); + const activationPublicKey = rawEd25519PublicKey(crypto.createPublicKey(activationPrivateKey)); + const activationSignerIdentityId = sha256Hex(Buffer.concat([ACTIVATION_ID_DOMAIN, activationPublicKey])); + if (activationSignerIdentityId !== activationValue.activationSignerIdentityId + || !activationPublicKey.equals(activationValue.activationSignerPublicKey)) { + throw new Error("Idunn activation credential does not match the root-provisioned Activation witness."); + } + + if (expectedValue.writeLeaseRequired !== (process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] !== undefined)) { + throw new Error("Idunn process write-lease environment does not match Expected."); + } + const boundEndpoint = requiredEnvironment(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT); + if (!expectedValue.route || expectedValue.route.candidateEndpoint !== boundEndpoint) { + throw new Error("Idunn candidate bind differs from the Expected route."); + } + if (expectedValue.expectedSignerIdentityId !== providerSignerIdentityId(providerPrivateKey)) { + throw new Error("Provider identity does not match Idunn Expected."); + } + + const authority: IdunnRuntimeAuthority = { + expected: expectedValue, + activation: activationValue, + providerSignerIdentityId: expectedValue.expectedSignerIdentityId, + activationSignerIdentityId, + boundEndpoint, + ...(process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] + ? { processWriteLeasePath: process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] } + : {}), + }; + authorityKeys.set(authority, { providerPrivateKey, activationPrivateKey }); + return authority; +} + +/** + * Signs the fixed Idunn v2 positional runtime-presence contract with the + * provider identity and this launch's Idunn-issued activation key. + */ +export function signIdunnRuntimePresence( + authority: IdunnRuntimeAuthority, + fields: Omit, +): { presence: RuntimePresenceHealth; payload: Uint8Array; canonicalSha256: string } { + const presence: RuntimePresenceHealth = { + ...fields, + target: authority.expected.target, + expectedProjectionSha256: authority.expected.canonicalSha256, + planId: authority.expected.planId, + incarnationId: authority.expected.incarnationId, + sealedReleaseId: authority.expected.sealedReleaseId, + activationWitnessSha256: authority.activation.canonicalSha256, + stateSchemaGeneration: authority.expected.stateSchemaGeneration, + stateContractSha256: authority.expected.stateContractSha256, + runtimeId: authority.expected.runtimeId, + runtimeInstanceId: authority.activation.runtimeInstanceId, + boundEndpoint: authority.boundEndpoint, + healthContract: authority.expected.healthContract, + signerIdentityId: authority.providerSignerIdentityId, + activationSignerIdentityId: authority.activationSignerIdentityId, + }; + const keys = authorityKeys.get(authority); + if (!keys) throw new Error("Idunn runtime authority was not opened by the CultNet credential reader."); + const proofPayload = runtimePresenceProofPayload(presence); + const providerSignature = crypto.sign(null, runtimePresenceProviderSigningMessage(proofPayload), keys.providerPrivateKey); + const activationSignature = crypto.sign(null, runtimePresenceActivationSigningMessage(proofPayload), keys.activationPrivateKey); + const payload = encodeRuntimePresenceHealth(presence, providerSignature, activationSignature); + return { + presence, + payload, + canonicalSha256: prefixedSha256(Buffer.from(payload)), + }; +} + +export function createIdunnRuntimePresencePublisher( + options: IdunnRuntimePresencePublisherOptions, +): IdunnRuntimePresencePublisher { + const endpoint = parseRudpEndpoint(options.endpoint); + const expected = options.authority.expected; + if (options.healthContract !== expected.healthContract) throw new Error("Runtime presence contract differs from Expected."); + if (options.authority.boundEndpoint !== expected.route?.candidateEndpoint) throw new Error("Runtime presence bind differs from Expected."); + for (const required of expected.capabilities) { + if (!options.capabilities.some((actual) => actual.capability === required.capability + && actual.schema === required.schema + && actual.compatibility === required.compatibility + && actual.capacity >= required.minimumCapacity)) { + throw new Error(`Runtime does not provide Expected capability ${required.capability}/${required.schema}.`); + } + } + const connectionId = 0x0d1d0002; + let sequence = 0; + let latestLeaseSha256: string | null = null; + const recentWarmingProofs: string[] = []; + + const assertWriteLease = async () => { + if (!expected.writeLeaseRequired) return ""; + const leasePath = options.authority.processWriteLeasePath; + if (!leasePath) throw new Error("Idunn process write lease is required but no lease path is configured."); + const record = readAuthorityRecord(leasePath, "idunn.process_write_lease", IDUNN_PROCESS_WRITE_LEASE_SCHEMA); + const lease = decodeArray(record.payload, 14, "Idunn process write lease"); + assertLeaseMatches(lease, options.authority, recentWarmingProofs); + latestLeaseSha256 = prefixedSha256(Buffer.from(encode(lease))); + return latestLeaseSha256; + }; + + const publish = async (state: RuntimePresenceHealth["state"], detail: string) => { + const writeLeaseSha256 = state === "warming" || !expected.writeLeaseRequired ? null : await assertWriteLease(); + sequence += 1; + const signed = signIdunnRuntimePresence(options.authority, { + capabilities: options.capabilities, + state, + detail: detail.slice(0, 512), + writeLeaseSha256, + publisherSequence: sequence, + observedAtUnixMillis: Date.now(), + }); + await publishDocument(endpoint, connectionId, { + schemaVersion: "cultnet.document_put_raw.v0", + messageId: `runtime-presence:${expected.target}:${options.authority.activation.runtimeInstanceId}:${sequence}`, + document: { + schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, + recordKey: expected.target, + storedAt: new Date().toISOString(), + payloadEncoding: "messagepack", + payload: signed.payload, + sourceRuntimeId: expected.runtimeId, + sourceRole: "runtime-presence-health-publisher", + tags: ["cultnet.transport.rudp.v0", "runtime-presence"], + }, + }); + if (state === "warming") { + recentWarmingProofs.push(signed.canonicalSha256); + if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift(); + } + return signed.canonicalSha256; + }; + + return { + runtimeId: expected.runtimeId, + runtimeInstanceId: options.authority.activation.runtimeInstanceId, + requiresWriteLease: expected.writeLeaseRequired, + publish, + async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) { + if (!expected.writeLeaseRequired) return ""; + let warmingSequence = 0; + while (!signal?.aborted) { + await publish("warming", "waiting-for-process-write-lease"); + warmingSequence += 1; + try { + return await assertWriteLease(); + } catch (error) { + if (warmingSequence > 720) throw new Error("Timed out waiting for Idunn process write lease.", { cause: error }); + } + await abortableDelay(pollIntervalMs, signal); + } + throw signal?.reason ?? new Error("Aborted while waiting for Idunn process write lease."); + }, + assertWriteLease, + }; +} + +async function publishDocument( + endpoint: { host: string; port: number }, + connectionId: number, + message: Record, +): Promise { + const socket = dgram.createSocket(endpoint.host.includes(":") ? "udp6" : "udp4"); + await new Promise((resolve, reject) => { + socket.once("error", reject); + socket.bind(0, endpoint.host.includes(":") ? "::" : "0.0.0.0", () => { + socket.off("error", reject); + resolve(); + }); + }); + const receiver = receivePackets(socket); + const session = new CultNetRudpSession({ connectionId, initialSequence: 1, resendDelayMs: 100 }); + try { + await sendPacket(socket, endpoint, session.createConnect(Date.now(), new Uint8Array())); + await receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "accept", 5000); + const wirePayload = Uint8Array.from(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0") as Uint8Array); + const packets = session.sendMany("schema", wirePayload, { reliable: true, ordered: true, nowMs: Date.now() }); + const ack = receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "ack", 2000); + for (const packet of packets) await sendPacket(socket, endpoint, packet); + await ack; + } finally { + receiver.close(); + socket.close(); + } +} + +type PacketReceiver = { + socket: dgram.Socket; + next(timeoutMs: number): Promise; + close(): void; +}; + +function receivePackets(socket: dgram.Socket): PacketReceiver { + const packets: CultNetRudpPacket[] = []; + const waiters: Array<{ resolve: (packet: CultNetRudpPacket) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }> = []; + const errors: Error[] = []; + const drain = () => { + while (waiters.length && (packets.length || errors.length)) { + const waiter = waiters.shift()!; + clearTimeout(waiter.timer); + if (errors.length) waiter.reject(errors.shift()!); + else waiter.resolve(packets.shift()!); + } + }; + const onMessage = (wire: Buffer) => { + try { packets.push(decodeRudpPacket(wire)); } catch (error) { errors.push(error as Error); } + drain(); + }; + const onError = (error: Error) => { errors.push(error); drain(); }; + socket.on("message", onMessage); + socket.on("error", onError); + return { + socket, + next(timeoutMs) { + if (packets.length) return Promise.resolve(packets.shift()!); + if (errors.length) return Promise.reject(errors.shift()!); + return new Promise((resolve, reject) => { + const waiter = { + resolve, + reject, + timer: setTimeout(() => { + const index = waiters.indexOf(waiter); + if (index >= 0) waiters.splice(index, 1); + const error = new Error("Timed out waiting for CultNet RUDP packet.") as NodeJS.ErrnoException; + error.code = "ETIMEDOUT"; + reject(error); + }, Math.max(1, timeoutMs)), + }; + waiters.push(waiter); + }); + }, + close() { + socket.off("message", onMessage); + socket.off("error", onError); + for (const waiter of waiters.splice(0)) { + clearTimeout(waiter.timer); + waiter.reject(new Error("CultNet RUDP publisher closed.")); + } + }, + }; +} + +async function receiveUntil( + receiver: PacketReceiver, + session: CultNetRudpSession, + endpoint: { host: string; port: number }, + predicate: (packet: CultNetRudpPacket) => boolean, + timeoutMs: number, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const packet = await receiver.next(Math.min(100, deadline - Date.now())); + const received = session.receive(packet, Date.now()); + if (received.reply) throw new Error("Runtime presence received an unexpected reply-required packet."); + if (predicate(packet)) return; + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code !== "ETIMEDOUT") throw error; + } + for (const packet of session.dueResends(Date.now())) await sendPacket(receiver.socket, endpoint, packet); + } + throw new Error(`Timed out waiting for CultNet RUDP response after ${timeoutMs} ms.`); +} + +async function sendPacket(socket: dgram.Socket, endpoint: { host: string; port: number }, packet: CultNetRudpPacket): Promise { + const wire = encodeRudpPacket(packet); + await new Promise((resolve, reject) => { + socket.send(wire, endpoint.port, endpoint.host, (error) => error ? reject(error) : resolve()); + }); +} + +function readAuthorityRecord(filePath: string, type: string, schemaId: string): { payload: Uint8Array } { + const decoded = decode(fs.readFileSync(filePath)); + if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { + throw new Error(`Idunn authority file ${filePath} is not a CultCache v1 store.`); + } + if (decoded[2].length !== 1) throw new Error(`Idunn authority file ${filePath} must contain exactly one record.`); + const matchingRecords = (decoded[2] as unknown[]).filter((raw) => { + const row = array(raw, 4, "CultCache record"); + return row[1] === schemaId; + }); + if (matchingRecords.length !== 1) throw new Error(`Idunn authority file must contain exactly one ${schemaId} record.`); + const row = array(matchingRecords[0], 4, "CultCache record"); + const catalog = (decoded[1] as unknown[]).find((raw) => { + const entry = Array.isArray(raw) ? raw : []; + return entry[0] === schemaId; + }); + const catalogEntry = array(catalog, 7, "CultCache schema catalog entry"); + if (catalogEntry[1] !== type) throw new Error(`Idunn authority record has unexpected CultCache type ${String(catalogEntry[1])}.`); + if (!(row[3] instanceof Uint8Array)) throw new Error("Idunn authority payload is not MessagePack bytes."); + return { payload: row[3] }; +} + +function decodeExpected(payload: Uint8Array): ExpectedIncarnation { + const values = decodeArray(payload, 18, "Idunn Expected"); + if (values[0] !== IDUNN_EXPECTED_INCARNATION_SCHEMA) throw new Error("Idunn Expected schema is unsupported."); + const canonicalBytes = Buffer.from(encode(values)); + if (!canonicalBytes.equals(Buffer.from(payload))) throw new Error("Idunn Expected is not canonical MessagePack."); + const stateSchemaGeneration = nullableString(values[12], "Expected state generation"); + const stateContractSha256 = nullableString(values[13], "Expected state contract"); + if ((stateSchemaGeneration === null) !== (stateContractSha256 === null)) throw new Error("Idunn Expected state lineage is partial."); + if (typeof values[14] !== "boolean") throw new Error("Idunn Expected write-lease flag is not boolean."); + const route = decodeRoute(values[15]); + const writeLeaseRequired = values[14]; + if (writeLeaseRequired && stateSchemaGeneration === null) throw new Error("Stateless Idunn Expected cannot require a write lease."); + const target = string(values[1], "Expected target"); + const planId = string(values[2], "Expected plan id"); + const incarnationId = string(values[3], "Expected incarnation id"); + const sealedReleaseId = string(values[4], "Expected sealed release"); + const sourceRepository = string(values[5], "Expected source repository"); + const sourceRevision = string(values[6], "Expected source revision"); + const recipeSha256 = string(values[7], "Expected recipe hash"); + const runtimeId = string(values[8], "Expected runtime id"); + const expectedSignerIdentityId = string(values[9], "Expected signer identity"); + const healthContract = string(values[10], "Expected health contract"); + const artifactSha256 = string(values[11], "Expected artifact hash"); + for (const [name, hash] of [["plan", planId], ["release", sealedReleaseId], ["recipe", recipeSha256], ["artifact", artifactSha256]] as const) { + if (!/^sha256-[0-9a-f]{64}$/u.test(hash)) throw new Error(`Expected ${name} hash is malformed.`); + } + if (!/^[0-9a-f]{40}$/u.test(sourceRevision)) throw new Error("Expected source revision is malformed."); + if (!route || route.transport !== "http" || !route.candidateEndpoint.startsWith("http://")) { + throw new Error("Idunn Expected must include an HTTP candidate route."); + } + return { + schemaVersion: string(values[0], "Expected schema"), + target, + planId, + incarnationId, + sealedReleaseId, + sourceRepository, + sourceRevision, + recipeSha256, + runtimeId, + expectedSignerIdentityId, + healthContract, + artifactSha256, + stateSchemaGeneration, + stateContractSha256, + writeLeaseRequired, + route, + capabilities: decodeExpectedCapabilities(values[16]), + dependencies: decodeExpectedDependencies(values[17]), + canonicalBytes, + canonicalSha256: prefixedSha256(canonicalBytes), + }; +} + +function decodeActivation(payload: Uint8Array): RuntimeActivation { + const values = decodeArray(payload, 10, "Idunn Activation"); + if (values[0] !== IDUNN_RUNTIME_ACTIVATION_SCHEMA) throw new Error("Idunn Activation schema is unsupported."); + const canonicalBytes = Buffer.from(encode(values)); + if (!canonicalBytes.equals(Buffer.from(payload))) throw new Error("Idunn Activation is not canonical MessagePack."); + const publicKey = bytes(values[5], "Activation signer public key"); + if (publicKey.length !== 32) throw new Error("Activation signer public key is not Ed25519."); + const activationSignerIdentityId = string(values[4], "Activation signer identity"); + if (number(values[6], "Activation issue time") <= 0 + || !/^[0-9a-f]{64}$/u.test(string(values[7], "Idunn signer identity")) + || values[8] !== "ed25519" + || bytes(values[9], "Activation signature").length !== 64) { + throw new Error("Idunn Activation signature contract is malformed."); + } + if (sha256Hex(Buffer.concat([ACTIVATION_ID_DOMAIN, publicKey])) !== activationSignerIdentityId) { + throw new Error("Activation signer identity does not match its public key."); + } + return { + schemaVersion: string(values[0], "Activation schema"), + expectedProjectionSha256: string(values[1], "Activation Expected hash"), + runtimeId: string(values[2], "Activation runtime id"), + runtimeInstanceId: string(values[3], "Activation instance id"), + activationSignerIdentityId, + activationSignerPublicKey: Buffer.from(publicKey), + canonicalSha256: prefixedSha256(canonicalBytes), + }; +} + +function decodeExpectedCapabilities(value: unknown): ExpectedIncarnation["capabilities"] { + return arrayOf(value, "Expected capabilities").map((raw) => { + const item = array(raw, 4, "Expected capability"); + return { + capability: string(item[0], "Capability id"), + schema: string(item[1], "Capability schema"), + compatibility: string(item[2], "Capability compatibility"), + minimumCapacity: number(item[3], "Capability capacity"), + }; + }); +} + +function decodeExpectedDependencies(value: unknown): ExpectedIncarnation["dependencies"] { + return arrayOf(value, "Expected dependencies").map((raw) => { + const item = array(raw, 10, "Expected dependency"); + return { + kind: string(item[0], "Dependency kind"), + capability: string(item[1], "Dependency capability"), + schema: string(item[2], "Dependency schema"), + compatibility: string(item[3], "Dependency compatibility"), + providerEndpoint: nullableString(item[9], "Dependency provider endpoint"), + }; + }); +} + +function decodeRoute(value: unknown): ExpectedIncarnation["route"] { + if (value === null) return null; + const route = array(value, 4, "Expected route"); + return { + routeId: string(route[0], "Route id"), + transport: string(route[1], "Route transport"), + stableEndpoint: string(route[2], "Stable route endpoint"), + candidateEndpoint: string(route[3], "Candidate route endpoint"), + }; +} + +function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { + const record = readAuthorityRecordBytes(credentialBytes, "gamecult.provider_health_identity", "gamecult.provider_health_identity.private.v1"); + const fields = decodeArray(record, 10, "provider-health identity"); + const [schema, identityId, publicKeyValue, protectedSeedValue, protectorKind, binding, version, assurance, createdAt, enrollmentNonceValue] = fields; + if (schema !== "gamecult.provider_health_identity.private.v1" || version !== "v1") throw new Error("Provider-health identity schema is unsupported."); + string(createdAt, "Provider-health identity creation time"); + const enrollmentNonce = bytes(enrollmentNonceValue, "Provider-health enrollment nonce"); + if (enrollmentNonce.length !== 32) throw new Error("Provider-health enrollment nonce has an invalid length."); + const publicKey = bytesValue(publicKeyValue, "Provider-health public key"); + const protectedSeed = bytesValue(protectedSeedValue, "Provider-health protected seed"); + const machineId = fs.readFileSync("/etc/machine-id", "utf8").trim(); + if (!machineId) throw new Error("Linux machine-id is unavailable for provider-health identity."); + const expectedBinding = `${PROVIDER_PROTECTOR_CONTEXT}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`; + if (protectorKind !== "linux_file_mode_machine_id_binding" || binding !== expectedBinding || assurance !== "os_installation_file_bound_cloneable_baseline") { + throw new Error("Provider-health identity protector does not match this Linux installation."); + } + if (publicKey.length !== 32 || protectedSeed.length !== 32) throw new Error("Provider-health identity key material has an invalid length."); + const mask = crypto.createHash("sha256").update(Buffer.concat([ + Buffer.from("gamecult-linux-service-seed-v1\0", "utf8"), + Buffer.from(PROVIDER_PROTECTOR_CONTEXT, "utf8"), + Buffer.from(expectedBinding, "utf8"), + ])).digest(); + const seed = Buffer.from(protectedSeed.map((value, index) => value ^ mask[index]!)); + const key = privateKeyFromSeed(seed); + seed.fill(0); + const derivedPublicKey = rawEd25519PublicKey(crypto.createPublicKey(key)); + const derivedId = sha256Hex(Buffer.concat([PROVIDER_ID_DOMAIN, derivedPublicKey])); + if (!derivedPublicKey.equals(publicKey) || identityId !== derivedId) throw new Error("Provider-health private key differs from its enrolled identity."); + return key; +} + +function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string): Uint8Array { + const decoded = decode(bytes); + if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { + throw new Error("Runtime credential is not a CultCache v1 store."); + } + if (decoded[2].length !== 1) throw new Error("Runtime credential must contain exactly one record."); + const rows = (decoded[2] as unknown[]).filter((raw) => Array.isArray(raw) && raw[1] === schemaId); + if (rows.length !== 1) throw new Error(`Runtime credential must contain exactly one ${schemaId} record.`); + const catalog = (decoded[1] as unknown[]).find((raw) => Array.isArray(raw) && raw[0] === schemaId); + if (!Array.isArray(catalog) || catalog[1] !== type) throw new Error("Runtime credential has an unexpected CultCache type."); + const row = array(rows[0], 4, "Runtime credential record"); + return bytesValue(row[3], "Runtime credential payload"); +} + +function inheritedDescriptorMap(): Map { + if (process.env.LISTEN_PID !== String(process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process."); + const count = Number(process.env.LISTEN_FDS); + const names = process.env.LISTEN_FDNAMES?.split(":") ?? []; + if (!Number.isInteger(count) || count < 1 || names.length !== count) throw new Error("Inherited Idunn descriptor list is malformed."); + return new Map(names.map((name, index) => [name, index + 3])); +} + +function readDescriptor(descriptor: number): Buffer { + const fdPath = `/proc/self/fd/${descriptor}`; + return fs.readFileSync(fdPath); +} + +function privateKeyFromSeed(seed: Uint8Array): crypto.KeyObject { + return crypto.createPrivateKey({ key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(seed)]), format: "der", type: "pkcs8" }); +} + +function rawEd25519PublicKey(publicKey: crypto.KeyObject): Buffer { + const der = publicKey.export({ type: "spki", format: "der" }) as Buffer; + return Buffer.from(der.subarray(der.length - 32)); +} + +function providerSignerIdentityId(privateKey: crypto.KeyObject): string { + return sha256Hex(Buffer.concat([PROVIDER_ID_DOMAIN, rawEd25519PublicKey(crypto.createPublicKey(privateKey))])); +} + +function assertLeaseMatches(values: unknown[], authority: IdunnRuntimeAuthority, recentWarmingProofs: string[]): void { + const expected = authority.expected; + const activation = authority.activation; + const matches = values[0] === IDUNN_PROCESS_WRITE_LEASE_SCHEMA + && values[1] === expected.target + && values[2] === expected.canonicalSha256 + && values[3] === expected.planId + && values[4] === expected.incarnationId + && values[5] === expected.sealedReleaseId + && values[6] === activation.canonicalSha256 + && values[7] === expected.stateSchemaGeneration + && values[8] === expected.stateContractSha256 + && values[9] === expected.runtimeId + && values[10] === activation.runtimeInstanceId + && typeof values[11] === "string" + && recentWarmingProofs.includes(values[11]) + && Number.isSafeInteger(values[12]) && Number(values[12]) > 0 + && Number.isSafeInteger(values[13]) && Number(values[13]) > 0; + if (!matches) throw new Error("Idunn process write lease does not match the current Expected incarnation."); +} + +function parseRudpEndpoint(value: string): { host: string; port: number } { + const text = value.replace(/^rudp:\/\//i, ""); + const match = text.match(/^\[([^\]]+)\]:(\d+)$/) ?? text.match(/^([^:]+):(\d+)$/); + if (!match) throw new Error(`Invalid Odin RUDP endpoint: ${value}`); + const port = Number(match[2]); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid Odin RUDP port: ${match[2]}`); + return { host: match[1]!, port }; +} + +function normalizeRudpEndpoint(value: string): string { + const normalized = value.trim().toLowerCase().replace(/^rudp:\/\//, ""); + const parsed = parseRudpEndpoint(normalized); + return `${parsed.host.toLowerCase()}:${parsed.port}`; +} + +function requiredEnvironment(name: string): string { + const value = process.env[name]?.trim(); + if (!value) throw new Error(`${name} is required for Idunn runtime presence.`); + return value; +} + +function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, milliseconds); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason ?? new Error("Aborted.")); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +function array(value: unknown, length: number, label: string): unknown[] { + if (!Array.isArray(value) || value.length !== length) throw new Error(`${label} is not a ${length}-field positional contract.`); + return value; +} + +function decodeArray(payload: Uint8Array, length: number, label: string): unknown[] { + return array(decode(payload), length, label); +} + +function arrayOf(value: unknown, label: string): unknown[] { + if (!Array.isArray(value)) throw new Error(`${label} is not an array.`); + return value; +} + +function string(value: unknown, label: string): string { + if (typeof value !== "string" || !value.trim() || value.trim() !== value || /[\u0000-\u001f\u007f]/u.test(value)) { + throw new Error(`${label} is not a valid authority string.`); + } + return value; +} + +function nullableString(value: unknown, label: string): string | null { + return value === null ? null : string(value, label); +} + +function number(value: unknown, label: string): number { + if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${label} is not a non-negative integer.`); + return value; +} + +function bytes(value: unknown, label: string): Uint8Array { + if (!(value instanceof Uint8Array)) throw new Error(`${label} is not bytes.`); + return value; +} + +function bytesValue(value: unknown, label: string): Buffer { + return Buffer.from(bytes(value, label)); +} + +function prefixedSha256(bytes: Uint8Array): string { + return `sha256-${sha256Hex(bytes)}`; +} + +function sha256Hex(bytes: Uint8Array): string { + return crypto.createHash("sha256").update(bytes).digest("hex"); +} diff --git a/packages/cultnet-ts/src/index.ts b/packages/cultnet-ts/src/index.ts index 84bef769..3db890ef 100644 --- a/packages/cultnet-ts/src/index.ts +++ b/packages/cultnet-ts/src/index.ts @@ -197,3 +197,17 @@ export { type RuntimePresenceHealth, type RuntimePresenceState, } from "./runtime-presence-health"; + +export { + IDUNN_EXPECTED_INCARNATION_SCHEMA, + IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT, + IDUNN_PROCESS_WRITE_LEASE_SCHEMA, + IDUNN_RUNTIME_BUNDLE_ENVIRONMENT, + IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, + IDUNN_RUNTIME_ACTIVATION_SCHEMA, + createIdunnRuntimePresencePublisher, + loadIdunnRuntimeAuthorityFromEnvironment, + type IdunnRuntimeAuthority, + type IdunnRuntimePresencePublisher, + type IdunnRuntimePresencePublisherOptions, +} from "./idunn-runtime-authority"; diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts new file mode 100644 index 00000000..dd079c91 --- /dev/null +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -0,0 +1,140 @@ +import { mock, test } from "node:test"; +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { decode, encode } from "@msgpack/msgpack"; + +import { + loadIdunnRuntimeAuthorityFromEnvironment, + signIdunnRuntimePresence, +} from "../src/idunn-runtime-authority"; +import { + runtimePresenceActivationSigningMessage, + runtimePresenceProofPayload, + runtimePresenceProviderSigningMessage, +} from "../src/runtime-presence-health"; + +const providerIdentityContext = "gamecult-provider-health-identity-v1"; +const providerIdDomain = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8"); +const activationIdDomain = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8"); + +test("opens Idunn's machine-bound identity and signs the exact Expected incarnation twice", (context) => { + const directory = mkdtempSync(path.join(os.tmpdir(), "cultnet-runtime-authority-")); + context.after(() => rmSync(directory, { recursive: true, force: true })); + + const machineId = "1234567890abcdef1234567890abcdef"; + const providerSeed = Buffer.alloc(32, 0x31); + const activationSeed = Buffer.alloc(32, 0x72); + const providerKey = privateKeyFromSeed(providerSeed); + const activationKey = privateKeyFromSeed(activationSeed); + const providerPublic = rawPublic(crypto.createPublicKey(providerKey)); + const activationPublic = rawPublic(crypto.createPublicKey(activationKey)); + const providerIdentity = sha256Hex(Buffer.concat([providerIdDomain, providerPublic])); + const activationIdentity = sha256Hex(Buffer.concat([activationIdDomain, activationPublic])); + const target = "streampixels-service"; + const contract = "streampixels-service.cultnet-rudp-service-health"; + const candidate = "http://127.0.0.1:18831"; + const expectedValues = [ + "idunn.expected_incarnation.v2", target, `sha256-${"1".repeat(64)}`, "incarnation-1", + `sha256-${"2".repeat(64)}`, "https://github.com/GameCult/StreamPixels.git", "a".repeat(40), + `sha256-${"3".repeat(64)}`, "streampixels-service-yggdrasil", providerIdentity, contract, + `sha256-${"4".repeat(64)}`, "service-boundary-v1", `sha256-${"5".repeat(64)}`, true, + ["streampixels-service-http", "http", "http://127.0.0.1:8831", candidate], + [["streampixels.service.api", "streampixels.api.v1", "v1", 1]], + [["shared-infrastructure", "odin.verse-rendezvous", "odin.verse-topology.v1", "v1", 1, "before-promotion", null, null, null, "rudp://127.0.0.1:17871"]], + ]; + const expectedBytes = Buffer.from(encode(expectedValues)); + const expectedSha = `sha256-${sha256Hex(expectedBytes)}`; + const activationValues = [ + "idunn.runtime_activation.v2", expectedSha, "streampixels-service-yggdrasil", + `sha256-${"6".repeat(64)}`, activationIdentity, activationPublic, Date.now(), + "7".repeat(64), "ed25519", new Uint8Array(64).fill(0x17), + ]; + const bundle = path.join(directory, "bundle"); + fs.mkdirSync(bundle); + writeFileSync(path.join(bundle, "expected.cc"), cultCacheStore( + "idunn.expected_incarnation", "idunn.expected_incarnation.v2", "expected", expectedBytes, + )); + writeFileSync(path.join(bundle, "activation.cc"), cultCacheStore( + "idunn.runtime_activation", "idunn.runtime_activation.v2", "activation", Buffer.from(encode(activationValues)), + )); + + const binding = `${providerIdentityContext}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`; + const mask = crypto.createHash("sha256").update(Buffer.concat([ + Buffer.from("gamecult-linux-service-seed-v1\0", "utf8"), + Buffer.from(providerIdentityContext, "utf8"), + Buffer.from(binding, "utf8"), + ])).digest(); + const protectedSeed = Buffer.from(providerSeed.map((value, index) => value ^ mask[index]!)); + const providerCredential = cultCacheStore( + "gamecult.provider_health_identity", "gamecult.provider_health_identity.private.v1", + "gamecult-provider-health-identity", Buffer.from(encode([ + "gamecult.provider_health_identity.private.v1", providerIdentity, providerPublic, protectedSeed, + "linux_file_mode_machine_id_binding", binding, "v1", "os_installation_file_bound_cloneable_baseline", + "2026-01-01T00:00:00Z", new Uint8Array(32).fill(0x2a), + ])), + ); + + const originalEnvironment = { ...process.env }; + context.after(() => { + for (const key of Object.keys(process.env)) if (!(key in originalEnvironment)) delete process.env[key]; + Object.assign(process.env, originalEnvironment); + }); + process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; + process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; + process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(directory, "lease.cc"); + process.env.LISTEN_PID = String(process.pid); + process.env.LISTEN_FDS = "2"; + process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; + const realReadFileSync = fs.readFileSync.bind(fs); + mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { + if (filePath === "/proc/self/fd/3") return activationSeed; + if (filePath === "/proc/self/fd/4") return providerCredential; + if (filePath === "/etc/machine-id") return machineId; + return realReadFileSync(filePath as never, ...args as never[]); + }); + + const authority = loadIdunnRuntimeAuthorityFromEnvironment(target, contract, "127.0.0.1:17871"); + const signed = signIdunnRuntimePresence(authority, { + capabilities: [{ capability: "streampixels.service.api", schema: "streampixels.api.v1", compatibility: "v1", capacity: 1 }], + state: "warming", + detail: "starting", + writeLeaseSha256: null, + publisherSequence: 1, + observedAtUnixMillis: Date.now(), + }); + const proof = runtimePresenceProofPayload(signed.presence); + assert.equal((decode(expectedBytes) as unknown[]).length, 18); + assert.equal(signed.presence.expectedProjectionSha256, expectedSha); + const signedRecord = decode(signed.payload) as unknown[]; + assert.equal(crypto.verify(null, runtimePresenceProviderSigningMessage(proof), crypto.createPublicKey(providerKey), Buffer.from(signedRecord[21] as Uint8Array)), true); + assert.equal(crypto.verify(null, runtimePresenceActivationSigningMessage(proof), crypto.createPublicKey(activationKey), Buffer.from(signedRecord[23] as Uint8Array)), true); +}); + +function cultCacheStore(type: string, schemaId: string, key: string, payload: Uint8Array): Buffer { + return Buffer.from(encode([ + "cultcache.store.v1", + [[schemaId, type, `${schemaId}.v1`, schemaId, "{}", [schemaId], []]], + [[key, schemaId, "2026-01-01T00:00:00Z", payload]], + ])); +} + +function privateKeyFromSeed(seed: Uint8Array): crypto.KeyObject { + return crypto.createPrivateKey({ + key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), Buffer.from(seed)]), + format: "der", + type: "pkcs8", + }); +} + +function rawPublic(key: crypto.KeyObject): Buffer { + const der = key.export({ type: "spki", format: "der" }) as Buffer; + return Buffer.from(der.subarray(der.length - 32)); +} + +function sha256Hex(bytes: Uint8Array): string { + return crypto.createHash("sha256").update(bytes).digest("hex"); +} From 21dfd83211dba864d39b1252eb43078ba1778740 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 00:10:26 +0200 Subject: [PATCH 02/64] Validate systemd descriptor PID across namespaces --- .../cultnet-ts/src/idunn-runtime-authority.ts | 16 +++++++++++++++- .../test/idunn-runtime-authority.test.ts | 5 ++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index 28e61e97..00f35c2f 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -588,13 +588,27 @@ function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string) } function inheritedDescriptorMap(): Map { - if (process.env.LISTEN_PID !== String(process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process."); + if (process.env.LISTEN_PID !== currentSystemdListenPid()) throw new Error("Inherited Idunn descriptors do not belong to this process."); const count = Number(process.env.LISTEN_FDS); const names = process.env.LISTEN_FDNAMES?.split(":") ?? []; if (!Number.isInteger(count) || count < 1 || names.length !== count) throw new Error("Inherited Idunn descriptor list is malformed."); return new Map(names.map((name, index) => [name, index + 3])); } +function currentSystemdListenPid(): string { + try { + const status = fs.readFileSync("/proc/self/status", "utf8"); + const namespacePids = /^NSpid:\s+([0-9]+)(?:\s|$)/mu.exec(status); + // systemd records LISTEN_PID in its PID namespace. In a PrivatePIDs + // service, Node's process.pid is namespace-local, while the first NSpid + // value is the same host PID systemd used for LISTEN_PID. + return namespacePids?.[1] ?? String(process.pid); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return String(process.pid); + throw error; + } +} + function readDescriptor(descriptor: number): Buffer { const fdPath = `/proc/self/fd/${descriptor}`; return fs.readFileSync(fdPath); diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index dd079c91..d1b4dcdb 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -86,11 +86,14 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(directory, "lease.cc"); - process.env.LISTEN_PID = String(process.pid); + // systemd reports the host PID while Node inside PrivatePIDs sees PID 1. + const listenPid = String(process.pid + 1000); + process.env.LISTEN_PID = listenPid; process.env.LISTEN_FDS = "2"; process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; const realReadFileSync = fs.readFileSync.bind(fs); mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { + if (filePath === "/proc/self/status") return `Name:\tnode\nNSpid:\t${listenPid}\t1\n`; if (filePath === "/proc/self/fd/3") return activationSeed; if (filePath === "/proc/self/fd/4") return providerCredential; if (filePath === "/etc/machine-id") return machineId; From 71aa615d93973680386d6ff256a86ab156bc107d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 00:24:02 +0200 Subject: [PATCH 03/64] Allow systemd descriptors in PID namespace init --- .../cultnet-ts/src/idunn-runtime-authority.ts | 21 +++++++------------ .../test/idunn-runtime-authority.test.ts | 14 +++++++++---- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index 00f35c2f..de4f3579 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -588,25 +588,20 @@ function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string) } function inheritedDescriptorMap(): Map { - if (process.env.LISTEN_PID !== currentSystemdListenPid()) throw new Error("Inherited Idunn descriptors do not belong to this process."); + if (!systemdListenPidMatches(process.env.LISTEN_PID, process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process."); const count = Number(process.env.LISTEN_FDS); const names = process.env.LISTEN_FDNAMES?.split(":") ?? []; if (!Number.isInteger(count) || count < 1 || names.length !== count) throw new Error("Inherited Idunn descriptor list is malformed."); return new Map(names.map((name, index) => [name, index + 3])); } -function currentSystemdListenPid(): string { - try { - const status = fs.readFileSync("/proc/self/status", "utf8"); - const namespacePids = /^NSpid:\s+([0-9]+)(?:\s|$)/mu.exec(status); - // systemd records LISTEN_PID in its PID namespace. In a PrivatePIDs - // service, Node's process.pid is namespace-local, while the first NSpid - // value is the same host PID systemd used for LISTEN_PID. - return namespacePids?.[1] ?? String(process.pid); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return String(process.pid); - throw error; - } +export function systemdListenPidMatches(listenPid: string | undefined, processPid: number): boolean { + if (listenPid === String(processPid)) return true; + // systemd sets LISTEN_PID in the host PID namespace. With PrivatePIDs=yes, + // the service's main process is namespace PID 1 and cannot read that host + // PID through its private /proc mount. A descendant has a PID greater than + // 1 and must not reuse the inherited descriptor set. + return processPid === 1 && /^\d+$/u.test(listenPid ?? "") && Number(listenPid) > 1; } function readDescriptor(descriptor: number): Buffer { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index d1b4dcdb..cfd2b5a4 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -10,6 +10,7 @@ import { decode, encode } from "@msgpack/msgpack"; import { loadIdunnRuntimeAuthorityFromEnvironment, signIdunnRuntimePresence, + systemdListenPidMatches, } from "../src/idunn-runtime-authority"; import { runtimePresenceActivationSigningMessage, @@ -21,6 +22,14 @@ const providerIdentityContext = "gamecult-provider-health-identity-v1"; const providerIdDomain = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8"); const activationIdDomain = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8"); +test("matches systemd's host PID for the private PID namespace init only", () => { + assert.equal(systemdListenPidMatches(String(process.pid), process.pid), true); + assert.equal(systemdListenPidMatches("1725346", 1), true); + assert.equal(systemdListenPidMatches("1725346", 2), false); + assert.equal(systemdListenPidMatches("not-a-pid", 1), false); + assert.equal(systemdListenPidMatches(undefined, 1), false); +}); + test("opens Idunn's machine-bound identity and signs the exact Expected incarnation twice", (context) => { const directory = mkdtempSync(path.join(os.tmpdir(), "cultnet-runtime-authority-")); context.after(() => rmSync(directory, { recursive: true, force: true })); @@ -86,14 +95,11 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(directory, "lease.cc"); - // systemd reports the host PID while Node inside PrivatePIDs sees PID 1. - const listenPid = String(process.pid + 1000); - process.env.LISTEN_PID = listenPid; + process.env.LISTEN_PID = String(process.pid); process.env.LISTEN_FDS = "2"; process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; const realReadFileSync = fs.readFileSync.bind(fs); mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { - if (filePath === "/proc/self/status") return `Name:\tnode\nNSpid:\t${listenPid}\t1\n`; if (filePath === "/proc/self/fd/3") return activationSeed; if (filePath === "/proc/self/fd/4") return providerCredential; if (filePath === "/etc/machine-id") return machineId; From 5697802dbf86bc9249df21dd208ab332a649704e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 00:35:15 +0200 Subject: [PATCH 04/64] Read inherited Idunn descriptors directly --- packages/cultnet-ts/src/idunn-runtime-authority.ts | 3 +-- packages/cultnet-ts/test/idunn-runtime-authority.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index de4f3579..ea07ba27 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -605,8 +605,7 @@ export function systemdListenPidMatches(listenPid: string | undefined, processPi } function readDescriptor(descriptor: number): Buffer { - const fdPath = `/proc/self/fd/${descriptor}`; - return fs.readFileSync(fdPath); + return fs.readFileSync(descriptor); } function privateKeyFromSeed(seed: Uint8Array): crypto.KeyObject { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index cfd2b5a4..a2277c92 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -100,8 +100,8 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; const realReadFileSync = fs.readFileSync.bind(fs); mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { - if (filePath === "/proc/self/fd/3") return activationSeed; - if (filePath === "/proc/self/fd/4") return providerCredential; + if (filePath === 3) return activationSeed; + if (filePath === 4) return providerCredential; if (filePath === "/etc/machine-id") return machineId; return realReadFileSync(filePath as never, ...args as never[]); }); From 5dd25718af6c32ce8f9881676fed3a0c5c4e15a5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 00:52:03 +0200 Subject: [PATCH 05/64] Read Idunn identity envelope format --- .../cultnet-ts/src/idunn-runtime-authority.ts | 18 +++++++++++++-- .../test/idunn-runtime-authority.test.ts | 23 +++++++++++++++---- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index ea07ba27..c6f82c27 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -543,8 +543,7 @@ function decodeRoute(value: unknown): ExpectedIncarnation["route"] { } function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { - const record = readAuthorityRecordBytes(credentialBytes, "gamecult.provider_health_identity", "gamecult.provider_health_identity.private.v1"); - const fields = decodeArray(record, 10, "provider-health identity"); + const fields = decodeArray(readProviderHealthIdentityCredential(credentialBytes), 10, "provider-health identity"); const [schema, identityId, publicKeyValue, protectedSeedValue, protectorKind, binding, version, assurance, createdAt, enrollmentNonceValue] = fields; if (schema !== "gamecult.provider_health_identity.private.v1" || version !== "v1") throw new Error("Provider-health identity schema is unsupported."); string(createdAt, "Provider-health identity creation time"); @@ -573,6 +572,21 @@ function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { return key; } +function readProviderHealthIdentityCredential(bytes: Buffer): Uint8Array { + const decoded = decode(bytes); + if (!Array.isArray(decoded) || decoded.length !== 1) { + throw new Error("Provider-health identity credential must contain exactly one envelope."); + } + const envelope = array(decoded[0], 5, "Provider-health identity envelope"); + if (envelope[0] !== "gamecult-provider-health-identity" + || envelope[1] !== "gamecult.provider_health_identity.private.v1" + || envelope[4] !== "gamecult.provider_health_identity.private.v1") { + throw new Error("Provider-health identity credential belongs to a different profile or schema."); + } + string(envelope[3], "Provider-health identity stored-at time"); + return bytesValue(envelope[2], "Provider-health identity payload"); +} + function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string): Uint8Array { const decoded = decode(bytes); if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index a2277c92..1ffeb2ba 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -78,14 +78,18 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat Buffer.from(binding, "utf8"), ])).digest(); const protectedSeed = Buffer.from(providerSeed.map((value, index) => value ^ mask[index]!)); - const providerCredential = cultCacheStore( - "gamecult.provider_health_identity", "gamecult.provider_health_identity.private.v1", - "gamecult-provider-health-identity", Buffer.from(encode([ + const providerCredential = Buffer.from(encode([[ + "gamecult-provider-health-identity", + "gamecult.provider_health_identity.private.v1", + Buffer.from(encode([ "gamecult.provider_health_identity.private.v1", providerIdentity, providerPublic, protectedSeed, "linux_file_mode_machine_id_binding", binding, "v1", "os_installation_file_bound_cloneable_baseline", "2026-01-01T00:00:00Z", new Uint8Array(32).fill(0x2a), ])), - ); + "2026-01-01T00:00:00Z", + "gamecult.provider_health_identity.private.v1", + ]])); + let descriptorProviderCredential = providerCredential; const originalEnvironment = { ...process.env }; context.after(() => { @@ -101,7 +105,7 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat const realReadFileSync = fs.readFileSync.bind(fs); mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { if (filePath === 3) return activationSeed; - if (filePath === 4) return providerCredential; + if (filePath === 4) return descriptorProviderCredential; if (filePath === "/etc/machine-id") return machineId; return realReadFileSync(filePath as never, ...args as never[]); }); @@ -121,6 +125,15 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat const signedRecord = decode(signed.payload) as unknown[]; assert.equal(crypto.verify(null, runtimePresenceProviderSigningMessage(proof), crypto.createPublicKey(providerKey), Buffer.from(signedRecord[21] as Uint8Array)), true); assert.equal(crypto.verify(null, runtimePresenceActivationSigningMessage(proof), crypto.createPublicKey(activationKey), Buffer.from(signedRecord[23] as Uint8Array)), true); + + descriptorProviderCredential = Buffer.from(encode([ + ...(decode(providerCredential) as unknown[][]), + ...(decode(providerCredential) as unknown[][]), + ])); + assert.throws( + () => loadIdunnRuntimeAuthorityFromEnvironment(target, contract, "127.0.0.1:17871"), + /exactly one envelope/, + ); }); function cultCacheStore(type: string, schemaId: string, key: string, payload: Uint8Array): Buffer { From 2c5dc3e27833050f667053b6a8a6c2428672cd11 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 01:00:52 +0200 Subject: [PATCH 06/64] Decode Idunn identity byte vectors --- packages/cultnet-ts/src/idunn-runtime-authority.ts | 13 ++++++++++--- .../cultnet-ts/test/idunn-runtime-authority.test.ts | 4 ++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index c6f82c27..e01be597 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -547,10 +547,10 @@ function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { const [schema, identityId, publicKeyValue, protectedSeedValue, protectorKind, binding, version, assurance, createdAt, enrollmentNonceValue] = fields; if (schema !== "gamecult.provider_health_identity.private.v1" || version !== "v1") throw new Error("Provider-health identity schema is unsupported."); string(createdAt, "Provider-health identity creation time"); - const enrollmentNonce = bytes(enrollmentNonceValue, "Provider-health enrollment nonce"); + const enrollmentNonce = providerIdentityByteVector(enrollmentNonceValue, "Provider-health enrollment nonce"); if (enrollmentNonce.length !== 32) throw new Error("Provider-health enrollment nonce has an invalid length."); - const publicKey = bytesValue(publicKeyValue, "Provider-health public key"); - const protectedSeed = bytesValue(protectedSeedValue, "Provider-health protected seed"); + const publicKey = Buffer.from(providerIdentityByteVector(publicKeyValue, "Provider-health public key")); + const protectedSeed = Buffer.from(providerIdentityByteVector(protectedSeedValue, "Provider-health protected seed")); const machineId = fs.readFileSync("/etc/machine-id", "utf8").trim(); if (!machineId) throw new Error("Linux machine-id is unavailable for provider-health identity."); const expectedBinding = `${PROVIDER_PROTECTOR_CONTEXT}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`; @@ -587,6 +587,13 @@ function readProviderHealthIdentityCredential(bytes: Buffer): Uint8Array { return bytesValue(envelope[2], "Provider-health identity payload"); } +function providerIdentityByteVector(value: unknown, label: string): Uint8Array { + if (!Array.isArray(value) || value.some((byte) => typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255)) { + throw new Error(`${label} is not a byte vector.`); + } + return Uint8Array.from(value as number[]); +} + function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string): Uint8Array { const decoded = decode(bytes); if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 1ffeb2ba..4b7b4865 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -82,9 +82,9 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat "gamecult-provider-health-identity", "gamecult.provider_health_identity.private.v1", Buffer.from(encode([ - "gamecult.provider_health_identity.private.v1", providerIdentity, providerPublic, protectedSeed, + "gamecult.provider_health_identity.private.v1", providerIdentity, Array.from(providerPublic), Array.from(protectedSeed), "linux_file_mode_machine_id_binding", binding, "v1", "os_installation_file_bound_cloneable_baseline", - "2026-01-01T00:00:00Z", new Uint8Array(32).fill(0x2a), + "2026-01-01T00:00:00Z", Array(32).fill(0x2a), ])), "2026-01-01T00:00:00Z", "gamecult.provider_health_identity.private.v1", From 564d5bf732f263ff23f3c58e3d98ffec9bb23564 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 02:11:12 +0200 Subject: [PATCH 07/64] Fix Idunn runtime presence RUDP publication --- .../cultnet-ts/src/idunn-runtime-authority.ts | 22 +++++-- .../test/idunn-runtime-authority.test.ts | 63 ++++++++++++++++++- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index e01be597..2956cc2f 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -13,7 +13,7 @@ import { encodeRuntimePresenceHealth, type RuntimePresenceHealth, } from "./runtime-presence-health"; -import { encodeCultNetMessageForWire } from "./contracts"; +import { encodeCultNetMessageForWire, parseCultNetMessage } from "./contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; import dgram from "node:dgram"; @@ -306,11 +306,23 @@ async function publishDocument( try { await sendPacket(socket, endpoint, session.createConnect(Date.now(), new Uint8Array())); await receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "accept", 5000); - const wirePayload = Uint8Array.from(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0") as Uint8Array); + const wirePayload = encode(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0")); const packets = session.sendMany("schema", wirePayload, { reliable: true, ordered: true, nowMs: Date.now() }); - const ack = receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "ack", 2000); for (const packet of packets) await sendPacket(socket, endpoint, packet); - await ack; + await receiveUntil( + receiver, + session, + endpoint, + () => session.outstandingReliablePacketCount === 0, + 2000, + (frame) => { + if (frame.channelId !== "schema") return; + const response = parseCultNetMessage(decode(frame.payload)); + if (response.schemaVersion === "cultnet.error.v0") { + throw new Error(`Odin rejected runtime presence: ${response.error}`); + } + }, + ); } finally { receiver.close(); socket.close(); @@ -379,6 +391,7 @@ async function receiveUntil( endpoint: { host: string; port: number }, predicate: (packet: CultNetRudpPacket) => boolean, timeoutMs: number, + onDelivered?: (frame: { channelId: string; payload: Uint8Array; sequence: number }) => void, ): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { @@ -386,6 +399,7 @@ async function receiveUntil( const packet = await receiver.next(Math.min(100, deadline - Date.now())); const received = session.receive(packet, Date.now()); if (received.reply) throw new Error("Runtime presence received an unexpected reply-required packet."); + for (const frame of received.delivered) onDelivered?.(frame); if (predicate(packet)) return; } catch (error) { if ((error as NodeJS.ErrnoException)?.code !== "ETIMEDOUT") throw error; diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 4b7b4865..a27499cf 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -1,6 +1,7 @@ import { mock, test } from "node:test"; import assert from "node:assert/strict"; import crypto from "node:crypto"; +import dgram from "node:dgram"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -8,10 +9,12 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { decode, encode } from "@msgpack/msgpack"; import { + createIdunnRuntimePresencePublisher, loadIdunnRuntimeAuthorityFromEnvironment, signIdunnRuntimePresence, systemdListenPidMatches, } from "../src/idunn-runtime-authority"; +import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "../src/rudp"; import { runtimePresenceActivationSigningMessage, runtimePresenceProofPayload, @@ -30,7 +33,7 @@ test("matches systemd's host PID for the private PID namespace init only", () => assert.equal(systemdListenPidMatches(undefined, 1), false); }); -test("opens Idunn's machine-bound identity and signs the exact Expected incarnation twice", (context) => { +test("opens Idunn identity and publishes valid CultNet data while surfacing piggybacked application errors", async (context) => { const directory = mkdtempSync(path.join(os.tmpdir(), "cultnet-runtime-authority-")); context.after(() => rmSync(directory, { recursive: true, force: true })); @@ -126,6 +129,64 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat assert.equal(crypto.verify(null, runtimePresenceProviderSigningMessage(proof), crypto.createPublicKey(providerKey), Buffer.from(signedRecord[21] as Uint8Array)), true); assert.equal(crypto.verify(null, runtimePresenceActivationSigningMessage(proof), crypto.createPublicKey(activationKey), Buffer.from(signedRecord[23] as Uint8Array)), true); + const peer = dgram.createSocket("udp4"); + await new Promise((resolve, reject) => { + peer.once("error", reject); + peer.bind(0, "127.0.0.1", resolve); + }); + context.after(() => peer.close()); + const address = peer.address(); + assert.equal(typeof address, "object"); + const peerPort = (address as { port: number }).port; + let serverSession: CultNetRudpSession | undefined; + let receivedMessage: unknown; + let responseAck: number | undefined; + let peerFailure: Error | undefined; + peer.on("message", (wire, remote) => { + try { + const packet = decodeRudpPacket(wire); + if (packet.packetType === "connect") { + serverSession = new CultNetRudpSession({ connectionId: packet.connectionId, initialSequence: 100 }); + const accept = serverSession.acceptConnect(packet, Date.now()); + peer.send(encodeRudpPacket(accept), remote.port, remote.address); + return; + } + if (!serverSession) throw new Error("Publisher sent data before establishing RUDP."); + const result = serverSession.receive(packet, Date.now()); + const frame = result.delivered.find((candidate) => candidate.channelId === "schema"); + if (!frame) return; + receivedMessage = decode(frame.payload); + const errorPayload = encode({ + schemaVersion: "cultnet.error.v0", + error: "test admission denied", + routingHint: null, + code: null, + details: null, + }); + const [response] = serverSession.sendMany("schema", errorPayload, { + reliable: true, + ordered: true, + nowMs: Date.now(), + }); + assert.ok(response); + responseAck = response.ack; + peer.send(encodeRudpPacket(response), remote.port, remote.address); + } catch (error) { + peerFailure = error as Error; + } + }); + const publisher = createIdunnRuntimePresencePublisher({ + authority, + endpoint: `rudp://127.0.0.1:${peerPort}`, + healthContract: contract, + capabilities: [{ capability: "streampixels.service.api", schema: "streampixels.api.v1", compatibility: "v1", capacity: 1 }], + }); + await assert.rejects(publisher.publish("warming", "local RUDP integration"), /Odin rejected runtime presence: test admission denied/); + assert.deepEqual(receivedMessage && (receivedMessage as { schemaVersion?: string }).schemaVersion, "cultnet.document_put_raw.v0"); + assert.ok(Buffer.from(encode(receivedMessage)).byteLength > 0); + assert.equal(responseAck, 2, "the response data packet must acknowledge the publisher's reliable schema packet"); + assert.equal(peerFailure, undefined, peerFailure?.message); + descriptorProviderCredential = Buffer.from(encode([ ...(decode(providerCredential) as unknown[][]), ...(decode(providerCredential) as unknown[][]), From 02f13527eb091b74e7fb617fa4570e8891cda4e9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 02:51:12 +0200 Subject: [PATCH 08/64] Use explicit Ajv ESM entrypoint --- packages/cultnet-ts/src/contracts.ts | 2 +- packages/cultnet-ts/src/json-schema-contract.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cultnet-ts/src/contracts.ts b/packages/cultnet-ts/src/contracts.ts index d90af381..4bfdafad 100644 --- a/packages/cultnet-ts/src/contracts.ts +++ b/packages/cultnet-ts/src/contracts.ts @@ -1,4 +1,4 @@ -import Ajv2020, { type ValidateFunction } from "ajv/dist/2020"; +import Ajv2020, { type ValidateFunction } from "ajv/dist/2020.js"; import documentRecordSchema from "../contracts/cultnet/cultnet.document-record.schema.json"; import helloSchema from "../contracts/cultnet/cultnet.hello.schema.json"; diff --git a/packages/cultnet-ts/src/json-schema-contract.ts b/packages/cultnet-ts/src/json-schema-contract.ts index 4d8fb85d..399290ef 100644 --- a/packages/cultnet-ts/src/json-schema-contract.ts +++ b/packages/cultnet-ts/src/json-schema-contract.ts @@ -1,4 +1,4 @@ -import Ajv2020, { type ErrorObject, type ValidateFunction } from "ajv/dist/2020"; +import Ajv2020, { type ErrorObject, type ValidateFunction } from "ajv/dist/2020.js"; import type { CultCacheSchema } from "@gamecult/cultcache-ts"; export interface JsonSchemaContract extends CultCacheSchema { From 265f716391c3183d2ebb4e2812c1e26e69ea529a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 03:29:01 +0200 Subject: [PATCH 09/64] Expose published Idunn presence snapshots --- .../cultnet-ts/src/idunn-runtime-authority.ts | 34 +++++++++++++------ .../test/idunn-runtime-authority.test.ts | 21 ++++++++++-- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index 2956cc2f..af294c3f 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -13,7 +13,7 @@ import { encodeRuntimePresenceHealth, type RuntimePresenceHealth, } from "./runtime-presence-health"; -import { encodeCultNetMessageForWire, parseCultNetMessage } from "./contracts"; +import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord } from "./contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; import dgram from "node:dgram"; @@ -79,6 +79,7 @@ export type IdunnRuntimePresencePublisher = { readonly runtimeId: string; readonly runtimeInstanceId: string; readonly requiresWriteLease: boolean; + latestPresenceDocument(): CultNetRawDocumentRecord | null; publish(state: RuntimePresenceHealth["state"], detail: string): Promise; waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; assertWriteLease(): Promise; @@ -219,6 +220,7 @@ export function createIdunnRuntimePresencePublisher( const connectionId = 0x0d1d0002; let sequence = 0; let latestLeaseSha256: string | null = null; + let latestPresenceDocument: CultNetRawDocumentRecord | null = null; const recentWarmingProofs: string[] = []; const assertWriteLease = async () => { @@ -243,20 +245,22 @@ export function createIdunnRuntimePresencePublisher( publisherSequence: sequence, observedAtUnixMillis: Date.now(), }); + const document: CultNetRawDocumentRecord = { + schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, + recordKey: expected.target, + storedAt: new Date().toISOString(), + payloadEncoding: "messagepack", + payload: new Uint8Array(signed.payload), + sourceRuntimeId: expected.runtimeId, + sourceRole: "runtime-presence-health-publisher", + tags: ["cultnet.transport.rudp.v0", "runtime-presence"], + }; await publishDocument(endpoint, connectionId, { schemaVersion: "cultnet.document_put_raw.v0", messageId: `runtime-presence:${expected.target}:${options.authority.activation.runtimeInstanceId}:${sequence}`, - document: { - schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, - recordKey: expected.target, - storedAt: new Date().toISOString(), - payloadEncoding: "messagepack", - payload: signed.payload, - sourceRuntimeId: expected.runtimeId, - sourceRole: "runtime-presence-health-publisher", - tags: ["cultnet.transport.rudp.v0", "runtime-presence"], - }, + document, }); + latestPresenceDocument = document; if (state === "warming") { recentWarmingProofs.push(signed.canonicalSha256); if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift(); @@ -268,6 +272,14 @@ export function createIdunnRuntimePresencePublisher( runtimeId: expected.runtimeId, runtimeInstanceId: options.authority.activation.runtimeInstanceId, requiresWriteLease: expected.writeLeaseRequired, + latestPresenceDocument() { + if (!latestPresenceDocument) return null; + return { + ...latestPresenceDocument, + payload: new Uint8Array(latestPresenceDocument.payload), + ...(latestPresenceDocument.tags ? { tags: [...latestPresenceDocument.tags] } : {}), + }; + }, publish, async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) { if (!expected.writeLeaseRequired) return ""; diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index a27499cf..6dcdc956 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -142,6 +142,7 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg let receivedMessage: unknown; let responseAck: number | undefined; let peerFailure: Error | undefined; + let rejectOdinAdmission = true; peer.on("message", (wire, remote) => { try { const packet = decodeRudpPacket(wire); @@ -156,14 +157,18 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg const frame = result.delivered.find((candidate) => candidate.channelId === "schema"); if (!frame) return; receivedMessage = decode(frame.payload); - const errorPayload = encode({ + const responsePayload = encode(rejectOdinAdmission ? { schemaVersion: "cultnet.error.v0", error: "test admission denied", routingHint: null, code: null, details: null, + } : { + schemaVersion: "cultnet.snapshot_response.v0", + messageId: "ack", + documents: [], }); - const [response] = serverSession.sendMany("schema", errorPayload, { + const [response] = serverSession.sendMany("schema", responsePayload, { reliable: true, ordered: true, nowMs: Date.now(), @@ -186,6 +191,18 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg assert.ok(Buffer.from(encode(receivedMessage)).byteLength > 0); assert.equal(responseAck, 2, "the response data packet must acknowledge the publisher's reliable schema packet"); assert.equal(peerFailure, undefined, peerFailure?.message); + assert.equal(publisher.latestPresenceDocument(), null, "a rejected publication must not become the snapshot source"); + + rejectOdinAdmission = false; + await publisher.publish("warming", "accepted presence"); + const publishedDocument = (receivedMessage as { document: { payload: Uint8Array; schemaId: string; recordKey: string } }).document; + const snapshotDocument = publisher.latestPresenceDocument(); + assert.ok(snapshotDocument); + assert.equal(snapshotDocument.schemaId, publishedDocument.schemaId); + assert.equal(snapshotDocument.recordKey, publishedDocument.recordKey); + assert.deepEqual(Buffer.from(snapshotDocument.payload), Buffer.from(publishedDocument.payload)); + snapshotDocument.payload[0] = snapshotDocument.payload[0]! ^ 0xff; + assert.deepEqual(Buffer.from(publisher.latestPresenceDocument()?.payload ?? []), Buffer.from(publishedDocument.payload), "snapshot readers cannot mutate publisher state"); descriptorProviderCredential = Buffer.from(encode([ ...(decode(providerCredential) as unknown[][]), From 542ddd3e5830ad7dc44e69298e5469f97f992422 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 03:54:21 +0200 Subject: [PATCH 10/64] Bind runtime presence to route challenges --- .../cultnet-ts/src/idunn-runtime-authority.ts | 32 ++++++++++++++----- .../test/idunn-runtime-authority.test.ts | 15 +++++++-- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index af294c3f..b675d5c3 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -13,7 +13,7 @@ import { encodeRuntimePresenceHealth, type RuntimePresenceHealth, } from "./runtime-presence-health"; -import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord } from "./contracts"; +import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord, type CultNetSnapshotRequestMessage } from "./contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; import dgram from "node:dgram"; @@ -80,6 +80,7 @@ export type IdunnRuntimePresencePublisher = { readonly runtimeInstanceId: string; readonly requiresWriteLease: boolean; latestPresenceDocument(): CultNetRawDocumentRecord | null; + publishRouteObservation(request: CultNetSnapshotRequestMessage): Promise; publish(state: RuntimePresenceHealth["state"], detail: string): Promise; waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; assertWriteLease(): Promise; @@ -268,17 +269,32 @@ export function createIdunnRuntimePresencePublisher( return signed.canonicalSha256; }; + const copyLatestPresenceDocument = (): CultNetRawDocumentRecord | null => { + if (!latestPresenceDocument) return null; + return { + ...latestPresenceDocument, + payload: new Uint8Array(latestPresenceDocument.payload), + ...(latestPresenceDocument.tags ? { tags: [...latestPresenceDocument.tags] } : {}), + }; + }; + return { runtimeId: expected.runtimeId, runtimeInstanceId: options.authority.activation.runtimeInstanceId, requiresWriteLease: expected.writeLeaseRequired, - latestPresenceDocument() { - if (!latestPresenceDocument) return null; - return { - ...latestPresenceDocument, - payload: new Uint8Array(latestPresenceDocument.payload), - ...(latestPresenceDocument.tags ? { tags: [...latestPresenceDocument.tags] } : {}), - }; + latestPresenceDocument: copyLatestPresenceDocument, + async publishRouteObservation(request) { + if (!request.messageId || request.messageId.trim() !== request.messageId) throw new Error("Idunn route observation requires a message id."); + if ((request.schemaIds && !request.schemaIds.includes(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA)) + || (request.recordKeys && !request.recordKeys.includes(expected.target)) + || request.shardId !== undefined + || request.shardEpoch !== undefined) { + throw new Error("Idunn route observation does not request this runtime presence document."); + } + await publish("active", `route-observation:${request.messageId}`); + const document = copyLatestPresenceDocument(); + if (!document) throw new Error("Idunn route observation was published without a presence document."); + return document; }, publish, async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 6dcdc956..7969fde2 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -19,6 +19,7 @@ import { runtimePresenceActivationSigningMessage, runtimePresenceProofPayload, runtimePresenceProviderSigningMessage, + RUNTIME_PRESENCE_SLOT, } from "../src/runtime-presence-health"; const providerIdentityContext = "gamecult-provider-health-identity-v1"; @@ -53,7 +54,7 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg "idunn.expected_incarnation.v2", target, `sha256-${"1".repeat(64)}`, "incarnation-1", `sha256-${"2".repeat(64)}`, "https://github.com/GameCult/StreamPixels.git", "a".repeat(40), `sha256-${"3".repeat(64)}`, "streampixels-service-yggdrasil", providerIdentity, contract, - `sha256-${"4".repeat(64)}`, "service-boundary-v1", `sha256-${"5".repeat(64)}`, true, + `sha256-${"4".repeat(64)}`, "service-boundary-v1", `sha256-${"5".repeat(64)}`, false, ["streampixels-service-http", "http", "http://127.0.0.1:8831", candidate], [["streampixels.service.api", "streampixels.api.v1", "v1", 1]], [["shared-infrastructure", "odin.verse-rendezvous", "odin.verse-topology.v1", "v1", 1, "before-promotion", null, null, null, "rudp://127.0.0.1:17871"]], @@ -101,7 +102,7 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg }); process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; - process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(directory, "lease.cc"); + delete process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE; process.env.LISTEN_PID = String(process.pid); process.env.LISTEN_FDS = "2"; process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; @@ -195,12 +196,20 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg rejectOdinAdmission = false; await publisher.publish("warming", "accepted presence"); + const snapshotDocument = await publisher.publishRouteObservation({ + schemaVersion: "cultnet.snapshot_request.v0", + messageId: "route-challenge-1", + schemaIds: ["gamecult.runtime_presence_health.v2"], + recordKeys: [target], + }); const publishedDocument = (receivedMessage as { document: { payload: Uint8Array; schemaId: string; recordKey: string } }).document; - const snapshotDocument = publisher.latestPresenceDocument(); assert.ok(snapshotDocument); assert.equal(snapshotDocument.schemaId, publishedDocument.schemaId); assert.equal(snapshotDocument.recordKey, publishedDocument.recordKey); assert.deepEqual(Buffer.from(snapshotDocument.payload), Buffer.from(publishedDocument.payload)); + const routePresence = decode(snapshotDocument.payload) as unknown[]; + assert.equal(routePresence[RUNTIME_PRESENCE_SLOT.state], "active"); + assert.equal(routePresence[RUNTIME_PRESENCE_SLOT.detail], "route-observation:route-challenge-1"); snapshotDocument.payload[0] = snapshotDocument.payload[0]! ^ 0xff; assert.deepEqual(Buffer.from(publisher.latestPresenceDocument()?.payload ?? []), Buffer.from(publishedDocument.payload), "snapshot readers cannot mutate publisher state"); From 29c3e4c2b56198128a917137b6adabad207b4619 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 00:48:13 +0200 Subject: [PATCH 11/64] Add the content plane to cultnet-rs: chunk messages, pack, answer, verified fetch ContentChunkRequest/Response join CultNetMessage on the raw path, byte identical to the reference's field order. content.rs owns normalize_hash, pack_content, validate_manifest, answer_content_chunk_request and fetch_content, mirroring CultMeshCdn and CultMeshLegacyRudpContentServer. The C# vector test is added here; the vector files and Rust tests follow. Co-Authored-By: Claude Sonnet 5 --- packages/cultnet-rs/src/content.rs | 365 ++++++++++++++++++ packages/cultnet-rs/src/contracts.rs | 119 ++++++ packages/cultnet-rs/src/lib.rs | 2 + .../CultMeshContentVectorTests.cs | 258 +++++++++++++ 4 files changed, 744 insertions(+) create mode 100644 packages/cultnet-rs/src/content.rs create mode 100644 tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs diff --git a/packages/cultnet-rs/src/content.rs b/packages/cultnet-rs/src/content.rs new file mode 100644 index 00000000..bbf460b9 --- /dev/null +++ b/packages/cultnet-rs/src/content.rs @@ -0,0 +1,365 @@ +//! CultMesh content plane: chunking, hashing, manifest shape and validation, answering one chunk +//! request, and verifying a fetched body. Mirrors `CultMeshCdn` (`CultMeshCdn.cs`) and +//! `CultMeshLegacyRudpContentServer` (`CultMeshContentSessions.cs`); the two chunk messages are +//! `CultNetMessage::ContentChunkRequest`/`ContentChunkResponse` in `contracts.rs`. +//! +//! This is the only owner of these rules in Rust. A consumer hands `fetch_content` a transport +//! closure and gets verified bytes; it never hashes, chunks or validates a manifest itself. + +use std::collections::BTreeMap; + +use anyhow::{Result, anyhow, bail}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::CultNetMessage; + +/// One chunk of a packed body. `chunk_hash` is lowercase SHA-256 hex of `payload`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultMeshCdnChunk { + pub chunk_hash: String, + pub payload: Vec, +} + +/// `CultMeshCdnChunkRef`. Encodes as the reference's positional array under every encoder. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "ChunkRefWire", into = "ChunkRefWire")] +pub struct CultMeshCdnChunkRef { + pub chunk_hash: String, + pub offset: i64, + pub size_bytes: i32, + pub record_key: String, +} + +/// `CultMeshCdnArtifactManifest`. Encodes as the reference's positional array (keys 0-9). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "ManifestWire", into = "ManifestWire")] +pub struct CultMeshCdnArtifactManifest { + pub artifact_id: String, + pub kind: String, + pub version: String, + pub content_hash: String, + pub size_bytes: i64, + pub mime_type: String, + pub created_at_utc: String, + pub chunks: Vec, + pub tags: Vec, + pub metadata: BTreeMap, +} + +// The tuple mirrors: `to_vec_named` would write a map for a named-field struct, but a tuple +// struct is an array under every serde encoder. +#[derive(Serialize, Deserialize)] +struct ChunkRefWire(String, i64, i32, String); + +#[derive(Serialize, Deserialize)] +struct ManifestWire( + String, + String, + String, + String, + i64, + String, + String, + Vec, + Vec, + BTreeMap, +); + +impl From for ChunkRefWire { + fn from(value: CultMeshCdnChunkRef) -> Self { + Self(value.chunk_hash, value.offset, value.size_bytes, value.record_key) + } +} + +impl From for CultMeshCdnChunkRef { + fn from(value: ChunkRefWire) -> Self { + Self { + chunk_hash: value.0, + offset: value.1, + size_bytes: value.2, + record_key: value.3, + } + } +} + +impl From for ManifestWire { + fn from(value: CultMeshCdnArtifactManifest) -> Self { + Self( + value.artifact_id, + value.kind, + value.version, + value.content_hash, + value.size_bytes, + value.mime_type, + value.created_at_utc, + value.chunks, + value.tags, + value.metadata, + ) + } +} + +impl From for CultMeshCdnArtifactManifest { + fn from(value: ManifestWire) -> Self { + Self { + artifact_id: value.0, + kind: value.1, + version: value.2, + content_hash: value.3, + size_bytes: value.4, + mime_type: value.5, + created_at_utc: value.6, + chunks: value.7, + tags: value.8, + metadata: value.9, + } + } +} + +fn sha256_hex(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} + +fn chunk_record_key(hash: &str) -> String { + format!("mesh:cdn:chunk:{hash}") +} + +/// `CultMeshCdn.NormalizeHash`: an optional case-insensitive `sha256:` prefix is stripped, then the +/// rest is trimmed and lowercased. A blank hash is refused. +pub fn normalize_hash(hash: &str) -> Result { + if hash.trim().is_empty() { + bail!("Hash must be non-empty."); + } + let stripped = match hash.get(..7) { + Some(prefix) if prefix.eq_ignore_ascii_case("sha256:") => &hash[7..], + _ => hash, + }; + Ok(stripped.trim().to_lowercase()) +} + +/// `CultMeshCdn.PackArtifact`: splits `bytes` into content-addressed chunks and builds the manifest. +/// An empty body packs as one zero-length chunk, as the reference does. +pub fn pack_content( + artifact_id: &str, + kind: &str, + version: &str, + mime_type: &str, + created_at_utc: &str, + bytes: &[u8], + chunk_size: usize, +) -> Result<(CultMeshCdnArtifactManifest, Vec)> { + if artifact_id.trim().is_empty() { + bail!("Artifact id must be non-empty."); + } + if chunk_size == 0 || i32::try_from(chunk_size).is_err() { + bail!("ChunkSizeBytes must be greater than zero and fit in an int."); + } + let pieces: Vec<&[u8]> = if bytes.is_empty() { + vec![bytes] + } else { + bytes.chunks(chunk_size).collect() + }; + let mut offset = 0i64; + let mut chunks = Vec::with_capacity(pieces.len()); + let mut refs = Vec::with_capacity(pieces.len()); + for piece in pieces { + let chunk_hash = sha256_hex(piece); + refs.push(CultMeshCdnChunkRef { + record_key: chunk_record_key(&chunk_hash), + chunk_hash: chunk_hash.clone(), + offset, + // A piece is at most `chunk_size` bytes, which fits an i32 (checked above). + size_bytes: piece.len() as i32, + }); + offset += piece.len() as i64; + chunks.push(CultMeshCdnChunk { + chunk_hash, + payload: piece.to_vec(), + }); + } + let manifest = CultMeshCdnArtifactManifest { + artifact_id: artifact_id.to_string(), + kind: non_blank_or(kind, "asset"), + version: version.to_string(), + content_hash: sha256_hex(bytes), + size_bytes: bytes.len() as i64, + mime_type: non_blank_or(mime_type, "application/octet-stream"), + created_at_utc: created_at_utc.to_string(), + chunks: refs, + tags: Vec::new(), + metadata: BTreeMap::new(), + }; + validate_manifest(&manifest)?; + Ok((manifest, chunks)) +} + +fn non_blank_or(value: &str, default: &str) -> String { + if value.trim().is_empty() { + default.to_string() + } else { + value.to_string() + } +} + +/// The chunk list in offset order, as the reference reads it (`OrderBy(chunk => chunk.Offset)`). +fn in_offset_order(manifest: &CultMeshCdnArtifactManifest) -> Vec<&CultMeshCdnChunkRef> { + let mut refs: Vec<&CultMeshCdnChunkRef> = manifest.chunks.iter().collect(); + refs.sort_by_key(|chunk| chunk.offset); + refs +} + +/// `CultMeshCdn.ValidateManifestShape`: non-negative size, chunks contiguous from offset 0 once +/// sorted by offset, non-negative chunk sizes, and chunk sizes summing to the manifest size. +pub fn validate_manifest(manifest: &CultMeshCdnArtifactManifest) -> Result<()> { + if manifest.size_bytes < 0 { + bail!("CDN artifact manifest has a negative size."); + } + let mut expected_offset = 0i64; + for chunk in in_offset_order(manifest) { + if chunk.offset != expected_offset { + bail!("CDN artifact chunks are not contiguous."); + } + if chunk.size_bytes < 0 { + bail!("CDN artifact chunk has a negative size."); + } + expected_offset = expected_offset + .checked_add(i64::from(chunk.size_bytes)) + .ok_or_else(|| anyhow!("CDN artifact chunk sizes overflow."))?; + } + if expected_offset != manifest.size_bytes { + bail!("CDN artifact chunk sizes do not sum to the manifest size."); + } + Ok(()) +} + +/// `CultMeshCdn.ValidateChunk`: the chunk's size and full SHA-256 must be what the reference and +/// the chunk's own claim say. `ref_hash` is already normalized. +fn validate_chunk( + ref_hash: &str, + ref_size: i32, + claimed_hash: &str, + claimed_size: i64, + payload: &[u8], +) -> Result<()> { + if i64::try_from(payload.len()).ok() != Some(i64::from(ref_size)) || claimed_size != i64::from(ref_size) { + bail!("CDN artifact chunk payload metadata does not match its manifest reference."); + } + let actual = sha256_hex(payload); + if ref_hash != actual || normalize_hash(claimed_hash)? != actual { + bail!("CDN artifact chunk hash does not match its payload."); + } + Ok(()) +} + +/// `CultMeshLegacyRudpContentServer.HandleAsync`, in its validation order: message id, hash +/// normalisation, record-key agreement with `mesh:cdn:chunk:`, lookup, then size and hash of +/// what is served. A failure is `found: false` with an empty payload and the reference's +/// `: ` in `error`; it is never silence. `lookup` takes the normalized hash. +pub fn answer_content_chunk_request<'a>( + request: &CultNetMessage, + lookup: impl Fn(&str) -> Option<&'a [u8]>, +) -> CultNetMessage { + let CultNetMessage::ContentChunkRequest { + message_id, + chunk_hash, + record_key, + expected_size_bytes, + } = request + else { + return CultNetMessage::Error { + error: "not a cultmesh.content_chunk_request.v1 message".to_string(), + code: None, + details: None, + }; + }; + let served = (|| -> std::result::Result<(String, Vec), String> { + if message_id.trim().is_empty() { + return Err("InvalidDataException: Content chunk request requires a message identity.".to_string()); + } + let hash = normalize_hash(chunk_hash) + .map_err(|_| "ArgumentException: Hash must be non-empty. (Parameter 'ChunkHash')".to_string())?; + if !record_key.trim().is_empty() && *record_key != chunk_record_key(&hash) { + return Err("InvalidDataException: Content chunk record key disagrees with its content hash.".to_string()); + } + let payload = lookup(&hash).ok_or_else(|| "FileNotFoundException: Content chunk is not available.".to_string())?; + validate_chunk(&hash, *expected_size_bytes, &hash, payload.len() as i64, payload) + .map_err(|error| format!("InvalidDataException: {error}"))?; + Ok((hash, payload.to_vec())) + })(); + match served { + Ok((hash, payload)) => CultNetMessage::ContentChunkResponse { + message_id: message_id.clone(), + found: true, + chunk_hash: hash, + size_bytes: *expected_size_bytes, + payload, + error: String::new(), + }, + Err(error) => CultNetMessage::ContentChunkResponse { + message_id: message_id.clone(), + found: false, + chunk_hash: chunk_hash.clone(), + size_bytes: 0, + payload: Vec::new(), + error, + }, + } +} + +/// The client half: fetches every chunk of `manifest` through `ask`, one in flight, in offset +/// order, and returns the body only after each chunk and then the whole body verify. `max_bytes` +/// is checked against the manifest before the first request. `ask` sends a request on the +/// caller's session and returns the answer; it owns transport, this function owns verification. +pub fn fetch_content( + manifest: &CultMeshCdnArtifactManifest, + max_bytes: u64, + mut ask: impl FnMut(CultNetMessage) -> Result, +) -> Result> { + validate_manifest(manifest)?; + if manifest.size_bytes as u64 > max_bytes { + bail!( + "CDN artifact of {} bytes exceeds the {max_bytes}-byte cap.", + manifest.size_bytes + ); + } + let mut body = Vec::new(); + for chunk in in_offset_order(manifest) { + let hash = normalize_hash(&chunk.chunk_hash)?; + let message_id = uuid::Uuid::new_v4().simple().to_string(); + let record_key = if chunk.record_key.trim().is_empty() { + chunk_record_key(&hash) + } else { + chunk.record_key.clone() + }; + let answer = ask(CultNetMessage::ContentChunkRequest { + message_id: message_id.clone(), + chunk_hash: hash.clone(), + record_key, + expected_size_bytes: chunk.size_bytes, + })?; + let CultNetMessage::ContentChunkResponse { + message_id: answered, + found, + chunk_hash, + size_bytes, + payload, + error, + } = answer + else { + bail!("chunk '{hash}' was answered with something other than a content chunk response"); + }; + if answered != message_id { + bail!("chunk '{hash}' was answered for message '{answered}', not '{message_id}'"); + } + if !found { + bail!("content provider rejected chunk '{hash}': {error}"); + } + validate_chunk(&hash, chunk.size_bytes, &chunk_hash, i64::from(size_bytes), &payload)?; + body.extend_from_slice(&payload); + } + if sha256_hex(&body) != normalize_hash(&manifest.content_hash)? { + bail!("CDN artifact content hash does not match its manifest."); + } + Ok(body) +} diff --git a/packages/cultnet-rs/src/contracts.rs b/packages/cultnet-rs/src/contracts.rs index 68edf97a..038b0708 100644 --- a/packages/cultnet-rs/src/contracts.rs +++ b/packages/cultnet-rs/src/contracts.rs @@ -508,6 +508,26 @@ pub enum CultNetMessage { #[serde(default, skip_serializing_if = "Option::is_none")] source_runtime_id: Option, }, + /// `cultmesh.content_chunk_request.v1`. Mirrors `CultMeshContentChunkRequestMessage`; raw path. + #[serde(rename = "cultmesh.content_chunk_request.v1", rename_all = "camelCase")] + ContentChunkRequest { + message_id: String, + chunk_hash: String, + record_key: String, + expected_size_bytes: i32, + }, + /// `cultmesh.content_chunk_response.v1`. Mirrors `CultMeshContentChunkResponseMessage`. `payload` + /// is `bin`, so it travels the raw path; the serde attribute never runs on the wire. + #[serde(rename = "cultmesh.content_chunk_response.v1", rename_all = "camelCase")] + ContentChunkResponse { + message_id: String, + found: bool, + chunk_hash: String, + size_bytes: i32, + #[serde(with = "serde_bytes")] + payload: Vec, + error: String, + }, } fn messagepack_base64_encoding() -> String { @@ -529,6 +549,8 @@ pub fn parse_cultnet_message( "cultnet.document_put_raw.v0" | "cultnet.snapshot_response_raw.v0" | "cultnet.snapshot_response_raw.v1" + | "cultmesh.content_chunk_request.v1" + | "cultmesh.content_chunk_response.v1" | "cultnet.error.v0", ) => parse_raw_cultnet_schema_message(wire_value)?, _ => { @@ -553,6 +575,8 @@ pub fn encode_cultnet_message_for_wire( CultNetMessage::DocumentPutRaw { .. } | CultNetMessage::SnapshotResponseRaw { .. } | CultNetMessage::SnapshotResponseRawV1 { .. } + | CultNetMessage::ContentChunkRequest { .. } + | CultNetMessage::ContentChunkResponse { .. } | CultNetMessage::Error { .. } => encode_raw_cultnet_schema_message(message), _ => Ok(rmp_serde::from_slice(&rmp_serde::to_vec( &serde_json::to_value(message)?, @@ -777,6 +801,40 @@ fn validate_message(message: &CultNetMessage) -> Result<()> { validate_shard_descriptor(shard)?; } } + CultNetMessage::ContentChunkRequest { + message_id, + chunk_hash, + record_key: _, + expected_size_bytes, + } => { + require_non_empty(message_id, "messageId")?; + if crate::normalize_hash(chunk_hash)?.is_empty() { + return Err(anyhow!("CultNet field chunkHash must be non-empty")); + } + if *expected_size_bytes < 0 { + return Err(anyhow!("CultNet field expectedSizeBytes must not be negative")); + } + } + CultNetMessage::ContentChunkResponse { + message_id, + found, + chunk_hash: _, + size_bytes, + payload, + error, + } => { + require_non_empty(message_id, "messageId")?; + if *found { + if i64::try_from(payload.len()).ok() != Some(i64::from(*size_bytes)) { + return Err(anyhow!("CultNet field payload length must equal sizeBytes")); + } + if !error.is_empty() { + return Err(anyhow!("CultNet field error must be empty when found")); + } + } else if !payload.is_empty() { + return Err(anyhow!("CultNet field payload must be empty when not found")); + } + } CultNetMessage::OperationRequest { message_id, service_id, @@ -1044,6 +1102,23 @@ fn parse_raw_cultnet_schema_message(input: &rmpv::Value) -> Result Ok(CultNetMessage::ContentChunkRequest { + message_id: require_legacy_string(get("messageId"), "messageId")?, + chunk_hash: require_legacy_string(get("chunkHash"), "chunkHash")?, + record_key: require_legacy_string(get("recordKey"), "recordKey")?, + expected_size_bytes: require_legacy_i32(get("expectedSizeBytes"), "expectedSizeBytes")?, + }), + "cultmesh.content_chunk_response.v1" => Ok(CultNetMessage::ContentChunkResponse { + message_id: require_legacy_string(get("messageId"), "messageId")?, + found: require_legacy_bool(get("found"), "found")?, + chunk_hash: require_legacy_string(get("chunkHash"), "chunkHash")?, + size_bytes: require_legacy_i32(get("sizeBytes"), "sizeBytes")?, + payload: get("payload") + .and_then(rmpv::Value::as_slice) + .ok_or_else(|| anyhow!("payload must be binary data"))? + .to_vec(), + error: require_legacy_string(get("error"), "error")?, + }), "cultnet.error.v0" => { let code = get("code") .filter(|value| !value.is_nil()) @@ -1209,6 +1284,43 @@ fn encode_raw_cultnet_schema_message(message: &CultNetMessage) -> Result vec![ + ( + rmpv::Value::from("schemaVersion"), + rmpv::Value::from("cultmesh.content_chunk_request.v1"), + ), + (rmpv::Value::from("messageId"), rmpv::Value::from(message_id.as_str())), + (rmpv::Value::from("chunkHash"), rmpv::Value::from(chunk_hash.as_str())), + (rmpv::Value::from("recordKey"), rmpv::Value::from(record_key.as_str())), + ( + rmpv::Value::from("expectedSizeBytes"), + rmpv::Value::from(*expected_size_bytes), + ), + ], + CultNetMessage::ContentChunkResponse { + message_id, + found, + chunk_hash, + size_bytes, + payload, + error, + } => vec![ + ( + rmpv::Value::from("schemaVersion"), + rmpv::Value::from("cultmesh.content_chunk_response.v1"), + ), + (rmpv::Value::from("messageId"), rmpv::Value::from(message_id.as_str())), + (rmpv::Value::from("found"), rmpv::Value::from(*found)), + (rmpv::Value::from("chunkHash"), rmpv::Value::from(chunk_hash.as_str())), + (rmpv::Value::from("sizeBytes"), rmpv::Value::from(*size_bytes)), + (rmpv::Value::from("payload"), rmpv::Value::Binary(payload.clone())), + (rmpv::Value::from("error"), rmpv::Value::from(error.as_str())), + ], // R-N: matches the landed C# `CultNetErrorMessage` // (src/GameCult.Networking/CultNetSchemaMessages.cs) key for key and in its declared // order - schemaVersion, error, routingHint, code, details - with every optional key @@ -1422,6 +1534,13 @@ fn require_legacy_u32(value: Option<&rmpv::Value>, field_name: &str) -> Result, field_name: &str) -> Result { + let number = value + .and_then(rmpv::Value::as_i64) + .ok_or_else(|| anyhow!("{field_name} must be an integer"))?; + i32::try_from(number).map_err(|_| anyhow!("{field_name} does not fit in i32")) +} + fn require_legacy_u64(value: Option<&rmpv::Value>, field_name: &str) -> Result { value .and_then(rmpv::Value::as_u64) diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index cf858647..5bfd1857 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -1,3 +1,4 @@ +mod content; mod contracts; mod idunn_deployment_brake; mod idunn_lifecycle_brake; @@ -19,6 +20,7 @@ mod selection; mod shard_catalog; mod transport; +pub use content::*; pub use contracts::*; pub use idunn_deployment_brake::*; pub use idunn_lifecycle_brake::*; diff --git a/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs b/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs new file mode 100644 index 00000000..2e156891 --- /dev/null +++ b/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using FluentAssertions; +using GameCult.Caching; +using GameCult.Networking; +using MessagePack; +using NUnit.Framework; + +namespace GameCult.Mesh.Tests; + +/// +/// Content-plane parity vectors shared with packages/cultnet-rs/tests/content.rs. Each runtime +/// writes its own file under contracts/cultmesh and judges both. The chunk answers in these +/// files are produced by itself, so the failure +/// spellings are the reference's own bytes. +/// +[TestFixture] +public sealed class CultMeshContentVectorTests +{ + private const int BodyLength = 1_315_551; + private const int ChunkSize = 262_144; + private const string CreatedAtUtc = "2026-09-22T00:00:00.0000000+00:00"; + private const string ArtifactId = "eureka/content-vector"; + + private sealed record Vector(string Label, string Kind, byte[] Bytes); + + [Test] + public void WriteContentVectors() + { + if (Environment.GetEnvironmentVariable("CULTNET_WRITE_VECTORS") != "1") + Assert.Ignore("Set CULTNET_WRITE_VECTORS=1 to (re)write the committed vector file."); + File.WriteAllText(VectorPath("content-vectors.cs-written.json"), ToJson(BuildVectors(out _, out _))); + } + + [Test] + public void CommittedCsVectorsEqualAFreshEncode() + { + var fresh = BuildVectors(out _, out _); + var committed = ReadVectors("content-vectors.cs-written.json"); + committed.Select(v => (v.Label, v.Kind)).Should().Equal(fresh.Select(v => (v.Label, v.Kind))); + foreach (var (expected, actual) in fresh.Zip(committed)) + actual.Bytes.Should().Equal(expected.Bytes, $"vector '{actual.Label}' drifted from the reference's encode"); + } + + [Test] + public void RustVectorsDecodeInTheReference() + { + BuildVectors(out var cache, out var messages); + var rust = ReadVectors("content-vectors.rs-written.json"); + rust.Should().NotBeEmpty(); + rust.Select(v => v.Label).Should().Equal(messages.Keys, "both runtimes write the same labelled vectors"); + foreach (var vector in rust) + { + var expected = messages[vector.Label]; + switch (vector.Kind) + { + case "request": + var request = MessagePackSerializer.Deserialize(vector.Bytes, CultNetSchemaMessageSerialization.Options); + request.Should().BeEquivalentTo((CultMeshContentChunkRequestMessage)expected); + Reencode(request).Should().Equal(vector.Bytes, vector.Label); + break; + case "response": + var response = MessagePackSerializer.Deserialize(vector.Bytes, CultNetSchemaMessageSerialization.Options); + response.Should().BeEquivalentTo((CultMeshContentChunkResponseMessage)expected); + Reencode(response).Should().Equal(vector.Bytes, vector.Label); + break; + case "manifest": + var manifest = MessagePackSerializer.Deserialize(vector.Bytes, CultNetSchemaMessageSerialization.Options); + manifest.Should().BeEquivalentTo((CultMeshCdnArtifactManifest)expected); + Reencode(manifest).Should().Equal(vector.Bytes, vector.Label); + break; + default: + Assert.Fail($"unknown vector kind '{vector.Kind}'"); + break; + } + } + + // Rust's answers to Rust's requests must be what the reference answers to the same bytes. + foreach (var vector in rust.Where(v => v.Label.EndsWith(".request", StringComparison.Ordinal))) + { + var request = MessagePackSerializer.Deserialize(vector.Bytes, CultNetSchemaMessageSerialization.Options); + var rustAnswer = rust.Single(v => v.Label == vector.Label[..^".request".Length] + ".response"); + Reencode(Answer(cache, request)).Should().Equal(rustAnswer.Bytes, vector.Label); + } + } + + [Test] + public void PackArtifactOfTheFixtureBodyEqualsTheFixtureManifest() + { + var artifact = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options()); + var committed = ReadVectors("content-vectors.cs-written.json").Single(v => v.Label == "manifest"); + Reencode(artifact.Manifest).Should().Equal(committed.Bytes); + var rust = ReadVectors("content-vectors.rs-written.json").Single(v => v.Label == "manifest"); + rust.Bytes.Should().Equal(committed.Bytes, "Rust's pack_content and the reference pack the same bytes to the same manifest"); + } + + private static byte[] Body() => + Enumerable.Range(0, BodyLength).Select(i => (byte)(i % 251)).ToArray(); + + private static CultMeshCdnPackOptions Options() => new() + { + ChunkSizeBytes = ChunkSize, + Version = "1", + MimeType = "application/x-cultnet-vector", + CreatedAtUtc = CreatedAtUtc + }; + + private static byte[] Reencode(CultMeshContentChunkRequestMessage message) => + CultNetSchemaMessageSerialization.Serialize(message); + + private static byte[] Reencode(CultMeshContentChunkResponseMessage message) => + CultNetSchemaMessageSerialization.Serialize(message); + + private static byte[] Reencode(CultMeshCdnArtifactManifest manifest) => + MessagePackSerializer.Serialize(manifest, CultNetSchemaMessageSerialization.Options); + + private static CultMeshContentChunkRequestMessage Request(string id, string hash, string key, int size) => new() + { + MessageId = id, + ChunkHash = hash, + RecordKey = key, + ExpectedSizeBytes = size + }; + + /// The cs-written file's vectors, in file order. Messages are keyed by label. + private static List BuildVectors(out CultCache cache, out Dictionary messages) + { + var artifact = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options()); + var content = new CultCache(CultMesh.CreateCultCacheDocumentRegistry( + typeof(CultMeshCdnArtifactManifest), typeof(CultMeshCdnArtifactChunk))); + CultMeshCdn.PublishAsync(content, artifact).GetAwaiter().GetResult(); + cache = content; + + var last = artifact.Chunks[^1]; + var key = "mesh:cdn:chunk:" + last.ChunkHash; + var lastDigit = last.ChunkHash[^1] == '0' ? '1' : '0'; + var vectors = new List(); + var map = new Dictionary(StringComparer.Ordinal); + messages = map; + + void AddRequest(string label, CultMeshContentChunkRequestMessage message) + { + map[label] = message; + vectors.Add(new Vector(label, "request", Reencode(message))); + } + + void AddResponse(string label, CultMeshContentChunkResponseMessage message) + { + map[label] = message; + vectors.Add(new Vector(label, "response", Reencode(message))); + } + + void AddAnswer(string name, CultMeshContentChunkRequestMessage request) + { + AddRequest(name + ".request", request); + AddResponse(name + ".response", Answer(content, request)); + } + + AddAnswer("answer_found", Request("vector-found", "SHA256:" + last.ChunkHash, key, last.SizeBytes)); + AddAnswer("answer_not_found", Request("vector-missing", new string('0', 64), string.Empty, 100)); + AddAnswer("answer_record_key_disagrees", Request("vector-key", last.ChunkHash, "mesh:cdn:chunk:other", last.SizeBytes)); + AddAnswer("answer_size_mismatch", Request("vector-size", last.ChunkHash, key, last.SizeBytes - 1)); + AddResponse("response_hash_last_digit", new CultMeshContentChunkResponseMessage + { + MessageId = "vector-digit", + Found = true, + ChunkHash = last.ChunkHash[..^1] + lastDigit, + SizeBytes = last.SizeBytes, + Payload = last.Payload, + Error = string.Empty + }); + + void AddManifest(string label, CultMeshCdnArtifactManifest manifest) + { + map[label] = manifest; + vectors.Add(new Vector(label, "manifest", Reencode(manifest))); + } + + AddManifest("manifest", artifact.Manifest); + var shuffled = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options()).Manifest; + shuffled.Chunks = new[] { 3, 0, 5, 1, 4, 2 }.Select(i => shuffled.Chunks[i]).ToArray(); + AddManifest("manifest_out_of_order", shuffled); + AddManifest("manifest_empty_body", CultMeshCdn.PackArtifact(ArtifactId, Array.Empty(), Options()).Manifest); + return vectors; + } + + private static CultMeshContentChunkResponseMessage Answer(CultCache cache, CultMeshContentChunkRequestMessage request) + { + var host = new ReferenceHost(); + using var server = new CultMeshLegacyRudpContentServer(host, cache); + var peer = new ReferencePeer(); + host.Dispatch(request, peer).GetAwaiter().GetResult(); + return peer.Sent ?? throw new InvalidOperationException("The reference server answered with silence."); + } + + private sealed class ReferenceHost : ICultNetSchemaServer + { + private Func? _handler; + + public void OnCultNet(Func callback) + where TMessage : ICultNetSchemaMessage => + _handler = (Func)(object)callback; + + public void RemoveCultNetMessageListener(Delegate callback) + where TMessage : ICultNetSchemaMessage => _handler = null; + + public Task Dispatch(CultMeshContentChunkRequestMessage request, ICultNetSchemaServerPeer peer) => + _handler!(request, peer); + } + + private sealed class ReferencePeer : ICultNetSchemaServerPeer + { + public CultMeshContentChunkResponseMessage? Sent { get; private set; } + + public void SendCultNet(TMessage message) where TMessage : ICultNetSchemaMessage => + Sent = (CultMeshContentChunkResponseMessage)(object)message; + } + + private static string ToJson(List vectors) => JsonSerializer.Serialize( + new + { + vectors = vectors.Select(v => new + { + label = v.Label, + kind = v.Kind, + messagePackBase64 = Convert.ToBase64String(v.Bytes) + }) + }, + new JsonSerializerOptions { WriteIndented = true }); + + private static List ReadVectors(string name) + { + var path = VectorPath(name); + if (!File.Exists(path)) + Assert.Inconclusive($"{path} is missing - write it first (CULTNET_WRITE_VECTORS=1)."); + using var document = JsonDocument.Parse(File.ReadAllText(path)); + return document.RootElement.GetProperty("vectors").EnumerateArray() + .Select(v => new Vector( + v.GetProperty("label").GetString()!, + v.GetProperty("kind").GetString()!, + Convert.FromBase64String(v.GetProperty("messagePackBase64").GetString()!))) + .ToList(); + } + + private static string VectorPath(string name) => Path.Combine(RepoRoot(), "contracts", "cultmesh", name); + + private static string RepoRoot() + { + var directory = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); + while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CultLib.sln"))) + directory = directory.Parent; + return directory?.FullName ?? throw new InvalidOperationException("CultLib.sln was not found above the test directory."); + } +} From 11485fb4914a3e0778ffb2f44e8381e38f53812f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 00:49:58 +0200 Subject: [PATCH 12/64] Pin the content plane against the reference's bytes content-vectors.cs-written.json is written by CultMeshContentVectorTests on Linux, and includes the answers CultMeshLegacyRudpContentServer gives, so the failure spellings are the reference's. tests/content.rs judges it. The rs-written mirror follows in the next commit. Co-Authored-By: Claude Sonnet 5 --- .../cultmesh/content-vectors.cs-written.json | 64 +++ packages/cultnet-rs/tests/content.rs | 520 ++++++++++++++++++ 2 files changed, 584 insertions(+) create mode 100644 contracts/cultmesh/content-vectors.cs-written.json create mode 100644 packages/cultnet-rs/tests/content.rs diff --git a/contracts/cultmesh/content-vectors.cs-written.json b/contracts/cultmesh/content-vectors.cs-written.json new file mode 100644 index 00000000..30a139ed --- /dev/null +++ b/contracts/cultmesh/content-vectors.cs-written.json @@ -0,0 +1,64 @@ +{ + "vectors": [ + { + "label": "answer_found.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkrHZlY3Rvci1mb3VuZKljaHVua0hhc2jZR1NIQTI1Njo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXJlY29yZEtledlPbWVzaDpjZG46Y2h1bms6NTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y7FleHBlY3RlZFNpemVCeXRlc80S3w==" + }, + { + "label": "answer_found.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKx2ZWN0b3ItZm91bmSlZm91bmTDqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXPNEt\u002BncGF5bG9hZMUS3/n6AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0\u002BP0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn\u002BAgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq\u002BwsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5\u002Bjp6uvs7e7v8PHy8/T19vf4\u002BfoAAQIDBAUGBwgJCgsMDQ4PEBESExQ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request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkrnZlY3Rvci1taXNzaW5nqWNodW5rSGFzaNlAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMKlyZWNvcmRLZXmgsWV4cGVjdGVkU2l6ZUJ5dGVzZA==" + }, + { + "label": "answer_not_found.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK52ZWN0b3ItbWlzc2luZ6Vmb3VuZMKpY2h1bmtIYXNo2UAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2TZGaWxlTm90Rm91bmRFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgaXMgbm90IGF2YWlsYWJsZS4=" + }, + { + "label": "answer_record_key_disagrees.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkqnZlY3Rvci1rZXmpY2h1bmtIYXNo2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXJlY29yZEtlebRtZXNoOmNkbjpjaHVuazpvdGhlcrFleHBlY3RlZFNpemVCeXRlc80S3w==" + }, + { + "label": "answer_record_key_disagrees.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKp2ZWN0b3Ita2V5pWZvdW5kwqljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpc2l6ZUJ5dGVzAKdwYXlsb2FkxAClZXJyb3LZT0ludmFsaWREYXRhRXhjZXB0aW9uOiBDb250ZW50IGNodW5rIHJlY29yZCBrZXkgZGlzYWdyZWVzIHdpdGggaXRzIGNvbnRlbnQgaGFzaC4=" + }, + { + "label": "answer_size_mismatch.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkq3ZlY3Rvci1zaXplqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lyZWNvcmRLZXnZT21lc2g6Y2RuOmNodW5rOjU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOxZXhwZWN0ZWRTaXplQnl0ZXPNEt4=" + }, + { + "label": "answer_size_mismatch.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKt2ZWN0b3Itc2l6ZaVmb3VuZMKpY2h1bmtIYXNo2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2WBJbnZhbGlkRGF0YUV4Y2VwdGlvbjogQ0ROIGFydGlmYWN0IGNodW5rIHBheWxvYWQgbWV0YWRhdGE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MWMxNDlhZmJmNGM4OTk2ZmI5MjQyN2FlNDFlNDY0OWI5MzRjYTQ5NTk5MWI3ODUyYjg1NZCA" + } + ] +} diff --git a/packages/cultnet-rs/tests/content.rs b/packages/cultnet-rs/tests/content.rs new file mode 100644 index 00000000..363a600d --- /dev/null +++ b/packages/cultnet-rs/tests/content.rs @@ -0,0 +1,520 @@ +//! The content plane (`src/content.rs`, the two chunk messages in `src/contracts.rs`), pinned against +//! the C# reference. `contracts/cultmesh/content-vectors.cs-written.json` is the reference's own +//! bytes (written by `CultMeshContentVectorTests`, including the answers `CultMeshLegacyRudpContentServer` +//! gives); `content-vectors.rs-written.json` is this binary's mirror, regenerated with +//! `CULTNET_WRITE_VECTORS=1`, and judged by the C# side. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use base64::Engine; +use cultnet_rs::{ + CultMeshCdnArtifactManifest, CultNetMessage, CultNetWireContract, answer_content_chunk_request, + decode_cultnet_message_from_slice, encode_cultnet_message_for_wire, encode_cultnet_message_to_vec, + fetch_content, normalize_hash, pack_content, validate_manifest, +}; +use serde::{Deserialize, Serialize}; + +const CHUNK: usize = 262_144; +const BODY_LEN: usize = 1_315_551; +const CREATED: &str = "2026-09-22T00:00:00.0000000+00:00"; +const SCHEMA_V0: CultNetWireContract = CultNetWireContract::CultNetSchemaV0; + +fn body() -> Vec { + (0..BODY_LEN).map(|i| (i % 251) as u8).collect() +} + +fn pack(bytes: &[u8]) -> (CultMeshCdnArtifactManifest, Vec) { + pack_content( + "eureka/content-vector", + "asset", + "1", + "application/x-cultnet-vector", + CREATED, + bytes, + CHUNK, + ) + .expect("packs") +} + +fn store(chunks: &[cultnet_rs::CultMeshCdnChunk]) -> HashMap> { + chunks + .iter() + .map(|chunk| (chunk.chunk_hash.clone(), chunk.payload.clone())) + .collect() +} + +fn lookup_in<'a>(store: &'a HashMap>) -> impl Fn(&str) -> Option<&'a [u8]> { + move |hash| store.get(hash).map(Vec::as_slice) +} + +fn wire(message: &CultNetMessage) -> Vec { + encode_cultnet_message_to_vec(message, SCHEMA_V0).expect("encodes") +} + +fn unwire(bytes: &[u8]) -> Result { + decode_cultnet_message_from_slice(bytes, SCHEMA_V0) +} + +fn manifest_bytes(manifest: &CultMeshCdnArtifactManifest) -> Vec { + rmp_serde::to_vec_named(manifest).expect("encodes") +} + +fn request(id: &str, hash: &str, key: &str, size: i32) -> CultNetMessage { + CultNetMessage::ContentChunkRequest { + message_id: id.to_string(), + chunk_hash: hash.to_string(), + record_key: key.to_string(), + expected_size_bytes: size, + } +} + +fn response_of(message: &CultNetMessage) -> (&str, bool, &str, &[u8], &str) { + match message { + CultNetMessage::ContentChunkResponse { + message_id, + found, + chunk_hash, + payload, + error, + .. + } => (message_id, *found, chunk_hash, payload, error), + other => panic!("not a content chunk response: {other:?}"), + } +} + +/// A transport closure that answers from `chunks` through the wire, counting calls. +fn serving<'a>( + chunks: &'a HashMap>, + calls: &'a std::cell::Cell, +) -> impl FnMut(CultNetMessage) -> Result + 'a { + move |message| { + calls.set(calls.get() + 1); + let request = unwire(&wire(&message))?; + unwire(&wire(&answer_content_chunk_request(&request, lookup_in(chunks)))) + } +} + +fn flip_last_digit(hash: &str) -> String { + let last = if hash.ends_with('0') { '1' } else { '0' }; + format!("{}{last}", &hash[..hash.len() - 1]) +} + +// ------------------------------------------------------------------------------------------ +// Vector files +// ------------------------------------------------------------------------------------------ + +#[derive(Serialize, Deserialize)] +struct VectorFile { + vectors: Vec, +} + +#[derive(Serialize, Deserialize)] +struct VectorEntry { + label: String, + kind: String, + #[serde(rename = "messagePackBase64")] + message_pack_base64: String, +} + +struct Vector { + label: String, + kind: &'static str, + bytes: Vec, +} + +fn vector_path(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("..") + .join("contracts") + .join("cultmesh") + .join(name) +} + +fn read_vectors(name: &str) -> Vec<(String, String, Vec)> { + let path = vector_path(name); + let text = std::fs::read_to_string(&path).unwrap_or_else(|_| { + panic!("{} is missing - write it first (CULTNET_WRITE_VECTORS=1)", path.display()) + }); + let file: VectorFile = serde_json::from_str(&text).expect("vector file parses"); + assert!(!file.vectors.is_empty(), "the vector file must carry at least one vector"); + file.vectors + .into_iter() + .map(|v| { + let bytes = base64::engine::general_purpose::STANDARD + .decode(&v.message_pack_base64) + .expect("base64"); + (v.label, v.kind, bytes) + }) + .collect() +} + +/// The vectors this runtime writes: the same labelled set the C# writer produces, built from Rust +/// values and answered by Rust's `answer_content_chunk_request`. +fn local_vectors() -> Vec { + let (manifest, chunks) = pack(&body()); + let store = store(&chunks); + let last = chunks.last().expect("chunks"); + let last_size = last.payload.len() as i32; + let key = format!("mesh:cdn:chunk:{}", last.chunk_hash); + let mut vectors = Vec::new(); + let mut push_message = |label: String, kind: &'static str, message: &CultNetMessage| { + vectors.push(Vector { label, kind, bytes: wire(message) }); + }; + let answers = [ + ("answer_found", request("vector-found", &format!("SHA256:{}", last.chunk_hash), &key, last_size)), + ("answer_not_found", request("vector-missing", &"0".repeat(64), "", 100)), + ( + "answer_record_key_disagrees", + request("vector-key", &last.chunk_hash, "mesh:cdn:chunk:other", last_size), + ), + ("answer_size_mismatch", request("vector-size", &last.chunk_hash, &key, last_size - 1)), + ]; + for (name, request) in &answers { + push_message(format!("{name}.request"), "request", request); + let answer = answer_content_chunk_request(request, lookup_in(&store)); + push_message(format!("{name}.response"), "response", &answer); + } + push_message( + "response_hash_last_digit".to_string(), + "response", + &CultNetMessage::ContentChunkResponse { + message_id: "vector-digit".to_string(), + found: true, + chunk_hash: flip_last_digit(&last.chunk_hash), + size_bytes: last_size, + payload: last.payload.clone(), + error: String::new(), + }, + ); + let mut push_manifest = |label: &str, manifest: &CultMeshCdnArtifactManifest| { + vectors.push(Vector { + label: label.to_string(), + kind: "manifest", + bytes: manifest_bytes(manifest), + }); + }; + push_manifest("manifest", &manifest); + let mut shuffled = manifest.clone(); + shuffled.chunks = [3, 0, 5, 1, 4, 2].iter().map(|&i| manifest.chunks[i].clone()).collect(); + push_manifest("manifest_out_of_order", &shuffled); + push_manifest("manifest_empty_body", &pack(&[]).0); + vectors +} + +fn to_json(vectors: &[Vector]) -> String { + let file = VectorFile { + vectors: vectors + .iter() + .map(|v| VectorEntry { + label: v.label.clone(), + kind: v.kind.to_string(), + message_pack_base64: base64::engine::general_purpose::STANDARD.encode(&v.bytes), + }) + .collect(), + }; + serde_json::to_string_pretty(&file).expect("serializes") +} + +/// The committed rs-written file is what this binary encodes now. Under `CULTNET_WRITE_VECTORS=1` +/// it is rewritten instead, for the C# test `RustVectorsDecodeInTheReference` to judge. +#[test] +fn rust_written_vectors_are_current() { + let fresh = local_vectors(); + let path = vector_path("content-vectors.rs-written.json"); + if std::env::var("CULTNET_WRITE_VECTORS").as_deref() == Ok("1") { + std::fs::write(&path, to_json(&fresh)).expect("writes the vector file"); + return; + } + let committed = read_vectors("content-vectors.rs-written.json"); + assert_eq!(committed.len(), fresh.len()); + for ((label, kind, bytes), fresh) in committed.iter().zip(&fresh) { + assert_eq!((label.as_str(), kind.as_str()), (fresh.label.as_str(), fresh.kind)); + assert_eq!(bytes, &fresh.bytes, "vector '{label}' drifted from this binary's encode"); + } +} + +/// Byte identity, both ways, against the reference's own bytes: every vector the reference wrote +/// decodes here and this runtime's independently built value encodes to exactly those bytes. The +/// manifest vector also pins `pack_content` (same body and options, same manifest, byte for byte). +#[test] +fn reference_vectors_encode_byte_identically() { + let local = local_vectors(); + let reference = read_vectors("content-vectors.cs-written.json"); + assert_eq!( + reference.iter().map(|(l, _, _)| l.as_str()).collect::>(), + local.iter().map(|v| v.label.as_str()).collect::>(), + "both runtimes write the same labelled vectors" + ); + for ((label, kind, reference_bytes), mine) in reference.iter().zip(&local) { + assert_eq!(reference_bytes, &mine.bytes, "vector '{label}' is not byte identical"); + match kind.as_str() { + "request" | "response" => { + let decoded = unwire(reference_bytes).expect("the reference's bytes decode"); + assert_eq!(&wire(&decoded), reference_bytes, "vector '{label}' does not re-encode identically"); + } + "manifest" => { + let decoded: CultMeshCdnArtifactManifest = + rmp_serde::from_slice(reference_bytes).expect("the reference's manifest decodes"); + assert_eq!(&manifest_bytes(&decoded), reference_bytes, "manifest '{label}' does not re-encode identically"); + } + other => panic!("unknown vector kind {other}"), + } + } +} + +/// F1's failure mode: a chunk response carries `bin`, which the JSON-value path cannot carry. +#[test] +fn a_chunk_response_carries_bin_through_the_raw_path() { + let payload: Vec = (0..=255u8).collect(); + let message = CultNetMessage::ContentChunkResponse { + message_id: "m".to_string(), + found: true, + chunk_hash: "ab".to_string(), + size_bytes: 256, + payload: payload.clone(), + error: String::new(), + }; + let wire_value = encode_cultnet_message_for_wire(&message, SCHEMA_V0).expect("encodes"); + let entries = wire_value.as_map().expect("a map"); + let (_, value) = entries.iter().find(|(k, _)| k.as_str() == Some("payload")).expect("payload key"); + assert!(matches!(value, rmpv::Value::Binary(bytes) if *bytes == payload), "payload must be bin"); + assert_eq!(unwire(&wire(&message)).expect("decodes"), message); +} + +#[test] +fn normalize_hash_matches_the_reference() { + for (input, expected) in [ + ("SHA256:ABCdef", "abcdef"), + ("sha256:abc", "abc"), + ("sha256: ABC ", "abc"), + (" ABC ", "abc"), + (" sha256:abc", "sha256:abc"), + ("sha256:", ""), + ("plain", "plain"), + ] { + assert_eq!(normalize_hash(input).expect("normalizes"), expected, "input {input:?}"); + } + for blank in ["", " "] { + assert!(normalize_hash(blank).is_err(), "{blank:?} must be refused"); + } + // The fixture's uppercase-prefix request names the same chunk as its bare hash. + let reference = read_vectors("content-vectors.cs-written.json"); + let (_, _, bytes) = reference.iter().find(|(l, _, _)| l == "answer_found.request").expect("vector"); + let CultNetMessage::ContentChunkRequest { chunk_hash, .. } = unwire(bytes).expect("decodes") else { + panic!("not a request"); + }; + assert!(chunk_hash.starts_with("SHA256:")); + let (_, chunks) = pack(&body()); + assert_eq!(normalize_hash(&chunk_hash).expect("normalizes"), chunks.last().unwrap().chunk_hash); +} + +#[test] +fn a_manifest_out_of_offset_order_is_accepted_as_the_reference_accepts_it() { + let reference = read_vectors("content-vectors.cs-written.json"); + let (_, _, bytes) = reference.iter().find(|(l, _, _)| l == "manifest_out_of_order").expect("vector"); + let manifest: CultMeshCdnArtifactManifest = rmp_serde::from_slice(bytes).expect("decodes"); + assert_ne!(manifest.chunks[0].offset, 0, "the fixture's chunk list is shuffled"); + validate_manifest(&manifest).expect("the reference accepts it"); + let (_, chunks) = pack(&body()); + let store = store(&chunks); + let calls = std::cell::Cell::new(0); + let fetched = fetch_content(&manifest, BODY_LEN as u64, serving(&store, &calls)).expect("fetches"); + assert_eq!(fetched, body()); + assert_eq!(calls.get(), 6); +} + +#[test] +fn a_hostile_manifest_is_refused_before_any_request() { + let (good, chunks) = pack(&body()); + let store = store(&chunks); + let mut hostile = Vec::new(); + let mut negative = good.clone(); + negative.size_bytes = -1; + hostile.push(negative); + let mut gap = good.clone(); + gap.chunks[2].offset += 1; + hostile.push(gap); + let mut overlap = good.clone(); + overlap.chunks[3].offset -= 1; + hostile.push(overlap); + let mut short = good.clone(); + short.size_bytes -= 1; + hostile.push(short); + let mut negative_chunk = good.clone(); + negative_chunk.chunks[5].size_bytes = -4831; + hostile.push(negative_chunk); + for manifest in hostile { + let calls = std::cell::Cell::new(0); + assert!(fetch_content(&manifest, u64::MAX, serving(&store, &calls)).is_err()); + assert_eq!(calls.get(), 0, "a corrupt manifest must not make the client ask"); + } +} + +#[test] +fn a_manifest_over_the_cap_is_refused_before_any_request() { + let (manifest, chunks) = pack(&body()); + let store = store(&chunks); + let size = BODY_LEN as u64; + + let calls = std::cell::Cell::new(0); + let fetched = fetch_content(&manifest, size, serving(&store, &calls)).expect("exactly the cap is accepted"); + assert_eq!(fetched.len(), BODY_LEN); + assert_eq!(calls.get(), 6); + + // One byte over, and sizes where doubling the cap would admit the body. + for cap in [size - 1, size / 2 + 1, size / 2, 0] { + let calls = std::cell::Cell::new(0); + assert!(fetch_content(&manifest, cap, serving(&store, &calls)).is_err(), "cap {cap} must refuse"); + assert_eq!(calls.get(), 0, "cap {cap} must refuse before any request"); + } +} + +#[test] +fn a_chunk_whose_hash_differs_in_the_last_digit_is_refused() { + let reference = read_vectors("content-vectors.cs-written.json"); + let (_, _, bytes) = reference.iter().find(|(l, _, _)| l == "response_hash_last_digit").expect("vector"); + let CultNetMessage::ContentChunkResponse { chunk_hash: claimed, payload, .. } = unwire(bytes).expect("decodes") else { + panic!("not a response"); + }; + // A one-chunk manifest for exactly that payload: its bytes are right, only the response's claim is off. + let (manifest, chunks) = pack(&payload); + let honest = chunks[0].chunk_hash.clone(); + assert_ne!(claimed, honest); + assert_eq!(claimed[..claimed.len() - 1], honest[..honest.len() - 1], "they differ in the last digit only"); + let error = fetch_content(&manifest, u64::MAX, |message| { + let CultNetMessage::ContentChunkRequest { message_id, .. } = message else { + panic!("not a request"); + }; + let CultNetMessage::ContentChunkResponse { found, size_bytes, payload, error, .. } = + unwire(bytes).expect("decodes") + else { + panic!("not a response"); + }; + Ok(CultNetMessage::ContentChunkResponse { + message_id, + found, + chunk_hash: claimed.clone(), + size_bytes, + payload, + error, + }) + }) + .expect_err("a hash off by one digit is a different hash"); + assert!(error.to_string().contains("does not match its payload"), "{error}"); +} + +#[test] +fn a_body_whose_chunks_verify_but_whole_hash_does_not_is_refused() { + let (mut manifest, chunks) = pack(&body()); + manifest.content_hash = pack(b"another body").0.content_hash; + let store = store(&chunks); + let calls = std::cell::Cell::new(0); + let error = fetch_content(&manifest, u64::MAX, serving(&store, &calls)).expect_err("whole body must verify"); + assert_eq!(calls.get(), 6, "every chunk verified; only the whole body is wrong"); + assert!(error.to_string().contains("content hash"), "{error}"); +} + +#[test] +fn a_response_for_another_message_id_is_refused() { + let (manifest, chunks) = pack(&body()); + let store = store(&chunks); + let error = fetch_content(&manifest, u64::MAX, |message| { + let mut answer = answer_content_chunk_request(&message, lookup_in(&store)); + if let CultNetMessage::ContentChunkResponse { message_id, .. } = &mut answer { + *message_id = "someone-else".to_string(); + } + Ok(answer) + }) + .expect_err("an answer to another request is not this answer"); + assert!(error.to_string().contains("someone-else"), "{error}"); +} + +#[test] +fn an_empty_body_packs_one_zero_length_chunk_and_fetches() { + let (manifest, chunks) = pack(&[]); + assert_eq!((manifest.chunks.len(), chunks.len(), manifest.size_bytes), (1, 1, 0)); + let store = store(&chunks); + let calls = std::cell::Cell::new(0); + assert_eq!(fetch_content(&manifest, 0, serving(&store, &calls)).expect("fetches"), Vec::::new()); + assert_eq!(calls.get(), 1); +} + +#[test] +fn answer_refuses_a_record_key_that_disagrees_with_its_hash() { + let (_, chunks) = pack(&body()); + let store = store(&chunks); + let last = chunks.last().unwrap(); + let asked = std::cell::Cell::new(false); + let answer = answer_content_chunk_request( + &request("m", &last.chunk_hash, "mesh:cdn:chunk:other", last.payload.len() as i32), + |hash| { + asked.set(true); + lookup_in(&store)(hash) + }, + ); + let (id, found, _, payload, error) = response_of(&answer); + assert_eq!((id, found, payload.len()), ("m", false, 0)); + assert_eq!(error, "InvalidDataException: Content chunk record key disagrees with its content hash."); + assert!(!asked.get(), "the key check precedes the lookup, as in HandleAsync"); +} + +/// Every failure is an answer (`found: false`, empty payload, the reference's spelling) and equals, +/// byte for byte, what `CultMeshLegacyRudpContentServer` answered to the same request bytes. +#[test] +fn answer_serves_found_false_with_the_reference_error_spelling() { + let (_, chunks) = pack(&body()); + let store = store(&chunks); + let reference = read_vectors("content-vectors.cs-written.json"); + let mut judged = 0; + for (label, _, request_bytes) in reference.iter().filter(|(l, _, _)| l.ends_with(".request")) { + let name = label.trim_end_matches(".request"); + let request = unwire(request_bytes).expect("decodes"); + let answer = answer_content_chunk_request(&request, lookup_in(&store)); + let (_, _, expected_bytes) = reference + .iter() + .find(|(l, _, _)| *l == format!("{name}.response")) + .expect("paired response"); + assert_eq!(&wire(&answer), expected_bytes, "{name}: answer differs from the reference's"); + let (_, found, _, payload, error) = response_of(&answer); + if name == "answer_found" { + assert!(found && error.is_empty() && !payload.is_empty()); + } else { + assert!(!found && payload.is_empty(), "{name}"); + assert!(error.contains("Exception: "), "{name}: {error}"); + } + judged += 1; + } + assert_eq!(judged, 4); +} + +#[test] +fn content_messages_refuse_what_the_reference_never_produces() { + let refused = |message: CultNetMessage| assert!(encode_cultnet_message_for_wire(&message, SCHEMA_V0).is_err(), "{message:?}"); + refused(request("", "abc", "", 1)); + refused(request("m", "sha256: ", "", 1)); + refused(request("m", "abc", "", -1)); + let response = |found: bool, size: i32, payload: &[u8], error: &str| CultNetMessage::ContentChunkResponse { + message_id: "m".to_string(), + found, + chunk_hash: "abc".to_string(), + size_bytes: size, + payload: payload.to_vec(), + error: error.to_string(), + }; + refused(response(true, 3, &[1, 2], "")); + refused(response(true, 2, &[1, 2], "boom")); + refused(response(false, 0, &[1], "boom")); + assert!(encode_cultnet_message_for_wire(&response(true, 2, &[1, 2], ""), SCHEMA_V0).is_ok()); + assert!(encode_cultnet_message_for_wire(&response(false, 0, &[], "boom"), SCHEMA_V0).is_ok()); +} + +#[test] +fn gamecult_networking_contract_refuses_content_messages() { + let legacy = CultNetWireContract::GameCultNetworkingV0; + let message = request("m", "abc", "", 1); + assert!(encode_cultnet_message_for_wire(&message, legacy).is_err()); + assert!(decode_cultnet_message_from_slice(&wire(&message), legacy).is_err()); +} From 8a66b1d23032564d4c660eac3a9ee0c886cf3f5d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 00:51:55 +0200 Subject: [PATCH 13/64] Commit the Rust-written content vectors and document the Rust content path content-vectors.rs-written.json is written by cultnet-rs and is identical to the reference's file. transport-planes.md and content-sessions.md name the Rust runtime's content path as the explicit compatibility path on the session the client already holds, lasting until an authenticated content connector exists behind the same fetch_content owner; runtime-parity-scope.md gets the evidence row. Co-Authored-By: Claude Sonnet 5 --- .../cultmesh/content-vectors.rs-written.json | 64 +++++++++++++++++++ docs/runtime-parity-scope.md | 10 +++ src/GameCult.Mesh/docs/content-sessions.md | 8 +++ src/GameCult.Mesh/docs/transport-planes.md | 8 +++ 4 files changed, 90 insertions(+) create mode 100644 contracts/cultmesh/content-vectors.rs-written.json diff --git a/contracts/cultmesh/content-vectors.rs-written.json b/contracts/cultmesh/content-vectors.rs-written.json new file mode 100644 index 00000000..c4b58833 --- /dev/null +++ b/contracts/cultmesh/content-vectors.rs-written.json @@ -0,0 +1,64 @@ +{ + "vectors": [ + { + "label": "answer_found.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkrHZlY3Rvci1mb3VuZKljaHVua0hhc2jZR1NIQTI1Njo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXJlY29yZEtledlPbWVzaDpjZG46Y2h1bms6NTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y7FleHBlY3RlZFNpemVCeXRlc80S3w==" + }, + { + "label": "answer_found.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKx2ZWN0b3ItZm91bmSlZm91bmTDqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXPNEt+ncGF5bG9hZMUS3/n6AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqK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MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMKlyZWNvcmRLZXmgsWV4cGVjdGVkU2l6ZUJ5dGVzZA==" + }, + { + "label": "answer_not_found.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK52ZWN0b3ItbWlzc2luZ6Vmb3VuZMKpY2h1bmtIYXNo2UAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2TZGaWxlTm90Rm91bmRFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgaXMgbm90IGF2YWlsYWJsZS4=" + }, + { + "label": "answer_record_key_disagrees.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkqnZlY3Rvci1rZXmpY2h1bmtIYXNo2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXJlY29yZEtlebRtZXNoOmNkbjpjaHVuazpvdGhlcrFleHBlY3RlZFNpemVCeXRlc80S3w==" + }, + { + "label": "answer_record_key_disagrees.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKp2ZWN0b3Ita2V5pWZvdW5kwqljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpc2l6ZUJ5dGVzAKdwYXlsb2FkxAClZXJyb3LZT0ludmFsaWREYXRhRXhjZXB0aW9uOiBDb250ZW50IGNodW5rIHJlY29yZCBrZXkgZGlzYWdyZWVzIHdpdGggaXRzIGNvbnRlbnQgaGFzaC4=" + }, + { + "label": "answer_size_mismatch.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkq3ZlY3Rvci1zaXplqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lyZWNvcmRLZXnZT21lc2g6Y2RuOmNodW5rOjU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOxZXhwZWN0ZWRTaXplQnl0ZXPNEt4=" + }, + { + "label": "answer_size_mismatch.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKt2ZWN0b3Itc2l6ZaVmb3VuZMKpY2h1bmtIYXNo2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2WBJbnZhbGlkRGF0YUV4Y2VwdGlvbjogQ0ROIGFydGlmYWN0IGNodW5rIHBheWxvYWQgbWV0YWRhdGEgZG9lcyBub3QgbWF0Y2ggaXRzIG1hbmlmZXN0IHJlZmVyZW5jZS4=" + }, + { + "label": "response_hash_last_digit", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW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ylNlAYzdmMWJkZTllMWVmYTdkMTM4NWQ1MWIwNzdlYTg3YjBjMzg2MGQyOGRhNDNkNWQ2ZjIyMWU4NDVjNGMyMzYwZs4ACAAAzgAEAADZT21lc2g6Y2RuOmNodW5rOmM3ZjFiZGU5ZTFlZmE3ZDEzODVkNTFiMDc3ZWE4N2IwYzM4NjBkMjhkYTQzZDVkNmYyMjFlODQ1YzRjMjM2MGaQgA==" + }, + { + "label": "manifest_empty_body", + "kind": "manifest", + "messagePackBase64": "mrVldXJla2EvY29udGVudC12ZWN0b3KlYXNzZXShMdlAZTNiMGM0NDI5OGZjMWMxNDlhZmJmNGM4OTk2ZmI5MjQyN2FlNDFlNDY0OWI5MzRjYTQ5NTk5MWI3ODUyYjg1NQC8YXBwbGljYXRpb24veC1jdWx0bmV0LXZlY3RvctkhMjAyNi0wOS0yMlQwMDowMDowMC4wMDAwMDAwKzAwOjAwkZTZQGUzYjBjNDQyOThmYzFjMTQ5YWZiZjRjODk5NmZiOTI0MjdhZTQxZTQ2NDliOTM0Y2E0OTU5OTFiNzg1MmI4NTUAANlPbWVzaDpjZG46Y2h1bms6ZTNiMGM0NDI5OGZjMWMxNDlhZmJmNGM4OTk2ZmI5MjQyN2FlNDFlNDY0OWI5MzRjYTQ5NTk5MWI3ODUyYjg1NZCA" + } + ] +} diff --git a/docs/runtime-parity-scope.md b/docs/runtime-parity-scope.md index 72768673..109a287f 100644 --- a/docs/runtime-parity-scope.md +++ b/docs/runtime-parity-scope.md @@ -73,6 +73,16 @@ to speak CultNet or participate in CultMesh. `tests/GameCult.Networking.Tests/SelectionParityVectorTests.cs` carry the semantic ones. A single rows-to-bytes path driving both halves in one call remains its own cut (R-AR) and is not part of this claim. +- CultMesh content plane (`cultmesh.content_chunk_request.v1` and `.response.v1` + plus the CDN manifest, C#/Rust only): byte parity in both directions, and the + reference's answer to a chunk request, including its failure spellings. + `packages/cultnet-rs/tests/content.rs` and + `tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs` judge + `contracts/cultmesh/content-vectors.cs-written.json` and + `content-vectors.rs-written.json`. Rust carries these chunks only on the + session the client already holds (see `src/GameCult.Mesh/docs/transport-planes.md`); + it has no authenticated content connector, so it claims no TCP+TLS or QUIC + content path. ## Expansion Work Outside The Current Parity Claim diff --git a/src/GameCult.Mesh/docs/content-sessions.md b/src/GameCult.Mesh/docs/content-sessions.md index 313a21cf..673327e2 100644 --- a/src/GameCult.Mesh/docs/content-sessions.md +++ b/src/GameCult.Mesh/docs/content-sessions.md @@ -47,6 +47,14 @@ The content protocol uses one bounded response per manifest chunk. A snapshot response containing `gamecult.mesh.cdn_artifact_chunk.v1` payload records is a legacy transport path and must not be used for bulk delivery. +The Rust runtime speaks the same chunk messages through `cultnet-rs` +`fetch_content`, which verifies every chunk and then the whole body, and +`answer_content_chunk_request`, which mirrors the legacy server's validation +order and error spelling. Its transport is an explicit closure over the session +the caller already holds, carrying the chunks as ordinary schema frames until +Rust has an authenticated content connector; the chunk bytes, manifest shape +and verification do not change when that connector arrives. + The transfer owner may keep a bounded window of requests in flight per content hash (four by default, never more than 32). Candidate chunks can arrive out of order, but only the transfer owner writes them, and it flushes and checkpoints diff --git a/src/GameCult.Mesh/docs/transport-planes.md b/src/GameCult.Mesh/docs/transport-planes.md index eddb9794..ea6a6389 100644 --- a/src/GameCult.Mesh/docs/transport-planes.md +++ b/src/GameCult.Mesh/docs/transport-planes.md @@ -102,6 +102,14 @@ lower priority than TCP. Existing hot-state publishers that still package payloads as schema messages must move to the realtime connector contract; the new seam does not pretend that migration has already occurred. +The Rust runtime's content path is this compatibility path, chosen explicitly: +`cultnet-rs` sends chunk requests and reads chunk responses on the session the +client already holds, byte-identical on the wire to +`CultMeshLegacyRudpContentServer` (`fetch_content` and +`answer_content_chunk_request`). It is never an implicit default, and it lasts +until Rust has an authenticated content connector (TCP+TLS or QUIC), which will +sit behind the same `fetch_content` owner rather than beside it. + ## Security and release gate The current TCP control and content connectors are plaintext and therefore From 8b8650221bba433e9eb758c0c14ef131fa961cc4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:12:15 +0200 Subject: [PATCH 14/64] cultnet-ts: bound runtime presence detail by UTF-8 bytes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Rust owner refuses detail over 512 UTF-8 bytes; TypeScript counted UTF-16 units, so 300 x "é" was signed and then refused, and a slice inside a surrogate pair produced invalid UTF-8. One helper, truncateRuntimePresenceDetail, now cuts on a code point boundary at 512 bytes and serves both the publisher and validateRuntimePresence. Co-Authored-By: Claude Sonnet 5 --- .../cultnet-ts/src/idunn-runtime-authority.ts | 3 +- .../cultnet-ts/src/runtime-presence-health.ts | 21 ++++++++++++- .../test/runtime-presence-health.test.ts | 30 +++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index b675d5c3..d55c4dc4 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -9,6 +9,7 @@ import { IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, runtimePresenceActivationSigningMessage, runtimePresenceProofPayload, + truncateRuntimePresenceDetail, runtimePresenceProviderSigningMessage, encodeRuntimePresenceHealth, type RuntimePresenceHealth, @@ -241,7 +242,7 @@ export function createIdunnRuntimePresencePublisher( const signed = signIdunnRuntimePresence(options.authority, { capabilities: options.capabilities, state, - detail: detail.slice(0, 512), + detail: truncateRuntimePresenceDetail(detail), writeLeaseSha256, publisherSequence: sequence, observedAtUnixMillis: Date.now(), diff --git a/packages/cultnet-ts/src/runtime-presence-health.ts b/packages/cultnet-ts/src/runtime-presence-health.ts index 8d70da8e..4cdccd1e 100644 --- a/packages/cultnet-ts/src/runtime-presence-health.ts +++ b/packages/cultnet-ts/src/runtime-presence-health.ts @@ -171,6 +171,25 @@ function presenceTuple( return fields; } +/** The Rust owner (`cultnet-rs`) bounds presence detail by UTF-8 bytes, not UTF-16 units. */ +export const RUNTIME_PRESENCE_DETAIL_MAX_BYTES = 512; + +/** + * Longest prefix of `detail` within the UTF-8 byte limit, cut on a code point + * boundary. The single rule for both signing and validation: a detail is valid + * exactly when this returns it unchanged. + */ +export function truncateRuntimePresenceDetail(detail: string): string { + let bytes = 0; + let end = 0; + for (const char of detail) { + bytes += Buffer.byteLength(char, "utf8"); + if (bytes > RUNTIME_PRESENCE_DETAIL_MAX_BYTES) break; + end += char.length; + } + return detail.slice(0, end); +} + /** * Reject statements the contract forbids, before they are signed. * @@ -185,7 +204,7 @@ export function validateRuntimePresence(presence: RuntimePresenceHealth): void { if (presence.observedAtUnixMillis <= 0 || !Number.isSafeInteger(presence.observedAtUnixMillis)) { throw new Error("runtime presence observation time must be a positive integer"); } - if (presence.detail.length > 512 || /\p{Cc}/u.test(presence.detail)) { + if (truncateRuntimePresenceDetail(presence.detail) !== presence.detail || /\p{Cc}/u.test(presence.detail)) { throw new Error("runtime presence detail is too long or carries control characters"); } if (presence.state === "warming" && presence.writeLeaseSha256 !== null) { diff --git a/packages/cultnet-ts/test/runtime-presence-health.test.ts b/packages/cultnet-ts/test/runtime-presence-health.test.ts index fa21aeaa..5a4de05f 100644 --- a/packages/cultnet-ts/test/runtime-presence-health.test.ts +++ b/packages/cultnet-ts/test/runtime-presence-health.test.ts @@ -18,6 +18,7 @@ import { RUNTIME_PRESENCE_FIELD_COUNT, encodeRuntimePresenceHealth, runtimePresenceProofPayload, + truncateRuntimePresenceDetail, validateRuntimePresence, type RuntimePresenceHealth, } from "../src/runtime-presence-health"; @@ -121,3 +122,32 @@ test("statements the contract forbids are refused before they are signed", () => const partialLineage = { ...referencePresence(), stateContractSha256: null }; assert.throws(() => validateRuntimePresence(partialLineage), /state lineage is partial/); }); + +const utf8Bytes = (text: string) => Buffer.byteLength(text, "utf8"); +const isValidUtf8 = (text: string) => !Buffer.from(text, "utf8").toString("utf8").includes("\uFFFD") && !text.includes("\uFFFD"); + +test("presence detail is truncated to 512 UTF-8 bytes, not UTF-16 units", () => { + const truncated = truncateRuntimePresenceDetail("é".repeat(300)); + assert.ok(utf8Bytes(truncated) <= 512); + assert.equal(truncated, "é".repeat(256)); + assert.ok(isValidUtf8(truncated)); +}); + +test("presence detail drops a 4-byte character straddling the boundary whole", () => { + const truncated = truncateRuntimePresenceDetail("a".repeat(510) + "😀"); + assert.equal(truncated, "a".repeat(510)); + assert.ok(isValidUtf8(truncated)); + assert.equal(truncateRuntimePresenceDetail("a".repeat(508) + "😀"), "a".repeat(508) + "😀"); +}); + +test("presence detail of exactly 512 ASCII bytes passes unchanged and 513 is cut", () => { + const exact = "a".repeat(512); + assert.equal(truncateRuntimePresenceDetail(exact), exact); + assert.doesNotThrow(() => validateRuntimePresence({ ...referencePresence(), detail: exact })); + assert.equal(truncateRuntimePresenceDetail(exact + "a"), exact); + assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: exact + "a" }), /too long/); +}); + +test("validation refuses a detail that is short in UTF-16 units but over 512 UTF-8 bytes", () => { + assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: "é".repeat(300) }), /too long/); +}); From 8e578ea2ab27b7e2f37415b05967ba10a94ce683 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:12:15 +0200 Subject: [PATCH 15/64] cultnet-ts: delete unused readAuthorityRecordBytes Never called; removed with nothing else depending on it. Co-Authored-By: Claude Sonnet 5 --- packages/cultnet-ts/src/idunn-runtime-authority.ts | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index d55c4dc4..d96c892b 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -637,20 +637,6 @@ function providerIdentityByteVector(value: unknown, label: string): Uint8Array { return Uint8Array.from(value as number[]); } -function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string): Uint8Array { - const decoded = decode(bytes); - if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { - throw new Error("Runtime credential is not a CultCache v1 store."); - } - if (decoded[2].length !== 1) throw new Error("Runtime credential must contain exactly one record."); - const rows = (decoded[2] as unknown[]).filter((raw) => Array.isArray(raw) && raw[1] === schemaId); - if (rows.length !== 1) throw new Error(`Runtime credential must contain exactly one ${schemaId} record.`); - const catalog = (decoded[1] as unknown[]).find((raw) => Array.isArray(raw) && raw[0] === schemaId); - if (!Array.isArray(catalog) || catalog[1] !== type) throw new Error("Runtime credential has an unexpected CultCache type."); - const row = array(rows[0], 4, "Runtime credential record"); - return bytesValue(row[3], "Runtime credential payload"); -} - function inheritedDescriptorMap(): Map { if (!systemdListenPidMatches(process.env.LISTEN_PID, process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process."); const count = Number(process.env.LISTEN_FDS); From a957f07539055fff91e3f660cc48d22a543578d1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:19:41 +0200 Subject: [PATCH 16/64] cultnet-ts: one UTF-8 byte bound for presence and daemon health detail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit signed-daemon-health sliced detail at 512 UTF-16 units while the Rust owner counts bytes, so 300 x "é" failed shape validation. truncateUtf8Bytes now serves runtime presence and both daemon-health sites, replacing truncateRuntimePresenceDetail. It makes the string well formed first, so a lone surrogate becomes U+FFFD instead of invalid UTF-8 in msgpack. The unsigned payload is extracted as unsignedDaemonHealthPayload so it can be tested without a socket. Co-Authored-By: Claude Sonnet 5 --- .../cultnet-ts/src/idunn-runtime-authority.ts | 5 +- .../cultnet-ts/src/runtime-presence-health.ts | 20 ++------ .../cultnet-ts/src/signed-daemon-health.ts | 32 +++++++++---- packages/cultnet-ts/src/utf8-bound.ts | 20 ++++++++ .../test/runtime-presence-health.test.ts | 24 +++++++--- .../test/signed-daemon-health.test.ts | 48 +++++++++++++++++++ 6 files changed, 114 insertions(+), 35 deletions(-) create mode 100644 packages/cultnet-ts/src/utf8-bound.ts create mode 100644 packages/cultnet-ts/test/signed-daemon-health.test.ts diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index d96c892b..5ea30fff 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -6,14 +6,15 @@ import { decode, encode } from "@msgpack/msgpack"; import { GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME, + RUNTIME_PRESENCE_DETAIL_MAX_BYTES, IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, runtimePresenceActivationSigningMessage, runtimePresenceProofPayload, - truncateRuntimePresenceDetail, runtimePresenceProviderSigningMessage, encodeRuntimePresenceHealth, type RuntimePresenceHealth, } from "./runtime-presence-health"; +import { truncateUtf8Bytes } from "./utf8-bound"; import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord, type CultNetSnapshotRequestMessage } from "./contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; @@ -242,7 +243,7 @@ export function createIdunnRuntimePresencePublisher( const signed = signIdunnRuntimePresence(options.authority, { capabilities: options.capabilities, state, - detail: truncateRuntimePresenceDetail(detail), + detail: truncateUtf8Bytes(detail, RUNTIME_PRESENCE_DETAIL_MAX_BYTES), writeLeaseSha256, publisherSequence: sequence, observedAtUnixMillis: Date.now(), diff --git a/packages/cultnet-ts/src/runtime-presence-health.ts b/packages/cultnet-ts/src/runtime-presence-health.ts index 4cdccd1e..7f38fa6f 100644 --- a/packages/cultnet-ts/src/runtime-presence-health.ts +++ b/packages/cultnet-ts/src/runtime-presence-health.ts @@ -20,6 +20,8 @@ import { encode } from "@msgpack/msgpack"; +import { truncateUtf8Bytes } from "./utf8-bound"; + export const GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA = "gamecult.runtime_presence_health.v2"; /** Purpose for the stable provider-health signature over the proof payload. */ @@ -174,22 +176,6 @@ function presenceTuple( /** The Rust owner (`cultnet-rs`) bounds presence detail by UTF-8 bytes, not UTF-16 units. */ export const RUNTIME_PRESENCE_DETAIL_MAX_BYTES = 512; -/** - * Longest prefix of `detail` within the UTF-8 byte limit, cut on a code point - * boundary. The single rule for both signing and validation: a detail is valid - * exactly when this returns it unchanged. - */ -export function truncateRuntimePresenceDetail(detail: string): string { - let bytes = 0; - let end = 0; - for (const char of detail) { - bytes += Buffer.byteLength(char, "utf8"); - if (bytes > RUNTIME_PRESENCE_DETAIL_MAX_BYTES) break; - end += char.length; - } - return detail.slice(0, end); -} - /** * Reject statements the contract forbids, before they are signed. * @@ -204,7 +190,7 @@ export function validateRuntimePresence(presence: RuntimePresenceHealth): void { if (presence.observedAtUnixMillis <= 0 || !Number.isSafeInteger(presence.observedAtUnixMillis)) { throw new Error("runtime presence observation time must be a positive integer"); } - if (truncateRuntimePresenceDetail(presence.detail) !== presence.detail || /\p{Cc}/u.test(presence.detail)) { + if (truncateUtf8Bytes(presence.detail, RUNTIME_PRESENCE_DETAIL_MAX_BYTES) !== presence.detail || /\p{Cc}/u.test(presence.detail)) { throw new Error("runtime presence detail is too long or carries control characters"); } if (presence.state === "warming" && presence.writeLeaseSha256 !== null) { diff --git a/packages/cultnet-ts/src/signed-daemon-health.ts b/packages/cultnet-ts/src/signed-daemon-health.ts index d4f0f0ce..db800181 100644 --- a/packages/cultnet-ts/src/signed-daemon-health.ts +++ b/packages/cultnet-ts/src/signed-daemon-health.ts @@ -19,6 +19,10 @@ import { encode } from "@msgpack/msgpack"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; import { encodeCultNetMessageForWire } from "./contracts"; +import { truncateUtf8Bytes } from "./utf8-bound"; + +/** The Rust owner (`cultnet-rs`) bounds daemon health detail by UTF-8 bytes. */ +export const DAEMON_HEALTH_DETAIL_MAX_BYTES = 512; export const CULTNET_RUDP_PROTOCOL_ID = "cultnet.transport.rudp.v0"; @@ -120,15 +124,7 @@ export async function publishSignedDaemonHealth( const observedAt = health.observedAt || new Date().toISOString(); const signed = publisher.privateKey ? signedDaemonHealthPayload(publisher, health, observedAt) : null; - const payload = signed?.payload || encode([ - publisher.daemonId, - health.state, - String(health.detail || "").slice(0, 512), - observedAt, - publisher.healthContract, - "daemon-published", - CULTNET_RUDP_PROTOCOL_ID, - ]); + const payload = signed?.payload || unsignedDaemonHealthPayload(publisher, health, observedAt); const message = { schemaVersion: "cultnet.document_put_raw.v0", @@ -165,6 +161,22 @@ export async function publishSignedDaemonHealth( } } +export function unsignedDaemonHealthPayload( + publisher: SignedDaemonHealthPublisher, + health: DaemonHealth, + observedAt: string, +): Uint8Array { + return encode([ + publisher.daemonId, + health.state, + truncateUtf8Bytes(String(health.detail || ""), DAEMON_HEALTH_DETAIL_MAX_BYTES), + observedAt, + publisher.healthContract, + "daemon-published", + CULTNET_RUDP_PROTOCOL_ID, + ]); +} + export function signedDaemonHealthPayload( publisher: SignedDaemonHealthPublisher, health: DaemonHealth, @@ -185,7 +197,7 @@ export function signedDaemonHealthPayload( publisher.healthContract, publisher.sourceRuntimeId, health.state, - String(health.detail || "").slice(0, 512), + truncateUtf8Bytes(String(health.detail || ""), DAEMON_HEALTH_DETAIL_MAX_BYTES), publisher.signerIdentityId, publisher.publisherIncarnationId, publisher.publisherSequence, diff --git a/packages/cultnet-ts/src/utf8-bound.ts b/packages/cultnet-ts/src/utf8-bound.ts new file mode 100644 index 00000000..d21ee849 --- /dev/null +++ b/packages/cultnet-ts/src/utf8-bound.ts @@ -0,0 +1,20 @@ +/** + * Longest prefix of `value` whose UTF-8 encoding fits in `maxBytes`, cut on a + * code point boundary. Rust owners (`cultnet-rs`) bound strings by UTF-8 bytes, + * not UTF-16 units, so every TypeScript publisher bounds through this one path. + * + * Lone surrogates are replaced with U+FFFD first: they have no UTF-8 encoding, + * and a msgpack writer would otherwise emit invalid bytes that Rust refuses. + * A value is therefore in bounds exactly when this returns it unchanged. + */ +export function truncateUtf8Bytes(value: string, maxBytes: number): string { + const wellFormed = (value as string & { toWellFormed(): string }).toWellFormed(); + let bytes = 0; + let end = 0; + for (const char of wellFormed) { + bytes += Buffer.byteLength(char, "utf8"); + if (bytes > maxBytes) break; + end += char.length; + } + return wellFormed.slice(0, end); +} diff --git a/packages/cultnet-ts/test/runtime-presence-health.test.ts b/packages/cultnet-ts/test/runtime-presence-health.test.ts index 5a4de05f..2dc4a845 100644 --- a/packages/cultnet-ts/test/runtime-presence-health.test.ts +++ b/packages/cultnet-ts/test/runtime-presence-health.test.ts @@ -18,10 +18,10 @@ import { RUNTIME_PRESENCE_FIELD_COUNT, encodeRuntimePresenceHealth, runtimePresenceProofPayload, - truncateRuntimePresenceDetail, validateRuntimePresence, type RuntimePresenceHealth, } from "../src/runtime-presence-health"; +import { truncateUtf8Bytes } from "../src/utf8-bound"; // Read from the source tree, not a copy beside the compiled test: the vectors // are generated output and must have exactly one home. @@ -127,27 +127,39 @@ const utf8Bytes = (text: string) => Buffer.byteLength(text, "utf8"); const isValidUtf8 = (text: string) => !Buffer.from(text, "utf8").toString("utf8").includes("\uFFFD") && !text.includes("\uFFFD"); test("presence detail is truncated to 512 UTF-8 bytes, not UTF-16 units", () => { - const truncated = truncateRuntimePresenceDetail("é".repeat(300)); + const truncated = truncateUtf8Bytes("é".repeat(300), 512); assert.ok(utf8Bytes(truncated) <= 512); assert.equal(truncated, "é".repeat(256)); assert.ok(isValidUtf8(truncated)); }); test("presence detail drops a 4-byte character straddling the boundary whole", () => { - const truncated = truncateRuntimePresenceDetail("a".repeat(510) + "😀"); + const truncated = truncateUtf8Bytes("a".repeat(510) + "😀", 512); assert.equal(truncated, "a".repeat(510)); assert.ok(isValidUtf8(truncated)); - assert.equal(truncateRuntimePresenceDetail("a".repeat(508) + "😀"), "a".repeat(508) + "😀"); + assert.equal(truncateUtf8Bytes("a".repeat(508) + "😀", 512), "a".repeat(508) + "😀"); }); test("presence detail of exactly 512 ASCII bytes passes unchanged and 513 is cut", () => { const exact = "a".repeat(512); - assert.equal(truncateRuntimePresenceDetail(exact), exact); + assert.equal(truncateUtf8Bytes(exact, 512), exact); assert.doesNotThrow(() => validateRuntimePresence({ ...referencePresence(), detail: exact })); - assert.equal(truncateRuntimePresenceDetail(exact + "a"), exact); + assert.equal(truncateUtf8Bytes(exact + "a", 512), exact); assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: exact + "a" }), /too long/); }); test("validation refuses a detail that is short in UTF-16 units but over 512 UTF-8 bytes", () => { assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: "é".repeat(300) }), /too long/); }); + +test("a lone high surrogate at the end becomes U+FFFD and the result is valid UTF-8", () => { + const truncated = truncateUtf8Bytes("abc\uD83D", 512); + assert.equal(truncated, "abc\uFFFD"); + assert.equal(Buffer.from(truncated, "utf8").toString("utf8"), truncated); +}); + +test("a lone low surrogate in the middle becomes U+FFFD and the result is valid UTF-8", () => { + const truncated = truncateUtf8Bytes("ab\uDE00cd", 512); + assert.equal(truncated, "ab\uFFFDcd"); + assert.equal(Buffer.from(truncated, "utf8").toString("utf8"), truncated); +}); diff --git a/packages/cultnet-ts/test/signed-daemon-health.test.ts b/packages/cultnet-ts/test/signed-daemon-health.test.ts new file mode 100644 index 00000000..1c433b04 --- /dev/null +++ b/packages/cultnet-ts/test/signed-daemon-health.test.ts @@ -0,0 +1,48 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import { decode } from "@msgpack/msgpack"; + +import { + signedDaemonHealthPayload, + unsignedDaemonHealthPayload, + type SignedDaemonHealthPublisher, +} from "../src/signed-daemon-health"; + +function publisher(): SignedDaemonHealthPublisher { + return { + daemonId: "heimdall", + endpoint: { host: "127.0.0.1", port: 1 }, + healthContract: "contract", + publisherIncarnationId: "incarnation", + publisherSequence: 0, + sourceRuntimeId: "runtime", + contract: { + connectionId: 1, + signedSchemaId: "signed.schema", + unsignedSchemaId: "unsigned.schema", + } as SignedDaemonHealthPublisher["contract"], + privateKey: crypto.generateKeyPairSync("ed25519").privateKey, + signerIdentityId: "signer", + }; +} + +const observedAt = "2026-01-01T00:00:00.000Z"; +const detail = "é".repeat(300); + +function assertBounded(text: unknown) { + assert.equal(typeof text, "string"); + const bytes = Buffer.from(text as string, "utf8"); + assert.ok(bytes.length <= 512, `detail is ${bytes.length} bytes`); + assert.equal(bytes.toString("utf8"), text); +} + +test("unsigned daemon health detail is bounded by UTF-8 bytes", () => { + const fields = decode(unsignedDaemonHealthPayload(publisher(), { state: "ok", detail }, observedAt)) as unknown[]; + assertBounded(fields[2]); +}); + +test("signed daemon health detail is bounded by UTF-8 bytes", () => { + const { statement } = signedDaemonHealthPayload(publisher(), { state: "ok", detail }, observedAt); + assertBounded(statement[5]); +}); From 0791e1b7d0c1a97691819203a41c8f33a2e53015 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:21:18 +0200 Subject: [PATCH 17/64] Raise the TypeScript packages' Node floor to 20 The UTF-8 detail bound calls String.prototype.toWellFormed, which Node 20 introduced. Node 18 reached end of life in April 2025, and CI runs Node 24. All four TypeScript packages move together so the family keeps one floor. Co-Authored-By: Claude Opus 5.5 --- packages/cultcache-ts/package.json | 2 +- packages/cultmesh-browser/package.json | 2 +- packages/cultmesh-ts/package.json | 2 +- packages/cultnet-ts/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/cultcache-ts/package.json b/packages/cultcache-ts/package.json index 67f8d5ed..c708bfc9 100644 --- a/packages/cultcache-ts/package.json +++ b/packages/cultcache-ts/package.json @@ -45,7 +45,7 @@ }, "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultcache-ts#readme", "engines": { - "node": ">=18" + "node": ">=20" }, "dependencies": { "@msgpack/msgpack": "^3.1.3", diff --git a/packages/cultmesh-browser/package.json b/packages/cultmesh-browser/package.json index c49062b0..186ab630 100644 --- a/packages/cultmesh-browser/package.json +++ b/packages/cultmesh-browser/package.json @@ -37,7 +37,7 @@ "directory": "packages/cultmesh-browser" }, "engines": { - "node": ">=18" + "node": ">=20" }, "dependencies": { "@msgpack/msgpack": "^3.1.3", diff --git a/packages/cultmesh-ts/package.json b/packages/cultmesh-ts/package.json index 65a32110..4d59133a 100644 --- a/packages/cultmesh-ts/package.json +++ b/packages/cultmesh-ts/package.json @@ -40,7 +40,7 @@ }, "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultmesh-ts#readme", "engines": { - "node": ">=18" + "node": ">=20" }, "dependencies": { "@msgpack/msgpack": "^3.1.2", diff --git a/packages/cultnet-ts/package.json b/packages/cultnet-ts/package.json index d34278f5..f33b8f83 100644 --- a/packages/cultnet-ts/package.json +++ b/packages/cultnet-ts/package.json @@ -53,7 +53,7 @@ }, "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultnet-ts#readme", "engines": { - "node": ">=18" + "node": ">=20" }, "dependencies": { "@msgpack/msgpack": "^3.1.3", From 0e7d2204cd105ecc8dcde01cfe16d1394d49aff1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:32:57 +0200 Subject: [PATCH 18/64] cultnet-rs: example generating Rust-owned Idunn runtime fixtures Real enrolled identities, a validated Expected, an Activation issued by IdunnRuntimeActivationLaunch, bundle files through the CultCache store, and runtime-presence vectors signed by the Rust signers and run through authenticate/correlate before they are written. cultnet-ts tests will commit the output. Co-Authored-By: Claude Sonnet 5 --- .../examples/idunn_runtime_fixture.rs | 276 ++++++++++++++++++ 1 file changed, 276 insertions(+) create mode 100644 packages/cultnet-rs/examples/idunn_runtime_fixture.rs diff --git a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs new file mode 100644 index 00000000..e97eb47b --- /dev/null +++ b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs @@ -0,0 +1,276 @@ +//! Generate the Idunn runtime fixtures that cultnet-ts is tested against. +//! +//! The Rust owner builds every input: real enrolled identities, an Expected that +//! passes `validate`, an Activation issued by `IdunnRuntimeActivationLaunch`, the +//! bundle files written through `SingleFileMessagePackBackingStore`, and +//! runtime-presence vectors signed by the Rust signers. Each vector is also run +//! through `authenticate_runtime_presence_claim` and +//! `correlate_runtime_presence_claim` before it is written, so the bytes +//! committed to the TypeScript tests are ones this verifier accepted (or, for +//! the low-capacity vector, ones it correlates to the typed capacity +//! disagreement). Ed25519 is deterministic, so the TypeScript signer must +//! reproduce each vector byte for byte from the same fields. +//! +//! Linux only: the provider identity is bound to `/etc/machine-id`, and the +//! generated `machine-id` file records the value the identities were bound to. +//! +//! Usage: idunn_runtime_fixture + +use std::fs; +use std::path::Path; + +use anyhow::{Result, bail, ensure}; +use cultcache_rs::{ + CacheBackingStore, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, +}; +use cultnet_rs::{ + GameCultProviderHealthIdentity, GameCultRuntimeCapability, + GameCultRuntimePresenceHealthPurpose, GameCultRuntimePresenceHealthRecord, + IDUNN_EXPECTED_INCARNATION_SCHEMA, IDUNN_RUNTIME_ACTIVATION_SCHEMA, + IdunnExpectedCapability, IdunnExpectedDependency, IdunnExpectedIncarnationRecord, + IdunnExpectedRoute, IdunnRuntimeActivationLaunch, IdunnRuntimeActivationRecord, + IdunnRuntimeActivationSigner, IdunnServiceIdentity, RuntimePresenceAuthenticationContext, + authenticate_runtime_presence_claim, correlate_runtime_presence_claim, + enroll_service_identity_at, verify_runtime_authority, +}; + +/// The TypeScript tests pin the same values; drift shows up as a byte mismatch. +const OBSERVED_AT: u64 = 1_790_000_000_000; +const ISSUED_AT: u64 = OBSERVED_AT - 5_000; +const SEQUENCE: u64 = 1; +const DETAIL: &str = "route-observation:route-challenge-1"; +const STORED_AT: &str = "2026-01-01T00:00:00.000Z"; + +struct Set { + dir: &'static str, + target: &'static str, + transport: &'static str, + stable: &'static str, + candidate: &'static str, + minimum_capacity: u32, + odin_dependency: bool, +} + +const SETS: [Set; 3] = [ + Set { + dir: "web", + target: "streampixels-web", + transport: "http", + stable: "http://127.0.0.1:8830", + candidate: "http://127.0.0.1:18830", + minimum_capacity: 1, + odin_dependency: false, + }, + Set { + dir: "service", + target: "streampixels-service", + transport: "tcp", + stable: "tcp://127.0.0.1:8831", + candidate: "tcp://127.0.0.1:18831", + minimum_capacity: 2, + odin_dependency: true, + }, + Set { + dir: "rudp-route", + target: "streampixels-rudp", + transport: "rudp", + stable: "rudp://127.0.0.1:8832", + candidate: "rudp://127.0.0.1:18832", + minimum_capacity: 1, + odin_dependency: false, + }, +]; + +fn main() -> Result<()> { + let Some(out) = std::env::args().nth(1) else { + bail!("usage: idunn_runtime_fixture "); + }; + let machine_id = fs::read_to_string("/etc/machine-id")?; + fs::create_dir_all(&out)?; + fs::write(Path::new(&out).join("machine-id"), machine_id.trim())?; + let idunn = enroll_service_identity_at::( + &Path::new(&out).join("idunn-identity.private"), + )?; + let idunn_anchor = idunn.trust_anchor()?; + fs::remove_file(Path::new(&out).join("idunn-identity.private"))?; + let _ = fs::remove_file(Path::new(&out).join("idunn-identity.private.lock")); + for set in &SETS { + build(Path::new(&out).join(set.dir).as_path(), set, &idunn, &idunn_anchor)?; + } + Ok(()) +} + +fn digest(byte: char) -> String { + format!("sha256-{}", byte.to_string().repeat(64)) +} + +fn build( + dir: &Path, + set: &Set, + idunn: &cultnet_rs::ServiceIdentitySigner, + idunn_anchor: &cultnet_rs::ServiceIdentityTrustAnchor, +) -> Result<()> { + fs::create_dir_all(dir)?; + let provider_path = dir.join("provider-identity.credential"); + let provider = enroll_service_identity_at::(&provider_path)?; + let provider_anchor = provider.trust_anchor()?; + let _ = fs::remove_file(dir.join("provider-identity.credential.lock")); + + let capability = format!("{}.api", set.target); + let capability_schema = format!("{}.api.v1", set.target); + let expected = IdunnExpectedIncarnationRecord { + schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(), + target: set.target.into(), + plan_id: digest('1'), + incarnation_id: format!("{}/incarnation-1", set.target), + sealed_release_id: digest('2'), + source_repository: "github.com/GameCult/StreamPixels".into(), + source_revision: "a".repeat(40), + recipe_sha256: digest('3'), + runtime_id: format!("{}-yggdrasil", set.target), + expected_signer_identity_id: provider_anchor.identity_id.clone(), + health_contract: format!("{}.runtime-health", set.target), + artifact_sha256: digest('4'), + state_schema_generation: None, + state_contract_sha256: None, + write_lease_required: false, + route: Some(IdunnExpectedRoute { + route_id: format!("{}-route", set.target), + transport: set.transport.into(), + stable_endpoint: set.stable.into(), + candidate_endpoint: set.candidate.into(), + }), + capabilities: vec![IdunnExpectedCapability { + capability: capability.clone(), + schema: capability_schema.clone(), + compatibility: "v1".into(), + minimum_capacity: set.minimum_capacity, + }], + dependencies: if set.odin_dependency { + vec![IdunnExpectedDependency { + kind: "shared-infrastructure".into(), + capability: "odin.verse-rendezvous".into(), + schema: "odin.verse-topology.v1".into(), + compatibility: "v1".into(), + minimum_capacity: 1, + startup: "before-promotion".into(), + provider_id: Some("odin".into()), + provider_authority: Some("managed-incarnation".into()), + provider_expected_projection_sha256: Some(digest('5')), + provider_endpoint: Some("rudp://127.0.0.1:17871".into()), + }] + } else { + Vec::new() + }, + }; + expected.validate()?; + + let launch = IdunnRuntimeActivationLaunch::issue(&expected, digest('6'), ISSUED_AT, idunn)?; + let mut credential = Vec::new(); + let activation = launch.write_credential(&mut credential)?; + ensure!(credential.len() == 32, "activation credential is a 32-byte seed"); + fs::write(dir.join("activation-key.seed"), &credential)?; + let activation_signer = IdunnRuntimeActivationSigner::from_credential_reader(&credential[..])?; + + write_record( + &dir.join("expected.cc"), + &expected.target, + IdunnExpectedIncarnationRecord::TYPE, + IDUNN_EXPECTED_INCARNATION_SCHEMA, + expected.canonical_bytes()?, + )?; + write_record( + &dir.join("activation.cc"), + &expected.target, + IdunnRuntimeActivationRecord::TYPE, + IDUNN_RUNTIME_ACTIVATION_SCHEMA, + activation.canonical_bytes()?, + )?; + + let authority = + verify_runtime_authority(&expected, &activation, idunn_anchor, &provider_anchor.public_key)?; + let vectors = [ + ("presence-active.bin", "active", set.minimum_capacity, None), + ("presence-warming.bin", "warming", set.minimum_capacity, None), + ( + "presence-active-below-minimum.bin", + "active", + set.minimum_capacity.saturating_sub(1), + Some("expected-capability-000-capacity"), + ), + ]; + for (name, state, capacity, disagreement) in vectors { + if capacity == 0 { + continue; + } + let mut presence = GameCultRuntimePresenceHealthRecord { + schema_version: cultnet_rs::GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), + target: expected.target.clone(), + expected_projection_sha256: activation.expected_projection_sha256.clone(), + plan_id: expected.plan_id.clone(), + incarnation_id: expected.incarnation_id.clone(), + sealed_release_id: expected.sealed_release_id.clone(), + activation_witness_sha256: activation.canonical_sha256()?, + state_schema_generation: None, + state_contract_sha256: None, + runtime_id: expected.runtime_id.clone(), + runtime_instance_id: activation.runtime_instance_id.clone(), + bound_endpoint: Some(set.candidate.into()), + capabilities: vec![GameCultRuntimeCapability { + capability: capability.clone(), + schema: capability_schema.clone(), + compatibility: "v1".into(), + capacity, + }], + health_contract: expected.health_contract.clone(), + state: state.into(), + detail: DETAIL.into(), + write_lease_sha256: None, + signer_identity_id: provider_anchor.identity_id.clone(), + publisher_sequence: SEQUENCE, + observed_at_unix_millis: OBSERVED_AT, + signature_algorithm: "ed25519".into(), + signature: Vec::new(), + activation_signer_identity_id: activation_signer.identity_id(), + activation_signature: Vec::new(), + }; + let proof = presence.canonical_proof_payload()?; + presence.signature = provider + .sign::(&proof) + .signature; + presence.activation_signature = activation_signer.sign_presence_proof(&presence)?; + let bytes = rmp_serde::to_vec(&presence)?; + + let claim = authenticate_runtime_presence_claim( + &bytes, + &authority, + RuntimePresenceAuthenticationContext { + trusted_received_at_unix_millis: OBSERVED_AT + 1_000, + maximum_age_millis: 30_000, + maximum_future_skew_millis: 0, + }, + )?; + let correlation = correlate_runtime_presence_claim(claim, &authority)?; + let codes: Vec<&str> = correlation + .disagreements() + .iter() + .map(|entry| entry.code.as_str()) + .collect(); + match disagreement { + None => ensure!(codes.is_empty(), "{name}: unexpected disagreements {codes:?}"), + Some(code) => ensure!(codes == [code], "{name}: expected only {code}, got {codes:?}"), + } + fs::write(dir.join(name), bytes)?; + } + Ok(()) +} + +fn write_record(path: &Path, key: &str, kind: &str, schema: &str, payload: Vec) -> Result<()> { + SingleFileMessagePackBackingStore::new(path).push(&CultCacheEnvelope { + key: key.into(), + r#type: kind.into(), + payload, + stored_at: STORED_AT.into(), + schema_id: Some(schema.into()), + }) +} From 1e86bf0dc376af037c8c3aa2f8fae5b06ccf5c4f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:34:42 +0200 Subject: [PATCH 19/64] Place the document variants target and cut map on main The target (2026-09-17, with the operator's rulings) lived only on codex/document-variants. The cut map is Imagination's pass of 2026-09-29. Its operator questions Q1-Q7 are open. Co-Authored-By: Claude Opus 5.5 --- docs/document-variants-cut.md | 372 +++++++++++++++++++++++++++++++ docs/document-variants-target.md | 146 ++++++++++++ 2 files changed, 518 insertions(+) create mode 100644 docs/document-variants-cut.md create mode 100644 docs/document-variants-target.md diff --git a/docs/document-variants-cut.md b/docs/document-variants-cut.md new file mode 100644 index 00000000..987778ae --- /dev/null +++ b/docs/document-variants-cut.md @@ -0,0 +1,372 @@ +# CultCache document variants: cut map (draft) + +Date 2026-09-29. Imagination output for `docs/document-variants-target.md` (branch +`codex/document-variants`). Body read at `origin/main` `268e0ef`. This map owns means only; +the target owns ends and rulings 1-7. Nothing here is decided that the batch in section 4 +asks the operator to decide. + +## 1. Probe facts (run, not inferred) + +Probe: scratch clone `scratchpad/variant-probe` (commit `7b6de8e`, probe files only), run on +Yggdrasil via `ygg-verify.sh` with images `dotnet`, `rust`, `python:3.12-slim`, `node:22`. +Each runtime's current reader wrote a normal store, the bytes were altered four ways, and +the store was reopened. Output in `scratchpad/probe-out/*.txt`. + +| Altered store | C# | Python | TypeScript | Rust | +| --- | --- | --- | --- | --- | +| A. v1 header, record gains slot 4, payload empty | refuses, "read past end of stream" | refuses, "incomplete input" | refuses, "Offset outside DataView" | refuses (strict tuple), misleading legacy-envelope message | +| B. v1, slot 4 plus a full payload | **loads the payload silently** | **loads silently** | **loads silently** | refuses | +| C. header `cultcache.store.v2` | **ignores the header**; refused only by the empty payload | refuses, misleading "legacy envelopes" message | refuses | refuses | +| D. payload holds the delta as a sparse array | **loads `Name=''`, `Max=99`** | **loads `name=None`** | refuses | loads; `get` of that key fails | + +Consequences: +- The **empty payload is the only tripwire every shipped reader trips**, pinned builds + included (Aetheria pins `caching-unity-v1.4.0`). A variant record's payload must be empty, + and the delta must live outside it. +- A payload-as-delta encoding is ruled out: C# and Python misread it silently. +- C# never checks `formatVersion` (`CultDocumentMessagePackSerialization.DeserializeSnapshot` + defaults a missing one to v1). C#, Python and TypeScript skip extra record slots silently. + These are latent defects today and become misreads when the format grows. +- Every refusal is loud but none of them names the record. The target requires named refusals, + so current readers need a small fix (C0). + +Other Body facts that shape the map: +- **CultNet has no member-path grammar.** `docs/cultnet-selection-cut.md` D2: "Declared + aliases, not a field-path language". It reaches top-level declared `index`/`role` aliases + only (`CultDocumentMemberView`). Nothing exists to reuse. See section 3. +- **The schema catalog describes top-level members only.** A nested type (`BehaviorData`, + `PerformanceStat`, `HardpointData`) appears only as a CLR type name. Soft drift and hard + rejection cannot see below slot level. +- **Resolution needs a codec, and the core has none.** `GameCult.Caching` holds objects. The + MessagePack codec lives in `GameCult.Caching.MessagePack`. `CultInspectorModel` already + takes the codec as two injected functions (`CultCacheMessagePack.CreateInspectorModel`). +- **Same concrete type implies same home store.** `Home(type)` routes by type, so ruling 3 + ("same store") falls out of ruling 6. No separate check is needed. +- **The name index shadows silently.** `Index()` does `MapOf(_names, type)[name] = key`, so a + second record with the same name overwrites the entry. A variant that inherits its base's + name would make `GetByName` return one of the two, depending on apply order. +- **Studio edits by whole-document upsert.** `CultInspectorEdit.Commit` calls + `UpsertAsync(type, copy, key)`, and `Duplicate` clones through the codec. +- **Raw readers bypass the cache.** In CultLib: `CultMesh.ReadSingleFileDocument` + (`CultMeshSingleFileDocuments.cs:112`), plus its legacy snapshot decoder. In consumers: + AetheriaEve `AetheriaRuntimeCatalogStore` (directory-store pages). +- **Kotlin reads no store files.** It sees CultNet raw snapshots only. + +## 2. Model page (step 0b) + +| Kind | Named by | Over time | Decided by | +| --- | --- | --- | --- | +| Variant record | its own `CultRecordKey`, minted like any record; same `schemaId` as its type | created, re-overridden, rebased, removed; never converted to or from a plain record implicitly (Q1) | author through Studio or the variant write API; the cache validates | +| Base reference | the base's key, in the record's variant slot | changed only by an explicit rebase; a base cannot be deleted while it has variants, unless the same batch rebases or removes them | author; the cache refuses a cycle, a missing base, a different concrete type, a global type | +| Override entry | `(op, path, id, value)`; op is Set, Insert or Remove | added by editing; removed by clearing; survives base edits while its path resolves | author; the cache refuses unresolvable entries (Q2, Q4) | +| Member path | a sequence of `(slot, elementId)` steps; `slot` is the MessagePack `[Key]`; `elementId` is `""` unless the step enters an object-list element | a type change can invalidate it | the type's owner (slot authority); ids by the element's creator | +| Element id | a `[CultElementId]` string member on an object-list element type; `""` means unset | minted by the cache on write when unset; copied unchanged into variants; a moved element is a new element | cache mints it; it is never retargeted | +| Resolved view | `CultStoredDocument.Document` for a variant key | recomputed inside the hold that admits the variant, or any base on its chain | the cache only; never persisted, never written back (Q1) | +| Index and name entries | as today, from the resolved view | a dependent's entries are dropped and re-added in the same `Apply` as its base change | the cache; a variant must override the `[CultName]` member (rule R6) | +| Watches | as today; each re-resolved dependent emits `Updated` with its own `Sequence` | published in the same hold as the base change | the cache | +| Compare-exchange | `(schemaId, storedAt)` of the stored delta (ruling 2) | a base change does not stamp its variants | the cache; the resolved view is not an identity | +| Persisted format version | store header `formatVersion` | `cultcache.store.v2` when the store holds at least one variant; `v1` otherwise (Q5) | the writing store, from content | +| Variant slot on the wire (CultNet) | **empty cell**: no CultNet message carries a delta today | C5 | ruling 4 decides deltas; the message shape is C5's design | +| Dictionary entries, scalar lists, arrays | **empty cell**: no stable identity exists | whole-member Set only (Q7) | Q7 | +| Template (non-item) bases | **empty cell**: parked by ruling 6 | none | not in these cuts | + +## 3. Where the Body contradicts the target + +1. **"A member path in CultNet's grammar"** (ruling 1 and fork 1 text) has nothing to reuse. + CultNet selection deliberately has no path language. This map specifies a minimal slot + path (section 2) owned by `GameCult.Caching`. If CultNet ever needs paths, it can adopt + this one. Nothing is shared today, and nothing is invented twice. +2. **"Overrides are subject to the same soft drift rules as full records"** conflicts with + the ends list: "Loading refuses an override naming a member that does not exist on the + type". Under soft drift, a persisted slot missing locally is ignored with a warning, so + the two rules disagree for a dropped member. Below top level, the catalog has no shape to + drift against at all. See Q4. +3. **"Deletes first"** has little to delete: the feature is additive. The honest deletions + are the silent extra-slot skips and C#'s ignored header. C0 puts them first. + +## 4. Operator questions (one batch) + +**Q1. A plain `Upsert` of a whole document at a variant's key.** It happens when Studio's +current edit commits, when AetherDb migrations do `batch.Upsert(type, doc, key)`, and on a +CultNet remote write. +- (a) Refuse it loudly. A variant changes only through the variant API. Flattening is an + explicit, separate operation. +- (b) Diff the document against the base and store the difference. Ids make the diff + deterministic, but a value set equal to the base stops being an override without anyone + saying so. +- (c) Flatten silently (today's behaviour by default). +- **Recommend (a).** Affects C1's write path, C3's edit commit, and every AetherDb migration + (each skips variants or uses the variant API). + +**Q2. A base edit that removes an element some variant overrides.** +- (a) Refuse the commit unless the same batch clears or retargets those overrides. Studio + offers keep, retarget or clear at edit time, and "keep" means the base edit is not + committed. The store never holds a conflict, and loading refuses one. +- (b) Persist the conflict. The override goes inert, readers get the resolved document + without it, and Studio lists it. +- **Recommend (a).** Option (b) makes a reader's resolved document silently differ from what + the author wrote. Affects C2's validation, C3's rebase UI, and migrations that remove + behaviours. + +**Q3. Scope of "ids everywhere".** +- (a) Every object-list element in every registered document type, in all 28 consumers. The + registry refuses a type whose element types lack an id. +- (b) Only document types that opt in with `[CultVariants]`. For those, the registry requires + `[CultElementId]` on every object element type reachable through their lists, including + union bases. +- **Recommend (b).** Option (a) breaks 28 registries for a feature that one consumer uses. + Affects C2 and Aetheria's adoption cut. A `BehaviorData` id needs a base slot above the + subclasses' highest key (32), which adds about 30 nil bytes per behaviour unless Aetheria + renumbers. + +**Q4. Schema drift under overrides** (contradiction 2). +- (a) Refuse loading when an override names a member missing at any depth, or holds a value + that will not decode into the member's current type. Record this as a stated exception to + soft drift in `cultcache-schema-compatibility.md`. +- (b) Top-level overrides follow catalog soft drift (ignore with a warning); nested ones are + refused. +- **Recommend (a).** It follows the target's ends and is one rule. The cost: after a type + change drops an overridden member, the catalog must be rewritten before the new build opens + it. + +**Q5. Format version.** +- (a) Write `cultcache.store.v2` only when the store holds a variant. Stores without variants + stay byte-identical `v1` for every consumer. +- (b) Always write v2 after the upgrade. +- **Recommend (a).** The empty payload remains the tripwire for pinned old C#, which ignores + the header. Affects C0 and C1. + +**Q6. Slice scope.** Should the directory store and CultNet refuse variants loudly until +their own cuts? The directory store's only consumer is AetheriaEve's raw reader. CultNet +must carry deltas (ruling 4), and no message can yet. +- **Recommend yes.** It is two refusals. Otherwise C1 must design CultNet messages first. + Affects C1's size and the order of C5. + +**Q7. What is addressable below a member.** The proposal: object-list elements by id only. +Dictionary entries, scalar lists and arrays are replaced whole. +- **Recommend yes.** Aetheria's cases (`Hardpoints` whole; `Behaviors[id]...Max`) fit. Keyed + dictionary addressing can be added later without a format change. Affects C2. + +## 5. Cuts, in order + +All cuts are in `F:\Projects\CultLib`. Rebase `codex/document-variants` (docs only) onto +`origin/main`. Each cut is one Hands pass on that branch and merges to main after its Soul +pass. Probes show that a C1 writer can merge safely before other runtimes change, because +every reader refuses it. Verification uses `ygg-verify.sh /f/Projects/CultLib ''`. +The command strings below are the ``. Keep the job's exit status last. + +Overlap: BP-1 (`cultmesh/rust-content-plane`) edits `docs/runtime-parity-scope.md`, which +C0 also edits. Rebase after BP-1 merges. `codex/fix-node24-ajv-esm` has no diff against main. + +### C0. Tripwires: every reader refuses what C1 will write, and names the record + +Deletes: +- The silent extra-slot skip in the C# record decoder + (`CultDocumentMessagePackSerialization.ReadPersistedRecord`'s trailing `Skip` loop) and + its copy in `CultMeshSingleFileDocuments.ReadLegacyPersistedRecord`. +- The `?? "cultcache.store.v1"` defaulting of the header. +- Python `raw_record[:4]` slicing. +- The TypeScript and Python fallthrough to the legacy envelope decoder when the header is a + `cultcache.store.*` string they do not know. + +Adds, one rule in each runtime: a snapshot whose header is not `v1`, or whose record has more +than 4 slots, is refused with a message that names the version or the record key, and says +the store needs a runtime that resolves variants. C# accepts `v1` only, until C1 adds `v2`. + +Keeps: every v1 byte and every v1 test. + +Verification (rule: "unknown header or extra record slot is refused by name"). Each runtime +gets one test, and each test's negative is fixture B from section 1 (full payload plus slot +4) loading: +- `dotnet`: `dotnet test tests/GameCult.Caching.Tests --filter FullyQualifiedName~PreCut2StoreFormat` +- `node:22`: `npm install --no-audit --no-fund && cd packages/cultcache-ts && npm test` +- `python:3.12-slim`: `pip install -q msgpack -e packages/cultcache-py && python -m unittest discover packages/cultcache-py/tests` +- `rust`: `cd packages/cultcache-rs && cargo test` (message only; Rust already refuses) + +Subtraction: about −20 lines of skip and fallthrough; +4 small refusals and 4 tests. Build: +the 4 cache packages only. + +### C1. C# core: variant records, top-level Set overrides, resolution in the admitting hold + +Adds: +- **`CultPersistedRecord.Variant`**, record slot 4: `[baseKey, overrides[]]`. Payload slot 3 + is empty for a variant. An override is `[op, path[], id, value]`. + - Owner: `GameCult.Caching`. + - Consumer: both file stores and Studio. + - Invariant: an old reader refuses rather than misreads (section 1). + - Why no existing owner serves: the payload cannot hold the delta (probe D). +- **`CultStoredDocument.Variant`** (base key and overrides; null for plain records). + `Document` stays the resolved view. +- **A codec port on `CultCache`**: the `(serialize, deserialize)` pair `CultInspectorModel` + already takes, lifted. + - Owner: `GameCult.Caching.MessagePack`, supplied by `CultCacheMessagePack.Create`. + - Consumers: resolution and the inspector model. + - Invariant: one codec per cache; clones and override values use the store's encoding. + - `CultInspectorModel`'s constructor takes the port instead of its own pair, so there is one + pair, not two. + - A cache without a codec refuses variant writes. +- **Write API** on `CultCacheBatch`, with single-call equivalents: `UpsertVariant(key, baseKey, + overrides)`, `Flatten(key)` (Q1a), `Remove` unchanged. Rebase is `UpsertVariant` with a new + base. +- **`Validate` resolves** every admitted variant and every dependent of an admitted or + evicted base, in base-first order, against the post-batch set. It refuses, naming keys: + a cycle; a missing base; a different concrete type; a global type; an evicted base with + surviving variants; an override slot missing on the type (Q4); a value that will not + decode; a variant whose resolved `[CultName]` equals its base's (R6); a plain `Upsert` at a + variant key (Q1a). +- **`Apply` re-resolves dependents** in the same hold. Each emits `Updated` and is re-indexed. + A base change stamps no dependent `storedAt`. +- **Header**: the store writes `v2` iff it holds a variant (Q5a) and reads `v1` and `v2`. +- **Refusals** (Q6): `DirectoryMessagePackBackingStore` push and commit of a variant; + `CultNetDocumentRegistry` row building for a variant; `CultMesh.ReadSingleFileDocument` of + a variant key. +- **Contracts**: the variant record section in `cultcache-persistence-format.md`; the Q4 + exception in `cultcache-schema-compatibility.md`; a "variants: C# resolves; others refuse" + row in `runtime-parity-scope.md`. + +Authority map: +- Owner: `CultCache.Validate`/`Apply` owns the resolved view. +- Inputs: stored deltas, base records, the codec. +- Outputs: the resolved `Document`, index entries, changes. +- Demoted: the resolved `Document` is no longer a writable owner for a variant key (Q1a). + `storedAt` is the delta's identity only. +- Forbidden writers: store `Loaded` callbacks never resolve; Studio never writes a resolved + document to a variant key; CultNet never emits a variant row. +- Shared paths: a load (`Admit` with a source), a single write, a batch and a remove all pass + the same `Validate` and `Apply`. There is no second resolution path. + +Verification. New `VariantTests.cs`; each rule gets a positive and a named negative: +- a load with a variant resolves; +- a base edit updates the variant's `Get`, `GetByName` and `GetByIndex`, and `Watch` sees both + changes inside one publication, with no gap in `Sequence` between them. Negative: a + subscriber observing the base change must already read the new variant. +- `Expect` on the variant survives a base change; +- each refusal case, and the refusal message names both keys; +- the header is `v1` without variants and `v2` with them; +- a read-only store resolves; +- a variant round-trips byte-identically through flush. + +Cross-runtime vectors: the Caching interop peer gains `write-variant --file`. A test in +`packages/cultcache-ts/test/cult-cache.test.ts` asserts that TypeScript refuses that file by +name; Python and Rust tests read the same fixture from `contracts/cultcache/variant-store.cc`. + +Command, `dotnet`: +`dotnet test tests/GameCult.Caching.Tests && dotnet test tests/GameCult.Networking.Tests --filter FullyQualifiedName~Registry`, +then the C0 commands for `node:22`, `python` and `rust` against the new fixture. + +Subtraction: the inspector's own codec pair collapses into the port; otherwise net additive, +estimated +350 to 450 lines of core and +400 of tests. Build: the Caching and MessagePack +projects, Caching.Tests, the Networking test filter, the interop peer. + +### C2. C# element identity and nested paths (Set, Insert, Remove) + +Adds: +- **`[CultElementId]`** (a string member) and **`[CultVariants]`** (a document-type opt-in, + Q3b). The registry refuses an opted-in type with an id-less object element type reachable + through a list, union bases included. +- **Minting**: on write, the cache mints ids for unset ids in opted-in types, and refuses a + duplicate id within one list. +- **Path steps below top level.** +- **Insert** anchored after an id, where `""` means the head. An inserted run sits + immediately after its anchor and before base elements added there later. +- **Remove** by id. +- **Canonical order**: removes, then inserts in list order, then sets by path. +- **Q2a refusal**: a base commit that orphans an override is refused. +- **Q7**: whole-member Set for dictionaries, scalar lists and arrays. +- **`CultCache.MintElementIds()`**: the one-shot rewrite for existing stores (ruling 1). It + upserts every record of opted-in types through the normal path. + +Keeps: the C1 format unchanged. C2 fills path shapes that C1 refused. + +Verification: +- Two look-alike elements (two of one union subtype) get different overrides, and a base + insert before them retargets nothing. +- Rebase re-applies overrides by id. A missing id is refused, and the message names the + variant, path and id. +- A Set on a removed element is refused. +- Minting is idempotent. +- An opted-in type without ids is refused; a type that has not opted in is untouched. This is + the negative for Q3b's blast radius. +- A C#-written nested-override fixture joins `contracts/cultcache/`. + +Command: `dotnet test tests/GameCult.Caching.Tests`. + +Estimate +300 lines and +350 of tests. Build: as C1, without Networking. + +### C3. Studio: edit the delta + +Adds, in `CultInspectorModel` (engine-free; the lowering stays a renderer): +- For a variant edit, each member path is marked inherited or overridden. +- `Commit` writes `UpsertVariant` with overrides equal to the prior overrides plus a + structural diff by id. It is deterministic because ids exist. +- An explicit "override" pins a value equal to its base's. +- `ClearOverride(path)`. +- `CreateVariant(record)` next to `Duplicate`; it prompts for a name (R6). +- `Rebase(record, base)` returns a conflict list for Q2a before commit. + +Lowering, in `CultCacheStudioWindow`/`Drawers`: an overridden marker and a revert control per +member, a base link, and variant creation and rebase controls. + +Verification: +- `CultInspectorModelTests`: the diff produces exactly the touched paths; clear removes one + entry; the pin survives an equal value; rebase conflicts are listed. +- Negative: a Studio commit never calls a plain `Upsert` at a variant key. + +Only the operator can check these in Unity against a copy of `Aetheria.cc`: +- the markers read correctly; +- clearing reverts the value live; +- a hull variant replaces `Hardpoints`; +- a laser variant changes one behaviour's `PerformanceStat.Max`; +- a base edit shows in the open variant. + +Then tag `caching-unity-v1.5.0`. **This is the point where Aetheria is unblocked.** + +Estimate +250 model, +150 lowering, +250 tests. Build: Caching.Tests. The Unity package is +checked by the operator in the editor. + +### C4. Aetheria adoption (Aetheria repo, its own cut, after the release) + +- Bump the package to `v1.5.0`. +- Add `[CultVariants]` to `HullData`, `EquippableItemData`'s concrete types and `ConsumableItemData`. +- Add `[CultElementId]` to `BehaviorData` (base) and `HardpointData`. +- Run `MintElementIds` once over `GameData/Aetheria.cc`. +- AetherDb migrations skip variants or use the variant API (Q1a). +- Re-author the families listed in section 6. + +### C5. CultNet deltas (C# reference) + +Adds a new raw-record message version that carries the variant slot, following selection D3: +a v1 message string, so peers not in this cut refuse through their own dispatch. The C1 +refusal in `CultNetDocumentRegistry` is deleted. Scheduled when a CultNet consumer needs +variants; none does today. + +### Parked: TypeScript, Python and Rust resolution + +Each runtime gets its own cut when a consumer that reads a variant-bearing store exists +(ruling 5). None does. `Aetheria.cc` is read by C# only. + +## 6. First payoff in `Aetheria.cc` + +Scan of the live file (206 records, `v1`): records of one schema whose leaves differ by at +most 20 percent, name excluded. This is a heuristic; the operator confirms the real families. + +| Type | Records | Families that collapse | Records becoming variants | +| --- | --- | --- | --- | +| geardata | 32 | Refinery / Assembly Line / Deep Ore / Surface Ore / Shipyard (1 to 3 leaves differ); Small / Medium / Large Drive; RevvITup 2.0 / deep space burnout / Talaria; Skiron / Iapyx; Arctica / cold like my heart | 10 | +| weaponitemdata | 18 | ChargeBlast SG / ChargeBlast+- (14 of 253 leaves differ); pswarm / scorched void policy; Earp / 6k Shooter; Spectra / ColdFire | 4 | +| hulldata | 5 | Longinus / LonginusX (only `Behaviors`, `Hardpoints` and two cosmetic members differ) | 1 | + +That is 15 of 55 equipment records. In most of these families the difference lies inside +`Behaviors`, so element-level overrides (C2) are what pay. Top-level overrides alone would +still copy each behaviour list. + +## 7. Consumers + +There are 28 projects: C# 13, Rust 9, TypeScript 10, Python 1, Kotlin 0 (Explore survey; +dependency-level for most, read in detail for Aetheria and AetheriaEve). +- **See variants:** Aetheria through C# `Get`, `GetByName` and `CultRecordRef` (resolved + documents only), CultCache Studio (deltas), and AetherDb tools (must honour Q1). +- **Must stay oblivious or refuse:** every other consumer. No other project reads + `Aetheria.cc`. Raw readers refuse through the empty payload plus C0/C1: `CultMesh` + single-file reads, AetheriaEve's directory-page reader (the directory store refuses + variants, Q6), and Mimir (writer only). diff --git a/docs/document-variants-target.md b/docs/document-variants-target.md new file mode 100644 index 00000000..1adbbe50 --- /dev/null +++ b/docs/document-variants-target.md @@ -0,0 +1,146 @@ +# CultCache Document Variants: Target + +Date: 2026-09-17 + +Status: target, before any substrate map or cut map. This document owns the ends. +A cut map, written after an Imagination pass over the Body, will own the means. +Branch: `codex/document-variants`. + +## Why + +A CultCache record today is always complete. To make a bigger laser from a +laser, an author copies the record and re-specifies every stat. For a ship hull +with several hardpoint layouts, every layout is a full copy of the hull. When +the base changes, each copy has to be found and edited by hand, and copies drift +apart silently. + +The first consumer is Aetheria's catalog (`F:\Projects\Aetheria\GameData\Aetheria.cc`), +edited in CultCache Studio: + +- **Hull variants:** one hull with several hardpoint layout options. A variant + replaces the whole `HullData.Hardpoints` member. +- **Item variants:** a bigger laser. A variant changes stats nested inside the + design's behavior list, for example one behavior's `PerformanceStat.Max`. + +## Rulings (operator, 2026-09-17) + +- **This is a CultCache feature, not an Aetheria mechanism.** Operator: "Yes, this + is absolutely a CultCache feature, write it up in CultLib". +- **A variant is stored as a delta from its base and resolved by the cache.** A + record stores a reference to its base plus a sparse set of overrides. The + cache resolves it; readers see complete documents. The operator chose this + over two alternatives. Authoring-only variants in Studio over flattened stored + copies leave a derived cache pretending to be data. Per-type variant records + in each consumer rebuild the feature bespoke for every type. + +## Ends + +- **Readers see complete documents.** `Get`, `GetAll`, lookups by name and by + index, watches and snapshots return resolved documents. No consumer outside + the cache and its authoring tools handles a delta. +- **A base change reaches its variants.** Editing a base changes every variant + that does not override the edited value. Watches, indexes and name lookups + observe that change on the variants too, in the same commit that changed the + base. +- **A variant is a record.** It has its own key and name, and references to it + behave like references to any record. In Aetheria a lot's design and a + product's design can name a variant directly. +- **Studio edits the delta.** It shows which values a variant inherits and which + it overrides, and it can clear an override so the base value applies again. +- **Loading refuses a broken variant loudly and names the records.** Cases: + - a cycle of bases; + - a base that does not exist; + - a base whose type the variant's type cannot inherit from; + - an override naming a member that does not exist on the type. + + Deleting a base that still has variants is refused. + +## Invariants that must survive + +- **Wire parity** for the persisted format (`src/GameCult.Caching/Contracts/cultcache-persistence-format.md`, + `docs/persisted-record-encoding.md`). Every runtime that reads a store holding + variants resolves them identically, or refuses the store loudly. Which + runtimes resolve is decided in the map, against + `docs/runtime-parity-scope.md`; none may misread silently. +- **One home store per type**, and atomic single-store commit + (`cultcache-store-composition.md`). A base change and the resulting variant + changes are one commit, not a repair that runs afterwards. +- **Schema compatibility** (`cultcache-schema-compatibility.md`): overrides are + subject to the same semantic identity, soft drift and hard rejection rules as + full records. +- **Compare-exchange** (`Expect`, `ExpectUnchanged`) keeps a single meaning for + variants. The map settles whether it tests the stored delta or the resolved + document; it must not mean both. + +## Fork rulings (operator, 2026-09-17) + +- **1, granularity: stable element identity, ids everywhere** (operator, 2026-09-17: "ids + everywhere"). + - Every object element in a list carries a stable id, minted when the element is created. + This is the approach of sequence CRDTs (RGA, YATA/Yjs, Automerge, Fugue). + - Matching algorithms (Myers, diff3, GumTree) are heuristics. They fail on look-alike + elements such as two `EnergyDraw` behaviors, which is why identity is minted, not + inferred. + - An override addresses an element id plus a member path in CultNet's grammar. An + insertion is a new element anchored after an existing id; a removal names the + removed id. Index addressing is out. + - Rebasing is deterministic. An override whose element id exists in the new base + re-applies. One whose element is missing is an explicit conflict that Studio shows, + to keep, retarget or clear; it is never silently retargeted. + - Existing stores get ids minted once, by a rewrite. +- **2, where resolution lives: at load, kept in memory** (operator: "agreed"). Resolution + computes a variant's complete document from its base chain and its overrides. + - The cache holds both the stored delta and the resolved document. + - A base edit re-resolves its variants inside the same commit, so watches and indexes + observe the change atomically. + - Compare-exchange (`Expect`) tests the stored delta. The resolved document is derived. +- **3, cross-store bases: no.** A variant and its base live in the same store. +- **4, CultNet: deltas.** +- **5, runtimes: C# first.** TypeScript, Python, Rust and Kotlin refuse a store + or snapshot containing variants, loudly, until each implements resolution. +- **6, type change: the same concrete type only** (operator: "agreed"). + - An override can only name members the base type has, and rebasing requires the same + type. + - A variant whose type differs from its base's is refused loudly. + - Subtype variants are parked until real content needs a template base. A record + flagged as a template, not a real item, may be the smaller feature. +- **7, clearing and rebasing.** + - Clearing an override removes that member from the variant's stored delta. A member + that is not overridden is not stored. + - Rebasing (changing a variant's base) is supported. Operator: "rebasing is a nice + tool to have, things can get annoying otherwise". + +## Open forks, for the Imagination pass to map and the operator to rule + +1. **Override granularity.** + - Top-level members are enough for hardpoint layouts. + - A bigger laser needs overrides inside list elements. Addressing list + elements by index is fragile: an insertion into the base silently retargets + every variant's overrides. + - Candidates: stable element identity (for example a behavior's type within its + design); replacing whole list elements only; or addressing paths. + - CultNet's selection work already resolves member paths per leaf type, + inherited members included (`docs/cultnet-selection-cut.md`). A variant's + delta addressing should reuse that grammar, not invent a second one. +2. **Where resolution lives:** at load in the cache core, lazily on read, or as a + materialized view the cache maintains. This affects memory, watch cost, and + the compare-exchange meaning. +3. **Base and variant across stores.** Can a variant in one store name a base in + another (a run-store variant of a catalog record)? This interacts with + one-home-store routing and read-only stores. +4. **CultNet.** Do variants travel as deltas, or resolved? A subscriber that + receives only resolved documents needs no resolver; one that edits needs + deltas. +5. **Runtime scope.** Which of C#, TypeScript, Python, Rust and Kotlin resolve, + and which refuse a store containing variants. +6. **Type change.** May a variant's type be a subtype of its base's type, + adding members, or must the two types match? +7. **Clearing and reparenting.** What clearing an override writes, and whether + a variant can change its base. + +## Not in scope + +- Scaling or formula variants ("every stat times 1.5"). An override states a + value. Generated authoring can compute values. +- Any Aetheria catalog content. Aetheria adopts the feature after a release, as + its own cut. From f5c597a81dd23a313c3d31374603dead7f6be500 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:40:30 +0200 Subject: [PATCH 20/64] cultnet-rs fixture example: remove the store lock files it leaves Co-Authored-By: Claude Sonnet 5 --- packages/cultnet-rs/examples/idunn_runtime_fixture.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs index e97eb47b..185f9a4e 100644 --- a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs +++ b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs @@ -272,5 +272,9 @@ fn write_record(path: &Path, key: &str, kind: &str, schema: &str, payload: Vec Date: Tue, 29 Sep 2026 01:44:04 +0200 Subject: [PATCH 21/64] cultnet-rs fixture example: name an Odin port a dev machine does not run Co-Authored-By: Claude Sonnet 5 --- .../cultnet-rs/examples/idunn_runtime_fixture.rs | 2 +- .../test/fixtures/idunn-runtime/.gitattributes | 1 + .../test/fixtures/idunn-runtime/README.md | 15 +++++++++++++++ .../test/fixtures/idunn-runtime/machine-id | 1 + .../idunn-runtime/rudp-route/activation-key.seed | 2 ++ .../idunn-runtime/rudp-route/activation.cc | Bin 0 -> 800 bytes .../idunn-runtime/rudp-route/expected.cc | Bin 0 -> 1076 bytes .../idunn-runtime/rudp-route/presence-active.bin | Bin 0 -> 922 bytes .../rudp-route/presence-warming.bin | Bin 0 -> 923 bytes .../rudp-route/provider-identity.credential | Bin 0 -> 680 bytes .../idunn-runtime/service/activation-key.seed | 1 + .../fixtures/idunn-runtime/service/activation.cc | Bin 0 -> 806 bytes .../fixtures/idunn-runtime/service/expected.cc | Bin 0 -> 1308 bytes .../service/presence-active-below-minimum.bin | Bin 0 -> 940 bytes .../idunn-runtime/service/presence-active.bin | Bin 0 -> 940 bytes .../idunn-runtime/service/presence-warming.bin | Bin 0 -> 941 bytes .../service/provider-identity.credential | Bin 0 -> 685 bytes .../idunn-runtime/web/activation-key.seed | 1 + .../fixtures/idunn-runtime/web/activation.cc | Bin 0 -> 798 bytes .../test/fixtures/idunn-runtime/web/expected.cc | Bin 0 -> 1067 bytes .../idunn-runtime/web/presence-active.bin | Bin 0 -> 915 bytes .../idunn-runtime/web/presence-warming.bin | Bin 0 -> 916 bytes .../web/provider-identity.credential | Bin 0 -> 683 bytes 23 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/.gitattributes create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/README.md create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/machine-id create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/expected.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-active.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/provider-identity.credential create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation-key.seed create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service/expected.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active-below-minimum.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-warming.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service/provider-identity.credential create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation-key.seed create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/web/expected.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/web/provider-identity.credential diff --git a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs index 185f9a4e..d6b432a6 100644 --- a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs +++ b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs @@ -157,7 +157,7 @@ fn build( provider_id: Some("odin".into()), provider_authority: Some("managed-incarnation".into()), provider_expected_projection_sha256: Some(digest('5')), - provider_endpoint: Some("rudp://127.0.0.1:17871".into()), + provider_endpoint: Some("rudp://127.0.0.1:47871".into()), }] } else { Vec::new() diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/.gitattributes b/packages/cultnet-ts/test/fixtures/idunn-runtime/.gitattributes new file mode 100644 index 00000000..fa1385d9 --- /dev/null +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/.gitattributes @@ -0,0 +1 @@ +* -text diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md b/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md new file mode 100644 index 00000000..99e7b07f --- /dev/null +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md @@ -0,0 +1,15 @@ +# Idunn runtime fixtures + +Written by the Rust owner, not by the TypeScript tests. Regenerate with +`packages/cultnet-rs/examples/idunn_runtime_fixture.rs` (CultLib `f5c597a`; it uses +cultnet-rs only, and Idunn's `IdunnRuntimeActivationLaunch` is that same crate's). +It needs Linux and a machine-id equal to the `machine-id` file here, because the +provider identity is bound to it. On Yggdrasil: + + DOCKER_ARGS='--cap-add SYS_ADMIN --security-opt apparmor=unconfined' bash ygg-verify.sh HEAD rust 'cd packages/cultnet-rs && cp /tmp/mid && mount --bind /tmp/mid /etc/machine-id && cargo run -q --example idunn_runtime_fixture /tmp/out' + +then copy `/tmp/out` over this directory. Every `presence-*.bin` was accepted by +`authenticate_runtime_presence_claim` and correlated by +`correlate_runtime_presence_claim` before being written; the +`below-minimum` vector correlates to exactly `expected-capability-000-capacity`. +Ed25519 is deterministic, so the TypeScript signer must reproduce them byte for byte. diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/machine-id b/packages/cultnet-ts/test/fixtures/idunn-runtime/machine-id new file mode 100644 index 00000000..a71716fc --- /dev/null +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/machine-id @@ -0,0 +1 @@ +c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1 \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed new file mode 100644 index 00000000..ddaffdda --- /dev/null +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed @@ -0,0 +1,2 @@ + +²ÊVÖH¾\IJ½ôðŸíȈ{’^ª+l£Z¼}k† \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc new file mode 100644 index 0000000000000000000000000000000000000000..556e8a173ce1d8648b70b1435402d0bdd183fff8 GIT binary patch literal 800 zcmbu5J!lj`6vvZB5J9v^P_WP|#3FaTnVpZF1Iej{R+4B4Q8978_Ofz&7xv>wOtgw3 zRxSn<5wtRXfT&d<5EM>GBZ4Bhm4&D&1$%K2v5{=!@E8W(|Nno#c{g9^td(l1r)@1s zJF%^GQGRPRG+Db{i?enbMs`Z-H0;VW?6hlLys}wuZL@|mxzw`E;=+6-aR`w-AtPI< zS4yHPLw}^>HclK;x!MhOhR8P-Rxn^z z1>|ZBp#HmR0C47YfA3D2u{f4YOH5hS5QP-O0Rdz&mPAr!jj+t)RQr?*g(b&9Krt6U zvD6l*;6iJ`DPdOf)qi-abIqoSWfHdj4q^X!iU!6^3ZzZoBLon*r=mm=3D#&26VTiv z)=2HUUl0hCFAWAK=gb&i5wExR%f98OS9+aqPX@Q$-v5KP*I&Iqv=N^!&KC#nKG@p4 z__nXF|9)>|Vzy`y7AOQp3kn7?!a;fju)C?}R)CD}f$uh=J%Krs2CNbSdloqaMKGXc zYcQoq^cu$(M}|H>-h;*_4j#U@dw5`6Y+w2?`tj()s|%m5y}7C99JK~Cm20>uxXN}UE7o3VK)&J4~j^dW^18ewCR|L@37*)yZ8bM)1in% z5TBvo!jLR}U1OUU8>@%w+~>Yf#$V3heBQ*Q&;hYlFM8ox<@0fI7%a(vi)s*#Is!H_Lsd3FI^%Yxzb*7 zPEIe&=5&VT=q?u-r%@UVc$lkM;ib(k6AZDbLL~1YgwFf|2;uSj#>eN{X0vlWSk=jW ziVagmE8?|QhxTKtDp~}>E23)k0^t`fU`eEP

-1f@ufyF7D5}SZ&dNVv&@-BA#p2 ztLMF*m(e^3s~yzVyB@X>GMHsyn^>-H6NYTWbnfYd7+q*$k8u|x(=;p>Q{rLba^0pj zBal?B8a>F0SOgJQeNIE+FA5~S;=;WmKsAjh(F{7{pk XnYbK{Yg~Y)!Q@w|{605*v_AX-A<<{3 literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-active.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-active.bin new file mode 100644 index 0000000000000000000000000000000000000000..13a93f5562abac952f33314dc17202825e216e8d GIT binary patch literal 922 zcmbu7O=uHA7=}~4iO_?HUaUXGqLfW%zMYxf2?{w>L{Fg?L9AtV=G$atn}pp>G#AB_ zh#-hPi?+~$AYwuB4~!TOidY1#gjR}L{5c8=J&3wm$tB+U&Sm&!_}&-ZXEC#--CtDW zsB2-8jcVm27{{?{gfW&ij+Ib_Nhw>0n{g7M8m|T?F^sLKW~%K2aY+FemSG?aypCX8uhR%<4{o6Dk`fasFW?* zF@iO!vxuQW1=7{7Ef}~Cm0TDgL{g$C8fuK^D&F z6pJQOaS(QF#2R(`PhYvAAqq~Gq=)9H>)LQ};#QY?R#k&L|D9&*bh1u++S|Kd|6yaT z(lV`d64bHXA604zS`{zGsQ$Nt-0DP^R2X8ph!$gGoL;_SeW*B>j1JQ%;-@n~R>u54TQQY*a4k9_kk?OoT- z0|=EyFn$`05I?j}!+RH=92tJ_ ztg%VIIyU<2ZqT>0_5AXU!snl}@0Uh)&n-@BJe29(xb^As#LIW^;f$D2#D*AK63 J=>OE$`y2izGi?9> literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin new file mode 100644 index 0000000000000000000000000000000000000000..1211a6059e5c63d55e7ba915d9f89e5dd5ca2b66 GIT binary patch literal 923 zcmbu7KWG#|6vpq+fTjNm5hTHAxtE!@GqX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o>Z;froxpcmW48`1;=yy_~vnH{bES!CFo_Ebva~^E;yuZ=2 zzeWEOLsQ;Nd>s=29i=H(v=(`P2PoMkkr!~ldo1+4#P>PS#7!dC3!=nNJU4+HsYL-O1Dfk>*v{@uTwHuxo{tqoN;VqaX;z(>KXx4A zhBh`IiKECPtG|t8ZS9t4V_Y_^#OG}e^QhjoXdUhsu-12R2ofJ zTxgroZK{1p7_^!j2+;aS2(yGS3j}pQg|gacWt21)w3OBdt|fBHP;uZMrJAwj<)u!s z-SfqwO;jz4+fM#A^&~abk>O#WB2QWcBOoP%EAvk~`R7$NdiK9Tz7BWm(3RynF8l+@ z-QwrIGHF!DESF5rr07oTKm7dt#>iI3lvEsJrHC#pX9ZN?fn>f#5*Wdl=G>yvR7=Wy zskvrc`ymM>q7a1G7FX5+=Mt0*EG1p5j?;CgF&;Y)&{EDJXcUf4eDMzs4UFIDUHta; zd1Ldy&XtKv&f(eF@8ZMy^`CREUp#!gcUAQ?XK!~$Hy^F{Z+@Mhe6w+OY>R?{qW6e7`WC)y)1hTT~-x z#>z>qIu<422o6@N7-M8`u!O3dlyWutI8LglMk?V1mSZQzYArOF_QWMcx#tAvxdg3} z3XD}CTvu9cQCQ8aFG(PXPZT1xuIDo?h#|%(Ej$8(yDG5FL$F1q9j$Wa!^o&=q>^wn za-eBOx2WbJVbE%Bz(?yLAJ*nM)k^5sD$ zEf_*AQ-FfH9t&Ja17sdB20mpJ1D}Iwv`9dyFQjV~bp_GNg3u_i0mpLT4quqN_^HgtSrDc;+8qW9QZ-_hdRJ=bRYFTYzo-+A-w LjrE^>r?&qF!IL?E literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-warming.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-warming.bin new file mode 100644 index 0000000000000000000000000000000000000000..62b7ff86cceb9219a5d8c0e059e2473baff42e0a GIT binary patch literal 941 zcmbu7J!lkR5QZf<-_L%3sm{uXjYSH@B78rycME%a=kDIc6e1#u zpiP2Zf=CDk#L}P;Fb4@~)l@DwdAlscO|F zIt`&^ Cr8(08 literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/provider-identity.credential b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/provider-identity.credential new file mode 100644 index 0000000000000000000000000000000000000000..45db9617f2fcfb960f3afda9b8ec42fdc1a6b2d1 GIT binary patch literal 685 zcmb7?KWG#|6vjm@v=?kt5(Nv*9y7Bye|9S^1gjuoBM8gP&TMvNZ#UlUT@nHT8(TFZ zij5!y4WgaI&LBuczruD^)FNn;#$M5pc%@)?FudV?-{YGfbMtmPIiq_n9hOZn+pkB3 zb^RcBx@_{m_f=Cg3+>cc(iuyVZAmhg_(3t!jq8l)tKEC=?aa}ha+-Fj3WaqfN@W-t z&aKmi8O1`O3^yS+A|sh{PD(_dx^>cWKr}%jQ8~gU)(Gs>M z4)(Ep7GLnKJz5ska6ZY3(j~px`a`FAQ8~{cF-2vIYNnkV!}=%BU_|4;M$b4HI?zo@c@YSB^P2/W•ËW;ÆsÖSÅ2�µ4 \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc new file mode 100644 index 0000000000000000000000000000000000000000..6127df727f18aed025681ae2377af563f9d11ed6 GIT binary patch literal 798 zcmbtPKWGzS6mK^R;-cu{Acs0=65sd#zJMBVa4Qz1h*ISHckPv2TJA0}w&i)csD$?7E54-p5UxA=Ix<@fi^bxpIL8)YV3CCjH$S81Wn zt)Y1?%ouVSwJ2xI>dFoU$9k*RQE1z?^h`)#d^D-d6CjqLz zw*mmCUkt9^E)w>SXA=rDUS?7OMFJ@+z(ioe2rH^}6k5&&5rD9V85W_jm|8_b%)HDZ z8-f%X^wWRqmd}rm+f-$7{ci^U&*|4dA*2OoLQ1ND8xV%0P-$zJW>RY~Is&9MRfdGr z84OkfR}nh{S>`3r`sO);SR&SJ)p?A2z} zrENPFmb+IDBpZ8o?p~MsHm)66LETC5@XpAOk>5E8WdT3+}}Oh-j69 zwg?^~;9;B=DU#YK^qa>l-p}{`X09K2+LWAeA5bD&F`y3V-@FDQjUoiyHgE~zEQmOZ zBPN4ZggWMExiu>-x2Z@)UQC@ums+A~3E3VCL36c2I&J&g`3T}f)%KUaO0Pmf2E;fMaM+RA;#`Z5XSiUV`Kcewpkp!kSnVt zJ~PV|ovetrd>6)#mFi@k$6OIvsS!v&ts~wFjhb5Fu6kX@!EA*4vk_)n?4OtyMOVZq z-@Ja&Xo#34K{MOon2S2G9M7?;94KJR0{{Vz&8h8Km{FjZS8%l~EMeNB>X;s7)ONt~ zge~YePmba=l0gW%53DKuc^B4-m`vUW!+bJ5Zlx0Ld@0*c)5|psV%i9+LtMw9c(|Y? XQ+0pvn5ROl9X$W0RKMo7L)Lp=Z0uzi literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin new file mode 100644 index 0000000000000000000000000000000000000000..15ae2e8c9912a0fa89482131e573b2a8f3a72105 GIT binary patch literal 915 zcmbtSO-NKx7##^(7((qTf-INuX72yJZx%7TA_&^F47oqwo%ixNGrf5;Wr0xyfe<2P zEsdzGorx6`q@`esuvOGh&?a}e(M2t^8Zr#5o#)$qhwprc!}*lk-Rddpez1)s%cqS> z7WYGMErmK%Ec8a8lPtX9Z~1U%G;VTrYq$a-XzCz=`K zl@mfzi7;u?oJeIIVNO#;c>By@r%)&j`YVLDh!>kJ7UGK4X+>vowG!YB!(@xt5Mma9 z35GlakF5vJ5z^Xm&O8^yS}M5LL~zRpSIR0WfPz=XU{9H+;mpjl&6b0Ka@nQ29w!@L z#1`=+%CcIqP{2gyQG0L^D@D=Bjj7Gg^STy4{ogX*#CMvwWBMQNPhW!dn%vhmi<{8u zNvn+vf~u)Q+Wehj;&3fTHV(*G|}}7TJtl| literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin new file mode 100644 index 0000000000000000000000000000000000000000..1d106eb5ff53a16de8ad39b93facaf8125c67181 GIT binary patch literal 916 zcmbtSO-NKx7@fhS76r8kY?G1LqIl!|zxT}|XHi%SNz$ZNa(})%^J4yb^Bl`f3$xaO z1wnxn-Dd0hfKTud_Y za5;%eFjS4924xFF1<=K$kg1cIS`vdURin#LtOX-r8a=gwCR_wO)QDk;wUfwtWR)kH z8RL}`LQ;t^Y0{iXWgTHoQ$=|5%weZcC=L26gtv+3TP=1)Wvk<|PNGUVz?+82HnAzh zEC3S>c?KR^51b>Uwd0(5E{L^MaIcBrmJzO$RZ;*2uZ+Q-GEc*~x!J9jgDd&Gi*+q3 zZhjHl#N$GeRI^=On8*xj4$fkwD4LjjwDoyLSEDEYTW0F`ULB`j{KNg}OR!Os=@A{5 zqH?~`5m$y22r8xqas7Av*^P}Y=wcDdc?j@aBWICy1~cUq3vDwR#5@2vP|{NA8PXIe zvI2$NF-N2e74cM4sepMW9ZkPYrP5RLeZ|x?IKnv&=W`#D9p77L7vB%|Ex+mi{5pOA z!TvpqSKl36-uv*_)WV7Gb^rDBC6ZsA{B&)1|6q6T#i!@TU-qt~1{%-cK&HC0kwY3| zBL$aX$TSibNh`3@##wH7XbiH(BWw)QmMR98AZL)!9(fL?S%~?ZUmIvF)Y`_+9X>fa zu)fx^{-yoZk>fu*?~X04T)%OvW&HNO(XsYUTDj2kBYX2sX4iyGeLPFPojEjfs#;3CV5$`#dIw=@*?Pp45!)4##s zIqLTeOGHXdVug?bgi%II1%HjfSkV0`SbmHTaQ(m%zL*`yFNdkdA5-ant=-)(`3)Eu B6f*z- literal 0 HcmV?d00001 From 69a21bb0579ca7ffbe680ba2e0b938f3b91d66c3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:55:09 +0200 Subject: [PATCH 22/64] Record the operator's rulings on document variants Q1-Q7 Q3 is ids everywhere, minted on load (not opt-in). Q4 is soft drift for dangling overrides, which supersedes one of the target's refusals. The others were ruled as recommended. Co-Authored-By: Claude Opus 5.5 --- docs/document-variants-cut.md | 32 ++++++++++++++++++++++++++++++++ docs/document-variants-target.md | 4 +++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/docs/document-variants-cut.md b/docs/document-variants-cut.md index 987778ae..a52f0e83 100644 --- a/docs/document-variants-cut.md +++ b/docs/document-variants-cut.md @@ -86,6 +86,38 @@ Other Body facts that shape the map: ## 4. Operator questions (one batch) +**Operator rulings, 2026-09-29, each asked on its own:** + +- **Q1: (a)**, a plain `Upsert` at a variant's key is refused loudly. +- **Q2: (a)**, a base edit removing an overridden element is refused unless the same batch + resolves it. Operator's reading: "the very existence of that element in the child collection + must become the new override state... you can't change the parent without also changing the + child... that's the resolve part of (a)." +- **Q3: ids everywhere, not opt-in.** Operator: "Opt-in sounds nice but consider the UX. We're + planting a footgun if we don't require ids everywhere." Rollout: **required, minted on load**. + The C# registry requires an id member on object-list element types. A store written before ids + existed loads, and ids are minted once on its first write (C2's rewrite). Other runtimes carry + the id as an ordinary member and enforce the rule when they gain variants. Each consumer's type + edit is a sweep in its own repo after C2. +- **Q4: (c) soft drift everywhere. This reverses the recommendation and supersedes the target's + end "loading refuses ... an override naming a member that does not exist on the type".** + Operator: "Soft drift everywhere aligns with the vision... the rationale for adopting + migrationless changes is still valid for variants. Any member dropped in a type change is a + design change, the reason for it to apply to the parent also applies to the variant." A + dangling override, at any depth, is ignored with a warning naming the variant and the member, + and the variant inherits the base value. The other broken-variant refusals (a base cycle, a + missing base, an incompatible base type) stand. +- **Q5: (a)**, the v2 header is written only when the store holds a variant. +- **Q6: yes**, the directory store and CultNet refuse variants loudly until their own cuts. +- **Q7: yes**, object-list elements are addressable by id, and dictionaries, scalar lists and + arrays are replaced whole. The operator asked first whether design roles and quality levels + use dictionaries. They do not: `CraftedItemData.Roles` is a `List` and + `FactionProduct.Roles` is a `List` (Aetheria `ItemData.cs:316`, + `FactionProduct.cs:30`). A market-segment product becomes a variant overriding one + `ProductRole` by id. + +*The questions as asked:* + **Q1. A plain `Upsert` of a whole document at a variant's key.** It happens when Studio's current edit commits, when AetherDb migrations do `batch.Upsert(type, doc, key)`, and on a CultNet remote write. diff --git a/docs/document-variants-target.md b/docs/document-variants-target.md index 1adbbe50..42b07bc4 100644 --- a/docs/document-variants-target.md +++ b/docs/document-variants-target.md @@ -51,7 +51,9 @@ edited in CultCache Studio: - a cycle of bases; - a base that does not exist; - a base whose type the variant's type cannot inherit from; - - an override naming a member that does not exist on the type. + - ~~an override naming a member that does not exist on the type~~ **superseded 2026-09-29 + (operator, variants Q4 c): a dangling override soft-drifts like any dropped member, ignored + with a warning; see `document-variants-cut.md` section 4.** Deleting a base that still has variants is refused. From 2cb694d612b238b0161053700676bb75bce6a590 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:04:33 +0200 Subject: [PATCH 23/64] Pin the C0 refusal vectors shared by every runtime An unknown store header, a record slot beyond four with a full payload, the v2 variant record C1 will write, and a v1 store written by the base-commit Python writer. Every runtime's tests read these bytes. Co-Authored-By: Claude Sonnet 5 --- .../document-variants-c0/.gitattributes | 3 ++ .../extra-slot-full-payload.msgpack | Bin 0 -> 1666 bytes .../vectors/document-variants-c0/generate.py | 34 ++++++++++++++++++ .../unknown-header.msgpack | Bin 0 -> 1651 bytes .../document-variants-c0/v1-base.msgpack | 1 + .../document-variants-c0/variant-v2.msgpack | Bin 0 -> 1798 bytes 6 files changed, 38 insertions(+) create mode 100644 tests/vectors/document-variants-c0/.gitattributes create mode 100644 tests/vectors/document-variants-c0/extra-slot-full-payload.msgpack create mode 100644 tests/vectors/document-variants-c0/generate.py create mode 100644 tests/vectors/document-variants-c0/unknown-header.msgpack create mode 100644 tests/vectors/document-variants-c0/v1-base.msgpack create mode 100644 tests/vectors/document-variants-c0/variant-v2.msgpack diff --git a/tests/vectors/document-variants-c0/.gitattributes b/tests/vectors/document-variants-c0/.gitattributes new file mode 100644 index 00000000..8efeaf12 --- /dev/null +++ b/tests/vectors/document-variants-c0/.gitattributes @@ -0,0 +1,3 @@ +# Refusal vectors are byte-exact; never convert line endings. +* binary +*.py text diff --git a/tests/vectors/document-variants-c0/extra-slot-full-payload.msgpack b/tests/vectors/document-variants-c0/extra-slot-full-payload.msgpack new file mode 100644 index 0000000000000000000000000000000000000000..a9bf1bd94985cce8d369c1f25adde8c5991574ee GIT binary patch literal 1666 zcmcJQyKWOf6o!dt5D!2dwgktT`^;{KC=d+=iD(eTT+TQvt#_l{aV|o62jT>g2OvU% z&>)Z~EyGKg7vMFRbsUq(Nhm_fojEiA|DW?|Xa9>G6v1k{4&5eHHFP)e@ZID|v#tpj znNp5==aEi{)Yemj1x*=p$}1~92x2J3f-_=4O00zhtBgfdd7d(<)Hk1Rhd~WZccTV7 z2&9__=zqU(H7d__opzogV^e|@O9500jys90l@t+)Byvu2i7od^Draztu&3Hs##3vN z{k635I%#64zJ8|rkYve)l1XP)^aAQ8ugc5nqP1AshrWq*N%k_{T~r~-P$wx*uAi!O zlCZPUimmQ6F=lr))Op#9C-dexc&MSYao6jjfq0uPcjg~K*F6ZUXAGBvqKF4e2iuQ| zTu0T}N^=q@)C1V=8KUHQCr`^j$;}v<#@T(fyEh-+b)gv^-g@7L{CuvB zyXgkOo|BQAdFLz3dt-+Oh}EmVcJN)5 zNOua}8fy&3i_Df)fJJ88)w9eh&WUB#ag8+N+*?L9m6lM<98m&GBTee407d~Mc;XyZ z)?gO-^+5UL_rH*B72^<3xV{3}nX_1W6|!rvy$H%pBD+Y+bw{-qNoiv&kTM?azx~+$ zYBF7J=EZ+Qb8?>`B34kkg6SIO8D<$3U4|$jL_9<&L+Iz7;n7s|_V9S>z(7${Tg{t; zbDuYD31cSNsinKa4>K1J4nDPXWL2H_@^WtCx`Vi+FF1CKu~}d4?S0*<^AMn1HsIq^ Kvm76UW%36Piz$!* literal 0 HcmV?d00001 diff --git a/tests/vectors/document-variants-c0/generate.py b/tests/vectors/document-variants-c0/generate.py new file mode 100644 index 00000000..fafd5dfe --- /dev/null +++ b/tests/vectors/document-variants-c0/generate.py @@ -0,0 +1,34 @@ +"""Generates the shared C0 refusal vectors from the pre-Cut 2 v1 store (written before any +variant code existed). Every runtime's tests read the committed bytes; nothing regenerates them +at test time. Run: python generate.py (needs msgpack). + + unknown-header.msgpack header cultcache.store.v9, otherwise the v1 store + extra-slot-full-payload.msgpack v1 header, record item:anvil gains slot 4, payload stays full + v1-base.msgpack NOT generated here: written once by the Python runtime at CultLib + 69a21bb (SingleFileMessagePackBackingStore.push of alpha and + beta, type vectors.item, before any C0 code existed) + variant-v2.msgpack what C1 writes for a variant: header v2, record slot 4 = + [baseKey, overrides[]], empty payload (override op Set = 0, + path steps are [slot, elementId]) +""" +import pathlib + +import msgpack + +here = pathlib.Path(__file__).resolve().parent +source = here.parent.parent / "GameCult.Caching.Tests" / "Fixtures" / "pre-cut2" / "single-file-v1" / "store.msgpack" +header, catalog, records = msgpack.unpackb(source.read_bytes(), raw=False) +assert header == "cultcache.store.v1" +anvil = records[0] +assert anvil[0] == "item:anvil" + + +def write(name, snapshot): + (here / name).write_bytes(msgpack.packb(snapshot, use_bin_type=True)) + + +write("unknown-header.msgpack", ["cultcache.store.v9", catalog, records]) +write("extra-slot-full-payload.msgpack", + [header, catalog, [anvil + [["item:bellows", []]]] + records[1:]]) +variant = ["item:anvil-big", anvil[1], anvil[2], b"", ["item:anvil", [[0, [[1, ""]], "", 99]]]] +write("variant-v2.msgpack", ["cultcache.store.v2", catalog, records + [variant]]) diff --git a/tests/vectors/document-variants-c0/unknown-header.msgpack b/tests/vectors/document-variants-c0/unknown-header.msgpack new file mode 100644 index 0000000000000000000000000000000000000000..82f07c2c69a4d24ea55be081b8ad55a6d6446ce5 GIT binary patch literal 1651 zcmcJQyKdA#6o!dt5D!2dT*Ahh`;6To3PeLeA{s<7moteauN~R5xd`PUvRR2d01*;| z27yGmT6l@@0=x#}&1OloNhm@}&zzb6|Ihj4Irw4+Ww6?AK-z}7fpjYyzB_r=ZfL?q zu9TzRd89KUwe{3sK{JM&^2$mNf*4A%;EY(15^EvBDq|5C zfuu!%{`X5)(=9yLb=rA~jLisAECWy(IPN5}R#HSHlE^v9CAQovshq(X!k%hl8PBXm z_Se$p+oX-5`uc_LLy{+#N+!Ko(JN@$qOPv0i`HUkANnTNCHd=kcUgxdN4=yvy?(0F zOTzAEC$_rV#+d19Xo_k*o-Epz;Gu!a#$B(=7UFHX+MRy{-K;}cJ!iNYlw~|vIoNqp z7CNfVR@&1*p&7tl@5~6E8+lp}st_eFI(c3NN^ZxvaOUSzha11vJzt)6FAaZW6=j%%bD=iV}^skDS*=7Rh0h?&69@&5wU`@6-?JK&oRrXNExDp5b+qH9HF20hDTG;yQAZ&0|RAQZ@0JY z0b?fFnTPws4>Q?EqfZ?UdEFH2MKw2Z)6QSf2prqP*sKu`_P=g7MF>zW8}RXMS&lEj GGWi3ckRs>+ literal 0 HcmV?d00001 diff --git a/tests/vectors/document-variants-c0/v1-base.msgpack b/tests/vectors/document-variants-c0/v1-base.msgpack new file mode 100644 index 00000000..dcdb411f --- /dev/null +++ b/tests/vectors/document-variants-c0/v1-base.msgpack @@ -0,0 +1 @@ +“²cultcache.store.v1‘—¬vectors.item¬vectors.item¯vectors.item.v1¬vectors.itemÙL{"schemaName":"vectors.item","schemaVersion":"vectors.item.v1","members":[]}‘¬vectors.item�’”¥alpha¬vectors.item¹2026-09-29T00:00:00+00:00Ä’¥alpha”¤beta¬vectors.item¹2026-09-29T00:00:01+00:00Ä’¤beta \ No newline at end of file diff --git a/tests/vectors/document-variants-c0/variant-v2.msgpack b/tests/vectors/document-variants-c0/variant-v2.msgpack new file mode 100644 index 0000000000000000000000000000000000000000..3f3efe42d6587dd3e1369f33e29128f2c528b925 GIT binary patch literal 1798 zcmcJQyKWOf6owPgARd4^YzdAv_nF-eQ6L%$644-vxtwuUTCbzsaV|o62pdPFOhJSM zfdYXAyR9T5o8= zMW&Ra-g%@`BDM9@U_n!cobt*_4}usSl!75`BRi39zD)rsxJE2=a-Q29e zb^~eV0op&VTy1XQnXc2$Q)FyPkYXu-O2Kg_k+qT{B9TPSNiMPFUPCkYuQll&9BE zR2oUx-5iUp?bb17b1hVP*@`Fg`UQBXptNz<>!OBun=W@}A3;|w2x}J%m))X>2TKP# zkBeMK)#*xo8Yom<*lU~_!80RII^8lv$;(cjm4TAmF*1p>_j<248{VSO^beNak3)XG z)W*?h_;Yx$d^8DoJl&e)iaVp>IkO_d0opnwG&qwYLOBTIl%zs3ixCr2BW{>>)(PSw zt~k=2g15#RgYi7GWhcNqv*Xo^%qq@_W!7Zkxl0VH_h z99Gs~7Wwr+`N^MuAv;!#Lpu&#OB6??VJaJ&4C_3Bq zZF|6&Np|MpUjM^X_Tk{u7>BG=<*mG&nOL;**E9mh_AoYW#Qom4?J5re$`u1X{##b! mA7F*-e>oq_s>xe3Pm8`A*Lb=#oTdH+EP8{bUVr)U(EbIpD^I%s literal 0 HcmV?d00001 From 98ed042fcc8b5d363ae6ddd20f9ceebccea020b6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:04:33 +0200 Subject: [PATCH 24/64] C#: refuse unknown store headers and extra record slots by name Delete the trailing Skip loop in the record reader, the ?? v1 header default, and the mesh reader's copy of the record decoder. The single-file store and CultMesh single-file reads accept cultcache.store.v1 only. Persistence-format and parity docs state the rule. Co-Authored-By: Claude Sonnet 5 --- docs/runtime-parity-scope.md | 2 + .../CultDocumentMessagePackSerialization.cs | 27 ++++++-- .../Contracts/cultcache-persistence-format.md | 5 ++ .../CultMeshSingleFileDocuments.cs | 30 +++----- .../PreCut2StoreFormatTests.cs | 68 +++++++++++++++++++ .../CultMeshVariantRefusalTests.cs | 47 +++++++++++++ 6 files changed, 153 insertions(+), 26 deletions(-) create mode 100644 tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs diff --git a/docs/runtime-parity-scope.md b/docs/runtime-parity-scope.md index 72768673..46b1e77b 100644 --- a/docs/runtime-parity-scope.md +++ b/docs/runtime-parity-scope.md @@ -13,6 +13,8 @@ Cross-runtime parity has three layers: - Wire parity: shared CultCache file/state contracts, schema-v0 MessagePack documents, transport profiles, and RUDP packets must cross runtime boundaries without translation folklore. + Every store reader refuses, by name, a header or record slot it does not + understand (vectors: `tests/vectors/document-variants-c0`). - Feature parity: each runtime must expose the CultCache/CultNet/CultMesh surfaces needed for its intended role, with unsupported production-server ownership called out plainly. diff --git a/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs b/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs index 1e99125e..bb62d2ed 100644 --- a/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs +++ b/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs @@ -30,6 +30,7 @@ public sealed class CultDocumentResolver : IFormatterResolver public static class CultDocumentMessagePackSerialization { + private const string SingleFileFormatVersion = "cultcache.store.v1"; private const int PersistedRecordFieldCount = 4; private const int SchemaCatalogEntryFieldCount = 7; private const int SchemaCatalogMemberFieldCount = 8; @@ -139,7 +140,8 @@ public static class CultDocumentMessagePackSerialization if (fieldCount > 0) { - snapshot.FormatVersion = reader.ReadString() ?? "cultcache.store.v1"; + snapshot.FormatVersion = reader.ReadString() + ?? throw new NotSupportedException("Store snapshot declares no format version; this runtime reads " + SingleFileFormatVersion + " only."); } if (fieldCount > 1) @@ -170,6 +172,17 @@ public static class CultDocumentMessagePackSerialization return snapshot; } + ///

Refuses a single-file snapshot this runtime cannot read, naming the format it found. + public static void RequireSingleFileFormat(CultPersistedStoreSnapshot snapshot) + { + if (!string.Equals(snapshot.FormatVersion, SingleFileFormatVersion, StringComparison.Ordinal)) + { + throw new NotSupportedException( + $"Store format {snapshot.FormatVersion} is not readable; this runtime reads {SingleFileFormatVersion} only. " + + "The store needs a runtime that resolves document variants."); + } + } + private static void WritePersistedRecord(ref MessagePackWriter writer, CultPersistedRecord record) { writer.WriteArrayHeader(PersistedRecordFieldCount); @@ -179,7 +192,7 @@ public static class CultDocumentMessagePackSerialization writer.Write(record.Payload); } - private static CultPersistedRecord ReadPersistedRecord(ref MessagePackReader reader) + public static CultPersistedRecord ReadPersistedRecord(ref MessagePackReader reader) { var fieldCount = reader.ReadArrayHeader(); var record = new CultPersistedRecord(); @@ -204,9 +217,11 @@ public static class CultDocumentMessagePackSerialization record.Payload = reader.ReadBytes()?.ToArray() ?? Array.Empty(); } - for (var index = PersistedRecordFieldCount; index < fieldCount; index++) + if (fieldCount > PersistedRecordFieldCount) { - reader.Skip(); + throw new NotSupportedException( + $"Record '{record.Key}' (schema '{record.SchemaId}') has {fieldCount} slots; this runtime reads {PersistedRecordFieldCount}. " + + "The store needs a runtime that resolves document variants."); } return record; @@ -371,7 +386,9 @@ public class SingleFileMessagePackBackingStore : SingleFileBackingStore protected override CultPersistedStoreSnapshot DeserializeSnapshot(byte[] data) { - return CultDocumentMessagePackSerialization.DeserializeSnapshot(data); + var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(data); + CultDocumentMessagePackSerialization.RequireSingleFileFormat(snapshot); + return snapshot; } protected override byte[] SerializePayload(object document) diff --git a/src/GameCult.Caching/Contracts/cultcache-persistence-format.md b/src/GameCult.Caching/Contracts/cultcache-persistence-format.md index e8231c10..4511f3c5 100644 --- a/src/GameCult.Caching/Contracts/cultcache-persistence-format.md +++ b/src/GameCult.Caching/Contracts/cultcache-persistence-format.md @@ -212,6 +212,11 @@ Example: The payload is the domain object only. It does not repeat the key, schema id, or stored timestamp. +Under `cultcache.store.v1` a record has exactly these four slots. A reader refuses any +other `cultcache.store.*` header and any record with more than four slots, naming the +version or the record's key and schema id. It never skips a slot it does not +understand. + ## Canonical Semantic Schema Hash `schemaId` should be derived from a canonical semantic schema hash. diff --git a/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs b/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs index 5e2295df..46bfb47e 100644 --- a/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs +++ b/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs @@ -236,14 +236,18 @@ namespace GameCult.Mesh private static CultPersistedStoreSnapshot ReadSingleFileSnapshot(string path) { var bytes = File.ReadAllBytes(path); + CultPersistedStoreSnapshot snapshot; try { - return CultDocumentMessagePackSerialization.DeserializeSnapshot(bytes); + snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(bytes); } catch (Exception ex) when (ex is MessagePackSerializationException or InvalidOperationException) { - return ReadLegacySingleFileSnapshot(bytes); + snapshot = ReadLegacySingleFileSnapshot(bytes); } + + CultDocumentMessagePackSerialization.RequireSingleFileFormat(snapshot); + return snapshot; } private static CultPersistedStoreSnapshot ReadLegacySingleFileSnapshot(byte[] bytes) @@ -252,7 +256,8 @@ namespace GameCult.Mesh var fieldCount = reader.ReadArrayHeader(); var snapshot = new CultPersistedStoreSnapshot(); if (fieldCount > 0) - snapshot.FormatVersion = reader.ReadString() ?? "cultcache.store.v1"; + snapshot.FormatVersion = reader.ReadString() + ?? throw new NotSupportedException("Store snapshot declares no format version."); if (fieldCount > 1) { @@ -267,7 +272,7 @@ namespace GameCult.Mesh var recordCount = reader.ReadArrayHeader(); snapshot.Records = new CultPersistedRecord[recordCount]; for (var index = 0; index < recordCount; index++) - snapshot.Records[index] = ReadLegacyPersistedRecord(ref reader); + snapshot.Records[index] = CultDocumentMessagePackSerialization.ReadPersistedRecord(ref reader); } for (var index = 3; index < fieldCount; index++) @@ -303,23 +308,6 @@ namespace GameCult.Mesh return entry; } - private static CultPersistedRecord ReadLegacyPersistedRecord(ref MessagePackReader reader) - { - var fieldCount = reader.ReadArrayHeader(); - var record = new CultPersistedRecord(); - if (fieldCount > 0) record.Key = reader.ReadString() ?? string.Empty; - if (fieldCount > 1) record.SchemaId = reader.ReadString() ?? string.Empty; - if (fieldCount > 2) record.StoredAt = reader.ReadString() ?? string.Empty; - if (fieldCount > 3) - { - var payload = reader.ReadBytes(); - record.Payload = payload.HasValue ? payload.Value.ToArray() : Array.Empty(); - } - for (var index = 4; index < fieldCount; index++) - reader.Skip(); - return record; - } - private static bool PublishesSchema(CultSchemaCatalogEntry[] catalog, string schemaId) { return catalog.Any(entry => diff --git a/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs b/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs index 6089b94e..6757a806 100644 --- a/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs +++ b/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.IO; +using System.Linq; using System.Threading.Tasks; using GameCult.Caching; using GameCult.Caching.MessagePack; @@ -83,6 +84,73 @@ namespace GameCult.Caching.Tests } } + // Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests. + private const string ItemSchemaId = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788"; + + private static string VectorPath(string name) + { + for (var dir = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); dir != null; dir = dir.Parent) + { + var candidate = Path.Combine(dir.FullName, "tests", "vectors", "document-variants-c0", name); + if (File.Exists(candidate)) return candidate; + } + throw new FileNotFoundException($"Shared vector {name} not found above {TestContext.CurrentContext.TestDirectory}."); + } + + private static async Task PullRefusalAsync(string vector) + { + var root = Path.Combine(Path.GetTempPath(), $"cultlib-vector-{Guid.NewGuid():N}"); + Directory.CreateDirectory(root); + try + { + var file = Path.Combine(root, "store.msgpack"); + File.Copy(VectorPath(vector), file); + using var cache = new CultCache(); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(file)); + var error = Assert.CatchAsync(async () => await cache.PullAllBackingStoresAsync()); + Assert.That(error, Is.Not.Null); + Assert.That(error!.ToString(), Does.Contain(nameof(NotSupportedException))); + return error.ToString(); + } + finally + { + if (Directory.Exists(root)) Directory.Delete(root, recursive: true); + } + } + + [Test] + public async Task SingleFileRefusesUnknownHeaderByName() + { + Assert.That(await PullRefusalAsync("unknown-header.msgpack"), Does.Contain("cultcache.store.v9")); + } + + [Test] + public async Task SingleFileRefusesExtraRecordSlotNamingTheRecord() + { + var message = await PullRefusalAsync("extra-slot-full-payload.msgpack"); + Assert.That(message, Does.Contain("item:anvil")); + Assert.That(message, Does.Contain(ItemSchemaId)); + } + + [Test] + public async Task SingleFileRefusesVariantStoreByVersionOrRecord() + { + Assert.That(await PullRefusalAsync("variant-v2.msgpack"), + Does.Contain("cultcache.store.v2").Or.Contain("item:anvil-big")); + } + + [Test] + public void V1StoreWrittenAtTheBaseCommitStillDecodesByteForByte() + { + var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(VectorPath("v1-base.msgpack"))); + CultDocumentMessagePackSerialization.RequireSingleFileFormat(snapshot); + + Assert.That(snapshot.FormatVersion, Is.EqualTo("cultcache.store.v1")); + Assert.That(snapshot.Records.Select(record => record.Key), Is.EqualTo(new[] { "alpha", "beta" })); + Assert.That(snapshot.Records[0].Payload, Is.EqualTo(new byte[] { 0x92, 0xa5, (byte)'a', (byte)'l', (byte)'p', (byte)'h', (byte)'a', 0x01 })); + Assert.That(snapshot.Records[1].Payload, Is.EqualTo(new byte[] { 0x92, 0xa4, (byte)'b', (byte)'e', (byte)'t', (byte)'a', 0x02 })); + } + // Format strings taken from DirectoryMessagePackBackingStore.cs at 0db1fe5. [TestCase("cultcache.store.v1")] [TestCase("cultcache.store.v1.directory")] diff --git a/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs b/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs new file mode 100644 index 00000000..7636cacf --- /dev/null +++ b/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using FluentAssertions; +using GameCult.Caching; +using NUnit.Framework; + +#nullable enable + +namespace GameCult.Mesh.Tests; + +// Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests. +public sealed class CultMeshVariantRefusalTests +{ + private const string ItemSchemaId = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788"; + + private static string VectorPath(string name) + { + for (var dir = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); dir != null; dir = dir.Parent) + { + var candidate = Path.Combine(dir.FullName, "tests", "vectors", "document-variants-c0", name); + if (File.Exists(candidate)) return candidate; + } + throw new FileNotFoundException($"Shared vector {name} not found above {TestContext.CurrentContext.TestDirectory}."); + } + + private static NotSupportedException Refusal(string vector) => + Assert.Throws(() => + CultMesh.ReadSingleFileDocumentPayload(VectorPath(vector), new CultRecordKey("item:bellows"), ItemSchemaId))!; + + [Test] + public void ReadSingleFileDocument_RefusesUnknownHeaderByName() => + Refusal("unknown-header.msgpack").Message.Should().Contain("cultcache.store.v9"); + + [Test] + public void ReadSingleFileDocument_RefusesExtraRecordSlotNamingTheRecord() + { + var message = Refusal("extra-slot-full-payload.msgpack").Message; + message.Should().Contain("item:anvil").And.Contain(ItemSchemaId); + } + + [Test] + public void ReadSingleFileDocument_RefusesVariantStoreByVersionOrRecord() + { + var message = Refusal("variant-v2.msgpack").Message; + (message.Contains("cultcache.store.v2") || message.Contains("item:anvil-big")).Should().BeTrue(message); + } +} From 569d668141b3c76929d10ec5adfd4de40a2685a8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:04:34 +0200 Subject: [PATCH 25/64] TypeScript: refuse unknown store headers and extra record slots by name The store reader and the inspector share one header and record-slot rule; an unknown cultcache.store.* header no longer falls through to the legacy envelope decoder. Co-Authored-By: Claude Sonnet 5 --- .../cultcache-ts/src/cult-cache-inspector.ts | 9 ++-- .../single-file-messagepack-backing-store.ts | 6 +-- packages/cultcache-ts/src/store-format.ts | 33 ++++++++++++++ packages/cultcache-ts/test/cult-cache.test.ts | 45 +++++++++++++++++++ 4 files changed, 84 insertions(+), 9 deletions(-) create mode 100644 packages/cultcache-ts/src/store-format.ts diff --git a/packages/cultcache-ts/src/cult-cache-inspector.ts b/packages/cultcache-ts/src/cult-cache-inspector.ts index 1301fe47..54e75700 100644 --- a/packages/cultcache-ts/src/cult-cache-inspector.ts +++ b/packages/cultcache-ts/src/cult-cache-inspector.ts @@ -1,5 +1,7 @@ import { decode } from "@msgpack/msgpack"; +import { STORE_FORMAT_VERSION, isV1Snapshot, requireV1RecordSlots } from "./store-format"; + export interface CultCacheInspection { filePath: string; fileSizeBytes: number; @@ -39,8 +41,6 @@ export interface InspectedRecord { payloadDecodeError?: string; } -const STORE_FORMAT_VERSION = "cultcache.store.v1"; - export function inspectCultCacheBytes( filePath: string, bytes: Uint8Array, @@ -197,6 +197,7 @@ function decodeV1Record(value: unknown, catalogBySchemaId: Map { return typeof value === "object" && value !== null; } diff --git a/packages/cultcache-ts/src/single-file-messagepack-backing-store.ts b/packages/cultcache-ts/src/single-file-messagepack-backing-store.ts index 4d2bb4f9..b7d9684c 100644 --- a/packages/cultcache-ts/src/single-file-messagepack-backing-store.ts +++ b/packages/cultcache-ts/src/single-file-messagepack-backing-store.ts @@ -4,6 +4,7 @@ import { dirname, resolve } from "node:path"; import { decode, encode } from "@msgpack/msgpack"; import { z } from "zod"; +import { STORE_FORMAT_VERSION, isV1Snapshot, requireV1RecordSlots } from "./store-format"; import type { CacheBackingStore, CultCacheEnvelope, @@ -12,8 +13,6 @@ import type { PushAllOptions, } from "./types"; -const STORE_FORMAT_VERSION = "cultcache.store.v1"; - const envelopeSchema = z.object({ key: z.string().min(1), type: z.string().min(1), @@ -285,7 +284,7 @@ function encodeCatalogMember(member: CultCacheSchemaCatalogMember): unknown[] { } function decodeSnapshot(decoded: unknown): DecodedSnapshot | undefined { - if (!Array.isArray(decoded) || decoded.length === 0 || decoded[0] !== STORE_FORMAT_VERSION) { + if (!isV1Snapshot(decoded)) { return undefined; } @@ -436,6 +435,7 @@ function decodeRecord(value: unknown): PersistedRecord { throw new Error("CultCache persisted records must be MessagePack arrays."); } + requireV1RecordSlots(value); const [key = "", schemaId = "", storedAt = "", payload = new Uint8Array()] = value; if (!isNonEmptyString(key) || !isNonEmptyString(schemaId) || !isNonEmptyString(storedAt)) { throw new Error("CultCache persisted records must declare key, schemaId, and storedAt."); diff --git a/packages/cultcache-ts/src/store-format.ts b/packages/cultcache-ts/src/store-format.ts new file mode 100644 index 00000000..02de60e7 --- /dev/null +++ b/packages/cultcache-ts/src/store-format.ts @@ -0,0 +1,33 @@ +export const STORE_FORMAT_VERSION = "cultcache.store.v1"; + +const STORE_FORMAT_PREFIX = "cultcache.store."; +const PERSISTED_RECORD_SLOTS = 4; + +/** + * True for a v1 snapshot, false for anything that is not a CultCache store header (the legacy + * envelope array). Any other `cultcache.store.*` header is refused by name. + */ +export function isV1Snapshot(decoded: unknown): decoded is unknown[] { + if (!Array.isArray(decoded) || typeof decoded[0] !== "string" || !decoded[0].startsWith(STORE_FORMAT_PREFIX)) { + return false; + } + + if (decoded[0] !== STORE_FORMAT_VERSION) { + throw new Error( + `CultCache store format "${decoded[0]}" is not readable; this runtime reads "${STORE_FORMAT_VERSION}" only. ` + + "The store needs a runtime that resolves document variants.", + ); + } + + return true; +} + +/** Refuses a persisted record with more slots than v1 defines, naming its key and schema id. */ +export function requireV1RecordSlots(record: unknown[]): void { + if (record.length > PERSISTED_RECORD_SLOTS) { + throw new Error( + `CultCache record "${String(record[0])}" (schema "${String(record[1])}") has ${record.length} slots; ` + + `this runtime reads ${PERSISTED_RECORD_SLOTS}. The store needs a runtime that resolves document variants.`, + ); + } +} diff --git a/packages/cultcache-ts/test/cult-cache.test.ts b/packages/cultcache-ts/test/cult-cache.test.ts index 5932b2f8..a743ba00 100644 --- a/packages/cultcache-ts/test/cult-cache.test.ts +++ b/packages/cultcache-ts/test/cult-cache.test.ts @@ -1413,3 +1413,48 @@ async function runJsonCommand( return JSON.parse(trimmed.split(/\r?\n/).at(-1) as string); } + +// Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests. +const variantVectors = resolve(cultLibRoot, "tests", "vectors", "document-variants-c0"); +const itemSchemaId = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788"; + +async function pullVector(name: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "cultcache-vector-")); + const file = join(dir, "store.msgpack"); + await writeFile(file, await readFile(join(variantVectors, name))); + return new SingleFileMessagePackBackingStore(file).pullAll(); +} + +test("SingleFileMessagePackBackingStore refuses an unknown store header by name", async () => { + await assert.rejects(() => pullVector("unknown-header.msgpack"), /cultcache\.store\.v9/u); +}); + +test("SingleFileMessagePackBackingStore refuses an extra record slot naming the record", async () => { + await assert.rejects( + () => pullVector("extra-slot-full-payload.msgpack"), + (error: Error) => error.message.includes("item:anvil") && error.message.includes(itemSchemaId), + ); +}); + +test("SingleFileMessagePackBackingStore refuses a variant store by version or record", async () => { + await assert.rejects( + () => pullVector("variant-v2.msgpack"), + (error: Error) => error.message.includes("cultcache.store.v2") || error.message.includes("item:anvil-big"), + ); +}); + +test("CultCache inspector refuses the same vectors by name", async () => { + const inspect = async (name: string) => inspectCultCacheBytes(name, await readFile(join(variantVectors, name))); + await assert.rejects(() => inspect("unknown-header.msgpack"), /cultcache\.store\.v9/u); + await assert.rejects( + () => inspect("extra-slot-full-payload.msgpack"), + (error: Error) => error.message.includes("item:anvil") && error.message.includes(itemSchemaId), + ); +}); + +test("a v1 store written at the base commit still reads byte for byte", async () => { + const envelopes = await pullVector("v1-base.msgpack"); + assert.deepEqual(envelopes.map((entry) => [entry.key, entry.type]), [["alpha", "vectors.item"], ["beta", "vectors.item"]]); + assert.deepEqual([...envelopes[0]!.payload], [0x92, 0xa5, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x01]); + assert.deepEqual([...envelopes[1]!.payload], [0x92, 0xa4, 0x62, 0x65, 0x74, 0x61, 0x02]); +}); From c8777fe08d4b7bd4de9df327b60387be29d4e50a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:04:34 +0200 Subject: [PATCH 26/64] Python: refuse unknown store headers and extra record slots by name Delete the raw_record[:4] slice and the legacy-envelope fallthrough for unknown cultcache.store.* headers. Co-Authored-By: Claude Sonnet 5 --- .../cultcache-py/src/cultcache_py/stores.py | 18 ++++++++-- packages/cultcache-py/tests/test_cultcache.py | 34 +++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/packages/cultcache-py/src/cultcache_py/stores.py b/packages/cultcache-py/src/cultcache_py/stores.py index 697882e0..0980f743 100644 --- a/packages/cultcache-py/src/cultcache_py/stores.py +++ b/packages/cultcache-py/src/cultcache_py/stores.py @@ -14,6 +14,8 @@ from .backing_store import ( ) STORE_FORMAT_VERSION = "cultcache.store.v1" +_STORE_FORMAT_PREFIX = "cultcache.store." +_PERSISTED_RECORD_SLOTS = 4 class JsonLinesBackingStore: @@ -153,7 +155,14 @@ def _encode_v1_snapshot(envelopes: list[CultCacheEnvelope]) -> list[Any]: def _decode_v1_snapshot(decoded: Any) -> list[CultCacheEnvelope] | None: - if not isinstance(decoded, list) or not decoded or decoded[0] != STORE_FORMAT_VERSION: + if not isinstance(decoded, list) or not decoded: + return None + if isinstance(decoded[0], str) and decoded[0].startswith(_STORE_FORMAT_PREFIX) and decoded[0] != STORE_FORMAT_VERSION: + raise ValueError( + f"CultCache store format {decoded[0]!r} is not readable; this runtime reads {STORE_FORMAT_VERSION!r} only. " + "The store needs a runtime that resolves document variants." + ) + if decoded[0] != STORE_FORMAT_VERSION: return None if len(decoded) < 3 or not isinstance(decoded[1], list) or not isinstance(decoded[2], list): raise ValueError("CultCache v1 snapshot must contain a schema catalog and record array") @@ -169,7 +178,12 @@ def _decode_v1_snapshot(decoded: Any) -> list[CultCacheEnvelope] | None: for raw_record in decoded[2]: if not isinstance(raw_record, list) or len(raw_record) < 4: raise ValueError("CultCache persisted records must be MessagePack arrays") - key, schema_id, stored_at, payload = raw_record[:4] + if len(raw_record) > _PERSISTED_RECORD_SLOTS: + raise ValueError( + f"CultCache record {raw_record[0]!r} (schema {raw_record[1]!r}) has {len(raw_record)} slots; " + f"this runtime reads {_PERSISTED_RECORD_SLOTS}. The store needs a runtime that resolves document variants." + ) + key, schema_id, stored_at, payload = raw_record if not isinstance(key, str) or not key: raise ValueError("CultCache persisted records must declare a key") if not isinstance(schema_id, str) or not schema_id: diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index ac81cc6d..b4168690 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -802,5 +802,39 @@ class CultCacheTests(unittest.TestCase): self.assertEqual(cache.get_required_envelope(document, "item:one").key, "item:one") + # Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests. + _VECTORS = Path(__file__).resolve().parents[3] / "tests" / "vectors" / "document-variants-c0" + _ITEM_SCHEMA_ID = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788" + + def _pull_vector(self, name: str) -> list[CultCacheEnvelope]: + with tempfile.TemporaryDirectory() as tmp: + store_path = Path(tmp) / "store.msgpack" + store_path.write_bytes((self._VECTORS / name).read_bytes()) + return SingleFileMessagePackBackingStore(store_path).pull_all() + + def test_single_file_refuses_unknown_header_by_name(self) -> None: + with self.assertRaises(ValueError) as caught: + self._pull_vector("unknown-header.msgpack") + self.assertIn("cultcache.store.v9", str(caught.exception)) + + def test_single_file_refuses_extra_record_slot_naming_the_record(self) -> None: + with self.assertRaises(ValueError) as caught: + self._pull_vector("extra-slot-full-payload.msgpack") + self.assertIn("item:anvil", str(caught.exception)) + self.assertIn(self._ITEM_SCHEMA_ID, str(caught.exception)) + + def test_single_file_refuses_variant_store_by_version_or_record(self) -> None: + with self.assertRaises(ValueError) as caught: + self._pull_vector("variant-v2.msgpack") + message = str(caught.exception) + self.assertTrue("cultcache.store.v2" in message or "item:anvil-big" in message, message) + + def test_v1_store_written_at_the_base_commit_still_reads_byte_for_byte(self) -> None: + envelopes = self._pull_vector("v1-base.msgpack") + self.assertEqual([(e.key, e.type) for e in envelopes], [("alpha", "vectors.item"), ("beta", "vectors.item")]) + self.assertEqual(envelopes[0].payload, b"\x92\xa5alpha\x01") + self.assertEqual(envelopes[1].payload, b"\x92\xa4beta\x02") + + if __name__ == "__main__": unittest.main() From 95f04c1efb5788042b3b17d75a7916a33cbec95f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:04:34 +0200 Subject: [PATCH 27/64] Rust: name the record and the version when a store is refused PersistedRecord refuses a fifth slot naming its key and schema id, and an unknown cultcache.store.* header no longer falls through to the legacy envelope decode that hid the cause. Co-Authored-By: Claude Sonnet 5 --- packages/cultcache-rs/src/lib.rs | 128 +++++++++++++++++++++++++++++-- 1 file changed, 121 insertions(+), 7 deletions(-) diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index ed9cae32..a535b935 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -271,7 +271,7 @@ struct PersistedSchemaCatalogMember( Option, ); -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, serde::Serialize)] struct PersistedRecord( String, String, @@ -279,6 +279,66 @@ struct PersistedRecord( #[serde(with = "serde_bytes")] Vec, ); +impl<'de> serde::Deserialize<'de> for PersistedRecord { + /// Reads the four v1 slots and refuses a fifth, naming the record. A record with more + /// slots was written by a runtime that resolves document variants. + fn deserialize>(deserializer: D) -> std::result::Result { + use serde::de::{Error, IgnoredAny, SeqAccess, Visitor}; + + struct RecordVisitor; + impl<'de> Visitor<'de> for RecordVisitor { + type Value = PersistedRecord; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a CultCache persisted record of 4 slots") + } + + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let key: String = seq.next_element()?.ok_or_else(|| A::Error::invalid_length(0, &self))?; + let schema_id: String = seq.next_element()?.ok_or_else(|| A::Error::invalid_length(1, &self))?; + let stored_at: String = seq.next_element()?.ok_or_else(|| A::Error::invalid_length(2, &self))?; + let payload: serde_bytes::ByteBuf = + seq.next_element()?.ok_or_else(|| A::Error::invalid_length(3, &self))?; + if seq.next_element::()?.is_some() { + return Err(A::Error::custom(format!( + "CultCache record {key:?} (schema {schema_id:?}) has more than 4 slots; this runtime reads 4. The store needs a runtime that resolves document variants." + ))); + } + Ok(PersistedRecord(key, schema_id, stored_at, payload.into_vec())) + } + } + + deserializer.deserialize_seq(RecordVisitor) + } +} + +/// The store header string, or `None` when the bytes are not a snapshot-shaped array +/// (the legacy envelope array starts with a map). +fn store_header(bytes: &[u8]) -> Option { + struct Header(String); + impl<'de> serde::Deserialize<'de> for Header { + fn deserialize>(deserializer: D) -> std::result::Result { + struct HeaderVisitor; + impl<'de> serde::de::Visitor<'de> for HeaderVisitor { + type Value = Header; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("an array whose first slot is the store header") + } + + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let header: String = seq + .next_element()? + .ok_or_else(|| ::invalid_length(0, &self))?; + Ok(Header(header)) + } + } + deserializer.deserialize_seq(HeaderVisitor) + } + } + rmp_serde::from_slice::
(bytes).ok().map(|header| header.0) +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct PushAllOptions { pub soft: bool, @@ -658,9 +718,11 @@ impl SingleFileMessagePackBackingStore { if bytes.is_empty() { return Ok(Vec::new()); } - decode_store_snapshot(&bytes) - .or_else(|_| rmp_serde::from_slice(&bytes)) - .with_context(|| format!("failed to decode MessagePack {}", self.path.display())) + match store_header(&bytes) { + Some(header) if header.starts_with("cultcache.store.") => decode_store_snapshot(&bytes), + _ => rmp_serde::from_slice(&bytes).map_err(anyhow::Error::from), + } + .map_err(|error| anyhow!("failed to decode MessagePack {}: {error:#}", self.path.display())) } /// Reads one filesystem snapshot without creating or opening the sibling @@ -2518,11 +2580,15 @@ fn encode_store_snapshot(entries: &[CultCacheEnvelope]) -> Result Result> { + if let Some(header) = store_header(bytes) { + if header != "cultcache.store.v1" { + return Err(anyhow!( + "CultCache store format {header:?} is not readable; this runtime reads \"cultcache.store.v1\" only. The store needs a runtime that resolves document variants." + )); + } + } let snapshot: PersistedStoreSnapshot = rmp_serde::from_slice(bytes).context("failed to decode CultCache v1 snapshot")?; - if snapshot.0 != "cultcache.store.v1" { - return Err(anyhow!("unsupported CultCache snapshot {}", snapshot.0)); - } let catalog = snapshot .1 @@ -4573,4 +4639,52 @@ mod tests { assert_eq!(store.pull_all_read_only_snapshot()?, vec![admitted]); Ok(()) } + + // Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests. + const ITEM_SCHEMA_ID: &str = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788"; + + fn pull_vector(name: &str) -> Result> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.msgpack"); + let vector = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/vectors/document-variants-c0") + .join(name); + std::fs::copy(vector, &path)?; + SingleFileMessagePackBackingStore::new(&path).pull_all() + } + + fn refusal(name: &str) -> String { + format!("{:#}", pull_vector(name).unwrap_err()) + } + + #[test] + fn single_file_refuses_unknown_header_by_name() { + assert!(refusal("unknown-header.msgpack").contains("cultcache.store.v9")); + } + + #[test] + fn single_file_refuses_extra_record_slot_naming_the_record() { + let message = refusal("extra-slot-full-payload.msgpack"); + assert!(message.contains("item:anvil"), "{message}"); + assert!(message.contains(ITEM_SCHEMA_ID), "{message}"); + } + + #[test] + fn single_file_refuses_variant_store_by_version_or_record() { + let message = refusal("variant-v2.msgpack"); + assert!( + message.contains("cultcache.store.v2") || message.contains("item:anvil-big"), + "{message}" + ); + } + + #[test] + fn v1_store_written_at_the_base_commit_still_reads_byte_for_byte() -> Result<()> { + let envelopes = pull_vector("v1-base.msgpack")?; + let rows: Vec<_> = envelopes.iter().map(|e| (e.key.as_str(), e.r#type.as_str())).collect(); + assert_eq!(rows, vec![("alpha", "vectors.item"), ("beta", "vectors.item")]); + assert_eq!(envelopes[0].payload, b"\x92\xa5alpha\x01"); + assert_eq!(envelopes[1].payload, b"\x92\xa4beta\x02"); + Ok(()) + } } From 6b107c1adc2c083b922caf4139859ca4f5cacac8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:05:14 +0200 Subject: [PATCH 28/64] cultnet-ts: Rust-generated Idunn runtime fixtures Expected, Activation, identities and signed presence vectors from the cultnet-rs example; the README says how to regenerate them. Co-Authored-By: Claude Sonnet 5 --- .../test/fixtures/idunn-runtime/README.md | 2 +- .../rudp-route/activation-key.seed | 3 +-- .../idunn-runtime/rudp-route/activation.cc | Bin 800 -> 800 bytes .../idunn-runtime/rudp-route/expected.cc | Bin 1076 -> 1076 bytes .../rudp-route/presence-active.bin | Bin 922 -> 922 bytes .../rudp-route/presence-warming.bin | Bin 923 -> 923 bytes .../rudp-route/provider-identity.credential | Bin 680 -> 688 bytes .../idunn-runtime/service/activation-key.seed | 2 +- .../idunn-runtime/service/activation.cc | Bin 806 -> 806 bytes .../idunn-runtime/service/expected.cc | Bin 1308 -> 1308 bytes .../service/presence-active-below-minimum.bin | Bin 940 -> 940 bytes .../idunn-runtime/service/presence-active.bin | Bin 940 -> 940 bytes .../service/presence-warming.bin | Bin 941 -> 941 bytes .../service/provider-identity.credential | Bin 685 -> 673 bytes .../idunn-runtime/web/activation-key.seed | 3 ++- .../fixtures/idunn-runtime/web/activation.cc | Bin 798 -> 798 bytes .../fixtures/idunn-runtime/web/expected.cc | Bin 1067 -> 1067 bytes .../idunn-runtime/web/presence-active.bin | Bin 915 -> 915 bytes .../idunn-runtime/web/presence-warming.bin | Bin 916 -> 916 bytes .../web/provider-identity.credential | Bin 683 -> 676 bytes 20 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md b/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md index 99e7b07f..de1ccea4 100644 --- a/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md @@ -1,7 +1,7 @@ # Idunn runtime fixtures Written by the Rust owner, not by the TypeScript tests. Regenerate with -`packages/cultnet-rs/examples/idunn_runtime_fixture.rs` (CultLib `f5c597a`; it uses +`packages/cultnet-rs/examples/idunn_runtime_fixture.rs` (CultLib `9ba6ac4`; it uses cultnet-rs only, and Idunn's `IdunnRuntimeActivationLaunch` is that same crate's). It needs Linux and a machine-id equal to the `machine-id` file here, because the provider identity is bound to it. On Yggdrasil: diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed index ddaffdda..1ae250bc 100644 --- a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed @@ -1,2 +1 @@ - -²ÊVÖH¾\IJ½ôðŸíȈ{’^ª+l£Z¼}k† \ No newline at end of file +v$ñ´ØÃ/Š ¼Èá|Æuö«g4FÜK%k±€~qû \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc index 556e8a173ce1d8648b70b1435402d0bdd183fff8..3676c985fb95c7105989d04f20473d4644699db5 100644 GIT binary patch delta 325 zcmWN}JuE{}7=Yn+(8U#t5GE6Dkeu(_^Xo4iCDMkaVQHN2+;a>>V(TU;Q$s{71W7kG zO*&AEkTwm5&I|^@Y>`+b?)DB(-fE_rsg=`N4gi)2D=9O?06K?}5+=nMjluh)jB;gi3-tsW6hsg=uX?0u&G~EdvuL zZ;P75zBzm_TIp^L%??}#h25}z`02lM`HABGb9v={YAfvR>ZDTXYIAY9^pYi!avX&= z(mUb_Qd3e8fr>b1+9Riydc}3@0Tl{x)L82x&%m*mAVYfLV#+z_X14F|ZR9FE@0kxS z&z6G8o7Laq&tShRwJLWruaEWd!q>@1qup6wc+YRR;OTaxF*mk1eYz8F*4nvamih;r C+-_k2 delta 325 zcmWO0zbnLX9LMpyWLX!Ywl(|I!V%U4==&tu`1_+vR8ViXFC7PHee(p_Db3%8fejlb>EPr6WP GrTzhj)NV%r diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/expected.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/expected.cc index e546f849e2b62d9874000d6a21ad4bb9c741651b..040ea0f69b70a5dcd3de806d7bc62e3d2000f294 100644 GIT binary patch delta 76 zcmV~$yAgmO3;@uA^Nw*sh>&zP4nlqlxrhaOxq|QQy6bzCD=-F6x9G6g8;Y}bnA!w^ aI8D5FR0zs(8o^u5nL~a`)De0d3JcnEixkwjA1O;K6`#6^tMPOhr$iiq5Sq(u8 zv78`^Aead^f}5CT(Mv3(K&TdhOQRrHh4gRr`xd{&$2Z+I-F0_x*Z@EjHae-j@DP}T zLhF@8LMl*1&VVS`C6banfrhAL@Dgkwr&kW0JLRRZ{q_2RdSgrd{a7su$;4o@lRhys zgs8H?kTrTHNNh7gmYB$^9DFe;>HwM9VE~=xu9P>ICs?vYmm(|SF@dCnK?xUtq|lfn zB~@q$*4dh=bs;Irc~Ycdthm8a>%Z-Zq3RR=nIBA@nOk0c)moh2d1vfRWu<1= zQ#8(KTLj5A1nsg%iv^hf{>l}>G*Pt00YMlSHTYCyjDbYTom$`I)@{%BzwN)j*xUSc zu+_3JdKXqNZ@<|yyy<84?2q>Cj~kWdpPud$zh*|iT(~zo`*QCi{5rU?dpuMc*DhV} F{s*O)pYH$w delta 442 zcmWO2O^D4=7zXfrLsL?-kd!h)CYsba?|IM1JE(sdX{>IuQJPWb<2|9NDVKCNbDNc< zp6Q?uL7Rh}&Y{lCrq1H|3fZ#l^EBX;n_(q$~~xgf1w;C`m@e zNg?Vi45Y{bq%qnRCnmtaiabRWSYN8u>NDNOcx{doXf3H*OE`ZhqMPtbahR?^^wFvGJ}N`4w&)-mp>u z7+(x27nu;b#Go;t7o4I36wxZ=&}HQH(!6;JbNz>oO`-9fB)qAmc8Hl GdjA7pE1M_) diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin index 1211a6059e5c63d55e7ba915d9f89e5dd5ca2b66..ad4c0d9f1d15e506031aba710fe9223d3f672f0a 100644 GIT binary patch delta 442 zcmWlVKSNHt8uZ|OpZ9qYF|dC_4GIpo)Zn2l zx*RTP&{PnK2*QDR22FuNQA0yRoJ2?k4gH$FpW!=v_^b@93@p^I7yuw)$w?hVfXEz` zw?Rpd9!nI&8N3(l5=w~yK?5lng9IDV>4VGnCWAC~q}{&Q?o`|F?$$_1Mh2Um42hW` zlFG)%tbJgF#5Q}#(kBcm$52ip9U(J2A3>*=vqiO-W69RLM65*c2_z;Tm2eSI3hgst zQl*Aqovk4)TwvBQCq&dDlceH(rBZad*QYDbI7wpwyR}ERf1l^x$rm!7pw9f^*$eCY z%f}-Q4V~)^|5=^cSsY&5d(ynqYOGGp-Q1WO9DV%dQ)8$3c31AI=I4iv;-F?YAQ@-0 zErVnmqjouX>q{{I{go?&X+*N+!Gkc4G=x-Uq=+KrZf$Ytet+hO&ir&w)wS`zSpT*) zzkDOV9y>Mu^~1>I#OT=7V;g&eM@y$)ZMOKq_mBO4uYPOc`K8vI?fuzbKdS!#kwBg{ delta 442 zcmWO2O^A(A90u_BjoVoIT1{yt%`B(R`Jey)eE7(#X_6YD=(0SYMln;^D9yFNW{P=B zQj^^70#g=hSgDcb)?^|JDYsBFDTO9kpd`-jSv-s1^UU?l_05hR4CuI%kdW~RV9}C{ z!9*z(c}>bVunJNlP=*m$9~l{Cyf=zaMyq-U&QDk%Ia1fV>vp4ld9K1}qXnbA77{@# zZb$}T%y4FT3_Jv#JMtv@W*lwfRH0AC4_-DmvFjH#a&PuQqxW zfV9~VQkF56a&&|aEsMbmK<1Ue7_8U%PGl)B&C_#T$q=+d(XEERoqGJ_<6v{^rLjGq zmfz3s+pzOT8QXu~EFT*@dhgNGf#&*t`?kM#<@3seMft3=K7Mu^j4Z9bqRS@+zU=bF Ef9koK*Z=?k diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/provider-identity.credential b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/provider-identity.credential index be91ad0caedb4a48db32cb012ca9745c8ec3a654..8e1849bed2cbbf500423c8ae70cbb54bb1d8aff1 100644 GIT binary patch delta 323 zcmZ{cyGz4R7)P~IbaZsA#NyDTe!00#bGs-w_`0Sh>b7%PFY(@?)aV%f|Ktu_qivbE{x5OU>z;Kg!2@o@Qp8Q zV{IBA7wJF@-v4pVGpoVZzQ483dTutIZ!v*SS51~D`yja2+?(vDnEbefN z5I?vaMm11-n`MzF$`Q|H%(P+Z7H7Iisji~#bPHE#pn_@=2Y5x47{CdRig@YRJ?!J! lK?@uB&Ew6}W)w8>g!f2c#7vEZ#{R!YYQZi_H>ku${{WO5kc|KU delta 315 zcmZ{e%`1a(0LN{$93KbHWO2aO@9lY>-?JKpl=~)4(epNWI}F=lV!2QnVM#bTcs;l& zIk>oe@AGJ(9c1SzqRjjOZlBBN)8{I18rY8ceYKqtnxi^TI!sck+EOw@NQ)c7rUtdS z>u@2|B+-~-yB4FGrb>&M!ePR4xnUZ%AfnXJ1`pR!(bxxX8c#UE5ni#1+ZAjiP-$=Jq;k28O2qAwHmkJ)RHWbGP-ms6anIy`%m)JrP>-g4C!vTsd kDLlthgYzgyy&xk@3lSs4{x5qyljfXjr)L+#g-w6(7j8(1CIA2c diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation-key.seed b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation-key.seed index 06b4b38e..96376850 100644 --- a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation-key.seed +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation-key.seed @@ -1 +1 @@ -ÿWýck1òT ÷²¹ú[Á^ka©$}R%.\Ú–—¨k2 \ No newline at end of file +>�Õ8ÑÇ£rÆyÜà�&—ž@‚â± ç�ÜÌqM}‰ \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation.cc index 9ab8bf43efb594ecaf705082f7c8077721c1a83c..b633e64c21e43688fba5f0946933b20b0da03d1c 100644 GIT binary patch delta 325 zcmWlTze|Ea9EWug9HeloDZ#Pi?%w;}dj|~?($Ex$R8!oK?+p$SM&J_B;A%rO1`VPa z4$%}SEg8~KER5V#VQ84AKEqCBDmrKM+<;mn{ zgwkPD?1^EzDrrDv0Fm4qV3zsF>O3{l2#QQwi-G49xg&-f)(K^fFd)*OUfe_xT3+ch%iPpWz+{Pi0dW@lxnFs8p{y>O&C!Ot?e%ZtL^RmeWY<-3{w$>D|jvDNQN_96X~$>$#viDb1oH(z{?c@!)G zbXowCs4JNw<3PbM!2~q~6$2Fnbxczk83b>2_rnv$z2y|hkw+>7(am^yt24XtKHjc= z{ox7xzPZE2`t(aWGuVOl@oO$LZgz4WHw1TN5+G@q-RwAFy~cy$I5oW^Z@?+RCV#&%s$pl0Pw06ZF* pOX5X$j>u%Dnjq~|n2RHnB8slAWHq8}l;xYxp_|^Ly_=py1%4MO7fApB delta 89 zcmV~$!3{uA3;@swE^Z_yut58(zjd|AuU29nS2KvjG`8{H)m_~))N2%+Q7L=CvI&tf odlXBiiLx3SvE?0hjSvCwNbZizibWSs@J(mmjPFt3Rg0p6KV}*jmH+?% diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active-below-minimum.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active-below-minimum.bin index ed6f48b9bb48dc5dadc90d1d4454676ca49d764b..441e0bf465768df545ba951e9fe70b01a27e10e3 100644 GIT binary patch delta 444 zcmWlUJ808U6o(U9=pa4@2OoQvBHY)x_nbu|Qmu4Qs%wS&I2T{IC^k!pLs0~wMzJ^u zx`>L!K?zRLf&mRg+6o0D5)4@CP!ybe7XSX%?*|{>{LuW+^@E3Ri88Zt7DxfB? zEYVsY*+f>-11ph2445<8g0O+Cm_b2+?xFK1y#l+ZUf)}PTRp%+r-WKL3C=_ifjsz# z=mmKVkdlXFNfizkIAswM7eD36qq9org@qUO^la$?Cj}s>RhhZ^^Hpc9apuUzt-nv! zx4f^8O+0;heBjZ?xz96S+p9O$?k|tL+j)6Y?@yz)GQ8vU!{)Q;^~S}!dH$TAuCmoU;_!t%m_tBR?+xS;P8Jk7!VqqMh1wPQf^gfwAY`V8-KpBbg8{G zS)01@ZG5n|^>P1N|4sGw%J&OXAG(vxQ@c9N(zcP)i~D9j4eUNQoKJKczb1}###Y;d F{{X|HrojLJ delta 444 zcmWO2KSv#I_U8pWp@0>baiq#+-eZjU?mRJP|NqDHSQ3xw>HO2)9nM9Gt~ zKAEIUvL%#W#5n-&A(_z_kI@GvsH_!5<#}uTa`94_jKR>VAD{SX4<8&Fe^gug{rPQc zYhdT<#I53Jqw&Xm-FUb?|LNVUH+$A%f4A{$uJ6+0*BgUdzwS@2Z(bYQb>-sVi5*3! zo`G0J6i3>sQhO>zSyT!GDUvc6%)JC9QE*;!B<&zYMwi4%?@X)yv^}|Zb7pn={Os_z z?t}Mt#}@se_R!hCUlwO;_+sSW#~bHvc7GfgJ=5m?eSPysuyf(|eqUXlrrk^5Yr|8; Ef6}*|IRF3v diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active.bin index f9bb5d1887b9ab4524b31b33838ce55994ac48f3..1f13b519925596e9b77619edbbd991d2321f5b30 100644 GIT binary patch delta 444 zcmWlUIcSto6h>#TNa2bM;?@MkM%1_6`|dLsCIliP5v@cE!&~kn30g>+6d5Lk*hTUy zVqppqi3q90CLlTk!=T{c0wO^REyczns4#K){o3=v;j9d-3@nbFvVzbUlQLx%3REEN z09g{Ek8C0<>4B9D`ghWxNHFxF$#^w zIU&1zRf;5{B&$_6%QRB zslM2BvD@C*xZXe5|NCkD#_~jMaOS~<^`CD(ylie6i6`do_WEC!?$7O7*qZKqJ~mld ztCw9YoM6Xb97+`=U~s}^W`Z&!t7v>Eari$O37z$ zjObE9q2Q9mx`pMNX?ZNioy)$Ps8wE_k1xyssD&;5= zTZ)prgKWV=U>2l|m(fCkltQ!y&}tPjt&Pr11)z zb(A`q4B0VT3qXA&5o+x)I8Oq~tEE!;Nq6je=^2yI8hy96bsP7OA8D?vcV1rmI~x}4 zRIk^o37J$9m3KYsPo(EZl9Q|D6t)+I(eu=2P=tY-kEpi9TZsztPX*YP*DW)=ba)X3K24b1?#4e zA0CymMW`Sz9rTn4t#lBn2&p9s=@0~UD5R)E^!2+wKX`Z+I~O~r2Txi-Mr)liWfp)C zNI5ht$rvA5M+WJUL8K4^-x?aJJmdt3(zWV4E-ZCC-v4N0;r@?_ z=U3j&f4dDsxm$YtMLih}@A1XH0PA01$Yz2TAh**K7 zfG%>%Ddy-itK>afWs(mxLSSksuuPyOtiK>JbQI)=F{$<=LY?wp?UJ!g}ciW8}$sx z6qPvCmWuXRgsdV`0STo9qw*+0K@84oj;I}^$jT*gGCI?%Pj?&3dxuvJ9oT2=YYg5r2``QP2SkCL Apa1{> diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/provider-identity.credential b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/provider-identity.credential index 45db9617f2fcfb960f3afda9b8ec42fdc1a6b2d1..0b9ae91fe0544f8f1b0d3f6074e252b4e2d62efb 100644 GIT binary patch delta 316 zcmZ{c&nts*0EfNPike)w%wc}C)4Xrr_t*Ew)@n&sk{WNxL3!V8uhc{ua?mSonl;Tq zlgvd$C?c*Y~UL2jY+{n@P2RJ@YPtQfL7OYt9((iHA3n-qS(sZU~ZBBDcRb3(s z;WCqIJWq*E4Iwx;RWolmlsc}iIu7Hy%Uy1WEYVrcu-SWCe<*=ks$+fQo8|uBd#aEZ*^`Sh1 zhJ*@E@l;i$S5H`k#EB6%siK)oBf7~%tfffn`GWcu_R?t?2PokOnA(UYr(JxGVn35E q-~rco42N+P!d=E6(uhW7B4q9Vt3SM8FXgjqg`%>uy1ZU32O@udkbXM= delta 317 zcmZ{eze@s90LRM`Y7bf}j6nLK^6ov~-MiZwf+mTOAZWSsJ(EBx;V2N4me$N0YKsOb z3ERT9q{XQ3(0UftAho!(7j^vs@twYW`F!}Eh8y8ZIusf_T+zzP){>fFx>Ur>7>qfb zOJzIM5tQk|;SS@Do+VkKlwlAe6_rwIoD0nsrljP#FM`&vhWa)-ljv?P;{{I%+@p>z z+Bkzp0MxKIzEDJOD~D!Kn*lWzo5wz;?^biJxr-}_R~#(i5tsNLL3?Nb=Oy$aqXkqK z@rDm?roU4bY04}nEN&!pLkK}d(wHN}B7Zkh_`(B@@q?<1#sqHhiR%qq;JpxNZ*YRz lPBd66LHyZ#3P)>b`BRioJx/W•ËW;ÆsÖSÅ2�µ4 \ No newline at end of file +c$…Jp[vcϽ|½Ô@ ž×í†`JÛûd +Í_z3Í3¢ \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc index 6127df727f18aed025681ae2377af563f9d11ed6..00c3c07fe4835b043b3eb018a11aa82dc52faabf 100644 GIT binary patch delta 325 zcmWO0zbnLX9LMoH>c}Mw5*EX4bba2RU*FG1UA`29>Cz>|aG#%7%vWa;16?VDn=i$s z7_eE@cc#>lB0m@93>Jf~eE)#gZ$Y1WGI0MXPn^30)P#)#atR;loiH12@(^~ z&IpW|p;T$Cz)SDF`&I2Mjlb3A zRx%@7mkYPwg~liucwMixm+#vjx%X%%`#jB#8kwG<=3-Ykx%P7SG?ncb9$f9a-uo^0 F{sSiua76$B delta 325 zcmWO0JtzcF902gU<#Htpu^0>(xblDB?+v)J%Pq1P-v50RW${rLMIsi9E~CqI1}UA+ zLS2`Ol#!T$8yi`&CB-s^+O_&JgQI4ulJ9c;?nfoWcnZHT5~4= diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/expected.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/expected.cc index 0b02a2e82b37bd2acf684a71abdc3196199b0264..748cc83dc11de7479ac6e80fcb4d8d49f79eb59a 100644 GIT binary patch delta 76 zcmWN{u@S%^2mrv#**Fdg3UtXRfJ~GzY%*7-NWT7EcYTg>+GrvkX`KZPAf}Gw6i;G; Z=wT*EBbu^n$Wol}Pc)w1(fPj0`vEWg6-odA delta 76 zcmV~$!4ZHk2n4`!@<}-uP{>b9N#JP6GV-x5t8jPKRo|^#P9Ad?OOx(kkR*VBsk5fg YU@-Yf{RoMs(XAy9R)b_{@N<{%2U>L&bN~PV diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin index 15ae2e8c9912a0fa89482131e573b2a8f3a72105..cefcf1d0f05aedf619ed6d6bb5b67de23d286e83 100644 GIT binary patch delta 440 zcmWNNO^D4=7{>oMG8UtdWU!)HSZL09&wD;z)ZAvHnUqec_|BkO+O@Y@^RsfV+V)Rl?hFL$2| z&rfbNzXlh&{rhvfc8{&Tf4ust@u4}`99bKwTttEv9Wf4@Y62LO|-D zP#s%JrMhX+$w4%M2uhvA76%u**`*nDNUd4F-}beJTfg%u%LAO>LbBu=Hp3w%Fh8F0Re|4aMH62V+mi zPj574N7j4qCJ$YCG4bul)>7;HMq_!dHvjs^$ceMN&5N7;FQ4Y`e)w3~u0aqYT7%Ym z9l#J+GQx$J2qXF!fg*#5Q3p~^XOfU2n83i8<6ujt2Hob{pR?}H^X2xv_H`Kjeen2F xufHh%J?qx1Lx)e^+Uy-Y_G`5MXkzDOdv3w(y*X1F+o?|PzrWf)UTMCn{0GnGpGW`z diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin index 1d106eb5ff53a16de8ad39b93facaf8125c67181..375131d00f282c71e7b67679f28c03c0bc167f71 100644 GIT binary patch delta 440 zcmWNNO-Phc7=^z<@FUt7h)_@x{K?<{S5xn=k_hK1_3H^W}5kw-z zd@x4PLP2CA+&Bv*h=iDM5mC5vR}?`D!A0%6`@=csc{*jMY&WkuE^MS|H4B{cV0-}W z$PxxiDLU>za39G6D3TIAAWtr(`FzEG^(M0Q`G?Ebz zq7_mRcgE+t!3oWBQlQZugg3RXMNwPpPuwoLF@RFs^&8vwMu%@L|N6eV^RczR^x<`V zcI^7G=THnhYZgntM_#>rxAJ1|esB2kPJ8j(=@ajF&m3K9ws*Vq_QB8D-uRD!g9fP} zECdxPyONs4q>OPwYRR*pY%R;umI2Fzg6Y7SWQZzyff+x_eq*ET*3Yum`N^@Tbmv<& zKC}O3`N{OZ`QvnQZezQ*l^)K_9gdv3_UX~hM(0oa%TQTgaW}%=)@JK(H8nI?{s()C Bm6iYi delta 440 zcmWO2J!q3r6oBFHqt-Ym=pd+r6`>A_<=mfhe>#{TO6^cAHWnT4J@+0(6o2YegbX#h z`au)~g+M_U2WNE=q7)qz9AZ#9NwqE_NO04v@3Xy~TBmmJ_$>MWT38X11!5q_GUyoD zC1b3zAmoTqT1QFh6qJ)F(Ik-^cpD)OW|l67Q8`*w(^YqC_5Mbka@Ixz>&${UBLakw z5H+KbM9LrsX^^x;=g3);Rc05XV5M34)mvrRBA^t7cI>pLk%Q)(bIQ(=vaBJftbh!7 zOgc%MypybgvMy^*HmUMMQIy@@{N>_lP7+c0UgPu4Eq}&e^gk`mufJRP{P3D&SyuuYbWYM{xy4DUii`ZcDuEGVX;1U>E*fh>$#1hIe3-#PF<@F8W4nt)}ZxX z2QUPdjBp_)!iYXbpvWL%)Pa=KnIxnLCNMDOINH){@Md$cwzQ{x_Tb6o=5TXt_;cdT zp=19hAFq7fxO4ZxSo`6w<&}wjlj`dEnZMKbA5CqmsQ7Y5{yu%+`Kc@Y!{h$}_;i># diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/provider-identity.credential b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/provider-identity.credential index baff802e3960ec5acb009a91fd33d54d7a4b471f..52b1b8e809059949d9b7af89dab19973f0b1e529 100644 GIT binary patch delta 316 zcmZ3@x`cH?2s7jFS(9s-^y+UqB$^spSR^HZ^Gn1X!t@IZJBwDEucV-)#R4Q6nh?puUDJ%p* zNuw6p2@wRr@&+snJ`k}IMG|b%sD*29cZ+imr)rm@G*cb)Nz4tG*QAi z8cVSv&J>z94yVx=#tq82o$88iDO@LW>4>^Q8}Haa4ZCP1dgmiW6{q-IMQw66HiXT- zZoJOnE>juld|Xs{#(l2*tQ>bqamfT@V?;jDU&=G?Q+frhiM42!@Dn%jDD5RGI>rI& eJ Date: Tue, 29 Sep 2026 02:05:14 +0200 Subject: [PATCH 29/64] cultnet-ts: split Idunn authority from the Odin publisher; answer route challenges locally idunn-runtime-authority.ts now loads and signs only: no Odin endpoint, no Odin dependency check, no RUDP. createIdunnRuntimeSigner signs presence and answers Idunn's route challenge with answerRouteObservation(request, state), a synchronous local signature in the state the app reports. The RUDP publisher moves to idunn-odin-presence-publisher.ts for services that declare odin.verse-rendezvous, and keeps the Expected-endpoint check. Deleted: the TS capability-minimum refusal (the Rust correlation records the typed disagreement), latestPresenceDocument, the forced "active", and the publisher's redundant health-contract and bind checks. Route validation now accepts http, tcp and rudp as Rust does; the machine-id falls back to /var/lib/dbus/machine-id. Tests run against the Rust-written fixtures. Co-Authored-By: Claude Sonnet 5 --- .../src/idunn-odin-presence-publisher.ts | 240 +++++++++++ .../cultnet-ts/src/idunn-runtime-authority.ts | 344 ++++----------- packages/cultnet-ts/src/index.ts | 10 +- .../test/idunn-runtime-authority.test.ts | 398 +++++++++--------- 4 files changed, 538 insertions(+), 454 deletions(-) create mode 100644 packages/cultnet-ts/src/idunn-odin-presence-publisher.ts diff --git a/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts b/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts new file mode 100644 index 00000000..8e13acb4 --- /dev/null +++ b/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts @@ -0,0 +1,240 @@ +import dgram from "node:dgram"; +import { decode, encode } from "@msgpack/msgpack"; + +import { encodeCultNetMessageForWire, parseCultNetMessage } from "./contracts"; +import type { IdunnRuntimeSigner } from "./idunn-runtime-authority"; +import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; +import type { CultNetRudpPacket } from "./rudp"; +import type { RuntimePresenceHealth } from "./runtime-presence-health"; + +const ODIN_CAPABILITY = "odin.verse-rendezvous"; +const MAX_LEASE_WAIT_ROUNDS = 720; + +export type IdunnRuntimePresencePublisher = { + readonly runtimeId: string; + readonly runtimeInstanceId: string; + readonly requiresWriteLease: boolean; + publish(state: RuntimePresenceHealth["state"], detail: string): Promise; + waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; + assertWriteLease(): Promise; +}; + +export type IdunnRuntimePresencePublisherOptions = { + signer: IdunnRuntimeSigner; + endpoint: string; +}; + +/** + * Publishes the signer's presence to Odin over RUDP, for services that are + * CultMesh-aware and declare `odin.verse-rendezvous` in Expected. The route + * proof never passes through here: `signer.answerRouteObservation` answers + * Idunn's challenge locally and needs no Odin. Capability shortfalls are not + * judged here either; the correlation owner records a typed disagreement. + */ +export function createIdunnRuntimePresencePublisher( + options: IdunnRuntimePresencePublisherOptions, +): IdunnRuntimePresencePublisher { + const { signer } = options; + const endpoint = parseRudpEndpoint(options.endpoint); + const odinDependency = signer.authority.expected.dependencies.find((dependency) => dependency.kind === "shared-infrastructure" + && dependency.capability === ODIN_CAPABILITY); + if (!odinDependency || normalizeRudpEndpoint(odinDependency.providerEndpoint ?? "") !== normalizeRudpEndpoint(options.endpoint)) { + throw new Error("Configured Odin endpoint does not match Idunn Expected dependency authority."); + } + const connectionId = 0x0d1d0002; + let messageSequence = 0; + + const publish = async (state: RuntimePresenceHealth["state"], detail: string) => { + const signed = signer.sign(state, detail); + messageSequence += 1; + await publishDocument(endpoint, connectionId, { + schemaVersion: "cultnet.document_put_raw.v0", + messageId: `runtime-presence:${signer.authority.expected.target}:${signer.runtimeInstanceId}:${messageSequence}`, + document: signed.document, + }); + if (state === "warming") signer.recordPublishedWarming(signed.canonicalSha256); + return signed.canonicalSha256; + }; + + return { + runtimeId: signer.runtimeId, + runtimeInstanceId: signer.runtimeInstanceId, + requiresWriteLease: signer.requiresWriteLease, + publish, + async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) { + if (!signer.requiresWriteLease) return ""; + let warmingSequence = 0; + while (!signal?.aborted) { + await publish("warming", "waiting-for-process-write-lease"); + warmingSequence += 1; + try { + return signer.assertWriteLease(); + } catch (error) { + if (warmingSequence > MAX_LEASE_WAIT_ROUNDS) throw new Error("Timed out waiting for Idunn process write lease.", { cause: error }); + } + await abortableDelay(pollIntervalMs, signal); + } + throw signal?.reason ?? new Error("Aborted while waiting for Idunn process write lease."); + }, + async assertWriteLease() { + return signer.assertWriteLease(); + }, + }; +} + +async function publishDocument( + endpoint: { host: string; port: number }, + connectionId: number, + message: Record, +): Promise { + const socket = dgram.createSocket(endpoint.host.includes(":") ? "udp6" : "udp4"); + await new Promise((resolve, reject) => { + socket.once("error", reject); + socket.bind(0, endpoint.host.includes(":") ? "::" : "0.0.0.0", () => { + socket.off("error", reject); + resolve(); + }); + }); + const receiver = receivePackets(socket); + const session = new CultNetRudpSession({ connectionId, initialSequence: 1, resendDelayMs: 100 }); + try { + await sendPacket(socket, endpoint, session.createConnect(Date.now(), new Uint8Array())); + await receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "accept", 5000); + const wirePayload = encode(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0")); + const packets = session.sendMany("schema", wirePayload, { reliable: true, ordered: true, nowMs: Date.now() }); + for (const packet of packets) await sendPacket(socket, endpoint, packet); + await receiveUntil( + receiver, + session, + endpoint, + () => session.outstandingReliablePacketCount === 0, + 2000, + (frame) => { + if (frame.channelId !== "schema") return; + const response = parseCultNetMessage(decode(frame.payload)); + if (response.schemaVersion === "cultnet.error.v0") { + throw new Error(`Odin rejected runtime presence: ${response.error}`); + } + }, + ); + } finally { + receiver.close(); + socket.close(); + } +} + +type PacketReceiver = { + socket: dgram.Socket; + next(timeoutMs: number): Promise; + close(): void; +}; + +function receivePackets(socket: dgram.Socket): PacketReceiver { + const packets: CultNetRudpPacket[] = []; + const waiters: Array<{ resolve: (packet: CultNetRudpPacket) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }> = []; + const errors: Error[] = []; + const drain = () => { + while (waiters.length && (packets.length || errors.length)) { + const waiter = waiters.shift()!; + clearTimeout(waiter.timer); + if (errors.length) waiter.reject(errors.shift()!); + else waiter.resolve(packets.shift()!); + } + }; + const onMessage = (wire: Buffer) => { + try { packets.push(decodeRudpPacket(wire)); } catch (error) { errors.push(error as Error); } + drain(); + }; + const onError = (error: Error) => { errors.push(error); drain(); }; + socket.on("message", onMessage); + socket.on("error", onError); + return { + socket, + next(timeoutMs) { + if (packets.length) return Promise.resolve(packets.shift()!); + if (errors.length) return Promise.reject(errors.shift()!); + return new Promise((resolve, reject) => { + const waiter = { + resolve, + reject, + timer: setTimeout(() => { + const index = waiters.indexOf(waiter); + if (index >= 0) waiters.splice(index, 1); + const error = new Error("Timed out waiting for CultNet RUDP packet.") as NodeJS.ErrnoException; + error.code = "ETIMEDOUT"; + reject(error); + }, Math.max(1, timeoutMs)), + }; + waiters.push(waiter); + }); + }, + close() { + socket.off("message", onMessage); + socket.off("error", onError); + for (const waiter of waiters.splice(0)) { + clearTimeout(waiter.timer); + waiter.reject(new Error("CultNet RUDP publisher closed.")); + } + }, + }; +} + +async function receiveUntil( + receiver: PacketReceiver, + session: CultNetRudpSession, + endpoint: { host: string; port: number }, + predicate: (packet: CultNetRudpPacket) => boolean, + timeoutMs: number, + onDelivered?: (frame: { channelId: string; payload: Uint8Array; sequence: number }) => void, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const packet = await receiver.next(Math.min(100, deadline - Date.now())); + const received = session.receive(packet, Date.now()); + if (received.reply) throw new Error("Runtime presence received an unexpected reply-required packet."); + for (const frame of received.delivered) onDelivered?.(frame); + if (predicate(packet)) return; + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code !== "ETIMEDOUT") throw error; + } + for (const packet of session.dueResends(Date.now())) await sendPacket(receiver.socket, endpoint, packet); + } + throw new Error(`Timed out waiting for CultNet RUDP response after ${timeoutMs} ms.`); +} + +async function sendPacket(socket: dgram.Socket, endpoint: { host: string; port: number }, packet: CultNetRudpPacket): Promise { + const wire = encodeRudpPacket(packet); + await new Promise((resolve, reject) => { + socket.send(wire, endpoint.port, endpoint.host, (error) => error ? reject(error) : resolve()); + }); +} + +function parseRudpEndpoint(value: string): { host: string; port: number } { + const text = value.replace(/^rudp:\/\//i, ""); + const match = text.match(/^\[([^\]]+)\]:(\d+)$/) ?? text.match(/^([^:]+):(\d+)$/); + if (!match) throw new Error(`Invalid Odin RUDP endpoint: ${value}`); + const port = Number(match[2]); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid Odin RUDP port: ${match[2]}`); + return { host: match[1]!, port }; +} + +function normalizeRudpEndpoint(value: string): string { + const normalized = value.trim().toLowerCase().replace(/^rudp:\/\//, ""); + const parsed = parseRudpEndpoint(normalized); + return `${parsed.host.toLowerCase()}:${parsed.port}`; +} + +function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, milliseconds); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason ?? new Error("Aborted.")); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index 5ea30fff..47e132b3 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -15,10 +15,7 @@ import { type RuntimePresenceHealth, } from "./runtime-presence-health"; import { truncateUtf8Bytes } from "./utf8-bound"; -import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord, type CultNetSnapshotRequestMessage } from "./contracts"; -import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; -import type { CultNetRudpPacket } from "./rudp"; -import dgram from "node:dgram"; +import type { CultNetRawDocumentRecord, CultNetSnapshotRequestMessage } from "./contracts"; export const IDUNN_EXPECTED_INCARNATION_SCHEMA = "idunn.expected_incarnation.v2"; export const IDUNN_RUNTIME_ACTIVATION_SCHEMA = "idunn.runtime_activation.v2"; @@ -77,33 +74,50 @@ export type IdunnRuntimeAuthority = { processWriteLeasePath?: string; }; -export type IdunnRuntimePresencePublisher = { +export type SignedRuntimePresence = { + document: CultNetRawDocumentRecord; + canonicalSha256: string; +}; + +/** + * Signs this launch's runtime presence and answers Idunn's route challenge. It + * owns no network: Odin publication, if a service wants it, is a separate + * consumer of `sign`. + */ +export type IdunnRuntimeSigner = { + readonly authority: IdunnRuntimeAuthority; readonly runtimeId: string; readonly runtimeInstanceId: string; readonly requiresWriteLease: boolean; - latestPresenceDocument(): CultNetRawDocumentRecord | null; - publishRouteObservation(request: CultNetSnapshotRequestMessage): Promise; - publish(state: RuntimePresenceHealth["state"], detail: string): Promise; - waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; - assertWriteLease(): Promise; + /** Signs one presence document. Every call takes the next publisher sequence. */ + sign(state: RuntimePresenceHealth["state"], detail: string): SignedRuntimePresence; + /** + * Answers an Idunn route challenge from local authority alone: signs a fresh + * presence in the given state, with no network. The caller supplies the + * app's current health (`warming` until first healthy). + */ + answerRouteObservation(request: CultNetSnapshotRequestMessage, state: RuntimePresenceHealth["state"]): CultNetRawDocumentRecord; + /** Reads Idunn's write lease and checks it names this incarnation and a warming proof this process published. */ + assertWriteLease(): string; + /** Marks a warming presence as accepted by its consumer, making it a valid lease target. */ + recordPublishedWarming(canonicalSha256: string): void; }; -export type IdunnRuntimePresencePublisherOptions = { +export type IdunnRuntimeSignerOptions = { authority: IdunnRuntimeAuthority; - endpoint: string; - healthContract: string; capabilities: RuntimePresenceHealth["capabilities"]; }; /** * Loads the root-provisioned Idunn bundle and parent-only signing descriptors. * The expected record and activation witness are accepted only when their - * exact positional contracts and mutual incarnation binding agree. + * exact positional contracts and mutual incarnation binding agree. Nothing + * here reads Odin: whether a target talks to Odin is decided by the + * publisher a service chooses to create. */ export function loadIdunnRuntimeAuthorityFromEnvironment( target: string, healthContract: string, - odinEndpoint: string, ): IdunnRuntimeAuthority { const bundle = requiredEnvironment(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT); const expected = readAuthorityRecord(path.join(bundle, "expected.cc"), "idunn.expected_incarnation", IDUNN_EXPECTED_INCARNATION_SCHEMA); @@ -113,11 +127,6 @@ export function loadIdunnRuntimeAuthorityFromEnvironment( if (expectedValue.target !== target || expectedValue.healthContract !== healthContract) { throw new Error("Idunn Expected target or health contract does not match this runtime."); } - const odinDependency = expectedValue.dependencies.find((dependency) => dependency.kind === "shared-infrastructure" - && dependency.capability === "odin.verse-rendezvous"); - if (!odinDependency || normalizeRudpEndpoint(odinDependency.providerEndpoint ?? "") !== normalizeRudpEndpoint(odinEndpoint)) { - throw new Error("Configured Odin endpoint does not match Idunn Expected dependency authority."); - } if (activationValue.expectedProjectionSha256 !== expectedValue.canonicalSha256 || activationValue.runtimeId !== expectedValue.runtimeId) { throw new Error("Idunn Activation does not bind this exact Expected incarnation."); @@ -167,6 +176,7 @@ export function loadIdunnRuntimeAuthorityFromEnvironment( return authority; } + /** * Signs the fixed Idunn v2 positional runtime-presence contract with the * provider identity and this launch's Idunn-issued activation key. @@ -205,42 +215,26 @@ export function signIdunnRuntimePresence( }; } -export function createIdunnRuntimePresencePublisher( - options: IdunnRuntimePresencePublisherOptions, -): IdunnRuntimePresencePublisher { - const endpoint = parseRudpEndpoint(options.endpoint); - const expected = options.authority.expected; - if (options.healthContract !== expected.healthContract) throw new Error("Runtime presence contract differs from Expected."); - if (options.authority.boundEndpoint !== expected.route?.candidateEndpoint) throw new Error("Runtime presence bind differs from Expected."); - for (const required of expected.capabilities) { - if (!options.capabilities.some((actual) => actual.capability === required.capability - && actual.schema === required.schema - && actual.compatibility === required.compatibility - && actual.capacity >= required.minimumCapacity)) { - throw new Error(`Runtime does not provide Expected capability ${required.capability}/${required.schema}.`); - } - } - const connectionId = 0x0d1d0002; +export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): IdunnRuntimeSigner { + const { authority } = options; + const expected = authority.expected; let sequence = 0; - let latestLeaseSha256: string | null = null; - let latestPresenceDocument: CultNetRawDocumentRecord | null = null; const recentWarmingProofs: string[] = []; - const assertWriteLease = async () => { + const assertWriteLease = () => { if (!expected.writeLeaseRequired) return ""; - const leasePath = options.authority.processWriteLeasePath; + const leasePath = authority.processWriteLeasePath; if (!leasePath) throw new Error("Idunn process write lease is required but no lease path is configured."); const record = readAuthorityRecord(leasePath, "idunn.process_write_lease", IDUNN_PROCESS_WRITE_LEASE_SCHEMA); const lease = decodeArray(record.payload, 14, "Idunn process write lease"); - assertLeaseMatches(lease, options.authority, recentWarmingProofs); - latestLeaseSha256 = prefixedSha256(Buffer.from(encode(lease))); - return latestLeaseSha256; + assertLeaseMatches(lease, authority, recentWarmingProofs); + return prefixedSha256(Buffer.from(encode(lease))); }; - const publish = async (state: RuntimePresenceHealth["state"], detail: string) => { - const writeLeaseSha256 = state === "warming" || !expected.writeLeaseRequired ? null : await assertWriteLease(); + const sign = (state: RuntimePresenceHealth["state"], detail: string): SignedRuntimePresence => { + const writeLeaseSha256 = state === "warming" || !expected.writeLeaseRequired ? null : assertWriteLease(); sequence += 1; - const signed = signIdunnRuntimePresence(options.authority, { + const signed = signIdunnRuntimePresence(authority, { capabilities: options.capabilities, state, detail: truncateUtf8Bytes(detail, RUNTIME_PRESENCE_DETAIL_MAX_BYTES), @@ -248,44 +242,28 @@ export function createIdunnRuntimePresencePublisher( publisherSequence: sequence, observedAtUnixMillis: Date.now(), }); - const document: CultNetRawDocumentRecord = { - schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, - recordKey: expected.target, - storedAt: new Date().toISOString(), - payloadEncoding: "messagepack", - payload: new Uint8Array(signed.payload), - sourceRuntimeId: expected.runtimeId, - sourceRole: "runtime-presence-health-publisher", - tags: ["cultnet.transport.rudp.v0", "runtime-presence"], - }; - await publishDocument(endpoint, connectionId, { - schemaVersion: "cultnet.document_put_raw.v0", - messageId: `runtime-presence:${expected.target}:${options.authority.activation.runtimeInstanceId}:${sequence}`, - document, - }); - latestPresenceDocument = document; - if (state === "warming") { - recentWarmingProofs.push(signed.canonicalSha256); - if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift(); - } - return signed.canonicalSha256; - }; - - const copyLatestPresenceDocument = (): CultNetRawDocumentRecord | null => { - if (!latestPresenceDocument) return null; return { - ...latestPresenceDocument, - payload: new Uint8Array(latestPresenceDocument.payload), - ...(latestPresenceDocument.tags ? { tags: [...latestPresenceDocument.tags] } : {}), + canonicalSha256: signed.canonicalSha256, + document: { + schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, + recordKey: expected.target, + storedAt: new Date().toISOString(), + payloadEncoding: "messagepack", + payload: new Uint8Array(signed.payload), + sourceRuntimeId: expected.runtimeId, + sourceRole: "runtime-presence-health-publisher", + tags: ["cultnet.transport.rudp.v0", "runtime-presence"], + }, }; }; return { + authority, runtimeId: expected.runtimeId, - runtimeInstanceId: options.authority.activation.runtimeInstanceId, + runtimeInstanceId: authority.activation.runtimeInstanceId, requiresWriteLease: expected.writeLeaseRequired, - latestPresenceDocument: copyLatestPresenceDocument, - async publishRouteObservation(request) { + sign, + answerRouteObservation(request, state) { if (!request.messageId || request.messageId.trim() !== request.messageId) throw new Error("Idunn route observation requires a message id."); if ((request.schemaIds && !request.schemaIds.includes(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA)) || (request.recordKeys && !request.recordKeys.includes(expected.target)) @@ -293,159 +271,16 @@ export function createIdunnRuntimePresencePublisher( || request.shardEpoch !== undefined) { throw new Error("Idunn route observation does not request this runtime presence document."); } - await publish("active", `route-observation:${request.messageId}`); - const document = copyLatestPresenceDocument(); - if (!document) throw new Error("Idunn route observation was published without a presence document."); - return document; - }, - publish, - async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) { - if (!expected.writeLeaseRequired) return ""; - let warmingSequence = 0; - while (!signal?.aborted) { - await publish("warming", "waiting-for-process-write-lease"); - warmingSequence += 1; - try { - return await assertWriteLease(); - } catch (error) { - if (warmingSequence > 720) throw new Error("Timed out waiting for Idunn process write lease.", { cause: error }); - } - await abortableDelay(pollIntervalMs, signal); - } - throw signal?.reason ?? new Error("Aborted while waiting for Idunn process write lease."); + return sign(state, `route-observation:${request.messageId}`).document; }, assertWriteLease, - }; -} - -async function publishDocument( - endpoint: { host: string; port: number }, - connectionId: number, - message: Record, -): Promise { - const socket = dgram.createSocket(endpoint.host.includes(":") ? "udp6" : "udp4"); - await new Promise((resolve, reject) => { - socket.once("error", reject); - socket.bind(0, endpoint.host.includes(":") ? "::" : "0.0.0.0", () => { - socket.off("error", reject); - resolve(); - }); - }); - const receiver = receivePackets(socket); - const session = new CultNetRudpSession({ connectionId, initialSequence: 1, resendDelayMs: 100 }); - try { - await sendPacket(socket, endpoint, session.createConnect(Date.now(), new Uint8Array())); - await receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "accept", 5000); - const wirePayload = encode(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0")); - const packets = session.sendMany("schema", wirePayload, { reliable: true, ordered: true, nowMs: Date.now() }); - for (const packet of packets) await sendPacket(socket, endpoint, packet); - await receiveUntil( - receiver, - session, - endpoint, - () => session.outstandingReliablePacketCount === 0, - 2000, - (frame) => { - if (frame.channelId !== "schema") return; - const response = parseCultNetMessage(decode(frame.payload)); - if (response.schemaVersion === "cultnet.error.v0") { - throw new Error(`Odin rejected runtime presence: ${response.error}`); - } - }, - ); - } finally { - receiver.close(); - socket.close(); - } -} - -type PacketReceiver = { - socket: dgram.Socket; - next(timeoutMs: number): Promise; - close(): void; -}; - -function receivePackets(socket: dgram.Socket): PacketReceiver { - const packets: CultNetRudpPacket[] = []; - const waiters: Array<{ resolve: (packet: CultNetRudpPacket) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }> = []; - const errors: Error[] = []; - const drain = () => { - while (waiters.length && (packets.length || errors.length)) { - const waiter = waiters.shift()!; - clearTimeout(waiter.timer); - if (errors.length) waiter.reject(errors.shift()!); - else waiter.resolve(packets.shift()!); - } - }; - const onMessage = (wire: Buffer) => { - try { packets.push(decodeRudpPacket(wire)); } catch (error) { errors.push(error as Error); } - drain(); - }; - const onError = (error: Error) => { errors.push(error); drain(); }; - socket.on("message", onMessage); - socket.on("error", onError); - return { - socket, - next(timeoutMs) { - if (packets.length) return Promise.resolve(packets.shift()!); - if (errors.length) return Promise.reject(errors.shift()!); - return new Promise((resolve, reject) => { - const waiter = { - resolve, - reject, - timer: setTimeout(() => { - const index = waiters.indexOf(waiter); - if (index >= 0) waiters.splice(index, 1); - const error = new Error("Timed out waiting for CultNet RUDP packet.") as NodeJS.ErrnoException; - error.code = "ETIMEDOUT"; - reject(error); - }, Math.max(1, timeoutMs)), - }; - waiters.push(waiter); - }); - }, - close() { - socket.off("message", onMessage); - socket.off("error", onError); - for (const waiter of waiters.splice(0)) { - clearTimeout(waiter.timer); - waiter.reject(new Error("CultNet RUDP publisher closed.")); - } + recordPublishedWarming(canonicalSha256) { + recentWarmingProofs.push(canonicalSha256); + if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift(); }, }; } -async function receiveUntil( - receiver: PacketReceiver, - session: CultNetRudpSession, - endpoint: { host: string; port: number }, - predicate: (packet: CultNetRudpPacket) => boolean, - timeoutMs: number, - onDelivered?: (frame: { channelId: string; payload: Uint8Array; sequence: number }) => void, -): Promise { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - try { - const packet = await receiver.next(Math.min(100, deadline - Date.now())); - const received = session.receive(packet, Date.now()); - if (received.reply) throw new Error("Runtime presence received an unexpected reply-required packet."); - for (const frame of received.delivered) onDelivered?.(frame); - if (predicate(packet)) return; - } catch (error) { - if ((error as NodeJS.ErrnoException)?.code !== "ETIMEDOUT") throw error; - } - for (const packet of session.dueResends(Date.now())) await sendPacket(receiver.socket, endpoint, packet); - } - throw new Error(`Timed out waiting for CultNet RUDP response after ${timeoutMs} ms.`); -} - -async function sendPacket(socket: dgram.Socket, endpoint: { host: string; port: number }, packet: CultNetRudpPacket): Promise { - const wire = encodeRudpPacket(packet); - await new Promise((resolve, reject) => { - socket.send(wire, endpoint.port, endpoint.host, (error) => error ? reject(error) : resolve()); - }); -} - function readAuthorityRecord(filePath: string, type: string, schemaId: string): { payload: Uint8Array } { const decoded = decode(fs.readFileSync(filePath)); if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { @@ -495,9 +330,7 @@ function decodeExpected(payload: Uint8Array): ExpectedIncarnation { if (!/^sha256-[0-9a-f]{64}$/u.test(hash)) throw new Error(`Expected ${name} hash is malformed.`); } if (!/^[0-9a-f]{40}$/u.test(sourceRevision)) throw new Error("Expected source revision is malformed."); - if (!route || route.transport !== "http" || !route.candidateEndpoint.startsWith("http://")) { - throw new Error("Idunn Expected must include an HTTP candidate route."); - } + if (route) validateRoute(route); return { schemaVersion: string(values[0], "Expected schema"), target, @@ -575,6 +408,24 @@ function decodeExpectedDependencies(value: unknown): ExpectedIncarnation["depend }); } +// The Rust owner (IdunnExpectedRoute::validate) accepts http, tcp and rudp +// routes; a runtime is not entitled to a narrower admission than Idunn's. +const ROUTE_SCHEMES: Record = { + http: { stable: ["http://", "https://"], candidate: ["http://"] }, + tcp: { stable: ["tcp://"], candidate: ["tcp://"] }, + rudp: { stable: ["rudp://"], candidate: ["rudp://"] }, +}; + +function validateRoute(route: NonNullable): void { + const schemes = ROUTE_SCHEMES[route.transport]; + if (!schemes) throw new Error("Idunn Expected route transport is unsupported."); + if (!schemes.stable.some((scheme) => route.stableEndpoint.startsWith(scheme)) + || !schemes.candidate.some((scheme) => route.candidateEndpoint.startsWith(scheme))) { + throw new Error(`Idunn Expected ${route.transport} route endpoints use an unsupported scheme.`); + } + if (route.stableEndpoint === route.candidateEndpoint) throw new Error("Idunn Expected stable and candidate route endpoints are identical."); +} + function decodeRoute(value: unknown): ExpectedIncarnation["route"] { if (value === null) return null; const route = array(value, 4, "Expected route"); @@ -595,7 +446,7 @@ function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { if (enrollmentNonce.length !== 32) throw new Error("Provider-health enrollment nonce has an invalid length."); const publicKey = Buffer.from(providerIdentityByteVector(publicKeyValue, "Provider-health public key")); const protectedSeed = Buffer.from(providerIdentityByteVector(protectedSeedValue, "Provider-health protected seed")); - const machineId = fs.readFileSync("/etc/machine-id", "utf8").trim(); + const machineId = readMachineId(); if (!machineId) throw new Error("Linux machine-id is unavailable for provider-health identity."); const expectedBinding = `${PROVIDER_PROTECTOR_CONTEXT}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`; if (protectorKind !== "linux_file_mode_machine_id_binding" || binding !== expectedBinding || assurance !== "os_installation_file_bound_cloneable_baseline") { @@ -616,6 +467,15 @@ function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { return key; } +// Same sources, same order as the Rust identity protector. +function readMachineId(): string { + try { + return fs.readFileSync("/etc/machine-id", "utf8").trim(); + } catch { + return fs.readFileSync("/var/lib/dbus/machine-id", "utf8").trim(); + } +} + function readProviderHealthIdentityCredential(bytes: Buffer): Uint8Array { const decoded = decode(bytes); if (!Array.isArray(decoded) || decoded.length !== 1) { @@ -693,40 +553,12 @@ function assertLeaseMatches(values: unknown[], authority: IdunnRuntimeAuthority, if (!matches) throw new Error("Idunn process write lease does not match the current Expected incarnation."); } -function parseRudpEndpoint(value: string): { host: string; port: number } { - const text = value.replace(/^rudp:\/\//i, ""); - const match = text.match(/^\[([^\]]+)\]:(\d+)$/) ?? text.match(/^([^:]+):(\d+)$/); - if (!match) throw new Error(`Invalid Odin RUDP endpoint: ${value}`); - const port = Number(match[2]); - if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid Odin RUDP port: ${match[2]}`); - return { host: match[1]!, port }; -} - -function normalizeRudpEndpoint(value: string): string { - const normalized = value.trim().toLowerCase().replace(/^rudp:\/\//, ""); - const parsed = parseRudpEndpoint(normalized); - return `${parsed.host.toLowerCase()}:${parsed.port}`; -} - function requiredEnvironment(name: string): string { const value = process.env[name]?.trim(); if (!value) throw new Error(`${name} is required for Idunn runtime presence.`); return value; } -function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise { - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, milliseconds); - const onAbort = () => { - clearTimeout(timer); - reject(signal?.reason ?? new Error("Aborted.")); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} function array(value: unknown, length: number, label: string): unknown[] { if (!Array.isArray(value) || value.length !== length) throw new Error(`${label} is not a ${length}-field positional contract.`); diff --git a/packages/cultnet-ts/src/index.ts b/packages/cultnet-ts/src/index.ts index 3db890ef..8950f638 100644 --- a/packages/cultnet-ts/src/index.ts +++ b/packages/cultnet-ts/src/index.ts @@ -205,9 +205,15 @@ export { IDUNN_RUNTIME_BUNDLE_ENVIRONMENT, IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, IDUNN_RUNTIME_ACTIVATION_SCHEMA, - createIdunnRuntimePresencePublisher, + createIdunnRuntimeSigner, loadIdunnRuntimeAuthorityFromEnvironment, type IdunnRuntimeAuthority, + type IdunnRuntimeSigner, + type IdunnRuntimeSignerOptions, + type SignedRuntimePresence, +} from "./idunn-runtime-authority"; +export { + createIdunnRuntimePresencePublisher, type IdunnRuntimePresencePublisher, type IdunnRuntimePresencePublisherOptions, -} from "./idunn-runtime-authority"; +} from "./idunn-odin-presence-publisher"; diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 7969fde2..1639b9aa 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -1,30 +1,92 @@ -import { mock, test } from "node:test"; +import { test, type TestContext } from "node:test"; import assert from "node:assert/strict"; -import crypto from "node:crypto"; import dgram from "node:dgram"; import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { decode, encode } from "@msgpack/msgpack"; import { createIdunnRuntimePresencePublisher, + createIdunnRuntimeSigner, loadIdunnRuntimeAuthorityFromEnvironment, - signIdunnRuntimePresence, - systemdListenPidMatches, -} from "../src/idunn-runtime-authority"; + type IdunnRuntimeAuthority, +} from "../src"; +import { systemdListenPidMatches } from "../src/idunn-runtime-authority"; +import type { CultNetSnapshotRequestMessage } from "../src/contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "../src/rudp"; -import { - runtimePresenceActivationSigningMessage, - runtimePresenceProofPayload, - runtimePresenceProviderSigningMessage, - RUNTIME_PRESENCE_SLOT, -} from "../src/runtime-presence-health"; +import { RUNTIME_PRESENCE_SLOT } from "../src/runtime-presence-health"; -const providerIdentityContext = "gamecult-provider-health-identity-v1"; -const providerIdDomain = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8"); -const activationIdDomain = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8"); +// Every input below was written by the Rust owner; see fixtures/idunn-runtime/README.md. +// The only values this file pins are the ones the generator also pins. +const FIXTURES = path.join(__dirname, "..", "..", "test", "fixtures", "idunn-runtime"); +const OBSERVED_AT = 1_790_000_000_000; +const CHALLENGE: CultNetSnapshotRequestMessage = { + schemaVersion: "cultnet.snapshot_request.v0", + messageId: "route-challenge-1", +}; + +type FixtureSet = "web" | "service" | "rudp-route"; + +function fixtureFile(set: FixtureSet, name: string): Buffer { + return fs.readFileSync(path.join(FIXTURES, set, name)); +} + +/** The Expected fields the tests need, read from the Rust-written file rather than re-spelled. */ +function expectedFacts(set: FixtureSet) { + const store = decode(fixtureFile(set, "expected.cc")) as unknown[][][]; + const values = decode(store[2]![0]![3] as Uint8Array) as unknown[]; + const route = values[15] as string[]; + const capabilities = (values[16] as Array<[string, string, string, number]>).map(([capability, schema, compatibility, minimum]) => ({ + capability, schema, compatibility, capacity: minimum, + })); + const dependencies = values[17] as unknown[][]; + return { + target: values[1] as string, + healthContract: values[10] as string, + candidate: route[3]!, + capabilities, + odinEndpoint: dependencies.map((dependency) => dependency[9] as string)[0], + }; +} + +/** Points the process at one Rust-written bundle and its inherited descriptors, as Idunn's systemd unit would. */ +function openAuthority(context: TestContext, set: FixtureSet, options: { machineId?: "etc" | "dbus" } = {}): IdunnRuntimeAuthority { + const facts = expectedFacts(set); + const originalEnvironment = { ...process.env }; + context.after(() => { + for (const key of Object.keys(process.env)) if (!(key in originalEnvironment)) delete process.env[key]; + Object.assign(process.env, originalEnvironment); + }); + process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = path.join(FIXTURES, set); + process.env.GAMECULT_IDUNN_CANDIDATE_BIND = facts.candidate; + delete process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE; + process.env.LISTEN_PID = String(process.pid); + process.env.LISTEN_FDS = "2"; + process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; + const machineId = fs.readFileSync(path.join(FIXTURES, "machine-id"), "utf8"); + const realReadFileSync = fs.readFileSync.bind(fs); + context.mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { + if (filePath === 3) return fixtureFile(set, "activation-key.seed"); + if (filePath === 4) return fixtureFile(set, "provider-identity.credential"); + if (filePath === "/etc/machine-id") { + if (options.machineId === "dbus") throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }); + return machineId; + } + if (filePath === "/var/lib/dbus/machine-id") return machineId; + return realReadFileSync(filePath as never, ...args as never[]); + }); + return loadIdunnRuntimeAuthorityFromEnvironment(facts.target, facts.healthContract); +} + +function signerFor(context: TestContext, set: FixtureSet, capacityDelta = 0) { + const authority = openAuthority(context, set); + const capabilities = expectedFacts(set).capabilities.map((capability) => ({ ...capability, capacity: capability.capacity + capacityDelta })); + return createIdunnRuntimeSigner({ authority, capabilities }); +} + +function freezeClock(context: TestContext): void { + context.mock.method(Date, "now", () => OBSERVED_AT); +} test("matches systemd's host PID for the private PID namespace init only", () => { assert.equal(systemdListenPidMatches(String(process.pid), process.pid), true); @@ -34,216 +96,160 @@ test("matches systemd's host PID for the private PID namespace init only", () => assert.equal(systemdListenPidMatches(undefined, 1), false); }); -test("opens Idunn identity and publishes valid CultNet data while surfacing piggybacked application errors", async (context) => { - const directory = mkdtempSync(path.join(os.tmpdir(), "cultnet-runtime-authority-")); - context.after(() => rmSync(directory, { recursive: true, force: true })); +for (const set of ["web", "service", "rudp-route"] as const) { + test(`opens the Rust-written ${set} bundle with no Odin endpoint, whatever route transport Rust admits`, (context) => { + const authority = openAuthority(context, set); + assert.equal(authority.expected.target, expectedFacts(set).target); + assert.equal(authority.boundEndpoint, expectedFacts(set).candidate); + }); +} - const machineId = "1234567890abcdef1234567890abcdef"; - const providerSeed = Buffer.alloc(32, 0x31); - const activationSeed = Buffer.alloc(32, 0x72); - const providerKey = privateKeyFromSeed(providerSeed); - const activationKey = privateKeyFromSeed(activationSeed); - const providerPublic = rawPublic(crypto.createPublicKey(providerKey)); - const activationPublic = rawPublic(crypto.createPublicKey(activationKey)); - const providerIdentity = sha256Hex(Buffer.concat([providerIdDomain, providerPublic])); - const activationIdentity = sha256Hex(Buffer.concat([activationIdDomain, activationPublic])); - const target = "streampixels-service"; - const contract = "streampixels-service.cultnet-rudp-service-health"; - const candidate = "http://127.0.0.1:18831"; - const expectedValues = [ - "idunn.expected_incarnation.v2", target, `sha256-${"1".repeat(64)}`, "incarnation-1", - `sha256-${"2".repeat(64)}`, "https://github.com/GameCult/StreamPixels.git", "a".repeat(40), - `sha256-${"3".repeat(64)}`, "streampixels-service-yggdrasil", providerIdentity, contract, - `sha256-${"4".repeat(64)}`, "service-boundary-v1", `sha256-${"5".repeat(64)}`, false, - ["streampixels-service-http", "http", "http://127.0.0.1:8831", candidate], - [["streampixels.service.api", "streampixels.api.v1", "v1", 1]], - [["shared-infrastructure", "odin.verse-rendezvous", "odin.verse-topology.v1", "v1", 1, "before-promotion", null, null, null, "rudp://127.0.0.1:17871"]], +test("a target that declares no Odin dependency opens and answers Idunn's challenge without one", (context) => { + assert.equal(expectedFacts("web").odinEndpoint, undefined); + const signer = signerFor(context, "web"); + assert.ok(signer.answerRouteObservation(CHALLENGE, "warming").payload.byteLength > 0); +}); + +test("finds the machine-id at the dbus path when /etc/machine-id is absent, as the Rust protector does", (context) => { + assert.ok(openAuthority(context, "web", { machineId: "dbus" })); +}); + +test("rejects a credential file holding more than one envelope", (context) => { + openAuthority(context, "web"); + const credential = decode(fixtureFile("web", "provider-identity.credential")) as unknown[][]; + const doubled = Buffer.from(encode([...credential, ...credential])); + const realReadFileSync = fs.readFileSync; + context.mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => + filePath === 4 ? doubled : (realReadFileSync as (...all: unknown[]) => unknown)(filePath, ...args)); + assert.throws( + () => loadIdunnRuntimeAuthorityFromEnvironment(expectedFacts("web").target, expectedFacts("web").healthContract), + /exactly one envelope/, + ); +}); + +test("answers a route challenge byte for byte as the Rust-verified vectors, in the state the app reports", (context) => { + freezeClock(context); + const signer = signerFor(context, "web"); + const warming = signer.answerRouteObservation(CHALLENGE, "warming"); + assert.deepEqual(Buffer.from(warming.payload), fixtureFile("web", "presence-warming.bin")); + assert.equal((decode(warming.payload) as unknown[])[RUNTIME_PRESENCE_SLOT.state], "warming"); + const second = signer.answerRouteObservation(CHALLENGE, "active"); + assert.equal((decode(second.payload) as unknown[])[RUNTIME_PRESENCE_SLOT.publisherSequence], 2); + // Sequence 2 cannot match a vector written at sequence 1; sign the same fields from a fresh signer. + const fresh = signerFor(context, "web"); + assert.deepEqual(Buffer.from(fresh.answerRouteObservation(CHALLENGE, "active").payload), fixtureFile("web", "presence-active.bin")); +}); + +test("a service with an Odin dependency signs the Rust-verified vectors, including a shortfall Rust correlates to a capacity disagreement", (context) => { + freezeClock(context); + assert.deepEqual( + Buffer.from(signerFor(context, "service").answerRouteObservation(CHALLENGE, "active").payload), + fixtureFile("service", "presence-active.bin"), + ); + assert.deepEqual( + Buffer.from(signerFor(context, "service", -1).answerRouteObservation(CHALLENGE, "active").payload), + fixtureFile("service", "presence-active-below-minimum.bin"), + ); +}); + +test("answers locally: synchronously, with no socket opened", (context) => { + const sockets = context.mock.method(dgram, "createSocket"); + const signer = signerFor(context, "web"); + const answer = signer.answerRouteObservation(CHALLENGE, "warming"); + assert.equal(typeof (answer as unknown as { then?: unknown }).then, "undefined"); + assert.equal(sockets.mock.callCount(), 0); +}); + +test("refuses a challenge that does not ask for this runtime's presence", (context) => { + const signer = signerFor(context, "web"); + const cases: CultNetSnapshotRequestMessage[] = [ + { ...CHALLENGE, messageId: "" }, + { ...CHALLENGE, messageId: " padded" }, + { ...CHALLENGE, recordKeys: ["another-target"] }, + { ...CHALLENGE, schemaIds: ["another.schema"] }, + { ...CHALLENGE, shardId: "shard-1" }, ]; - const expectedBytes = Buffer.from(encode(expectedValues)); - const expectedSha = `sha256-${sha256Hex(expectedBytes)}`; - const activationValues = [ - "idunn.runtime_activation.v2", expectedSha, "streampixels-service-yggdrasil", - `sha256-${"6".repeat(64)}`, activationIdentity, activationPublic, Date.now(), - "7".repeat(64), "ed25519", new Uint8Array(64).fill(0x17), - ]; - const bundle = path.join(directory, "bundle"); - fs.mkdirSync(bundle); - writeFileSync(path.join(bundle, "expected.cc"), cultCacheStore( - "idunn.expected_incarnation", "idunn.expected_incarnation.v2", "expected", expectedBytes, - )); - writeFileSync(path.join(bundle, "activation.cc"), cultCacheStore( - "idunn.runtime_activation", "idunn.runtime_activation.v2", "activation", Buffer.from(encode(activationValues)), - )); - - const binding = `${providerIdentityContext}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`; - const mask = crypto.createHash("sha256").update(Buffer.concat([ - Buffer.from("gamecult-linux-service-seed-v1\0", "utf8"), - Buffer.from(providerIdentityContext, "utf8"), - Buffer.from(binding, "utf8"), - ])).digest(); - const protectedSeed = Buffer.from(providerSeed.map((value, index) => value ^ mask[index]!)); - const providerCredential = Buffer.from(encode([[ - "gamecult-provider-health-identity", - "gamecult.provider_health_identity.private.v1", - Buffer.from(encode([ - "gamecult.provider_health_identity.private.v1", providerIdentity, Array.from(providerPublic), Array.from(protectedSeed), - "linux_file_mode_machine_id_binding", binding, "v1", "os_installation_file_bound_cloneable_baseline", - "2026-01-01T00:00:00Z", Array(32).fill(0x2a), - ])), - "2026-01-01T00:00:00Z", - "gamecult.provider_health_identity.private.v1", - ]])); - let descriptorProviderCredential = providerCredential; - - const originalEnvironment = { ...process.env }; - context.after(() => { - for (const key of Object.keys(process.env)) if (!(key in originalEnvironment)) delete process.env[key]; - Object.assign(process.env, originalEnvironment); - }); - process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; - process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; - delete process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE; - process.env.LISTEN_PID = String(process.pid); - process.env.LISTEN_FDS = "2"; - process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; - const realReadFileSync = fs.readFileSync.bind(fs); - mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { - if (filePath === 3) return activationSeed; - if (filePath === 4) return descriptorProviderCredential; - if (filePath === "/etc/machine-id") return machineId; - return realReadFileSync(filePath as never, ...args as never[]); - }); - - const authority = loadIdunnRuntimeAuthorityFromEnvironment(target, contract, "127.0.0.1:17871"); - const signed = signIdunnRuntimePresence(authority, { - capabilities: [{ capability: "streampixels.service.api", schema: "streampixels.api.v1", compatibility: "v1", capacity: 1 }], - state: "warming", - detail: "starting", - writeLeaseSha256: null, - publisherSequence: 1, - observedAtUnixMillis: Date.now(), - }); - const proof = runtimePresenceProofPayload(signed.presence); - assert.equal((decode(expectedBytes) as unknown[]).length, 18); - assert.equal(signed.presence.expectedProjectionSha256, expectedSha); - const signedRecord = decode(signed.payload) as unknown[]; - assert.equal(crypto.verify(null, runtimePresenceProviderSigningMessage(proof), crypto.createPublicKey(providerKey), Buffer.from(signedRecord[21] as Uint8Array)), true); - assert.equal(crypto.verify(null, runtimePresenceActivationSigningMessage(proof), crypto.createPublicKey(activationKey), Buffer.from(signedRecord[23] as Uint8Array)), true); + for (const request of cases) assert.throws(() => signer.answerRouteObservation(request, "active"), /route observation/); +}); +async function startOdinPeer(context: TestContext, endpoint: string) { const peer = dgram.createSocket("udp4"); + const port = Number(endpoint.slice(endpoint.lastIndexOf(":") + 1)); await new Promise((resolve, reject) => { peer.once("error", reject); - peer.bind(0, "127.0.0.1", resolve); + peer.bind(port, "127.0.0.1", resolve); }); context.after(() => peer.close()); - const address = peer.address(); - assert.equal(typeof address, "object"); - const peerPort = (address as { port: number }).port; + const state = { + reject: false, + received: [] as Array<{ schemaVersion?: string; document: { payload: Uint8Array } }>, + responseAck: undefined as number | undefined, + failure: undefined as Error | undefined, + }; let serverSession: CultNetRudpSession | undefined; - let receivedMessage: unknown; - let responseAck: number | undefined; - let peerFailure: Error | undefined; - let rejectOdinAdmission = true; peer.on("message", (wire, remote) => { try { const packet = decodeRudpPacket(wire); if (packet.packetType === "connect") { serverSession = new CultNetRudpSession({ connectionId: packet.connectionId, initialSequence: 100 }); - const accept = serverSession.acceptConnect(packet, Date.now()); - peer.send(encodeRudpPacket(accept), remote.port, remote.address); + peer.send(encodeRudpPacket(serverSession.acceptConnect(packet, Date.now())), remote.port, remote.address); return; } if (!serverSession) throw new Error("Publisher sent data before establishing RUDP."); - const result = serverSession.receive(packet, Date.now()); - const frame = result.delivered.find((candidate) => candidate.channelId === "schema"); + const frame = serverSession.receive(packet, Date.now()).delivered.find((candidate) => candidate.channelId === "schema"); if (!frame) return; - receivedMessage = decode(frame.payload); - const responsePayload = encode(rejectOdinAdmission ? { - schemaVersion: "cultnet.error.v0", - error: "test admission denied", - routingHint: null, - code: null, - details: null, - } : { - schemaVersion: "cultnet.snapshot_response.v0", - messageId: "ack", - documents: [], - }); - const [response] = serverSession.sendMany("schema", responsePayload, { + state.received.push(decode(frame.payload) as never); + const [response] = serverSession.sendMany("schema", encode(state.reject + ? { schemaVersion: "cultnet.error.v0", error: "test admission denied", routingHint: null, code: null, details: null } + : { schemaVersion: "cultnet.snapshot_response.v0", messageId: "ack", documents: [] }), { reliable: true, ordered: true, nowMs: Date.now(), }); assert.ok(response); - responseAck = response.ack; + state.responseAck = response.ack; peer.send(encodeRudpPacket(response), remote.port, remote.address); } catch (error) { - peerFailure = error as Error; + state.failure = error as Error; } }); - const publisher = createIdunnRuntimePresencePublisher({ - authority, - endpoint: `rudp://127.0.0.1:${peerPort}`, - healthContract: contract, - capabilities: [{ capability: "streampixels.service.api", schema: "streampixels.api.v1", compatibility: "v1", capacity: 1 }], - }); - await assert.rejects(publisher.publish("warming", "local RUDP integration"), /Odin rejected runtime presence: test admission denied/); - assert.deepEqual(receivedMessage && (receivedMessage as { schemaVersion?: string }).schemaVersion, "cultnet.document_put_raw.v0"); - assert.ok(Buffer.from(encode(receivedMessage)).byteLength > 0); - assert.equal(responseAck, 2, "the response data packet must acknowledge the publisher's reliable schema packet"); - assert.equal(peerFailure, undefined, peerFailure?.message); - assert.equal(publisher.latestPresenceDocument(), null, "a rejected publication must not become the snapshot source"); + return state; +} + +test("the Odin publisher publishes the signer's document to the endpoint Expected names and surfaces Odin's rejection", async (context) => { + const endpoint = expectedFacts("service").odinEndpoint!; + const peer = await startOdinPeer(context, endpoint); + const signer = signerFor(context, "service"); + const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint }); - rejectOdinAdmission = false; await publisher.publish("warming", "accepted presence"); - const snapshotDocument = await publisher.publishRouteObservation({ - schemaVersion: "cultnet.snapshot_request.v0", - messageId: "route-challenge-1", - schemaIds: ["gamecult.runtime_presence_health.v2"], - recordKeys: [target], - }); - const publishedDocument = (receivedMessage as { document: { payload: Uint8Array; schemaId: string; recordKey: string } }).document; - assert.ok(snapshotDocument); - assert.equal(snapshotDocument.schemaId, publishedDocument.schemaId); - assert.equal(snapshotDocument.recordKey, publishedDocument.recordKey); - assert.deepEqual(Buffer.from(snapshotDocument.payload), Buffer.from(publishedDocument.payload)); - const routePresence = decode(snapshotDocument.payload) as unknown[]; - assert.equal(routePresence[RUNTIME_PRESENCE_SLOT.state], "active"); - assert.equal(routePresence[RUNTIME_PRESENCE_SLOT.detail], "route-observation:route-challenge-1"); - snapshotDocument.payload[0] = snapshotDocument.payload[0]! ^ 0xff; - assert.deepEqual(Buffer.from(publisher.latestPresenceDocument()?.payload ?? []), Buffer.from(publishedDocument.payload), "snapshot readers cannot mutate publisher state"); + assert.equal(peer.received[0]?.schemaVersion, "cultnet.document_put_raw.v0"); + const published = decode(peer.received[0]!.document.payload) as unknown[]; + assert.equal(published[RUNTIME_PRESENCE_SLOT.state], "warming"); + assert.equal(published[RUNTIME_PRESENCE_SLOT.publisherSequence], 1); + assert.equal(peer.responseAck, 2, "the response data packet must acknowledge the publisher's reliable schema packet"); - descriptorProviderCredential = Buffer.from(encode([ - ...(decode(providerCredential) as unknown[][]), - ...(decode(providerCredential) as unknown[][]), - ])); - assert.throws( - () => loadIdunnRuntimeAuthorityFromEnvironment(target, contract, "127.0.0.1:17871"), - /exactly one envelope/, - ); + peer.reject = true; + await assert.rejects(publisher.publish("active", "denied presence"), /Odin rejected runtime presence: test admission denied/); + assert.equal(peer.failure, undefined, peer.failure?.message); }); -function cultCacheStore(type: string, schemaId: string, key: string, payload: Uint8Array): Buffer { - return Buffer.from(encode([ - "cultcache.store.v1", - [[schemaId, type, `${schemaId}.v1`, schemaId, "{}", [schemaId], []]], - [[key, schemaId, "2026-01-01T00:00:00Z", payload]], - ])); -} +test("the Odin publisher leaves a capability shortfall to the Rust correlation instead of refusing to publish", async (context) => { + const endpoint = expectedFacts("service").odinEndpoint!; + const peer = await startOdinPeer(context, endpoint); + const publisher = createIdunnRuntimePresencePublisher({ signer: signerFor(context, "service", -1), endpoint }); + await publisher.publish("active", "below minimum"); + const capabilities = (decode(peer.received[0]!.document.payload) as unknown[])[RUNTIME_PRESENCE_SLOT.capabilities] as unknown[][]; + assert.equal(capabilities[0]![3], expectedFacts("service").capabilities[0]!.capacity - 1); +}); -function privateKeyFromSeed(seed: Uint8Array): crypto.KeyObject { - return crypto.createPrivateKey({ - key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), Buffer.from(seed)]), - format: "der", - type: "pkcs8", - }); -} - -function rawPublic(key: crypto.KeyObject): Buffer { - const der = key.export({ type: "spki", format: "der" }) as Buffer; - return Buffer.from(der.subarray(der.length - 32)); -} - -function sha256Hex(bytes: Uint8Array): string { - return crypto.createHash("sha256").update(bytes).digest("hex"); -} +test("the Odin publisher takes only the endpoint Expected names", (context) => { + assert.throws( + () => createIdunnRuntimePresencePublisher({ signer: signerFor(context, "service"), endpoint: "rudp://127.0.0.1:1" }), + /does not match Idunn Expected dependency authority/, + ); + assert.throws( + () => createIdunnRuntimePresencePublisher({ signer: signerFor(context, "web"), endpoint: expectedFacts("service").odinEndpoint! }), + /does not match Idunn Expected dependency authority/, + ); +}); From 16432d4b1ec8af338b375b896207d08da4a4fdbc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:12:43 +0200 Subject: [PATCH 30/64] Fix the BP-1 findings in the cultnet-rs content plane A hostile manifest of empty chunks no longer becomes a request flood: fetch_content refuses a zero-size chunk beside other chunks, and settles the content hash and every chunk hash (normalised, non-empty) before the first request. Every bad chunk request is now answered found:false in the reference handler's validation order, never refused at decode. validate_message no longer refuses content chunk requests or responses, so a blank message id or hash, a prefix-only hash and a negative size reach answer_content_chunk_request. The answer follows the reference's double normalisation (handler, then CreateRecordKey), which fixes the prefix-only hash spelling to ArgumentException on 'chunkHash'. The cs vectors gain nine reference-server answers (blank and whitespace id, blank, whitespace and prefix-only hash, negative size, record-key case, blank record key, double prefix) and a metadata-order manifest; Rust answers all of them byte-identically. Manifest metadata is Vec<(String, String)> in wire order and refuses a duplicate key, replacing the BTreeMap that re-sorted keys. Tests pin the surviving mutants: unusable chunk sizes, the payload-length and claimed-size halves of the chunk check, stable sort at equal offsets, the normalised hash and canonical key actually sent, and the kind/mime defaults never trimming. Co-Authored-By: Claude Sonnet 5 --- .../cultmesh/content-vectors.cs-written.json | 95 ++++++ .../cultmesh/content-vectors.rs-written.json | 95 ++++++ packages/cultnet-rs/src/content.rs | 87 +++++- packages/cultnet-rs/src/contracts.rs | 38 +-- packages/cultnet-rs/tests/content.rs | 293 ++++++++++++++++-- .../CultMeshContentVectorTests.cs | 13 + 6 files changed, 551 insertions(+), 70 deletions(-) diff --git a/contracts/cultmesh/content-vectors.cs-written.json b/contracts/cultmesh/content-vectors.cs-written.json index 30a139ed..a0ae2fe2 100644 --- a/contracts/cultmesh/content-vectors.cs-written.json +++ b/contracts/cultmesh/content-vectors.cs-written.json @@ -40,6 +40,96 @@ "kind": "response", "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKt2ZWN0b3Itc2l6ZaVmb3VuZMKpY2h1bmtIYXNo2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2WBJbnZhbGlkRGF0YUV4Y2VwdGlvbjogQ0ROIGFydGlmYWN0IGNodW5rIHBheWxvYWQgbWV0YWRhdGEgZG9lcyBub3QgbWF0Y2ggaXRzIG1hbmlmZXN0IHJlZmVyZW5jZS4=" }, + { + "label": "answer_blank_message_id.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkoKljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9tZXNoOmNkbjpjaHVuazo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjsWV4cGVjdGVkU2l6ZUJ5dGVzzRLf" + }, + { + "label": "answer_blank_message_id.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKClZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlISW52YWxpZERhdGFFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgcmVxdWVzdCByZXF1aXJlcyBhIG1lc3NhZ2UgaWRlbnRpdHku" + }, + { + "label": "answer_whitespace_message_id.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkoyAgIKljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9tZXNoOmNkbjpjaHVuazo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjsWV4cGVjdGVkU2l6ZUJ5dGVzzRLf" + }, + { + "label": "answer_whitespace_message_id.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKMgICClZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlISW52YWxpZERhdGFFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgcmVxdWVzdCByZXF1aXJlcyBhIG1lc3NhZ2UgaWRlbnRpdHku" + }, + { + "label": "answer_blank_hash.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlksXZlY3Rvci1ibGFuay1oYXNoqWNodW5rSGFzaKCpcmVjb3JkS2V5oLFleHBlY3RlZFNpemVCeXRlc2Q=" + }, + { + "label": "answer_blank_hash.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZLF2ZWN0b3ItYmxhbmstaGFzaKVmb3VuZMKpY2h1bmtIYXNooKlzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlCQXJndW1lbnRFeGNlcHRpb246IEhhc2ggbXVzdCBiZSBub24tZW1wdHkuIChQYXJhbWV0ZXIgJ0NodW5rSGFzaCcp" + }, + { + "label": "answer_whitespace_hash.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlksXZlY3Rvci1zcGFjZS1oYXNoqWNodW5rSGFzaKMgICCpcmVjb3JkS2V5oLFleHBlY3RlZFNpemVCeXRlc2Q=" + }, + { + "label": "answer_whitespace_hash.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZLF2ZWN0b3Itc3BhY2UtaGFzaKVmb3VuZMKpY2h1bmtIYXNooyAgIKlzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlCQXJndW1lbnRFeGNlcHRpb246IEhhc2ggbXVzdCBiZSBub24tZW1wdHkuIChQYXJhbWV0ZXIgJ0NodW5rSGFzaCcp" + }, + { + "label": "answer_prefix_only_hash.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlksnZlY3Rvci1wcmVmaXgtaGFzaKljaHVua0hhc2iqc2hhMjU2OiAgIKlyZWNvcmRLZXmgsWV4cGVjdGVkU2l6ZUJ5dGVzZA==" + }, + { + "label": "answer_prefix_only_hash.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZLJ2ZWN0b3ItcHJlZml4LWhhc2ilZm91bmTCqWNodW5rSGFzaKpzaGEyNTY6ICAgqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2UJBcmd1bWVudEV4Y2VwdGlvbjogSGFzaCBtdXN0IGJlIG5vbi1lbXB0eS4gKFBhcmFtZXRlciAnY2h1bmtIYXNoJyk=" + }, + { + "label": "answer_negative_size.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkr3ZlY3Rvci1uZWdhdGl2ZaljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9tZXNoOmNkbjpjaHVuazo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjsWV4cGVjdGVkU2l6ZUJ5dGVz/w==" + }, + { + "label": "answer_negative_size.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK92ZWN0b3ItbmVnYXRpdmWlZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlgSW52YWxpZERhdGFFeGNlcHRpb246IENETiBhcnRpZmFjdCBjaHVuayBwYXlsb2FkIG1ldGFkYXRhIGRvZXMgbm90IG1hdGNoIGl0cyBtYW5pZmVzdCByZWZlcmVuY2Uu" + }, + { + "label": "answer_record_key_case.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkr3ZlY3Rvci1rZXktY2FzZaljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9NRVNIOkNETjpDSFVOSzo1OTkzQUM2MDQwN0U4NjYwMTg3M0JDMzhFRTZGOERCM0VBOTEyRTk4NzYxQ0I1NThBQjk3OTVEQjMwNkI0NzRDsWV4cGVjdGVkU2l6ZUJ5dGVzzRLf" + }, + { + "label": "answer_record_key_case.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK92ZWN0b3Ita2V5LWNhc2WlZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlPSW52YWxpZERhdGFFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgcmVjb3JkIGtleSBkaXNhZ3JlZXMgd2l0aCBpdHMgY29udGVudCBoYXNoLg==" + }, + { + "label": "answer_blank_record_key.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlksHZlY3Rvci1rZXktYmxhbmupY2h1bmtIYXNo2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXJlY29yZEtleaMgICCxZXhwZWN0ZWRTaXplQnl0ZXPNEt8=" + }, + { + "label": "answer_blank_record_key.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWF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OEhYaHiImKi4yNjo\u002BQkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3\u002BDh4uPk5ebn6Onq6\u002Bzt7u/w8fLz9PX29/j5\u002BgABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp\u002BgoaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2\u002Bv8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4\u002BTl5ufo6err7O3u7/Dx8vP09fb3\u002BPn6AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7pWVycm9yoA==" + }, + { + "label": "answer_double_prefix.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkrXZlY3Rvci1kb3VibGWpY2h1bmtIYXNo2U5zaGEyNTY6c2hhMjU2OjU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V5oLFleHBlY3RlZFNpemVCeXRlc80S3w==" + }, + { + "label": "answer_double_prefix.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK12ZWN0b3ItZG91YmxlpWZvdW5k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3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5\u002Bjp6uvs7e7v8PHy8/T19vf4\u002BfoAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1\u002Bf4CBgoOEhYaHiImKi4yNjo\u002BQkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3\u002BDh4uPk5ebn6Onq6\u002Bzt7u/w8fLz9PX29/j5\u002BgABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6O6VlcnJvcqA=" + }, { "label": "response_hash_last_digit", "kind": "response", @@ -55,6 +145,11 @@ "kind": "manifest", "messagePackBase64": "mrVldXJla2EvY29udGVudC12ZWN0b3KlYXNzZXShMdlAZjRhZTJhN2M5NWY0ZDk2NjA1OGY3NWMxMzE4NWFhMGFiNmE5MWZjNWFmYWQ4ODYyOTZlZjJhZWU3NTVhMmFmMc4AFBLfvGFwcGxpY2F0aW9uL3gtY3VsdG5ldC12ZWN0b3LZITIwMjYtMDktMjJUMDA6MDA6MDAuMDAwMDAwMCswMDowMJaU2UBhYTE0NDRiZTRiNjQwOThmNWRkODYzYjViMGFjNTYxNDgwYjNmYjVjNDFmYzA3Y2Y1MGE2MmVkYzk0MTI0YmNjzgAMAADOAAQAANlPbWVzaDpjZG46Y2h1bms6YWExNDQ0YmU0YjY0MDk4ZjVkZDg2M2I1YjBhYzU2MTQ4MGIzZmI1YzQxZmMwN2NmNTBhNjJlZGM5NDEyNGJjY5TZQDMxYTFmOWRlYTAxNjk1NTEwOTJkMDVlOGJmNGE0NDYy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zYjViMGFjNTYxNDgwYjNmYjVjNDFmYzA3Y2Y1MGE2MmVkYzk0MTI0YmNjlNlAMjgzMTcxNTg1OWYwMWYzZjk2M2RkMGYxMTk0ZGJkYmI3NjA5OTk3NDIzMDE1ZDMxZjYwNzkxMWUxYmY4NjQwMs4AEAAAzgAEAADZT21lc2g6Y2RuOmNodW5rOjI4MzE3MTU4NTlmMDFmM2Y5NjNkZDBmMTE5NGRiZGJiNzYwOTk5NzQyMzAxNWQzMWY2MDc5MTFlMWJmODY0MDKU2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjzgAUAADNEt/ZT21lc2g6Y2RuOmNodW5rOjU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOQg6R6ZXRhoTGlYWxwaGGhMqNtaWShMw==" + }, { "label": "manifest_empty_body", "kind": "manifest", diff --git a/contracts/cultmesh/content-vectors.rs-written.json b/contracts/cultmesh/content-vectors.rs-written.json index c4b58833..38538e2b 100644 --- a/contracts/cultmesh/content-vectors.rs-written.json +++ b/contracts/cultmesh/content-vectors.rs-written.json @@ -40,6 +40,96 @@ "kind": "response", "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKt2ZWN0b3Itc2l6ZaVmb3VuZMKpY2h1bmtIYXNo2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2WBJbnZhbGlkRGF0YUV4Y2VwdGlvbjogQ0ROIGFydGlmYWN0IGNodW5rIHBheWxvYWQgbWV0YWRhdGEgZG9lcyBub3QgbWF0Y2ggaXRzIG1hbmlmZXN0IHJlZmVyZW5jZS4=" }, + { + "label": "answer_blank_message_id.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkoKljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9tZXNoOmNkbjpjaHVuazo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjsWV4cGVjdGVkU2l6ZUJ5dGVzzRLf" + }, + { + "label": "answer_blank_message_id.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKClZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlISW52YWxpZERhdGFFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgcmVxdWVzdCByZXF1aXJlcyBhIG1lc3NhZ2UgaWRlbnRpdHku" + }, + { + "label": "answer_whitespace_message_id.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkoyAgIKljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9tZXNoOmNkbjpjaHVuazo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjsWV4cGVjdGVkU2l6ZUJ5dGVzzRLf" + }, + { + "label": "answer_whitespace_message_id.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKMgICClZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlISW52YWxpZERhdGFFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgcmVxdWVzdCByZXF1aXJlcyBhIG1lc3NhZ2UgaWRlbnRpdHku" + }, + { + "label": "answer_blank_hash.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlksXZlY3Rvci1ibGFuay1oYXNoqWNodW5rSGFzaKCpcmVjb3JkS2V5oLFleHBlY3RlZFNpemVCeXRlc2Q=" + }, + { + "label": "answer_blank_hash.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZLF2ZWN0b3ItYmxhbmstaGFzaKVmb3VuZMKpY2h1bmtIYXNooKlzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlCQXJndW1lbnRFeGNlcHRpb246IEhhc2ggbXVzdCBiZSBub24tZW1wdHkuIChQYXJhbWV0ZXIgJ0NodW5rSGFzaCcp" + }, + { + "label": "answer_whitespace_hash.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlksXZlY3Rvci1zcGFjZS1oYXNoqWNodW5rSGFzaKMgICCpcmVjb3JkS2V5oLFleHBlY3RlZFNpemVCeXRlc2Q=" + }, + { + "label": "answer_whitespace_hash.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZLF2ZWN0b3Itc3BhY2UtaGFzaKVmb3VuZMKpY2h1bmtIYXNooyAgIKlzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlCQXJndW1lbnRFeGNlcHRpb246IEhhc2ggbXVzdCBiZSBub24tZW1wdHkuIChQYXJhbWV0ZXIgJ0NodW5rSGFzaCcp" + }, + { + "label": "answer_prefix_only_hash.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlksnZlY3Rvci1wcmVmaXgtaGFzaKljaHVua0hhc2iqc2hhMjU2OiAgIKlyZWNvcmRLZXmgsWV4cGVjdGVkU2l6ZUJ5dGVzZA==" + }, + { + "label": "answer_prefix_only_hash.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZLJ2ZWN0b3ItcHJlZml4LWhhc2ilZm91bmTCqWNodW5rSGFzaKpzaGEyNTY6ICAgqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2UJBcmd1bWVudEV4Y2VwdGlvbjogSGFzaCBtdXN0IGJlIG5vbi1lbXB0eS4gKFBhcmFtZXRlciAnY2h1bmtIYXNoJyk=" + }, + { + "label": "answer_negative_size.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkr3ZlY3Rvci1uZWdhdGl2ZaljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9tZXNoOmNkbjpjaHVuazo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjsWV4cGVjdGVkU2l6ZUJ5dGVz/w==" + }, + { + "label": "answer_negative_size.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK92ZWN0b3ItbmVnYXRpdmWlZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlgSW52YWxpZERhdGFFeGNlcHRpb246IENETiBhcnRpZmFjdCBjaHVuayBwYXlsb2FkIG1ldGFkYXRhIGRvZXMgbm90IG1hdGNoIGl0cyBtYW5pZmVzdCByZWZlcmVuY2Uu" + }, + { + "label": "answer_record_key_case.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkr3ZlY3Rvci1rZXktY2FzZaljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9NRVNIOkNETjpDSFVOSzo1OTkzQUM2MDQwN0U4NjYwMTg3M0JDMzhFRTZGOERCM0VBOTEyRTk4NzYxQ0I1NThBQjk3OTVEQjMwNkI0NzRDsWV4cGVjdGVkU2l6ZUJ5dGVzzRLf" + }, + { + "label": "answer_record_key_case.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK92ZWN0b3Ita2V5LWNhc2WlZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlPSW52YWxpZERhdGFFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgcmVjb3JkIGtleSBkaXNhZ3JlZXMgd2l0aCBpdHMgY29udGVudCBoYXNoLg==" + }, + { + "label": "answer_blank_record_key.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlksHZlY3Rvci1rZXktYmxhbmupY2h1bmtIYXNo2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXJlY29yZEtleaMgICCxZXhwZWN0ZWRTaXplQnl0ZXPNEt8=" + }, + { + "label": "answer_blank_record_key.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZLB2ZWN0b3Ita2V5LWJsYW5rpWZvdW5kw6ljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpc2l6ZUJ5dGVzz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gcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7pWVycm9yoA==" + }, + { + "label": "answer_double_prefix.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkrXZlY3Rvci1kb3VibGWpY2h1bmtIYXNo2U5zaGEyNTY6c2hhMjU2OjU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V5oLFleHBlY3RlZFNpemVCeXRlc80S3w==" + }, + { + "label": "answer_double_prefix.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK12ZWN0b3ItZG91YmxlpWZvdW5kw6ljaHVua0hhc2jZR3NoYTI1Njo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjqXNpemVCeXRlc80S36dwYXlsb2FkxRLf+foAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+gABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4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BgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+foAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+gABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6O6VlcnJvcqA=" + }, { "label": "response_hash_last_digit", "kind": "response", @@ -55,6 +145,11 @@ "kind": "manifest", "messagePackBase64": "mrVldXJla2EvY29udGVudC12ZWN0b3KlYXNzZXShMdlAZjRhZTJhN2M5NWY0ZDk2NjA1OGY3NWMxMzE4NWFhMGFiNmE5MWZjNWFmYWQ4ODYyOTZlZjJhZWU3NTVhMmFmMc4AFBLfvGFwcGxpY2F0aW9uL3gtY3VsdG5ldC12ZWN0b3LZITIwMjYtMDktMjJUMDA6MDA6MDAuMDAwMDAwMCswMDowMJaU2UBhYTE0NDRiZTRiNjQwOThmNW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MWVmYTdkMTM4NWQ1MWIwNzdlYTg3YjBjMzg2MGQyOGRhNDNkNWQ2ZjIyMWU4NDVjNGMyMzYwZpTZQGFhMTQ0NGJlNGI2NDA5OGY1ZGQ4NjNiNWIwYWM1NjE0ODBiM2ZiNWM0MWZjMDdjZjUwYTYyZWRjOTQxMjRiY2POAAwAAM4ABAAA2U9tZXNoOmNkbjpjaHVuazphYTE0NDRiZTRiNjQwOThmNWRkODYzYjViMGFjNTYxNDgwYjNmYjVjNDFmYzA3Y2Y1MGE2MmVkYzk0MTI0YmNjlNlAMjgzMTcxNTg1OWYwMWYzZjk2M2RkMGYxMTk0ZGJkYmI3NjA5OTk3NDIzMDE1ZDMxZjYwNzkxMWUxYmY4NjQwMs4AEAAAzgAEAADZT21lc2g6Y2RuOmNodW5rOjI4MzE3MTU4NTlmMDFmM2Y5NjNkZDBmMTE5NGRiZGJiNzYwOTk5NzQyMzAxNWQzMWY2MDc5MTFlMWJmODY0MDKU2UA1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjzgAUAADNEt/ZT21lc2g6Y2RuOmNodW5rOjU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOQg6R6ZXRhoTGlYWxwaGGhMqNtaWShMw==" + }, { "label": "manifest_empty_body", "kind": "manifest", diff --git a/packages/cultnet-rs/src/content.rs b/packages/cultnet-rs/src/content.rs index bbf460b9..843d4b86 100644 --- a/packages/cultnet-rs/src/content.rs +++ b/packages/cultnet-rs/src/content.rs @@ -6,8 +6,6 @@ //! This is the only owner of these rules in Rust. A consumer hands `fetch_content` a transport //! closure and gets verified bytes; it never hashes, chunks or validates a manifest itself. -use std::collections::BTreeMap; - use anyhow::{Result, anyhow, bail}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -44,7 +42,9 @@ pub struct CultMeshCdnArtifactManifest { pub created_at_utc: String, pub chunks: Vec, pub tags: Vec, - pub metadata: BTreeMap, + /// Caller metadata in wire order. The reference writes a `Dictionary` in insertion order and + /// refuses a duplicate key at read, so this keeps the order it was read in and refuses a duplicate. + pub metadata: Vec<(String, String)>, } // The tuple mirrors: `to_vec_named` would write a map for a named-field struct, but a tuple @@ -63,9 +63,46 @@ struct ManifestWire( String, Vec, Vec, - BTreeMap, + #[serde(with = "ordered_map")] Vec<(String, String)>, ); +/// A string map that keeps its key order and refuses a duplicate key, as `Dictionary` +/// deserialises. `Vec<(String, String)>` is the in-memory shape; the wire shape is a msgpack map. +mod ordered_map { + use std::fmt; + + use serde::de::{self, MapAccess, Visitor}; + use serde::{Deserializer, Serializer}; + + pub fn serialize(pairs: &[(String, String)], serializer: S) -> Result { + serializer.collect_map(pairs.iter().map(|(key, value)| (key, value))) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + struct Pairs; + impl<'de> Visitor<'de> for Pairs { + type Value = Vec<(String, String)>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a map of strings") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut seen = std::collections::HashSet::new(); + let mut pairs = Vec::new(); + while let Some((key, value)) = map.next_entry::()? { + if !seen.insert(key.clone()) { + return Err(de::Error::custom(format!("duplicate metadata key '{key}'"))); + } + pairs.push((key, value)); + } + Ok(pairs) + } + } + deserializer.deserialize_map(Pairs) + } +} + impl From for ChunkRefWire { fn from(value: CultMeshCdnChunkRef) -> Self { Self(value.chunk_hash, value.offset, value.size_bytes, value.record_key) @@ -138,6 +175,15 @@ pub fn normalize_hash(hash: &str) -> Result { Ok(stripped.trim().to_lowercase()) } +/// A hash the client will put on the wire or compare against: normalized and not empty. +fn non_empty_hash(hash: &str) -> Result { + let normalized = normalize_hash(hash)?; + if normalized.is_empty() { + bail!("Hash must be non-empty."); + } + Ok(normalized) +} + /// `CultMeshCdn.PackArtifact`: splits `bytes` into content-addressed chunks and builds the manifest. /// An empty body packs as one zero-length chunk, as the reference does. pub fn pack_content( @@ -188,7 +234,7 @@ pub fn pack_content( created_at_utc: created_at_utc.to_string(), chunks: refs, tags: Vec::new(), - metadata: BTreeMap::new(), + metadata: Vec::new(), }; validate_manifest(&manifest)?; Ok((manifest, chunks)) @@ -277,13 +323,17 @@ pub fn answer_content_chunk_request<'a>( if message_id.trim().is_empty() { return Err("InvalidDataException: Content chunk request requires a message identity.".to_string()); } - let hash = normalize_hash(chunk_hash) - .map_err(|_| "ArgumentException: Hash must be non-empty. (Parameter 'ChunkHash')".to_string())?; - if !record_key.trim().is_empty() && *record_key != chunk_record_key(&hash) { + // The handler normalises the wire hash, then `CreateRecordKey` normalises that result again + // (and spells its parameter `chunkHash`); the lookup, the size check and the hash check all + // use the second result, and the answer echoes the first. + let blank = |parameter: &str| format!("ArgumentException: Hash must be non-empty. (Parameter '{parameter}')"); + let hash = normalize_hash(chunk_hash).map_err(|_| blank("ChunkHash"))?; + let canonical = normalize_hash(&hash).map_err(|_| blank("chunkHash"))?; + if !record_key.trim().is_empty() && *record_key != chunk_record_key(&canonical) { return Err("InvalidDataException: Content chunk record key disagrees with its content hash.".to_string()); } - let payload = lookup(&hash).ok_or_else(|| "FileNotFoundException: Content chunk is not available.".to_string())?; - validate_chunk(&hash, *expected_size_bytes, &hash, payload.len() as i64, payload) + let payload = lookup(&canonical).ok_or_else(|| "FileNotFoundException: Content chunk is not available.".to_string())?; + validate_chunk(&canonical, *expected_size_bytes, &canonical, payload.len() as i64, payload) .map_err(|error| format!("InvalidDataException: {error}"))?; Ok((hash, payload.to_vec())) })(); @@ -323,9 +373,20 @@ pub fn fetch_content( manifest.size_bytes ); } + // Everything the client will send or compare is settled before the first request. A zero-size + // chunk is legal only as an empty body's single chunk (the reference packs it so); anywhere else + // it is a request that yields nothing, and a manifest of them is a request flood. + let ordered = in_offset_order(manifest); + if ordered.len() > 1 && ordered.iter().any(|chunk| chunk.size_bytes == 0) { + bail!("CDN artifact has a zero-size chunk beside other chunks."); + } + let content_hash = non_empty_hash(&manifest.content_hash)?; + let hashes = ordered + .iter() + .map(|chunk| non_empty_hash(&chunk.chunk_hash)) + .collect::>>()?; let mut body = Vec::new(); - for chunk in in_offset_order(manifest) { - let hash = normalize_hash(&chunk.chunk_hash)?; + for (chunk, hash) in ordered.into_iter().zip(hashes) { let message_id = uuid::Uuid::new_v4().simple().to_string(); let record_key = if chunk.record_key.trim().is_empty() { chunk_record_key(&hash) @@ -358,7 +419,7 @@ pub fn fetch_content( validate_chunk(&hash, chunk.size_bytes, &chunk_hash, i64::from(size_bytes), &payload)?; body.extend_from_slice(&payload); } - if sha256_hex(&body) != normalize_hash(&manifest.content_hash)? { + if sha256_hex(&body) != content_hash { bail!("CDN artifact content hash does not match its manifest."); } Ok(body) diff --git a/packages/cultnet-rs/src/contracts.rs b/packages/cultnet-rs/src/contracts.rs index 038b0708..0925215e 100644 --- a/packages/cultnet-rs/src/contracts.rs +++ b/packages/cultnet-rs/src/contracts.rs @@ -801,40 +801,10 @@ fn validate_message(message: &CultNetMessage) -> Result<()> { validate_shard_descriptor(shard)?; } } - CultNetMessage::ContentChunkRequest { - message_id, - chunk_hash, - record_key: _, - expected_size_bytes, - } => { - require_non_empty(message_id, "messageId")?; - if crate::normalize_hash(chunk_hash)?.is_empty() { - return Err(anyhow!("CultNet field chunkHash must be non-empty")); - } - if *expected_size_bytes < 0 { - return Err(anyhow!("CultNet field expectedSizeBytes must not be negative")); - } - } - CultNetMessage::ContentChunkResponse { - message_id, - found, - chunk_hash: _, - size_bytes, - payload, - error, - } => { - require_non_empty(message_id, "messageId")?; - if *found { - if i64::try_from(payload.len()).ok() != Some(i64::from(*size_bytes)) { - return Err(anyhow!("CultNet field payload length must equal sizeBytes")); - } - if !error.is_empty() { - return Err(anyhow!("CultNet field error must be empty when found")); - } - } else if !payload.is_empty() { - return Err(anyhow!("CultNet field payload must be empty when not found")); - } - } + // The reference's serializer accepts any content chunk message. It refuses a bad request in + // its handler and answers `found: false` (`answer_content_chunk_request`); a bad response is + // refused by `fetch_content`'s verification. Refusing either here would leave a peer in silence. + CultNetMessage::ContentChunkRequest { .. } | CultNetMessage::ContentChunkResponse { .. } => {} CultNetMessage::OperationRequest { message_id, service_id, diff --git a/packages/cultnet-rs/tests/content.rs b/packages/cultnet-rs/tests/content.rs index 363a600d..e4edb0bf 100644 --- a/packages/cultnet-rs/tests/content.rs +++ b/packages/cultnet-rs/tests/content.rs @@ -61,6 +61,24 @@ fn manifest_bytes(manifest: &CultMeshCdnArtifactManifest) -> Vec { rmp_serde::to_vec_named(manifest).expect("encodes") } +fn decode_manifest(bytes: &[u8]) -> CultMeshCdnArtifactManifest { + rmp_serde::from_slice(bytes).expect("decodes") +} + +/// The manifest's bytes with its metadata map replaced by `pairs`, written in exactly that order +/// (and with duplicates, if given): what a peer that is not this crate can put on the wire. +fn manifest_with_metadata(manifest: &CultMeshCdnArtifactManifest, pairs: &[(&str, &str)]) -> Vec { + let encoded = manifest_bytes(manifest); + let mut value = rmpv::decode::read_value(&mut encoded.as_slice()).expect("a msgpack value"); + let rmpv::Value::Array(fields) = &mut value else { + panic!("the manifest is a positional array"); + }; + fields[9] = rmpv::Value::Map(pairs.iter().map(|(k, v)| (rmpv::Value::from(*k), rmpv::Value::from(*v))).collect()); + let mut out = Vec::new(); + rmpv::encode::write_value(&mut out, &value).expect("writes"); + out +} + fn request(id: &str, hash: &str, key: &str, size: i32) -> CultNetMessage { CultNetMessage::ContentChunkRequest { message_id: id.to_string(), @@ -171,6 +189,21 @@ fn local_vectors() -> Vec { request("vector-key", &last.chunk_hash, "mesh:cdn:chunk:other", last_size), ), ("answer_size_mismatch", request("vector-size", &last.chunk_hash, &key, last_size - 1)), + ("answer_blank_message_id", request("", &last.chunk_hash, &key, last_size)), + ("answer_whitespace_message_id", request(" ", &last.chunk_hash, &key, last_size)), + ("answer_blank_hash", request("vector-blank-hash", "", "", 100)), + ("answer_whitespace_hash", request("vector-space-hash", " ", "", 100)), + ("answer_prefix_only_hash", request("vector-prefix-hash", "sha256: ", "", 100)), + ("answer_negative_size", request("vector-negative", &last.chunk_hash, &key, -1)), + ( + "answer_record_key_case", + request("vector-key-case", &last.chunk_hash, &key.to_uppercase(), last_size), + ), + ("answer_blank_record_key", request("vector-key-blank", &last.chunk_hash, " ", last_size)), + ( + "answer_double_prefix", + request("vector-double", &format!("sha256:sha256:{}", last.chunk_hash), "", last_size), + ), ]; for (name, request) in &answers { push_message(format!("{name}.request"), "request", request); @@ -200,6 +233,8 @@ fn local_vectors() -> Vec { let mut shuffled = manifest.clone(); shuffled.chunks = [3, 0, 5, 1, 4, 2].iter().map(|&i| manifest.chunks[i].clone()).collect(); push_manifest("manifest_out_of_order", &shuffled); + let tagged = decode_manifest(&manifest_with_metadata(&manifest, &[("zeta", "1"), ("alpha", "2"), ("mid", "3")])); + push_manifest("manifest_metadata_order", &tagged); push_manifest("manifest_empty_body", &pack(&[]).0); vectors } @@ -479,7 +514,7 @@ fn answer_serves_found_false_with_the_reference_error_spelling() { .expect("paired response"); assert_eq!(&wire(&answer), expected_bytes, "{name}: answer differs from the reference's"); let (_, found, _, payload, error) = response_of(&answer); - if name == "answer_found" { + if ["answer_found", "answer_blank_record_key", "answer_double_prefix"].contains(&name) { assert!(found && error.is_empty() && !payload.is_empty()); } else { assert!(!found && payload.is_empty(), "{name}"); @@ -487,28 +522,7 @@ fn answer_serves_found_false_with_the_reference_error_spelling() { } judged += 1; } - assert_eq!(judged, 4); -} - -#[test] -fn content_messages_refuse_what_the_reference_never_produces() { - let refused = |message: CultNetMessage| assert!(encode_cultnet_message_for_wire(&message, SCHEMA_V0).is_err(), "{message:?}"); - refused(request("", "abc", "", 1)); - refused(request("m", "sha256: ", "", 1)); - refused(request("m", "abc", "", -1)); - let response = |found: bool, size: i32, payload: &[u8], error: &str| CultNetMessage::ContentChunkResponse { - message_id: "m".to_string(), - found, - chunk_hash: "abc".to_string(), - size_bytes: size, - payload: payload.to_vec(), - error: error.to_string(), - }; - refused(response(true, 3, &[1, 2], "")); - refused(response(true, 2, &[1, 2], "boom")); - refused(response(false, 0, &[1], "boom")); - assert!(encode_cultnet_message_for_wire(&response(true, 2, &[1, 2], ""), SCHEMA_V0).is_ok()); - assert!(encode_cultnet_message_for_wire(&response(false, 0, &[], "boom"), SCHEMA_V0).is_ok()); + assert_eq!(judged, 13); } #[test] @@ -518,3 +532,236 @@ fn gamecult_networking_contract_refuses_content_messages() { assert!(encode_cultnet_message_for_wire(&message, legacy).is_err()); assert!(decode_cultnet_message_from_slice(&wire(&message), legacy).is_err()); } + +// ------------------------------------------------------------------------------------------ +// BP-1 fixes +// ------------------------------------------------------------------------------------------ + +fn chunk_ref(hash: &str, offset: i64, size: i32) -> cultnet_rs::CultMeshCdnChunkRef { + cultnet_rs::CultMeshCdnChunkRef { + chunk_hash: hash.to_string(), + offset, + size_bytes: size, + record_key: String::new(), + } +} + +/// A manifest with the given chunk list and stated size, everything else from a real pack. +fn manifest_of(size: i64, chunks: Vec) -> CultMeshCdnArtifactManifest { + let mut manifest = pack(&[]).0; + manifest.size_bytes = size; + manifest.chunks = chunks; + manifest +} + +// F1: a zero-size chunk is legal only as an empty body's single chunk. +#[test] +fn a_zero_size_chunk_flood_is_refused_before_any_request() { + let (empty, empty_chunks) = pack(&[]); + let empty_store = store(&empty_chunks); + let flood = manifest_of(0, (0..100_000).map(|_| chunk_ref(&empty.content_hash, 0, 0)).collect()); + validate_manifest(&flood).expect("the shared shape rule accepts it, as the reference does"); + let calls = std::cell::Cell::new(0); + assert!(fetch_content(&flood, u64::MAX, serving(&empty_store, &calls)).is_err()); + assert_eq!(calls.get(), 0, "100,000 empty chunks must not become 100,000 requests"); + + // A zero-size chunk beside real ones is refused too, so skipping it is never the client's job. + let (good, chunks) = pack(&body()); + let body_store = store(&chunks); + let mut zero_inside = good.clone(); + let boundary = zero_inside.chunks[2].offset; + zero_inside.chunks.insert(2, chunk_ref(&empty.content_hash, boundary, 0)); + validate_manifest(&zero_inside).expect("shape-valid"); + let calls = std::cell::Cell::new(0); + assert!(fetch_content(&zero_inside, u64::MAX, serving(&body_store, &calls)).is_err()); + assert_eq!(calls.get(), 0); + + // An empty body still fetches, through its one zero-length chunk. + let calls = std::cell::Cell::new(0); + assert_eq!(fetch_content(&empty, 0, serving(&empty_store, &calls)).expect("fetches"), Vec::::new()); + assert_eq!(calls.get(), 1); +} + +// F2, F5: every bad request is answered, in the reference's validation order and spelling. The +// byte-identity against the reference server's own answers is `answer_serves_found_false_...`. +#[test] +fn a_bad_request_is_answered_never_dropped() { + let (_, chunks) = pack(&body()); + let store = store(&chunks); + let last = chunks.last().unwrap(); + let size = last.payload.len() as i32; + let size_mismatch = "InvalidDataException: CDN artifact chunk payload metadata does not match its manifest reference."; + for (label, bad, spelling) in [ + ( + "blank id", + request("", &last.chunk_hash, "", size), + "InvalidDataException: Content chunk request requires a message identity.", + ), + ("blank hash", request("m", "", "", size), "ArgumentException: Hash must be non-empty. (Parameter 'ChunkHash')"), + ( + "prefix-only hash", + request("m", "sha256: ", "", size), + "ArgumentException: Hash must be non-empty. (Parameter 'chunkHash')", + ), + ("negative size", request("m", &last.chunk_hash, "", -1), size_mismatch), + ] { + let answer = answer_content_chunk_request(&bad, lookup_in(&store)); + let (_, found, _, payload, error) = response_of(&answer); + assert!(!found && payload.is_empty(), "{label}"); + assert_eq!(error, spelling, "{label}"); + // And both travel: neither the request nor its answer is stopped at decode or encode. + assert_eq!(unwire(&wire(&bad)).expect("the request decodes"), bad, "{label}"); + assert_eq!(unwire(&wire(&answer)).expect("the answer encodes and decodes"), answer, "{label}"); + } +} + +// F3: metadata keeps the order it was read in and refuses a duplicate key. +#[test] +fn manifest_metadata_keeps_wire_order_and_refuses_a_duplicate_key() { + let reference = read_vectors("content-vectors.cs-written.json"); + let (_, _, bytes) = reference.iter().find(|(l, _, _)| l == "manifest_metadata_order").expect("vector"); + let decoded = decode_manifest(bytes); + assert_eq!(&manifest_bytes(&decoded), bytes, "zeta, alpha, mid re-encode as zeta, alpha, mid"); + + let base = pack(&body()).0; + let duplicated = manifest_with_metadata(&base, &[("k", "1"), ("other", "2"), ("k", "3")]); + assert!(rmp_serde::from_slice::(&duplicated).is_err()); + let unique = manifest_with_metadata(&base, &[("k", "1"), ("other", "2")]); + assert_eq!(manifest_bytes(&decode_manifest(&unique)), unique); +} + +// F4: hashes are settled before the first request. +#[test] +fn a_blank_hash_is_refused_before_any_request() { + let (good, chunks) = pack(&body()); + let store = store(&chunks); + let mut blank_content = good.clone(); + blank_content.content_hash = " ".to_string(); + let mut prefix_content = good.clone(); + prefix_content.content_hash = "sha256: ".to_string(); + let mut blank_chunk = good.clone(); + blank_chunk.chunks[3].chunk_hash = " ".to_string(); + let mut prefix_chunk = good.clone(); + prefix_chunk.chunks[3].chunk_hash = "SHA256: ".to_string(); + for (label, manifest) in [ + ("blank content hash", blank_content), + ("prefix-only content hash", prefix_content), + ("blank chunk hash at 3", blank_chunk), + ("prefix-only chunk hash at 3", prefix_chunk), + ] { + let calls = std::cell::Cell::new(0); + assert!(fetch_content(&manifest, u64::MAX, serving(&store, &calls)).is_err(), "{label}"); + assert_eq!(calls.get(), 0, "{label}: refused before any request"); + } +} + +// F6: `pack_content` refuses a chunk size the reference's int cannot hold, without panicking. +#[test] +fn pack_content_refuses_an_unusable_chunk_size() { + for size in [0usize, i32::MAX as usize + 1, usize::MAX] { + let refused = std::panic::catch_unwind(|| pack_content("a", "", "", "", "", b"abc", size)); + assert!(matches!(refused, Ok(Err(_))), "chunk size {size} must be refused cleanly"); + } + let (manifest, _) = + pack_content("a", "", "", "", "", b"abc", i32::MAX as usize).expect("i32::MAX is a valid chunk size"); + assert_eq!(manifest.chunks.len(), 1); +} + +// F6: `PackArtifact` defaults a blank kind and mime type and otherwise uses the value untouched. +#[test] +fn pack_defaults_only_a_blank_kind_and_mime_type_and_never_trims() { + let packed = |kind: &str, mime: &str| pack_content("a", kind, "v", mime, CREATED, b"abc", 2).expect("packs").0; + for blank in ["", " ", "\t \n"] { + let manifest = packed(blank, blank); + assert_eq!( + (manifest.kind.as_str(), manifest.mime_type.as_str()), + ("asset", "application/octet-stream"), + "{blank:?}" + ); + } + let manifest = packed(" build ", " text/plain "); + assert_eq!((manifest.kind.as_str(), manifest.mime_type.as_str()), (" build ", " text/plain ")); +} + +/// The honest answer to `request`, taken apart so a test can lie in one field. +fn honest(request: &CultNetMessage, store: &HashMap>) -> (String, bool, String, i32, Vec, String) { + match answer_content_chunk_request(request, lookup_in(store)) { + CultNetMessage::ContentChunkResponse { message_id, found, chunk_hash, size_bytes, payload, error } => { + (message_id, found, chunk_hash, size_bytes, payload, error) + } + other => panic!("{other:?}"), + } +} + +// F6: the two halves of the per-chunk check, each on its own. +#[test] +fn a_chunk_whose_length_or_claim_disagrees_with_the_manifest_is_refused() { + let (manifest, chunks) = pack(&body()); + let store = store(&chunks); + // Each lie maps (honest size, honest payload) to (claimed size, payload served). + type Lie = fn(i32, Vec) -> (i32, Vec); + let lies: [(&str, Lie); 4] = [ + ("a payload of the claimed length that is not the manifest's length", |size, mut p| { + p.truncate(p.len() - 1); + (size - 1, p) + }), + ("a payload whose length is not its claimed size, the claim being the manifest's", |size, mut p| { + p.truncate(p.len() - 1); + (size, p) + }), + ("the right payload under a wrong claimed size", |size, p| (size - 1, p)), + ("a longer payload of its claimed length", |size, mut p| { + p.push(0); + (size + 1, p) + }), + ]; + for (label, lie) in lies { + let error = fetch_content(&manifest, u64::MAX, |message| { + let (message_id, found, chunk_hash, honest_size, payload, error) = honest(&message, &store); + let (size_bytes, payload) = lie(honest_size, payload); + Ok(CultNetMessage::ContentChunkResponse { message_id, found, chunk_hash, size_bytes, payload, error }) + }) + .expect_err(label); + assert!(error.to_string().contains("payload metadata does not match"), "{label}: {error}"); + } +} + +// F6: `[5@0, 0@0]` is not contiguous under the reference's stable sort by offset alone. +#[test] +fn equal_offsets_keep_their_manifest_order() { + let hash = "0".repeat(64); + let five_then_zero = manifest_of(5, vec![chunk_ref(&hash, 0, 5), chunk_ref(&hash, 0, 0)]); + assert!(validate_manifest(&five_then_zero).is_err(), "the stable sort keeps 5@0 first, so 0@0 lands at offset 5"); + let zero_then_five = manifest_of(5, vec![chunk_ref(&hash, 0, 0), chunk_ref(&hash, 0, 5)]); + validate_manifest(&zero_then_five).expect("0@0 first leaves 5@0 at offset 0"); +} + +// F6: what goes on the wire is the normalized hash and the canonical record key. +#[test] +fn the_client_sends_the_normalized_hash_and_canonical_record_key() { + let (mut manifest, chunks) = pack(&body()); + let store = store(&chunks); + let honest_hashes: Vec = manifest.chunks.iter().map(|c| c.chunk_hash.clone()).collect(); + manifest.content_hash = format!("SHA256:{}", manifest.content_hash.to_uppercase()); + for (index, chunk) in manifest.chunks.iter_mut().enumerate() { + chunk.chunk_hash = format!("sha256:{}", chunk.chunk_hash.to_uppercase()); + // Alternate chunks name their key; the rest leave it blank for the client to derive. + chunk.record_key = + if index % 2 == 0 { format!("mesh:cdn:chunk:{}", honest_hashes[index]) } else { " ".to_string() }; + } + let mut sent = Vec::new(); + let fetched = fetch_content(&manifest, u64::MAX, |message| { + sent.push(message.clone()); + Ok(answer_content_chunk_request(&message, lookup_in(&store))) + }) + .expect("fetches"); + assert_eq!(fetched, body()); + assert_eq!(sent.len(), honest_hashes.len()); + for (message, hash) in sent.iter().zip(&honest_hashes) { + let CultNetMessage::ContentChunkRequest { chunk_hash, record_key, .. } = message else { + panic!("not a request"); + }; + assert_eq!(chunk_hash, hash, "the normalized hash is what is sent"); + assert_eq!(record_key, &format!("mesh:cdn:chunk:{hash}"), "and the canonical key"); + } +} diff --git a/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs b/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs index 2e156891..6c5763bb 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs @@ -164,6 +164,16 @@ public sealed class CultMeshContentVectorTests AddAnswer("answer_not_found", Request("vector-missing", new string('0', 64), string.Empty, 100)); AddAnswer("answer_record_key_disagrees", Request("vector-key", last.ChunkHash, "mesh:cdn:chunk:other", last.SizeBytes)); AddAnswer("answer_size_mismatch", Request("vector-size", last.ChunkHash, key, last.SizeBytes - 1)); + // Requests the reference refuses in its handler, never at deserialisation: each is answered. + AddAnswer("answer_blank_message_id", Request(string.Empty, last.ChunkHash, key, last.SizeBytes)); + AddAnswer("answer_whitespace_message_id", Request(" ", last.ChunkHash, key, last.SizeBytes)); + AddAnswer("answer_blank_hash", Request("vector-blank-hash", string.Empty, string.Empty, 100)); + AddAnswer("answer_whitespace_hash", Request("vector-space-hash", " ", string.Empty, 100)); + AddAnswer("answer_prefix_only_hash", Request("vector-prefix-hash", "sha256: ", string.Empty, 100)); + AddAnswer("answer_negative_size", Request("vector-negative", last.ChunkHash, key, -1)); + AddAnswer("answer_record_key_case", Request("vector-key-case", last.ChunkHash, key.ToUpperInvariant(), last.SizeBytes)); + AddAnswer("answer_blank_record_key", Request("vector-key-blank", last.ChunkHash, " ", last.SizeBytes)); + AddAnswer("answer_double_prefix", Request("vector-double", "sha256:sha256:" + last.ChunkHash, string.Empty, last.SizeBytes)); AddResponse("response_hash_last_digit", new CultMeshContentChunkResponseMessage { MessageId = "vector-digit", @@ -184,6 +194,9 @@ public sealed class CultMeshContentVectorTests var shuffled = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options()).Manifest; shuffled.Chunks = new[] { 3, 0, 5, 1, 4, 2 }.Select(i => shuffled.Chunks[i]).ToArray(); AddManifest("manifest_out_of_order", shuffled); + var tagged = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options()).Manifest; + tagged.Metadata = new Dictionary { ["zeta"] = "1", ["alpha"] = "2", ["mid"] = "3" }; + AddManifest("manifest_metadata_order", tagged); AddManifest("manifest_empty_body", CultMeshCdn.PackArtifact(ArtifactId, Array.Empty(), Options()).Manifest); return vectors; } From dc9162f85ddc7162473d62ddf0c27db88352fcb9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:12:44 +0200 Subject: [PATCH 31/64] Correct the content-plane parity claim for metadata order and bad requests Co-Authored-By: Claude Sonnet 5 --- docs/runtime-parity-scope.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/runtime-parity-scope.md b/docs/runtime-parity-scope.md index 109a287f..6710c2dd 100644 --- a/docs/runtime-parity-scope.md +++ b/docs/runtime-parity-scope.md @@ -74,8 +74,10 @@ to speak CultNet or participate in CultMesh. semantic ones. A single rows-to-bytes path driving both halves in one call remains its own cut (R-AR) and is not part of this claim. - CultMesh content plane (`cultmesh.content_chunk_request.v1` and `.response.v1` - plus the CDN manifest, C#/Rust only): byte parity in both directions, and the - reference's answer to a chunk request, including its failure spellings. + plus the CDN manifest, C#/Rust only): byte parity in both directions (manifest metadata keeps its wire key order and a + duplicate key is refused, as the reference refuses it), and the reference's answer + to a chunk request, including its failure spellings: every bad request is + answered `found: false`, never refused at decode. `packages/cultnet-rs/tests/content.rs` and `tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs` judge `contracts/cultmesh/content-vectors.cs-written.json` and From 36aa8d8791ee80f93fbd0ddd04a68a24ed29a3fb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:34:11 +0200 Subject: [PATCH 32/64] Rust: drain the header peek so rmp-serde accepts the array The peek left snapshot slots unread and rmp-serde refused the length mismatch, so every store fell through to the legacy decode. Co-Authored-By: Claude Sonnet 5 --- packages/cultcache-rs/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index a535b935..e48ebad8 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -330,6 +330,7 @@ fn store_header(bytes: &[u8]) -> Option { let header: String = seq .next_element()? .ok_or_else(|| ::invalid_length(0, &self))?; + while seq.next_element::()?.is_some() {} Ok(Header(header)) } } From 66bd07b9416510969600248545151fd0cbbf1fb0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:35:57 +0200 Subject: [PATCH 33/64] Pin the legacy-layout and missing-header refusals The legacy catalog layout reaches CultMesh's fallback reader, and a nil header was the only defaulted header; each gets one vector or test. The C# store tests catch the refusal where the store attaches. Co-Authored-By: Claude Sonnet 5 --- .../PreCut2StoreFormatTests.cs | 27 ++++++++++++------- .../CultMeshVariantRefusalTests.cs | 7 +++++ .../vectors/document-variants-c0/generate.py | 7 +++++ .../legacy-catalog-extra-slot.msgpack | 1 + 4 files changed, 33 insertions(+), 9 deletions(-) create mode 100644 tests/vectors/document-variants-c0/legacy-catalog-extra-slot.msgpack diff --git a/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs b/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs index 6757a806..479eb762 100644 --- a/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs +++ b/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs @@ -97,7 +97,7 @@ namespace GameCult.Caching.Tests throw new FileNotFoundException($"Shared vector {name} not found above {TestContext.CurrentContext.TestDirectory}."); } - private static async Task PullRefusalAsync(string vector) + private static string Refusal(string vector) { var root = Path.Combine(Path.GetTempPath(), $"cultlib-vector-{Guid.NewGuid():N}"); Directory.CreateDirectory(root); @@ -106,8 +106,7 @@ namespace GameCult.Caching.Tests var file = Path.Combine(root, "store.msgpack"); File.Copy(VectorPath(vector), file); using var cache = new CultCache(); - cache.AddBackingStore(new SingleFileMessagePackBackingStore(file)); - var error = Assert.CatchAsync(async () => await cache.PullAllBackingStoresAsync()); + var error = Assert.Catch(() => cache.AddBackingStore(new SingleFileMessagePackBackingStore(file))); Assert.That(error, Is.Not.Null); Assert.That(error!.ToString(), Does.Contain(nameof(NotSupportedException))); return error.ToString(); @@ -119,26 +118,36 @@ namespace GameCult.Caching.Tests } [Test] - public async Task SingleFileRefusesUnknownHeaderByName() + public void SingleFileRefusesUnknownHeaderByName() { - Assert.That(await PullRefusalAsync("unknown-header.msgpack"), Does.Contain("cultcache.store.v9")); + Assert.That(Refusal("unknown-header.msgpack"), Does.Contain("cultcache.store.v9")); } [Test] - public async Task SingleFileRefusesExtraRecordSlotNamingTheRecord() + public void SingleFileRefusesExtraRecordSlotNamingTheRecord() { - var message = await PullRefusalAsync("extra-slot-full-payload.msgpack"); + var message = Refusal("extra-slot-full-payload.msgpack"); Assert.That(message, Does.Contain("item:anvil")); Assert.That(message, Does.Contain(ItemSchemaId)); } [Test] - public async Task SingleFileRefusesVariantStoreByVersionOrRecord() + public void SingleFileRefusesVariantStoreByVersionOrRecord() { - Assert.That(await PullRefusalAsync("variant-v2.msgpack"), + Assert.That(Refusal("variant-v2.msgpack"), Does.Contain("cultcache.store.v2").Or.Contain("item:anvil-big")); } + [Test] + public void SnapshotWithoutAFormatVersionIsRefusedNotDefaultedToV1() + { + // [nil, [], []] + var bytes = new byte[] { 0x93, 0xc0, 0x90, 0x90 }; + + Assert.That(() => CultDocumentMessagePackSerialization.DeserializeSnapshot(bytes), + Throws.TypeOf().With.Message.Contains("format version")); + } + [Test] public void V1StoreWrittenAtTheBaseCommitStillDecodesByteForByte() { diff --git a/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs b/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs index 7636cacf..a5be069a 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs @@ -38,6 +38,13 @@ public sealed class CultMeshVariantRefusalTests message.Should().Contain("item:anvil").And.Contain(ItemSchemaId); } + [Test] + public void ReadSingleFileDocument_RefusesExtraRecordSlotInTheLegacyCatalogLayoutToo() + { + var message = Refusal("legacy-catalog-extra-slot.msgpack").Message; + message.Should().Contain("item:anvil").And.Contain(ItemSchemaId); + } + [Test] public void ReadSingleFileDocument_RefusesVariantStoreByVersionOrRecord() { diff --git a/tests/vectors/document-variants-c0/generate.py b/tests/vectors/document-variants-c0/generate.py index fafd5dfe..e3d2547d 100644 --- a/tests/vectors/document-variants-c0/generate.py +++ b/tests/vectors/document-variants-c0/generate.py @@ -4,6 +4,10 @@ at test time. Run: python generate.py (needs msgpack). unknown-header.msgpack header cultcache.store.v9, otherwise the v1 store extra-slot-full-payload.msgpack v1 header, record item:anvil gains slot 4, payload stays full + legacy-catalog-extra-slot.msgpack + v1 header, catalog entry in the older layout (contentHash at slot + 5), so CultMesh's legacy snapshot reader takes it, plus the + extra-slot record v1-base.msgpack NOT generated here: written once by the Python runtime at CultLib 69a21bb (SingleFileMessagePackBackingStore.push of alpha and beta, type vectors.item, before any C0 code existed) @@ -32,3 +36,6 @@ write("extra-slot-full-payload.msgpack", [header, catalog, [anvil + [["item:bellows", []]]] + records[1:]]) variant = ["item:anvil-big", anvil[1], anvil[2], b"", ["item:anvil", [[0, [[1, ""]], "", 99]]]] write("variant-v2.msgpack", ["cultcache.store.v2", catalog, records + [variant]]) +legacy_entry = [catalog[0][0], catalog[0][1], catalog[0][2], catalog[0][4], None, catalog[0][3], []] +write("legacy-catalog-extra-slot.msgpack", + [header, [legacy_entry], [anvil + [["item:bellows", []]]]]) diff --git a/tests/vectors/document-variants-c0/legacy-catalog-extra-slot.msgpack b/tests/vectors/document-variants-c0/legacy-catalog-extra-slot.msgpack new file mode 100644 index 00000000..7ae1a542 --- /dev/null +++ b/tests/vectors/document-variants-c0/legacy-catalog-extra-slot.msgpack @@ -0,0 +1 @@ +“²cultcache.store.v1‘—ÙGsha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788µfixtures.precut2.item¸fixtures.precut2.item.v1Úp{"schemaName":"fixtures.precut2.item","schemaVersion":"fixtures.precut2.item.v1","members":[{"slot":0,"name":"Name","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":true},{"slot":1,"name":"Count","type":"System.Int32","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false}]}ÀÙGsha256:dadf30bc920849ee89ed5d70cc73027070dd7571c5f878db1901f3abc459cc0c�‘•ªitem:anvilÙGsha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788Ù!2026-09-13T15:14:36.4032226+00:00Ä’¥anvil’¬item:bellows� \ No newline at end of file From a7eb9967e9541c42f10c8217d9e8710b76765bb4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 02:59:59 +0200 Subject: [PATCH 34/64] Pin the metadata decode message so the last content.rs mutant is caught Co-Authored-By: Claude Sonnet 5 --- packages/cultnet-rs/tests/content.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/cultnet-rs/tests/content.rs b/packages/cultnet-rs/tests/content.rs index e4edb0bf..b36ae5f4 100644 --- a/packages/cultnet-rs/tests/content.rs +++ b/packages/cultnet-rs/tests/content.rs @@ -628,6 +628,17 @@ fn manifest_metadata_keeps_wire_order_and_refuses_a_duplicate_key() { assert!(rmp_serde::from_slice::(&duplicated).is_err()); let unique = manifest_with_metadata(&base, &[("k", "1"), ("other", "2")]); assert_eq!(manifest_bytes(&decode_manifest(&unique)), unique); + + // Metadata that is not a map is refused, and says what was expected. + let mut value = rmpv::decode::read_value(&mut manifest_bytes(&base).as_slice()).expect("a msgpack value"); + let rmpv::Value::Array(fields) = &mut value else { + panic!("the manifest is a positional array"); + }; + fields[9] = rmpv::Value::from(5); + let mut not_a_map = Vec::new(); + rmpv::encode::write_value(&mut not_a_map, &value).expect("writes"); + let error = rmp_serde::from_slice::(¬_a_map).expect_err("not a map"); + assert!(error.to_string().contains("a map of strings"), "{error}"); } // F4: hashes are settled before the first request. From 3c9ce3823ce7039db84947ae3c3fecfd52ba9fa0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:05:12 +0200 Subject: [PATCH 35/64] cultnet-rs fixture example: add a lease-bound stateful Idunn set Adds `service-stateful` (streampixels-service shape, state lineage set, write_lease_required) with a Rust-issued lease.cc, warming/active/degraded vectors bound to it, and two wrong leases (other warming digest, other target). Each vector still passes authenticate + correlate before it is written. Co-Authored-By: Claude Sonnet 5 --- .../examples/idunn_runtime_fixture.rs | 129 ++++++++++++++---- .../test/fixtures/idunn-runtime/README.md | 8 +- 2 files changed, 111 insertions(+), 26 deletions(-) diff --git a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs index d6b432a6..57364c10 100644 --- a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs +++ b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs @@ -11,6 +11,13 @@ //! disagreement). Ed25519 is deterministic, so the TypeScript signer must //! reproduce each vector byte for byte from the same fields. //! +//! The `service-stateful` set is the lease-bound shape: Expected carries a state +//! lineage and requires a write lease, and Rust issues `lease.cc` naming the +//! warming vector's digest. Its warming vector is sequence 1; the active and +//! degraded vectors are sequence 2 and bind to that lease. Two further leases are +//! deliberately wrong (`lease-other-warming.cc` names a different warming digest, +//! `lease-other-target.cc` names another target) for the TypeScript refusal tests. +//! //! Linux only: the provider identity is bound to `/etc/machine-id`, and the //! generated `machine-id` file records the value the identities were bound to. //! @@ -26,9 +33,10 @@ use cultcache_rs::{ use cultnet_rs::{ GameCultProviderHealthIdentity, GameCultRuntimeCapability, GameCultRuntimePresenceHealthPurpose, GameCultRuntimePresenceHealthRecord, - IDUNN_EXPECTED_INCARNATION_SCHEMA, IDUNN_RUNTIME_ACTIVATION_SCHEMA, - IdunnExpectedCapability, IdunnExpectedDependency, IdunnExpectedIncarnationRecord, - IdunnExpectedRoute, IdunnRuntimeActivationLaunch, IdunnRuntimeActivationRecord, + IDUNN_EXPECTED_INCARNATION_SCHEMA, IDUNN_PROCESS_WRITE_LEASE_SCHEMA, + IDUNN_RUNTIME_ACTIVATION_SCHEMA, IdunnExpectedCapability, IdunnExpectedDependency, + IdunnExpectedIncarnationRecord, IdunnExpectedRoute, IdunnProcessWriteLeaseRecord, + IdunnRuntimeActivationLaunch, IdunnRuntimeActivationRecord, IdunnRuntimeActivationSigner, IdunnServiceIdentity, RuntimePresenceAuthenticationContext, authenticate_runtime_presence_claim, correlate_runtime_presence_claim, enroll_service_identity_at, verify_runtime_authority, @@ -49,9 +57,10 @@ struct Set { candidate: &'static str, minimum_capacity: u32, odin_dependency: bool, + stateful: bool, } -const SETS: [Set; 3] = [ +const SETS: [Set; 4] = [ Set { dir: "web", target: "streampixels-web", @@ -60,6 +69,7 @@ const SETS: [Set; 3] = [ candidate: "http://127.0.0.1:18830", minimum_capacity: 1, odin_dependency: false, + stateful: false, }, Set { dir: "service", @@ -69,6 +79,17 @@ const SETS: [Set; 3] = [ candidate: "tcp://127.0.0.1:18831", minimum_capacity: 2, odin_dependency: true, + stateful: false, + }, + Set { + dir: "service-stateful", + target: "streampixels-service", + transport: "tcp", + stable: "tcp://127.0.0.1:8833", + candidate: "tcp://127.0.0.1:18833", + minimum_capacity: 2, + odin_dependency: true, + stateful: true, }, Set { dir: "rudp-route", @@ -78,6 +99,7 @@ const SETS: [Set; 3] = [ candidate: "rudp://127.0.0.1:18832", minimum_capacity: 1, odin_dependency: false, + stateful: false, }, ]; @@ -131,9 +153,9 @@ fn build( expected_signer_identity_id: provider_anchor.identity_id.clone(), health_contract: format!("{}.runtime-health", set.target), artifact_sha256: digest('4'), - state_schema_generation: None, - state_contract_sha256: None, - write_lease_required: false, + state_schema_generation: set.stateful.then(|| "streampixels-state-v1".to_string()), + state_contract_sha256: set.stateful.then(|| digest('7')), + write_lease_required: set.stateful, route: Some(IdunnExpectedRoute { route_id: format!("{}-route", set.target), transport: set.transport.into(), @@ -189,20 +211,13 @@ fn build( let authority = verify_runtime_authority(&expected, &activation, idunn_anchor, &provider_anchor.public_key)?; - let vectors = [ - ("presence-active.bin", "active", set.minimum_capacity, None), - ("presence-warming.bin", "warming", set.minimum_capacity, None), - ( - "presence-active-below-minimum.bin", - "active", - set.minimum_capacity.saturating_sub(1), - Some("expected-capability-000-capacity"), - ), - ]; - for (name, state, capacity, disagreement) in vectors { - if capacity == 0 { - continue; - } + let sign_vector = |name: &str, + state: &str, + capacity: u32, + sequence: u64, + write_lease_sha256: Option, + disagreement: Option<&str>| + -> Result { let mut presence = GameCultRuntimePresenceHealthRecord { schema_version: cultnet_rs::GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), target: expected.target.clone(), @@ -211,8 +226,8 @@ fn build( incarnation_id: expected.incarnation_id.clone(), sealed_release_id: expected.sealed_release_id.clone(), activation_witness_sha256: activation.canonical_sha256()?, - state_schema_generation: None, - state_contract_sha256: None, + state_schema_generation: expected.state_schema_generation.clone(), + state_contract_sha256: expected.state_contract_sha256.clone(), runtime_id: expected.runtime_id.clone(), runtime_instance_id: activation.runtime_instance_id.clone(), bound_endpoint: Some(set.candidate.into()), @@ -225,9 +240,9 @@ fn build( health_contract: expected.health_contract.clone(), state: state.into(), detail: DETAIL.into(), - write_lease_sha256: None, + write_lease_sha256, signer_identity_id: provider_anchor.identity_id.clone(), - publisher_sequence: SEQUENCE, + publisher_sequence: sequence, observed_at_unix_millis: OBSERVED_AT, signature_algorithm: "ed25519".into(), signature: Vec::new(), @@ -250,6 +265,7 @@ fn build( maximum_future_skew_millis: 0, }, )?; + let presence_sha256 = claim.signed_presence_sha256().to_string(); let correlation = correlate_runtime_presence_claim(claim, &authority)?; let codes: Vec<&str> = correlation .disagreements() @@ -261,6 +277,69 @@ fn build( Some(code) => ensure!(codes == [code], "{name}: expected only {code}, got {codes:?}"), } fs::write(dir.join(name), bytes)?; + Ok(presence_sha256) + }; + + if !set.stateful { + sign_vector("presence-active.bin", "active", set.minimum_capacity, SEQUENCE, None, None)?; + sign_vector("presence-warming.bin", "warming", set.minimum_capacity, SEQUENCE, None, None)?; + if set.minimum_capacity > 1 { + sign_vector( + "presence-active-below-minimum.bin", + "active", + set.minimum_capacity - 1, + SEQUENCE, + None, + Some("expected-capability-000-capacity"), + )?; + } + return Ok(()); + } + + // Lease-bound set. The warming vector comes first because the lease names it. + let warming_sha256 = + sign_vector("presence-warming.bin", "warming", set.minimum_capacity, SEQUENCE, None, None)?; + let activation_sha256 = activation.canonical_sha256()?; + let lease_for = |target: &str, warming_presence_sha256: &str| IdunnProcessWriteLeaseRecord { + schema_version: IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into(), + target: target.into(), + expected_projection_sha256: activation.expected_projection_sha256.clone(), + plan_id: expected.plan_id.clone(), + incarnation_id: expected.incarnation_id.clone(), + sealed_release_id: expected.sealed_release_id.clone(), + activation_witness_sha256: activation_sha256.clone(), + state_schema_generation: expected.state_schema_generation.clone().unwrap_or_default(), + state_contract_sha256: expected.state_contract_sha256.clone().unwrap_or_default(), + runtime_id: expected.runtime_id.clone(), + runtime_instance_id: activation.runtime_instance_id.clone(), + warming_presence_sha256: warming_presence_sha256.into(), + lease_epoch: 1, + issued_at_unix_millis: OBSERVED_AT - 1_000, + }; + let lease = lease_for(set.target, &warming_sha256); + let other_warming = lease_for(set.target, &digest('d')); + let other_target = lease_for("streampixels-web", &warming_sha256); + for (name, record) in [ + ("lease.cc", &lease), + ("lease-other-warming.cc", &other_warming), + ("lease-other-target.cc", &other_target), + ] { + let bytes = record.canonical_bytes()?; + ensure!( + IdunnProcessWriteLeaseRecord::decode_canonical(&bytes)? == *record, + "{name}: lease does not round-trip" + ); + write_record( + &dir.join(name), + &record.target, + IdunnProcessWriteLeaseRecord::TYPE, + IDUNN_PROCESS_WRITE_LEASE_SCHEMA, + bytes, + )?; + } + let lease_sha256 = lease.canonical_sha256()?; + for (name, state) in [("presence-active.bin", "active"), ("presence-degraded.bin", "degraded")] { + sign_vector(name, state, set.minimum_capacity, SEQUENCE + 1, Some(lease_sha256.clone()), None)?; } Ok(()) } diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md b/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md index de1ccea4..dd683a16 100644 --- a/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md @@ -8,8 +8,14 @@ provider identity is bound to it. On Yggdrasil: DOCKER_ARGS='--cap-add SYS_ADMIN --security-opt apparmor=unconfined' bash ygg-verify.sh HEAD rust 'cd packages/cultnet-rs && cp /tmp/mid && mount --bind /tmp/mid /etc/machine-id && cargo run -q --example idunn_runtime_fixture /tmp/out' -then copy `/tmp/out` over this directory. Every `presence-*.bin` was accepted by +then copy `/tmp/out` over this directory. `--cap-add SYS_ADMIN` exists only so the bind mount can present the committed `machine-id`, which keeps Yggdrasil's real machine-id out of the repo. Every `presence-*.bin` was accepted by `authenticate_runtime_presence_claim` and correlated by `correlate_runtime_presence_claim` before being written; the `below-minimum` vector correlates to exactly `expected-capability-000-capacity`. Ed25519 is deterministic, so the TypeScript signer must reproduce them byte for byte. + +`service-stateful` is the lease-bound shape (`streampixels-service`, state lineage set, +`write_lease_required: true`). Rust issues `lease.cc`, which names the digest of its +`presence-warming.bin`; `presence-active.bin` and `presence-degraded.bin` are sequence 2 and +carry that lease's digest. `lease-other-warming.cc` names a different warming digest and +`lease-other-target.cc` names another target; the TypeScript lease check must refuse both. From 4ec75eec18976f57a08082cb633f7088cb5a05c2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:10:55 +0200 Subject: [PATCH 36/64] cultnet-ts: regenerate Idunn runtime fixtures with the stateful lease-bound set Output of the Rust generator (3c9ce38) on Yggdrasil. Every set is re-enrolled, so all bytes change; adds service-stateful with lease.cc, the two wrong leases and the warming/active/degraded vectors. Co-Authored-By: Claude Sonnet 5 --- .../rudp-route/activation-key.seed | 2 +- .../idunn-runtime/rudp-route/activation.cc | Bin 800 -> 800 bytes .../idunn-runtime/rudp-route/expected.cc | Bin 1076 -> 1076 bytes .../rudp-route/presence-active.bin | Bin 922 -> 922 bytes .../rudp-route/presence-warming.bin | Bin 923 -> 923 bytes .../rudp-route/provider-identity.credential | Bin 688 -> 671 bytes .../service-stateful/activation-key.seed | 1 + .../service-stateful/activation.cc | Bin 0 -> 806 bytes .../service-stateful/expected.cc | Bin 0 -> 1401 bytes .../service-stateful/lease-other-target.cc | Bin 0 -> 1012 bytes .../service-stateful/lease-other-warming.cc | Bin 0 -> 1020 bytes .../idunn-runtime/service-stateful/lease.cc | Bin 0 -> 1020 bytes .../service-stateful/presence-active.bin | Bin 0 -> 1105 bytes .../service-stateful/presence-degraded.bin | Bin 0 -> 1107 bytes .../service-stateful/presence-warming.bin | Bin 0 -> 1034 bytes .../provider-identity.credential | Bin 0 -> 680 bytes .../idunn-runtime/service/activation-key.seed | 2 +- .../idunn-runtime/service/activation.cc | Bin 806 -> 806 bytes .../idunn-runtime/service/expected.cc | Bin 1308 -> 1308 bytes .../service/presence-active-below-minimum.bin | Bin 940 -> 940 bytes .../idunn-runtime/service/presence-active.bin | Bin 940 -> 940 bytes .../service/presence-warming.bin | Bin 941 -> 941 bytes .../service/provider-identity.credential | Bin 673 -> 672 bytes .../idunn-runtime/web/activation-key.seed | 3 +-- .../fixtures/idunn-runtime/web/activation.cc | Bin 798 -> 798 bytes .../fixtures/idunn-runtime/web/expected.cc | Bin 1067 -> 1067 bytes .../idunn-runtime/web/presence-active.bin | Bin 915 -> 915 bytes .../idunn-runtime/web/presence-warming.bin | Bin 916 -> 916 bytes .../web/provider-identity.credential | Bin 676 -> 682 bytes 29 files changed, 4 insertions(+), 4 deletions(-) create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation-key.seed create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/expected.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-target.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-warming.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease.cc create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-active.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-degraded.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-warming.bin create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/provider-identity.credential diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed index 1ae250bc..b0f0159c 100644 --- a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed @@ -1 +1 @@ -v$ñ´ØÃ/Š ¼Èá|Æuö«g4FÜK%k±€~qû \ No newline at end of file +¢_Î#Ÿ/ "Q0\ûiCâ]\Ê�¦‚†ó;ÛY¨ø„k \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc index 3676c985fb95c7105989d04f20473d4644699db5..57e2c86029f18c42beddce4b50be125380e8fcfc 100644 GIT binary patch delta 324 zcmWN|Jt)Ls9Ki9rQv^|5mpaKnxm~PuI=P?ucKtW=nn)z$Mxj{x${OK;AOS-p zFk>~45|F@L<0VHy1?TvR#c2gs}xOzCgbM^c_d7E!G zJGJ4x_UBXT9CA}`aN&9>wft8*3y(){v(?d&mHVFWq1}n&y-I8PB0k+pR38R<{{cce BZk7N5 delta 324 zcmWN}FGxc{9Ki7{xZ)FwD4I;uhYI(*|L5ODK{m7uEyKHecL<7LTN9>fC?Xa`g*9ys z7IYRFyfM_Utid2^wg?u%*S_Jyx0b18>Xq~Y0|1M-6_{$I!8m7#YME6W6DM)!z2V+|X@M+z%VapZ+^vm@FMWSJqn7J7IrMH#_s_k}yVK|0X BZY%%* diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/expected.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/expected.cc index 040ea0f69b70a5dcd3de806d7bc62e3d2000f294..878c090bc8ed0450e3418b0897d15ba3e4eddb71 100644 GIT binary patch delta 76 zcmWN>u@QhE3mewscsnj8f1fl-d7w=T?U? b$AnO`snc9~T%8D1y9O`-Q!O5HpXvPoI6W3X delta 76 zcmV~$yAgmO3;@uA^Nw*sh>&zP4nlqlxrhaOxq|QQy6bzCD=-F6x9G6g8;Y}bnA!w^ aI8D5FR0zs(8o^u~Z-rDiWw1do6+3P!7Pj?q$lF<0xW%}1qxgdpuQ0;DQT0H zF<^+v+00f-lFDKx^8b<5w(M%%qNpu(CMJvJoWL0AJN07i%b81Kts8@Dd-pG{w(pMQ ziAQc~;Qh~se=mR7IQ!>XV`KP0_ttt_znX9KKD`{<_51tmzVYVA*H^|DzFvJk(5puw z!5QO)1EX!u8WRS}j1oXqSFuyUgLYLR8cr#OOc*L-XFZZJo%+z+p?hyXKOQaCw-3%< z9NM~m{Qi$q&!+E;bY~6^(utmZ`sDm(bI5nL~a`)De0d3JcnEixkwjA1O;K6`#6^tMPOhr$iiq5Sq(u8 zv78`^Aead^f}5CT(Mv3(K&TdhOQRrHh4gRr`xd{&$2Z+I-F0_x*Z@EjHae-j@DP}T zLhF@8LMl*1&VVS`C6banfrhAL@Dgkwr&kW0JLRRZ{q_2RdSgrd{a7su$;4o@lRhys zgs8H?kTrTHNNh7gmYB$^9DFe;>HwM9VE~=xu9P>ICs?vYmm(|SF@dCnK?xUtq|lfn zB~@q$*4dh=bs;Irc~Ycdthm8a>%Z-Zq3RR=nIBA@nOk0c)moh2d1vfRWu<1= zQ#8(KTLj5A1nsg%iv^hf{>l}>G*Pt00YMlSHTYCyjDbYTom$`I)@{%BzwN)j*xUSc zu+_3JdKXqNZ@<|yyy<84?2q>Cj~kWdpPud$zh*|iT(~zo`*QCi{5rU?dpuMc*DhV} F{s*O)pYH$w diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin index ad4c0d9f1d15e506031aba710fe9223d3f672f0a..246e99cb2b4f3d875d4b9ab2a7e3c52a0151c603 100644 GIT binary patch delta 442 zcmWlVOGuSb6ou~}TpcuUkdXyaLc@e}_Id4t6h8@O1U)7Of#liyoKum5N)SR!ND`gI zy--9r5qby_7!?K8$nK;FDuPI87Bz@QH^Lh9_?xWJf^U6mv2(GrF}R;{vL4V%QsAOc zAiYLsm6sVv37ZXC(@Y>6LSDC)%wD+MG3X_pWnR$(G&)rd27scv8BM@+ zTFF9!GsX)CM%$D$MhuiPN&r<|m7NM6w5tkia*P}jVW^Cq^+?9F%EtHlryINbwyvIj zIDLEa<NHt8uZ|OpZ9qYF|dC_4GIpo)Zn2l zx*RTP&{PnK2*QDR22FuNQA0yRoJ2?k4gH$FpW!=v_^b@93@p^I7yuw)$w?hVfXEz` zw?Rpd9!nI&8N3(l5=w~yK?5lng9IDV>4VGnCWAC~q}{&Q?o`|F?$$_1Mh2Um42hW` zlFG)%tbJgF#5Q}#(kBcm$52ip9U(J2A3>*=vqiO-W69RLM65*c2_z;Tm2eSI3hgst zQl*Aqovk4)TwvBQCq&dDlceH(rBZad*QYDbI7wpwyR}ERf1l^x$rm!7pw9f^*$eCY z%f}-Q4V~)^|5=^cSsY&5d(ynqYOGGp-Q1WO9DV%dQ)8$3c31AI=I4iv;-F?YAQ@-0 zErVnmqjouX>q{{I{go?&X+*N+!Gkc4G=x-Uq=+KrZf$Ytet+hO&ir&w)wS`zSpT*) zzkDOV9y>Mu^~1>I#OT=7V;g&eM@y$)ZMOKq_mBO4uYPOc`K8vI?fuzbKdS!#kwBg{ diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/provider-identity.credential b/packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/provider-identity.credential index 8e1849bed2cbbf500423c8ae70cbb54bb1d8aff1..d8026bb447ee01203b4b6a3a9e1cf3ef1984f771 100644 GIT binary patch delta 285 zcmZ9EJxBs!9EVk~MM5a3poT&lM3n#gzmNA$#A*s7qQM-R?%unLS{rM)p$HNJ!nYXIbP2@;x$%XI!l&ujdQSac8@r{k^cLRAE6X^pCg<@LA1)IflS2;bxEn`p6Q4!Y U+*XQ-%^cY|wk!01+1QR5e|nN~TmS$7 delta 323 zcmZw9JxIe)7=>Z26dfHMD{U8>)Gs%;X>Jz<2mf&EEHueYMeQIc6hx{nI*5M(2f>PN z4$@AFh=b^O1lvJ~=wfkk5mXAgXu3O|7tV7Su79ih&BZ!VN9`Gb;4!%RE2)G22= z8WWCb>6ErK!HAo#EgW5E7D?_JDVtL|CndLBM+m{mwVD0Y7EvbqCt_GdgHPi$K?!{0 z3!7LT!N&l$;04=bI6`F@SGX^t7JN`atvjmZu|BjE$DN8ZRMG4~b9`p1h!fo66ZJ9N z;2Jgj;Jg=Qudn^NL>c0ll#$d8&E!loC_zD@mbifn)Ukqc9D8_$AL+s|4hnb)>JD~s sX`z8N{ATgysH0Il;sNh|lo2yj5-Jnf7WJR*EBRbO+6%Mu-eM^B2gKHq3jhEB diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation-key.seed b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation-key.seed new file mode 100644 index 00000000..491dbddb --- /dev/null +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation-key.seed @@ -0,0 +1 @@ +KýaŸz´-2‰Ë¡V>)ë»xìºÚÏ®¢T =/‰* \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation.cc new file mode 100644 index 0000000000000000000000000000000000000000..3d670ab64a880f82aa8a23f590cbf40a670e3be8 GIT binary patch literal 806 zcmbu5J!n%=6vq=090VO46kH@Kh?sEieeZr{$|hY(1(ncJ&UiStxD2vWl;hG!`geKn=-!JDGN2k*nMJOwW90E*3W4Ut%fMBbQ3mkV`b4<9Af@;JG z4}oJGf(#Ht99xDcRfhqn{qxv| z;p(^NmxqNy@#$cqJ~ygqzb_JqYeYHGMsgqFh*iKu5Mt063j!8Qz?juogh4>D#MqzB zLsDa2fF;y_4Qe;17q@SX6{9EphmGCK2N&+VTG_m@b-P}xcZTEpulBaS9A2B^h3n7Q b+R<~H!$$|soY?++?|Z|1-9Gtd_;K$qI`kv; literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/expected.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/expected.cc new file mode 100644 index 0000000000000000000000000000000000000000..8e96b29b011a97ffb9d2abad505584f2de0ea0ce GIT binary patch literal 1401 zcmbtU&5G1O5LWTx)hAfu#e<#c&R=J85Aw9UOK*@VM&( zi0&-QieAKr2>3Ae%u3vm%qZkb=TbjkRabS@(I?*Inlqk(U2CbpZpr-JSCKSjX~RJU zTto6wl$@!OX(3CybuPARyS?o?<7vouQ+MTSt2Vh5>>(?_imaV<*1g}xPeIitw}082 z@W!QpA~yC`^!&w}`R;Vy&KIY(R=|o%96(;98dNJd?Djf$uoECm%z1)wv_3Y*_}Pz} zw|-u`z1w*(UbkOo%<%(6MxwKZt~0sPUqt#~&Pa57GoiC4wz(`O`=*}{%u|~@Uf1){ zx}M!#_MhmJa!2CZPyx{4Y?dfii@dv^`W#QW8w50T!Q(XHNytObY}J%n6o4{dxz76Qcq6gg45pa|)c$E99f|LYi_HL+ z?;k1IXgJZlIyHYZnGlEC*nA`kL)TsYEhH=Hd~rU+WwT0r*`_cPd)$&6^Y=?L016T$ z%GC5ptA^`F!BQr|Y$P+yfE1JoylQ1rpIwn^S;<_^4ljwWe~ckDOAb{^7IL-DKCEm% a7p!EnHG9A3`VRRcai*GNvqT;ZDftC?QqFb& literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-target.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-target.cc new file mode 100644 index 0000000000000000000000000000000000000000..9f99abd088dd3391e03cdc3212121cea2fc80037 GIT binary patch literal 1012 zcmbtQ%Ze015Zv`EJoniiGwazkKj2L~hzCWMtg5V?hVGuFt9Mor|G`1QoA?PL2rGzQ zcF&&YZ)_j546^NEg1BWyWMsVl7|xp^P+0LI59^*68{EGAQpfYITb%Xlz&W2>^!30e z4O9L({(R%`+l`Y^HgeW>*Ssk57^9{8)N-*b=FEyae|8^npX+t^pY`$fsA#$M<9e}t z^7Q3)Hp{E+n-6*DncB1Z88^ASU_UFk6d+6qIPxLD@)s8X@c8=H_T8-VpF6vIc|}5- zQdyR$RfsmFz$`HOkYuvSdW*saS7{GcSj84mv6EoHVl<#Nk#=G-!UM4@_PWU2Z|cBz z>n>2=(Jq&R`~tPOit5ra#Wbe1&+f)o{10ZfWAk&DKA6pYeX z{t=ex9Ei!t8%$P+=%WKeF4zi9!pcQps(^(g gQE5=5v_VBAiINC{jnOia1~~qHbaedw>cQ&v4|jw^VE_OC literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-warming.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-warming.cc new file mode 100644 index 0000000000000000000000000000000000000000..cc21e54c91719e55e58befe66fc9b3e5e93c2f2a GIT binary patch literal 1020 zcmbtS%SyvQ6m9(q*IAo*XOhe${Q-C4LR=_P=5ePDBx%W{RT2NeqT){c22oHD-RRnN z|Hk+rQfT8Mhr2uXJmzt6rzUBsgc_n}%Ta;el+3Q56FtduZ(NKNTH8M=k`ntV3j0Mr ztt4MpGL@{FM%#IM>e#AACbmU}PS0sFb2ff=_pq?ZDF0`@%B~a{X0lp$dIyJRv&Jsx zv&(y17AUfDa*U~UEf&*6VWa4g0%b0cYIXs7-{S$m{`=b1O`~#Y)_ltj1r3=SaP&zS zD9w#gh?HoljBmK%k`u~R9EB1%uMhC+lft&K=a%$;R-vYF&c6uBs? zXK+a!Mq8pb0xBi=sEi5F0GAjtlyM{wViWl>$B-xiMh7BNz>M~dh&7XvP$WL%_^?>I r6eYUTzn;7$UKZ_t{)u}s80bRSB(0CZTB0`6Ez$kxbh@{1JHz!)1eH#i literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease.cc new file mode 100644 index 0000000000000000000000000000000000000000..b387f6e67d284a14f33e3cc85be640bccb5a74c3 GIT binary patch literal 1020 zcmbtS%W4!s6ixgJ*S)qU_tvv(ejqz>AubdNx2kSs8oGNzS7%hje{fK7Cw_w{D2Q%! z?Rx&kRzpi5=`7}Ocjul*JzjkX=gkl(tay=!b~z3y&UAG1eA%dH>Ri{+!o zFSfH?UT$B1%tO!Ap4Cse$z|q#QwN?EeHI{02{_JufaTv=0Kmhax8A&)RbH93JI*T- z+LX$&M6E)!DFtSM(T60HP1ai!Hn>WAu)->~h>D#A0~VtJt%|}`2NSe)$QNC+eXs> literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-active.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-active.bin new file mode 100644 index 0000000000000000000000000000000000000000..b1c33139c5ba7d8e8cb1d71bd3e64614386b23b7 GIT binary patch literal 1105 zcmbtTPe_zO990hm5;q^oB7RnsEq=#E}e^z`SY9Ig>{wP&$YnJ=+Lc5 zJb4li1)jo^f*>l)o7%yMg)#^tLV~)aVMw1ETY{bT4a{L?c<;@;H}4wSs_j|Ri*BG0 zr%MCHINyss{Ut18(P2*xO(D*uE9_A@E}`k|&tJhpIaS6|CGW7>Rn8eEWGVvWR7B20 z2o8}^Z(ZO40$897oL0gTU=Sft8lmPy5};lZA&e24)re@Fs2<(TXGgy1OsQz%d|xp| zYhtWU)QAYPmT+_-L>LHI6cVjg28j-eYd}GrA;CvRIUDd!8dYsfk=6TAM-j*cYoG)V^Sq)KsqckIb-`f1ajfBL_T zbcIe%kh1*`3)zJcW3`s`*ox1#RcUU4~7C}1&*|3n|Ga;T{1 z$z*~8F2FkGgaK|ji%$a%W+&ab@ao^S6zUA3iTkA74sMrJH|}8>54-=jIQIYhA;W-$$Bn z?yY8o5nF{*5}1ZagYqE+k33>p5u>dRm>8yLHrvU9mD+d#AZ7ADiE*=;p|Q1tui9Yc z&G^RtUoXy|+_QMr4Zgp9W^HtOJv0AlspZn@!(+>>!{cl#5TTPYkKgPr?Ti1eYepU-Iz|W< z^uh?CD0&qDp4Ul@N5klsyBva=Z*-HEW@MyqwX5@pvGBVis5@ zyte=ZJ7Ycd!V4oX5mrfNkRT!efpGweB8~)h95JRfQ=~zJn?${9GoQ(9!RoM}E7@Wp zjvHd6Ni>KMF$Phv-Ur~3Fu*t%B{d-BB~=0#wiMXu6^+ z5U>9ADVoIdjr8l;#mCZV7wU30*SH3660;Rs>P;r2z!NAMxED)F>BQvI&GZwxlzsNU zjYJjSsp7VJY|{gOS{h$3=RF7MP&;t-SXdm1Uan|X>$w(o@A`_(=v)p8Y4|66Z=?l@ z9gQaKrJzh0ODxlZ8cG6S3}fP=n2>Nnc&Zo}EV+@?SmPwFr#!PrS<1PP6ap)pb<)Zp zu%5^$aRNqa!MMlYlKcD4 z?MMu^*HcWhwaQ5@h!TMk(s}P4(10k3v@*&=WEg{9?I-buEA5yNoJT(tX)CSl!=Zr_`v$HJ&F>xE O*)cu3>&L-~!M5LP#AciT literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-warming.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-warming.bin new file mode 100644 index 0000000000000000000000000000000000000000..9634ec21965c0a46f18c63457cbc5d5a20ec5512 GIT binary patch literal 1034 zcmbtTJ!n%=7)_j{6vRytiX?;6OYXhz-M=hmQK9}-I@s2s+c2)Z~( zJJizRAZoQ}9n_&%D2O5$TognqVn7h>BseJQq7J65L<)7v`L=sM&Ue0h&V85I)k+ss z8BDDdXQEmd2W1$oL{Np$z-SRvDK2K}iA|IZ)>HuZ1|f}XCs^o<0>i#VWE|d#%k?{8`Ep)T=zP+abk+9RD!So4t~?y`K8%?J1h_^?8n bzppnY_uuBPZ+-7sSs2{&13f!-ZKU@PdMZ+@ literal 0 HcmV?d00001 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/provider-identity.credential b/packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/provider-identity.credential new file mode 100644 index 0000000000000000000000000000000000000000..3429906f256d59afca8712a91eb1360581602e80 GIT binary patch literal 680 zcmb7?yK59t6vo%i!XkxY5d@!w##!#2$9+ttTf|z_Mu@|mJNNDmOlBlIJ6Z8hkf0%I zkwP(QA*h9wWtv#XR|ysqjUZ?WwGaeby%M(+OmjGg^L>YNew^hy?UBBkH+odm-qnSw z$uqOy4U8)4f#>qF&g*OK>4~H}kt92kWFm2myiv93Hgsdpuhrc-+A}uNMCyPsE&>y3 zp6N_z5r*3O!bH?JsZcy(Tq!1HN=cN4RuQgwC;~w(f8RNbWh@=X3p}2}`boUR{R?wF zZ1-pIqhwhkT& z@W8dUuz6}9wy{#W+wAA`qTFN7_*3j0g zhDlxyYgH7g&Z}}~)3h3uS)z-oG%9tQr)p^2A*Ma%6Q6lRdcM3!XiP~=f^H}T3ArTU z3~@F2!}lv5jj)Pm4Q}9dCqF+shbNc!Ps�Õ8ÑÇ£rÆyÜà�&—ž@‚â± ç�ÜÌqM}‰ \ No newline at end of file +ö�„Bf®Õ=?ÞÀ�Z¹jÇâÏ&ŠÜæ3¦õÜŸf…mJ \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation.cc index b633e64c21e43688fba5f0946933b20b0da03d1c..3fa6a1f3f4885d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9=pa4@2OoQvBHY)x_nbu|Qmu4Qs%wS&I2T{IC^k!pLs0~wMzJ^u zx`>L!K?zRLf&mRg+6o0D5)4@CP!ybe7XSX%?*|{>{LuW+^@E3Ri88Zt7DxfB? zEYVsY*+f>-11ph2445<8g0O+Cm_b2+?xFK1y#l+ZUf)}PTRp%+r-WKL3C=_ifjsz# z=mmKVkdlXFNfizkIAswM7eD36qq9org@qUO^la$?Cj}s>RhhZ^^Hpc9apuUzt-nv! zx4f^8O+0;heBjZ?xz96S+p9O$?k|tL+j)6Y?@yz)GQ8vU!{)Q;^~S}!dH$TAuCmoU;_!t%m_tBR?+xS;P8Jk7!VqqMh1wPQf^gfwAY`V8-KpBbg8{G zS)01@ZG5n|^>P1N|4sGw%J&OXAG(vxQ@c9N(zcP)i~D9j4eUNQoKJKczb1}###Y;d F{{X|HrojLJ diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active.bin index 1f13b519925596e9b77619edbbd991d2321f5b30..d28b1349f8a9ebaa5d5536d8b5407273e36d7bde 100644 GIT binary patch delta 444 zcmWNMO-of#6hQ9_%OEI(Y9M8S?+v1obN1fnYw+ShVXrT0+Q`n?_Z%ezgCZ0M(g#6M z)Fp@rtw%%-R0wL&D2-mu!W={xL`d`l9GM{Dovq1&wPrhKJ0JI-3E)K1+F5cE*nkcy zH;`K`l(&e$T2hEI304$=Jxd5cS{nqCF5$}Q>q8!tK3)_jim#(5jppDfNrYrAdlMx| z3o)Y0a}4BS08GfjVhne;-xr4_tFKJM``M{nq^LdS7kz)l_}##>AcJZ5P+@SF^Y0{JX0=J6d1Pep<>_ z8WeQ|8=0+S>omID9J*VzIug!>~9S^JD z_YW*@KKnU3^LpRL!NK|e)!n!H%=RDGCJ%q^zSnhN#TNa2bM;?@MkM%1_6`|dLsCIliP5v@cE!&~kn30g>+6d5Lk*hTUy zVqppqi3q90CLlTk!=T{c0wO^REyczns4#K){o3=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m! z`@`|R!sY5tZWH&o7>nOH$!_)HLyugP*O0!M#WU(Sz&Bpe9KD01MmWxy2Bl(>TgI5gu@j$5aZZ XN!;aIX-X(Jh%%^hJH&sr7Im{f0hn|8 diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation-key.seed b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation-key.seed index 1f8ff352..7b6d37ff 100644 --- a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation-key.seed +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation-key.seed @@ -1,2 +1 @@ -c$…Jp[vcϽ|½Ô@ ž×í†`JÛûd -Í_z3Í3¢ \ No newline at end of file +¯ÂOd×f¯l*oµ‘ÀFªv‰n�hLûÑpšS´p \ No newline at end of file diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc index 00c3c07fe4835b043b3eb018a11aa82dc52faabf..3931baf2d0ad2e084e2704913f368f46605cef11 100644 GIT binary patch delta 325 zcmWN~zbnLH9Kdmx>no@LtU~+2E=M0`~x;u@9DL?%b9Yfx{}H}<{h)1qtp_D0kmjC)ZT0Gh8yNVa)T-g zXO$-FlE_Ii6hvHWrQ`N(DlS_LF(ybFI3a3>DhWn`4vGQ;E~G#UsH`U7T47X-aT8HS zX>>hZ>zt|%^fhg{$Y=Z=Fc}Mw5*EX4bba2RU*FG1UA`29>Cz>|aG#%7%vWa;16?VDn=i$s z7_eE@cc#>lB0m@93>Jf~eE)#gZ$Y1WGI0MXPn^30)P#)#atR;loiH12@(^~ z&IpW|p;T$Cz)SDF`&I2Mjlb3A zRx%@7mkYPwg~liucwMixm+#vjx%X%%`#jB#8kwG<=3-Ykx%P7SG?ncb9$f9a-uo^0 F{sSiua76$B diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/expected.cc b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/expected.cc index 748cc83dc11de7479ac6e80fcb4d8d49f79eb59a..dbf7153b5b59ff258a410787f85a7f7695945346 100644 GIT binary patch delta 76 zcmV~$!4-fY2msL6^Wr#(fN-l(0A-=Z@X}mO(f_;d`X1%-IoU>t7%LKElO}0ukbw~k ZbU{mX!tTSH5Q6wnm delta 76 zcmWN{u@S%^2mrv#**Fdg3UtXRfJ~GzY%*7-NWT7EcYTg>+GrvkX`KZPAf}Gw6i;G; Z=wT*EBbu^n$Wol}Pc)w1(fPj0`vEWg6-odA diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin index cefcf1d0f05aedf619ed6d6bb5b67de23d286e83..37edbf6569b2e60ee4819cef5745c6445523a4aa 100644 GIT binary patch delta 441 zcmWlUU1-f=9DvU$b2PhAa>0d0(^?(9zxVfhKYmj>x!_P5xL8VVbXG3#Up?1P&(o^3DmQlR4I&2NBcWyu$pL!w zDRYbr(UB7oG&!_c1#j8-ATt>)P#Htamh-}%lOs+lU2Qf8o9)%jx$&CdY^-obqa}l= zh@`?0fdGYGk$`ZH0kxAR7*r7;I0`Of7F#m zmbW~3`Qpcp?!^;FPIcDozxDX*+kFGQM+cu?Z}fE<&)=PsyT=Z4#i&6!W|y=US>&#OBV(;qM0{`+&o)uoMn^V5sls@vxWs(0(h>O+&)Cbu43S{|-! G>iQ4Da+wtX delta 441 zcmWNNO^D4=7{>oMG8UtdYCS{ha^q#MLg=tobd!yN@$#s)V zsf)%{YRbY`DRG<9j7W_d5lW4f?3lX6**`tc^ZT_2+5Z^k9+bDWcU4vE^v2Iu-4sD&9A|^ZvWxT?mZ)`@1L%|X?$o7Hiy@SEBQm7c(k^2>ErcA!@pX;QV%*R2T`X` zWT6o$YimiNL0JqHZN-*x0z@HH!bB-hFze(M7yN|1`qc8m^Pl_o9zQqp^~~LTc@8%B ztJiODT>M1e`-jH9Eg$L3zMP)lbyn>A{9@tiwjHCV?mf7D=j4{de=bbv`K_C(|AX_J ALI3~& diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin index 375131d00f282c71e7b67679f28c03c0bc167f71..55409b8dfb48737e1978b3c92261076c18e2bded 100644 GIT binary patch delta 441 zcmWlUOGuPa7(nMI%7Qj7q8xBxMnM$a?|%33eNi^JsUV^UXj#GBCxK~5k5weIQ&4bf zU{--3;@TG>(rzH=fr}z=XA3t$n_5f#!dV~AX?3-_<_50^5rgnipzv$95@wpK9{=k2S{9y_Vc`DXKCbN*2C^F&Q>wj`W2NXjB=rKH9X zK>-T0F9G2k0~#l7u&5(Ia4PuV60v~1@Tw>#eT>H0K;#T7Z4?ktcI;#hDug6CNyzNA zLSG6=D@oq6jHx^kWp1%msTA{_TTd!WDN3z@JGF_S&G*z;{We4Ob+xp7VfuID+OIRm zcVDjc9oYHV+c^E{#}QxUQ@i6mlY1lg#)iJHjohw3UA=T}WAE?t%O{R**F2`2C0d64 zH4aEJIRZ{(lYlZ*qX#6<78Da^5<b&NEl;#_qRzvuTnkJYjqqd%0HNHgWU zoXzN>kvT~>I~SWsBPY8^%Iza39G6D3TIAAWtr(`_;(nvCgo<11DIypvkTKFuMH8)$(nv-? zh*n5N+!>$$1}8MjNr6Ut5Z*LC7e!-pc==}0j{%h8ZdmQyo|?F^`s3^K-S_Q-m3PmY z3)7d5Jb_~5ajRJQIk~a^X6@hAZ2!OXXj!-`Z8 z7J`bDWl7CqQpPwTwdC1Q)|PE)%YbDFW|u-Yp7%~Py>=F0RVy7i@= znLl{B`f%>w;!!%*+1eRwr+f3A-;>8@KRmcz^?r3fjg`$ccP;F1zi$7nua1qD{{i1~ BmC67B diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/web/provider-identity.credential b/packages/cultnet-ts/test/fixtures/idunn-runtime/web/provider-identity.credential index 52b1b8e809059949d9b7af89dab19973f0b1e529..2e617139cb114b951bfdc3fca179a02ff872830c 100644 GIT binary patch delta 297 zcmZXOyGjE=07cD8w6d^Ku@WC((CEzU?Ci{bf?yGdAx$9rEG#5JB$7rY(Z*&a3U-1T zBtoh{&`L|u3pNW9P;4x11i?ZFr zt!x&!+;x4Xd`1K17+iNuhf0Gp>6nUnKGy}2f$`ioF^M`J(MsW`i1t!BgU;w`4)-Hy z;s)3Ft|A=6U1fL?Ux+f*crjhVAujN?f|;vzoMC%bSRDHCb6!7U(}Wnq2u6qego}(9F;fmfKR-mSHW)l)f$x2$8Z+F+H=lAqG51a;$QtiG*v9RM;bG5iIHO3t23TiW5 z5F#yZy0*(4*RTyDsT6|ghAA~}J6y6wu3N-2bzxf$)gAk-Z3rJY8z-nHaDhYQQ4H>S z2&nc@EX|aom4uyA{maa z3GAUfQ&4>GIT9mA%(PUEX(rXZ(+cqrX~j+!rsi;m12k|mk47JU@I08o6ZY|f>&VCw tnn44uOLtR^6%@*?h&>uD;gJS>y From 8072314b7c47c20f594d7585250296949299904e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:11:48 +0200 Subject: [PATCH 37/64] cultnet-ts: the Idunn signer owns the reported health and warming proofs The signer holds the last reported health, starting at warming, and gains reportHealth(state). sign(detail), answerRouteObservation(request) and the Odin publisher's publish(detail) no longer take a state, so the route answer and the Odin publish cannot disagree and a fresh signer cannot answer active. Every warming presence the signer signs becomes a valid write-lease target; the publisher's recordPublishedWarming is deleted. Tests now assert every committed stateless vector, dead ones included. Co-Authored-By: Claude Sonnet 5 --- .../src/idunn-odin-presence-publisher.ts | 11 +- .../cultnet-ts/src/idunn-runtime-authority.ts | 42 +++++--- .../test/idunn-runtime-authority.test.ts | 100 ++++++++++++------ 3 files changed, 100 insertions(+), 53 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts b/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts index 8e13acb4..2e992658 100644 --- a/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts +++ b/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts @@ -5,7 +5,6 @@ import { encodeCultNetMessageForWire, parseCultNetMessage } from "./contracts"; import type { IdunnRuntimeSigner } from "./idunn-runtime-authority"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; -import type { RuntimePresenceHealth } from "./runtime-presence-health"; const ODIN_CAPABILITY = "odin.verse-rendezvous"; const MAX_LEASE_WAIT_ROUNDS = 720; @@ -14,7 +13,8 @@ export type IdunnRuntimePresencePublisher = { readonly runtimeId: string; readonly runtimeInstanceId: string; readonly requiresWriteLease: boolean; - publish(state: RuntimePresenceHealth["state"], detail: string): Promise; + /** Publishes the signer's presence in the health the signer reports. */ + publish(detail: string): Promise; waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; assertWriteLease(): Promise; }; @@ -44,15 +44,14 @@ export function createIdunnRuntimePresencePublisher( const connectionId = 0x0d1d0002; let messageSequence = 0; - const publish = async (state: RuntimePresenceHealth["state"], detail: string) => { - const signed = signer.sign(state, detail); + const publish = async (detail: string) => { + const signed = signer.sign(detail); messageSequence += 1; await publishDocument(endpoint, connectionId, { schemaVersion: "cultnet.document_put_raw.v0", messageId: `runtime-presence:${signer.authority.expected.target}:${signer.runtimeInstanceId}:${messageSequence}`, document: signed.document, }); - if (state === "warming") signer.recordPublishedWarming(signed.canonicalSha256); return signed.canonicalSha256; }; @@ -65,7 +64,7 @@ export function createIdunnRuntimePresencePublisher( if (!signer.requiresWriteLease) return ""; let warmingSequence = 0; while (!signal?.aborted) { - await publish("warming", "waiting-for-process-write-lease"); + await publish("waiting-for-process-write-lease"); warmingSequence += 1; try { return signer.assertWriteLease(); diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index 47e132b3..bb217ed0 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -82,25 +82,30 @@ export type SignedRuntimePresence = { /** * Signs this launch's runtime presence and answers Idunn's route challenge. It * owns no network: Odin publication, if a service wants it, is a separate - * consumer of `sign`. + * consumer of `sign`. The signer is the single owner of the reported health: + * it starts `warming`, the app moves it with `reportHealth`, and every + * presence it signs, however it is carried, states that health. */ export type IdunnRuntimeSigner = { readonly authority: IdunnRuntimeAuthority; readonly runtimeId: string; readonly runtimeInstanceId: string; readonly requiresWriteLease: boolean; - /** Signs one presence document. Every call takes the next publisher sequence. */ - sign(state: RuntimePresenceHealth["state"], detail: string): SignedRuntimePresence; + /** Records the app's health. Until the first call the signer reports `warming`. */ + reportHealth(state: RuntimePresenceHealth["state"]): void; + /** + * Signs one presence document in the reported health. Every call takes the + * next publisher sequence; every warming presence signed becomes a valid + * write-lease target. + */ + sign(detail: string): SignedRuntimePresence; /** * Answers an Idunn route challenge from local authority alone: signs a fresh - * presence in the given state, with no network. The caller supplies the - * app's current health (`warming` until first healthy). + * presence in the reported health, with no network. */ - answerRouteObservation(request: CultNetSnapshotRequestMessage, state: RuntimePresenceHealth["state"]): CultNetRawDocumentRecord; - /** Reads Idunn's write lease and checks it names this incarnation and a warming proof this process published. */ + answerRouteObservation(request: CultNetSnapshotRequestMessage): CultNetRawDocumentRecord; + /** Reads Idunn's write lease and checks it names this incarnation and a warming presence this signer signed. */ assertWriteLease(): string; - /** Marks a warming presence as accepted by its consumer, making it a valid lease target. */ - recordPublishedWarming(canonicalSha256: string): void; }; export type IdunnRuntimeSignerOptions = { @@ -219,6 +224,7 @@ export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): Id const { authority } = options; const expected = authority.expected; let sequence = 0; + let health: RuntimePresenceHealth["state"] = "warming"; const recentWarmingProofs: string[] = []; const assertWriteLease = () => { @@ -231,7 +237,8 @@ export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): Id return prefixedSha256(Buffer.from(encode(lease))); }; - const sign = (state: RuntimePresenceHealth["state"], detail: string): SignedRuntimePresence => { + const sign = (detail: string): SignedRuntimePresence => { + const state = health; const writeLeaseSha256 = state === "warming" || !expected.writeLeaseRequired ? null : assertWriteLease(); sequence += 1; const signed = signIdunnRuntimePresence(authority, { @@ -242,6 +249,10 @@ export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): Id publisherSequence: sequence, observedAtUnixMillis: Date.now(), }); + if (state === "warming") { + recentWarmingProofs.push(signed.canonicalSha256); + if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift(); + } return { canonicalSha256: signed.canonicalSha256, document: { @@ -262,8 +273,11 @@ export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): Id runtimeId: expected.runtimeId, runtimeInstanceId: authority.activation.runtimeInstanceId, requiresWriteLease: expected.writeLeaseRequired, + reportHealth(state) { + health = state; + }, sign, - answerRouteObservation(request, state) { + answerRouteObservation(request) { if (!request.messageId || request.messageId.trim() !== request.messageId) throw new Error("Idunn route observation requires a message id."); if ((request.schemaIds && !request.schemaIds.includes(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA)) || (request.recordKeys && !request.recordKeys.includes(expected.target)) @@ -271,13 +285,9 @@ export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): Id || request.shardEpoch !== undefined) { throw new Error("Idunn route observation does not request this runtime presence document."); } - return sign(state, `route-observation:${request.messageId}`).document; + return sign(`route-observation:${request.messageId}`).document; }, assertWriteLease, - recordPublishedWarming(canonicalSha256) { - recentWarmingProofs.push(canonicalSha256); - if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift(); - }, }; } diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 1639b9aa..1df6e98f 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -25,7 +25,7 @@ const CHALLENGE: CultNetSnapshotRequestMessage = { messageId: "route-challenge-1", }; -type FixtureSet = "web" | "service" | "rudp-route"; +type FixtureSet = "web" | "service" | "rudp-route" | "service-stateful"; function fixtureFile(set: FixtureSet, name: string): Buffer { return fs.readFileSync(path.join(FIXTURES, set, name)); @@ -50,7 +50,11 @@ function expectedFacts(set: FixtureSet) { } /** Points the process at one Rust-written bundle and its inherited descriptors, as Idunn's systemd unit would. */ -function openAuthority(context: TestContext, set: FixtureSet, options: { machineId?: "etc" | "dbus" } = {}): IdunnRuntimeAuthority { +function openAuthority( + context: TestContext, + set: FixtureSet, + options: { machineId?: "etc" | "dbus"; lease?: string } = {}, +): IdunnRuntimeAuthority { const facts = expectedFacts(set); const originalEnvironment = { ...process.env }; context.after(() => { @@ -59,7 +63,8 @@ function openAuthority(context: TestContext, set: FixtureSet, options: { machine }); process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = path.join(FIXTURES, set); process.env.GAMECULT_IDUNN_CANDIDATE_BIND = facts.candidate; - delete process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE; + if (options.lease) process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(FIXTURES, set, options.lease); + else delete process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE; process.env.LISTEN_PID = String(process.pid); process.env.LISTEN_FDS = "2"; process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; @@ -78,8 +83,8 @@ function openAuthority(context: TestContext, set: FixtureSet, options: { machine return loadIdunnRuntimeAuthorityFromEnvironment(facts.target, facts.healthContract); } -function signerFor(context: TestContext, set: FixtureSet, capacityDelta = 0) { - const authority = openAuthority(context, set); +function signerFor(context: TestContext, set: FixtureSet, capacityDelta = 0, lease?: string) { + const authority = openAuthority(context, set, { lease }); const capabilities = expectedFacts(set).capabilities.map((capability) => ({ ...capability, capacity: capability.capacity + capacityDelta })); return createIdunnRuntimeSigner({ authority, capabilities }); } @@ -107,7 +112,7 @@ for (const set of ["web", "service", "rudp-route"] as const) { test("a target that declares no Odin dependency opens and answers Idunn's challenge without one", (context) => { assert.equal(expectedFacts("web").odinEndpoint, undefined); const signer = signerFor(context, "web"); - assert.ok(signer.answerRouteObservation(CHALLENGE, "warming").payload.byteLength > 0); + assert.ok(signer.answerRouteObservation(CHALLENGE).payload.byteLength > 0); }); test("finds the machine-id at the dbus path when /etc/machine-id is absent, as the Rust protector does", (context) => { @@ -127,35 +132,44 @@ test("rejects a credential file holding more than one envelope", (context) => { ); }); -test("answers a route challenge byte for byte as the Rust-verified vectors, in the state the app reports", (context) => { +function presenceSlot(document: { payload: Uint8Array }, slot: number): unknown { + return (decode(document.payload) as unknown[])[slot]; +} + +// Every committed vector is asserted, dead ones included. Stateless sets sign at sequence 1. +for (const set of ["web", "service", "rudp-route"] as const) { + test(`${set}: a fresh signer answers warming, and after reportHealth('active') answers active, byte for byte as the Rust-verified vectors`, (context) => { + freezeClock(context); + assert.deepEqual(Buffer.from(signerFor(context, set).answerRouteObservation(CHALLENGE).payload), fixtureFile(set, "presence-warming.bin")); + const active = signerFor(context, set); + active.reportHealth("active"); + assert.deepEqual(Buffer.from(active.answerRouteObservation(CHALLENGE).payload), fixtureFile(set, "presence-active.bin")); + }); +} + +test("a shortfall signs the vector Rust correlates to the typed capacity disagreement", (context) => { freezeClock(context); - const signer = signerFor(context, "web"); - const warming = signer.answerRouteObservation(CHALLENGE, "warming"); - assert.deepEqual(Buffer.from(warming.payload), fixtureFile("web", "presence-warming.bin")); - assert.equal((decode(warming.payload) as unknown[])[RUNTIME_PRESENCE_SLOT.state], "warming"); - const second = signer.answerRouteObservation(CHALLENGE, "active"); - assert.equal((decode(second.payload) as unknown[])[RUNTIME_PRESENCE_SLOT.publisherSequence], 2); - // Sequence 2 cannot match a vector written at sequence 1; sign the same fields from a fresh signer. - const fresh = signerFor(context, "web"); - assert.deepEqual(Buffer.from(fresh.answerRouteObservation(CHALLENGE, "active").payload), fixtureFile("web", "presence-active.bin")); + const signer = signerFor(context, "service", -1); + signer.reportHealth("active"); + assert.deepEqual(Buffer.from(signer.answerRouteObservation(CHALLENGE).payload), fixtureFile("service", "presence-active-below-minimum.bin")); }); -test("a service with an Odin dependency signs the Rust-verified vectors, including a shortfall Rust correlates to a capacity disagreement", (context) => { +test("the signer owns the reported health: a fresh signer is warming, reportHealth moves it, the sequence keeps counting", (context) => { freezeClock(context); - assert.deepEqual( - Buffer.from(signerFor(context, "service").answerRouteObservation(CHALLENGE, "active").payload), - fixtureFile("service", "presence-active.bin"), - ); - assert.deepEqual( - Buffer.from(signerFor(context, "service", -1).answerRouteObservation(CHALLENGE, "active").payload), - fixtureFile("service", "presence-active-below-minimum.bin"), - ); + const signer = signerFor(context, "web"); + const first = signer.answerRouteObservation(CHALLENGE); + assert.equal(presenceSlot(first, RUNTIME_PRESENCE_SLOT.state), "warming"); + assert.equal(presenceSlot(signer.sign("detail"), RUNTIME_PRESENCE_SLOT.state), "warming"); + signer.reportHealth("active"); + const third = signer.answerRouteObservation(CHALLENGE); + assert.equal(presenceSlot(third, RUNTIME_PRESENCE_SLOT.state), "active"); + assert.equal(presenceSlot(third, RUNTIME_PRESENCE_SLOT.publisherSequence), 3); }); test("answers locally: synchronously, with no socket opened", (context) => { const sockets = context.mock.method(dgram, "createSocket"); const signer = signerFor(context, "web"); - const answer = signer.answerRouteObservation(CHALLENGE, "warming"); + const answer = signer.answerRouteObservation(CHALLENGE); assert.equal(typeof (answer as unknown as { then?: unknown }).then, "undefined"); assert.equal(sockets.mock.callCount(), 0); }); @@ -169,7 +183,7 @@ test("refuses a challenge that does not ask for this runtime's presence", (conte { ...CHALLENGE, schemaIds: ["another.schema"] }, { ...CHALLENGE, shardId: "shard-1" }, ]; - for (const request of cases) assert.throws(() => signer.answerRouteObservation(request, "active"), /route observation/); + for (const request of cases) assert.throws(() => signer.answerRouteObservation(request), /route observation/); }); async function startOdinPeer(context: TestContext, endpoint: string) { @@ -222,7 +236,7 @@ test("the Odin publisher publishes the signer's document to the endpoint Expecte const signer = signerFor(context, "service"); const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint }); - await publisher.publish("warming", "accepted presence"); + await publisher.publish("accepted presence"); assert.equal(peer.received[0]?.schemaVersion, "cultnet.document_put_raw.v0"); const published = decode(peer.received[0]!.document.payload) as unknown[]; assert.equal(published[RUNTIME_PRESENCE_SLOT.state], "warming"); @@ -230,15 +244,18 @@ test("the Odin publisher publishes the signer's document to the endpoint Expecte assert.equal(peer.responseAck, 2, "the response data packet must acknowledge the publisher's reliable schema packet"); peer.reject = true; - await assert.rejects(publisher.publish("active", "denied presence"), /Odin rejected runtime presence: test admission denied/); + signer.reportHealth("active"); + await assert.rejects(publisher.publish("denied presence"), /Odin rejected runtime presence: test admission denied/); assert.equal(peer.failure, undefined, peer.failure?.message); }); test("the Odin publisher leaves a capability shortfall to the Rust correlation instead of refusing to publish", async (context) => { const endpoint = expectedFacts("service").odinEndpoint!; const peer = await startOdinPeer(context, endpoint); - const publisher = createIdunnRuntimePresencePublisher({ signer: signerFor(context, "service", -1), endpoint }); - await publisher.publish("active", "below minimum"); + const signer = signerFor(context, "service", -1); + signer.reportHealth("active"); + const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint }); + await publisher.publish("below minimum"); const capabilities = (decode(peer.received[0]!.document.payload) as unknown[])[RUNTIME_PRESENCE_SLOT.capabilities] as unknown[][]; assert.equal(capabilities[0]![3], expectedFacts("service").capabilities[0]!.capacity - 1); }); @@ -253,3 +270,24 @@ test("the Odin publisher takes only the endpoint Expected names", (context) => { /does not match Idunn Expected dependency authority/, ); }); + +test("the route answer and the Odin publish report the same state, because the signer owns it", async (context) => { + const endpoint = expectedFacts("service").odinEndpoint!; + const peer = await startOdinPeer(context, endpoint); + const signer = signerFor(context, "service"); + const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint }); + + await publisher.publish("first"); + assert.equal(presenceSlot(peer.received[0]!.document, RUNTIME_PRESENCE_SLOT.state), "warming"); + assert.equal(presenceSlot(signer.answerRouteObservation(CHALLENGE), RUNTIME_PRESENCE_SLOT.state), "warming"); + + signer.reportHealth("active"); + await publisher.publish("second"); + assert.equal(presenceSlot(peer.received[1]!.document, RUNTIME_PRESENCE_SLOT.state), "active"); + assert.equal(presenceSlot(signer.answerRouteObservation(CHALLENGE), RUNTIME_PRESENCE_SLOT.state), "active"); + // One sequence across both carriers. + assert.deepEqual( + [1, 2].map((index) => presenceSlot(peer.received[index - 1]!.document, RUNTIME_PRESENCE_SLOT.publisherSequence)), + [1, 3], + ); +}); From 67b8ae3eda1915a86aecb1befbbbb8676be44696 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:13:28 +0200 Subject: [PATCH 38/64] cultnet-ts: freeze the Idunn authority and allow one signer per authority The loaded authority is deeply frozen (bind, health contract, Expected, Activation, identities), so a caller cannot steer what the signer signs; the typed Buffers that could not be frozen are dropped (Expected canonical bytes, Activation public key kept as hex only for the load-time comparison). A second createIdunnRuntimeSigner on the same authority throws, so two signers cannot emit sequence 1 under one runtimeInstanceId. Tests: stateful set pinned against Rust (warming, active, degraded), lease accepted for a route-answered warming, refused for another warming and another target, one signer per authority, frozen authority. Co-Authored-By: Claude Sonnet 5 --- .../cultnet-ts/src/idunn-runtime-authority.ts | 41 ++++++++--- .../test/idunn-runtime-authority.test.ts | 72 +++++++++++++++++++ 2 files changed, 104 insertions(+), 9 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index bb217ed0..cd942cec 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -30,6 +30,7 @@ const ACTIVATION_ID_DOMAIN = Buffer.from("idunn.runtime-activation.id.v1\0", "ut const CULTCACHE_STORE_FORMAT = "cultcache.store.v1"; const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex"); const MAX_RECENT_WARMING_PROOFS = 64; +const authoritiesWithSigner = new WeakSet(); const authorityKeys = new WeakMap(); type ExpectedIncarnation = { @@ -51,7 +52,6 @@ type ExpectedIncarnation = { route: { routeId: string; transport: string; stableEndpoint: string; candidateEndpoint: string } | null; capabilities: Array<{ capability: string; schema: string; compatibility: string; minimumCapacity: number }>; dependencies: Array<{ kind: string; capability: string; schema: string; compatibility: string; providerEndpoint: string | null }>; - canonicalBytes: Buffer; canonicalSha256: string; }; @@ -61,18 +61,27 @@ type RuntimeActivation = { runtimeId: string; runtimeInstanceId: string; activationSignerIdentityId: string; - activationSignerPublicKey: Buffer; + activationSignerPublicKeyHex: string; canonicalSha256: string; }; -export type IdunnRuntimeAuthority = { +type DeepReadonly = T extends readonly (infer U)[] + ? readonly DeepReadonly[] + : T extends object ? { readonly [K in keyof T]: DeepReadonly } : T; + +/** + * What Idunn admitted for this launch. Deeply frozen at load: bind, health + * contract, Expected, Activation and identities are read-only for the life of + * the process, so no caller can steer what the signer signs. + */ +export type IdunnRuntimeAuthority = DeepReadonly<{ expected: ExpectedIncarnation; activation: RuntimeActivation; providerSignerIdentityId: string; activationSignerIdentityId: string; boundEndpoint: string; processWriteLeasePath?: string; -}; +}>; export type SignedRuntimePresence = { document: CultNetRawDocumentRecord; @@ -152,7 +161,7 @@ export function loadIdunnRuntimeAuthorityFromEnvironment( const activationPublicKey = rawEd25519PublicKey(crypto.createPublicKey(activationPrivateKey)); const activationSignerIdentityId = sha256Hex(Buffer.concat([ACTIVATION_ID_DOMAIN, activationPublicKey])); if (activationSignerIdentityId !== activationValue.activationSignerIdentityId - || !activationPublicKey.equals(activationValue.activationSignerPublicKey)) { + || activationPublicKey.toString("hex") !== activationValue.activationSignerPublicKeyHex) { throw new Error("Idunn activation credential does not match the root-provisioned Activation witness."); } @@ -167,7 +176,7 @@ export function loadIdunnRuntimeAuthorityFromEnvironment( throw new Error("Provider identity does not match Idunn Expected."); } - const authority: IdunnRuntimeAuthority = { + const authority: IdunnRuntimeAuthority = deepFreeze({ expected: expectedValue, activation: activationValue, providerSignerIdentityId: expectedValue.expectedSignerIdentityId, @@ -176,7 +185,7 @@ export function loadIdunnRuntimeAuthorityFromEnvironment( ...(process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] ? { processWriteLeasePath: process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] } : {}), - }; + }); authorityKeys.set(authority, { providerPrivateKey, activationPrivateKey }); return authority; } @@ -220,8 +229,15 @@ export function signIdunnRuntimePresence( }; } +/** + * One signer per loaded authority: the publisher sequence and the warming proofs + * are the signer's, and a second signer would restart the sequence under the + * same runtimeInstanceId. + */ export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): IdunnRuntimeSigner { const { authority } = options; + if (authoritiesWithSigner.has(authority)) throw new Error("This Idunn runtime authority already has a signer."); + authoritiesWithSigner.add(authority); const expected = authority.expected; let sequence = 0; let health: RuntimePresenceHealth["state"] = "warming"; @@ -291,6 +307,14 @@ export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): Id }; } +function deepFreeze(value: T): T { + if (value !== null && typeof value === "object" && !Object.isFrozen(value)) { + for (const child of Object.values(value)) deepFreeze(child); + Object.freeze(value); + } + return value; +} + function readAuthorityRecord(filePath: string, type: string, schemaId: string): { payload: Uint8Array } { const decoded = decode(fs.readFileSync(filePath)); if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { @@ -360,7 +384,6 @@ function decodeExpected(payload: Uint8Array): ExpectedIncarnation { route, capabilities: decodeExpectedCapabilities(values[16]), dependencies: decodeExpectedDependencies(values[17]), - canonicalBytes, canonicalSha256: prefixedSha256(canonicalBytes), }; } @@ -388,7 +411,7 @@ function decodeActivation(payload: Uint8Array): RuntimeActivation { runtimeId: string(values[2], "Activation runtime id"), runtimeInstanceId: string(values[3], "Activation instance id"), activationSignerIdentityId, - activationSignerPublicKey: Buffer.from(publicKey), + activationSignerPublicKeyHex: Buffer.from(publicKey).toString("hex"), canonicalSha256: prefixedSha256(canonicalBytes), }; } diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 1df6e98f..5f34c02c 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -291,3 +291,75 @@ test("the route answer and the Odin publish report the same state, because the s [1, 3], ); }); + +// The lease-bound set: Rust issued lease.cc naming presence-warming.bin's digest, and presence-active.bin +// and presence-degraded.bin carry that lease's digest. +const STATEFUL = "service-stateful" as const; + +function statefulSigner(context: TestContext, lease = "lease.cc") { + return signerFor(context, STATEFUL, 0, lease); +} + +test("stateful: warming, active and degraded match the Rust-verified vectors byte for byte, active and degraded bound to Rust's lease", (context) => { + freezeClock(context); + const signer = statefulSigner(context); + assert.deepEqual(Buffer.from(signer.answerRouteObservation(CHALLENGE).payload), fixtureFile(STATEFUL, "presence-warming.bin")); + signer.reportHealth("active"); + const active = signer.answerRouteObservation(CHALLENGE); + assert.deepEqual(Buffer.from(active.payload), fixtureFile(STATEFUL, "presence-active.bin")); + assert.match(String(presenceSlot(active, RUNTIME_PRESENCE_SLOT.writeLeaseSha256)), /^sha256-[0-9a-f]{64}$/); + + const degraded = statefulSigner(context); + degraded.answerRouteObservation(CHALLENGE); + degraded.reportHealth("degraded"); + assert.deepEqual(Buffer.from(degraded.answerRouteObservation(CHALLENGE).payload), fixtureFile(STATEFUL, "presence-degraded.bin")); +}); + +test("a warming answered on the route becomes a lease target: Rust's lease naming it is accepted", (context) => { + freezeClock(context); + const signer = statefulSigner(context); + assert.throws(() => signer.assertWriteLease(), /does not match the current Expected incarnation/, "no warming signed yet"); + signer.answerRouteObservation(CHALLENGE); + assert.equal(signer.assertWriteLease(), presenceSlot({ payload: fixtureFile(STATEFUL, "presence-active.bin") }, RUNTIME_PRESENCE_SLOT.writeLeaseSha256)); +}); + +for (const [lease, reason] of [["lease-other-warming.cc", "names another warming digest"], ["lease-other-target.cc", "names another target"]] as const) { + test(`a lease that ${reason} is refused, and the signer cannot sign active under it`, (context) => { + freezeClock(context); + const signer = statefulSigner(context, lease); + signer.answerRouteObservation(CHALLENGE); + assert.throws(() => signer.assertWriteLease(), /does not match the current Expected incarnation/); + signer.reportHealth("active"); + assert.throws(() => signer.answerRouteObservation(CHALLENGE), /does not match the current Expected incarnation/); + }); +} + +test("one signer per loaded authority", (context) => { + const authority = openAuthority(context, "web"); + const capabilities = expectedFacts("web").capabilities; + createIdunnRuntimeSigner({ authority, capabilities }); + assert.throws(() => createIdunnRuntimeSigner({ authority, capabilities }), /already has a signer/); +}); + +test("the loaded authority is frozen: the bind, contract, Expected, Activation and identities cannot change, and the signer signs the loaded endpoint", (context) => { + freezeClock(context); + const authority = openAuthority(context, "web"); + const loaded = expectedFacts("web"); + const open = authority as unknown as { [key: string]: any }; + const mutations: Array<[string, () => void]> = [ + ["boundEndpoint", () => { open.boundEndpoint = "http://127.0.0.1:1"; }], + ["providerSignerIdentityId", () => { open.providerSignerIdentityId = "forged"; }], + ["activationSignerIdentityId", () => { open.activationSignerIdentityId = "forged"; }], + ["expected.healthContract", () => { open.expected.healthContract = "forged"; }], + ["expected.target", () => { open.expected.target = "forged"; }], + ["expected.canonicalSha256", () => { open.expected.canonicalSha256 = "forged"; }], + ["expected.route.candidateEndpoint", () => { open.expected.route.candidateEndpoint = "http://127.0.0.1:1"; }], + ["expected.capabilities[0].minimumCapacity", () => { open.expected.capabilities[0].minimumCapacity = 0; }], + ["expected.capabilities.push", () => { open.expected.capabilities.push({}); }], + ["activation.runtimeInstanceId", () => { open.activation.runtimeInstanceId = "forged"; }], + ["activation.canonicalSha256", () => { open.activation.canonicalSha256 = "forged"; }], + ]; + for (const [name, mutate] of mutations) assert.throws(mutate, TypeError, name); + const signer = createIdunnRuntimeSigner({ authority, capabilities: loaded.capabilities }); + assert.equal(presenceSlot(signer.answerRouteObservation(CHALLENGE), RUNTIME_PRESENCE_SLOT.boundEndpoint), loaded.candidate); +}); From 06d250070a9ece3b62a5e6565ea1fc84bf654513 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:13:37 +0200 Subject: [PATCH 39/64] cultnet-ts: add an idunn-runtime subpath export that does not load dgram `cultnet-ts/idunn-runtime` exposes the signer and loader alone. Web apps import it instead of the package root, which also carries the Odin publisher and node:dgram. The root export is unchanged. Test loads both under a stubbed dgram: the subpath loads, the root fails. Co-Authored-By: Claude Sonnet 5 --- packages/cultnet-ts/package.json | 5 ++++ .../test/idunn-runtime-authority.test.ts | 24 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/packages/cultnet-ts/package.json b/packages/cultnet-ts/package.json index f33b8f83..e72a10aa 100644 --- a/packages/cultnet-ts/package.json +++ b/packages/cultnet-ts/package.json @@ -15,6 +15,11 @@ "require": "./dist/contracts.js", "default": "./dist/contracts.js" }, + "./idunn-runtime": { + "types": "./dist/idunn-runtime-authority.d.ts", + "require": "./dist/idunn-runtime-authority.js", + "default": "./dist/idunn-runtime-authority.js" + }, "./authority": { "types": "./dist/cultmesh-authority.d.ts", "require": "./dist/cultmesh-authority.js", diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 5f34c02c..075738be 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -1,5 +1,6 @@ import { test, type TestContext } from "node:test"; import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; import dgram from "node:dgram"; import fs from "node:fs"; import path from "node:path"; @@ -363,3 +364,26 @@ test("the loaded authority is frozen: the bind, contract, Expected, Activation a const signer = createIdunnRuntimeSigner({ authority, capabilities: loaded.capabilities }); assert.equal(presenceSlot(signer.answerRouteObservation(CHALLENGE), RUNTIME_PRESENCE_SLOT.boundEndpoint), loaded.candidate); }); + +// A web app must be able to import the signer without pulling the Odin publisher and dgram. +function loadUnderDgramStub(modulePath: string): string { + const script = [ + 'const Module = require("node:module");', + "const load = Module._load;", + 'Module._load = function (request, ...rest) { if (request === "dgram" || request === "node:dgram") throw new Error("dgram was loaded"); return load.call(this, request, ...rest); };', + "try { require(process.argv[1]); process.stdout.write(\"loaded\"); } catch (error) { process.stdout.write(\"failed: \" + error.message); }", + ].join("\n"); + const run = spawnSync(process.execPath, ["-e", script, modulePath], { encoding: "utf8" }); + assert.equal(run.status, 0, run.stderr); + return run.stdout; +} + +test("the idunn-runtime subpath loads the signer and loader without loading dgram; the package root does load it", () => { + const subpath = require.resolve("cultnet-ts/idunn-runtime"); + assert.equal(loadUnderDgramStub(subpath), "loaded"); + assert.equal(loadUnderDgramStub(require.resolve("cultnet-ts")), "failed: dgram was loaded"); + const exported = require(subpath) as Record; + assert.equal(typeof exported.createIdunnRuntimeSigner, "function"); + assert.equal(typeof exported.loadIdunnRuntimeAuthorityFromEnvironment, "function"); + assert.equal(exported.createIdunnRuntimePresencePublisher, undefined); +}); From 322b7c815ae64f2aa008c344dc4a995f345c3a20 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:15:40 +0200 Subject: [PATCH 40/64] cultnet-ts test: read the signed document, not the SignedRuntimePresence wrapper Co-Authored-By: Claude Sonnet 5 --- packages/cultnet-ts/test/idunn-runtime-authority.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 075738be..560f5933 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -160,7 +160,7 @@ test("the signer owns the reported health: a fresh signer is warming, reportHeal const signer = signerFor(context, "web"); const first = signer.answerRouteObservation(CHALLENGE); assert.equal(presenceSlot(first, RUNTIME_PRESENCE_SLOT.state), "warming"); - assert.equal(presenceSlot(signer.sign("detail"), RUNTIME_PRESENCE_SLOT.state), "warming"); + assert.equal(presenceSlot(signer.sign("detail").document, RUNTIME_PRESENCE_SLOT.state), "warming"); signer.reportHealth("active"); const third = signer.answerRouteObservation(CHALLENGE); assert.equal(presenceSlot(third, RUNTIME_PRESENCE_SLOT.state), "active"); From addaf10c22259f90867f60d4f1120592f3825113 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:19:42 +0200 Subject: [PATCH 41/64] Sweep the Q4 reversal into the C1 spec: overrides soft-drift Co-Authored-By: Claude Opus 5.5 --- docs/document-variants-cut.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/document-variants-cut.md b/docs/document-variants-cut.md index a52f0e83..f8d67880 100644 --- a/docs/document-variants-cut.md +++ b/docs/document-variants-cut.md @@ -243,18 +243,23 @@ Adds: - **`Validate` resolves** every admitted variant and every dependent of an admitted or evicted base, in base-first order, against the post-batch set. It refuses, naming keys: a cycle; a missing base; a different concrete type; a global type; an evicted base with - surviving variants; an override slot missing on the type (Q4); a value that will not - decode; a variant whose resolved `[CultName]` equals its base's (R6); a plain `Upsert` at a - variant key (Q1a). + surviving variants; a variant whose resolved `[CultName]` equals its base's (R6); a plain + `Upsert` at a variant key (Q1a). **Not refused (Q4 c, operator 2026-09-29):** an override + naming a slot the type no longer has, or holding a value that no longer decodes into the + member's type, soft-drifts exactly as the same member would on a plain record under + `cultcache-schema-compatibility.md`. It is ignored with a warning naming the variant and + the member, and the variant inherits the base value. One rule, the existing soft-drift + path, never a variant-specific one. - **`Apply` re-resolves dependents** in the same hold. Each emits `Updated` and is re-indexed. A base change stamps no dependent `storedAt`. - **Header**: the store writes `v2` iff it holds a variant (Q5a) and reads `v1` and `v2`. - **Refusals** (Q6): `DirectoryMessagePackBackingStore` push and commit of a variant; `CultNetDocumentRegistry` row building for a variant; `CultMesh.ReadSingleFileDocument` of a variant key. -- **Contracts**: the variant record section in `cultcache-persistence-format.md`; the Q4 - exception in `cultcache-schema-compatibility.md`; a "variants: C# resolves; others refuse" - row in `runtime-parity-scope.md`. +- **Contracts**: the variant record section in `cultcache-persistence-format.md`; one + sentence in `cultcache-schema-compatibility.md` saying overrides soft-drift like members + (Q4 c, no exception); a "variants: C# resolves; others refuse" row in + `runtime-parity-scope.md`. Authority map: - Owner: `CultCache.Validate`/`Apply` owns the resolved view. From 4cdc8864a258358790f9fd72e0801286397de258 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:20:11 +0200 Subject: [PATCH 42/64] Sweep Q3 (ids everywhere, minted on load) into the C2 spec Co-Authored-By: Claude Opus 5.5 --- docs/document-variants-cut.md | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/document-variants-cut.md b/docs/document-variants-cut.md index f8d67880..8abb8f87 100644 --- a/docs/document-variants-cut.md +++ b/docs/document-variants-cut.md @@ -58,7 +58,7 @@ Other Body facts that shape the map: | --- | --- | --- | --- | | Variant record | its own `CultRecordKey`, minted like any record; same `schemaId` as its type | created, re-overridden, rebased, removed; never converted to or from a plain record implicitly (Q1) | author through Studio or the variant write API; the cache validates | | Base reference | the base's key, in the record's variant slot | changed only by an explicit rebase; a base cannot be deleted while it has variants, unless the same batch rebases or removes them | author; the cache refuses a cycle, a missing base, a different concrete type, a global type | -| Override entry | `(op, path, id, value)`; op is Set, Insert or Remove | added by editing; removed by clearing; survives base edits while its path resolves | author; the cache refuses unresolvable entries (Q2, Q4) | +| Override entry | `(op, path, id, value)`; op is Set, Insert or Remove | added by editing; removed by clearing; survives base edits while its path resolves | author; the cache refuses entries a base edit strands (Q2); an entry whose member left the type soft-drifts with a warning (Q4 c) | | Member path | a sequence of `(slot, elementId)` steps; `slot` is the MessagePack `[Key]`; `elementId` is `""` unless the step enters an object-list element | a type change can invalidate it | the type's owner (slot authority); ids by the element's creator | | Element id | a `[CultElementId]` string member on an object-list element type; `""` means unset | minted by the cache on write when unset; copied unchanged into variants; a moved element is a new element | cache mints it; it is never retargeted | | Resolved view | `CultStoredDocument.Document` for a variant key | recomputed inside the hold that admits the variant, or any base on its chain | the cache only; never persisted, never written back (Q1) | @@ -298,11 +298,13 @@ projects, Caching.Tests, the Networking test filter, the interop peer. ### C2. C# element identity and nested paths (Set, Insert, Remove) Adds: -- **`[CultElementId]`** (a string member) and **`[CultVariants]`** (a document-type opt-in, - Q3b). The registry refuses an opted-in type with an id-less object element type reachable - through a list, union bases included. -- **Minting**: on write, the cache mints ids for unset ids in opted-in types, and refuses a - duplicate id within one list. +- **`[CultElementId]`** (a string member). **Ids everywhere, not opt-in (Q3, operator + 2026-09-29): there is no `[CultVariants]` attribute.** The C# registry requires an id member + on every object element type reachable through a list in any registered document type, + union bases included, and refuses a type that lacks one. +- **Minting**: on write, the cache mints ids for unset ids in every type, and refuses a + duplicate id within one list. A store written before ids existed loads, and its ids are + minted on its first write (minted on load, per the operator's rollout ruling). - **Path steps below top level.** - **Insert** anchored after an id, where `""` means the head. An inserted run sits immediately after its anchor and before base elements added there later. @@ -311,7 +313,12 @@ Adds: - **Q2a refusal**: a base commit that orphans an override is refused. - **Q7**: whole-member Set for dictionaries, scalar lists and arrays. - **`CultCache.MintElementIds()`**: the one-shot rewrite for existing stores (ruling 1). It - upserts every record of opted-in types through the normal path. + upserts every record that has an unset id through the normal path. +- **The consumer sweep (Q3 rollout).** About 28 consumers carry list-element types, and each + needs an id member before it can take the CultLib that requires one. C2 ships the + requirement. Self schedules the per-repo sweep, one small type edit per consumer, before + those consumers bump. C2 lists the element types it finds per consumer, as data for that + sweep. Keeps: the C1 format unchanged. C2 fills path shapes that C1 refused. @@ -322,8 +329,9 @@ Verification: variant, path and id. - A Set on a removed element is refused. - Minting is idempotent. -- An opted-in type without ids is refused; a type that has not opted in is untouched. This is - the negative for Q3b's blast radius. +- A registered type with an id-less list element type is refused, naming the type and member. +- A store written before ids loads, and its ids are minted exactly once on first write + (idempotent). - A C#-written nested-override fixture joins `contracts/cultcache/`. Command: `dotnet test tests/GameCult.Caching.Tests`. From a5edd976d0ff1f74408c0d4b5551b694593ff100 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:20:30 +0200 Subject: [PATCH 43/64] Sweep Q3 into C4: no per-type opt-in Co-Authored-By: Claude Opus 5.5 --- docs/document-variants-cut.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/document-variants-cut.md b/docs/document-variants-cut.md index 8abb8f87..3136b586 100644 --- a/docs/document-variants-cut.md +++ b/docs/document-variants-cut.md @@ -372,7 +372,7 @@ checked by the operator in the editor. ### C4. Aetheria adoption (Aetheria repo, its own cut, after the release) - Bump the package to `v1.5.0`. -- Add `[CultVariants]` to `HullData`, `EquippableItemData`'s concrete types and `ConsumableItemData`. +- Add `[CultElementId]` to every list-element type Aetheria's documents carry (ids everywhere, Q3). There is no per-type opt-in. - Add `[CultElementId]` to `BehaviorData` (base) and `HardpointData`. - Run `MintElementIds` once over `GameData/Aetheria.cc`. - AetherDb migrations skip variants or use the variant API (Q1a). From 5ed9dbbcb8562b552bcf4f49cd2f731464665348 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:26:10 +0200 Subject: [PATCH 44/64] cultnet-ts: stop exporting signIdunnRuntimePresence; document two limits The function took state and lease digest from the caller, so anyone holding the authority could sign active without reportHealth or assertWriteLease. It is now private to the signer. Test: the subpath and root do not expose it. Docs: waitForWriteLease throws out of publish if health is already non-warming; MAX_RECENT_WARMING_PROOFS=64 is a recorded limit. Co-Authored-By: Claude Sonnet 5 --- packages/cultnet-ts/src/idunn-odin-presence-publisher.ts | 5 +++++ packages/cultnet-ts/src/idunn-runtime-authority.ts | 4 +++- packages/cultnet-ts/test/idunn-runtime-authority.test.ts | 2 ++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts b/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts index 2e992658..3713363d 100644 --- a/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts +++ b/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts @@ -15,6 +15,11 @@ export type IdunnRuntimePresencePublisher = { readonly requiresWriteLease: boolean; /** Publishes the signer's presence in the health the signer reports. */ publish(detail: string): Promise; + /** + * Publishes warming presence until Idunn's lease names one. Call it before + * `reportHealth('active')`: once the signer reports a non-warming health, + * `publish` inside this loop throws (it needs the lease) instead of polling. + */ waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; assertWriteLease(): Promise; }; diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index cd942cec..7f7b882f 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -29,6 +29,8 @@ const PROVIDER_PROTECTOR_CONTEXT = "gamecult-provider-health-identity-v1"; const ACTIVATION_ID_DOMAIN = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8"); const CULTCACHE_STORE_FORMAT = "cultcache.store.v1"; const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex"); +// Limit: more than this many warmings signed between Idunn's observation and +// assertWriteLease would push the leased one out and refuse a valid lease. const MAX_RECENT_WARMING_PROOFS = 64; const authoritiesWithSigner = new WeakSet(); const authorityKeys = new WeakMap(); @@ -195,7 +197,7 @@ export function loadIdunnRuntimeAuthorityFromEnvironment( * Signs the fixed Idunn v2 positional runtime-presence contract with the * provider identity and this launch's Idunn-issued activation key. */ -export function signIdunnRuntimePresence( +function signIdunnRuntimePresence( authority: IdunnRuntimeAuthority, fields: Omit, ): { presence: RuntimePresenceHealth; payload: Uint8Array; canonicalSha256: string } { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 560f5933..b5c9236a 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -386,4 +386,6 @@ test("the idunn-runtime subpath loads the signer and loader without loading dgra assert.equal(typeof exported.createIdunnRuntimeSigner, "function"); assert.equal(typeof exported.loadIdunnRuntimeAuthorityFromEnvironment, "function"); assert.equal(exported.createIdunnRuntimePresencePublisher, undefined); + assert.equal(exported.signIdunnRuntimePresence, undefined); + assert.equal((require("cultnet-ts") as Record).signIdunnRuntimePresence, undefined); }); From 5b538aaf07a73bb1b1d99384d8af0d12d670e395 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:29:41 +0200 Subject: [PATCH 45/64] Answer chunk requests whose string fields are nil A C# caller that leaves ChunkHash, MessageId or RecordKey null writes msgpack nil; the reference reads it back as null, treats it as blank and answers found:false. Rust now decodes nil as blank in content chunk requests, so those requests are answered with the reference bytes instead of dropped. Three nil vectors from the reference server are judged by decoding them in Rust. Record two content-plane limits in the parity scope. Co-Authored-By: Claude Sonnet 5 --- .../cultmesh/content-vectors.cs-written.json | 30 +++++++++++++++++ docs/runtime-parity-scope.md | 5 +++ packages/cultnet-rs/src/contracts.rs | 15 +++++++-- packages/cultnet-rs/tests/content.rs | 32 +++++++++++++++++-- .../CultMeshContentVectorTests.cs | 13 ++++++++ 5 files changed, 90 insertions(+), 5 deletions(-) diff --git a/contracts/cultmesh/content-vectors.cs-written.json b/contracts/cultmesh/content-vectors.cs-written.json index a0ae2fe2..0eaaaece 100644 --- a/contracts/cultmesh/content-vectors.cs-written.json +++ b/contracts/cultmesh/content-vectors.cs-written.json @@ -130,6 +130,36 @@ "kind": "response", "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK12ZWN0b3ItZG91YmxlpWZvdW5kw6ljaHVua0hhc2jZR3NoYTI1Njo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I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4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1\u002Bf4CBgoOEhYaHiImKi4yNjo\u002BQkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3\u002BDh4uPk5ebn6Onq6\u002Bzt7u/w8fLz9PX29/j5\u002BgABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6O6VlcnJvcqA=" }, + { + "label": "nil_message_id.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkwKljaHVua0hhc2jZQDU5OTNhYzYwNDA3ZTg2NjAxODczYmMzOGVlNmY4ZGIzZWE5MTJlOTg3NjFjYjU1OGFiOTc5NWRiMzA2YjQ3NGOpcmVjb3JkS2V52U9tZXNoOmNkbjpjaHVuazo1OTkzYWM2MDQwN2U4NjYwMTg3M2JjMzhlZTZmOGRiM2VhOTEyZTk4NzYxY2I1NThhYjk3OTVkYjMwNmI0NzRjsWV4cGVjdGVkU2l6ZUJ5dGVzzRLf" + }, + { + "label": "nil_message_id.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZKClZm91bmTCqWNodW5rSGFzaNlANTk5M2FjNjA0MDdlODY2MDE4NzNiYzM4ZWU2ZjhkYjNlYTkxMmU5ODc2MWNiNTU4YWI5Nzk1ZGIzMDZiNDc0Y6lzaXplQnl0ZXMAp3BheWxvYWTEAKVlcnJvctlISW52YWxpZERhdGFFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgcmVxdWVzdCByZXF1aXJlcyBhIG1lc3NhZ2UgaWRlbnRpdHku" + }, + { + "label": "nil_hash.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkr3ZlY3Rvci1uaWwtaGFzaKljaHVua0hhc2jAqXJlY29yZEtleaCxZXhwZWN0ZWRTaXplQnl0ZXNk" + }, + { + "label": "nil_hash.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK92ZWN0b3ItbmlsLWhhc2ilZm91bmTCqWNodW5rSGFzaKCpc2l6ZUJ5dGVzAKdwYXlsb2FkxAClZXJyb3LZQkFyZ3VtZW50RXhjZXB0aW9uOiBIYXNoIG11c3QgYmUgbm9uLWVtcHR5LiAoUGFyYW1ldGVyICdDaHVua0hhc2gnKQ==" + }, + { + "label": "nil_record_key.request", + "kind": "request", + "messagePackBase64": "ha1zY2hlbWFWZXJzaW9u2SFjdWx0bWVzaC5jb250ZW50X2NodW5rX3JlcXVlc3QudjGpbWVzc2FnZUlkrnZlY3Rvci1uaWwta2V5qWNodW5rSGFzaNlAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMKlyZWNvcmRLZXnAsWV4cGVjdGVkU2l6ZUJ5dGVzZA==" + }, + { + "label": "nil_record_key.response", + "kind": "response", + "messagePackBase64": "h61zY2hlbWFWZXJzaW9u2SJjdWx0bWVzaC5jb250ZW50X2NodW5rX3Jlc3BvbnNlLnYxqW1lc3NhZ2VJZK52ZWN0b3ItbmlsLWtleaVmb3VuZMKpY2h1bmtIYXNo2UAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwqXNpemVCeXRlcwCncGF5bG9hZMQApWVycm9y2TZGaWxlTm90Rm91bmRFeGNlcHRpb246IENvbnRlbnQgY2h1bmsgaXMgbm90IGF2YWlsYWJsZS4=" + }, { "label": "response_hash_last_digit", "kind": "response", diff --git a/docs/runtime-parity-scope.md b/docs/runtime-parity-scope.md index 6710c2dd..4ea8f845 100644 --- a/docs/runtime-parity-scope.md +++ b/docs/runtime-parity-scope.md @@ -85,6 +85,11 @@ to speak CultNet or participate in CultMesh. session the client already holds (see `src/GameCult.Mesh/docs/transport-planes.md`); it has no authenticated content connector, so it claims no TCP+TLS or QUIC content path. + Recorded limits: a caller that passes `max_bytes = u64::MAX` to `fetch_content` gets an unbounded + body, because the reference refuses artifacts over `int.MaxValue` bytes and Rust bounds them only by the + caller's cap. + `normalize_hash` matches the `sha256:` prefix ASCII-case-insensitively while C# `OrdinalIgnoreCase` may + also match non-ASCII forms (for example `Å¿ha256:`); unprobed, and it affects hostile input only. ## Expansion Work Outside The Current Parity Claim diff --git a/packages/cultnet-rs/src/contracts.rs b/packages/cultnet-rs/src/contracts.rs index 0925215e..cc50171d 100644 --- a/packages/cultnet-rs/src/contracts.rs +++ b/packages/cultnet-rs/src/contracts.rs @@ -1073,9 +1073,9 @@ fn parse_raw_cultnet_schema_message(input: &rmpv::Value) -> Result Ok(CultNetMessage::ContentChunkRequest { - message_id: require_legacy_string(get("messageId"), "messageId")?, - chunk_hash: require_legacy_string(get("chunkHash"), "chunkHash")?, - record_key: require_legacy_string(get("recordKey"), "recordKey")?, + message_id: legacy_string_or_nil(get("messageId"), "messageId")?, + chunk_hash: legacy_string_or_nil(get("chunkHash"), "chunkHash")?, + record_key: legacy_string_or_nil(get("recordKey"), "recordKey")?, expected_size_bytes: require_legacy_i32(get("expectedSizeBytes"), "expectedSizeBytes")?, }), "cultmesh.content_chunk_response.v1" => Ok(CultNetMessage::ContentChunkResponse { @@ -1721,6 +1721,15 @@ fn require_legacy_bytes(value: Option<&rmpv::Value>, field_name: &str) -> Result Ok(URL_SAFE_NO_PAD.encode(bytes)) } +/// A string the reference reads back as null when its writer set it to null (msgpack nil), which its +/// handlers treat as blank. Only content chunk requests use it: they are answered, never dropped. +fn legacy_string_or_nil(value: Option<&rmpv::Value>, field_name: &str) -> Result { + match value { + Some(rmpv::Value::Nil) => Ok(String::new()), + other => require_legacy_string(other, field_name), + } +} + fn require_legacy_string(value: Option<&rmpv::Value>, field_name: &str) -> Result { let value = value .and_then(rmpv::Value::as_str) diff --git a/packages/cultnet-rs/tests/content.rs b/packages/cultnet-rs/tests/content.rs index b36ae5f4..178ebe3c 100644 --- a/packages/cultnet-rs/tests/content.rs +++ b/packages/cultnet-rs/tests/content.rs @@ -277,7 +277,11 @@ fn rust_written_vectors_are_current() { #[test] fn reference_vectors_encode_byte_identically() { let local = local_vectors(); - let reference = read_vectors("content-vectors.cs-written.json"); + // The nil-field vectors are bytes only the reference writes; `nil_fields_are_answered_as_blanks` judges them. + let reference: Vec<_> = read_vectors("content-vectors.cs-written.json") + .into_iter() + .filter(|(label, _, _)| !label.starts_with("nil_")) + .collect(); assert_eq!( reference.iter().map(|(l, _, _)| l.as_str()).collect::>(), local.iter().map(|v| v.label.as_str()).collect::>(), @@ -522,7 +526,7 @@ fn answer_serves_found_false_with_the_reference_error_spelling() { } judged += 1; } - assert_eq!(judged, 13); + assert_eq!(judged, 16); } #[test] @@ -615,6 +619,30 @@ fn a_bad_request_is_answered_never_dropped() { } } +// A caller that leaves a string null writes msgpack nil. The reference reads null, treats it as blank +// and answers; Rust decodes nil as blank so the same request gets the same answer, byte for byte. +#[test] +fn nil_fields_are_answered_as_blanks() { + let (_, chunks) = pack(&body()); + let store = store(&chunks); + let reference = read_vectors("content-vectors.cs-written.json"); + for (name, spelling) in [ + ("nil_message_id", "InvalidDataException: Content chunk request requires a message identity."), + ("nil_hash", "ArgumentException: Hash must be non-empty. (Parameter 'ChunkHash')"), + ("nil_record_key", "FileNotFoundException: Content chunk is not available."), + ] { + let find = |suffix: &str| { + let label = format!("{name}.{suffix}"); + reference.iter().find(|(l, _, _)| *l == label).expect("vector").2.clone() + }; + let request_bytes = find("request"); + assert!(request_bytes.contains(&0xc0), "{name}: the reference wrote nil"); + let answer = answer_content_chunk_request(&unwire(&request_bytes).expect("nil decodes"), lookup_in(&store)); + assert_eq!(wire(&answer), find("response"), "{name}: answer differs from the reference's"); + assert_eq!(response_of(&answer).4, spelling, "{name}"); + } +} + // F3: metadata keeps the order it was read in and refuses a duplicate key. #[test] fn manifest_metadata_keeps_wire_order_and_refuses_a_duplicate_key() { diff --git a/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs b/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs index 6c5763bb..2fa26aa1 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs @@ -174,6 +174,19 @@ public sealed class CultMeshContentVectorTests AddAnswer("answer_record_key_case", Request("vector-key-case", last.ChunkHash, key.ToUpperInvariant(), last.SizeBytes)); AddAnswer("answer_blank_record_key", Request("vector-key-blank", last.ChunkHash, " ", last.SizeBytes)); AddAnswer("answer_double_prefix", Request("vector-double", "sha256:sha256:" + last.ChunkHash, string.Empty, last.SizeBytes)); + + // A caller that leaves a string null writes msgpack nil; the reference reads it back as null and + // answers. These are judged by Rust decoding the reference's bytes (Rust never writes nil), so + // they stay out of the label-matched mirror set. + void AddNilAnswer(string name, CultMeshContentChunkRequestMessage request) + { + vectors.Add(new Vector(name + ".request", "request", Reencode(request))); + vectors.Add(new Vector(name + ".response", "response", Reencode(Answer(content, request)))); + } + + AddNilAnswer("nil_message_id", Request(null, last.ChunkHash, key, last.SizeBytes)); + AddNilAnswer("nil_hash", Request("vector-nil-hash", null, string.Empty, 100)); + AddNilAnswer("nil_record_key", Request("vector-nil-key", new string('0', 64), null, 100)); AddResponse("response_hash_last_digit", new CultMeshContentChunkResponseMessage { MessageId = "vector-digit", From dbc87b94471053da04445a72a7e830352e3b959c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:51:53 +0200 Subject: [PATCH 46/64] C# core: variant records, top-level Set overrides, resolution in the admitting hold A variant record stores [baseKey, overrides[]] in record slot 4 and an empty payload; the cache resolves it against its base inside the hold that admits it or any record on its base chain, and re-resolves dependents in the same Apply, so a base change reaches its variants with contiguous sequences and no stamp. Plain Upsert at a variant key is refused (Flatten is the explicit way); cycle, missing base, different concrete type, evicted base with survivors and a name that shadows the base are refused naming the keys. Overrides of a dropped slot or an undecodable value are ignored with a warning and reported as compatible drift. The store writes cultcache.store.v2 only when it holds a variant and reads v1 and v2. The codec pair CultInspectorModel took becomes CultCodec, shared with the cache, which needs it to clone documents and overlay override values. The directory store, CultMesh single-file reads and CultNet row building refuse a variant by name until their own cuts. Co-Authored-By: Claude Sonnet 5 --- docs/runtime-parity-scope.md | 3 + .../CultCacheMessagePack.cs | 21 +- .../CultDocumentMessagePackSerialization.cs | 160 +++++- .../DirectoryMessagePackBackingStore.cs | 11 + .../Contracts/cultcache-persistence-format.md | 36 +- .../cultcache-schema-compatibility.md | 7 + src/GameCult.Caching/CultCache.cs | 475 +++++++++++++++++- src/GameCult.Caching/CultInspectorModel.cs | 20 +- src/GameCult.Caching/CultVariants.cs | 95 ++++ .../CultMeshSingleFileDocuments.cs | 13 + .../CultNetDocumentRegistry.cs | 11 +- 11 files changed, 797 insertions(+), 55 deletions(-) create mode 100644 src/GameCult.Caching/CultVariants.cs diff --git a/docs/runtime-parity-scope.md b/docs/runtime-parity-scope.md index 46b1e77b..97fa1b48 100644 --- a/docs/runtime-parity-scope.md +++ b/docs/runtime-parity-scope.md @@ -15,6 +15,9 @@ Cross-runtime parity has three layers: without translation folklore. Every store reader refuses, by name, a header or record slot it does not understand (vectors: `tests/vectors/document-variants-c0`). + Document variants: C# resolves them (`cultcache.store.v2`); every other runtime, + CultMesh single-file reads, the directory store and CultNet refuse a variant by name + (vector written by C#: `tests/vectors/document-variants-c1`). - Feature parity: each runtime must expose the CultCache/CultNet/CultMesh surfaces needed for its intended role, with unsupported production-server ownership called out plainly. diff --git a/src/GameCult.Caching.MessagePack/CultCacheMessagePack.cs b/src/GameCult.Caching.MessagePack/CultCacheMessagePack.cs index e1a68c12..4fa55076 100644 --- a/src/GameCult.Caching.MessagePack/CultCacheMessagePack.cs +++ b/src/GameCult.Caching.MessagePack/CultCacheMessagePack.cs @@ -19,13 +19,19 @@ namespace GameCult.Caching.MessagePack public static class CultCacheMessagePack { - // The inspection model over this codec. Values serialize without the document guard but with their owning document's - // options, resolvers included, so dictionary keys compare by the bytes the store writes; clones deserialize as - // registered documents. - public static CultInspectorModel CreateInspectorModel(CultDocumentRegistry registry) => new CultInspectorModel( - registry, + // The store's encoding as one port. Values serialize without the document guard but with their owning document's + // options, resolvers included, so dictionary keys compare by the bytes the store writes; a document type + // deserializes as a registered document, a member type as itself. + public static CultCodec CreateCodec(CultDocumentRegistry registry) => new CultCodec( (value, type, document) => global::MessagePack.MessagePackSerializer.Serialize(type, value, CultDocumentMessagePackSerialization.OptionsFor(document.Assembly)), - (type, bytes) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, bytes, registry)); + (type, document, bytes) => type == document + ? CultDocumentMessagePackSerialization.DeserializeUntyped(type, bytes, registry) + : global::MessagePack.MessagePackSerializer.Deserialize(type, bytes, CultDocumentMessagePackSerialization.OptionsFor(document.Assembly)), + CultDocumentMessagePackSerialization.OverlaySlots); + + // The inspection model over that codec. + public static CultInspectorModel CreateInspectorModel(CultDocumentRegistry registry) => + new CultInspectorModel(registry, CreateCodec(registry)); // Opening hydrates. A consumer that wants a fresh store removes the records it does not keep, upserts, and // flushes; the atomic replace does the rest. @@ -37,7 +43,8 @@ namespace GameCult.Caching.MessagePack } options ??= new CultCacheOpenOptions(); - var cache = new CultCache(options.Registry) + var registry = options.Registry ?? CultDocumentRegistry.Shared; + var cache = new CultCache(registry, CreateCodec(registry)) { FlushAttachedStoresOnDispose = options.FlushOnDispose }; diff --git a/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs b/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs index bb62d2ed..ef1b4092 100644 --- a/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs +++ b/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs @@ -1,6 +1,7 @@ using System; using System.Buffers; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Linq; using System.Reflection; using GameCult.Caching; @@ -30,8 +31,8 @@ public sealed class CultDocumentResolver : IFormatterResolver public static class CultDocumentMessagePackSerialization { - private const string SingleFileFormatVersion = "cultcache.store.v1"; private const int PersistedRecordFieldCount = 4; + private const int VariantRecordFieldCount = 5; private const int SchemaCatalogEntryFieldCount = 7; private const int SchemaCatalogMemberFieldCount = 8; private const int StoreSnapshotFieldCount = 3; @@ -95,6 +96,49 @@ public static class CultDocumentMessagePackSerialization ?? throw new InvalidOperationException($"MessagePack returned null for Cult document type {type.FullName}."); } + /// + /// Replaces slots of a serialized document payload (a MessagePack array indexed by slot) with already-encoded member + /// values, leaving every other slot byte for byte as it was. A slot past the end extends the array with nil. + /// + public static byte[] OverlaySlots(byte[] payload, IReadOnlyList> slots) + { + var reader = new MessagePackReader(payload); + if (reader.NextMessagePackType != MessagePackType.Array) + { + throw new InvalidOperationException("A document payload is a MessagePack array; this one is not, so its slots cannot be overridden."); + } + + var count = reader.ReadArrayHeader(); + var elements = new List(count); + for (var index = 0; index < count; index++) + { + var start = reader.Position; + reader.Skip(); + elements.Add(reader.Sequence.Slice(start, reader.Position).ToArray()); + } + + foreach (var (slot, value) in slots) + { + while (elements.Count <= slot) + { + elements.Add(new byte[] { 0xc0 }); + } + + elements[slot] = value; + } + + var buffer = new ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(elements.Count); + foreach (var element in elements) + { + writer.WriteRaw(element); + } + + writer.Flush(); + return buffer.WrittenSpan.ToArray(); + } + public static byte[] SerializePersistedRecord(CultPersistedRecord record) { var buffer = new global::System.Buffers.ArrayBufferWriter(); @@ -141,7 +185,7 @@ public static class CultDocumentMessagePackSerialization if (fieldCount > 0) { snapshot.FormatVersion = reader.ReadString() - ?? throw new NotSupportedException("Store snapshot declares no format version; this runtime reads " + SingleFileFormatVersion + " only."); + ?? throw new NotSupportedException("Store snapshot declares no format version; this runtime reads " + CultPersistedStoreSnapshot.FormatV1 + " and " + CultPersistedStoreSnapshot.FormatV2 + "."); } if (fieldCount > 1) @@ -172,24 +216,110 @@ public static class CultDocumentMessagePackSerialization return snapshot; } - /// Refuses a single-file snapshot this runtime cannot read, naming the format it found. + /// Refuses a single-file snapshot this runtime cannot read, naming the format or record it found. public static void RequireSingleFileFormat(CultPersistedStoreSnapshot snapshot) { - if (!string.Equals(snapshot.FormatVersion, SingleFileFormatVersion, StringComparison.Ordinal)) + var version = snapshot.FormatVersion; + if (!string.Equals(version, CultPersistedStoreSnapshot.FormatV1, StringComparison.Ordinal) && + !string.Equals(version, CultPersistedStoreSnapshot.FormatV2, StringComparison.Ordinal)) { throw new NotSupportedException( - $"Store format {snapshot.FormatVersion} is not readable; this runtime reads {SingleFileFormatVersion} only. " + - "The store needs a runtime that resolves document variants."); + $"Store format {version} is not readable; this runtime reads {CultPersistedStoreSnapshot.FormatV1} and {CultPersistedStoreSnapshot.FormatV2}."); + } + + // Only a v2 store may hold a variant: a v1 header over a variant record is a store no reader could trust. + if (string.Equals(version, CultPersistedStoreSnapshot.FormatV1, StringComparison.Ordinal)) + { + var variant = snapshot.Records.FirstOrDefault(record => record.Variant != null); + if (variant != null) + { + throw new NotSupportedException( + $"Record '{variant.Key}' (schema '{variant.SchemaId}') is a variant but the store declares {version}; variants need {CultPersistedStoreSnapshot.FormatV2}."); + } } } private static void WritePersistedRecord(ref MessagePackWriter writer, CultPersistedRecord record) { - writer.WriteArrayHeader(PersistedRecordFieldCount); + writer.WriteArrayHeader(record.Variant == null ? PersistedRecordFieldCount : VariantRecordFieldCount); writer.Write(record.Key); writer.Write(record.SchemaId); writer.Write(record.StoredAt); writer.Write(record.Payload); + if (record.Variant != null) + { + // Slot 4: [baseKey, overrides[]]; an override is [op, path[], id, value], a path step [slot, elementId], + // and the value is the member's own MessagePack encoding, inline. + writer.WriteArrayHeader(2); + writer.Write(record.Variant.BaseKey); + writer.WriteArrayHeader(record.Variant.Overrides.Count); + foreach (var entry in record.Variant.Overrides) + { + writer.WriteArrayHeader(4); + writer.Write((int)entry.Op); + writer.WriteArrayHeader(entry.Path.Count); + foreach (var step in entry.Path) + { + writer.WriteArrayHeader(2); + writer.Write(step.Slot); + writer.Write(step.ElementId); + } + + writer.Write(entry.Id); + writer.WriteRaw(entry.Value); + } + } + } + + private static CultVariantDelta ReadVariant(ref MessagePackReader reader, string key, string schemaId) + { + var slots = reader.ReadArrayHeader(); + if (slots != 2) + { + throw new NotSupportedException( + $"Record '{key}' (schema '{schemaId}') has a variant slot of {slots} entries; this runtime reads 2 (base key, overrides)."); + } + + var baseKey = reader.ReadString() ?? string.Empty; + var count = reader.ReadArrayHeader(); + var overrides = new CultVariantOverride[count]; + for (var index = 0; index < count; index++) + { + var fields = reader.ReadArrayHeader(); + if (fields != 4) + { + throw new NotSupportedException( + $"Record '{key}' (schema '{schemaId}') has an override of {fields} entries; this runtime reads 4 (op, path, id, value)."); + } + + var op = reader.ReadInt32(); + if (op is < 0 or > 2) + { + throw new NotSupportedException($"Record '{key}' (schema '{schemaId}') has an override with unknown op {op}."); + } + + var stepCount = reader.ReadArrayHeader(); + var path = new CultPathStep[stepCount]; + for (var step = 0; step < stepCount; step++) + { + var stepFields = reader.ReadArrayHeader(); + if (stepFields != 2) + { + throw new NotSupportedException( + $"Record '{key}' (schema '{schemaId}') has a path step of {stepFields} entries; this runtime reads 2 (slot, elementId)."); + } + + path[step] = new CultPathStep(reader.ReadInt32(), reader.ReadString() ?? string.Empty); + } + + var id = reader.ReadString() ?? string.Empty; + var start = reader.Position; + reader.Skip(); + var value = reader.Sequence.Slice(start, reader.Position).ToArray(); + overrides[index] = new CultVariantOverride((CultOverrideOp)op, path, id, value); + } + + return new CultVariantDelta(baseKey, overrides); } public static CultPersistedRecord ReadPersistedRecord(ref MessagePackReader reader) @@ -217,11 +347,21 @@ public static class CultDocumentMessagePackSerialization record.Payload = reader.ReadBytes()?.ToArray() ?? Array.Empty(); } - if (fieldCount > PersistedRecordFieldCount) + if (fieldCount > VariantRecordFieldCount) { throw new NotSupportedException( - $"Record '{record.Key}' (schema '{record.SchemaId}') has {fieldCount} slots; this runtime reads {PersistedRecordFieldCount}. " + - "The store needs a runtime that resolves document variants."); + $"Record '{record.Key}' (schema '{record.SchemaId}') has {fieldCount} slots; this runtime reads {PersistedRecordFieldCount} " + + $"(or {VariantRecordFieldCount} for a variant)."); + } + + if (fieldCount == VariantRecordFieldCount) + { + record.Variant = ReadVariant(ref reader, record.Key, record.SchemaId); + if (record.Payload.Length != 0) + { + throw new NotSupportedException( + $"Record '{record.Key}' (schema '{record.SchemaId}') is a variant and must carry an empty payload."); + } } return record; diff --git a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs index 9e185202..fa9d4899 100644 --- a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs +++ b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs @@ -135,9 +135,18 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore Trace("publish"); } + // Variants wait for the directory store's own cut; until then it refuses one rather than persist a resolved view as a plain page. + private static void RefuseVariant(CultStoredDocument entry) + { + if (entry.Variant != null) + throw new NotSupportedException( + $"Record '{entry.Key.Value}' is a variant of '{entry.Variant.BaseKey}'; the directory store does not hold document variants yet."); + } + public override void Push(CultStoredDocument entry) { ThrowIfReadOnly(); + RefuseVariant(entry); Held(() => { Entries[entry.Key.Value] = entry; @@ -162,6 +171,8 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore public override CultCommitOutcome CommitBatch(CultCommitRequest request, bool wait) { ThrowIfReadOnly(); + foreach (var entry in request.Upserts) + RefuseVariant(entry); return Held(() => { Directory.CreateDirectory(_manifestFile.DirectoryName!); diff --git a/src/GameCult.Caching/Contracts/cultcache-persistence-format.md b/src/GameCult.Caching/Contracts/cultcache-persistence-format.md index 4511f3c5..1205d904 100644 --- a/src/GameCult.Caching/Contracts/cultcache-persistence-format.md +++ b/src/GameCult.Caching/Contracts/cultcache-persistence-format.md @@ -213,9 +213,39 @@ The payload is the domain object only. It does not repeat the key, schema id, or stored timestamp. Under `cultcache.store.v1` a record has exactly these four slots. A reader refuses any -other `cultcache.store.*` header and any record with more than four slots, naming the -version or the record's key and schema id. It never skips a slot it does not -understand. +`cultcache.store.*` header it does not know and any record with more slots than its +header allows, naming the version or the record's key and schema id. It never skips a +slot it does not understand. + +## Variant Records + +A variant record is a record whose document is a base record's document with some +members replaced. It stores the difference, never the resolved document. It carries a +fifth slot: + +``` +[key, schemaId, storedAt, payload, [baseKey, overrides[]]] +``` + +- `payload` is empty. An older reader that ignores the fifth slot reads an empty + payload as a corrupt document and refuses, which is why the delta lives outside it. +- `schemaId` is the type's schema id, the same as the base's. A variant has its base's + concrete type, and lives in the same store (one home store per type). +- An override is `[op, path[], id, value]`. `op` is `0` Set, `1` Insert or `2` Remove. + A path step is `[slot, elementId]`: `slot` is the member's MessagePack `[Key]` and + `elementId` is `""` unless the step enters an object-list element. `value` is the + member's own MessagePack encoding, inline. A top-level Set has one step and `id` `""`; + a reader that resolves only that shape refuses the others, naming the variant. +- A store holding at least one variant declares `cultcache.store.v2`; a store holding + none declares `cultcache.store.v1` and is byte-identical to what a runtime without + variants writes. A `v1` header over a variant record is refused. +- A variant's resolved document is derived in memory when the cache admits the record + or any record on its base chain, and is never written back. A plain write at a + variant's key is refused; `Flatten` replaces a variant with a plain record holding its + resolved document. +- The C# runtime resolves variants. Every other runtime refuses a `v2` store by name. + CultMesh single-file reads, the directory store and CultNet refuse a variant record by + name until each has its own cut. ## Canonical Semantic Schema Hash diff --git a/src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md b/src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md index 297c3184..818840ee 100644 --- a/src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md +++ b/src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md @@ -105,3 +105,10 @@ lie about the payload: - no compatible local schema candidate This is not negotiable. Better a loud refusal than quiet bit-rot. + +## Variant overrides + +A variant's override drifts exactly as the same member would on a plain record: an +override naming a slot the type no longer has, or holding a value that no longer decodes +into the member's type, is ignored with a warning naming the variant and the member, and +the variant inherits the base value. There is no separate rule for variants. diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 2f8e316a..24c20cfc 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -55,11 +55,17 @@ namespace GameCult.Caching public string SchemaId { get; set; } = string.Empty; public string StoredAt { get; set; } = string.Empty; public byte[] Payload { get; set; } = Array.Empty(); + + // Non-null for a variant record (slot 4): its base and overrides. Its payload is empty. + public CultVariantDelta? Variant { get; set; } } public sealed class CultPersistedStoreSnapshot { - public string FormatVersion { get; set; } = "cultcache.store.v1"; + public const string FormatV1 = "cultcache.store.v1"; + public const string FormatV2 = "cultcache.store.v2"; + + public string FormatVersion { get; set; } = FormatV1; public CultSchemaCatalogEntry[] SchemaCatalog { get; set; } = Array.Empty(); public CultPersistedRecord[] Records { get; set; } = Array.Empty(); } @@ -336,13 +342,43 @@ namespace GameCult.Caching Key = key; StoredAt = storedAt; Descriptor = descriptor; - Document = document; + _document = document; } + // A variant: the delta is what is stored; the cache resolves it against its base in the hold that admits it. + internal CultStoredDocument( + CultRecordKey key, + string storedAt, + CultDocumentDescriptor descriptor, + CultVariantDelta variant, + object? resolved) + { + Key = key; + StoredAt = storedAt; + Descriptor = descriptor; + Variant = variant; + _document = resolved; + } + + private readonly object? _document; + public CultRecordKey Key { get; } public string StoredAt { get; } public CultDocumentDescriptor Descriptor { get; } - public object Document { get; } + + // The complete document. For a variant, the resolved view: derived, never written back. + public object Document => _document ?? + throw new InvalidOperationException($"Variant {Key.Value} has not been resolved; only the cache resolves a variant."); + + // The base and overrides a variant record stores; null for a plain record. + public CultVariantDelta? Variant { get; } + + // A plain record staged by Flatten: the one way a plain record may replace a variant at its key. + internal bool Flattens { get; set; } + + internal bool IsResolved => _document != null; + + internal CultStoredDocument Resolved(object document) => new(Key, StoredAt, Descriptor, Variant!, document); } public sealed class CultDocumentRegistry @@ -1662,11 +1698,29 @@ namespace GameCult.Caching private static string Identity(string key, string schemaId, string storedAt) => $"{key}\n{schemaId}\n{storedAt}"; } + // One staged write: a plain record (Stored), a variant (Variant), a flatten, or, with none of those, a removal. + internal sealed class StagedOperation + { + public StagedOperation(CultRecordKey key, CultStoredDocument? stored, CultVariantDelta? variant, bool flatten) + { + Key = key; + Stored = stored; + Variant = variant; + Flatten = flatten; + } + + public CultRecordKey Key { get; } + public CultStoredDocument? Stored { get; } + public CultVariantDelta? Variant { get; } + public bool Flatten { get; } + public bool IsRemoval => Stored == null && Variant == null && !Flatten; + } + // An explicit value: nothing staged here is visible to anyone until Commit returns. public sealed class CultCacheBatch { private readonly CultCache _cache; - internal readonly Dictionary Operations = new(StringComparer.Ordinal); + internal readonly Dictionary Operations = new(StringComparer.Ordinal); internal readonly List<(CultRecordKey Key, string? SchemaId, string? StoredAt)> Expected = new(); internal bool ExpectsUnchanged; internal bool Sealed; @@ -1691,7 +1745,24 @@ namespace GameCult.Caching public void Remove(CultRecordKey key) { ThrowIfSealed(); - Operations[key.Value] = (key, null); + Operations[key.Value] = new StagedOperation(key, null, null, false); + } + + // Stages a variant record: its base and a sparse set of overrides, resolved by the cache when the batch commits. + // A variant changes only through here; rebasing is this call with another base. + public CultRecordKey UpsertVariant(CultRecordKey key, CultRecordKey baseKey, IEnumerable? overrides = null) + { + ThrowIfSealed(); + Operations[key.Value] = new StagedOperation( + key, null, new CultVariantDelta(baseKey.Value, (overrides ?? Array.Empty()).ToArray()), false); + return key; + } + + // Replaces a variant with a plain record holding its resolved document: the explicit, separate operation (Q1a). + public void Flatten(CultRecordKey key) + { + ThrowIfSealed(); + Operations[key.Value] = new StagedOperation(key, null, null, true); } public void Expect(CultRecordKey key, object? current) @@ -1711,7 +1782,7 @@ namespace GameCult.Caching { ThrowIfSealed(); var stored = _cache.CreateStoredDocument(document, key); - Operations[stored.Key.Value] = (stored.Key, stored); + Operations[stored.Key.Value] = new StagedOperation(stored.Key, stored, null, false); return stored.Key; } @@ -1730,6 +1801,11 @@ namespace GameCult.Caching private readonly Dictionary> _names = new(); private readonly Dictionary<(Type Type, string Alias), Dictionary> _indexes = new(); private readonly Dictionary _globals = new(); + private readonly CultCodec? _codec; + // Keys holding a variant, and the drift report of each variant whose overrides were partly ignored: both derived + // from the entries by Apply, never decided anywhere else. + private readonly HashSet _variantKeys = new(StringComparer.Ordinal); + private readonly Dictionary _variantReports = new(StringComparer.Ordinal); private readonly ConditionalWeakTable _handles = new(); private readonly Subject _changes = new(); private readonly object _gate = new(); @@ -1738,13 +1814,42 @@ namespace GameCult.Caching [ThreadStatic] private static List<(Change Change, bool Loaded)>? _held; private bool _dirtyInMemory; - public CultCache(CultDocumentRegistry? registry = null) + // The codec is the store's encoding (CultCacheMessagePack.Create supplies it). A cache without one holds no variants: + // resolving a variant needs to clone documents and decode override values. + public CultCache(CultDocumentRegistry? registry = null, CultCodec? codec = null) { _registry = registry ?? CultDocumentRegistry.Shared; + _codec = codec; } public CultDocumentRegistry Registry => _registry; + public CultCodec? Codec => _codec; + + // Overrides a variant carries that no longer resolve (a slot the type dropped, a value that no longer decodes), + // reported as compatible drift: the override is ignored and the variant inherits the base value. + public IReadOnlyList VariantMigrationReports + { + get + { + lock (_gate) + return _variantReports.Values.ToArray(); + } + } + + // The whole override of one member, encoded with this cache's codec, ready for UpsertVariant. + public CultVariantOverride Override(Type documentType, string member, object? value) + { + if (_codec == null) throw new InvalidOperationException("This cache has no codec; create it with CultCacheMessagePack.Create."); + var found = _registry.GetRequired(documentType).RichMembers.FirstOrDefault(entry => entry.Member.Name == member) + ?? throw new ArgumentException($"{documentType.Name} has no persisted member '{member}'.", nameof(member)); + return CultVariantOverride.Set( + found.Slot, + _codec.Serialize(value!, found.MemberType, documentType)); + } + + public CultVariantOverride Override(string member, object? value) where T : class => Override(typeof(T), member, value); + public bool IsDirty { get @@ -1841,7 +1946,7 @@ namespace GameCult.Caching store.AttachRegistry(_registry); store.Cache = this; - store.Loaded = (loaded, dropped) => Admit(loaded, dropped, store, _ => CultCommitOutcome.Committed); + store.Loaded = (loaded, dropped) => Admit(loaded, dropped, store, (_, _) => CultCommitOutcome.Committed); _stores.Add(candidate); try { @@ -1915,11 +2020,39 @@ namespace GameCult.Caching return Task.FromResult(Write(document, key)); } + // A single-call variant write; a batch stages the same thing with CultCacheBatch.UpsertVariant. + public Task UpsertVariantAsync(CultRecordKey key, CultRecordKey baseKey, IEnumerable? overrides = null) + { + var delta = new CultVariantDelta(baseKey.Value, (overrides ?? Array.Empty()).ToArray()); + return Task.FromResult(Held(() => + { + var stored = StampVariant(key, DescriptorOfBase(key, delta.BaseKey, null), delta); + Admit(new[] { stored }, Array.Empty(), null, (home, docs) => + { + home?.Push(docs[0]); + return CultCommitOutcome.Committed; + }); + return key; + })); + } + + // Replaces a variant with a plain record holding its resolved document (Q1a's explicit operation). + public Task FlattenAsync(CultRecordKey key) => Task.FromResult(Held(() => + { + var stored = StampFlatten(key); + Admit(new[] { stored }, Array.Empty(), null, (home, docs) => + { + home?.Push(docs[0]); + return CultCommitOutcome.Committed; + }); + return key; + })); + public bool Remove(CultRecordKey key) => Held(() => { if (!_entries.TryGetValue(key.Value, out var existing)) return false; - Admit(Array.Empty(), new[] { existing }, null, home => + Admit(Array.Empty(), new[] { existing }, null, (home, _) => { home?.Delete(existing); return CultCommitOutcome.Committed; @@ -1950,6 +2083,13 @@ namespace GameCult.Caching return _handles.TryGetValue(document, out var box) ? new CultRecordHandle(box.Key) : null; } + // The stored form of a record: for a variant, the delta beside the resolved document. + public CultStoredDocument? GetStored(CultRecordKey key) + { + lock (_gate) + return _entries.TryGetValue(key.Value, out var stored) ? stored : null; + } + public object? Get(CultRecordKey key) { lock (_gate) @@ -2039,7 +2179,53 @@ namespace GameCult.Caching // Call under the gate that admits the result, so no load can land a later storedAt in between. private CultStoredDocument Stamp(CultRecordKey key, CultDocumentDescriptor descriptor, object document) => - new(key, MintStoredAt(_entries.TryGetValue(key.Value, out var previous) ? previous.StoredAt : null), descriptor, document); + new(key, MintStoredAt(PreviousStoredAt(key)), descriptor, document); + + // An unresolved variant: the admitting hold resolves it against its base before anything lands. + private CultStoredDocument StampVariant(CultRecordKey key, CultDocumentDescriptor descriptor, CultVariantDelta delta) => + new(key, MintStoredAt(PreviousStoredAt(key)), descriptor, delta, null); + + // The plain record a Flatten stages: the variant's resolved document, under the variant's own key and schema. + private CultStoredDocument StampFlatten(CultRecordKey key) + { + if (!_entries.TryGetValue(key.Value, out var existing) || existing.Variant == null) + throw new InvalidOperationException($"Flatten({key.Value}): the record is not a variant."); + return new CultStoredDocument(key, MintStoredAt(existing.StoredAt), existing.Descriptor, existing.Document) { Flattens = true }; + } + + private string? PreviousStoredAt(CultRecordKey key) => _entries.TryGetValue(key.Value, out var previous) ? previous.StoredAt : null; + + // The concrete type a variant takes from its base, walking bases through what the batch stages and then the cache. + // Refuses a cycle or a base that is not there, naming the keys, exactly as the admitting hold would. + private CultDocumentDescriptor DescriptorOfBase(CultRecordKey variant, string baseKey, CultCacheBatch? batch) + { + var seen = new List { variant.Value }; + var next = baseKey; + while (true) + { + if (seen.Contains(next)) + throw CycleRefusal(seen.Append(next)); + var staged = batch != null && batch.Operations.TryGetValue(next, out var op) ? op : null; + if (staged != null) + { + if (staged.Stored != null) + return staged.Stored.Descriptor; + if (staged.Variant != null) + { + seen.Add(next); + next = staged.Variant.BaseKey; + continue; + } + + if (!staged.Flatten) + throw MissingBaseRefusal(variant.Value, baseKey, removed: true); + } + + if (!_entries.TryGetValue(next, out var existing)) + throw MissingBaseRefusal(variant.Value, baseKey, removed: false); + return existing.Descriptor; + } + } internal CultStoredDocument? Observe(CultRecordKey key, object? current) { @@ -2068,9 +2254,9 @@ namespace GameCult.Caching private CultRecordKey Write(object document, CultRecordKey? key) => Held(() => { var stored = CreateStoredDocument(document, key); - Admit(new[] { stored }, Array.Empty(), null, home => + Admit(new[] { stored }, Array.Empty(), null, (home, docs) => { - home?.Push(stored); + home?.Push(docs[0]); return CultCommitOutcome.Committed; }); return stored.Key; @@ -2094,16 +2280,19 @@ namespace GameCult.Caching { // Staging stamped outside this gate; a pull since then may hold a later storedAt, so stamp again. var upserts = batch.Operations.Values - .Where(op => op.Stored != null) - .Select(op => Stamp(op.Key, op.Stored!.Descriptor, op.Stored.Document)) + .Where(op => !op.IsRemoval) + .Select(op => op.Stored != null ? Stamp(op.Key, op.Stored.Descriptor, op.Stored.Document) + : op.Variant != null ? StampVariant(op.Key, DescriptorOfBase(op.Key, op.Variant.BaseKey, batch), op.Variant) + : StampFlatten(op.Key)) .ToArray(); var deletes = batch.Operations.Values - .Where(op => op.Stored == null && _entries.ContainsKey(op.Key.Value)) + .Where(op => op.IsRemoval && _entries.ContainsKey(op.Key.Value)) .Select(op => _entries[op.Key.Value]) .ToArray(); - var request = new CultCommitRequest(upserts, deletes, batch.Expected.ToArray(), batch.ExpectsUnchanged); - return Admit(upserts, deletes, null, home => + return Admit(upserts, deletes, null, (home, resolved) => { + // What the store holds is what the hold resolved: a variant's delta beside its resolved view. + var request = new CultCommitRequest(resolved, deletes, batch.Expected.ToArray(), batch.ExpectsUnchanged); if (home != null) { if (request.HasConditions && home.IsDirty) @@ -2127,14 +2316,18 @@ namespace GameCult.Caching IReadOnlyList admitted, IReadOnlyList evicted, CacheBackingStore? source, - Func land) => Held(() => + Func, CultCommitOutcome> land) => Held(() => { if (_held == null) throw new InvalidOperationException("An admission reached the cache under a plain lock on its gate; every admission runs in a hold."); - var outcome = land(Validate(admitted, evicted, source)); + var home = Validate(admitted, evicted, source); + // The one resolution: a variant admitted, a base admitted or evicted, all resolved here against the post-batch + // set, before land and before memory. land receives the admitted records with variants resolved. + var plan = Resolve(admitted, evicted, source); + var outcome = land(home, plan.Admitted); if (outcome != CultCommitOutcome.Committed) return outcome; - foreach (var change in Apply(admitted, evicted, source)) + foreach (var change in Apply(plan, evicted, source)) _held.Add((change, source != null)); return CultCommitOutcome.Committed; }); @@ -2262,12 +2455,215 @@ namespace GameCult.Caching } } - private List Apply( + private sealed class VariantPlan + { + public VariantPlan(IReadOnlyList admitted) + { + Admitted = admitted; + } + + // The admitted records, variants resolved. + public IReadOnlyList Admitted { get; } + + // Variants this admission did not write whose base chain it changed: re-resolved, same delta, same storedAt. + public List Dependents { get; } = new(); + + // The drift report of every variant resolved here; null when nothing was ignored. + public Dictionary Reports { get; } = new(StringComparer.Ordinal); + } + + // Resolves every admitted variant and every variant whose base chain this admission changes, base first, against + // the post-admission set. It refuses a broken variant naming the keys, and mutates nothing. + private VariantPlan Resolve( IReadOnlyList admitted, IReadOnlyList evicted, CacheBackingStore? source) { - var changes = new List(admitted.Count + evicted.Count); + if (_variantKeys.Count == 0 && admitted.All(stored => stored.Variant == null)) + return new VariantPlan(admitted); + + var incoming = admitted.ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal); + var gone = evicted.Select(stored => stored.Key.Value).ToHashSet(StringComparer.Ordinal); + CultStoredDocument? Lookup(string key) => + incoming.TryGetValue(key, out var found) ? found + : gone.Contains(key) ? null + : _entries.TryGetValue(key, out var held) ? held : null; + + // A variant is written only through the variant API: a plain record never lands on a variant's key, and the + // reverse is a rebase or a flatten, never an accident. A load reports what is on disk and is not a write. + if (source == null) + { + foreach (var stored in admitted) + { + _entries.TryGetValue(stored.Key.Value, out var present); + if (stored.Variant == null && !stored.Flattens && present?.Variant != null) + throw new InvalidOperationException( + $"Record {stored.Key.Value} is a variant of {present.Variant.BaseKey}; a plain write cannot replace it. " + + "Change it through the variant API, or Flatten it."); + if (stored.Variant != null && present != null && present.Variant == null) + throw new InvalidOperationException( + $"Record {stored.Key.Value} is a plain record; it cannot become a variant of {stored.Variant.BaseKey} in place. Use a new key."); + if (stored.Variant != null && present?.Variant != null && + present.Descriptor.DocumentType != stored.Descriptor.DocumentType) + throw new InvalidOperationException( + $"Variant {stored.Key.Value} is a {present.Descriptor.DocumentType.Name}; " + + $"rebasing it onto {stored.Variant.BaseKey} would make it a {stored.Descriptor.DocumentType.Name}."); + } + } + + var changed = new HashSet(incoming.Keys.Concat(gone), StringComparer.Ordinal); + var toResolve = new List(admitted.Where(stored => stored.Variant != null).Select(stored => stored.Key.Value)); + foreach (var variantKey in _variantKeys) + { + if (incoming.ContainsKey(variantKey) || gone.Contains(variantKey)) + continue; + var next = _entries[variantKey].Variant!.BaseKey; + for (var steps = 0; steps <= _entries.Count; steps++) + { + if (changed.Contains(next)) + { + toResolve.Add(variantKey); + break; + } + + var link = Lookup(next); + if (link?.Variant == null) + break; + next = link.Variant.BaseKey; + } + } + + if (toResolve.Count == 0) + return new VariantPlan(admitted); + + var pending = new HashSet(toResolve, StringComparer.Ordinal); + var done = new Dictionary(StringComparer.Ordinal); + var reports = new Dictionary(StringComparer.Ordinal); + var stack = new List(); + foreach (var key in toResolve) + ResolveOne(key); + + var plan = new VariantPlan(admitted.Select(stored => stored.Variant != null ? done[stored.Key.Value] : stored).ToList()); + foreach (var key in toResolve.Where(key => !incoming.ContainsKey(key))) + plan.Dependents.Add(done[key]); + foreach (var pair in reports) + plan.Reports[pair.Key] = pair.Value; + return plan; + + CultStoredDocument ResolveOne(string key) + { + if (done.TryGetValue(key, out var finished)) + return finished; + var variant = Lookup(key)!; + if (stack.Contains(key)) + throw CycleRefusal(stack.SkipWhile(entry => entry != key).Append(key)); + stack.Add(key); + + var delta = variant.Variant!; + var baseStored = Lookup(delta.BaseKey) ?? throw MissingBaseRefusal(key, delta.BaseKey, gone.Contains(delta.BaseKey)); + if (baseStored.Variant != null && pending.Contains(delta.BaseKey)) + baseStored = ResolveOne(delta.BaseKey); + + var descriptor = variant.Descriptor; + if (_codec == null) + throw new InvalidOperationException( + $"Variant {key} needs a codec to resolve; this cache has none. Create it with CultCacheMessagePack.Create."); + if (baseStored.Descriptor.DocumentType != descriptor.DocumentType) + throw new InvalidOperationException( + $"Variant {key} is a {descriptor.DocumentType.Name} but its base {delta.BaseKey} is a {baseStored.Descriptor.DocumentType.Name}; " + + "a variant has its base's concrete type."); + + var type = descriptor.DocumentType; + var kept = new List>(); + var ignored = new List(); + var warnings = new List(); + foreach (var entry in delta.Overrides) + { + if (entry.Op != CultOverrideOp.Set || entry.Path.Count != 1 || entry.Path[0].ElementId.Length != 0 || entry.Id.Length != 0) + throw new InvalidOperationException( + $"Variant {key} carries {entry.Op} at {entry.PathText}; this runtime resolves top-level Set overrides only."); + var slot = entry.Path[0].Slot; + var member = descriptor.RichMembers.FirstOrDefault(candidate => candidate.Slot == slot); + if (member == null) + { + var name = delta.SlotNames != null && delta.SlotNames.TryGetValue(slot, out var persistedName) + ? $"'{persistedName}'" : "unnamed"; + ignored.Add(slot); + warnings.Add(new CultSchemaMigrationWarning + { + Code = "ignored_extra_slot", + Message = $"Variant {key} overrides slot {slot} ({name}), which {type.Name} no longer has; the override is ignored and the variant inherits the base value." + }); + continue; + } + + try + { + _codec.Deserialize(member.MemberType, type, entry.Value); + } + catch (Exception exception) + { + ignored.Add(slot); + warnings.Add(new CultSchemaMigrationWarning + { + Code = "ignored_undecodable_override", + Message = $"Variant {key} overrides slot {slot} ('{member.Member.Name}') with a value that no longer decodes as {member.MemberType.Name} " + + $"({exception.GetBaseException().Message}); the override is ignored and the variant inherits the base value." + }); + continue; + } + + kept.Add(new KeyValuePair(slot, entry.Value)); + } + + var payload = _codec.Serialize(baseStored.Document, type, type); + var document = _codec.Deserialize(type, type, kept.Count == 0 ? payload : _codec.Overlay(payload, kept)) + ?? throw new InvalidOperationException($"Variant {key} resolved to nothing."); + + // R6: the name index maps one name to one key, so a variant that kept its base's name would shadow it. + if (descriptor.NameAccessor?.Invoke(document) is { Length: > 0 } variantName) + { + for (var ancestor = baseStored; ancestor != null; + ancestor = ancestor.Variant == null ? null : done.TryGetValue(ancestor.Variant.BaseKey, out var above) ? above : Lookup(ancestor.Variant.BaseKey)) + { + if (descriptor.NameAccessor(ancestor.Document) == variantName) + throw new InvalidOperationException( + $"Variant {key} and its base {ancestor.Key.Value} are both named '{variantName}'; a variant must override its name."); + } + } + + reports[key] = ignored.Count == 0 + ? null + : new CultSchemaMigrationReport + { + PersistedSchemaId = descriptor.SchemaId, + LocalSchemaId = descriptor.SchemaId, + PersistedSchemaName = descriptor.SchemaName, + LocalSchemaName = descriptor.SchemaName, + Kind = CultSchemaMigrationKind.CompatibleDrift, + IgnoredExtraSlots = ignored.OrderBy(slot => slot).ToArray(), + Warnings = warnings.ToArray() + }; + stack.RemoveAt(stack.Count - 1); + return done[key] = variant.Resolved(document); + } + } + + private static InvalidOperationException CycleRefusal(IEnumerable keys) => + new($"Variant bases form a cycle: {string.Join(" -> ", keys)}."); + + private static InvalidOperationException MissingBaseRefusal(string variant, string baseKey, bool removed) => + new(removed + ? $"Record {baseKey} cannot go: variant {variant} is based on it. Remove or rebase the variant in the same commit." + : $"Variant {variant} is based on {baseKey}, which does not exist."); + + private List Apply( + VariantPlan plan, + IReadOnlyList evicted, + CacheBackingStore? source) + { + var admitted = plan.Admitted; + var changes = new List(admitted.Count + evicted.Count + plan.Dependents.Count); foreach (var stored in evicted) { if (!_entries.TryGetValue(stored.Key.Value, out var existing)) @@ -2275,10 +2671,12 @@ namespace GameCult.Caching Unindex(existing); _entries.Remove(stored.Key.Value); _handles.Remove(existing.Document); + _variantKeys.Remove(stored.Key.Value); + _variantReports.Remove(stored.Key.Value); changes.Add(new Change(CultCacheDocumentChangeKind.Removed, existing, null, existing.Document, ++_sequence)); } - foreach (var stored in admitted) + foreach (var stored in admitted.Concat(plan.Dependents)) { _entries.TryGetValue(stored.Key.Value, out var previous); if (previous != null) @@ -2290,6 +2688,14 @@ namespace GameCult.Caching _entries[stored.Key.Value] = stored; _handles.AddOrUpdate(stored.Document, new KeyBox(stored.Key)); Index(stored); + if (stored.Variant == null) + _variantKeys.Remove(stored.Key.Value); + else + _variantKeys.Add(stored.Key.Value); + if (plan.Reports.TryGetValue(stored.Key.Value, out var report) && report != null) + _variantReports[stored.Key.Value] = report; + else + _variantReports.Remove(stored.Key.Value); changes.Add(new Change( previous == null ? CultCacheDocumentChangeKind.Added : CultCacheDocumentChangeKind.Updated, stored, @@ -2486,12 +2892,14 @@ namespace GameCult.Caching protected CultPersistedRecord ToPersistedRecord(CultStoredDocument entry, Func serializePayload) { + // A variant persists its delta and an empty payload; the resolved view is never written. return new CultPersistedRecord { Key = entry.Key.Value, SchemaId = entry.Descriptor.SchemaId, StoredAt = entry.StoredAt, - Payload = serializePayload(entry.Document) + Payload = entry.Variant != null ? Array.Empty() : serializePayload(entry.Document), + Variant = entry.Variant == null ? null : new CultVariantDelta(entry.Variant.BaseKey, entry.Variant.Overrides) }; } @@ -2501,6 +2909,21 @@ namespace GameCult.Caching Func deserializePayload) { var resolution = Registry.ResolvePersistedSchemaDetailed(record.SchemaId, catalog); + if (record.Variant != null) + { + // The cache resolves it against its base when it admits the load; the catalog names the slots the type may have dropped. + var persisted = catalog.FirstOrDefault(entry => string.Equals(entry.SchemaId, record.SchemaId, StringComparison.Ordinal)); + return new CultStoredDocument( + new CultRecordKey(record.Key), + record.StoredAt, + resolution.Descriptor, + new CultVariantDelta(record.Variant.BaseKey, record.Variant.Overrides) + { + SlotNames = persisted?.Members.ToDictionary(member => member.Slot, member => member.MemberName) + }, + null); + } + var document = deserializePayload(resolution.Descriptor.DocumentType, record.Payload); return new CultStoredDocument( new CultRecordKey(record.Key), @@ -2675,6 +3098,10 @@ namespace GameCult.Caching var used = new HashSet(ordered.Select(record => record.SchemaId), StringComparer.Ordinal); var snapshot = new CultPersistedStoreSnapshot { + // v2 exactly when the store holds a variant: a store without one stays byte-identical v1. + FormatVersion = ordered.Any(record => record.Variant != null) + ? CultPersistedStoreSnapshot.FormatV2 + : CultPersistedStoreSnapshot.FormatV1, SchemaCatalog = catalog .GroupBy(entry => entry.SchemaId, StringComparer.Ordinal) .Select(group => group.First()) diff --git a/src/GameCult.Caching/CultInspectorModel.cs b/src/GameCult.Caching/CultInspectorModel.cs index e5b5581f..99d82205 100644 --- a/src/GameCult.Caching/CultInspectorModel.cs +++ b/src/GameCult.Caching/CultInspectorModel.cs @@ -292,22 +292,24 @@ namespace GameCult.Caching typeof(int), typeof(long), typeof(uint), typeof(short), typeof(ushort), typeof(byte), typeof(sbyte) }; - private readonly Func _serialize; - private readonly Func _deserialize; + private readonly CultCodec _codec; private readonly Dictionary _shapes = new Dictionary(); private readonly Dictionary _metadata = new Dictionary(); - // serialize (value, value type, owning document type) and deserialize are the store's codec - // (CultCacheMessagePack.CreateInspectorModel for .cc stores). Edits clone documents through both; dictionary keys - // compare by serialize under their owning document, exactly as the store writes them inside it, so serialize must - // take any value, not only documents. - public CultInspectorModel(CultDocumentRegistry registry, Func serialize, Func deserialize) + // The codec is the store's (CultCacheMessagePack.CreateInspectorModel for .cc stores), the one a CultCache resolves + // variants with. Edits clone documents through it; dictionary keys compare by its Serialize under their owning + // document, exactly as the store writes them inside it. + public CultInspectorModel(CultDocumentRegistry registry, CultCodec codec) { Registry = registry ?? throw new ArgumentNullException(nameof(registry)); - _serialize = serialize ?? throw new ArgumentNullException(nameof(serialize)); - _deserialize = deserialize ?? throw new ArgumentNullException(nameof(deserialize)); + _codec = codec ?? throw new ArgumentNullException(nameof(codec)); } + private byte[] _serialize(object value, Type type, Type document) => _codec.Serialize(value, type, document); + + private object _deserialize(Type type, byte[] bytes) => + _codec.Deserialize(type, type, bytes) ?? throw new InvalidOperationException($"The codec returned null for {type.FullName}."); + public CultDocumentRegistry Registry { get; } public static string RecordLabel(CultStoredDocument record) diff --git a/src/GameCult.Caching/CultVariants.cs b/src/GameCult.Caching/CultVariants.cs new file mode 100644 index 00000000..08882c79 --- /dev/null +++ b/src/GameCult.Caching/CultVariants.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace GameCult.Caching +{ + // The store's encoding, as the cache needs it: the one pair CultInspectorModel and variant resolution share. + // Serialize takes any value, not only documents, under its owning document type's options; Deserialize is its + // inverse (a document type is checked against the registry, a member type is not); Overlay replaces slots of a + // serialized document payload with already-encoded member values and touches nothing else. + public sealed class CultCodec + { + public CultCodec( + Func serialize, + Func deserialize, + Func>, byte[]> overlay) + { + Serialize = serialize ?? throw new ArgumentNullException(nameof(serialize)); + Deserialize = deserialize ?? throw new ArgumentNullException(nameof(deserialize)); + Overlay = overlay ?? throw new ArgumentNullException(nameof(overlay)); + } + + // (value, value type, owning document type) + public Func Serialize { get; } + + // (value type, owning document type, bytes) + public Func Deserialize { get; } + + // (document payload, slot and encoded value pairs) + public Func>, byte[]> Overlay { get; } + } + + public enum CultOverrideOp + { + Set = 0, + Insert = 1, + Remove = 2 + } + + // One step of a member path: the MessagePack slot, and the id of the object-list element the step enters ("" when it + // does not enter one). + public sealed class CultPathStep + { + public CultPathStep(int slot, string elementId = "") + { + Slot = slot; + ElementId = elementId ?? string.Empty; + } + + public int Slot { get; } + public string ElementId { get; } + + public override string ToString() => ElementId.Length == 0 ? $"[{Slot}]" : $"[{Slot}:{ElementId}]"; + } + + // The wire shape [op, path[], id, value]; value is the override's already-encoded MessagePack value. + public sealed class CultVariantOverride + { + public CultVariantOverride(CultOverrideOp op, IReadOnlyList path, string id, byte[] value) + { + Op = op; + Path = path ?? throw new ArgumentNullException(nameof(path)); + Id = id ?? string.Empty; + Value = value ?? throw new ArgumentNullException(nameof(value)); + } + + public CultOverrideOp Op { get; } + public IReadOnlyList Path { get; } + public string Id { get; } + public byte[] Value { get; } + + // A top-level Set: the whole member at slot takes the encoded value. + public static CultVariantOverride Set(int slot, byte[] value) => + new(CultOverrideOp.Set, new[] { new CultPathStep(slot) }, string.Empty, value); + + internal string PathText => string.Concat(Path.Select(step => step.ToString())); + } + + // What a variant record stores: its base and its overrides. Never the resolved document. + public sealed class CultVariantDelta + { + public CultVariantDelta(string baseKey, IReadOnlyList overrides) + { + BaseKey = baseKey ?? throw new ArgumentNullException(nameof(baseKey)); + Overrides = overrides ?? throw new ArgumentNullException(nameof(overrides)); + } + + public string BaseKey { get; } + public IReadOnlyList Overrides { get; } + + // Member names by slot from the catalog the delta was loaded under, for warnings about slots the type dropped. + // Not persisted. + internal IReadOnlyDictionary? SlotNames { get; set; } + } +} diff --git a/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs b/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs index 46bfb47e..67cc4cdf 100644 --- a/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs +++ b/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs @@ -156,6 +156,8 @@ namespace GameCult.Mesh $"CultCache document '{path}' record '{key.Value}' has schema '{record.SchemaId}', expected '{expectedSchemaId}'."); } + RefuseVariant(path, record); + if (!PublishesSchema(snapshot.SchemaCatalog, expectedSchemaId)) { throw new InvalidDataException( @@ -189,6 +191,8 @@ namespace GameCult.Mesh $"CultCache document '{path}' has schema '{record.SchemaId}', expected '{expectedSchemaId}'."); } + RefuseVariant(path, record); + if (!PublishesSchema(snapshot.SchemaCatalog, expectedSchemaId)) { throw new InvalidDataException( @@ -198,6 +202,15 @@ namespace GameCult.Mesh return record.Payload; } + // A variant record's payload is empty; its document exists only as the cache resolves it against its base. + private static void RefuseVariant(string path, CultPersistedRecord record) + { + if (record.Variant != null) + throw new NotSupportedException( + $"CultCache document '{path}' record '{record.Key}' is a variant of '{record.Variant.BaseKey}'; " + + "CultMesh does not resolve document variants, open the store with a CultCache."); + } + private static void WriteSingleFileDocumentPayload( string path, CultRecordKey key, diff --git a/src/GameCult.Networking/CultNetDocumentRegistry.cs b/src/GameCult.Networking/CultNetDocumentRegistry.cs index be114002..60446d31 100644 --- a/src/GameCult.Networking/CultNetDocumentRegistry.cs +++ b/src/GameCult.Networking/CultNetDocumentRegistry.cs @@ -393,7 +393,7 @@ namespace GameCult.Networking stored = stored.Where(entry => rowFilter(entry.Descriptor, entry.Key)); var rows = stored .Select(entry => new CultNetSelectionEvaluator.Row( - entry.Descriptor, entry.Key, entry.Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) + entry.Descriptor, entry.Key, RefuseVariant(entry).Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) .ToArray(); var full = CultNetSelectionEvaluator.EvaluateAll(_documents, rows, selection); // R-Q: a page's asOf is exact only when every matched row is committed through one shard's @@ -487,7 +487,7 @@ namespace GameCult.Networking stored = stored.Where(entry => rowFilter(entry.Descriptor, entry.Key)); var rows = stored .Select(entry => new CultNetSelectionEvaluator.Row( - entry.Descriptor, entry.Key, entry.Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) + entry.Descriptor, entry.Key, RefuseVariant(entry).Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) .ToArray(); var full = CultNetSelectionEvaluator.EvaluateAll(_documents, rows, selection); @@ -549,6 +549,13 @@ namespace GameCult.Networking }; } + // CultNet carries no variant deltas yet, and a resolved view sent as a plain record would be a lie about the store. + private static CultStoredDocument RefuseVariant(CultStoredDocument entry) => + entry.Variant == null + ? entry + : throw new NotSupportedException( + $"Record '{entry.Key.Value}' is a variant of '{entry.Variant.BaseKey}'; CultNet does not carry document variants yet."); + /// /// Builds the wire record for one evaluated row. The shared path under snapshot and change /// (docs/cultnet-selection-cut.md, section 8's "shared paths"). From fc78b9ad2b6cad16766959e402f13d74e8bc02b6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 03:52:35 +0200 Subject: [PATCH 47/64] Test the C# variant path and add the C#-written variant store as a shared vector VariantTests drive the cache batch API and the real single-file store. The C1 vector was written by the code under test through that path; C# reads it and rewrites it byte for byte, and the other runtimes' tests read the same bytes next. The C0 tests that expected C# to refuse a v2 store now expect what C1 does with it. Co-Authored-By: Claude Sonnet 5 --- .../PreCut2StoreFormatTests.cs | 25 +- tests/GameCult.Caching.Tests/VariantTests.cs | 700 ++++++++++++++++++ .../CultMeshVariantRefusalTests.cs | 12 +- .../CultNetDocumentRegistryVariantTests.cs | 78 ++ .../document-variants-c1/.gitattributes | 3 + .../variant-store.msgpack | Bin 0 -> 1391 bytes 6 files changed, 812 insertions(+), 6 deletions(-) create mode 100644 tests/GameCult.Caching.Tests/VariantTests.cs create mode 100644 tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs create mode 100644 tests/vectors/document-variants-c1/.gitattributes create mode 100644 tests/vectors/document-variants-c1/variant-store.msgpack diff --git a/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs b/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs index 479eb762..181eca56 100644 --- a/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs +++ b/tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs @@ -131,11 +131,30 @@ namespace GameCult.Caching.Tests Assert.That(message, Does.Contain(ItemSchemaId)); } + // C1 reads v2. This vector was written by hand before C1 existed and its variant keeps its base's name, so a + // cache with a codec refuses it under R6, naming both records; a cache without one cannot resolve it at all. [Test] - public void SingleFileRefusesVariantStoreByVersionOrRecord() + public void SingleFileRefusesTheHandWrittenVariantVectorNamingTheRecords() { - Assert.That(Refusal("variant-v2.msgpack"), - Does.Contain("cultcache.store.v2").Or.Contain("item:anvil-big")); + var root = Path.Combine(Path.GetTempPath(), $"cultlib-vector-{Guid.NewGuid():N}"); + Directory.CreateDirectory(root); + try + { + var file = Path.Combine(root, "store.msgpack"); + File.Copy(VectorPath("variant-v2.msgpack"), file); + + using var withCodec = new CultCache(CultDocumentRegistry.Shared, CultCacheMessagePack.CreateCodec(CultDocumentRegistry.Shared)); + var named = Assert.Throws(() => withCodec.AddBackingStore(new SingleFileMessagePackBackingStore(file)))!; + Assert.That(named.Message, Does.Contain("item:anvil-big").And.Contain("item:anvil")); + + using var without = new CultCache(); + var codecless = Assert.Throws(() => without.AddBackingStore(new SingleFileMessagePackBackingStore(file)))!; + Assert.That(codecless.Message, Does.Contain("item:anvil-big").And.Contain("codec")); + } + finally + { + if (Directory.Exists(root)) Directory.Delete(root, recursive: true); + } } [Test] diff --git a/tests/GameCult.Caching.Tests/VariantTests.cs b/tests/GameCult.Caching.Tests/VariantTests.cs new file mode 100644 index 00000000..501af538 --- /dev/null +++ b/tests/GameCult.Caching.Tests/VariantTests.cs @@ -0,0 +1,700 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using NUnit.Framework; +using R3; + +namespace GameCult.Caching.Tests +{ + // The contract is src/GameCult.Caching/Contracts/cultcache-persistence-format.md (variant records) and + // docs/document-variants-cut.md C1. Every input goes through the cache's own write API and the real single-file store. + public class VariantTests + { + private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] + { + typeof(VariantGear), typeof(VariantOther), typeof(VariantGlobal) + }); + + private static readonly CultRecordKey BaseKey = new("laser"); + private static readonly CultRecordKey BigKey = new("laser-big"); + + private string _directory = string.Empty; + + [SetUp] + public void CreateDirectory() + { + _directory = Path.Combine(Path.GetTempPath(), $"cultlib-variants-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_directory); + } + + [TearDown] + public void DeleteDirectory() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + private string PathOf(string name) => Path.Combine(_directory, name); + + private static CultCache Open(string path, bool readOnly = false, CultDocumentRegistry? registry = null) => + CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = registry ?? Registry, ReadOnly = readOnly }); + + private static VariantGear Laser() => new() { Name = "laser", Power = 10, Code = "l1", Tags = { "beam" } }; + + private static void SeedBase(CultCache cache) => + cache.Commit(batch => batch.Upsert(typeof(VariantGear), Laser(), BaseKey)); + + // laser-big: a variant of laser that overrides its name and power and inherits the rest. + private static void SeedBig(CultCache cache, CultRecordKey? key = null, CultRecordKey? baseKey = null, string name = "laser big", int power = 25) => + cache.Commit(batch => batch.UpsertVariant(key ?? BigKey, baseKey ?? BaseKey, new[] + { + cache.Override(nameof(VariantGear.Name), name), + cache.Override(nameof(VariantGear.Power), power) + })); + + private static void EditBase(CultCache cache, Action edit) => + cache.Commit(batch => + { + var edited = Laser(); + edit(edited); + batch.Upsert(typeof(VariantGear), edited, BaseKey); + }); + + private static InvalidOperationException Refused(TestDelegate write) => + Assert.Throws(write)!; + + // ---- resolution ---- + + [Test] + public void ALoadedVariantResolvesAgainstItsBase() + { + var path = PathOf("gear.cc"); + using (var writer = Open(path)) + { + SeedBase(writer); + SeedBig(writer); + } + + using var cache = Open(path); + var big = cache.Get(BigKey)!; + Assert.That(big.Name, Is.EqualTo("laser big")); + Assert.That(big.Power, Is.EqualTo(25)); + Assert.That(big.Code, Is.EqualTo("l1"), "an inherited member"); + Assert.That(big.Tags, Is.EqualTo(new[] { "beam" }), "an inherited list"); + Assert.That(cache.Get(BaseKey)!.Power, Is.EqualTo(10)); + Assert.That(cache.GetStored(BigKey)!.Variant!.BaseKey, Is.EqualTo(BaseKey.Value)); + Assert.That(cache.GetStored(BigKey)!.Variant!.Overrides, Has.Count.EqualTo(2)); + } + + [Test] + public void AVariantOfAVariantResolvesBaseFirstAndFollowsTheRoot() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + SeedBig(cache); + var hugeKey = new CultRecordKey("laser-huge"); + SeedBig(cache, hugeKey, BigKey, name: "laser huge", power: 40); + + Assert.That(cache.Get(hugeKey)!.Tags, Is.EqualTo(new[] { "beam" })); + EditBase(cache, gear => gear.Tags.Add("pierce")); + + Assert.That(cache.Get(hugeKey)!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); + Assert.That(cache.Get(hugeKey)!.Power, Is.EqualTo(40)); + } + + [Test] + public void ABaseEditReachesItsVariantsThroughGetNameAndIndexAndOneWatchPublication() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + SeedBig(cache); + cache.Commit(batch => batch.UpsertVariant(new CultRecordKey("laser-coded"), BaseKey, new[] + { + cache.Override(nameof(VariantGear.Name), "laser coded"), + cache.Override(nameof(VariantGear.Code), "l9") + })); + + var seen = new List<(string Key, long Sequence, string BigTagsAtThatMoment, string BigNameLookupTags)>(); + using var subscription = cache.Watch().Subscribe(change => seen.Add(( + change.Key.Value, + change.Sequence, + string.Join(",", cache.Get(BigKey)!.Tags), + string.Join(",", cache.GetByName("laser big")!.Tags)))); + + EditBase(cache, gear => { gear.Tags.Add("pierce"); gear.Code = "l2"; }); + + Assert.That(cache.Get(BigKey)!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); + Assert.That(cache.GetByName("laser big")!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); + Assert.That(cache.GetByName("laser big")!.Power, Is.EqualTo(25), "the override survives the base edit"); + Assert.That(cache.GetByIndex("code", "l9")!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); + // big inherited the old code; its stale index entry must be gone, not shadowing. + Assert.That(cache.GetByIndex("code", "l1"), Is.Null); + Assert.That(cache.GetByIndex("code", "l2")!.Name, Is.Not.Null); + + Assert.That(seen.Select(entry => entry.Key), Is.EquivalentTo(new[] { BaseKey.Value, BigKey.Value, "laser-coded" })); + Assert.That(seen.Select(entry => entry.Sequence), Is.EqualTo(Enumerable.Range((int)seen[0].Sequence, seen.Count).Select(n => (long)n)), + "one commit, one run of sequences with no gap"); + Assert.That(seen.Select(entry => entry.BigTagsAtThatMoment), Is.All.EqualTo("beam,pierce"), + "a subscriber observing the base change already reads the new variant"); + Assert.That(seen.Select(entry => entry.BigNameLookupTags), Is.All.EqualTo("beam,pierce")); + } + + [Test] + public void AReResolvedDependentKeepsItsStoredAtAndIsAnUpdatedChange() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + SeedBig(cache); + var before = cache.GetStored(BigKey)!; + var changes = new List>(); + using var subscription = cache.WatchRecord(BigKey).Subscribe(changes.Add); + + EditBase(cache, gear => gear.Tags.Add("pierce")); + + Assert.That(cache.GetStored(BigKey)!.StoredAt, Is.EqualTo(before.StoredAt), "a base change stamps no dependent"); + Assert.That(changes, Has.Count.EqualTo(1)); + Assert.That(changes[0].Kind, Is.EqualTo(CultCacheDocumentChangeKind.Updated)); + Assert.That(changes[0].PreviousDocument!.Tags, Is.EqualTo(new[] { "beam" })); + Assert.That(changes[0].Document!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); + } + + [Test] + public void ExpectOnAVariantSurvivesABaseChangeButNotAChangeToItsDelta() + { + var path = PathOf("gear.cc"); + using (var seed = Open(path)) + { + SeedBase(seed); + SeedBig(seed); + } + + using var a = Open(path); + using var b = Open(path); + var seen = a.Get(BigKey)!; + + EditBase(b, gear => gear.Tags.Add("pierce")); + Assert.That(a.Commit(batch => + { + batch.Expect(BigKey, seen); + batch.Upsert(typeof(VariantOther), new VariantOther { Name = "marker" }, new CultRecordKey("marker")); + }), Is.True, "the base changed; the variant's stored delta did not"); + + a.PullAllBackingStoresAsync(); + seen = a.Get(BigKey)!; + SeedBig(b, power: 26); + Assert.That(a.Commit(batch => + { + batch.Expect(BigKey, seen); + batch.Upsert(typeof(VariantOther), new VariantOther { Name = "second" }, new CultRecordKey("second")); + }), Is.False, "another writer changed the variant's own delta"); + } + + // ---- refusals, each naming the keys ---- + + [Test] + public void ACycleOfBasesIsRefusedNamingEveryKey() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + var a = new CultRecordKey("cycle-a"); + var b = new CultRecordKey("cycle-b"); + + var staged = Refused(() => cache.Commit(batch => + { + batch.UpsertVariant(a, b); + batch.UpsertVariant(b, a); + })); + Assert.That(staged.Message, Does.Contain("cycle").And.Contain(a.Value).And.Contain(b.Value)); + + SeedBig(cache); + var huge = new CultRecordKey("laser-huge"); + SeedBig(cache, huge, BigKey, name: "laser huge"); + var rebased = Refused(() => cache.Commit(batch => batch.UpsertVariant(BigKey, huge))); + Assert.That(rebased.Message, Does.Contain("cycle").And.Contain(BigKey.Value).And.Contain(huge.Value)); + Assert.That(cache.GetStored(BigKey)!.Variant!.BaseKey, Is.EqualTo(BaseKey.Value), "nothing landed"); + } + + [Test] + public void AMissingBaseIsRefusedNamingBoth() + { + using var cache = Open(PathOf("gear.cc")); + var error = Refused(() => cache.UpsertVariantAsync(BigKey, new CultRecordKey("no-such-base")).GetAwaiter().GetResult()); + Assert.That(error.Message, Does.Contain(BigKey.Value).And.Contain("no-such-base")); + Assert.That(cache.Get(BigKey), Is.Null); + } + + [Test] + public void ABaseInAnotherTypeIsRefusedOnRebaseAndOnLoad() + { + var path = PathOf("gear.cc"); + using (var cache = Open(path)) + { + SeedBase(cache); + SeedBig(cache); + cache.Commit(batch => batch.Upsert(typeof(VariantOther), new VariantOther { Name = "other" }, new CultRecordKey("other"))); + + var rebase = Refused(() => cache.Commit(batch => batch.UpsertVariant(BigKey, new CultRecordKey("other")))); + Assert.That(rebase.Message, Does.Contain(BigKey.Value).And.Contain("VariantOther")); + } + + // A store whose variant record names another type than its base's: the loader refuses it naming both keys. + var bad = PathOf("bad.cc"); + var gear = Registry.GetRequired(); + var other = Registry.GetRequired(); + File.WriteAllBytes(bad, CultDocumentMessagePackSerialization.SerializeSnapshot(new CultPersistedStoreSnapshot + { + FormatVersion = CultPersistedStoreSnapshot.FormatV2, + SchemaCatalog = new[] { gear.ToCatalogEntry(), other.ToCatalogEntry() }, + Records = new[] + { + new CultPersistedRecord + { + Key = "gear-base", SchemaId = gear.SchemaId, StoredAt = "2026-01-01T00:00:00.0000000Z", + Payload = CultDocumentMessagePackSerialization.SerializeUntyped(Laser(), typeof(VariantGear), Registry) + }, + new CultPersistedRecord + { + Key = "other-variant", SchemaId = other.SchemaId, StoredAt = "2026-01-01T00:00:00.0000000Z", + Variant = new CultVariantDelta("gear-base", Array.Empty()) + } + } + })); + var load = Refused(() => Open(bad).Dispose()); + Assert.That(load.Message, Does.Contain("other-variant").And.Contain("gear-base")); + } + + [Test] + public void AVariantOfAGlobalIsRefused() + { + using var cache = Open(PathOf("gear.cc")); + var key = cache.UpsertAsync(new VariantGlobal { Value = "one" }).GetAwaiter().GetResult().Key; + var error = Refused(() => cache.UpsertVariantAsync(BigKey, key).GetAwaiter().GetResult()); + Assert.That(error.Message, Does.Contain(BigKey.Value).And.Contain("global")); + } + + [Test] + public void RemovingABaseThatKeepsVariantsIsRefusedUnlessTheSameBatchRemovesOrRebasesThem() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + var spare = new CultRecordKey("spare"); + cache.Commit(batch => batch.Upsert(typeof(VariantGear), new VariantGear { Name = "spare", Power = 3 }, spare)); + SeedBig(cache); + + var refused = Refused(() => cache.Commit(batch => batch.Remove(BaseKey))); + Assert.That(refused.Message, Does.Contain(BaseKey.Value).And.Contain(BigKey.Value)); + Assert.That(cache.Get(BaseKey), Is.Not.Null); + Assert.That(cache.Get(BigKey), Is.Not.Null); + + Assert.That(cache.Commit(batch => + { + batch.UpsertVariant(BigKey, spare, cache.GetStored(BigKey)!.Variant!.Overrides); + batch.Remove(BaseKey); + }), Is.True, "rebased in the same batch"); + Assert.That(cache.Get(BigKey)!.Code, Is.EqualTo(string.Empty), "now resolved from spare"); + + Assert.That(cache.Commit(batch => + { + batch.Remove(spare); + batch.Remove(BigKey); + }), Is.True, "removed in the same batch"); + } + + [Test] + public void AVariantThatKeepsItsBasesNameIsRefused() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + var error = Refused(() => cache.UpsertVariantAsync(BigKey, BaseKey).GetAwaiter().GetResult()); + Assert.That(error.Message, Does.Contain(BigKey.Value).And.Contain(BaseKey.Value).And.Contain("laser")); + + var sameName = Refused(() => SeedBig(cache, name: "laser")); + Assert.That(sameName.Message, Does.Contain(BigKey.Value).And.Contain(BaseKey.Value)); + + SeedBig(cache); + var grand = new CultRecordKey("laser-grand"); + var grandOfBase = Refused(() => SeedBig(cache, grand, BigKey, name: "laser")); + Assert.That(grandOfBase.Message, Does.Contain(grand.Value).And.Contain(BaseKey.Value), "the whole chain, not only the parent"); + } + + [Test] + public void ABaseEditThatWouldGiveAVariantItsBasesNameIsRefused() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + SeedBig(cache); + + var error = Refused(() => EditBase(cache, gear => gear.Name = "laser big")); + Assert.That(error.Message, Does.Contain(BigKey.Value).And.Contain(BaseKey.Value)); + Assert.That(cache.Get(BaseKey)!.Name, Is.EqualTo("laser")); + } + + [Test] + public void APlainWriteAtAVariantsKeyIsRefusedByEveryPathAndFlattenIsTheExplicitWay() + { + var path = PathOf("gear.cc"); + using var cache = Open(path); + SeedBase(cache); + SeedBig(cache); + var plain = new VariantGear { Name = "laser big", Power = 99 }; + + Assert.That(Refused(() => cache.UpsertAsync(typeof(VariantGear), plain, BigKey).GetAwaiter().GetResult()).Message, + Does.Contain(BigKey.Value)); + Assert.That(Refused(() => cache.Commit(batch => batch.Upsert(typeof(VariantGear), plain, BigKey))).Message, + Does.Contain(BigKey.Value)); + Assert.That(cache.GetStored(BigKey)!.Variant, Is.Not.Null); + Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(25)); + + cache.FlattenAsync(BigKey).GetAwaiter().GetResult(); + var flat = cache.GetStored(BigKey)!; + Assert.That(flat.Variant, Is.Null); + Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(25), "flatten keeps the resolved values"); + EditBase(cache, gear => gear.Tags.Add("pierce")); + Assert.That(cache.Get(BigKey)!.Tags, Is.EqualTo(new[] { "beam" }), "a flattened record no longer follows its base"); + cache.UpsertAsync(typeof(VariantGear), plain, BigKey).GetAwaiter().GetResult(); + Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(99), "and is an ordinary record again"); + cache.FlushAsync().GetAwaiter().GetResult(); + Assert.That(HeaderOf(path), Is.EqualTo("cultcache.store.v1"), "no variant left in the store"); + } + + [Test] + public void FlattenRefusesARecordThatIsNotAVariantAndAPlainRecordCannotBecomeOne() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + Assert.That(Refused(() => cache.FlattenAsync(BaseKey).GetAwaiter().GetResult()).Message, Does.Contain(BaseKey.Value)); + var spare = new CultRecordKey("spare"); + cache.Commit(batch => batch.Upsert(typeof(VariantGear), new VariantGear { Name = "spare" }, spare)); + Assert.That(Refused(() => cache.UpsertVariantAsync(spare, BaseKey).GetAwaiter().GetResult()).Message, Does.Contain(spare.Value)); + } + + [Test] + public void ACacheWithoutACodecHoldsNoVariants() + { + using var cache = new CultCache(Registry); + cache.Commit(batch => batch.Upsert(typeof(VariantGear), Laser(), BaseKey)); + var error = Refused(() => cache.UpsertVariantAsync(BigKey, BaseKey).GetAwaiter().GetResult()); + Assert.That(error.Message, Does.Contain(BigKey.Value).And.Contain("codec")); + } + + [Test] + public void OnlyTopLevelSetOverridesResolveInThisCut() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + var element = new CultVariantOverride( + CultOverrideOp.Set, new[] { new CultPathStep(3, "el-1"), new CultPathStep(0) }, string.Empty, new byte[] { 0x01 }); + var error = Refused(() => cache.UpsertVariantAsync(BigKey, BaseKey, new[] { element }).GetAwaiter().GetResult()); + Assert.That(error.Message, Does.Contain(BigKey.Value).And.Contain("top-level")); + + var insert = new CultVariantOverride(CultOverrideOp.Insert, new[] { new CultPathStep(3) }, "new", new byte[] { 0xa1, 0x78 }); + Assert.That(Refused(() => cache.UpsertVariantAsync(BigKey, BaseKey, new[] { insert }).GetAwaiter().GetResult()).Message, + Does.Contain(BigKey.Value).And.Contain("top-level")); + } + + // ---- soft drift: an override drifts exactly as the same member would on a plain record ---- + + [Test] + public void AnOverrideOfASlotTheTypeNoLongerHasIsIgnoredWithAWarningNamingVariantAndMember() + { + var path = PathOf("drift.cc"); + var wide = CultDocumentRegistry.ForTypes(new[] { typeof(DriftWide) }); + using (var writer = Open(path, registry: wide)) + { + writer.Commit(batch => + { + batch.Upsert(typeof(DriftWide), new DriftWide { Name = "drift", Power = 1, Wing = "base wing" }, new CultRecordKey("drift-base")); + batch.UpsertVariant(new CultRecordKey("drift-variant"), new CultRecordKey("drift-base"), new[] + { + writer.Override(nameof(DriftWide.Name), "drift variant"), + writer.Override(nameof(DriftWide.Power), 7), + writer.Override(nameof(DriftWide.Wing), "variant wing") + }); + }); + } + + var narrow = CultDocumentRegistry.ForTypes(new[] { typeof(DriftNarrow) }); + using var cache = Open(path, registry: narrow); + var variant = cache.Get(new CultRecordKey("drift-variant"))!; + Assert.That(variant.Power, Is.EqualTo(7), "the override the type still has applies"); + Assert.That(variant.Name, Is.EqualTo("drift variant")); + + var report = cache.VariantMigrationReports.Single(); + Assert.That(report.Kind, Is.EqualTo(CultSchemaMigrationKind.CompatibleDrift)); + Assert.That(report.IgnoredExtraSlots, Is.EqualTo(new[] { 2 })); + var warning = report.Warnings.Single(); + Assert.That(warning.Code, Is.EqualTo("ignored_extra_slot"), "the code a dropped member gets on a plain record"); + Assert.That(warning.Message, Does.Contain("drift-variant").And.Contain("Wing")); + } + + [Test] + public void AnOverrideThatNoLongerDecodesIsIgnoredWithAWarningAndTheBaseValueApplies() + { + var path = PathOf("gear.cc"); + const int notAnInt = 1; // VariantGear.Power, [Key(1)] + using (var cache = Open(path)) + { + SeedBase(cache); + cache.Commit(batch => batch.UpsertVariant(BigKey, BaseKey, new[] + { + cache.Override(nameof(VariantGear.Name), "laser big"), + CultVariantOverride.Set(notAnInt, new byte[] { 0xa3, (byte)'a', (byte)'b', (byte)'c' }) + })); + var warning = cache.VariantMigrationReports.Single().Warnings.Single(); + Assert.That(warning.Message, Does.Contain(BigKey.Value).And.Contain("Power")); + Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(10), "inherits the base value"); + Assert.That(cache.Get(BigKey)!.Name, Is.EqualTo("laser big")); + } + + using var reloaded = Open(path); + Assert.That(reloaded.Get(BigKey)!.Power, Is.EqualTo(10)); + Assert.That(reloaded.VariantMigrationReports.Single().Warnings.Single().Message, Does.Contain("Power")); + } + + // ---- persisted format ---- + + private static string HeaderOf(string path) => + CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).FormatVersion; + + [Test] + public void TheHeaderIsV1WithoutVariantsAndV2WithThem() + { + var path = PathOf("gear.cc"); + using var cache = Open(path); + SeedBase(cache); + Assert.That(HeaderOf(path), Is.EqualTo("cultcache.store.v1")); + + SeedBig(cache); + Assert.That(HeaderOf(path), Is.EqualTo("cultcache.store.v2")); + var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)); + var variant = snapshot.Records.Single(record => record.Key == BigKey.Value); + Assert.That(variant.Payload, Is.Empty, "the payload is the tripwire old readers refuse on"); + Assert.That(variant.Variant!.BaseKey, Is.EqualTo(BaseKey.Value)); + Assert.That(snapshot.Records.Single(record => record.Key == BaseKey.Value).Variant, Is.Null); + + cache.Commit(batch => batch.Remove(BigKey)); + Assert.That(HeaderOf(path), Is.EqualTo("cultcache.store.v1"), "the last variant gone, the store is v1 again"); + } + + [Test] + public async Task AStoreWithoutVariantsRewritesByteIdenticalToTheOneWrittenBeforeVariantsExisted() + { + var fixture = Path.Combine(TestContext.CurrentContext.TestDirectory, "Fixtures", "pre-cut2", "single-file-v1", "store.msgpack"); + var copy = PathOf("store.msgpack"); + File.Copy(fixture, copy); + var before = File.ReadAllBytes(copy); + + using (var cache = new CultCache(CultDocumentRegistry.ForTypes(new[] { typeof(PreCut2FixtureItem), typeof(PreCut2FixtureNote) }))) + { + cache.AddBackingStore(new SingleFileMessagePackBackingStore(copy)); + await cache.PullAllBackingStoresAsync(); + cache.BackingStores[0].PushAll(); + } + + Assert.That(File.ReadAllBytes(copy), Is.EqualTo(before)); + } + + [Test] + public void AVariantStoreRoundTripsByteIdenticalThroughAFlush() + { + var path = PathOf("gear.cc"); + using (var cache = Open(path)) + { + SeedBase(cache); + SeedBig(cache); + } + + var written = File.ReadAllBytes(path); + using (var cache = Open(path)) + { + cache.BackingStores[0].PushAll(); + } + + Assert.That(File.ReadAllBytes(path), Is.EqualTo(written)); + } + + [Test] + public void AReadOnlyStoreResolvesItsVariants() + { + var path = PathOf("gear.cc"); + using (var cache = Open(path)) + { + SeedBase(cache); + SeedBig(cache); + } + + var before = File.ReadAllBytes(path); + using var readOnly = Open(path, readOnly: true); + Assert.That(readOnly.Get(BigKey)!.Power, Is.EqualTo(25)); + Assert.That(readOnly.Get(BigKey)!.Code, Is.EqualTo("l1")); + Assert.That(File.ReadAllBytes(path), Is.EqualTo(before)); + } + + [Test] + public void ABaseEditFromAnotherWriterReachesVariantsWhenTheStoreIsPulled() + { + var path = PathOf("gear.cc"); + using var a = Open(path); + SeedBase(a); + SeedBig(a); + using var b = Open(path); + Assert.That(b.Get(BigKey)!.Tags, Is.EqualTo(new[] { "beam" })); + + EditBase(a, gear => gear.Tags.Add("pierce")); + b.PullAllBackingStoresAsync(); + + Assert.That(b.Get(BigKey)!.Tags, Is.EqualTo(new[] { "beam", "pierce" }), + "the pull carried only the base; the variant was re-resolved in the admitting hold"); + } + + [Test] + public void ARebaseResolvesFromTheNewBase() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + SeedBig(cache); + var spare = new CultRecordKey("spare"); + cache.Commit(batch => batch.Upsert(typeof(VariantGear), new VariantGear { Name = "spare", Code = "s1", Tags = { "arc" } }, spare)); + + cache.Commit(batch => batch.UpsertVariant(BigKey, spare, cache.GetStored(BigKey)!.Variant!.Overrides)); + + Assert.That(cache.Get(BigKey)!.Tags, Is.EqualTo(new[] { "arc" })); + Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(25)); + Assert.That(cache.GetStored(BigKey)!.Variant!.BaseKey, Is.EqualTo(spare.Value)); + } + + // ---- the other stores refuse loudly until their own cuts ---- + + [Test] + public void TheDirectoryStoreRefusesAVariantByPushAndByCommit() + { + using var cache = CultCacheMessagePack.Create(PathOf("dir.cc"), new CultCacheOpenOptions { Registry = Registry, UseDirectoryStore = true }); + SeedBase(cache); + + var push = Assert.Throws(() => cache.UpsertVariantAsync( + BigKey, BaseKey, new[] { cache.Override(nameof(VariantGear.Name), "laser big") }).GetAwaiter().GetResult())!; + Assert.That(push.Message, Does.Contain(BigKey.Value)); + var commit = Assert.Throws(() => SeedBig(cache))!; + Assert.That(commit.Message, Does.Contain(BigKey.Value)); + Assert.That(cache.Get(BigKey), Is.Null); + } + + // ---- shared vector ---- + + // Written once by the code under test through the production path; every runtime's tests read the committed bytes. + // CULTLIB_WRITE_VARIANT_VECTOR=1 prints the store as base64 instead of asserting. + [Test] + public void TheCommittedC1VectorResolvesAndRewritesByteIdentical() + { + var vector = VectorPath("variant-store.msgpack"); + var path = PathOf("gear.cc"); + if (Environment.GetEnvironmentVariable("CULTLIB_WRITE_VARIANT_VECTOR") == "1") + { + using (var cache = Open(path)) + { + SeedBase(cache); + SeedBig(cache); + } + + Console.WriteLine("VARIANT-VECTOR-BASE64:" + Convert.ToBase64String(File.ReadAllBytes(path))); + Assert.Pass("vector printed"); + } + + File.Copy(vector, path); + using (var cache = Open(path)) + { + Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(25)); + Assert.That(cache.Get(BigKey)!.Code, Is.EqualTo("l1")); + cache.BackingStores[0].PushAll(); + } + + Assert.That(File.ReadAllBytes(path), Is.EqualTo(File.ReadAllBytes(vector))); + Assert.That(HeaderOf(path), Is.EqualTo("cultcache.store.v2")); + } + + private static string VectorPath(string name) + { + for (var dir = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); dir != null; dir = dir.Parent) + { + var candidate = Path.Combine(dir.FullName, "tests", "vectors", "document-variants-c1", name); + if (File.Exists(candidate) || Environment.GetEnvironmentVariable("CULTLIB_WRITE_VARIANT_VECTOR") == "1" && Directory.Exists(Path.GetDirectoryName(candidate))) + return candidate; + } + + if (Environment.GetEnvironmentVariable("CULTLIB_WRITE_VARIANT_VECTOR") == "1") + return name; + throw new FileNotFoundException($"Shared vector {name} not found above {TestContext.CurrentContext.TestDirectory}."); + } + + [CultDocument("tests.variant_gear", "tests.variant_gear.v1")] + [MessagePackObject(AllowPrivate = true)] + internal sealed class VariantGear + { + [Key(0)] + [CultName] + public string Name = string.Empty; + + [Key(1)] + public int Power; + + [Key(2)] + [CultIndex("code")] + public string Code = string.Empty; + + [Key(3)] + public List Tags = new(); + } + + [CultDocument("tests.variant_other", "tests.variant_other.v1")] + [MessagePackObject(AllowPrivate = true)] + internal sealed class VariantOther + { + [Key(0)] + [CultName] + public string Name = string.Empty; + } + + [CultDocument("tests.variant_global", "tests.variant_global.v1")] + [MessagePackObject(AllowPrivate = true)] + [CultGlobal] + internal sealed class VariantGlobal + { + [Key(0)] + public string Value = string.Empty; + } + + // The same schema at two versions of the type: Wide has a member Narrow later dropped. + [CultDocument("tests.variant_drift", "tests.variant_drift.v1")] + [MessagePackObject(AllowPrivate = true)] + internal sealed class DriftWide + { + [Key(0)] + [CultName] + public string Name = string.Empty; + + [Key(1)] + public int Power; + + [Key(2)] + public string Wing = string.Empty; + } + + [CultDocument("tests.variant_drift", "tests.variant_drift.v2")] + [MessagePackObject(AllowPrivate = true)] + internal sealed class DriftNarrow + { + [Key(0)] + [CultName] + public string Name = string.Empty; + + [Key(1)] + public int Power; + } + } +} diff --git a/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs b/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs index a5be069a..2521aa8a 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs @@ -45,10 +45,16 @@ public sealed class CultMeshVariantRefusalTests message.Should().Contain("item:anvil").And.Contain(ItemSchemaId); } + // Q6: CultMesh does not resolve variants. It refuses a variant key naming it and its base, and still reads the plain + // records of the same v2 store. [Test] - public void ReadSingleFileDocument_RefusesVariantStoreByVersionOrRecord() + public void ReadSingleFileDocument_RefusesAVariantKeyByNameButReadsItsPlainNeighbours() { - var message = Refusal("variant-v2.msgpack").Message; - (message.Contains("cultcache.store.v2") || message.Contains("item:anvil-big")).Should().BeTrue(message); + var refusal = Assert.Throws(() => + CultMesh.ReadSingleFileDocumentPayload(VectorPath("variant-v2.msgpack"), new CultRecordKey("item:anvil-big"), ItemSchemaId))!; + refusal.Message.Should().Contain("item:anvil-big").And.Contain("item:anvil'"); + + CultMesh.ReadSingleFileDocumentPayload(VectorPath("variant-v2.msgpack"), new CultRecordKey("item:bellows"), ItemSchemaId) + .Should().NotBeEmpty(); } } diff --git a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs new file mode 100644 index 00000000..46f91438 --- /dev/null +++ b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs @@ -0,0 +1,78 @@ +#nullable enable +using System; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using NUnit.Framework; + +namespace GameCult.Networking.Tests +{ + // Q6 (docs/document-variants-cut.md C1): CultNet carries no variant deltas yet, so building a row for one is refused + // loudly, on the v1 selection path and on the v0 snapshot path alike. + public sealed class CultNetDocumentRegistryVariantTests + { + private static readonly CultRecordKey BaseKey = new("variant-fixture-base"); + private static readonly CultRecordKey VariantKey = new("variant-fixture-big"); + + private static async Task<(CultCache Cache, CultNetDocumentRegistry Documents)> BuildFixtureAsync(bool withVariant) + { + var registry = CultDocumentRegistry.Shared; + var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry)); + var documents = new CultNetDocumentRegistry(registry) + .Register(CultNetDocumentBinding.ForDocument(registry)); + await cache.UpsertAsync(new VariantWireFixture { Name = "base", Power = 1 }, new CultRecordHandle(BaseKey)); + if (withVariant) + await cache.UpsertVariantAsync(VariantKey, BaseKey, new[] + { + cache.Override(nameof(VariantWireFixture.Name), "big"), + cache.Override(nameof(VariantWireFixture.Power), 9) + }); + return (cache, documents); + } + + [Test] + public async Task SelectionResponseRefusesAVariantRowNamingIt() + { + var (cache, documents) = await BuildFixtureAsync(withVariant: true); + var selection = new CultNetSelection { Projection = CultNetSelectionProjections.Document }; + + var error = Assert.Throws(() => + documents.CreateSelectionResponse(cache, "m1", selection, ordinalOf: (_, _) => 1, asOf: 1))!; + + Assert.That(error.Message, Does.Contain(VariantKey.Value).And.Contain(BaseKey.Value)); + } + + [Test] + public async Task RawSnapshotResponseRefusesAVariantRowNamingIt() + { + var (cache, documents) = await BuildFixtureAsync(withVariant: true); + + var error = Assert.Throws(() => documents.CreateRawSnapshotResponse(cache, "m1"))!; + + Assert.That(error.Message, Does.Contain(VariantKey.Value)); + } + + [Test] + public async Task ACacheWithoutVariantsStillAnswersBothPaths() + { + var (cache, documents) = await BuildFixtureAsync(withVariant: false); + var selection = new CultNetSelection { Projection = CultNetSelectionProjections.Document }; + + Assert.That(documents.CreateSelectionResponse(cache, "m1", selection, ordinalOf: (_, _) => 1, asOf: 1).Documents, Has.Length.EqualTo(1)); + Assert.That(documents.CreateRawSnapshotResponse(cache, "m2").Documents, Has.Length.EqualTo(1)); + } + + [CultDocument("variants.wire-fixture", "variants.wire-fixture.v1")] + [MessagePackObject(AllowPrivate = true)] + public sealed class VariantWireFixture + { + [Key(0)] + [CultName] + public string Name = string.Empty; + + [Key(1)] + public int Power; + } + } +} diff --git a/tests/vectors/document-variants-c1/.gitattributes b/tests/vectors/document-variants-c1/.gitattributes new file mode 100644 index 00000000..8efeaf12 --- /dev/null +++ b/tests/vectors/document-variants-c1/.gitattributes @@ -0,0 +1,3 @@ +# Refusal vectors are byte-exact; never convert line endings. +* binary +*.py text diff --git a/tests/vectors/document-variants-c1/variant-store.msgpack b/tests/vectors/document-variants-c1/variant-store.msgpack new file mode 100644 index 0000000000000000000000000000000000000000..3604a68da1979eac264453f272960bea7d7ed467 GIT binary patch literal 1391 zcmcJOO^ee&7{|No&6`JWnyYP?nPieo5JC2^2qIz^FCsFTJkt#%sbr?rvh0Uwt=MCg z?m^JYg7;GW67|zKNn^CugW&c!&)fg^yv&(q#!8|`;EI__5X(YYx zhwslUW!lO3Bc6d3TDy8yyN-AYg-ZJQUxN&kiOV31Opp~mGgZ^RwnEgl@=f8Ye%sQc zm!(X1q%>r9R~Jd%Gnt8c0ulmg^}DQd5~*|><6T3=NAcSNRIk3?0{VDNG!3@Na~^d!QwP5 zC%mV2SdRK>3PPKuEBhF7C=y{mOq9O6wZ41%9NY8radYke`@g2M)}p+P&s+Gb)$;3d zc5qSM#i!a;orCeLmb1e}xu>0+)uJ5j?AoH7+}f`5{&8Ye<;nCSu-IVAmVip z>kxK=aOnCWVm89&^ZV=$LLoxmZq%aJKcslPh=6BrKUNf-DCzB)1XI_iKCMYwlTG`R VX=^-b&F348TLz;v9L(o8e*nV`+>rnP literal 0 HcmV?d00001 From 1ddf6e0d562f855fbdb04888674264ebf3bdea98 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 04:17:31 +0200 Subject: [PATCH 48/64] Mark the three share-mode tests Windows-only They hold a FileShare.Read handle and expect a delete or replace to fail; Linux unlink and rename ignore open handles, so they can never pass there and showed as three standing failures. [Platform("Win")] reports them skipped with a reason on Linux and keeps them running on Windows. No Linux failure injection exists: the store names its temp file with a fresh GUID and the suite is likely root in the verify container, so read-only directories do not fail. Co-Authored-By: Claude Sonnet 5 --- tests/GameCult.Caching.Tests/BackingStoreTests.cs | 1 + tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs | 1 + tests/GameCult.Caching.Tests/StoreRoutingTests.cs | 1 + 3 files changed, 3 insertions(+) diff --git a/tests/GameCult.Caching.Tests/BackingStoreTests.cs b/tests/GameCult.Caching.Tests/BackingStoreTests.cs index 86613c52..7e88c283 100644 --- a/tests/GameCult.Caching.Tests/BackingStoreTests.cs +++ b/tests/GameCult.Caching.Tests/BackingStoreTests.cs @@ -707,6 +707,7 @@ namespace GameCult.Caching.Tests } [Test] + [Platform("Win", Reason = "Holds an open FileShare.Read handle and expects a delete or replace to fail; Linux unlink and rename ignore open handles.")] public async Task DirectoryMessagePackBackingStore_Deletion_Commits_While_Locked_Old_Page_Remains_An_Orphan() { var filePath = Path.Combine(Path.GetTempPath(), $"cultlib-tests-{Guid.NewGuid():N}.cc"); diff --git a/tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs b/tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs index 41ef46ad..840110bc 100644 --- a/tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs +++ b/tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs @@ -37,6 +37,7 @@ namespace GameCult.Caching.Tests } [Test] + [Platform("Win", Reason = "Holds an open FileShare.Read handle and expects a delete or replace to fail; Linux unlink and rename ignore open handles.")] public async Task FailedManifestReplaceKeepsPreviousGeneration() { using var cache = Open(out _); diff --git a/tests/GameCult.Caching.Tests/StoreRoutingTests.cs b/tests/GameCult.Caching.Tests/StoreRoutingTests.cs index fc99f01f..af7e7da7 100644 --- a/tests/GameCult.Caching.Tests/StoreRoutingTests.cs +++ b/tests/GameCult.Caching.Tests/StoreRoutingTests.cs @@ -439,6 +439,7 @@ namespace GameCult.Caching.Tests } [Test] + [Platform("Win", Reason = "Holds an open FileShare.Read handle and expects a delete or replace to fail; Linux unlink and rename ignore open handles.")] public void BatchIsAllOrNothingOnStoreFailure() { var registry = Registry(); From 33664434f95b59253d0de50d32d9ef770dace13d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 04:21:58 +0200 Subject: [PATCH 49/64] Drop the unreachable single-record CultMesh variant refusal; tolerate duplicate catalog slots A variant needs its base beside it, so a single-record store can never hold one: that overload's refusal could not fire. SlotNames no longer throws on a catalog that repeats a slot. Co-Authored-By: Claude Sonnet 5 --- src/GameCult.Caching/CultCache.cs | 2 +- src/GameCult.Mesh/CultMeshSingleFileDocuments.cs | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 24c20cfc..00b849a0 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -2919,7 +2919,7 @@ namespace GameCult.Caching resolution.Descriptor, new CultVariantDelta(record.Variant.BaseKey, record.Variant.Overrides) { - SlotNames = persisted?.Members.ToDictionary(member => member.Slot, member => member.MemberName) + SlotNames = persisted?.Members.GroupBy(member => member.Slot).ToDictionary(group => group.Key, group => group.First().MemberName) }, null); } diff --git a/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs b/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs index 67cc4cdf..700b7a50 100644 --- a/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs +++ b/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs @@ -191,8 +191,6 @@ namespace GameCult.Mesh $"CultCache document '{path}' has schema '{record.SchemaId}', expected '{expectedSchemaId}'."); } - RefuseVariant(path, record); - if (!PublishesSchema(snapshot.SchemaCatalog, expectedSchemaId)) { throw new InvalidDataException( From b93934f6b432bff62efc144cc6b6308d9df4ee6a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 04:21:59 +0200 Subject: [PATCH 50/64] Pin the variant rules a mutant survived or that lost their only test Reader refusals (v1 header over a variant, payload on a variant, unknown op), a load that finds a variant flattened by another writer, a re-resolution reaching a read-only cache, a base removed in the same batch as its new variant, and plain-record-to-variant refused without the name rule masking it. Co-Authored-By: Claude Sonnet 5 --- tests/GameCult.Caching.Tests/VariantTests.cs | 99 +++++++++++++++++++- 1 file changed, 97 insertions(+), 2 deletions(-) diff --git a/tests/GameCult.Caching.Tests/VariantTests.cs b/tests/GameCult.Caching.Tests/VariantTests.cs index 501af538..fec33c96 100644 --- a/tests/GameCult.Caching.Tests/VariantTests.cs +++ b/tests/GameCult.Caching.Tests/VariantTests.cs @@ -304,6 +304,14 @@ namespace GameCult.Caching.Tests batch.Remove(spare); batch.Remove(BigKey); }), Is.True, "removed in the same batch"); + + SeedBase(cache); + var removedInTheBatch = Refused(() => cache.Commit(batch => + { + batch.Remove(BaseKey); + batch.UpsertVariant(BigKey, BaseKey); + })); + Assert.That(removedInTheBatch.Message, Does.Contain(BigKey.Value).And.Contain(BaseKey.Value)); } [Test] @@ -371,7 +379,9 @@ namespace GameCult.Caching.Tests Assert.That(Refused(() => cache.FlattenAsync(BaseKey).GetAwaiter().GetResult()).Message, Does.Contain(BaseKey.Value)); var spare = new CultRecordKey("spare"); cache.Commit(batch => batch.Upsert(typeof(VariantGear), new VariantGear { Name = "spare" }, spare)); - Assert.That(Refused(() => cache.UpsertVariantAsync(spare, BaseKey).GetAwaiter().GetResult()).Message, Does.Contain(spare.Value)); + var named = new[] { cache.Override(nameof(VariantGear.Name), "spare variant") }; + Assert.That(Refused(() => cache.UpsertVariantAsync(spare, BaseKey, named).GetAwaiter().GetResult()).Message, Does.Contain(spare.Value)); + Assert.That(cache.GetStored(spare)!.Variant, Is.Null, "the plain record is still plain"); } [Test] @@ -529,10 +539,16 @@ namespace GameCult.Caching.Tests SeedBig(cache); } - var before = File.ReadAllBytes(path); using var readOnly = Open(path, readOnly: true); Assert.That(readOnly.Get(BigKey)!.Power, Is.EqualTo(25)); Assert.That(readOnly.Get(BigKey)!.Code, Is.EqualTo("l1")); + + // A base edit another writer commits reaches the read-only cache's variant when it pulls: a re-resolution is no write. + using var writer = Open(path); + EditBase(writer, gear => gear.Tags.Add("pierce")); + var before = File.ReadAllBytes(path); + readOnly.PullAllBackingStoresAsync(); + Assert.That(readOnly.Get(BigKey)!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); Assert.That(File.ReadAllBytes(path), Is.EqualTo(before)); } @@ -553,6 +569,24 @@ namespace GameCult.Caching.Tests "the pull carried only the base; the variant was re-resolved in the admitting hold"); } + [Test] + public void AFlattenFromAnotherWriterReachesACacheHoldingTheVariant() + { + var path = PathOf("gear.cc"); + using var a = Open(path); + SeedBase(a); + SeedBig(a); + using var b = Open(path); + Assert.That(b.GetStored(BigKey)!.Variant, Is.Not.Null); + + a.FlattenAsync(BigKey).GetAwaiter().GetResult(); + a.FlushAsync().GetAwaiter().GetResult(); + b.PullAllBackingStoresAsync(); + + Assert.That(b.GetStored(BigKey)!.Variant, Is.Null, "a load reports what is on disk; it is not a plain write refused at a variant key"); + Assert.That(b.Get(BigKey)!.Power, Is.EqualTo(25)); + } + [Test] public void ARebaseResolvesFromTheNewBase() { @@ -569,6 +603,67 @@ namespace GameCult.Caching.Tests Assert.That(cache.GetStored(BigKey)!.Variant!.BaseKey, Is.EqualTo(spare.Value)); } + // ---- readers ---- + + private string WriteStore(params CultPersistedRecord[] records) => WriteStore(CultPersistedStoreSnapshot.FormatV2, records); + + private string WriteStore(string formatVersion, params CultPersistedRecord[] records) + { + var path = PathOf($"hand-{Guid.NewGuid():N}.cc"); + var gear = Registry.GetRequired(); + File.WriteAllBytes(path, CultDocumentMessagePackSerialization.SerializeSnapshot(new CultPersistedStoreSnapshot + { + FormatVersion = formatVersion, + SchemaCatalog = new[] { gear.ToCatalogEntry() }, + Records = records + })); + return path; + } + + private static CultPersistedRecord PlainGear(string key) => new() + { + Key = key, + SchemaId = Registry.GetRequired().SchemaId, + StoredAt = "2026-01-01T00:00:00.0000000Z", + Payload = CultDocumentMessagePackSerialization.SerializeUntyped(Laser(), typeof(VariantGear), Registry) + }; + + private static CultPersistedRecord VariantGearRecord(string key, string baseKey, byte[]? payload = null, CultOverrideOp op = CultOverrideOp.Set) => new() + { + Key = key, + SchemaId = Registry.GetRequired().SchemaId, + StoredAt = "2026-01-01T00:00:00.0000000Z", + Payload = payload ?? Array.Empty(), + Variant = new CultVariantDelta(baseKey, new[] + { + new CultVariantOverride(op, new[] { new CultPathStep(0) }, string.Empty, new byte[] { 0xa1, (byte)'x' }) + }) + }; + + [Test] + public void AVariantRecordUnderAV1HeaderIsRefusedNamingTheRecord() + { + var path = WriteStore(CultPersistedStoreSnapshot.FormatV1, PlainGear("hand-base"), VariantGearRecord("hand-variant", "hand-base")); + var error = Assert.Throws(() => Open(path).Dispose())!; + Assert.That(error.Message, Does.Contain("hand-variant").And.Contain("cultcache.store.v2")); + } + + [Test] + public void AVariantRecordWithAPayloadIsRefusedNamingTheRecord() + { + var path = WriteStore(PlainGear("hand-base"), VariantGearRecord("hand-variant", "hand-base", payload: new byte[] { 0x90 })); + var error = Assert.Throws(() => Open(path).Dispose())!; + Assert.That(error.Message, Does.Contain("hand-variant").And.Contain("payload")); + } + + [Test] + public void AnOverrideWithAnUnknownOpIsRefusedNamingTheRecord() + { + var path = WriteStore(PlainGear("hand-base"), VariantGearRecord("hand-variant", "hand-base", op: (CultOverrideOp)7)); + var error = Assert.Throws(() => Open(path).Dispose())!; + Assert.That(error.Message, Does.Contain("hand-variant").And.Contain("op 7")); + } + // ---- the other stores refuse loudly until their own cuts ---- [Test] From 136adce9ff02145f248f2f4cb1ebd91f90db6787 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 04:21:59 +0200 Subject: [PATCH 51/64] Prove TypeScript, Python and Rust refuse the C#-written variant store by name Co-Authored-By: Claude Sonnet 5 --- packages/cultcache-py/tests/test_cultcache.py | 6 ++++++ packages/cultcache-rs/src/lib.rs | 10 ++++++++++ packages/cultcache-ts/test/cult-cache.test.ts | 7 +++++++ 3 files changed, 23 insertions(+) diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index b4168690..6001c905 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -829,6 +829,12 @@ class CultCacheTests(unittest.TestCase): message = str(caught.exception) self.assertTrue("cultcache.store.v2" in message or "item:anvil-big" in message, message) + def test_single_file_refuses_the_csharp_written_variant_store_by_version_or_record(self) -> None: + with self.assertRaises(ValueError) as caught: + self._pull_vector("../document-variants-c1/variant-store.msgpack") + message = str(caught.exception) + self.assertTrue("cultcache.store.v2" in message or "laser-big" in message, message) + def test_v1_store_written_at_the_base_commit_still_reads_byte_for_byte(self) -> None: envelopes = self._pull_vector("v1-base.msgpack") self.assertEqual([(e.key, e.type) for e in envelopes], [("alpha", "vectors.item"), ("beta", "vectors.item")]) diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index e48ebad8..c9a7d282 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -4679,6 +4679,16 @@ mod tests { ); } + // The store the C# runtime wrote through its own variant API (tests/vectors/document-variants-c1). + #[test] + fn single_file_refuses_the_csharp_written_variant_store_by_version_or_record() { + let message = refusal("../document-variants-c1/variant-store.msgpack"); + assert!( + message.contains("cultcache.store.v2") || message.contains("laser-big"), + "{message}" + ); + } + #[test] fn v1_store_written_at_the_base_commit_still_reads_byte_for_byte() -> Result<()> { let envelopes = pull_vector("v1-base.msgpack")?; diff --git a/packages/cultcache-ts/test/cult-cache.test.ts b/packages/cultcache-ts/test/cult-cache.test.ts index a743ba00..8753af47 100644 --- a/packages/cultcache-ts/test/cult-cache.test.ts +++ b/packages/cultcache-ts/test/cult-cache.test.ts @@ -1443,6 +1443,13 @@ test("SingleFileMessagePackBackingStore refuses a variant store by version or re ); }); +test("SingleFileMessagePackBackingStore refuses the C#-written variant store by version or record", async () => { + await assert.rejects( + () => pullVector("../document-variants-c1/variant-store.msgpack"), + (error: Error) => error.message.includes("cultcache.store.v2") || error.message.includes("laser-big"), + ); +}); + test("CultCache inspector refuses the same vectors by name", async () => { const inspect = async (name: string) => inspectCultCacheBytes(name, await readFile(join(variantVectors, name))); await assert.rejects(() => inspect("unknown-header.msgpack"), /cultcache\.store\.v9/u); From c3add7dd1b9f212c4c30465a22815e365d502d95 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 04:30:40 +0200 Subject: [PATCH 52/64] Idunn runtime fixture generator takes its specification as input The four hard-coded sets become flags, with @file response-file splicing. A consumer keeps its own .args file instead of committing a patch against the example. fixture.args carries CultLib own sets; the README documents the flags. Committed fixture bytes are unchanged. Co-Authored-By: Claude Sonnet 5 --- .../examples/idunn_runtime_fixture.rs | 266 ++++++++++++------ .../test/fixtures/idunn-runtime/README.md | 21 ++ .../test/fixtures/idunn-runtime/fixture.args | 35 +++ 3 files changed, 232 insertions(+), 90 deletions(-) create mode 100644 packages/cultnet-ts/test/fixtures/idunn-runtime/fixture.args diff --git a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs index 57364c10..287b0f34 100644 --- a/packages/cultnet-rs/examples/idunn_runtime_fixture.rs +++ b/packages/cultnet-rs/examples/idunn_runtime_fixture.rs @@ -11,22 +11,48 @@ //! disagreement). Ed25519 is deterministic, so the TypeScript signer must //! reproduce each vector byte for byte from the same fields. //! -//! The `service-stateful` set is the lease-bound shape: Expected carries a state +//! A `stateful` set is the lease-bound shape: Expected carries a state //! lineage and requires a write lease, and Rust issues `lease.cc` naming the //! warming vector's digest. Its warming vector is sequence 1; the active and //! degraded vectors are sequence 2 and bind to that lease. Two further leases are //! deliberately wrong (`lease-other-warming.cc` names a different warming digest, -//! `lease-other-target.cc` names another target) for the TypeScript refusal tests. +//! `lease-other-target.cc` names another target) for refusal tests. //! //! Linux only: the provider identity is bound to `/etc/machine-id`, and the //! generated `machine-id` file records the value the identities were bound to. //! -//! Usage: idunn_runtime_fixture +//! Usage: idunn_runtime_fixture ... +//! +//! The specification is command-line flags. `@` splices in a response +//! file: one flag per line, `--flag value` split at the first whitespace, blank +//! lines and `#` lines ignored. CultLib's own sets are +//! `packages/cultnet-ts/test/fixtures/idunn-runtime/fixture.args`. +//! +//! Global flags: +//! --source-repository Expected.source_repository (default github.com/GameCult/Example) +//! --detail presence detail (default route-observation:route-challenge-1) +//! +//! `--set ` opens a fixture set written to `/`; the flags +//! below apply to the set most recently opened: +//! --target required +//! --transport --stable --candidate required: the route +//! --capability default `.api` +//! --schema default `.v1` +//! --health-contract default `.runtime-health` +//! --minimum-capacity default 1; above 1 also writes presence-active-below-minimum.bin +//! --stateful state lineage, write lease and lease vectors +//! --state-schema-generation stateful only; default state-v1 +//! --lease-other-target stateful only; default the first other set's target +//! --dependency k=v,k=v,... repeatable; keys kind, capability, schema, provider, +//! endpoint (required), compatibility (v1), capacity (1), +//! startup (before-promotion), authority (managed-incarnation), +//! projection (one hex digit the digest is filled with, 5) +use std::collections::BTreeMap; use std::fs; use std::path::Path; -use anyhow::{Result, bail, ensure}; +use anyhow::{Context, Result, bail, ensure}; use cultcache_rs::{ CacheBackingStore, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, }; @@ -46,67 +72,138 @@ use cultnet_rs::{ const OBSERVED_AT: u64 = 1_790_000_000_000; const ISSUED_AT: u64 = OBSERVED_AT - 5_000; const SEQUENCE: u64 = 1; -const DETAIL: &str = "route-observation:route-challenge-1"; const STORED_AT: &str = "2026-01-01T00:00:00.000Z"; -struct Set { - dir: &'static str, - target: &'static str, - transport: &'static str, - stable: &'static str, - candidate: &'static str, - minimum_capacity: u32, - odin_dependency: bool, - stateful: bool, +struct Spec { + source_repository: String, + detail: String, + sets: Vec, } -const SETS: [Set; 4] = [ - Set { - dir: "web", - target: "streampixels-web", - transport: "http", - stable: "http://127.0.0.1:8830", - candidate: "http://127.0.0.1:18830", - minimum_capacity: 1, - odin_dependency: false, - stateful: false, - }, - Set { - dir: "service", - target: "streampixels-service", - transport: "tcp", - stable: "tcp://127.0.0.1:8831", - candidate: "tcp://127.0.0.1:18831", - minimum_capacity: 2, - odin_dependency: true, - stateful: false, - }, - Set { - dir: "service-stateful", - target: "streampixels-service", - transport: "tcp", - stable: "tcp://127.0.0.1:8833", - candidate: "tcp://127.0.0.1:18833", - minimum_capacity: 2, - odin_dependency: true, - stateful: true, - }, - Set { - dir: "rudp-route", - target: "streampixels-rudp", - transport: "rudp", - stable: "rudp://127.0.0.1:8832", - candidate: "rudp://127.0.0.1:18832", - minimum_capacity: 1, - odin_dependency: false, - stateful: false, - }, -]; +#[derive(Default)] +struct Set { + dir: String, + target: String, + transport: String, + stable: String, + candidate: String, + capability: Option, + schema: Option, + health_contract: Option, + minimum_capacity: u32, + stateful: bool, + state_schema_generation: Option, + lease_other_target: Option, + dependencies: Vec, +} + +fn expand(args: impl Iterator) -> Result> { + let mut flat = Vec::new(); + for arg in args { + let Some(file) = arg.strip_prefix('@') else { + flat.push(arg); + continue; + }; + for line in fs::read_to_string(file).with_context(|| format!("reading {file}"))?.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + match line.split_once(char::is_whitespace) { + Some((flag, value)) => flat.extend([flag.to_string(), value.trim().to_string()]), + None => flat.push(line.to_string()), + } + } + } + Ok(flat) +} + +fn dependency(text: &str) -> Result { + let mut fields = BTreeMap::new(); + for pair in text.split(',') { + let (key, value) = pair + .split_once('=') + .with_context(|| format!("dependency field `{pair}` is not key=value"))?; + ensure!(fields.insert(key, value).is_none(), "dependency key `{key}` repeated"); + } + let mut take = |key: &str, default: Option<&str>| -> Result { + match (fields.remove(key), default) { + (Some(value), _) => Ok(value.to_string()), + (None, Some(default)) => Ok(default.to_string()), + (None, None) => bail!("dependency needs `{key}`"), + } + }; + let dependency = IdunnExpectedDependency { + kind: take("kind", None)?, + capability: take("capability", None)?, + schema: take("schema", None)?, + compatibility: take("compatibility", Some("v1"))?, + minimum_capacity: take("capacity", Some("1"))?.parse()?, + startup: take("startup", Some("before-promotion"))?, + provider_id: Some(take("provider", None)?), + provider_authority: Some(take("authority", Some("managed-incarnation"))?), + provider_expected_projection_sha256: Some(digest( + take("projection", Some("5"))?.chars().next().context("empty projection")?, + )), + provider_endpoint: Some(take("endpoint", None)?), + }; + ensure!(fields.is_empty(), "unknown dependency keys {:?}", fields.keys().collect::>()); + Ok(dependency) +} + +fn parse(args: impl Iterator) -> Result { + let mut spec = Spec { + source_repository: "github.com/GameCult/Example".into(), + detail: "route-observation:route-challenge-1".into(), + sets: Vec::new(), + }; + let mut args = expand(args)?.into_iter(); + while let Some(flag) = args.next() { + let mut value = || args.next().with_context(|| format!("{flag} needs a value")); + match flag.as_str() { + "--source-repository" => spec.source_repository = value()?, + "--detail" => spec.detail = value()?, + "--set" => spec.sets.push(Set { dir: value()?, minimum_capacity: 1, ..Set::default() }), + _ => { + let set = spec.sets.last_mut().with_context(|| format!("{flag} before any --set"))?; + match flag.as_str() { + "--target" => set.target = value()?, + "--transport" => set.transport = value()?, + "--stable" => set.stable = value()?, + "--candidate" => set.candidate = value()?, + "--capability" => set.capability = Some(value()?), + "--schema" => set.schema = Some(value()?), + "--health-contract" => set.health_contract = Some(value()?), + "--minimum-capacity" => set.minimum_capacity = value()?.parse()?, + "--stateful" => set.stateful = true, + "--state-schema-generation" => set.state_schema_generation = Some(value()?), + "--lease-other-target" => set.lease_other_target = Some(value()?), + "--dependency" => set.dependencies.push(dependency(&value()?)?), + other => bail!("unknown flag {other}"), + } + } + } + } + ensure!(!spec.sets.is_empty(), "no --set given"); + for set in &spec.sets { + for (name, field) in [ + ("target", &set.target), + ("transport", &set.transport), + ("stable", &set.stable), + ("candidate", &set.candidate), + ] { + ensure!(!field.is_empty(), "set {} needs --{name}", set.dir); + } + } + Ok(spec) +} fn main() -> Result<()> { - let Some(out) = std::env::args().nth(1) else { - bail!("usage: idunn_runtime_fixture "); + let mut args = std::env::args().skip(1); + let Some(out) = args.next() else { + bail!("usage: idunn_runtime_fixture ... (see the file header)"); }; + let spec = parse(args)?; let machine_id = fs::read_to_string("/etc/machine-id")?; fs::create_dir_all(&out)?; fs::write(Path::new(&out).join("machine-id"), machine_id.trim())?; @@ -116,8 +213,8 @@ fn main() -> Result<()> { let idunn_anchor = idunn.trust_anchor()?; fs::remove_file(Path::new(&out).join("idunn-identity.private"))?; let _ = fs::remove_file(Path::new(&out).join("idunn-identity.private.lock")); - for set in &SETS { - build(Path::new(&out).join(set.dir).as_path(), set, &idunn, &idunn_anchor)?; + for set in &spec.sets { + build(Path::new(&out).join(&set.dir).as_path(), &spec, set, &idunn, &idunn_anchor)?; } Ok(()) } @@ -128,6 +225,7 @@ fn digest(byte: char) -> String { fn build( dir: &Path, + spec: &Spec, set: &Set, idunn: &cultnet_rs::ServiceIdentitySigner, idunn_anchor: &cultnet_rs::ServiceIdentityTrustAnchor, @@ -138,29 +236,29 @@ fn build( let provider_anchor = provider.trust_anchor()?; let _ = fs::remove_file(dir.join("provider-identity.credential.lock")); - let capability = format!("{}.api", set.target); - let capability_schema = format!("{}.api.v1", set.target); + let capability = set.capability.clone().unwrap_or_else(|| format!("{}.api", set.target)); + let capability_schema = set.schema.clone().unwrap_or_else(|| format!("{capability}.v1")); let expected = IdunnExpectedIncarnationRecord { schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(), - target: set.target.into(), + target: set.target.clone(), plan_id: digest('1'), incarnation_id: format!("{}/incarnation-1", set.target), sealed_release_id: digest('2'), - source_repository: "github.com/GameCult/StreamPixels".into(), + source_repository: spec.source_repository.clone(), source_revision: "a".repeat(40), recipe_sha256: digest('3'), runtime_id: format!("{}-yggdrasil", set.target), expected_signer_identity_id: provider_anchor.identity_id.clone(), - health_contract: format!("{}.runtime-health", set.target), + health_contract: set.health_contract.clone().unwrap_or_else(|| format!("{}.runtime-health", set.target)), artifact_sha256: digest('4'), - state_schema_generation: set.stateful.then(|| "streampixels-state-v1".to_string()), + state_schema_generation: set.stateful.then(|| set.state_schema_generation.clone().unwrap_or_else(|| "state-v1".into())), state_contract_sha256: set.stateful.then(|| digest('7')), write_lease_required: set.stateful, route: Some(IdunnExpectedRoute { route_id: format!("{}-route", set.target), - transport: set.transport.into(), - stable_endpoint: set.stable.into(), - candidate_endpoint: set.candidate.into(), + transport: set.transport.clone(), + stable_endpoint: set.stable.clone(), + candidate_endpoint: set.candidate.clone(), }), capabilities: vec![IdunnExpectedCapability { capability: capability.clone(), @@ -168,22 +266,7 @@ fn build( compatibility: "v1".into(), minimum_capacity: set.minimum_capacity, }], - dependencies: if set.odin_dependency { - vec![IdunnExpectedDependency { - kind: "shared-infrastructure".into(), - capability: "odin.verse-rendezvous".into(), - schema: "odin.verse-topology.v1".into(), - compatibility: "v1".into(), - minimum_capacity: 1, - startup: "before-promotion".into(), - provider_id: Some("odin".into()), - provider_authority: Some("managed-incarnation".into()), - provider_expected_projection_sha256: Some(digest('5')), - provider_endpoint: Some("rudp://127.0.0.1:47871".into()), - }] - } else { - Vec::new() - }, + dependencies: set.dependencies.clone(), }; expected.validate()?; @@ -230,7 +313,7 @@ fn build( state_contract_sha256: expected.state_contract_sha256.clone(), runtime_id: expected.runtime_id.clone(), runtime_instance_id: activation.runtime_instance_id.clone(), - bound_endpoint: Some(set.candidate.into()), + bound_endpoint: Some(set.candidate.clone()), capabilities: vec![GameCultRuntimeCapability { capability: capability.clone(), schema: capability_schema.clone(), @@ -239,7 +322,7 @@ fn build( }], health_contract: expected.health_contract.clone(), state: state.into(), - detail: DETAIL.into(), + detail: spec.detail.clone(), write_lease_sha256, signer_identity_id: provider_anchor.identity_id.clone(), publisher_sequence: sequence, @@ -316,9 +399,12 @@ fn build( lease_epoch: 1, issued_at_unix_millis: OBSERVED_AT - 1_000, }; - let lease = lease_for(set.target, &warming_sha256); - let other_warming = lease_for(set.target, &digest('d')); - let other_target = lease_for("streampixels-web", &warming_sha256); + let other_target_name = set.lease_other_target.clone().unwrap_or_else(|| { + spec.sets.iter().map(|other| other.target.clone()).find(|target| *target != set.target).unwrap_or_else(|| format!("{}-other", set.target)) + }); + let lease = lease_for(&set.target, &warming_sha256); + let other_warming = lease_for(&set.target, &digest('d')); + let other_target = lease_for(&other_target_name, &warming_sha256); for (name, record) in [ ("lease.cc", &lease), ("lease-other-warming.cc", &other_warming), diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md b/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md index dd683a16..7856c78d 100644 --- a/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/README.md @@ -19,3 +19,24 @@ Ed25519 is deterministic, so the TypeScript signer must reproduce them byte for `presence-warming.bin`; `presence-active.bin` and `presence-degraded.bin` are sequence 2 and carry that lease's digest. `lease-other-warming.cc` names a different warming digest and `lease-other-target.cc` names another target; the TypeScript lease check must refuse both. + +## Generating a consumer's own set + +The generator takes its specification as input, so a consumer needs no patch to CultLib. The +specification is command-line flags; `@` splices in a response file (one `--flag value` +per line, `#` comments). CultLib's own sets are `fixture.args` here: + + cargo run -q --example idunn_runtime_fixture /tmp/out @/fixture.args + +The consumer keeps its own `.args` file in its repository and runs the same command with the +same machine-id bind mount as above. Global flags: `--source-repository`, `--detail`. Each +`--set ` opens a set written to `/`, and the flags after it configure it: +`--target`, `--transport`, `--stable`, `--candidate` (required); `--capability` (default +`.api`), `--schema` (default `.v1`), `--health-contract` (default +`.runtime-health`), `--minimum-capacity` (default 1), `--stateful` with +`--state-schema-generation` and `--lease-other-target`, and repeatable +`--dependency kind=..,capability=..,schema=..,provider=..,endpoint=..` (optional `compatibility`, +`capacity`, `startup`, `authority`, `projection`). The full grammar is the header of the example. + +Every generation enrolls fresh keys, so regenerated bytes differ from the committed ones. The +committed set stays; `fixture.args` regenerates the same file list, sizes and structure. diff --git a/packages/cultnet-ts/test/fixtures/idunn-runtime/fixture.args b/packages/cultnet-ts/test/fixtures/idunn-runtime/fixture.args new file mode 100644 index 00000000..04dc36aa --- /dev/null +++ b/packages/cultnet-ts/test/fixtures/idunn-runtime/fixture.args @@ -0,0 +1,35 @@ +# CultLib's own fixture sets, in the generator's response-file form: +# idunn_runtime_fixture @fixture.args +--source-repository github.com/GameCult/StreamPixels +--detail route-observation:route-challenge-1 + +--set web +--target streampixels-web +--transport http +--stable http://127.0.0.1:8830 +--candidate http://127.0.0.1:18830 + +--set service +--target streampixels-service +--transport tcp +--stable tcp://127.0.0.1:8831 +--candidate tcp://127.0.0.1:18831 +--minimum-capacity 2 +--dependency kind=shared-infrastructure,capability=odin.verse-rendezvous,schema=odin.verse-topology.v1,provider=odin,endpoint=rudp://127.0.0.1:47871 + +--set service-stateful +--target streampixels-service +--transport tcp +--stable tcp://127.0.0.1:8833 +--candidate tcp://127.0.0.1:18833 +--minimum-capacity 2 +--stateful +--state-schema-generation streampixels-state-v1 +--lease-other-target streampixels-web +--dependency kind=shared-infrastructure,capability=odin.verse-rendezvous,schema=odin.verse-topology.v1,provider=odin,endpoint=rudp://127.0.0.1:47871 + +--set rudp-route +--target streampixels-rudp +--transport rudp +--stable rudp://127.0.0.1:8832 +--candidate rudp://127.0.0.1:18832 From 4a781b150cf2638ea56535bf96485e4b51571893 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 06:48:42 +0200 Subject: [PATCH 53/64] Record Soul on variants C1 and Self's defaults for its fix batch Co-Authored-By: Claude Opus 5.5 --- docs/document-variants-cut.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/document-variants-cut.md b/docs/document-variants-cut.md index 3136b586..51136a78 100644 --- a/docs/document-variants-cut.md +++ b/docs/document-variants-cut.md @@ -295,6 +295,25 @@ Subtraction: the inspector's own codec pair collapses into the port; otherwise n estimated +350 to 450 lines of core and +400 of tests. Build: the Caching and MessagePack projects, Caching.Tests, the Networking test filter, the interop peer. +**C1 status, 2026-09-29 (Self).** C1 landed on `hands/variants-c1` (`136adce`). Soul (Opus) found it +not closeable, and a fix batch is in Hands: +- **F1:** CultNet's live-change paths leak variants as plain records, which breaks Q6. +- **F3:** an undecodable override soft-drifted where a plain record refuses to load. +- **F4:** invalid overrides were accepted at write. +- **F2:** an inherited unique index value shadows the base, and the winner depends on order. + +**Self's readings and defaults, not new operator rulings:** +- **Q4 (c) read literally:** an override follows the plain-record outcome. A missing slot + soft-drifts; a value that no longer decodes refuses loudly, as a plain record does. +- **Invalid overrides are refused at write.** Drift covers type changes after the fact, not + bad writes. +- **F2 extends R6 to indexes.** A commit that leaves a variant sharing an indexed value + with another record is refused. +- **One override per slot.** + +**Open for the operator:** plain records with duplicate unique-index values are silently +overwritten today. That predates variants. Fixing it could refuse existing stores. + ### C2. C# element identity and nested paths (Set, Insert, Remove) Adds: From cdb8ee5dcc82518719518070b161ff955967b404 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 06:58:51 +0200 Subject: [PATCH 54/64] CultNet refuses a variant on both live-change paths, loudly, by key A load or write that landed a variant reached CultNet subscribers as a plain "added" record carrying the full resolved payload; a later base edit published only the base, so the subscriber's copy of the variant went stale. Under Q6 CultNet carries no variants until its own cut. Both live paths now refuse a change whose key holds a variant, after selection and authorization match, and send the matching subscriber a CultNetErrorMessage naming the variant and its base. Refused loudly rather than omitted: an omission is a silent hole in the subscriber's view, and the snapshot path already refuses by throwing. Tests: a real load through a real RUDP subscription never delivers the variant as a record and delivers the typed error; the database server's change builder refuses the same change. Co-Authored-By: Claude Sonnet 5 --- .../CultNetDatabaseServer.cs | 16 ++- .../CultNetDatabaseSubscriptionServer.cs | 14 +- .../CultNetDocumentRegistry.cs | 15 +- .../CultNetDocumentRegistryVariantTests.cs | 129 ++++++++++++++++++ 4 files changed, 167 insertions(+), 7 deletions(-) diff --git a/src/GameCult.Networking/CultNetDatabaseServer.cs b/src/GameCult.Networking/CultNetDatabaseServer.cs index 1a66dc2a..0dc489ed 100644 --- a/src/GameCult.Networking/CultNetDatabaseServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseServer.cs @@ -504,7 +504,18 @@ namespace GameCult.Networking { return _database.WatchAllChanges().Subscribe(change => { - var outbound = CreateChangeMessage(change, subscriptionId, selection); + CultNetDatabaseChangeRawMessage? outbound; + try + { + outbound = CreateChangeMessage(change, subscriptionId, selection); + } + catch (NotSupportedException refusal) + { + // Q6: a variant is not a record CultNet can carry; the subscriber that would have received it is told, by key. + peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); + return; + } + if (outbound != null) { peer.SendCultNet(outbound); @@ -549,11 +560,12 @@ namespace GameCult.Networking }; } + CultNetDocumentRegistry.RefuseVariantChange(_database.Cache, key); return new CultNetDatabaseChangeRawMessage { MessageId = Guid.NewGuid().ToString("N"), SubscriptionId = subscriptionId, - ChangeKind = kind == CultNetDatabaseChangeKind.Added ? "added" : "updated", + ChangeKind = kind ==CultNetDatabaseChangeKind.Added ? "added" : "updated", Document = _database.Documents.ToRawRecord(descriptor, key, document, DateTimeOffset.UtcNow.ToString("O")) }; } diff --git a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs index 2ccb031c..359a9dfb 100644 --- a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs @@ -315,7 +315,18 @@ namespace GameCult.Networking } var sourceRecordKey = ResolveChangeRecordKey(change); - var matched = CreateMatchedRecord(change, request, peer); + CultNetRawDocumentRecord? matched; + try + { + matched = CreateMatchedRecord(change, request, peer); + } + catch (NotSupportedException refusal) + { + // Q6: a variant is not a record CultNet can carry; the subscriber that would have received it is told, by key. + peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); + return; + } + ApplyProjectedChange( projection, sourceRecordKey, @@ -541,6 +552,7 @@ namespace GameCult.Networking if (kind == CultNetDatabaseChangeKind.Removed || document == null) return null; + CultNetDocumentRegistry.RefuseVariantChange(_database.Cache, key); return _database.Documents.ToRawRecord(descriptor, key, document, DateTimeOffset.UtcNow.ToString("O")); } diff --git a/src/GameCult.Networking/CultNetDocumentRegistry.cs b/src/GameCult.Networking/CultNetDocumentRegistry.cs index 60446d31..356761f5 100644 --- a/src/GameCult.Networking/CultNetDocumentRegistry.cs +++ b/src/GameCult.Networking/CultNetDocumentRegistry.cs @@ -551,10 +551,17 @@ namespace GameCult.Networking // CultNet carries no variant deltas yet, and a resolved view sent as a plain record would be a lie about the store. private static CultStoredDocument RefuseVariant(CultStoredDocument entry) => - entry.Variant == null - ? entry - : throw new NotSupportedException( - $"Record '{entry.Key.Value}' is a variant of '{entry.Variant.BaseKey}'; CultNet does not carry document variants yet."); + entry.Variant == null ? entry : throw VariantRefusal(entry); + + // The live-change funnel's refusal: a load or write that lands a variant must not reach a subscriber as a record. + internal static void RefuseVariantChange(CultCache cache, CultRecordKey key) + { + if (cache.GetStored(key) is { Variant: not null } entry) + throw VariantRefusal(entry); + } + + private static NotSupportedException VariantRefusal(CultStoredDocument entry) => + new($"Record '{entry.Key.Value}' is a variant of '{entry.Variant!.BaseKey}'; CultNet does not carry document variants yet."); /// /// Builds the wire record for one evaluated row. The shared path under snapshot and change diff --git a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs index 46f91438..2a8ddc58 100644 --- a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs @@ -1,5 +1,12 @@ #nullable enable using System; +using System.Collections.Concurrent; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Reflection; +using System.Threading; using System.Threading.Tasks; using GameCult.Caching; using GameCult.Caching.MessagePack; @@ -63,6 +70,128 @@ namespace GameCult.Networking.Tests Assert.That(documents.CreateRawSnapshotResponse(cache, "m2").Documents, Has.Length.EqualTo(1)); } + // The live-change funnel: a load that lands a variant reaches a subscriber as neither a record nor silence. + [Test] + public async Task ALoadThatLandsAVariantNeverReachesASubscriberAsARecordAndTheSubscriberIsToldByKey() + { + var registry = CultDocumentRegistry.Shared; + var directory = Path.Combine(Path.GetTempPath(), $"cultlib-variant-live-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directory); + try + { + var path = Path.Combine(directory, "wire.cc"); + using (var writer = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = registry })) + { + writer.Commit(batch => batch.Upsert(typeof(VariantWireFixture), new VariantWireFixture { Name = "base", Power = 1 }, BaseKey)); + writer.UpsertVariantAsync(VariantKey, BaseKey, new[] + { + writer.Override(nameof(VariantWireFixture.Name), "big"), + writer.Override(nameof(VariantWireFixture.Power), 9) + }).GetAwaiter().GetResult(); + } + + var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry)); + var documents = new CultNetDocumentRegistry(registry) + .Register(CultNetDocumentBinding.ForDocument(registry)); + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents }); + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + socket.ReceiveTimeout = 20; + using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions + { + RuntimeId = "variant-live-server", + Socket = socket + }); + using var subscriptions = new CultNetDatabaseSubscriptionServer(server, database); + using var cancellation = new CancellationTokenSource(); + var serverThread = new Thread(() => + { + while (!cancellation.IsCancellationRequested) + { + _ = server.PollOnceAsync().GetAwaiter().GetResult(); + Thread.Sleep(1); + } + }) { IsBackground = true }; + serverThread.Start(); + try + { + using var client = CultNetSchemaClients.CreateRudp("variant-live-client"); + var snapshot = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var changes = new ConcurrentQueue(); + var errors = new ConcurrentQueue(); + client.OnCultNet(_ => snapshot.TrySetResult(true)); + client.OnCultNet(changes.Enqueue); + client.OnCultNet(errors.Enqueue); + client.Connect("127.0.0.1", server.LocalEndPoint.Port); + await WaitUntilAsync(() => client.Connected); + client.SendCultNet(new CultNetDatabaseSubscribeMessage + { + MessageId = "subscribe-all", + SubscriptionId = "all", + IncludeSnapshot = true + }); + await WaitUntilAsync(() => snapshot.Task.IsCompleted); + + cache.AddBackingStore(new SingleFileMessagePackBackingStore(path)); + + await WaitUntilAsync(() => !errors.IsEmpty || changes.Any(change => change.Document?.RecordKey == VariantKey.Value)); + await Task.Delay(200); // let anything else already in flight arrive + + Assert.That(changes.Select(change => change.Document?.RecordKey), Does.Not.Contain(VariantKey.Value), + "a variant must not reach a subscriber as a plain record"); + Assert.That(errors.Select(error => error.Error), Has.Some.Contains(VariantKey.Value), + "the subscriber is told, naming the variant"); + } + finally + { + cancellation.Cancel(); + serverThread.Join(); + } + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Test] + public async Task TheDatabaseServersLiveChangeForAVariantIsRefusedNamingIt() + { + var (cache, documents) = await BuildFixtureAsync(withVariant: true); + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents }); + using var server = new Server(cache, ServerSecurityOptions.Development()); + using var databaseServer = new CultNetDatabaseServer(server, database); + var schemaId = cache.Registry.GetRequired().SchemaId; + var change = new CultNetDatabaseChange( + CultNetDatabaseChangeKind.Added, + VariantKey, + schemaId, + database.Shards[0], + cache.Get(VariantKey)!, + previousDocument: null); + var method = typeof(CultNetDatabaseServer).GetMethod("CreateChangeMessage", BindingFlags.Instance | BindingFlags.NonPublic)!; + + var refused = Assert.Throws(() => method.Invoke(databaseServer, new object[] + { + change, "sub-1", new CultNetSelection { Projection = CultNetSelectionProjections.Document } + }))!; + + Assert.That(refused.InnerException, Is.TypeOf()); + Assert.That(refused.InnerException!.Message, Does.Contain(VariantKey.Value).And.Contain(BaseKey.Value)); + } + + private static async Task WaitUntilAsync(Func condition) + { + var deadline = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(5); + while (!condition()) + { + if (DateTimeOffset.UtcNow > deadline) + Assert.Fail("Condition was not satisfied before timeout."); + await Task.Delay(5); + } + } + + [CultDocument("variants.wire-fixture", "variants.wire-fixture.v1")] [MessagePackObject(AllowPrivate = true)] public sealed class VariantWireFixture From c66d79e248c17502b090374b145e0d6a77ae6c55 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 06:58:51 +0200 Subject: [PATCH 55/64] Variant overrides follow the plain-record outcome; bad writes and shared indexes are refused F3: an override drifts exactly as the same member would on a plain record. A slot the type dropped is ignored and reported by the store's schema resolution (LastSchemaMigrationReports), the one surface a plain record uses; a value that no longer decodes refuses the load, naming the variant and member. The second report surface (VariantMigrationReports, the per-variant report map, the catalog slot-name plumbing) is deleted. F4: an override for a slot the type does not have, or a value that does not decode as the member, is refused at write. Drift is for type changes after the fact, not for bad writes. F5: two overrides of one slot are refused. F2: a variant that shares an indexed value with another record is refused, naming both keys and the index (the R6 rule extended to [CultIndex]); plain record duplicate handling is unchanged. F7: a flatten now resolves against the same batch, so a base edited in that batch is in the flattened record; and the directory store refuses to load a variant page as it refuses to write one. The C1 vector's big variant now overrides its indexed code, as the unique-index rule requires. Co-Authored-By: Claude Sonnet 5 --- .../DirectoryMessagePackBackingStore.cs | 4 + .../cultcache-schema-compatibility.md | 18 +- src/GameCult.Caching/CultCache.cs | 156 ++++++------ src/GameCult.Caching/CultVariants.cs | 4 - tests/GameCult.Caching.Tests/VariantTests.cs | 222 ++++++++++++++++-- .../vectors/document-variants-c0/generate.py | 8 +- 6 files changed, 304 insertions(+), 108 deletions(-) diff --git a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs index fa9d4899..3ef36be2 100644 --- a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs +++ b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs @@ -502,6 +502,10 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore var record = CultDocumentMessagePackSerialization.DeserializePersistedRecord(pagePayload); if (!string.Equals(record.Key, metadata.Key, StringComparison.Ordinal)) throw new InvalidDataException($"Record page '{path}' contains key '{record.Key}', expected '{metadata.Key}'."); + // The shared decoder reads a variant page; this store does not hold variants, so a load refuses it as a write does. + if (record.Variant != null) + throw new NotSupportedException( + $"Record '{record.Key}' is a variant of '{record.Variant.BaseKey}'; the directory store does not hold document variants yet."); return record; } diff --git a/src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md b/src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md index 818840ee..9ae6f553 100644 --- a/src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md +++ b/src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md @@ -108,7 +108,17 @@ This is not negotiable. Better a loud refusal than quiet bit-rot. ## Variant overrides -A variant's override drifts exactly as the same member would on a plain record: an -override naming a slot the type no longer has, or holding a value that no longer decodes -into the member's type, is ignored with a warning naming the variant and the member, and -the variant inherits the base value. There is no separate rule for variants. +A variant's override follows the same outcome as the same member on a plain record; there +is no separate rule for variants, and no separate report. + +- An override naming a slot the type no longer has is ignored, exactly as a plain record + ignores a dropped member. The drift is reported once, by the store's schema resolution + (`LastSchemaMigrationReports`), for the variant's record as for any other record of the + schema. The variant inherits the base value. +- An override holding a value that no longer decodes into the member's type refuses the + load, exactly as a plain record holding such a value does; the refusal names the variant + and the member. + +Drift is for type changes after the fact. A write is validated: an override for a slot the +type does not have, a value that does not decode as the member, or two overrides of one +slot is refused when written. diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 00b849a0..f17d5b93 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -1802,10 +1802,8 @@ namespace GameCult.Caching private readonly Dictionary<(Type Type, string Alias), Dictionary> _indexes = new(); private readonly Dictionary _globals = new(); private readonly CultCodec? _codec; - // Keys holding a variant, and the drift report of each variant whose overrides were partly ignored: both derived - // from the entries by Apply, never decided anywhere else. + // Keys holding a variant: derived from the entries by Apply, never decided anywhere else. private readonly HashSet _variantKeys = new(StringComparer.Ordinal); - private readonly Dictionary _variantReports = new(StringComparer.Ordinal); private readonly ConditionalWeakTable _handles = new(); private readonly Subject _changes = new(); private readonly object _gate = new(); @@ -1826,17 +1824,6 @@ namespace GameCult.Caching public CultCodec? Codec => _codec; - // Overrides a variant carries that no longer resolve (a slot the type dropped, a value that no longer decodes), - // reported as compatible drift: the override is ignored and the variant inherits the base value. - public IReadOnlyList VariantMigrationReports - { - get - { - lock (_gate) - return _variantReports.Values.ToArray(); - } - } - // The whole override of one member, encoded with this cache's codec, ready for UpsertVariant. public CultVariantOverride Override(Type documentType, string member, object? value) { @@ -2467,9 +2454,6 @@ namespace GameCult.Caching // Variants this admission did not write whose base chain it changed: re-resolved, same delta, same storedAt. public List Dependents { get; } = new(); - - // The drift report of every variant resolved here; null when nothing was ignored. - public Dictionary Reports { get; } = new(StringComparer.Ordinal); } // Resolves every admitted variant and every variant whose base chain this admission changes, base first, against @@ -2512,7 +2496,9 @@ namespace GameCult.Caching } var changed = new HashSet(incoming.Keys.Concat(gone), StringComparer.Ordinal); - var toResolve = new List(admitted.Where(stored => stored.Variant != null).Select(stored => stored.Key.Value)); + // A flatten resolves like the variant it replaces, against the post-batch set, so a base edited in the same + // batch is in it; it lands as the plain record of that resolution. + var toResolve = new List(admitted.Where(stored => stored.Variant != null || stored.Flattens).Select(stored => stored.Key.Value)); foreach (var variantKey in _variantKeys) { if (incoming.ContainsKey(variantKey) || gone.Contains(variantKey)) @@ -2538,16 +2524,14 @@ namespace GameCult.Caching var pending = new HashSet(toResolve, StringComparer.Ordinal); var done = new Dictionary(StringComparer.Ordinal); - var reports = new Dictionary(StringComparer.Ordinal); var stack = new List(); + Dictionary<(Type Type, string Alias), Dictionary>? claimed = null; foreach (var key in toResolve) ResolveOne(key); - var plan = new VariantPlan(admitted.Select(stored => stored.Variant != null ? done[stored.Key.Value] : stored).ToList()); + var plan = new VariantPlan(admitted.Select(stored => done.TryGetValue(stored.Key.Value, out var resolved) ? resolved : stored).ToList()); foreach (var key in toResolve.Where(key => !incoming.ContainsKey(key))) plan.Dependents.Add(done[key]); - foreach (var pair in reports) - plan.Reports[pair.Key] = pair.Value; return plan; CultStoredDocument ResolveOne(string key) @@ -2559,9 +2543,11 @@ namespace GameCult.Caching throw CycleRefusal(stack.SkipWhile(entry => entry != key).Append(key)); stack.Add(key); - var delta = variant.Variant!; + // A flatten carries no delta of its own; the variant it replaces does. + var isVariant = variant.Variant != null; + var delta = variant.Variant ?? _entries[key].Variant!; var baseStored = Lookup(delta.BaseKey) ?? throw MissingBaseRefusal(key, delta.BaseKey, gone.Contains(delta.BaseKey)); - if (baseStored.Variant != null && pending.Contains(delta.BaseKey)) + if (pending.Contains(delta.BaseKey)) baseStored = ResolveOne(delta.BaseKey); var descriptor = variant.Descriptor; @@ -2575,25 +2561,25 @@ namespace GameCult.Caching var type = descriptor.DocumentType; var kept = new List>(); - var ignored = new List(); - var warnings = new List(); + var seen = new HashSet(); + // Bad writes are refused; drift is for type changes after the fact. A load, a re-resolution and a flatten + // carry what was already stored, so they follow the plain-record outcome instead. + var writing = source == null && isVariant && incoming.ContainsKey(key); foreach (var entry in delta.Overrides) { if (entry.Op != CultOverrideOp.Set || entry.Path.Count != 1 || entry.Path[0].ElementId.Length != 0 || entry.Id.Length != 0) throw new InvalidOperationException( $"Variant {key} carries {entry.Op} at {entry.PathText}; this runtime resolves top-level Set overrides only."); var slot = entry.Path[0].Slot; + if (!seen.Add(slot)) + throw new InvalidOperationException($"Variant {key} overrides slot {slot} more than once; a variant has one override per slot."); var member = descriptor.RichMembers.FirstOrDefault(candidate => candidate.Slot == slot); if (member == null) { - var name = delta.SlotNames != null && delta.SlotNames.TryGetValue(slot, out var persistedName) - ? $"'{persistedName}'" : "unnamed"; - ignored.Add(slot); - warnings.Add(new CultSchemaMigrationWarning - { - Code = "ignored_extra_slot", - Message = $"Variant {key} overrides slot {slot} ({name}), which {type.Name} no longer has; the override is ignored and the variant inherits the base value." - }); + if (writing) + throw new InvalidOperationException($"Variant {key} overrides slot {slot}, which {type.Name} does not have."); + // A slot the type dropped soft-drifts exactly as the same member does on a plain record: ignored, + // reported by the store's schema resolution (LastSchemaMigrationReports), the variant inherits the base. continue; } @@ -2603,14 +2589,10 @@ namespace GameCult.Caching } catch (Exception exception) { - ignored.Add(slot); - warnings.Add(new CultSchemaMigrationWarning - { - Code = "ignored_undecodable_override", - Message = $"Variant {key} overrides slot {slot} ('{member.Member.Name}') with a value that no longer decodes as {member.MemberType.Name} " + - $"({exception.GetBaseException().Message}); the override is ignored and the variant inherits the base value." - }); - continue; + // A value that no longer decodes refuses exactly as a plain record holding it does. + throw new InvalidOperationException( + $"Variant {key} overrides '{member.Member.Name}' (slot {slot}) with a value that does not decode as {member.MemberType.Name}: " + + exception.GetBaseException().Message, exception); } kept.Add(new KeyValuePair(slot, entry.Value)); @@ -2620,32 +2602,73 @@ namespace GameCult.Caching var document = _codec.Deserialize(type, type, kept.Count == 0 ? payload : _codec.Overlay(payload, kept)) ?? throw new InvalidOperationException($"Variant {key} resolved to nothing."); - // R6: the name index maps one name to one key, so a variant that kept its base's name would shadow it. - if (descriptor.NameAccessor?.Invoke(document) is { Length: > 0 } variantName) + if (isVariant) { - for (var ancestor = baseStored; ancestor != null; - ancestor = ancestor.Variant == null ? null : done.TryGetValue(ancestor.Variant.BaseKey, out var above) ? above : Lookup(ancestor.Variant.BaseKey)) + // R6: the name index maps one name to one key, so a variant that kept its base's name would shadow it. + if (descriptor.NameAccessor?.Invoke(document) is { Length: > 0 } variantName) { - if (descriptor.NameAccessor(ancestor.Document) == variantName) + for (var ancestor = baseStored; ancestor != null; + ancestor = ancestor.Variant == null ? null : done.TryGetValue(ancestor.Variant.BaseKey, out var above) ? above : Lookup(ancestor.Variant.BaseKey)) + { + if (descriptor.NameAccessor(ancestor.Document) == variantName) + throw new InvalidOperationException( + $"Variant {key} and its base {ancestor.Key.Value} are both named '{variantName}'; a variant must override its name."); + } + } + + // The same rule for an indexed value: a unique index maps one value to one key, so a variant that + // inherited its base's value (or any other record's) would be found in place of it or lose it. + foreach (var pair in descriptor.IndexAccessors) + { + var value = pair.Value(document); + if (string.IsNullOrWhiteSpace(value)) + continue; + claimed ??= ClaimIncomingIndexValues(); + var claim = (type, pair.Key); + string? other = null; + if (claimed.TryGetValue(claim, out var claims) && claims.TryGetValue(value, out var claimant) && claimant != key) + other = claimant; + else if (_indexes.TryGetValue(claim, out var held) && held.TryGetValue(value, out var holder) && holder != key && + !incoming.ContainsKey(holder) && !gone.Contains(holder) && !pending.Contains(holder)) + other = holder; + if (other != null) throw new InvalidOperationException( - $"Variant {key} and its base {ancestor.Key.Value} are both named '{variantName}'; a variant must override its name."); + $"Variant {key} and {other} both hold index {pair.Key} '{value}'; a variant must override its indexed member."); } } - reports[key] = ignored.Count == 0 - ? null - : new CultSchemaMigrationReport + if (descriptor.IndexAccessors.Count > 0) + { + claimed ??= ClaimIncomingIndexValues(); + foreach (var pair in descriptor.IndexAccessors) { - PersistedSchemaId = descriptor.SchemaId, - LocalSchemaId = descriptor.SchemaId, - PersistedSchemaName = descriptor.SchemaName, - LocalSchemaName = descriptor.SchemaName, - Kind = CultSchemaMigrationKind.CompatibleDrift, - IgnoredExtraSlots = ignored.OrderBy(slot => slot).ToArray(), - Warnings = warnings.ToArray() - }; + var value = pair.Value(document); + if (!string.IsNullOrWhiteSpace(value)) + MapOf(claimed, (type, pair.Key))[value] = key; + } + } + stack.RemoveAt(stack.Count - 1); - return done[key] = variant.Resolved(document); + return done[key] = isVariant + ? variant.Resolved(document) + : new CultStoredDocument(variant.Key, variant.StoredAt, variant.Descriptor, document) { Flattens = true }; + } + + // The indexed values the plain records of this admission will hold, by (type, index) then value. + Dictionary<(Type Type, string Alias), Dictionary> ClaimIncomingIndexValues() + { + var claims = new Dictionary<(Type Type, string Alias), Dictionary>(); + foreach (var stored in incoming.Values.Where(stored => stored.Variant == null && !stored.Flattens)) + { + foreach (var pair in stored.Descriptor.IndexAccessors) + { + var value = pair.Value(stored.Document); + if (!string.IsNullOrWhiteSpace(value)) + MapOf(claims, (stored.Descriptor.DocumentType, pair.Key))[value] = stored.Key.Value; + } + } + + return claims; } } @@ -2672,7 +2695,6 @@ namespace GameCult.Caching _entries.Remove(stored.Key.Value); _handles.Remove(existing.Document); _variantKeys.Remove(stored.Key.Value); - _variantReports.Remove(stored.Key.Value); changes.Add(new Change(CultCacheDocumentChangeKind.Removed, existing, null, existing.Document, ++_sequence)); } @@ -2692,10 +2714,6 @@ namespace GameCult.Caching _variantKeys.Remove(stored.Key.Value); else _variantKeys.Add(stored.Key.Value); - if (plan.Reports.TryGetValue(stored.Key.Value, out var report) && report != null) - _variantReports[stored.Key.Value] = report; - else - _variantReports.Remove(stored.Key.Value); changes.Add(new Change( previous == null ? CultCacheDocumentChangeKind.Added : CultCacheDocumentChangeKind.Updated, stored, @@ -2911,16 +2929,12 @@ namespace GameCult.Caching var resolution = Registry.ResolvePersistedSchemaDetailed(record.SchemaId, catalog); if (record.Variant != null) { - // The cache resolves it against its base when it admits the load; the catalog names the slots the type may have dropped. - var persisted = catalog.FirstOrDefault(entry => string.Equals(entry.SchemaId, record.SchemaId, StringComparison.Ordinal)); + // The cache resolves it against its base when it admits the load. return new CultStoredDocument( new CultRecordKey(record.Key), record.StoredAt, resolution.Descriptor, - new CultVariantDelta(record.Variant.BaseKey, record.Variant.Overrides) - { - SlotNames = persisted?.Members.GroupBy(member => member.Slot).ToDictionary(group => group.Key, group => group.First().MemberName) - }, + new CultVariantDelta(record.Variant.BaseKey, record.Variant.Overrides), null); } diff --git a/src/GameCult.Caching/CultVariants.cs b/src/GameCult.Caching/CultVariants.cs index 08882c79..ee5cc523 100644 --- a/src/GameCult.Caching/CultVariants.cs +++ b/src/GameCult.Caching/CultVariants.cs @@ -87,9 +87,5 @@ namespace GameCult.Caching public string BaseKey { get; } public IReadOnlyList Overrides { get; } - - // Member names by slot from the catalog the delta was loaded under, for warnings about slots the type dropped. - // Not persisted. - internal IReadOnlyDictionary? SlotNames { get; set; } } } diff --git a/tests/GameCult.Caching.Tests/VariantTests.cs b/tests/GameCult.Caching.Tests/VariantTests.cs index fec33c96..f8544e50 100644 --- a/tests/GameCult.Caching.Tests/VariantTests.cs +++ b/tests/GameCult.Caching.Tests/VariantTests.cs @@ -50,12 +50,13 @@ namespace GameCult.Caching.Tests private static void SeedBase(CultCache cache) => cache.Commit(batch => batch.Upsert(typeof(VariantGear), Laser(), BaseKey)); - // laser-big: a variant of laser that overrides its name and power and inherits the rest. + // laser-big: a variant of laser that overrides its name, power and code (an indexed value must be its own) and inherits the rest. private static void SeedBig(CultCache cache, CultRecordKey? key = null, CultRecordKey? baseKey = null, string name = "laser big", int power = 25) => cache.Commit(batch => batch.UpsertVariant(key ?? BigKey, baseKey ?? BaseKey, new[] { cache.Override(nameof(VariantGear.Name), name), - cache.Override(nameof(VariantGear.Power), power) + cache.Override(nameof(VariantGear.Power), power), + cache.Override(nameof(VariantGear.Code), name) })); private static void EditBase(CultCache cache, Action edit) => @@ -85,7 +86,7 @@ namespace GameCult.Caching.Tests var big = cache.Get(BigKey)!; Assert.That(big.Name, Is.EqualTo("laser big")); Assert.That(big.Power, Is.EqualTo(25)); - Assert.That(big.Code, Is.EqualTo("l1"), "an inherited member"); + Assert.That(big.Code, Is.EqualTo("laser big"), "the override the unique index requires"); Assert.That(big.Tags, Is.EqualTo(new[] { "beam" }), "an inherited list"); Assert.That(cache.Get(BaseKey)!.Power, Is.EqualTo(10)); Assert.That(cache.GetStored(BigKey)!.Variant!.BaseKey, Is.EqualTo(BaseKey.Value)); @@ -133,9 +134,10 @@ namespace GameCult.Caching.Tests Assert.That(cache.GetByName("laser big")!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); Assert.That(cache.GetByName("laser big")!.Power, Is.EqualTo(25), "the override survives the base edit"); Assert.That(cache.GetByIndex("code", "l9")!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); - // big inherited the old code; its stale index entry must be gone, not shadowing. + // the base's old code entry must be gone, not shadowing, and its new one must find the base itself. Assert.That(cache.GetByIndex("code", "l1"), Is.Null); - Assert.That(cache.GetByIndex("code", "l2")!.Name, Is.Not.Null); + Assert.That(cache.GetByIndex("code", "l2")!.Name, Is.EqualTo("laser")); + Assert.That(cache.GetByIndex("code", "laser big")!.Name, Is.EqualTo("laser big")); Assert.That(seen.Select(entry => entry.Key), Is.EquivalentTo(new[] { BaseKey.Value, BigKey.Value, "laser-coded" })); Assert.That(seen.Select(entry => entry.Sequence), Is.EqualTo(Enumerable.Range((int)seen[0].Sequence, seen.Count).Select(n => (long)n)), @@ -297,7 +299,7 @@ namespace GameCult.Caching.Tests batch.UpsertVariant(BigKey, spare, cache.GetStored(BigKey)!.Variant!.Overrides); batch.Remove(BaseKey); }), Is.True, "rebased in the same batch"); - Assert.That(cache.Get(BigKey)!.Code, Is.EqualTo(string.Empty), "now resolved from spare"); + Assert.That(cache.Get(BigKey)!.Tags, Is.Empty, "now resolved from spare"); Assert.That(cache.Commit(batch => { @@ -435,36 +437,204 @@ namespace GameCult.Caching.Tests Assert.That(variant.Power, Is.EqualTo(7), "the override the type still has applies"); Assert.That(variant.Name, Is.EqualTo("drift variant")); - var report = cache.VariantMigrationReports.Single(); - Assert.That(report.Kind, Is.EqualTo(CultSchemaMigrationKind.CompatibleDrift)); - Assert.That(report.IgnoredExtraSlots, Is.EqualTo(new[] { 2 })); - var warning = report.Warnings.Single(); - Assert.That(warning.Code, Is.EqualTo("ignored_extra_slot"), "the code a dropped member gets on a plain record"); - Assert.That(warning.Message, Does.Contain("drift-variant").And.Contain("Wing")); + // The same decision, on the same surface, that the plain base record gets from the store's schema resolution. + var reports = cache.BackingStores[0].LastSchemaMigrationReports; + Assert.That(reports, Has.Count.EqualTo(2), "one per record: the base and the variant"); + Assert.That(reports.Select(report => report.Kind), Is.All.EqualTo(CultSchemaMigrationKind.CompatibleDrift)); + Assert.That(reports.Select(report => string.Join(",", report.IgnoredExtraSlots)), Is.All.EqualTo("2")); + Assert.That(reports.SelectMany(report => report.Warnings).Select(warning => warning.Code), Is.All.EqualTo("ignored_extra_slot")); + } + + private static readonly byte[] NotAnInt = { 0xa3, (byte)'a', (byte)'b', (byte)'c' }; + + private static CultVariantOverride TextOverride(int slot, string value) + { + var bytes = new byte[value.Length + 1]; + bytes[0] = (byte)(0xa0 | value.Length); + for (var index = 0; index < value.Length; index++) + bytes[index + 1] = (byte)value[index]; + return CultVariantOverride.Set(slot, bytes); + } + + private static CultPersistedRecord OverridingRecord(string key, string baseKey, params CultVariantOverride[] overrides) => new() + { + Key = key, + SchemaId = Registry.GetRequired().SchemaId, + StoredAt = "2026-01-01T00:00:00.0000000Z", + Payload = Array.Empty(), + Variant = new CultVariantDelta(baseKey, overrides) + }; + + [Test] + public void AnOverrideThatNoLongerDecodesRefusesTheLoadAsAPlainRecordHoldingItDoes() + { + // VariantGear.Power is [Key(1)] int; a string there is the nested-type-change case with the schema id unchanged. + var plainRecord = new CultPersistedRecord + { + Key = "hand-plain", + SchemaId = Registry.GetRequired().SchemaId, + StoredAt = "2026-01-01T00:00:00.0000000Z", + Payload = new byte[] { 0x94, 0xa1, (byte)'x', 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa0, 0x90 } + }; + Assert.That(Assert.Catch(() => Open(WriteStore(plainRecord)).Dispose()), Is.Not.Null, "the plain-record outcome is a refusal"); + + var path = WriteStore(PlainGear("hand-base"), OverridingRecord("hand-variant", "hand-base", CultVariantOverride.Set(1, NotAnInt))); + var refused = Assert.Catch(() => Open(path).Dispose())!; + Assert.That(refused.Message, Does.Contain("hand-variant").And.Contain("Power")); } [Test] - public void AnOverrideThatNoLongerDecodesIsIgnoredWithAWarningAndTheBaseValueApplies() + public void AnOverrideOfASlotTheTypeNeverHadIsIgnoredOnLoadAsAPlainRecordIgnoresAnExtraSlot() + { + var path = WriteStore(PlainGear("hand-base"), OverridingRecord("hand-variant", "hand-base", + CultVariantOverride.Set(99, new byte[] { 0x01 }), + TextOverride(0, "hand variant"), + TextOverride(2, "hand-code"))); + using var cache = Open(path); + Assert.That(cache.Get(new CultRecordKey("hand-variant"))!.Name, Is.EqualTo("hand variant")); + Assert.That(cache.Get(new CultRecordKey("hand-variant"))!.Power, Is.EqualTo(10), "inherits the base"); + } + + // ---- a bad write is refused; drift is for type changes after the fact ---- + + [Test] + public void AnInvalidOverrideIsRefusedAtWriteNamingVariantSlotAndReasonAndNothingLands() + { + var path = PathOf("gear.cc"); + using var cache = Open(path); + SeedBase(cache); + + var unknown = Refused(() => cache.Commit(batch => batch.UpsertVariant(BigKey, BaseKey, new[] + { + CultVariantOverride.Set(99, new byte[] { 0x01 }) + }))); + Assert.That(unknown.Message, Does.Contain(BigKey.Value).And.Contain("99").And.Contain("does not have")); + + var wrongType = Refused(() => cache.UpsertVariantAsync(BigKey, BaseKey, new[] + { + CultVariantOverride.Set(1, NotAnInt) + }).GetAwaiter().GetResult()); + Assert.That(wrongType.Message, Does.Contain(BigKey.Value).And.Contain("Power").And.Contain("slot 1")); + + Assert.That(cache.Get(BigKey), Is.Null); + cache.FlushAsync().GetAwaiter().GetResult(); + Assert.That(HeaderOf(path), Is.EqualTo("cultcache.store.v1"), "no variant was persisted"); + } + + [Test] + public void TwoOverridesOfOneSlotAreRefusedAtWriteAndAnUnknownMemberNameIsAnArgumentException() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + + var twice = Refused(() => cache.Commit(batch => batch.UpsertVariant(BigKey, BaseKey, new[] + { + cache.Override(nameof(VariantGear.Power), 1), + cache.Override(nameof(VariantGear.Power), 2) + }))); + Assert.That(twice.Message, Does.Contain(BigKey.Value).And.Contain("slot 1").And.Contain("more than once")); + Assert.That(cache.Get(BigKey), Is.Null); + + var unknownName = Assert.Throws(() => cache.Override("Nope", 1))!; + Assert.That(unknownName.Message, Does.Contain("Nope")); + } + + // ---- a variant may not share an indexed value with another record ---- + + [Test] + public void AVariantThatInheritsAnIndexedValueIsRefusedNamingBothKeysAndTheIndex() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + + var inherited = Refused(() => cache.Commit(batch => batch.UpsertVariant(BigKey, BaseKey, new[] + { + cache.Override(nameof(VariantGear.Name), "laser big") + }))); + Assert.That(inherited.Message, Does.Contain(BigKey.Value).And.Contain(BaseKey.Value).And.Contain("code").And.Contain("l1")); + + var explicitly = Refused(() => cache.Commit(batch => batch.UpsertVariant(BigKey, BaseKey, new[] + { + cache.Override(nameof(VariantGear.Name), "laser big"), + cache.Override(nameof(VariantGear.Code), "l1") + }))); + Assert.That(explicitly.Message, Does.Contain(BigKey.Value).And.Contain(BaseKey.Value)); + Assert.That(cache.Get(BigKey), Is.Null, "nothing landed"); + Assert.That(cache.GetByIndex("code", "l1")!.Name, Is.EqualTo("laser")); + + SeedBig(cache); + Assert.That(cache.GetByIndex("code", "l1")!.Name, Is.EqualTo("laser")); + Assert.That(cache.GetByIndex("code", "laser big")!.Name, Is.EqualTo("laser big")); + } + + [Test] + public void ABaseEditThatWouldGiveItsVariantsIndexedValueToTheBaseIsRefused() + { + using var cache = Open(PathOf("gear.cc")); + SeedBase(cache); + SeedBig(cache); + + var refused = Refused(() => EditBase(cache, gear => gear.Code = "laser big")); + Assert.That(refused.Message, Does.Contain(BigKey.Value).And.Contain(BaseKey.Value).And.Contain("code")); + Assert.That(cache.Get(BaseKey)!.Code, Is.EqualTo("l1"), "nothing landed"); + } + + [Test] + public void ALoadedVariantThatInheritsAnIndexedValueRefusesTheLoadNamingBothKeys() + { + var path = WriteStore(PlainGear("hand-base"), OverridingRecord("hand-variant", "hand-base")); + var refused = Assert.Throws(() => Open(path).Dispose())!; + Assert.That(refused.Message, Does.Contain("hand-variant").And.Contain("hand-base").And.Contain("code")); + } + + // ---- flatten resolves against the same batch ---- + + [Test] + public void AFlattenAndABaseEditInOneBatchLandTheResolutionOfTheWholeBatch() { var path = PathOf("gear.cc"); - const int notAnInt = 1; // VariantGear.Power, [Key(1)] using (var cache = Open(path)) { SeedBase(cache); - cache.Commit(batch => batch.UpsertVariant(BigKey, BaseKey, new[] + SeedBig(cache); + cache.Commit(batch => { - cache.Override(nameof(VariantGear.Name), "laser big"), - CultVariantOverride.Set(notAnInt, new byte[] { 0xa3, (byte)'a', (byte)'b', (byte)'c' }) - })); - var warning = cache.VariantMigrationReports.Single().Warnings.Single(); - Assert.That(warning.Message, Does.Contain(BigKey.Value).And.Contain("Power")); - Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(10), "inherits the base value"); - Assert.That(cache.Get(BigKey)!.Name, Is.EqualTo("laser big")); + var edited = Laser(); + edited.Tags.Add("pierce"); + batch.Upsert(typeof(VariantGear), edited, BaseKey); + batch.Flatten(BigKey); + }); + + Assert.That(cache.GetStored(BigKey)!.Variant, Is.Null); + Assert.That(cache.Get(BigKey)!.Tags, Is.EqualTo(new[] { "beam", "pierce" }), "the edit made in the same batch"); + Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(25)); } using var reloaded = Open(path); - Assert.That(reloaded.Get(BigKey)!.Power, Is.EqualTo(10)); - Assert.That(reloaded.VariantMigrationReports.Single().Warnings.Single().Message, Does.Contain("Power")); + Assert.That(reloaded.GetStored(BigKey)!.Variant, Is.Null); + Assert.That(reloaded.Get(BigKey)!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); + } + + // ---- the directory store refuses a variant page on load as it does on write ---- + + [Test] + public void TheDirectoryStoreRefusesToLoadAVariantPage() + { + var manifest = PathOf("dir-page.cc"); + var records = DirectoryMessagePackBackingStore.DefaultRecordDirectoryPath(manifest); + Directory.CreateDirectory(records); + var page = CultDocumentMessagePackSerialization.SerializePersistedRecord(OverridingRecord("hand-variant", "hand-base", TextOverride(0, "x"))); + var hash = System.Security.Cryptography.SHA256.HashData(page); + File.WriteAllBytes(Path.Combine(records, Convert.ToHexString(hash).ToLowerInvariant() + ".msgpack"), page); + + using var store = new DirectoryMessagePackBackingStore(manifest, records); + var read = typeof(DirectoryMessagePackBackingStore).GetMethod( + "ReadPersistedRecordPage", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + var refused = Assert.Throws( + () => read.Invoke(store, new object?[] { new CultPersistedRecord { Key = "hand-variant", Payload = hash }, null }))!; + + Assert.That(refused.InnerException, Is.TypeOf()); + Assert.That(refused.InnerException!.Message, Does.Contain("hand-variant").And.Contain("directory store")); } // ---- persisted format ---- @@ -541,7 +711,7 @@ namespace GameCult.Caching.Tests using var readOnly = Open(path, readOnly: true); Assert.That(readOnly.Get(BigKey)!.Power, Is.EqualTo(25)); - Assert.That(readOnly.Get(BigKey)!.Code, Is.EqualTo("l1")); + Assert.That(readOnly.Get(BigKey)!.Code, Is.EqualTo("laser big")); // A base edit another writer commits reaches the read-only cache's variant when it pulls: a re-resolution is no write. using var writer = Open(path); @@ -705,7 +875,7 @@ namespace GameCult.Caching.Tests using (var cache = Open(path)) { Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(25)); - Assert.That(cache.Get(BigKey)!.Code, Is.EqualTo("l1")); + Assert.That(cache.Get(BigKey)!.Code, Is.EqualTo("laser big")); cache.BackingStores[0].PushAll(); } diff --git a/tests/vectors/document-variants-c0/generate.py b/tests/vectors/document-variants-c0/generate.py index e3d2547d..c6e5d2da 100644 --- a/tests/vectors/document-variants-c0/generate.py +++ b/tests/vectors/document-variants-c0/generate.py @@ -11,9 +11,11 @@ at test time. Run: python generate.py (needs msgpack). v1-base.msgpack NOT generated here: written once by the Python runtime at CultLib 69a21bb (SingleFileMessagePackBackingStore.push of alpha and beta, type vectors.item, before any C0 code existed) - variant-v2.msgpack what C1 writes for a variant: header v2, record slot 4 = - [baseKey, overrides[]], empty payload (override op Set = 0, - path steps are [slot, elementId]) + variant-v2.msgpack the wire shape of a variant record, hand-built: header v2, record slot 4 = + [baseKey, overrides[]], empty payload (override op Set = 0, path steps + are [slot, elementId]). C1 does not write this store and refuses to load + it: the variant resolves to its base's name (R6). It exercises readers + that refuse a variant by version or record. """ import pathlib From 2845d3591bee3e4683f14b08dbb9aba12bfd7992 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 06:59:29 +0200 Subject: [PATCH 56/64] Regenerate the C1 variant vector: the variant overrides its indexed code The unique-index rule refuses a variant that inherits its base's [CultIndex] value, so the vector's laser-big now carries a code override. Written by the code under test through the production path; the other runtimes still refuse it by version and by the laser-big key. Co-Authored-By: Claude Sonnet 5 --- .../variant-store.msgpack | Bin 1391 -> 1408 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/tests/vectors/document-variants-c1/variant-store.msgpack b/tests/vectors/document-variants-c1/variant-store.msgpack index 3604a68da1979eac264453f272960bea7d7ed467..692b225d2c8591a97a6cbd625093df89e6085d29 100644 GIT binary patch delta 101 zcmaFQ)xf=BEepSim8qqbp{bsUiIJhXx#8qJEY+ScF;jD66GH<-Z36=<1A`+Bla}Tr i7N-_Xp29G362pQ8E5SU4q|9`X0ONuMk|3H1Sponi5+WV| delta 84 zcmZqRe$TaGEepS)m5I5Pfu){-p^1U1x#i?NEY%h;F+)=mb5nCuZ36=<1A`+Bla}Tr d7N-_Xn!+$~62pQ8E5SU4q|9`X0ONuMk^mHQ8wdaZ From 5d6847e2208bf60b52d1f94fc1adfb8517ebd6bd Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 07:04:01 +0200 Subject: [PATCH 57/64] Align the C1 tests with the unique-index rule and fix the live-subscription fixture Hand-written and directory-store variants now override their indexed value or name as the rules require; the subscription test writes its variant through a committed batch so the file holds it, subscribes by key, and reports what it saw when it times out. Co-Authored-By: Claude Sonnet 5 --- tests/GameCult.Caching.Tests/VariantTests.cs | 8 ++++---- .../CultNetDocumentRegistryVariantTests.cs | 12 +++++++----- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/tests/GameCult.Caching.Tests/VariantTests.cs b/tests/GameCult.Caching.Tests/VariantTests.cs index f8544e50..2cd7cde2 100644 --- a/tests/GameCult.Caching.Tests/VariantTests.cs +++ b/tests/GameCult.Caching.Tests/VariantTests.cs @@ -90,7 +90,7 @@ namespace GameCult.Caching.Tests Assert.That(big.Tags, Is.EqualTo(new[] { "beam" }), "an inherited list"); Assert.That(cache.Get(BaseKey)!.Power, Is.EqualTo(10)); Assert.That(cache.GetStored(BigKey)!.Variant!.BaseKey, Is.EqualTo(BaseKey.Value)); - Assert.That(cache.GetStored(BigKey)!.Variant!.Overrides, Has.Count.EqualTo(2)); + Assert.That(cache.GetStored(BigKey)!.Variant!.Overrides, Has.Count.EqualTo(3)); } [Test] @@ -442,7 +442,7 @@ namespace GameCult.Caching.Tests Assert.That(reports, Has.Count.EqualTo(2), "one per record: the base and the variant"); Assert.That(reports.Select(report => report.Kind), Is.All.EqualTo(CultSchemaMigrationKind.CompatibleDrift)); Assert.That(reports.Select(report => string.Join(",", report.IgnoredExtraSlots)), Is.All.EqualTo("2")); - Assert.That(reports.SelectMany(report => report.Warnings).Select(warning => warning.Code), Is.All.EqualTo("ignored_extra_slot")); + Assert.That(reports.Select(report => report.Warnings.Select(warning => warning.Code)), Has.All.Contain("ignored_extra_slot")); } private static readonly byte[] NotAnInt = { 0xa3, (byte)'a', (byte)'b', (byte)'c' }; @@ -582,7 +582,7 @@ namespace GameCult.Caching.Tests [Test] public void ALoadedVariantThatInheritsAnIndexedValueRefusesTheLoadNamingBothKeys() { - var path = WriteStore(PlainGear("hand-base"), OverridingRecord("hand-variant", "hand-base")); + var path = WriteStore(PlainGear("hand-base"), OverridingRecord("hand-variant", "hand-base", TextOverride(0, "hand variant"))); var refused = Assert.Throws(() => Open(path).Dispose())!; Assert.That(refused.Message, Does.Contain("hand-variant").And.Contain("hand-base").And.Contain("code")); } @@ -843,7 +843,7 @@ namespace GameCult.Caching.Tests SeedBase(cache); var push = Assert.Throws(() => cache.UpsertVariantAsync( - BigKey, BaseKey, new[] { cache.Override(nameof(VariantGear.Name), "laser big") }).GetAwaiter().GetResult())!; + BigKey, BaseKey, new[] { cache.Override(nameof(VariantGear.Name), "laser big"), cache.Override(nameof(VariantGear.Code), "laser big") }).GetAwaiter().GetResult())!; Assert.That(push.Message, Does.Contain(BigKey.Value)); var commit = Assert.Throws(() => SeedBig(cache))!; Assert.That(commit.Message, Does.Contain(BigKey.Value)); diff --git a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs index 2a8ddc58..8c70c31e 100644 --- a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs @@ -83,11 +83,11 @@ namespace GameCult.Networking.Tests using (var writer = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = registry })) { writer.Commit(batch => batch.Upsert(typeof(VariantWireFixture), new VariantWireFixture { Name = "base", Power = 1 }, BaseKey)); - writer.UpsertVariantAsync(VariantKey, BaseKey, new[] + writer.Commit(batch => batch.UpsertVariant(VariantKey, BaseKey, new[] { writer.Override(nameof(VariantWireFixture.Name), "big"), writer.Override(nameof(VariantWireFixture.Power), 9) - }).GetAwaiter().GetResult(); + })); } var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry)); @@ -128,13 +128,15 @@ namespace GameCult.Networking.Tests { MessageId = "subscribe-all", SubscriptionId = "all", + RecordKeys = new[] { BaseKey.Value, VariantKey.Value }, IncludeSnapshot = true }); await WaitUntilAsync(() => snapshot.Task.IsCompleted); cache.AddBackingStore(new SingleFileMessagePackBackingStore(path)); - await WaitUntilAsync(() => !errors.IsEmpty || changes.Any(change => change.Document?.RecordKey == VariantKey.Value)); + await WaitUntilAsync(() => !errors.IsEmpty || changes.Any(change => change.Document?.RecordKey == VariantKey.Value), + () => $"changes={string.Join(",", changes.Select(c => c.ChangeKind + ":" + c.Document?.RecordKey))} errors={string.Join(",", errors.Select(e => e.Error))} cacheKeys={cache.GetStored(BaseKey) != null}/{cache.GetStored(VariantKey) != null}"); await Task.Delay(200); // let anything else already in flight arrive Assert.That(changes.Select(change => change.Document?.RecordKey), Does.Not.Contain(VariantKey.Value), @@ -180,13 +182,13 @@ namespace GameCult.Networking.Tests Assert.That(refused.InnerException!.Message, Does.Contain(VariantKey.Value).And.Contain(BaseKey.Value)); } - private static async Task WaitUntilAsync(Func condition) + private static async Task WaitUntilAsync(Func condition, Func? diagnostic = null) { var deadline = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(5); while (!condition()) { if (DateTimeOffset.UtcNow > deadline) - Assert.Fail("Condition was not satisfied before timeout."); + Assert.Fail("Condition was not satisfied before timeout. " + diagnostic?.Invoke()); await Task.Delay(5); } } From 354f9743e6524be706b4f57a86c0d3278ea3edae Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 08:28:24 +0200 Subject: [PATCH 58/64] Refuse a plain write that shares a variant's indexed value; a flush sheds overrides the type lacks The index rule is about the commit's result, so it now runs for every commit that changes an indexed value: a plain record landing on a value a variant of the post-commit set holds is refused naming both keys and the index (the held index is never trusted; a plain write had already overwritten it). Plain-vs-plain is untouched. A variant sheds overrides of slots its type lacks when it is flushed, as a plain record sheds the member, and the load's report names the slot when the schema itself never had it. Co-Authored-By: Claude Sonnet 5 --- src/GameCult.Caching/CultCache.cs | 98 +++++++++++- tests/GameCult.Caching.Tests/VariantTests.cs | 150 +++++++++++++++++++ 2 files changed, 245 insertions(+), 3 deletions(-) diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index f17d5b93..2d4e7137 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -2520,7 +2520,11 @@ namespace GameCult.Caching } if (toResolve.Count == 0) - return new VariantPlan(admitted); + { + var unchanged = new VariantPlan(admitted); + RefusePlainSharingWithVariant(unchanged, incoming, gone); + return unchanged; + } var pending = new HashSet(toResolve, StringComparer.Ordinal); var done = new Dictionary(StringComparer.Ordinal); @@ -2532,6 +2536,7 @@ namespace GameCult.Caching var plan = new VariantPlan(admitted.Select(stored => done.TryGetValue(stored.Key.Value, out var resolved) ? resolved : stored).ToList()); foreach (var key in toResolve.Where(key => !incoming.ContainsKey(key))) plan.Dependents.Add(done[key]); + RefusePlainSharingWithVariant(plan, incoming, gone); return plan; CultStoredDocument ResolveOne(string key) @@ -2672,6 +2677,61 @@ namespace GameCult.Caching } } + // The index rule is about the commit's result, so it holds for every commit that changes an indexed value, in either + // order: a variant resolving onto another record's value is refused in ResolveOne; a plain record landing on a + // variant's value is refused here, against the variants of the post-commit set (never the held index, which the plain + // write would already have overwritten). Plain-vs-plain sharing is not this rule's business. + private void RefusePlainSharingWithVariant( + VariantPlan plan, + IReadOnlyDictionary incoming, + HashSet gone) + { + Dictionary<(Type Type, string Alias), Dictionary>? variantValues = null; + foreach (var stored in plan.Admitted) + { + if (stored.Variant != null || stored.Descriptor.IndexAccessors.Count == 0) + continue; + foreach (var pair in stored.Descriptor.IndexAccessors) + { + var value = pair.Value(stored.Document); + if (string.IsNullOrWhiteSpace(value)) + continue; + variantValues ??= HeldByVariants(plan, incoming, gone); + if (variantValues.TryGetValue((stored.Descriptor.DocumentType, pair.Key), out var values) && + values.TryGetValue(value, out var variantKey) && variantKey != stored.Key.Value) + throw new InvalidOperationException( + $"Record {stored.Key.Value} and variant {variantKey} both hold index {pair.Key} '{value}'; " + + "a variant may not share an indexed value with another record."); + } + } + } + + // The indexed values the variants of the post-commit set hold: those this commit resolved, and those it left alone. + private Dictionary<(Type Type, string Alias), Dictionary> HeldByVariants( + VariantPlan plan, + IReadOnlyDictionary incoming, + HashSet gone) + { + var variants = new Dictionary(StringComparer.Ordinal); + foreach (var variantKey in _variantKeys.Where(variantKey => !incoming.ContainsKey(variantKey) && !gone.Contains(variantKey))) + variants[variantKey] = _entries[variantKey]; + foreach (var stored in plan.Admitted.Concat(plan.Dependents).Where(stored => stored.Variant != null)) + variants[stored.Key.Value] = stored; + + var held = new Dictionary<(Type Type, string Alias), Dictionary>(); + foreach (var stored in variants.Values) + { + foreach (var pair in stored.Descriptor.IndexAccessors) + { + var value = pair.Value(stored.Document); + if (!string.IsNullOrWhiteSpace(value)) + MapOf(held, (stored.Descriptor.DocumentType, pair.Key))[value] = stored.Key.Value; + } + } + + return held; + } + private static InvalidOperationException CycleRefusal(IEnumerable keys) => new($"Variant bases form a cycle: {string.Join(" -> ", keys)}."); @@ -2917,10 +2977,41 @@ namespace GameCult.Caching SchemaId = entry.Descriptor.SchemaId, StoredAt = entry.StoredAt, Payload = entry.Variant != null ? Array.Empty() : serializePayload(entry.Document), - Variant = entry.Variant == null ? null : new CultVariantDelta(entry.Variant.BaseKey, entry.Variant.Overrides) + Variant = entry.Variant == null ? null : new CultVariantDelta(entry.Variant.BaseKey, OverridesTheTypeHas(entry).ToArray()) }; } + // A plain record sheds a member its type dropped when it is flushed; a variant sheds the override of that slot, so + // a later type reusing the slot number cannot resurrect it. The load's report names the shed slots. + private static IEnumerable OverridesTheTypeHas(CultStoredDocument entry) => + entry.Variant!.Overrides.Where(entryOverride => + entryOverride.Path.Count != 1 || entry.Descriptor.RichMembers.Any(member => member.Slot == entryOverride.Path[0].Slot)); + + // A variant's override of a slot its type lacks is ignored like an extra slot on a plain record. Schema resolution + // reports slots the persisted schema had and the type dropped; an override the schema never had is added here. + protected static CultSchemaMigrationReport ReportVariantSheds(CultSchemaMigrationReport report, CultStoredDocument stored) + { + if (stored.Variant == null) + return report; + var shed = stored.Variant.Overrides + .Where(entryOverride => entryOverride.Path.Count == 1 && + stored.Descriptor.RichMembers.All(member => member.Slot != entryOverride.Path[0].Slot)) + .Select(entryOverride => entryOverride.Path[0].Slot) + .Except(report.IgnoredExtraSlots) + .Distinct() + .OrderBy(slot => slot) + .ToArray(); + if (shed.Length == 0) + return report; + report.IgnoredExtraSlots = report.IgnoredExtraSlots.Concat(shed).OrderBy(slot => slot).ToArray(); + report.Warnings = report.Warnings.Concat(shed.Select(slot => new CultSchemaMigrationWarning + { + Code = "ignored_extra_slot", + Message = $"Variant {stored.Key.Value} overrides slot {slot}, which {stored.Descriptor.DocumentType.Name} does not have; the override is ignored and shed on flush." + })).ToArray(); + return report; + } + protected CultStoredDocument ToStoredDocument( CultPersistedRecord record, IReadOnlyCollection catalog, @@ -2993,8 +3084,9 @@ namespace GameCult.Caching var persisted = new Dictionary(StringComparer.Ordinal); foreach (var record in snapshot.Records) { - reports.Add(Registry.ResolvePersistedSchemaReport(record.SchemaId, snapshot.SchemaCatalog)); + var report = Registry.ResolvePersistedSchemaReport(record.SchemaId, snapshot.SchemaCatalog); var stored = ToStoredDocument(record, snapshot.SchemaCatalog, DeserializePayload); + reports.Add(ReportVariantSheds(report, stored)); persisted[stored.Key.Value] = stored; } diff --git a/tests/GameCult.Caching.Tests/VariantTests.cs b/tests/GameCult.Caching.Tests/VariantTests.cs index 2cd7cde2..c81e892b 100644 --- a/tests/GameCult.Caching.Tests/VariantTests.cs +++ b/tests/GameCult.Caching.Tests/VariantTests.cs @@ -587,6 +587,140 @@ namespace GameCult.Caching.Tests Assert.That(refused.Message, Does.Contain("hand-variant").And.Contain("hand-base").And.Contain("code")); } + // ---- the index rule holds for the commit's result, in either write order, and the store always reopens ---- + + private static VariantGear Other(string code) => new() { Name = "other", Power = 1, Code = code }; + + [Test] + public async Task APlainWriteThatWouldShareAVariantsIndexedValueIsRefusedNamingBothKeysAndTheStoreReopens() + { + var path = PathOf("gear.cc"); + var other = new CultRecordKey("other"); + using (var cache = Open(path)) + { + SeedBase(cache); + SeedBig(cache); + + var refused = Refused(() => cache.Commit(batch => batch.Upsert(typeof(VariantGear), Other("laser big"), other))); + Assert.That(refused.Message, Does.Contain(other.Value).And.Contain(BigKey.Value).And.Contain("code").And.Contain("laser big")); + + var single = Assert.ThrowsAsync( + () => cache.UpsertAsync(Other("laser big"), new CultRecordHandle(other)))!; + Assert.That(single.Message, Does.Contain(other.Value).And.Contain(BigKey.Value)); + + Assert.That(cache.Get(other), Is.Null, "nothing landed"); + Assert.That(cache.GetByIndex("code", "laser big")!.Name, Is.EqualTo("laser big"), "the variant is still found by its value"); + EditBase(cache, gear => gear.Power = 11); + Assert.That(cache.Get(BigKey)!.Power, Is.EqualTo(25), "the variant is still editable through its base"); + await Task.CompletedTask; + } + + using var reopened = Open(path); + Assert.That(reopened.GetByIndex("code", "laser big")!.Name, Is.EqualTo("laser big")); + Assert.That(reopened.Get(other), Is.Null); + } + + [Test] + public void ABaseEditOrANewPlainRecordFirstThenAVariantOnTheSameValueIsRefusedAndTheStoreReopens() + { + var path = PathOf("gear.cc"); + var other = new CultRecordKey("other"); + using (var cache = Open(path)) + { + SeedBase(cache); + cache.Commit(batch => batch.Upsert(typeof(VariantGear), Other("laser big"), other)); + + var refused = Refused(() => SeedBig(cache)); + Assert.That(refused.Message, Does.Contain(BigKey.Value).And.Contain(other.Value).And.Contain("code").And.Contain("laser big")); + Assert.That(cache.Get(BigKey), Is.Null, "nothing landed"); + + // The same batch, either staging order: the result is what is judged. + var sameBatchPlainFirst = Refused(() => cache.Commit(batch => + { + batch.Upsert(typeof(VariantGear), Other("taken"), new CultRecordKey("taker")); + batch.UpsertVariant(BigKey, BaseKey, new[] + { + cache.Override(nameof(VariantGear.Name), "laser big"), + cache.Override(nameof(VariantGear.Code), "taken") + }); + })); + Assert.That(sameBatchPlainFirst.Message, Does.Contain(BigKey.Value).And.Contain("taker")); + var sameBatchVariantFirst = Refused(() => cache.Commit(batch => + { + batch.UpsertVariant(BigKey, BaseKey, new[] + { + cache.Override(nameof(VariantGear.Name), "laser big"), + cache.Override(nameof(VariantGear.Code), "taken") + }); + batch.Upsert(typeof(VariantGear), Other("taken"), new CultRecordKey("taker")); + })); + Assert.That(sameBatchVariantFirst.Message, Does.Contain(BigKey.Value).And.Contain("taker")); + + // Plain-vs-plain sharing is not this rule's business. + Assert.DoesNotThrow(() => cache.Commit(batch => batch.Upsert(typeof(VariantGear), Other("l1"), new CultRecordKey("twin")))); + } + + using var reopened = Open(path); + Assert.That(reopened.Get(BigKey), Is.Null); + Assert.That(reopened.Get(other), Is.Not.Null); + } + + // ---- a variant sheds overrides its type lacks when it is flushed, as a plain record sheds the member ---- + + [Test] + public void AFlushShedsAnOverrideOfADroppedSlotSoALaterTypeReusingTheSlotDoesNotResurrectIt() + { + var path = PathOf("drift.cc"); + var wide = CultDocumentRegistry.ForTypes(new[] { typeof(DriftWide) }); + using (var writer = Open(path, registry: wide)) + { + writer.Commit(batch => + { + batch.Upsert(typeof(DriftWide), new DriftWide { Name = "drift", Power = 1, Wing = "base wing" }, new CultRecordKey("drift-base")); + batch.UpsertVariant(new CultRecordKey("drift-variant"), new CultRecordKey("drift-base"), new[] + { + writer.Override(nameof(DriftWide.Name), "drift variant"), + writer.Override(nameof(DriftWide.Wing), "stale wing") + }); + }); + } + + using (var narrow = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftNarrow) }))) + narrow.BackingStores[0].PushAll(); + + Assert.That(OverriddenSlotsOn(path, "drift-variant"), Is.EqualTo(new[] { 0 }), "the dropped slot's override is gone from the flushed record"); + + using var reused = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftReused) })); + Assert.That(reused.Get(new CultRecordKey("drift-base"))!.Colour, Is.Empty); + Assert.That(reused.Get(new CultRecordKey("drift-variant"))!.Colour, Is.Empty, "the variant inherits its base's colour, not the old wing"); + } + + [Test] + public void AnOverrideOfASlotTheTypeNeverHadIsReportedOnLoadAndShedOnTheNextFlush() + { + var path = WriteStore(PlainGear("hand-base"), OverridingRecord("hand-variant", "hand-base", + CultVariantOverride.Set(99, new byte[] { 0x01 }), + TextOverride(0, "hand variant"), + TextOverride(2, "hand-code"))); + using (var cache = Open(path)) + { + var variantReport = cache.BackingStores[0].LastSchemaMigrationReports.Single(report => report.IgnoredExtraSlots.Length > 0); + Assert.That(variantReport.IgnoredExtraSlots, Is.EqualTo(new[] { 99 })); + Assert.That(variantReport.Warnings.Select(warning => warning.Code), Has.Some.EqualTo("ignored_extra_slot")); + Assert.That(variantReport.Warnings.Select(warning => warning.Message), Has.Some.Contain("hand-variant")); + cache.BackingStores[0].PushAll(); + } + + Assert.That(OverriddenSlotsOn(path, "hand-variant").OrderBy(slot => slot), Is.EqualTo(new[] { 0, 2 })); + using var reopened = Open(path); + Assert.That(reopened.BackingStores[0].LastSchemaMigrationReports.SelectMany(report => report.IgnoredExtraSlots), Is.Empty); + Assert.That(reopened.Get(new CultRecordKey("hand-variant"))!.Name, Is.EqualTo("hand variant")); + } + + private static int[] OverriddenSlotsOn(string path, string key) => + CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records + .Single(record => record.Key == key).Variant!.Overrides.Select(entry => entry.Path[0].Slot).ToArray(); + // ---- flatten resolves against the same batch ---- [Test] @@ -950,6 +1084,22 @@ namespace GameCult.Caching.Tests public string Wing = string.Empty; } + // A later type that reuses the slot Narrow dropped, for another member. + [CultDocument("tests.variant_drift", "tests.variant_drift.v3")] + [MessagePackObject(AllowPrivate = true)] + internal sealed class DriftReused + { + [Key(0)] + [CultName] + public string Name = string.Empty; + + [Key(1)] + public int Power; + + [Key(2)] + public string Colour = string.Empty; + } + [CultDocument("tests.variant_drift", "tests.variant_drift.v2")] [MessagePackObject(AllowPrivate = true)] internal sealed class DriftNarrow From b572823d0d9ed7744d59f0cef03ccb647d3e7779 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 08:28:24 +0200 Subject: [PATCH 59/64] Refuse variants after the selection is applied, and never tell a subscriber about the removal of one it was only refused The selection paths (SelectPage, SelectAll) refused every stored variant before the selection ran, so once any variant existed a hop-bearing subscription threw out of its change handler and went silent. They now refuse only a variant the selection selects; the subscription server delivers that as a typed error and keeps its projection. The database server no longer sends removed for a key the subscriber only ever received as an error. A flatten racing the delivery check is recorded in a comment. Co-Authored-By: Claude Sonnet 5 --- .../CultNetDatabaseServer.cs | 52 ++++-- .../CultNetDatabaseSubscriptionServer.cs | 24 ++- .../CultNetDocumentRegistry.cs | 28 ++- .../CultNetDocumentRegistryVariantTests.cs | 160 ++++++++++++++++++ 4 files changed, 240 insertions(+), 24 deletions(-) diff --git a/src/GameCult.Networking/CultNetDatabaseServer.cs b/src/GameCult.Networking/CultNetDatabaseServer.cs index 0dc489ed..d53315ed 100644 --- a/src/GameCult.Networking/CultNetDatabaseServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseServer.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; @@ -502,27 +503,48 @@ namespace GameCult.Networking string subscriptionId, CultNetServerPeer peer) { + // Keys this subscriber only ever received as a refusal: it was never given them as records. + var refused = new HashSet(StringComparer.Ordinal); return _database.WatchAllChanges().Subscribe(change => { - CultNetDatabaseChangeRawMessage? outbound; - try - { - outbound = CreateChangeMessage(change, subscriptionId, selection); - } - catch (NotSupportedException refusal) - { - // Q6: a variant is not a record CultNet can carry; the subscriber that would have received it is told, by key. - peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); - return; - } - + var outbound = DeliverChange(change, subscriptionId, selection, refused, error => peer.SendCultNet(error)); if (outbound != null) - { peer.SendCultNet(outbound); - } }); } + // One subscriber's view of one change. A variant is not a record CultNet can carry (Q6): the subscriber is told, by key, and + // is not later told the variant was removed, because it never held it. + internal CultNetDatabaseChangeRawMessage? DeliverChange( + object change, + string subscriptionId, + CultNetSelection selection, + HashSet refused, + Action sendError) + { + CultNetDatabaseChangeRawMessage? outbound; + try + { + outbound = CreateChangeMessage(change, subscriptionId, selection); + } + catch (NotSupportedException refusal) + { + var refusedKey = change.GetType().GetProperty("Key")?.GetValue(change) is CultRecordKey changed ? changed.Value : string.Empty; + lock (refused) + refused.Add(refusedKey); + sendError(new CultNetErrorMessage { Error = refusal.Message }); + return null; + } + + if (outbound == null) + return null; + var recordKey = outbound.RecordKey ?? outbound.Document?.RecordKey ?? string.Empty; + bool wasRefused; + lock (refused) + wasRefused = refused.Remove(recordKey); + return wasRefused && outbound.ChangeKind == "removed" ? null : outbound; + } + internal CultNetDatabaseChangeRawMessage? CreateChangeMessage( object change, string subscriptionId, @@ -565,7 +587,7 @@ namespace GameCult.Networking { MessageId = Guid.NewGuid().ToString("N"), SubscriptionId = subscriptionId, - ChangeKind = kind ==CultNetDatabaseChangeKind.Added ? "added" : "updated", + ChangeKind = kind == CultNetDatabaseChangeKind.Added ? "added" : "updated", Document = _database.Documents.ToRawRecord(descriptor, key, document, DateTimeOffset.UtcNow.ToString("O")) }; } diff --git a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs index 359a9dfb..bb1f3900 100644 --- a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs @@ -204,6 +204,13 @@ namespace GameCult.Networking peer.SendCultNet(CultNetErrorMessage.ForReferenceOutsideTarget(ex)); return Task.CompletedTask; } + catch (NotSupportedException refusal) + { + // Q6: a snapshot that selects a variant is refused to this subscriber as a typed error. + Withdraw(key, sendRemovals: false, forgetRequest: true); + peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); + return Task.CompletedTask; + } catch { Withdraw(key, sendRemovals: false, forgetRequest: true); @@ -342,9 +349,20 @@ namespace GameCult.Networking if (!_projections.TryGetValue(key, out var projection)) return; var legacyRequest = request.ToLegacyShape(key.Id); var authorized = _authorizeRequest?.Invoke(legacyRequest, key.Peer) != false; - var next = authorized - ? CreateProjectedSnapshot(request, key.Peer) - : ProjectedSnapshot.Empty; + ProjectedSnapshot next; + try + { + next = authorized + ? CreateProjectedSnapshot(request, key.Peer) + : ProjectedSnapshot.Empty; + } + catch (NotSupportedException refusal) + { + // Q6: the selection selects a variant, which CultNet cannot carry. This subscriber is told, by key, and keeps what + // it was delivered; a change never throws out of the change handler. + key.Peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); + return; + } // With _projectRecord gone (docs/cultnet-selection-cut.md, S2-2), a projection's dictionary // key is always the record's own RecordKey/SchemaId, so the two can never disagree here; diff --git a/src/GameCult.Networking/CultNetDocumentRegistry.cs b/src/GameCult.Networking/CultNetDocumentRegistry.cs index 356761f5..5df34e98 100644 --- a/src/GameCult.Networking/CultNetDocumentRegistry.cs +++ b/src/GameCult.Networking/CultNetDocumentRegistry.cs @@ -391,11 +391,13 @@ namespace GameCult.Networking var stored = cache.AllStoredDocuments; if (rowFilter != null) stored = stored.Where(entry => rowFilter(entry.Descriptor, entry.Key)); - var rows = stored + var entries = stored.ToArray(); + var rows = entries .Select(entry => new CultNetSelectionEvaluator.Row( - entry.Descriptor, entry.Key, RefuseVariant(entry).Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) + entry.Descriptor, entry.Key, entry.Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) .ToArray(); var full = CultNetSelectionEvaluator.EvaluateAll(_documents, rows, selection); + RefuseSelectedVariants(entries, full.Ordered); // R-Q: a page's asOf is exact only when every matched row is committed through one shard's // log - a caller that knows about shards (CultNetDatabaseServer) supplies shardIdOf; one // that does not (the raw v0/shard-scoped rowFilter paths, which are already bounded to a @@ -485,12 +487,14 @@ namespace GameCult.Networking var stored = cache.AllStoredDocuments; if (rowFilter != null) stored = stored.Where(entry => rowFilter(entry.Descriptor, entry.Key)); - var rows = stored + var entries = stored.ToArray(); + var rows = entries .Select(entry => new CultNetSelectionEvaluator.Row( - entry.Descriptor, entry.Key, RefuseVariant(entry).Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) + entry.Descriptor, entry.Key, entry.Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) .ToArray(); var full = CultNetSelectionEvaluator.EvaluateAll(_documents, rows, selection); + RefuseSelectedVariants(entries, full.Ordered); var records = full.Ordered.Select(row => ToRawRecord(row, options)).ToArray(); var wantDocument = selection.Projection == CultNetSelectionProjections.Document; var edges = selection.HasHop @@ -550,12 +554,24 @@ namespace GameCult.Networking } // CultNet carries no variant deltas yet, and a resolved view sent as a plain record would be a lie about the store. - private static CultStoredDocument RefuseVariant(CultStoredDocument entry) => - entry.Variant == null ? entry : throw VariantRefusal(entry); + // The refusal follows the selection: a variant is refused only when the selection selects it, never for existing. + private static void RefuseSelectedVariants(IReadOnlyList entries, IReadOnlyList selected) + { + if (selected.Count == 0 || !entries.Any(entry => entry.Variant != null)) + return; + var variants = entries.Where(entry => entry.Variant != null).ToDictionary(entry => entry.Key.Value, StringComparer.Ordinal); + foreach (var row in selected) + { + if (variants.TryGetValue(row.Key.Value, out var variant)) + throw VariantRefusal(variant); + } + } // The live-change funnel's refusal: a load or write that lands a variant must not reach a subscriber as a record. internal static void RefuseVariantChange(CultCache cache, CultRecordKey key) { + // Recorded, not fixed: a Flatten committed on another thread between the change's admission and this read makes + // the record plain here, and its resolved view is delivered. The window is one thread hop wide. if (cache.GetStored(key) is { Variant: not null } entry) throw VariantRefusal(entry); } diff --git a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs index 8c70c31e..2ae6dfab 100644 --- a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs @@ -182,6 +182,153 @@ namespace GameCult.Networking.Tests Assert.That(refused.InnerException!.Message, Does.Contain(VariantKey.Value).And.Contain(BaseKey.Value)); } + + // A hop-bearing selection reconciles the whole store on every change. The refusal follows the selection: a subscriber + // whose selection never selects the variant keeps receiving; one that does is told, as a typed error, not a silent stop. + [Test] + public async Task AHopBearingSubscriptionReconcilesPastAVariantItDoesNotSelectAndIsToldWhenItDoes() + { + var registry = CultDocumentRegistry.Shared; + var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry)); + var documents = new CultNetDocumentRegistry(registry) + .Register(CultNetDocumentBinding.ForDocument(registry)) + .Register(CultNetDocumentBinding.ForDocument(registry)); + var wireSchemaId = registry.GetRequired().SchemaId; + cache.Commit(batch => + { + batch.Upsert(typeof(VariantWireFixture), new VariantWireFixture { Name = "base", Power = 1 }, BaseKey); + batch.Upsert(typeof(VariantCiterFixture), Citer("citer-one", BaseKey), new CultRecordKey("citer-one")); + }); + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents }); + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + socket.ReceiveTimeout = 20; + using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions { RuntimeId = "variant-hop-server", Socket = socket }); + using var subscriptions = new CultNetDatabaseSubscriptionServer(server, database); + using var cancellation = new CancellationTokenSource(); + var serverThread = new Thread(() => + { + while (!cancellation.IsCancellationRequested) + { + _ = server.PollOnceAsync().GetAwaiter().GetResult(); + Thread.Sleep(1); + } + }) { IsBackground = true }; + serverThread.Start(); + try + { + using var client = CultNetSchemaClients.CreateRudp("variant-hop-client"); + var snapshots = new ConcurrentQueue(); + var changes = new ConcurrentQueue(); + var errors = new ConcurrentQueue(); + client.OnCultNet(snapshots.Enqueue); + client.OnCultNet(changes.Enqueue); + client.OnCultNet(errors.Enqueue); + client.Connect("127.0.0.1", server.LocalEndPoint.Port); + await WaitUntilAsync(() => client.Connected); + string Diagnostic() => + $"changes={string.Join(",", changes.Select(c => c.SubscriptionId + ":" + c.ChangeKind + ":" + (c.Document?.RecordKey ?? c.RecordKey)))} " + + $"errors={string.Join(",", errors.Select(e => e.Error))}"; + + // "citers": rows citing the base. It never selects the variant. + client.SendCultNet(new CultNetDatabaseSubscribeV1Message + { + MessageId = "citers", + SubscriptionId = "citers", + IncludeSnapshot = true, + Selection = new CultNetSelection + { + Cites = new CultNetCitation { Target = new CultNetRecordRef { SchemaId = wireSchemaId, RecordKey = BaseKey.Value }, Role = "Ref" } + } + }); + await WaitUntilAsync(() => snapshots.Count == 1, Diagnostic); + + cache.Commit(batch => batch.UpsertVariant(VariantKey, BaseKey, new[] + { + cache.Override(nameof(VariantWireFixture.Name), "big") + })); + cache.Commit(batch => batch.Upsert(typeof(VariantCiterFixture), Citer("citer-two", BaseKey), new CultRecordKey("citer-two"))); + + await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-two"), Diagnostic); + Assert.That(errors, Is.Empty, "a subscriber that never selects the variant is never told about it"); + + // "cited": wire rows some citer cites. Once a citer cites the variant, it selects it. + client.SendCultNet(new CultNetDatabaseSubscribeV1Message + { + MessageId = "cited", + SubscriptionId = "cited", + IncludeSnapshot = true, + Selection = new CultNetSelection + { + Schemas = new[] { wireSchemaId }, + Cited = new CultNetIncoming { Role = "Ref", Exists = true } + } + }); + await WaitUntilAsync(() => snapshots.Count == 2, Diagnostic); + Assert.That(errors, Is.Empty, "only the base is cited yet"); + cache.Commit(batch => batch.Upsert(typeof(VariantCiterFixture), Citer("citer-three", VariantKey), new CultRecordKey("citer-three"))); + + await WaitUntilAsync(() => errors.Any(error => error.Error.Contains(VariantKey.Value)), Diagnostic); + Assert.That(changes.Where(change => change.SubscriptionId == "cited").Select(change => change.Document?.RecordKey), + Does.Not.Contain(VariantKey.Value), "a variant never reaches a subscriber as a record"); + + // The first subscriber is still alive after the refusal. + cache.Commit(batch => batch.Upsert(typeof(VariantCiterFixture), Citer("citer-four", BaseKey), new CultRecordKey("citer-four"))); + await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-four"), Diagnostic); + } + finally + { + cancellation.Cancel(); + serverThread.Join(); + } + } + + private static CultNetDatabaseChangeRawMessage? Deliver( + CultNetDatabaseServer server, + object change, + CultNetSelection selection, + System.Collections.Generic.HashSet refused, + System.Collections.Generic.List errors) + { + var method = typeof(CultNetDatabaseServer).GetMethod("DeliverChange", BindingFlags.Instance | BindingFlags.NonPublic)!; + return (CultNetDatabaseChangeRawMessage?)method.Invoke(server, new object[] + { + change, "sub", selection, refused, (Action)errors.Add + }); + } + + private static VariantCiterFixture Citer(string name, CultRecordKey target) => + new() { Name = name, Ref = new CultRecordRef(target) }; + + // A subscriber told a variant only as an error is not later told it was removed: it never held it. + [Test] + public async Task RemovingAVariantTheSubscriberWasOnlyToldAboutAsAnErrorSendsNoRemoval() + { + var (cache, documents) = await BuildFixtureAsync(withVariant: true); + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents }); + using var server = new Server(cache, ServerSecurityOptions.Development()); + using var databaseServer = new CultNetDatabaseServer(server, database); + var schemaId = cache.Registry.GetRequired().SchemaId; + var selection = new CultNetSelection { Projection = CultNetSelectionProjections.Document }; + var refused = new System.Collections.Generic.HashSet(); + var errors = new System.Collections.Generic.List(); + + var added = new CultNetDatabaseChange( + CultNetDatabaseChangeKind.Added, VariantKey, schemaId, database.Shards[0], cache.Get(VariantKey)!, previousDocument: null); + Assert.That(Deliver(databaseServer, added, selection, refused, errors), Is.Null); + Assert.That(errors, Has.Count.EqualTo(1)); + + var removed = new CultNetDatabaseChange( + CultNetDatabaseChangeKind.Removed, VariantKey, schemaId, database.Shards[0], document: null, previousDocument: cache.Get(VariantKey)!); + Assert.That(Deliver(databaseServer, removed, selection, refused, errors), Is.Null, + "no removal for a key the subscriber never held as a record"); + + // A record it did hold is still told about. + var baseRemoved = new CultNetDatabaseChange( + CultNetDatabaseChangeKind.Removed, BaseKey, schemaId, database.Shards[0], document: null, previousDocument: cache.Get(BaseKey)!); + Assert.That(Deliver(databaseServer, baseRemoved, selection, refused, errors)?.ChangeKind, Is.EqualTo("removed")); + } + private static async Task WaitUntilAsync(Func condition, Func? diagnostic = null) { var deadline = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(5); @@ -205,5 +352,18 @@ namespace GameCult.Networking.Tests [Key(1)] public int Power; } + + [CultDocument("variants.wire-citer-fixture", "variants.wire-citer-fixture.v1")] + [MessagePackObject(AllowPrivate = true)] + public sealed class VariantCiterFixture + { + [Key(0)] + [CultName] + public string Name = string.Empty; + + [Key(1)] + [CultReference(typeof(VariantWireFixture))] + public CultRecordRef Ref; + } } } From 4f632fbf4616b6018af88cd15f02090a4b93df55 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 08:42:32 +0200 Subject: [PATCH 60/64] Drive the hop-subscription test through the database write path Batch commits on the cache do not reach the database's change stream, so the subscriber's citers were written with database.PutAsync; the variant goes in through UpsertVariantAsync. On the previous source the second subscriber stops receiving after the variant exists (red); it now keeps receiving. Co-Authored-By: Claude Sonnet 5 --- .../CultNetDocumentRegistryVariantTests.cs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs index 2ae6dfab..7aeadc15 100644 --- a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs @@ -243,13 +243,16 @@ namespace GameCult.Networking.Tests }); await WaitUntilAsync(() => snapshots.Count == 1, Diagnostic); - cache.Commit(batch => batch.UpsertVariant(VariantKey, BaseKey, new[] + await database.PutAsync(new CultRecordKey("citer-two"), Citer("citer-two", BaseKey)); + await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-two"), Diagnostic); + + // With a variant in the store, the same subscriber keeps receiving. + await cache.UpsertVariantAsync(VariantKey, BaseKey, new[] { cache.Override(nameof(VariantWireFixture.Name), "big") - })); - cache.Commit(batch => batch.Upsert(typeof(VariantCiterFixture), Citer("citer-two", BaseKey), new CultRecordKey("citer-two"))); - - await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-two"), Diagnostic); + }); + await database.PutAsync(new CultRecordKey("citer-three"), Citer("citer-three", BaseKey)); + await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-three"), Diagnostic); Assert.That(errors, Is.Empty, "a subscriber that never selects the variant is never told about it"); // "cited": wire rows some citer cites. Once a citer cites the variant, it selects it. @@ -266,15 +269,15 @@ namespace GameCult.Networking.Tests }); await WaitUntilAsync(() => snapshots.Count == 2, Diagnostic); Assert.That(errors, Is.Empty, "only the base is cited yet"); - cache.Commit(batch => batch.Upsert(typeof(VariantCiterFixture), Citer("citer-three", VariantKey), new CultRecordKey("citer-three"))); + await database.PutAsync(new CultRecordKey("citer-four"), Citer("citer-four", VariantKey)); await WaitUntilAsync(() => errors.Any(error => error.Error.Contains(VariantKey.Value)), Diagnostic); Assert.That(changes.Where(change => change.SubscriptionId == "cited").Select(change => change.Document?.RecordKey), Does.Not.Contain(VariantKey.Value), "a variant never reaches a subscriber as a record"); // The first subscriber is still alive after the refusal. - cache.Commit(batch => batch.Upsert(typeof(VariantCiterFixture), Citer("citer-four", BaseKey), new CultRecordKey("citer-four"))); - await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-four"), Diagnostic); + await database.PutAsync(new CultRecordKey("citer-five"), Citer("citer-five", BaseKey)); + await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-five"), Diagnostic); } finally { From 282e337c2cf1f3ad0c5ef115df1c73009a5e5843 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 09:20:47 +0200 Subject: [PATCH 61/64] Variants C1: the held index tells the truth; a merge is judged on what the file will hold The held index kept one key per value, last writer winning, and RemoveKey dropped a value outright. Two consequences: removing or changing one of two plain holders left the other unfindable, and the variant index rule judged a variant against that lossy view, so a variant could land on a value a plain record still held and the store then refused to reopen. - _indexes maps a value to the keys holding it, oldest first. Index, Unindex and the removal maintain the set. GetByIndex finds the most recently indexed holder of a value, so removing the winner finds the other (behaviour change for plain duplicates: it used to find nothing). - One rule, RefuseVariantIndexSharing, serves both write orders. It reads the truthful index minus what the commit replaces or removes, plus what it lands. ResolveOne no longer judges indexes; ClaimIncomingIndexValues, HeldByVariants and RefusePlainSharingWithVariant are gone. - A conditional commit merged onto the file is judged by the cache's own resolution (CacheBackingStore.Judging) on the merged set: records other writers added, records they removed, and the batch. Another writer's variant sharing a value with the batch, or a base removal that strands another writer's variant, is refused with the named refusal instead of writing an unopenable store. - Shedding is one decision at load. ToStoredDocument resolves the schema once and returns the report with it; a variant's override of a slot the type lacks is dropped from the delta there, so flush needs no predicate and every store reports through the same surface (ReportVariantSheds and OverridesTheTypeHas are gone). The directory store refuses variants and loads through the same call. Co-Authored-By: Claude Sonnet 5 --- .../DirectoryMessagePackBackingStore.cs | 4 +- src/GameCult.Caching/CultCache.cs | 272 +++++++++--------- tests/GameCult.Caching.Tests/VariantTests.cs | 197 +++++++++++++ 3 files changed, 329 insertions(+), 144 deletions(-) diff --git a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs index 3ef36be2..8244d76a 100644 --- a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs +++ b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs @@ -339,11 +339,11 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore var started = tracePages ? Stopwatch.GetTimestamp() : 0L; var metadata = records[index]; var record = ReadPersistedRecordPage(metadata, out var pagePayload); - recordReports[index] = Registry.ResolvePersistedSchemaReport(record.SchemaId, catalogEntries); storedRecords[index] = ToStoredDocument( record, catalogEntries, - (type, payload) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, Registry)); + (type, payload) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, Registry), + out recordReports[index]); if (tracePages) { pageBytes[index] = pagePayload.LongLength; diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 2d4e7137..65c75b93 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -1799,7 +1799,8 @@ namespace GameCult.Caching private readonly List<(CacheBackingStore Store, Type[] Homes)> _stores = new(); private readonly Dictionary _entries = new(StringComparer.Ordinal); private readonly Dictionary> _names = new(); - private readonly Dictionary<(Type Type, string Alias), Dictionary> _indexes = new(); + // Every key holding a value, oldest first: the index is truthful about duplicates, so removing one holder never hides another. + private readonly Dictionary<(Type Type, string Alias), Dictionary>> _indexes = new(); private readonly Dictionary _globals = new(); private readonly CultCodec? _codec; // Keys holding a variant: derived from the entries by Apply, never decided anywhere else. @@ -1934,6 +1935,7 @@ namespace GameCult.Caching store.AttachRegistry(_registry); store.Cache = this; store.Loaded = (loaded, dropped) => Admit(loaded, dropped, store, (_, _) => CultCommitOutcome.Committed); + store.Judging = (arriving, departing) => { Resolve(arriving, departing, store); }; _stores.Add(candidate); try { @@ -1943,6 +1945,7 @@ namespace GameCult.Caching { _stores.Remove(candidate); store.Loaded = null; + store.Judging = null; store.Cache = null; throw; } @@ -2121,11 +2124,13 @@ namespace GameCult.Caching .SelectMany(pair => pair.Value.TryGetValue(name, out var key) ? new[] { key } : Array.Empty())); } + // A value held by one record finds it. Records of one type sharing a value (plain duplicates) find the most recently + // indexed holder, and removing that holder finds the one before it: a held value never finds nothing. public T? GetByIndex(string alias, string value) where T : class { return Single($"index {alias}='{value}'", () => _indexes .Where(pair => pair.Key.Alias == alias && typeof(T).IsAssignableFrom(pair.Key.Type)) - .SelectMany(pair => pair.Value.TryGetValue(value, out var key) ? new[] { key } : Array.Empty())); + .SelectMany(pair => pair.Value.TryGetValue(value, out var keys) ? new[] { keys[keys.Count - 1] } : Array.Empty())); } public void Dispose() @@ -2522,21 +2527,20 @@ namespace GameCult.Caching if (toResolve.Count == 0) { var unchanged = new VariantPlan(admitted); - RefusePlainSharingWithVariant(unchanged, incoming, gone); + RefuseVariantIndexSharing(unchanged, incoming, gone); return unchanged; } var pending = new HashSet(toResolve, StringComparer.Ordinal); var done = new Dictionary(StringComparer.Ordinal); var stack = new List(); - Dictionary<(Type Type, string Alias), Dictionary>? claimed = null; foreach (var key in toResolve) ResolveOne(key); var plan = new VariantPlan(admitted.Select(stored => done.TryGetValue(stored.Key.Value, out var resolved) ? resolved : stored).ToList()); foreach (var key in toResolve.Where(key => !incoming.ContainsKey(key))) plan.Dependents.Add(done[key]); - RefusePlainSharingWithVariant(plan, incoming, gone); + RefuseVariantIndexSharing(plan, incoming, gone); return plan; CultStoredDocument ResolveOne(string key) @@ -2567,9 +2571,6 @@ namespace GameCult.Caching var type = descriptor.DocumentType; var kept = new List>(); var seen = new HashSet(); - // Bad writes are refused; drift is for type changes after the fact. A load, a re-resolution and a flatten - // carry what was already stored, so they follow the plain-record outcome instead. - var writing = source == null && isVariant && incoming.ContainsKey(key); foreach (var entry in delta.Overrides) { if (entry.Op != CultOverrideOp.Set || entry.Path.Count != 1 || entry.Path[0].ElementId.Length != 0 || entry.Id.Length != 0) @@ -2579,14 +2580,10 @@ namespace GameCult.Caching if (!seen.Add(slot)) throw new InvalidOperationException($"Variant {key} overrides slot {slot} more than once; a variant has one override per slot."); var member = descriptor.RichMembers.FirstOrDefault(candidate => candidate.Slot == slot); + // Drift is the load's business (ToStoredDocument sheds an override of a slot the type lacks), so a delta + // reaching here names only slots the type has, unless someone is writing one it never had. if (member == null) - { - if (writing) - throw new InvalidOperationException($"Variant {key} overrides slot {slot}, which {type.Name} does not have."); - // A slot the type dropped soft-drifts exactly as the same member does on a plain record: ignored, - // reported by the store's schema resolution (LastSchemaMigrationReports), the variant inherits the base. - continue; - } + throw new InvalidOperationException($"Variant {key} overrides slot {slot}, which {type.Name} does not have."); try { @@ -2620,37 +2617,6 @@ namespace GameCult.Caching $"Variant {key} and its base {ancestor.Key.Value} are both named '{variantName}'; a variant must override its name."); } } - - // The same rule for an indexed value: a unique index maps one value to one key, so a variant that - // inherited its base's value (or any other record's) would be found in place of it or lose it. - foreach (var pair in descriptor.IndexAccessors) - { - var value = pair.Value(document); - if (string.IsNullOrWhiteSpace(value)) - continue; - claimed ??= ClaimIncomingIndexValues(); - var claim = (type, pair.Key); - string? other = null; - if (claimed.TryGetValue(claim, out var claims) && claims.TryGetValue(value, out var claimant) && claimant != key) - other = claimant; - else if (_indexes.TryGetValue(claim, out var held) && held.TryGetValue(value, out var holder) && holder != key && - !incoming.ContainsKey(holder) && !gone.Contains(holder) && !pending.Contains(holder)) - other = holder; - if (other != null) - throw new InvalidOperationException( - $"Variant {key} and {other} both hold index {pair.Key} '{value}'; a variant must override its indexed member."); - } - } - - if (descriptor.IndexAccessors.Count > 0) - { - claimed ??= ClaimIncomingIndexValues(); - foreach (var pair in descriptor.IndexAccessors) - { - var value = pair.Value(document); - if (!string.IsNullOrWhiteSpace(value)) - MapOf(claimed, (type, pair.Key))[value] = key; - } } stack.RemoveAt(stack.Count - 1); @@ -2658,80 +2624,56 @@ namespace GameCult.Caching ? variant.Resolved(document) : new CultStoredDocument(variant.Key, variant.StoredAt, variant.Descriptor, document) { Flattens = true }; } - - // The indexed values the plain records of this admission will hold, by (type, index) then value. - Dictionary<(Type Type, string Alias), Dictionary> ClaimIncomingIndexValues() - { - var claims = new Dictionary<(Type Type, string Alias), Dictionary>(); - foreach (var stored in incoming.Values.Where(stored => stored.Variant == null && !stored.Flattens)) - { - foreach (var pair in stored.Descriptor.IndexAccessors) - { - var value = pair.Value(stored.Document); - if (!string.IsNullOrWhiteSpace(value)) - MapOf(claims, (stored.Descriptor.DocumentType, pair.Key))[value] = stored.Key.Value; - } - } - - return claims; - } } - // The index rule is about the commit's result, so it holds for every commit that changes an indexed value, in either - // order: a variant resolving onto another record's value is refused in ResolveOne; a plain record landing on a - // variant's value is refused here, against the variants of the post-commit set (never the held index, which the plain - // write would already have overwritten). Plain-vs-plain sharing is not this rule's business. - private void RefusePlainSharingWithVariant( + // The one index rule, judged on the commit's result whatever the write order: a variant may not share an indexed + // value with another record. It reads the truthful held index (every holder of a value), minus the records this + // commit replaces or removes, plus the records it lands. Plain-vs-plain sharing is not this rule's business. + // A unique index maps a value to one key at lookup; a variant sharing it would be found in place of its + // holder or lose the value, and the store would refuse to reopen. + private void RefuseVariantIndexSharing( VariantPlan plan, IReadOnlyDictionary incoming, HashSet gone) { - Dictionary<(Type Type, string Alias), Dictionary>? variantValues = null; - foreach (var stored in plan.Admitted) + var landing = plan.Admitted.Concat(plan.Dependents).ToList(); + if (landing.All(stored => stored.Descriptor.IndexAccessors.Count == 0)) + return; + var replaced = new HashSet(incoming.Keys.Concat(gone).Concat(plan.Dependents.Select(stored => stored.Key.Value)), StringComparer.Ordinal); + var landingByKey = landing.ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal); + + bool IsVariant(string key) => + landingByKey.TryGetValue(key, out var landed) ? landed.Variant != null : _variantKeys.Contains(key); + + foreach (var stored in landing) { - if (stored.Variant != null || stored.Descriptor.IndexAccessors.Count == 0) - continue; foreach (var pair in stored.Descriptor.IndexAccessors) { var value = pair.Value(stored.Document); if (string.IsNullOrWhiteSpace(value)) continue; - variantValues ??= HeldByVariants(plan, incoming, gone); - if (variantValues.TryGetValue((stored.Descriptor.DocumentType, pair.Key), out var values) && - values.TryGetValue(value, out var variantKey) && variantKey != stored.Key.Value) + var type = stored.Descriptor.DocumentType; + var holders = (_indexes.TryGetValue((type, pair.Key), out var held) && held.TryGetValue(value, out var heldKeys) + ? heldKeys.Where(heldKey => !replaced.Contains(heldKey)) + : Enumerable.Empty()) + .Concat(landing + .Where(other => other.Descriptor.DocumentType == type && pair.Value(other.Document) == value) + .Select(other => other.Key.Value)) + .Where(holder => holder != stored.Key.Value) + .Distinct(StringComparer.Ordinal) + .ToArray(); + if (stored.Variant != null && holders.Length > 0) throw new InvalidOperationException( - $"Record {stored.Key.Value} and variant {variantKey} both hold index {pair.Key} '{value}'; " + + $"Variant {stored.Key.Value} and {holders[0]} both hold index {pair.Key} '{value}'; a variant must override its indexed member."); + var variantHolder = holders.FirstOrDefault(IsVariant); + if (stored.Variant == null && variantHolder != null) + throw new InvalidOperationException( + $"Record {stored.Key.Value} and variant {variantHolder} both hold index {pair.Key} '{value}'; " + "a variant may not share an indexed value with another record."); } } } - // The indexed values the variants of the post-commit set hold: those this commit resolved, and those it left alone. - private Dictionary<(Type Type, string Alias), Dictionary> HeldByVariants( - VariantPlan plan, - IReadOnlyDictionary incoming, - HashSet gone) - { - var variants = new Dictionary(StringComparer.Ordinal); - foreach (var variantKey in _variantKeys.Where(variantKey => !incoming.ContainsKey(variantKey) && !gone.Contains(variantKey))) - variants[variantKey] = _entries[variantKey]; - foreach (var stored in plan.Admitted.Concat(plan.Dependents).Where(stored => stored.Variant != null)) - variants[stored.Key.Value] = stored; - - var held = new Dictionary<(Type Type, string Alias), Dictionary>(); - foreach (var stored in variants.Values) - { - foreach (var pair in stored.Descriptor.IndexAccessors) - { - var value = pair.Value(stored.Document); - if (!string.IsNullOrWhiteSpace(value)) - MapOf(held, (stored.Descriptor.DocumentType, pair.Key))[value] = stored.Key.Value; - } - } - - return held; - } - private static InvalidOperationException CycleRefusal(IEnumerable keys) => new($"Variant bases form a cycle: {string.Join(" -> ", keys)}."); @@ -2837,7 +2779,7 @@ namespace GameCult.Caching { var value = pair.Value(stored.Document); if (!string.IsNullOrWhiteSpace(value)) - MapOf(_indexes, (type, pair.Key))[value] = stored.Key.Value; + AddHolder(_indexes, (type, pair.Key), value, stored.Key.Value); } } @@ -2850,7 +2792,27 @@ namespace GameCult.Caching if (_names.TryGetValue(type, out var names)) RemoveKey(names, stored.Key.Value); foreach (var pair in _indexes.Where(pair => pair.Key.Type == type)) - RemoveKey(pair.Value, stored.Key.Value); + RemoveHolder(pair.Value, stored.Key.Value); + } + + // Re-indexing a key makes it the most recent holder of its value. + private static void AddHolder(Dictionary<(Type Type, string Alias), Dictionary>> indexes, (Type, string) index, string value, string key) + { + if (!indexes.TryGetValue(index, out var map)) + indexes[index] = map = new Dictionary>(StringComparer.Ordinal); + if (!map.TryGetValue(value, out var keys)) + map[value] = keys = new List(); + keys.Remove(key); + keys.Add(key); + } + + private static void RemoveHolder(Dictionary> map, string key) + { + foreach (var pair in map.ToArray()) + { + if (pair.Value.Remove(key) && pair.Value.Count == 0) + map.Remove(pair.Key); + } } private static Dictionary MapOf(Dictionary> maps, TKey key) @@ -2924,6 +2886,11 @@ namespace GameCult.Caching // any of it; if the cache refuses a record the call throws and the store keeps its previous view. protected internal Action, IReadOnlyList>? Loaded; + // Set by the cache at attach: the cache's own resolution (variants, their indexed values, their bases) run over a + // set of records a store is about to hold, mutating nothing. It throws the refusal the cache would give the same + // set arriving as a load. + protected internal Action, IReadOnlyList>? Judging; + private readonly object _detachedGate = new(); internal CultCache? Cache; @@ -2977,55 +2944,51 @@ namespace GameCult.Caching SchemaId = entry.Descriptor.SchemaId, StoredAt = entry.StoredAt, Payload = entry.Variant != null ? Array.Empty() : serializePayload(entry.Document), - Variant = entry.Variant == null ? null : new CultVariantDelta(entry.Variant.BaseKey, OverridesTheTypeHas(entry).ToArray()) + Variant = entry.Variant }; } - // A plain record sheds a member its type dropped when it is flushed; a variant sheds the override of that slot, so - // a later type reusing the slot number cannot resurrect it. The load's report names the shed slots. - private static IEnumerable OverridesTheTypeHas(CultStoredDocument entry) => - entry.Variant!.Overrides.Where(entryOverride => - entryOverride.Path.Count != 1 || entry.Descriptor.RichMembers.Any(member => member.Slot == entryOverride.Path[0].Slot)); - - // A variant's override of a slot its type lacks is ignored like an extra slot on a plain record. Schema resolution - // reports slots the persisted schema had and the type dropped; an override the schema never had is added here. - protected static CultSchemaMigrationReport ReportVariantSheds(CultSchemaMigrationReport report, CultStoredDocument stored) - { - if (stored.Variant == null) - return report; - var shed = stored.Variant.Overrides - .Where(entryOverride => entryOverride.Path.Count == 1 && - stored.Descriptor.RichMembers.All(member => member.Slot != entryOverride.Path[0].Slot)) - .Select(entryOverride => entryOverride.Path[0].Slot) - .Except(report.IgnoredExtraSlots) - .Distinct() - .OrderBy(slot => slot) - .ToArray(); - if (shed.Length == 0) - return report; - report.IgnoredExtraSlots = report.IgnoredExtraSlots.Concat(shed).OrderBy(slot => slot).ToArray(); - report.Warnings = report.Warnings.Concat(shed.Select(slot => new CultSchemaMigrationWarning - { - Code = "ignored_extra_slot", - Message = $"Variant {stored.Key.Value} overrides slot {slot}, which {stored.Descriptor.DocumentType.Name} does not have; the override is ignored and shed on flush." - })).ToArray(); - return report; - } - + // The one load surface: a persisted record resolved against the current type, with the report of what that + // resolution shed. A plain record sheds a member its type dropped by never carrying it into the document; a variant + // sheds the override of such a slot by never carrying it into the delta, so a later type reusing the slot number + // cannot resurrect it and a flush needs no rule of its own. The report is the schema diff's ignored slots plus the + // overrides whose slot the type does not have, including one the persisted schema never listed. protected CultStoredDocument ToStoredDocument( CultPersistedRecord record, IReadOnlyCollection catalog, - Func deserializePayload) + Func deserializePayload, + out CultSchemaMigrationReport report) { var resolution = Registry.ResolvePersistedSchemaDetailed(record.SchemaId, catalog); + report = resolution.Report; if (record.Variant != null) { + var descriptor = resolution.Descriptor; + bool Has(CultVariantOverride entryOverride) => + entryOverride.Path.Count != 1 || descriptor.RichMembers.Any(member => member.Slot == entryOverride.Path[0].Slot); + var shed = record.Variant.Overrides + .Where(entryOverride => !Has(entryOverride)) + .Select(entryOverride => entryOverride.Path[0].Slot) + .Distinct() + .OrderBy(slot => slot) + .ToArray(); + if (shed.Length > 0) + { + var alreadyReported = report.IgnoredExtraSlots; + report.IgnoredExtraSlots = alreadyReported.Concat(shed.Except(alreadyReported)).OrderBy(slot => slot).ToArray(); + report.Warnings = report.Warnings.Concat(shed.Select(slot => new CultSchemaMigrationWarning + { + Code = "ignored_extra_slot", + Message = $"Variant {record.Key} overrides slot {slot}, which {descriptor.DocumentType.Name} does not have; the override is ignored and shed on flush." + })).ToArray(); + } + // The cache resolves it against its base when it admits the load. return new CultStoredDocument( new CultRecordKey(record.Key), record.StoredAt, - resolution.Descriptor, - new CultVariantDelta(record.Variant.BaseKey, record.Variant.Overrides), + descriptor, + new CultVariantDelta(record.Variant.BaseKey, record.Variant.Overrides.Where(Has).ToArray()), null); } @@ -3084,9 +3047,8 @@ namespace GameCult.Caching var persisted = new Dictionary(StringComparer.Ordinal); foreach (var record in snapshot.Records) { - var report = Registry.ResolvePersistedSchemaReport(record.SchemaId, snapshot.SchemaCatalog); - var stored = ToStoredDocument(record, snapshot.SchemaCatalog, DeserializePayload); - reports.Add(ReportVariantSheds(report, stored)); + var stored = ToStoredDocument(record, snapshot.SchemaCatalog, DeserializePayload, out var report); + reports.Add(report); persisted[stored.Key.Value] = stored; } @@ -3169,6 +3131,11 @@ namespace GameCult.Caching var catalog = ontoDisk ? disk.SchemaCatalog : Entries.Values.Select(entry => entry.Descriptor.ToCatalogEntry()); + // The committer judged the batch against its own view; the file may have moved since. A merge is judged on the + // set the file will hold, exactly as that set would be judged loading: what other processes wrote (arriving), + // what they removed (departing), and this batch. + if (ontoDisk && Judging != null) + JudgeMerge(request, disk); foreach (var entry in request.Deletes) records.Remove(entry.Key.Value); foreach (var entry in request.Upserts) @@ -3183,6 +3150,27 @@ namespace GameCult.Caching return CultCommitOutcome.Committed; } + private void JudgeMerge(CultCommitRequest request, CultPersistedStoreSnapshot disk) + { + var landing = request.Upserts.Select(entry => entry.Key.Value).ToHashSet(StringComparer.Ordinal); + var removing = request.Deletes.Select(entry => entry.Key.Value).ToHashSet(StringComparer.Ordinal); + var onDisk = disk.Records.Select(record => record.Key).ToHashSet(StringComparer.Ordinal); + var arriving = new List(request.Upserts); + foreach (var record in disk.Records) + { + if (landing.Contains(record.Key) || removing.Contains(record.Key)) + continue; + if (Entries.TryGetValue(record.Key, out var known) && known.StoredAt == record.StoredAt && known.Descriptor.SchemaId == record.SchemaId) + continue; + arriving.Add(ToStoredDocument(record, disk.SchemaCatalog, DeserializePayload, out _)); + } + + var departing = new List(request.Deletes); + departing.AddRange(Entries.Values.Where(known => + !onDisk.Contains(known.Key.Value) && !landing.Contains(known.Key.Value) && !removing.Contains(known.Key.Value))); + Judging!(arriving, departing); + } + private CultPersistedStoreSnapshot? ReadSnapshot() { FileInfo.Refresh(); diff --git a/tests/GameCult.Caching.Tests/VariantTests.cs b/tests/GameCult.Caching.Tests/VariantTests.cs index c81e892b..6f6654e2 100644 --- a/tests/GameCult.Caching.Tests/VariantTests.cs +++ b/tests/GameCult.Caching.Tests/VariantTests.cs @@ -749,6 +749,203 @@ namespace GameCult.Caching.Tests Assert.That(reloaded.Get(BigKey)!.Tags, Is.EqualTo(new[] { "beam", "pierce" })); } + // ---- the held index is truthful: every holder of a value, so no rule judges a variant against a lossy view ---- + + private static VariantGear Named(string name, string code) => new() { Name = name, Power = 1, Code = code }; + + private static CultRecordKey[] SharedCodePair(CultCache cache) + { + var p1 = new CultRecordKey("p1"); + var p2 = new CultRecordKey("p2"); + cache.Commit(batch => + { + batch.Upsert(typeof(VariantGear), Named("p1", "x"), p1); + batch.Upsert(typeof(VariantGear), Named("p2", "x"), p2); + }); + return new[] { p1, p2 }; + } + + private static void VariantOnCode(CultCache cache, string code) => + cache.Commit(batch => batch.UpsertVariant(BigKey, BaseKey, new[] + { + cache.Override(nameof(VariantGear.Name), "laser big"), + cache.Override(nameof(VariantGear.Code), code) + })); + + [Test] + public void PlainDuplicatesFindTheMostRecentHolderAndRemovingEitherLeavesTheOtherFindable() + { + var path = PathOf("gear.cc"); + using (var cache = Open(path)) + { + var pair = SharedCodePair(cache); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p2"), "the last writer"); + + cache.Remove(pair[1]); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p1"), "removing the winner finds the other holder"); + + cache.Commit(batch => batch.Upsert(typeof(VariantGear), Named("p2", "x"), pair[1])); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p2")); + cache.Remove(pair[0]); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p2"), "removing the loser changes nothing"); + cache.Remove(pair[1]); + Assert.That(cache.GetByIndex("code", "x"), Is.Null); + cache.BackingStores[0].PushAll(); + } + + using var reopened = Open(path); + Assert.That(reopened.GetByIndex("code", "x"), Is.Null); + } + + [Test] + public void AVariantOnAValueAPlainRecordStillHoldsAfterItsTwinWasRemovedIsRefusedAndTheStoreReopens() + { + var path = PathOf("gear.cc"); + using (var cache = Open(path)) + { + SeedBase(cache); + var pair = SharedCodePair(cache); + cache.Remove(pair[1]); + + var refused = Refused(() => VariantOnCode(cache, "x")); + Assert.That(refused.Message, Does.Contain(BigKey.Value).And.Contain("p1").And.Contain("code").And.Contain("'x'")); + Assert.That(cache.Get(BigKey), Is.Null, "nothing landed"); + cache.BackingStores[0].PushAll(); + } + + using var reopened = Open(path); + Assert.That(reopened.Get(BigKey), Is.Null); + Assert.That(reopened.GetByIndex("code", "x")!.Name, Is.EqualTo("p1")); + } + + [Test] + public void AVariantOnAValueAPlainRecordStillHoldsAfterItsTwinChangedItsValueIsRefusedAndTheStoreReopens() + { + var path = PathOf("gear.cc"); + using (var cache = Open(path)) + { + SeedBase(cache); + var pair = SharedCodePair(cache); + cache.Commit(batch => batch.Upsert(typeof(VariantGear), Named("p2", "y"), pair[1])); + + var refused = Refused(() => VariantOnCode(cache, "x")); + Assert.That(refused.Message, Does.Contain(BigKey.Value).And.Contain("p1").And.Contain("'x'")); + Assert.DoesNotThrow(() => VariantOnCode(cache, "z"), "an unshared value is fine"); + cache.BackingStores[0].PushAll(); + } + + using var reopened = Open(path); + Assert.That(reopened.GetByIndex("code", "z")!.Name, Is.EqualTo("laser big")); + Assert.That(reopened.GetByIndex("code", "x")!.Name, Is.EqualTo("p1")); + } + + // ---- a merge onto the file is judged on the set the file will hold ---- + + [Test] + public void AConditionalCommitThatWouldShareAnIndexedValueWithAnotherWritersVariantIsRefusedAndTheStoreReopens() + { + var path = PathOf("gear.cc"); + var other = new CultRecordKey("other"); + using (var seed = Open(path)) + SeedBase(seed); + + using (var a = Open(path)) + using (var b = Open(path)) + { + a.Commit(batch => batch.UpsertVariant(BigKey, BaseKey, new[] + { + a.Override(nameof(VariantGear.Name), "laser big"), + a.Override(nameof(VariantGear.Code), "shared") + })); + + var refused = Refused(() => b.Commit(batch => + { + batch.Expect(other, null); + batch.Upsert(typeof(VariantGear), Named("other", "shared"), other); + })); + Assert.That(refused.Message, Does.Contain(other.Value).And.Contain(BigKey.Value).And.Contain("code").And.Contain("shared")); + Assert.That(b.Get(other), Is.Null, "nothing landed in memory"); + } + + using var reopened = Open(path); + Assert.That(reopened.Get(other), Is.Null, "nothing landed on the file"); + Assert.That(reopened.GetByIndex("code", "shared")!.Name, Is.EqualTo("laser big")); + } + + [Test] + public void AConditionalCommitThatRemovesAnotherWritersVariantsBaseIsRefusedAndTheStoreReopens() + { + var path = PathOf("gear.cc"); + using (var seed = Open(path)) + SeedBase(seed); + + using (var a = Open(path)) + using (var b = Open(path)) + { + var seen = b.Get(BaseKey)!; + SeedBig(a); + + var refused = Refused(() => b.Commit(batch => + { + batch.Expect(BaseKey, seen); + batch.Remove(BaseKey); + })); + Assert.That(refused.Message, Does.Contain(BaseKey.Value).And.Contain(BigKey.Value)); + Assert.That(b.Get(BaseKey), Is.Not.Null, "nothing landed in memory"); + } + + using var reopened = Open(path); + Assert.That(reopened.Get(BaseKey), Is.Not.Null); + Assert.That(reopened.Get(BigKey)!.Name, Is.EqualTo("laser big")); + } + + [Test] + public void AConditionalCommitThatIsSoundOnTheMergedSetStillLands() + { + var path = PathOf("gear.cc"); + var other = new CultRecordKey("other"); + using (var seed = Open(path)) + SeedBase(seed); + + using (var a = Open(path)) + using (var b = Open(path)) + { + SeedBig(a); + Assert.That(b.Commit(batch => + { + batch.Expect(other, null); + batch.Upsert(typeof(VariantGear), Named("other", "fine"), other); + }), Is.True); + } + + using var reopened = Open(path); + Assert.That(reopened.Get(other), Is.Not.Null); + Assert.That(reopened.Get(BigKey), Is.Not.Null, "the other writer's variant survives the merge"); + } + + [Test] + public void AVariantLoadedUnderANarrowerTypeHoldsOnlyTheOverridesTheTypeHasAndReportsTheRest() + { + var path = PathOf("drift.cc"); + using (var writer = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftWide) }))) + { + writer.Commit(batch => + { + batch.Upsert(typeof(DriftWide), new DriftWide { Name = "drift", Power = 1, Wing = "base wing" }, new CultRecordKey("drift-base")); + batch.UpsertVariant(new CultRecordKey("drift-variant"), new CultRecordKey("drift-base"), new[] + { + writer.Override(nameof(DriftWide.Name), "drift variant"), + writer.Override(nameof(DriftWide.Wing), "stale wing") + }); + }); + } + + using var narrow = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftNarrow) })); + Assert.That(narrow.GetStored(new CultRecordKey("drift-variant"))!.Variant!.Overrides.Select(entry => entry.Path[0].Slot), Is.EqualTo(new[] { 0 }), + "the dropped slot's override is shed when the record is loaded, not decided again at flush"); + Assert.That(narrow.BackingStores[0].LastSchemaMigrationReports.SelectMany(report => report.IgnoredExtraSlots), Does.Contain(2)); + } + // ---- the directory store refuses a variant page on load as it does on write ---- [Test] From a0baa542d0009d17dcdb8bb9a8033cb5f406e43a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 09:20:48 +0200 Subject: [PATCH 62/64] CultNet: refuse hop edges whose citer is a variant; withdraw a refused hop subscription An edge carries the reference payload of its citer's resolved document, and the citer is never a selected row under `cited`, so a variant citer slipped past the selected-row refusal. Edges are now checked by the same rule (typed NotSupportedException naming the variant), on the paged and the whole-set paths. Reconcile refused a hop subscriber whose selection selected a variant without withdrawing it, so it was told again on every store change. It withdraws as the subscribe path does. Co-Authored-By: Claude Sonnet 5 --- .../CultNetDatabaseSubscriptionServer.cs | 6 +- .../CultNetDocumentRegistry.cs | 24 +++-- .../CultNetDocumentRegistryVariantTests.cs | 96 ++++++++++++++++++- 3 files changed, 113 insertions(+), 13 deletions(-) diff --git a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs index bb1f3900..60bb66a5 100644 --- a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs @@ -358,8 +358,10 @@ namespace GameCult.Networking } catch (NotSupportedException refusal) { - // Q6: the selection selects a variant, which CultNet cannot carry. This subscriber is told, by key, and keeps what - // it was delivered; a change never throws out of the change handler. + // Q6: the selection selects a variant, which CultNet cannot carry. Refused as the subscribe path refuses it: the + // subscription is withdrawn, so the peer is told once, not once per store change; a change never throws out of + // the change handler. + Withdraw(key, sendRemovals: false, forgetRequest: true); key.Peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); return; } diff --git a/src/GameCult.Networking/CultNetDocumentRegistry.cs b/src/GameCult.Networking/CultNetDocumentRegistry.cs index 5df34e98..eb23d503 100644 --- a/src/GameCult.Networking/CultNetDocumentRegistry.cs +++ b/src/GameCult.Networking/CultNetDocumentRegistry.cs @@ -397,7 +397,7 @@ namespace GameCult.Networking entry.Descriptor, entry.Key, entry.Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt)) .ToArray(); var full = CultNetSelectionEvaluator.EvaluateAll(_documents, rows, selection); - RefuseSelectedVariants(entries, full.Ordered); + RefuseVariants(entries, full.Ordered.Select(row => row.Key)); // R-Q: a page's asOf is exact only when every matched row is committed through one shard's // log - a caller that knows about shards (CultNetDatabaseServer) supplies shardIdOf; one // that does not (the raw v0/shard-scoped rowFilter paths, which are already bounded to a @@ -417,6 +417,7 @@ namespace GameCult.Networking } var evaluation = CultNetSelectionEvaluator.Page(full, selection, asOf, cursorKey); + RefuseVariants(entries, evaluation.Edges.Select(edge => edge.From.Key)); var records = evaluation.Rows.Select(row => ToRawRecord(row, options)).ToArray(); var wantDocument = selection.Projection == CultNetSelectionProjections.Document; @@ -494,12 +495,13 @@ namespace GameCult.Networking .ToArray(); var full = CultNetSelectionEvaluator.EvaluateAll(_documents, rows, selection); - RefuseSelectedVariants(entries, full.Ordered); + RefuseVariants(entries, full.Ordered.Select(row => row.Key)); var records = full.Ordered.Select(row => ToRawRecord(row, options)).ToArray(); var wantDocument = selection.Projection == CultNetSelectionProjections.Document; - var edges = selection.HasHop - ? CultNetSelectionEvaluator.EdgesFor(full.Ordered, full).Select(edge => ToEdge(edge, wantDocument)).ToArray() - : null; + var hopEdges = selection.HasHop ? CultNetSelectionEvaluator.EdgesFor(full.Ordered, full) : null; + if (hopEdges != null) + RefuseVariants(entries, hopEdges.Select(edge => edge.From.Key)); + var edges = hopEdges?.Select(edge => ToEdge(edge, wantDocument)).ToArray(); return new CultNetSelectionPage { @@ -554,15 +556,17 @@ namespace GameCult.Networking } // CultNet carries no variant deltas yet, and a resolved view sent as a plain record would be a lie about the store. - // The refusal follows the selection: a variant is refused only when the selection selects it, never for existing. - private static void RefuseSelectedVariants(IReadOnlyList entries, IReadOnlyList selected) + // The refusal follows the selection: a variant is refused only when the selection selects it, never for existing. An + // edge carries its citer's reference payload, read from the citer's resolved document, so a variant citing is selected + // by the selection's hop exactly as a variant row is. + private static void RefuseVariants(IReadOnlyList entries, IEnumerable selected) { - if (selected.Count == 0 || !entries.Any(entry => entry.Variant != null)) + if (!entries.Any(entry => entry.Variant != null)) return; var variants = entries.Where(entry => entry.Variant != null).ToDictionary(entry => entry.Key.Value, StringComparer.Ordinal); - foreach (var row in selected) + foreach (var key in selected) { - if (variants.TryGetValue(row.Key.Value, out var variant)) + if (variants.TryGetValue(key.Value, out var variant)) throw VariantRefusal(variant); } } diff --git a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs index 7aeadc15..a4658117 100644 --- a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs @@ -275,9 +275,103 @@ namespace GameCult.Networking.Tests Assert.That(changes.Where(change => change.SubscriptionId == "cited").Select(change => change.Document?.RecordKey), Does.Not.Contain(VariantKey.Value), "a variant never reaches a subscriber as a record"); - // The first subscriber is still alive after the refusal. + // The first subscriber is still alive after the refusal; the refused one is withdrawn, not told again per change. + var told = errors.Count; await database.PutAsync(new CultRecordKey("citer-five"), Citer("citer-five", BaseKey)); await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-five"), Diagnostic); + await Task.Delay(200); + Assert.That(errors.Count, Is.EqualTo(told), "a refused subscription is withdrawn: one error, not one per store change"); + } + finally + { + cancellation.Cancel(); + serverThread.Join(); + } + } + + // An edge carries its citer's reference payload, read from the citer's resolved document. A selection whose hop + // reaches a variant citer is refused as a selection of a variant row is, though only the cited row is selected. + private static async Task<(CultCache Cache, CultNetDocumentRegistry Documents, CultNetSelection Selection, CultRecordKey CiterVariant)> BuildCitedByVariantFixtureAsync() + { + var registry = CultDocumentRegistry.Shared; + var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry)); + var documents = new CultNetDocumentRegistry(registry) + .Register(CultNetDocumentBinding.ForDocument(registry)) + .Register(CultNetDocumentBinding.ForDocument(registry)); + cache.Commit(batch => + { + batch.Upsert(typeof(VariantWireFixture), new VariantWireFixture { Name = "base", Power = 1 }, BaseKey); + batch.Upsert(typeof(VariantCiterFixture), Citer("citer-one", BaseKey), new CultRecordKey("citer-one")); + }); + var citerVariant = new CultRecordKey("citer-variant"); + await cache.UpsertVariantAsync(citerVariant, new CultRecordKey("citer-one"), new[] + { + cache.Override(nameof(VariantCiterFixture.Name), "citer variant") + }); + var selection = new CultNetSelection + { + Schemas = new[] { cache.Registry.GetRequired().SchemaId }, + Cited = new CultNetIncoming { Role = "Ref", Exists = true }, + Projection = CultNetSelectionProjections.Document + }; + return (cache, documents, selection, citerVariant); + } + + [Test] + public async Task AHopEdgeWhoseCiterIsAVariantIsRefusedNamingItAndAStoreWithoutOneAnswers() + { + var (cache, documents, selection, citerVariant) = await BuildCitedByVariantFixtureAsync(); + + var error = Assert.Throws(() => + documents.CreateSelectionResponse(cache, "m1", selection, ordinalOf: (_, _) => 1, asOf: 1))!; + Assert.That(error.Message, Does.Contain(citerVariant.Value)); + + cache.Commit(batch => batch.Remove(citerVariant)); + var answered = documents.CreateSelectionResponse(cache, "m2", selection, ordinalOf: (_, _) => 1, asOf: 1); + Assert.That(answered.Edges, Has.Length.EqualTo(1)); + Assert.That(answered.Edges![0].From.RecordKey, Is.EqualTo("citer-one")); + } + + [Test] + public async Task AHopSubscriptionWhoseEdgeCiterIsAVariantIsRefusedOnceAndWithdrawn() + { + var (cache, documents, selection, citerVariant) = await BuildCitedByVariantFixtureAsync(); + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents }); + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + socket.ReceiveTimeout = 20; + using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions { RuntimeId = "variant-edge-server", Socket = socket }); + using var subscriptions = new CultNetDatabaseSubscriptionServer(server, database); + using var cancellation = new CancellationTokenSource(); + var serverThread = new Thread(() => + { + while (!cancellation.IsCancellationRequested) + { + _ = server.PollOnceAsync().GetAwaiter().GetResult(); + Thread.Sleep(1); + } + }) { IsBackground = true }; + serverThread.Start(); + try + { + using var client = CultNetSchemaClients.CreateRudp("variant-edge-client"); + var snapshots = new ConcurrentQueue(); + var errors = new ConcurrentQueue(); + client.OnCultNet(snapshots.Enqueue); + client.OnCultNet(errors.Enqueue); + client.Connect("127.0.0.1", server.LocalEndPoint.Port); + await WaitUntilAsync(() => client.Connected); + + client.SendCultNet(new CultNetDatabaseSubscribeV1Message + { + MessageId = "edges", + SubscriptionId = "edges", + IncludeSnapshot = true, + Selection = selection + }); + await WaitUntilAsync(() => errors.Any(error => error.Error.Contains(citerVariant.Value))); + Assert.That(snapshots, Is.Empty, "the snapshot's edges would carry the variant's resolved reference"); + Assert.That(errors, Has.Count.EqualTo(1)); } finally { From 2eec4368501f1739b3f5180d098de91a300aea41 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 10:12:20 +0200 Subject: [PATCH 63/64] Variants C1: the index rule is linear, a merge judges only when a variant is involved, duplicates are deterministic - RefuseVariantIndexSharing built its holder list per landing record by scanning every landing record, so opening a store with one variant was quadratic. It now groups what lands once and looks each (index, value) up once. Pinned by a count of index-accessor reads at two sizes, not a clock. - JudgeMerge decoded every unseen disk record before Resolve could exit early, so a plain-only store failed a conditional commit on another writer's schema it does not register. It now judges only when the batch, the disk (by the record's variant header, never its payload) or this cache holds a variant. - Plain duplicates find the holder with the smallest key (ordinal), so the choice is the same live, after a flush and after a reopen. The comment claiming "most recently indexed" was wrong across reload. - A dropped slot is reported once per record, not once by the schema diff and again by the variant. Co-Authored-By: Claude Sonnet 5 --- src/GameCult.Caching/CultCache.cs | 76 ++++++--- tests/GameCult.Caching.Tests/VariantTests.cs | 165 ++++++++++++++++++- 2 files changed, 210 insertions(+), 31 deletions(-) diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 65c75b93..b2f06659 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -1799,7 +1799,7 @@ namespace GameCult.Caching private readonly List<(CacheBackingStore Store, Type[] Homes)> _stores = new(); private readonly Dictionary _entries = new(StringComparer.Ordinal); private readonly Dictionary> _names = new(); - // Every key holding a value, oldest first: the index is truthful about duplicates, so removing one holder never hides another. + // Every key holding a value (unordered): the index is truthful about duplicates, so removing one holder never hides another. private readonly Dictionary<(Type Type, string Alias), Dictionary>> _indexes = new(); private readonly Dictionary _globals = new(); private readonly CultCodec? _codec; @@ -1823,6 +1823,9 @@ namespace GameCult.Caching public CultDocumentRegistry Registry => _registry; + // Read under the gate, by a store judging a merge. + internal bool HoldsVariants => _variantKeys.Count > 0; + public CultCodec? Codec => _codec; // The whole override of one member, encoded with this cache's codec, ready for UpsertVariant. @@ -2124,13 +2127,16 @@ namespace GameCult.Caching .SelectMany(pair => pair.Value.TryGetValue(name, out var key) ? new[] { key } : Array.Empty())); } - // A value held by one record finds it. Records of one type sharing a value (plain duplicates) find the most recently - // indexed holder, and removing that holder finds the one before it: a held value never finds nothing. + // A value held by one record finds it. Records of one type sharing a value (plain duplicates) find the holder with the + // smallest key (ordinal), whatever order they were written or loaded in: the choice is a function of the held set, so + // it is the same live, after a flush and after a reopen, and removing that holder finds the next. public T? GetByIndex(string alias, string value) where T : class { return Single($"index {alias}='{value}'", () => _indexes .Where(pair => pair.Key.Alias == alias && typeof(T).IsAssignableFrom(pair.Key.Type)) - .SelectMany(pair => pair.Value.TryGetValue(value, out var keys) ? new[] { keys[keys.Count - 1] } : Array.Empty())); + .SelectMany(pair => pair.Value.TryGetValue(value, out var keys) + ? new[] { keys.Aggregate((best, next) => string.CompareOrdinal(next, best) < 0 ? next : best) } + : Array.Empty())); } public void Dispose() @@ -2645,6 +2651,9 @@ namespace GameCult.Caching bool IsVariant(string key) => landingByKey.TryGetValue(key, out var landed) ? landed.Variant != null : _variantKeys.Contains(key); + // One pass over what lands, one lookup per (index, value): the rule is linear in the records landing. + var landedValues = new List<(CultStoredDocument Stored, (Type Type, string Alias) Index, string Value)>(); + var landed = new Dictionary<((Type Type, string Alias) Index, string Value), List>(); foreach (var stored in landing) { foreach (var pair in stored.Descriptor.IndexAccessors) @@ -2652,25 +2661,38 @@ namespace GameCult.Caching var value = pair.Value(stored.Document); if (string.IsNullOrWhiteSpace(value)) continue; - var type = stored.Descriptor.DocumentType; - var holders = (_indexes.TryGetValue((type, pair.Key), out var held) && held.TryGetValue(value, out var heldKeys) + var index = (stored.Descriptor.DocumentType, pair.Key); + landedValues.Add((stored, index, value)); + if (!landed.TryGetValue((index, value), out var landedKeys)) + landed[(index, value)] = landedKeys = new List(); + landedKeys.Add(stored.Key.Value); + } + } + + var holdersOf = new Dictionary<((Type Type, string Alias) Index, string Value), (string[] All, string[] Variants)>(); + foreach (var (stored, index, value) in landedValues) + { + if (!holdersOf.TryGetValue((index, value), out var known)) + { + var all = (_indexes.TryGetValue(index, out var held) && held.TryGetValue(value, out var heldKeys) ? heldKeys.Where(heldKey => !replaced.Contains(heldKey)) : Enumerable.Empty()) - .Concat(landing - .Where(other => other.Descriptor.DocumentType == type && pair.Value(other.Document) == value) - .Select(other => other.Key.Value)) - .Where(holder => holder != stored.Key.Value) + .Concat(landed[(index, value)]) .Distinct(StringComparer.Ordinal) .ToArray(); - if (stored.Variant != null && holders.Length > 0) - throw new InvalidOperationException( - $"Variant {stored.Key.Value} and {holders[0]} both hold index {pair.Key} '{value}'; a variant must override its indexed member."); - var variantHolder = holders.FirstOrDefault(IsVariant); - if (stored.Variant == null && variantHolder != null) - throw new InvalidOperationException( - $"Record {stored.Key.Value} and variant {variantHolder} both hold index {pair.Key} '{value}'; " + - "a variant may not share an indexed value with another record."); + holdersOf[(index, value)] = known = (all, all.Where(IsVariant).ToArray()); } + + var self = stored.Key.Value; + var holder = known.All.FirstOrDefault(candidate => candidate != self); + if (stored.Variant != null && holder != null) + throw new InvalidOperationException( + $"Variant {self} and {holder} both hold index {index.Alias} '{value}'; a variant must override its indexed member."); + var variantHolder = known.Variants.FirstOrDefault(candidate => candidate != self); + if (stored.Variant == null && variantHolder != null) + throw new InvalidOperationException( + $"Record {self} and variant {variantHolder} both hold index {index.Alias} '{value}'; " + + "a variant may not share an indexed value with another record."); } } @@ -2795,7 +2817,6 @@ namespace GameCult.Caching RemoveHolder(pair.Value, stored.Key.Value); } - // Re-indexing a key makes it the most recent holder of its value. private static void AddHolder(Dictionary<(Type Type, string Alias), Dictionary>> indexes, (Type, string) index, string value, string key) { if (!indexes.TryGetValue(index, out var map)) @@ -2974,9 +2995,10 @@ namespace GameCult.Caching .ToArray(); if (shed.Length > 0) { - var alreadyReported = report.IgnoredExtraSlots; - report.IgnoredExtraSlots = alreadyReported.Concat(shed.Except(alreadyReported)).OrderBy(slot => slot).ToArray(); - report.Warnings = report.Warnings.Concat(shed.Select(slot => new CultSchemaMigrationWarning + // A slot the schema diff already reported is not reported twice. + var unreported = shed.Except(report.IgnoredExtraSlots).ToArray(); + report.IgnoredExtraSlots = report.IgnoredExtraSlots.Concat(unreported).OrderBy(slot => slot).ToArray(); + report.Warnings = report.Warnings.Concat(unreported.Select(slot => new CultSchemaMigrationWarning { Code = "ignored_extra_slot", Message = $"Variant {record.Key} overrides slot {slot}, which {descriptor.DocumentType.Name} does not have; the override is ignored and shed on flush." @@ -3134,7 +3156,7 @@ namespace GameCult.Caching // The committer judged the batch against its own view; the file may have moved since. A merge is judged on the // set the file will hold, exactly as that set would be judged loading: what other processes wrote (arriving), // what they removed (departing), and this batch. - if (ontoDisk && Judging != null) + if (ontoDisk && Judging != null && MergeInvolvesVariants(request, disk)) JudgeMerge(request, disk); foreach (var entry in request.Deletes) records.Remove(entry.Key.Value); @@ -3150,6 +3172,14 @@ namespace GameCult.Caching return CultCommitOutcome.Committed; } + // Only a variant makes a merge more than the committer's own judgement: a variant it lands, one another writer wrote + // (read from the record's header, never its payload), or one this cache holds. A plain-only store never decodes + // another writer's records, so a schema this cache does not register cannot fail a commit that involves no variant. + private bool MergeInvolvesVariants(CultCommitRequest request, CultPersistedStoreSnapshot disk) => + Cache?.HoldsVariants == true || + request.Upserts.Any(entry => entry.Variant != null) || + disk.Records.Any(record => record.Variant != null); + private void JudgeMerge(CultCommitRequest request, CultPersistedStoreSnapshot disk) { var landing = request.Upserts.Select(entry => entry.Key.Value).ToHashSet(StringComparer.Ordinal); diff --git a/tests/GameCult.Caching.Tests/VariantTests.cs b/tests/GameCult.Caching.Tests/VariantTests.cs index 6f6654e2..c8d7a8df 100644 --- a/tests/GameCult.Caching.Tests/VariantTests.cs +++ b/tests/GameCult.Caching.Tests/VariantTests.cs @@ -773,22 +773,22 @@ namespace GameCult.Caching.Tests })); [Test] - public void PlainDuplicatesFindTheMostRecentHolderAndRemovingEitherLeavesTheOtherFindable() + public void RemovingTheHolderADuplicateValueFindsLeavesTheOtherFindable() { var path = PathOf("gear.cc"); using (var cache = Open(path)) { var pair = SharedCodePair(cache); - Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p2"), "the last writer"); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p1"), "the smallest key"); - cache.Remove(pair[1]); - Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p1"), "removing the winner finds the other holder"); - - cache.Commit(batch => batch.Upsert(typeof(VariantGear), Named("p2", "x"), pair[1])); - Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p2")); cache.Remove(pair[0]); - Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p2"), "removing the loser changes nothing"); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p2"), "removing the holder finds the other one"); + + cache.Commit(batch => batch.Upsert(typeof(VariantGear), Named("p1", "x"), pair[0])); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p1")); cache.Remove(pair[1]); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("p1"), "removing the other changes nothing"); + cache.Remove(pair[0]); Assert.That(cache.GetByIndex("code", "x"), Is.Null); cache.BackingStores[0].PushAll(); } @@ -946,6 +946,155 @@ namespace GameCult.Caching.Tests Assert.That(narrow.BackingStores[0].LastSchemaMigrationReports.SelectMany(report => report.IgnoredExtraSlots), Does.Contain(2)); } + // ---- batch 4: linear rule, judge only when a variant is involved, deterministic duplicates, one warning ---- + + [CultDocument("tests.variant_counted", "tests.variant_counted.v1")] + [MessagePackObject(AllowPrivate = true)] + internal sealed class CountedGear + { + public static long CodeReads; + [IgnoreMember] + private string _code = string.Empty; + + [Key(0)] + [CultName] + public string Name = string.Empty; + + [Key(1)] + [CultIndex("code")] + public string Code + { + get + { + System.Threading.Interlocked.Increment(ref CodeReads); + return _code; + } + set => _code = value; + } + } + + // The pin is a count of index-accessor reads, not a clock: linear work doubles with the records, quadratic work quadruples. + private long IndexReadsOpening(int records) + { + var registry = CultDocumentRegistry.ForTypes(new[] { typeof(CountedGear) }); + var path = PathOf($"counted-{records}.cc"); + using (var writer = Open(path, registry: registry)) + { + writer.Commit(batch => + { + for (var index = 0; index < records; index++) + batch.Upsert(typeof(CountedGear), new CountedGear { Name = $"n{index}", Code = $"c{index}" }, new CultRecordKey($"k{index}")); + }); + writer.Commit(batch => batch.UpsertVariant(new CultRecordKey("kv"), new CultRecordKey("k0"), new[] + { + writer.Override(nameof(CountedGear.Name), "variant"), + writer.Override(nameof(CountedGear.Code), "variant-code") + })); + } + + System.Threading.Interlocked.Exchange(ref CountedGear.CodeReads, 0); + using (Open(path, registry: registry)) + return System.Threading.Interlocked.Read(ref CountedGear.CodeReads); + } + + [Test] + public void OpeningAStoreWithAVariantReadsEachIndexedValueAFixedNumberOfTimes() + { + var small = IndexReadsOpening(1000); + var large = IndexReadsOpening(2000); + Assert.That(large, Is.LessThan(small * 3), $"index reads: {small} at 1000 records, {large} at 2000; doubling the records must not quadruple the work"); + } + + [Test] + public void ASchemaThisCacheDoesNotRegisterDoesNotFailAConditionalCommitThatInvolvesNoVariant() + { + var path = PathOf("gear.cc"); + var other = new CultRecordKey("other"); + var narrow = CultDocumentRegistry.ForTypes(new[] { typeof(VariantGear) }); + using (var seed = Open(path)) + SeedBase(seed); + + using (var a = Open(path)) + using (var b = Open(path, registry: narrow)) + { + a.Commit(batch => batch.Upsert(typeof(VariantOther), new VariantOther { Name = "foreign" }, new CultRecordKey("foreign"))); + Assert.That(b.Commit(batch => + { + batch.Expect(other, null); + batch.Upsert(typeof(VariantGear), Named("other", "fine"), other); + }), Is.True); + } + + using var reopened = Open(path); + Assert.That(reopened.Get(other), Is.Not.Null); + Assert.That(reopened.Get(new CultRecordKey("foreign")), Is.Not.Null, "the other writer's record survives the merge"); + } + + [Test] + public void AVariantAnotherWriterLandedIsStillJudgedWhenThisCacheHoldsNoVariant() + { + var path = PathOf("gear.cc"); + var other = new CultRecordKey("other"); + using (var seed = Open(path)) + SeedBase(seed); + + using (var a = Open(path)) + using (var b = Open(path)) + { + VariantOnCode(a, "shared"); + Refused(() => b.Commit(batch => + { + batch.Expect(other, null); + batch.Upsert(typeof(VariantGear), Named("other", "shared"), other); + })); + } + } + + [Test] + public void PlainDuplicatesFindTheSmallestKeyLiveAfterAFlushAndAfterAReopen() + { + var path = PathOf("gear.cc"); + using (var cache = Open(path)) + { + cache.Commit(batch => batch.Upsert(typeof(VariantGear), Named("nb", "x"), new CultRecordKey("b"))); + cache.Commit(batch => batch.Upsert(typeof(VariantGear), Named("na", "x"), new CultRecordKey("a"))); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("na"), "live"); + cache.BackingStores[0].PushAll(); + Assert.That(cache.GetByIndex("code", "x")!.Name, Is.EqualTo("na"), "after a flush"); + } + + using (var reopened = Open(path)) + { + Assert.That(reopened.GetByIndex("code", "x")!.Name, Is.EqualTo("na"), "after a reopen"); + reopened.Remove(new CultRecordKey("a")); + reopened.Commit(batch => batch.Upsert(typeof(VariantGear), Named("na", "x"), new CultRecordKey("a"))); + Assert.That(reopened.GetByIndex("code", "x")!.Name, Is.EqualTo("na"), "rewriting the smaller key does not change the choice"); + } + } + + [Test] + public void ADroppedSlotIsReportedOncePerRecord() + { + var path = PathOf("drift.cc"); + using (var writer = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftWide) }))) + { + writer.Commit(batch => + { + batch.Upsert(typeof(DriftWide), new DriftWide { Name = "drift", Power = 1, Wing = "base wing" }, new CultRecordKey("drift-base")); + batch.UpsertVariant(new CultRecordKey("drift-variant"), new CultRecordKey("drift-base"), new[] + { + writer.Override(nameof(DriftWide.Name), "drift variant"), + writer.Override(nameof(DriftWide.Wing), "stale wing") + }); + }); + } + + using var narrow = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftNarrow) })); + var variantReport = narrow.BackingStores[0].LastSchemaMigrationReports.Last(); + Assert.That(variantReport.Warnings.Count(warning => warning.Code == "ignored_extra_slot"), Is.EqualTo(1)); + Assert.That(variantReport.IgnoredExtraSlots, Is.EqualTo(new[] { 2 })); + } + // ---- the directory store refuses a variant page on load as it does on write ---- [Test] From cbd3b4f3ce3963979a7b30e88305c467e5c8a638 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 10:12:20 +0200 Subject: [PATCH 64/64] CultNet: a withdrawn hop subscription is refused with a typed error and its rows are withdrawn Reconcile's withdrawal sent an untyped error with no subscription id and left the peer holding the rows the subscription had delivered. It now sends removals for those rows, then a variant_unsupported error whose details carry field "subscriptionId" and the id (the existing details slots; no new wire key). The subscribe and per-change paths use the same code. The error schema and the Rust CultNetErrorCode accept variant_unsupported, so a Rust peer decodes it instead of refusing an unknown code. Co-Authored-By: Claude Sonnet 5 --- contracts/cultnet/cultnet.error.schema.json | 6 +++--- .../contracts/cultnet/cultnet.error.schema.json | 6 +++--- packages/cultnet-rs/src/contracts.rs | 5 ++++- .../CultNetDatabaseSubscriptionServer.cs | 13 +++++++------ src/GameCult.Networking/CultNetSchemaMessages.cs | 12 ++++++++++++ .../CultNetDocumentRegistryVariantTests.cs | 4 ++++ 6 files changed, 33 insertions(+), 13 deletions(-) diff --git a/contracts/cultnet/cultnet.error.schema.json b/contracts/cultnet/cultnet.error.schema.json index 8653cbd5..15880fa1 100644 --- a/contracts/cultnet/cultnet.error.schema.json +++ b/contracts/cultnet/cultnet.error.schema.json @@ -28,7 +28,7 @@ "code": { "description": "Machine-readable refusal code (R-N). Additive: a v0 peer that does not know this field ignores it.", "type": ["string", "null"], - "enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target"] + "enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target", "variant_unsupported"] }, "details": { "description": "Code-specific structured detail (R-N). Every field is populated only for the code that defines it; the others are null, not omitted.", @@ -36,8 +36,8 @@ "additionalProperties": false, "required": ["field", "value", "asOf", "current"], "properties": { - "field": { "description": "selection_invalid: the selection field that failed.", "type": ["string", "null"] }, - "value": { "description": "selection_invalid: the offending value, when there is one string worth naming.", "type": ["string", "null"] }, + "field": { "description": "selection_invalid: the selection field that failed. variant_unsupported: \"subscriptionId\", when a subscription was ended.", "type": ["string", "null"] }, + "value": { "description": "selection_invalid: the offending value, when there is one string worth naming. variant_unsupported: the id of the subscription that ended.", "type": ["string", "null"] }, "asOf": { "description": "cursor_stale: the cursor's own minted asOf.", "type": ["integer", "null"], "minimum": 0 }, "current": { "description": "cursor_stale: the answering server's current asOf.", "type": ["integer", "null"], "minimum": 0 } } diff --git a/packages/cultnet-rs/contracts/cultnet/cultnet.error.schema.json b/packages/cultnet-rs/contracts/cultnet/cultnet.error.schema.json index 8653cbd5..15880fa1 100644 --- a/packages/cultnet-rs/contracts/cultnet/cultnet.error.schema.json +++ b/packages/cultnet-rs/contracts/cultnet/cultnet.error.schema.json @@ -28,7 +28,7 @@ "code": { "description": "Machine-readable refusal code (R-N). Additive: a v0 peer that does not know this field ignores it.", "type": ["string", "null"], - "enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target"] + "enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target", "variant_unsupported"] }, "details": { "description": "Code-specific structured detail (R-N). Every field is populated only for the code that defines it; the others are null, not omitted.", @@ -36,8 +36,8 @@ "additionalProperties": false, "required": ["field", "value", "asOf", "current"], "properties": { - "field": { "description": "selection_invalid: the selection field that failed.", "type": ["string", "null"] }, - "value": { "description": "selection_invalid: the offending value, when there is one string worth naming.", "type": ["string", "null"] }, + "field": { "description": "selection_invalid: the selection field that failed. variant_unsupported: \"subscriptionId\", when a subscription was ended.", "type": ["string", "null"] }, + "value": { "description": "selection_invalid: the offending value, when there is one string worth naming. variant_unsupported: the id of the subscription that ended.", "type": ["string", "null"] }, "asOf": { "description": "cursor_stale: the cursor's own minted asOf.", "type": ["integer", "null"], "minimum": 0 }, "current": { "description": "cursor_stale: the answering server's current asOf.", "type": ["integer", "null"], "minimum": 0 } } diff --git a/packages/cultnet-rs/src/contracts.rs b/packages/cultnet-rs/src/contracts.rs index cc50171d..f31ade85 100644 --- a/packages/cultnet-rs/src/contracts.rs +++ b/packages/cultnet-rs/src/contracts.rs @@ -250,7 +250,7 @@ impl CultNetShardDescriptor { } } -/// Machine-readable `cultnet.error.v0` refusal code (R-N). Mirrors the four strings +/// Machine-readable `cultnet.error.v0` refusal code (R-N). Mirrors the five strings /// `contracts/cultnet/cultnet.error.schema.json` enumerates for `code`; a peer that receives a fifth /// string it does not know refuses to decode rather than guess a meaning for it. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -260,6 +260,7 @@ pub enum CultNetErrorCode { CursorStale, CursorInvalid, ReferenceOutsideTarget, + VariantUnsupported, } impl CultNetErrorCode { @@ -269,6 +270,7 @@ impl CultNetErrorCode { Self::CursorStale => "cursor_stale", Self::CursorInvalid => "cursor_invalid", Self::ReferenceOutsideTarget => "reference_outside_target", + Self::VariantUnsupported => "variant_unsupported", } } @@ -278,6 +280,7 @@ impl CultNetErrorCode { "cursor_stale" => Ok(Self::CursorStale), "cursor_invalid" => Ok(Self::CursorInvalid), "reference_outside_target" => Ok(Self::ReferenceOutsideTarget), + "variant_unsupported" => Ok(Self::VariantUnsupported), other => Err(anyhow!("ErrorMessage.Code {other:?} is not a recognized cultnet.error.v0 code")), } } diff --git a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs index 60bb66a5..f3150740 100644 --- a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs @@ -208,7 +208,7 @@ namespace GameCult.Networking { // Q6: a snapshot that selects a variant is refused to this subscriber as a typed error. Withdraw(key, sendRemovals: false, forgetRequest: true); - peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); + peer.SendCultNet(CultNetErrorMessage.ForVariantUnsupported(refusal.Message, subscriptionId)); return Task.CompletedTask; } catch @@ -330,7 +330,7 @@ namespace GameCult.Networking catch (NotSupportedException refusal) { // Q6: a variant is not a record CultNet can carry; the subscriber that would have received it is told, by key. - peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); + peer.SendCultNet(CultNetErrorMessage.ForVariantUnsupported(refusal.Message)); return; } @@ -358,11 +358,12 @@ namespace GameCult.Networking } catch (NotSupportedException refusal) { - // Q6: the selection selects a variant, which CultNet cannot carry. Refused as the subscribe path refuses it: the - // subscription is withdrawn, so the peer is told once, not once per store change; a change never throws out of + // Q6: the selection selects a variant, which CultNet cannot carry. The subscription is withdrawn, so the peer is + // told once, not once per store change; the rows it delivered are withdrawn too (removals first), so the peer + // does not keep them as live, and the typed error names the subscription that ended. A change never throws out of // the change handler. - Withdraw(key, sendRemovals: false, forgetRequest: true); - key.Peer.SendCultNet(new CultNetErrorMessage { Error = refusal.Message }); + Withdraw(key, sendRemovals: true, forgetRequest: true); + key.Peer.SendCultNet(CultNetErrorMessage.ForVariantUnsupported(refusal.Message, key.Id)); return; } diff --git a/src/GameCult.Networking/CultNetSchemaMessages.cs b/src/GameCult.Networking/CultNetSchemaMessages.cs index f343fad7..4daa76d5 100644 --- a/src/GameCult.Networking/CultNetSchemaMessages.cs +++ b/src/GameCult.Networking/CultNetSchemaMessages.cs @@ -546,6 +546,18 @@ namespace GameCult.Networking : null }; + /// + /// Builds the wire error for a selection that selects a document variant, which CultNet does not carry yet: code + /// variant_unsupported, details { field: "subscriptionId", value } when a subscription was ended by it. + /// + public static CultNetErrorMessage ForVariantUnsupported(string message, string? subscriptionId = null) => + new CultNetErrorMessage + { + Error = message, + Code = "variant_unsupported", + Details = subscriptionId == null ? null : new CultNetErrorDetails { Field = "subscriptionId", Value = subscriptionId } + }; + /// /// Builds the wire error for an out-of-target reference refusal (R-N): code /// reference_outside_target, no details. diff --git a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs index a4658117..64de1093 100644 --- a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs @@ -272,6 +272,10 @@ namespace GameCult.Networking.Tests await database.PutAsync(new CultRecordKey("citer-four"), Citer("citer-four", VariantKey)); await WaitUntilAsync(() => errors.Any(error => error.Error.Contains(VariantKey.Value)), Diagnostic); + var refusal = errors.First(error => error.Error.Contains(VariantKey.Value)); + Assert.That(refusal.Code, Is.EqualTo("variant_unsupported")); + Assert.That(refusal.Details?.Value, Is.EqualTo("cited"), "the peer can tell which subscription ended"); + await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "cited" && change.ChangeKind == "removed" && change.RecordKey == BaseKey.Value), Diagnostic); Assert.That(changes.Where(change => change.SubscriptionId == "cited").Select(change => change.Document?.RecordKey), Does.Not.Contain(VariantKey.Value), "a variant never reaches a subscriber as a record");