cultnet-ts: chunk references carry the element id (slot 4), as the reference reads and writes it; changelogs for the flush-over-damage refusal

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-22 21:55:15 +02:00
commit 2c9043357e
6 changed files with 37 additions and 9 deletions

View file

@ -2,6 +2,7 @@
## Unreleased
- A write over a file the reader refuses (`StoreUnreadableError`, from `push`, `push_all` and `delete`) refuses and leaves the file as it is. A flush used to replace such a file. A write set cannot merge with a disk it cannot read, so the file is repaired or removed by its owner before the store writes again.
- Added `StoreUnreadableError` (a `ValueError`) for a store file this runtime cannot read, and `SchemaConflictError` (a `ValueError`) for a
write the catalog cannot describe. A store is exactly three slots; a schema is never recovered from a record's payload.
- The single-file writer derives the catalog from the records it writes: one entry per carried schema id, the registered entry over an

View file

@ -8,6 +8,7 @@ All notable changes to `@gamecult/cultcache-ts` are recorded here, following
### Breaking
- A single-file store refuses a zero-byte file as `StoreUnreadableError`; only a path with nothing at it is an empty store. A header this runtime does not read is refused, and the refusal echoes the header only as `cultcache.store.v<digits>`.
- A write over a file the reader refuses (`StoreUnreadableError`, from `push`, `pushAll` and `delete`) refuses and leaves the file as it is. A flush used to replace such a file. A write set cannot merge with a disk it cannot read, so the file is repaired or removed by its owner before the store writes again.
- A dangling symbolic link at the store path is an I/O error with code `ENOENT`, not an empty store.
### Added

View file

@ -5,6 +5,10 @@ All notable changes to `cultnet-ts` are recorded here, following
## Unreleased
### Breaking
- `CultMeshCdnChunkRef` carries `id` (slot 4), the reference's element id. `encodeManifest` writes five-slot chunk references and `packContent` sets the decimal offset as the id, as the reference does; a manifest written before ids reads `""` and is rewritten with the slot. Content vectors regenerated from the reference.
- Needs the cultcache-ts release that ships with this change (its manifest range moves with that release): the Idunn runtime authority reader calls `readSingleFileStore`, which 0.14.x does not export. An absent authority file is now a plain `Error` without a code.
## [0.3.0]

View file

@ -143,7 +143,9 @@ imports no `node:` module, so a browser bundle can take it.
- The decoder reads what MessagePack-CSharp reads and refuses what it refuses:
nil in a string, tag or metadata slot is `null` and is written back as nil,
a missing trailing slot takes the reference's default, extra slots and trailing
bytes are skipped, a float-encoded integer is refused, and invalid UTF-8
bytes are skipped (a chunk reference's fifth slot is its element id, a string
or nil, `""` when absent; `packContent` writes the decimal offset as the id, as the
reference does), a float-encoded integer is refused, and invalid UTF-8
decodes to U+FFFD. A nil `chunks` is refused, as the reference's
`ValidateManifest` refuses it. `content-acceptance-vectors.json` is the
reference's own verdict on each of those shapes.

View file

@ -26,6 +26,8 @@ export interface CultMeshCdnChunkRef {
readonly offset: number;
readonly sizeBytes: number;
readonly recordKey: string | null;
// Element id, slot 4: the reference derives it from the offset when packing; "" when a manifest written before ids omits it.
readonly id: string | null;
}
// Metadata is ordered entries, never an object: a JS object reorders integer-like keys, and the entry order is wire bytes.
@ -142,13 +144,13 @@ const mapHeader = (count: number): Uint8Array =>
/** A string slot is written as C# writes it: a lone surrogate has no UTF-8 encoding and becomes U+FFFD at every length. */
const text = <T>(field: T): T => (typeof field === "string" ? wellFormed(field) : field) as T;
/** The positional ten-array of the C# `[MessagePackObject]`: chunk references are four-arrays, metadata a map in entry order. */
/** The positional ten-array of the C# `[MessagePackObject]`: chunk references are five-arrays, metadata a map in entry order. */
export function encodeManifest(manifest: CultMeshCdnArtifactManifest): Uint8Array {
const { artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc, chunks, tags, metadata } = manifest;
return concat([
Uint8Array.of(0x9a),
...[artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc].map(field => encode(text(field))),
encode(chunks.map(c => [text(c.chunkHash), c.offset, c.sizeBytes, text(c.recordKey)])),
encode(chunks.map(c => [text(c.chunkHash), c.offset, c.sizeBytes, text(c.recordKey), text(c.id)])),
encode(tags === null ? null : tags.map(text)),
...(metadata === null ? [encode(null)] : [mapHeader(metadata.length), ...metadata.flatMap(([key, value]) => [encode(text(key)), encode(text(value))])]),
]);
@ -279,6 +281,7 @@ function readChunkRef(reader: Reader): CultMeshCdnChunkRef {
// The reference's `int`.
sizeBytes: slot(() => { const size = reader.integer("chunks.sizeBytes"); return size >= -(2 ** 31) && size < 2 ** 31 ? size : wrongType("chunks.sizeBytes"); }, 0),
recordKey: slot(() => reader.string("chunks.recordKey"), ""),
id: slot(() => reader.string("chunks.id"), ""),
};
for (; index < count; index += 1) reader.skip();
return chunk;
@ -308,7 +311,7 @@ export async function packContent(
sizeBytes: bytes.length,
mimeType: isNullOrWhiteSpaceCSharp(options.mimeType) ? "application/octet-stream" : options.mimeType!,
createdAtUtc: options.createdAtUtc ?? `${new Date().toISOString().slice(0, 23)}0000+00:00`,
chunks: chunks.map(({ chunkHash, payload }, index) => ({ chunkHash, offset: offsets[index]!, sizeBytes: payload.length, recordKey: chunkRecordKey(chunkHash) })),
chunks: chunks.map(({ chunkHash, payload }, index) => ({ chunkHash, offset: offsets[index]!, sizeBytes: payload.length, recordKey: chunkRecordKey(chunkHash), id: String(offsets[index]) })),
tags: options.tags ?? [],
metadata: options.metadata ?? [],
};

View file

@ -49,14 +49,14 @@ const HASH = "a".repeat(64);
const manifestOf = (over: Partial<CultMeshCdnArtifactManifest> = {}): CultMeshCdnArtifactManifest => ({
artifactId: "id", kind: "asset", version: "1", contentHash: HASH, sizeBytes: 4, mimeType: "text/plain", createdAtUtc: "t",
chunks: [{ chunkHash: HASH, offset: 0, sizeBytes: 4, recordKey: `mesh:cdn:chunk:${HASH}` }], tags: ["t"], metadata: [["k", "v"]],
chunks: [{ chunkHash: HASH, offset: 0, sizeBytes: 4, recordKey: `mesh:cdn:chunk:${HASH}`, id: "0" }], tags: ["t"], metadata: [["k", "v"]],
...over,
});
// Wire bytes of a ten-array with any field replaced, metadata as a plain object (no integer-like keys).
const fieldsOf = (over: Record<number, unknown> = {}) => {
const m = manifestOf();
const fields: unknown[] = [m.artifactId, m.kind, m.version, m.contentHash, m.sizeBytes, m.mimeType, m.createdAtUtc,
m.chunks.map(c => [c.chunkHash, c.offset, c.sizeBytes, c.recordKey]), m.tags, { k: "v" }];
m.chunks.map(c => [c.chunkHash, c.offset, c.sizeBytes, c.recordKey, c.id]), m.tags, { k: "v" }];
for (const [index, value] of Object.entries(over)) fields[Number(index)] = value;
return fields;
};
@ -95,7 +95,7 @@ test("the packed chunks are copies that rejoin to the body, each named by the ha
assert.deepEqual(Array.from(chunks.flatMap(c => Array.from(c.payload))), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
for (const [i, c] of chunks.entries()) {
assert.equal(c.chunkHash, await sha256Hex(c.payload));
assert.deepEqual(manifest.chunks[i], { chunkHash: c.chunkHash, offset: i * 4, sizeBytes: c.payload.length, recordKey: chunkRecordKey(c.chunkHash) });
assert.deepEqual(manifest.chunks[i], { chunkHash: c.chunkHash, offset: i * 4, sizeBytes: c.payload.length, recordKey: chunkRecordKey(c.chunkHash), id: String(i * 4) });
}
const twins = await packContent("x", new Uint8Array(8), { chunkSizeBytes: 4 });
assert.equal(twins.manifest.chunks[0]!.chunkHash, twins.manifest.chunks[1]!.chunkHash, "equal chunks share a hash");
@ -216,7 +216,7 @@ test("a metadata key that is not a string names the field", () => {
});
test("validateManifest refuses negative size, a gap, an overlap and a size-sum mismatch with the C# messages", () => {
const chunk = (offset: number, sizeBytes: number) => ({ chunkHash: HASH, offset, sizeBytes, recordKey: "k" });
const chunk = (offset: number, sizeBytes: number) => ({ chunkHash: HASH, offset, sizeBytes, recordKey: "k", id: String(offset) });
const refuses = (over: Partial<CultMeshCdnArtifactManifest>, message: string) =>
assert.throws(() => validateManifest(manifestOf(over)), new Error(message));
refuses({ sizeBytes: -1, chunks: [] }, "CDN artifact manifest has a negative size.");
@ -232,7 +232,7 @@ test("validateManifest refuses negative size, a gap, an overlap and a size-sum m
});
test("validateManifest refuses a size that is not a whole number below 2^53 and a chunk size an int cannot hold, whether decoded or hand-built", () => {
const chunk = (offset: number, sizeBytes: number) => ({ chunkHash: HASH, offset, sizeBytes, recordKey: "k" });
const chunk = (offset: number, sizeBytes: number) => ({ chunkHash: HASH, offset, sizeBytes, recordKey: "k", id: String(offset) });
const refuses = (over: Partial<CultMeshCdnArtifactManifest>, message: string) =>
assert.throws(() => validateManifest(manifestOf(over)), new Error(message));
const manifestMessage = "CDN artifact manifest size is not a whole number below 2^53.";
@ -405,6 +405,23 @@ test("nil in a reference slot reads as null and writes back as nil; a missing tr
assert.deepEqual(short, { artifactId: "id", kind: "asset", version: "", contentHash: "", sizeBytes: 0, mimeType: "application/octet-stream", createdAtUtc: "", chunks: [], tags: [], metadata: [] });
});
test("a chunk reference's id is slot 4: nil reads null and writes nil, an absent slot reads \"\" and is written, packContent writes the decimal offset", async () => {
const chunk = (id: unknown[]) => [HASH, 0, 4, "k", ...id];
const read = (id: unknown[]) => decodeManifest(encode(fieldsOf({ 7: [chunk(id)] }) as unknown[], { useBigInt64: true, maxDepth: 1000 })).chunks[0]!;
const nilled = encode(fieldsOf({ 7: [chunk([null])] }), { useBigInt64: true, maxDepth: 1000 });
const nilManifest = decodeManifest(nilled);
assert.equal(nilManifest.chunks[0]!.id, null);
assert.deepEqual(encodeManifest(nilManifest), nilled);
const absent = decodeManifest(encode(fieldsOf({ 7: [[HASH, 0, 4, "k"]] }), { useBigInt64: true, maxDepth: 1000 }));
assert.equal(absent.chunks[0]!.id, "");
assert.deepEqual(decodeManifest(encodeManifest(absent)).chunks[0], { chunkHash: HASH, offset: 0, sizeBytes: 4, recordKey: "k", id: "" });
assert.equal(read(["7"]).id, "7");
assert.throws(() => read([0]), /./);
const packed = await packContent("x", new Uint8Array(9), { chunkSizeBytes: 4 });
assert.deepEqual(packed.manifest.chunks.map(c => c.id), ["0", "4", "8"]);
assert.deepEqual((await packContent("x", new Uint8Array(0))).manifest.chunks.map(c => c.id), ["0"]);
});
// Refusals that are the same refusal in the reference but would read differently if the wrong rule fired: the message
// names the true cause (the sign, the nil chunk, the reserved code, the early end), never a neighbouring field.
test("a refusal names its true cause", () => {