From 911c3b8a0eb3995f37d303d08452b46f1b79ba7c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:35:10 +0100 Subject: [PATCH 1/6] cultnet-rs: typed database_change_raw.v0 and database_unsubscribe.v0, and a transport-free SubscriptionAssembler with the C# client's commit bound and fault Co-Authored-By: Claude Sonnet 5.5 --- packages/cultnet-rs/src/contracts.rs | 137 ++++++++ packages/cultnet-rs/src/lib.rs | 2 + packages/cultnet-rs/src/subscription.rs | 239 +++++++++++++ .../tests/database_change_commit_vector.rs | 60 ++-- packages/cultnet-rs/tests/subscription.rs | 320 ++++++++++++++++++ 5 files changed, 734 insertions(+), 24 deletions(-) create mode 100644 packages/cultnet-rs/src/subscription.rs create mode 100644 packages/cultnet-rs/tests/subscription.rs diff --git a/packages/cultnet-rs/src/contracts.rs b/packages/cultnet-rs/src/contracts.rs index bf907806..93190264 100644 --- a/packages/cultnet-rs/src/contracts.rs +++ b/packages/cultnet-rs/src/contracts.rs @@ -440,6 +440,31 @@ pub enum CultNetMessage { #[serde(default, skip_serializing_if = "Option::is_none")] supported_body_transports: Option>, }, + /// Mirrors `CultNetDatabaseUnsubscribeMessage`. + #[serde(rename = "cultnet.database_unsubscribe.v0", rename_all = "camelCase")] + DatabaseUnsubscribe { + message_id: String, + subscription_id: String, + }, + /// One change of a live subscription. Mirrors `CultNetDatabaseChangeRawMessage`: the writer + /// sends every key, nil where unset; the decoder refuses what the reference's receiver + /// refuses (see `validate_message`). + #[serde(rename = "cultnet.database_change_raw.v0", rename_all = "camelCase")] + DatabaseChangeRaw { + message_id: String, + subscription_id: String, + change_kind: DatabaseChangeKind, + #[serde(default)] + document: Option, + #[serde(default)] + record_key: Option, + #[serde(default)] + schema_id: Option, + #[serde(default)] + commit_id: Option, + #[serde(default)] + commit_count: Option, + }, /// `cultnet.snapshot_response_raw.v1` (section 2: `SelectionPage`). Decoded by the derive from /// the message bytes in one pass (rows and scalars, a duplicated key refused); encoded by /// `encode_raw_cultnet_schema_message` for the reference's fixed nil-keyed shape. Mirrors @@ -552,6 +577,25 @@ fn messagepack_base64_encoding() -> String { "messagepack-base64".to_string() } +/// The `changeKind` of a `cultnet.database_change_raw.v0` message. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum DatabaseChangeKind { + Added, + Updated, + Removed, +} + +impl DatabaseChangeKind { + fn wire(self) -> &'static str { + match self { + Self::Added => "added", + Self::Updated => "updated", + Self::Removed => "removed", + } + } +} + fn true_default() -> bool { true } @@ -566,6 +610,8 @@ pub fn encode_cultnet_message_for_wire( CultNetMessage::DocumentPutRaw { .. } | CultNetMessage::SnapshotResponseRaw { .. } | CultNetMessage::SnapshotResponseRawV1 { .. } + | CultNetMessage::DatabaseChangeRaw { .. } + | CultNetMessage::DatabaseUnsubscribe { .. } | CultNetMessage::ContentChunkRequest { .. } | CultNetMessage::ContentChunkResponse { .. } | CultNetMessage::Error { .. } @@ -754,6 +800,60 @@ fn validate_message(message: &CultNetMessage) -> Result<()> { "supportedBodyTransports", )?; } + CultNetMessage::DatabaseUnsubscribe { message_id, subscription_id } => { + require_non_empty(message_id, "messageId")?; + require_non_empty(subscription_id, "subscriptionId")?; + } + CultNetMessage::DatabaseChangeRaw { + message_id, + subscription_id, + change_kind, + document, + record_key, + schema_id, + commit_id, + commit_count, + } => { + require_non_empty(message_id, "messageId")?; + require_non_empty(subscription_id, "subscriptionId")?; + match change_kind { + DatabaseChangeKind::Removed => { + if record_key.as_deref().is_none_or(|key| key.is_empty()) + || schema_id.as_deref().is_none_or(|id| id.is_empty()) + { + return Err(anyhow!( + "CultNet database change 'removed' must carry recordKey and schemaId" + )); + } + } + DatabaseChangeKind::Added | DatabaseChangeKind::Updated => { + if document.is_none() { + return Err(anyhow!( + "CultNet database change '{}' must carry a document", + change_kind.wire() + )); + } + } + } + match (commit_id.as_deref(), commit_count) { + (None, None) => {} + (Some(id), Some(count)) => { + if id.is_empty() { + return Err(anyhow!("CultNet field commitId must be non-empty")); + } + if *count < 2 { + return Err(anyhow!( + "CultNet field commitCount must be at least 2, received {count}" + )); + } + } + _ => { + return Err(anyhow!( + "CultNet fields commitId and commitCount are set together or not at all" + )); + } + } + } CultNetMessage::SnapshotResponseRawV1 { message_id, matched: _, @@ -1286,6 +1386,43 @@ fn encode_raw_cultnet_schema_message(message: &CultNetMessage) -> Result vec![ + (rmpv::Value::from("schemaVersion"), rmpv::Value::from("cultnet.database_unsubscribe.v0")), + (rmpv::Value::from("messageId"), rmpv::Value::from(message_id.as_str())), + (rmpv::Value::from("subscriptionId"), rmpv::Value::from(subscription_id.as_str())), + ], + // The C# writer's key order, every key present, nil where unset. + CultNetMessage::DatabaseChangeRaw { + message_id, + subscription_id, + change_kind, + document, + record_key, + schema_id, + commit_id, + commit_count, + } => { + let text = |value: &Option| { + value.as_deref().map(rmpv::Value::from).unwrap_or(rmpv::Value::Nil) + }; + vec![ + (rmpv::Value::from("schemaVersion"), rmpv::Value::from("cultnet.database_change_raw.v0")), + (rmpv::Value::from("messageId"), rmpv::Value::from(message_id.as_str())), + (rmpv::Value::from("subscriptionId"), rmpv::Value::from(subscription_id.as_str())), + (rmpv::Value::from("changeKind"), rmpv::Value::from(change_kind.wire())), + ( + rmpv::Value::from("document"), + document.as_ref().map(encode_typed).unwrap_or(rmpv::Value::Nil), + ), + (rmpv::Value::from("recordKey"), text(record_key)), + (rmpv::Value::from("schemaId"), text(schema_id)), + (rmpv::Value::from("commitId"), text(commit_id)), + ( + rmpv::Value::from("commitCount"), + commit_count.map(rmpv::Value::from).unwrap_or(rmpv::Value::Nil), + ), + ] + } CultNetMessage::ContentChunkRequest { message_id, chunk_hash, diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index e008a2ba..59a95726 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -21,6 +21,7 @@ mod schema_discovery; mod security; mod selection; mod shard_catalog; +mod subscription; mod transport; pub use content::*; @@ -45,4 +46,5 @@ pub use schema_discovery::*; pub use security::*; pub use selection::*; pub use shard_catalog::*; +pub use subscription::*; pub use transport::*; diff --git a/packages/cultnet-rs/src/subscription.rs b/packages/cultnet-rs/src/subscription.rs new file mode 100644 index 00000000..f429c1e7 --- /dev/null +++ b/packages/cultnet-rs/src/subscription.rs @@ -0,0 +1,239 @@ +//! The subscriber's side of `cultnet.database_subscribe.v1`, with no transport, clock or threads: it is fed decoded +//! messages and returns events. It mirrors `CultNetDatabaseSubscriptionClient.HandleChange` (commit assembly, the +//! buffer bound, the fault) so that a driver cannot decide commit completeness, bounds or fault itself. + +use crate::{CultNetMessage, DatabaseChangeKind, SelectionDocumentRecord}; +use anyhow::{Result, anyhow}; +use std::collections::{HashMap, HashSet}; + +/// The most commits that may be incomplete at once (`MaxPendingCommits` in the C# client). +pub const MAX_PENDING_COMMITS: usize = 64; +/// The most changes the incomplete commits may announce between them (`MaxBufferedChanges` in the C# client). +pub const MAX_BUFFERED_CHANGES: u64 = 1_000_000; + +/// One record change. `record_key` and `schema_id` are the document's for added and updated changes, the message's +/// for removed ones; `document` is `None` for a removal. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Change { + pub kind: DatabaseChangeKind, + pub record_key: String, + pub schema_id: String, + pub document: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SubscriptionEvent { + /// The answer to a subscribe the driver began. + Snapshot { subscription_id: String, documents: Vec }, + /// One change, or every change of one commit in arrival order; a partial commit is never emitted. + Commit { subscription_id: String, changes: Vec }, + /// The connection's replica no longer matches its source. Nothing more is emitted until `reset`. + Faulted { reason: String }, +} + +struct PendingCommit { + announced: u32, + ids: HashSet, + changes: Vec, +} + +#[derive(Default)] +struct Subscription { + snapshotted: bool, + /// Complete commits that arrived before the snapshot, in arrival order. + waiting: Vec>, +} + +/// The one owner of subscription state for a connection. +#[derive(Default)] +pub struct SubscriptionAssembler { + outstanding: HashMap, + subscriptions: HashMap, + commits: HashMap<(String, String), PendingCommit>, + fault: Option, +} + +impl SubscriptionAssembler { + pub fn new() -> Self { + Self::default() + } + + /// Records a subscribe the driver sent. Refused once faulted, and for a message id already outstanding. + pub fn begin(&mut self, subscription_id: &str, message_id: &str) -> Result<()> { + if self.fault.is_some() { + return Err(anyhow!( + "the replica refused a commit and differs from its source; reset before subscribing" + )); + } + if self.outstanding.contains_key(message_id) { + return Err(anyhow!("Duplicate database subscription message id '{message_id}'.")); + } + self.outstanding.insert(message_id.to_owned(), subscription_id.to_owned()); + self.subscriptions.entry(subscription_id.to_owned()).or_default(); + Ok(()) + } + + /// Forgets a subscription and evicts its buffered commits. + pub fn end(&mut self, subscription_id: &str) { + self.subscriptions.remove(subscription_id); + self.outstanding.retain(|_, id| id != subscription_id); + self.commits.retain(|(id, _), _| id != subscription_id); + } + + /// Clears every subscription and the fault. + pub fn reset(&mut self) { + *self = Self::default(); + } + + pub fn fault(&self) -> Option<&str> { + self.fault.as_deref() + } + + /// Feeds one decoded message. Messages that are not a snapshot response or a change (an error, a hello) are + /// not this assembler's and return nothing. + pub fn accept(&mut self, message: CultNetMessage) -> Vec { + if self.fault.is_some() { + return Vec::new(); + } + match message { + CultNetMessage::SnapshotResponseRawV1 { message_id, documents, .. } => { + self.snapshot(&message_id, documents.unwrap_or_default()) + } + CultNetMessage::DatabaseChangeRaw { + message_id, + subscription_id, + change_kind, + document, + record_key, + schema_id, + commit_id, + commit_count, + } => { + let change = Change { + kind: change_kind, + record_key: document + .as_ref() + .map(|document| document.record_key.clone()) + .or(record_key) + .unwrap_or_default(), + schema_id: document + .as_ref() + .map(|document| document.schema_id.clone()) + .or(schema_id) + .unwrap_or_default(), + document, + }; + self.change(message_id, subscription_id, change, commit_id, commit_count) + } + _ => Vec::new(), + } + } + + fn snapshot(&mut self, message_id: &str, documents: Vec) -> Vec { + let Some(subscription_id) = self.outstanding.remove(message_id) else { + return Vec::new(); + }; + let Some(subscription) = self.subscriptions.get_mut(&subscription_id) else { + return Vec::new(); + }; + subscription.snapshotted = true; + let mut events = vec![SubscriptionEvent::Snapshot { subscription_id: subscription_id.clone(), documents }]; + events.extend(subscription.waiting.drain(..).map(|changes| SubscriptionEvent::Commit { + subscription_id: subscription_id.clone(), + changes, + })); + events + } + + fn change( + &mut self, + message_id: String, + subscription_id: String, + change: Change, + commit_id: Option, + commit_count: Option, + ) -> Vec { + // A straggler of a subscription that was ended, or never made, is not buffered. + if !self.subscriptions.contains_key(&subscription_id) { + return Vec::new(); + } + let complete = match (commit_id, commit_count) { + (Some(commit_id), Some(count)) if count > 1 => { + match self.add_to_commit(&subscription_id, commit_id, count, message_id, change) { + Ok(Some(complete)) => complete, + Ok(None) => return Vec::new(), + Err(refusal) => { + return self.fault_with(format!("CultNet subscription '{subscription_id}': {refusal}.")); + } + } + } + _ => vec![change], + }; + let subscription = self.subscriptions.get_mut(&subscription_id).expect("checked live above"); + if subscription.snapshotted { + vec![SubscriptionEvent::Commit { subscription_id, changes: complete }] + } else { + subscription.waiting.push(complete); + Vec::new() + } + } + + /// Adds one part; returns the whole commit once its last part arrives, a refusal text when a bound or a + /// consistency check fails. The buffered total is derived from the announced counts of the incomplete commits. + fn add_to_commit( + &mut self, + subscription_id: &str, + commit_id: String, + count: u32, + message_id: String, + change: Change, + ) -> std::result::Result>, String> { + let held = (subscription_id.to_owned(), commit_id); + match self.commits.get(&held) { + None => { + if self.commits.len() >= MAX_PENDING_COMMITS { + return Err(format!("more than {MAX_PENDING_COMMITS} commits are incomplete at once")); + } + let announced: u64 = self.commits.values().map(|commit| u64::from(commit.announced)).sum(); + if u64::from(count) + announced > MAX_BUFFERED_CHANGES { + return Err(format!( + "commit '{}' announces {count} changes; the incomplete commits may announce {MAX_BUFFERED_CHANGES} between them", + held.1 + )); + } + } + Some(pending) => { + if pending.announced != count { + return Err(format!( + "commit '{}' announces {} and {count} changes", + held.1, pending.announced + )); + } + if pending.ids.contains(&message_id) { + return Err(format!("commit '{}' delivered message '{message_id}' twice", held.1)); + } + } + } + let pending = self.commits.entry(held.clone()).or_insert_with(|| PendingCommit { + announced: count, + ids: HashSet::new(), + changes: Vec::new(), + }); + pending.ids.insert(message_id); + pending.changes.push(change); + if pending.changes.len() < count as usize { + return Ok(None); + } + Ok(self.commits.remove(&held).map(|commit| commit.changes)) + } + + /// The one fault path: drop what was waiting, latch, say so once. + fn fault_with(&mut self, reason: String) -> Vec { + self.commits.clear(); + for subscription in self.subscriptions.values_mut() { + subscription.waiting.clear(); + } + self.fault = Some(reason.clone()); + vec![SubscriptionEvent::Faulted { reason }] + } +} diff --git a/packages/cultnet-rs/tests/database_change_commit_vector.rs b/packages/cultnet-rs/tests/database_change_commit_vector.rs index 322227dc..a1f1eea5 100644 --- a/packages/cultnet-rs/tests/database_change_commit_vector.rs +++ b/packages/cultnet-rs/tests/database_change_commit_vector.rs @@ -1,43 +1,55 @@ //! `tests/vectors/database-change-commit/two-change-commit.msgpack` is written only by the C# reference: two -//! `cultnet.database_change_raw.v0` messages of one commit, every key present, nil where unset. cultnet-rs has no typed -//! `database_change_raw` message yet, so this walks the stream with the same `rmpv` values its wire decoder builds on and -//! pins the keys and values a Rust adopter will read. A rename of `commitId` or `commitCount` in the C# writer fails here. +//! `cultnet.database_change_raw.v0` messages of one commit, every key present, nil where unset. This decodes each into +//! the typed message and re-encodes it to the same bytes, so a rename of `commitId` or `commitCount` in the C# writer, or +//! a drift in the Rust writer's key order, fails here. -use rmpv::Value; +use cultnet_rs::*; +use serde::Deserialize; use std::io::Cursor; -fn messages() -> Vec { +/// The stream's messages as byte slices, split by skipping one value at a time. +fn messages() -> Vec> { let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/vectors/database-change-commit/two-change-commit.msgpack"); let bytes = std::fs::read(path).expect("the vector is committed"); let mut cursor = Cursor::new(bytes.as_slice()); let mut out = Vec::new(); while (cursor.position() as usize) < bytes.len() { - out.push(rmpv::decode::read_value(&mut cursor).expect("a msgpack value")); + let start = cursor.position() as usize; + let mut de = rmp_serde::Deserializer::new(&mut cursor); + serde::de::IgnoredAny::deserialize(&mut de).expect("a msgpack value"); + out.push(bytes[start..cursor.position() as usize].to_vec()); } out } -fn field<'a>(message: &'a Value, key: &str) -> &'a Value { - message - .as_map() - .and_then(|entries| entries.iter().find(|(k, _)| k.as_str() == Some(key))) - .map(|(_, v)| v) - .unwrap_or_else(|| panic!("the C# writer wrote no key {key}")) -} - #[test] -fn a_two_change_commit_written_by_csharp_carries_its_commit_id_count_and_changes() { +fn a_two_change_commit_written_by_csharp_decodes_typed_and_re_encodes_byte_for_byte() { let messages = messages(); assert_eq!(messages.len(), 2); - for message in &messages { - assert_eq!(field(message, "schemaVersion").as_str(), Some("cultnet.database_change_raw.v0")); - assert_eq!(field(message, "commitId").as_str(), Some("9f1c0f0e4b7a4c1f9d2e")); - assert_eq!(field(message, "commitCount").as_u64(), Some(2)); - assert_eq!(field(message, "changeKind").as_str(), Some("removed")); - assert_eq!(field(message, "subscriptionId").as_str(), Some("sub-1")); - assert_eq!(field(message, "schemaId").as_str(), Some("schema-note")); - assert!(field(message, "document").is_nil(), "a removed change's document is nil"); + let mut keys = Vec::new(); + for bytes in &messages { + let message = decode_cultnet_message_from_slice(bytes, CultNetWireContract::CultNetSchemaV0).unwrap(); + let CultNetMessage::DatabaseChangeRaw { + subscription_id, + change_kind, + document, + record_key, + schema_id, + commit_id, + commit_count, + .. + } = &message + else { + panic!("expected database_change_raw, got {message:?}"); + }; + assert_eq!(subscription_id, "sub-1"); + assert_eq!(*change_kind, DatabaseChangeKind::Removed); + assert_eq!(schema_id.as_deref(), Some("schema-note")); + assert_eq!(commit_id.as_deref(), Some("9f1c0f0e4b7a4c1f9d2e")); + assert_eq!(*commit_count, Some(2)); + assert!(document.is_none(), "a removed change's document is nil"); + keys.push(record_key.clone().unwrap()); + assert_eq!(&encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0).unwrap(), bytes); } - let keys: Vec<_> = messages.iter().map(|m| field(m, "recordKey").as_str().unwrap().to_string()).collect(); assert_eq!(keys, ["note:a", "note:b"]); } diff --git a/packages/cultnet-rs/tests/subscription.rs b/packages/cultnet-rs/tests/subscription.rs new file mode 100644 index 00000000..2175095e --- /dev/null +++ b/packages/cultnet-rs/tests/subscription.rs @@ -0,0 +1,320 @@ +//! The two subscription messages and the transport-free assembler. The bounds and faults mirror the C# client's +//! `HandleChange`; each has a test that fails without it. + +use cultnet_rs::*; +use rmpv::Value; + +fn s(text: &str) -> Value { + Value::from(text) +} + +fn decode(entries: Vec<(&str, Value)>) -> anyhow::Result { + let map = Value::Map(entries.into_iter().map(|(key, value)| (s(key), value)).collect()); + decode_cultnet_message_from_slice(&rmp_serde::to_vec(&map).unwrap(), CultNetWireContract::CultNetSchemaV0) +} + +fn removed(extra: Vec<(&str, Value)>) -> anyhow::Result { + let mut entries = vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m1")), + ("subscriptionId", s("sub")), + ("changeKind", s("removed")), + ("recordKey", s("k")), + ("schemaId", s("note")), + ]; + entries.extend(extra); + decode(entries) +} + +fn error_text(result: anyhow::Result) -> String { + format!("{:#}", result.expect_err("the decoder refuses this")) +} + +fn record(key: &str) -> SelectionDocumentRecord { + SelectionDocumentRecord { + schema_id: "note".into(), + schema_name: None, + schema_version: None, + schema_content_hash: None, + record_key: key.into(), + stored_at: "2026-11-28T00:00:00Z".into(), + payload_encoding: "messagepack".into(), + payload: vec![0x90], + source_runtime_id: None, + source_agent_id: None, + source_role: None, + tags: None, + } +} + +fn change(message_id: &str, subscription: &str, key: &str, commit: Option<(&str, u32)>) -> CultNetMessage { + CultNetMessage::DatabaseChangeRaw { + message_id: message_id.into(), + subscription_id: subscription.into(), + change_kind: DatabaseChangeKind::Updated, + document: Some(record(key)), + record_key: None, + schema_id: None, + commit_id: commit.map(|(id, _)| id.into()), + commit_count: commit.map(|(_, count)| count), + } +} + +fn snapshot(message_id: &str, keys: &[&str]) -> CultNetMessage { + CultNetMessage::SnapshotResponseRawV1 { + message_id: message_id.into(), + matched: keys.len() as u32, + as_of: 1, + next: None, + headers: None, + documents: Some(keys.iter().map(|key| record(key)).collect()), + edges: None, + shard_id: None, + shard_epoch: None, + shard_log_sequence: None, + } +} + +fn live(subscription: &str) -> SubscriptionAssembler { + let mut assembler = SubscriptionAssembler::new(); + assembler.begin(subscription, &format!("begin-{subscription}")).unwrap(); + assert_eq!(assembler.accept(snapshot(&format!("begin-{subscription}"), &[])).len(), 1); + assembler +} + +fn keys(event: &SubscriptionEvent) -> Vec { + match event { + SubscriptionEvent::Commit { changes, .. } => changes.iter().map(|change| change.record_key.clone()).collect(), + other => panic!("expected a commit, got {other:?}"), + } +} + +fn faulted(events: &[SubscriptionEvent]) -> &str { + match events { + [SubscriptionEvent::Faulted { reason }] => reason, + other => panic!("expected one fault, got {other:?}"), + } +} + +#[test] +fn a_removal_unsubscribe_and_a_change_round_trip_in_the_writers_key_order() { + for message in [ + change("m", "sub", "k", Some(("c", 2))), + change("m", "sub", "k", None), + CultNetMessage::DatabaseUnsubscribe { message_id: "m".into(), subscription_id: "sub".into() }, + ] { + let bytes = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0).unwrap(); + assert_eq!(decode_cultnet_message_from_slice(&bytes, CultNetWireContract::CultNetSchemaV0).unwrap(), message); + } +} + +#[test] +fn a_change_encodes_every_key_with_nil_where_unset() { + let value = encode_cultnet_message_for_wire(&change("m", "sub", "k", None), CultNetWireContract::CultNetSchemaV0).unwrap(); + let keys: Vec<_> = value.as_map().unwrap().iter().map(|(key, _)| key.as_str().unwrap().to_string()).collect(); + assert_eq!( + keys, + ["schemaVersion", "messageId", "subscriptionId", "changeKind", "document", "recordKey", "schemaId", "commitId", "commitCount"] + ); + let nil: Vec<_> = value.as_map().unwrap().iter().filter(|(_, v)| v.is_nil()).map(|(k, _)| k.as_str().unwrap()).collect(); + assert_eq!(nil, ["recordKey", "schemaId", "commitId", "commitCount"]); +} + +#[test] +fn decode_refuses_an_added_or_updated_change_without_a_document() { + for kind in ["added", "updated"] { + let result = decode(vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m")), + ("subscriptionId", s("sub")), + ("changeKind", s(kind)), + ("document", Value::Nil), + ]); + assert!(error_text(result).contains("must carry a document")); + } +} + +#[test] +fn decode_refuses_a_removal_without_record_key_or_schema_id() { + for dropped in ["recordKey", "schemaId"] { + let mut entries = vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m")), + ("subscriptionId", s("sub")), + ("changeKind", s("removed")), + ("recordKey", s("k")), + ("schemaId", s("note")), + ]; + entries.retain(|(key, _)| *key != dropped); + assert!(error_text(decode(entries)).contains("recordKey and schemaId")); + } +} + +#[test] +fn decode_refuses_a_commit_count_below_two_an_empty_commit_id_and_a_half_set_pair() { + assert!(error_text(removed(vec![("commitId", s("c")), ("commitCount", Value::from(1))])).contains("commitCount")); + assert!(error_text(removed(vec![("commitId", s("")), ("commitCount", Value::from(2))])).contains("commitId")); + assert!(error_text(removed(vec![("commitCount", Value::from(2))])).contains("together")); + assert!(error_text(removed(vec![("commitId", s("c"))])).contains("together")); + removed(vec![("commitId", s("c")), ("commitCount", Value::from(2))]).expect("a well-formed commit part decodes"); +} + +#[test] +fn decode_refuses_a_duplicate_key_and_an_unknown_change_kind() { + let text = error_text(removed(vec![("recordKey", s("other"))])); assert!(text.contains("duplicate field"), "{text}"); + let result = decode(vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m")), + ("subscriptionId", s("sub")), + ("changeKind", s("renamed")), + ]); + assert!(result.is_err()); +} + +#[test] +fn a_two_part_commit_is_one_commit_in_arrival_order_and_never_partial() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k1", Some(("c", 2)))).is_empty(), "the first part is held"); + let events = assembler.accept(change("b", "sub", "k2", Some(("c", 2)))); + assert_eq!(events.len(), 1); + assert_eq!(keys(&events[0]), ["k1", "k2"]); +} + +#[test] +fn a_single_change_is_a_one_change_commit() { + let mut assembler = live("sub"); + let events = assembler.accept(change("a", "sub", "k1", None)); + assert_eq!(keys(&events[0]), ["k1"]); +} + +#[test] +fn a_removal_reports_the_messages_key_and_schema() { + let mut assembler = live("sub"); + let events = assembler.accept(removed(vec![]).unwrap()); + let SubscriptionEvent::Commit { changes, .. } = &events[0] else { panic!("{events:?}") }; + assert_eq!((changes[0].kind, changes[0].record_key.as_str(), changes[0].schema_id.as_str()), (DatabaseChangeKind::Removed, "k", "note")); + assert!(changes[0].document.is_none()); +} + +#[test] +fn the_sixty_fifth_incomplete_commit_faults_and_the_sixty_fourth_does_not() { + let mut assembler = live("sub"); + for index in 0..MAX_PENDING_COMMITS { + let id = format!("c{index}"); + assert!(assembler.accept(change(&format!("m{index}"), "sub", "k", Some((&id, 2)))).is_empty()); + } + let events = assembler.accept(change("overflow", "sub", "k", Some(("c-over", 2)))); + assert_eq!( + faulted(&events), + "CultNet subscription 'sub': more than 64 commits are incomplete at once." + ); + assert!(assembler.fault().is_some()); +} + +#[test] +fn announced_totals_up_to_the_bound_are_held_and_one_change_past_it_faults() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("one", 999_998)))).is_empty()); + assert!(assembler.accept(change("b", "sub", "k", Some(("two", 2)))).is_empty(), "exactly 1_000_000 is within the bound"); + assert!(assembler.fault().is_none()); + let events = assembler.accept(change("c", "sub", "k", Some(("three", 2)))); + assert_eq!( + faulted(&events), + "CultNet subscription 'sub': commit 'three' announces 2 changes; the incomplete commits may announce 1000000 between them." + ); +} + +#[test] +fn a_completed_commit_stops_counting_against_the_bound() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("one", 2)))).is_empty()); + assert_eq!(assembler.accept(change("b", "sub", "k", Some(("one", 2)))).len(), 1); + assert!(assembler.accept(change("c", "sub", "k", Some(("big", 1_000_000)))).is_empty()); + assert!(assembler.fault().is_none()); +} + +#[test] +fn a_commit_that_announces_two_different_counts_faults() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("c", 3)))).is_empty()); + let events = assembler.accept(change("b", "sub", "k", Some(("c", 2)))); + assert_eq!(faulted(&events), "CultNet subscription 'sub': commit 'c' announces 3 and 2 changes."); +} + +#[test] +fn a_message_id_delivered_twice_in_one_commit_faults() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("c", 3)))).is_empty()); + let events = assembler.accept(change("a", "sub", "k2", Some(("c", 3)))); + assert_eq!(faulted(&events), "CultNet subscription 'sub': commit 'c' delivered message 'a' twice."); +} + +#[test] +fn after_a_fault_accept_returns_nothing_until_reset_and_the_buffers_are_gone() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("c", 3)))).is_empty()); + assembler.accept(change("b", "sub", "k", Some(("c", 2)))); + assert!(assembler.accept(change("x", "sub", "k", None)).is_empty()); + assert!(assembler.begin("other", "m").is_err()); + assembler.reset(); + assert!(assembler.fault().is_none()); + // The old commit was dropped by the fault and the subscription by the reset. + assert!(assembler.accept(change("c3", "sub", "k", Some(("c", 3)))).is_empty()); + assembler.begin("sub", "again").unwrap(); + assert_eq!(assembler.accept(snapshot("again", &["r"])).len(), 1); + assert_eq!(keys(&assembler.accept(change("y", "sub", "k", None))[0]), ["k"]); +} + +#[test] +fn a_change_for_an_ended_or_never_begun_subscription_yields_nothing_and_is_not_buffered() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "ghost", "k", None)).is_empty()); + assert!(assembler.accept(change("b", "ghost", "k", Some(("c", 2)))).is_empty()); + assembler.end("sub"); + assert!(assembler.accept(change("c", "sub", "k", None)).is_empty()); + // Not buffered: 64 stragglers of distinct commits would fault if they were. + for index in 0..=MAX_PENDING_COMMITS { + let id = format!("s{index}"); + assert!(assembler.accept(change(&format!("m{index}"), "sub", "k", Some((&id, 2)))).is_empty()); + } + assert!(assembler.fault().is_none()); +} + +#[test] +fn ending_a_subscription_evicts_its_incomplete_commits() { + let mut assembler = live("sub"); + for index in 0..MAX_PENDING_COMMITS { + let id = format!("c{index}"); + assert!(assembler.accept(change(&format!("m{index}"), "sub", "k", Some((&id, 2)))).is_empty()); + } + assembler.end("sub"); + let mut other = assembler; + other.begin("sub", "b2").unwrap(); + other.accept(snapshot("b2", &[])); + assert!(other.accept(change("z", "sub", "k", Some(("fresh", 2)))).is_empty()); + assert!(other.fault().is_none(), "the evicted commits no longer count against the bound"); +} + +#[test] +fn a_snapshot_whose_message_id_was_never_begun_yields_nothing() { + let mut assembler = SubscriptionAssembler::new(); + assert!(assembler.accept(snapshot("nobody", &["r"])).is_empty()); + assembler.begin("sub", "m").unwrap(); + let events = assembler.accept(snapshot("m", &["r"])); + assert!(matches!(&events[0], SubscriptionEvent::Snapshot { subscription_id, documents } if subscription_id == "sub" && documents.len() == 1)); + assert!(assembler.accept(snapshot("m", &["r"])).is_empty(), "a snapshot answers its begin once"); +} + +#[test] +fn changes_that_arrive_before_the_snapshot_follow_it_in_order() { + let mut assembler = SubscriptionAssembler::new(); + assembler.begin("sub", "m").unwrap(); + assert!(assembler.accept(change("a", "sub", "first", None)).is_empty()); + assert!(assembler.accept(change("b", "sub", "second-a", Some(("c", 2)))).is_empty()); + assert!(assembler.accept(change("c", "sub", "second-b", Some(("c", 2)))).is_empty()); + assert!(assembler.accept(change("d", "sub", "third", None)).is_empty()); + let events = assembler.accept(snapshot("m", &["r"])); + assert!(matches!(events[0], SubscriptionEvent::Snapshot { .. })); + let order: Vec<_> = events[1..].iter().map(keys).collect(); + assert_eq!(order, [vec!["first"], vec!["second-a", "second-b"], vec!["third"]]); +} -- 2.47.3 From b34cb0293b3652bc5e31fc8401dc32b923964f01 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:35:10 +0100 Subject: [PATCH 2/6] CultNet C#: write the database-subscription session vector from a live subscription server Co-Authored-By: Claude Sonnet 5.5 --- .../CultNetReplicaCommitTests.cs | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs index 78b1f4d0..05fa5cef 100644 --- a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs @@ -65,6 +65,8 @@ namespace GameCult.Networking.Tests { if (message is CultNetDatabaseSubscribeMessage subscribe) _server.Dispatch(subscribe, _peer).GetAwaiter().GetResult(); + else if (message is CultNetDatabaseSubscribeV1Message subscribeV1) + _server.Dispatch(subscribeV1, _peer).GetAwaiter().GetResult(); else if (message is CultNetDatabaseUnsubscribeMessage unsubscribe) _server.Dispatch(unsubscribe, _peer).GetAwaiter().GetResult(); } @@ -108,6 +110,8 @@ namespace GameCult.Networking.Tests private readonly CultNetDatabaseSubscriptionServer _server; public void Reconcile() => _server.Reconcile(); public CultNetDatabaseSubscriptionServer Server => _server; + private LoopbackServer Wire { get; } + public void SubscribeV1(CultNetDatabaseSubscribeV1Message message) => Wire.Dispatch(message, Peer).GetAwaiter().GetResult(); public Task Subscribe(string id) => Client.SubscribeAsync(id, schemaIds: new[] { Source.Registry.GetRequired().SchemaId }); public object Gate => typeof(CultNetDatabaseSubscriptionServer) @@ -122,6 +126,7 @@ namespace GameCult.Networking.Tests seedReplica?.Invoke(Replica); Database = new CultNetDatabase(Source); var wire = new LoopbackServer(); + Wire = wire; _server = new CultNetDatabaseSubscriptionServer(wire, Database, authorizeRecord: authorizeRecord, authorizeRequest: authorizeRequest); var documents = new CultNetDocumentRegistry(Replica.Registry) .Register(CultNetDocumentBinding.ForDocument(Replica.Registry)); @@ -262,6 +267,73 @@ namespace GameCult.Networking.Tests Assert.That(Convert.ToHexString(bytes), Is.EqualTo(Convert.ToHexString(System.IO.File.ReadAllBytes(path)))); } + [Test] + public async Task ASubscriptionSessionIsWrittenAsTheSubscriptionVectorOtherRuntimesDecode() + { + // tests/vectors/database-subscription/session.msgpack: one v1 subscribe and what a live subscription server sends back + // (a snapshot of two records, one single change, one two-change commit, one removal), each as the C# serializer + // writes it, concatenated. Message ids, commit ids and timestamps are made deterministic after the server wrote + // them; everything else is the server's. Written with CULTCACHE_WRITE_VECTORS=1; every other run compares bytes. + using var run = new Replication(source => Stage(source, ("a", "one"), ("b", "two")), subscribe: false); + var subscribe = new CultNetDatabaseSubscribeV1Message + { + MessageId = "subscribe-1", + SubscriptionId = "sub-1", + Selection = new CultNetSelection + { + Schemas = new[] { run.Source.Registry.GetRequired().SchemaId }, + Projection = CultNetSelectionProjections.Document + } + }; + run.SubscribeV1(subscribe); + Stage(run.Source, ("c", "three")); + await Until(() => run.Peer.Sent.Count >= 2); + Stage(run.Source, ("a", "two"), ("b", "one")); + await Until(() => run.Peer.Sent.Count >= 4); + Assert.That(run.Source.Commit(batch => batch.Remove(new CultRecordKey("c"))), Is.True); + await Until(() => run.Peer.Sent.Count >= 5); + + const string storedAt = "2026-11-28T00:00:00.0000000Z"; + var index = 0; + var stream = new List { CultNetSchemaMessageSerialization.Serialize(subscribe) }; + foreach (var bytes in run.Peer.Sent) + { + switch (CultNetSchemaMessageSerialization.Deserialize(bytes)) + { + case CultNetSnapshotResponseRawV1Message snapshot: + snapshot.MessageId = subscribe.MessageId; + foreach (var document in snapshot.Documents!) document.StoredAt = storedAt; + stream.Add(CultNetSchemaMessageSerialization.Serialize(snapshot)); + break; + case CultNetDatabaseChangeRawMessage change: + change.MessageId = $"change-{index++}"; + if (change.CommitId != null) change.CommitId = "9f1c0f0e4b7a4c1f9d2e"; + if (change.Document != null) change.Document.StoredAt = storedAt; + stream.Add(CultNetSchemaMessageSerialization.Serialize(change)); + break; + default: + Assert.Fail("The server sent a message the vector does not name."); + break; + } + } + + var all = stream.SelectMany(bytes => bytes).ToArray(); + var directory = TestContext.CurrentContext.TestDirectory; + while (directory != null && !System.IO.Directory.Exists(System.IO.Path.Combine(directory, "tests", "vectors"))) + directory = System.IO.Path.GetDirectoryName(directory); + Assert.That(directory, Is.Not.Null, "tests/vectors is above the test directory"); + var path = System.IO.Path.Combine(directory!, "tests", "vectors", "database-subscription", "session.msgpack"); + if (Environment.GetEnvironmentVariable("CULTCACHE_WRITE_VECTORS") == "1") + { + System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!); + System.IO.File.WriteAllBytes(path, all); + return; + } + + Assert.That(System.IO.File.Exists(path), Is.True, "the vector is committed"); + Assert.That(Convert.ToHexString(all), Is.EqualTo(Convert.ToHexString(System.IO.File.ReadAllBytes(path)))); + } + [Test] public void AnOlderPeerReadsTheChangeAndIgnoresTheCommitFields() { -- 2.47.3 From 678f058aaed353d241315bb86c1865fd8f94f77a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:36:05 +0100 Subject: [PATCH 3/6] cultnet-rs: decode and drive the C#-written subscription session vector Co-Authored-By: Claude Sonnet 5.5 --- packages/cultnet-rs/tests/subscription.rs | 52 ++++++++++++++++++ tests/vectors/database-subscription/README.md | 10 ++++ .../database-subscription/session.msgpack | Bin 0 -> 3220 bytes 3 files changed, 62 insertions(+) create mode 100644 tests/vectors/database-subscription/README.md create mode 100644 tests/vectors/database-subscription/session.msgpack diff --git a/packages/cultnet-rs/tests/subscription.rs b/packages/cultnet-rs/tests/subscription.rs index 2175095e..699a4784 100644 --- a/packages/cultnet-rs/tests/subscription.rs +++ b/packages/cultnet-rs/tests/subscription.rs @@ -318,3 +318,55 @@ fn changes_that_arrive_before_the_snapshot_follow_it_in_order() { let order: Vec<_> = events[1..].iter().map(keys).collect(); assert_eq!(order, [vec!["first"], vec!["second-a", "second-b"], vec!["third"]]); } + +/// The C#-written session: subscribe, snapshot, a single change, a two-change commit, a removal. +fn session() -> Vec> { + use serde::Deserialize; + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/vectors/database-subscription/session.msgpack"); + let bytes = std::fs::read(path).expect("the vector is committed"); + let mut cursor = std::io::Cursor::new(bytes.as_slice()); + let mut out = Vec::new(); + while (cursor.position() as usize) < bytes.len() { + let start = cursor.position() as usize; + let mut de = rmp_serde::Deserializer::new(&mut cursor); + serde::de::IgnoredAny::deserialize(&mut de).expect("a msgpack value"); + out.push(bytes[start..cursor.position() as usize].to_vec()); + } + out +} + +#[test] +fn the_csharp_session_decodes_typed_and_its_server_messages_re_encode_byte_for_byte() { + let messages = session(); + assert_eq!(messages.len(), 6); + let decoded: Vec<_> = messages + .iter() + .map(|bytes| decode_cultnet_message_from_slice(bytes, CultNetWireContract::CultNetSchemaV0).unwrap()) + .collect(); + assert!(matches!(&decoded[0], CultNetMessage::DatabaseSubscribeV1 { subscription_id, .. } if subscription_id == "sub-1")); + for (message, bytes) in decoded.iter().zip(&messages).skip(1) { + assert_eq!(&encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0).unwrap(), bytes); + } + let CultNetMessage::SnapshotResponseRawV1 { documents: Some(documents), .. } = &decoded[1] else { panic!("{:?}", decoded[1]) }; + assert!(documents.iter().all(|document| document.schema_content_hash.is_some() && document.schema_name.is_some())); +} + +#[test] +fn the_csharp_session_drives_the_assembler_to_a_snapshot_and_three_commits() { + let messages = session(); + let decoded: Vec<_> = messages + .iter() + .map(|bytes| decode_cultnet_message_from_slice(bytes, CultNetWireContract::CultNetSchemaV0).unwrap()) + .collect(); + let mut assembler = SubscriptionAssembler::new(); + assembler.begin("sub-1", "subscribe-1").unwrap(); + let events: Vec<_> = decoded.into_iter().skip(1).flat_map(|message| assembler.accept(message)).collect(); + assert_eq!(events.len(), 4, "{events:?}"); + let SubscriptionEvent::Snapshot { documents, .. } = &events[0] else { panic!("{events:?}") }; + assert_eq!(documents.iter().map(|d| d.record_key.as_str()).collect::>(), ["a", "b"]); + assert_eq!(keys(&events[1]), ["c"]); + assert_eq!(keys(&events[2]), ["a", "b"]); + assert_eq!(keys(&events[3]), ["c"]); + let SubscriptionEvent::Commit { changes, .. } = &events[3] else { unreachable!() }; + assert_eq!(changes[0].kind, DatabaseChangeKind::Removed); +} diff --git a/tests/vectors/database-subscription/README.md b/tests/vectors/database-subscription/README.md new file mode 100644 index 00000000..7ee25f78 --- /dev/null +++ b/tests/vectors/database-subscription/README.md @@ -0,0 +1,10 @@ +# database-subscription vectors + +Written only by the C# reference, `ASubscriptionSessionIsWrittenAsTheSubscriptionVectorOtherRuntimesDecode` in +`tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs`, with `CULTCACHE_WRITE_VECTORS=1`. Every other run compares the bytes. + +- `session.msgpack`: concatenated MessagePack messages of one subscription, in order: `cultnet.database_subscribe.v1` + (`sub-1`, schema selection, document projection); `cultnet.snapshot_response_raw.v1` answering it with two records + (`a`, `b`); one single `cultnet.database_change_raw.v0` (`updated`, `c`, no commit fields); a two-change commit + (`updated` `a` and `b`, `commitId` `9f1c0f0e4b7a4c1f9d2e`, `commitCount` 2); one `removed` change (`c`). Message ids, + the commit id and `storedAt` are fixed after the server wrote them. diff --git a/tests/vectors/database-subscription/session.msgpack b/tests/vectors/database-subscription/session.msgpack new file mode 100644 index 0000000000000000000000000000000000000000..9efe6dec78eb8af2ab175934a78ad9897f81e92e GIT binary patch literal 3220 zcmeHK-EPw`7)854JO(e&DoK+x+1;2XsD?md6Bpc6j{T(xOYC4f8+`*NxM5GgM7#b> zV@yIqNCR2GOYCiMo2=cWl}TL@H;W?0{_NQK&N)7I-W&-WL5iLO7cryXah^yDvPzId z0TR#@c_1*41E_ABgA{~7EohL#Nw{KuD$AMF12jliS1aZ~KmvFa+3giGi1%j?MT9KJ zT@HzDxF&eSMOF}a2)vLu9`X%r)xdP14g?Ilj!jF4d^f$`pt6QBdXbW`^ z#*h%9x;U0lK8PA-oV_e&?h}Ud6sQ~$5Ev+lY3pYPilkCApQ!;@mXRYs*|;1LqhCzaKMa{b!hLSzL1OqS&^rfVYwC4tXSTr zVJwgDs!?1ojx*Fw7$R#Fvylo8OCe_nZ}rNy-*@*uG72A#1NVDNUURFTS?7cW?@aTZ6aKe;YS-$AL&~-<_>Y=?^1e3g@t?v1&zv)S F_7BS>%Ub{d literal 0 HcmV?d00001 -- 2.47.3 From 1e3bedbd414600860d09bd685e0afc39cfb54a57 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:39:15 +0100 Subject: [PATCH 4/6] cultnet-rs: a one-change commit announcement is a single change, as in the C# client Co-Authored-By: Claude Sonnet 5.5 --- packages/cultnet-rs/tests/subscription.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/cultnet-rs/tests/subscription.rs b/packages/cultnet-rs/tests/subscription.rs index 699a4784..b3f1cc28 100644 --- a/packages/cultnet-rs/tests/subscription.rs +++ b/packages/cultnet-rs/tests/subscription.rs @@ -370,3 +370,10 @@ fn the_csharp_session_drives_the_assembler_to_a_snapshot_and_three_commits() { let SubscriptionEvent::Commit { changes, .. } = &events[3] else { unreachable!() }; assert_eq!(changes[0].kind, DatabaseChangeKind::Removed); } + +#[test] +fn a_commit_that_announces_one_change_is_a_single_change_not_a_buffered_commit() { + let mut assembler = live("sub"); + let events = assembler.accept(change("a", "sub", "k1", Some(("c", 1)))); + assert_eq!(keys(&events[0]), ["k1"], "C# treats commitCount <= 1 as no commit"); +} -- 2.47.3 From 8be603acdb40dc9392ea0a14c1b212f0ff07dbcb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:39:24 +0100 Subject: [PATCH 5/6] cultnet-rs: pin the id refusals of the two subscription messages Co-Authored-By: Claude Sonnet 5.5 --- packages/cultnet-rs/tests/subscription.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/packages/cultnet-rs/tests/subscription.rs b/packages/cultnet-rs/tests/subscription.rs index b3f1cc28..9bdd2229 100644 --- a/packages/cultnet-rs/tests/subscription.rs +++ b/packages/cultnet-rs/tests/subscription.rs @@ -377,3 +377,24 @@ fn a_commit_that_announces_one_change_is_a_single_change_not_a_buffered_commit() let events = assembler.accept(change("a", "sub", "k1", Some(("c", 1)))); assert_eq!(keys(&events[0]), ["k1"], "C# treats commitCount <= 1 as no commit"); } + +#[test] +fn decode_refuses_an_unsubscribe_or_change_without_its_ids() { + for (field, other) in [("messageId", "subscriptionId"), ("subscriptionId", "messageId")] { + let result = decode(vec![ + ("schemaVersion", s("cultnet.database_unsubscribe.v0")), + (field, s("")), + (other, s("x")), + ]); + assert!(error_text(result).contains(field)); + } + assert!(error_text(removed(vec![]).and_then(|_| decode(vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m")), + ("subscriptionId", s(" ")), + ("changeKind", s("removed")), + ("recordKey", s("k")), + ("schemaId", s("n")), + ]))) + .contains("subscriptionId")); +} -- 2.47.3 From c5d8f8047c005ca0c3bd008f45a6e7c326b47fb7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:57:46 +0100 Subject: [PATCH 6/6] CultNet contract: a decoder refuses commitCount below two; a change for an ended subscription is dropped. cultnet-rs: pin that a one-change announcement ignores a full buffer Co-Authored-By: Claude Sonnet 5.5 --- contracts/cultnet/cultnet-distributed-database.md | 4 ++-- packages/cultnet-rs/tests/subscription.rs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/contracts/cultnet/cultnet-distributed-database.md b/contracts/cultnet/cultnet-distributed-database.md index a1c20466..0ed19837 100644 --- a/contracts/cultnet/cultnet-distributed-database.md +++ b/contracts/cultnet/cultnet-distributed-database.md @@ -141,7 +141,7 @@ A malformed put or delete is `message_invalid`, not a per-operation code: the pe shard view and advances the replica cursor to that sequence. - Realtime subscriptions publish domain changes, not storage envelopes. - A subscription's `database_change_raw` messages may carry `commitId` and `commitCount`: the changes of one cache - commit that this subscription delivers (`commitCount` of them, at least two). Both fields are optional and additive; a + commit that this subscription delivers (`commitCount` of them, at least two; a decoder refuses less). Both fields are optional and additive; a peer that does not know them ignores them and applies each change alone. A replica that knows them applies the commit's changes as one commit, so the replica judges the result (a swap of two unique-index values) and not the state between records. A replica whose cache refuses a commit is faulted, never silent. `commitId` is opaque and valid only @@ -149,7 +149,7 @@ A malformed put or delete is `message_invalid`, not a per-operation code: the pe never forwards a commit that its last snapshot to the subscription already reflects (the database server adopts next). A replica may bound how many changes it buffers across incomplete commits (the C# client: `MaxBufferedChanges`, 1,000,000). One bound covers every commit, whatever made it, a `Reconcile` diff included: a commit announcing more faults the replica loudly, and a faulted - consumer resubscribes for a snapshot, which is one message and has no such bound. A server does not split a commit to + consumer resubscribes for a snapshot, which is one message and has no such bound. A change for a subscription the client has ended or never began is dropped, never applied or buffered, whether it is a single change or part of a commit. A server does not split a commit to fit a replica's bound. The C# subscription server and database server tag commits; other runtimes adopt next. - The C# writer sets every key of a `database_change_raw` message, nil where unset: a removed change carries `document` nil, an added or updated one `recordKey` and `schemaId` nil. The schema accepts those nils; an added or updated change diff --git a/packages/cultnet-rs/tests/subscription.rs b/packages/cultnet-rs/tests/subscription.rs index 9bdd2229..b81c4e01 100644 --- a/packages/cultnet-rs/tests/subscription.rs +++ b/packages/cultnet-rs/tests/subscription.rs @@ -398,3 +398,15 @@ fn decode_refuses_an_unsubscribe_or_change_without_its_ids() { ]))) .contains("subscriptionId")); } + +#[test] +fn a_one_change_announcement_never_counts_against_a_full_buffer() { + let mut assembler = live("sub"); + for index in 0..MAX_PENDING_COMMITS { + let id = format!("c{index}"); + assert!(assembler.accept(change(&format!("m{index}"), "sub", "k", Some((&id, 2)))).is_empty()); + } + let events = assembler.accept(change("single", "sub", "k1", Some(("one", 1)))); + assert_eq!(keys(&events[0]), ["k1"], "a single change is not a buffered commit, so the full cap does not refuse it"); + assert!(assembler.fault().is_none()); +} -- 2.47.3