cultnet-rs: retire the dynamic document lane; every received byte decodes once through the door

Deletes CultNetDocumentRecord, the DocumentPut and SnapshotResponse variants,
parse_cultnet_message, require_typed, round_trip_typed, the eight replication
functions and the two catalog schemas (parked at tag
parked/cultnet-rs-dynamic-document-lane). decode_cultnet_message_from_slice is
the one decode; raw v1 rows, identity credentials and the signed-record readers
decode through cultcache_rs::decode_payload. Adds tests/decode_door.rs. 0.2.0.

Not yet compiled at this commit (verification runs on Yggdrasil).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-16 00:33:31 +02:00
commit bdae8b831a
14 changed files with 425 additions and 432 deletions

View file

@ -213,7 +213,7 @@ dependencies = [
[[package]]
name = "cultnet-rs"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"aes-gcm",
"anyhow",

View file

@ -1,6 +1,6 @@
[package]
name = "cultnet-rs"
version = "0.1.0"
version = "0.2.0"
edition = "2024"
publish = false
license = "MIT"

View file

@ -164,7 +164,7 @@ cadence and flushes changed state back through the typed cache. `update(...)`,
wants a more explicit Rust shape.
When a canonical document put arrives while local state is dirty,
`apply_document_put_message(...)` or `apply_raw_document_put_message(...)`
`apply_raw_document_put_message(...)`
records a `CultNetReactiveDocumentReconciliation`: the canonical value, the
predicted local value, and a delta that can be smoothed by the caller. CultCache
payloads serialize by numeric field slot, so Rust tuple-backed deltas use slot

View file

@ -1,19 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.document-put.schema.json",
"title": "CultNet Document Put Message",
"type": "object",
"required": [
"schemaVersion",
"messageId",
"document"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.document_put.v0" },
"messageId": { "type": "string", "minLength": 1 },
"document": {
"$ref": "./cultnet.document-record.schema.json"
}
}
}

View file

@ -1,22 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.snapshot-response.schema.json",
"title": "CultNet Snapshot Response Message",
"type": "object",
"required": [
"schemaVersion",
"messageId",
"documents"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.snapshot_response.v0" },
"messageId": { "type": "string", "minLength": 1 },
"documents": {
"type": "array",
"items": {
"$ref": "./cultnet.document-record.schema.json"
}
}
}
}

View file

@ -4,7 +4,6 @@ use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use crate::{Edge, RawDocumentHeader, Selection, SelectionDocumentRecord};
@ -30,23 +29,6 @@ pub enum CultNetRawPayloadEncoding {
Messagepack,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CultNetDocumentRecord<TPayload = Value> {
pub schema_id: String,
pub record_key: String,
pub stored_at: String,
pub payload: TPayload,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_runtime_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_agent_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_role: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CultNetDocumentOperation {
@ -357,7 +339,7 @@ pub enum CultNetMessage {
// `cultnet.schema.v0` path (parse_raw_cultnet_schema_message/encode_raw_cultnet_schema_message)
// like the other messages that need exact wire control, not through this derive - the derive
// attributes below exist only so the enum as a whole still compiles and round-trips through the
// generic `serde_json::Value` path other tooling may still reach for.
// generic variants, which decode through the door from the message bytes.
#[serde(rename = "cultnet.error.v0", rename_all = "camelCase")]
Error {
error: String,
@ -370,11 +352,6 @@ pub enum CultNetMessage {
SampleChangeName { name: String },
#[serde(rename = "cultnet.sample.chat.v0", rename_all = "camelCase")]
SampleChat { text: String },
#[serde(rename = "cultnet.document_put.v0", rename_all = "camelCase")]
DocumentPut {
message_id: String,
document: CultNetDocumentRecord<Value>,
},
#[serde(rename = "cultnet.document_delete.v0", rename_all = "camelCase")]
DocumentDelete {
message_id: String,
@ -394,11 +371,6 @@ pub enum CultNetMessage {
#[serde(default, skip_serializing_if = "Option::is_none")]
record_keys: Option<Vec<String>>,
},
#[serde(rename = "cultnet.snapshot_response.v0", rename_all = "camelCase")]
SnapshotResponse {
message_id: String,
documents: Vec<CultNetDocumentRecord<Value>>,
},
#[serde(rename = "cultnet.snapshot_response_raw.v0", rename_all = "camelCase")]
SnapshotResponseRaw {
message_id: String,
@ -544,33 +516,6 @@ fn true_default() -> bool {
true
}
pub fn parse_cultnet_message(
wire_value: &rmpv::Value,
contract: CultNetWireContract,
) -> Result<CultNetMessage> {
match contract {
CultNetWireContract::CultNetSchemaV0 => {
let message = match schema_version_from_wire_value(wire_value)? {
Some(
"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)?,
_ => {
let json_value: Value = rmp_serde::from_slice(&rmp_serde::to_vec(wire_value)?)?;
serde_json::from_value(json_value)?
}
};
validate_message(&message)?;
Ok(message)
}
CultNetWireContract::GameCultNetworkingV0 => parse_gamecult_networking_message(wire_value),
}
}
pub fn encode_cultnet_message_for_wire(
message: &CultNetMessage,
contract: CultNetWireContract,
@ -584,7 +529,7 @@ pub fn encode_cultnet_message_for_wire(
| CultNetMessage::ContentChunkRequest { .. }
| CultNetMessage::ContentChunkResponse { .. }
| CultNetMessage::Error { .. } => encode_raw_cultnet_schema_message(message),
_ => Ok(rmp_serde::from_slice(&rmp_serde::to_vec(
_ => Ok(cultcache_rs::decode_payload(&rmp_serde::to_vec(
&serde_json::to_value(message)?,
)?)?),
},
@ -605,7 +550,24 @@ pub fn decode_cultnet_message_from_slice(
contract: CultNetWireContract,
) -> Result<CultNetMessage> {
let wire_value: rmpv::Value = cultcache_rs::decode_payload(bytes)?;
parse_cultnet_message(&wire_value, contract)
match contract {
CultNetWireContract::CultNetSchemaV0 => {
let message = match schema_version_from_wire_value(&wire_value)? {
Some(
"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(bytes, &wire_value)?,
_ => cultcache_rs::decode_payload::<CultNetMessage>(bytes)?,
};
validate_message(&message)?;
Ok(message)
}
CultNetWireContract::GameCultNetworkingV0 => parse_gamecult_networking_message(&wire_value),
}
}
fn validate_message(message: &CultNetMessage) -> Result<()> {
@ -669,13 +631,6 @@ fn validate_message(message: &CultNetMessage) -> Result<()> {
CultNetMessage::Error { error, code: _, details: _ } => require_non_empty(error, "error")?,
CultNetMessage::SampleChangeName { name } => require_non_empty(name, "name")?,
CultNetMessage::SampleChat { text } => require_non_empty(text, "text")?,
CultNetMessage::DocumentPut {
message_id,
document,
} => {
require_non_empty(message_id, "messageId")?;
validate_document_record(document)?;
}
CultNetMessage::DocumentDelete {
message_id,
schema_id,
@ -701,15 +656,6 @@ fn validate_message(message: &CultNetMessage) -> Result<()> {
require_optional_string_vec(schema_ids.as_deref(), "schemaIds")?;
require_optional_string_vec(record_keys.as_deref(), "recordKeys")?;
}
CultNetMessage::SnapshotResponse {
message_id,
documents,
} => {
require_non_empty(message_id, "messageId")?;
for document in documents {
validate_document_record(document)?;
}
}
CultNetMessage::SnapshotResponseRaw {
message_id,
documents,
@ -874,17 +820,6 @@ fn validate_mutation_contract(contract: &CultNetDocumentMutationContract) -> Res
Ok(())
}
fn validate_document_record(document: &CultNetDocumentRecord<Value>) -> Result<()> {
require_non_empty(&document.schema_id, "schemaId")?;
require_non_empty(&document.record_key, "recordKey")?;
require_non_empty(&document.stored_at, "storedAt")?;
require_optional_non_empty(document.source_runtime_id.as_deref(), "sourceRuntimeId")?;
require_optional_non_empty(document.source_agent_id.as_deref(), "sourceAgentId")?;
require_optional_non_empty(document.source_role.as_deref(), "sourceRole")?;
require_optional_string_vec(document.tags.as_deref(), "tags")?;
Ok(())
}
fn validate_raw_document_record(document: &CultNetRawDocumentRecord) -> Result<()> {
require_non_empty(&document.schema_id, "schemaId")?;
require_non_empty(&document.record_key, "recordKey")?;
@ -976,7 +911,21 @@ fn schema_version_from_wire_value(input: &rmpv::Value) -> Result<Option<&str>> {
}))
}
fn parse_raw_cultnet_schema_message(input: &rmpv::Value) -> Result<CultNetMessage> {
/// The row arrays of `cultnet.snapshot_response_raw.v1`, decoded from the original bytes so each
/// row is typed in one pass through the door; nil and absent both read as `None`, other keys are
/// ignored.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SnapshotResponseRawV1Rows {
#[serde(default)]
headers: Option<Vec<RawDocumentHeader>>,
#[serde(default)]
documents: Option<Vec<SelectionDocumentRecord>>,
#[serde(default)]
edges: Option<Vec<Edge>>,
}
fn parse_raw_cultnet_schema_message(bytes: &[u8], input: &rmpv::Value) -> Result<CultNetMessage> {
let object = input
.as_map()
.ok_or_else(|| anyhow!("cultnet.schema.v0 raw messages must be objects"))?;
@ -1012,51 +961,8 @@ fn parse_raw_cultnet_schema_message(input: &rmpv::Value) -> Result<CultNetMessag
})
}
"cultnet.snapshot_response_raw.v1" => {
let headers = get("headers")
.filter(|value| !value.is_nil())
.map(|value| {
value
.as_array()
.ok_or_else(|| anyhow!("headers must be an array"))?
.iter()
.enumerate()
.map(|(index, value)| {
require_typed::<RawDocumentHeader>(Some(value), &format!("headers[{index}]"))
})
.collect::<Result<Vec<_>>>()
})
.transpose()?;
let documents = get("documents")
.filter(|value| !value.is_nil())
.map(|value| {
value
.as_array()
.ok_or_else(|| anyhow!("documents must be an array"))?
.iter()
.enumerate()
.map(|(index, value)| {
require_typed::<SelectionDocumentRecord>(
Some(value),
&format!("documents[{index}]"),
)
})
.collect::<Result<Vec<_>>>()
})
.transpose()?;
let edges = get("edges")
.filter(|value| !value.is_nil())
.map(|value| {
value
.as_array()
.ok_or_else(|| anyhow!("edges must be an array"))?
.iter()
.enumerate()
.map(|(index, value)| {
require_typed::<Edge>(Some(value), &format!("edges[{index}]"))
})
.collect::<Result<Vec<_>>>()
})
.transpose()?;
let SnapshotResponseRawV1Rows { headers, documents, edges } =
cultcache_rs::decode_payload(bytes).map_err(|err| anyhow!("rows: {err}"))?;
Ok(CultNetMessage::SnapshotResponseRawV1 {
message_id: require_legacy_string(get("messageId"), "messageId")?,
@ -1469,34 +1375,16 @@ fn encode_raw_document_record(document: &CultNetRawDocumentRecord) -> rmpv::Valu
])
}
// R-M: `SelectionDocumentRecord`, `RawDocumentHeader`, `Edge` and `RecordRef` already derive
// `Serialize`/`Deserialize` (selection.rs) with the same camelCase field names this hand-written
// codec used to spell out by hand - about 335 lines duplicating what those derives already do.
//
// `rmpv::ext::to_value`/`from_value` looked like the natural generic bridge, but they serialize a
// struct positionally (`serialize_struct` as a MessagePack array, one slot per field in
// declaration order, breaking as soon as a `skip_serializing_if` field is actually skipped) -
// wrong for these types twice over: it is not the named-map encoding this wire always uses
// (section 10's rule; `rmp_serde::to_vec_named` elsewhere in this crate), and it does not
// round-trip at all once a field is omitted. These two helpers instead go through
// `rmp_serde::to_vec_named`/`from_slice` (named-map bytes, proven both ways by
// `tests/selection.rs`'s `snapshot_response_raw_v1_round_trips_*` tests) and hand the bytes to
// `rmpv::Value`'s own `Serialize`/`Deserialize` (already used throughout this file, e.g. to decode
// the outer message envelope) to shuttle to/from the `rmpv::Value` tree the rest of this codec
// builds by hand.
fn require_typed<T: serde::de::DeserializeOwned>(
value: Option<&rmpv::Value>,
field_name: &str,
) -> Result<T> {
let value = value.ok_or_else(|| anyhow!("{field_name} is required"))?;
let bytes = rmp_serde::to_vec(value).map_err(|err| anyhow!("{field_name}: {err}"))?;
rmp_serde::from_slice(&bytes).map_err(|err| anyhow!("{field_name}: {err}"))
}
// R-M: `SelectionDocumentRecord`, `RawDocumentHeader`, `Edge` and `RecordRef` derive
// `Serialize`/`Deserialize` (selection.rs) with the camelCase field names this wire uses.
// `encode_typed` goes through `rmp_serde::to_vec_named` (the named-map encoding this wire always
// uses; `rmpv::ext::to_value` would write a struct positionally) and reads the bytes back into the
// `rmpv::Value` tree the rest of this codec builds by hand, through the decode door. Received rows
// are never re-encoded to become typed: `SnapshotResponseRawV1Rows` reads them from the original bytes.
fn encode_typed<T: Serialize>(value: &T) -> rmpv::Value {
let bytes = rmp_serde::to_vec_named(value).expect("selection wire types always encode to MessagePack");
rmp_serde::from_slice(&bytes).expect("named-map MessagePack bytes always decode into rmpv::Value")
cultcache_rs::decode_payload(&bytes).expect("named-map MessagePack bytes always decode into rmpv::Value")
}
fn require_legacy_u32(value: Option<&rmpv::Value>, field_name: &str) -> Result<u32> {

View file

@ -68,7 +68,7 @@ impl IdunnLifecycleBrakeRecord {
if messagepack_array_len(payload) != Some(9) {
bail!("lifecycle brake is not the 9-field positional contract");
}
let value: Self = rmp_serde::from_slice(payload)?;
let value: Self = cultcache_rs::decode_payload(payload)?;
value.validate()?;
if rmp_serde::to_vec(&value)? != payload {
bail!("lifecycle brake encoding is not canonical");

View file

@ -123,7 +123,7 @@ impl IdunnSignedDaemonHealthRecord {
pub fn decode_canonical_signed_payload(payload: &[u8]) -> Result<(Self, Vec<u8>)> {
match messagepack_array_len(payload) {
Some(18) => {
let statement: Self = rmp_serde::from_slice(payload)
let statement: Self = cultcache_rs::decode_payload(payload)
.context("decoding generic signed daemon health")?;
if rmp_serde::to_vec(&statement)? != payload {
bail!("signed daemon health payload is not canonical positional MessagePack");
@ -133,7 +133,7 @@ impl IdunnSignedDaemonHealthRecord {
Ok((statement, rmp_serde::to_vec(&unsigned)?))
}
Some(17) => {
let legacy: LegacyIdunnSignedDaemonHealthWire = rmp_serde::from_slice(payload)
let legacy: LegacyIdunnSignedDaemonHealthWire = cultcache_rs::decode_payload(payload)
.context("decoding legacy generic signed daemon health")?;
if rmp_serde::to_vec(&legacy)? != payload {
bail!("signed daemon health payload is not canonical positional MessagePack");

View file

@ -18,7 +18,6 @@ use std::thread::JoinHandle;
use std::time::Duration;
use crate::CultNetDocumentMutationContract;
use crate::CultNetDocumentRecord;
use crate::CultNetMessage;
use crate::CultNetRawDocumentRecord;
use crate::CultNetRawPayloadEncoding;
@ -152,33 +151,6 @@ impl CultNetDocumentRegistry {
.collect()
}
pub fn create_document_put_message<T>(
&self,
message_id: impl Into<String>,
record_key: impl Into<String>,
value: &T,
options: CultNetDocumentPutOptions,
) -> Result<CultNetMessage>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let binding = self.require_binding(T::TYPE)?;
let payload = serde_json::to_value(round_trip_typed(value)?)?;
Ok(CultNetMessage::DocumentPut {
message_id: message_id.into(),
document: CultNetDocumentRecord {
schema_id: binding.schema_id.clone(),
record_key: record_key.into(),
stored_at: options.stored_at.unwrap_or_else(now_utc_second),
payload,
source_runtime_id: options.source_runtime_id,
source_agent_id: options.source_agent_id,
source_role: options.source_role,
tags: options.tags,
},
})
}
pub fn create_document_delete_message(
&self,
message_id: impl Into<String>,
@ -230,38 +202,6 @@ impl CultNetDocumentRegistry {
})
}
pub fn create_snapshot_response(
&self,
cache: &CultCache,
message_id: impl Into<String>,
schema_ids: Option<&[String]>,
record_keys: Option<&[String]>,
) -> Result<CultNetMessage> {
let requested_schema_ids = schema_ids.map(|items| items.iter().collect::<BTreeSet<_>>());
let requested_record_keys = record_keys.map(|items| items.iter().collect::<BTreeSet<_>>());
let mut documents = Vec::new();
for envelope in cache.snapshot() {
let binding = self.require_binding(&envelope.r#type)?;
if requested_schema_ids
.as_ref()
.is_some_and(|ids| !ids.contains(&binding.schema_id))
{
continue;
}
if requested_record_keys
.as_ref()
.is_some_and(|keys| !keys.contains(&envelope.key))
{
continue;
}
documents.push(self.document_record_from_envelope(&envelope)?);
}
Ok(CultNetMessage::SnapshotResponse {
message_id: message_id.into(),
documents,
})
}
pub fn create_raw_snapshot_response(
&self,
cache: &CultCache,
@ -294,36 +234,6 @@ impl CultNetDocumentRegistry {
})
}
pub fn apply_document_put_message<T>(
&self,
cache: &mut CultCache,
message: &CultNetMessage,
) -> Result<T>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let CultNetMessage::DocumentPut { document, .. } = message else {
return Err(anyhow!("expected cultnet.document_put.v0"));
};
let binding = self.require_binding(T::TYPE)?;
if document.schema_id != binding.schema_id {
return Err(anyhow!(
"schema id {:?} does not match registered Rust type {:?} schema {:?}",
document.schema_id,
T::TYPE,
binding.schema_id
));
}
let value: T = serde_json::from_value(document.payload.clone()).with_context(|| {
format!(
"failed to decode CultNet payload schema {:?} as {}",
binding.schema_id,
T::SCHEMA_NAME
)
})?;
cache.put(&document.record_key, &value)
}
pub fn apply_document_delete_message<T>(
&self,
cache: &mut CultCache,
@ -381,68 +291,6 @@ impl CultNetDocumentRegistry {
})
}
pub fn apply_snapshot_response<T>(
&self,
cache: &mut CultCache,
response: &CultNetMessage,
) -> Result<Vec<T>>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let CultNetMessage::SnapshotResponse { documents, .. } = response else {
return Err(anyhow!("expected cultnet.snapshot_response.v0"));
};
let mut applied = Vec::new();
let binding = self.require_binding(T::TYPE)?;
for document in documents {
if document.schema_id != binding.schema_id {
continue;
}
applied.push(self.apply_document_put_message::<T>(
cache,
&CultNetMessage::DocumentPut {
message_id: "snapshot-apply".to_string(),
document: document.clone(),
},
)?);
}
Ok(applied)
}
pub fn sync_document_from_snapshot_response<T>(
&self,
cache: &mut CultCache,
response: &CultNetMessage,
record_key: &str,
) -> Result<T>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let CultNetMessage::SnapshotResponse { documents, .. } = response else {
return Err(anyhow!("expected cultnet.snapshot_response.v0"));
};
let binding = self.require_binding(T::TYPE)?;
let document = documents
.iter()
.find(|document| {
document.schema_id == binding.schema_id && document.record_key == record_key
})
.ok_or_else(|| {
anyhow!(
"No CultNet snapshot document for schema {:?} and record key {:?}",
binding.schema_id,
record_key
)
})?;
self.apply_document_put_message::<T>(
cache,
&CultNetMessage::DocumentPut {
message_id: "snapshot-sync".to_string(),
document: document.clone(),
},
)
}
pub fn apply_raw_snapshot_response<T>(
&self,
cache: &mut CultCache,
@ -517,29 +365,6 @@ impl CultNetDocumentRegistry {
CultNetReactiveDocument::new(self.clone(), cache, record_key, options)
}
fn document_record_from_envelope(
&self,
envelope: &CultCacheEnvelope,
) -> Result<CultNetDocumentRecord<Value>> {
let binding = self.require_binding(&envelope.r#type)?;
let payload: Value = cultcache_rs::decode_payload(&envelope.payload).with_context(|| {
format!(
"failed to decode CultCache envelope {:?} at {:?} as generic CultNet payload",
envelope.r#type, envelope.key
)
})?;
Ok(CultNetDocumentRecord {
schema_id: binding.schema_id.clone(),
record_key: envelope.key.clone(),
stored_at: envelope.stored_at.clone(),
payload,
source_runtime_id: None,
source_agent_id: None,
source_role: None,
tags: None,
})
}
pub fn raw_document_record_from_envelope(
&self,
envelope: &CultCacheEnvelope,
@ -732,18 +557,6 @@ where
flush_reactive_document::<T>(&self.cache, &self.current, &self.state, &self.record_key)
}
pub fn apply_document_put_message(&self, message: &CultNetMessage) -> Result<T> {
let canonical = {
let mut cache = self
.cache
.lock()
.map_err(|_| anyhow!("CultCache mutex poisoned"))?;
self.registry
.apply_document_put_message::<T>(&mut cache, message)?
};
self.apply_canonical_value(canonical)
}
pub fn apply_raw_document_put_message(&self, message: &CultNetMessage) -> Result<T> {
let canonical = {
let mut cache = self
@ -1002,13 +815,6 @@ fn numeric_delta(predicted: &Value, canonical: &Value) -> Option<Value> {
serde_json::Number::from_f64(predicted - canonical).map(Value::Number)
}
fn round_trip_typed<T>(value: &T) -> Result<T>
where
T: Serialize + DeserializeOwned,
{
Ok(rmp_serde::from_slice(&rmp_serde::to_vec(value)?)?)
}
fn now_utc_second() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

View file

@ -390,7 +390,7 @@ impl IdunnExpectedIncarnationRecord {
bail!("expected incarnation is not the 18-field positional contract");
}
let expected: Self =
rmp_serde::from_slice(payload).context("decoding expected incarnation")?;
cultcache_rs::decode_payload(payload).context("decoding expected incarnation")?;
if rmp_serde::to_vec(&expected)? != payload {
bail!("expected incarnation is not canonical positional MessagePack");
}
@ -629,7 +629,7 @@ impl OdinRuntimeTopologyCorrelationRecord {
bail!("topology correlation is not the 21-field positional contract");
}
let receipt: Self =
rmp_serde::from_slice(payload).context("decoding runtime topology correlation")?;
cultcache_rs::decode_payload(payload).context("decoding runtime topology correlation")?;
if rmp_serde::to_vec(&receipt)? != payload {
bail!("topology correlation is not canonical positional MessagePack");
}
@ -1173,7 +1173,7 @@ pub fn authenticate_runtime_presence_claim(
bail!("runtime presence payload is not the 24-field positional contract");
}
let presence: GameCultRuntimePresenceHealthRecord =
rmp_serde::from_slice(canonical_presence).context("decoding runtime presence health")?;
cultcache_rs::decode_payload(canonical_presence).context("decoding runtime presence health")?;
if rmp_serde::to_vec(&presence)? != canonical_presence {
bail!("runtime presence payload is not canonical positional MessagePack");
}
@ -1470,7 +1470,7 @@ impl IdunnRuntimeActivationRecord {
bail!("runtime activation is not the 10-field positional contract");
}
let activation: Self =
rmp_serde::from_slice(payload).context("decoding runtime activation")?;
cultcache_rs::decode_payload(payload).context("decoding runtime activation")?;
if rmp_serde::to_vec(&activation)? != payload {
bail!("runtime activation is not canonical positional MessagePack");
}
@ -1604,7 +1604,7 @@ impl IdunnProcessWriteLeaseRecord {
if messagepack_array_len(payload) != Some(14) {
bail!("process write lease is not the 14-field positional contract");
}
let lease: Self = rmp_serde::from_slice(payload).context("decoding process write lease")?;
let lease: Self = cultcache_rs::decode_payload(payload).context("decoding process write lease")?;
if rmp_serde::to_vec(&lease)? != payload {
bail!("process write lease is not canonical positional MessagePack");
}

View file

@ -284,13 +284,6 @@ pub fn builtin_schema_registry() -> Result<CultNetSchemaRegistry> {
Some("cultnet.sample.chat.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet/cultnet.document-put.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.document_put.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet/cultnet.document-delete.schema.json"),
CultNetSchemaKind::WireMessage,
@ -319,13 +312,6 @@ pub fn builtin_schema_registry() -> Result<CultNetSchemaRegistry> {
Some("cultnet.snapshot_request.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet/cultnet.snapshot-response.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.snapshot_response.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet/cultnet.snapshot-response-raw.schema.json"),
CultNetSchemaKind::WireMessage,

View file

@ -285,11 +285,10 @@ pub fn open_service_identity_credential_reader<P: ServiceIdentityProfile>(
pub fn open_service_identity_credential_bytes<P: ServiceIdentityProfile>(
bytes: &[u8],
) -> Result<ServiceIdentitySigner<P>> {
let mut decoder = rmp_serde::Deserializer::new(std::io::Cursor::new(bytes));
let entries = Vec::<CultCacheEnvelope>::deserialize(&mut decoder)
let entries = cultcache_rs::decode_payload::<Vec<CultCacheEnvelope>>(bytes)
.context("immutable service identity credential is malformed MessagePack")?;
if decoder.position() != bytes.len() as u64 {
bail!("immutable service identity credential contains trailing data");
if Zeroizing::new(rmp_serde::to_vec(&entries)?).as_slice() != bytes {
bail!("immutable service identity credential is not its canonical encoding");
}
open_service_identity_envelopes::<P>(&entries)
}

View file

@ -1780,7 +1780,7 @@ fn document_registry_advertises_mutation_contracts_with_bindings() -> Result<()>
}
#[test]
fn a_stored_payload_nested_past_the_bound_is_not_replicated_as_a_document() -> Result<()> {
fn a_replicated_payload_nested_past_the_bound_is_refused_typed_on_apply() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("foreign.msgpack");
let limit = cultcache_rs::MAX_PAYLOAD_DEPTH;
@ -1803,9 +1803,10 @@ fn a_stored_payload_nested_past_the_bound_is_not_replicated_as_a_document() -> R
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store))?;
cache.pull_all_backing_stores()?;
let at_limit = registry.create_snapshot_response(&cache, "at", None, None)?;
let CultNetMessage::SnapshotResponse { documents, .. } = at_limit else {
panic!("expected a snapshot response");
// The raw lane copies payload bytes without decoding; the receiver's apply is the door.
let at_limit = registry.create_raw_snapshot_response(&cache, "at", None, None)?;
let CultNetMessage::SnapshotResponseRaw { documents, .. } = &at_limit else {
panic!("expected a raw snapshot response");
};
assert_eq!(documents.len(), 1);
@ -1814,7 +1815,12 @@ fn a_stored_payload_nested_past_the_bound_is_not_replicated_as_a_document() -> R
cache.register_entry_type::<GhostlightAgentStateFixture>()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store))?;
cache.pull_all_backing_stores()?;
let error = registry.create_snapshot_response(&cache, "past", None, None).unwrap_err();
let past = registry.create_raw_snapshot_response(&cache, "past", None, Some(&["past".to_string()]))?;
let mut target = CultCache::new();
target.register_entry_type::<GhostlightAgentStateFixture>()?;
let error = registry
.apply_raw_snapshot_response::<GhostlightAgentStateFixture>(&mut target, &past)
.unwrap_err();
assert_eq!(
error.downcast_ref::<cultcache_rs::PayloadTooDeep>(),
Some(&cultcache_rs::PayloadTooDeep { depth: limit + 1, limit })
@ -1844,15 +1850,15 @@ fn document_registry_replicates_typed_cultcache_state() -> Result<()> {
origin.pull_all_backing_stores()?;
origin.put("epiphany.persona", &payload)?;
let snapshot = registry.create_snapshot_response(&origin, "snapshot-1", None, None)?;
let snapshot = registry.create_raw_snapshot_response(&origin, "snapshot-1", None, None)?;
let mut target = CultCache::new();
target.register_entry_type::<GhostlightAgentStateFixture>()?;
target.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store))?;
target.pull_all_backing_stores()?;
let applied =
registry.apply_snapshot_response::<GhostlightAgentStateFixture>(&mut target, &snapshot)?;
let synced = registry.sync_document_from_snapshot_response::<GhostlightAgentStateFixture>(
registry.apply_raw_snapshot_response::<GhostlightAgentStateFixture>(&mut target, &snapshot)?;
let synced = registry.sync_raw_document_from_snapshot_response::<GhostlightAgentStateFixture>(
&mut target,
&snapshot,
"epiphany.persona",
@ -1864,7 +1870,7 @@ fn document_registry_replicates_typed_cultcache_state() -> Result<()> {
payload
);
let direct_put = registry.create_document_put_message(
let direct_put = registry.create_raw_document_put_message(
"put-1",
"epiphany.persona",
&GhostlightAgentStateFixture {
@ -1874,7 +1880,7 @@ fn document_registry_replicates_typed_cultcache_state() -> Result<()> {
CultNetDocumentPutOptions::default(),
)?;
let updated = registry
.apply_document_put_message::<GhostlightAgentStateFixture>(&mut target, &direct_put)?;
.apply_raw_document_put_message::<GhostlightAgentStateFixture>(&mut target, &direct_put)?;
assert_eq!(updated.display_name, "Persona Prime");
Ok(())
}
@ -2260,7 +2266,7 @@ fn reactive_document_tracks_canonical_reconciliation_delta() -> Result<()> {
note.body = "local-prediction".to_string();
note.revision = 2;
})?;
let authoritative = registry.create_document_put_message(
let authoritative = registry.create_raw_document_put_message(
"put-authoritative",
"note:reconcile",
&GhostlightReactiveNoteFixture {
@ -2270,7 +2276,7 @@ fn reactive_document_tracks_canonical_reconciliation_delta() -> Result<()> {
CultNetDocumentPutOptions::default(),
)?;
reactive.apply_document_put_message(&authoritative)?;
reactive.apply_raw_document_put_message(&authoritative)?;
let current = reactive.current();
let current = current.lock().expect("reactive current mutex").clone();

View file

@ -0,0 +1,349 @@
//! Every MessagePack byte cultnet-rs receives decodes once through `cultcache_rs::decode_payload`:
//! a message, the row arrays of `snapshot_response_raw.v1`, a raw document payload applied to a cache,
//! and an immutable identity credential. Each test decodes in a child test process on a thread of a
//! stated size, so an abort fails one named test; values are built, encoded and compared on a large
//! thread, and only the decode runs on the small one.
use anyhow::Result;
use cultcache_rs::CultCache;
use cultcache_rs::CultSlots;
use cultcache_rs::DatabaseEntry;
use cultcache_rs::MAX_PAYLOAD_DEPTH;
use cultcache_rs::PayloadTooDeep;
use cultnet_rs::*;
const CHILD_MARKER: &str = "CULTNET_DECODE_DOOR_CHILD";
const SMALL: usize = 256 * 1024;
const BIG: usize = 64 * 1024 * 1024;
/// A five-byte MessagePack string standing where a test wants its nested value spliced in.
const SENTINEL: [u8; 5] = [0xa4, b'D', b'E', b'E', b'P'];
#[derive(Clone, Debug, PartialEq, CultSlots)]
struct Wide32 {
#[cultcache(key = 0)]
a0: [u64; 32],
#[cultcache(key = 1)]
a1: [u64; 32],
#[cultcache(key = 2)]
a2: [u64; 32],
#[cultcache(key = 3)]
a3: [u64; 32],
#[cultcache(key = 4)]
a4: [u64; 32],
#[cultcache(key = 5)]
a5: [u64; 32],
#[cultcache(key = 6)]
a6: [u64; 32],
#[cultcache(key = 7)]
a7: [u64; 32],
#[cultcache(key = 8)]
a8: [u64; 32],
#[cultcache(key = 9)]
a9: [u64; 32],
#[cultcache(key = 10)]
a10: [u64; 32],
#[cultcache(key = 11)]
a11: [u64; 32],
#[cultcache(key = 12)]
a12: [u64; 32],
#[cultcache(key = 13)]
a13: [u64; 32],
#[cultcache(key = 14)]
a14: [u64; 32],
#[cultcache(key = 15)]
a15: [u64; 32],
#[cultcache(key = 16)]
a16: [u64; 32],
#[cultcache(key = 17)]
a17: [u64; 32],
#[cultcache(key = 18)]
a18: [u64; 32],
#[cultcache(key = 19)]
a19: [u64; 32],
#[cultcache(key = 20)]
a20: [u64; 32],
#[cultcache(key = 21)]
a21: [u64; 32],
#[cultcache(key = 22)]
a22: [u64; 32],
#[cultcache(key = 23)]
a23: [u64; 32],
#[cultcache(key = 24)]
a24: [u64; 32],
#[cultcache(key = 25)]
a25: [u64; 32],
#[cultcache(key = 26)]
a26: [u64; 32],
#[cultcache(key = 27)]
a27: [u64; 32],
#[cultcache(key = 28)]
a28: [u64; 32],
#[cultcache(key = 29)]
a29: [u64; 32],
#[cultcache(key = 30)]
a30: [u64; 32],
#[cultcache(key = 31)]
a31: [u64; 32],
#[cultcache(key = 32)]
next: Option<Box<Wide32>>,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "cultnet.decode-door.wide", schema = "DecodeDoorWide")]
struct WideDocument {
#[cultcache(key = 0)]
chain: Wide32,
}
fn on_stack<R: Send + 'static>(bytes: usize, body: impl FnOnce() -> R + Send + 'static) -> R {
std::thread::Builder::new().stack_size(bytes).spawn(body).unwrap().join().unwrap()
}
/// Runs `body` in a child process that runs only the test `name`; the parent passes when the child
/// exits cleanly having run exactly that one test. An abort in the child fails the parent.
fn in_child(name: &str, body: impl FnOnce()) {
if std::env::var_os(CHILD_MARKER).is_some() {
body();
return;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([name, "--exact", "--nocapture", "--test-threads=1"])
.env(CHILD_MARKER, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success() && stdout.contains("1 passed"),
"child {name} failed: {:?}\n{stdout}\n{stderr}",
output.status
);
}
/// `levels` one-element arrays around a nil, from marker bytes: the encoders recurse too.
fn nested(levels: usize) -> Vec<u8> {
let mut bytes = vec![0x91; levels];
bytes.push(0xc0);
bytes
}
/// Swaps the one sentinel string in `bytes` for `with`.
fn splice(bytes: Vec<u8>, with: &[u8]) -> Vec<u8> {
let at = bytes
.windows(SENTINEL.len())
.position(|window| window == SENTINEL)
.expect("sentinel present");
[&bytes[..at], with, &bytes[at + SENTINEL.len()..]].concat()
}
fn map_with_sentinel(mut entries: Vec<(rmpv::Value, rmpv::Value)>) -> Vec<u8> {
entries.push(("x".into(), "DEEP".into()));
rmp_serde::to_vec(&rmpv::Value::Map(entries)).unwrap()
}
fn hello_with(unknown: &[u8]) -> Vec<u8> {
splice(
map_with_sentinel(vec![
("schemaVersion".into(), "cultnet.hello.v0".into()),
("runtimeId".into(), "rt".into()),
("runtimeKind".into(), "test".into()),
]),
unknown,
)
}
fn decode_message(bytes: Vec<u8>, stack: usize) -> Result<CultNetMessage> {
*on_stack(stack, move || {
Box::new(decode_cultnet_message_from_slice(&bytes, CultNetWireContract::CultNetSchemaV0))
})
}
#[test]
fn generic_message_with_deep_unknown_key_decodes_on_a_small_thread() {
in_child("generic_message_with_deep_unknown_key_decodes_on_a_small_thread", || {
let plain = decode_message(hello_with(&nested(0)), SMALL).unwrap();
let deep = decode_message(hello_with(&nested(MAX_PAYLOAD_DEPTH - 2)), SMALL).unwrap();
assert_eq!(deep, plain);
});
}
#[test]
fn message_past_the_bound_is_refused_typed() {
in_child("message_past_the_bound_is_refused_typed", || {
let error = decode_message(hello_with(&nested(MAX_PAYLOAD_DEPTH + 1)), SMALL).unwrap_err();
let refusal = error.downcast_ref::<PayloadTooDeep>().expect("typed refusal");
assert_eq!(refusal.limit, MAX_PAYLOAD_DEPTH);
});
}
fn raw_v1_bytes(header_unknown: Option<&[u8]>) -> Vec<u8> {
let mut header: Vec<(rmpv::Value, rmpv::Value)> = vec![
("schemaId".into(), "s".into()),
("recordKey".into(), "k".into()),
("storedAt".into(), "2026-10-16T00:00:00Z".into()),
];
if header_unknown.is_some() {
header.push(("x".into(), "DEEP".into()));
}
let message = rmpv::Value::Map(vec![
("schemaVersion".into(), "cultnet.snapshot_response_raw.v1".into()),
("messageId".into(), "m".into()),
("matched".into(), 1.into()),
("asOf".into(), 7.into()),
("headers".into(), rmpv::Value::Array(vec![rmpv::Value::Map(header)])),
]);
let bytes = rmp_serde::to_vec(&message).unwrap();
match header_unknown {
Some(nested) => splice(bytes, nested),
None => bytes,
}
}
#[test]
fn raw_v1_rows_with_deep_unknown_key_decode_on_a_small_thread() {
in_child("raw_v1_rows_with_deep_unknown_key_decode_on_a_small_thread", || {
let plain = decode_message(raw_v1_bytes(None), SMALL).unwrap();
// The message map, the headers array and the header map sit above the unknown key.
let deep = decode_message(raw_v1_bytes(Some(&nested(MAX_PAYLOAD_DEPTH - 3))), SMALL).unwrap();
let CultNetMessage::SnapshotResponseRawV1 { headers: Some(rows), .. } = &deep else {
panic!("expected raw v1 rows");
};
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].record_key, "k");
assert_eq!(deep, plain);
});
}
fn wide_chain(levels: usize) -> Wide32 {
let mut chain: Option<Box<Wide32>> = None;
for level in (0..levels).rev() {
let mut node = Wide32 { next: chain, ..empty_wide() };
node.a0[0] = level as u64;
chain = Some(Box::new(node));
}
*chain.unwrap()
}
fn empty_wide() -> Wide32 {
Wide32 {
a0: [0; 32],
a1: [0; 32],
a2: [0; 32],
a3: [0; 32],
a4: [0; 32],
a5: [0; 32],
a6: [0; 32],
a7: [0; 32],
a8: [0; 32],
a9: [0; 32],
a10: [0; 32],
a11: [0; 32],
a12: [0; 32],
a13: [0; 32],
a14: [0; 32],
a15: [0; 32],
a16: [0; 32],
a17: [0; 32],
a18: [0; 32],
a19: [0; 32],
a20: [0; 32],
a21: [0; 32],
a22: [0; 32],
a23: [0; 32],
a24: [0; 32],
a25: [0; 32],
a26: [0; 32],
a27: [0; 32],
a28: [0; 32],
a29: [0; 32],
a30: [0; 32],
a31: [0; 32],
next: None,
}
}
fn registry() -> CultNetDocumentRegistry {
let mut registry = CultNetDocumentRegistry::new();
registry.register(CultNetDocumentBinding::for_entry::<WideDocument>("cultnet.decode-door.wide".to_string()));
registry
}
/// The wire bytes of a raw put of a `levels`-deep Wide32 document, built on a large thread.
fn raw_put_bytes(levels: usize) -> Vec<u8> {
on_stack(BIG, move || {
let document = WideDocument { chain: wide_chain(levels) };
let message = registry()
.create_raw_document_put_message("m", "k", &document, CultNetDocumentPutOptions::default())
.unwrap();
encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0).unwrap()
})
}
/// Receives and applies on the small thread; the applied record is boxed there.
fn receive_and_apply(bytes: Vec<u8>) -> Result<WideDocument> {
*on_stack(SMALL, move || {
Box::new((|| {
let message = decode_cultnet_message_from_slice(&bytes, CultNetWireContract::CultNetSchemaV0)?;
let mut cache = CultCache::new();
cache.register_entry_type::<WideDocument>()?;
registry().apply_raw_document_put_message::<WideDocument>(&mut cache, &message)
})())
})
}
#[test]
fn raw_put_of_a_wide32_chain_applies_on_a_small_thread() {
in_child("raw_put_of_a_wide32_chain_applies_on_a_small_thread", || {
let levels = MAX_PAYLOAD_DEPTH - 2;
let applied = receive_and_apply(raw_put_bytes(levels)).unwrap();
on_stack(BIG, move || assert!(applied.chain == wide_chain(levels)));
let error = receive_and_apply(raw_put_bytes(levels + 1)).unwrap_err();
assert!(error.downcast_ref::<PayloadTooDeep>().is_some(), "typed refusal");
});
}
#[test]
fn retired_dynamic_put_is_refused_typed() {
in_child("retired_dynamic_put_is_refused_typed", || {
let document = rmpv::Value::Map(vec![
("schemaId".into(), "s".into()),
("recordKey".into(), "k".into()),
("storedAt".into(), "2026-10-16T00:00:00Z".into()),
("payload".into(), "DEEP".into()),
]);
let bytes = splice(
rmp_serde::to_vec(&rmpv::Value::Map(vec![
("schemaVersion".into(), "cultnet.document_put.v0".into()),
("messageId".into(), "m".into()),
("document".into(), document),
]))
.unwrap(),
&nested(253),
);
let error = decode_message(bytes, SMALL).unwrap_err();
// The refusal keeps its kind and never quotes the received variant name.
assert!(!format!("{error:#}").contains("document_put"), "{error:#}");
});
}
#[test]
fn identity_credential_with_deep_key_is_refused_on_a_small_thread() {
in_child("identity_credential_with_deep_key_is_refused_on_a_small_thread", || {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("identity.cc");
enroll_service_identity_at::<IdunnServiceIdentity>(&path).unwrap();
let mut envelopes: rmpv::Value = rmp_serde::from_slice(&std::fs::read(path).unwrap()).unwrap();
let rmpv::Value::Map(envelope) = &mut envelopes.as_array_mut().unwrap()[0] else {
panic!("envelope is a map");
};
envelope.push(("zz".into(), "DEEP".into()));
let credential = rmp_serde::to_vec(&envelopes).unwrap();
for levels in [1000, 250] {
let bytes = splice(credential.clone(), &nested(levels));
let refused = on_stack(SMALL, move || {
open_service_identity_credential_bytes::<IdunnServiceIdentity>(&bytes).is_err()
});
assert!(refused, "{levels} levels deep");
}
});
}