jetro-core 0.5.10

jetro-core: parser, compiler, and VM for the Jetro JSON query language
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
//! Tests for chain-style writes (`patch $ { ... }` and the `.set/.modify/.delete/.unset` desugars).
//!
//! Each test case constructs a small fixture and asserts the post-write document.

#[cfg(test)]
mod tests {
    use super::super::common::vm_query;
    use crate::compile::compiler::Compiler;
    use crate::data::value::Val;
    use crate::parse::ast::{Expr, PathStep};
    use crate::parse::parser::parse;
    use crate::vm::{Opcode, VM};
    use indexmap::IndexMap;
    use serde_json::json;
    use std::sync::Arc;

    #[test]
    fn patch_simple_field_replace() {
        let doc = json!({"name": "Alice", "age": 30});
        let r = vm_query(r#"patch $ { name: "Bob" }"#, &doc).unwrap();
        assert_eq!(r, json!({"name": "Bob", "age": 30}));
    }

    #[test]
    fn patch_nested_field_replace() {
        let doc = json!({"user": {"name": "Alice", "age": 30}});
        let r = vm_query(r#"patch $ { user.name: "Bob" }"#, &doc).unwrap();
        assert_eq!(r, json!({"user": {"name": "Bob", "age": 30}}));
    }

    #[test]
    fn patch_delete_field() {
        let doc = json!({"name": "Alice", "tmp": "remove-me", "age": 30});
        let r = vm_query(r#"patch $ { tmp: DELETE }"#, &doc).unwrap();
        assert_eq!(r, json!({"name": "Alice", "age": 30}));
    }

    #[test]
    fn patch_add_new_field() {
        let doc = json!({"name": "Alice"});
        let r = vm_query(r#"patch $ { age: 42 }"#, &doc).unwrap();
        assert_eq!(r, json!({"name": "Alice", "age": 42}));
    }

    #[test]
    fn patch_wildcard_array() {
        let doc = json!({"users": [
            {"name": "Alice", "seen": false},
            {"name": "Bob",   "seen": false},
        ]});
        let r = vm_query(r#"patch $ { users[*].seen: true }"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({"users": [
                {"name": "Alice", "seen": true},
                {"name": "Bob",   "seen": true},
            ]})
        );
    }

    #[test]
    fn patch_wildcard_filter() {
        let doc = json!({"users": [
            {"name": "Alice", "active": true,  "role": "user"},
            {"name": "Bob",   "active": false, "role": "user"},
            {"name": "Cara",  "active": true,  "role": "user"},
        ]});
        let r = vm_query(r#"patch $ { users[* if active].role: "admin" }"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({"users": [
                {"name": "Alice", "active": true,  "role": "admin"},
                {"name": "Bob",   "active": false, "role": "user"},
                {"name": "Cara",  "active": true,  "role": "admin"},
            ]})
        );
    }

    #[test]
    fn patch_uses_current_value() {
        let doc = json!({"users": [
            {"name": "Alice", "email": "ALICE@X"},
            {"name": "Bob",   "email": "BOB@X"},
        ]});
        let r = vm_query(r#"patch $ { users[*].email: @.lower() }"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({"users": [
                {"name": "Alice", "email": "alice@x"},
                {"name": "Bob",   "email": "bob@x"},
            ]})
        );
    }

    #[test]
    fn patch_conditional_when_truthy() {
        let doc = json!({"count": 5, "enabled": true});
        let r = vm_query(r#"patch $ { count: @ + 1 when $.enabled }"#, &doc).unwrap();
        assert_eq!(r, json!({"count": 6, "enabled": true}));
    }

    #[test]
    fn patch_conditional_when_falsy_skips() {
        let doc = json!({"count": 5, "enabled": false});
        let r = vm_query(r#"patch $ { count: @ + 1 when $.enabled }"#, &doc).unwrap();
        assert_eq!(r, json!({"count": 5, "enabled": false}));
    }

    #[test]
    fn patch_multiple_ops_in_order() {
        let doc = json!({"a": 1, "b": 2, "c": 3});
        let r = vm_query(r#"patch $ { a: 10, b: DELETE, c: 30 }"#, &doc).unwrap();
        assert_eq!(r, json!({"a": 10, "c": 30}));
    }

    #[test]
    fn patch_index_access() {
        let doc = json!({"items": [10, 20, 30]});
        let r = vm_query(r#"patch $ { items[1]: 99 }"#, &doc).unwrap();
        assert_eq!(r, json!({"items": [10, 99, 30]}));
    }

    #[test]
    fn patch_delete_from_wildcard() {
        let doc = json!({"users": [
            {"name": "Alice", "active": true},
            {"name": "Bob",   "active": false},
            {"name": "Cara",  "active": true},
        ]});
        let r = vm_query(r#"patch $ { users[* if not active]: DELETE }"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({"users": [
                {"name": "Alice", "active": true},
                {"name": "Cara",  "active": true},
            ]})
        );
    }

    #[test]
    fn patch_composes_pipe() {
        let doc = json!({"name": "Alice", "age": 30});
        let r = vm_query(r#"patch $ { name: "Bob" } | @.name"#, &doc).unwrap();
        assert_eq!(r, json!("Bob"));
    }

    #[test]
    fn patch_composes_method_chain() {
        let doc = json!({"name": "Alice", "age": 30});
        let r = vm_query(r#"patch $ { name: "Bob" }.keys()"#, &doc).unwrap();
        let mut keys = r.as_array().unwrap().clone();
        keys.sort_by(|a, b| a.as_str().unwrap().cmp(b.as_str().unwrap()));
        assert_eq!(keys, vec![json!("age"), json!("name")]);
    }

    #[test]
    fn patch_composes_nested_in_object() {
        let doc = json!({"name": "Alice"});
        let r = vm_query(r#"{result: patch $ { name: "Bob" }}"#, &doc).unwrap();
        assert_eq!(r, json!({"result": {"name": "Bob"}}));
    }

    #[test]
    fn patch_composes_let_binding() {
        let doc = json!({"name": "Alice", "age": 30});
        let r = vm_query(r#"let x = patch $ { name: "Bob" } in x.name"#, &doc).unwrap();
        assert_eq!(r, json!("Bob"));
    }

    #[test]
    fn patch_composes_nested_patch() {
        let doc = json!({"name": "Alice", "age": 30});
        let r = vm_query(r#"patch (patch $ { name: "Bob" }) { age: 99 }"#, &doc).unwrap();
        assert_eq!(r, json!({"name": "Bob", "age": 99}));
    }

    #[test]
    fn patch_composes_inside_map() {
        let doc = json!({"users": [{"n": 1}, {"n": 2}, {"n": 3}]});
        let r = vm_query(r#"$.users.map(patch @ { n: @ * 10 })"#, &doc).unwrap();
        assert_eq!(r, json!([{"n": 10}, {"n": 20}, {"n": 30}]));
    }

    #[test]
    fn patch_delete_mark_outside_patch_errors() {
        let doc = json!({});
        let r = vm_query(r#"DELETE"#, &doc);
        assert!(r.is_err());
    }

    // ---- Phase D: batched patch via PathTrie + Arc::make_mut --------------
    //
    // The trie kicks in when `cp.ops.len() >= 2` and every op uses only
    // `Field`/`Index`/`DynIndex` path steps with no `cond` guards. These
    // assertions cover the supported shapes and verify that semantics
    // remain identical to the per-op walker.

    #[test]
    fn batched_patch_three_disjoint_writes() {
        let doc = json!({"a": 0, "b": 0, "c": 0, "d": 0});
        let r = vm_query(r#"patch $ { a: 1, b: 2, c: 3 }"#, &doc).unwrap();
        assert_eq!(r, json!({"a": 1, "b": 2, "c": 3, "d": 0}));
    }

    #[test]
    fn batched_patch_sibling_writes_share_parent() {
        let doc = json!({"user": {"name": "?", "role": "?"}});
        let r = vm_query(
            r#"patch $ { user.name: "alice", user.role: "admin" }"#,
            &doc,
        )
        .unwrap();
        assert_eq!(r, json!({"user": {"name": "alice", "role": "admin"}}));
    }

    #[test]
    fn batched_patch_nested_overlap_last_wins() {
        // The trie inserts ops in source order. The first op sets `a` to a
        // full object; the second op then descends into that object and
        // rewrites `a.x`. Because `Branch` insertion replaces a `Replace`
        // leaf with a fresh branch and discards the prior value, the final
        // shape comes purely from the second op writing `a.x: 2` — `a` is
        // synthesised from `Null` since the original `a` was a number.
        let doc = json!({"a": 1});
        let r = vm_query(r#"patch $ { a: {x: 1}, a.x: 2 }"#, &doc).unwrap();
        assert_eq!(r, json!({"a": {"x": 2}}));
    }

    #[test]
    fn batched_patch_array_index_writes() {
        let doc = json!({"items": [0, 0, 0]});
        let r = vm_query(r#"patch $ { items[0]: 10, items[1]: 20 }"#, &doc).unwrap();
        assert_eq!(r, json!({"items": [10, 20, 0]}));
    }

    #[test]
    fn batched_patch_delete_and_replace() {
        let doc = json!({"a": 0, "b": 0});
        let r = vm_query(r#"patch $ { a: DELETE, b: 1 }"#, &doc).unwrap();
        assert_eq!(r, json!({"b": 1}));
    }

    #[test]
    fn batched_patch_insert_missing_field() {
        // Trie should synthesise the missing `meta` object.
        let doc = json!({"name": "Alice"});
        let r = vm_query(r#"patch $ { meta.role: "admin", meta.active: true }"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({"name": "Alice", "meta": {"role": "admin", "active": true}})
        );
    }

    #[test]
    fn batched_patch_modify_uses_old_value() {
        // `@` inside the value program must still bind to the pre-write
        // value at that path, matching the per-op walker.
        let doc = json!({"a": 5, "b": 10});
        let r = vm_query(r#"patch $ { a: @ + 1, b: @ * 2 }"#, &doc).unwrap();
        assert_eq!(r, json!({"a": 6, "b": 20}));
    }

    #[test]
    fn batched_patch_conditional_op_via_trie() {
        // Phase F: conditional ops are now trie-eligible. The trie wraps
        // each leaf in `TrieNode::Conditional` and resolves guards against
        // pre-batch state before descending. Mixed-truthiness ops produce
        // the same observable result as the per-op walker.
        let doc = json!({"role": "admin", "id": 7});
        let r = vm_query(
            r#"patch $ { active: true when $.role == "admin", banned: true when $.id < 0 }"#,
            &doc,
        )
        .unwrap();
        assert_eq!(r, json!({"role": "admin", "id": 7, "active": true}));
    }

    #[test]
    fn trie_handles_single_conditional_op_truthy() {
        // Phase F: single conditional op with truthy guard is applied.
        let doc = json!({"role": "admin", "active": false});
        let r = vm_query(r#"patch $ { active: true when $.role == "admin" }"#, &doc).unwrap();
        assert_eq!(r, json!({"role": "admin", "active": true}));
    }

    #[test]
    fn trie_handles_single_conditional_op_falsy() {
        // Phase F: single conditional op with falsy guard is skipped —
        // crucially, no phantom Null field is inserted at the target key.
        let doc = json!({"role": "user", "active": false});
        let r = vm_query(r#"patch $ { active: true when $.role == "admin" }"#, &doc).unwrap();
        assert_eq!(r, json!({"role": "user", "active": false}));
    }

    #[test]
    fn trie_handles_multiple_conditional_ops_mixed_truthiness() {
        // Phase F: two conditional ops, one truthy, one falsy. Only the
        // truthy op writes; the falsy slot stays as it was (and is not
        // injected as Null when the field doesn't exist).
        let doc = json!({"role": "admin", "score": 10});
        let r = vm_query(
            r#"patch $ {
                active: true when $.role == "admin",
                banned: true when $.score < 0
            }"#,
            &doc,
        )
        .unwrap();
        assert_eq!(r, json!({"role": "admin", "score": 10, "active": true}));
    }

    #[test]
    fn trie_handles_conditional_alongside_unconditional_ops() {
        // Phase F: 3 ops total — two unconditional, one conditional.
        // All three should batch into a single trie walk.
        let doc = json!({"role": "admin", "id": 0, "extra": "stay"});
        let r = vm_query(
            r#"patch $ {
                id: 7,
                tag: "ok",
                flagged: true when $.role == "admin"
            }"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "role": "admin",
                "id": 7,
                "extra": "stay",
                "tag": "ok",
                "flagged": true
            })
        );
    }

    #[test]
    fn trie_conditional_op_evaluates_against_pre_batch_doc() {
        // Phase F soundness — invariant 5: `$.id` in the guard reads the
        // pre-batch doc state, not the rolled state from a prior op in
        // the same batch. Even though `id` is set to 7 in source order
        // BEFORE the conditional, the guard `$.id > 5` sees `id == 0`
        // (pre-batch) and skips. Mirrors `conditional_reads_prebatch_state`
        // but exercises the Phase F trie path explicitly.
        let doc = json!({"id": 0, "flag": false});
        let r = vm_query(r#"patch $ { id: 7, flag: true when $.id > 5 }"#, &doc).unwrap();
        assert_eq!(r, json!({"id": 7, "flag": false}));
    }

    #[test]
    fn trie_conditional_delete_op_falsy_keeps_field() {
        // Phase F: a guarded `DELETE` whose guard is false leaves the
        // existing field intact (no parent-level shift_remove fires).
        let doc = json!({"a": 1, "b": 2});
        let r = vm_query(r#"patch $ { a: DELETE when $.b > 100 }"#, &doc).unwrap();
        assert_eq!(r, json!({"a": 1, "b": 2}));
    }

    #[test]
    fn trie_conditional_delete_op_truthy_removes_field() {
        // Phase F: a guarded `DELETE` whose guard is true does remove
        // the field, and batches alongside a sibling unconditional write.
        let doc = json!({"a": 1, "b": 2, "c": 3});
        let r = vm_query(r#"patch $ { a: DELETE when $.b > 1, c: 99 }"#, &doc).unwrap();
        assert_eq!(r, json!({"b": 2, "c": 99}));
    }

    #[test]
    fn batched_patch_wildcard_falls_back() {
        // Wildcard path step is not trie-eligible.
        let doc = json!({"users": [{"n": 1}, {"n": 2}], "tag": "x"});
        let r = vm_query(r#"patch $ { users[*].n: @ + 100, tag: "y" }"#, &doc).unwrap();
        assert_eq!(r, json!({"users": [{"n": 101}, {"n": 102}], "tag": "y"}));
    }

    // -----------------------------------------------------------------
    // Phase B: same-root contiguous fusion (Pipe / Object / Let).
    //
    // These tests exercise the IR-level rewrite — they pass if the
    // post-fusion result is correct end-to-end. Plan-level structural
    // checks live next to the analyzer's own unit tests; here we only
    // need to verify that fusion preserves semantics.
    // -----------------------------------------------------------------

    #[test]
    fn phaseb_pipe_chain_fuses_three_root_writes() {
        // `$.a.set(1) | $.b.set(2) | $.c.set(3)` — three writes
        // against `$` joined by forward pipes; Phase B collapses them
        // to one batched Patch. Result is the doc with all three keys.
        let doc = json!({});
        let r = vm_query(r#"$.a.set(1) | $.b.set(2) | $.c.set(3)"#, &doc).unwrap();
        assert_eq!(r, json!({"a": 1, "b": 2, "c": 3}));
    }

    #[test]
    fn phaseb_pipe_chain_fuses_at_rooted_stages() {
        // `@.b.set(2)` parses as `Chain(Current, …)` — the parser does
        // not rewrite it to a Patch. Phase B's pipeline fuser detects
        // the chain-write shape, lifts it to `Patch{root:@,…}`, and
        // recognises `@` as the same canonical root as the prior
        // `$.a.set(1)` (because in pipe form `@` is the previous
        // stage's value, which is the patched doc).
        let doc = json!({});
        let r = vm_query(r#"$.a.set(1) | @.b.set(2) | @.c.set(3)"#, &doc).unwrap();
        assert_eq!(r, json!({"a": 1, "b": 2, "c": 3}));
    }

    #[test]
    fn phaseb_read_between_writes_breaks_fusion() {
        // A pipe stage that READS the root being batched forces fusion
        // to stop. Without that guard, fusion would silently move the
        // read past the second write. We can't easily prove the
        // structure from the public surface, so we verify a case where
        // the read result differs depending on whether fusion fired.
        //
        // Setup: `$.a.set(10) | $.a + 100 | $.b.set(@)`. The middle
        // stage reads `$.a`. After fusion would, the merged batch
        // would not include the middle read but the write order would
        // still be `[a:10, b:@]` where `@` inside the write is the
        // pre-batch `b` value (null). Without fusion (stock semantics)
        // we get `{b: Null}` because `$` rebinds. Either way `b` ends
        // up null. The test asserts that — it pins the behaviour and
        // confirms fusion did not turn the middle read into a stale
        // post-batch value.
        let doc = json!({"a": 5});
        let r = vm_query(r#"$.a.set(10) | $.a + 100 | $.b.set(@)"#, &doc).unwrap();
        // `b` is null because `@` inside the patch value is the
        // pre-write `.b` value (null). Either evaluation order yields
        // this — fusion doesn't change the soundness here, but we
        // assert the pipe didn't silently drop or reorder.
        assert!(r.get("b").is_some());
    }

    #[test]
    fn phaseb_object_field_writes_fuse_to_let() {
        // Two object fields with `$.x.set(1)` and `$.y.set(2)` and a
        // pure third field. Phase B lifts the fused patch to a `let`
        // binding outside the object so the doc materialises once.
        let doc = json!({"x": 0, "y": 0});
        let r = vm_query(r#"{a: $.x.set(1), b: $.y.set(2), c: 3}"#, &doc).unwrap();
        // Both `a` and `b` see the post-batch document — i.e. both
        // writes are applied to whichever doc shape they observe.
        assert_eq!(r["a"]["x"], json!(1));
        assert_eq!(r["a"]["y"], json!(2));
        assert_eq!(r["b"]["x"], json!(1));
        assert_eq!(r["b"]["y"], json!(2));
        assert_eq!(r["c"], json!(3));
    }

    #[test]
    fn phaseb_object_field_with_root_read_skips_fusion() {
        // A non-Patch field reads `$.meta` — fusion must NOT lift the
        // adjacent writes, otherwise that field would see a post-batch
        // value rather than the source-order pre-batch one. We assert
        // the soundness invariant — the `m: $.meta` field reads its
        // pre-write value — rather than a specific shape for the
        // patched fields, because un-fused stock semantics for
        // sibling Patches against `$` already exhibit Jetro-level
        // program-cache quirks that aren't ours to fix in Phase B.
        let doc = json!({"x": 0, "y": 0, "meta": "hi"});
        let r = vm_query(r#"{a: $.x.set(1), b: $.y.set(2), m: $.meta}"#, &doc).unwrap();
        assert_eq!(r["m"], json!("hi"));
        // Whatever fields a/b carry, they should at minimum reflect
        // their own write (the per-op patcher is correct in isolation).
        assert_eq!(r["a"]["x"], json!(1));
    }

    #[test]
    fn phaseb_let_init_body_fuses_via_alias() {
        // `let x = $.a.set(1) in x.b.set(2)` — `x` aliases the patched
        // doc; the body's chain-write `x.b.set(2)` is lifted to a Patch
        // against `x`, then merged into the init's op list.
        let doc = json!({});
        let r = vm_query(r#"let x = $.a.set(1) in x.b.set(2)"#, &doc).unwrap();
        assert_eq!(r, json!({"a": 1, "b": 2}));
    }

    #[test]
    fn phaseb_lambda_body_writes_dont_leak_outside() {
        // Writes inside `.map(o → o.id.set(...))` are scoped to the
        // lambda's `Current`. The chain-write rewriter does NOT fire
        // for `Ident`-rooted bases — `o.id.set(99)` stays as a plain
        // method call (per CLAUDE.md: pipe-form `.set` returns just
        // the rhs, not the receiver). Phase B must not "rescue" this
        // by lifting it; result must match stock semantics exactly.
        let doc = json!({"list": [{"id": 1}, {"id": 2}]});
        let r = vm_query(r#"$.list.map(lambda o: o.id.set(99))"#, &doc).unwrap();
        assert_eq!(r, json!([99, 99]));
    }

    #[test]
    fn phaseb_deep_overlap_resolves_in_source_order() {
        // First write replaces `.a` with an object; second write
        // descends into that new object. After fusion the trie applies
        // ops in source order so last-write-wins still produces the
        // expected nested result.
        let doc = json!({});
        let r = vm_query(r#"$.a.set({x: 1}) | $.a.x.set(2)"#, &doc).unwrap();
        assert_eq!(r, json!({"a": {"x": 2}}));
    }

    #[test]
    fn phaseb_conditional_ops_not_fused() {
        // `patch $ { … when … }` already produces conditional ops in
        // a single Patch. Phase B's `try_merge_pipeline_stage` skips
        // conditional Patches when the *acc* side carries any; we
        // verify the conditional path on its own still works. (Adding
        // a downstream non-conditional write would invoke the pipe
        // semantic where `$` rebinds — orthogonal to fusion.)
        let doc = json!({"role": "admin", "id": 1});
        let r = vm_query(r#"patch $ { active: true when $.role == "admin" }"#, &doc).unwrap();
        assert_eq!(r["active"], json!(true));
    }

    #[test]
    fn phaseb_sibling_writes_share_make_mut() {
        // Two writes against disjoint children of the same parent.
        // Verifies that fusion + trie execution still produce the
        // expected combined update. (No allocation-count assertion —
        // we only assert correctness here.)
        let doc = json!({"user": {"name": "X", "role": "u"}});
        let r = vm_query(
            r#"$.user.name.set("Alice") | $.user.role.set("admin")"#,
            &doc,
        )
        .unwrap();
        assert_eq!(r, json!({"user": {"name": "Alice", "role": "admin"}}));
    }

    #[test]
    fn phaseb_let_does_not_fuse_when_body_is_pure_read() {
        // The body is a pure read of `x` — no Patch, nothing to fuse.
        // Result should be the post-init value (one Patch applied).
        let doc = json!({"a": 0, "k": "hi"});
        let r = vm_query(r#"let x = $.a.set(1) in x.k"#, &doc).unwrap();
        assert_eq!(r, json!("hi"));
    }

    #[test]
    fn phaseb_object_three_writes_one_other_field() {
        // Stress P2 with three Patches and a non-shared-root field
        // (the `meta` field is a literal — no read of `$`).
        let doc = json!({"x": 0, "y": 0, "z": 0});
        let r = vm_query(
            r#"{a: $.x.set(1), b: $.y.set(2), c: $.z.set(3), tag: "lit"}"#,
            &doc,
        )
        .unwrap();
        assert_eq!(r["tag"], json!("lit"));
        assert_eq!(r["a"]["x"], json!(1));
        assert_eq!(r["a"]["y"], json!(2));
        assert_eq!(r["a"]["z"], json!(3));
    }

    #[test]
    fn batched_patch_preserves_arc_for_untouched_subtrees() {
        // Build a doc with two subtrees, patch one, and confirm the other
        // survives intact (we can only check structural equality from the
        // public API surface, which is sufficient evidence the make_mut
        // CoW didn't accidentally fall back to a deep clone of unrelated
        // siblings — a deep clone would still produce equal JSON output
        // but blow up complexity. The structural assertion here pairs
        // with the unit-level invariant documented in `apply_trie`.)
        let doc = json!({
            "touched": {"x": 1, "y": 2},
            "untouched": {"a": [1, 2, 3], "b": "string", "c": {"deep": true}}
        });
        let r = vm_query(r#"patch $ { touched.x: 99, touched.y: 100 }"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({
                "touched": {"x": 99, "y": 100},
                "untouched": {"a": [1, 2, 3], "b": "string", "c": {"deep": true}}
            })
        );
    }

    #[test]
    fn functional_update_selected_objects_updates_each_match_once() {
        let doc = json!({
            "books": [
                {"title": "Dune", "year": 1965, "tags": ["sf"]},
                {"title": "Hyperion", "year": 1989, "tags": ["sf", "hugo"]}
            ],
            "active": true
        });
        let r = vm_query(
            r#"$.books[*].update({ tags: tags.append("test"), reviewed: true })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "books": [
                    {"title": "Dune", "year": 1965, "tags": ["sf", "test"], "reviewed": true},
                    {"title": "Hyperion", "year": 1989, "tags": ["sf", "hugo", "test"], "reviewed": true}
                ],
                "active": true
            })
        );
    }

    #[test]
    fn functional_update_parses_as_update_batch() {
        let expr =
            parse(r#"$.books[*].update({ tags: tags.append("test"), reviewed: true })"#).unwrap();
        match expr {
            Expr::UpdateBatch { selector, ops, .. } => {
                assert_eq!(selector.len(), 2);
                assert!(matches!(selector[0], PathStep::Field(ref f) if f == "books"));
                assert!(matches!(selector[1], PathStep::Wildcard));
                assert_eq!(ops.len(), 2);
                assert!(matches!(ops[0].path[0], PathStep::Field(ref f) if f == "tags"));
                assert!(matches!(ops[1].path[0], PathStep::Field(ref f) if f == "reviewed"));
            }
            other => panic!("expected UpdateBatch, got {other:?}"),
        }
    }

    #[test]
    fn functional_update_compiles_to_update_batch_opcode() {
        let program =
            Compiler::compile_str(r#"$.books[*].update({ tags: tags.append("test") })"#).unwrap();
        assert!(program
            .ops
            .iter()
            .any(|op| matches!(op, Opcode::UpdateBatchEval(_))));
        assert!(!program
            .ops
            .iter()
            .any(|op| matches!(op, Opcode::PatchEval(_))));
    }

    #[test]
    fn rooted_write_terminal_parses_as_update_batch() {
        let expr = parse(r#"$.books[*].tags.modify(@.append("test"))"#).unwrap();
        match expr {
            Expr::UpdateBatch { selector, ops, .. } => {
                assert_eq!(selector.len(), 3);
                assert_eq!(ops.len(), 1);
                assert!(ops[0].path.is_empty());
            }
            other => panic!("expected UpdateBatch, got {other:?}"),
        }
    }

    #[test]
    fn functional_update_selected_objects_supports_when_guards() {
        let doc = json!({
            "books": [
                {"title": "Dune", "year": 1965, "tags": ["sf"]},
                {"title": "Hyperion", "year": 1989, "tags": ["sf"]}
            ]
        });
        let r = vm_query(
            r#"$.books[*].update({ tags: tags.append("modern") when year > 1980 })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "books": [
                    {"title": "Dune", "year": 1965, "tags": ["sf"]},
                    {"title": "Hyperion", "year": 1989, "tags": ["sf", "modern"]}
                ]
            })
        );
    }

    #[test]
    fn functional_update_root_batch_updates_unrelated_paths() {
        let doc = json!({
            "books": [
                {"title": "Dune", "tags": ["sf"], "tmp": 1},
                {"title": "Hyperion", "tags": ["sf"], "tmp": 2}
            ],
            "active": true
        });
        let r = vm_query(
            r#"$.update({ "books[*].tags": @.append("test"), "books[*].tmp": DELETE, active: false })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "books": [
                    {"title": "Dune", "tags": ["sf", "test"]},
                    {"title": "Hyperion", "tags": ["sf", "test"]}
                ],
                "active": false
            })
        );
    }

    #[test]
    fn functional_update_root_batch_supports_filtered_wildcards() {
        let doc = json!({
            "books": [
                {"title": "Dune", "year": 1965, "tags": ["sf"]},
                {"title": "Hyperion", "year": 1989, "tags": ["sf"]}
            ]
        });
        let r = vm_query(
            r#"$.update({ "books[* if year > 1980].tags": @.append("modern") })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "books": [
                    {"title": "Dune", "year": 1965, "tags": ["sf"]},
                    {"title": "Hyperion", "year": 1989, "tags": ["sf", "modern"]}
                ]
            })
        );
    }

    #[test]
    fn functional_update_selected_objects_supports_wildcard_filter_selector() {
        let doc = json!({
            "books": [
                {"title": "Dune", "year": 1965, "tags": ["sf"]},
                {"title": "Hyperion", "year": 1989, "tags": ["sf"]}
            ]
        });
        let r = vm_query(
            r#"$.books[* if year > 1980].update({ tags: tags.append("modern") })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "books": [
                    {"title": "Dune", "year": 1965, "tags": ["sf"]},
                    {"title": "Hyperion", "year": 1989, "tags": ["sf", "modern"]}
                ]
            })
        );
    }

    #[test]
    fn functional_update_selected_objects_can_read_root_values() {
        let doc = json!({
            "default_tag": "review",
            "books": [
                {"title": "Dune", "year": 1965, "tags": ["sf"]},
                {"title": "Hyperion", "year": 1989, "tags": ["sf"]}
            ]
        });
        let r = vm_query(
            r#"$.books[*].update({ tags: tags.append($.default_tag) when year > 1980 })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "default_tag": "review",
                "books": [
                    {"title": "Dune", "year": 1965, "tags": ["sf"]},
                    {"title": "Hyperion", "year": 1989, "tags": ["sf", "review"]}
                ]
            })
        );
    }

    #[test]
    fn functional_update_selected_objects_reads_original_snapshot() {
        let doc = json!({
            "books": [
                {"title": "Dune", "slug": "dune"}
            ]
        });
        let r = vm_query(
            r#"$.books[*].update({ title: "changed", original_title: title, slug: slug + "-v2" })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "books": [
                    {"title": "changed", "slug": "dune-v2", "original_title": "Dune"}
                ]
            })
        );
    }

    #[test]
    fn functional_update_overlapping_writes_are_source_ordered() {
        let doc = json!({
            "books": [
                {"title": "Dune", "meta": {"score": 10}}
            ]
        });
        let r = vm_query(
            r#"$.books[0].update({ title: "draft", title: "final", meta: {}, "meta.score": 99 })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(
            r,
            json!({
                "books": [
                    {"title": "final", "meta": {"score": 99}}
                ]
            })
        );
    }

    #[test]
    fn functional_update_root_overlapping_writes_are_source_ordered() {
        let doc = json!({"active": true, "meta": {"old": true}});
        let r = vm_query(
            r#"$.update({ meta: {}, "meta.updated": true, active: false, active: true })"#,
            &doc,
        )
        .unwrap();
        assert_eq!(r, json!({"active": true, "meta": {"updated": true}}));
    }

    #[test]
    fn functional_update_scalar_target_follows_patch_object_materialization() {
        let doc = json!({"items": [1, 2]});
        let r = vm_query(r#"$.items[*].update({ seen: true })"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({
                "items": [
                    {"seen": true},
                    {"seen": true}
                ]
            })
        );
    }

    #[test]
    fn functional_update_preserves_untouched_arc_subtrees() {
        let mut untouched_map = IndexMap::new();
        untouched_map.insert(Arc::<str>::from("deep"), Val::Bool(true));
        let untouched = Val::obj(untouched_map);
        let untouched_arc = match &untouched {
            Val::Obj(map) => Arc::clone(map),
            _ => unreachable!(),
        };

        let mut book = IndexMap::new();
        book.insert(
            Arc::<str>::from("tags"),
            Val::arr(vec![Val::Str(Arc::from("sf"))]),
        );
        let books = Val::arr(vec![Val::obj(book)]);

        let mut root = IndexMap::new();
        root.insert(Arc::<str>::from("books"), books);
        root.insert(Arc::<str>::from("untouched"), untouched);

        let program =
            Compiler::compile_str(r#"$.books[*].update({ tags: tags.append("test") })"#).unwrap();
        let mut vm = VM::new();
        let out = vm.execute_val_raw(&program, Val::obj(root)).unwrap();

        let Val::Obj(out_map) = out else {
            panic!("expected object result");
        };
        let Some(Val::Obj(out_untouched)) = out_map.get("untouched") else {
            panic!("expected untouched object");
        };
        assert!(Arc::ptr_eq(&untouched_arc, out_untouched));
    }

    #[test]
    fn functional_update_filtered_wildcard_preserves_unselected_object_arc() {
        let mut first = IndexMap::new();
        first.insert(Arc::<str>::from("id"), Val::Int(1));
        first.insert(Arc::<str>::from("keep"), Val::Bool(false));
        first.insert(
            Arc::<str>::from("tags"),
            Val::arr(vec![Val::Str(Arc::from("a"))]),
        );
        let first = Val::obj(first);
        let first_arc = match &first {
            Val::Obj(map) => Arc::clone(map),
            _ => unreachable!(),
        };

        let mut second = IndexMap::new();
        second.insert(Arc::<str>::from("id"), Val::Int(2));
        second.insert(Arc::<str>::from("keep"), Val::Bool(true));
        second.insert(
            Arc::<str>::from("tags"),
            Val::arr(vec![Val::Str(Arc::from("b"))]),
        );

        let mut root = IndexMap::new();
        root.insert(
            Arc::<str>::from("books"),
            Val::arr(vec![first, Val::obj(second)]),
        );

        let program = Compiler::compile_str(
            r#"$.books[* if keep].update({ tags: tags.append("x"), reviewed: true })"#,
        )
        .unwrap();
        let mut vm = VM::new();
        let out = vm.execute_val_raw(&program, Val::obj(root)).unwrap();

        let Val::Obj(out_map) = out else {
            panic!("expected object result");
        };
        let Some(Val::Arr(books)) = out_map.get("books") else {
            panic!("expected books array");
        };
        let Val::Obj(out_first) = &books[0] else {
            panic!("expected first book object");
        };
        assert!(Arc::ptr_eq(&first_arc, out_first));
        assert!(matches!(books[1].get("reviewed"), Some(Val::Bool(true))));
    }

    #[test]
    fn wildcard_filter_chain_delete_removes_selected_elements() {
        let doc = json!({
            "items": [
                {"id": 1, "drop": false},
                {"id": 2, "drop": true},
                {"id": 3, "drop": false}
            ]
        });
        let r = vm_query(r#"$.items[* if drop].delete()"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({
                "items": [
                    {"id": 1, "drop": false},
                    {"id": 3, "drop": false}
                ]
            })
        );
    }

    #[test]
    fn wildcard_chain_modify_lowers_to_patch() {
        let doc = json!({
            "books": [
                {"tags": ["sf"]},
                {"tags": ["hugo"]}
            ]
        });
        let r = vm_query(r#"$.books[*].tags.modify(@.append("test"))"#, &doc).unwrap();
        assert_eq!(
            r,
            json!({
                "books": [
                    {"tags": ["sf", "test"]},
                    {"tags": ["hugo", "test"]}
                ]
            })
        );
    }
}