Skip to main content

arete_server/snapshot/
mod.rs

1//! Opt-in periodic snapshots of in-memory server state (VM entity tables +
2//! projection caches) and a restore path that rehydrates on startup, so a
3//! restarted server comes back with its history instead of starting empty.
4//!
5//! arete-server owns all snapshot logic. The generated runtime's only
6//! responsibilities are (1) registering the `VmContext`/`SlotTracker` it
7//! creates via [`register_runtime`] and (2) hydrating from a restored blob via
8//! [`take_restored`] before connecting to Yellowstone. Those hooks resolve
9//! through a task-local [`SnapshotRuntime`], so multiple servers embedded in
10//! one process cannot consume or replace each other's snapshot state. A stack
11//! built with an older arete-macros simply never registers a VM; snapshots
12//! stay disabled with a warning.
13//!
14//! Consistency cut: every generated VM update holds a shared snapshot barrier
15//! guard until its mutation batch has been applied by the projector. Snapshot
16//! capture takes the exclusive guard before dumping either side, so the VM,
17//! projection caches, and resume watermark all describe the same processing
18//! cut. On restore the stream replays from that watermark; the snapshotted
19//! version trackers drop the overlap.
20
21pub mod envelope;
22#[cfg(feature = "snapshot-object-store")]
23pub mod object;
24pub mod store;
25
26pub use envelope::{SnapshotContract, SnapshotHeader, SnapshotPayload};
27#[cfg(feature = "snapshot-object-store")]
28pub use object::ObjectSnapshotStore;
29pub use store::{FsStore, SnapshotStore};
30
31use crate::cache::EntityCache;
32use crate::health::SlotTracker;
33use crate::mutation_batch::MutationBatch;
34use crate::view::ViewIndex;
35use anyhow::{Context, Result};
36use arete_interpreter::snapshot::{VmSnapshot, SNAPSHOT_FORMAT_VERSION};
37use arete_interpreter::vm::VmContext;
38use serde::Serialize;
39use sha2::{Digest, Sha256};
40use std::collections::{BTreeMap, BTreeSet, HashMap};
41use std::future::Future;
42use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
43use std::sync::{Arc, Mutex as StdMutex};
44use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
45use tokio::sync::{mpsc, OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock};
46use tracing::{debug, info, info_span, warn, Instrument};
47
48/// Rough Solana slot duration, used only to convert snapshot age into an
49/// estimated slot distance for the staleness clamp.
50const ESTIMATED_SLOT_MILLIS: u64 = 200;
51/// How long a snapshot cycle waits for in-flight VM updates and their queued
52/// projection batches to finish.
53const CONSISTENCY_CUT_TIMEOUT: Duration = Duration::from_secs(10);
54const STATE_CONTRACT_SCHEMA_V1: &str = "arete.snapshot-state-contract/v1";
55const PROJECTION_CONTRACT_SCHEMA_V1: &str = "arete.snapshot-projection-contract/v1";
56
57/// Configuration for state snapshots. Disabled by default; enable via
58/// `ServerBuilder::snapshots(...)` or `ARETE_SNAPSHOT_*` env vars.
59#[derive(Clone, Debug)]
60pub struct SnapshotConfig {
61    /// Master opt-in.
62    pub enabled: bool,
63    /// Where blobs live: `file:///var/lib/arete/snapshots`, a plain path, or
64    /// (with the `snapshot-object-store` feature) `s3://`/`gs://`/`az://`.
65    pub url: Option<String>,
66    /// Periodic snapshot cadence.
67    pub interval: Duration,
68    /// Retained snapshots; older ones are pruned after each write.
69    pub keep: usize,
70    /// Take a final snapshot on SIGTERM/SIGINT before exit.
71    pub snapshot_on_shutdown: bool,
72    /// Skip a periodic cycle when fewer batches were applied since the last
73    /// snapshot (quiet stacks snapshot rarely).
74    pub min_mutations: u64,
75    /// If the watermark's estimated lag is greater than this many slots,
76    /// including lag at snapshot time plus file age, hydrate state but start
77    /// the stream live instead of resuming from the watermark.
78    pub max_resume_age_slots: u64,
79    /// `/ready` stays 503 after a watermark resume until the projector is
80    /// within this many slots of the observed tip...
81    pub ready_max_lag_slots: u64,
82    /// ...or until this much time has passed (guards quiet stacks, where the
83    /// watermark never advances because nothing happens on-chain).
84    pub ready_max_hold: Duration,
85    /// Bytecode hashes from pre-contract snapshots that an operator has
86    /// explicitly approved for one state-only migration. These snapshots are
87    /// hydrated after structural state-id remapping and always start live.
88    pub legacy_bytecode_hashes: BTreeSet<String>,
89}
90
91impl Default for SnapshotConfig {
92    fn default() -> Self {
93        Self {
94            enabled: false,
95            url: None,
96            interval: Duration::from_secs(60),
97            keep: 4,
98            snapshot_on_shutdown: true,
99            min_mutations: 1,
100            // ~10 minutes of slots: conservative vs. typical provider
101            // `from_slot` replay windows (in-cluster richat rings are far
102            // more generous; raw Triton is minutes).
103            max_resume_age_slots: 1_500,
104            ready_max_lag_slots: 50,
105            ready_max_hold: Duration::from_secs(60),
106            legacy_bytecode_hashes: BTreeSet::new(),
107        }
108    }
109}
110
111impl SnapshotConfig {
112    /// Load snapshot settings from `ARETE_SNAPSHOT_*` env vars. Snapshots stay
113    /// disabled unless `ARETE_SNAPSHOT_ENABLED=true`.
114    pub fn from_env() -> Result<Self> {
115        let mut config = Self::default();
116        config.enabled = crate::config::env_bool("ARETE_SNAPSHOT_ENABLED")?.unwrap_or(false);
117        config.url = std::env::var("ARETE_SNAPSHOT_URL")
118            .ok()
119            .filter(|value| !value.trim().is_empty());
120        config.interval = Duration::from_secs(
121            crate::config::env_parse("ARETE_SNAPSHOT_INTERVAL_SECS")?
122                .unwrap_or(config.interval.as_secs()),
123        );
124        config.keep = crate::config::env_parse("ARETE_SNAPSHOT_KEEP")?.unwrap_or(config.keep);
125        config.snapshot_on_shutdown = crate::config::env_bool("ARETE_SNAPSHOT_ON_SHUTDOWN")?
126            .unwrap_or(config.snapshot_on_shutdown);
127        config.min_mutations = crate::config::env_parse("ARETE_SNAPSHOT_MIN_MUTATIONS")?
128            .unwrap_or(config.min_mutations);
129        config.max_resume_age_slots =
130            crate::config::env_parse("ARETE_SNAPSHOT_MAX_RESUME_AGE_SLOTS")?
131                .unwrap_or(config.max_resume_age_slots);
132        config.ready_max_lag_slots =
133            crate::config::env_parse("ARETE_SNAPSHOT_READY_MAX_LAG_SLOTS")?
134                .unwrap_or(config.ready_max_lag_slots);
135        config.ready_max_hold = Duration::from_secs(
136            crate::config::env_parse("ARETE_SNAPSHOT_READY_MAX_HOLD_SECS")?
137                .unwrap_or(config.ready_max_hold.as_secs()),
138        );
139        config.legacy_bytecode_hashes = std::env::var("ARETE_SNAPSHOT_LEGACY_BYTECODE_HASHES")
140            .ok()
141            .into_iter()
142            .flat_map(|value| {
143                value
144                    .split(',')
145                    .map(str::trim)
146                    .filter(|hash| !hash.is_empty())
147                    .map(str::to_ascii_lowercase)
148                    .collect::<Vec<_>>()
149            })
150            .collect();
151        config.validate()?;
152        Ok(config)
153    }
154
155    pub fn validate(&self) -> Result<()> {
156        if self.enabled && self.url.as_deref().is_none_or(|url| url.trim().is_empty()) {
157            anyhow::bail!("snapshots are enabled but ARETE_SNAPSHOT_URL is not set");
158        }
159        if self.enabled && (self.interval.is_zero() || self.keep == 0) {
160            anyhow::bail!("snapshot interval and keep count must be greater than zero");
161        }
162        for hash in &self.legacy_bytecode_hashes {
163            if hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit()) {
164                anyhow::bail!(
165                    "ARETE_SNAPSHOT_LEGACY_BYTECODE_HASHES contains invalid SHA-256 hash '{hash}'"
166                );
167            }
168        }
169        Ok(())
170    }
171}
172
173fn contract_hash<T: Serialize>(schema: &str, value: &T) -> SnapshotContract {
174    let canonical = arete_hash::canonicalize_jcs(value)
175        .expect("snapshot contracts contain only canonical JSON values");
176    let hash = hex::encode(Sha256::digest(canonical));
177    SnapshotContract {
178        schema: schema.to_string(),
179        hash,
180    }
181}
182
183fn state_contract(spec: &crate::Spec) -> Option<SnapshotContract> {
184    if spec.entity_specs.is_empty() {
185        return None;
186    }
187    let mut entities = Vec::with_capacity(spec.entity_specs.len());
188    for entity in &spec.entity_specs {
189        let mut indexes = entity
190            .identity
191            .lookup_indexes
192            .iter()
193            .map(|index| (&index.field_name, &index.temporal_field))
194            .collect::<Vec<_>>();
195        indexes.sort();
196        indexes.dedup();
197        let fields = entity
198            .field_mappings
199            .iter()
200            .map(|(path, field)| {
201                (
202                    path,
203                    serde_json::json!({
204                        "baseType": field.base_type,
205                        "integerKind": field.integer_kind,
206                        "isOptional": field.is_optional,
207                        "isArray": field.is_array,
208                        "innerType": field.inner_type,
209                        "resolvedType": field.resolved_type,
210                        "emit": field.emit,
211                    }),
212                )
213            })
214            .collect::<BTreeMap<_, _>>();
215        entities.push(serde_json::json!({
216            "name": entity.state_name,
217            "primaryKeys": entity.identity.primary_keys,
218            "lookupIndexes": indexes,
219            "fields": fields,
220        }));
221    }
222    entities.sort_by_key(|entity| entity["name"].as_str().unwrap_or_default().to_string());
223    Some(contract_hash(
224        STATE_CONTRACT_SCHEMA_V1,
225        &serde_json::json!({"entities": entities}),
226    ))
227}
228
229fn projection_contract(view_index: &ViewIndex) -> SnapshotContract {
230    contract_hash(PROJECTION_CONTRACT_SCHEMA_V1, &view_index.snapshot_specs())
231}
232
233fn state_ids_by_entity(spec: &crate::Spec) -> HashMap<String, u32> {
234    spec.bytecode
235        .entities
236        .iter()
237        .map(|(name, entity)| (name.clone(), entity.state_id))
238        .collect()
239}
240
241fn remap_snapshot_states(vm: &mut VmSnapshot, state_ids: &HashMap<String, u32>) -> Result<()> {
242    let states = std::mem::take(&mut vm.states);
243    for (_, table) in states {
244        let state_id = state_ids
245            .get(&table.entity_name)
246            .with_context(|| format!("snapshot contains unknown entity '{}'", table.entity_name))?;
247        if vm.states.insert(*state_id, table).is_some() {
248            anyhow::bail!("snapshot contains duplicate entity state for id {state_id}");
249        }
250    }
251    Ok(())
252}
253
254/// VM state handed from the restore path to the generated runtime, consumed
255/// exactly once via [`take_restored`].
256pub struct RestoredState {
257    pub vm: VmSnapshot,
258    /// `Some(slot)` to resume the Yellowstone stream from that slot; `None`
259    /// when the snapshot was too stale (state still hydrates, stream starts
260    /// live and account-derived state self-heals).
261    pub resume_watermark: Option<u64>,
262}
263
264#[derive(Clone)]
265struct RuntimeRegistration {
266    vm: Arc<StdMutex<VmContext>>,
267    slot_tracker: SlotTracker,
268}
269
270struct ResumeGate {
271    started: Instant,
272    max_lag_slots: u64,
273    max_hold: Duration,
274}
275
276/// Per-runtime barrier that keeps snapshot capture from splitting a VM update
277/// from the projection batch it produced.
278///
279/// Generated mutation producers enter the barrier in shared mode before
280/// touching the VM and transfer the guard to their [`MutationBatch`]. The
281/// projector releases it only after applying that batch. Snapshot capture
282/// enters in exclusive mode, which therefore waits for both in-flight parser
283/// work and queued projection work to finish.
284#[derive(Clone, Default)]
285pub struct SnapshotBarrier {
286    inner: Arc<RwLock<()>>,
287}
288
289impl SnapshotBarrier {
290    pub async fn enter_processing(&self) -> SnapshotProcessingGuard {
291        SnapshotProcessingGuard(self.inner.clone().read_owned().await)
292    }
293
294    async fn enter_snapshot(&self) -> OwnedRwLockWriteGuard<()> {
295        self.inner.clone().write_owned().await
296    }
297}
298
299/// Shared processing guard carried by a mutation batch until projection is
300/// complete. The inner guard is intentionally opaque outside arete-server.
301pub struct SnapshotProcessingGuard(#[allow(dead_code)] OwnedRwLockReadGuard<()>);
302
303impl std::fmt::Debug for SnapshotProcessingGuard {
304    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305        formatter.write_str("SnapshotProcessingGuard")
306    }
307}
308
309#[derive(Default)]
310struct SnapshotRuntimeState {
311    registered: StdMutex<Option<RuntimeRegistration>>,
312    restored: StdMutex<Option<RestoredState>>,
313    resume_gate: StdMutex<Option<ResumeGate>>,
314    processing_barrier: SnapshotBarrier,
315    /// Highest slot among mutation batches this runtime's projector has
316    /// applied. This is the safe `from_slot` resume point (`SlotTracker` is
317    /// not: it follows the raw slot subscription, not parser progress).
318    resume_watermark: AtomicU64,
319    applied_batches: AtomicU64,
320}
321
322/// Per-server snapshot coordination shared by its parser, projector, snapshot
323/// manager, and readiness endpoint.
324///
325/// The generated parser hooks use [`scope`](Self::scope) so their existing
326/// argument-free calls cannot accidentally bind to another server running in
327/// the same process.
328#[derive(Clone, Default)]
329pub struct SnapshotRuntime {
330    state: Arc<SnapshotRuntimeState>,
331}
332
333tokio::task_local! {
334    static ACTIVE_SNAPSHOT_RUNTIME: SnapshotRuntime;
335}
336
337impl SnapshotRuntime {
338    /// Run a generated parser future with this server's snapshot state.
339    pub async fn scope<F>(&self, future: F) -> F::Output
340    where
341        F: Future,
342    {
343        ACTIVE_SNAPSHOT_RUNTIME.scope(self.clone(), future).await
344    }
345
346    /// Associate the parser's VM and slot tracker with this server only.
347    pub fn register_runtime(
348        &self,
349        vm: Arc<StdMutex<VmContext>>,
350        slot_tracker: SlotTracker,
351    ) -> SnapshotBarrier {
352        let mut registered = self.state.registered.lock().unwrap();
353        if registered.is_some() {
354            debug!("Snapshot runtime registration replaced");
355        }
356        *registered = Some(RuntimeRegistration { vm, slot_tracker });
357        self.state.processing_barrier.clone()
358    }
359
360    /// Consume this server's restored VM state exactly once.
361    pub fn take_restored(&self) -> Option<RestoredState> {
362        self.state.restored.lock().unwrap().take()
363    }
364
365    /// Record a batch applied by this server's projector.
366    pub(crate) fn record_applied_batch(&self, slot: Option<u64>) {
367        self.state.applied_batches.fetch_add(1, Ordering::Relaxed);
368        if let Some(slot) = slot {
369            self.state
370                .resume_watermark
371                .fetch_max(slot, Ordering::Relaxed);
372        }
373    }
374
375    /// Returns `true` unless this server's watermark resume is still catching
376    /// up to its observed slot tip.
377    pub fn resume_gate_ready(&self) -> bool {
378        let mut gate_slot = self.state.resume_gate.lock().unwrap();
379        let Some(gate) = gate_slot.as_ref() else {
380            return true;
381        };
382        if gate.started.elapsed() >= gate.max_hold {
383            info!("Snapshot resume readiness gate released (max hold reached)");
384            *gate_slot = None;
385            return true;
386        }
387        let tip = self
388            .state
389            .registered
390            .lock()
391            .unwrap()
392            .as_ref()
393            .map(|registration| registration.slot_tracker.get())
394            .unwrap_or(0);
395        let applied = self.state.resume_watermark.load(Ordering::Relaxed);
396        if tip > 0 && tip.saturating_sub(applied) <= gate.max_lag_slots {
397            info!(tip, applied, "Snapshot resume caught up; marking ready");
398            *gate_slot = None;
399            return true;
400        }
401        false
402    }
403}
404
405/// Called by the generated runtime after it creates its `VmContext` and
406/// `SlotTracker`, so the snapshot manager can dump them later.
407///
408/// Whether or not snapshots are enabled, this also links the VM to the
409/// server's projector, which asks it for whole entities its bounded cache had
410/// to drop (see [`crate::projector::EntityResync`]).
411pub fn register_runtime(
412    vm: Arc<StdMutex<VmContext>>,
413    slot_tracker: SlotTracker,
414) -> Option<SnapshotBarrier> {
415    crate::projector::link_active_resync(&vm);
416    match ACTIVE_SNAPSHOT_RUNTIME.try_with(|runtime| runtime.register_runtime(vm, slot_tracker)) {
417        Ok(barrier) => Some(barrier),
418        Err(_) => {
419            debug!("Snapshot runtime registration ignored (snapshots disabled)");
420            None
421        }
422    }
423}
424
425/// Called by the generated runtime before connecting: returns the restored VM
426/// state (if any) exactly once.
427pub fn take_restored() -> Option<RestoredState> {
428    ACTIVE_SNAPSHOT_RUNTIME
429        .try_with(SnapshotRuntime::take_restored)
430        .ok()
431        .flatten()
432}
433
434/// Where the generated Yellowstone runtime should resume its stream.
435///
436/// `Option<u64>` cannot express this: "no checkpoint to resume from" and
437/// "gave up on the checkpoint" are both `None`, and only the second one
438/// loses data. Naming them apart is what lets the caller mark the hole.
439#[derive(Debug, Clone, Copy, PartialEq, Eq)]
440pub enum ReconnectPosition {
441    /// Resume from this slot; nothing is lost.
442    Slot(u64),
443    /// Start live because nothing has been processed yet.
444    Live,
445    /// Start live after abandoning a checkpoint the provider would not serve.
446    /// Every slot between `abandoned` and the live tip is lost.
447    LiveAfterGap { abandoned: u64 },
448}
449
450impl ReconnectPosition {
451    /// The `from_slot` to put on the subscription request.
452    pub fn from_slot(self) -> Option<u64> {
453        match self {
454            Self::Slot(slot) => Some(slot),
455            Self::Live | Self::LiveAfterGap { .. } => None,
456        }
457    }
458}
459
460/// Select a reconnect checkpoint for the generated Yellowstone runtime.
461///
462/// A restored replay never falls back to live: retries advance only to slots
463/// the main parser stream has finished processing. Without a restored replay,
464/// repeated short-lived connections eventually give up on the checkpoint —
465/// unless `live_fallback_attempts` is `None`, which refuses to trade data for
466/// availability.
467#[doc(hidden)]
468pub fn select_reconnect_from_slot(
469    restored_watermark: Option<u64>,
470    processed_watermark: u64,
471    attempt: u32,
472    live_fallback_attempts: Option<u32>,
473) -> ReconnectPosition {
474    if let Some(restored_watermark) = restored_watermark {
475        return ReconnectPosition::Slot(restored_watermark.max(processed_watermark));
476    }
477    if processed_watermark == 0 {
478        // Nothing has been processed, so starting live loses nothing.
479        return ReconnectPosition::Live;
480    }
481    match live_fallback_attempts {
482        Some(limit) if attempt >= limit => ReconnectPosition::LiveAfterGap {
483            abandoned: processed_watermark,
484        },
485        _ => ReconnectPosition::Slot(processed_watermark),
486    }
487}
488
489fn now_epoch_ms() -> u64 {
490    SystemTime::now()
491        .duration_since(UNIX_EPOCH)
492        .unwrap()
493        .as_millis() as u64
494}
495
496/// What kicked off a snapshot cycle.
497#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
498#[serde(rename_all = "snake_case")]
499pub enum SnapshotTrigger {
500    Periodic,
501    Shutdown,
502}
503
504/// Owns the store plus everything needed to dump and restore state. Created by
505/// `Runtime::run` when snapshots are enabled.
506pub struct SnapshotService {
507    config: SnapshotConfig,
508    store: Arc<dyn SnapshotStore>,
509    runtime: SnapshotRuntime,
510    bytecode_hash: String,
511    state_contract: Option<SnapshotContract>,
512    projection_contract: SnapshotContract,
513    state_ids: HashMap<String, u32>,
514    program_ids: Vec<String>,
515    entity_cache: EntityCache,
516    journal: Arc<crate::journal::EventJournal>,
517    batches_at_last_snapshot: AtomicU64,
518    warned_missing_vm: AtomicBool,
519}
520
521impl SnapshotService {
522    /// Build the store, then attempt a restore (any failure logs a warning
523    /// and cold-starts — restore problems must never block startup).
524    pub async fn initialize(
525        config: SnapshotConfig,
526        spec: &crate::Spec,
527        entity_cache: EntityCache,
528        view_index: &ViewIndex,
529        journal: Arc<crate::journal::EventJournal>,
530        _mutations_tx: mpsc::Sender<MutationBatch>,
531    ) -> Result<Arc<Self>> {
532        let url = config
533            .url
534            .clone()
535            .context("snapshots are enabled but no snapshot URL is configured")?;
536        let store = store::store_from_url(&url)?;
537
538        let mut program_ids = spec.program_ids.clone();
539        program_ids.sort();
540
541        let service = Arc::new(Self {
542            config,
543            store,
544            runtime: SnapshotRuntime::default(),
545            bytecode_hash: spec.bytecode.fingerprint(),
546            state_contract: state_contract(spec),
547            projection_contract: projection_contract(view_index),
548            state_ids: state_ids_by_entity(spec),
549            program_ids,
550            entity_cache,
551            journal,
552            batches_at_last_snapshot: AtomicU64::new(0),
553            warned_missing_vm: AtomicBool::new(false),
554        });
555        info!(
556            store = %service.store.describe(),
557            interval_secs = service.config.interval.as_secs(),
558            keep = service.config.keep,
559            "State snapshots enabled"
560        );
561
562        match service.restore(view_index).await {
563            Ok(true) => {}
564            Ok(false) => info!("No usable snapshot found; starting cold"),
565            Err(err) => warn!(
566                error = format!("{err:#}"),
567                "Failed to restore snapshot; starting cold"
568            ),
569        }
570        Ok(service)
571    }
572
573    pub fn config(&self) -> &SnapshotConfig {
574        &self.config
575    }
576
577    /// Return the per-server coordination handle that must be shared with the
578    /// matching parser, projector, and readiness endpoint.
579    pub fn runtime(&self) -> SnapshotRuntime {
580        self.runtime.clone()
581    }
582
583    /// Load and validate the latest snapshot, hydrate the projection caches,
584    /// and stash the VM portion for the generated runtime. Returns whether a
585    /// snapshot was applied.
586    async fn restore(&self, view_index: &ViewIndex) -> Result<bool> {
587        let Some((name, bytes)) = self.store.load_latest().await? else {
588            return Ok(false);
589        };
590
591        let header = envelope::decode_header(&bytes)
592            .with_context(|| format!("snapshot {name} has an unreadable header"))?;
593
594        if header.format_version != SNAPSHOT_FORMAT_VERSION {
595            warn!(
596                snapshot = %name,
597                found = header.format_version,
598                expected = SNAPSHOT_FORMAT_VERSION,
599                "Snapshot format version mismatch; discarding (cold start)"
600            );
601            return Ok(false);
602        }
603        let exact_bytecode = header.bytecode_hash == self.bytecode_hash;
604        let matching_contracts = self.state_contract.is_some()
605            && header.state_contract == self.state_contract
606            && header.projection_contract.as_ref() == Some(&self.projection_contract);
607        let approved_legacy = !exact_bytecode
608            && header.state_contract.is_none()
609            && header.projection_contract.is_none()
610            && self
611                .config
612                .legacy_bytecode_hashes
613                .contains(&header.bytecode_hash);
614        let legacy_migration = approved_legacy;
615        if !exact_bytecode && !matching_contracts && !approved_legacy {
616            warn!(
617                snapshot = %name,
618                "Snapshot was taken by an incompatible stack build; discarding (cold start)"
619            );
620            return Ok(false);
621        }
622        let mut snapshot_program_ids = header.program_ids.clone();
623        snapshot_program_ids.sort();
624        if snapshot_program_ids != self.program_ids {
625            warn!(
626                snapshot = %name,
627                "Snapshot program ids do not match this server; discarding (cold start)"
628            );
629            return Ok(false);
630        }
631
632        let mut payload = tokio::task::spawn_blocking(move || envelope::decode_payload(&bytes))
633            .await
634            .context("snapshot decode task panicked")?
635            .with_context(|| format!("snapshot {name} has an unreadable payload"))?;
636        if !exact_bytecode {
637            remap_snapshot_states(&mut payload.vm, &self.state_ids)
638                .with_context(|| format!("snapshot {name} state contract is incompatible"))?;
639        }
640        if legacy_migration {
641            // A pre-contract snapshot cannot prove that its materialized views
642            // still match the current projections. Preserve only durable VM
643            // state and let live input rebuild every projection cache.
644            payload.entity_cache.clear();
645            // Retained frames are published view output, shaped by the same
646            // projections, so the same doubt applies — and replaying stale
647            // frames is worse than a stale cache, because consumers keep them.
648            payload.journal = Default::default();
649        }
650
651        let cached_views = payload.entity_cache.len();
652        let cached_entities: usize = payload
653            .entity_cache
654            .iter()
655            .map(|(_, entries)| entries.len())
656            .sum();
657        let retained_events: usize = payload
658            .journal
659            .views
660            .values()
661            .map(|view| view.records.len())
662            .sum();
663        self.entity_cache.hydrate(payload.entity_cache).await;
664        // The VM keeps more entities than the cache does (and after a legacy
665        // migration the cache keeps none), so its next patch for one the
666        // cache lacks is only the fields that changed. A VM linked to the
667        // projector has that patch refused anyway: a restored entity's next
668        // mutation is not its creation, and only a creation is stored for a
669        // key the cache lacks. Treat them all as evicted as well, for a VM
670        // registered without that link; the memory is bounded (see
671        // `EntityCache`), and a view fed by a linked VM drops it.
672        remember_uncached_vm_keys(view_index, &payload.vm, &self.entity_cache).await;
673        // Only a shutdown snapshot is exact; see `EventJournal::hydrate`.
674        let exact_offsets = header.trigger == Some(SnapshotTrigger::Shutdown);
675        self.journal.hydrate(payload.journal, exact_offsets).await;
676        rebuild_sorted_caches(view_index, &self.entity_cache).await;
677
678        // Even when the stream starts live, the watermark seeds the applied
679        // position: the hydrated state already contains everything up to it.
680        self.runtime
681            .state
682            .resume_watermark
683            .fetch_max(header.resume_watermark, Ordering::Relaxed);
684
685        let age_ms = now_epoch_ms().saturating_sub(header.created_at_epoch_ms);
686        let estimated_age_slots = age_ms / ESTIMATED_SLOT_MILLIS;
687        // File age alone is insufficient: a shutdown checkpoint is freshly
688        // written even when a quiet program's last applied update is already
689        // far behind the observed chain tip. Account for both the lag already
690        // present at the consistency cut and the time elapsed since it.
691        let watermark_lag_at_snapshot =
692            header.observed_slot.saturating_sub(header.resume_watermark);
693        let estimated_resume_lag = watermark_lag_at_snapshot.saturating_add(estimated_age_slots);
694        let resume_watermark = if exact_bytecode
695            && header.resume_watermark > 0
696            && estimated_resume_lag <= self.config.max_resume_age_slots
697        {
698            Some(header.resume_watermark)
699        } else {
700            if header.resume_watermark > 0 && exact_bytecode {
701                warn!(
702                    resume_watermark = header.resume_watermark,
703                    observed_slot = header.observed_slot,
704                    watermark_lag_at_snapshot,
705                    estimated_age_slots,
706                    estimated_resume_lag,
707                    max_resume_age_slots = self.config.max_resume_age_slots,
708                    "Snapshot watermark is outside the resume window; hydrating state but \
709                     starting the stream live. Account-derived state self-heals from \
710                     full account writes; only instruction events in the gap are missed."
711                );
712            }
713            if !exact_bytecode {
714                warn!(
715                    snapshot = %name,
716                    matching_contracts,
717                    approved_legacy,
718                    legacy_state_only = legacy_migration,
719                    "Hydrated snapshot state from different bytecode; starting live"
720                );
721            }
722            None
723        };
724
725        if resume_watermark.is_none() {
726            // The stream starts live, so events between the retained tape and
727            // the first live append are lost. Offsets stay dense across that
728            // hole, which would present it to a consumer as an unbroken
729            // continuation — mark it so a replay across it is refused instead.
730            self.journal.mark_gap().await;
731        }
732
733        if resume_watermark.is_some() {
734            *self.runtime.state.resume_gate.lock().unwrap() = Some(ResumeGate {
735                started: Instant::now(),
736                max_lag_slots: self.config.ready_max_lag_slots,
737                max_hold: self.config.ready_max_hold,
738            });
739        }
740
741        info!(
742            snapshot = %name,
743            vm_entities = payload.vm.total_entries(),
744            cached_views,
745            cached_entities,
746            retained_events,
747            resume_watermark = header.resume_watermark,
748            resuming = resume_watermark.is_some(),
749            age_secs = age_ms / 1_000,
750            "Restored state from snapshot"
751        );
752
753        *self.runtime.state.restored.lock().unwrap() = Some(RestoredState {
754            vm: payload.vm,
755            resume_watermark,
756        });
757        Ok(true)
758    }
759
760    /// Spawn the periodic snapshot task.
761    pub fn spawn(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
762        let service = Arc::clone(self);
763        tokio::spawn(
764            async move {
765                let mut interval = tokio::time::interval(service.config.interval);
766                interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
767                // The first tick fires immediately; skip it so the first
768                // snapshot lands one full interval after startup.
769                interval.tick().await;
770                loop {
771                    interval.tick().await;
772                    if let Err(err) = service.snapshot_now(SnapshotTrigger::Periodic).await {
773                        // Snapshotting must never take down a healthy server.
774                        warn!(
775                            error = format!("{err:#}"),
776                            "Snapshot cycle failed; will retry next interval"
777                        );
778                    }
779                }
780            }
781            .instrument(info_span!("snapshot.manager")),
782        )
783    }
784
785    /// Run one snapshot cycle. Returns `Ok(false)` when skipped (no VM
786    /// registered yet, or too few mutations since the last snapshot).
787    pub async fn snapshot_now(&self, trigger: SnapshotTrigger) -> Result<bool> {
788        let Some(registration) = self.runtime.state.registered.lock().unwrap().clone() else {
789            if !self.warned_missing_vm.swap(true, Ordering::Relaxed) {
790                warn!(
791                    "Snapshots are enabled but no VM has been registered; the stack \
792                     may have been built with an older arete-macros version"
793                );
794            }
795            return Ok(false);
796        };
797
798        let applied_batches = self.runtime.state.applied_batches.load(Ordering::Relaxed);
799        if trigger == SnapshotTrigger::Periodic {
800            let since_last = applied_batches
801                .saturating_sub(self.batches_at_last_snapshot.load(Ordering::Relaxed));
802            if since_last < self.config.min_mutations {
803                debug!(since_last, "Skipping snapshot cycle (too few mutations)");
804                return Ok(false);
805            }
806        }
807
808        // Wait for every in-flight VM update and its queued projection batch
809        // to finish, then block new updates until both sides have been dumped.
810        // Processing guards move with their mutation batches and are released
811        // by the projector only after cache application, so this exclusive
812        // guard establishes one exact cut without an enqueue race.
813        let consistency_guard = tokio::time::timeout(
814            CONSISTENCY_CUT_TIMEOUT,
815            self.runtime.state.processing_barrier.enter_snapshot(),
816        )
817        .await
818        .context("timed out waiting for a consistent VM/projection snapshot cut")?;
819
820        let dump_started = Instant::now();
821        let (vm_snapshot, resume_watermark) = {
822            let vm = registration
823                .vm
824                .lock()
825                .map_err(|_| anyhow::anyhow!("VM mutex poisoned"))?;
826            let resume_watermark = self.runtime.state.resume_watermark.load(Ordering::Relaxed);
827            let vm_snapshot = vm.dump();
828            (vm_snapshot, resume_watermark)
829        };
830        let vm_lock_held = dump_started.elapsed();
831        let observed_slot = registration.slot_tracker.get();
832        let entity_cache_dump = self.entity_cache.dump().await;
833        // Dumped inside the same consistency guard as the cache, so a restore
834        // can never leave the cache ahead of the tape.
835        let journal_dump = self.journal.dump().await;
836        if trigger == SnapshotTrigger::Shutdown {
837            // Publishing continues after the guard releases — the parser is
838            // aborted only once this snapshot is encoded and stored — so
839            // without this the file would not hold every offset that reached a
840            // subscriber, and the restore below would adopt its epoch anyway.
841            self.journal.seal();
842        }
843        let applied_batches = self.runtime.state.applied_batches.load(Ordering::Relaxed);
844        drop(consistency_guard);
845
846        let created_at_epoch_ms = now_epoch_ms();
847        let header = SnapshotHeader {
848            format_version: SNAPSHOT_FORMAT_VERSION,
849            bytecode_hash: self.bytecode_hash.clone(),
850            state_contract: self.state_contract.clone(),
851            projection_contract: Some(self.projection_contract.clone()),
852            program_ids: self.program_ids.clone(),
853            resume_watermark,
854            observed_slot,
855            created_at_epoch_ms,
856            trigger: Some(trigger),
857            entry_counts: vm_snapshot
858                .entry_counts()
859                .into_iter()
860                .chain(
861                    // Retained record counts are otherwise invisible after the
862                    // restore log line.
863                    // Derived from the dump rather than a second trip
864                    // through the journal's lock inside the cut.
865                    journal_dump.views.iter().map(|(view_id, view)| {
866                        (format!("journal:{view_id}"), view.records.len() as u64)
867                    }),
868                )
869                .collect(),
870        };
871        let payload = SnapshotPayload {
872            vm: vm_snapshot,
873            entity_cache: entity_cache_dump,
874            journal: journal_dump,
875        };
876        let bytes = tokio::task::spawn_blocking(move || envelope::encode(&header, &payload))
877            .await
878            .context("snapshot encode task panicked")??;
879
880        let name = store::snapshot_name(created_at_epoch_ms, resume_watermark);
881        self.store.write(&name, &bytes).await?;
882        if let Err(err) = self.store.prune(self.config.keep).await {
883            warn!(error = format!("{err:#}"), "Failed to prune old snapshots");
884        }
885        self.batches_at_last_snapshot
886            .store(applied_batches, Ordering::Relaxed);
887
888        info!(
889            snapshot = %name,
890            bytes = bytes.len(),
891            resume_watermark,
892            observed_slot,
893            vm_lock_ms = vm_lock_held.as_millis() as u64,
894            trigger = ?trigger,
895            "Snapshot written"
896        );
897        Ok(true)
898    }
899}
900
901/// Mark every entity the restored VM holds but a restored view does not as
902/// evicted from that view, so the VM's next patch for it — only the fields
903/// that changed — is refused rather than stored as the whole entity even if
904/// the VM does not mark creations (see [`EntityCache`]'s "Only whole
905/// entities").
906async fn remember_uncached_vm_keys(
907    view_index: &ViewIndex,
908    vm: &VmSnapshot,
909    entity_cache: &EntityCache,
910) {
911    for table in vm.states.values() {
912        let views = view_index.by_export(&table.entity_name);
913        if views.is_empty() || table.data.is_empty() {
914            continue;
915        }
916        let keys: Vec<String> = table
917            .data
918            .iter()
919            .map(|(key, _)| crate::projector::Projector::extract_key(key))
920            .collect();
921        for view in views {
922            entity_cache
923                .remember_evicted(&view.id, keys.iter().cloned())
924                .await;
925        }
926    }
927}
928
929/// Rebuild each derived `SortedViewCache` from the hydrated `EntityCache`,
930/// mirroring the projector's upsert path. Sorted caches are not persisted:
931/// they are derived state and MB-scale rebuilds are sub-millisecond.
932async fn rebuild_sorted_caches(view_index: &ViewIndex, entity_cache: &EntityCache) {
933    let sorted_caches = view_index.sorted_caches();
934    let max_entries = entity_cache.max_entities_per_view();
935    for spec in view_index.get_derived_views() {
936        let Some(source_view) = spec.source_view.as_ref() else {
937            continue;
938        };
939        let entities = entity_cache.get_all(source_view).await;
940        if entities.is_empty() {
941            continue;
942        }
943        let filter = spec
944            .pipeline
945            .as_ref()
946            .and_then(|pipeline| pipeline.filter.as_ref());
947        let mut caches = sorted_caches.write().await;
948        if let Some(cache) = caches.get_mut(&spec.id) {
949            let count = entities.len();
950            for (key, entity) in entities {
951                if filter.is_none_or(|filter| filter.matches(&entity)) {
952                    cache.upsert(key, entity);
953                }
954            }
955            // Trim once after the batch; the bound matches the projector's.
956            cache.trim_to_max_entries(max_entries);
957            debug!(view_id = %spec.id, count, "Rebuilt sorted cache from snapshot");
958        }
959    }
960}
961
962#[cfg(test)]
963mod tests {
964    use super::*;
965    use crate::cache::CacheWrite;
966    use crate::view::{Delivery, Filters, Projection, ViewSpec};
967    use crate::websocket::frame::Mode;
968    use arete_interpreter::snapshot::StateTableSnapshot;
969    use serde_json::json;
970
971    fn view(id: &str, mode: Mode) -> ViewSpec {
972        ViewSpec {
973            id: id.to_string(),
974            export: "Round".to_string(),
975            mode,
976            wire_format: Default::default(),
977            projection: Projection::all(),
978            filters: Filters::all(),
979            delivery: Delivery::default(),
980            pipeline: None,
981            source_view: None,
982        }
983    }
984
985    /// After a restore the VM holds entities the cache does not; the VM's next
986    /// patch for one of them is a fragment and must not become the entity.
987    #[tokio::test]
988    async fn restored_vm_entities_missing_from_the_cache_are_remembered_as_evicted() {
989        let mut index = ViewIndex::new();
990        index.add_spec(view("Round/list", Mode::List));
991        index.add_spec(view("Round/state", Mode::State));
992        let cache = EntityCache::new();
993        cache
994            .hydrate(vec![(
995                "Round/list".to_string(),
996                vec![("2".to_string(), json!({"id": 2}))],
997            )])
998            .await;
999        let vm = VmSnapshot {
1000            states: HashMap::from([(
1001                0,
1002                StateTableSnapshot {
1003                    entity_name: "Round".to_string(),
1004                    data: vec![(json!(1), json!({"id": 1})), (json!(2), json!({"id": 2}))],
1005                    ..Default::default()
1006                },
1007            )]),
1008            ..Default::default()
1009        };
1010
1011        remember_uncached_vm_keys(&index, &vm, &cache).await;
1012
1013        assert!(matches!(
1014            cache.upsert("Round/list", "1", json!({"n": 1})).await,
1015            CacheWrite::Refused { .. }
1016        ));
1017        assert!(matches!(
1018            cache.upsert("Round/state", "1", json!({"n": 1})).await,
1019            CacheWrite::Refused { .. }
1020        ));
1021        assert_eq!(
1022            cache.upsert("Round/list", "2", json!({"n": 1})).await,
1023            CacheWrite::Merged
1024        );
1025        // A key the VM never held is new.
1026        assert_eq!(
1027            cache.upsert("Round/list", "3", json!({"id": 3})).await,
1028            CacheWrite::Created
1029        );
1030    }
1031}