Store readers: a schema is never recovered from a record's payload
The persistence contract requires the catalog to publish every schema its records name and specifies no recovery, so the catalog is the store's own description: Rust, TypeScript and Python stop inferring a schema name from a payload's first field, as C# never did, and a store naming an unpublished schema is unreadable in all four. missing-schema-versioned-v3 pins it with payloads that open with a schema version. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
91d464a038
commit
3a3de56341
6 changed files with 16 additions and 179 deletions
|
|
@ -217,19 +217,7 @@ def _decode_snapshot(decoded: Any) -> tuple[str, list[CultCacheEnvelope]] | None
|
|||
raise ValueError("CultCache persisted records must declare storedAt")
|
||||
catalog_entry = catalog_by_schema_id.get(schema_id)
|
||||
if catalog_entry is None:
|
||||
schema_version = _infer_schema_version_from_payload(_normalize_payload(payload))
|
||||
schema_name = _infer_schema_name(schema_version) if schema_version is not None else None
|
||||
if schema_name is None:
|
||||
raise ValueError(f'CultCache persisted record "{key}" references missing schema id "{schema_id}"')
|
||||
catalog_entry = CultCacheSchemaCatalogEntry(
|
||||
schema_id=schema_id,
|
||||
schema_name=schema_name,
|
||||
schema_version=schema_version,
|
||||
content_hash=schema_id,
|
||||
canonical_schema_json="",
|
||||
compatible_schema_ids=(),
|
||||
members=(),
|
||||
)
|
||||
raise ValueError(f"CultCache persisted record '{key}' references schema id '{schema_id}', which the store's catalog does not publish")
|
||||
normalized_payload = _normalize_payload(payload)
|
||||
envelopes.append(
|
||||
CultCacheEnvelope(
|
||||
|
|
@ -368,27 +356,3 @@ def _normalize_payload(payload: Any) -> bytes:
|
|||
if isinstance(payload, list) and all(isinstance(item, int) and 0 <= item <= 255 for item in payload):
|
||||
return bytes(payload)
|
||||
raise ValueError("CultCache record payload must be binary MessagePack bytes")
|
||||
|
||||
|
||||
def _infer_schema_version_from_payload(payload: bytes) -> str | None:
|
||||
try:
|
||||
msgpack = SingleFileMessagePackBackingStore._msgpack()
|
||||
decoded = msgpack.unpackb(payload, raw=False)
|
||||
except Exception:
|
||||
return None
|
||||
if isinstance(decoded, list) and decoded and isinstance(decoded[0], str):
|
||||
return decoded[0]
|
||||
if isinstance(decoded, dict):
|
||||
value = decoded.get("schemaVersion", decoded.get("schema_version"))
|
||||
return value if isinstance(value, str) else None
|
||||
return None
|
||||
|
||||
|
||||
def _infer_schema_name(schema_version: str) -> str | None:
|
||||
marker = schema_version.rfind(".v")
|
||||
if marker <= 0:
|
||||
return None
|
||||
version = schema_version[marker + 2:]
|
||||
if not version or not version.isdigit():
|
||||
return None
|
||||
return schema_version[:marker]
|
||||
|
|
|
|||
|
|
@ -2680,29 +2680,11 @@ fn decode_store_snapshot(bytes: &[u8]) -> Result<Vec<CultCacheEnvelope>> {
|
|||
.map(|record| {
|
||||
let r#type = match catalog.get(&record.1) {
|
||||
Some(schema_name) => schema_name.clone(),
|
||||
None => {
|
||||
// A record can outlive its catalog entry when another runtime
|
||||
// wrote it, or when the record is older than the catalog it
|
||||
// was stamped against. The payload is a MessagePack array
|
||||
// whose first field is the schema version, so the type can be
|
||||
// recovered from the record itself rather than failing the
|
||||
// whole snapshot.
|
||||
let schema_version =
|
||||
infer_schema_version_from_payload(&record.3).ok_or_else(|| {
|
||||
anyhow!(
|
||||
"CultCache record {:?} references missing schema {:?}",
|
||||
record.0,
|
||||
record.1
|
||||
)
|
||||
})?;
|
||||
infer_schema_name(&schema_version).ok_or_else(|| {
|
||||
anyhow!(
|
||||
"CultCache record {:?} references missing schema {:?}",
|
||||
record.0,
|
||||
record.1
|
||||
)
|
||||
})?
|
||||
}
|
||||
None => bail!(
|
||||
"CultCache record {:?} references schema {:?}, which the store's catalog does not publish",
|
||||
record.0,
|
||||
record.1
|
||||
),
|
||||
};
|
||||
Ok(CultCacheEnvelope {
|
||||
key: record.0,
|
||||
|
|
@ -2715,9 +2697,8 @@ fn decode_store_snapshot(bytes: &[u8]) -> Result<Vec<CultCacheEnvelope>> {
|
|||
.collect()
|
||||
}
|
||||
|
||||
/// A record recovered from its payload carries a schema name, while the
|
||||
/// registry is keyed by entry type. Accept either, so a snapshot whose catalog
|
||||
/// entry is gone still resolves to the registered definition.
|
||||
/// A record's catalog carries a schema name, while the registry is keyed by
|
||||
/// entry type. Accept either.
|
||||
fn resolve_registered_type(
|
||||
known_types: &BTreeSet<String>,
|
||||
schema_name_definitions: &BTreeMap<String, String>,
|
||||
|
|
@ -2730,68 +2711,6 @@ fn resolve_registered_type(
|
|||
schema_name_definitions.get(persisted_type).cloned()
|
||||
}
|
||||
|
||||
fn infer_schema_version_from_payload(payload: &[u8]) -> Option<String> {
|
||||
let mut offset = 0usize;
|
||||
read_array_header(payload, &mut offset)?;
|
||||
read_string(payload, &mut offset)
|
||||
}
|
||||
|
||||
fn read_array_header(payload: &[u8], offset: &mut usize) -> Option<u32> {
|
||||
let marker = *payload.get(*offset)?;
|
||||
*offset += 1;
|
||||
match marker {
|
||||
0x90..=0x9f => Some((marker & 0x0f) as u32),
|
||||
0xdc => {
|
||||
let bytes = payload.get(*offset..(*offset + 2))?;
|
||||
*offset += 2;
|
||||
Some(u16::from_be_bytes([bytes[0], bytes[1]]) as u32)
|
||||
}
|
||||
0xdd => {
|
||||
let bytes = payload.get(*offset..(*offset + 4))?;
|
||||
*offset += 4;
|
||||
Some(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_string(payload: &[u8], offset: &mut usize) -> Option<String> {
|
||||
let marker = *payload.get(*offset)?;
|
||||
*offset += 1;
|
||||
let length = match marker {
|
||||
0xa0..=0xbf => (marker & 0x1f) as usize,
|
||||
0xd9 => {
|
||||
let length = *payload.get(*offset)? as usize;
|
||||
*offset += 1;
|
||||
length
|
||||
}
|
||||
0xda => {
|
||||
let bytes = payload.get(*offset..(*offset + 2))?;
|
||||
*offset += 2;
|
||||
u16::from_be_bytes([bytes[0], bytes[1]]) as usize
|
||||
}
|
||||
0xdb => {
|
||||
let bytes = payload.get(*offset..(*offset + 4))?;
|
||||
*offset += 4;
|
||||
u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let bytes = payload.get(*offset..(*offset + length))?;
|
||||
std::str::from_utf8(bytes).ok().map(str::to_string)
|
||||
}
|
||||
|
||||
fn infer_schema_name(schema_version: &str) -> Option<String> {
|
||||
let marker = schema_version.rfind(".v")?;
|
||||
let version = schema_version.get((marker + 2)..)?;
|
||||
if marker == 0 || version.is_empty() || !version.bytes().all(|value| value.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(schema_version[..marker].to_string())
|
||||
}
|
||||
|
||||
fn escape_json_string(value: &str) -> String {
|
||||
value.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -280,7 +280,7 @@ function decodeStoreFile(data: Uint8Array): DiskStore {
|
|||
const snapshot = decodeSnapshot(decoded);
|
||||
if (snapshot) {
|
||||
const envelopes = snapshot.records.map((record): CultCacheEnvelope => {
|
||||
const catalogEntry = resolveCatalogEntryForRecord(record, snapshot.catalogBySchemaId);
|
||||
const catalogEntry = snapshot.catalogBySchemaId.get(record.schemaId);
|
||||
if (!catalogEntry) {
|
||||
throw new Error(`CultCache persisted record "${record.key}" references missing schema id "${record.schemaId}".`);
|
||||
}
|
||||
|
|
@ -342,59 +342,6 @@ function decodeSnapshot(decoded: unknown): DecodedSnapshot | undefined {
|
|||
return { format: decoded[0], catalogBySchemaId, records };
|
||||
}
|
||||
|
||||
function resolveCatalogEntryForRecord(
|
||||
record: PersistedRecord,
|
||||
catalogBySchemaId: Map<string, CultCacheSchemaCatalogEntry>,
|
||||
): CultCacheSchemaCatalogEntry | undefined {
|
||||
const existing = catalogBySchemaId.get(record.schemaId);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const schemaVersion = inferSchemaVersionFromPayload(record.payload);
|
||||
if (!schemaVersion) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const schemaName = inferSchemaName(schemaVersion);
|
||||
if (!schemaName) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
schemaId: record.schemaId,
|
||||
schemaName,
|
||||
schemaVersion,
|
||||
contentHash: record.schemaId,
|
||||
canonicalSchemaJson: "",
|
||||
compatibleSchemaIds: [],
|
||||
members: [],
|
||||
};
|
||||
}
|
||||
|
||||
function inferSchemaVersionFromPayload(payload: Uint8Array): string | undefined {
|
||||
try {
|
||||
const decoded = decode(payload);
|
||||
if (Array.isArray(decoded) && typeof decoded[0] === "string") {
|
||||
return decoded[0];
|
||||
}
|
||||
|
||||
if (isObject(decoded)) {
|
||||
const schemaVersion = decoded.schemaVersion ?? decoded.schema_version;
|
||||
return typeof schemaVersion === "string" ? schemaVersion : undefined;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function inferSchemaName(schemaVersion: string): string | undefined {
|
||||
const match = /^(.*)\.v\d+$/.exec(schemaVersion);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
function decodeCatalogEntry(value: unknown): CultCacheSchemaCatalogEntry {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new Error("CultCache schema catalog entries must be MessagePack arrays.");
|
||||
|
|
|
|||
|
|
@ -118,6 +118,10 @@ These are store-level bookkeeping fields, not per-record domain metadata.
|
|||
The store must embed a catalog entry for every schema referenced by the records
|
||||
it contains.
|
||||
|
||||
A reader never recovers a schema from a record's payload: a record whose schema id the
|
||||
catalog does not publish (by id or as a compatible id) makes the store unreadable, whatever
|
||||
the payload's first field says. The catalog is the store's own description of itself.
|
||||
|
||||
This is not decorative paperwork. It is what allows another CultCache
|
||||
implementation to inspect an old store, resolve the schema for each record, and
|
||||
decide whether it can:
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ vectors = {
|
|||
"header-only-v3": pack(["cultcache.store.v3"]),
|
||||
# v3-base with its schema catalog emptied: every record names a schema the store does not publish.
|
||||
"missing-schema-v3": pack([base[0], [], base[2]]),
|
||||
# The same, with each payload opening with its schema version: no runtime recovers a schema from a payload.
|
||||
"missing-schema-versioned-v3": pack([base[0], [], [record[:3] + [pack(["vectors.item.v1", "n", 1])] for record in base[2]]]),
|
||||
# v3-base plus a variant of alpha: a fifth record slot, [baseKey, overrides[]], over an empty payload, overriding the name. Only C# reads it.
|
||||
"variant-slot-v3": pack([base[0], base[1], base[2] + [["gamma"] + base[2][0][1:3] + [b"", ["alpha", [[0, [[0, ""]], "", "gamma"]]]]]]),
|
||||
# v3-base with a fourth top-level slot after the records.
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
“²cultcache.store.v3<76>’”¥alpha¬vectors.item¹2026-09-29T00:00:00+00:00Ä“¯vectors.item.v1¡n”¤beta¬vectors.item¹2026-09-29T00:00:01+00:00Ä“¯vectors.item.v1¡n
|
||||
Loading…
Reference in a new issue