Skip to main content

ledger_engine/
cold.rs

1//! Cold history: ASTJ5 / JC05 segments, canonical profile (codec in the
2//! `astj5` crate). For deep, closed history; the hot format (module
3//! `history`) and the API stay the same.
4//!
5//! A segment whose first ledger is F is four files in one directory:
6//! - `cold-F.astj`: an ASTJ5 archive of independent blocks of at most 1024 ledgers
7//!   or 4 MiB of exact bytes (`BLOCK_RAW`); each block has a SHA-512Half of its exact bytes;
8//! - `cold-F.asix`: only in segments written before 0.3, the codec's four
9//!   ASIX2 indexes (transaction and ledger by hash, account history, object
10//!   history). Nothing reads them: lookups go through the partition indexes
11//!   (`coldindex`). `ColdSegment::drop_index` removes them;
12//! - `cold-F.kinds`: the kind of every state change (`XWCK\0\1`);
13//! - `cold-F.seal`: optional, digests of every block's stored bytes taken
14//!   after the block passed the full check (`XWCS\0\1`, one per block, or
15//!   `XWCS\0\2`, a list per block: a JC06 block has its head and each part),
16//!   see below;
17//! - `cold-F.json`: the manifest with range, profile, change kind mode,
18//!   and size and SHA-512Half of every file. Written last, via a temporary
19//!   file and rename: without a manifest there is no segment.
20//!
21//! State patches are stored only where the metadata doesn't give them
22//! (`coldpatch`). A segment written that way has format `astraea-cold/2`, so a
23//! server that doesn't know the format refuses it; `astraea-cold/1` segments
24//! hold every patch and stay readable. Each ledger says which it is, so a segment
25//! rewritten while it is being read is read correctly from either archive.
26//!
27//! Change kinds. The codec row (`Row`) does not carry them, and they cannot be
28//! guessed from the metadata. A source with explicit kinds (the node's gRPC) uses
29//! mode `explicit`: kinds are stored as a separate stream and count toward the size.
30//! The XRPLA publication does not distinguish them, so it uses mode `not_recorded`:
31//! such a segment serves transactions, and a request for a ledger with changes
32//! gets an error rather than a guess.
33//!
34//! Reading goes through the codec's pool of prepared blocks (`astj5::pool`): before
35//! a block enters the cache, its SHA-512Half, the transaction roots and the
36//! header chain are checked. The check costs as much as preparing the block,
37//! so it runs once, when the segment is written (or by `write_seal` for older
38//! segments), and the seal keeps the result: a block whose stored bytes match
39//! its digest is prepared without repeating it. A block that doesn't match, or
40//! a segment without a seal, is checked in full on every load. The seal is not
41//! in the manifest; a damaged one only costs speed. A segment's cache holds up to
42//! `BLOCK_BUDGET` bytes of blocks, different blocks are prepared in parallel (at
43//! most `PREPARES` at once), and a block wanted by concurrent requests is
44//! prepared only once. The cache as a whole holds `COLD_BUDGET` bytes: past
45//! that, and past `COLD_OPEN` open segments, the least recently read segments
46//! are closed. A request for
47//! many ledgers at once (`Cold::ledgers`) reads them block by block on up to
48//! `COLD_READERS` threads.
49
50use std::collections::{BTreeMap, HashMap, VecDeque};
51use std::fs::{self, File};
52use std::io::Write;
53use std::path::{Path, PathBuf};
54use std::sync::{Arc, Mutex};
55
56use astraea_journal_codec::{Options, Row, pack_bounded, pool::Pool, unpack};
57use serde_json::{Value, json};
58use witness_core::ledger::LedgerHeader;
59use witness_core::sha512_half;
60
61use crate::coldpatch;
62use crate::ledger::{Change, Ledger, StateChange};
63
64type Res<T> = Result<T, String>;
65
66const KINDS_MAGIC: &[u8; 6] = b"XWCK\x00\x01";
67const SEAL_MAGIC: &[u8; 6] = b"XWCS\x00\x01";
68const SEAL_LISTS: &[u8; 6] = b"XWCS\x00\x02";
69/// The manifest format segments are written in, and the older one with every patch.
70const FORMAT: &str = "astraea-cold/2";
71const FORMAT_ALL_PATCHES: &str = "astraea-cold/1";
72/// Default archive block: at most this many ledgers and exact bytes.
73/// The research's canonical profile uses 16 MiB. 4 MiB costs +18.7% in size
74/// at the 104 million epoch and +26% on recent history, but a cold read takes
75/// 24 ms instead of 118.
76/// A ledger larger than the limit gets a block sized to fit it (`write_with`).
77pub const BLOCK_LEDGERS: usize = 1024;
78pub const BLOCK_RAW: usize = 4 << 20;
79/// Blocks are written as JC06: cut into parts of whole ledgers and at most
80/// this many exact bytes, each decoded on its own. Reading one transaction
81/// then costs one part instead of the whole block.
82pub const PART_RAW: usize = 1 << 20;
83
84/// Archive block limit: ledgers and exact bytes, and the part size (0 writes
85/// JC05 blocks, decoded whole).
86#[derive(Debug, Clone, Copy)]
87pub struct BlockLimit {
88    pub ledgers: usize,
89    pub raw: usize,
90    pub part: usize,
91}
92
93impl Default for BlockLimit {
94    fn default() -> Self {
95        BlockLimit {
96            ledgers: BLOCK_LEDGERS,
97            raw: BLOCK_RAW,
98            part: PART_RAW,
99        }
100    }
101}
102/// Maximum number of cold segments open at once. One account_tx page over
103/// full history touches many segments; with too few open they are closed
104/// and reopened on every request. An open segment without cached blocks
105/// costs little.
106pub const COLD_OPEN: usize = 64;
107/// Byte budget for the prepared blocks of all open segments (codec estimate).
108/// Shared rather than split per segment: a busy account's page can hold about
109/// 400 MB of one segment's blocks, while most open segments hold one or two.
110pub const COLD_BUDGET: usize = 4 << 30;
111/// Most of the cold cache one segment may hold, and the number of concurrent
112/// prepares per segment. A block takes about 10 ms to prepare, and one
113/// account_tx page can need dozens of blocks from a single segment, so a
114/// segment prepares as many at once as one request reads in parallel. Below
115/// what one page needs, a page evicts its own blocks and reading it again costs
116/// as much as the first time.
117pub const BLOCK_BUDGET: usize = 1 << 30;
118pub const PREPARES: usize = COLD_READERS;
119/// Threads one `Cold::ledgers` call reads with.
120pub const COLD_READERS: usize = 8;
121/// Maximum change kinds in a segment: checked before allocating memory.
122const MAX_CHANGES: u64 = 1 << 32;
123
124fn io(e: std::io::Error) -> String {
125    e.to_string()
126}
127
128fn corrupt(what: impl std::fmt::Display) -> String {
129    format!("corrupt_history: cold segment: {what}")
130}
131
132/// The canonical profile, as in the research's `jointbench encode … canonical`,
133/// not `Options::default()`.
134pub fn canonical() -> Options {
135    Options {
136        joint: true,
137        adaptive: true,
138        chronological: true,
139        hash_order: true,
140        cached_slots: true,
141        recent: false,
142        split_shapes: true,
143        context_delta: true,
144        ..Options::default()
145    }
146}
147
148/// Where change kinds come from.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub enum Kinds {
151    Explicit,
152    NotRecorded,
153}
154
155impl Kinds {
156    fn name(self) -> &'static str {
157        match self {
158            Kinds::Explicit => "explicit",
159            Kinds::NotRecorded => "not_recorded",
160        }
161    }
162}
163
164/// Codec row from a ledger: changes as key and data (empty for a deleted object).
165pub fn row_of(l: &Ledger) -> Res<Row> {
166    Ok(Row {
167        seq: l.header()?.sequence,
168        header: l.header.clone(),
169        txs: l.transactions.clone(),
170        patches: l.changes.iter().map(|c| (c.key, c.data.clone())).collect(),
171    })
172}
173
174/// Kinds stream: `XWCK\0\1`, mode (1 is explicit, 0 means the source does not
175/// distinguish), u32 ledger count, then zstd of (each ledger's change count as a
176/// varint, then one kind byte per change, explicit mode only).
177fn kinds_bytes(ledgers: &[Ledger], mode: Kinds) -> Res<Vec<u8>> {
178    let mut body = Vec::new();
179    for l in ledgers {
180        crate::varint::put(&mut body, l.changes.len() as u64);
181    }
182    for l in ledgers {
183        for c in &l.changes {
184            if (c.change == Change::Deleted) != c.data.is_empty() {
185                return Err(format!(
186                    "ledger {}: change kind {:?} does not match the data of object {}",
187                    l.header()?.sequence,
188                    c.change,
189                    hex::encode_upper(c.key)
190                ));
191            }
192            if mode == Kinds::Explicit {
193                body.push(c.change as u8);
194            }
195        }
196    }
197    let mut out = KINDS_MAGIC.to_vec();
198    out.push(u8::from(mode == Kinds::Explicit));
199    out.extend((ledgers.len() as u32).to_le_bytes());
200    out.extend(zstd::bulk::compress(&body, 19).map_err(io)?);
201    Ok(out)
202}
203
204/// Parsed kinds stream: where each ledger starts in the stream, and the kinds.
205#[derive(Debug)]
206struct KindsIndex {
207    mode: Kinds,
208    starts: Vec<u64>,
209    kinds: Vec<u8>,
210}
211
212fn parse_kinds(b: &[u8], ledgers: usize) -> Res<KindsIndex> {
213    if b.get(..6) != Some(KINDS_MAGIC.as_slice()) || b.len() < 11 {
214        return Err(corrupt("change kinds stream: not XWCK"));
215    }
216    let mode = match b[6] {
217        1 => Kinds::Explicit,
218        0 => Kinds::NotRecorded,
219        _ => return Err(corrupt("kinds stream: mode")),
220    };
221    let n = u32::from_le_bytes([b[7], b[8], b[9], b[10]]) as usize;
222    if n != ledgers {
223        return Err(corrupt("kinds stream: ledger count"));
224    }
225    // Decompression limit, set before allocating: a varint per ledger and a byte per change.
226    let cap = ledgers
227        .checked_mul(10)
228        .and_then(|x| x.checked_add(MAX_CHANGES as usize))
229        .ok_or_else(|| corrupt("kinds stream: size"))?;
230    let body = zstd::bulk::decompress(&b[11..], cap.min(1 << 31)).map_err(corrupt)?;
231    let mut at = 0;
232    let mut starts = Vec::with_capacity(ledgers + 1);
233    let mut total = 0u64;
234    starts.push(0);
235    for _ in 0..ledgers {
236        total = total
237            .checked_add(crate::varint::get(&body, &mut at).map_err(corrupt)?)
238            .filter(|t| *t <= MAX_CHANGES)
239            .ok_or_else(|| corrupt("kinds stream: too many changes"))?;
240        starts.push(total);
241    }
242    let kinds = body[at..].to_vec();
243    let want = if mode == Kinds::Explicit {
244        total as usize
245    } else {
246        0
247    };
248    if kinds.len() != want || kinds.iter().any(|k| Change::from_u8(*k).is_none()) {
249        return Err(corrupt("kinds stream: length or value"));
250    }
251    Ok(KindsIndex {
252        mode,
253        starts,
254        kinds,
255    })
256}
257
258pub(crate) fn sync_write(path: &Path, bytes: &[u8]) -> Res<()> {
259    let tmp = path.with_extension(format!(
260        "{}.tmp",
261        path.extension().and_then(|e| e.to_str()).unwrap_or("")
262    ));
263    let mut f = File::create(&tmp).map_err(io)?;
264    f.write_all(bytes).map_err(io)?;
265    f.sync_all().map_err(io)?;
266    fs::rename(&tmp, path).map_err(io)
267}
268
269/// Seal file: `XWCS\0\1` and one digest per block when every block has one,
270/// otherwise `XWCS\0\2` and, per block, a u32 count and its digests.
271fn seal_bytes(seal: &[Vec<[u8; 32]>]) -> Vec<u8> {
272    let lists = seal.iter().any(|d| d.len() != 1);
273    let mut out = if lists { SEAL_LISTS } else { SEAL_MAGIC }.to_vec();
274    out.extend((seal.len() as u32).to_le_bytes());
275    for d in seal {
276        if lists {
277            out.extend((d.len() as u32).to_le_bytes());
278        }
279        for x in d {
280            out.extend(x);
281        }
282    }
283    out
284}
285
286fn parse_seal(b: &[u8]) -> Option<Vec<Vec<[u8; 32]>>> {
287    let u32_at = |b: &[u8]| Some(u32::from_le_bytes(b.get(..4)?.try_into().ok()?) as usize);
288    if let Some(rest) = b.strip_prefix(SEAL_MAGIC) {
289        let n = u32_at(rest)?;
290        let body = &rest[4..];
291        if body.len() != n.checked_mul(32)? {
292            return None;
293        }
294        return Some(body.as_chunks::<32>().0.iter().map(|d| vec![*d]).collect());
295    }
296    let rest = b.strip_prefix(SEAL_LISTS)?;
297    let n = u32_at(rest)?;
298    let mut at = 4;
299    let mut out = Vec::with_capacity(n.min(rest.len() / 36));
300    for _ in 0..n {
301        let k = u32_at(rest.get(at..)?)?;
302        at += 4;
303        let body = rest.get(at..at.checked_add(k.checked_mul(32)?)?)?;
304        out.push(body.as_chunks::<32>().0.to_vec());
305        at += body.len();
306    }
307    (at == rest.len()).then_some(out)
308}
309
310/// The data files a manifest lists, by their position in `names`: the
311/// archive and the kinds, and the ASIX2 indexes of an older segment.
312fn listed(m: &Value) -> Vec<(usize, &'static str)> {
313    let mut v = vec![(0, "astj"), (2, "kinds")];
314    if m["files"].get("asix").is_some() {
315        v.push((1, "asix"));
316    }
317    v
318}
319
320fn names(dir: &Path, first: u32) -> [PathBuf; 4] {
321    ["astj", "asix", "kinds", "json"].map(|e| dir.join(format!("cold-{first:010}.{e}")))
322}
323
324/// Removes a file, and its target if it is a link (published segments are
325/// links into the loader's directory). A missing file is not an error.
326fn remove_with_link(p: &Path) -> Res<()> {
327    if let Ok(real) = fs::canonicalize(p)
328        && real != p
329    {
330        fs::remove_file(&real).map_err(io)?;
331    }
332    match fs::remove_file(p) {
333        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(io(e)),
334        _ => Ok(()),
335    }
336}
337
338/// Exact bytes of a row in a block (as the codec counts them when cutting blocks).
339fn row_raw(r: &Row) -> usize {
340    20 + r.header.len()
341        + r.txs
342            .iter()
343            .map(|(t, m)| 8 + t.len() + m.len())
344            .sum::<usize>()
345        + r.patches.iter().map(|(_, v)| 36 + v.len()).sum::<usize>()
346}
347
348/// Writes a segment from consecutive ledgers and publishes it with a manifest.
349/// Before writing, the archive is unpacked again and compared with the rows,
350/// the indexes are checked by re-encoding the decoded form, and the kinds by
351/// parsing. Returns the manifest.
352pub fn write(dir: &Path, ledgers: &[Ledger], mode: Kinds) -> Res<Value> {
353    write_with(dir, ledgers, mode, BlockLimit::default())
354}
355
356/// `write` with a different block limit.
357pub fn write_with(dir: &Path, ledgers: &[Ledger], mode: Kinds, limit: BlockLimit) -> Res<Value> {
358    let first = ledgers.first().ok_or("empty range")?.header()?.sequence;
359    let mut rows = ledgers.iter().map(row_of).collect::<Res<Vec<_>>>()?;
360    for (k, r) in rows.iter().enumerate() {
361        if r.seq != first + k as u32 {
362            return Err(format!(
363                "ledgers out of sequence: at position {k} found {}",
364                r.seq
365            ));
366        }
367    }
368    let last = first + rows.len() as u32 - 1;
369    let changes: usize = rows.iter().map(|r| r.patches.len()).sum();
370    for r in &mut rows {
371        r.patches = coldpatch::compact(r);
372    }
373    // A ledger larger than the limit (some exceed 4 MiB) is not split: for such a
374    // segment the limit is raised to its size; other segments are unaffected.
375    let raw = rows.iter().map(row_raw).max().unwrap_or(0) + 4;
376    let limit = BlockLimit {
377        raw: limit.raw.max(raw),
378        ..limit
379    };
380    let opt = Options {
381        part_raw: limit.part,
382        ..canonical()
383    };
384    let (archive, _) = pack_bounded(&rows, limit.ledgers, limit.raw, opt)?;
385    if unpack(&archive)? != rows {
386        return Err("ASTJ5 archive did not restore the ledgers exactly".into());
387    }
388    let kinds = kinds_bytes(ledgers, mode)?;
389    let k = parse_kinds(&kinds, rows.len())?;
390    if mode == Kinds::Explicit {
391        let all: Vec<u8> = ledgers
392            .iter()
393            .flat_map(|l| l.changes.iter().map(|c| c.change as u8))
394            .collect();
395        if k.kinds != all {
396            return Err("kinds stream did not round-trip".into());
397        }
398    }
399    let [pa, _, pk, pm] = names(dir, first);
400    let file =
401        |b: &[u8]| json!({"bytes": b.len(), "sha512half": hex::encode_upper(sha512_half(b))});
402    let manifest = json!({
403        "format": FORMAT,
404        "payload": if limit.part > 0 { "ASTJ6" } else { "ASTJ5" },
405        "profile": "canonical",
406        "codec": "astraea-journal-codec 0.1.0 (astraea-journal-sequential-2026-10-27)",
407        "first": first,
408        "last": last,
409        "ledgers": rows.len(),
410        "transactions": rows.iter().map(|r| r.txs.len()).sum::<usize>(),
411        "changes": changes,
412        "blocks": u32::from_le_bytes(archive[8..12].try_into().map_err(|_| "archive header")?),
413        "max_block_ledgers": limit.ledgers,
414        "max_block_raw_bytes": limit.raw,
415        "max_part_raw_bytes": limit.part,
416        "change_kinds": mode.name(),
417        "files": {
418            "astj": file(&archive),
419            "kinds": file(&kinds),
420        },
421    });
422    fs::create_dir_all(dir).map_err(io)?;
423    sync_write(&pa, &archive)?;
424    sync_write(&pk, &kinds)?;
425    // The full check of every block, once; readers then trust the seal.
426    let seal = Pool::open(&pa, 0, 1)
427        .and_then(|p| p.seal(COLD_READERS))
428        .map_err(corrupt)?;
429    sync_write(&pa.with_extension("seal"), &seal_bytes(&seal))?;
430    let m = serde_json::to_vec_pretty(&manifest).map_err(|e| e.to_string())?;
431    sync_write(&pm, &m)?;
432    File::open(dir).and_then(|d| d.sync_all()).map_err(io)?;
433    Ok(manifest)
434}
435
436/// An open segment: the block pool and change kinds.
437struct Open {
438    pool: Pool,
439    kinds: KindsIndex,
440}
441
442impl std::fmt::Debug for Open {
443    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
444        f.debug_struct("Open").finish_non_exhaustive()
445    }
446}
447
448/// A published cold segment. Files are opened on the first read.
449#[derive(Debug)]
450pub struct ColdSegment {
451    pub first: u32,
452    pub last: u32,
453    pub kinds: Kinds,
454    pub manifest: Value,
455    paths: [PathBuf; 4],
456    open: Mutex<Option<Arc<Open>>>,
457    budget: std::sync::atomic::AtomicUsize,
458}
459
460impl ColdSegment {
461    /// Segments in a directory from their manifests, by ascending first ledger;
462    /// overlapping segments are an error.
463    pub fn scan(dir: &Path) -> Res<Vec<Arc<ColdSegment>>> {
464        ColdSegment::scan_with(dir, &[])
465    }
466
467    /// Like `scan`, but segments from `prev` (matched by first ledger) are taken
468    /// as is, without reading the manifest.
469    fn scan_with(dir: &Path, prev: &[Arc<ColdSegment>]) -> Res<Vec<Arc<ColdSegment>>> {
470        let mut out = Vec::new();
471        let Ok(entries) = fs::read_dir(dir) else {
472            return Ok(out);
473        };
474        for e in entries {
475            let p = e.map_err(io)?.path();
476            let name = p
477                .file_name()
478                .map(|n| n.to_string_lossy().into_owned())
479                .unwrap_or_default();
480            if !(name.starts_with("cold-") && name.ends_with(".json")) {
481                continue;
482            }
483            let known = name["cold-".len()..name.len() - ".json".len()]
484                .parse::<u32>()
485                .ok()
486                .and_then(|f| prev.iter().find(|x| x.first == f));
487            if let Some(x) = known {
488                out.push(x.clone());
489                continue;
490            }
491            let m: Value = serde_json::from_slice(&fs::read(&p).map_err(io)?).map_err(corrupt)?;
492            if ![FORMAT, FORMAT_ALL_PATCHES]
493                .map(Value::from)
494                .contains(&m["format"])
495                || !["ASTJ5", "ASTJ6"].map(Value::from).contains(&m["payload"])
496            {
497                return Err(corrupt(format!("{name}: unknown format")));
498            }
499            let num = |k: &str| m[k].as_u64().and_then(|v| u32::try_from(v).ok());
500            let (Some(first), Some(last)) = (num("first"), num("last")) else {
501                return Err(corrupt(format!("{name}: range")));
502            };
503            let kinds = match m["change_kinds"].as_str() {
504                Some("explicit") => Kinds::Explicit,
505                Some("not_recorded") => Kinds::NotRecorded,
506                _ => return Err(corrupt(format!("{name}: kinds mode"))),
507            };
508            let paths = names(dir, first);
509            for (i, k) in listed(&m) {
510                let len = fs::metadata(&paths[i]).map_err(io)?.len();
511                if Some(len) != m["files"][k]["bytes"].as_u64() {
512                    return Err(corrupt(format!("{name}: wrong size of file {k}")));
513                }
514            }
515            out.push(Arc::new(ColdSegment {
516                first,
517                last,
518                kinds,
519                manifest: m,
520                paths,
521                open: Mutex::new(None),
522                budget: std::sync::atomic::AtomicUsize::new(BLOCK_BUDGET),
523            }));
524        }
525        out.sort_by_key(|s| s.first);
526        if out.windows(2).any(|w| w[1].first <= w[0].last) {
527            return Err(corrupt("segments overlap"));
528        }
529        Ok(out)
530    }
531
532    /// SHA-512Half of all files, checked against the manifest. Expensive on large
533    /// segments, so it runs during verification, not on every open.
534    pub fn verify_files(&self) -> Res<()> {
535        for (i, k) in listed(&self.manifest) {
536            let b = fs::read(&self.paths[i]).map_err(io)?;
537            if Some(hex::encode_upper(sha512_half(&b)).as_str())
538                != self.manifest["files"][k]["sha512half"].as_str()
539            {
540                return Err(corrupt(format!(
541                    "cold-{}.{k}: hash does not match the manifest",
542                    self.first
543                )));
544            }
545        }
546        Ok(())
547    }
548
549    fn lock(&self) -> std::sync::MutexGuard<'_, Option<Arc<Open>>> {
550        self.open.lock().unwrap_or_else(|p| p.into_inner())
551    }
552
553    pub fn is_open(&self) -> bool {
554        self.lock().is_some()
555    }
556
557    fn seal_path(&self) -> PathBuf {
558        self.paths[0].with_extension("seal")
559    }
560
561    /// Whether the segment has a seal file.
562    pub fn sealed(&self) -> bool {
563        self.seal_path().exists()
564    }
565
566    /// Checks every block in full and writes the seal next to the archive
567    /// file. If the archive is a link, the seal goes next to its target and
568    /// gets a link here. Takes effect from the next time the segment is opened.
569    pub fn write_seal(&self, threads: usize) -> Res<PathBuf> {
570        let seal = Pool::open(&self.paths[0], 0, 1)
571            .and_then(|p| p.seal(threads))
572            .map_err(corrupt)?;
573        let real = fs::canonicalize(&self.paths[0])
574            .map_err(io)?
575            .with_extension("seal");
576        sync_write(&real, &seal_bytes(&seal))?;
577        let here = self.seal_path();
578        if real != here && fs::symlink_metadata(&here).is_err() {
579            std::os::unix::fs::symlink(&real, &here).map_err(io)?;
580        }
581        Ok(real)
582    }
583
584    /// Whether the segment's blocks are JC06 (cut into parts).
585    pub fn in_parts(&self) -> bool {
586        self.manifest["payload"] == "ASTJ6"
587    }
588
589    /// Whether the segment stores only the patches the metadata doesn't give.
590    pub fn patches_derived(&self) -> bool {
591        self.manifest["format"] == FORMAT
592    }
593
594    /// Ledger `seq` as written: transactions and every patch.
595    fn whole_row(&self, o: &Open, seq: u32) -> Res<Row> {
596        let mut row = o.pool.ledger(seq).map_err(corrupt)?;
597        row.patches = coldpatch::restore(&row.txs, row.seq, &row.patches).map_err(corrupt)?;
598        Ok(row)
599    }
600
601    /// Writes the segment again in the current format, with JC06 blocks of at most
602    /// `part` exact bytes per part, next to the archive (the target of a link). The ledgers,
603    /// indexes and change kinds come out the same, which is checked; the
604    /// archive, seal and manifest are then replaced, each by rename. A reader
605    /// that has the segment open keeps the old archive; one that opens it
606    /// between the renames finds a seal that doesn't match and checks blocks
607    /// in full. Returns the new manifest.
608    pub fn recode(&self, part: usize) -> Res<Value> {
609        let o = self.opened()?;
610        let mut ledgers = Vec::with_capacity((self.last - self.first + 1) as usize);
611        for seq in self.first..=self.last {
612            ledgers.push(if self.kinds == Kinds::Explicit {
613                self.read(&o, seq, true)?
614            } else {
615                // Kinds are not recorded: written the same way as the loader does.
616                let row = self.whole_row(&o, seq)?;
617                Ledger {
618                    header: row.header,
619                    transactions: row.txs,
620                    changes: row
621                        .patches
622                        .into_iter()
623                        .map(|(key, data)| StateChange {
624                            key,
625                            change: if data.is_empty() {
626                                Change::Deleted
627                            } else {
628                                Change::Modified
629                            },
630                            data,
631                        })
632                        .collect(),
633                }
634            });
635        }
636        drop(o);
637        let real = fs::canonicalize(&self.paths[0]).map_err(io)?;
638        let dir = real.parent().ok_or("archive without a directory")?;
639        let staging = dir.join(format!(".recode-{:010}", self.first));
640        let _ = fs::remove_dir_all(&staging);
641        let limit = BlockLimit {
642            ledgers: self.manifest["max_block_ledgers"]
643                .as_u64()
644                .map_or(BLOCK_LEDGERS, |n| n as usize),
645            raw: self.manifest["max_block_raw_bytes"]
646                .as_u64()
647                .map_or(BLOCK_RAW, |n| n as usize),
648            part,
649        };
650        let m = write_with(&staging, &ledgers, self.kinds, limit)?;
651        drop(ledgers);
652        let [na, _, nk, nm] = names(&staging, self.first);
653        if fs::read(&nk).map_err(io)? != fs::read(&self.paths[2]).map_err(io)? {
654            let _ = fs::remove_dir_all(&staging);
655            return Err(corrupt(format!(
656                "{}: recoding changed it",
657                self.paths[2].display()
658            )));
659        }
660        let target = |p: &Path| -> Res<PathBuf> { fs::canonicalize(p).map_err(io) };
661        fs::rename(&na, &real).map_err(io)?;
662        let seal = real.with_extension("seal");
663        fs::rename(na.with_extension("seal"), &seal).map_err(io)?;
664        if seal != self.seal_path() && fs::symlink_metadata(self.seal_path()).is_err() {
665            std::os::unix::fs::symlink(&seal, self.seal_path()).map_err(io)?;
666        }
667        fs::rename(&nm, target(&self.paths[3])?).map_err(io)?;
668        File::open(dir).and_then(|d| d.sync_all()).map_err(io)?;
669        fs::remove_dir_all(&staging).map_err(io)?;
670        // The new manifest no longer lists the ASIX2 indexes.
671        remove_with_link(&self.paths[1])?;
672        self.close();
673        Ok(m)
674    }
675
676    /// Removes the ASIX2 indexes of a segment written before 0.3: the
677    /// manifest is replaced first (via a temporary file and rename), then the
678    /// file, so a crash in between leaves only an unlisted file behind.
679    /// Returns the bytes freed; 0 if the segment has none.
680    pub fn drop_index(&self) -> Res<u64> {
681        if self.manifest["files"].get("asix").is_none() {
682            return Ok(0);
683        }
684        let bytes = self.manifest["files"]["asix"]["bytes"]
685            .as_u64()
686            .unwrap_or(0);
687        let mut m = self.manifest.clone();
688        if let Some(files) = m["files"].as_object_mut() {
689            files.remove("asix");
690        }
691        let real = fs::canonicalize(&self.paths[3]).map_err(io)?;
692        let tmp = real.with_extension("json.tmp");
693        sync_write(
694            &tmp,
695            &serde_json::to_vec_pretty(&m).map_err(|e| e.to_string())?,
696        )?;
697        fs::rename(&tmp, &real).map_err(io)?;
698        if let Some(dir) = real.parent() {
699            File::open(dir).and_then(|d| d.sync_all()).map_err(io)?;
700        }
701        remove_with_link(&self.paths[1])?;
702        Ok(bytes)
703    }
704
705    /// Closes the files and frees the block cache; reads in progress finish.
706    pub fn close(&self) {
707        *self.lock() = None;
708    }
709
710    /// Bytes of prepared blocks in the cache (codec estimate).
711    pub fn cached_bytes(&self) -> usize {
712        self.lock().as_ref().map_or(0, |o| o.pool.cached_bytes())
713    }
714
715    fn opened(&self) -> Res<Arc<Open>> {
716        let mut g = self.lock();
717        if let Some(o) = g.as_ref() {
718            return Ok(o.clone());
719        }
720        let budget = self.budget.load(std::sync::atomic::Ordering::Relaxed);
721        let mut pool = Pool::open(&self.paths[0], budget, PREPARES).map_err(corrupt)?;
722        // Without a usable seal every block is checked in full, as before.
723        if let Some(seal) = fs::read(self.seal_path()).ok().and_then(|b| parse_seal(&b)) {
724            let _ = pool.set_seal(seal);
725        }
726        if pool.first() != Some(self.first) {
727            return Err(corrupt(
728                "archive does not start at the manifest's first ledger",
729            ));
730        }
731        let ledgers = (self.last - self.first + 1) as usize;
732        let kinds = parse_kinds(&fs::read(&self.paths[2]).map_err(io)?, ledgers)?;
733        if kinds.mode != self.kinds {
734            return Err(corrupt("kinds mode does not match the manifest"));
735        }
736        let o = Arc::new(Open { pool, kinds });
737        *g = Some(o.clone());
738        Ok(o)
739    }
740
741    /// Ledger `seq`: header and transactions, plus changes if
742    /// `with_changes` (requires explicit kinds).
743    pub fn ledger(&self, seq: u32, with_changes: bool) -> Res<Ledger> {
744        self.check(seq, with_changes)?;
745        let o = self.opened()?;
746        self.read(&o, seq, with_changes)
747    }
748
749    fn check(&self, seq: u32, with_changes: bool) -> Res<()> {
750        if seq < self.first || seq > self.last {
751            return Err(format!(
752                "ledger {seq} is outside cold segment {}",
753                self.first
754            ));
755        }
756        if with_changes && self.kinds == Kinds::NotRecorded {
757            return Err(format!(
758                "ledger {seq}: the cold segment's source does not distinguish created from modified objects, so changes are not served"
759            ));
760        }
761        Ok(())
762    }
763
764    fn header(&self, o: &Open, seq: u32) -> Res<Vec<u8>> {
765        let raw = o.pool.header(seq).map_err(corrupt)?;
766        let got = LedgerHeader::parse(&raw).map_err(corrupt)?.sequence;
767        if got != seq {
768            return Err(corrupt(format!("at position {seq} found ledger {got}")));
769        }
770        Ok(raw)
771    }
772
773    /// Header of ledger `seq` and its transactions with the given
774    /// TransactionIndex values, without changes.
775    fn read_txs(&self, o: &Open, seq: u32, indexes: &[u32]) -> Res<Ledger> {
776        let mut header = None;
777        let mut transactions = Vec::with_capacity(indexes.len());
778        for &index in indexes {
779            if let Some(at) = o.pool.tx_with_index(seq, index).map_err(corrupt)? {
780                header.get_or_insert(at.header);
781                transactions.push((at.tx, at.meta));
782            }
783        }
784        let header = match header {
785            Some(h) => h,
786            None => o.pool.header(seq).map_err(corrupt)?,
787        };
788        let got = LedgerHeader::parse(&header).map_err(corrupt)?.sequence;
789        if got != seq {
790            return Err(corrupt(format!("at position {seq} found ledger {got}")));
791        }
792        Ok(Ledger {
793            header,
794            transactions,
795            changes: Vec::new(),
796        })
797    }
798
799    fn read(&self, o: &Open, seq: u32, with_changes: bool) -> Res<Ledger> {
800        // Patches are decoded only when changes are asked for: they outweigh
801        // the transactions and API reads don't need them.
802        let row = if with_changes {
803            self.whole_row(o, seq)?
804        } else {
805            o.pool.ledger_txs(seq).map_err(corrupt)?
806        };
807        if row.seq != seq {
808            return Err(corrupt(format!(
809                "at position {seq} found ledger {}",
810                row.seq
811            )));
812        }
813        let changes = if with_changes {
814            let i = (seq - self.first) as usize;
815            let (a, b) = (o.kinds.starts[i] as usize, o.kinds.starts[i + 1] as usize);
816            if b - a != row.patches.len() {
817                return Err(corrupt(format!(
818                    "ledger {seq}: kind count does not match the changes"
819                )));
820            }
821            row.patches
822                .into_iter()
823                .zip(&o.kinds.kinds[a..b])
824                .map(|((key, data), k)| {
825                    let change = Change::from_u8(*k).ok_or_else(|| corrupt("change kind"))?;
826                    if (change == Change::Deleted) != data.is_empty() {
827                        return Err(corrupt(format!(
828                            "ledger {seq}: kind does not match the data"
829                        )));
830                    }
831                    Ok(StateChange { key, change, data })
832                })
833                .collect::<Res<Vec<_>>>()?
834        } else {
835            Vec::new()
836        };
837        Ok(Ledger {
838            header: row.header,
839            transactions: row.txs,
840            changes,
841        })
842    }
843}
844
845/// A ledger's header and its state patches: key and object, empty if deleted.
846pub type LedgerPatches = (Vec<u8>, Vec<([u8; 32], Vec<u8>)>);
847
848/// Cold segments of a directory, with a budget for open ones.
849#[derive(Debug)]
850pub struct Cold {
851    segments: Vec<Arc<ColdSegment>>,
852    /// Open segments, most recent last. Shared by all generations from
853    /// `open_with`: readers still holding an older generation spend
854    /// the same budget and close the same segments.
855    recent: Arc<Mutex<VecDeque<Arc<ColdSegment>>>>,
856    /// How many segments may be open at once (`COLD_OPEN`).
857    open_limit: usize,
858    /// Bytes of prepared blocks all open segments may hold (`COLD_BUDGET`).
859    cache_budget: usize,
860}
861
862impl Default for Cold {
863    fn default() -> Self {
864        Cold {
865            segments: Vec::new(),
866            recent: Arc::default(),
867            open_limit: COLD_OPEN,
868            cache_budget: COLD_BUDGET,
869        }
870    }
871}
872
873impl Cold {
874    pub fn open(dir: &Path) -> Res<Cold> {
875        Cold::open_with(dir, &Cold::default())
876    }
877
878    /// Like `open`, but segments from `prev` carry over as is, with their open
879    /// files, block cache and place in the open budget.
880    pub fn open_with(dir: &Path, prev: &Cold) -> Res<Cold> {
881        Ok(Cold {
882            segments: ColdSegment::scan_with(dir, &prev.segments)?,
883            recent: prev.recent.clone(),
884            open_limit: prev.open_limit,
885            cache_budget: prev.cache_budget,
886        })
887    }
888
889    pub fn segments(&self) -> &[Arc<ColdSegment>] {
890        &self.segments
891    }
892
893    pub fn first(&self) -> Option<u32> {
894        self.segments.first().map(|s| s.first)
895    }
896
897    pub fn last(&self) -> Option<u32> {
898        self.segments.last().map(|s| s.last)
899    }
900
901    pub fn contains(&self, seq: u32) -> bool {
902        self.find(seq).is_some()
903    }
904
905    fn find(&self, seq: u32) -> Option<usize> {
906        let i = self
907            .segments
908            .partition_point(|s| s.first <= seq)
909            .checked_sub(1)?;
910        (seq <= self.segments[i].last).then_some(i)
911    }
912
913    /// Same segments with a different open limit (tests use a small one).
914    pub fn with_open_limit(mut self, n: usize) -> Cold {
915        self.open_limit = n.max(1);
916        self
917    }
918
919    /// Same segments with a different budget for the whole block cache.
920    pub fn with_cache_budget(mut self, bytes: usize) -> Cold {
921        self.cache_budget = bytes;
922        self
923    }
924
925    /// A ledger from the cold history; `None` if it is not here. Without
926    /// changes only the header and transactions are decoded.
927    pub fn ledger(&self, seq: u32, with_changes: bool) -> Res<Option<Ledger>> {
928        let Some(i) = self.find(seq) else {
929            return Ok(None);
930        };
931        self.segments[i].check(seq, with_changes)?;
932        let (seg, o) = self.open_segment(i)?;
933        seg.read(&o, seq, with_changes).map(Some)
934    }
935
936    /// Header and state patches of a cold ledger, without transactions or
937    /// change kinds; `None` if it is not here. A patch with empty data deletes
938    /// the object. A source without kinds has these too, but nothing has checked
939    /// them against `AccountHash`: that is for the caller (`coldreplay`).
940    pub fn patches(&self, seq: u32) -> Res<Option<LedgerPatches>> {
941        let Some(i) = self.find(seq) else {
942            return Ok(None);
943        };
944        let (seg, o) = self.open_segment(i)?;
945        let row = seg.whole_row(&o, seq)?;
946        if row.seq != seq {
947            return Err(corrupt(format!(
948                "at position {seq} found ledger {}",
949                row.seq
950            )));
951        }
952        Ok(Some((row.header, row.patches)))
953    }
954
955    /// Header of a cold ledger alone; `None` if it is not here.
956    pub fn header(&self, seq: u32) -> Res<Option<Vec<u8>>> {
957        let Some(i) = self.find(seq) else {
958            return Ok(None);
959        };
960        self.segments[i].check(seq, false)?;
961        let (seg, o) = self.open_segment(i)?;
962        seg.header(&o, seq).map(Some)
963    }
964
965    /// Several ledgers without changes; those not in cold history are left
966    /// out. Ledgers of one block go to one reader, so the block is prepared
967    /// once, and different blocks are read on up to `COLD_READERS` threads.
968    pub fn ledgers(&self, seqs: &[u32]) -> Res<HashMap<u32, Ledger>> {
969        self.grouped(seqs, &|seg, o, seq| seg.read(o, seq, false))
970    }
971
972    /// Ledgers holding only the transactions asked for, by ledger and
973    /// TransactionIndex, and their headers; an index the ledger doesn't have is
974    /// left out. In a JC06 block only the part holding a ledger is decoded.
975    pub fn transactions(&self, wants: &[(u32, u32)]) -> Res<HashMap<u32, Ledger>> {
976        let mut by_seq: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
977        for &(seq, index) in wants {
978            by_seq.entry(seq).or_default().push(index);
979        }
980        let seqs: Vec<u32> = by_seq.keys().copied().collect();
981        self.grouped(&seqs, &|seg, o, seq| seg.read_txs(o, seq, &by_seq[&seq]))
982    }
983
984    /// Reads `seqs` with `read`, block by block on up to `COLD_READERS` threads.
985    fn grouped(
986        &self,
987        seqs: &[u32],
988        read: &(dyn Fn(&ColdSegment, &Open, u32) -> Res<Ledger> + Sync),
989    ) -> Res<HashMap<u32, Ledger>> {
990        type Group = (Arc<ColdSegment>, Arc<Open>, Vec<u32>);
991        let mut open: HashMap<usize, Arc<Open>> = HashMap::new();
992        let mut blocks: BTreeMap<(usize, usize), Vec<u32>> = BTreeMap::new();
993        for &seq in seqs {
994            let Some(i) = self.find(seq) else { continue };
995            self.segments[i].check(seq, false)?;
996            let o = match open.get(&i) {
997                Some(o) => o,
998                None => {
999                    let (_, o) = self.open_segment(i)?;
1000                    open.entry(i).or_insert(o)
1001                }
1002            };
1003            let b = o.pool.block_id(seq).map_err(corrupt)?;
1004            blocks.entry((i, b)).or_default().push(seq);
1005        }
1006        let groups: Vec<Group> = blocks
1007            .into_iter()
1008            .map(|((i, _), seqs)| (self.segments[i].clone(), open[&i].clone(), seqs))
1009            .collect();
1010        let read = |(seg, o, seqs): &Group| -> Res<Vec<(u32, Ledger)>> {
1011            seqs.iter()
1012                .map(|&seq| {
1013                    crate::limits::check()?;
1014                    Ok((seq, read(seg, o, seq)?))
1015                })
1016                .collect()
1017        };
1018        let mut out = HashMap::with_capacity(seqs.len());
1019        if groups.len() <= 1 {
1020            for g in &groups {
1021                out.extend(read(g)?);
1022            }
1023            return Ok(out);
1024        }
1025        // Readers run under the request's deadline, which is per thread.
1026        let deadline = crate::limits::current();
1027        let next = std::sync::atomic::AtomicUsize::new(0);
1028        let parts = std::thread::scope(|sc| {
1029            let workers: Vec<_> = (0..COLD_READERS.min(groups.len()))
1030                .map(|_| {
1031                    sc.spawn(|| -> Res<Vec<(u32, Ledger)>> {
1032                        let _deadline = crate::limits::start_at(deadline);
1033                        let mut got = Vec::new();
1034                        loop {
1035                            let k = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1036                            let Some(g) = groups.get(k) else {
1037                                return Ok(got);
1038                            };
1039                            got.extend(read(g)?);
1040                        }
1041                    })
1042                })
1043                .collect();
1044            workers
1045                .into_iter()
1046                .map(|w| {
1047                    w.join()
1048                        .unwrap_or_else(|_| Err("cold reader panicked".into()))
1049                })
1050                .collect::<Vec<_>>()
1051        });
1052        for p in parts {
1053            out.extend(p?);
1054        }
1055        Ok(out)
1056    }
1057
1058    fn open_segment(&self, i: usize) -> Res<(&Arc<ColdSegment>, Arc<Open>)> {
1059        let seg = &self.segments[i];
1060        // Open budget: a slot is freed and the segment is opened under the
1061        // shared lock, before reading, so there are never more than `COLD_OPEN` open.
1062        // The read itself happens outside the lock; reads already running on a closed
1063        // segment finish with their own instance. Then the byte budget: while the
1064        // cache as a whole is over it, the least recently read segments other than
1065        // this one are closed.
1066        let o = {
1067            let mut r = self.recent.lock().unwrap_or_else(|p| p.into_inner());
1068            r.retain(|s| !Arc::ptr_eq(s, seg));
1069            while r.len() >= self.open_limit {
1070                match r.pop_front() {
1071                    Some(s) => s.close(),
1072                    None => break,
1073                }
1074            }
1075            let o = seg.opened()?;
1076            r.push_back(seg.clone());
1077            let mut total = r.iter().map(|s| s.cached_bytes()).sum::<usize>();
1078            while total > self.cache_budget && r.len() > 1 {
1079                let Some(s) = r.pop_front() else { break };
1080                total -= s.cached_bytes().min(total);
1081                s.close();
1082            }
1083            o
1084        };
1085        Ok((seg, o))
1086    }
1087
1088    /// How many segments are open right now. Counted under the same lock that
1089    /// guards closing and opening segments; otherwise the count could see
1090    /// a closing segment and a freshly opened one at the same time.
1091    pub fn open_count(&self) -> usize {
1092        let _r = self.recent.lock().unwrap_or_else(|p| p.into_inner());
1093        self.segments.iter().filter(|s| s.is_open()).count()
1094    }
1095}
1096
1097#[cfg(test)]
1098pub(crate) mod tests {
1099    use super::*;
1100
1101    /// A chain of ledgers without transactions, with changes of all three kinds.
1102    pub(crate) fn chain(first: u32, n: u32) -> Vec<Ledger> {
1103        let mut out: Vec<Ledger> = Vec::new();
1104        let mut parent = [0u8; 32];
1105        for k in 0..n {
1106            // Header: sequence (BE), coins, parent; the transaction root is the
1107            // empty tree.
1108            let mut header = vec![0u8; 118];
1109            header[..4].copy_from_slice(&(first + k).to_be_bytes());
1110            header[12..44].copy_from_slice(&parent);
1111            parent = LedgerHeader::parse(&header).unwrap().hash();
1112            let changes = vec![
1113                StateChange {
1114                    key: [k as u8; 32],
1115                    change: Change::Created,
1116                    data: vec![0x11, 0x00, 0x61, k as u8],
1117                },
1118                StateChange {
1119                    key: [0xAA; 32],
1120                    change: Change::Modified,
1121                    data: vec![0x11, 0x00, 0x61, 7],
1122                },
1123                StateChange {
1124                    key: [0xBB; 32],
1125                    change: Change::Deleted,
1126                    data: vec![],
1127                },
1128            ];
1129            out.push(Ledger {
1130                header,
1131                transactions: vec![],
1132                changes,
1133            });
1134        }
1135        out
1136    }
1137
1138    #[test]
1139    fn segment_round_trips_with_explicit_kinds() {
1140        let dir = tempfile::tempdir().unwrap();
1141        let ls = chain(100, 40);
1142        let m = write(dir.path(), &ls, Kinds::Explicit).unwrap();
1143        assert_eq!(m["last"], 139);
1144        let cold = Cold::open(dir.path()).unwrap();
1145        cold.segments()[0].verify_files().unwrap();
1146        for l in &ls {
1147            let seq = l.header().unwrap().sequence;
1148            assert_eq!(cold.ledger(seq, true).unwrap().unwrap(), *l);
1149            let t = cold.ledger(seq, false).unwrap().unwrap();
1150            assert!(t.changes.is_empty() && t.header == l.header);
1151        }
1152        assert!(cold.ledger(99, false).unwrap().is_none());
1153        assert!(cold.ledger(140, false).unwrap().is_none());
1154    }
1155
1156    #[test]
1157    fn segments_without_asix_and_older_ones_with_it() {
1158        let dir = tempfile::tempdir().unwrap();
1159        let ls = chain(100, 20);
1160        let m = write(dir.path(), &ls, Kinds::Explicit).unwrap();
1161        assert!(m["files"].get("asix").is_none());
1162        let [_, asix, _, man] = names(dir.path(), 100);
1163        assert!(!asix.exists());
1164        // A segment from before 0.3: its manifest lists ASIX2 indexes.
1165        let index = b"ASIX2 indexes from before 0.3".to_vec();
1166        fs::write(&asix, &index).unwrap();
1167        let mut old = m.clone();
1168        old["files"]["asix"] =
1169            json!({"bytes": index.len(), "sha512half": hex::encode_upper(sha512_half(&index))});
1170        fs::write(&man, serde_json::to_vec(&old).unwrap()).unwrap();
1171        let cold = Cold::open(dir.path()).unwrap();
1172        cold.segments()[0].verify_files().unwrap();
1173        // Published through a link, as the loader does.
1174        let live = tempfile::tempdir().unwrap();
1175        for e in ["astj", "asix", "kinds", "json"] {
1176            let n = format!("cold-0000000100.{e}");
1177            std::os::unix::fs::symlink(dir.path().join(&n), live.path().join(&n)).unwrap();
1178        }
1179        let cold = Cold::open(live.path()).unwrap();
1180        assert_eq!(cold.segments()[0].drop_index().unwrap(), index.len() as u64);
1181        assert!(!asix.exists() && !live.path().join("cold-0000000100.asix").exists());
1182        let cold = Cold::open(live.path()).unwrap();
1183        assert_eq!(cold.segments()[0].drop_index().unwrap(), 0);
1184        cold.segments()[0].verify_files().unwrap();
1185        assert_eq!(cold.ledger(110, true).unwrap().unwrap(), ls[10]);
1186    }
1187
1188    #[test]
1189    fn ledger_larger_than_block_limit_gets_its_own_limit() {
1190        let dir = tempfile::tempdir().unwrap();
1191        let mut ls = chain(200, 6);
1192        ls[3].changes[0].data = vec![0x11; 3000];
1193        let small = BlockLimit {
1194            ledgers: 1024,
1195            raw: 1024,
1196            ..BlockLimit::default()
1197        };
1198        let m = write_with(dir.path(), &ls, Kinds::Explicit, small).unwrap();
1199        assert!(m["max_block_raw_bytes"].as_u64().unwrap() > 3000);
1200        let cold = Cold::open(dir.path()).unwrap();
1201        for l in &ls {
1202            let seq = l.header().unwrap().sequence;
1203            assert_eq!(cold.ledger(seq, true).unwrap().unwrap(), *l);
1204        }
1205    }
1206
1207    /// A chain of ledgers with transactions (in hash order, as ledgers store
1208    /// them) and a matching transaction root, and the changes of `chain`.
1209    pub(crate) fn chain_with_txs(first: u32, n: u32) -> Vec<Ledger> {
1210        let mut out = chain(first, n);
1211        let mut parent = [0u8; 32];
1212        for (k, l) in out.iter_mut().enumerate() {
1213            let mut txs: Vec<(Vec<u8>, Vec<u8>)> = (0..(k as u32 % 4 + 1))
1214                .map(|i| {
1215                    let mut tx = vec![0x12, 0x00, 0x00, 0x24];
1216                    tx.extend((k as u32 * 10 + i).to_be_bytes());
1217                    // TransactionIndex, empty AffectedNodes, TransactionResult.
1218                    let mut meta = vec![0x20, 0x1C];
1219                    meta.extend(i.to_be_bytes());
1220                    meta.extend([0xF8, 0xF1, 0x03, 0x10, 0x00]);
1221                    (tx, meta)
1222                })
1223                .collect();
1224            txs.sort_by_key(|(t, _)| witness_core::shamap::tx_id(t));
1225            let leaves: Vec<_> = txs
1226                .iter()
1227                .map(|(t, m)| {
1228                    let id = witness_core::shamap::tx_id(t);
1229                    (id, witness_core::shamap::tx_leaf_hash(t, m, &id))
1230                })
1231                .collect();
1232            l.header[12..44].copy_from_slice(&parent);
1233            l.header[44..76].copy_from_slice(&witness_core::shamap::root(&leaves));
1234            parent = LedgerHeader::parse(&l.header).unwrap().hash();
1235            l.transactions = txs;
1236        }
1237        out
1238    }
1239
1240    #[test]
1241    fn transactions_are_read_alone_by_transaction_index() {
1242        for part in [0, 200] {
1243            let dir = tempfile::tempdir().unwrap();
1244            let ls = chain_with_txs(700, 20);
1245            let limit = BlockLimit {
1246                ledgers: 8,
1247                raw: 1 << 20,
1248                part,
1249            };
1250            let m = write_with(dir.path(), &ls, Kinds::Explicit, limit).unwrap();
1251            assert_eq!(m["payload"], if part > 0 { "ASTJ6" } else { "ASTJ5" });
1252            let cold = Cold::open(dir.path()).unwrap();
1253            for l in &ls {
1254                let seq = l.header().unwrap().sequence;
1255                assert_eq!(cold.ledger(seq, true).unwrap().unwrap(), *l);
1256            }
1257            let wants = [(703, 1), (703, 0), (715, 2), (719, 0), (705, 9), (690, 0)];
1258            let got = cold.transactions(&wants).unwrap();
1259            assert!(!got.contains_key(&690));
1260            assert_eq!(got.len(), 4);
1261            assert_eq!(got[&703].transactions.len(), 2);
1262            assert!(got[&705].transactions.is_empty());
1263            for (seq, l) in &got {
1264                let full = &ls[(seq - 700) as usize];
1265                assert_eq!(l.header, full.header);
1266                assert!(l.changes.is_empty());
1267                for t in &l.transactions {
1268                    assert!(full.transactions.contains(t));
1269                }
1270            }
1271            assert_eq!(got[&715].transactions[0].1[2..6], 2u32.to_be_bytes());
1272        }
1273    }
1274
1275    /// A chain whose transactions modify one account each, with exactly the
1276    /// patch their metadata gives, plus the changes of `chain`, sorted by key.
1277    fn chain_with_derived_patches(first: u32, n: u32) -> Vec<Ledger> {
1278        let mut out = chain(first, n);
1279        let mut parent = [0u8; 32];
1280        for (k, l) in out.iter_mut().enumerate() {
1281            let seq = l.header().unwrap().sequence;
1282            let mut tx = vec![0x12, 0x00, 0x00, 0x24];
1283            tx.extend((k as u32).to_be_bytes());
1284            let id = witness_core::shamap::tx_id(&tx);
1285            let key = [0xC0 + k as u8; 32];
1286            let sequence = [0x24, 0, 0, 0, k as u8];
1287            let mut meta = vec![0x20, 0x1C, 0, 0, 0, 0, 0xF8, 0xE5, 0x11, 0x00, 0x61, 0x56];
1288            meta.extend(key);
1289            meta.push(0xE7);
1290            meta.extend(sequence);
1291            meta.extend([0xE1, 0xE1, 0xF1, 0x03, 0x10, 0x00]);
1292            let mut data = vec![0x11, 0x00, 0x61];
1293            data.extend(sequence);
1294            l.changes.push(StateChange {
1295                key,
1296                change: Change::Modified,
1297                data,
1298            });
1299            l.changes.sort_by_key(|c| c.key);
1300            let leaf = witness_core::shamap::tx_leaf_hash(&tx, &meta, &id);
1301            l.header[12..44].copy_from_slice(&parent);
1302            l.header[44..76].copy_from_slice(&witness_core::shamap::root(&[(id, leaf)]));
1303            parent = LedgerHeader::parse(&l.header).unwrap().hash();
1304            l.transactions = vec![(tx, meta)];
1305            assert_eq!(seq, first + k as u32);
1306        }
1307        out
1308    }
1309
1310    #[test]
1311    fn patches_the_metadata_gives_are_not_stored() {
1312        let dir = tempfile::tempdir().unwrap();
1313        let ls = chain_with_derived_patches(900, 12);
1314        let m = write(dir.path(), &ls, Kinds::Explicit).unwrap();
1315        assert_eq!(m["format"], FORMAT);
1316        assert_eq!(m["changes"], 12 * 4);
1317        let cold = Cold::open(dir.path()).unwrap();
1318        for l in &ls {
1319            let seq = l.header().unwrap().sequence;
1320            assert_eq!(cold.ledger(seq, true).unwrap().unwrap(), *l);
1321        }
1322        let seg = &cold.segments()[0];
1323        assert!(seg.patches_derived());
1324        let pool = Pool::open(&seg.paths[0], 0, 1).unwrap();
1325        // The marker and the three changes of `chain`.
1326        assert_eq!(pool.ledger(905).unwrap().patches.len(), 4);
1327    }
1328
1329    #[test]
1330    fn older_segments_with_every_patch_are_read_and_recoded() {
1331        for kinds in [Kinds::Explicit, Kinds::NotRecorded] {
1332            let dir = tempfile::tempdir().unwrap();
1333            let ls = chain_with_txs(950, 12);
1334            let mut m = write(dir.path(), &ls, kinds).unwrap();
1335            // A manifest in the older format; each row says how it is stored.
1336            m["format"] = FORMAT_ALL_PATCHES.into();
1337            let json = names(dir.path(), 950)[3].clone();
1338            fs::write(&json, serde_json::to_vec(&m).unwrap()).unwrap();
1339            let cold = Cold::open(dir.path()).unwrap();
1340            let seg = &cold.segments()[0];
1341            assert!(seg.in_parts() && !seg.patches_derived());
1342            if kinds == Kinds::Explicit {
1343                assert_eq!(cold.ledger(955, true).unwrap().unwrap(), ls[5]);
1344            }
1345            seg.recode(PART_RAW).unwrap();
1346            let cold = Cold::open(dir.path()).unwrap();
1347            assert!(cold.segments()[0].patches_derived());
1348            if kinds == Kinds::Explicit {
1349                assert_eq!(cold.ledger(955, true).unwrap().unwrap(), ls[5]);
1350            }
1351        }
1352    }
1353
1354    #[test]
1355    fn unknown_formats_are_refused() {
1356        let dir = tempfile::tempdir().unwrap();
1357        let mut m = write(dir.path(), &chain(970, 4), Kinds::Explicit).unwrap();
1358        m["format"] = "astraea-cold/3".into();
1359        let json = names(dir.path(), 970)[3].clone();
1360        fs::write(&json, serde_json::to_vec(&m).unwrap()).unwrap();
1361        assert!(
1362            ColdSegment::scan(dir.path())
1363                .unwrap_err()
1364                .contains("unknown format")
1365        );
1366    }
1367
1368    #[test]
1369    fn segments_are_recoded_in_parts() {
1370        for kinds in [Kinds::Explicit, Kinds::NotRecorded] {
1371            let dir = tempfile::tempdir().unwrap();
1372            let ls = chain_with_txs(800, 30);
1373            let limit = BlockLimit {
1374                ledgers: 8,
1375                raw: 1 << 20,
1376                part: 0,
1377            };
1378            write_with(dir.path(), &ls, kinds, limit).unwrap();
1379            let cold = Cold::open(dir.path()).unwrap();
1380            let seg = &cold.segments()[0];
1381            assert!(!seg.in_parts());
1382            let before = cold.ledger(810, false).unwrap().unwrap();
1383            let m = seg.recode(300).unwrap();
1384            assert_eq!(m["payload"], "ASTJ6");
1385            assert!(
1386                fs::read_dir(dir.path()).unwrap().all(|e| !e
1387                    .unwrap()
1388                    .file_name()
1389                    .to_string_lossy()
1390                    .starts_with('.'))
1391            );
1392            // The segment already open reads the new archive once reopened.
1393            assert_eq!(cold.ledger(810, false).unwrap().unwrap(), before);
1394            let again = Cold::open(dir.path()).unwrap();
1395            assert!(again.segments()[0].in_parts());
1396            again.segments()[0].verify_files().unwrap();
1397            for l in &ls {
1398                let seq = l.header().unwrap().sequence;
1399                let got = again
1400                    .ledger(seq, kinds == Kinds::Explicit)
1401                    .unwrap()
1402                    .unwrap();
1403                if kinds == Kinds::Explicit {
1404                    assert_eq!(got, *l);
1405                } else {
1406                    assert_eq!(
1407                        (&got.header, &got.transactions),
1408                        (&l.header, &l.transactions)
1409                    );
1410                }
1411            }
1412            assert_eq!(
1413                again.transactions(&[(805, 1)]).unwrap()[&805]
1414                    .transactions
1415                    .len(),
1416                1
1417            );
1418        }
1419    }
1420
1421    #[test]
1422    fn ledgers_read_in_parallel_match_single_reads() {
1423        let dir = tempfile::tempdir().unwrap();
1424        let small = BlockLimit {
1425            ledgers: 3,
1426            raw: 1 << 20,
1427            ..BlockLimit::default()
1428        };
1429        for f in [100u32, 120, 140] {
1430            write_with(dir.path(), &chain(f, 12), Kinds::Explicit, small).unwrap();
1431        }
1432        let cold = Cold::open(dir.path()).unwrap().with_open_limit(2);
1433        let seqs: Vec<u32> = vec![150, 149, 141, 130, 125, 111, 104, 103, 99, 115];
1434        let got = cold.ledgers(&seqs).unwrap();
1435        assert_eq!(got.len(), 8);
1436        assert!(!got.contains_key(&99) && !got.contains_key(&115));
1437        for (seq, l) in &got {
1438            assert_eq!(*l, cold.ledger(*seq, false).unwrap().unwrap());
1439            assert!(l.changes.is_empty());
1440        }
1441        assert!(cold.open_count() <= 2);
1442        assert!(cold.ledgers(&[]).unwrap().is_empty());
1443    }
1444
1445    #[test]
1446    fn readers_keep_the_request_deadline() {
1447        let dir = tempfile::tempdir().unwrap();
1448        let small = BlockLimit {
1449            ledgers: 3,
1450            raw: 1 << 20,
1451            ..BlockLimit::default()
1452        };
1453        for f in [100u32, 120, 140] {
1454            write_with(dir.path(), &chain(f, 12), Kinds::Explicit, small).unwrap();
1455        }
1456        let seqs: Vec<u32> = (100..112).chain(120..132).chain(140..152).collect();
1457        let cold = Cold::open(dir.path()).unwrap();
1458        assert_eq!(cold.ledgers(&seqs).unwrap().len(), seqs.len());
1459        let _d = crate::limits::start(std::time::Duration::ZERO);
1460        assert_eq!(cold.ledgers(&seqs).unwrap_err(), crate::limits::EXCEEDED);
1461    }
1462
1463    #[test]
1464    fn segments_are_sealed_and_read_without_a_usable_seal() {
1465        let dir = tempfile::tempdir().unwrap();
1466        let ls = chain(300, 9);
1467        let small = BlockLimit {
1468            ledgers: 4,
1469            raw: 1 << 20,
1470            ..BlockLimit::default()
1471        };
1472        write_with(dir.path(), &ls, Kinds::Explicit, small).unwrap();
1473        let seal = dir.path().join("cold-0000000300.seal");
1474        assert_eq!(parse_seal(&fs::read(&seal).unwrap()).unwrap().len(), 3);
1475        let lists = vec![vec![[1; 32]], vec![[2; 32], [3; 32]], vec![]];
1476        assert_eq!(parse_seal(&seal_bytes(&lists)), Some(lists.clone()));
1477        let one = vec![vec![[4; 32]]; 2];
1478        assert_eq!(seal_bytes(&one)[..6], *SEAL_MAGIC);
1479        assert_eq!(parse_seal(&seal_bytes(&one)), Some(one));
1480        let mut cut = seal_bytes(&lists);
1481        cut.pop();
1482        assert!(parse_seal(&cut).is_none());
1483        let read_all = |dir: &Path| {
1484            let cold = Cold::open(dir).unwrap();
1485            for l in &ls {
1486                let seq = l.header().unwrap().sequence;
1487                assert_eq!(cold.ledger(seq, true).unwrap().unwrap(), *l);
1488            }
1489        };
1490        read_all(dir.path());
1491        fs::write(&seal, b"XWCS\x00\x01junk").unwrap();
1492        read_all(dir.path());
1493        fs::remove_file(&seal).unwrap();
1494        read_all(dir.path());
1495        // An older segment published through links gets its seal next to the
1496        // archive and a link beside the published one.
1497        let live = tempfile::tempdir().unwrap();
1498        for e in ["astj", "kinds", "json"] {
1499            let n = format!("cold-0000000300.{e}");
1500            std::os::unix::fs::symlink(dir.path().join(&n), live.path().join(&n)).unwrap();
1501        }
1502        let cold = Cold::open(live.path()).unwrap();
1503        assert!(!cold.segments()[0].sealed());
1504        cold.segments()[0].write_seal(2).unwrap();
1505        assert!(seal.exists() && cold.segments()[0].sealed());
1506        assert!(
1507            fs::symlink_metadata(live.path().join("cold-0000000300.seal"))
1508                .unwrap()
1509                .file_type()
1510                .is_symlink()
1511        );
1512        read_all(live.path());
1513    }
1514
1515    #[test]
1516    fn reopen_keeps_open_segments_and_their_budget() {
1517        let dir = tempfile::tempdir().unwrap();
1518        write(dir.path(), &chain(20, 5), Kinds::Explicit).unwrap();
1519        let cold = Cold::open(dir.path()).unwrap();
1520        cold.ledger(21, true).unwrap().unwrap();
1521        write(dir.path(), &chain(10, 5), Kinds::Explicit).unwrap();
1522        let next = Cold::open_with(dir.path(), &cold).unwrap();
1523        assert_eq!((next.first(), next.last()), (Some(10), Some(24)));
1524        assert!(Arc::ptr_eq(&next.segments()[1], &cold.segments()[0]));
1525        assert_eq!(next.open_count(), 1);
1526        next.ledger(11, true).unwrap().unwrap();
1527        assert_eq!(next.open_count(), 2);
1528    }
1529
1530    #[test]
1531    fn not_recorded_kinds_refuse_changes_and_bad_kinds_are_rejected() {
1532        let dir = tempfile::tempdir().unwrap();
1533        let ls = chain(5, 3);
1534        write(dir.path(), &ls, Kinds::NotRecorded).unwrap();
1535        let cold = Cold::open(dir.path()).unwrap();
1536        assert!(cold.ledger(6, false).unwrap().is_some());
1537        assert!(cold.ledger(6, true).is_err());
1538        let mut bad = chain(50, 1);
1539        bad[0].changes[0].change = Change::Deleted;
1540        assert!(write(dir.path(), &bad, Kinds::Explicit).is_err());
1541    }
1542
1543    #[test]
1544    fn cache_budget_is_shared_by_open_segments() {
1545        let dir = tempfile::tempdir().unwrap();
1546        for f in [10u32, 20, 30] {
1547            write(dir.path(), &chain(f, 5), Kinds::Explicit).unwrap();
1548        }
1549        // A roomy budget keeps every segment and its blocks.
1550        let cold = Cold::open(dir.path()).unwrap();
1551        for s in [10u32, 20, 30] {
1552            cold.ledger(s, false).unwrap().unwrap();
1553        }
1554        assert_eq!(cold.open_count(), 3);
1555        assert!(cold.segments().iter().all(|s| s.cached_bytes() > 0));
1556        // A tiny one: opening the next segment closes the older ones, whatever
1557        // the open limit, and reads still work.
1558        let cold = Cold::open(dir.path()).unwrap().with_cache_budget(1);
1559        for s in [10u32, 20, 30, 11] {
1560            assert!(cold.ledger(s, false).unwrap().is_some());
1561            assert_eq!(cold.open_count(), 1);
1562        }
1563    }
1564
1565    #[test]
1566    fn budget_closes_old_segments_and_tampering_is_caught() {
1567        let dir = tempfile::tempdir().unwrap();
1568        for f in [10u32, 20, 30] {
1569            write(dir.path(), &chain(f, 5), Kinds::Explicit).unwrap();
1570        }
1571        let cold = Cold::open(dir.path()).unwrap().with_open_limit(2);
1572        for s in [10u32, 20, 30, 12] {
1573            cold.ledger(s, true).unwrap().unwrap();
1574        }
1575        assert_eq!(cold.open_count(), 2);
1576        // Concurrently: the number of open segments never exceeds the budget.
1577        let cold = Arc::new(cold);
1578        let seen = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1579        let hs: Vec<_> = (0..6u32)
1580            .map(|t| {
1581                let (cold, seen) = (cold.clone(), seen.clone());
1582                std::thread::spawn(move || {
1583                    for k in 0..60u32 {
1584                        let seq = [10u32, 20, 30][((k + t) % 3) as usize] + k % 5;
1585                        cold.ledger(seq, true).unwrap().unwrap();
1586                        seen.fetch_max(cold.open_count(), std::sync::atomic::Ordering::Relaxed);
1587                    }
1588                })
1589            })
1590            .collect();
1591        for h in hs {
1592            h.join().unwrap();
1593        }
1594        assert!(seen.load(std::sync::atomic::Ordering::Relaxed) <= 2);
1595        let p = dir.path().join("cold-0000000020.kinds");
1596        let mut b = fs::read(&p).unwrap();
1597        let n = b.len();
1598        b[n - 1] ^= 1;
1599        fs::write(&p, b).unwrap();
1600        let cold = Cold::open(dir.path()).unwrap();
1601        assert!(cold.segments()[1].verify_files().is_err());
1602        assert!(cold.ledger(21, true).is_err());
1603    }
1604}