tidaldb/tidal/src/db/replication_ops.rs

892 lines
42 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Replication, multi-tenancy, and control-plane methods on [`TidalDb`].
use std::sync::Arc;
use super::TidalDb;
impl TidalDb {
/// Access the replication state (for lag gauges and tests).
#[must_use]
#[allow(clippy::missing_const_for_fn)] // Arc field prevents const in practice
pub fn replication_state(&self) -> &Arc<crate::replication::state::ReplicationState> {
&self.replication_state
}
/// Start the segment receiver for a follower node.
///
/// The receiver thread blocks on the transport's `recv_segment()` and
/// applies each received WAL segment to the local signal ledger. This
/// shape wires NO blob applier: a kind-1/2 (item/embedding) batch halts
/// the receiver loudly. Cluster nodes use
/// [`start_replication_with_blobs`](Self::start_replication_with_blobs).
///
/// # Errors
///
/// Returns `TidalError::Internal` if no ledger is wired (ephemeral without schema).
pub fn start_replication<T: crate::replication::Transport + ?Sized>(
&self,
transport: std::sync::Arc<T>,
) -> crate::Result<()> {
self.start_receiver(transport, None)
}
/// Start the segment receiver with the full m11p2 apply surface: signal
/// batches fold into the ledger, and kind-1/2 blob batches (item metadata
/// / embeddings) apply through this database's WAL-first item write paths.
///
/// Takes `self: &Arc<Self>` because the receiver thread needs a handle to
/// the database; it holds a `Weak` (never a strong `Arc`) so the receiver
/// cannot keep the database alive past its owner — once the last strong
/// handle drops, an in-flight blob apply fails with "database closed" and
/// the receiver halts instead of leaking.
///
/// # Errors
///
/// Returns `TidalError::Internal` if no ledger is wired (ephemeral without schema).
pub fn start_replication_with_blobs<T: crate::replication::Transport + ?Sized>(
self: &Arc<Self>,
transport: std::sync::Arc<T>,
) -> crate::Result<()> {
let applier: Arc<dyn crate::replication::receiver::ReplicatedBlobApplier> =
Arc::new(WeakBlobApplier(Arc::downgrade(self)));
self.start_receiver(transport, Some(applier))
}
/// Shared body of the two receiver-start shapes.
fn start_receiver<T: crate::replication::Transport + ?Sized>(
&self,
transport: std::sync::Arc<T>,
blob_applier: Option<Arc<dyn crate::replication::receiver::ReplicatedBlobApplier>>,
) -> crate::Result<()> {
let ledger = self.ledger()?.clone();
let state = Arc::clone(&self.replication_state);
// Feed the control-plane lag gauge so `tidaldb_replication_lag_seqno`
// reflects real follower backpressure (leader HWM − applied) instead of
// staying pinned at 0 (obs-REPL-1). The gauge shares this node's
// `replication_state`, so applied advances stay consistent.
let lag_gauge = Some(self.control_plane.lag_gauge());
let handle = crate::replication::receiver::spawn_receiver(
transport,
ledger,
state,
lag_gauge,
blob_applier,
);
if let Ok(mut guard) = self.receiver_handle.lock() {
*guard = Some(handle);
}
Ok(())
}
/// The flushed-batch ship feed (cluster + persistent mode only): the
/// replication ship queue's hot-path source (m11p2).
#[must_use]
pub fn wal_ship_feed(&self) -> Option<Arc<crate::wal::feed::WalShipFeed>> {
self.ship_feed.clone()
}
/// The WAL-tail term mark (m11p4): the highest kind-3 term marker this
/// node's log carries, as `(term, seq, leader_region)`. `(0, 0, 0)` = a
/// pre-election log.
///
/// The term is the `lastLogTerm` half of the vote restriction; the
/// leader region names the STREAM whose seqno numbering the frontier
/// half must be read in (`replication_state().applied_seqno` of that
/// region's shard for a follower; the node's own flushed frontier when
/// it led the term itself).
#[must_use]
pub fn wal_term_mark(&self) -> (u64, u64, u16) {
self.wal_term_mark.snapshot()
}
/// The applied cluster membership (m11p5): the highest-version kind-4
/// record this node's log carries, as `(version, term, members)`. `None`
/// = the topology era (membership epoch 0; no conf-change has run).
#[must_use]
pub fn cluster_membership(&self) -> Option<(u64, u64, Vec<crate::wal::format::MemberEntry>)> {
self.cluster_membership.snapshot()
}
/// Journal a kind-4 membership record as this node's next WAL record
/// (m11p5): the leader's full-roster conf-change snapshot. Waits for the
/// group-commit fsync (the record ships to followers through the normal
/// feed like any blob), folds the membership cell, and returns the seqno
/// the record landed at.
///
/// This is the data-layer write only — it does NOT mutate any peer set,
/// quorum, or transport (those ride a later stage's apply path). It mirrors
/// [`append_term_marker`](Self::append_term_marker)'s staged-append +
/// group-commit-wait + fold-cell discipline.
///
/// # Errors
///
/// - `TidalError::invalid_input` outside cluster mode (no replicated log),
/// for a structurally-invalid roster (empty / oversized / duplicate id),
/// or for a version that does not strictly advance the applied cell (a
/// record must monotonically supersede — re-appending or regressing a
/// version would let the cell disagree with the log's tail).
/// - `TidalError::Durability` if the append cannot be staged or its fsync
/// fails — the caller MUST treat the conf-change as NOT having happened.
pub fn append_membership_record(
&self,
record: crate::wal::format::MembershipRecord,
) -> crate::Result<u64> {
if !self.replicate_blobs {
return Err(crate::TidalError::invalid_input(
"membership records require cluster mode (the WAL is not a replicated log here)",
));
}
// Structural validation BEFORE the log: an invalid roster would fail
// apply identically on every follower (the receiver halts on apply
// errors), so it must never enter the replicated log.
record
.validate()
.map_err(|e| crate::TidalError::invalid_input(format!("{e}")))?;
// Monotonic-version guard: the cell advances only forward, so a record
// whose version does not strictly exceed the applied version could
// never advance the cell — refuse it loudly rather than journal a
// no-op record that the fold would silently ignore.
if let Some(applied) = self.cluster_membership.version()
&& record.version <= applied
{
return Err(crate::TidalError::invalid_input(format!(
"membership record version {} does not advance the applied version {applied} \
(versions are strictly increasing)",
record.version
)));
}
let sender = {
let wal = self
.wal
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
wal.as_ref().map(crate::wal::WalHandle::sender)
};
let Some(sender) = sender else {
return Err(crate::TidalError::invalid_input(
"membership records require a durable WAL",
));
};
let version = record.version;
let term = record.term;
let members = record.members.clone();
let blob = crate::wal::format::BlobRecord::Membership(record);
let seq = sender
.append_blob_staged(Arc::new(blob))
.map_err(|e| {
crate::TidalError::Durability(crate::schema::DurabilityError {
message: format!("membership record staging failed: {e}"),
})
})?
.wait()
.map_err(|e| {
crate::TidalError::Durability(crate::schema::DurabilityError {
message: format!("membership record append failed: {e}"),
})
})?;
super::wal_bridge::bump_last_seq_atomic(&self.last_wal_seq, seq);
self.cluster_membership.advance(version, term, members);
tracing::info!(
version,
term,
seq,
"membership record journaled (conf-change)"
);
Ok(seq)
}
/// Journal a kind-3 term marker as this node's next WAL record (m11p4):
/// the FIRST entry an elected leader writes in its term. Waits for the
/// group-commit fsync (the marker ships to followers through the normal
/// feed like any record), folds the term-mark cell, and returns the seqno
/// the marker landed at.
///
/// # Errors
///
/// - `TidalError::invalid_input` for `term == 0` (the topology era never
/// journals a marker) or outside cluster mode (no replicated log).
/// - `TidalError::Durability` if the append cannot be staged or its
/// fsync fails — the caller MUST abort the leadership activation: a
/// leader whose term marker is not durable cannot prove its term.
pub fn append_term_marker(&self, term: u64, leader_region: u16) -> crate::Result<u64> {
if term == 0 {
return Err(crate::TidalError::invalid_input(
"term markers exist only for elected terms (>= 1)",
));
}
if !self.replicate_blobs {
return Err(crate::TidalError::invalid_input(
"term markers require cluster mode (the WAL is not a replicated log here)",
));
}
let sender = {
let wal = self
.wal
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
wal.as_ref().map(crate::wal::WalHandle::sender)
};
let Some(sender) = sender else {
return Err(crate::TidalError::invalid_input(
"term markers require a durable WAL",
));
};
let record =
crate::wal::format::BlobRecord::TermMarker(crate::wal::format::TermMarkerRecord {
term,
leader_region,
});
let seq = sender
.append_blob_staged(Arc::new(record))
.map_err(|e| {
crate::TidalError::Durability(crate::schema::DurabilityError {
message: format!("term marker staging failed: {e}"),
})
})?
.wait()
.map_err(|e| {
crate::TidalError::Durability(crate::schema::DurabilityError {
message: format!("term marker append failed: {e}"),
})
})?;
super::wal_bridge::bump_last_seq_atomic(&self.last_wal_seq, seq);
self.wal_term_mark.advance(term, seq, leader_region);
tracing::info!(term, seq, "term marker journaled (leadership activation)");
Ok(seq)
}
/// Read encoded WAL batches covering seqnos `>= from_seq` from the durable
/// segments, up to `max_events`/`max_bytes` — the segment read-back behind
/// the `StreamSegments` catch-up path (m11p2).
///
/// Returns batches in seqno order, starting at the first batch whose
/// coverage reaches `from_seq`. An empty result means `from_seq` is past
/// the durable frontier (caught up). When the segments below `from_seq`
/// have been TRUNCATED (checkpoint compaction), the first returned batch
/// starts above `from_seq`; the caller decides whether that is a baseline
/// announcement (promoted leader) or an unservable hole (full-resync
/// territory, m11p5 snapshots).
///
/// # Errors
///
/// Returns the underlying [`WalError`](crate::wal::error::WalError) —
/// typed, not stringified, so the catch-up service can distinguish
/// [`SegmentFormatUnknown`](crate::wal::error::WalError::SegmentFormatUnknown)
/// ("this log can never serve that range; snapshot required" →
/// `FAILED_PRECONDITION` on the wire) from a transient read/IO failure
/// (→ `INTERNAL`, retryable). Ephemeral mode (no WAL on disk) is an
/// `Io` error; cluster mode refuses to start without a data dir, so that
/// arm is unreachable on a serving node.
pub fn read_wal_batches(
&self,
from_seq: u64,
max_events: u64,
max_bytes: usize,
) -> std::result::Result<Vec<crate::wal::reader::RawBatch>, crate::wal::error::WalError> {
let Some(wal_dir) = self.config.resolved_wal_dir() else {
return Err(crate::wal::error::WalError::Io(std::io::Error::other(
"no durable WAL on this node (ephemeral mode); catch-up \
read-back requires a persistent data dir",
)));
};
let segments = crate::wal::segment::list_segments(&wal_dir)?;
let mut out: Vec<crate::wal::reader::RawBatch> = Vec::new();
let mut events = 0u64;
let mut bytes = 0usize;
let max_events = max_events.max(1);
let max_bytes = max_bytes.max(1);
'segments: for (_first, path) in &segments {
// Cheap skip: a segment whose filename first_seq is far above the
// window's end can't help once we have data; segments below
// from_seq may still contain covering batches, so scan them.
let batches = crate::wal::reader::scan_segment_raw(path)?;
for batch in batches {
if batch.last_seq < from_seq {
continue;
}
let would_exceed = events + batch.event_count > max_events
|| bytes + batch.bytes.len() > max_bytes;
if !out.is_empty() && would_exceed {
break 'segments;
}
events += batch.event_count;
bytes += batch.bytes.len();
out.push(batch);
}
}
Ok(out)
}
/// The earliest WAL seqno this node's durable log can still serve to a
/// catch-up stream (m11p5 §2): the first byte of the lowest-numbered
/// segment on disk. A puller whose `from_seqno` is at or below this can
/// resume from the live WAL with no snapshot; below it means the covering
/// segments were compacted and a snapshot is required.
///
/// Returns `1` (the first real seqno; seq 0 is the dedup sentinel) when the
/// WAL is empty or absent — an empty log serves everything from the start,
/// so nothing is ever "below" the floor.
///
/// This reads `list_segments`' first entry, whose `first_seq` is the
/// segment's starting seqno (segments are named by their first seq and the
/// list is sorted ascending). It does NOT scan segment bodies, so it is
/// cheap enough to call on the stage path (per request) — unlike
/// [`read_wal_batches`](Self::read_wal_batches), which scans bytes.
///
/// # Errors
///
/// Returns the underlying [`WalError`](crate::wal::error::WalError) when the
/// segment directory cannot be listed (IO) or holds an unparseable `.seg`
/// name ([`SegmentFormatUnknown`](crate::wal::error::WalError::SegmentFormatUnknown))
/// — the same typed surface `read_wal_batches` exposes, so the snapshot
/// source can route a format-unknown log into "snapshot required" rather
/// than guessing.
pub fn earliest_servable_seq(&self) -> std::result::Result<u64, crate::wal::error::WalError> {
let Some(wal_dir) = self.config.resolved_wal_dir() else {
// Ephemeral mode has no durable log; treat as "serves from 1" — but
// cluster mode refuses to start without a data dir, so this arm is
// unreachable on a serving node (it keeps the accessor total).
return Ok(1);
};
let segments = crate::wal::segment::list_segments(&wal_dir)?;
// `list_segments` is sorted ascending by `first_seq`; the first entry is
// the earliest still-on-disk segment. Empty ⇒ nothing has been
// compacted away, so the floor is the first real seqno.
Ok(segments
.first()
.map_or(1, |(first_seq, _)| (*first_seq).max(1)))
}
/// The current WAL tail seqno (the highest seq durably appended). The seq a
/// snapshot artifact is captured at, and the seq the retention pin is taken
/// at *before* the copy (m11p5 §2.1).
#[must_use]
pub fn last_wal_seq(&self) -> u64 {
self.last_wal_seq.load(std::sync::atomic::Ordering::Acquire)
}
/// Stage a snapshot artifact under `dest`, pinning WAL retention at the
/// captured seq BEFORE the copy begins (m11p5 §2.1).
///
/// This is the engine-owned half of the leader-side snapshot path: the
/// PIN-before-copy ordering is load-bearing (a pin installed *after* staging
/// cannot protect the copy window from the 30 s checkpoint thread, which may
/// compact between the ledger checkpoint and the marker write), so it lives
/// here rather than being left to the caller to sequence. The tidal-server
/// `NodeSnapshotSource` (caching, TTL, active-fetch accounting, manifest)
/// wraps this; on artifact reap it calls
/// [`unpin_wal_retention`](Self::unpin_wal_retention).
///
/// Sequence:
/// 1. Capture `S = last_wal_seq` (the live tail).
/// 2. **Pin at `S` before any copy** — the pin clamps online compaction's
/// floor so the segment chain covering `S + 1` survives.
/// 3. `create_backup_with(dest, { skip_text_flush, exclude_top_level })` —
/// quiesces signal writes, checkpoints the ledger + replication HWM at
/// the artifact's own captured seq, flushes fjall, copies (minus the
/// exclusions), writes the WAL checkpoint marker into the copy.
/// 4. Re-derive the artifact's exact recovered seq and **re-pin to it only
/// if it is LOWER** than `S` — `create_backup` captures its own
/// `last_wal_seq` internally, which can only equal or exceed the `S` we
/// pinned at (the tail never goes backward), so the pin can only need to
/// be HELD or LOWERED, never raised. Lowering is safe (it keeps strictly
/// more history); raising would open a gap below the artifact's resume
/// point. In practice the artifact seq ≥ `S`, so the pin stays at `S`.
///
/// Returns the artifact's WAL seq — the frontier a joiner advances to and
/// resumes the live stream from (`artifact_seq + 1`). On ANY error the pin
/// is RELEASED before returning (a failed stage must not leak a pin that
/// would freeze compaction forever).
///
/// # Errors
///
/// - [`TidalError::Backpressure`](crate::TidalError) is NOT returned here
/// (it gates the writers, not this caller); a concurrent in-flight backup
/// surfaces as `TidalError::Internal` "a backup is already in progress" —
/// the caller maps it to `SnapshotStageError::Busy`.
/// - `TidalError::Internal` for ephemeral mode (no data dir).
/// - `TidalError::Durability` if the checkpoint, copy, or marker write fails.
pub fn stage_snapshot(
&self,
dest: &std::path::Path,
exclude_top_level: Vec<&'static str>,
) -> crate::Result<u64> {
use std::sync::atomic::Ordering;
// 1 + 2: capture the tail and PIN BEFORE the copy. The pin must be
// installed before `create_backup_with` so the copy window is protected
// from the periodic compaction (§2.1).
let pinned_at = self.last_wal_seq.load(Ordering::Acquire);
self.pin_wal_retention(pinned_at);
// 3: stage. On error, release the pin we took — a failed stage must not
// leave compaction frozen.
let info = match self.create_backup_with(
dest,
&super::backup::BackupOptions {
skip_text_flush: true,
exclude_top_level,
},
) {
Ok(info) => info,
Err(e) => {
self.unpin_wal_retention();
return Err(e);
}
};
// 4: the artifact's recovered seq is the WAL checkpoint marker the copy
// carries — by construction `create_backup` writes it at its own
// captured `last_wal_seq`, which is `>= pinned_at` (the tail is
// monotonic). Re-derive it from the artifact and lower the pin only if
// it is below `pinned_at` (never raise — that would open a gap). We read
// the artifact's marker rather than trusting the live tail, so the pin
// tracks the artifact, not a tail that advanced after the copy.
let artifact_seq = read_artifact_marker_seq(dest).unwrap_or(pinned_at);
if artifact_seq < pinned_at {
// Lowering keeps strictly MORE history than `pinned_at` would — safe,
// and required so the resume range `artifact_seq + 1` is retained.
self.pin_wal_retention(artifact_seq);
}
tracing::info!(
dest = %dest.display(),
pinned_at,
artifact_seq,
item_count = info.item_count,
size_bytes = info.size_bytes,
"snapshot artifact staged (WAL retention pinned)"
);
Ok(artifact_seq)
}
/// Durably checkpoint this node's replicated state into a crash-consistent
/// on-disk snapshot, synchronously (no 30 s wait).
///
/// Writes, atomically-consistent with each other:
/// 1. the signal-ledger aggregate (fjall checkpoint at the current WAL seq),
/// 2. the WAL checkpoint marker at the SAME seq (so a subsequent crash replays
/// only post-checkpoint follower-WAL events — no double-counting of events
/// already folded into the aggregate), and
/// 3. the replication high-water-mark ([`ReplicationState`] checkpoint).
///
/// This lands the exact on-disk state a clean checkpoint cycle would.
///
/// # Why this is a real, non-test API (m11p5 §2.6)
///
/// The boot-time snapshot install seeds the replication frontier
/// (`applied_seqno(leader_shard) = the installed artifact's recovered WAL
/// tail`) and then MUST persist that seed BEFORE starting the receiver or any
/// pull — otherwise a crash between the seed and the first stream pull would
/// re-derive a fresh frontier and re-fetch a snapshot. Persisting the seed is
/// exactly this checkpoint, so it is promoted from test-only to a real
/// public API. The historical name `force_replication_checkpoint` is kept as
/// a thin test-only alias so existing crash-recovery tests still compile.
///
/// No-op in ephemeral mode (no durable storage / no WAL). Returns the same
/// errors the periodic and shutdown checkpoints would.
///
/// # Errors
///
/// Returns `TidalError::Storage`/`TidalError::Durability` if any of the
/// signal-ledger, WAL-marker, or replication-state checkpoints fail.
///
/// [`ReplicationState`]: crate::replication::state::ReplicationState
pub fn persist_replication_checkpoint(&self) -> crate::Result<()> {
let (Some(ledger), Some(storage)) = (&self.ledger, &self.storage) else {
return Ok(());
};
let seq = self.last_wal_seq.load(std::sync::atomic::Ordering::Acquire);
let meta = crate::signals::checkpoint::CheckpointMeta {
checkpoint_time_ns: crate::schema::Timestamp::now().as_nanos(),
wal_sequence: seq,
payload_hash: [0u8; 32],
};
ledger.checkpoint(storage.items_engine(), meta)?;
crate::db::state_rebuild::checkpoint_replication_state(
storage.items_engine(),
self.replication_state.as_ref(),
)?;
// Advance the WAL checkpoint marker so reopen replays only follower-WAL
// events strictly after `seq` — keeping the WAL marker consistent with the
// fjall ledger checkpoint at the same seq (the same invariant shutdown
// maintains), so the recovered aggregate is not double-counted. The
// marker write is delegated out of the lock scope below to keep the WAL
// mutex held for only the borrow.
if seq > 0 {
let marker_result = {
let guard = self
.wal
.lock()
.map_err(|_| crate::TidalError::internal("wal_access", "WAL mutex poisoned"))?;
guard.as_ref().map(|wal| wal.checkpoint(seq))
};
if let Some(Err(e)) = marker_result {
return Err(crate::TidalError::Durability(
crate::schema::DurabilityError {
message: format!("persist_replication_checkpoint WAL marker failed: {e}"),
},
));
}
}
Ok(())
}
/// Test-only alias for [`persist_replication_checkpoint`](Self::persist_replication_checkpoint).
///
/// Kept so the existing crash-recovery tests (`m8p2_replication_durability`,
/// `m11p5_membership_record`) compile unchanged after the promotion to a
/// real public API.
#[cfg(any(test, feature = "test-utils"))]
pub fn force_replication_checkpoint(&self) -> crate::Result<()> {
self.persist_replication_checkpoint()
}
/// Snapshot this node's live CRDT state for reconciliation after a partition.
///
/// Walks the signal ledger and the hard-negative index into a
/// [`StateSnapshot`](crate::replication::reconcile::StateSnapshot):
///
/// - **Signals:** every `(entity, signal_type)` entry becomes a per-node
/// [`CrdtSignalState`](crate::replication::crdt::CrdtSignalState) attributed
/// to this node's shard, carrying its decay score, `last_update_ns`, and —
/// crucially — its live `AllTime` windowed count as the per-node bucket
/// count, so the windowed total round-trips through merge instead of
/// collapsing to 0.
/// - **Hard negatives:** every in-memory `(user, item)` pair becomes an
/// `LWWRegister<HardNegAction::Hide>` stamped at the current HLC. The index
/// stores only resolved membership, so "currently hidden as of now" is the
/// honest local assertion; the reconciliation engine's HLC LWW then resolves
/// it against any remote hide/unhide.
///
/// Pair this with [`reconcile_with`](Self::reconcile_with) on the *other*
/// node's snapshot (exchanged over the control plane after a partition heals)
/// to deterministically merge diverged state. Producing a snapshot does not
/// mutate any state.
///
/// # Errors
///
/// Returns `TidalError::Internal` if this node was opened without a schema
/// (no signal ledger to snapshot).
pub fn take_crdt_snapshot(
&self,
) -> crate::Result<crate::replication::reconcile::StateSnapshot> {
use crate::replication::{
crdt::{Hlc, LWWRegister},
reconcile::{HardNegAction, StateSnapshot},
};
let ledger = self.ledger()?;
let local_shard = self.config.cluster.shard_id;
let mut snapshot = StateSnapshot::new();
// Signal contributions (stored decay accumulator + windowed bucket count
// per entry). The contribution carries each entry's stored score paired
// with its own last_update_ns; decay is applied once at reconcile time.
//
// # Why the canonical replication shard, NOT `local_shard` (BUG 2 fix)
//
// Signals are fully replicated from a SINGLE writer (the cluster leader)
// through the WAL relay: every node folds the *same* event stream into
// its local hot accumulator in the same order, so after convergence every
// node's `(stored_score, last_update_ns)` for a given (entity, signal) is
// bitwise-identical. The local hot accumulator is therefore NOT a
// per-node-disjoint contribution — it already contains the other nodes'
// (relayed) events. Attributing the whole accumulator to `local_shard`
// fabricates N disjoint per-shard contributions for one logical stream,
// which `CrdtSignalState::merge` then SUMS — double-counting every
// replicated event on every reconcile (the lag-free creep the UAT saw).
//
// Keying every node's signal contribution to ONE canonical shard
// ([`ShardId::SINGLE`], matching the WAL relay's `RegionId::SINGLE`
// addressing) makes the same logical contribution carry the same shard key
// everywhere. `merge` is then last-writer-wins per that single key:
// reconcile of two converged nodes is an exact no-op (identical
// `(score, ts)` → merge keeps it unchanged), and reconcile of a leader vs.
// a partition-lagging follower deterministically keeps the leader's
// more-complete accumulator (larger `last_update_ns`) without summing. The
// attribution is honest because there is exactly one writer stream per
// signal: a single canonical contributor, not one-per-replica.
let canonical_shard = crate::replication::shard::ShardId::SINGLE;
for (entity_id, type_id, state) in ledger.crdt_contributions(canonical_shard) {
snapshot.add_signal_state(entity_id, type_id, state);
}
// Hard-negative membership → per-pair Hide registers stamped at now().
// One HLC for this node attributes every register to this shard with a
// strictly-monotonic timestamp, so the reconcile engine can LWW-order
// them against remote hide/unhide decisions. The configured wall-clock
// offset (0 in production) flows in here so a clock-skew UAT process
// stamps registers with its genuinely skewed HLC.
let hlc = Hlc::for_shard_with_offset(local_shard, self.config.hlc_offset_ms);
for (user_id, item_id) in self.hard_negatives.all_pairs() {
let mut reg = LWWRegister::empty();
reg.write(HardNegAction::Hide, hlc.now());
snapshot.add_hardneg_register(
crate::schema::EntityId::new(user_id),
crate::schema::EntityId::new(u64::from(item_id)),
reg,
);
}
Ok(snapshot)
}
/// Reconcile this node's live state against a remote node's CRDT snapshot
/// after a partition heals.
///
/// Builds a [`ReconciliationEngine`](crate::replication::reconcile::ReconciliationEngine)
/// bound to this node's signal ledger and hard-negative index, takes this
/// node's current [`take_crdt_snapshot`](Self::take_crdt_snapshot) as the
/// local side, computes the deterministic
/// [`MergePlan`](crate::replication::reconcile::MergePlan) against
/// `remote_snapshot`, and applies it:
///
/// - signal states are CRDT-merged per `(entity, signal_type)` (per-node
/// contributions preserved, windowed counts summed) and folded into both
/// the hot and warm tiers via `apply_crdt_state`;
/// - hard negatives are LWW-resolved per `(user, item)` by HLC timestamp and
/// committed (Hide → add, Unhide → remove).
///
/// Applying is idempotent: re-running with the same `remote_snapshot`
/// produces identical state, so this is safe under at-least-once delivery of
/// the snapshot exchange. Returns the number of operations applied (signal
/// merges + hard-negative resolutions) for observability.
///
/// This is the production entry point that heals a partition — without it the
/// CRDT subsystem never runs outside tests. Wire it into the anti-entropy /
/// reconnection flow by exchanging snapshots between the two sides and calling
/// this on each. (No standing reconnection hook exists yet; the control plane
/// tracks health only.)
///
/// # Errors
///
/// Returns `TidalError::Internal` if this node has no schema/ledger, or if a
/// signal type in the plan is unknown to this ledger, or a hard-negative item
/// ID exceeds the `u32` bitmap range.
pub fn reconcile_with(
&self,
remote_snapshot: &crate::replication::reconcile::StateSnapshot,
) -> crate::Result<usize> {
use crate::replication::reconcile::ReconciliationEngine;
self.require_writeable("reconcile_with")?;
let ledger = Arc::clone(self.ledger()?);
let hard_neg = Arc::clone(&self.hard_negatives);
let local_snapshot = self.take_crdt_snapshot()?;
let engine = ReconciliationEngine::new(ledger, hard_neg);
let plan = engine.plan(&local_snapshot, remote_snapshot);
let op_count = plan.operation_count();
engine.apply(&plan)?;
tracing::info!(
ops = op_count,
signal_merges = plan.signal_merges.len(),
hardneg_resolutions = plan.hardneg_resolutions.len(),
"reconcile_with: applied CRDT merge plan after partition heal"
);
Ok(op_count)
}
/// Restore the tenant router's migration routing state (dual-write pairs +
/// shard pins) from its durable checkpoint.
///
/// Idempotent and safe to call once at open: on first boot / no checkpoint /
/// ephemeral mode it restores nothing (every tenant uses jump-hash routing).
/// Without it, a crash mid-migration silently reverts a finalized tenant to
/// jump-hash routing (Accuracy-W). A read error is non-fatal: the node starts
/// with empty routing and logs the failure.
///
/// **Open-time wiring (db/mod.rs, out of scope):** call this once in
/// `from_parts` immediately after `build_control_plane`, e.g.
/// `db.restore_migration_routing();` after the `TidalDb` value is built — or,
/// before the value exists, `crate::replication::tenant::restore_migration_routing(sb.items_engine(), &tenant_router)`.
pub(crate) fn restore_migration_routing(&self) {
let Ok(storage) = self.storage() else {
return; // ephemeral / no schema: nothing durable to restore.
};
if let Err(e) = crate::replication::tenant::restore_migration_routing(
storage.items_engine(),
&self.tenant_router,
) {
tracing::warn!(
error = %e,
"migration routing checkpoint read failed; tenant routing starts empty \
(tenants fall back to jump-hash routing)"
);
}
}
/// Returns the shared `TenantRouter` for multi-tenant routing.
#[must_use]
#[allow(clippy::missing_const_for_fn)]
pub fn tenant_router(&self) -> Arc<crate::replication::TenantRouter> {
Arc::clone(&self.tenant_router)
}
/// Returns a reference to the embedded control plane.
#[must_use]
#[allow(clippy::missing_const_for_fn)]
pub fn control_plane(&self) -> &Arc<crate::replication::ControlPlane> {
&self.control_plane
}
/// Create a `RollingUpgradeCoordinator` backed by this instance's control plane.
#[must_use]
pub fn rolling_upgrade_coordinator(&self) -> crate::replication::RollingUpgradeCoordinator {
crate::replication::RollingUpgradeCoordinator::new(Arc::clone(&self.control_plane))
}
/// Write a signal on behalf of a tenant, enforcing per-tenant rate limits.
///
/// Dispatches to each assigned shard. On single-node deployments all
/// assignments resolve to the local shard, so behavior is identical to
/// calling `signal()` directly.
///
/// # On-node tenant isolation is LOGICAL, not physical
///
/// `tenant_id` drives the per-tenant rate limiter and the shard routing
/// only. The local write below goes to the single shared signal
/// ledger/entity store with **no** tenant namespace in the key, so on a
/// single node hosting multiple tenants every tenant's signals co-mingle in
/// one keyspace/WAL. Physical per-tenant keyspace/WAL isolation and
/// enforcement of `TenantConfig::max_storage_bytes`/`max_entities` are a
/// separate, not-yet-wired task (`docs/specs/14-scale-architecture.md`).
///
/// # Remote-shard dispatch is NOT yet wired (fully fails closed)
///
/// During a dual-write migration the tenant router resolves two assignments
/// (source and target shard). Cross-node dispatch of the remote half over
/// the replication transport is **not yet implemented** (tracked as the
/// "Task 5" shipper-integrated remote dispatch in `docs/specs/14`, per
/// `CODING_GUIDELINES.md` §12 "no TODO without a tracking note"). Rather than
/// silently dropping the remote write — which would lose signals during a
/// migration with no error visible to the caller — this method **fails
/// closed BEFORE any write happens**: it checks every resolved assignment
/// first, and if *any* targets a non-local shard it returns
/// `TidalError::Internal` with zero mutations. This makes the operation
/// atomic from the caller's perspective — a retry after the error cannot
/// double-count the local half, because the local half is never written when
/// the whole op cannot succeed (W8).
///
/// # Errors
///
/// - `TidalError::QuotaExceeded` — tenant rate limit exceeded.
/// - `TidalError::Internal` — no eligible shards for the tenant, OR an
/// assignment targets a non-local shard while cross-node dispatch is
/// unwired (see above). In the latter case NO signal was written.
/// - Any error from the underlying `signal()` call.
pub fn signal_for_tenant(
&self,
tenant_id: crate::replication::TenantId,
signal_type: &str,
entity_id: crate::schema::EntityId,
weight: f64,
timestamp: crate::schema::Timestamp,
) -> crate::Result<()> {
self.require_writeable("signal_for_tenant")?;
if let Some(limiter) = self.tenant_router.rate_limiter_for(tenant_id) {
limiter.try_acquire()?;
}
// Resolve all shard targets (1 in normal mode; 2 during dual-write migration).
let assignments = self.tenant_router.write_assignments(tenant_id, entity_id)?;
let local_shard = self.config.cluster.shard_id;
// Fail CLOSED *before* any write (W8): scan all assignments first. If any
// targets a non-local shard, the cross-node dispatch needed to satisfy
// the dual-write is unwired (Task 5, docs/specs/14), so the whole op
// cannot succeed. Returning here — before the local write — makes the
// operation atomic: a caller that retries the returned Err cannot
// double-count the local signal (signal()/record_signal accumulates and
// is not idempotent). A previous version wrote the local half first and
// only then errored, so every retry inflated the local weight.
if let Some(remote) = assignments.iter().find(|a| a.shard_id != local_shard) {
tracing::warn!(
tenant_id = tenant_id.0,
shard_id = remote.shard_id.0,
entity_id = entity_id.as_u64(),
signal_type,
"signal_for_tenant: remote-shard dispatch is not wired (Task 5); \
failing closed BEFORE any write to avoid silently dropping the \
dual-write or double-counting the local half on retry"
);
return Err(crate::TidalError::internal(
"signal_for_tenant",
format!(
"remote-shard dispatch not yet wired: assignment targets shard {} \
but this node is shard {}; cross-node dual-write requires the \
transport-integrated shipper (Task 5, docs/specs/14)",
remote.shard_id.0, local_shard.0
),
));
}
// Every assignment is local: apply the local write(s). On a single node
// all assignments resolve to the same local shard, so the write happens
// once per assignment (normally exactly one).
for _assignment in &assignments {
self.signal(signal_type, entity_id, weight, timestamp)?;
}
Ok(())
}
}
/// Read the WAL checkpoint-marker seq a staged snapshot artifact carries
/// (m11p5): `<dest>/wal/checkpoint.meta`. `None` when the artifact's WAL has no
/// marker (an empty-WAL artifact at seq 0 writes none) or the marker is
/// unreadable — the caller treats that as "no lower seq to re-pin to" and holds
/// the pin at the captured tail.
fn read_artifact_marker_seq(dest: &std::path::Path) -> Option<u64> {
let wal_dir = dest.join("wal");
match crate::wal::checkpoint::CheckpointManager::read(&wal_dir) {
Ok(Some((seq, _ts))) => Some(seq),
Ok(None) => None,
Err(e) => {
// A corrupt/unreadable marker in our OWN just-written artifact is a
// surprise; log it but do not fail the stage — holding the pin at
// the captured tail is the conservative (more-history) choice.
tracing::warn!(
dest = %dest.display(),
error = %e,
"could not read staged snapshot WAL marker; holding the retention \
pin at the captured tail"
);
None
}
}
}
/// `Weak`-handle adapter from the segment receiver's blob-apply seam to the
/// database's WAL-first item write paths.
///
/// Holds a `Weak` so the receiver thread can never keep the `TidalDb` alive
/// past its owner (an `Arc` here would cycle: db owns the receiver handle,
/// the receiver would own the db). After the last strong handle drops, an
/// in-flight apply fails with "database closed" and the receiver halts.
struct WeakBlobApplier(std::sync::Weak<TidalDb>);
impl WeakBlobApplier {
fn upgrade(&self) -> crate::Result<Arc<TidalDb>> {
self.0.upgrade().ok_or_else(|| {
crate::TidalError::internal(
"replicated_blob_apply",
"database closed while a replicated item/embedding apply was in flight",
)
})
}
}
impl crate::replication::receiver::ReplicatedBlobApplier for WeakBlobApplier {
fn apply_blobs(&self, records: Vec<crate::wal::format::BlobRecord>) -> crate::Result<()> {
// The FULL write path, not the local-apply variant: the follower
// re-journals every record in its OWN WAL (WAL-first, staged as one
// batch so the round shares group-commit fsyncs — m11p3) so follower
// recovery — and a later promotion's outbound stream — carry them.
self.upgrade()?.apply_replicated_blobs(records)
}
}