-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtree.rs
More file actions
3135 lines (2762 loc) · 119 KB
/
Copy pathtree.rs
File metadata and controls
3135 lines (2762 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use crate::config::TreeConfig;
use crate::diff::{
ConflictResolver, DiffResult, IgnoreConflictsResolver, MergeConflict, MergeResult,
};
use crate::digest::ValueDigest;
use crate::node::{Node, ProllyNode};
use crate::proof::Proof;
use crate::storage::NodeStorage;
use std::sync::Arc;
/// Trait representing a Prolly tree with a fixed size N and a node storage S.
/// This trait provides methods for creating, modifying, and querying the tree.
pub trait Tree<const N: usize, S: NodeStorage<N>> {
/// Creates a new Prolly tree with the specified root node and storage.
///
/// # Parameters
/// - `storage`: The storage to use for persisting nodes.
/// - `config`: The configuration for the tree.
///
/// # Returns
/// - A new instance of the tree.
fn new(storage: S, config: TreeConfig<N>) -> Self;
/// Inserts a key-value pair into the tree.
///
/// # Parameters
/// - `key`: The key to insert.
/// - `value`: The value associated with the key.
fn insert(&mut self, key: Vec<u8>, value: Vec<u8>);
/// Inserts multiple key-value pairs into the tree in an optimized way.
///
/// # Parameters
/// - `keys`: The keys to insert.
/// - `values`: The values associated with the keys.
fn insert_batch(&mut self, keys: &[Vec<u8>], values: &[Vec<u8>]);
/// Updates the value associated with the specified key in the tree.
///
/// # Parameters
/// - `key`: The key to update.
/// - `value`: The new value to associate with the key.
///
/// # Returns
/// - `true` if the key was found and updated, `false` otherwise.
fn update(&mut self, key: Vec<u8>, value: Vec<u8>) -> bool;
/// Deletes the key-value pair associated with the specified key from the tree.
///
/// # Parameters
/// - `key`: The key to delete.
///
/// # Returns
/// - `true` if the key was found and deleted, `false` otherwise.
fn delete(&mut self, key: &[u8]) -> bool;
/// Deletes multiple key-value pairs from the tree.
///
/// # Parameters
/// - `keys`: The keys to delete.
fn delete_batch(&mut self, keys: &[Vec<u8>]);
/// Finds the node associated with the specified key in the tree.
///
/// # Parameters
/// - `key`: The key to find.
///
/// # Returns
/// - `Some(ProllyNode<N>)` if the key was found, `None` otherwise.
fn find(&self, key: &[u8]) -> Option<ProllyNode<N>>;
/// Traverses the tree and returns a string representation of its structure.
///
/// # Returns
/// - A string representation of the tree structure.
fn traverse(&self) -> String;
/// Traverses the tree and returns a formatted string representation using the provided formatter function.
///
/// # Parameters
/// - `formatter`: A function to format each node.
///
/// # Returns
/// - A formatted string representation of the tree structure.
fn formatted_traverse<F>(&self, formatter: F) -> String
where
F: Fn(&ProllyNode<N>) -> String;
/// Gets the hash of the root node of the tree.
///
/// # Returns
/// - `Some(ValueDigest<N>)` if the root node exists, `None` otherwise.
fn get_root_hash(&self) -> Option<ValueDigest<N>>;
/// Gets the number of nodes in the tree.
///
/// # Returns
/// - The number of nodes in the tree.
fn size(&self) -> usize;
/// Gets the depth of the tree.
///
/// # Returns
/// - The depth of the tree.
fn depth(&self) -> usize;
/// Provides a summary of the tree structure and contents.
///
/// # Returns
/// - A summary of the tree.
fn summary(&self) -> String;
/// Provides various statistics about the tree.
///
/// # Returns
/// - A `TreeStats` object containing statistics about the tree.
fn stats(&self) -> TreeStats;
/// Loads the configuration for the tree from storage.
///
/// # Parameters
/// - `storage`: The storage to load the configuration from.
fn load_config(storage: &S) -> Result<TreeConfig<N>, &'static str>;
/// Saves the configuration for the tree to storage.
///
/// # Returns
/// - `Ok(())` if the configuration was saved successfully, `Err(&'static str)` otherwise.
fn save_config(&self) -> Result<(), &'static str>;
/// Generates a proof of existence for a given key in the tree.
///
/// This function traverses the tree from the root to the target node containing the key,
/// collecting the hashes of all nodes along the path. The proof can be used to verify the
/// existence of the key and its associated value without revealing other data in the tree.
///
/// # Arguments
///
/// * `key` - The key for which to generate the proof.
///
/// # Returns
///
/// A `Proof` struct containing the path of hashes and the hash of the target node (if the key exists).
fn generate_proof(&self, key: &[u8]) -> Proof<N>;
fn verify(&self, proof: Proof<N>, key: &[u8], expected_value: Option<&[u8]>) -> bool;
/// Computes the differences between two Prolly Trees.
///
/// This function compares the current tree (`self`) with another tree (`other`)
/// and identifies the differences between them. It traverses both trees and
/// generates a list of changes, including added, removed, and modified key-value pairs.
///
/// # Arguments
///
/// * `other` - The other Prolly Tree to compare against.
///
/// # Returns
///
/// A vector of `DiffResult` containing the differences between the two trees.
fn diff(&self, other: &Self) -> Vec<DiffResult>;
/// Prints the tree structure to the console.
/// This function is useful for debugging and visualizing the tree.
/// It prints the tree structure in a human-readable format.
/// The tree is printed in a depth-first manner, starting from the root node.
/// Each node is printed with its keys and values, along with the hash of the node.
///
fn print(&mut self);
/// Prints the tree structure with the proof path highlighted for a given key.
/// This function combines `generate_proof` and `print` to visualize the
/// cryptographic proof path through the tree structure with color coding.
///
/// # Arguments
///
/// * `key` - The key for which to generate and display the proof path.
///
/// # Returns
///
/// A boolean indicating whether the proof is valid.
fn print_proof(&self, key: &[u8]) -> bool;
/// Performs a three-way merge between source, destination and base trees.
///
/// This function implements a three-way merge algorithm for prolly trees.
/// Given three tree root hashes (base, source, destination), it computes
/// the differences between base->source and base->destination, then merges
/// changes from source into destination, detecting conflicts when both
/// branches modify the same key with different values.
///
/// # Arguments
///
/// * `source_root` - Root hash of the source (feature) tree
/// * `destination_root` - Root hash of the destination (main) tree
/// * `base_root` - Root hash of the common base tree
///
/// # Returns
///
/// A vector of `MergeResult` indicating the changes to apply and any conflicts
fn merge(
&self,
source_root: &ValueDigest<N>,
destination_root: &ValueDigest<N>,
base_root: &ValueDigest<N>,
) -> Vec<MergeResult>;
/// Applies merge results to create a new merged tree.
///
/// This method takes the destination tree and applies a list of merge results
/// to create a new tree with all the merged changes. If any conflicts are
/// present in the merge results, this method will return an error.
///
/// # Arguments
///
/// * `destination_root` - Root hash of the destination tree to merge into
/// * `merge_results` - List of merge operations to apply
///
/// # Returns
///
/// A new `ProllyTree` instance with merged changes, or an error if conflicts exist
fn apply_merge_results(
&self,
destination_root: &ValueDigest<N>,
merge_results: &[MergeResult],
) -> Result<Self, Vec<MergeConflict>>
where
Self: Sized;
/// Convenience method to perform a three-way merge with conflict resolution.
///
/// This method combines `merge()` and `apply_merge_results()` with a conflict resolver
/// to provide a flexible interface for merging. Conflicts that can't be resolved
/// are returned for manual resolution.
///
/// # Arguments
///
/// * `source_root` - Root hash of the source (feature) tree
/// * `destination_root` - Root hash of the destination (main) tree
/// * `base_root` - Root hash of the common base tree
/// * `resolver` - Conflict resolver to handle merge conflicts
///
/// # Returns
///
/// Either a new merged tree or a list of unresolved conflicts
fn merge_trees<R: ConflictResolver>(
&self,
source_root: &ValueDigest<N>,
destination_root: &ValueDigest<N>,
base_root: &ValueDigest<N>,
resolver: &R,
) -> Result<Self, Vec<MergeConflict>>
where
Self: Sized;
/// Convenience method for merge_trees with default IgnoreConflictsResolver
fn merge_trees_ignore_conflicts(
&self,
source_root: &ValueDigest<N>,
destination_root: &ValueDigest<N>,
base_root: &ValueDigest<N>,
) -> Result<Self, Vec<MergeConflict>>
where
Self: Sized,
{
self.merge_trees(
source_root,
destination_root,
base_root,
&IgnoreConflictsResolver,
)
}
}
pub struct TreeStats {
pub num_nodes: usize,
pub num_leaves: usize,
pub num_internal_nodes: usize,
pub avg_node_size: f64,
pub total_key_value_pairs: usize,
}
impl TreeStats {
pub fn new() -> Self {
TreeStats {
num_nodes: 0,
num_leaves: 0,
num_internal_nodes: 0,
avg_node_size: 0.0,
total_key_value_pairs: 0,
}
}
}
impl Default for TreeStats {
fn default() -> Self {
TreeStats::new()
}
}
#[derive(Debug, Clone)]
pub struct ProllyTree<const N: usize, S: NodeStorage<N>> {
pub root: ProllyNode<N>,
pub storage: S,
pub config: TreeConfig<N>,
}
impl<const N: usize, S: NodeStorage<N>> Tree<N, S> for ProllyTree<N, S> {
fn new(storage: S, config: TreeConfig<N>) -> Self {
let root = ProllyNode {
keys: Vec::new(),
key_schema: config.key_schema.clone(),
values: Vec::new(),
value_schema: config.value_schema.clone(),
is_leaf: true,
level: 0,
base: config.base,
modulus: config.modulus,
min_chunk_size: config.min_chunk_size,
max_chunk_size: config.max_chunk_size,
pattern: config.pattern,
split: false,
merged: false,
encode_types: Vec::new(),
encode_values: Vec::new(),
};
let root_hash = Some(root.get_hash());
let mut tree = ProllyTree {
root,
storage,
config,
};
tree.config.root_hash = root_hash;
tree
}
fn insert(&mut self, key: Vec<u8>, value: Vec<u8>) {
// Stream the single mutation through the cursor-driven chunker.
// This bypasses the legacy in-place balance code (which doesn't
// maintain history independence) and produces a canonical tree
// by construction.
self.apply_changes(std::iter::once((key, Some(value))));
self.persist_root();
}
fn insert_batch(&mut self, keys: &[Vec<u8>], values: &[Vec<u8>]) {
assert_eq!(
keys.len(),
values.len(),
"insert_batch requires the same number of keys and values"
);
let batch = keys.iter().cloned().zip(values.iter().cloned().map(Some));
self.apply_changes(batch);
}
fn update(&mut self, key: Vec<u8>, value: Vec<u8>) -> bool {
if self.find(&key).is_some() {
self.insert(key, value);
true
} else {
false
}
}
fn delete(&mut self, key: &[u8]) -> bool {
// Pre-check: was the key present? Same answer as before but
// computed via the cursor walk inside apply_changes' probe path.
if self.find(key).is_none() {
return false;
}
self.apply_changes(std::iter::once((key.to_vec(), None)));
self.persist_root();
true
}
fn delete_batch(&mut self, keys: &[Vec<u8>]) {
let batch = keys.iter().map(|k| (k.clone(), None));
self.apply_changes(batch);
}
fn find(&self, key: &[u8]) -> Option<ProllyNode<N>> {
self.root.find(key, &self.storage)
}
fn traverse(&self) -> String {
self.root.traverse(&self.storage)
}
fn formatted_traverse<F>(&self, formatter: F) -> String
where
F: Fn(&ProllyNode<N>) -> String,
{
self.root.formatted_traverse(&self.storage, formatter)
}
fn get_root_hash(&self) -> Option<ValueDigest<N>> {
Option::from(self.root.get_hash())
}
fn size(&self) -> usize {
fn count_pairs<const N: usize, S: NodeStorage<N>>(
node: &ProllyNode<N>,
storage: &S,
) -> usize {
if node.is_leaf {
node.keys.len()
} else {
let mut count = 0;
for value in &node.values {
if let Some(child_node) =
storage.get_node_by_hash(&ValueDigest::raw_hash(value))
{
count += count_pairs(&child_node, storage);
}
}
count
}
}
count_pairs(&self.root, &self.storage)
}
fn depth(&self) -> usize {
(self.root.level as usize) + 1
}
fn summary(&self) -> String {
let stats = self.stats();
format!(
"Tree Summary:\n- Number of Key-Value Pairs: {}\n- Number of Nodes: {}\n- Number of Leaves: {}\n- Number of Internal Nodes: {}\n- Average Leaf Node Size: {:.2}",
self.size(),
stats.num_nodes,
stats.num_leaves,
stats.num_internal_nodes,
stats.avg_node_size
)
}
fn stats(&self) -> TreeStats {
fn collect_stats<const N: usize, S: NodeStorage<N>>(
node: &ProllyNode<N>,
storage: &S,
stats: &mut TreeStats,
) {
stats.num_nodes += 1;
if node.is_leaf {
stats.num_leaves += 1;
stats.total_key_value_pairs += node.keys.len();
} else {
stats.num_internal_nodes += 1;
for value in &node.values {
if let Some(child_node) =
storage.get_node_by_hash(&ValueDigest::raw_hash(value))
{
collect_stats(&child_node, storage, stats);
}
}
}
}
let mut stats = TreeStats::new();
collect_stats(&self.root, &self.storage, &mut stats);
if stats.num_leaves > 0 {
stats.avg_node_size = stats.total_key_value_pairs as f64 / stats.num_leaves as f64;
}
stats
}
fn load_config(storage: &S) -> Result<TreeConfig<N>, &'static str> {
// Implement the logic to load the configuration from storage
// Here we assume the config is stored with a specific key "tree_config"
if let Some(config_data) = storage.get_config("tree_config") {
let config: TreeConfig<N> =
serde_json::from_slice(&config_data).map_err(|_| "Failed to deserialize config")?;
Ok(config)
} else {
Err("Config not found")
}
}
fn save_config(&self) -> Result<(), &'static str> {
let mut config = self.config.clone();
config.root_hash = Option::from(self.root.get_hash());
let config_data = serde_json::to_vec(&config).map_err(|_| "Failed to serialize config")?;
self.storage.save_config("tree_config", &config_data);
Ok(())
}
/// Generates a proof of existence for a given key in the tree.
///
/// This function traverses the tree from the root to the target node containing the key,
/// collecting the hashes of all nodes along the path. The proof can be used to verify the
/// existence of the key and its associated value without revealing other data in the tree.
///
/// # Arguments
///
/// * `key` - The key for which to generate the proof.
/// * `storage` - The storage implementation to retrieve child nodes.
///
/// # Returns
///
/// A `Proof` struct containing the path of hashes and the hash of the target node (if the key exists).
fn generate_proof(&self, key: &[u8]) -> Proof<N> {
/// Recursive helper function to generate the proof path.
///
/// This function traverses the tree from the given node to the target node containing the key,
/// collecting the hashes of all nodes along the path. It returns the hash of the target node
/// if the key exists, or `None` if the key does not exist.
///
/// # Arguments
///
/// * `node` - The current node being traversed.
/// * `key` - The key for which to generate the proof.
/// * `storage` - The storage implementation to retrieve child nodes.
/// * `path` - The vector to store the hashes of the nodes along the path.
///
/// # Returns
///
/// The hash of the target node if the key exists, or `None` if the key does not exist.
fn generate_proof_recursive<const N: usize, S: NodeStorage<N>>(
node: &ProllyNode<N>,
key: &[u8],
storage: &S,
path: &mut Vec<ValueDigest<N>>,
) -> Option<ValueDigest<N>> {
path.push(node.get_hash());
if node.is_leaf {
if node.keys.iter().any(|k| k == key) {
Some(node.get_hash())
} else {
None
}
} else {
// Mirror `ProllyNode::find`: after certain delete patterns an internal
// node can transiently have no children (or fewer values than keys), so
// guard the empty case and clamp the index instead of indexing out of
// bounds and panicking.
if node.values.is_empty() {
return None;
}
let i = node.keys.iter().rposition(|k| key >= &k[..]).unwrap_or(0);
let i = i.min(node.values.len() - 1);
let child_hash = node.values[i].clone();
if let Some(child_node) =
storage.get_node_by_hash(&ValueDigest::raw_hash(&child_hash))
{
generate_proof_recursive(&child_node, key, storage, path)
} else {
None
}
}
}
let mut path = Vec::new();
let target_hash = generate_proof_recursive(&self.root, key, &self.storage, &mut path);
Proof { path, target_hash }
}
fn verify(&self, proof: Proof<N>, key: &[u8], expected_value: Option<&[u8]>) -> bool {
// Start with the root hash
let mut current_hash = self.root.get_hash();
for (i, node_hash) in proof.path.iter().enumerate() {
// Retrieve the node content from storage using the current hash
if let Some(node) = self.storage.get_node_by_hash(¤t_hash) {
// Check if the current node's hash matches the expected hash in the path
if node.get_hash() != *node_hash {
return false;
}
// If it's the last node in the path, verify the leaf node
if i == proof.path.len() - 1 {
return if node.is_leaf {
node.keys.iter().any(|k| k == key)
&& match expected_value {
None => true,
Some(ev) => node.values.iter().any(|v| ev == &v[..]),
}
} else {
false // Path should end at a leaf node
};
}
// Move to the next node in the path by finding the correct child
let child_index = node.keys.iter().rposition(|k| key >= &k[..]).unwrap_or(0);
current_hash = ValueDigest::raw_hash(&node.values[child_index]);
} else {
// If the node is not found in storage, the proof is invalid
return false;
}
}
false // If we exit the loop without verifying, the proof is invalid
}
fn diff(&self, other: &Self) -> Vec<DiffResult> {
let mut diffs = Vec::new();
self.diff_recursive(&self.root, &other.root, &mut diffs);
diffs
}
fn print(&mut self) {
self.root.print_tree(&self.storage);
}
fn print_proof(&self, key: &[u8]) -> bool {
// Generate the proof for the given key
let proof = self.generate_proof(key);
// Verify the proof
let is_valid = self.verify(proof.clone(), key, None);
// Print the tree structure with proof path highlighted
#[cfg(feature = "tracing")]
tracing::debug!("root:");
#[cfg(not(feature = "tracing"))]
println!("root:");
self.root.print_tree_with_proof(&self.storage, &proof, key);
// Print proof information
#[cfg(feature = "tracing")]
{
tracing::debug!("Proof for key {:?} is valid: {}", key, is_valid);
tracing::debug!("Proof: {:#?}", proof);
}
#[cfg(not(feature = "tracing"))]
{
println!("\nProof for key {key:?} is valid: {is_valid}");
println!("Proof: {proof:#?}");
}
is_valid
}
fn merge(
&self,
source_root: &ValueDigest<N>,
destination_root: &ValueDigest<N>,
base_root: &ValueDigest<N>,
) -> Vec<MergeResult> {
// Load trees from storage using the provided root hashes
let source_tree = self.storage.get_node_by_hash(source_root);
let destination_tree = self.storage.get_node_by_hash(destination_root);
let base_tree = self.storage.get_node_by_hash(base_root);
let (source_tree, destination_tree, base_tree) =
match (source_tree, destination_tree, base_tree) {
(Some(s), Some(d), Some(b)) => (s, d, b),
_ => {
// If we can't load one of the trees, return an error as a conflict
return vec![MergeResult::Conflict(MergeConflict {
key: b"<merge_error>".to_vec(),
base_value: None,
source_value: None,
destination_value: Some(b"Failed to load tree from storage".to_vec()),
})];
}
};
// Compute diffs directly using the node-level diffing
let mut base_to_source_diffs = Vec::new();
let mut base_to_destination_diffs = Vec::new();
self.diff_nodes_recursive(&base_tree, &source_tree, &mut base_to_source_diffs);
self.diff_nodes_recursive(
&base_tree,
&destination_tree,
&mut base_to_destination_diffs,
);
// Convert diffs to maps for easier processing
let mut source_changes: std::collections::HashMap<Vec<u8>, DiffResult> =
std::collections::HashMap::new();
let mut destination_changes: std::collections::HashMap<Vec<u8>, DiffResult> =
std::collections::HashMap::new();
for diff in base_to_source_diffs {
let key = match &diff {
DiffResult::Added(k, _) => k.clone(),
DiffResult::Removed(k, _) => k.clone(),
DiffResult::Modified(k, _, _) => k.clone(),
};
source_changes.insert(key, diff);
}
for diff in base_to_destination_diffs {
let key = match &diff {
DiffResult::Added(k, _) => k.clone(),
DiffResult::Removed(k, _) => k.clone(),
DiffResult::Modified(k, _, _) => k.clone(),
};
destination_changes.insert(key, diff);
}
// Collect all keys that were changed in either branch
let mut all_changed_keys = std::collections::HashSet::new();
for key in source_changes.keys() {
all_changed_keys.insert(key.clone());
}
for key in destination_changes.keys() {
all_changed_keys.insert(key.clone());
}
let mut merge_results = Vec::new();
// Process each changed key
for key in all_changed_keys {
let source_change = source_changes.get(&key);
let destination_change = destination_changes.get(&key);
match (source_change, destination_change) {
// Only source changed - apply source change
(Some(source_diff), None) => match source_diff {
DiffResult::Added(_, value) => {
merge_results.push(MergeResult::Added(key, value.clone()));
}
DiffResult::Removed(_, _) => {
merge_results.push(MergeResult::Removed(key));
}
DiffResult::Modified(_, _, new_value) => {
merge_results.push(MergeResult::Modified(key, new_value.clone()));
}
},
// Only destination changed - no action needed (destination already has the change)
(None, Some(_)) => {
// Destination change already exists, no merge action needed
}
// Both changed - need to check for conflicts
(Some(source_diff), Some(destination_diff)) => {
let conflict =
self.detect_conflict(&key, source_diff, destination_diff, &base_tree);
if let Some(conflict) = conflict {
merge_results.push(MergeResult::Conflict(conflict));
} else {
// No conflict, apply source change (assuming identical changes)
match source_diff {
DiffResult::Added(_, value) => {
merge_results.push(MergeResult::Added(key, value.clone()));
}
DiffResult::Removed(_, _) => {
merge_results.push(MergeResult::Removed(key));
}
DiffResult::Modified(_, _, new_value) => {
merge_results.push(MergeResult::Modified(key, new_value.clone()));
}
}
}
}
// Neither changed (shouldn't happen due to our key collection logic)
(None, None) => {}
}
}
merge_results
}
fn apply_merge_results(
&self,
destination_root: &ValueDigest<N>,
merge_results: &[MergeResult],
) -> Result<Self, Vec<MergeConflict>> {
// Check for conflicts first
let mut conflicts = Vec::new();
for result in merge_results {
if let MergeResult::Conflict(conflict) = result {
conflicts.push((*conflict).clone());
}
}
if !conflicts.is_empty() {
return Err(conflicts);
}
// Load the destination tree
let destination_tree =
self.storage
.get_node_by_hash(destination_root)
.ok_or_else(|| {
vec![MergeConflict {
key: b"<apply_error>".to_vec(),
base_value: None,
source_value: None,
destination_value: Some(b"Failed to load destination tree".to_vec()),
}]
})?;
// Create a new tree starting from the destination
let mut new_tree = ProllyTree {
root: Arc::unwrap_or_clone(destination_tree),
storage: self.storage.clone(),
config: self.config.clone(),
};
// Apply each merge result
for result in merge_results {
match result {
MergeResult::Added(key, value) => {
new_tree.insert(key.clone(), value.clone());
}
MergeResult::Modified(key, value) => {
new_tree.insert(key.clone(), value.clone()); // insert overwrites existing
}
MergeResult::Removed(key) => {
new_tree.delete(key);
}
MergeResult::Conflict(_) => {
// This should not happen since we checked for conflicts above
unreachable!("Conflicts should have been filtered out");
}
}
}
Ok(new_tree)
}
fn merge_trees<R: ConflictResolver>(
&self,
source_root: &ValueDigest<N>,
destination_root: &ValueDigest<N>,
base_root: &ValueDigest<N>,
resolver: &R,
) -> Result<Self, Vec<MergeConflict>> {
let merge_results = self.merge(source_root, destination_root, base_root);
// Separate conflicts from other merge results and try to resolve conflicts
let mut resolved_results = Vec::new();
let mut unresolved_conflicts = Vec::new();
for result in merge_results {
match result {
MergeResult::Conflict(conflict) => {
if let Some(resolved_result) = resolver.resolve_conflict(&conflict) {
resolved_results.push(resolved_result);
} else {
unresolved_conflicts.push(conflict);
}
}
other => resolved_results.push(other),
}
}
// If there are still unresolved conflicts, return them
if !unresolved_conflicts.is_empty() {
return Err(unresolved_conflicts);
}
// Apply the resolved results
self.apply_merge_results(destination_root, &resolved_results)
}
}
impl<const N: usize, S: NodeStorage<N>> ProllyTree<N, S> {
/// Compute differences between two nodes recursively
fn diff_nodes_recursive(
&self,
old_node: &ProllyNode<N>,
new_node: &ProllyNode<N>,
diffs: &mut Vec<DiffResult>,
) {
// O(differences) structural diff (Dolt/Noms): the tree is content-addressed,
// so equal get_hash() => byte-identical subtree => zero diffs; skip it without
// loading. Descend only into differing children. Emits the IDENTICAL DiffResult
// set as the full-leaf flatten (diff_nodes_flatten), guarded by a differential test.
if old_node.get_hash() == new_node.get_hash() {
return;
}
match (old_node.is_leaf, new_node.is_leaf) {
(true, true) => {
let o: Vec<(Vec<u8>, Vec<u8>)> = old_node
.keys
.iter()
.cloned()
.zip(old_node.values.iter().cloned())
.collect();
let n: Vec<(Vec<u8>, Vec<u8>)> = new_node
.keys
.iter()
.cloned()
.zip(new_node.values.iter().cloned())
.collect();
self.merge_join_pairs(&o, &n, diffs);
}
(false, false) => self.diff_internal(old_node, new_node, diffs),
_ => {
// height divergence (one side shallower): flatten the divergent region.
let mut op = Vec::new();
self.collect_pairs_recursive(old_node, &mut op);
let mut np = Vec::new();
self.collect_pairs_recursive(new_node, &mut np);
self.merge_join_pairs(&op, &np, diffs);
}
}
}
/// Both nodes internal: skip children whose stored child-hash is equal (O(1), no
/// load), flatten + merge-join the rest. Provably identical to the full flatten:
/// a common child subtree has identical (k,v) on both sides => contributes no diff.
fn diff_internal(
&self,
old_node: &ProllyNode<N>,
new_node: &ProllyNode<N>,
diffs: &mut Vec<DiffResult>,
) {
use std::collections::HashSet;
// The node is content-addressed: an internal node's `values` ARE its child
// hashes, so byte-equal `values[i]` <=> identical child subtree (same (k,v)).
// Skip common children by hash WITHOUT loading them (the O(diff) win), and
// load only the differing children (mirroring `children()`'s raw_hash lookup).
let new_hashes: HashSet<&Vec<u8>> = new_node.values.iter().collect();
let old_hashes: HashSet<&Vec<u8>> = old_node.values.iter().collect();
let mut old_pairs: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
for child_hash in &old_node.values {
if new_hashes.contains(child_hash) {
continue; // identical subtree on the new side => contributes no diff
}
if let Some(child) = self
.storage
.get_node_by_hash(&ValueDigest::raw_hash(child_hash))
{
self.collect_pairs_recursive(&child, &mut old_pairs);
}
}
let mut new_pairs: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
for child_hash in &new_node.values {
if old_hashes.contains(child_hash) {
continue;
}
if let Some(child) = self
.storage
.get_node_by_hash(&ValueDigest::raw_hash(child_hash))
{
self.collect_pairs_recursive(&child, &mut new_pairs);
}
}
self.merge_join_pairs(&old_pairs, &new_pairs, diffs);
}
/// Merge-join two sorted (key,value) streams into DiffResults.
fn merge_join_pairs(
&self,
old_pairs: &[(Vec<u8>, Vec<u8>)],
new_pairs: &[(Vec<u8>, Vec<u8>)],
diffs: &mut Vec<DiffResult>,
) {
let mut oi = old_pairs.iter().peekable();
let mut ni = new_pairs.iter().peekable();
while let (Some((ok, ov)), Some((nk, nv))) = (oi.peek(), ni.peek()) {
match ok.cmp(nk) {
std::cmp::Ordering::Less => {
diffs.push(DiffResult::Removed(ok.clone(), ov.clone()));
oi.next();
}
std::cmp::Ordering::Greater => {
diffs.push(DiffResult::Added(nk.clone(), nv.clone()));
ni.next();
}
std::cmp::Ordering::Equal => {
if ov != nv {
diffs.push(DiffResult::Modified(ok.clone(), ov.clone(), nv.clone()));
}
oi.next();
ni.next();
}
}
}
for (ok, ov) in oi {
diffs.push(DiffResult::Removed(ok.clone(), ov.clone()));
}
for (nk, nv) in ni {
diffs.push(DiffResult::Added(nk.clone(), nv.clone()));
}
}
/// Proven full-leaf flatten diff — kept as the differential-test oracle.
#[cfg(test)]
fn diff_nodes_flatten(
&self,
old_node: &ProllyNode<N>,
new_node: &ProllyNode<N>,