Skip to main content

macrame/temporal/
replay.rs

1use serde::{Deserialize, Serialize};
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
4
5use crate::error::{DbError, Result};
6use crate::temporal::as_of::NodeAttributes;
7
8/// Full materialized state reconstructed from transaction_log replay (§5.5).
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct MaterializedState {
11    pub seq_anchor: i64,
12    pub timestamp: String,
13    pub concepts: HashMap<String, NodeAttributes>,
14    pub edges: Vec<(String, String, String, String, String)>,
15    /// **Nothing had been recorded yet at `timestamp`** (0.8.0, B5, D-121).
16    ///
17    /// An empty state has two meanings and a caller can act differently on
18    /// them. *Everything was retired by then* is a fact about the data;
19    /// *the ledger had not started* is a fact about the question. Both come
20    /// back as zero concepts and zero edges, so the difference has to be
21    /// carried rather than inferred.
22    ///
23    /// Set only when the log was verified **intact** — see
24    /// `hot_log_reach`. If rows had been archived away, `ts` below the hot
25    /// floor is not "before history", it is "the history is in the other file",
26    /// and that path raises instead of answering.
27    ///
28    /// `#[serde(default)]` so the field is additive: a snapshot written without
29    /// it deserialises with `false`, which is the right answer for any state
30    /// that had rows to fold. Old snapshots cannot actually reach this code —
31    /// the container carries `SCHEMA_VERSION` and v8 refused every v7 file
32    /// (D-043) — but the tolerance costs nothing and the next field to arrive
33    /// may not land in a release that bumps the schema.
34    #[serde(default)]
35    pub predates_recorded_history: bool,
36}
37
38impl MaterializedState {
39    /// The state before any log row has been applied.
40    fn empty(ts: &str) -> Self {
41        Self {
42            seq_anchor: 0,
43            timestamp: ts.to_string(),
44            concepts: HashMap::new(),
45            edges: Vec::new(),
46            predates_recorded_history: false,
47        }
48    }
49}
50
51/// The newest log payload shape this build writes and the highest it can read.
52///
53/// Kept beside the folds because they are the only readers, and bumped in step
54/// with the `json_object('v', …)` literals in `schema::ddl` — a test asserts the
55/// two agree, since nothing else would notice them drifting apart.
56pub(crate) const PAYLOAD_VERSION: u8 = 2;
57
58/// Every fold partitions on `(table_name, entity_id)`, never `entity_id` alone.
59///
60/// The two namespaces are not disjoint and nothing makes them so. A link's
61/// `entity_id` is the synthetic `source|target|type|valid_from`; a concept's is
62/// whatever the caller passed, unvalidated (defect AD). Partitioning on the id
63/// alone therefore lets a concept and a link contend for one window, and
64/// `ROW_NUMBER() = 1` hands the whole partition to whichever has the greater
65/// `seq_id` — so the loser vanishes from the reconstruction while sitting
66/// plainly in both `concepts` and `transaction_log`. Silent, and on the read
67/// path the ledger exists to make trustworthy.
68///
69/// Validating identifiers would make the collision unreachable and is the
70/// durable fix; this makes it harmless regardless, which is the property worth
71/// having at the fold. `table_name` leads the partition because the log is
72/// already indexed on `entity_id` and the discriminator is two values wide.
73const HOT_FOLD: &str = r#"
74    SELECT seq_id, table_name, entity_id, operation, payload
75    FROM (
76        SELECT seq_id, table_name, entity_id, operation, payload,
77               ROW_NUMBER() OVER (PARTITION BY table_name, entity_id ORDER BY seq_id DESC) as rn
78        FROM transaction_log
79        WHERE recorded_at <= ?1
80    ) WHERE rn = 1
81"#;
82
83/// Fold over hot and cold together (§5.5, D-026). Requires `cold` to be ATTACHed.
84///
85/// The hot entry wins for entities present in both files because its `seq_id` is
86/// greater — the same last-writer-wins rule as snapshot composition.
87const COLD_FOLD: &str = r#"
88    SELECT seq_id, table_name, entity_id, operation, payload
89    FROM (
90        SELECT seq_id, table_name, entity_id, operation, payload,
91               ROW_NUMBER() OVER (PARTITION BY table_name, entity_id ORDER BY seq_id DESC) as rn
92        FROM (
93            SELECT seq_id, table_name, entity_id, operation, payload, recorded_at FROM main.transaction_log
94            UNION ALL
95            SELECT seq_id, table_name, entity_id, operation, payload, recorded_at FROM cold.transaction_log
96        ) WHERE recorded_at <= ?1
97    ) WHERE rn = 1
98"#;
99
100/// Fold over the hot log *above a snapshot anchor* (§5.5, D-049).
101///
102/// `seq_id > ?2` is an inequality, and deliberately so: `AUTOINCREMENT` leaves
103/// gaps whenever a transaction rolls back, so successor arithmetic
104/// (`seq_id = :anchor + 1`) would stop at the first gap and silently truncate
105/// the delta. This is the first anchored fold in the crate, which makes it the
106/// first code D-024's rule has ever bound — before this the rule was vacuous,
107/// not satisfied.
108const ANCHORED_HOT_FOLD: &str = r#"
109    SELECT seq_id, table_name, entity_id, operation, payload
110    FROM (
111        SELECT seq_id, table_name, entity_id, operation, payload,
112               ROW_NUMBER() OVER (PARTITION BY table_name, entity_id ORDER BY seq_id DESC) as rn
113        FROM transaction_log
114        WHERE recorded_at <= ?1 AND seq_id > ?2
115    ) WHERE rn = 1
116"#;
117
118/// Fold over hot **and cold** above a snapshot anchor (§5.5, 0.5.5).
119///
120/// The union is what lets composition survive an archive. Rows keep their
121/// `seq_id` when they move to cold — the cold schema declares a plain `INTEGER
122/// PRIMARY KEY` precisely so history is not renumbered — so `seq_id > ?2`
123/// partitions the two files consistently and last-writer-wins across them by the
124/// same rule the unanchored folds use.
125const ANCHORED_COLD_FOLD: &str = r#"
126    SELECT seq_id, table_name, entity_id, operation, payload
127    FROM (
128        SELECT seq_id, table_name, entity_id, operation, payload,
129               ROW_NUMBER() OVER (PARTITION BY table_name, entity_id ORDER BY seq_id DESC) as rn
130        FROM (
131            SELECT seq_id, table_name, entity_id, operation, payload, recorded_at FROM main.transaction_log
132            UNION ALL
133            SELECT seq_id, table_name, entity_id, operation, payload, recorded_at FROM cold.transaction_log
134        ) WHERE recorded_at <= ?1 AND seq_id > ?2
135    ) WHERE rn = 1
136"#;
137
138/// The winning log rows for one fold, before they are applied to a base state.
139///
140/// Absence and disappearance are different facts, and a merge is where the
141/// difference starts to matter. A full fold from nothing can treat "this entity
142/// went away" and "there is no row for it" identically — both end as absence.
143/// Composed onto a snapshot they are opposites: a disappearance must *remove*
144/// the entity the snapshot carries, and skipping it leaves the snapshot's stale
145/// row standing as though nothing had happened. So they are collected rather
146/// than dropped, and the full fold applies them to an empty base, which keeps
147/// one code path for both cases (D-049).
148///
149/// **There is one such set, not two (D-072).** It used to carry `edges_gone`
150/// beside `concepts_gone`, and both were populated only from the `'D'` branch of
151/// [`fold_delta`] — so when that branch became an error, `edges_gone` was left
152/// reachable by nothing. Closing one unreachable path by opening another is not
153/// a fix, so it went too.
154///
155/// The asymmetry is real and worth stating, because "concepts can vanish and
156/// edges cannot" looks like an oversight until you follow it:
157///
158/// * A **concept** disappears by being *retired*, which writes a `'U'` row whose
159///   payload has `retired = 1`. That is a genuine removal from a composed state
160///   and `concepts_gone` carries it.
161/// * An **edge** never disappears. It is retired by asserting a successor over
162///   the same interval key — same `source|target|type|valid_from`, later
163///   `recorded_at` — so the log row is an `'I'` under the *same* `entity_id`, and
164///   last-writer-wins in [`Self::apply_to`] replaces the tuple in place. There is
165///   nothing to remove because nothing left; the interval simply closed.
166///
167/// That is Doctrine III showing through: an edge assertion is immutable and
168/// superseded, never deleted.
169#[derive(Default)]
170struct Delta {
171    concepts: HashMap<String, NodeAttributes>,
172    /// Keyed by `transaction_log.entity_id`: `source|target|type|valid_from`.
173    edges: HashMap<String, (String, String, String, String, String)>,
174    /// Concepts retired as of the fold's instant. See the type's note for why
175    /// there is no edge equivalent.
176    concepts_gone: HashSet<String>,
177    max_seq: i64,
178}
179
180/// The log's `entity_id` for a link, rebuilt from a materialised edge tuple.
181///
182/// Must match `trg_links_log_i`'s
183/// `source_id || '|' || target_id || '|' || edge_type || '|' || valid_from`
184/// exactly, or a delta row will fail to replace the snapshot row it supersedes.
185/// Safe because ULIDs are Crockford base32 and edge types are `[A-Z0-9]+`, so
186/// `|` cannot occur inside a component (§4.3).
187fn edge_key(e: &(String, String, String, String, String)) -> String {
188    format!("{}|{}|{}|{}", e.0, e.1, e.2, e.3)
189}
190
191/// Release a `cold` handle left attached by an earlier call (§5.5, D-044).
192///
193/// Both ATTACH sites pair with an unconditional DETACH on the way out, so in
194/// the normal course this finds nothing and the statement fails harmlessly with
195/// "no such database: cold". It exists for the case the pairing cannot cover: a
196/// panic unwinding between the two, which skips the DETACH no matter which exit
197/// path the `Result` would have taken.
198///
199/// A `Drop` guard is the reflex here and does not work — `execute` is `async`,
200/// and a `Drop` impl cannot await, so it would build a future, discard it, and
201/// leave the handle attached while looking like it had cleaned up. Recovering
202/// on the way *in* needs no destructor, works regardless of how the handle
203/// leaked, and turns permanent poisoning of the connection into one failed
204/// statement nobody sees.
205pub(crate) async fn detach_stale_cold(conn: &libsql::Connection) {
206    let _ = conn.execute("DETACH DATABASE cold", ()).await;
207}
208
209/// Reconstruct database state as believed at past instant `ts` using window-function log fold (§5.5, D-026).
210///
211/// When `ts` predates the hot log's horizon the cold database is ATTACHed for
212/// exactly one fold and DETACHed unconditionally on the way out, error paths
213/// included. ATTACH is not transactional and survives ROLLBACK, so a handle
214/// leaked by an early return would make every later `reconstruct` *and* every
215/// later `archive` fail with "database cold is already in use" — one corrupt
216/// payload would permanently poison the connection. This is the same failure
217/// mode `archive()` carries a note about, and the two now share a shape.
218/// Snapshot composition (§5.5, D-049) applies when `snapshots_dir` holds a
219/// snapshot at or before `ts` and no archive database exists — see
220/// `snapshot_anchor` for why archiving disables it. Otherwise the fold runs
221/// from genesis, which is correct and costs what the whole log costs.
222pub async fn reconstruct(
223    conn: &libsql::Connection,
224    ts: &str,
225    archive_path: Option<&Path>,
226    snapshots_dir: Option<&Path>,
227) -> Result<MaterializedState> {
228    match hot_log_reach(conn, ts, archive_path).await? {
229        HotLogReach::Covers => {
230            if let Some(base) = snapshot_anchor(snapshots_dir, ts) {
231                let anchor = base.seq_anchor;
232                let delta = fold_delta(conn, ANCHORED_HOT_FOLD, libsql::params![ts, anchor]).await?;
233                return Ok(delta.apply_to(base, ts));
234            }
235            return fold(conn, ts, HOT_FOLD).await;
236        }
237        HotLogReach::PredatesRecordedHistory => {
238            // Nothing had been recorded by `ts`, and nothing has been removed
239            // from the log, so there is no history anywhere to go looking for.
240            // The empty state is the answer, flagged so a caller can tell it
241            // from a state that is empty because everything was retired.
242            let mut state = MaterializedState::empty(ts);
243            state.predates_recorded_history = true;
244            return Ok(state);
245        }
246        HotLogReach::NeedsArchive => {}
247    }
248
249    // The delta lives in the cold archive database. Both ways of failing to
250    // reach it carry `archive_hint`, which is the message the rejected hot-side
251    // marker was wanted for — see that function for why no marker is needed.
252    //
253    // **Computed inside the error arms, not before them.** `NeedsArchive` is the
254    // ordinary path to a cold fold and usually succeeds; an eager hint would put
255    // an extra query on it for a string almost every caller discards. An
256    // injection probe caught this — `a_failed_cold_reconstruct_still_detaches`
257    // reached the hint on a run that raised nothing from here.
258    let archive = match archive_path {
259        Some(p) => p,
260        None => {
261            return Err(DbError::ReplayCorrupt {
262                seq: 0,
263                reason: format!(
264                    "state at {ts} predates the hot log and no archive path was given; {}",
265                    archive_hint(conn).await
266                ),
267            })
268        }
269    };
270    if !archive.exists() {
271        return Err(DbError::ReplayCorrupt {
272            seq: 0,
273            reason: format!(
274                "archive database file {archive:?} does not exist; {}",
275                archive_hint(conn).await
276            ),
277        });
278    }
279
280    detach_stale_cold(conn).await;
281
282    // Bound, not interpolated: a path is caller data, and hand-rolled quote
283    // doubling is a worse version of what the driver already does correctly.
284    conn.execute(
285        "ATTACH DATABASE ?1 AS cold",
286        libsql::params![archive.to_string_lossy().as_ref()],
287    )
288    .await?;
289
290    // Composition works across the archive boundary because the anchored fold
291    // unions both files; before 0.5.5 it was refused here rather than made to
292    // work, and the refusal was the only thing keeping the answer right.
293    let result = match snapshot_anchor(snapshots_dir, ts) {
294        Some(base) => {
295            let anchor = base.seq_anchor;
296            fold_delta(conn, ANCHORED_COLD_FOLD, libsql::params![ts, anchor])
297                .await
298                .map(|delta| delta.apply_to(base, ts))
299        }
300        None => fold(conn, ts, COLD_FOLD).await,
301    };
302
303    // Unconditional: see the ATTACH note above.
304    if let Err(e) = conn.execute("DETACH DATABASE cold", ()).await {
305        tracing::warn!("reconstruct: failed to DETACH cold database: {e}");
306    }
307
308    result
309}
310
311/// Fold from genesis and compare against the composed answer (§5.5, T5.3,
312/// D-092).
313///
314/// # The problem this exists for
315///
316/// [`crate::temporal::save_snapshot`] is written by `write_final`, which calls
317/// [`reconstruct`] — and `reconstruct` composes onto the *previous* snapshot
318/// whenever one is usable. So snapshot *n* is derived from snapshot *n−1*, and
319/// there is no periodic full fold anywhere in the chain. An error introduced at
320/// any link is copied forward indefinitely, and every subsequent read agrees
321/// with it, because they are all reading the same descendant.
322///
323/// The project's own open item names the difficulty honestly: a full fold is
324/// exactly the cost snapshots exist to avoid, so this cannot run on every read.
325/// It is a **scheduling** problem, and this function is the thing to schedule.
326///
327/// # It reports; it does not repair
328///
329/// Deliberate, and not merely conservative. Under [Doctrine VI] a snapshot is
330/// derivative and disposable, so the repair is *delete the snapshots* — one
331/// line, available to the caller, and correct without this function's help.
332/// What the caller cannot get for themselves is the knowledge that the chain
333/// diverged, and silently rewriting the file would destroy the only evidence of
334/// a bug in composition. A divergence here is not a corrupt database; it is a
335/// wrong **cache**, and it means composition has a defect worth finding.
336///
337/// # Cost
338///
339/// One fold from genesis over the whole log, plus one composed reconstruction.
340/// That is the expensive path by construction — see [`crate::Database::
341/// verify_snapshot_chain`] for the handle-level entry point and the note on
342/// when to run it.
343///
344/// [Doctrine VI]: ../../../docs/architecture/s0-s3-foundations.md#doctrine-vi
345pub async fn verify_snapshot_chain(
346    conn: &libsql::Connection,
347    ts: &str,
348    archive_path: Option<&Path>,
349    snapshots_dir: &Path,
350) -> Result<ChainCheck> {
351    // The composed answer: what every reader gets today.
352    let composed = reconstruct(conn, ts, archive_path, Some(snapshots_dir)).await?;
353    // The authority: the same instant, with the snapshot directory withheld, so
354    // `snapshot_anchor` finds nothing and the fold runs from genesis. Passing
355    // `None` is what makes this an independent computation rather than a second
356    // call to the thing under test.
357    let folded = reconstruct(conn, ts, archive_path, None).await?;
358    Ok(ChainCheck::compare(ts, &composed, &folded))
359}
360
361/// The result of a [`verify_snapshot_chain`] cross-check.
362///
363/// Carries the disagreements rather than a bool, because "the chain diverged" is
364/// not actionable and "these three concepts differ, and this edge is present in
365/// one and not the other" is. Bounded — see [`ChainCheck::SAMPLE_LIMIT`] — since
366/// a chain that went wrong early can disagree about every row, and a report that
367/// is the size of the database is one nobody reads.
368#[derive(Debug, Clone)]
369pub struct ChainCheck {
370    pub timestamp: String,
371    /// `seq_anchor` of the composed answer and of the genesis fold. These
372    /// **may legitimately differ**: the composed answer anchors at the snapshot
373    /// it started from plus its delta, and the fold anchors at the newest row it
374    /// saw. Reported for diagnosis, never compared.
375    pub composed_anchor: i64,
376    pub folded_anchor: i64,
377    pub composed_concepts: usize,
378    pub folded_concepts: usize,
379    pub composed_edges: usize,
380    pub folded_edges: usize,
381    /// Concept ids present in one and not the other, or whose attributes differ.
382    pub concept_disagreements: Vec<String>,
383    /// Edge keys present in one and not the other.
384    pub edge_disagreements: Vec<String>,
385    /// True when either list was truncated at [`ChainCheck::SAMPLE_LIMIT`].
386    pub truncated: bool,
387}
388
389impl ChainCheck {
390    /// How many disagreements of each kind to carry.
391    pub const SAMPLE_LIMIT: usize = 32;
392
393    pub fn diverged(&self) -> bool {
394        !self.concept_disagreements.is_empty() || !self.edge_disagreements.is_empty()
395    }
396
397    fn compare(ts: &str, composed: &MaterializedState, folded: &MaterializedState) -> Self {
398        let mut concept_disagreements = Vec::new();
399        let mut truncated = false;
400
401        let mut ids: Vec<&String> = composed.concepts.keys().collect();
402        ids.extend(folded.concepts.keys());
403        ids.sort_unstable();
404        ids.dedup();
405        for id in ids {
406            let a = composed.concepts.get(id);
407            let b = folded.concepts.get(id);
408            let same = match (a, b) {
409                (Some(a), Some(b)) => {
410                    a.title == b.title
411                        && a.content == b.content
412                        && a.embedding_model == b.embedding_model
413                }
414                (None, None) => true,
415                _ => false,
416            };
417            if !same {
418                if concept_disagreements.len() < Self::SAMPLE_LIMIT {
419                    concept_disagreements.push(id.clone());
420                } else {
421                    truncated = true;
422                }
423            }
424        }
425
426        // Edges are a `Vec` of tuples with no declared order, so the comparison
427        // is on the set. Comparing the vectors directly would report a
428        // divergence for a reordering, which is not one — and that false
429        // positive is worse than useless here, because the whole point of this
430        // check is that a report means "go and find the bug".
431        let key = |e: &(String, String, String, String, String)| {
432            format!("{}|{}|{}|{}|{}", e.0, e.1, e.2, e.3, e.4)
433        };
434        let ca: HashSet<String> = composed.edges.iter().map(key).collect();
435        let fa: HashSet<String> = folded.edges.iter().map(key).collect();
436        let mut edge_disagreements: Vec<String> = ca.symmetric_difference(&fa).cloned().collect();
437        edge_disagreements.sort_unstable();
438        if edge_disagreements.len() > Self::SAMPLE_LIMIT {
439            edge_disagreements.truncate(Self::SAMPLE_LIMIT);
440            truncated = true;
441        }
442
443        Self {
444            timestamp: ts.to_string(),
445            composed_anchor: composed.seq_anchor,
446            folded_anchor: folded.seq_anchor,
447            composed_concepts: composed.concepts.len(),
448            folded_concepts: folded.concepts.len(),
449            composed_edges: ca.len(),
450            folded_edges: fa.len(),
451            concept_disagreements,
452            edge_disagreements,
453            truncated,
454        }
455    }
456}
457
458impl std::fmt::Display for ChainCheck {
459    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
460        if !self.diverged() {
461            return write!(
462                f,
463                "snapshot chain agrees with a genesis fold at {}: {} concepts, {} edges",
464                self.timestamp, self.folded_concepts, self.folded_edges
465            );
466        }
467        write!(
468            f,
469            "snapshot chain DIVERGED at {}: composed {} concepts / {} edges, \
470             genesis fold {} concepts / {} edges; {} concept and {} edge \
471             disagreements{}. The snapshots are a wrong cache, not a corrupt \
472             ledger — deleting the snapshot directory restores correctness and \
473             loses only speed (Doctrine VI). concepts: {:?} edges: {:?}",
474            self.timestamp,
475            self.composed_concepts,
476            self.composed_edges,
477            self.folded_concepts,
478            self.folded_edges,
479            self.concept_disagreements.len(),
480            self.edge_disagreements.len(),
481            if self.truncated { " (truncated)" } else { "" },
482            self.concept_disagreements,
483            self.edge_disagreements,
484        )
485    }
486}
487
488/// The newest usable snapshot at or before `ts`, or `None` to fold from genesis.
489///
490/// **Composition used to be disabled once an archive database existed, and as of
491/// 0.5.5 it is not.** The reason for the refusal was real: `LOG_ARCHIVABLE`
492/// (§5.7) removes superseded rows scattered through the sequence, so a row above
493/// the anchor and at or before `ts` could be in cold while a newer row for the
494/// same entity — recorded *after* `ts`, invisible to the fold — kept it out of
495/// the hot log. The delta missed it and the snapshot answered with a stale
496/// value. The fix is the one that note named: the cold log is now in the delta,
497/// via [`ANCHORED_COLD_FOLD`], so the archived row is visible again and there is
498/// nothing left to refuse.
499///
500/// Selection loads candidates newest-first and stops at the first whose
501/// timestamp is at or before `ts`, so the common case — `reconstruct(now)` —
502/// reads exactly one file. A snapshot this build cannot read
503/// ([`DbError::SnapshotIncompatible`], D-043) is skipped, not raised: an
504/// incompatible snapshot is an ordinary consequence of upgrading, and the whole
505/// point of distinguishing it from corruption is that the answer is to carry on
506/// without it.
507fn snapshot_anchor(snapshots_dir: Option<&Path>, ts: &str) -> Option<MaterializedState> {
508    let dir = snapshots_dir?;
509
510    let mut candidates: Vec<(i64, PathBuf)> = std::fs::read_dir(dir)
511        .ok()?
512        .flatten()
513        .map(|e| e.path())
514        .filter_map(|p| super::snapshot::seq_from_filename(&p).map(|s| (s, p)))
515        .collect();
516    candidates.sort_by_key(|(seq, _)| std::cmp::Reverse(*seq));
517
518    for (_, path) in candidates {
519        match super::snapshot::load_snapshot(&path) {
520            // Sound as a string comparison because every timestamp is the
521            // canonical fixed width (D-029).
522            Ok(state) if state.timestamp.as_str() <= ts => return Some(state),
523            Ok(_) => continue,
524            Err(DbError::SnapshotIncompatible { reason, .. }) => {
525                tracing::warn!("skipping snapshot {path:?}: {reason}");
526                continue;
527            }
528            Err(e) => {
529                tracing::warn!("skipping unreadable snapshot {path:?}: {e}");
530                continue;
531            }
532        }
533    }
534    None
535}
536
537/// Where the answer for `ts` lives.
538///
539/// Three cases, not two (0.8.0, B5, D-121). This used to be a `bool`, and the
540/// missing third case is the whole of B5: *below the log's floor* was folded in
541/// with *the delta is elsewhere*, so a question about a time before the ledger
542/// started came back as [`DbError::ReplayCorrupt`] — the class meaning the
543/// ledger is damaged — naming an archive file the caller had never created.
544enum HotLogReach {
545    /// The hot log holds everything needed at `ts`. Fold it.
546    Covers,
547    /// Nothing had been recorded by `ts`, and nothing has ever been removed
548    /// from the log, so no other file could hold it either. The empty state is
549    /// the correct answer, not a failure to find one.
550    PredatesRecordedHistory,
551    /// The delta is in the cold archive. If it cannot be reached, that is an
552    /// error and stays one.
553    NeedsArchive,
554}
555
556/// Whether the hot log alone can answer for `ts` — a *completeness* test.
557///
558/// **This replaces a reach test that was not one (0.5.5).** The previous version
559/// asked `MIN(recorded_at) <= ts`: whether the hot log stretches back far enough
560/// to contain `ts`. That is a different question from whether it still contains
561/// everything needed to answer at `ts`, and `LOG_ARCHIVABLE` (§5.7) is exactly
562/// what pulls the two apart — it removes *superseded* rows, scattered through
563/// the sequence rather than forming a prefix. One entity archived and another
564/// not is enough: the unarchived one keeps `MIN` pointing before the cutoff
565/// while the archived one's winning row is gone, and the fold silently returns a
566/// state missing an entity. Measured, not theorised — see
567/// `reconstructing_before_the_archive_cutoff_keeps_every_entity`.
568///
569/// The sound test rests on the one guarantee the archive does make: **the newest
570/// row per entity is never archivable**, because archivability requires a later
571/// row to exist. So if `ts` is at or after the newest hot stamp, every entity's
572/// winning row at `ts` is its newest row overall, and every such row is hot.
573/// That covers `reconstruct(now)` — the common case, and the case §5.7 designed
574/// `LOG_ARCHIVABLE` around — and nothing else.
575///
576/// Anything earlier goes to the cold file. That is more ATTACHes than the old
577/// rule performed, and the trade is not close: the old rule was cheaper because
578/// it was answering a question nobody asked.
579///
580/// With no archive database in play the reach test *is* the completeness test —
581/// nothing has been removed, so the hot log is the whole log — and it is kept,
582/// because it is also what distinguishes "before recorded history" from "the
583/// cold file is missing" (D-026).
584async fn hot_log_reach(
585    conn: &libsql::Connection,
586    ts: &str,
587    archive_path: Option<&Path>,
588) -> Result<HotLogReach> {
589    let row = conn
590        .query(
591            "SELECT MIN(recorded_at), MAX(recorded_at) FROM transaction_log",
592            (),
593        )
594        .await?
595        .next()
596        .await?;
597    let (min_recorded_at, max_recorded_at): (Option<String>, Option<String>) = match row {
598        Some(r) => (r.get(0).ok(), r.get(1).ok()),
599        None => (None, None),
600    };
601
602    // Sound as string comparisons because every recorded_at is the canonical
603    // fixed width (D-029).
604    if archive_path.is_some_and(|p| p.exists()) {
605        // An empty hot log beside an archive is the fully-archived case and
606        // covers nothing. It cannot arise from `archive()` itself — the newest
607        // row per entity always stays — but answering "covered" here would make
608        // such a file reconstruct to the empty state with no error at all.
609        return Ok(match max_recorded_at {
610            Some(max_ts) if max_ts.as_str() <= ts => HotLogReach::Covers,
611            _ => HotLogReach::NeedsArchive,
612        });
613    }
614
615    match min_recorded_at {
616        Some(min_ts) if min_ts.as_str() <= ts => Ok(HotLogReach::Covers),
617        // No log at all: a genuinely empty database, and the empty state has
618        // always been the answer here.
619        None => Ok(HotLogReach::PredatesRecordedHistory),
620        // `ts` is below the hot log's floor, and there is no archive file to
621        // consult. Which of the two meanings that has is decided by whether
622        // anything was ever removed from the log — see `hot_log_is_intact`.
623        Some(_) => Ok(if hot_log_is_intact(conn).await? {
624            HotLogReach::PredatesRecordedHistory
625        } else {
626            HotLogReach::NeedsArchive
627        }),
628    }
629}
630
631/// What the caller needs to know when the cold delta cannot be reached —
632/// **assembled from the hot file alone** (0.9.0, C4).
633///
634/// # This is the message the hot-side marker was wanted for
635///
636/// [D-121](../../docs/architecture/s13-decision-register.md) rejected a hot-side
637/// marker recording *archived at* and *horizon*, then left the door open: 0.9.0
638/// was to adopt it "only if it wants the richer message". C4 asked for the
639/// message and found the marker cannot supply it, because the proposed message —
640/// *"this database was archived on X; pass the archive path"* — is **weaker**
641/// than what the hot log already carries:
642///
643/// * *how many rows went* is `MAX(seq_id) - COUNT(*)`, exact for the reason
644///   [`hot_log_is_intact`] gives;
645/// * *how far back the hot file still reaches* is `MIN(seq_id)` and its
646///   `recorded_at` — which is the fact that actually tells a caller whether the
647///   archive is worth fetching, and which a marker's archive **timestamp** does
648///   not give them;
649/// * *that archiving happened at all* is the one bit [`hot_log_is_intact`]
650///   already answers.
651///
652/// The only datum a marker would add is the wall-clock instant of the last
653/// archive run, and no branch and no caller needs it. So the marker is refused
654/// outright rather than deferred again: under
655/// [D-036](../../docs/architecture/s13-decision-register.md) a hot-table addition
656/// lands pre-1.0 or not at all, and a table whose whole content is a timestamp
657/// used in one error string is not worth a rung.
658///
659/// # There is no "nothing was archived" case, and that was settled by injection
660///
661/// This first carried a branch for `removed == 0`, on the reasoning that the
662/// `NeedsArchive` arm is reachable without any archiving. That reasoning was
663/// **wrong about where the cost lands and right about the branch**, and only a
664/// probe told the two apart: replacing the branch body with a panic showed it
665/// firing from `a_failed_cold_reconstruct_still_detaches`, a test that raises
666/// nothing from here — because the hint was being computed *before* the two
667/// arms that use it, on every cold fold. Made lazy, the probe went quiet across
668/// all 27 targets.
669///
670/// So the branch was dead at the use sites: both arms require
671/// [`hot_log_is_intact`] to have returned false, or an archive file to have
672/// existed when `hot_log_reach` looked and to have gone by the time this did.
673/// Rows really were removed in every case that gets here, and the message may
674/// say so without qualification. Deleted rather than kept as a defensive
675/// fallback, for the reason `delete_guarded` records about
676/// `classify_archive_violation`: unreachable code that looks reasonable is
677/// harder to remove later than now.
678///
679/// Best-effort by construction: this runs on the error path, where a second
680/// failure must not replace the diagnosis with its own. A query that does not
681/// answer yields a hint that says so, and the caller still gets the error it came
682/// for.
683async fn archive_hint(conn: &libsql::Connection) -> String {
684    // `COUNT(*)` always returns a row, so `None` here means the query itself
685    // failed and there is nothing to say beyond that.
686    let row = match conn
687        .query(
688            "SELECT COUNT(*), MIN(seq_id), MAX(seq_id), MIN(recorded_at) FROM transaction_log",
689            (),
690        )
691        .await
692    {
693        Ok(mut rows) => rows.next().await.ok().flatten(),
694        Err(_) => None,
695    };
696
697    let Some(row) = row else {
698        return "the hot log could not be inspected for an archive horizon".into();
699    };
700    let count: i64 = row.get(0).unwrap_or(0);
701    if count == 0 {
702        return "the hot log is empty".into();
703    }
704    let min: i64 = row.get(1).unwrap_or(0);
705    let max: i64 = row.get(2).unwrap_or(0);
706    let floor: String = row.get(3).unwrap_or_default();
707    let removed = max - count;
708
709    format!(
710        "{removed} log rows have been archived out of this database; the hot log \
711         now begins at seq_id {min} ({floor})"
712    )
713}
714
715/// Was any row ever removed from `transaction_log`? — answered exactly, from
716/// the hot file alone (0.8.0, B5, D-121).
717///
718/// # Why this question needs answering at all
719///
720/// With `ts` below the hot log's floor and no archive file present, the state
721/// on disk is consistent with two very different histories: **nothing was ever
722/// archived**, in which case the hot log is the whole log and the answer to
723/// *what was believed at `ts`* is "nothing yet"; or **rows were archived and
724/// the cold file is gone**, in which case the answer is unknowable and saying
725/// "nothing" would be inventing one. Before this, the two were conflated and
726/// both raised — which made an ordinary question about a young database report
727/// the ledger as damaged.
728///
729/// # Why `seq_id` settles it, with no marker and no schema change
730///
731/// `transaction_log.seq_id` is `INTEGER PRIMARY KEY AUTOINCREMENT`, so values
732/// are allocated 1, 2, 3, … and **never reused**. A rolled-back transaction
733/// leaves no gap — `sqlite_sequence` rolls back with it, which
734/// [D-049](../../docs/architecture/s13-decision-register.md) established by
735/// measurement after assuming the opposite. So the only thing that can perturb
736/// the sequence is deletion, and `trg_txlog_guard_delete` confines deletion to
737/// an archive session.
738///
739/// Therefore: if nothing was removed, the ids are exactly `1..=MAX` and
740/// `COUNT(*) == MAX(seq_id)` with `MIN(seq_id) == 1`. And conversely — this is
741/// the half that makes it a proof rather than a heuristic — those two equalities
742/// force the set of `COUNT` distinct ids inside `[1, MAX]` to be all of it, so
743/// nothing is missing. The test is exact in both directions, not merely
744/// suggestive.
745///
746/// **It does not depend on the archive removing a contiguous block**, which it
747/// does not: `archive()` removes *superseded* rows scattered through the
748/// sequence. Scattered removal leaves interior gaps, which fails the count
749/// equality; removal from the front raises `MIN` above 1. Removal from the end
750/// cannot happen, because the newest row per entity is never archivable.
751///
752/// # What it deliberately does not claim
753///
754/// Nothing about *when* the archiving happened or *what* went, which is what
755/// the rejected hot-side marker would have carried. It answers one bit, and one
756/// bit is what the branch above needs.
757async fn hot_log_is_intact(conn: &libsql::Connection) -> Result<bool> {
758    let row = conn
759        .query(
760            "SELECT COUNT(*), MIN(seq_id), MAX(seq_id) FROM transaction_log",
761            (),
762        )
763        .await?
764        .next()
765        .await?;
766    let Some(row) = row else {
767        return Ok(true);
768    };
769    let count: i64 = row.get(0).unwrap_or(0);
770    if count == 0 {
771        return Ok(true);
772    }
773    let min: i64 = row.get(1).unwrap_or(0);
774    let max: i64 = row.get(2).unwrap_or(0);
775    Ok(min == 1 && count == max)
776}
777
778/// Run one fold query from nothing — the unanchored path.
779async fn fold(conn: &libsql::Connection, ts: &str, query: &str) -> Result<MaterializedState> {
780    let delta = fold_delta(conn, query, libsql::params![ts]).await?;
781    Ok(delta.apply_to(MaterializedState::empty(ts), ts))
782}
783
784/// Run one fold query and collect the winning rows, deletions included.
785async fn fold_delta(
786    conn: &libsql::Connection,
787    query: &str,
788    params: impl libsql::params::IntoParams,
789) -> Result<Delta> {
790    let mut rows = conn.query(query, params).await?;
791    let mut d = Delta::default();
792    let (concepts, edges, max_seq) = (&mut d.concepts, &mut d.edges, &mut d.max_seq);
793
794    while let Some(row) = rows.next().await? {
795        let seq_id: i64 = row.get(0)?;
796        let table_name: String = row.get(1)?;
797        let _entity_id: String = row.get(2)?;
798        let op: String = row.get(3)?;
799        let payload_str: String = row.get(4)?;
800
801        if seq_id > *max_seq {
802            *max_seq = seq_id;
803        }
804
805        // A `'D'` row is corruption, not a tombstone (D-072).
806        //
807        // Doctrine V permits no physical delete outside an archive session, and
808        // the archive *moves* rows rather than logging their removal — so no
809        // trigger in the schema writes a `'D'`, and no code path in the crate
810        // can produce one. This arm used to treat it as a tombstone, which read
811        // as a claim that deletions are recorded and reconstructible. They are
812        // not. Refusing here makes the doctrine enforced at the fold rather than
813        // assumed by it, and is the same call D-060 made for overlap: the layer
814        // that can notice should.
815        //
816        // Retirement is unaffected and is the mechanism that actually removes a
817        // concept from a composed state — see the `retired != 0` branch below,
818        // which is where `concepts_gone` is populated in practice.
819        if op == "D" {
820            return Err(DbError::ReplayCorrupt {
821                seq: seq_id,
822                reason: format!(
823                    "transaction_log carries a 'D' operation for {table_name} \
824                     entity {_entity_id:?}; Doctrine V permits no physical delete \
825                     outside an archive session, and the archive logs none. This \
826                     row was not written by this crate."
827                ),
828            });
829        }
830
831        let payload: serde_json::Value =
832            serde_json::from_str(&payload_str).map_err(|e| DbError::ReplayCorrupt {
833                seq: seq_id,
834                reason: format!("Failed to parse payload JSON: {e}"),
835            })?;
836
837        // v1 and v2 differ by one added field, so v1 folds by reading it as
838        // absent — which is what `Option` already means here. A future shape
839        // that *removes* or *retypes* a field would not be able to share this
840        // path, and would want a match on `v` rather than a ceiling.
841        let v = payload.get("v").and_then(|v| v.as_u64()).unwrap_or(1);
842        if v > PAYLOAD_VERSION as u64 {
843            return Err(DbError::PayloadVersion {
844                got: v as u8,
845                max: PAYLOAD_VERSION,
846            });
847        }
848
849        if table_name == "concepts" {
850            let id = _entity_id;
851            let retired = payload.get("retired").and_then(|r| r.as_i64()).unwrap_or(0);
852            if retired == 0 {
853                let title = payload
854                    .get("title")
855                    .and_then(|s| s.as_str())
856                    .unwrap_or("")
857                    .to_string();
858                let content = payload
859                    .get("content")
860                    .and_then(|s| s.as_str())
861                    .unwrap_or("")
862                    .to_string();
863                let embedding_model = payload
864                    .get("embedding_model")
865                    .and_then(|s| s.as_str())
866                    .map(|s| s.to_string());
867                concepts.insert(
868                    id.clone(),
869                    NodeAttributes {
870                        id,
871                        title,
872                        content,
873                        embedding_model,
874                    },
875                );
876            } else {
877                // Retirement is the application axis (§4.1), and a reconstruction
878                // shows what was visible. Onto a snapshot that means removing
879                // the concept, not declining to add it.
880                d.concepts_gone.insert(id);
881            }
882        } else if table_name == "links" {
883            let src = payload
884                .get("source_id")
885                .and_then(|s| s.as_str())
886                .unwrap_or("")
887                .to_string();
888            let tgt = payload
889                .get("target_id")
890                .and_then(|s| s.as_str())
891                .unwrap_or("")
892                .to_string();
893            let edge_type = payload
894                .get("edge_type")
895                .and_then(|s| s.as_str())
896                .unwrap_or("")
897                .to_string();
898            let vf = payload
899                .get("valid_from")
900                .and_then(|s| s.as_str())
901                .unwrap_or("")
902                .to_string();
903            let vt = payload
904                .get("valid_to")
905                .and_then(|s| s.as_str())
906                .unwrap_or("")
907                .to_string();
908            edges.insert(_entity_id, (src, tgt, edge_type, vf, vt));
909        }
910    }
911
912    Ok(d)
913}
914
915impl Delta {
916    /// Compose onto `base` under last-writer-wins by `seq_id` (§5.5).
917    ///
918    /// The delta is by construction newer than the base — it is the fold of
919    /// everything above the base's anchor — so every row it carries wins, and
920    /// every retirement it carries removes. This is the same rule
921    /// `trg_links_current_sync`'s upsert applies and the same rule the cold
922    /// fold applies; that the three agree is asserted by test rather than by
923    /// this comment (§8).
924    fn apply_to(self, base: MaterializedState, ts: &str) -> MaterializedState {
925        let mut concepts = base.concepts;
926        let mut edges: HashMap<String, (String, String, String, String, String)> =
927            base.edges.into_iter().map(|e| (edge_key(&e), e)).collect();
928
929        for id in self.concepts_gone {
930            concepts.remove(&id);
931        }
932        // No edge equivalent: an edge is superseded in place under the same
933        // `entity_id`, never removed — see [`Delta`] (D-072).
934        concepts.extend(self.concepts);
935        edges.extend(self.edges);
936
937        // Sorted so the result is a function of the state and not of hash
938        // iteration order — `reconstruct` is compared against itself by the
939        // property suite, and two runs must be equal, not merely equivalent.
940        let mut edges: Vec<_> = edges.into_values().collect();
941        edges.sort();
942
943        MaterializedState {
944            seq_anchor: self.max_seq.max(base.seq_anchor),
945            timestamp: ts.to_string(),
946            concepts,
947            edges,
948            // A delta was applied, so there was history to fold. `reconstruct`
949            // sets the flag on the one path that never gets here.
950            predates_recorded_history: false,
951        }
952    }
953}