proofs: Lean 4 kernel-checked cache-restore correctness + prefix measure tool

proofs/auto_ckpt.lean: core-only Lean 4 model of the auto-ckpt / GEN 0 RESUME rule, kernel PASS (no sorryAx). Proves restore soundness (s <= lcp => first s tokens match, bit-identical recompute), branch invalidation (divergence at p => lcp <= p), and GEN 0 -> RESUME L. Backs the invariants in review/osservazioni-auto-ckpt.md.

examples/prefix_measure.rs: measures the real static prefix from live SQLite sessions via build_prefix_ids (no engine): ~1135 tokens/session, 575 tool_declare, ~589 shared cross-session. README Status documents both + the agreed next engine-side --auto-ckpt step. Suite 162 passed + 3 ignored, clippy/fmt clean.
This commit is contained in:
adm committed 2026-11-26 20:59:15 +01:00
1 parent db2dee2d2c
commit 862897fdbc
3 files changed
+280

No files matched your search

+14
View File
@@ -309,6 +309,20 @@ always sees a fresh notepad, no frozen header, no schema migration). The joint
`GEN 0 → RESUME` measurement on HIP (`examples/prewarm_bench.rs`) **passed**:
`cached_tokens == L == 385`, only the 35 new user tokens prefilled.
The cache-reuse correctness is also **formally verified**: `proofs/auto_ckpt.lean`
is a core-only Lean 4 model of the prefix-cache restore rule, kernel-checked
(`lean proofs/auto_ckpt.lean`, no `sorryAx`). It proves that selecting a checkpoint
at depth `s ≤ lcp` restores exactly the prompt's first `s` tokens (so recomputing
only the delta is bit-identical), that a divergence at `p` invalidates deeper
snapshots, and that a `GEN 0` over a prefix makes the next turn `RESUME` the whole
prefix. `examples/prefix_measure.rs` measures the real static prefix from the live
SQLite sessions (≈1135 tokens per session, 575 of them `tool_declare`; only ≈589
shared cross-session, since `SYSTEM_PROMPT` leads with the session identity). The
agreed next engine-side step is **automatic multi-level prefix checkpointing**
(`--auto-ckpt`: a per-slot snapshot pool + exact-`lcp` restore at every `GEN`,
opt-in and protocol-transparent). strata-ctl needs no change for it, provided the
pool retains the exact end-of-prefill checkpoint so `RESUME == L` still holds.
Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function
returns a clear 400), multi-slot batching, logprobs / structured output, automatic
engine restart after a crash, a full SSRF guard against DNS rebinding, and the
+173
View File
@@ -0,0 +1,173 @@
//! Measure the REAL static prompt prefix (in tokens) across the live GUI sessions.
//!
//! Answers the engine coder's auto-ckpt anchor question: how big is the pure
//! static prefix (tool_declare + SYSTEM_PROMPT + TOOL_USE, before <NOTEPAD>) and
//! with <NOTEPAD> included, in real chats? Also measures the CROSS-SESSION common
//! static prefix (the deepest anchor that survives a session switch on --parallel 1).
//!
//! cargo run --release --example prefix_measure
//! cargo run --release --example prefix_measure -- --config /path/to.json
//!
//! Reads the same SQLite store the server uses (WAL: safe concurrent reader).
//! No engine, no generation: pure formatter token counts via build_prefix_ids.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use strata_ctl::api::types::ChatRequest;
use strata_ctl::api::Formatter;
use strata_ctl::config::Config;
use strata_ctl::context;
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
use strata_ctl::store::{SqliteStore, Store};
use strata_ctl::window;
fn lcp(a: &[u32], b: &[u32]) -> usize {
a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count()
}
fn main() {
let mut path = Config::default_path();
let args: Vec<String> = std::env::args().skip(1).collect();
if let Some(i) = args.iter().position(|a| a == "--config") {
if let Some(p) = args.get(i + 1) {
path = PathBuf::from(p);
}
}
let cfg = Config::load(&path).expect("config loads");
strata_ctl::i18n::init(&cfg.language());
let dir = cfg.tokenizer.clone().expect("config has a tokenizer dir");
let tok = Arc::new(InklingTokenizer::load_dir(Path::new(&dir)).expect("tokenizer loads"));
let src =
std::fs::read_to_string(Path::new(&dir).join("chat_template.jinja")).expect("template");
let template = ChatTemplate::new(&src).expect("template compiles");
let fmt = Arc::new(InklingFormatter::new(
tok,
template,
cfg.model_name().to_string(),
cfg.reasoning_effort.clone(),
cfg.sampling.to_sampling(),
));
let db = cfg.gui_db_path();
let store = SqliteStore::open(&db).expect("store opens");
println!("db: {}", db.display());
let user_name = store
.get_defaults()
.ok()
.flatten()
.and_then(|d| d.user_name)
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| "User".to_string());
let sections = store.context_sections().expect("sections");
println!("user_name: {user_name}");
println!("sections (store order):");
for s in &sections {
println!(" [{}] {} ({} chars)", s.position, s.name, s.content.len());
}
let tools = strata_ctl::agent::agent_tools();
let mkreq = |msgs: Vec<strata_ctl::api::types::ChatMessage>| ChatRequest {
model: cfg.model_name().to_string(),
messages: msgs,
tools: Some(tools.clone()),
tool_choice: Some(serde_json::json!("auto")),
..Default::default()
};
let ids = |msgs: Vec<strata_ctl::api::types::ChatMessage>| -> Vec<u32> {
fmt.build_prefix_ids(&mkreq(msgs)).expect("prefix ids")
};
let sessions = store.list_sessions().expect("sessions");
println!("\n=== PER-SESSION STATIC PREFIX (tokens, agent tools ON) ===");
println!(
"{:<28} {:>8} {:>8} {:>10} {:>8} {:>6}",
"session", "static", "np_delta", "static+np", "full", "hist"
);
let mut statics: Vec<(String, Vec<u32>)> = Vec::new();
let mut tool_declare_delta: Option<usize> = None;
for sess in &sessions {
let notepad = store.notepad(&sess.id).unwrap_or_default();
let ws = store.window_start(&sess.id).unwrap_or(0);
let (history, _total) = store.message_window(&sess.id, ws).unwrap_or((vec![], 0));
let sel = window::select(&history, ws);
let hist = &history[sel.start..];
let static_msgs = context::pinned_messages(sess, &sections, &[]);
let np_msgs = context::pinned_messages(sess, &sections, &notepad);
let full_msgs = context::compose_prefix(sess, hist, &user_name, &sections, &notepad);
let i_static = ids(static_msgs.clone());
let i_np = ids(np_msgs);
let i_full = ids(full_msgs);
// The static boundary is TEXT-level (the template concatenates system
// messages), so the last token(s) before <NOTEPAD>/<DIALOG> can re-merge
// when the following block changes. Measure the COMMON LEADING tokens
// (lcp) — exactly the prefix the engine's auto-ckpt lcp sees in the real
// prompt — instead of assuming a clean special-token boundary.
let static_pure = lcp(&i_static, &i_np);
let static_np = lcp(&i_np, &i_full);
if tool_declare_delta.is_none() {
println!(
" [boundary] sections render={} lcp->notepad={} (re-merge {}); pinned render={} lcp->dialog={} (re-merge {})",
i_static.len(), static_pure, i_static.len() - static_pure,
i_np.len(), static_np, i_np.len() - static_np
);
}
// Isolate tool_declare overhead once (sections rendered WITHOUT tools).
if tool_declare_delta.is_none() {
let no_tools = ChatRequest {
model: cfg.model_name().to_string(),
messages: static_msgs,
..Default::default()
};
let i_nt = fmt.build_prefix_ids(&no_tools).expect("no-tools ids");
tool_declare_delta = Some(i_static.len().saturating_sub(i_nt.len()));
}
let title: String = sess.title.chars().take(28).collect();
println!(
"{:<28} {:>8} {:>8} {:>10} {:>8} {:>6}",
title,
static_pure,
static_np - static_pure,
static_np,
i_full.len(),
hist.len()
);
statics.push((sess.title.clone(), i_static[..static_pure].to_vec()));
}
if let Some(d) = tool_declare_delta {
println!("\ntool_declare overhead (tools ON vs OFF, sections only): {d} tokens");
}
// Cross-session common static prefix: the deepest anchor that survives a
// session switch on --parallel 1 (one conversation cache). Bounded by where
// session-specific content ({identity} = title/folder inside SYSTEM_PROMPT)
// first diverges.
if statics.len() >= 2 {
let mut global = statics[0].1.clone();
let mut min_pair = usize::MAX;
let mut max_pair = 0usize;
for i in 0..statics.len() {
for j in (i + 1)..statics.len() {
let l = lcp(&statics[i].1, &statics[j].1);
min_pair = min_pair.min(l);
max_pair = max_pair.max(l);
}
let l = lcp(&global, &statics[i].1);
global.truncate(l);
}
println!("\n=== CROSS-SESSION STATIC COMMON PREFIX ===");
println!("sessions compared: {}", statics.len());
println!("common to ALL sessions: {} tokens", global.len());
println!("pairwise min: {min_pair} pairwise max: {max_pair}");
}
}
+93
View File
@@ -0,0 +1,93 @@
/-
Auto-checkpoint / GEN 0 RESUME — modello formale kernel-checked (Lean 4 core).
Backing formale di review/osservazioni-auto-ckpt.md. Token = Nat, prompt/catena = List Nat.
Proprietà verificate dal kernel:
- lcp_sound : ripristino sound (s ≤ lcp ⇒ i primi s token coincidono) → "logit bit-identici"
- lcp_le_of_take_ne: invalidazione oltre il branch point (divergenza a p ⇒ lcp ≤ p)
- lcp_append_self : dopo GEN 0 su `pre`, il turno reale `pre ++ new` ha lcp = pre.length
- tk_append_len : ripristinare L = pre.length token restituisce esattamente `pre` (RESUME L)
-/
namespace AutoCkpt
/-- Lunghezza del prefisso comune di due liste di token. -/
def lcp : List Nat → List Nat → Nat
| [], _ => 0
| _, [] => 0
| a :: as, b :: bs => if a = b then Nat.succ (lcp as bs) else 0
/-- Primi n token (take proprio, per restare solo core). -/
def tk : Nat → List Nat → List Nat
| 0, _ => []
| _+1, [] => []
| n+1, a :: as => a :: tk n as
/-- RESTORE SOUNDNESS: ogni checkpoint con profondità s ≤ lcp ripristina esattamente
i primi s token del nuovo prompt. È il cuore del "zero approssimazioni, logit
bit-identici al prefill da zero": ricalcolare solo il delta è corretto. -/
theorem lcp_sound : ∀ (P C : List Nat) (s : Nat), s ≤ lcp P C → tk s P = tk s C := by
intro P
induction P with
| nil =>
intro C s hs
have h0 : lcp ([] : List Nat) C = 0 := rfl
have hs0 : s = 0 := by omega
subst hs0; rfl
| cons a as ih =>
intro C s hs
cases C with
| nil =>
have h0 : lcp (a :: as) ([] : List Nat) = 0 := rfl
have hs0 : s = 0 := by omega
subst hs0; rfl
| cons b bs =>
by_cases hab : a = b
· have hlcp : lcp (a :: as) (b :: bs) = Nat.succ (lcp as bs) := by simp [lcp, hab]
cases s with
| zero => rfl
| succ k =>
have hk : k ≤ lcp as bs := by omega
have ihk := ih bs k hk
simp [tk, hab, ihk]
· have hlcp : lcp (a :: as) (b :: bs) = 0 := by simp [lcp, hab]
have hs0 : s = 0 := by omega
subst hs0; rfl
/-- INVALIDAZIONE: se i primi p+1 token divergono, lcp ≤ p. Quindi ogni checkpoint
con seq_len > p fallisce la guardia s ≤ lcp e non viene selezionato: una scrittura
a pos p invalida automaticamente gli snapshot oltre il branch point. -/
theorem lcp_le_of_take_ne (P C : List Nat) (p : Nat)
(h : tk (p+1) P ≠ tk (p+1) C) : lcp P C ≤ p := by
by_cases hle : lcp P C ≤ p
· exact hle
· have hs : p+1 ≤ lcp P C := by omega
exact absurd (lcp_sound P C (p+1) hs) h
/-- Dopo GEN 0 su `pre` (catena = pre), il turno reale `pre ++ new` condivide
esattamente pre.length token: la guardia min(lcp, prompt_len-1) ammette L. -/
theorem lcp_append_self : ∀ (pre new : List Nat), lcp (pre ++ new) pre = pre.length := by
intro pre
induction pre with
| nil => intro new; cases new <;> rfl
| cons a as ih => intro new; simp [lcp, ih, List.cons_append]
/-- Ripristinare L = pre.length token dal turno reale restituisce esattamente il
prefisso pre-riscaldato `pre`: RESUME L riutilizza tutto il prefisso GEN 0. -/
theorem tk_append_len : ∀ (pre new : List Nat), tk pre.length (pre ++ new) = pre := by
intro pre
induction pre with
| nil => intro new; rfl
| cons a as ih => intro new; simp [tk, ih, List.cons_append]
/-- Capstone GEN 0 → RESUME L: lcp = L e il ripristino di L token è esattamente `pre`. -/
theorem gen0_resume_full (pre new : List Nat) :
lcp (pre ++ new) pre = pre.length ∧ tk pre.length (pre ++ new) = pre :=
⟨lcp_append_self pre new, tk_append_len pre new⟩
end AutoCkpt
-- Audit kernel: nessun `sorryAx` = nessuna prova ammessa/non verificata.
#print axioms AutoCkpt.lcp_sound
#print axioms AutoCkpt.lcp_le_of_take_ne
#print axioms AutoCkpt.gen0_resume_full