hearth-store 0.4.2

The NEDB spine of hearth: every residency transition is a bi-temporal, causally-linked, tamper-evident event.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! hearth-store — the NEDB spine.
//!
//! Every residency transition is a bi-temporal, causally-linked,
//! tamper-evident event in an embedded NEDB database. This is not a log
//! bolted onto the side of the supervisor: it IS the supervisor's state.
//!
//! Three properties no other serving stack has, inherited for free:
//!
//!   * `state_as_of(model, seq)` — what was resident *then*, not now.
//!   * `why(model)` — a causal chain from the current state back through
//!     every transition that produced it, not a guess from grep.
//!   * `verify()` — cryptographic proof the history wasn't rewritten.
//!
//! Layout: one versioned document per model in the `residency` collection
//! (id = model name). Each transition is a new version of that document,
//! with `caused_by` linking to the event that produced it — a load links
//! to the pull that fetched the bytes, a loss links to the load it undid.
//! NEDB's version chain gives history; its DAG gives causality; its
//! Merkle head gives tamper-evidence.

use std::path::Path;

use hearth_core::{LostReason, Residency};
use nedb_engine::db::Db;
use nedb_engine::store::Node;
use serde_json::{json, Value};

/// Collection holding one versioned doc per model.
const RESIDENCY: &str = "residency";
/// Collection holding one versioned doc per model for pulls.
const PULLS: &str = "pulls";

/// A recorded event: the node hash (for causal linking) and its seq
/// (for AS OF reads). Everything a caller needs to chain the next event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventRef {
    pub hash: String,
    pub seq: u64,
}

impl EventRef {
    fn of(node: &Node) -> Self {
        EventRef {
            hash: node.hash.clone(),
            seq: node.seq,
        }
    }
}

/// What kind of transition is being recorded.
///
/// These mirror `hearth_core::Residency` but carry the extra facts the
/// state machine doesn't hold (endpoint, pid, timing) — the store is the
/// system of record, the state machine is the decision procedure.
#[derive(Debug, Clone, PartialEq)]
pub enum Transition {
    /// Model declared into the fleet. `admitted: false` means the budget
    /// refused it — recorded anyway, because a refusal is a fact too.
    Declared { vram_bytes: u64, admitted: bool },
    /// Bytes are being fetched. Source is the resolved origin
    /// ("ollama:library/llama3:latest", "hf:owner/repo@Q4_K_M", "file:...").
    PullStarted { source: String },
    /// Bytes landed and digest-verified.
    PullCompleted { path: String, size_bytes: u64 },
    /// A runtime child was spawned and is warming.
    Loading { pid: u32, endpoint: String },
    /// The runtime answered its health probe.
    Resident { endpoint: String, warmup_ms: u64 },
    /// The model stopped being resident, with the named reason.
    Lost { reason: LostReason },
    /// Deliberate operator stop. Not a loss — an instruction.
    Unloaded,
}

impl Transition {
    fn kind(&self) -> &'static str {
        match self {
            Transition::Declared { .. } => "declared",
            Transition::PullStarted { .. } => "pull_started",
            Transition::PullCompleted { .. } => "pull_completed",
            Transition::Loading { .. } => "loading",
            Transition::Resident { .. } => "resident",
            Transition::Lost { .. } => "lost",
            Transition::Unloaded => "unloaded",
        }
    }

    fn facts(&self) -> Value {
        match self {
            Transition::Declared {
                vram_bytes,
                admitted,
            } => json!({ "vram_bytes": vram_bytes, "admitted": admitted }),
            Transition::PullStarted { source } => json!({ "source": source }),
            Transition::PullCompleted { path, size_bytes } => {
                json!({ "path": path, "size_bytes": size_bytes })
            }
            Transition::Loading { pid, endpoint } => {
                json!({ "pid": pid, "endpoint": endpoint })
            }
            Transition::Resident {
                endpoint,
                warmup_ms,
            } => json!({ "endpoint": endpoint, "warmup_ms": warmup_ms }),
            Transition::Lost { reason } => json!({ "reason": lost_reason_str(*reason) }),
            Transition::Unloaded => json!({}),
        }
    }
}

fn lost_reason_str(reason: LostReason) -> &'static str {
    match reason {
        LostReason::Evicted => "evicted",
        LostReason::GpuDetached => "gpu_detached",
        LostReason::ProcessExited => "process_exited",
        LostReason::Unhealthy => "unhealthy",
    }
}

/// One event read back out of the spine.
#[derive(Debug, Clone)]
pub struct Event {
    pub model: String,
    pub kind: String,
    pub facts: Value,
    pub seq: u64,
    pub hash: String,
    pub ts: f64,
}

impl Event {
    fn of(node: &Node) -> Option<Event> {
        let obj = node.data.as_object()?;
        Some(Event {
            model: node.id.clone(),
            kind: obj.get("kind")?.as_str()?.to_string(),
            facts: obj.get("facts").cloned().unwrap_or(Value::Null),
            seq: node.seq,
            hash: node.hash.clone(),
            ts: node.ts,
        })
    }
}

/// The spine itself: an embedded NEDB database.
pub struct Spine {
    db: Db,
}

impl Spine {
    /// Open (or create) an on-disk spine.
    pub fn open(root: &Path) -> Result<Spine, String> {
        let db = Db::open(root, None).map_err(|e| e.to_string())?;
        Ok(Spine { db })
    }

    /// Pure in-memory spine — tests and ephemeral runs. Nothing survives drop.
    pub fn in_memory() -> Spine {
        Spine {
            db: Db::in_memory(),
        }
    }

    /// Record a transition for `model`, causally linked to the events that
    /// produced it. Returns the ref future events should cite as cause.
    pub fn record(
        &self,
        model: &str,
        transition: &Transition,
        caused_by: &[EventRef],
    ) -> Result<EventRef, String> {
        let coll = match transition {
            Transition::PullStarted { .. } | Transition::PullCompleted { .. } => PULLS,
            _ => RESIDENCY,
        };
        let doc = json!({
            "kind": transition.kind(),
            "facts": transition.facts(),
        });
        let causes: Vec<String> = caused_by.iter().map(|r| r.hash.clone()).collect();
        let node = self
            .db
            .put(coll, model, doc, causes, None, None)
            .map_err(|e| e.to_string())?;
        // Transitions are rare and each one is a fact someone may need after
        // a crash — durability at event granularity, not process-exit
        // granularity. A supervisor that loses its history on SIGKILL has a
        // spine made of RAM. (Found live: the first e2e run lost everything.)
        self.flush();
        Ok(EventRef::of(&node))
    }

    /// The model's current state — the latest residency event.
    pub fn latest(&self, model: &str) -> Option<Event> {
        self.db.get(RESIDENCY, model).as_ref().and_then(Event::of)
    }

    /// The latest pull event for `model`, if it was ever fetched.
    ///
    /// Separate from `latest` on purpose: a pull is not a residency state, and
    /// letting one answer "is this model warm" would conflate having the bytes
    /// with having them loaded. But the events were previously written to their
    /// own collection and read by nothing, so `hearth why` reported "no history
    /// in the spine" for a model it had just downloaded and verified — a false
    /// statement, which is worse than an empty one.
    pub fn latest_pull(&self, model: &str) -> Option<Event> {
        self.db.get(PULLS, model).as_ref().and_then(Event::of)
    }

    /// Where the bytes came from, newest first: the pull chain.
    ///
    /// `PullCompleted` cites `PullStarted` as its cause, so this walks the same
    /// causal links `why` does — "where did this file come from" is a query
    /// against a verifiable chain rather than an archaeology project.
    pub fn provenance(&self, model: &str) -> Vec<Event> {
        let Some(latest) = self.latest_pull(model) else {
            return Vec::new();
        };
        self.db
            .trace(&latest.hash, false, 64)
            .iter()
            .filter_map(Event::of)
            .collect()
    }

    /// What the model's state was at sequence `seq`. Time travel.
    pub fn state_as_of(&self, model: &str, seq: u64) -> Option<Event> {
        self.db
            .get_as_of(RESIDENCY, model, seq)
            .as_ref()
            .and_then(Event::of)
    }

    /// The causal chain that produced the model's current state, newest
    /// first: the answer to "why is this model (not) resident?"
    pub fn why(&self, model: &str) -> Vec<Event> {
        let Some(latest) = self.latest(model) else {
            return Vec::new();
        };
        self.db
            .trace(&latest.hash, false, 64)
            .iter()
            .filter_map(Event::of)
            .collect()
    }

    /// Reconstruct `Residency` from the latest event, for handing back to
    /// the `hearth_core` state machine after a restart.
    pub fn residency(&self, model: &str, now_ms: u64) -> Option<Residency> {
        let ev = self.latest(model)?;
        let vram = ev
            .facts
            .get("vram_bytes")
            .and_then(Value::as_u64)
            .unwrap_or(0);
        match ev.kind.as_str() {
            "resident" => Some(Residency::Resident {
                since: now_ms,
                vram_bytes: vram,
            }),
            "loading" => Some(Residency::Loading { since: now_ms }),
            "lost" => {
                let reason = match ev.facts.get("reason").and_then(Value::as_str) {
                    Some("gpu_detached") => LostReason::GpuDetached,
                    Some("process_exited") => LostReason::ProcessExited,
                    Some("unhealthy") => LostReason::Unhealthy,
                    _ => LostReason::Evicted,
                };
                Some(Residency::Lost { at: now_ms, reason })
            }
            "unloaded" => Some(Residency::Stopped { at: now_ms }),
            _ => None,
        }
    }

    /// Latest residency event for every model the spine has ever seen.
    pub fn all_latest(&self) -> Vec<Event> {
        self.db
            .list(RESIDENCY)
            .iter()
            .filter_map(Event::of)
            .collect()
    }

    /// Current global sequence — the clock `state_as_of` reads against.
    pub fn seq(&self) -> u64 {
        self.db.seq.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Merkle head of the whole history.
    pub fn head(&self) -> String {
        self.db.head()
    }

    /// Verify every node against its hash. `(checked, failures)`.
    pub fn verify(&self) -> (usize, Vec<String>) {
        self.db.verify()
    }

    /// Flush everything to disk (no-op in memory).
    pub fn flush(&self) {
        self.db.flush_all();
        self.db.flush_manifest_if_dirty();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn spine() -> Spine {
        Spine::in_memory()
    }

    #[test]
    fn declared_is_recorded_and_latest() {
        let s = spine();
        s.record(
            "muse",
            &Transition::Declared {
                vram_bytes: 4_000_000_000,
                admitted: true,
            },
            &[],
        )
        .unwrap();
        let ev = s.latest("muse").unwrap();
        assert_eq!(ev.kind, "declared");
        assert_eq!(ev.facts["admitted"], json!(true));
    }

    #[test]
    fn refusal_is_a_fact_too() {
        let s = spine();
        s.record(
            "too-big",
            &Transition::Declared {
                vram_bytes: u64::MAX,
                admitted: false,
            },
            &[],
        )
        .unwrap();
        assert_eq!(s.latest("too-big").unwrap().facts["admitted"], json!(false));
    }

    #[test]
    fn full_lifecycle_chains_causally() {
        let s = spine();
        let declared = s
            .record(
                "muse",
                &Transition::Declared {
                    vram_bytes: 4_000_000_000,
                    admitted: true,
                },
                &[],
            )
            .unwrap();
        let pull = s
            .record(
                "muse",
                &Transition::PullStarted {
                    source: "ollama:library/muse:latest".into(),
                },
                std::slice::from_ref(&declared),
            )
            .unwrap();
        let pulled = s
            .record(
                "muse",
                &Transition::PullCompleted {
                    path: "/blobs/sha256-abc".into(),
                    size_bytes: 4_000_000_000,
                },
                &[pull],
            )
            .unwrap();
        let loading = s
            .record(
                "muse",
                &Transition::Loading {
                    pid: 4242,
                    endpoint: "127.0.0.1:8080".into(),
                },
                &[pulled],
            )
            .unwrap();
        let resident = s
            .record(
                "muse",
                &Transition::Resident {
                    endpoint: "127.0.0.1:8080".into(),
                    warmup_ms: 43_000,
                },
                &[loading],
            )
            .unwrap();

        // why() walks the causal chain back through the whole story.
        let why = s.why("muse");
        let kinds: Vec<&str> = why.iter().map(|e| e.kind.as_str()).collect();
        assert_eq!(
            kinds,
            vec![
                "resident",
                "loading",
                "pull_completed",
                "pull_started",
                "declared"
            ]
        );
        assert_eq!(why[0].hash, resident.hash);
    }

    #[test]
    fn as_of_separates_then_from_now() {
        let s = spine();
        let loading = s
            .record(
                "muse",
                &Transition::Loading {
                    pid: 1,
                    endpoint: "127.0.0.1:8080".into(),
                },
                &[],
            )
            .unwrap();
        let resident = s
            .record(
                "muse",
                &Transition::Resident {
                    endpoint: "127.0.0.1:8080".into(),
                    warmup_ms: 100,
                },
                &[loading],
            )
            .unwrap();
        s.record(
            "muse",
            &Transition::Lost {
                reason: LostReason::GpuDetached,
            },
            std::slice::from_ref(&resident),
        )
        .unwrap();

        // Now: lost. Then (at the resident event's seq): resident.
        assert_eq!(s.latest("muse").unwrap().kind, "lost");
        let then = s.state_as_of("muse", resident.seq).unwrap();
        assert_eq!(then.kind, "resident");
    }

    #[test]
    fn residency_reconstructs_for_the_state_machine() {
        let s = spine();
        let r = s
            .record(
                "muse",
                &Transition::Resident {
                    endpoint: "e".into(),
                    warmup_ms: 5,
                },
                &[],
            )
            .unwrap();
        assert!(matches!(
            s.residency("muse", 0),
            Some(Residency::Resident { .. })
        ));
        s.record(
            "muse",
            &Transition::Lost {
                reason: LostReason::Evicted,
            },
            &[r],
        )
        .unwrap();
        assert!(matches!(
            s.residency("muse", 0),
            Some(Residency::Lost {
                reason: LostReason::Evicted,
                ..
            })
        ));
    }

    #[test]
    fn lost_reason_survives_the_round_trip() {
        let s = spine();
        s.record(
            "muse",
            &Transition::Lost {
                reason: LostReason::GpuDetached,
            },
            &[],
        )
        .unwrap();
        assert!(matches!(
            s.residency("muse", 0),
            Some(Residency::Lost {
                reason: LostReason::GpuDetached,
                ..
            })
        ));
    }

    #[test]
    fn verify_is_clean_over_a_real_history() {
        let s = spine();
        for i in 0..5 {
            s.record(
                "muse",
                &Transition::Resident {
                    endpoint: format!("e{i}"),
                    warmup_ms: i,
                },
                &[],
            )
            .unwrap();
        }
        let (checked, failures) = s.verify();
        assert!(checked >= 5);
        assert!(failures.is_empty(), "verify failures: {failures:?}");
    }

    #[test]
    fn on_disk_history_survives_reopen() {
        let dir = tempfile::tempdir().unwrap();
        let resident_seq;
        {
            let s = Spine::open(dir.path()).unwrap();
            let l = s
                .record(
                    "muse",
                    &Transition::Loading {
                        pid: 7,
                        endpoint: "127.0.0.1:9".into(),
                    },
                    &[],
                )
                .unwrap();
            let r = s
                .record(
                    "muse",
                    &Transition::Resident {
                        endpoint: "127.0.0.1:9".into(),
                        warmup_ms: 12,
                    },
                    &[l],
                )
                .unwrap();
            resident_seq = r.seq;
            s.record(
                "muse",
                &Transition::Lost {
                    reason: LostReason::Evicted,
                },
                &[r],
            )
            .unwrap();
            s.flush();
        }
        // Fresh process, same disk: history intact, AS OF still answers.
        let s = Spine::open(dir.path()).unwrap();
        assert_eq!(s.latest("muse").unwrap().kind, "lost");
        assert_eq!(
            s.state_as_of("muse", resident_seq).unwrap().kind,
            "resident"
        );
        let (checked, failures) = s.verify();
        assert!(checked >= 3);
        assert!(failures.is_empty());
    }
    // -- pull provenance ---------------------------------------------------
    //
    // Pull events are written to their own collection, and for one commit they
    // were read by nothing — so `hearth why` reported "no history in the spine"
    // about a model it had just downloaded and digest-verified. Recorded but
    // unreachable is not recorded.

    #[test]
    fn a_pull_is_reachable_after_it_is_recorded() {
        let s = Spine::in_memory();
        let started = s
            .record(
                "tinyllama:latest",
                &Transition::PullStarted {
                    source: "ollama:library/tinyllama:latest".into(),
                },
                &[],
            )
            .unwrap();
        s.record(
            "tinyllama:latest",
            &Transition::PullCompleted {
                path: "/b/sha256-2af3".into(),
                size_bytes: 637_699_456,
            },
            &[started],
        )
        .unwrap();

        let chain = s.provenance("tinyllama:latest");
        assert_eq!(chain.len(), 2, "completed <- started: {chain:?}");
        assert_eq!(chain[0].kind, "pull_completed");
        assert_eq!(chain[1].kind, "pull_started");
        assert_eq!(
            chain[1].facts["source"],
            serde_json::json!("ollama:library/tinyllama:latest"),
            "the origin is the entire point of recording it"
        );
        assert_eq!(
            chain[0].facts["size_bytes"],
            serde_json::json!(637_699_456u64)
        );
    }

    #[test]
    fn a_pull_is_not_a_residency_state() {
        // Having the bytes is not having them loaded. If a pull answered
        // `latest`, a downloaded-but-never-served model would read as resident.
        let s = Spine::in_memory();
        s.record(
            "m",
            &Transition::PullCompleted {
                path: "/b/x".into(),
                size_bytes: 1,
            },
            &[],
        )
        .unwrap();
        assert!(s.latest("m").is_none(), "not a residency event");
        assert!(s.why("m").is_empty());
        assert!(s.latest_pull("m").is_some(), "but it IS a pull event");
    }

    #[test]
    fn provenance_of_something_never_pulled_is_empty_not_a_panic() {
        let s = Spine::in_memory();
        assert!(s.provenance("never-heard-of-it").is_empty());
    }
}