interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

ledger: checkpoint reads only sequences and block hashes (#71 stage 1)

merged dd0ef0eea77b208b #90 · opened 2026-11-06 20:51 UTC · closed 2026-11-06 21:19 UTC · merged 2026-11-06 21:19 UTC

Imported from GitHub aien-dev/spark-rsi-mv#90, by drakestapleton

Base 7e8bf7da7f2adc0bea7938cc042d8a7873619cc1 · Head a708ac977ea014558c1c536ef7b0a44507663f6c

Merged on GitHub as 505c75dedac8796f4fa16f5376db13e9bd0f7d84; reachable from main 2edaf6704304e089f6f50fcd3daedd71b2446840 (observed 2026-11-18T16:40:15Z)

drakestapleton wrote on 2026-11-06 20:51 UTC

Refs #71. Stage 1 only. Stage 2 (append-maintained Merkle frontier or cached internal nodes) is out of scope and not started.

What changed

ImprovementLedger::checkpoint called all_blocks(), which selects every column, materializes every payload and parses every blob list, though a checkpoint needs only the block hashes, their count and the last sequence. It now runs one SELECT sequence, block_hash FROM blocks ORDER BY sequence ASC (one SQLite statement, one read snapshot) through a private helper leaf_hashes, and holds the connection lock across that read and the checkpoint insert, so no append through this handle lands between them.

Unchanged: the Merkle format, root bytes, duplicate-last behavior, hex hash encoding, compute_merkle_root, the signature scheme, and the empty-ledger refusal (Cannot create checkpoint on empty ledger). verify_chain_integrity (the other all_blocks caller) keeps all_blocks: the audit needs every payload, link and blob list and stays authoritative. src/main.rs ledger log also keeps it (it prints full blocks).

Behavior note: on main, a payload column holding non-text bytes made checkpoint fail as a side effect of materializing it. checkpoint never verified payload digests (a text payload edit was already checkpointed on main), so that refusal was incidental. The full audit still refuses such a ledger; the repro test asserts this.

a708ac977ea014558c1c536ef7b0a44507663f6c on branch fix/issue-71-checkpoint-hash-query, base main 7e8bf7da.

Evidence (Spark host, taskset -c 6 nice -n 10 bwrap --dev-bind / / --dev /dev --proc /proc --)

Command: cargo test --locked --test test_cryptographic_improvement_ledger checkpoint_

RunTreercLast line
beforemain src/ledger/db.rs + new tests101test result: FAILED. 3 passed; 1 failed — test_checkpoint_does_not_materialize_payloads panicked: checkpoint must not read payloads: "Invalid column type Blob at index: 4, name: payload_json"
afterthis branch0test result: ok. 4 passed; 0 failed
negative controlthis branch with checkpoint pointed back at all_blocks() (uncommitted)101test result: FAILED. 3 passed; 1 failed — same panic
  • test_checkpoint_does_not_materialize_payloads (repro): stores X'FF00FE' as the payload of block 2, asserts all_blocks() fails, then asserts checkpoint succeeds with the root, count, sequence and signature computed by the all_blocks path before the corruption, and that verify_chain_integrity still refuses.
  • test_checkpoint_matches_all_blocks_path_prefix_by_prefix (parity): at prefix sizes 0,1,2,3,4,5,7,8,9,16,17, checkpoint and the pre-change all_blocks construction give identical up_to_sequence, block_count, merkle_root and signature (p256 RFC 6979, deterministic); size 0 gives the same refusal and stores nothing; each stored checkpoint round-trips and the audit verifies it with the key. Passes before and after, as parity should.

Other host-local gates at the head:

  • Full suite, cargo test --locked -j1 --no-fail-fast -- --test-threads=1 (bwrap, core 6, CARGO_TARGET_DIR in /dev/shm with an in-tree target symlink to it so the judge unit tests find their fixture binary): rc 101, 339 passed, 3 failed, 1 ignored; test_cryptographic_improvement_ledger 12/12 ok. The 3 failures (test_codebase_observation_current_repo: assertion failed: telemetry.tests_passing; daemon_cycle_with_a_correct_fixture_reaches_the_later_gates: identity; daemon_cycle_with_a_wrong_answering_fixture_is_refused_and_rolled_back: quota decision) fail identically with main's src/ledger/db.rs on the same host (rc 101, same panics): pre-existing on this host, not regressions from this change. Two GPU tests reported NOT_RUN (opt-in).
  • cargo fmt --all -- --check: rc 0.
  • tests/gates/run.sh crumb-verify with crumb built from aien-architecture-mv @12ad0141 (the CI pin): rc 0, crumb verify: OK: 33 crumbs current at HEAD a708ac9.
  • tests/gates/run.sh zero-disk-secrets: rc 0.

Labels

  • Tier: IMPLEMENTED, EXERCISED (host).
  • Repro/parity/negative control: PASS (host-local).
  • GitHub CI on the head: NOT_RUN (desk gate; the workflow runs on pull_request only).
  • No measured speedup claimed: this removes payload materialization from the checkpoint path; it does not measure disk traffic or wall time. Host results are not hardware evidence.

Apply it

git checkout -b patch-dd0ef0eea77b208b 7e8bf7da7f2adc0bea7938cc042d8a7873619cc1
curl -fsSL https://interplane.io/drakestapleton/spark-rsi-mv/patches/dd0ef0eea77b208b.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/spark-rsi-mv
90
a708ac977ea014558c1c536ef7b0a44507663f6c
{"kind":"github-import","owner":"aien-dev","repo":"spark-rsi-mv","number":90,"url":"https://github.com/aien-dev/spark-rsi-mv/pull/90","export_sha256":"274548dca61e9cb7f97fef8d3451b6ff09d0babff95d5d063c62bba1ec8d9c07","imported_utc":"2026-11-18T16:40:15Z"}

Changes

diff --git a/src/ledger/db.rs b/src/ledger/db.rs
index c015495..bed56c2 100644
--- a/src/ledger/db.rs
+++ b/src/ledger/db.rs
@@ -237,6 +237,23 @@ impl ImprovementLedger {
         Ok(blocks)
     }
 
+    /// Every block hash in sequence order, and the last sequence, from one SELECT (one SQLite
+    /// read snapshot). Unlike `all_blocks`, payloads and blob lists are neither read nor parsed.
+    fn leaf_hashes(conn: &Connection) -> Result<(Vec<String>, Option<u64>), String> {
+        let mut stmt = conn
+            .prepare("SELECT sequence, block_hash FROM blocks ORDER BY sequence ASC")
+            .map_err(|e| e.to_string())?;
+        let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
+        let mut hashes = Vec::new();
+        let mut last_sequence = None;
+        while let Some(row) = rows.next().map_err(|e| e.to_string())? {
+            let seq: i64 = row.get(0).map_err(|e| e.to_string())?;
+            hashes.push(row.get(1).map_err(|e| e.to_string())?);
+            last_sequence = Some(seq as u64);
+        }
+        Ok((hashes, last_sequence))
+    }
+
     fn row_to_block(row: &rusqlite::Row) -> Result<LedgerBlock, String> {
         let seq: i64 = row.get(0).map_err(|e| e.to_string())?;
         let bt_str: String = row.get(1).map_err(|e| e.to_string())?;
@@ -358,16 +375,17 @@ impl ImprovementLedger {
         self.append_block(BlockType::PromotionEvidence, payload_json, Vec::new())
     }
 
+    /// Signs and stores a Merkle checkpoint over every block hash. Reads only sequences and
+    /// hashes; payload and blob verification stays with `verify_chain_integrity`.
     pub fn checkpoint(&self, signing_key: Option<&SigningKey>) -> Result<MerkleCheckpoint, String> {
-        let blocks = self.all_blocks()?;
-        if blocks.is_empty() {
+        // One lock for the read and the insert: no append through this handle lands between them.
+        let conn = self.conn.lock().map_err(|e| e.to_string())?;
+        let (leaf_hashes, last_sequence) = Self::leaf_hashes(&conn)?;
+        let Some(up_to_sequence) = last_sequence else {
             return Err("Cannot create checkpoint on empty ledger".to_string());
-        }
-
-        let leaf_hashes: Vec<String> = blocks.iter().map(|b| b.block_hash.clone()).collect();
-        let up_to_sequence = blocks.last().unwrap().sequence;
+        };
         let merkle_root = compute_merkle_root(&leaf_hashes);
-        let block_count = blocks.len() as u64;
+        let block_count = leaf_hashes.len() as u64;
 
         let mut checkpoint = MerkleCheckpoint::new(up_to_sequence, merkle_root, block_count);
 
@@ -375,7 +393,6 @@ impl ImprovementLedger {
             checkpoint.sign(key);
         }
 
-        let conn = self.conn.lock().map_err(|e| e.to_string())?;
         conn.execute(
             "INSERT OR REPLACE INTO checkpoints (
                 up_to_sequence, merkle_root, block_count, timestamp_utc, signature
diff --git a/tests/test_cryptographic_improvement_ledger.rs b/tests/test_cryptographic_improvement_ledger.rs
index 2e15c23..610fefd 100644
--- a/tests/test_cryptographic_improvement_ledger.rs
+++ b/tests/test_cryptographic_improvement_ledger.rs
@@ -3,7 +3,10 @@ use rusqlite::Connection;
 use spark_rsi::daemon::RsiEngine;
 use spark_rsi::evaluator::EvaluationMetricsSummary;
 use spark_rsi::evaluator::EvaluationReceipt;
-use spark_rsi::ledger::{BlockType, ImprovementLedger, LedgerBlock, PromotionEvidencePayload};
+use spark_rsi::ledger::{
+    compute_merkle_root, BlockType, ImprovementLedger, LedgerBlock, MerkleCheckpoint,
+    PromotionEvidencePayload,
+};
 use spark_rsi::models::RsiConfig;
 use std::fs;
 use std::process::Command;
@@ -485,3 +488,113 @@ fn test_audit_report_names_what_it_did_not_check() {
     let report = ledger.verify_chain_integrity(Some(&verifying_key)).unwrap();
     assert!(report.unchecked(true).is_empty());
 }
+
+/// The checkpoint construction before issue #71 stage 1: every full block through `all_blocks`.
+fn checkpoint_via_all_blocks(
+    ledger: &ImprovementLedger,
+    signing_key: &SigningKey,
+) -> Result<MerkleCheckpoint, String> {
+    let blocks = ledger.all_blocks()?;
+    if blocks.is_empty() {
+        return Err("Cannot create checkpoint on empty ledger".to_string());
+    }
+    let leaf_hashes: Vec<String> = blocks.iter().map(|b| b.block_hash.clone()).collect();
+    let mut checkpoint = MerkleCheckpoint::new(
+        blocks.last().unwrap().sequence,
+        compute_merkle_root(&leaf_hashes),
+        blocks.len() as u64,
+    );
+    checkpoint.sign(signing_key);
+    Ok(checkpoint)
+}
+
+/// Issue #71 stage 1: a checkpoint needs only sequences and block hashes, so it must not read
+/// payloads. A payload stored as non-text bytes cannot be materialized as a `LedgerBlock`.
+#[test]
+fn test_checkpoint_does_not_materialize_payloads() {
+    let tmp = tempfile::tempdir().unwrap();
+    let rsi_root = tmp.path().join(".rsi");
+    let ledger = ImprovementLedger::open(&rsi_root).unwrap();
+    let signing_key = SigningKey::from_bytes(&[88u8; 32].into()).unwrap();
+
+    for i in 1..=3 {
+        ledger
+            .append_block(
+                BlockType::Evaluation,
+                format!("{{\"eval\": {}}}", i),
+                Vec::new(),
+            )
+            .unwrap();
+    }
+    let expected = checkpoint_via_all_blocks(&ledger, &signing_key).unwrap();
+
+    let conn = Connection::open(rsi_root.join("ledger.db")).unwrap();
+    conn.execute(
+        "UPDATE blocks SET payload_json = X'FF00FE' WHERE sequence = 2",
+        [],
+    )
+    .unwrap();
+    assert!(
+        ledger.all_blocks().is_err(),
+        "a non-text payload must not materialize"
+    );
+
+    let checkpoint = ledger
+        .checkpoint(Some(&signing_key))
+        .expect("checkpoint must not read payloads");
+    assert_eq!(checkpoint.up_to_sequence, expected.up_to_sequence);
+    assert_eq!(checkpoint.block_count, expected.block_count);
+    assert_eq!(checkpoint.merkle_root, expected.merkle_root);
+    assert_eq!(checkpoint.signature, expected.signature);
+
+    // The full audit still reads every payload and refuses this ledger.
+    assert!(ledger.verify_chain_integrity(None).is_err());
+}
+
+/// Issue #71 stage 1 parity: root, count, sequence and signature are those of the `all_blocks`
+/// path at every prefix size, including the empty-ledger refusal.
+#[test]
+fn test_checkpoint_matches_all_blocks_path_prefix_by_prefix() {
+    let signing_key = SigningKey::from_bytes(&[88u8; 32].into()).unwrap();
+    let verifying_key = VerifyingKey::from(&signing_key);
+
+    // Size 0: both paths refuse and nothing is stored.
+    let tmp = tempfile::tempdir().unwrap();
+    let rsi_root = tmp.path().join(".rsi");
+    let empty = ImprovementLedger::open(&rsi_root).unwrap();
+    Connection::open(rsi_root.join("ledger.db"))
+        .unwrap()
+        .execute("DELETE FROM blocks", [])
+        .unwrap();
+    let expected = checkpoint_via_all_blocks(&empty, &signing_key).unwrap_err();
+    assert_eq!(empty.checkpoint(Some(&signing_key)).unwrap_err(), expected);
+    assert!(empty.latest_checkpoint().unwrap().is_none());
+
+    let tmp = tempfile::tempdir().unwrap();
+    let ledger = ImprovementLedger::open(&tmp.path().join(".rsi")).unwrap();
+    let mut size = 1; // Genesis
+    for target in [1usize, 2, 3, 4, 5, 7, 8, 9, 16, 17] {
+        while size < target {
+            ledger
+                .append_block(
+                    BlockType::Evaluation,
+                    format!("{{\"eval\": {}}}", size),
+                    Vec::new(),
+                )
+                .unwrap();
+            size += 1;
+        }
+        let expected = checkpoint_via_all_blocks(&ledger, &signing_key).unwrap();
+        let checkpoint = ledger.checkpoint(Some(&signing_key)).unwrap();
+        assert_eq!(checkpoint.block_count, target as u64, "prefix {target}");
+        let fields = |c: &MerkleCheckpoint| {
+            let (root, signature) = (c.merkle_root.clone(), c.signature.clone());
+            (c.up_to_sequence, c.block_count, root, signature)
+        };
+        assert_eq!(fields(&checkpoint), fields(&expected), "prefix {target}");
+        assert!(checkpoint.verify_signature(&verifying_key));
+        assert_eq!(ledger.latest_checkpoint().unwrap(), Some(checkpoint));
+        let report = ledger.verify_chain_integrity(Some(&verifying_key)).unwrap();
+        assert!(report.checkpoint_verified && report.signature_verified);
+    }
+}