1459 lines
54 KiB
Rust
1459 lines
54 KiB
Rust
use super::super::error::WalError;
|
||
use crate::replication::{RegionId, ShardId};
|
||
|
||
// ── Signal batch format ─────────────────────────────────────────────────────
|
||
|
||
/// Magic bytes identifying a tidalDB WAL batch frame: "TIDL" in LE byte order.
|
||
///
|
||
/// Stored as `[0x44, 0x4C, 0x49, 0x54]` which is `0x54494C44` as a u32 LE.
|
||
/// This allows `u32::from_le_bytes(magic) == 0x54494C44` to validate.
|
||
pub const MAGIC: [u8; 4] = [0x44, 0x4C, 0x49, 0x54];
|
||
|
||
/// Wire format version 1: original single-node format. Bytes 28-31 are
|
||
/// zero-padded reserved space. Event records are 21 bytes.
|
||
pub const FORMAT_VERSION_V1: u8 = 1;
|
||
|
||
/// Wire format version 2: adds `shard_id` and `region_id` to the header.
|
||
///
|
||
/// Bytes 28-29 carry `shard_id` (u16 LE) and bytes 30-31 carry `region_id`
|
||
/// (u16 LE) for multi-node replication. Backward compatible with v1
|
||
/// because v1 always wrote zeros at bytes 28-31, which decode as
|
||
/// `ShardId::SINGLE` and `RegionId::SINGLE`. Event records are 21 bytes.
|
||
pub const FORMAT_VERSION_V2: u8 = 2;
|
||
|
||
/// Wire format version 3 (M9): widens the per-event record from 21 to 32 bytes
|
||
/// to carry governance metadata — `scope`, `writer_agent`, `share_policy_version`
|
||
/// and `membership_epoch`.
|
||
///
|
||
/// The 64-byte header is unchanged (shard/region still at bytes 28-31). Only the
|
||
/// event payload grows. v1/v2 batches (21-byte events) still decode: the new
|
||
/// governance fields default to zero, i.e. [`SignalScope::Local`], a direct
|
||
/// (non-agent) writer, share-policy version 0, and membership epoch 0 — exactly
|
||
/// the semantics those events had before scopes existed.
|
||
///
|
||
/// [`SignalScope::Local`]: crate::governance::scope::SignalScope::Local
|
||
pub const FORMAT_VERSION_V3: u8 = 3;
|
||
|
||
/// Current wire format version. All new batches are encoded as v3.
|
||
pub const FORMAT_VERSION: u8 = FORMAT_VERSION_V3;
|
||
|
||
/// Record type discriminant for signal events.
|
||
pub const RECORD_TYPE_SIGNAL: u8 = 0x01;
|
||
|
||
// ── Batch kinds (m11p2: one replicated log) ─────────────────────────────────
|
||
//
|
||
// The header's `flags` byte (byte 5, reserved-and-always-zero before m11p2)
|
||
// is the batch KIND. Kind 0 is the original fixed-size signal-event payload —
|
||
// every batch ever written before m11p2 carries it, so old logs decode
|
||
// unchanged. Kinds 1/2 carry ONE variable-length blob record (item metadata /
|
||
// item embedding) and consume exactly one seqno (`event_count == 1`). The
|
||
// framing (magic, payload_len, BLAKE3 over header[0..32] || payload) is
|
||
// IDENTICAL for all kinds, so the recovery scanner and segment rotation never
|
||
// branch on kind.
|
||
//
|
||
// Compatibility: a pre-m11p2 reader treats `flags` as reserved and would
|
||
// misparse a blob payload as event records, so `decode_batch` on an OLD
|
||
// binary fails the event-size check and surfaces Corruption — a loud halt,
|
||
// never silent misapplication. Mixed-version clusters must therefore upgrade
|
||
// followers before the leader ships kind-1/2 batches (runbook upgrade note;
|
||
// the version handshake lands in m11p8).
|
||
|
||
/// Batch kind: fixed-size signal event records (the original payload).
|
||
pub const BATCH_KIND_SIGNALS: u8 = 0;
|
||
/// Batch kind: one item-metadata blob record.
|
||
pub const BATCH_KIND_ITEM_METADATA: u8 = 1;
|
||
/// Batch kind: one item-embedding blob record.
|
||
pub const BATCH_KIND_EMBEDDING: u8 = 2;
|
||
/// Batch kind: one term-marker record (m11p4 leader election).
|
||
///
|
||
/// Journaled by a leader as its FIRST log entry of an elected term (≥ 1) and
|
||
/// replicated like any record, so every replica's WAL carries the term of the
|
||
/// leadership that wrote its tail — the `(lastLogTerm, lastLogIndex)` half of
|
||
/// Raft's vote restriction, crash-atomic with the frontier by construction
|
||
/// (they live in the same fsync stream). Never written at term 0 (the
|
||
/// topology-file era), so a rolling m11p3→m11p4 upgrade ships zero unknown
|
||
/// record kinds until the first election — which itself requires a vote
|
||
/// quorum of upgraded binaries.
|
||
pub const BATCH_KIND_TERM_MARKER: u8 = 3;
|
||
|
||
/// Batch kind: one cluster-membership record (m11p5 conf-changes).
|
||
///
|
||
/// Carries the FULL voter/learner/removed roster as data on the one replicated
|
||
/// log (the §3 design): the leader journals it, every replica folds it into a
|
||
/// `ClusterMembership` cell, and recovery re-derives the roster from the last
|
||
/// record at-or-below the durable frontier (latest version wins — no merge
|
||
/// logic, because records are full snapshots, not deltas). Folding has no
|
||
/// storage effect, exactly like the kind-3 term marker.
|
||
///
|
||
/// Compatibility mirrors kind-3: membership epoch 0 IS the topology file, so a
|
||
/// cluster that has never run a conf-change ships zero kind-4 records and
|
||
/// behaves byte-for-byte as before. A kind-4 record reaching a pre-p5 follower
|
||
/// is an unknown batch kind → `Corruption` → the receiver's torn-state halt;
|
||
/// the leader's capability gate (§3.1, a later stage) is what prevents that.
|
||
pub const BATCH_KIND_MEMBERSHIP: u8 = 4;
|
||
|
||
/// Record-level format version of a kind-4 membership payload (byte 0).
|
||
///
|
||
/// Distinct from the 64-byte frame's [`FORMAT_VERSION`], so the membership
|
||
/// record can evolve its field set independently of the frame; an unknown
|
||
/// value is `Corruption` (forward-compatible refusal, never a silent misparse).
|
||
pub const MEMBERSHIP_RECORD_VERSION: u8 = 1;
|
||
|
||
/// Hard ceiling on the number of members in one kind-4 record.
|
||
///
|
||
/// Far above any realistic cluster (the design's reference `StatefulSet` is
|
||
/// single digits) while bounding the decode allocation a hostile/torn payload
|
||
/// can request.
|
||
pub const MAX_MEMBERSHIP_MEMBERS: usize = 4096;
|
||
|
||
/// Hard ceiling on a single member's `name`/`grpc_addr`/`http_addr` string.
|
||
///
|
||
/// A DNS name plus scheme/port stays well under this; the bound stops a torn
|
||
/// length prefix from driving a multi-gigabyte allocation before the frame's
|
||
/// own [`MAX_BLOB_PAYLOAD_BYTES`] check can fire.
|
||
pub const MAX_MEMBERSHIP_STRING_BYTES: usize = 4096;
|
||
|
||
/// Size of the batch header in bytes (one cache line).
|
||
pub const HEADER_SIZE: usize = 64;
|
||
|
||
/// Byte offset of the `payload_len` (u32 LE) field within the batch header.
|
||
///
|
||
/// The header layout is owned here (see [`BatchHeader`]); readers that need to
|
||
/// size a batch before a full decode must reference this constant rather than
|
||
/// re-hardcoding the offset, so the framing can never drift between the encoder
|
||
/// and the recovery scanner.
|
||
pub const HEADER_PAYLOAD_LEN_OFFSET: usize = 24;
|
||
|
||
/// Length in bytes of the `payload_len` field (a u32).
|
||
const PAYLOAD_LEN_FIELD_SIZE: usize = 4;
|
||
|
||
/// Size of a v1/v2 event record in bytes (the legacy, pre-governance layout).
|
||
pub const EVENT_SIZE: usize = 21;
|
||
|
||
/// Size of a v3 event record in bytes (legacy 21 + 11 governance bytes).
|
||
pub const EVENT_SIZE_V3: usize = 32;
|
||
|
||
/// Maximum number of events in a single batch.
|
||
pub const MAX_EVENTS_PER_BATCH: u16 = 256;
|
||
|
||
/// Read the `payload_len` field from a slice positioned at a batch header.
|
||
///
|
||
/// `header` must begin at the batch's magic bytes and contain at least
|
||
/// [`HEADER_SIZE`] bytes. This is the single owner of the `payload_len` byte
|
||
/// offset, used by the recovery scanner to bound a batch before a full
|
||
/// [`decode_batch`] so the offset cannot drift from the header layout.
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` if `header` is shorter than the field.
|
||
pub fn payload_len_from_header(header: &[u8]) -> Result<u32, WalError> {
|
||
let end = HEADER_PAYLOAD_LEN_OFFSET + PAYLOAD_LEN_FIELD_SIZE;
|
||
let field = header
|
||
.get(HEADER_PAYLOAD_LEN_OFFSET..end)
|
||
.ok_or_else(|| WalError::Corruption {
|
||
message: "failed to read payload_len".into(),
|
||
})?;
|
||
Ok(u32::from_le_bytes(field.try_into().map_err(|_| {
|
||
WalError::Corruption {
|
||
message: "failed to read payload_len".into(),
|
||
}
|
||
})?))
|
||
}
|
||
|
||
/// The on-wire event-record size for a given format version.
|
||
#[must_use]
|
||
pub const fn event_size_for_version(version: u8) -> usize {
|
||
match version {
|
||
FORMAT_VERSION_V3 => EVENT_SIZE_V3,
|
||
// v1 and v2 (and, defensively, anything else accepted by decode) use the
|
||
// legacy 21-byte layout.
|
||
_ => EVENT_SIZE,
|
||
}
|
||
}
|
||
|
||
/// Decoded batch header.
|
||
///
|
||
/// # Wire layout (64 bytes, one cache line)
|
||
///
|
||
/// ```text
|
||
/// Bytes 0- 3: MAGIC [0x44, 0x4C, 0x49, 0x54] ("TIDL")
|
||
/// Byte 4: format version (u8)
|
||
/// Byte 5: flags (u8, reserved)
|
||
/// Bytes 6- 7: event_count (u16 LE)
|
||
/// Bytes 8-15: first_seq (u64 LE)
|
||
/// Bytes 16-23: batch_timestamp (u64 LE)
|
||
/// Bytes 24-27: payload_len (u32 LE)
|
||
/// Bytes 28-29: shard_id (u16 LE) -- v2+; zero in v1 and single-node
|
||
/// Bytes 30-31: region_id (u16 LE) -- v2+; zero in v1 and single-node
|
||
/// Bytes 32-63: BLAKE3 checksum (32 bytes)
|
||
/// ```
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub struct BatchHeader {
|
||
pub version: u8,
|
||
pub flags: u8,
|
||
pub event_count: u16,
|
||
pub first_seq: u64,
|
||
pub batch_timestamp: u64,
|
||
pub payload_len: u32,
|
||
pub checksum: [u8; 32],
|
||
/// Shard that produced this batch. `ShardId::SINGLE` (0) in single-node
|
||
/// deployments and when reading v1 batches.
|
||
pub shard_id: ShardId,
|
||
/// Region that produced this batch. `RegionId::SINGLE` (0) in single-node
|
||
/// deployments and when reading v1 batches.
|
||
pub region_id: RegionId,
|
||
}
|
||
|
||
/// A single signal event record in wire format.
|
||
///
|
||
/// The first four fields (`entity_id`, `signal_type`, `weight`,
|
||
/// `timestamp_nanos`) are the original v1/v2 payload. The remaining fields are
|
||
/// the v3 governance envelope (M9); when reading a v1/v2 batch they decode to
|
||
/// their zero defaults (local scope, direct writer, no share policy, epoch 0).
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub struct EventRecord {
|
||
pub entity_id: u64,
|
||
pub signal_type: u8,
|
||
pub weight: f32,
|
||
pub timestamp_nanos: u64,
|
||
/// v3 — [`SignalScope`](crate::governance::scope::SignalScope) discriminant.
|
||
pub scope: u8,
|
||
/// v3 — interned writer-agent id (0 = direct user write).
|
||
pub writer_agent: u16,
|
||
/// v3 — share-policy version in effect at write time.
|
||
pub share_policy_version: u16,
|
||
/// v3 — membership epoch in effect (0 when not community-scoped).
|
||
pub membership_epoch: u32,
|
||
}
|
||
|
||
impl EventRecord {
|
||
/// Construct a default-scope (local) event — the common case.
|
||
#[must_use]
|
||
pub const fn signal(
|
||
entity_id: u64,
|
||
signal_type: u8,
|
||
weight: f32,
|
||
timestamp_nanos: u64,
|
||
) -> Self {
|
||
Self {
|
||
entity_id,
|
||
signal_type,
|
||
weight,
|
||
timestamp_nanos,
|
||
scope: 0,
|
||
writer_agent: 0,
|
||
share_policy_version: 0,
|
||
membership_epoch: 0,
|
||
}
|
||
}
|
||
|
||
/// Construct an event carrying explicit governance metadata.
|
||
///
|
||
/// The eight parameters are the flat v3 wire fields; this is the raw
|
||
/// record constructor, so they are passed positionally rather than via a
|
||
/// wrapper struct.
|
||
#[must_use]
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub const fn scoped(
|
||
entity_id: u64,
|
||
signal_type: u8,
|
||
weight: f32,
|
||
timestamp_nanos: u64,
|
||
scope: u8,
|
||
writer_agent: u16,
|
||
share_policy_version: u16,
|
||
membership_epoch: u32,
|
||
) -> Self {
|
||
Self {
|
||
entity_id,
|
||
signal_type,
|
||
weight,
|
||
timestamp_nanos,
|
||
scope,
|
||
writer_agent,
|
||
share_policy_version,
|
||
membership_epoch,
|
||
}
|
||
}
|
||
|
||
/// Serialize this event into the 32-byte v3 wire format.
|
||
#[must_use]
|
||
pub fn to_bytes(&self) -> [u8; EVENT_SIZE_V3] {
|
||
let mut buf = [0u8; EVENT_SIZE_V3];
|
||
buf[0..8].copy_from_slice(&self.entity_id.to_le_bytes());
|
||
buf[8] = self.signal_type;
|
||
buf[9..13].copy_from_slice(&self.weight.to_le_bytes());
|
||
buf[13..21].copy_from_slice(&self.timestamp_nanos.to_le_bytes());
|
||
// v3 governance envelope.
|
||
buf[21] = self.scope;
|
||
buf[22..24].copy_from_slice(&self.writer_agent.to_le_bytes());
|
||
buf[24..26].copy_from_slice(&self.share_policy_version.to_le_bytes());
|
||
buf[26..30].copy_from_slice(&self.membership_epoch.to_le_bytes());
|
||
// buf[30..32] reserved (zero).
|
||
buf
|
||
}
|
||
|
||
/// Serialize this event into the legacy 21-byte v1/v2 wire format.
|
||
///
|
||
/// Drops the governance envelope. Used only for constructing legacy batches
|
||
/// (e.g. backward-compatibility tests); the live write path always emits v3.
|
||
#[must_use]
|
||
pub fn to_bytes_legacy(&self) -> [u8; EVENT_SIZE] {
|
||
let mut buf = [0u8; EVENT_SIZE];
|
||
buf[0..8].copy_from_slice(&self.entity_id.to_le_bytes());
|
||
buf[8] = self.signal_type;
|
||
buf[9..13].copy_from_slice(&self.weight.to_le_bytes());
|
||
buf[13..21].copy_from_slice(&self.timestamp_nanos.to_le_bytes());
|
||
buf
|
||
}
|
||
|
||
/// Deserialize an event, auto-detecting the layout by slice length.
|
||
///
|
||
/// A 21-byte slice is a legacy v1/v2 record (governance fields decode to
|
||
/// zero / [`SignalScope::Local`]); a 32-byte slice is a v3 record.
|
||
///
|
||
/// [`SignalScope::Local`]: crate::governance::scope::SignalScope::Local
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` if the slice is neither 21 nor 32 bytes.
|
||
pub fn from_bytes(bytes: &[u8]) -> Result<Self, WalError> {
|
||
match bytes.len() {
|
||
EVENT_SIZE => Self::from_bytes_legacy(bytes),
|
||
EVENT_SIZE_V3 => Self::from_bytes_v3(bytes),
|
||
other => Err(WalError::Corruption {
|
||
message: format!(
|
||
"event record: expected {EVENT_SIZE} or {EVENT_SIZE_V3} bytes, got {other}"
|
||
),
|
||
}),
|
||
}
|
||
}
|
||
|
||
/// Parse the shared base fields (bytes 0..21).
|
||
fn parse_base(bytes: &[u8]) -> Result<(u64, u8, f32, u64), WalError> {
|
||
let entity_id =
|
||
u64::from_le_bytes(bytes[0..8].try_into().map_err(|_| WalError::Corruption {
|
||
message: "event record: invalid entity_id bytes".into(),
|
||
})?);
|
||
let signal_type = bytes[8];
|
||
let weight =
|
||
f32::from_le_bytes(bytes[9..13].try_into().map_err(|_| WalError::Corruption {
|
||
message: "event record: invalid weight bytes".into(),
|
||
})?);
|
||
let timestamp_nanos =
|
||
u64::from_le_bytes(bytes[13..21].try_into().map_err(|_| WalError::Corruption {
|
||
message: "event record: invalid timestamp bytes".into(),
|
||
})?);
|
||
Ok((entity_id, signal_type, weight, timestamp_nanos))
|
||
}
|
||
|
||
/// Deserialize a legacy 21-byte record (governance defaults to zero).
|
||
fn from_bytes_legacy(bytes: &[u8]) -> Result<Self, WalError> {
|
||
let (entity_id, signal_type, weight, timestamp_nanos) = Self::parse_base(bytes)?;
|
||
Ok(Self::signal(
|
||
entity_id,
|
||
signal_type,
|
||
weight,
|
||
timestamp_nanos,
|
||
))
|
||
}
|
||
|
||
/// Deserialize a v3 32-byte record (with governance envelope).
|
||
fn from_bytes_v3(bytes: &[u8]) -> Result<Self, WalError> {
|
||
let (entity_id, signal_type, weight, timestamp_nanos) = Self::parse_base(bytes)?;
|
||
let scope = bytes[21];
|
||
let writer_agent =
|
||
u16::from_le_bytes(bytes[22..24].try_into().map_err(|_| WalError::Corruption {
|
||
message: "event record: invalid writer_agent bytes".into(),
|
||
})?);
|
||
let share_policy_version =
|
||
u16::from_le_bytes(bytes[24..26].try_into().map_err(|_| WalError::Corruption {
|
||
message: "event record: invalid share_policy_version bytes".into(),
|
||
})?);
|
||
let membership_epoch =
|
||
u32::from_le_bytes(bytes[26..30].try_into().map_err(|_| WalError::Corruption {
|
||
message: "event record: invalid membership_epoch bytes".into(),
|
||
})?);
|
||
// Bytes [30..32] are reserved and the encoder always writes them zero
|
||
// (see `to_bytes`). They are covered by the batch BLAKE3, so a flip here
|
||
// already fails the checksum at the batch level; this per-record check is
|
||
// the second line of defense for the rarer case where the reserved space
|
||
// is non-zero yet checksum-consistent (e.g. a future writer that started
|
||
// using these bytes, or a hand-crafted frame). Surfacing it as corruption
|
||
// — rather than silently discarding the bytes — keeps the reserved space
|
||
// genuinely reserved: an old reader will refuse a record whose semantics
|
||
// it cannot represent instead of decoding it with the new field dropped.
|
||
if bytes[30] != 0 || bytes[31] != 0 {
|
||
return Err(WalError::Corruption {
|
||
message: "event record: non-zero v3 reserved bytes [30..32]".into(),
|
||
});
|
||
}
|
||
Ok(Self::scoped(
|
||
entity_id,
|
||
signal_type,
|
||
weight,
|
||
timestamp_nanos,
|
||
scope,
|
||
writer_agent,
|
||
share_policy_version,
|
||
membership_epoch,
|
||
))
|
||
}
|
||
}
|
||
|
||
/// Encode a batch of events into the WAL wire format (single-node convenience).
|
||
///
|
||
/// Equivalent to `encode_batch_with_shard(events, first_seq, batch_ts,
|
||
/// ShardId::SINGLE, RegionId::SINGLE)`.
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` if `events` is empty or exceeds
|
||
/// `MAX_EVENTS_PER_BATCH`.
|
||
pub fn encode_batch(
|
||
events: &[EventRecord],
|
||
first_seq: u64,
|
||
batch_ts: u64,
|
||
) -> Result<Vec<u8>, WalError> {
|
||
encode_batch_with_shard(
|
||
events,
|
||
first_seq,
|
||
batch_ts,
|
||
ShardId::SINGLE,
|
||
RegionId::SINGLE,
|
||
)
|
||
}
|
||
|
||
/// Encode a batch of events with explicit shard and region identity.
|
||
///
|
||
/// Produces a byte vector containing the 64-byte header followed by tightly
|
||
/// packed 32-byte v3 event records. The BLAKE3 checksum covers
|
||
/// `header[0..32] || event_bytes`, which includes the shard/region bytes.
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` if `events` is empty or exceeds
|
||
/// `MAX_EVENTS_PER_BATCH`.
|
||
pub fn encode_batch_with_shard(
|
||
events: &[EventRecord],
|
||
first_seq: u64,
|
||
batch_ts: u64,
|
||
shard_id: ShardId,
|
||
region_id: RegionId,
|
||
) -> Result<Vec<u8>, WalError> {
|
||
let event_count = events.len();
|
||
if event_count == 0 || event_count > usize::from(MAX_EVENTS_PER_BATCH) {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"batch event count {event_count} out of range [1, {MAX_EVENTS_PER_BATCH}]"
|
||
),
|
||
});
|
||
}
|
||
|
||
let mut payload = Vec::with_capacity(event_count * EVENT_SIZE_V3);
|
||
for event in events {
|
||
payload.extend_from_slice(&event.to_bytes());
|
||
}
|
||
encode_frame(
|
||
BATCH_KIND_SIGNALS,
|
||
event_count as u16,
|
||
&payload,
|
||
first_seq,
|
||
batch_ts,
|
||
shard_id,
|
||
region_id,
|
||
)
|
||
}
|
||
|
||
/// Hard ceiling on a blob (kind-1/2) batch payload.
|
||
///
|
||
/// Far above any real item metadata or embedding (a 1536-dim f32 vector is
|
||
/// 6 KiB) while staying well under the 16 MiB segment rotation threshold and
|
||
/// the transport's 64 MiB cap.
|
||
pub const MAX_BLOB_PAYLOAD_BYTES: usize = 8 * 1024 * 1024;
|
||
|
||
/// One replicated item-metadata mutation (batch kind 1).
|
||
///
|
||
/// `metadata_bytes` is the SAME serialization the storage layer persists
|
||
/// (`db::metadata::serialize_metadata`), so leader storage, the wire, and
|
||
/// follower storage can never drift on the encoding.
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub struct ItemMetadataRecord {
|
||
pub entity_id: u64,
|
||
pub metadata_bytes: Vec<u8>,
|
||
}
|
||
|
||
/// One replicated item-embedding mutation (batch kind 2).
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub struct EmbeddingRecord {
|
||
pub entity_id: u64,
|
||
pub values: Vec<f32>,
|
||
}
|
||
|
||
/// One term-marker record (batch kind 3, m11p4): the first log entry an
|
||
/// elected leader journals in its term. Folding it has no storage effect —
|
||
/// replicas record `(term, seq)` as their WAL-tail term.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub struct TermMarkerRecord {
|
||
/// The elected term this marker opens (always ≥ 1).
|
||
pub term: u64,
|
||
/// The region that leads `term`.
|
||
pub leader_region: u16,
|
||
}
|
||
|
||
/// The role a member holds in the latest membership record (m11p5).
|
||
///
|
||
/// The discriminant is the on-disk encoding — it is PERMANENT. `Removed` is a
|
||
/// tombstone: a removed member keeps its id (ids are never reused, §3) so a
|
||
/// later record can never collide its burned id with a new join.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
#[repr(u8)]
|
||
pub enum MemberRole {
|
||
/// Counts toward election and commit-index quorums.
|
||
Voter = 0,
|
||
/// Receives the stream and reports, but is never counted toward any
|
||
/// quorum (promotion input only — §3.3 learner-marks blocker).
|
||
Learner = 1,
|
||
/// Tombstone: this id is burned. The node is fenced from the data plane;
|
||
/// its id is never reused.
|
||
Removed = 2,
|
||
}
|
||
|
||
impl MemberRole {
|
||
/// The on-disk discriminant byte.
|
||
#[must_use]
|
||
pub const fn to_byte(self) -> u8 {
|
||
self as u8
|
||
}
|
||
|
||
/// Decode a role byte. An unknown discriminant is rejected (a forward-only
|
||
/// schema; a pre-decode `Corruption` beats a silently-misread role).
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` for any byte outside `{0, 1, 2}`.
|
||
pub fn from_byte(b: u8) -> Result<Self, WalError> {
|
||
match b {
|
||
0 => Ok(Self::Voter),
|
||
1 => Ok(Self::Learner),
|
||
2 => Ok(Self::Removed),
|
||
other => Err(WalError::Corruption {
|
||
message: format!("membership record: unknown member role {other}"),
|
||
}),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// One member in a kind-4 membership record (m11p5).
|
||
///
|
||
/// `id` is PERMANENT — assigned once on join (`max(all ids ever) + 1`), never
|
||
/// renumbered, never reused even after a `Removed` tombstone. The addresses are
|
||
/// advertised (DNS-capable) host:port strings; this data layer does not parse
|
||
/// or validate them syntactically (that is the topology/transport layer's job).
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub struct MemberEntry {
|
||
/// Permanent member id (never renumbered, never reused).
|
||
pub id: u16,
|
||
/// Human-readable region name.
|
||
pub name: String,
|
||
/// Advertised gRPC address (host:port; DNS name or literal IP).
|
||
pub grpc_addr: String,
|
||
/// Advertised HTTP address (scheme://host:port).
|
||
pub http_addr: String,
|
||
/// This member's role in this roster snapshot.
|
||
pub role: MemberRole,
|
||
}
|
||
|
||
/// One cluster-membership record (batch kind 4, m11p5): the FULL roster.
|
||
///
|
||
/// Holds the `appending leader's term` at `version`. Records are snapshots, not
|
||
/// deltas — recovery folds the latest `version` at-or-below the durable
|
||
/// frontier with no merge logic. Folding has no storage effect; replicas record
|
||
/// `(version, term, members)` in their [`ClusterMembership`] cell.
|
||
///
|
||
/// [`ClusterMembership`]: crate::wal::ClusterMembership
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub struct MembershipRecord {
|
||
/// Monotonic conf version. The latest record (highest version) wins; a
|
||
/// re-applied or recovered older record never regresses the cell.
|
||
pub version: u64,
|
||
/// The leadership term that appended this roster.
|
||
pub term: u64,
|
||
/// The full member roster at this version (≥ 1 entry, unique ids).
|
||
pub members: Vec<MemberEntry>,
|
||
}
|
||
|
||
impl MembershipRecord {
|
||
/// Structurally validate the roster: non-empty, within the member ceiling,
|
||
/// and free of duplicate ids. Roles are validated at decode time (an
|
||
/// in-memory `MemberRole` is already a valid variant by construction).
|
||
///
|
||
/// Called by both the encoder (reject a malformed record before it enters
|
||
/// the log) and the decoder (reject a hostile/torn payload before it folds
|
||
/// the cell), so the leader, the wire, and the follower can never disagree
|
||
/// on what a valid roster is.
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` for an empty roster, a roster exceeding
|
||
/// [`MAX_MEMBERSHIP_MEMBERS`], or a duplicate member id.
|
||
pub fn validate(&self) -> Result<(), WalError> {
|
||
if self.members.is_empty() {
|
||
return Err(WalError::Corruption {
|
||
message: "membership record: roster is empty (a cluster has at least one member)"
|
||
.into(),
|
||
});
|
||
}
|
||
if self.members.len() > MAX_MEMBERSHIP_MEMBERS {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"membership record: {} members exceeds the {MAX_MEMBERSHIP_MEMBERS} ceiling",
|
||
self.members.len()
|
||
),
|
||
});
|
||
}
|
||
// Duplicate-id detection. The roster is small (single to low-double
|
||
// digits in practice), so an O(n²)-free pass via a sorted scan would be
|
||
// overkill; a HashSet keeps the intent obvious and stays O(n).
|
||
let mut seen = std::collections::HashSet::with_capacity(self.members.len());
|
||
for member in &self.members {
|
||
if !seen.insert(member.id) {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"membership record: duplicate member id {} (ids are permanent and unique)",
|
||
member.id
|
||
),
|
||
});
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
/// A decoded batch payload, by kind.
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub enum BatchPayload {
|
||
/// Kind 0: fixed-size signal event records.
|
||
Signals(Vec<EventRecord>),
|
||
/// Kind 1: one item-metadata blob.
|
||
ItemMetadata(ItemMetadataRecord),
|
||
/// Kind 2: one item-embedding blob.
|
||
Embedding(EmbeddingRecord),
|
||
/// Kind 3: one term marker (m11p4 election).
|
||
TermMarker(TermMarkerRecord),
|
||
/// Kind 4: one cluster-membership record (m11p5 conf-changes).
|
||
Membership(MembershipRecord),
|
||
}
|
||
|
||
/// One blob (kind-1/2) record submitted for a WAL append.
|
||
///
|
||
/// The writer-side counterpart of the blob arms of [`BatchPayload`]: a blob
|
||
/// append consumes exactly ONE seqno and is flushed as its own batch (the
|
||
/// group-commit writer never mixes kinds within a batch).
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub enum BlobRecord {
|
||
/// An item-metadata mutation (batch kind 1).
|
||
ItemMetadata(ItemMetadataRecord),
|
||
/// An item-embedding mutation (batch kind 2).
|
||
Embedding(EmbeddingRecord),
|
||
/// A term marker (batch kind 3, m11p4): no entity, no storage effect.
|
||
TermMarker(TermMarkerRecord),
|
||
/// A cluster-membership record (batch kind 4, m11p5): no entity, no
|
||
/// storage effect — folded into the `ClusterMembership` cell.
|
||
Membership(MembershipRecord),
|
||
}
|
||
|
||
impl BlobRecord {
|
||
/// The batch kind this record encodes as (header `flags` byte).
|
||
#[must_use]
|
||
pub const fn kind(&self) -> u8 {
|
||
match self {
|
||
Self::ItemMetadata(_) => BATCH_KIND_ITEM_METADATA,
|
||
Self::Embedding(_) => BATCH_KIND_EMBEDDING,
|
||
Self::TermMarker(_) => BATCH_KIND_TERM_MARKER,
|
||
Self::Membership(_) => BATCH_KIND_MEMBERSHIP,
|
||
}
|
||
}
|
||
|
||
/// The entity this mutation targets (0 for control records — a term marker
|
||
/// and a membership record have none).
|
||
#[must_use]
|
||
pub const fn entity_id(&self) -> u64 {
|
||
match self {
|
||
Self::ItemMetadata(r) => r.entity_id,
|
||
Self::Embedding(r) => r.entity_id,
|
||
Self::TermMarker(_) | Self::Membership(_) => 0,
|
||
}
|
||
}
|
||
|
||
/// Encode this record as a single-seqno batch at `seq`.
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` if the blob exceeds
|
||
/// [`MAX_BLOB_PAYLOAD_BYTES`] (or an embedding's dimension exceeds `u32`).
|
||
pub fn encode(
|
||
&self,
|
||
seq: u64,
|
||
batch_ts: u64,
|
||
shard_id: ShardId,
|
||
region_id: RegionId,
|
||
) -> Result<Vec<u8>, WalError> {
|
||
match self {
|
||
Self::ItemMetadata(r) => {
|
||
encode_item_metadata_batch(r, seq, batch_ts, shard_id, region_id)
|
||
}
|
||
Self::Embedding(r) => encode_embedding_batch(r, seq, batch_ts, shard_id, region_id),
|
||
Self::TermMarker(r) => encode_term_marker_batch(r, seq, batch_ts, shard_id, region_id),
|
||
Self::Membership(r) => encode_membership_batch(r, seq, batch_ts, shard_id, region_id),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Encode a kind-1 item-metadata batch (one record, one seqno).
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` if the metadata exceeds
|
||
/// [`MAX_BLOB_PAYLOAD_BYTES`].
|
||
pub fn encode_item_metadata_batch(
|
||
record: &ItemMetadataRecord,
|
||
seq: u64,
|
||
batch_ts: u64,
|
||
shard_id: ShardId,
|
||
region_id: RegionId,
|
||
) -> Result<Vec<u8>, WalError> {
|
||
let mut payload = Vec::with_capacity(8 + record.metadata_bytes.len());
|
||
payload.extend_from_slice(&record.entity_id.to_le_bytes());
|
||
payload.extend_from_slice(&record.metadata_bytes);
|
||
encode_frame(
|
||
BATCH_KIND_ITEM_METADATA,
|
||
1,
|
||
&payload,
|
||
seq,
|
||
batch_ts,
|
||
shard_id,
|
||
region_id,
|
||
)
|
||
}
|
||
|
||
/// Encode a kind-2 item-embedding batch (one record, one seqno).
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` if the vector exceeds
|
||
/// [`MAX_BLOB_PAYLOAD_BYTES`].
|
||
pub fn encode_embedding_batch(
|
||
record: &EmbeddingRecord,
|
||
seq: u64,
|
||
batch_ts: u64,
|
||
shard_id: ShardId,
|
||
region_id: RegionId,
|
||
) -> Result<Vec<u8>, WalError> {
|
||
let mut payload = Vec::with_capacity(12 + record.values.len() * 4);
|
||
payload.extend_from_slice(&record.entity_id.to_le_bytes());
|
||
let dim = u32::try_from(record.values.len()).map_err(|_| WalError::Corruption {
|
||
message: format!("embedding dimension {} exceeds u32", record.values.len()),
|
||
})?;
|
||
payload.extend_from_slice(&dim.to_le_bytes());
|
||
for v in &record.values {
|
||
payload.extend_from_slice(&v.to_le_bytes());
|
||
}
|
||
encode_frame(
|
||
BATCH_KIND_EMBEDDING,
|
||
1,
|
||
&payload,
|
||
seq,
|
||
batch_ts,
|
||
shard_id,
|
||
region_id,
|
||
)
|
||
}
|
||
|
||
/// Encode a kind-3 term-marker batch (one record, one seqno):
|
||
/// `term (u64 LE) | leader_region (u16 LE)`.
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` only through the shared frame encoder
|
||
/// (the 10-byte payload can never exceed the blob ceiling).
|
||
pub fn encode_term_marker_batch(
|
||
record: &TermMarkerRecord,
|
||
seq: u64,
|
||
batch_ts: u64,
|
||
shard_id: ShardId,
|
||
region_id: RegionId,
|
||
) -> Result<Vec<u8>, WalError> {
|
||
let mut payload = Vec::with_capacity(10);
|
||
payload.extend_from_slice(&record.term.to_le_bytes());
|
||
payload.extend_from_slice(&record.leader_region.to_le_bytes());
|
||
encode_frame(
|
||
BATCH_KIND_TERM_MARKER,
|
||
1,
|
||
&payload,
|
||
seq,
|
||
batch_ts,
|
||
shard_id,
|
||
region_id,
|
||
)
|
||
}
|
||
|
||
/// Encode a kind-4 membership batch (one record, one seqno).
|
||
///
|
||
/// Payload layout (all integers little-endian; strings length-prefixed):
|
||
/// ```text
|
||
/// rec_version u8 | version u64 | term u64 | member_count u32
|
||
/// member* : id u16 | role u8 | name_len u32 | name | grpc_len u32 | grpc
|
||
/// | http_len u32 | http
|
||
/// ```
|
||
///
|
||
/// The leading `rec_version` byte is the record-level format version
|
||
/// ([`MEMBERSHIP_RECORD_VERSION`]), distinct from the frame's
|
||
/// [`FORMAT_VERSION`], so the membership field set can evolve independently.
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` if the record fails structural validation
|
||
/// (empty roster, too many members, duplicate id), if any string exceeds
|
||
/// [`MAX_MEMBERSHIP_STRING_BYTES`], or if the assembled payload exceeds the
|
||
/// blob ceiling (via the shared frame encoder).
|
||
pub fn encode_membership_batch(
|
||
record: &MembershipRecord,
|
||
seq: u64,
|
||
batch_ts: u64,
|
||
shard_id: ShardId,
|
||
region_id: RegionId,
|
||
) -> Result<Vec<u8>, WalError> {
|
||
record.validate()?;
|
||
let member_count = u32::try_from(record.members.len()).map_err(|_| WalError::Corruption {
|
||
message: format!(
|
||
"membership record: {} members exceeds u32",
|
||
record.members.len()
|
||
),
|
||
})?;
|
||
|
||
// Pre-size: fixed prefix (1 + 8 + 8 + 4) plus a per-member estimate. An
|
||
// undersized guess only forces a realloc; the explicit bound below is what
|
||
// protects against a hostile length.
|
||
let mut payload = Vec::with_capacity(21 + record.members.len() * 64);
|
||
payload.push(MEMBERSHIP_RECORD_VERSION);
|
||
payload.extend_from_slice(&record.version.to_le_bytes());
|
||
payload.extend_from_slice(&record.term.to_le_bytes());
|
||
payload.extend_from_slice(&member_count.to_le_bytes());
|
||
|
||
for member in &record.members {
|
||
payload.extend_from_slice(&member.id.to_le_bytes());
|
||
payload.push(member.role.to_byte());
|
||
push_membership_string(&mut payload, &member.name, "name")?;
|
||
push_membership_string(&mut payload, &member.grpc_addr, "grpc_addr")?;
|
||
push_membership_string(&mut payload, &member.http_addr, "http_addr")?;
|
||
}
|
||
|
||
encode_frame(
|
||
BATCH_KIND_MEMBERSHIP,
|
||
1,
|
||
&payload,
|
||
seq,
|
||
batch_ts,
|
||
shard_id,
|
||
region_id,
|
||
)
|
||
}
|
||
|
||
/// Append a length-prefixed (`u32 LE` len + bytes) string to a membership
|
||
/// payload, refusing one above the per-string ceiling.
|
||
fn push_membership_string(buf: &mut Vec<u8>, s: &str, field: &str) -> Result<(), WalError> {
|
||
if s.len() > MAX_MEMBERSHIP_STRING_BYTES {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"membership record: {field} is {} bytes, exceeds the \
|
||
{MAX_MEMBERSHIP_STRING_BYTES}-byte ceiling",
|
||
s.len()
|
||
),
|
||
});
|
||
}
|
||
// `len() <= MAX_MEMBERSHIP_STRING_BYTES` (well under u32::MAX), so the cast
|
||
// cannot truncate.
|
||
#[allow(clippy::cast_possible_truncation)]
|
||
let len = s.len() as u32;
|
||
buf.extend_from_slice(&len.to_le_bytes());
|
||
buf.extend_from_slice(s.as_bytes());
|
||
Ok(())
|
||
}
|
||
|
||
/// Shared frame encoder for every batch kind: 64-byte header + payload, BLAKE3
|
||
/// over `header[0..32] || payload`. The single owner of the header layout —
|
||
/// every kind goes through here so the framing cannot drift.
|
||
fn encode_frame(
|
||
kind: u8,
|
||
event_count: u16,
|
||
payload: &[u8],
|
||
first_seq: u64,
|
||
batch_ts: u64,
|
||
shard_id: ShardId,
|
||
region_id: RegionId,
|
||
) -> Result<Vec<u8>, WalError> {
|
||
if kind != BATCH_KIND_SIGNALS && payload.len() > MAX_BLOB_PAYLOAD_BYTES {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"blob batch payload {} bytes exceeds the {MAX_BLOB_PAYLOAD_BYTES}-byte ceiling",
|
||
payload.len()
|
||
),
|
||
});
|
||
}
|
||
let total_len = HEADER_SIZE + payload.len();
|
||
let mut buf = vec![0u8; total_len];
|
||
|
||
// Write header fields [0..32]
|
||
buf[0..4].copy_from_slice(&MAGIC);
|
||
buf[4] = FORMAT_VERSION;
|
||
buf[5] = kind;
|
||
buf[6..8].copy_from_slice(&event_count.to_le_bytes());
|
||
buf[8..16].copy_from_slice(&first_seq.to_le_bytes());
|
||
buf[16..24].copy_from_slice(&batch_ts.to_le_bytes());
|
||
let payload_len_u32 = u32::try_from(payload.len()).map_err(|_| WalError::Corruption {
|
||
message: format!("batch payload {} bytes exceeds u32", payload.len()),
|
||
})?;
|
||
buf[24..28].copy_from_slice(&payload_len_u32.to_le_bytes());
|
||
// shard_id and region_id at bytes 28-31.
|
||
buf[28..30].copy_from_slice(&shard_id.0.to_le_bytes());
|
||
buf[30..32].copy_from_slice(®ion_id.0.to_le_bytes());
|
||
|
||
buf[HEADER_SIZE..].copy_from_slice(payload);
|
||
|
||
// Compute BLAKE3 over header[0..32] || payload
|
||
let checksum = compute_checksum(&buf[0..32], &buf[HEADER_SIZE..]);
|
||
buf[32..64].copy_from_slice(checksum.as_bytes());
|
||
|
||
Ok(buf)
|
||
}
|
||
|
||
/// Decode a SIGNAL batch from raw bytes (the kind-0 fast path).
|
||
///
|
||
/// Pre-m11p2 behavior preserved exactly for kind-0 batches; a kind-1/2 (blob)
|
||
/// batch is an error here — callers that can meet blob batches use
|
||
/// [`decode_batch_payload`].
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` on any validation failure, including a
|
||
/// non-signal batch kind.
|
||
pub fn decode_batch(bytes: &[u8]) -> Result<(BatchHeader, Vec<EventRecord>), WalError> {
|
||
let (header, payload) = decode_batch_payload(bytes)?;
|
||
match payload {
|
||
BatchPayload::Signals(events) => Ok((header, events)),
|
||
BatchPayload::ItemMetadata(_)
|
||
| BatchPayload::Embedding(_)
|
||
| BatchPayload::TermMarker(_)
|
||
| BatchPayload::Membership(_) => Err(WalError::Corruption {
|
||
message: format!(
|
||
"kind-{} batch decoded through the signals-only decode_batch; \
|
||
use decode_batch_payload",
|
||
header.flags
|
||
),
|
||
}),
|
||
}
|
||
}
|
||
|
||
/// Decode any batch kind from raw bytes.
|
||
///
|
||
/// Two-phase validation:
|
||
/// - Phase 1: magic bytes, version, kind, payload length bounds
|
||
/// - Phase 2: BLAKE3 checksum verification, then kind-specific payload parsing
|
||
///
|
||
/// For kind-0 (signals) the per-event record size is selected from the
|
||
/// header's format version ([`event_size_for_version`]), so v1/v2 (21-byte)
|
||
/// and v3 (32-byte) batches all decode through the same path. Kind-1/2 blob
|
||
/// batches always carry `event_count == 1`.
|
||
///
|
||
/// # Errors
|
||
///
|
||
/// Returns `WalError::Corruption` on any validation failure.
|
||
#[allow(clippy::too_many_lines)] // one linear validate-then-parse pass; splitting would scatter the frame layout
|
||
pub fn decode_batch_payload(bytes: &[u8]) -> Result<(BatchHeader, BatchPayload), WalError> {
|
||
if bytes.len() < HEADER_SIZE {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"batch too short for header: {} bytes, need {HEADER_SIZE}",
|
||
bytes.len()
|
||
),
|
||
});
|
||
}
|
||
|
||
// Phase 1: structural validation
|
||
if bytes[0..4] != MAGIC {
|
||
return Err(WalError::Corruption {
|
||
message: "invalid magic bytes".into(),
|
||
});
|
||
}
|
||
|
||
let version = bytes[4];
|
||
if version != FORMAT_VERSION_V1 && version != FORMAT_VERSION_V2 && version != FORMAT_VERSION_V3
|
||
{
|
||
return Err(WalError::Corruption {
|
||
message: format!("unsupported format version: {version}"),
|
||
});
|
||
}
|
||
let event_size = event_size_for_version(version);
|
||
|
||
let flags = bytes[5];
|
||
if flags != BATCH_KIND_SIGNALS
|
||
&& flags != BATCH_KIND_ITEM_METADATA
|
||
&& flags != BATCH_KIND_EMBEDDING
|
||
&& flags != BATCH_KIND_TERM_MARKER
|
||
&& flags != BATCH_KIND_MEMBERSHIP
|
||
{
|
||
return Err(WalError::Corruption {
|
||
message: format!("unsupported batch kind: {flags}"),
|
||
});
|
||
}
|
||
let event_count =
|
||
u16::from_le_bytes(bytes[6..8].try_into().map_err(|_| WalError::Corruption {
|
||
message: "invalid event_count bytes".into(),
|
||
})?);
|
||
|
||
if event_count == 0 || event_count > MAX_EVENTS_PER_BATCH {
|
||
return Err(WalError::Corruption {
|
||
message: format!("event count {event_count} out of range [1, {MAX_EVENTS_PER_BATCH}]"),
|
||
});
|
||
}
|
||
|
||
let first_seq =
|
||
u64::from_le_bytes(bytes[8..16].try_into().map_err(|_| WalError::Corruption {
|
||
message: "invalid first_seq bytes".into(),
|
||
})?);
|
||
|
||
let batch_timestamp =
|
||
u64::from_le_bytes(bytes[16..24].try_into().map_err(|_| WalError::Corruption {
|
||
message: "invalid batch_timestamp bytes".into(),
|
||
})?);
|
||
|
||
let payload_len = payload_len_from_header(bytes)?;
|
||
|
||
// v2+ fields at bytes 28-31. For v1 batches these bytes are always zero,
|
||
// which correctly decodes as ShardId::SINGLE and RegionId::SINGLE.
|
||
let shard_id = ShardId(u16::from_le_bytes(bytes[28..30].try_into().map_err(
|
||
|_| WalError::Corruption {
|
||
message: "invalid shard_id bytes".into(),
|
||
},
|
||
)?));
|
||
let region_id = RegionId(u16::from_le_bytes(bytes[30..32].try_into().map_err(
|
||
|_| WalError::Corruption {
|
||
message: "invalid region_id bytes".into(),
|
||
},
|
||
)?));
|
||
|
||
// Kind-specific payload-length bounds, BEFORE the checksum pass sizes its
|
||
// input from payload_len.
|
||
if flags == BATCH_KIND_SIGNALS {
|
||
let expected_payload = u32::from(event_count) * event_size as u32;
|
||
if payload_len != expected_payload {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"payload_len {payload_len} != event_count {event_count} * {event_size}"
|
||
),
|
||
});
|
||
}
|
||
} else {
|
||
if event_count != 1 {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"kind-{flags} blob batch must carry event_count 1, got {event_count}"
|
||
),
|
||
});
|
||
}
|
||
if payload_len as usize > MAX_BLOB_PAYLOAD_BYTES {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"blob batch payload {payload_len} bytes exceeds the \
|
||
{MAX_BLOB_PAYLOAD_BYTES}-byte ceiling"
|
||
),
|
||
});
|
||
}
|
||
}
|
||
|
||
let total_len = HEADER_SIZE + payload_len as usize;
|
||
if bytes.len() < total_len {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"batch truncated: have {} bytes, need {total_len}",
|
||
bytes.len()
|
||
),
|
||
});
|
||
}
|
||
|
||
// Extract stored checksum
|
||
let mut checksum = [0u8; 32];
|
||
checksum.copy_from_slice(&bytes[32..64]);
|
||
|
||
// Phase 2: BLAKE3 verification
|
||
let payload_bytes = &bytes[HEADER_SIZE..total_len];
|
||
let computed = compute_checksum(&bytes[0..32], payload_bytes);
|
||
if computed.as_bytes() != &checksum {
|
||
return Err(WalError::Corruption {
|
||
message: "BLAKE3 checksum mismatch".into(),
|
||
});
|
||
}
|
||
|
||
let payload = match flags {
|
||
BATCH_KIND_SIGNALS => {
|
||
let mut events = Vec::with_capacity(usize::from(event_count));
|
||
for i in 0..usize::from(event_count) {
|
||
let offset = i * event_size;
|
||
let event = EventRecord::from_bytes(&payload_bytes[offset..offset + event_size])?;
|
||
events.push(event);
|
||
}
|
||
BatchPayload::Signals(events)
|
||
}
|
||
BATCH_KIND_ITEM_METADATA => BatchPayload::ItemMetadata(decode_item_blob(payload_bytes)?),
|
||
BATCH_KIND_TERM_MARKER => BatchPayload::TermMarker(decode_term_marker_blob(payload_bytes)?),
|
||
BATCH_KIND_MEMBERSHIP => BatchPayload::Membership(decode_membership_blob(payload_bytes)?),
|
||
// The kind set was validated in phase 1; only embedding remains.
|
||
_ => BatchPayload::Embedding(decode_embedding_blob(payload_bytes)?),
|
||
};
|
||
|
||
let header = BatchHeader {
|
||
version,
|
||
flags,
|
||
event_count,
|
||
first_seq,
|
||
batch_timestamp,
|
||
payload_len,
|
||
checksum,
|
||
shard_id,
|
||
region_id,
|
||
};
|
||
|
||
Ok((header, payload))
|
||
}
|
||
|
||
/// Parse a kind-1 blob: `entity_id (u64 LE) | metadata bytes`.
|
||
fn decode_item_blob(payload: &[u8]) -> Result<ItemMetadataRecord, WalError> {
|
||
if payload.len() < 8 {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"item-metadata blob too short: {} bytes, need >= 8",
|
||
payload.len()
|
||
),
|
||
});
|
||
}
|
||
let entity_id =
|
||
u64::from_le_bytes(payload[0..8].try_into().map_err(|_| WalError::Corruption {
|
||
message: "item-metadata blob: invalid entity_id bytes".into(),
|
||
})?);
|
||
Ok(ItemMetadataRecord {
|
||
entity_id,
|
||
metadata_bytes: payload[8..].to_vec(),
|
||
})
|
||
}
|
||
|
||
/// Parse a kind-3 blob: `term (u64 LE) | leader_region (u16 LE)`.
|
||
fn decode_term_marker_blob(payload: &[u8]) -> Result<TermMarkerRecord, WalError> {
|
||
if payload.len() != 10 {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"term-marker blob length {} != 10 (term u64 + leader_region u16)",
|
||
payload.len()
|
||
),
|
||
});
|
||
}
|
||
let term = u64::from_le_bytes(payload[0..8].try_into().map_err(|_| WalError::Corruption {
|
||
message: "term-marker blob: invalid term bytes".into(),
|
||
})?);
|
||
let leader_region =
|
||
u16::from_le_bytes(
|
||
payload[8..10]
|
||
.try_into()
|
||
.map_err(|_| WalError::Corruption {
|
||
message: "term-marker blob: invalid leader_region bytes".into(),
|
||
})?,
|
||
);
|
||
if term == 0 {
|
||
return Err(WalError::Corruption {
|
||
message: "term-marker blob: term 0 is the topology era and never journals a marker"
|
||
.into(),
|
||
});
|
||
}
|
||
Ok(TermMarkerRecord {
|
||
term,
|
||
leader_region,
|
||
})
|
||
}
|
||
|
||
/// A cursor over a membership payload that reads fixed-width fields and
|
||
/// length-prefixed strings while refusing every over-read.
|
||
struct MembershipCursor<'a> {
|
||
bytes: &'a [u8],
|
||
pos: usize,
|
||
}
|
||
|
||
impl<'a> MembershipCursor<'a> {
|
||
const fn new(bytes: &'a [u8]) -> Self {
|
||
Self { bytes, pos: 0 }
|
||
}
|
||
|
||
fn take(&mut self, n: usize, what: &str) -> Result<&'a [u8], WalError> {
|
||
let end = self
|
||
.pos
|
||
.checked_add(n)
|
||
.ok_or_else(|| WalError::Corruption {
|
||
message: "membership record: length overflow".into(),
|
||
})?;
|
||
let slice = self
|
||
.bytes
|
||
.get(self.pos..end)
|
||
.ok_or_else(|| WalError::Corruption {
|
||
message: format!(
|
||
"membership record: truncated reading {what} (need {n} bytes at offset {}, \
|
||
have {})",
|
||
self.pos,
|
||
self.bytes.len()
|
||
),
|
||
})?;
|
||
self.pos = end;
|
||
Ok(slice)
|
||
}
|
||
|
||
fn u8(&mut self, what: &str) -> Result<u8, WalError> {
|
||
Ok(self.take(1, what)?[0])
|
||
}
|
||
|
||
fn u16(&mut self, what: &str) -> Result<u16, WalError> {
|
||
let b = self.take(2, what)?;
|
||
Ok(u16::from_le_bytes([b[0], b[1]]))
|
||
}
|
||
|
||
fn u32(&mut self, what: &str) -> Result<u32, WalError> {
|
||
let b = self.take(4, what)?;
|
||
Ok(u32::from_le_bytes(b.try_into().map_err(|_| {
|
||
WalError::Corruption {
|
||
message: format!("membership record: invalid {what} bytes"),
|
||
}
|
||
})?))
|
||
}
|
||
|
||
fn u64(&mut self, what: &str) -> Result<u64, WalError> {
|
||
let b = self.take(8, what)?;
|
||
Ok(u64::from_le_bytes(b.try_into().map_err(|_| {
|
||
WalError::Corruption {
|
||
message: format!("membership record: invalid {what} bytes"),
|
||
}
|
||
})?))
|
||
}
|
||
|
||
/// A `u32 LE` length prefix followed by that many UTF-8 bytes. The length
|
||
/// is bounded BEFORE the slice read so a torn prefix cannot drive a huge
|
||
/// allocation, and the bytes are validated as UTF-8 (the addresses and
|
||
/// names are always valid strings on the write side).
|
||
fn string(&mut self, field: &str) -> Result<String, WalError> {
|
||
let len = self.u32(field)? as usize;
|
||
if len > MAX_MEMBERSHIP_STRING_BYTES {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"membership record: {field} length {len} exceeds the \
|
||
{MAX_MEMBERSHIP_STRING_BYTES}-byte ceiling"
|
||
),
|
||
});
|
||
}
|
||
let bytes = self.take(len, field)?;
|
||
String::from_utf8(bytes.to_vec()).map_err(|_| WalError::Corruption {
|
||
message: format!("membership record: {field} is not valid UTF-8"),
|
||
})
|
||
}
|
||
}
|
||
|
||
/// Parse a kind-4 blob into a [`MembershipRecord`], defending against every
|
||
/// truncation and rejecting unknown roles, duplicate ids, an empty roster, or
|
||
/// trailing garbage.
|
||
fn decode_membership_blob(payload: &[u8]) -> Result<MembershipRecord, WalError> {
|
||
let mut cur = MembershipCursor::new(payload);
|
||
|
||
let rec_version = cur.u8("record version")?;
|
||
if rec_version != MEMBERSHIP_RECORD_VERSION {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"membership record: unknown record version {rec_version} \
|
||
(this binary writes {MEMBERSHIP_RECORD_VERSION})"
|
||
),
|
||
});
|
||
}
|
||
let version = cur.u64("version")?;
|
||
let term = cur.u64("term")?;
|
||
let member_count = cur.u32("member_count")? as usize;
|
||
// Bound the per-member loop allocation against the ceiling BEFORE reserving:
|
||
// a torn count must not drive a multi-gigabyte `Vec::with_capacity`.
|
||
if member_count > MAX_MEMBERSHIP_MEMBERS {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"membership record: member_count {member_count} exceeds the \
|
||
{MAX_MEMBERSHIP_MEMBERS} ceiling"
|
||
),
|
||
});
|
||
}
|
||
|
||
let mut members = Vec::with_capacity(member_count);
|
||
for _ in 0..member_count {
|
||
let id = cur.u16("member id")?;
|
||
let role = MemberRole::from_byte(cur.u8("member role")?)?;
|
||
let name = cur.string("name")?;
|
||
let grpc_addr = cur.string("grpc_addr")?;
|
||
let http_addr = cur.string("http_addr")?;
|
||
members.push(MemberEntry {
|
||
id,
|
||
name,
|
||
grpc_addr,
|
||
http_addr,
|
||
role,
|
||
});
|
||
}
|
||
|
||
// Reject trailing bytes: a record whose framed payload is longer than its
|
||
// declared roster is a torn or hostile encoding, not a forward-compatible
|
||
// extension (that travels through `rec_version`).
|
||
if cur.pos != payload.len() {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"membership record: {} trailing bytes after {} members",
|
||
payload.len() - cur.pos,
|
||
member_count
|
||
),
|
||
});
|
||
}
|
||
|
||
let record = MembershipRecord {
|
||
version,
|
||
term,
|
||
members,
|
||
};
|
||
// Empty-roster and duplicate-id checks (the structural invariants the
|
||
// encoder also enforces) run here so a hostile payload that slipped past
|
||
// framing still cannot fold a malformed roster into the cell.
|
||
record.validate()?;
|
||
Ok(record)
|
||
}
|
||
|
||
/// Parse a kind-2 blob: `entity_id (u64 LE) | dim (u32 LE) | dim × f32 LE`.
|
||
fn decode_embedding_blob(payload: &[u8]) -> Result<EmbeddingRecord, WalError> {
|
||
if payload.len() < 12 {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"embedding blob too short: {} bytes, need >= 12",
|
||
payload.len()
|
||
),
|
||
});
|
||
}
|
||
let entity_id =
|
||
u64::from_le_bytes(payload[0..8].try_into().map_err(|_| WalError::Corruption {
|
||
message: "embedding blob: invalid entity_id bytes".into(),
|
||
})?);
|
||
let dim = u32::from_le_bytes(
|
||
payload[8..12]
|
||
.try_into()
|
||
.map_err(|_| WalError::Corruption {
|
||
message: "embedding blob: invalid dim bytes".into(),
|
||
})?,
|
||
) as usize;
|
||
let expected = 12 + dim * 4;
|
||
if payload.len() != expected {
|
||
return Err(WalError::Corruption {
|
||
message: format!(
|
||
"embedding blob length {} != 12 + 4 * dim {dim}",
|
||
payload.len()
|
||
),
|
||
});
|
||
}
|
||
let mut values = Vec::with_capacity(dim);
|
||
for i in 0..dim {
|
||
let off = 12 + i * 4;
|
||
values.push(f32::from_le_bytes(
|
||
payload[off..off + 4]
|
||
.try_into()
|
||
.map_err(|_| WalError::Corruption {
|
||
message: "embedding blob: invalid f32 bytes".into(),
|
||
})?,
|
||
));
|
||
}
|
||
Ok(EmbeddingRecord { entity_id, values })
|
||
}
|
||
|
||
/// Compute the BLAKE3 checksum for a batch.
|
||
///
|
||
/// Input: `header_prefix[0..32] || event_bytes`.
|
||
/// The hash field at `[32..64]` is NOT part of the hash input.
|
||
fn compute_checksum(header_prefix: &[u8], event_bytes: &[u8]) -> blake3::Hash {
|
||
let mut hasher = blake3::Hasher::new();
|
||
hasher.update(header_prefix);
|
||
hasher.update(event_bytes);
|
||
hasher.finalize()
|
||
}
|
||
|
||
/// Compute the per-event content hash used for deduplication.
|
||
///
|
||
/// Returns the first 128 bits of the BLAKE3 hash of the canonical 32-byte v3
|
||
/// record image. A legacy (v1/v2) event decodes with zeroed governance fields,
|
||
/// so it hashes identically to a fresh v3 *local* event with the same base
|
||
/// fields — retry-dedup is therefore version-stable for local signals, while
|
||
/// events that differ only in governance (e.g. local vs community scope) hash
|
||
/// distinctly.
|
||
///
|
||
/// # Panics
|
||
///
|
||
/// Cannot panic. The `expect` is on a `try_into` converting a 16-byte slice
|
||
/// (from a 32-byte BLAKE3 hash) into `[u8; 16]`, which is infallible.
|
||
#[must_use]
|
||
pub fn event_content_hash(event: &EventRecord) -> u128 {
|
||
let bytes = event.to_bytes();
|
||
let hash = blake3::hash(&bytes);
|
||
let hash_bytes: &[u8; 32] = hash.as_bytes();
|
||
u128::from_le_bytes(
|
||
hash_bytes[..16]
|
||
.try_into()
|
||
.expect("BLAKE3 hash is always 32 bytes; first 16 is infallible"),
|
||
)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
#[allow(clippy::unwrap_used)]
|
||
#[path = "batch_tests.rs"]
|
||
mod tests;
|
||
|
||
#[cfg(test)]
|
||
#[allow(clippy::unwrap_used)]
|
||
mod header_layout_tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn v3_event_reserved_bytes_are_zero() {
|
||
// Bytes [30..32] of a v3 event record are reserved and MUST be written
|
||
// zero. They are covered by the batch BLAKE3, so a flip is already
|
||
// rejected on decode as corruption; this pins the writer-side invariant
|
||
// so the reserved space stays available for a future format version.
|
||
let event = EventRecord::scoped(42, RECORD_TYPE_SIGNAL, 1.0, 1000, 1, 7, 3, 9);
|
||
let bytes = event.to_bytes();
|
||
assert_eq!(
|
||
&bytes[30..32],
|
||
&[0u8, 0u8],
|
||
"v3 reserved bytes [30..32] must be zero on encode"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn payload_len_accessor_matches_decode() {
|
||
// The header accessor must read the exact same field decode_batch reads,
|
||
// so the recovery scanner and the full decoder can never disagree on a
|
||
// batch's payload size.
|
||
let events = vec![EventRecord::signal(1, RECORD_TYPE_SIGNAL, 1.0, 1)];
|
||
let encoded = encode_batch(&events, 1, 1).expect("encode should succeed");
|
||
let from_accessor = payload_len_from_header(&encoded).expect("accessor should succeed");
|
||
let (header, _) = decode_batch(&encoded).expect("decode should succeed");
|
||
assert_eq!(from_accessor, header.payload_len);
|
||
assert_eq!(from_accessor as usize, EVENT_SIZE_V3);
|
||
}
|
||
|
||
#[test]
|
||
fn payload_len_accessor_rejects_short_header() {
|
||
let short = [0u8; HEADER_PAYLOAD_LEN_OFFSET + 1];
|
||
assert!(payload_len_from_header(&short).is_err());
|
||
}
|
||
}
|