memory: share the zstd JSONL storage layer across the levels #107
No files matched your search
+7
-23
@@ -19,8 +19,6 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -36,6 +34,7 @@ use crate::llm::ChatBackend;
|
||||
use crate::llm::ChatMessage;
|
||||
use crate::memory::claim;
|
||||
use crate::memory::l4::L4uClaim;
|
||||
use crate::memory::store;
|
||||
use crate::tools::ToolContext;
|
||||
use crate::tools::ToolRegistry;
|
||||
|
||||
@@ -115,27 +114,12 @@ fn parse_l4u_filename(name: &str) -> Option<PeriodSpan> {
|
||||
}
|
||||
|
||||
fn load_l4u_file(path: &Path) -> Result<Vec<L4uClaim>> {
|
||||
let f = File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
|
||||
let mut dec = zstd::Decoder::new(f)
|
||||
.with_context(|| format!("Failed to init zstd decoder for {}", path.display()))?;
|
||||
let mut text = String::new();
|
||||
dec.read_to_string(&mut text)
|
||||
.with_context(|| format!("Failed to read {}", path.display()))?;
|
||||
|
||||
let mut claims = Vec::new();
|
||||
for raw in text.lines() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match serde_json::from_str::<L4uClaim>(line) {
|
||||
Ok(c) => claims.push(c),
|
||||
Err(err) => {
|
||||
warn!(source = %path.display(), error = %err, "Skipping malformed L4u claim line");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(claims)
|
||||
// USER.md does not cite, so the raw lines behind these claims are of no
|
||||
// interest here — unlike the levels that derive ids from them.
|
||||
Ok(store::read_claims(path)?
|
||||
.into_iter()
|
||||
.map(|(_, claim)| claim)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Render the L4u corpus as `[confidence] claim text` lines for the
|
||||
|
||||
@@ -5,9 +5,6 @@
|
||||
//! Future memory layers will own their own serialization separately.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
@@ -67,49 +64,6 @@ pub async fn extract_day(entries: &[L1Entry], backend: &dyn ChatBackend) -> Resu
|
||||
Ok(validated)
|
||||
}
|
||||
|
||||
/// Serialize claims as ZSTD-compressed JSONL at `path`, atomically.
|
||||
///
|
||||
/// Writes to `{path}.tmp` first and renames into place once the zstd stream
|
||||
/// has been finalised. Any error before the rename leaves the previous file
|
||||
/// (if any) intact, so a torn write never corrupts an on-disk L2 day.
|
||||
pub fn write_day_file(path: &Path, claims: &[L2Claim]) -> Result<()> {
|
||||
let tmp = tmp_path(path);
|
||||
// Best-effort: clear a stale tmp from a prior crash before we open it.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
let written = || -> Result<()> {
|
||||
let file =
|
||||
File::create(&tmp).with_context(|| format!("Failed to create {}", tmp.display()))?;
|
||||
let mut enc = zstd::Encoder::new(file, 0)
|
||||
.with_context(|| format!("Failed to init zstd encoder for {}", tmp.display()))?;
|
||||
for c in claims {
|
||||
let line = serde_json::to_string(c)?;
|
||||
enc.write_all(line.as_bytes())?;
|
||||
enc.write_all(b"\n")?;
|
||||
}
|
||||
enc.finish()
|
||||
.with_context(|| format!("Failed to finalize zstd stream for {}", tmp.display()))?;
|
||||
Ok(())
|
||||
}();
|
||||
|
||||
if let Err(err) = written {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
std::fs::rename(&tmp, path)
|
||||
.with_context(|| format!("Failed to rename {} -> {}", tmp.display(), path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tmp_path(target: &Path) -> std::path::PathBuf {
|
||||
let mut name = target
|
||||
.file_name()
|
||||
.map(|s| s.to_os_string())
|
||||
.unwrap_or_default();
|
||||
name.push(".tmp");
|
||||
target.with_file_name(name)
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT: &str = "\
|
||||
You are an offline memory-extraction pipeline analysing one day of chat \
|
||||
between a user and their AI assistant.
|
||||
@@ -145,7 +99,6 @@ Example output line:
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::future::Future;
|
||||
use std::io::Read;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -153,7 +106,6 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
use crate::llm::CompletionResult;
|
||||
use crate::memory::claim::Confidence;
|
||||
|
||||
struct FixedBackend {
|
||||
reply: String,
|
||||
@@ -194,90 +146,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_day_file_preserves_prior_on_no_change_after_failure() {
|
||||
// The atomic write contract: if write_day_file completes successfully,
|
||||
// the on-disk file is the new contents; the tmp sidecar is gone. Test
|
||||
// that a successful run leaves the directory clean.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("2026-05-09.jsonl.zst");
|
||||
let claims = vec![L2Claim {
|
||||
claim: "x".to_owned(),
|
||||
confidence: Confidence::High,
|
||||
sources: vec!["l1-00000-aaaaaa".to_owned()],
|
||||
}];
|
||||
write_day_file(&path, &claims).unwrap();
|
||||
assert!(path.exists());
|
||||
let tmp_sidecar = path.with_file_name("2026-05-09.jsonl.zst.tmp");
|
||||
assert!(!tmp_sidecar.exists(), "tmp sidecar must be cleaned up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_day_file_replaces_atomically() {
|
||||
// Two consecutive writes must each leave a complete file; readers
|
||||
// racing the second write must see one of the two valid payloads,
|
||||
// never a truncated stream.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("2026-05-10.jsonl.zst");
|
||||
let claims_v1 = vec![L2Claim {
|
||||
claim: "v1".to_owned(),
|
||||
confidence: Confidence::High,
|
||||
sources: vec!["l1-00000-aaaaaa".to_owned()],
|
||||
}];
|
||||
let claims_v2 = vec![L2Claim {
|
||||
claim: "v2-much-longer-claim-payload".to_owned(),
|
||||
confidence: Confidence::Medium,
|
||||
sources: vec!["l1-00001-bbbbbb".to_owned()],
|
||||
}];
|
||||
|
||||
write_day_file(&path, &claims_v1).unwrap();
|
||||
let v1_bytes = std::fs::read(&path).unwrap();
|
||||
write_day_file(&path, &claims_v2).unwrap();
|
||||
let v2_bytes = std::fs::read(&path).unwrap();
|
||||
assert_ne!(v1_bytes, v2_bytes);
|
||||
|
||||
// Decode v2 to confirm it round-trips, i.e. the rename swapped in a
|
||||
// valid zstd stream rather than appending to the previous file.
|
||||
let f = File::open(&path).unwrap();
|
||||
let mut dec = zstd::Decoder::new(f).unwrap();
|
||||
let mut text = String::new();
|
||||
dec.read_to_string(&mut text).unwrap();
|
||||
let lines: Vec<_> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 1);
|
||||
let parsed: L2Claim = serde_json::from_str(lines[0]).unwrap();
|
||||
assert_eq!(parsed.claim, "v2-much-longer-claim-payload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zstd_jsonl_roundtrip() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("2026-05-09.jsonl.zst");
|
||||
let claims = vec![
|
||||
L2Claim {
|
||||
claim: "a".to_owned(),
|
||||
confidence: Confidence::High,
|
||||
sources: vec!["l1-00000-aaaaaa".to_owned()],
|
||||
},
|
||||
L2Claim {
|
||||
claim: "b".to_owned(),
|
||||
confidence: Confidence::Low,
|
||||
sources: vec!["l1-00001-bbbbbb".to_owned()],
|
||||
},
|
||||
];
|
||||
write_day_file(&path, &claims).unwrap();
|
||||
let f = File::open(&path).unwrap();
|
||||
let mut dec = zstd::Decoder::new(f).unwrap();
|
||||
let mut text = String::new();
|
||||
dec.read_to_string(&mut text).unwrap();
|
||||
let lines: Vec<_> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 2);
|
||||
let parsed: Vec<L2Claim> = lines
|
||||
.iter()
|
||||
.map(|l| serde_json::from_str(l).unwrap())
|
||||
.collect();
|
||||
assert_eq!(parsed, claims);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extract_day_end_to_end() {
|
||||
let entries = vec![entry("l1-00000-aaaaaa"), entry("l1-00001-bbbbbb")];
|
||||
|
||||
+10
-84
@@ -9,9 +9,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -29,6 +26,7 @@ use crate::llm::ChatMessage;
|
||||
use crate::memory::claim;
|
||||
use crate::memory::claim::Claim;
|
||||
use crate::memory::l2::L2Claim;
|
||||
use crate::memory::store;
|
||||
use crate::tools::ToolContext;
|
||||
use crate::tools::ToolRegistry;
|
||||
|
||||
@@ -87,31 +85,14 @@ pub fn load_l2_corpus(input_dir: &Path) -> Result<Vec<(NaiveDate, Vec<L2Entry>)>
|
||||
}
|
||||
|
||||
fn load_day_file(date: NaiveDate, path: &Path) -> Result<Vec<L2Entry>> {
|
||||
let f = File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
|
||||
let mut dec = zstd::Decoder::new(f)
|
||||
.with_context(|| format!("Failed to init zstd decoder for {}", path.display()))?;
|
||||
let mut text = String::new();
|
||||
dec.read_to_string(&mut text)
|
||||
.with_context(|| format!("Failed to read {}", path.display()))?;
|
||||
|
||||
let mut entries = Vec::new();
|
||||
for raw in text.lines() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let claim: L2Claim = match serde_json::from_str(line) {
|
||||
Ok(c) => c,
|
||||
Err(err) => {
|
||||
warn!(source = %path.display(), error = %err, "Skipping malformed L2 claim line");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let index = entries.len();
|
||||
let id = compute_l2_id(date, index, line);
|
||||
entries.push(L2Entry { id, claim });
|
||||
}
|
||||
Ok(entries)
|
||||
Ok(store::read_claims(path)?
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, (raw_line, claim))| L2Entry {
|
||||
id: compute_l2_id(date, index, &raw_line),
|
||||
claim,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn compute_l2_id(date: NaiveDate, index: usize, raw_line: &str) -> String {
|
||||
@@ -193,22 +174,6 @@ pub async fn extract(
|
||||
Ok(claim::validate_sources(parsed, &valid_ids, "L3u"))
|
||||
}
|
||||
|
||||
/// Serialize claims as ZSTD-compressed JSONL at `path`.
|
||||
pub fn write_output_file(path: &Path, claims: &[L3uClaim]) -> Result<()> {
|
||||
let file =
|
||||
File::create(path).with_context(|| format!("Failed to create {}", path.display()))?;
|
||||
let mut enc = zstd::Encoder::new(file, 0)
|
||||
.with_context(|| format!("Failed to init zstd encoder for {}", path.display()))?;
|
||||
for c in claims {
|
||||
let line = serde_json::to_string(c)?;
|
||||
enc.write_all(line.as_bytes())?;
|
||||
enc.write_all(b"\n")?;
|
||||
}
|
||||
enc.finish()
|
||||
.with_context(|| format!("Failed to finalize zstd stream for {}", path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT: &str = "\
|
||||
You are a memory consolidation agent building a long-term model of a \
|
||||
specific user from summarised conversation logs.
|
||||
@@ -300,14 +265,7 @@ mod tests {
|
||||
|
||||
fn write_l2_day(dir: &Path, date: NaiveDate, claims: &[L2Claim]) {
|
||||
let path = dir.join(format!("{date}.jsonl.zst"));
|
||||
let f = File::create(&path).unwrap();
|
||||
let mut enc = zstd::Encoder::new(f, 0).unwrap();
|
||||
for c in claims {
|
||||
let line = serde_json::to_string(c).unwrap();
|
||||
enc.write_all(line.as_bytes()).unwrap();
|
||||
enc.write_all(b"\n").unwrap();
|
||||
}
|
||||
enc.finish().unwrap();
|
||||
store::write_claims(&path, claims).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -360,38 +318,6 @@ mod tests {
|
||||
assert!(rendered.contains("l2-20260509-000-aaaaaa [high] user lives in London"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zstd_jsonl_roundtrip() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("l3u-2026-04-01-2026-05-09.jsonl.zst");
|
||||
let claims = vec![
|
||||
L3uClaim {
|
||||
claim: "user lives in London".to_owned(),
|
||||
confidence: Confidence::High,
|
||||
sources: vec!["l2-20260509-000-aaaaaa".to_owned()],
|
||||
},
|
||||
L3uClaim {
|
||||
claim: "user supervises CS students at Cambridge".to_owned(),
|
||||
confidence: Confidence::Medium,
|
||||
sources: vec![
|
||||
"l2-20260427-000-bbbbbb".to_owned(),
|
||||
"l2-20260504-001-cccccc".to_owned(),
|
||||
],
|
||||
},
|
||||
];
|
||||
write_output_file(&path, &claims).unwrap();
|
||||
|
||||
let f = File::open(&path).unwrap();
|
||||
let mut dec = zstd::Decoder::new(f).unwrap();
|
||||
let mut text = String::new();
|
||||
dec.read_to_string(&mut text).unwrap();
|
||||
let parsed: Vec<L3uClaim> = text
|
||||
.lines()
|
||||
.map(|l| serde_json::from_str(l).unwrap())
|
||||
.collect();
|
||||
assert_eq!(parsed, claims);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extract_end_to_end() {
|
||||
let entries = vec![(
|
||||
|
||||
+11
-85
@@ -13,9 +13,6 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -33,6 +30,7 @@ use crate::llm::ChatMessage;
|
||||
use crate::memory::claim;
|
||||
use crate::memory::claim::Claim;
|
||||
use crate::memory::l3::L3uClaim;
|
||||
use crate::memory::store;
|
||||
use crate::tools::ToolContext;
|
||||
use crate::tools::ToolRegistry;
|
||||
|
||||
@@ -119,31 +117,14 @@ fn parse_period_from_filename(name: &str) -> Option<PeriodTag> {
|
||||
}
|
||||
|
||||
fn load_period_file(period: &PeriodTag, path: &Path) -> Result<Vec<L3uEntry>> {
|
||||
let f = File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
|
||||
let mut dec = zstd::Decoder::new(f)
|
||||
.with_context(|| format!("Failed to init zstd decoder for {}", path.display()))?;
|
||||
let mut text = String::new();
|
||||
dec.read_to_string(&mut text)
|
||||
.with_context(|| format!("Failed to read {}", path.display()))?;
|
||||
|
||||
let mut entries = Vec::new();
|
||||
for raw in text.lines() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let claim: L3uClaim = match serde_json::from_str(line) {
|
||||
Ok(c) => c,
|
||||
Err(err) => {
|
||||
warn!(source = %path.display(), error = %err, "Skipping malformed L3u claim line");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let index = entries.len();
|
||||
let id = compute_l3u_id(period, index, line);
|
||||
entries.push(L3uEntry { id, claim });
|
||||
}
|
||||
Ok(entries)
|
||||
Ok(store::read_claims(path)?
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, (raw_line, claim))| L3uEntry {
|
||||
id: compute_l3u_id(period, index, &raw_line),
|
||||
claim,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn compute_l3u_id(period: &PeriodTag, index: usize, raw_line: &str) -> String {
|
||||
@@ -233,22 +214,6 @@ pub async fn extract(
|
||||
Ok(claim::validate_sources(parsed, &valid_ids, "L4u"))
|
||||
}
|
||||
|
||||
/// Serialize claims as ZSTD-compressed JSONL at `path`.
|
||||
pub fn write_output_file(path: &Path, claims: &[L4uClaim]) -> Result<()> {
|
||||
let file =
|
||||
File::create(path).with_context(|| format!("Failed to create {}", path.display()))?;
|
||||
let mut enc = zstd::Encoder::new(file, 0)
|
||||
.with_context(|| format!("Failed to init zstd encoder for {}", path.display()))?;
|
||||
for c in claims {
|
||||
let line = serde_json::to_string(c)?;
|
||||
enc.write_all(line.as_bytes())?;
|
||||
enc.write_all(b"\n")?;
|
||||
}
|
||||
enc.finish()
|
||||
.with_context(|| format!("Failed to finalize zstd stream for {}", path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT: &str = "\
|
||||
You are a memory consolidation agent producing the user's *current* model \
|
||||
from a chronological series of consolidated period summaries (L3u files).
|
||||
@@ -353,14 +318,7 @@ mod tests {
|
||||
|
||||
fn write_l3u_period(dir: &Path, p: PeriodTag, claims: &[L3uClaim]) {
|
||||
let path = dir.join(format!("l3u-{}-{}.jsonl.zst", p.first, p.last));
|
||||
let f = File::create(&path).unwrap();
|
||||
let mut enc = zstd::Encoder::new(f, 0).unwrap();
|
||||
for c in claims {
|
||||
let line = serde_json::to_string(c).unwrap();
|
||||
enc.write_all(line.as_bytes()).unwrap();
|
||||
enc.write_all(b"\n").unwrap();
|
||||
}
|
||||
enc.finish().unwrap();
|
||||
store::write_claims(&path, claims).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -419,7 +377,7 @@ mod tests {
|
||||
let p = period(day(2026, 2, 24), day(2026, 5, 14));
|
||||
write_l3u_period(tmp.path(), p, &[l3u_claim("alpha")]);
|
||||
// Drop an l4u-named file in the same dir — must be ignored.
|
||||
File::create(tmp.path().join("l4u-2026-02-24-2026-05-14.jsonl.zst")).unwrap();
|
||||
std::fs::File::create(tmp.path().join("l4u-2026-02-24-2026-05-14.jsonl.zst")).unwrap();
|
||||
|
||||
let corpus = load_l3u_corpus(tmp.path()).unwrap();
|
||||
assert_eq!(corpus.len(), 1);
|
||||
@@ -445,38 +403,6 @@ mod tests {
|
||||
assert!(rendered.contains("l3u-20260224-20260514-000-aaaaaa [high] user lives in London"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zstd_jsonl_roundtrip() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("l4u-2025-12-01-2026-05-14.jsonl.zst");
|
||||
let claims = vec![
|
||||
L4uClaim {
|
||||
claim: "user lives in London".to_owned(),
|
||||
confidence: Confidence::High,
|
||||
sources: vec!["l3u-20260224-20260514-000-aaaaaa".to_owned()],
|
||||
},
|
||||
L4uClaim {
|
||||
claim: "user supervises CS students at Cambridge".to_owned(),
|
||||
confidence: Confidence::Medium,
|
||||
sources: vec![
|
||||
"l3u-20251201-20260223-000-bbbbbb".to_owned(),
|
||||
"l3u-20260224-20260514-001-cccccc".to_owned(),
|
||||
],
|
||||
},
|
||||
];
|
||||
write_output_file(&path, &claims).unwrap();
|
||||
|
||||
let f = File::open(&path).unwrap();
|
||||
let mut dec = zstd::Decoder::new(f).unwrap();
|
||||
let mut text = String::new();
|
||||
dec.read_to_string(&mut text).unwrap();
|
||||
let parsed: Vec<L4uClaim> = text
|
||||
.lines()
|
||||
.map(|l| serde_json::from_str(l).unwrap())
|
||||
.collect();
|
||||
assert_eq!(parsed, claims);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extract_end_to_end() {
|
||||
let p = period(day(2026, 2, 24), day(2026, 5, 14));
|
||||
|
||||
+5
-4
@@ -35,6 +35,7 @@ pub mod l2;
|
||||
pub mod l3;
|
||||
pub mod l4;
|
||||
pub mod nightly;
|
||||
pub mod store;
|
||||
|
||||
/// Run the L1 → L2 extraction pipeline.
|
||||
///
|
||||
@@ -65,7 +66,7 @@ pub async fn run_l1_to_l2(
|
||||
let out_path: PathBuf = output_dir.join(format!("{day}.jsonl.zst"));
|
||||
match l2::extract_day(&entries, backend.as_ref()).await {
|
||||
Ok(claims) => {
|
||||
l2::write_day_file(&out_path, &claims)?;
|
||||
store::write_claims(&out_path, &claims)?;
|
||||
info!(
|
||||
day = %day,
|
||||
claims = claims.len(),
|
||||
@@ -138,7 +139,7 @@ pub async fn run_l1_to_l2_incremental(
|
||||
match extract_with_retries(&entries, backend.as_ref()).await {
|
||||
Ok(claims) => {
|
||||
let out_path: PathBuf = output_dir.join(format!("{day}.jsonl.zst"));
|
||||
if let Err(err) = l2::write_day_file(&out_path, &claims) {
|
||||
if let Err(err) = store::write_claims(&out_path, &claims) {
|
||||
error!(day = %day, error = %err, "Failed to write L2 day file");
|
||||
summary.det_failures += 1;
|
||||
continue;
|
||||
@@ -295,7 +296,7 @@ pub async fn run_l2_to_l3u(
|
||||
.with_context(|| format!("Failed to create output directory {}", output_dir.display()))?;
|
||||
|
||||
let out_path: PathBuf = output_dir.join(format!("l3u-{first}-{last}.jsonl.zst"));
|
||||
l3::write_output_file(&out_path, &claims)?;
|
||||
store::write_claims(&out_path, &claims)?;
|
||||
info!(
|
||||
claims = claims.len(),
|
||||
out = %out_path.display(),
|
||||
@@ -341,7 +342,7 @@ pub async fn run_l3u_to_l4u(
|
||||
|
||||
let out_path: PathBuf =
|
||||
output_dir.join(format!("l4u-{earliest_first}-{latest_last}.jsonl.zst"));
|
||||
l4::write_output_file(&out_path, &claims)?;
|
||||
store::write_claims(&out_path, &claims)?;
|
||||
info!(
|
||||
claims = claims.len(),
|
||||
out = %out_path.display(),
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
//! On-disk storage for claim files.
|
||||
//!
|
||||
//! Every level of the hierarchy persists the same thing: a ZSTD-compressed
|
||||
//! JSONL stream of [`Claim`]s. Only the filename convention differs, and
|
||||
//! that belongs to the level that owns it.
|
||||
//!
|
||||
//! Reads hand back the exact on-disk line alongside each claim, because
|
||||
//! the levels above derive their citation ids by hashing that line — the
|
||||
//! id must be stable against the bytes as stored, not against a
|
||||
//! re-serialisation of the parsed value.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Read as _;
|
||||
use std::io::Write as _;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::memory::claim::Claim;
|
||||
|
||||
/// Read a ZSTD-compressed JSONL claim file, returning each claim with the
|
||||
/// raw line it was parsed from. Malformed lines are skipped with a warning
|
||||
/// rather than failing the read: one bad line should not cost us the file.
|
||||
pub fn read_claims(path: &Path) -> Result<Vec<(String, Claim)>> {
|
||||
let file = File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
|
||||
let mut dec = zstd::Decoder::new(file)
|
||||
.with_context(|| format!("Failed to init zstd decoder for {}", path.display()))?;
|
||||
let mut text = String::new();
|
||||
dec.read_to_string(&mut text)
|
||||
.with_context(|| format!("Failed to read {}", path.display()))?;
|
||||
|
||||
let mut out = Vec::new();
|
||||
for raw in text.lines() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match serde_json::from_str::<Claim>(line) {
|
||||
Ok(claim) => out.push((line.to_owned(), claim)),
|
||||
Err(err) => {
|
||||
warn!(source = %path.display(), error = %err, "Skipping malformed claim line");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Serialize claims as ZSTD-compressed JSONL at `path`, atomically.
|
||||
///
|
||||
/// Writes to `{path}.tmp` first and renames into place once the zstd
|
||||
/// stream has been finalised. Any error before the rename leaves the
|
||||
/// previous file (if any) intact, so a torn write never leaves a
|
||||
/// truncated stream that would poison every subsequent read of that
|
||||
/// level.
|
||||
pub fn write_claims(path: &Path, claims: &[Claim]) -> Result<()> {
|
||||
let tmp = tmp_path(path);
|
||||
// Best-effort: clear a stale tmp from a prior crash before we open it.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
let written = || -> Result<()> {
|
||||
let file =
|
||||
File::create(&tmp).with_context(|| format!("Failed to create {}", tmp.display()))?;
|
||||
let mut enc = zstd::Encoder::new(file, 0)
|
||||
.with_context(|| format!("Failed to init zstd encoder for {}", tmp.display()))?;
|
||||
for c in claims {
|
||||
let line = serde_json::to_string(c)?;
|
||||
enc.write_all(line.as_bytes())?;
|
||||
enc.write_all(b"\n")?;
|
||||
}
|
||||
enc.finish()
|
||||
.with_context(|| format!("Failed to finalize zstd stream for {}", tmp.display()))?;
|
||||
Ok(())
|
||||
}();
|
||||
|
||||
if let Err(err) = written {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
std::fs::rename(&tmp, path)
|
||||
.with_context(|| format!("Failed to rename {} -> {}", tmp.display(), path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tmp_path(target: &Path) -> PathBuf {
|
||||
let mut name = target
|
||||
.file_name()
|
||||
.map(|s| s.to_os_string())
|
||||
.unwrap_or_default();
|
||||
name.push(".tmp");
|
||||
target.with_file_name(name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory::claim::Confidence;
|
||||
|
||||
fn claim(text: &str) -> Claim {
|
||||
Claim {
|
||||
claim: text.to_owned(),
|
||||
confidence: Confidence::High,
|
||||
sources: vec!["l1-00000-aaaaaa".to_owned()],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrips_claims() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("day.jsonl.zst");
|
||||
let claims = vec![claim("alpha"), claim("beta")];
|
||||
write_claims(&path, &claims).unwrap();
|
||||
|
||||
let read = read_claims(&path).unwrap();
|
||||
assert_eq!(read.len(), 2);
|
||||
assert_eq!(
|
||||
read.iter().map(|(_, c)| c.clone()).collect::<Vec<_>>(),
|
||||
claims
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_returns_the_raw_line_verbatim() {
|
||||
// Citation ids are hashes of this string, so it must be the bytes as
|
||||
// stored rather than a re-serialisation of the parsed claim.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("day.jsonl.zst");
|
||||
write_claims(&path, &[claim("alpha")]).unwrap();
|
||||
|
||||
let read = read_claims(&path).unwrap();
|
||||
let (raw, parsed) = &read[0];
|
||||
assert_eq!(*raw, serde_json::to_string(parsed).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_skips_malformed_lines() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("day.jsonl.zst");
|
||||
let file = File::create(&path).unwrap();
|
||||
let mut enc = zstd::Encoder::new(file, 0).unwrap();
|
||||
enc.write_all(b"not json\n").unwrap();
|
||||
enc.write_all(serde_json::to_string(&claim("good")).unwrap().as_bytes())
|
||||
.unwrap();
|
||||
enc.write_all(b"\n\n").unwrap();
|
||||
enc.finish().unwrap();
|
||||
|
||||
let read = read_claims(&path).unwrap();
|
||||
assert_eq!(read.len(), 1);
|
||||
assert_eq!(read[0].1.claim, "good");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_replaces_atomically_and_leaves_no_tmp() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("day.jsonl.zst");
|
||||
write_claims(&path, &[claim("first")]).unwrap();
|
||||
write_claims(&path, &[claim("second")]).unwrap();
|
||||
|
||||
let read = read_claims(&path).unwrap();
|
||||
assert_eq!(read.len(), 1);
|
||||
assert_eq!(read[0].1.claim, "second");
|
||||
assert!(!tmp_path(&path).exists(), "tmp sidecar should be gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_preserves_prior_file_when_the_target_dir_is_gone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("nested").join("day.jsonl.zst");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
write_claims(&path, &[claim("first")]).unwrap();
|
||||
|
||||
// A write that cannot even create its tmp file must not disturb the
|
||||
// file already in place.
|
||||
let bad = dir
|
||||
.path()
|
||||
.join("nested")
|
||||
.join("missing")
|
||||
.join("x.jsonl.zst");
|
||||
assert!(write_claims(&bad, &[claim("second")]).is_err());
|
||||
|
||||
let read = read_claims(&path).unwrap();
|
||||
assert_eq!(read[0].1.claim, "first");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user