Skip to main content

astraea_journal_codec/
pool.rs

1//! Serving pool of prepared blocks for the Ledger Engine.
2//!
3//! A reader with one prepared block behind `&mut self` would serialize concurrent
4//! readers of different blocks and re-prepare on every switch. The
5//! pool keeps several prepared blocks under a byte budget, prepares different
6//! blocks in parallel (at most `max_prepares` at a time), and concurrent
7//! requests for the same block wait for one preparation. Verification before
8//! a block is cached: exact framing hashed
9//! one ledger at a time against the directory SHA512Half, ledger sequence,
10//! transaction roots and the internal parent chain.
11//!
12//! JC06 blocks open with their shared section only, and a part compiles when
13//! one of its ledgers is first read; the cached size of a block grows with its
14//! compiled parts. `tx_with_index` reads one transaction that way.
15//!
16//! That check costs about as much as preparing the block. A seal
17//! (`Pool::seal`) records, for every block that passed it, a digest of the
18//! stored block bytes. With a seal set (`set_seal`), a block whose bytes still
19//! match its digest is prepared without repeating the check; any other block is
20//! checked in full as before. A JC06 block has a digest of its head (sizes and
21//! shared section) and one per part: a read checks the head and the parts it
22//! compiles, not the whole block.
23//!
24//! A block evicted from the cache and read again is prepared again, and its
25//! parts compile again. What the first preparation established is not
26//! repeated: the pool remembers, for every seal digest, that the stored bytes
27//! matched it once in this process, and for sealed JC06 blocks the hashes of
28//! their transactions (at most `MEMO_BYTES` of them, least recently prepared
29//! blocks dropped first). So a head or part is hashed against its digest the
30//! first time it is used and trusted after that for as long as the pool is
31//! open; a part that does not match is refused every time, since only a match
32//! is remembered. The archive file is expected not to change under an open
33//! pool: a segment is rewritten through a new file, not in place.
34use super::*;
35use sha2::{Digest, Sha512};
36use std::collections::HashMap;
37use std::os::unix::fs::FileExt;
38use std::sync::atomic::{AtomicBool, Ordering};
39use std::sync::{Arc, Condvar, Mutex, OnceLock};
40/// Most bytes of remembered transaction hashes per pool. A 4 MiB block holds
41/// some thousands of transactions, a few hundred KB of hashes, against tens
42/// of MB for the prepared block.
43const MEMO_BYTES: usize = 8 << 20;
44/// Remembered transaction hashes per block: hashes, last use, and the tick.
45#[derive(Default)]
46struct Memos {
47    blocks: HashMap<usize, (fast::TxMemo, u64)>,
48    tick: u64,
49    bytes: usize,
50}
51fn memo_bytes(m: &fast::TxMemo) -> usize {
52    m.len() * std::mem::size_of::<OnceLock<[u8; 32]>>()
53}
54enum Data {
55    Prepared(Box<fast::Prepared>),
56    Rows(Vec<Row>),
57}
58type Cell = Arc<OnceLock<Result<Arc<Mutex<Data>>, String>>>;
59/// One transaction with the header of its ledger.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct TxAt {
62    pub header: Vec<u8>,
63    pub tx: Vec<u8>,
64    pub meta: Vec<u8>,
65}
66struct Slot {
67    index: usize,
68    cell: Cell,
69    bytes: usize,
70    used: u64,
71}
72pub struct Pool {
73    file: std::fs::File,
74    entries: Vec<Entry>,
75    budget: usize,
76    slots: Mutex<(Vec<Slot>, u64)>,
77    preparing: (Mutex<usize>, Condvar),
78    max_prepares: usize,
79    seal: Vec<Vec<[u8; 32]>>,
80    /// Per block and seal digest: the stored bytes matched it once.
81    checked: Vec<Arc<[AtomicBool]>>,
82    memos: Mutex<Memos>,
83}
84/// Seal digests of a block's stored bytes: the whole payload, or for JC06 the
85/// head and then every part.
86fn block_digests(hash: &[u8; 32], payload: &[u8]) -> Res<Vec<[u8; 32]>> {
87    if payload.first() != Some(&2) {
88        return Ok(vec![seal_digest(hash, payload)]);
89    }
90    let l = fast::frame_parts(&payload[1..])?;
91    let mut out = vec![seal_digest(hash, &payload[..1 + l.head])];
92    for (r, _) in l.parts {
93        out.push(seal_digest(hash, &payload[1 + r.start..1 + r.end]));
94    }
95    Ok(out)
96}
97impl std::fmt::Debug for Pool {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("Pool")
100            .field("blocks", &self.entries.len())
101            .field("budget", &self.budget)
102            .finish_non_exhaustive()
103    }
104}
105fn compiled(d: &Data) -> usize {
106    match d {
107        Data::Prepared(f) => f.compiled_parts(),
108        Data::Rows(_) => 0,
109    }
110}
111fn data_bytes(d: &Data) -> usize {
112    match d {
113        Data::Prepared(f) => f.memory_bytes(),
114        Data::Rows(rows) => rows
115            .iter()
116            .map(|r| {
117                r.header.len()
118                    + r.txs.iter().map(|(t, m)| t.len() + m.len()).sum::<usize>()
119                    + r.patches.iter().map(|(_, v)| v.len() + 32).sum::<usize>()
120            })
121            .sum(),
122    }
123}
124impl Pool {
125    /// `budget` bounds the estimated bytes of cached prepared blocks; one
126    /// block is always kept even if it alone exceeds the budget.
127    pub fn open(
128        path: impl AsRef<std::path::Path>,
129        budget: usize,
130        max_prepares: usize,
131    ) -> Res<Self> {
132        let a = ArchiveFile::open(path)?;
133        Ok(Self {
134            file: a.file,
135            entries: a.entries,
136            budget,
137            slots: Mutex::new((vec![], 0)),
138            preparing: (Mutex::new(0), Condvar::new()),
139            max_prepares: max_prepares.max(1),
140            seal: Vec::new(),
141            checked: Vec::new(),
142            memos: Mutex::new(Memos::default()),
143        })
144    }
145    /// Checks every block in full, on up to `threads` threads, and returns
146    /// the seal: the digests of every block, in directory order.
147    pub fn seal(&self, threads: usize) -> Res<Vec<Vec<[u8; 32]>>> {
148        let next = std::sync::atomic::AtomicUsize::new(0);
149        let n = self.entries.len();
150        let parts = std::thread::scope(|sc| {
151            let workers: Vec<_> = (0..threads.clamp(1, n.max(1)))
152                .map(|_| {
153                    sc.spawn(|| -> Res<Vec<(usize, Vec<[u8; 32]>)>> {
154                        let mut got = vec![];
155                        loop {
156                            let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
157                            if i >= n {
158                                return Ok(got);
159                            }
160                            let payload = self.payload(i)?;
161                            self.decode(i, &payload, false)?;
162                            got.push((i, block_digests(&self.entries[i].hash, &payload)?));
163                        }
164                    })
165                })
166                .collect();
167            workers
168                .into_iter()
169                .map(|w| {
170                    w.join()
171                        .unwrap_or_else(|_| Err("seal worker panicked".into()))
172                })
173                .collect::<Vec<_>>()
174        });
175        let mut out = vec![vec![]; n];
176        for p in parts {
177            for (i, d) in p? {
178                out[i] = d;
179            }
180        }
181        Ok(out)
182    }
183    /// Sets the seal from `seal` (as returned by `seal` for this archive). A
184    /// seal with the wrong number of digests is refused.
185    pub fn set_seal(&mut self, seal: Vec<Vec<[u8; 32]>>) -> Res<()> {
186        if seal.len() != self.entries.len() {
187            return Err("seal does not match the archive's blocks".into());
188        }
189        self.checked = seal
190            .iter()
191            .map(|d| d.iter().map(|_| AtomicBool::new(false)).collect())
192            .collect();
193        self.seal = seal;
194        *self.memos.lock().unwrap_or_else(|p| p.into_inner()) = Memos::default();
195        Ok(())
196    }
197    pub fn first(&self) -> Option<u32> {
198        self.entries.first().map(|e| e.first)
199    }
200    /// Bytes of cached prepared blocks and remembered transaction hashes.
201    pub fn cached_bytes(&self) -> usize {
202        let blocks: usize = self
203            .slots
204            .lock()
205            .unwrap_or_else(|p| p.into_inner())
206            .0
207            .iter()
208            .map(|s| s.bytes)
209            .sum();
210        blocks + self.memos.lock().unwrap_or_else(|p| p.into_inner()).bytes
211    }
212    /// Index of the block holding ledger `seq`: callers group reads by it.
213    pub fn block_id(&self, seq: u32) -> Res<usize> {
214        self.block_of(seq)
215    }
216    fn block_of(&self, seq: u32) -> Res<usize> {
217        let i = self
218            .entries
219            .partition_point(|e| e.first <= seq)
220            .checked_sub(1)
221            .ok_or("ledger extent")?;
222        let e = &self.entries[i];
223        if u64::from(seq) >= u64::from(e.first) + e.count as u64 {
224            return Err("ledger extent".into());
225        }
226        Ok(i)
227    }
228    fn load(&self, i: usize) -> Res<Data> {
229        // At most `max_prepares` decodes at once: each allocates its payload
230        // and decoded block.
231        {
232            let (m, cv) = &self.preparing;
233            let mut n = m.lock().unwrap_or_else(|p| p.into_inner());
234            while *n >= self.max_prepares {
235                n = cv.wait(n).unwrap_or_else(|p| p.into_inner());
236            }
237            *n += 1;
238        }
239        let out = self.load_inner(i);
240        let (m, cv) = &self.preparing;
241        *m.lock().unwrap_or_else(|p| p.into_inner()) -= 1;
242        cv.notify_one();
243        out
244    }
245    fn load_inner(&self, i: usize) -> Res<Data> {
246        let payload = self.payload(i)?;
247        let hash = &self.entries[i].hash;
248        let seal = self.seal.get(i).map_or(&[][..], Vec::as_slice);
249        let checked = self.checked.get(i);
250        // The first digest (whole payload, or a JC06 head): matched once in
251        // this process, or now.
252        let first_matches = |bytes: &[u8]| {
253            let flag = checked.and_then(|c| c.first());
254            if flag.is_some_and(|f| f.load(Ordering::Acquire)) {
255                return true;
256            }
257            let ok = seal[0] == seal_digest(hash, bytes);
258            if let (true, Some(f)) = (ok, flag) {
259                f.store(true, Ordering::Release);
260            }
261            ok
262        };
263        // A JC06 block is trusted by its head here and by each part as it compiles.
264        let parts = if payload.first() == Some(&2) && seal.len() > 1 {
265            fast::frame_parts(&payload[1..])
266                .ok()
267                .filter(|l| {
268                    l.parts.len() + 1 == seal.len() && first_matches(&payload[..1 + l.head])
269                })
270                .map(|_| seal[1..].to_vec())
271        } else {
272            None
273        };
274        let sealed = parts.is_some() || (seal.len() == 1 && first_matches(&payload));
275        let mut data = self.decode(i, &payload, sealed)?;
276        if let (Some(digests), Data::Prepared(f)) = (parts, &mut data) {
277            f.check_parts(*hash, digests)?;
278            if let Some(c) = checked {
279                let memo = self.tx_memo(i, f.tx_count());
280                f.remember(c.clone(), memo);
281            }
282        }
283        Ok(data)
284    }
285    /// Remembered transaction hashes of block `i` with `n` transactions,
286    /// dropping those of the least recently prepared blocks over `MEMO_BYTES`.
287    fn tx_memo(&self, i: usize, n: usize) -> fast::TxMemo {
288        let mut g = self.memos.lock().unwrap_or_else(|p| p.into_inner());
289        g.tick += 1;
290        let tick = g.tick;
291        let memo = match g.blocks.get_mut(&i) {
292            Some((m, used)) if m.len() == n => {
293                *used = tick;
294                return m.clone();
295            }
296            _ => {
297                let m: fast::TxMemo = (0..n).map(|_| OnceLock::new()).collect();
298                if let Some((old, _)) = g.blocks.insert(i, (m.clone(), tick)) {
299                    g.bytes -= memo_bytes(&old);
300                }
301                g.bytes += memo_bytes(&m);
302                m
303            }
304        };
305        while g.bytes > MEMO_BYTES {
306            let Some(k) = g
307                .blocks
308                .iter()
309                .filter(|(k, _)| **k != i)
310                .min_by_key(|(_, (_, used))| *used)
311                .map(|(k, _)| *k)
312            else {
313                break;
314            };
315            if let Some((old, _)) = g.blocks.remove(&k) {
316                g.bytes -= memo_bytes(&old);
317            }
318        }
319        memo
320    }
321    fn payload(&self, i: usize) -> Res<Vec<u8>> {
322        let e = &self.entries[i];
323        let mut payload = vec![0; e.length];
324        self.file
325            .read_exact_at(&mut payload, e.offset)
326            .map_err(er)?;
327        Ok(payload)
328    }
329    /// Block `i` from its stored bytes. `sealed`: the bytes match a seal digest,
330    /// so only the framing is checked, not the hashes, roots and chain.
331    fn decode(&self, i: usize, payload: &[u8], sealed: bool) -> Res<Data> {
332        let e = &self.entries[i];
333        let mut p = Read::new(payload);
334        let data = match p.byte()? {
335            mode @ (1 | 2) => {
336                let mut f = if mode == 1 {
337                    fast::Prepared::open(&payload[1..])?
338                } else {
339                    fast::Prepared::open_parts(&payload[1..])?
340                };
341                if f.ledger_count() != e.count {
342                    return Err("block count".into());
343                }
344                if sealed {
345                    for k in 0..e.count {
346                        if f.seq(k)
347                            != Some(e.first.checked_add(k as u32).ok_or("sequence overflow")?)
348                        {
349                            return Err("block sequence".into());
350                        }
351                    }
352                    return Ok(Data::Prepared(Box::new(f)));
353                }
354                let mut hash = Sha512::new();
355                hash.update((e.count as u32).to_le_bytes());
356                let mut previous: Option<LedgerHeader> = None;
357                for k in 0..e.count {
358                    let row = f.row(k)?;
359                    if row.seq != e.first.checked_add(k as u32).ok_or("sequence overflow")? {
360                        return Err("block sequence".into());
361                    }
362                    verify(std::slice::from_ref(&row))?;
363                    let h = LedgerHeader::parse(&row.header).map_err(er)?;
364                    if previous.as_ref().is_some_and(|p| h.parent_hash != p.hash()) {
365                        return Err("chain gap".into());
366                    }
367                    previous = Some(h);
368                    let bytes = rows_bytes(std::slice::from_ref(&row));
369                    hash.update(&bytes[4..]);
370                }
371                if hash.finalize()[..32] != e.hash {
372                    return Err("block identity".into());
373                }
374                Data::Prepared(Box::new(f))
375            }
376            0 => {
377                let n = u64::from_le_bytes(p.take(8)?.try_into().map_err(er)?);
378                if n > MAX as u64 {
379                    return Err("raw limit".into());
380                }
381                let raw = zstd::bulk::decompress(&payload[p.p..], n as usize).map_err(er)?;
382                if raw.len() != n as usize {
383                    return Err("raw size".into());
384                }
385                let rows = load_rows(&raw)?;
386                if rows.len() != e.count || rows.first().is_none_or(|r| r.seq != e.first) {
387                    return Err("block identity".into());
388                }
389                if !sealed {
390                    if sha512_half(&raw) != e.hash {
391                        return Err("block identity".into());
392                    }
393                    verify(&rows)?;
394                }
395                Data::Rows(rows)
396            }
397            _ => return Err("block mode".into()),
398        };
399        Ok(data)
400    }
401    /// Prepared block `i`, preparing it once for all concurrent callers.
402    fn block(&self, i: usize) -> Res<(Cell, Arc<Mutex<Data>>)> {
403        let cell = {
404            let mut g = self.slots.lock().unwrap_or_else(|p| p.into_inner());
405            g.1 += 1;
406            let tick = g.1;
407            if let Some(s) = g.0.iter_mut().find(|s| s.index == i) {
408                s.used = tick;
409                s.cell.clone()
410            } else {
411                let cell: Cell = Arc::new(OnceLock::new());
412                g.0.push(Slot {
413                    index: i,
414                    cell: cell.clone(),
415                    bytes: 0,
416                    used: tick,
417                });
418                cell
419            }
420        };
421        let got = cell
422            .get_or_init(|| self.load(i).map(|d| Arc::new(Mutex::new(d))))
423            .clone();
424        match &got {
425            Err(_) => self
426                .slots
427                .lock()
428                .unwrap_or_else(|p| p.into_inner())
429                .0
430                .retain(|s| !Arc::ptr_eq(&s.cell, &cell)),
431            Ok(d) => {
432                let bytes = data_bytes(&d.lock().unwrap_or_else(|p| p.into_inner()));
433                self.resize(&cell, bytes);
434            }
435        }
436        got.map(|d| (cell, d))
437    }
438    /// Records the size of a cached block and evicts least recently used ready
439    /// blocks over the budget, never that one.
440    fn resize(&self, cell: &Cell, bytes: usize) {
441        let mut g = self.slots.lock().unwrap_or_else(|p| p.into_inner());
442        if let Some(s) = g.0.iter_mut().find(|s| Arc::ptr_eq(&s.cell, cell)) {
443            s.bytes = bytes;
444        }
445        loop {
446            let total: usize = g.0.iter().map(|s| s.bytes).sum();
447            if total <= self.budget || g.0.len() <= 1 {
448                break;
449            }
450            let Some(k) =
451                g.0.iter()
452                    .enumerate()
453                    .filter(|(_, s)| s.bytes > 0 && !Arc::ptr_eq(&s.cell, cell))
454                    .min_by_key(|(_, s)| s.used)
455                    .map(|(k, _)| k)
456            else {
457                break;
458            };
459            g.0.swap_remove(k);
460        }
461    }
462    /// Runs `f` on the block holding ledger `seq` with the ledger's position in
463    /// it; a block that compiled more parts on the way is measured again.
464    fn with<T>(&self, seq: u32, f: impl FnOnce(&mut Data, usize) -> Res<T>) -> Res<T> {
465        let i = self.block_of(seq)?;
466        let local = (seq - self.entries[i].first) as usize;
467        let (cell, d) = self.block(i)?;
468        let (out, grown) = {
469            let mut d = d.lock().unwrap_or_else(|p| p.into_inner());
470            let before = compiled(&d);
471            let out = f(&mut d, local);
472            (out, (compiled(&d) != before).then(|| data_bytes(&d)))
473        };
474        if let Some(bytes) = grown {
475            self.resize(&cell, bytes);
476        }
477        out
478    }
479    pub fn ledger(&self, seq: u32) -> Res<Row> {
480        self.with(seq, |d, local| match d {
481            Data::Prepared(f) => f.row(local),
482            Data::Rows(rows) => rows.get(local).cloned().ok_or("ledger extent".into()),
483        })
484    }
485    /// Header of ledger `seq` only.
486    pub fn header(&self, seq: u32) -> Res<Vec<u8>> {
487        self.with(seq, |d, local| match d {
488            Data::Prepared(f) => f.header(local),
489            Data::Rows(rows) => rows
490                .get(local)
491                .map(|r| r.header.clone())
492                .ok_or("ledger extent".into()),
493        })
494    }
495    /// Ledger `seq` with transactions but no patches (`patches` is empty).
496    pub fn ledger_txs(&self, seq: u32) -> Res<Row> {
497        self.with(seq, |d, local| match d {
498            Data::Prepared(f) => f.row_txs(local),
499            Data::Rows(rows) => rows
500                .get(local)
501                .map(|r| Row {
502                    seq: r.seq,
503                    header: r.header.clone(),
504                    txs: r.txs.clone(),
505                    patches: Vec::new(),
506                })
507                .ok_or("ledger extent".into()),
508        })
509    }
510    /// Transaction at original storage position `within` of ledger `seq`.
511    pub fn tx(&self, seq: u32, within: usize) -> Res<(Vec<u8>, Vec<u8>)> {
512        self.with(seq, |d, local| match d {
513            Data::Prepared(f) => {
514                let base: usize = (0..local).map(|k| f.txs_in(k).unwrap_or(0)).sum();
515                if f.txs_in(local).is_none_or(|n| within >= n) {
516                    return Err("TX extent".into());
517                }
518                f.tx(base + within)
519            }
520            Data::Rows(rows) => rows
521                .get(local)
522                .and_then(|r| r.txs.get(within))
523                .cloned()
524                .ok_or("TX extent".into()),
525        })
526    }
527    /// Transaction of ledger `seq` whose metadata has TransactionIndex `index`,
528    /// with the ledger's header; for a JC06 block only the part holding the
529    /// ledger is compiled.
530    pub fn tx_with_index(&self, seq: u32, index: u32) -> Res<Option<TxAt>> {
531        self.with(seq, |d, local| match d {
532            Data::Prepared(f) => match f.tx_with_index(local, index)? {
533                Some((tx, meta)) => Ok(Some(TxAt {
534                    header: f.header(local)?,
535                    tx,
536                    meta,
537                })),
538                None => Ok(None),
539            },
540            Data::Rows(rows) => {
541                let r = rows.get(local).ok_or("ledger extent")?;
542                Ok(r.txs
543                    .iter()
544                    .find(|(_, m)| matches!(**m, [0x20, 0x1C, a, b, c, d, ..] if u32::from_be_bytes([a, b, c, d]) == index))
545                    .map(|(tx, meta)| TxAt {
546                        header: r.header.clone(),
547                        tx: tx.clone(),
548                        meta: meta.clone(),
549                    }))
550            }
551        })
552    }
553}
554#[cfg(test)]
555mod tests {
556    use super::*;
557    fn rows(first: u32, n: u32) -> Vec<Row> {
558        let mut out: Vec<Row> = vec![];
559        let mut parent = [0u8; 32];
560        for k in 0..n {
561            let mut header = vec![0u8; 118];
562            header[..4].copy_from_slice(&(first + k).to_be_bytes());
563            header[12..44].copy_from_slice(&parent);
564            parent = LedgerHeader::parse(&header).unwrap().hash();
565            out.push(Row {
566                seq: first + k,
567                header,
568                txs: vec![],
569                patches: vec![([k as u8; 32], vec![0x11, 0, 0x61, k as u8])],
570            });
571        }
572        out
573    }
574    #[test]
575    fn pool_reads_exact_rows_concurrently_under_budget() {
576        let rs = rows(10, 50);
577        let (archive, _) = pack_bounded(&rs, 8, MAX, Options::default()).unwrap();
578        let dir = std::env::temp_dir().join(format!("astj5-pool-{}", std::process::id()));
579        std::fs::create_dir_all(&dir).unwrap();
580        let path = dir.join("a.astj");
581        std::fs::write(&path, &archive).unwrap();
582        let pool = Arc::new(Pool::open(&path, 1, 2).unwrap());
583        let hs: Vec<_> = (0..4)
584            .map(|t| {
585                let (pool, rs) = (pool.clone(), rs.clone());
586                std::thread::spawn(move || {
587                    for k in 0..50 {
588                        let r = &rs[(k * 7 + t) % 50];
589                        assert_eq!(pool.ledger(r.seq).unwrap(), *r);
590                    }
591                })
592            })
593            .collect();
594        for h in hs {
595            h.join().unwrap();
596        }
597        assert!(pool.ledger(9).is_err() && pool.ledger(60).is_err());
598        assert!(pool.slots.lock().unwrap().0.len() <= 4);
599        std::fs::remove_dir_all(&dir).unwrap();
600    }
601    #[test]
602    fn header_and_transactions_read_without_patches() {
603        let rs = rows(10, 20);
604        let (archive, _) = pack_bounded(&rs, 8, MAX, Options::default()).unwrap();
605        let dir = std::env::temp_dir().join(format!("astj5-pool-tx-{}", std::process::id()));
606        std::fs::create_dir_all(&dir).unwrap();
607        let path = dir.join("a.astj");
608        std::fs::write(&path, &archive).unwrap();
609        let pool = Pool::open(&path, 1 << 20, 2).unwrap();
610        for r in &rs {
611            assert_eq!(pool.header(r.seq).unwrap(), r.header);
612            let t = pool.ledger_txs(r.seq).unwrap();
613            assert_eq!((t.seq, &t.header, &t.txs), (r.seq, &r.header, &r.txs));
614            assert!(t.patches.is_empty() && !r.patches.is_empty());
615        }
616        assert!(pool.header(30).is_err() && pool.ledger_txs(9).is_err());
617        std::fs::remove_dir_all(&dir).unwrap();
618    }
619    #[test]
620    fn parts_are_compiled_as_their_ledgers_are_read() {
621        let rs = rows(10, 40);
622        let opt = Options {
623            joint: true,
624            adaptive: true,
625            context_delta: true,
626            split_shapes: true,
627            chronological: true,
628            cached_slots: true,
629            hash_order: true,
630            part_raw: 600,
631            ..Options::default()
632        };
633        let (archive, stats) = pack_bounded(&rs, 20, MAX, opt).unwrap();
634        assert!(stats.iter().all(|s| s.parts > 2));
635        assert_eq!(unpack(&archive).unwrap(), rs);
636        let dir = std::env::temp_dir().join(format!("astj5-pool-parts-{}", std::process::id()));
637        std::fs::create_dir_all(&dir).unwrap();
638        let path = dir.join("a.astj");
639        std::fs::write(&path, &archive).unwrap();
640        let seal = Pool::open(&path, 1 << 20, 2).unwrap().seal(2).unwrap();
641        assert!(seal.iter().all(|d| d.len() > 3));
642        let mut pool = Pool::open(&path, 1 << 20, 2).unwrap();
643        pool.set_seal(seal.clone()).unwrap();
644        assert_eq!(pool.header(31).unwrap(), rs[21].header);
645        let one = pool.cached_bytes();
646        assert_eq!(pool.ledger(12).unwrap(), rs[2]);
647        assert!(pool.cached_bytes() > one);
648        assert_eq!(pool.tx_with_index(15, 0).unwrap(), None);
649        for r in &rs {
650            assert_eq!(pool.ledger_txs(r.seq).unwrap().header, r.header);
651        }
652        // Unsealed, every block is checked in full.
653        let full = Pool::open(&path, 1 << 20, 2).unwrap();
654        assert_eq!(full.ledger(49).unwrap(), rs[39]);
655        // A changed byte in the last part of the first block: under the seal only
656        // reads that compile that part fail; unsealed, the whole block does.
657        let e = &full.entries[0];
658        let mut bad = archive.clone();
659        bad[e.offset as usize + e.length - 1] ^= 1;
660        std::fs::write(&path, &bad).unwrap();
661        let mut pool = Pool::open(&path, 1 << 20, 2).unwrap();
662        pool.set_seal(seal.clone()).unwrap();
663        assert_eq!(pool.ledger(10).unwrap(), rs[0]);
664        let err = pool.ledger(29).unwrap_err();
665        assert!(err.contains("seal"), "{err}");
666        assert_eq!(pool.ledger(30).unwrap(), rs[20]);
667        assert!(Pool::open(&path, 1 << 20, 2).unwrap().ledger(10).is_err());
668        std::fs::remove_dir_all(&dir).unwrap();
669    }
670    #[test]
671    fn parts_matched_once_are_remembered_across_evictions() {
672        let rs = rows(10, 40);
673        let opt = Options {
674            joint: true,
675            adaptive: true,
676            context_delta: true,
677            split_shapes: true,
678            chronological: true,
679            cached_slots: true,
680            hash_order: true,
681            part_raw: 600,
682            ..Options::default()
683        };
684        let (archive, _) = pack_bounded(&rs, 20, MAX, opt).unwrap();
685        let dir = std::env::temp_dir().join(format!("astj5-pool-memo-{}", std::process::id()));
686        std::fs::create_dir_all(&dir).unwrap();
687        let path = dir.join("a.astj");
688        std::fs::write(&path, &archive).unwrap();
689        let seal = Pool::open(&path, 1 << 20, 2).unwrap().seal(2).unwrap();
690        // One byte of budget: reading the other block evicts this one.
691        let mut pool = Pool::open(&path, 1, 1).unwrap();
692        pool.set_seal(seal.clone()).unwrap();
693        let flags = |pool: &Pool, b: usize| -> Vec<bool> {
694            pool.checked[b]
695                .iter()
696                .map(|f| f.load(Ordering::Acquire))
697                .collect()
698        };
699        assert!(flags(&pool, 0).iter().all(|f| !f));
700        for round in 0..3 {
701            for r in &rs {
702                assert_eq!(pool.ledger(r.seq).unwrap(), *r, "round {round}");
703            }
704            assert!((0..2).all(|b| flags(&pool, b).iter().all(|f| *f)));
705        }
706        assert_eq!(pool.memos.lock().unwrap().blocks.len(), 2);
707        // A part that does not match is never remembered: refused every time.
708        let e = &pool.entries[0];
709        let mut bad = archive.clone();
710        bad[e.offset as usize + e.length - 1] ^= 1;
711        std::fs::write(&path, &bad).unwrap();
712        let mut pool = Pool::open(&path, 1, 1).unwrap();
713        pool.set_seal(seal).unwrap();
714        for _ in 0..3 {
715            let err = pool.ledger(29).unwrap_err();
716            assert!(err.contains("seal"), "{err}");
717            assert_eq!(pool.ledger(30).unwrap(), rs[20]);
718        }
719        let f = flags(&pool, 0);
720        assert!(f[0] && !f[f.len() - 1]);
721        std::fs::remove_dir_all(&dir).unwrap();
722    }
723    #[test]
724    fn seal_skips_the_check_only_for_unchanged_blocks() {
725        for opts in [
726            Options::default(),
727            Options {
728                joint: true,
729                ..Options::default()
730            },
731        ] {
732            let rs = rows(10, 24);
733            let (archive, _) = pack_bounded(&rs, 8, MAX, opts).unwrap();
734            let dir = std::env::temp_dir().join(format!(
735                "astj5-pool-seal-{}-{}",
736                std::process::id(),
737                opts.joint
738            ));
739            std::fs::create_dir_all(&dir).unwrap();
740            let path = dir.join("a.astj");
741            std::fs::write(&path, &archive).unwrap();
742            let seal = Pool::open(&path, 1 << 20, 2).unwrap().seal(3).unwrap();
743            assert_eq!(seal.len(), 3);
744            assert!(seal.iter().all(|d| d.len() == 1));
745            let mut pool = Pool::open(&path, 1 << 20, 2).unwrap();
746            assert!(pool.set_seal(seal[..2].to_vec()).is_err());
747            pool.set_seal(seal.clone()).unwrap();
748            for r in &rs {
749                assert_eq!(pool.ledger(r.seq).unwrap(), *r);
750            }
751            // A changed byte in the middle block: its digest no longer matches,
752            // so the block is checked in full and fails.
753            let e = &pool.entries[1];
754            let mut bad = archive.clone();
755            bad[e.offset as usize + e.length - 1] ^= 1;
756            std::fs::write(&path, &bad).unwrap();
757            let mut pool = Pool::open(&path, 1 << 20, 2).unwrap();
758            pool.set_seal(seal.clone()).unwrap();
759            assert!(pool.ledger(10).is_ok() && pool.ledger(26).is_ok());
760            assert!(pool.ledger(18).is_err());
761            assert!(Pool::open(&path, 1 << 20, 2).unwrap().seal(2).is_err());
762            std::fs::remove_dir_all(&dir).unwrap();
763        }
764    }
765    #[test]
766    fn a_seal_is_trusted_for_the_bytes_it_names() {
767        // A wrong directory hash fails the full check; a digest over that hash
768        // and the stored bytes skips it, which is why only `seal` should
769        // produce one.
770        let rs = rows(10, 8);
771        let (archive, _) = pack_bounded(&rs, 8, MAX, Options::default()).unwrap();
772        let dir = std::env::temp_dir().join(format!("astj5-pool-trust-{}", std::process::id()));
773        std::fs::create_dir_all(&dir).unwrap();
774        let path = dir.join("a.astj");
775        std::fs::write(&path, &archive).unwrap();
776        let mut pool = Pool::open(&path, 1 << 20, 2).unwrap();
777        pool.entries[0].hash = [0; 32];
778        assert!(pool.seal(1).is_err() && pool.ledger(12).is_err());
779        let e = &pool.entries[0];
780        let payload = archive[e.offset as usize..e.offset as usize + e.length].to_vec();
781        let mut pool = Pool::open(&path, 1 << 20, 2).unwrap();
782        pool.entries[0].hash = [0; 32];
783        pool.set_seal(vec![vec![seal_digest(&[0; 32], &payload)]])
784            .unwrap();
785        assert_eq!(pool.ledger(12).unwrap(), rs[2]);
786        std::fs::remove_dir_all(&dir).unwrap();
787    }
788}