Add pure CultNet snapshot query loop

This commit is contained in:
Meta Vens 2026-07-19 20:25:05 +01:00
commit 6b3e696c8e
5 changed files with 589 additions and 20 deletions

View file

@ -11,6 +11,7 @@ use cultnet_rs::CultNetDocumentPutOptions;
use cultnet_rs::CultNetDocumentRegistry;
use cultnet_rs::CultNetMessage;
use cultnet_rs::CultNetMutationAuthority;
use cultnet_rs::CultNetReadOnlySnapshotPolicy;
use cultnet_rs::CultNetSchemaKind;
use cultnet_rs::CultNetSchemaRegistration;
use cultnet_rs::CultNetSchemaRegistry;
@ -25,6 +26,7 @@ use cultnet_rs::builtin_schema_registry;
use cultnet_rs::decode_cultnet_message_from_slice;
use cultnet_rs::encode_cultnet_message_to_vec;
use cultnet_rs::encode_frame;
use cultnet_rs::serve_read_only_raw_snapshot;
use serde::Deserialize;
use serde::Serialize;
use socket2::Domain;
@ -641,26 +643,28 @@ fn handle_connection(
let response = schema_registry.create_catalog_response(&request)?;
send_message(&mut stream, &response)?;
}
CultNetMessage::SnapshotRequest {
message_id,
schema_ids,
record_keys,
} => {
let mut response = document_registry.create_raw_snapshot_response(
&cache.lock().expect("cache poisoned"),
message_id,
schema_ids.as_deref(),
record_keys.as_deref(),
)?;
if let CultNetMessage::SnapshotResponseRaw { documents, .. } = &mut response {
for document in documents.iter_mut() {
document.source_runtime_id = Some(config.runtime_id.clone());
document.source_agent_id = Some(config.agent_id.clone());
document.source_role = Some("peer".to_string());
document.tags =
Some(vec!["interop".to_string(), config.runtime_id.clone()]);
request @ CultNetMessage::SnapshotRequest { .. } => {
// Snapshot serving is a pure read. The backing projection owns
// the records and provenance; the protocol loop only filters
// an explicit allowlist and returns their exact payload bytes.
let (source, policy) = {
let cache = cache.lock().expect("cache poisoned");
let mut records = Vec::new();
let mut policy = CultNetReadOnlySnapshotPolicy::new();
for envelope in cache.snapshot() {
let mut record =
document_registry.raw_document_record_from_envelope(&envelope)?;
record.source_runtime_id = Some(config.runtime_id.clone());
record.source_agent_id = Some(config.agent_id.clone());
record.source_role = Some("peer".to_string());
record.tags = Some(vec!["interop".to_string(), config.runtime_id.clone()]);
policy.allow(&record.schema_id, &record.record_key)?;
records.push(record);
}
}
(records, policy)
};
let response =
serve_read_only_raw_snapshot(&document_registry, &policy, &source, &request)?;
send_message(&mut stream, &response)?;
}
message @ CultNetMessage::DocumentPutRaw { .. } => {

View file

@ -5,6 +5,7 @@ mod rudp;
mod schema_discovery;
mod security;
mod service_identity;
mod snapshot_query;
mod transport;
pub use contracts::*;
@ -14,4 +15,5 @@ pub use rudp::*;
pub use schema_discovery::*;
pub use security::*;
pub use service_identity::*;
pub use snapshot_query::*;
pub use transport::*;

View file

@ -403,7 +403,9 @@ impl CultNetDocumentRegistry {
})
}
fn raw_document_record_from_envelope(
/// Project a stored CultCache envelope as a raw CultNet record without
/// decoding or re-encoding its payload bytes.
pub fn raw_document_record_from_envelope(
&self,
envelope: &CultCacheEnvelope,
) -> Result<CultNetRawDocumentRecord> {

339
vendor/cultnet-rs/src/snapshot_query.rs vendored Normal file
View file

@ -0,0 +1,339 @@
use anyhow::{Result, anyhow};
use std::collections::{BTreeMap, BTreeSet};
use crate::{CultNetDocumentRegistry, CultNetMessage, CultNetRawDocumentRecord};
/// Read-only backing surface for a CultNet snapshot server.
///
/// Records returned here are already the stored wire records. The snapshot
/// server selects and clones them; it never decodes payloads, rewrites source
/// metadata, or applies them to another cache.
pub trait CultNetRawSnapshotSource {
fn raw_snapshot(&self) -> Result<Vec<CultNetRawDocumentRecord>>;
}
impl CultNetRawSnapshotSource for Vec<CultNetRawDocumentRecord> {
fn raw_snapshot(&self) -> Result<Vec<CultNetRawDocumentRecord>> {
Ok(self.clone())
}
}
impl<F> CultNetRawSnapshotSource for F
where
F: Fn() -> Result<Vec<CultNetRawDocumentRecord>>,
{
fn raw_snapshot(&self) -> Result<Vec<CultNetRawDocumentRecord>> {
self()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CultNetReadOnlySnapshotPolicy {
allowed_records: BTreeSet<(String, String)>,
}
impl CultNetReadOnlySnapshotPolicy {
pub fn new() -> Self {
Self::default()
}
pub fn allow(
&mut self,
schema_id: impl Into<String>,
record_key: impl Into<String>,
) -> Result<&mut Self> {
let schema_id = schema_id.into();
let record_key = record_key.into();
require_non_empty(&schema_id, "schema_id")?;
require_non_empty(&record_key, "record_key")?;
self.allowed_records.insert((schema_id, record_key));
Ok(self)
}
fn allows(&self, schema_id: &str, record_key: &str) -> bool {
self.allowed_records
.contains(&(schema_id.to_string(), record_key.to_string()))
}
}
/// Serve one raw snapshot request from an explicitly bounded, read-only view.
///
/// The document registry proves that every exposed schema belongs to the
/// runtime. The policy grants individual `(schema_id, record_key)` pairs. The
/// source owns the bytes and metadata; this function only selects records.
pub fn serve_read_only_raw_snapshot<S: CultNetRawSnapshotSource>(
document_registry: &CultNetDocumentRegistry,
policy: &CultNetReadOnlySnapshotPolicy,
source: &S,
request: &CultNetMessage,
) -> Result<CultNetMessage> {
let CultNetMessage::SnapshotRequest {
message_id,
schema_ids,
record_keys,
} = request
else {
return Err(anyhow!("expected cultnet.snapshot_request.v0"));
};
require_non_empty(message_id, "message_id")?;
reject_duplicates(schema_ids.as_deref(), "requested schema id")?;
reject_duplicates(record_keys.as_deref(), "requested record key")?;
let requested_schemas = schema_ids
.as_ref()
.map(|values| values.iter().map(String::as_str).collect::<BTreeSet<_>>());
let requested_keys = record_keys
.as_ref()
.map(|values| values.iter().map(String::as_str).collect::<BTreeSet<_>>());
let mut selected = Vec::new();
let mut seen = BTreeSet::new();
for document in source.raw_snapshot()? {
let identity = (document.schema_id.clone(), document.record_key.clone());
if !seen.insert(identity.clone()) {
return Err(anyhow!(
"snapshot source contains duplicate record {:?}/{:?}",
identity.0,
identity.1
));
}
if document_registry
.binding_by_schema_id(&document.schema_id)
.is_none()
{
return Err(anyhow!(
"snapshot source record {:?}/{:?} uses an unregistered schema",
document.schema_id,
document.record_key
));
}
if !policy.allows(&document.schema_id, &document.record_key) {
continue;
}
if requested_schemas
.as_ref()
.is_some_and(|schemas| !schemas.contains(document.schema_id.as_str()))
{
continue;
}
if requested_keys
.as_ref()
.is_some_and(|keys| !keys.contains(document.record_key.as_str()))
{
continue;
}
selected.push(document);
}
Ok(CultNetMessage::SnapshotResponseRaw {
message_id: message_id.clone(),
documents: selected,
})
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CultNetSnapshotSourceExpectation {
pub runtime_id: Option<String>,
pub agent_id: Option<String>,
pub role: Option<String>,
pub tags: Option<Vec<String>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetSnapshotRecordExpectation {
pub schema_id: String,
pub record_key: String,
pub source: CultNetSnapshotSourceExpectation,
}
impl CultNetSnapshotRecordExpectation {
pub fn new(schema_id: impl Into<String>, record_key: impl Into<String>) -> Self {
Self {
schema_id: schema_id.into(),
record_key: record_key.into(),
source: CultNetSnapshotSourceExpectation::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetRawSnapshotQuery {
message_id: String,
expectations: BTreeMap<(String, String), CultNetSnapshotSourceExpectation>,
}
impl CultNetRawSnapshotQuery {
pub fn new(
message_id: impl Into<String>,
records: Vec<CultNetSnapshotRecordExpectation>,
) -> Result<Self> {
let message_id = message_id.into();
require_non_empty(&message_id, "message_id")?;
if records.is_empty() {
return Err(anyhow!("snapshot query must request at least one record"));
}
let mut expectations = BTreeMap::new();
for record in records {
require_non_empty(&record.schema_id, "schema_id")?;
require_non_empty(&record.record_key, "record_key")?;
let identity = (record.schema_id, record.record_key);
if expectations
.insert(identity.clone(), record.source)
.is_some()
{
return Err(anyhow!(
"snapshot query contains duplicate requested record {:?}/{:?}",
identity.0,
identity.1
));
}
}
Ok(Self {
message_id,
expectations,
})
}
pub fn request(&self) -> CultNetMessage {
CultNetMessage::SnapshotRequest {
message_id: self.message_id.clone(),
schema_ids: Some(
self.expectations
.keys()
.map(|(schema_id, _)| schema_id.clone())
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
),
record_keys: Some(
self.expectations
.keys()
.map(|(_, record_key)| record_key.clone())
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
),
}
}
/// Validate a response and return records without mutating any local cache.
pub fn accept_response(
&self,
response: CultNetMessage,
) -> Result<Vec<CultNetRawDocumentRecord>> {
let CultNetMessage::SnapshotResponseRaw {
message_id,
documents,
} = response
else {
return Err(anyhow!("expected cultnet.snapshot_response_raw.v0"));
};
if message_id != self.message_id {
return Err(anyhow!(
"snapshot response message id {:?} does not match request {:?}",
message_id,
self.message_id
));
}
let mut seen = BTreeSet::new();
for document in &documents {
let identity = (document.schema_id.clone(), document.record_key.clone());
if !seen.insert(identity.clone()) {
return Err(anyhow!(
"snapshot response contains duplicate record {:?}/{:?}",
identity.0,
identity.1
));
}
let expected = self.expectations.get(&identity).ok_or_else(|| {
anyhow!(
"snapshot response contains unexpected record {:?}/{:?}",
identity.0,
identity.1
)
})?;
require_expected_metadata(
"source_runtime_id",
expected.runtime_id.as_deref(),
document.source_runtime_id.as_deref(),
&identity,
)?;
require_expected_metadata(
"source_agent_id",
expected.agent_id.as_deref(),
document.source_agent_id.as_deref(),
&identity,
)?;
require_expected_metadata(
"source_role",
expected.role.as_deref(),
document.source_role.as_deref(),
&identity,
)?;
if let Some(expected_tags) = expected.tags.as_ref()
&& document.tags.as_ref() != Some(expected_tags)
{
return Err(anyhow!(
"snapshot response record {:?}/{:?} has unexpected tags: expected {:?}, got {:?}",
identity.0,
identity.1,
expected_tags,
document.tags
));
}
}
Ok(documents)
}
}
pub fn query_read_only_raw_snapshot<F>(
query: &CultNetRawSnapshotQuery,
exchange: F,
) -> Result<Vec<CultNetRawDocumentRecord>>
where
F: FnOnce(CultNetMessage) -> Result<CultNetMessage>,
{
query.accept_response(exchange(query.request())?)
}
fn require_expected_metadata(
field: &str,
expected: Option<&str>,
actual: Option<&str>,
identity: &(String, String),
) -> Result<()> {
if let Some(expected) = expected
&& actual != Some(expected)
{
return Err(anyhow!(
"snapshot response record {:?}/{:?} has unexpected {field}: expected {:?}, got {:?}",
identity.0,
identity.1,
expected,
actual
));
}
Ok(())
}
fn reject_duplicates(values: Option<&[String]>, label: &str) -> Result<()> {
let Some(values) = values else {
return Ok(());
};
let mut seen = BTreeSet::new();
for value in values {
require_non_empty(value, label)?;
if !seen.insert(value) {
return Err(anyhow!("duplicate {label} {value:?}"));
}
}
Ok(())
}
fn require_non_empty(value: &str, field: &str) -> Result<()> {
if value.trim().is_empty() {
return Err(anyhow!("{field} must be non-empty"));
}
Ok(())
}

View file

@ -0,0 +1,222 @@
use anyhow::Result;
use cultnet_rs::{
CultNetDocumentBinding, CultNetDocumentRegistry, CultNetMessage, CultNetRawDocumentRecord,
CultNetRawPayloadEncoding, CultNetRawSnapshotQuery, CultNetReadOnlySnapshotPolicy,
CultNetSnapshotRecordExpectation, CultNetSnapshotSourceExpectation, CultNetWireContract,
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, query_read_only_raw_snapshot,
serve_read_only_raw_snapshot,
};
const HEALTH_SCHEMA: &str = "idunn.managed_health_projection.v1";
fn registry() -> CultNetDocumentRegistry {
let mut registry = CultNetDocumentRegistry::new();
registry.register(CultNetDocumentBinding {
schema_id: HEALTH_SCHEMA.to_string(),
document_type: "idunn.managed-health-projection".to_string(),
mutation_contract: None,
payload_schema_version: Some(HEALTH_SCHEMA.to_string()),
});
registry
}
fn record(key: &str, payload: Vec<u8>) -> CultNetRawDocumentRecord {
CultNetRawDocumentRecord {
schema_id: HEALTH_SCHEMA.to_string(),
record_key: key.to_string(),
stored_at: "2026-07-19T20:00:00Z".to_string(),
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
payload,
source_runtime_id: Some("idunn@yggdrasil".to_string()),
source_agent_id: Some("idunn".to_string()),
source_role: Some("deployment-owner".to_string()),
tags: Some(vec!["public-health".to_string()]),
}
}
fn expectation(key: &str) -> CultNetSnapshotRecordExpectation {
CultNetSnapshotRecordExpectation {
schema_id: HEALTH_SCHEMA.to_string(),
record_key: key.to_string(),
source: CultNetSnapshotSourceExpectation {
runtime_id: Some("idunn@yggdrasil".to_string()),
agent_id: Some("idunn".to_string()),
role: Some("deployment-owner".to_string()),
tags: Some(vec!["public-health".to_string()]),
},
}
}
#[test]
fn canonical_wire_loop_returns_exact_stored_raw_record_without_cache_apply() -> Result<()> {
let stored = record("epiphany-agent", vec![0x95, 0xc4, 0x02, 0xde, 0xad]);
let source = vec![stored.clone(), record("not-public", vec![0x01])];
let mut policy = CultNetReadOnlySnapshotPolicy::new();
policy.allow(HEALTH_SCHEMA, "epiphany-agent")?;
let query = CultNetRawSnapshotQuery::new("status-42", vec![expectation("epiphany-agent")])?;
let received = query_read_only_raw_snapshot(&query, |request| {
// This is the canonical transport loop: request and response both cross
// the CultNet wire codec. Neither side receives a cache to mutate.
let request_wire =
encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?;
let decoded_request =
decode_cultnet_message_from_slice(&request_wire, CultNetWireContract::CultNetSchemaV0)?;
let response =
serve_read_only_raw_snapshot(&registry(), &policy, &source, &decoded_request)?;
let response_wire =
encode_cultnet_message_to_vec(&response, CultNetWireContract::CultNetSchemaV0)?;
decode_cultnet_message_from_slice(&response_wire, CultNetWireContract::CultNetSchemaV0)
})?;
assert_eq!(received, vec![stored]);
Ok(())
}
#[test]
fn server_filters_by_exact_policy_pair_and_request() -> Result<()> {
let source = vec![record("epiphany-agent", vec![1]), record("odin", vec![2])];
let mut policy = CultNetReadOnlySnapshotPolicy::new();
policy.allow(HEALTH_SCHEMA, "epiphany-agent")?;
let request = CultNetMessage::SnapshotRequest {
message_id: "bounded".to_string(),
schema_ids: Some(vec![HEALTH_SCHEMA.to_string()]),
record_keys: Some(vec!["epiphany-agent".to_string(), "odin".to_string()]),
};
let response = serve_read_only_raw_snapshot(&registry(), &policy, &source, &request)?;
let CultNetMessage::SnapshotResponseRaw { documents, .. } = response else {
panic!("expected raw response");
};
assert_eq!(documents, vec![source[0].clone()]);
Ok(())
}
#[test]
fn server_rejects_duplicate_request_terms_and_ambiguous_backing_records() -> Result<()> {
let mut policy = CultNetReadOnlySnapshotPolicy::new();
policy.allow(HEALTH_SCHEMA, "epiphany-agent")?;
let duplicate_request = CultNetMessage::SnapshotRequest {
message_id: "duplicate-request".to_string(),
schema_ids: Some(vec![HEALTH_SCHEMA.to_string(), HEALTH_SCHEMA.to_string()]),
record_keys: Some(vec!["epiphany-agent".to_string()]),
};
let error = serve_read_only_raw_snapshot(
&registry(),
&policy,
&vec![record("epiphany-agent", vec![1])],
&duplicate_request,
)
.unwrap_err();
assert!(error.to_string().contains("duplicate requested schema id"));
let request = CultNetMessage::SnapshotRequest {
message_id: "duplicate-source".to_string(),
schema_ids: None,
record_keys: None,
};
let duplicate = record("epiphany-agent", vec![1]);
let error = serve_read_only_raw_snapshot(
&registry(),
&policy,
&vec![duplicate.clone(), duplicate],
&request,
)
.unwrap_err();
assert!(error.to_string().contains("duplicate record"));
Ok(())
}
#[test]
fn query_rejects_duplicate_expectations_wrong_message_and_unrelated_message() -> Result<()> {
let error = CultNetRawSnapshotQuery::new(
"duplicate",
vec![expectation("epiphany-agent"), expectation("epiphany-agent")],
)
.unwrap_err();
assert!(error.to_string().contains("duplicate requested record"));
let query = CultNetRawSnapshotQuery::new("wanted", vec![expectation("epiphany-agent")])?;
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "somebody-elses-response".to_string(),
documents: vec![],
})
.unwrap_err();
assert!(error.to_string().contains("does not match request"));
let error = query
.accept_response(CultNetMessage::Error {
error: "unrelated".to_string(),
})
.unwrap_err();
assert!(
error
.to_string()
.contains("expected cultnet.snapshot_response_raw.v0")
);
Ok(())
}
#[test]
fn query_rejects_unexpected_identity_duplicates_and_source_metadata() -> Result<()> {
let query = CultNetRawSnapshotQuery::new("hostile", vec![expectation("epiphany-agent")])?;
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "hostile".to_string(),
documents: vec![record("odin", vec![1])],
})
.unwrap_err();
assert!(error.to_string().contains("unexpected record"));
let document = record("epiphany-agent", vec![1]);
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "hostile".to_string(),
documents: vec![document.clone(), document],
})
.unwrap_err();
assert!(error.to_string().contains("duplicate record"));
let mut forged = record("epiphany-agent", vec![1]);
forged.source_runtime_id = Some("mallory".to_string());
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "hostile".to_string(),
documents: vec![forged],
})
.unwrap_err();
assert!(error.to_string().contains("unexpected source_runtime_id"));
let mut forged = record("epiphany-agent", vec![1]);
forged.tags = Some(vec!["private".to_string()]);
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "hostile".to_string(),
documents: vec![forged],
})
.unwrap_err();
assert!(error.to_string().contains("unexpected tags"));
Ok(())
}
#[test]
fn server_rejects_unregistered_source_schema_even_when_not_exposed() -> Result<()> {
let mut foreign = record("foreign", vec![1]);
foreign.schema_id = "xenos.unregistered.v0".to_string();
let request = CultNetMessage::SnapshotRequest {
message_id: "unregistered".to_string(),
schema_ids: None,
record_keys: None,
};
let error = serve_read_only_raw_snapshot(
&registry(),
&CultNetReadOnlySnapshotPolicy::new(),
&vec![foreign],
&request,
)
.unwrap_err();
assert!(error.to_string().contains("unregistered schema"));
Ok(())
}