TypeScript: a record is stamped with its registered schema id and the catalog publishes it; the inspector reads what the reader reads

putEnvelope and admission stamp the registered schema's id, and the store writer publishes every record's id (the entry the
envelope carries when it lists that id, else a default), so a replicated record under a compatible id no longer leaves a store
nothing can open. cultnet-ts stops preserving the incoming id. The inspector refuses a store of the wrong slot count and a record
whose schema the catalog does not publish, instead of recovering one from the payload.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-30 06:54:18 +02:00
commit 39a9de3b23
6 changed files with 184 additions and 120 deletions

View file

@ -1,6 +1,6 @@
import { decode } from "@msgpack/msgpack";
import { type StoreFormat, isStoreSnapshot, requireV1RecordSlots } from "./store-format";
import { type StoreFormat, isStoreSnapshot, requireStoreSlots, requireV1RecordSlots } from "./store-format";
export interface CultCacheInspection {
filePath: string;
@ -60,6 +60,7 @@ export function inspectCultCacheBytes(
}
function inspectV1Snapshot(filePath: string, fileSizeBytes: number, decoded: [StoreFormat, ...unknown[]]): CultCacheInspection {
requireStoreSlots(decoded);
const catalogRaw = decoded[1];
const recordsRaw = decoded[2];
if (!Array.isArray(catalogRaw) || !Array.isArray(recordsRaw)) {
@ -75,24 +76,6 @@ function inspectV1Snapshot(filePath: string, fileSizeBytes: number, decoded: [St
}
}
const records = recordsRaw.map((record) => decodeV1Record(record, catalogBySchemaId));
for (const record of records) {
if (!catalog.some((entry) => entry.schemaId === record.schemaId)) {
const schemaVersion = inferSchemaVersionFromPayloadPreview(record.payloadPreview);
const schemaName = schemaVersion ? inferSchemaName(schemaVersion) : undefined;
if (schemaName) {
catalog.push({
schemaId: record.schemaId,
schemaName,
schemaVersion: schemaVersion!,
contentHash: record.schemaId,
canonicalSchemaJson: "",
compatibleSchemaIds: [],
members: [],
});
}
}
}
return {
filePath,
fileSizeBytes,
@ -204,64 +187,21 @@ function decodeV1Record(value: unknown, catalogBySchemaId: Map<string, Inspected
}
const payloadBytes = normalizePayloadBytes(payload);
const catalogEntry = catalogBySchemaId.get(schemaId) ?? recoverCatalogEntry(schemaId, payloadBytes);
const catalogEntry = catalogBySchemaId.get(schemaId);
if (!catalogEntry) {
throw new Error(`CultCache persisted record "${key}" references missing schema id "${schemaId}".`);
}
return {
key,
schemaId,
schemaName: catalogEntry?.schemaName ?? "<missing catalog entry>",
schemaName: catalogEntry.schemaName,
storedAt,
payloadBytes: payloadBytes.length,
...previewPayload(payloadBytes),
};
}
function recoverCatalogEntry(schemaId: string, payload: Uint8Array): InspectedCatalogEntry | undefined {
let payloadPreview: unknown;
try {
payloadPreview = decode(payload);
} catch {
return undefined;
}
const schemaVersion = inferSchemaVersionFromPayloadPreview(payloadPreview);
if (!schemaVersion) {
return undefined;
}
const schemaName = inferSchemaName(schemaVersion);
if (!schemaName) {
return undefined;
}
return {
schemaId,
schemaName,
schemaVersion,
contentHash: schemaId,
canonicalSchemaJson: "",
compatibleSchemaIds: [],
members: [],
};
}
function inferSchemaVersionFromPayloadPreview(payloadPreview: unknown): string | undefined {
if (Array.isArray(payloadPreview) && typeof payloadPreview[0] === "string") {
return payloadPreview[0];
}
if (isRecord(payloadPreview)) {
const schemaVersion = payloadPreview.schemaVersion ?? payloadPreview.schema_version;
return typeof schemaVersion === "string" ? schemaVersion : undefined;
}
return undefined;
}
function inferSchemaName(schemaVersion: string): string | undefined {
const match = /^(.*)\.v\d+$/.exec(schemaVersion);
return match?.[1];
}
function decodeLegacyEnvelope(value: unknown): InspectedRecord {
if (!isRecord(value)) {
throw new Error("CultCache legacy envelopes must be MessagePack maps.");

View file

@ -462,8 +462,10 @@ export class CultCache {
type: envelope.type,
payload,
storedAt: envelope.storedAt,
schemaId: envelope.schemaId ?? registered.catalogEntry.schemaId,
catalogEntry: envelope.catalogEntry ?? registered.catalogEntry,
// The record is stamped with its registered schema's id, whatever id the envelope arrived under, so the
// catalog entry the store writes is the one its schema id names.
schemaId: registered.catalogEntry.schemaId,
catalogEntry: registered.catalogEntry,
};
await this.#writeNow(registered, entry, parsed);
return parsed;
@ -876,8 +878,10 @@ export class CultCache {
return {
...entry,
payload: this.#cloneBytes(entry.payload),
schemaId: entry.schemaId ?? registered.catalogEntry.schemaId,
catalogEntry: entry.catalogEntry ?? registered.catalogEntry,
// Admitted under the registered schema's id, as a put stamps it: a record loaded under a compatible id is
// written back under the id its catalog entry carries.
schemaId: registered.catalogEntry.schemaId,
catalogEntry: registered.catalogEntry,
value,
lookups: this.#lookupsFor(registered.nameAccessor, registered.indexAccessors, value),
};

View file

@ -215,24 +215,32 @@ function encodeSnapshot(entries: CultCacheEnvelope[], format: StoreFormat): unkn
];
}
// Every record's schema id is published by a catalog entry: the entry the envelope carries when it publishes that id (as its
// own id or a compatible one), else a default entry under the record's id. The catalog is keyed by the entry's own id, so a
// record read under a compatible id is written back beside the entry that lists it.
function catalogEntriesFor(entries: CultCacheEnvelope[]): Map<string, CultCacheSchemaCatalogEntry> {
const catalog = new Map<string, CultCacheSchemaCatalogEntry>();
for (const entry of entries) {
const schemaId = schemaIdForEnvelope(entry);
if (!catalog.has(schemaId)) {
catalog.set(schemaId, entry.catalogEntry ?? {
schemaId,
const supplied = entry.catalogEntry;
const publishes =
supplied !== undefined &&
(supplied.schemaId === schemaId || (supplied.compatibleSchemaIds ?? []).includes(schemaId));
const published: CultCacheSchemaCatalogEntry = publishes ? supplied : {
schemaId,
schemaName: entry.type,
schemaVersion: `${entry.type}.v1`,
contentHash: schemaId,
canonicalSchemaJson: JSON.stringify({
schemaName: entry.type,
schemaVersion: `${entry.type}.v1`,
contentHash: schemaId,
canonicalSchemaJson: JSON.stringify({
schemaName: entry.type,
schemaVersion: `${entry.type}.v1`,
members: [],
}),
compatibleSchemaIds: [schemaId],
members: [],
});
}),
compatibleSchemaIds: [schemaId],
members: [],
};
if (!catalog.has(published.schemaId)) {
catalog.set(published.schemaId, published);
}
}

View file

@ -1244,40 +1244,108 @@ test("CultCache inspector decodes v1 store catalog and record payloads from byte
]);
});
test("CultCache inspector recovers schema-stamped records missing catalog entries", async () => {
test("CultCache inspector refuses a record whose schema the catalog does not publish, and a store of the wrong slot count", async () => {
const tempDir = await mkdtemp(join(tmpdir(), "cultcache-inspector-"));
const file = join(tempDir, "missing-catalog.cc");
const record = [
"record-1",
"sha256:stale-schema-id-from-cold-record",
"2026-06-25T12:00:00Z",
encode(["tests.schema_stamped_entry.v1", "schema-stamped", "still readable"]),
];
assert.throws(
() => inspectCultCacheBytes("missing-catalog.cc", encode(["cultcache.store.v1", [], [record]])),
/references missing schema id/u,
);
assert.throws(() => inspectCultCacheBytes("header-only.cc", encode(["cultcache.store.v1"])), /top-level slots/u);
assert.throws(
() => inspectCultCacheBytes("extra-slot.cc", encode(["cultcache.store.v1", [], [], 0])),
/top-level slots/u,
);
await rm(tempDir, { recursive: true, force: true });
});
// A record written under an id its schema only lists as compatible is stamped with the registered id, and the store the write
// leaves opens and takes the next write. The envelope carries a catalog entry under the foreign id, as a replicated one does.
const foreignIdDocument = defineDocumentType({
type: "tests.foreign-id",
schema: z.object({ name: z.string() }),
schemaId: "tests.foreign-id.current",
schemaName: "tests.foreign-id",
schemaVersion: "tests.foreign_id.v1",
compatibleSchemaIds: ["tests.foreign-id.current", "tests.foreign-id.older"],
});
async function reopenForeignIdStore(file: string): Promise<CultCache> {
const cache = CultCache.builder()
.withDocumentType(foreignIdDocument)
.withGenericStore(new SingleFileMessagePackBackingStore(file))
.build();
await cache.pullAllBackingStores();
return cache;
}
function schemaIdsOf(bytes: Uint8Array): { record: string; catalog: string[] } {
const decoded = decode(bytes) as [string, unknown[][], unknown[][]];
return { record: decoded[2][0]![1] as string, catalog: decoded[1].map((entry) => entry[0] as string) };
}
test("putEnvelope under a compatible schema id writes a store that reopens and takes the next write", async () => {
const file = join(await mkdtemp(join(tmpdir(), "cultcache-foreign-id-")), "store.msgpack");
const cache = await reopenForeignIdStore(file);
const seed = await cache.put(foreignIdDocument, "seed", { name: "seed" });
const payload = cache.getRequiredEnvelope(foreignIdDocument, "seed").payload;
await cache.putEnvelope(foreignIdDocument, {
key: "foreign",
type: "tests.foreign-id",
schemaId: "tests.foreign-id.older",
payload,
storedAt: "2026-09-30T00:00:00.0000000Z",
catalogEntry: {
schemaId: "tests.foreign-id.older",
schemaName: "tests.foreign-id",
schemaVersion: "tests.foreign_id.v1",
contentHash: "tests.foreign-id.older",
canonicalSchemaJson: "",
compatibleSchemaIds: ["tests.foreign-id.older"],
members: [],
},
});
const ids = schemaIdsOf(await readFile(file));
assert.deepEqual(ids, { record: "tests.foreign-id.current", catalog: ["tests.foreign-id.current"] });
const reopened = await reopenForeignIdStore(file);
assert.deepEqual(reopened.getRequired(foreignIdDocument, "foreign"), seed);
await reopened.put(foreignIdDocument, "next", { name: "next" });
assert.deepEqual((await reopenForeignIdStore(file)).getRequired(foreignIdDocument, "next"), { name: "next" });
});
test("a record loaded under a compatible schema id is written back under the id its catalog entry carries", async () => {
const file = join(await mkdtemp(join(tmpdir(), "cultcache-foreign-id-")), "store.msgpack");
const payload = encode({ name: "old" });
await writeFile(
file,
encode([
"cultcache.store.v1",
[],
[
[
"record-1",
"sha256:stale-schema-id-from-cold-record",
"2026-06-25T12:00:00Z",
encode([
"tests.schema_stamped_entry.v1",
"schema-stamped",
"still readable",
]),
],
],
[[
"tests.foreign-id.current",
"tests.foreign-id",
"tests.foreign_id.v1",
"tests.foreign-id.current",
"",
["tests.foreign-id.current", "tests.foreign-id.older"],
[],
]],
[["old", "tests.foreign-id.older", "2026-09-30T00:00:00.0000000Z", payload]],
]),
);
const inspection = inspectCultCacheBytes(file, await readFile(file));
assert.equal(inspection.catalog.length, 1);
assert.equal(inspection.catalog[0]?.schemaId, "sha256:stale-schema-id-from-cold-record");
assert.equal(inspection.catalog[0]?.schemaName, "tests.schema_stamped_entry");
assert.equal(inspection.records[0]?.schemaName, "tests.schema_stamped_entry");
assert.deepEqual(inspection.records[0]?.payloadPreview, [
"tests.schema_stamped_entry.v1",
"schema-stamped",
"still readable",
]);
const cache = await reopenForeignIdStore(file);
await cache.put(foreignIdDocument, "next", { name: "next" });
const reopened = await reopenForeignIdStore(file);
assert.deepEqual(reopened.getRequired(foreignIdDocument, "old"), { name: "old" });
assert.deepEqual(reopened.getRequired(foreignIdDocument, "next"), { name: "next" });
});
interface InteropNote {
@ -1615,7 +1683,7 @@ test("SingleFileMessagePackBackingStore replaces a file exactly when it reads",
// The replaced file is a store: it carries the header its old content decides (a v3 store keeps its marker, all else
// is v1), and it holds what the operation wrote.
assert.equal((decode(await readFile(file)) as unknown[])[0], vector.endsWith("v3-base.msgpack") ? "cultcache.store.v3" : "cultcache.store.v1", `${vector} ${operation}`);
assert.equal((decode(await readFile(file)) as unknown[])[0], vector.includes("v3") ? "cultcache.store.v3" : "cultcache.store.v1", `${vector} ${operation}`);
const keys = (await new SingleFileMessagePackBackingStore(file).pullAll()).map((entry) => entry.key);
if (operation === "pushAll") {
assert.deepEqual(keys, envelopes.map((entry) => entry.key).sort(), `${vector} ${operation}`);

View file

@ -246,14 +246,11 @@ export class CultNetDocumentRegistry {
cache: CultCache,
message: CultNetDocumentPutRawMessage,
): Promise<unknown> {
const resolution = this.#resolveRawDocumentBinding(message.document);
const { binding } = resolution;
const binding = this.#resolveRawDocumentBinding(message.document);
return cache.putEnvelope(binding.definition, {
key: message.document.recordKey,
type: binding.definition.type,
schemaId: resolution.preserveIncomingSchemaId
? message.document.schemaId
: schemaIdForBinding(binding),
schemaId: schemaIdForBinding(binding),
payload: new Uint8Array(message.document.payload),
storedAt: message.document.storedAt,
});
@ -303,20 +300,17 @@ export class CultNetDocumentRegistry {
return binding;
}
#resolveRawDocumentBinding(document: CultNetRawDocumentRecord): {
binding: CultNetDocumentBinding;
preserveIncomingSchemaId: boolean;
} {
#resolveRawDocumentBinding(document: CultNetRawDocumentRecord): CultNetDocumentBinding {
const exact = this.getBySchemaId(document.schemaId);
if (exact) {
return { binding: exact, preserveIncomingSchemaId: true };
return exact;
}
const payload = new Uint8Array(document.payload);
for (const binding of this.#uniqueBindings()) {
try {
decodeDocumentValue(binding.definition, payload);
return { binding, preserveIncomingSchemaId: false };
return binding;
} catch {
// Keep looking; a foreign schema id is acceptable only when the payload validates locally.
}

View file

@ -1341,6 +1341,56 @@ test("CultNet raw replication preserves CultCache payload bytes for bit-compatib
}
});
test("CultNet raw replication under a compatible schema id leaves a store that reopens and takes the next write", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "cultnetts-raw-compatible-"));
try {
const definition = defineDocumentType({
type: "tests.raw-compatible",
schema: z.object({ name: z.string() }),
schemaId: "tests.raw-compatible.current",
schemaName: "tests.raw-compatible",
schemaVersion: "tests.raw_compatible.v1",
compatibleSchemaIds: ["tests.raw-compatible.current", "tests.raw-compatible.older"],
});
const registry = new CultNetDocumentRegistry([
defineCultNetDocumentBinding({ definition, payloadSchemaVersion: "tests.raw_compatible.v1" }),
]);
const open = async (): Promise<CultCache> => {
const cache = CultCache.builder()
.withDocumentType(definition)
.withGenericStore(new SingleFileMessagePackBackingStore(join(tempDir, "target.msgpack")))
.build();
await cache.pullAllBackingStores();
return cache;
};
const origin = CultCache.builder().withDocumentType(definition).build();
await origin.put(definition, "seed", { name: "seed" });
const payload = origin.getRequiredEnvelope(definition, "seed").payload;
const target = await open();
await registry.applyRawDocumentPutMessage(target, {
schemaVersion: "cultnet.document_put_raw.v0",
messageId: "raw-compatible-1",
document: {
schemaId: "tests.raw-compatible.older",
recordKey: "replicated",
storedAt: "2026-09-30T00:00:00.0000000Z",
payloadEncoding: "messagepack",
payload,
},
} as Parameters<CultNetDocumentRegistry["applyRawDocumentPutMessage"]>[1]);
const reopened = await open();
assert.deepEqual(reopened.getRequired(definition, "replicated"), { name: "seed" });
await reopened.put(definition, "next", { name: "next" });
assert.deepEqual((await open()).getRequired(definition, "next"), { name: "next" });
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
test("operation envelopes preserve typed service routing and payload correlation", () => {
const request = parseCultNetMessage({
schemaVersion: "cultnet.operation_request.v0",