CultLib/packages/cultnet-rs
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Meta Vens b090ca97f9 CultNet selection cut1, commit 3: the Rust runtime
docs/cultnet-selection-cut.md section 6/7: packages/cultnet-rs/src/selection.rs
(new) - the Rust spelling of the vocabulary at wire parity with the corrected
C# reference (e5348d3), matching D7: no cultcache-rs knowledge, the row owner
supplies declared values and edges through two traits.

- Wire types: Selection, FieldPredicate, Citation, Incoming, RecordRef, Edge,
  RawDocumentHeader, SelectionDocumentRecord (the v1 full-shape record, distinct
  from v0's CultNetRawDocumentRecord, which lacks schemaName/schemaVersion/
  schemaContentHash - a pre-existing v0 gap this cut does not touch).
  SelectionOperator mirrors CultNetSelectionOperator for evaluator ergonomics;
  FieldPredicate.op stays a raw wire string, never a serde-tagged union.
- canonical_number module (Q-J, section 2 "Numbers"): is_canonical (a
  hand-rolled digit-grammar parser, no regex dependency added),
  canonicalize_decimal_digits, expand_scientific_notation, compare (sign, then
  integer length, then digits, then padded fraction - no f64 anywhere), and
  render_i64/render_u64/render_f64/render_f32 for a Row implementer's own
  rendering. probe_f64_display_never_uses_exponent_notation empirically
  verifies the map's claim about Rust's f64 Display (confirmed true) rather
  than trusting it.
- Row/RowSet traits (D7): schema_id, record_key, ordinal, values, number
  (canonical string, never f64), references for Row; all_schema_ids,
  declared_indexes, declared_roles, is_numeric, target_leaves for RowSet.
  A blanket `impl<T: Row> Row for &T` lets sorted/filtered slices of
  references satisfy generic bounds without an extra copy.
- validate (S1 door refusals), matches (D6 single-row fast path, hop-bearing
  selections assert via debug_assert since Rust has no exception type to
  mirror C#'s InvalidOperationException), select (order/hop/cursor/paging,
  D9's reference_outside_target refusal, S23's per-row match - never through
  a unique-index map, because there is none here to begin with).
- Cursor: mint/parse/digest is this runtime's own internal algorithm (a
  cursor is opaque and never crosses runtimes - each server answers its own
  pages), not a byte-for-byte port of the reference's; what must match is the
  *rule* (asOf + last position + a digest bound to the selection), which it
  does, pinned by RS-CursorStale-Revert/Loosening and RS-CursorDigest-Revert.
- contracts.rs: three v1 CultNetMessage variants (SnapshotRequestV1,
  DatabaseSubscribeV1, SnapshotResponseRawV1) matching the C# messages'
  field-for-field shape. SnapshotResponseRawV1 carries binary payloads
  (documents[].payload, edges[].payload), so it is routed through the
  existing raw JSON-bypass path (parse_raw_cultnet_schema_message/
  encode_raw_cultnet_schema_message) alongside v0's DocumentPutRaw/
  SnapshotResponseRaw, with its own require_*/encode_* helpers for
  SelectionDocumentRecord, RawDocumentHeader, Edge and RecordRef.
  SnapshotRequestV1/DatabaseSubscribeV1 carry no binary and use the
  ordinary serde_json-intermediate path. No message-layer selection
  semantics validation here, matching the reference
  (CultNetSchemaMessageSerialization.cs only deserializes; a server calls
  selection::validate against its own RowSet before evaluating).
- snapshot_query.rs (D3/D4): serve_read_only_raw_snapshot's two hand-rolled
  allowlist filters collapse into one call to selection::matches over a
  lowered v0 Selection, through a minimal RawSnapshotRow wrapper whose
  ordinal/values/number/references are unreachable (the lowered selection
  never sets fields/cites/cited, so matches_schema_keys_fields never calls
  them) - documented, not hidden.

Ruling (Self, 2026-09-22, docs/cultnet-selection-cut.md commit 2 fix batch,
mirrored here per the coordinator's mid-task instruction rather than C#'s
pre-fix spelling as it stood at e5348d3):
- validate refuses an empty-but-present schemas/keys list (already had this)
  and now also refuses any individual entry that is empty or whitespace
  (fields[i]-style names: schemas[i]/keys[i]).
- The evaluator never sees []; matches_schema_keys_fields does not special-case
  an empty list as "no filter" (it never did here - that C# fallback,
  CultNetSelectionEvaluator.cs:84 pre-fix, was never mirrored into Rust).
- snapshot_query.rs's v0 lowering gets its own cleaning, owned by the
  lowering and not the evaluator: lower_v0_list turns an empty or
  all-blank v0 schemaIds/recordKeys list into None before it ever reaches
  validate or select.

Tests: cultnet-rs 173 passed, 0 failed (was 111 baseline #[test]s pre-cut;
+62 across lib unit tests, tests/selection.rs and tests/cultnet.rs).
cultcache-rs unmodified, 64 passed, 0 failed (untouched by this commit -
confirmed unaffected). GameCult.Networking.Tests (the new
SelectionParityVectorTests.cs file, compiled but not yet fully exercised -
see below) builds clean.

Mutation harness (tools/eureka-mutations.ps1, scripts/mutate-cultnet-
selection-rust.entries.ps1): 22 entries against src/selection.rs and
src/snapshot_query.rs, all KILLED, M0 green. Covers: S1's empty-list and
new blank-entry refusals (schemas and keys, revert x4), order/descending
(revert), cursor staleness (revert + loosening) and digest (revert), S7's
incoming negation (revert + loosening), S16's le/ge boundaries (revert x2),
S18's reference_outside_target (revert), Q-J's door regex and -0 exclusion
(revert x2), Q-J's comparator integer-length and sign (revert x2), Q-J's
integer-through-float64 renderer, decimal trailing-zero stripping and
exponent expansion (revert x3, the last two pinned via direct
canonical_number unit tests since render_f64 itself cannot reach exponent
notation given Rust's Display contract - verified, not assumed), and the
new v0-lowering rule (revert).

Negative grep: `rg -n "untagged" packages/cultnet-rs/src packages/cultcache-rs/src`
empty.

Not included here, landing as commit 4 once ready: the committed parity
vector files (contracts/cultnet/interop/selection-vectors.{cs,rs}-written.json).
Both directions already work for six evaluated selections and the []
door-refusal case; the blank-key-entry refusal vector cannot be generated
from the C# side yet because the parallel C# fix batch implementing that
door check (docs/cultnet-selection-cut.md, "Self's rulings...for the commit
2 fix batch") has not landed on this branch as of this commit. Rust's own
tests (validation_refuses_a_blank_entry_in_schemas_or_keys,
serve_read_only_raw_snapshot_lowers_an_empty_or_blank_v0_schema_list_to_no_filter)
already pin both new rules independently of C#.

Structural delta: packages/cultnet-rs/src/selection.rs +1407 (new),
contracts.rs +616/-21, snapshot_query.rs +76/-21 (net +55, collapsing the
fifth selector engine into one call), lib.rs +2, tests/cultnet.rs +67 (new
v0-lowering test), tests/selection.rs +900 (new, evaluator tests + vector
machinery), scripts/mutate-cultnet-selection-rust.entries.ps1 +233 (new),
tests/GameCult.Networking.Tests/SelectionParityVectorTests.cs +296 (new).
Against section 14's ~430-line estimate for selection.rs+contracts.rs: the
two together land at ~2000 lines added, well over estimate - the map's own
§14 correction already flagged commits 0/1 running roughly 2x estimate for
the same reason (the hop's incoming index, the cursor, and per-field door
messages cost more than the prose assumed), and the v1 raw-message handling
(SelectionDocumentRecord/RawDocumentHeader/Edge require_*/encode_* helpers,
~400 lines) was not separately budgeted at all.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-22 05:31:19 +02:00
..
examples Merge the CultCache store-routing cuts into main 2026-09-14 15:16:29 +02:00
src CultNet selection cut1, commit 3: the Rust runtime 2026-09-22 05:31:19 +02:00
tests CultNet selection cut1, commit 3: the Rust runtime 2026-09-22 05:31:19 +02:00
.gitignore Bring language packages into CultLib monorepo 2026-05-30 00:39:39 +01:00
Cargo.toml Return the Idunn and Odin authority contracts to CultLib 2026-09-03 22:56:59 +02:00
README.md Add Rust reactive document sync 2026-06-28 00:31:35 +01:00

CultNet RS

cultnet-rs is the Rust sibling of cultnet-ts: typed MessagePack messages, 4-byte length-prefixed direct-pipe framing, CultLib-shaped security helpers, and CultCache replication without making callers paw through raw envelopes like we lost a bet.

The contract is intentionally boring:

  • cultnet.schema.v0 sends schema-versioned MessagePack objects.
  • gamecult.networking.v0 maps the legacy C# union shape explicitly.
  • schema discovery uses explicit catalog request/response messages; no inbound auto-detect sludge.
  • document put/delete/snapshot messages move typed CultCache entries.
  • raw document put/snapshot messages preserve canonical MessagePack payload bytes for bit-compatible neighbors.
  • hello messages advertise supportedMutationContracts, so callers discover which document types are read-only, which accept typed intents, which authority owns the mutation, and which receipt documents prove the outcome.
  • payloads are decoded through registered Rust types before entering the cache.

This crate is not an HTTP wrapper. It is the wire vocabulary Epiphany, Ghostlight, VoidBot, and the rest of the swarm can share.

The public API surface is the schema plus its mutation contracts. A runtime does not expose a pile of bespoke verbs and hope everyone remembers the ritual; it advertises typed documents, typed intents, and typed receipts. Polite machines knock on the contract before touching the furniture.

Receipts

cargo test

The initial tests prove:

  • CultLib-compatible AES-GCM string encryption and HMAC session tokens
  • 4-byte big-endian MessagePack framing
  • schema-versioned message round trips
  • legacy gamecult.networking.v0 login mapping
  • schema discovery catalog responses with canonical JSON schema hashes
  • shard catalog request/response filtering and response application
  • CultCache snapshot replication through registered typed documents
  • raw snapshot replication that preserves the original payload bytes
  • raw snapshot replication into a local same-schema Rust alias type
  • document mutation contract advertisement through hello frames and registries

Schema Discovery

cultnet-rs now ships a built-in schema registry for the shared swarm contract surface:

  • core wire messages
  • legacy gamecult.networking.v0 auth/sample payloads
  • schema catalog request/response messages
  • shard catalog request/response messages
  • the canonical ghostlight.agent-state document payload schema

Use builtin_schema_registry() or CultMesh::create_builtin_schema_registry() when you want the standard catalog, or register your own closed-world schema set with CultNetSchemaRegistry / CultMesh::create_schema_registry(). Discovery stays explicit on purpose: peers advertise only the contracts they were compiled to understand, the same way CultCache only consumes the document types you registered instead of pretending polymorphism is a public park.

Shard Catalogs

Rust now exposes the same shard topology vocabulary as the other runtimes without claiming to be the full C# service body:

use cultnet_rs::{CultMesh, CultNetMessage, CultNetShardDescriptor};

let mut catalog = CultMesh::create_shard_catalog();
catalog.upsert(CultNetShardDescriptor {
    shard_id: "notes-a".to_string(),
    owner_runtime_id: "rust-primary".to_string(),
    epoch: 3,
    is_primary: Some(true),
    schema_ids: vec!["note.v0".to_string()],
    key_prefix: Some("note:".to_string()),
    primary_endpoints: vec!["rudp://127.0.0.1:4100".to_string()],
    replica_endpoints: vec![],
    read_replica_endpoints: vec![],
    region: None,
    authority_lease_id: None,
})?;

let response = catalog.create_catalog_response(&CultNetMessage::ShardCatalogRequest {
    message_id: "discover-shards".to_string(),
    schema_ids: Some(vec!["note.v0".to_string()]),
    record_keys: Some(vec!["note:1".to_string()]),
})?;

CultNetShardCatalog::apply_response(...) imports remote cultnet.shard_catalog_response.v0 descriptors into the local catalog. The catalog owns topology inspection only; shard-log serving, daemon policy, and game-session authority remain separate responsibilities.

Local Fast Lane

cultnet-rs now mirrors the raw replication seam from cultnet-ts:

  • cultnet.document_put_raw.v0
  • cultnet.snapshot_response_raw.v0

Those messages carry the exact persisted MessagePack payload bytes from CultCache along with the typed envelope metadata. Combined with CultCache::put_envelope::<T>(), that lets a bit-compatible neighbor ingest the document without re-encoding the payload first.

The receiving Rust type does not have to be the sender's concrete Rust type. If the local registry binds a different DatabaseEntry to the same schema id, sync_raw_document_from_snapshot_response::<LocalAlias>(...) hydrates one local alias type directly:

let mut target_registry = CultNetDocumentRegistry::new();
target_registry.register(CultNetDocumentBinding::for_entry_with_schema_id::<UiNote>(
    "aetheria.note.v1".to_string(),
    "aetheria.note.v1".to_string(),
));

let note = target_registry.sync_raw_document_from_snapshot_response::<UiNote>(
    &mut target_cache,
    &snapshot_response,
    "note:bridge",
)?;

That still is not zero-copy in the religious sense. Frames allocate, bytes move, and the receiving cache still decodes once to keep typed reads and validation honest. The win is narrower and realer: identical payload bytes stop getting decoded into generic sludge and then encoded right back into the same bytes for no reason.

Reactive Documents

For local state that should feel owned by the caller, Rust can wrap a registered CultCache record as a managed reactive document:

use std::sync::{Arc, Mutex};
use cultnet_rs::{CultNetReactiveDocumentOptions, CultNetDocumentRegistry};

let cache = Arc::new(Mutex::new(target_cache));
let note = registry.reactive_document::<UiNote>(
    Arc::clone(&cache),
    "note:bridge",
    CultNetReactiveDocumentOptions::default(),
)?;

{
    let current = note.current();
    current.lock().unwrap().body = "local prediction".to_string();
}

The handle polls the serialized current value on the configured debounce cadence and flushes changed state back through the typed cache. update(...), set_current(...), mark_dirty(), and flush() are available when the caller 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(...) 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 keys such as "0" and "1" when field names are not present on the wire.

CultMesh Rust Facade

Rust is still the low-level substrate runtime, not a clone of the C# game server. It does now expose the small CultMesh entrypoint needed for practical contact and authority ergonomics:

use cultnet_rs::{
    CultMesh, CultMeshAuthorityLease, CultMeshPeerCard, CultMeshRudpClientOptions,
    CultMeshRudpSocketOptions, CultNetMessage, CultNetSchemaKind,
};
use chrono::{Duration, Utc};

let schemas = CultMesh::create_builtin_schema_registry()?;
let shared_contracts = schemas.list(&cultnet_rs::CultNetSchemaCatalogOptions {
    include_schema_json: false,
    schema_ids: None,
    kinds: Some(vec![CultNetSchemaKind::SharedContract]),
});

let mut server = CultMesh::create_rudp_server(
    "rust-server",
    0x1020_3040,
    CultMeshRudpSocketOptions::default(),
)?;
let port = server.profile.transports[0].port.unwrap();

let peer = CultMeshPeerCard::new(
    "rust-server",
    "local",
    [format!("rudp://127.0.0.1:{port}")],
)
.with_roles(["schema"])
.with_authority_lease_id("lease:rust-server");

let now = Utc::now();
let mut peers = CultMesh::create_peer_catalog();
let mut leases = CultMesh::create_authority_lease_catalog();
peers.upsert(peer.clone())?;
leases.upsert(CultMeshAuthorityLease {
    lease_id: "lease:rust-server".to_string(),
    verse_id: "local".to_string(),
    peer_id: "rust-server".to_string(),
    roles: vec!["schema".to_string()],
    shard_ids: Vec::new(),
    issuer_runtime_id: None,
    valid_from: now - Duration::minutes(1),
    expires_at: now + Duration::minutes(1),
})?;

let mut client = CultMesh::connect_rudp_client_for_authorized_peer(
    "rust-client",
    0x1020_3040,
    &peers,
    &leases,
    "local",
    "schema",
    None,
    now,
    CultMeshRudpClientOptions {
        socket_options: CultMeshRudpSocketOptions::default(),
        connect_payload: b"join".to_vec(),
        ..CultMeshRudpClientOptions::default()
    },
)?;
client.send_schema_message(&CultNetMessage::SchemaCatalogRequest {
    message_id: "rust-schema-catalog".to_string(),
    include_schema_json: Some(false),
    schema_ids: None,
    kinds: Some(vec![CultNetSchemaKind::DocumentPayload]),
})?;

create_rudp_client... remains available when the caller intentionally owns the handshake and polling loop. connect_rudp_client... performs the client handshake before returning the same schema-message-capable RUDP transport.

For caller-owned reconnect loops, CultNetRudpReconnectLoop keeps transport construction outside the library while sharing the portable retry controller:

use cultnet_rs::{
    CultNetReconnectPolicyOptions, CultNetRudpReconnectLoop, create_reconnect_policy,
};

let policy = create_reconnect_policy(CultNetReconnectPolicyOptions::default());
let mut reconnect = CultNetRudpReconnectLoop::new(policy, b"join".to_vec(), || {
    CultMesh::create_rudp_client_for_peer(
        "rust-client",
        0x1020_3040,
        &peer,
        CultMeshRudpSocketOptions::default(),
    )
});

reconnect.start()?;
let decision = reconnect.handle_closed(now_ms, 0);
if decision.is_some() {
    reconnect.reconnect_if_due(now_ms)?;
}

CultMesh::parse_rudp_endpoint(...) handles advertised rudp://host:port contact hints, and CultMeshAuthorityLeaseCatalog keeps trust separate from discovery. A peer card can say where to dial; peers.first_authorized(...) and CultMesh::create_rudp_client_for_authorized_peer(...) only use that contact hint after a lease says the peer may own the requested role or shard.