clayers-repo 0.2.1

Content-addressed Merkle DAG repository for XML documents
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
//! Shared query tests.
//!
//! `QueryTester<S>` exercises `ObjectStore + RefStore + QueryStore` against
//! any backend. Each backend's test module invokes `query_tests!`.

use clayers_xml::ContentHash;
use chrono::Utc;

use crate::import;
use crate::object::{Author, CommitObject, Object, TagObject, TreeEntry, TreeObject};
use crate::query::{
    QueryMode, QueryResult, QueryStore, NamespaceMap,
    query_refs, resolve_to_document,
};
use crate::refs;
use crate::store::{ObjectStore, RefStore};

const TEST_XML: &str = r#"<root xmlns:app="urn:test:app"><app:item id="1" status="active"><app:name>Alpha</app:name></app:item><app:item id="2" status="inactive"><app:name>Beta</app:name></app:item><app:item id="3" status="active"><app:name>Gamma</app:name></app:item></root>"#;

fn test_namespaces() -> NamespaceMap {
    vec![("app".to_string(), "urn:test:app".to_string())]
}

fn author() -> Author {
    Author {
        name: "Test".into(),
        email: "test@test.com".into(),
    }
}

/// Test harness for query operations on any backend.
pub struct QueryTester<S: ObjectStore + RefStore + QueryStore> {
    pub store: S,
}

impl<S: ObjectStore + RefStore + QueryStore> QueryTester<S> {
    /// Import the test XML and return the document hash.
    async fn import_test_doc(&self) -> ContentHash {
        import::import_xml(&self.store, TEST_XML).await.unwrap()
    }

    /// Import, wrap in a tree, commit, and set a branch ref.
    async fn commit_test_doc(
        &self,
        branch: &str,
        xml: &str,
        parents: Vec<ContentHash>,
    ) -> (ContentHash, ContentHash) {
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();
        // Wrap document in a single-file tree.
        let tree = TreeObject::new(vec![
            TreeEntry { path: "doc.xml".into(), document: doc_hash },
        ]);
        let tree_xml = tree.to_xml();
        let tree_hash = crate::hash::hash_exclusive(&tree_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(tree_hash, Object::Tree(tree)).await.unwrap();
        tx.commit().await.unwrap();

        let commit = CommitObject {
            tree: tree_hash,
            parents,
            author: author(),
            timestamp: Utc::now(),
            message: format!("commit on {branch}"),
        };
        let commit_xml = commit.to_xml();
        let commit_hash = crate::hash::hash_exclusive(&commit_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(commit_hash, Object::Commit(commit)).await.unwrap();
        tx.commit().await.unwrap();
        self.store
            .set_ref(&refs::branch_ref(branch), commit_hash)
            .await
            .unwrap();
        (commit_hash, doc_hash)
    }

    // --- Query tests ---

    pub async fn test_query_count(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(doc_hash, "//app:item", QueryMode::Count, &test_namespaces())
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 3),
            _ => panic!("expected Count"),
        }
    }

    pub async fn test_query_text(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "//app:item[@id=\"1\"]/app:name",
                QueryMode::Text,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => {
                assert_eq!(texts.len(), 1);
                assert_eq!(texts[0], "Alpha");
            }
            _ => panic!("expected Text"),
        }
    }

    pub async fn test_query_xml(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "//app:item[@id=\"1\"]",
                QueryMode::Xml,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Xml(xmls) => {
                assert_eq!(xmls.len(), 1);
                assert!(xmls[0].contains("item"), "should contain element");
            }
            _ => panic!("expected Xml"),
        }
    }

    pub async fn test_query_with_predicate(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "//app:item[@status=\"active\"]",
                QueryMode::Count,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 2),
            _ => panic!("expected Count"),
        }
    }

    pub async fn test_query_nested_path(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "//app:item/app:name",
                QueryMode::Count,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 3),
            _ => panic!("expected Count"),
        }
    }

    pub async fn test_query_no_matches(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "//app:nonexistent",
                QueryMode::Count,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 0),
            _ => panic!("expected Count"),
        }
    }

    pub async fn test_query_by_branch(&self) {
        let (_, doc_hash) = self.commit_test_doc("query_branch", TEST_XML, vec![]).await;
        let resolved = resolve_to_document(&self.store, &self.store, "query_branch")
            .await
            .unwrap();
        assert_eq!(resolved, doc_hash);

        let result = self
            .store
            .query_document(resolved, "//app:item", QueryMode::Count, &test_namespaces())
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 3),
            _ => panic!("expected Count"),
        }
    }

    pub async fn test_query_by_tag(&self) {
        let (commit_hash, doc_hash) =
            self.commit_test_doc("query_tag_branch", TEST_XML, vec![]).await;

        // Create an annotated tag pointing at the commit.
        let tag = TagObject {
            target: commit_hash,
            name: "query_v1".into(),
            tagger: author(),
            timestamp: Utc::now(),
            message: "release".into(),
        };
        let tag_xml = tag.to_xml();
        let tag_hash = crate::hash::hash_exclusive(&tag_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(tag_hash, Object::Tag(tag)).await.unwrap();
        tx.commit().await.unwrap();
        self.store
            .set_ref(&refs::tag_ref("query_v1"), tag_hash)
            .await
            .unwrap();

        let resolved = resolve_to_document(&self.store, &self.store, "query_v1")
            .await
            .unwrap();
        assert_eq!(resolved, doc_hash);
    }

    pub async fn test_query_different_revisions(&self) {
        let xml_a = "<root><val>AAA</val></root>";
        let xml_b = "<root><val>BBB</val></root>";
        let (_, doc_a) = self.commit_test_doc("rev_a", xml_a, vec![]).await;
        let (_, doc_b) = self.commit_test_doc("rev_b", xml_b, vec![]).await;

        let result_a = self
            .store
            .query_document(doc_a, "//val", QueryMode::Text, &vec![])
            .await
            .unwrap();
        let result_b = self
            .store
            .query_document(doc_b, "//val", QueryMode::Text, &vec![])
            .await
            .unwrap();

        match (result_a, result_b) {
            (QueryResult::Text(a), QueryResult::Text(b)) => {
                assert_eq!(a, vec!["AAA"]);
                assert_eq!(b, vec!["BBB"]);
            }
            _ => panic!("expected Text results"),
        }
    }

    pub async fn test_query_all_refs(&self) {
        let (_, _) = self.commit_test_doc("allrefs_a", TEST_XML, vec![]).await;
        let (_, _) = self
            .commit_test_doc(
                "allrefs_b",
                "<root><val>other</val></root>",
                vec![],
            )
            .await;

        let results = query_refs(
            &self.store,
            &self.store,
            &self.store,
            "refs/heads/allrefs_",
            "//root",
            QueryMode::Count,
            &vec![],
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 2, "should query 2 branches");
    }

    pub async fn test_query_all_refs_deduplicates(&self) {
        // Both branches point to the same commit -> same doc.
        let (commit_hash, _) =
            self.commit_test_doc("dedup_a", TEST_XML, vec![]).await;
        // Set another branch to the same commit.
        self.store
            .set_ref(&refs::branch_ref("dedup_b"), commit_hash)
            .await
            .unwrap();

        let results = query_refs(
            &self.store,
            &self.store,
            &self.store,
            "refs/heads/dedup_",
            "//app:item",
            QueryMode::Count,
            &test_namespaces(),
        )
        .await
        .unwrap();

        // Same doc -> should only query once.
        assert_eq!(results.len(), 1, "should deduplicate same doc_hash");
    }

    pub async fn test_query_nonexistent_ref(&self) {
        let result = resolve_to_document(&self.store, &self.store, "nonexistent_branch").await;
        assert!(result.is_err(), "should error for missing ref");
    }

    // --- Adversarial / unhappy path tests ---

    /// `XPath` `app:item` is valid `XPath` 3.1 (child axis from context node).
    /// Against the test XML, evaluating from the document node, `app:item`
    /// matches nothing because root's child is `root`, not `app:item`.
    pub async fn test_query_malformed_xpath_no_slashes(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(doc_hash, "app:item", QueryMode::Count, &test_namespaces())
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 0, "app:item from document root matches nothing"),
            _ => panic!("expected Count"),
        }
    }

    /// Unbalanced bracket in predicate must error.
    pub async fn test_query_malformed_xpath_unbalanced_bracket(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(doc_hash, "//app:item[@id=\"1\"", QueryMode::Count, &test_namespaces())
            .await;
        assert!(result.is_err(), "unbalanced bracket should error");
    }

    /// `[id="1"]` is valid `XPath` 3.1: tests whether a child element named
    /// `id` has string value `"1"`. The test XML has `id` as an attribute,
    /// not a child element, so this matches nothing.
    pub async fn test_query_malformed_predicate_no_at(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(doc_hash, "//app:item[id=\"1\"]", QueryMode::Count, &test_namespaces())
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 0, "child-element predicate matches nothing"),
            _ => panic!("expected Count"),
        }
    }

    /// Query with unknown namespace prefix must error (xee-xpath rejects
    /// unknown prefixes at compile time).
    pub async fn test_query_unknown_prefix_returns_zero(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(doc_hash, "//bogus:item", QueryMode::Count, &test_namespaces())
            .await;
        assert!(result.is_err(), "unknown prefix should error at compile time");
    }

    /// No-namespace elements don't match prefixed queries.
    pub async fn test_query_prefix_vs_no_namespace(&self) {
        let xml = "<root><item id=\"1\">text</item></root>";
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();
        let result = self
            .store
            .query_document(doc_hash, "//app:item", QueryMode::Count, &test_namespaces())
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 0, "no-ns element should not match ns query"),
            _ => panic!("expected Count"),
        }
    }

    /// Query on a non-Document hash (e.g., a commit) must error.
    pub async fn test_query_on_commit_hash_errors(&self) {
        let (commit_hash, _) = self.commit_test_doc("err_commit", TEST_XML, vec![]).await;
        let result = self
            .store
            .query_document(commit_hash, "//app:item", QueryMode::Count, &test_namespaces())
            .await;
        assert!(result.is_err(), "querying a commit hash directly should error");
    }

    /// Query on a hash not in the store must error.
    pub async fn test_query_on_missing_hash_errors(&self) {
        let ghost = ContentHash::from_canonical(b"query_ghost");
        let result = self
            .store
            .query_document(ghost, "//anything", QueryMode::Count, &vec![])
            .await;
        assert!(result.is_err(), "querying missing hash should error");
    }

    /// Mixed content: comments and PIs are skipped, only elements match.
    pub async fn test_query_mixed_content_skips_non_elements(&self) {
        let xml = "<root><!-- comment --><?pi data?><item>text</item></root>";
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();
        let result = self
            .store
            .query_document(doc_hash, "//item", QueryMode::Count, &vec![])
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 1, "should find <item> despite comment/PI siblings"),
            _ => panic!("expected Count"),
        }
    }

    /// Deep nesting: query reaches leaf 5 levels down.
    pub async fn test_query_deep_nesting(&self) {
        let xml = "<a><b><c><d><e><leaf>found</leaf></e></d></c></b></a>";
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();
        let result = self
            .store
            .query_document(doc_hash, "//leaf", QueryMode::Text, &vec![])
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => {
                assert_eq!(texts.len(), 1);
                assert_eq!(texts[0], "found");
            }
            _ => panic!("expected Text"),
        }
    }

    /// Text extraction concatenates multiple text children.
    pub async fn test_query_text_concatenation(&self) {
        let xml = "<root><p>Hello <b>world</b>!</p></root>";
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();
        let result = self
            .store
            .query_document(doc_hash, "//p", QueryMode::Text, &vec![])
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => {
                assert_eq!(texts.len(), 1);
                assert_eq!(texts[0], "Hello world!");
            }
            _ => panic!("expected Text"),
        }
    }

    /// Round-trip fidelity: import -> query should see the same structure
    /// as import -> export -> reparse -> query.
    pub async fn test_query_roundtrip_fidelity(&self) {
        let xml = r#"<root xmlns:ns="urn:test"><ns:a id="1">one</ns:a><ns:a id="2">two</ns:a></root>"#;
        let ns = vec![("ns".to_string(), "urn:test".to_string())];

        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();

        // Count via direct query on objects.
        let result = self
            .store
            .query_document(doc_hash, "//ns:a", QueryMode::Count, &ns)
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 2),
            _ => panic!("expected Count"),
        }

        // Text via direct query - order should match document order.
        let result = self
            .store
            .query_document(doc_hash, "//ns:a", QueryMode::Text, &ns)
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => {
                assert_eq!(texts, vec!["one", "two"], "text order must match document order");
            }
            _ => panic!("expected Text"),
        }

        // Predicate query.
        let result = self
            .store
            .query_document(doc_hash, "//ns:a[@id=\"2\"]", QueryMode::Text, &ns)
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => {
                assert_eq!(texts, vec!["two"]);
            }
            _ => panic!("expected Text"),
        }
    }

    /// Resolve HEAD when it's not set must error.
    pub async fn test_resolve_head_not_set(&self) {
        let result = resolve_to_document(&self.store, &self.store, "HEAD").await;
        assert!(result.is_err(), "HEAD not set should error");
    }

    /// Resolve via full ref path.
    pub async fn test_resolve_full_ref_path(&self) {
        let (_, doc_hash) = self.commit_test_doc("fullref_test", TEST_XML, vec![]).await;
        let resolved = resolve_to_document(&self.store, &self.store, "refs/heads/fullref_test")
            .await
            .unwrap();
        assert_eq!(resolved, doc_hash);
    }

    /// Resolve an element hash (not commit/tag/doc) must error.
    pub async fn test_resolve_element_hash_errors(&self) {
        let xml = "<root>x</root>";
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();
        // Get the root element hash from the document.
        let doc_obj = self.store.get(&doc_hash).await.unwrap().unwrap();
        let root_hash = match doc_obj {
            Object::Document(d) => d.root,
            _ => panic!("expected Document"),
        };
        // Put this element hash into a ref so resolve_to_document gets it.
        self.store.set_ref("refs/heads/elem_ref", root_hash).await.unwrap();
        let result = resolve_to_document(&self.store, &self.store, "elem_ref").await;
        assert!(result.is_err(), "resolving to an element should error");
    }

    /// Xml output of a namespaced element must include the namespace URI.
    /// Catches `build_xot_from_objects` silently dropping namespace declarations.
    pub async fn test_query_xml_preserves_namespace(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "//app:item[@id=\"1\"]",
                QueryMode::Xml,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Xml(xmls) => {
                assert_eq!(xmls.len(), 1);
                let xml = &xmls[0];
                // The serialized XML must declare the namespace.
                assert!(
                    xml.contains("urn:test:app"),
                    "serialized XML should contain namespace URI, got: {xml}"
                );
            }
            _ => panic!("expected Xml"),
        }
    }

    /// Attributes must survive the import -> `build_xot` round-trip.
    /// Catches `build_xot_from_objects` silently dropping attributes.
    pub async fn test_query_xml_preserves_attributes(&self) {
        let xml = r#"<root><item a="1" b="2" c="3">text</item></root>"#;
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();
        let result = self
            .store
            .query_document(doc_hash, "//item[@a=\"1\"]", QueryMode::Xml, &vec![])
            .await
            .unwrap();
        match result {
            QueryResult::Xml(xmls) => {
                assert_eq!(xmls.len(), 1);
                let out = &xmls[0];
                assert!(out.contains("a="), "attribute a missing from: {out}");
                assert!(out.contains("b="), "attribute b missing from: {out}");
                assert!(out.contains("c="), "attribute c missing from: {out}");
            }
            _ => panic!("expected Xml"),
        }
    }

    /// Child order must be preserved through `build_xot_from_objects`.
    /// Catches children being appended in wrong order.
    pub async fn test_query_child_order_preserved(&self) {
        let xml = "<root><first/><second/><third/></root>";
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();
        let result = self
            .store
            .query_document(doc_hash, "//root", QueryMode::Xml, &vec![])
            .await
            .unwrap();
        match result {
            QueryResult::Xml(xmls) => {
                let out = &xmls[0];
                let first_pos = out.find("first").expect("first missing");
                let second_pos = out.find("second").expect("second missing");
                let third_pos = out.find("third").expect("third missing");
                assert!(
                    first_pos < second_pos && second_pos < third_pos,
                    "children out of order: {out}"
                );
            }
            _ => panic!("expected Xml"),
        }
    }

    /// `export_xml` and query Xml mode must produce structurally equivalent output.
    /// This catches divergence between the two XML-building code paths.
    ///
    /// Note: uses `entry` instead of `child` as element name because `child`
    /// is an `XPath` axis keyword that xee-xpath's lexer cannot use as a `QName`
    /// local part.
    pub async fn test_export_vs_query_xml_equivalence(&self) {
        use crate::export;

        let xml = r#"<root xmlns="urn:example"><entry id="1">hello</entry><entry id="2">world</entry></root>"#;
        let doc_hash = import::import_xml(&self.store, xml).await.unwrap();

        // Get the root element via export.
        let exported = export::export_xml(&self.store, doc_hash).await.unwrap();

        // Query using a prefix mapped to the default namespace.
        let ns = vec![("ex".to_string(), "urn:example".to_string())];
        let result = self
            .store
            .query_document(doc_hash, "//ex:entry[@id=\"1\"]", QueryMode::Text, &ns)
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => {
                assert_eq!(texts, vec!["hello"], "text via query must match");
            }
            _ => panic!("expected Text"),
        }

        // Both paths should agree on structure.
        assert!(exported.contains("hello"), "export missing 'hello'");
        assert!(exported.contains("world"), "export missing 'world'");

        // Query for count.
        let result = self
            .store
            .query_document(doc_hash, "//ex:entry", QueryMode::Count, &ns)
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 2),
            _ => panic!("expected Count"),
        }
    }

    /// `query_refs` with no matching refs returns empty vec, not error.
    pub async fn test_query_refs_empty_prefix(&self) {
        let results = query_refs(
            &self.store,
            &self.store,
            &self.store,
            "refs/heads/surely_no_match_",
            "//root",
            QueryMode::Count,
            &vec![],
        )
        .await
        .unwrap();

        assert!(results.is_empty(), "no matching refs should return empty vec");
    }

    // --- Tree-aware query tests ---

    /// Query across multiple documents in a tree.
    pub async fn test_query_tree_wide_count(&self) {
        use crate::query;

        let xml_a = "<root><item>alpha</item></root>";
        let xml_b = "<root><item>beta</item><item>gamma</item></root>";
        let doc_a = import::import_xml(&self.store, xml_a).await.unwrap();
        let doc_b = import::import_xml(&self.store, xml_b).await.unwrap();
        let tree = TreeObject::new(vec![
            TreeEntry { path: "a.xml".into(), document: doc_a },
            TreeEntry { path: "b.xml".into(), document: doc_b },
        ]);
        let tree_xml = tree.to_xml();
        let tree_hash = crate::hash::hash_exclusive(&tree_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(tree_hash, Object::Tree(tree)).await.unwrap();
        tx.commit().await.unwrap();

        let commit = CommitObject {
            tree: tree_hash,
            parents: vec![],
            author: author(),
            timestamp: Utc::now(),
            message: "tree_wide".into(),
        };
        let commit_xml = commit.to_xml();
        let commit_hash = crate::hash::hash_exclusive(&commit_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(commit_hash, Object::Commit(commit)).await.unwrap();
        tx.commit().await.unwrap();
        self.store.set_ref(&refs::branch_ref("tree_wide"), commit_hash).await.unwrap();

        let result = query::query(
            &self.store, &self.store, &self.store,
            "tree_wide", "//item", QueryMode::Count, &vec![],
        ).await.unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 3, "3 items across 2 docs"),
            _ => panic!("expected Count"),
        }
    }

    /// Query with file-scoped revspec (branch:path syntax).
    pub async fn test_query_file_scoped(&self) {

        let xml_a = "<root><item>alpha</item></root>";
        let xml_b = "<root><item>beta</item><item>gamma</item></root>";
        let doc_a = import::import_xml(&self.store, xml_a).await.unwrap();
        let doc_b = import::import_xml(&self.store, xml_b).await.unwrap();
        let tree = TreeObject::new(vec![
            TreeEntry { path: "a.xml".into(), document: doc_a },
            TreeEntry { path: "b.xml".into(), document: doc_b },
        ]);
        let tree_xml = tree.to_xml();
        let tree_hash = crate::hash::hash_exclusive(&tree_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(tree_hash, Object::Tree(tree)).await.unwrap();
        tx.commit().await.unwrap();

        let commit = CommitObject {
            tree: tree_hash,
            parents: vec![],
            author: author(),
            timestamp: Utc::now(),
            message: "file_scoped".into(),
        };
        let commit_xml = commit.to_xml();
        let commit_hash = crate::hash::hash_exclusive(&commit_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(commit_hash, Object::Commit(commit)).await.unwrap();
        tx.commit().await.unwrap();
        self.store.set_ref(&refs::branch_ref("file_scoped"), commit_hash).await.unwrap();

        // Query single doc (b.xml should have 2 items).
        let result = self.store.query_document(
            doc_b, "//item", QueryMode::Count, &vec![],
        ).await.unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 2, "b.xml has 2 items"),
            _ => panic!("expected Count"),
        }
    }

    // --- XPath 3.1 feature tests ---

    /// Absolute path (no `//` prefix) now works with `XPath` 3.1.
    pub async fn test_query_absolute_path(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(doc_hash, "/root/app:item", QueryMode::Count, &test_namespaces())
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 3),
            _ => panic!("expected Count"),
        }
    }

    /// `count()` function returns an atomic integer.
    pub async fn test_query_count_function(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(doc_hash, "count(//app:item)", QueryMode::Text, &test_namespaces())
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => {
                assert_eq!(texts.len(), 1);
                assert_eq!(texts[0], "3");
            }
            _ => panic!("expected Text"),
        }
    }

    /// `contains()` in predicate.
    pub async fn test_query_contains_predicate(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "//app:item[contains(@status, 'act')]",
                QueryMode::Count,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 3, "'active' and 'inactive' both contain 'act'"),
            _ => panic!("expected Count"),
        }
    }

    /// Positional predicate `[2]`.
    pub async fn test_query_positional_predicate(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "(//app:item)[2]/app:name",
                QueryMode::Text,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => assert_eq!(texts, vec!["Beta"]),
            _ => panic!("expected Text"),
        }
    }

    /// `last()` function.
    pub async fn test_query_last_function(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "(//app:item)[last()]/app:name",
                QueryMode::Text,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => assert_eq!(texts, vec!["Gamma"]),
            _ => panic!("expected Text"),
        }
    }

    /// Parent axis `..`.
    pub async fn test_query_parent_axis(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "//app:name[text()='Alpha']/..",
                QueryMode::Count,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 1, "parent is the app:item element"),
            _ => panic!("expected Count"),
        }
    }

    /// Explicit descendant axis.
    pub async fn test_query_descendant_axis(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "/root/descendant::app:name",
                QueryMode::Count,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Count(n) => assert_eq!(n, 3),
            _ => panic!("expected Count"),
        }
    }

    /// `string()` function.
    pub async fn test_query_string_function(&self) {
        let doc_hash = self.import_test_doc().await;
        let result = self
            .store
            .query_document(
                doc_hash,
                "string(//app:item[@id='1']/app:name)",
                QueryMode::Text,
                &test_namespaces(),
            )
            .await
            .unwrap();
        match result {
            QueryResult::Text(texts) => assert_eq!(texts, vec!["Alpha"]),
            _ => panic!("expected Text"),
        }
    }

    // --- Per-document query tests ---

    /// Helper: create a multi-doc tree with two files and commit it.
    async fn commit_multi_doc_tree(&self, branch: &str) {
        let xml_a = r#"<root xmlns:ns="urn:test"><ns:item id="1">alpha</ns:item><ns:item id="2">beta</ns:item></root>"#;
        let xml_b = r#"<root xmlns:ns="urn:test"><ns:item id="3">gamma</ns:item></root>"#;
        let doc_a = import::import_xml(&self.store, xml_a).await.unwrap();
        let doc_b = import::import_xml(&self.store, xml_b).await.unwrap();
        let tree = TreeObject::new(vec![
            TreeEntry { path: "a.xml".into(), document: doc_a },
            TreeEntry { path: "b.xml".into(), document: doc_b },
        ]);
        let tree_xml = tree.to_xml();
        let tree_hash = crate::hash::hash_exclusive(&tree_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(tree_hash, Object::Tree(tree)).await.unwrap();
        tx.commit().await.unwrap();
        let commit = CommitObject {
            tree: tree_hash,
            parents: vec![],
            author: author(),
            timestamp: Utc::now(),
            message: format!("multi-doc {branch}"),
        };
        let commit_xml = commit.to_xml();
        let commit_hash = crate::hash::hash_exclusive(&commit_xml).unwrap();
        let mut tx = self.store.transaction().await.unwrap();
        tx.put(commit_hash, Object::Commit(commit)).await.unwrap();
        tx.commit().await.unwrap();
        self.store.set_ref(&refs::branch_ref(branch), commit_hash).await.unwrap();
    }

    /// `query_by_document` returns per-document results with file paths.
    pub async fn test_query_by_document_returns_paths(&self) {
        use crate::query;

        self.commit_multi_doc_tree("by_doc_paths").await;
        let ns = vec![("ns".to_string(), "urn:test".to_string())];
        let results = query::query_by_document(
            &self.store, &self.store, &self.store,
            "by_doc_paths", "//ns:item", QueryMode::Count, &ns, &[],
        ).await.unwrap();

        assert_eq!(results.len(), 2, "should have results from 2 documents");
        let paths: Vec<&str> = results.iter().map(|r| r.path.as_str()).collect();
        assert!(paths.contains(&"a.xml"), "should include a.xml");
        assert!(paths.contains(&"b.xml"), "should include b.xml");

        // Verify counts per document.
        for doc in &results {
            match (&*doc.path, &doc.result) {
                ("a.xml", QueryResult::Count(n)) => assert_eq!(*n, 2),
                ("b.xml", QueryResult::Count(n)) => assert_eq!(*n, 1),
                _ => panic!("unexpected doc result: {:?}", doc.path),
            }
        }
    }

    /// `query_by_document` with file filter constrains to matching docs.
    pub async fn test_query_by_document_file_filter(&self) {
        use crate::query;

        self.commit_multi_doc_tree("by_doc_filter").await;
        let ns = vec![("ns".to_string(), "urn:test".to_string())];
        let results = query::query_by_document(
            &self.store, &self.store, &self.store,
            "by_doc_filter", "//ns:item", QueryMode::Count, &ns,
            &["b.xml".to_string()],
        ).await.unwrap();

        assert_eq!(results.len(), 1, "should only query b.xml");
        assert_eq!(results[0].path, "b.xml");
        match &results[0].result {
            QueryResult::Count(n) => assert_eq!(*n, 1),
            _ => panic!("expected Count"),
        }
    }

    /// `query_by_document` with file filter supports substring matching.
    pub async fn test_query_by_document_file_filter_substring(&self) {
        use crate::query;

        self.commit_multi_doc_tree("by_doc_substr").await;
        let ns = vec![("ns".to_string(), "urn:test".to_string())];
        // "a" matches "a.xml"
        let results = query::query_by_document(
            &self.store, &self.store, &self.store,
            "by_doc_substr", "//ns:item", QueryMode::Text, &ns,
            &["a".to_string()],
        ).await.unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].path, "a.xml");
        match &results[0].result {
            QueryResult::Text(texts) => assert_eq!(texts, &["alpha", "beta"]),
            _ => panic!("expected Text"),
        }
    }

    /// `query_by_document` skips documents with zero matches.
    pub async fn test_query_by_document_skips_empty(&self) {
        use crate::query;

        self.commit_multi_doc_tree("by_doc_empty").await;
        let results = query::query_by_document(
            &self.store, &self.store, &self.store,
            "by_doc_empty", "//nonexistent", QueryMode::Count, &vec![], &[],
        ).await.unwrap();

        assert!(results.is_empty(), "no documents should have matches");
    }

    /// `query_by_document` with empty file filter queries all documents.
    pub async fn test_query_by_document_no_filter_queries_all(&self) {
        use crate::query;

        self.commit_multi_doc_tree("by_doc_all").await;
        let ns = vec![("ns".to_string(), "urn:test".to_string())];
        let results = query::query_by_document(
            &self.store, &self.store, &self.store,
            "by_doc_all", "//ns:item", QueryMode::Count, &ns, &[],
        ).await.unwrap();

        // Both docs have matches.
        assert_eq!(results.len(), 2);
        let total: usize = results.iter().map(|r| match &r.result {
            QueryResult::Count(n) => *n,
            _ => 0,
        }).sum();
        assert_eq!(total, 3, "total across docs should be 3");
    }

    /// `resolve_to_tree` returns the tree hash and `TreeObject`.
    pub async fn test_resolve_to_tree_from_commit(&self) {
        use crate::query::resolve_to_tree;

        let (_, _) = self.commit_test_doc("resolve_tree_test", TEST_XML, vec![]).await;
        let (tree_hash, tree_obj) = resolve_to_tree(&self.store, &self.store, "resolve_tree_test")
            .await
            .unwrap();
        assert!(!tree_obj.entries.is_empty(), "tree should have entries");
        assert_eq!(tree_obj.entries[0].path, "doc.xml");
        assert_ne!(tree_hash, ContentHash::from_canonical(b"zero"));
    }
}

/// Generate test functions for query operations.
#[cfg(test)]
macro_rules! query_tests {
    ($create:expr) => {
        use crate::query::tests::QueryTester;

        #[tokio::test]
        async fn query_count() { QueryTester { store: $create }.test_query_count().await; }
        #[tokio::test]
        async fn query_text() { QueryTester { store: $create }.test_query_text().await; }
        #[tokio::test]
        async fn query_xml() { QueryTester { store: $create }.test_query_xml().await; }
        #[tokio::test]
        async fn query_with_predicate() { QueryTester { store: $create }.test_query_with_predicate().await; }
        #[tokio::test]
        async fn query_nested_path() { QueryTester { store: $create }.test_query_nested_path().await; }
        #[tokio::test]
        async fn query_no_matches() { QueryTester { store: $create }.test_query_no_matches().await; }
        #[tokio::test]
        async fn query_by_branch() { QueryTester { store: $create }.test_query_by_branch().await; }
        #[tokio::test]
        async fn query_by_tag() { QueryTester { store: $create }.test_query_by_tag().await; }
        #[tokio::test]
        async fn query_different_revisions() { QueryTester { store: $create }.test_query_different_revisions().await; }
        #[tokio::test]
        async fn query_all_refs() { QueryTester { store: $create }.test_query_all_refs().await; }
        #[tokio::test]
        async fn query_all_refs_deduplicates() { QueryTester { store: $create }.test_query_all_refs_deduplicates().await; }
        #[tokio::test]
        async fn query_nonexistent_ref() { QueryTester { store: $create }.test_query_nonexistent_ref().await; }
        #[tokio::test]
        async fn query_malformed_xpath_no_slashes() { QueryTester { store: $create }.test_query_malformed_xpath_no_slashes().await; }
        #[tokio::test]
        async fn query_malformed_xpath_unbalanced_bracket() { QueryTester { store: $create }.test_query_malformed_xpath_unbalanced_bracket().await; }
        #[tokio::test]
        async fn query_malformed_predicate_no_at() { QueryTester { store: $create }.test_query_malformed_predicate_no_at().await; }
        #[tokio::test]
        async fn query_unknown_prefix_returns_zero() { QueryTester { store: $create }.test_query_unknown_prefix_returns_zero().await; }
        #[tokio::test]
        async fn query_prefix_vs_no_namespace() { QueryTester { store: $create }.test_query_prefix_vs_no_namespace().await; }
        #[tokio::test]
        async fn query_on_commit_hash_errors() { QueryTester { store: $create }.test_query_on_commit_hash_errors().await; }
        #[tokio::test]
        async fn query_on_missing_hash_errors() { QueryTester { store: $create }.test_query_on_missing_hash_errors().await; }
        #[tokio::test]
        async fn query_mixed_content_skips_non_elements() { QueryTester { store: $create }.test_query_mixed_content_skips_non_elements().await; }
        #[tokio::test]
        async fn query_deep_nesting() { QueryTester { store: $create }.test_query_deep_nesting().await; }
        #[tokio::test]
        async fn query_text_concatenation() { QueryTester { store: $create }.test_query_text_concatenation().await; }
        #[tokio::test]
        async fn query_roundtrip_fidelity() { QueryTester { store: $create }.test_query_roundtrip_fidelity().await; }
        #[tokio::test]
        async fn resolve_head_not_set() { QueryTester { store: $create }.test_resolve_head_not_set().await; }
        #[tokio::test]
        async fn resolve_full_ref_path() { QueryTester { store: $create }.test_resolve_full_ref_path().await; }
        #[tokio::test]
        async fn resolve_element_hash_errors() { QueryTester { store: $create }.test_resolve_element_hash_errors().await; }
        #[tokio::test]
        async fn query_xml_preserves_namespace() { QueryTester { store: $create }.test_query_xml_preserves_namespace().await; }
        #[tokio::test]
        async fn query_xml_preserves_attributes() { QueryTester { store: $create }.test_query_xml_preserves_attributes().await; }
        #[tokio::test]
        async fn query_child_order_preserved() { QueryTester { store: $create }.test_query_child_order_preserved().await; }
        #[tokio::test]
        async fn export_vs_query_xml_equivalence() { QueryTester { store: $create }.test_export_vs_query_xml_equivalence().await; }
        #[tokio::test]
        async fn query_refs_empty_prefix() { QueryTester { store: $create }.test_query_refs_empty_prefix().await; }
        #[tokio::test]
        async fn query_tree_wide_count() { QueryTester { store: $create }.test_query_tree_wide_count().await; }
        #[tokio::test]
        async fn query_file_scoped() { QueryTester { store: $create }.test_query_file_scoped().await; }
        #[tokio::test]
        async fn resolve_to_tree_from_commit() { QueryTester { store: $create }.test_resolve_to_tree_from_commit().await; }
        #[tokio::test]
        async fn query_absolute_path() { QueryTester { store: $create }.test_query_absolute_path().await; }
        #[tokio::test]
        async fn query_count_function() { QueryTester { store: $create }.test_query_count_function().await; }
        #[tokio::test]
        async fn query_contains_predicate() { QueryTester { store: $create }.test_query_contains_predicate().await; }
        #[tokio::test]
        async fn query_positional_predicate() { QueryTester { store: $create }.test_query_positional_predicate().await; }
        #[tokio::test]
        async fn query_last_function() { QueryTester { store: $create }.test_query_last_function().await; }
        #[tokio::test]
        async fn query_parent_axis() { QueryTester { store: $create }.test_query_parent_axis().await; }
        #[tokio::test]
        async fn query_descendant_axis() { QueryTester { store: $create }.test_query_descendant_axis().await; }
        #[tokio::test]
        async fn query_string_function() { QueryTester { store: $create }.test_query_string_function().await; }
        #[tokio::test]
        async fn query_by_document_returns_paths() { QueryTester { store: $create }.test_query_by_document_returns_paths().await; }
        #[tokio::test]
        async fn query_by_document_file_filter() { QueryTester { store: $create }.test_query_by_document_file_filter().await; }
        #[tokio::test]
        async fn query_by_document_file_filter_substring() { QueryTester { store: $create }.test_query_by_document_file_filter_substring().await; }
        #[tokio::test]
        async fn query_by_document_skips_empty() { QueryTester { store: $create }.test_query_by_document_skips_empty().await; }
        #[tokio::test]
        async fn query_by_document_no_filter_queries_all() { QueryTester { store: $create }.test_query_by_document_no_filter_queries_all().await; }
    };
}

#[cfg(test)]
pub(crate) use query_tests;