Skip to main content

heika_state_transition/tree/
lazy.rs

1//! 必要なノードだけをメモリに持つ状態の木。[`super::PatriciaTree`] と同じ根になる(catapult の
2//! `tree/PatriciaTree.h` と同じ形)が、葉を全部は持たない。
3//!
4//! ノードは根からの位置([`Position`])で呼び、保存にも位置で書いてある。葉を置くか外すときは、根からその葉までの
5//! 道のノードだけを読む。経路が食い違えばノードを割り、外して枝の子が1つになれば残った子と合わせる。ハッシュは、
6//! 変わったノードだけを下から求め直す。枝のノードは子のハッシュを 16 個とも持っているので、兄弟の中身は要らない。
7//!
8//! まだ読んでいないノードが要ったら、その位置を記録して何もしない。記録があった実行は捨てて、記録された位置を
9//! 読んでから当て直す。
10
11use std::collections::{BTreeMap, BTreeSet};
12
13use heika_core::hash::Hash256;
14use heika_core::patricia::TreeNode;
15
16use super::{EMPTY_ROOT, KEY_NIBBLES, Position, ROOT, mask, nibble, set_nibble};
17
18/// この深さまでの位置のノードは、捨てずにいつも持つ(根に近いノードは、ほぼどの葉の道にもある)
19const PINNED_DEPTH: u8 = 3;
20
21#[derive(Default, Debug)]
22pub struct LazyTree {
23    /// 読んだノード。`None` は、読んだらなかった位置
24    nodes: BTreeMap<Position, Option<TreeNode>>,
25    /// 根を求めるときに、ハッシュを求め直すノードの位置
26    stale: BTreeSet<Position>,
27    /// 前にノードの変化を返してから、変わった位置
28    changed: BTreeSet<Position>,
29    /// 変わった位置の、変える前のもの(`None` は読んでいなかった)。実行を捨てるときに戻す
30    originals: BTreeMap<Position, Option<Option<TreeNode>>>,
31    /// まだ読んでいないのに要った位置
32    missed: BTreeSet<Position>,
33    /// 位置を最後に使った世代。捨てるときに古いものから捨てる
34    used: BTreeMap<Position, u64>,
35    /// 今の世代([`LazyTree::set_generation`])
36    generation: u64,
37}
38
39/// `position` のノード `node` の、経路の終わりまでのニブルを入れたキー(後ろは0)
40fn node_prefix(position: &Position, path: &[u8]) -> [u8; 32] {
41    let mut prefix = position.1;
42    for (index, &value) in path.iter().enumerate() {
43        set_nibble(&mut prefix, usize::from(position.0) + index, value);
44    }
45    prefix
46}
47
48/// 経路が `end` 個目のニブルで終わる枝の、ニブル `value` の子の位置
49fn child_position(prefix: &[u8; 32], end: usize, value: u8) -> Position {
50    let mut child = mask(prefix, end);
51    set_nibble(&mut child, end, value);
52    ((end + 1) as u8, child)
53}
54
55fn nibbles(key: &[u8; 32], from: usize, to: usize) -> Vec<u8> {
56    (from..to).map(|index| nibble(key, index)).collect()
57}
58
59fn no_links() -> Box<[Option<Hash256>; 16]> {
60    Box::new([None; 16])
61}
62
63/// 枝の子を置き直すときに入れておく仮のハッシュ。根を求めるときに本物にする
64const PENDING_LINK: Hash256 = Hash256([0xFF; 32]);
65
66impl LazyTree {
67    pub fn new() -> Self {
68        Self::default()
69    }
70
71    /// 読んだノードを入れる。`None` は、読んだらなかった。すでに持っていれば何もしない(変えたものを消さない)
72    pub fn load(&mut self, position: Position, node: Option<TreeNode>) {
73        self.nodes.entry(position).or_insert(node);
74        self.used.insert(position, self.generation);
75    }
76
77    /// これから読むか使うノードを、世代 `generation` で使ったことにする
78    pub fn set_generation(&mut self, generation: u64) {
79        self.generation = generation;
80    }
81
82    pub fn is_loaded(&self, position: &Position) -> bool {
83        self.nodes.contains_key(position)
84    }
85
86    /// 根から `key` の葉までの道で、次に読むべき位置。全部読んであれば `None`。足すときに食い違うところまでと、
87    /// 外すときに合わせる兄弟は含まない(それは当てる途中で記録される)
88    pub fn next_on_path(&self, key: &[u8; 32]) -> Option<Position> {
89        let mut position = ROOT;
90        loop {
91            let Some(node) = self.nodes.get(&position) else {
92                return Some(position);
93            };
94            let Some(TreeNode::Branch { path, links }) = node else {
95                return None;
96            };
97            let depth = usize::from(position.0);
98            let end = depth + path.len();
99            if (0..path.len()).any(|index| path[index] != nibble(key, depth + index)) {
100                return None;
101            }
102            let value = nibble(key, end);
103            links[usize::from(value)]?;
104            position = child_position(key, end, value);
105        }
106    }
107
108    /// まだ読んでいないのに要った位置
109    pub fn take_missed(&mut self) -> BTreeSet<Position> {
110        std::mem::take(&mut self.missed)
111    }
112
113    fn get(&mut self, position: &Position) -> Option<Option<TreeNode>> {
114        match self.nodes.get(position) {
115            Some(node) => {
116                self.used.insert(*position, self.generation);
117                Some(node.clone())
118            }
119            None => {
120                self.missed.insert(*position);
121                None
122            }
123        }
124    }
125
126    /// 道の上の枝に、ハッシュを求め直す印を付ける。根を求めるときに子のハッシュが書き換わるので、変える前を取っておく
127    fn touch(&mut self, position: Position) {
128        let before = self.nodes.get(&position).cloned();
129        self.originals.entry(position).or_insert(before);
130        self.stale.insert(position);
131        self.changed.insert(position);
132    }
133
134    fn put(&mut self, position: Position, node: Option<TreeNode>) {
135        let before = self.nodes.insert(position, node);
136        self.originals.entry(position).or_insert(before);
137        self.stale.insert(position);
138        self.changed.insert(position);
139    }
140
141    /// 葉を置く。同じキーがあれば値を置き換える。読んでいないノードが要ったら、記録して何もしない
142    pub fn set(&mut self, key: Hash256, value: Hash256) {
143        let key = key.0;
144        let mut position = ROOT;
145        let mut above = Vec::new();
146        loop {
147            let Some(node) = self.get(&position) else {
148                return;
149            };
150            let depth = usize::from(position.0);
151            match node {
152                None => {
153                    // 空の木か、枝の空いた子
154                    self.put(
155                        position,
156                        Some(TreeNode::Leaf {
157                            path: nibbles(&key, depth, KEY_NIBBLES),
158                            value,
159                        }),
160                    );
161                    break;
162                }
163                Some(TreeNode::Leaf { path, value: old }) => {
164                    let split =
165                        (0..path.len()).find(|&index| path[index] != nibble(&key, depth + index));
166                    let Some(split) = split else {
167                        if old != value {
168                            self.put(position, Some(TreeNode::Leaf { path, value }));
169                        } else {
170                            return;
171                        }
172                        break;
173                    };
174                    let leaf_key = node_prefix(&position, &path);
175                    self.split(
176                        position,
177                        &key,
178                        &path,
179                        split,
180                        TreeNode::Leaf {
181                            path: path[split + 1..].to_vec(),
182                            value: old,
183                        },
184                        &leaf_key,
185                        value,
186                    );
187                    break;
188                }
189                Some(TreeNode::Branch { path, links }) => {
190                    let split =
191                        (0..path.len()).find(|&index| path[index] != nibble(&key, depth + index));
192                    if let Some(split) = split {
193                        let branch_key = node_prefix(&position, &path);
194                        self.split(
195                            position,
196                            &key,
197                            &path,
198                            split,
199                            TreeNode::Branch {
200                                path: path[split + 1..].to_vec(),
201                                links,
202                            },
203                            &branch_key,
204                            value,
205                        );
206                        break;
207                    }
208                    let end = depth + path.len();
209                    let child_value = nibble(&key, end);
210                    let child = child_position(&key, end, child_value);
211                    above.push(position);
212                    if links[usize::from(child_value)].is_none() {
213                        let mut links = links;
214                        links[usize::from(child_value)] = Some(PENDING_LINK);
215                        self.put(position, Some(TreeNode::Branch { path, links }));
216                        self.put(
217                            child,
218                            Some(TreeNode::Leaf {
219                                path: nibbles(&key, end + 1, KEY_NIBBLES),
220                                value,
221                            }),
222                        );
223                        // 空いていた子の位置に、前に外した葉の読み込みが残っていても上書きする
224                        break;
225                    }
226                    position = child;
227                }
228            }
229        }
230        for position in above {
231            self.touch(position);
232        }
233    }
234
235    /// `position` のノード(経路 `path`)を `split` 個目で割り、元のノードを `moved` にして下へ動かし、`key` の
236    /// 葉を足す。`moved_key` は元のノードの経路の終わりまでのキー
237    #[allow(clippy::too_many_arguments)]
238    fn split(
239        &mut self,
240        position: Position,
241        key: &[u8; 32],
242        path: &[u8],
243        split: usize,
244        moved: TreeNode,
245        moved_key: &[u8; 32],
246        value: Hash256,
247    ) {
248        let depth = usize::from(position.0);
249        let end = depth + split;
250        let mut links = no_links();
251        let moved_value = path[split];
252        let new_value = nibble(key, end);
253        links[usize::from(moved_value)] = Some(PENDING_LINK);
254        links[usize::from(new_value)] = Some(PENDING_LINK);
255        self.put(
256            position,
257            Some(TreeNode::Branch {
258                path: path[..split].to_vec(),
259                links,
260            }),
261        );
262        self.put(child_position(moved_key, end, moved_value), Some(moved));
263        self.put(
264            child_position(key, end, new_value),
265            Some(TreeNode::Leaf {
266                path: nibbles(key, end + 1, KEY_NIBBLES),
267                value,
268            }),
269        );
270    }
271
272    /// 葉を外す。なければ何もしない。読んでいないノードが要ったら、記録して何もしない
273    pub fn remove(&mut self, key: &Hash256) {
274        let key = key.0;
275        let mut position = ROOT;
276        // 道の上の枝と、そこから進んだニブル
277        let mut above: Vec<(Position, u8)> = Vec::new();
278        loop {
279            let Some(node) = self.get(&position) else {
280                return;
281            };
282            let depth = usize::from(position.0);
283            match node {
284                None => return,
285                Some(TreeNode::Leaf { path, .. }) => {
286                    if (0..path.len()).any(|index| path[index] != nibble(&key, depth + index)) {
287                        return;
288                    }
289                    break;
290                }
291                Some(TreeNode::Branch { path, links }) => {
292                    if (0..path.len()).any(|index| path[index] != nibble(&key, depth + index)) {
293                        return;
294                    }
295                    let end = depth + path.len();
296                    let value = nibble(&key, end);
297                    if links[usize::from(value)].is_none() {
298                        return;
299                    }
300                    above.push((position, value));
301                    position = child_position(&key, end, value);
302                }
303            }
304        }
305        let leaf = position;
306        let Some((parent, value)) = above.pop() else {
307            // 根が葉だった
308            self.put(leaf, None);
309            return;
310        };
311        let Some(Some(TreeNode::Branch { path, mut links })) = self.nodes.get(&parent).cloned()
312        else {
313            return;
314        };
315        links[usize::from(value)] = None;
316        let remaining: Vec<usize> = (0..16).filter(|&index| links[index].is_some()).collect();
317        if let [only] = remaining[..] {
318            // 子が1つになった枝は、残った子と合わせる
319            let end = usize::from(parent.0) + path.len();
320            let parent_key = node_prefix(&parent, &path);
321            let sibling = child_position(&parent_key, end, only as u8);
322            let Some(sibling_node) = self.get(&sibling) else {
323                return;
324            };
325            let Some(sibling_node) = sibling_node else {
326                return;
327            };
328            let mut merged_path = path.clone();
329            merged_path.push(only as u8);
330            let merged = match sibling_node {
331                TreeNode::Leaf {
332                    path: sibling_path,
333                    value,
334                } => {
335                    merged_path.extend(sibling_path);
336                    TreeNode::Leaf {
337                        path: merged_path,
338                        value,
339                    }
340                }
341                TreeNode::Branch {
342                    path: sibling_path,
343                    links,
344                } => {
345                    merged_path.extend(sibling_path);
346                    TreeNode::Branch {
347                        path: merged_path,
348                        links,
349                    }
350                }
351            };
352            self.put(leaf, None);
353            self.put(sibling, None);
354            self.put(parent, Some(merged));
355        } else {
356            self.put(leaf, None);
357            self.put(parent, Some(TreeNode::Branch { path, links }));
358        }
359        for (position, _) in above {
360            self.touch(position);
361        }
362    }
363
364    /// 根のハッシュ。空なら [`EMPTY_ROOT`]。根を読んでいなければ、記録して [`EMPTY_ROOT`]
365    pub fn root(&mut self) -> Hash256 {
366        if self.stale.contains(&ROOT) {
367            self.rehash(ROOT);
368        }
369        self.stale.clear();
370        match self.get(&ROOT) {
371            Some(Some(node)) => node.hash(),
372            _ => EMPTY_ROOT,
373        }
374    }
375
376    /// `position` より下の、ハッシュを求め直す子の分を枝に入れ直して、このノードのハッシュを返す
377    fn rehash(&mut self, position: Position) -> Option<Hash256> {
378        let node = self.nodes.get(&position).cloned().flatten()?;
379        let TreeNode::Branch { path, mut links } = node else {
380            return Some(node.hash());
381        };
382        let end = usize::from(position.0) + path.len();
383        let prefix = node_prefix(&position, &path);
384        let mut updated = false;
385        for value in 0..16u8 {
386            let child = child_position(&prefix, end, value);
387            if links[usize::from(value)].is_some() && self.stale.contains(&child) {
388                links[usize::from(value)] = self.rehash(child);
389                updated = true;
390            }
391        }
392        let node = TreeNode::Branch { path, links };
393        let hash = node.hash();
394        if updated {
395            self.nodes.insert(position, Some(node));
396        }
397        Some(hash)
398    }
399
400    /// 前に呼んでから変わったノード。位置と、今のノードか、なくなったら `None`。[`LazyTree::root`] のあとで呼ぶ
401    pub fn take_node_changes(&mut self) -> Vec<(Position, Option<TreeNode>)> {
402        self.root();
403        self.originals.clear();
404        std::mem::take(&mut self.changed)
405            .into_iter()
406            .map(|position| (position, self.nodes.get(&position).cloned().flatten()))
407            .collect()
408    }
409
410    /// 前にノードの変化を返してから変えたノードを、変える前に戻す。保存に書かずに実行を捨てるとき
411    pub fn discard_changes(&mut self) {
412        for (position, before) in std::mem::take(&mut self.originals) {
413            match before {
414                Some(node) => {
415                    self.nodes.insert(position, node);
416                }
417                None => {
418                    self.nodes.remove(&position);
419                }
420            }
421        }
422        self.changed.clear();
423        self.stale.clear();
424        self.missed.clear();
425    }
426
427    /// ノードの変化を返さずに捨てる。保存にあるものと同じ木のとき
428    pub fn forget_node_changes(&mut self) {
429        self.changed.clear();
430        self.originals.clear();
431    }
432
433    /// 読んだノードが `capacity` を超えていれば、根に近いノードと変わったノードのほかを、使った世代の古いほうから
434    /// 捨てる。捨てた数
435    pub fn evict(&mut self, capacity: usize) -> usize {
436        if self.nodes.len() <= capacity {
437            return 0;
438        }
439        let mut candidates: Vec<(u64, Position)> = self
440            .nodes
441            .keys()
442            .filter(|position| position.0 > PINNED_DEPTH && !self.changed.contains(position))
443            .map(|position| (self.used.get(position).copied().unwrap_or(0), *position))
444            .collect();
445        candidates.sort_unstable_by_key(|(generation, _)| *generation);
446        let excess = self.nodes.len() - capacity;
447        let mut evicted = 0;
448        for (_, position) in candidates.into_iter().take(excess) {
449            self.nodes.remove(&position);
450            self.used.remove(&position);
451            evicted += 1;
452        }
453        evicted
454    }
455
456    /// 読んだノードの数
457    pub fn len(&self) -> usize {
458        self.nodes.len()
459    }
460
461    pub fn is_empty(&self) -> bool {
462        self.nodes.is_empty()
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use std::collections::HashMap;
469
470    use super::super::PatriciaTree;
471    use super::*;
472
473    /// 決まった乱数
474    struct Rng(u64);
475
476    impl Rng {
477        fn next(&mut self) -> u64 {
478            self.0 ^= self.0 << 13;
479            self.0 ^= self.0 >> 7;
480            self.0 ^= self.0 << 17;
481            self.0
482        }
483
484        fn key(&mut self) -> [u8; 32] {
485            let mut key = [0; 32];
486            for chunk in key.chunks_mut(8) {
487                chunk.copy_from_slice(&self.next().to_le_bytes());
488            }
489            key
490        }
491    }
492
493    /// 保存の代わり。コミットしたノードを位置で持つ
494    #[derive(Default)]
495    struct Store(HashMap<Position, TreeNode>);
496
497    impl Store {
498        fn commit(&mut self, changes: Vec<(Position, Option<TreeNode>)>) {
499            for (position, node) in changes {
500                match node {
501                    Some(node) => self.0.insert(position, node),
502                    None => self.0.remove(&position),
503                };
504            }
505        }
506
507        /// `keys` の道を先に読み、足りないノードを読みながら、`apply` が記録なしで済むまで繰り返す
508        fn run(&self, tree: &mut LazyTree, keys: &[[u8; 32]], apply: impl Fn(&mut LazyTree)) {
509            for key in keys {
510                while let Some(position) = tree.next_on_path(key) {
511                    tree.load(position, self.0.get(&position).cloned());
512                }
513            }
514            loop {
515                apply(tree);
516                let missed = tree.take_missed();
517                if missed.is_empty() {
518                    return;
519                }
520                tree.discard_changes();
521                for position in missed {
522                    tree.load(position, self.0.get(&position).cloned());
523                }
524            }
525        }
526    }
527
528    #[test]
529    fn matches_the_full_tree_through_inserts_updates_and_removals() {
530        let mut rng = Rng(0x1234_5678_9ABC_DEF1);
531        let mut full = PatriciaTree::new();
532        let mut store = Store::default();
533        let mut keys: Vec<[u8; 32]> = Vec::new();
534        for round in 0..300 {
535            // 毎回新しい木で、保存から必要な分だけ読む
536            let mut lazy = LazyTree::new();
537            let mut operations = Vec::new();
538            for _ in 0..(1 + rng.next() % 20) {
539                let roll = rng.next() % 10;
540                if roll < 5 || keys.is_empty() {
541                    // 似たキーを作って、深いところで割れるようにする
542                    let mut key = rng.key();
543                    if !keys.is_empty() && roll < 2 {
544                        let base = keys[(rng.next() as usize) % keys.len()];
545                        let shared = (rng.next() % 31) as usize;
546                        key[..shared].copy_from_slice(&base[..shared]);
547                    }
548                    keys.push(key);
549                    operations.push((key, Some(Hash256(rng.key()))));
550                } else if roll < 8 {
551                    let key = keys[(rng.next() as usize) % keys.len()];
552                    operations.push((key, Some(Hash256(rng.key()))));
553                } else {
554                    let index = (rng.next() as usize) % keys.len();
555                    operations.push((keys.swap_remove(index), None));
556                }
557            }
558            for (key, value) in &operations {
559                match value {
560                    Some(value) => full.set(Hash256(*key), *value),
561                    None => full.remove(&Hash256(*key)),
562                }
563            }
564            let touched: Vec<[u8; 32]> = operations.iter().map(|(key, _)| *key).collect();
565            store.run(&mut lazy, &touched, |tree| {
566                for (key, value) in &operations {
567                    match value {
568                        Some(value) => tree.set(Hash256(*key), *value),
569                        None => tree.remove(&Hash256(*key)),
570                    }
571                }
572                tree.root();
573            });
574            assert_eq!(lazy.root(), full.root(), "{round} 回目");
575            // 捨てて当て直しても同じになる(当てる途中で足りないものがあったときと同じ)
576            if round % 3 == 0 {
577                lazy.discard_changes();
578                for (key, value) in &operations {
579                    match value {
580                        Some(value) => lazy.set(Hash256(*key), *value),
581                        None => lazy.remove(&Hash256(*key)),
582                    }
583                }
584                assert!(lazy.take_missed().is_empty(), "{round} 回目");
585                assert_eq!(
586                    lazy.root(),
587                    full.root(),
588                    "{round} 回目、捨てて当て直したもの"
589                );
590            }
591            store.commit(lazy.take_node_changes());
592            // 保存にあるノードが、全部持つ木のノードと同じになる(全部比べるのは重いので、ときどき)
593            if round % 20 == 19 {
594                let expected: HashMap<Position, TreeNode> = full.nodes().into_iter().collect();
595                assert_eq!(store.0, expected, "{round} 回目");
596            }
597        }
598    }
599
600    #[test]
601    fn putting_leaves_back_after_eviction_needs_loading() {
602        // 根に近い段より深く葉が並ぶくらいの木
603        let mut rng = Rng(11);
604        let mut full = PatriciaTree::new();
605        let keys: Vec<[u8; 32]> = (0..20_000).map(|_| rng.key()).collect();
606        let before: Vec<Hash256> = keys.iter().map(|_| Hash256(rng.key())).collect();
607        for (key, value) in keys.iter().zip(&before) {
608            full.set(Hash256(*key), *value);
609        }
610        let old_root = full.root();
611        let mut store = Store(full.nodes().into_iter().collect());
612        // ブロックを当てて書き、読んだノードを手放す
613        let mut lazy = LazyTree::new();
614        let changed = &keys[..50];
615        store.run(&mut lazy, changed, |tree| {
616            for key in changed {
617                tree.set(Hash256(*key), Hash256([7; 32]));
618            }
619            tree.root();
620        });
621        store.commit(lazy.take_node_changes());
622        lazy.evict(0);
623        // 読み直さずに葉を前の値に戻すと、読んでいないノードの書き戻しが抜け、根が戻らない(巻き戻しで起きたこと)
624        for (key, value) in changed.iter().zip(&before) {
625            lazy.set(Hash256(*key), *value);
626        }
627        assert!(!lazy.take_missed().is_empty());
628        assert_ne!(lazy.root(), old_root);
629        // 足りないノードを読みながら戻せば、前の根になる
630        let mut lazy = LazyTree::new();
631        store.run(&mut lazy, changed, |tree| {
632            for (key, value) in changed.iter().zip(&before) {
633                tree.set(Hash256(*key), *value);
634            }
635            tree.root();
636        });
637        assert_eq!(lazy.root(), old_root);
638    }
639
640    #[test]
641    fn walks_the_path_to_load() {
642        let mut full = PatriciaTree::new();
643        let mut rng = Rng(7);
644        let keys: Vec<[u8; 32]> = (0..200).map(|_| rng.key()).collect();
645        for key in &keys {
646            full.set(Hash256(*key), Hash256(rng.key()));
647        }
648        let store: HashMap<Position, TreeNode> = full.nodes().into_iter().collect();
649        let mut lazy = LazyTree::new();
650        let mut reads = 0;
651        while let Some(position) = lazy.next_on_path(&keys[3]) {
652            lazy.load(position, store.get(&position).cloned());
653            reads += 1;
654        }
655        // 葉までの道だけを読む
656        assert!(reads <= 4, "{reads}");
657        lazy.set(Hash256(keys[3]), Hash256([9; 32]));
658        assert!(lazy.take_missed().is_empty());
659        full.set(Hash256(keys[3]), Hash256([9; 32]));
660        assert_eq!(lazy.root(), full.root());
661    }
662}