decl-lang 0.4.7

Decl — a declarative language for describing, generating, and validating structured data: the `decl` CLI (check / evaluate / validate / fmt) and the `decl-lsp` language server, implemented natively in Rust
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
//! Reference-round reuse over the value layer; mirrors qengine/rounds.ts.
use crate::ast::{walk_expr_tree, walk_type_exprs, Expr};
use crate::engine::{Edge, Engine, Inst};
use crate::qengine::graph::{QueryId, QueryPool};
use crate::qengine::revisions::Revisions;
use crate::semantics::*;
use hashbrown::{hash_table::Entry, HashTable};
use rustc_hash::{FxHashMap, FxHashSet};
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

fn address(inst: &Inst) -> usize {
    Rc::as_ptr(inst) as usize
}

type InvertedEdges<'a> = FxHashMap<&'a str, FxHashMap<String, Vec<&'a String>>>;

// Edge maps stay immutable throughout classification. Only canonical target
// spellings need owned storage; source paths and edge keys already have owners.
fn invert_edges(all: &HashMap<String, Edge>) -> InvertedEdges<'_> {
    let mut result = FxHashMap::default();
    for (key, edge) in all {
        let mut inv: FxHashMap<String, Vec<&String>> = FxHashMap::default();
        for (source, (_, refs)) in edge {
            for target in refs
                .iter()
                .map(|p| path_str(p, None))
                .collect::<FxHashSet<_>>()
            {
                inv.entry(target).or_default().push(source);
            }
        }
        for paths in inv.values_mut() {
            paths.sort();
        }
        result.insert(key.as_str(), inv);
    }
    result
}

fn identity(v: &Value) -> Option<(u8, usize)> {
    match v {
        Value::Ref(p) => Some((0, Rc::as_ptr(p) as usize)),
        Value::Arr(a) => Some((1, Rc::as_ptr(a) as usize)),
        Value::Map(m) => Some((2, Rc::as_ptr(m) as usize)),
        Value::Rec(r) => Some((3, address(r))),
        _ => None,
    }
}

// Freeze memo values have one fixed variant per source kind. Store their thin
// owners directly instead of repeating a kind tag and a full Value per entry.
// This scratch owns copied bodies only; it never changes the source graph.
/// Whether a value holds only scalars, and arrays and maps of such. A record,
/// a reference, a callable or anything still lazy makes it, and whatever holds
/// it, not plain. So does nesting beyond `PLAIN_DEPTH`: a native caller can
/// build an array that holds itself, and the copy that follows is the path
/// that remembers what it has visited.
fn plain(v: &Value) -> bool {
    const PLAIN_DEPTH: usize = 64;
    fn within(v: &Value, depth: usize) -> bool {
        match v {
            Value::Int(_)
            | Value::Float(_)
            | Value::Bool(_)
            | Value::Str(_)
            | Value::Null
            | Value::Absent
            | Value::Undef
            | Value::Q(_)
            | Value::Range(_) => true,
            Value::Arr(_) | Value::Map(_) if depth == PLAIN_DEPTH => false,
            Value::Arr(a) => a
                .try_borrow()
                .is_ok_and(|b| b.items.iter().all(|item| within(item, depth + 1))),
            Value::Map(m) => m
                .try_borrow()
                .is_ok_and(|b| b.entries.values().all(|value| within(value, depth + 1))),
            _ => false,
        }
    }
    within(v, 0)
}

#[derive(Default)]
struct CopyMemo {
    records: FxHashMap<usize, Inst>,
    // the record copies in the order they were made
    order: Vec<Inst>,
    arrays: FxHashMap<usize, Rc<RefCell<ArrV>>>,
    maps: FxHashMap<usize, Rc<RefCell<MapV>>>,
    refs: FxHashMap<usize, Rc<SegPath>>,
}

impl CopyMemo {
    fn get(&self, value: &Value) -> Option<Value> {
        match value {
            Value::Rec(record) => self.records.get(&address(record)).cloned().map(Value::Rec),
            Value::Arr(array) => self
                .arrays
                .get(&(Rc::as_ptr(array) as usize))
                .cloned()
                .map(Value::Arr),
            Value::Map(map) => self
                .maps
                .get(&(Rc::as_ptr(map) as usize))
                .cloned()
                .map(Value::Map),
            Value::Ref(path) => self
                .refs
                .get(&(Rc::as_ptr(path) as usize))
                .cloned()
                .map(Value::Ref),
            _ => None,
        }
    }
}

/// The registered records by canonical spelling, for one invalidation walk:
/// which records lie under a place. One text and one list of prefix lengths
/// hold every path, and an order by spelling replaces a table entry per prefix
/// per record: the records under a place are a run of that order.
struct RecordPaths {
    text: String,
    // where record i's spelling starts in `text`; one more entry ends the last
    starts: Vec<u32>,
    // the length of every prefix of every spelling, record by record
    ends: Vec<u32>,
    // where record i's prefix lengths start in `ends`; one more entry ends the last
    firsts: Vec<u32>,
    // record indices by spelling
    order: Vec<u32>,
}

impl RecordPaths {
    /// `None` when the registry outgrows 32-bit offsets.
    fn of(registry: &[Inst]) -> Option<Self> {
        let count = u32::try_from(registry.len()).ok()?;
        // Sized exactly: this index is live while the walk's other scratch is built.
        let segments = registry.iter().map(|r| r.borrow().path.len()).sum();
        let mut paths = Self {
            text: String::new(),
            starts: Vec::with_capacity(registry.len() + 1),
            ends: Vec::with_capacity(segments),
            firsts: Vec::with_capacity(registry.len() + 1),
            order: (0..count).collect(),
        };
        for r in registry {
            paths.starts.push(u32::try_from(paths.text.len()).ok()?);
            paths.firsts.push(u32::try_from(paths.ends.len()).ok()?);
            path_str_ends_into(&r.borrow().path, &mut paths.text, &mut paths.ends)?;
        }
        paths.starts.push(u32::try_from(paths.text.len()).ok()?);
        paths.firsts.push(u32::try_from(paths.ends.len()).ok()?);
        paths.text.shrink_to_fit();
        let mut order = std::mem::take(&mut paths.order);
        order.sort_unstable_by(|&a, &b| paths.spelling(a as usize).cmp(paths.spelling(b as usize)));
        paths.order = order;
        Some(paths)
    }
    fn spelling(&self, record: usize) -> &str {
        &self.text[self.starts[record] as usize..self.starts[record + 1] as usize]
    }
    /// Whether no two records share a spelling.
    fn distinct(&self) -> bool {
        self.order
            .windows(2)
            .all(|pair| self.spelling(pair[0] as usize) != self.spelling(pair[1] as usize))
    }
    /// The records at or under a place: those whose spelling starts with the
    /// place's and has a prefix ending there. Spellings that merely share the
    /// text (a sibling with a longer name) sit in the same run and are skipped.
    fn under<'a>(&'a self, place: &'a str) -> impl Iterator<Item = usize> + 'a {
        let from = self
            .order
            .partition_point(|&i| self.spelling(i as usize) < place);
        let length = u32::try_from(place.len()).ok();
        self.order[from..]
            .iter()
            .map(|&i| i as usize)
            .take_while(move |&i| self.spelling(i).starts_with(place))
            .filter(move |&i| {
                let ends = &self.ends[self.firsts[i] as usize..self.firsts[i + 1] as usize];
                length.is_some_and(|length| ends.binary_search(&length).is_ok())
            })
    }
}

/// Readers by dependency for one invalidation walk: a chained link per read
/// edge and one table entry per dependency, instead of a set per dependency.
/// The table is entered by the hash a key caches for its text and compared by
/// text: no spelling is hashed while the index is built, and a dependency is
/// found by its spelling whichever pool interned it.
struct Readers<'a> {
    names: Vec<&'a QueryId>,
    // (the dependency, the head of its chain: a link's index plus one)
    heads: HashTable<(&'a QueryId, u32)>,
    // (reader's index in `names`, the dependency's next link plus one; 0 ends)
    links: Vec<(u32, u32)>,
}

impl<'a> Readers<'a> {
    /// `None` when the graph outgrows the links' 32-bit indices.
    fn with_capacity(readers: usize, edges: usize) -> Option<Self> {
        (u32::try_from(readers).is_ok() && u32::try_from(edges).is_ok_and(|n| n < u32::MAX)).then(
            || Self {
                names: Vec::with_capacity(readers),
                heads: HashTable::new(),
                links: Vec::with_capacity(edges),
            },
        )
    }
    fn reader(&mut self, name: &'a QueryId) -> u32 {
        self.names.push(name);
        (self.names.len() - 1) as u32
    }
    fn insert(&mut self, dep: &'a QueryId, reader: u32) {
        let next = self.links.len() as u32 + 1;
        match self.heads.entry(
            dep.text_hash(),
            |(key, _)| *key == dep,
            |(key, _)| key.text_hash(),
        ) {
            Entry::Occupied(mut entry) => {
                let head = &mut entry.get_mut().1;
                self.links.push((reader, *head));
                *head = next;
            }
            Entry::Vacant(entry) => {
                self.links.push((reader, 0));
                entry.insert((dep, next));
            }
        }
    }
    fn of<'s>(&'s self, dep: &str) -> impl Iterator<Item = &'a str> + 's {
        let mut next = self
            .heads
            .find(QueryPool::text_hash(dep), |(key, _)| key.as_str() == dep)
            .map_or(0, |(_, head)| *head);
        std::iter::from_fn(move || {
            let (reader, following) = *self.links.get((next as usize).checked_sub(1)?)?;
            next = following;
            Some(self.names[reader as usize].as_str())
        })
    }
}

fn identical(a: &Value, b: &Value) -> bool {
    match (identity(a), identity(b)) {
        (Some(a), Some(b)) => a == b,
        (None, None) => value_eq(a, b),
        _ => false,
    }
}

// Compare observed shapes, leaving independently read member values to the graph.
fn same(a: &Value, b: &Value) -> bool {
    if identity(a).is_some() && identity(a) == identity(b) {
        return true;
    }
    match (a, b) {
        (Value::Rec(a), Value::Rec(b)) => {
            let (a, b) = (a.borrow(), b.borrow());
            a.type_name == b.type_name
                && Rc::ptr_eq(&a.rt, &b.rt)
                && a.path == b.path
                && a.slots.len() == b.slots.len()
                && a.slots.iter().zip(&b.slots).all(|((an, av), (bn, bv))| {
                    an == bn && av.kind == bv.kind && av.hidden == bv.hidden
                })
                && a.entry_order == b.entry_order
                && a.extras.len() == b.extras.len()
                && a.extras
                    .iter()
                    .zip(&b.extras)
                    .all(|((ak, av), (bk, bv))| ak == bk && same(av, bv))
        }
        (Value::Arr(a), Value::Arr(b)) => {
            let (a, b) = (a.borrow(), b.borrow());
            a.path == b.path
                && a.items.len() == b.items.len()
                && a.items.iter().zip(&b.items).all(|(x, y)| same(x, y))
        }
        (Value::Map(a), Value::Map(b)) => {
            let (a, b) = (a.borrow(), b.borrow());
            a.path == b.path
                && a.entries.len() == b.entries.len()
                && a.entries
                    .iter()
                    .zip(b.entries.iter())
                    .all(|((ak, av), (bk, bv))| ak == bk && same(av, bv))
        }
        (Value::Rec(_) | Value::Arr(_) | Value::Map(_), _)
        | (_, Value::Rec(_) | Value::Arr(_) | Value::Map(_)) => false,
        (Value::Absent, Value::Absent) => true,
        _ => value_eq(a, b),
    }
}

// A forwarded inverse reference or foreign record view depends on snapshot age,
// even when its canonical path has not changed. Owned scalar-built records do not.
fn snapshot_result(
    v: &Value,
    eng: &Engine,
    prefix: &str,
    seen: &mut FxHashSet<(u8, usize)>,
) -> bool {
    let Some(key) = identity(v) else {
        return false;
    };
    if !seen.insert(key) {
        return false;
    }
    match v {
        Value::Ref(_) => {
            eng.inverse_refs.borrow().contains_key(&key.1)
                || eng.snap_refs.borrow().contains_key(&key.1)
        }
        Value::Arr(a) => a
            .borrow()
            .items
            .iter()
            .any(|v| snapshot_result(v, eng, prefix, seen)),
        Value::Map(m) => m
            .borrow()
            .entries
            .iter()
            .any(|(_, v)| snapshot_result(v, eng, prefix, seen)),
        Value::Rec(r) => {
            if eng.owner_of(r).is_some() {
                return true;
            }
            let r = r.borrow();
            let path = path_str(&r.path, None);
            if !(path == prefix
                || path
                    .strip_prefix(prefix)
                    .is_some_and(|tail| tail.starts_with('.') || tail.starts_with('[')))
            {
                return true;
            }
            r.slots
                .iter()
                .any(|(_, s)| snapshot_result(&s.value, eng, prefix, seen))
                || r.extras
                    .iter()
                    .any(|(_, v)| snapshot_result(v, eng, prefix, seen))
        }
        _ => false,
    }
}

/// Retained round state. Values are memoized by member slots, without a second
/// database copy; structural and reference reads use the same dependency graph.
#[derive(Default)]
pub struct RoundCache {
    /// Revision verification for retained member slots.
    pub revisions: Rc<Revisions>,
    /// Successfully reused round transitions.
    pub reused_rounds: Cell<usize>,
    /// Sum of retained record counts across transitions.
    pub retained_records: Cell<usize>,
    /// Member computations invalidated across transitions.
    pub invalidated_slots: Cell<usize>,
    clean: RefCell<FxHashSet<usize>>,
    rebased: RefCell<FxHashMap<(u8, usize), (Value, Value)>>,
    // Every type name a `$referrers` expression of the universe names. A round
    // reaches a snapshot only through an answer, and an answer names a
    // registered record of such a type: the snapshot holds those records and
    // what they contain, and nothing else.
    types: FxHashSet<String>,
}
impl RoundCache {
    /// The cache of a universe that asks for referrers; `None` when none does.
    pub(crate) fn of(env: &Rc<Env>) -> Option<Self> {
        fn visit(env: &Rc<Env>, seen: &mut HashSet<usize>, types: &mut FxHashSet<String>) {
            if !seen.insert(Rc::as_ptr(env) as usize) {
                return;
            }
            let mut mark = |e: &Rc<Expr>| {
                if let Expr::Referrers { ty, .. } = &**e {
                    types.insert(ty.clone());
                }
            };
            for t in env.type_asts.borrow().values() {
                walk_type_exprs(&t.ast, true, &mut mark);
            }
            for f in env.funcs.borrow().values() {
                walk_expr_tree(&f.body, true, &mut mark);
                if let Some(t) = &f.ret {
                    walk_type_exprs(t, true, &mut mark);
                }
                for p in &f.params {
                    if let Some(t) = &p.ty {
                        walk_type_exprs(t, true, &mut mark);
                    }
                }
            }
            for c in env.consts.borrow().values() {
                walk_expr_tree(&c.expr, true, &mut mark);
                if let Some(t) = &c.ty {
                    walk_type_exprs(t, true, &mut mark);
                }
            }
            for (_, t, e) in env.outputs.borrow().iter() {
                walk_type_exprs(t, true, &mut mark);
                walk_expr_tree(e, true, &mut mark);
            }
            for (t, e) in env.inputs.borrow().values() {
                walk_type_exprs(t, true, &mut mark);
                if let Some(e) = e {
                    walk_expr_tree(e, true, &mut mark);
                }
            }
            for im in env.imports.borrow().values() {
                visit(&im.env, seen, types);
            }
            for (env, _) in env.namespaces.borrow().values() {
                visit(env, seen, types);
            }
        }
        let mut types = FxHashSet::default();
        visit(env, &mut HashSet::new(), &mut types);
        (!types.is_empty()).then(|| Self {
            types,
            ..Self::default()
        })
    }

    pub(crate) fn clean(&self, inst: &Inst) -> bool {
        self.clean.borrow().contains(&address(inst))
    }
    /// Once evaluation has cleared prev, value() bypasses this epoch's memo.
    /// A later evaluation installs a new RoundCache. Release both old value
    /// owners and table capacity, retaining the clean and revision state.
    pub(crate) fn release_rebased(&self) {
        let rebased = std::mem::take(&mut *self.rebased.borrow_mut());
        // Cached values can contain native captures whose destructors reenter
        // evaluation. No memo borrow may survive into their destruction.
        drop(rebased);
    }
    fn rebase_child<'a>(&self, v: &'a Value, eng: &Engine) -> Cow<'a, Value> {
        match v {
            Value::Ref(_) | Value::Arr(_) | Value::Map(_) => Cow::Owned(self.value(v, eng)),
            // These variants pass through value unchanged. Keep the input's
            // owner until a replacement container actually needs a clone.
            _ => Cow::Borrowed(v),
        }
    }
    pub(crate) fn value(&self, v: &Value, eng: &Engine) -> Value {
        if eng.prev.borrow().is_none() {
            return v.clone();
        }
        let Some(key) = identity(v) else {
            return v.clone();
        };
        if key.0 == 3 {
            return v.clone();
        }
        if let Some((_, cached)) = self.rebased.borrow().get(&key) {
            return cached.clone();
        }
        let result = match v {
            Value::Ref(p)
                if eng
                    .round_refs
                    .borrow()
                    .contains_key(&(Rc::as_ptr(p) as usize)) =>
            {
                let next = Rc::new((**p).clone());
                if let Some(prev) = eng.prev.borrow().as_ref() {
                    eng.snap_refs
                        .borrow_mut()
                        .insert(Rc::as_ptr(&next) as usize, (next.clone(), prev.clone()));
                }
                eng.round_refs
                    .borrow_mut()
                    .insert(Rc::as_ptr(&next) as usize, next.clone());
                eng.inverse_refs
                    .borrow_mut()
                    .insert(Rc::as_ptr(&next) as usize, next.clone());
                Value::Ref(next)
            }
            Value::Arr(a) => {
                let a = a.borrow();
                let mut replacement: Option<Vec<Value>> = None;
                for (index, original) in a.items.iter().enumerate() {
                    let next = self.rebase_child(original, eng);
                    if replacement.is_none() && !identical(&next, original) {
                        let mut items = Vec::with_capacity(a.items.len());
                        items.extend_from_slice(&a.items[..index]);
                        replacement = Some(items);
                    }
                    if let Some(items) = &mut replacement {
                        items.push(next.into_owned());
                    }
                }
                if let Some(items) = replacement {
                    #[cfg(feature = "runtime-diagnostics")]
                    crate::retention_diagnostics::array(
                        crate::retention_diagnostics::ArraySite::Rebased,
                        items.len(),
                        items.capacity(),
                    );
                    Value::Arr(Rc::new(RefCell::new(ArrV {
                        items,
                        path: a.path.clone(),
                    })))
                } else {
                    v.clone()
                }
            }
            Value::Map(m) => {
                let m = m.borrow();
                if m.entries.is_shared() {
                    let mut replacement: Option<Vec<Value>> = None;
                    for (index, original) in m.entries.values().enumerate() {
                        let next = self.rebase_child(original, eng);
                        if replacement.is_none() && !identical(&next, original) {
                            let mut values = Vec::with_capacity(m.entries.len());
                            values.extend(m.entries.values().take(index).cloned());
                            replacement = Some(values);
                        }
                        if let Some(values) = &mut replacement {
                            values.push(next.into_owned());
                        }
                    }
                    if let Some(values) = replacement {
                        Value::Map(Rc::new(RefCell::new(MapV {
                            entries: m.entries.with_values(values),
                            path: m.path.clone(),
                        })))
                    } else {
                        v.clone()
                    }
                } else {
                    let mut replacement: Option<OrderedMap<Value>> = None;
                    for (index, (key, original)) in m.entries.iter().enumerate() {
                        let next = self.rebase_child(original, eng);
                        if replacement.is_none() && !identical(&next, original) {
                            let mut entries = OrderedMap::with_capacity_and_hasher(
                                m.entries.len(),
                                Default::default(),
                            );
                            entries.extend(
                                m.entries
                                    .iter()
                                    .take(index)
                                    .map(|(k, v)| (k.clone(), v.clone())),
                            );
                            replacement = Some(entries);
                        }
                        if let Some(entries) = &mut replacement {
                            entries.insert(key.clone(), next.into_owned());
                        }
                    }
                    if let Some(entries) = replacement {
                        Value::Map(Rc::new(RefCell::new(MapV {
                            entries: entries.into(),
                            path: m.path.clone(),
                        })))
                    } else {
                        v.clone()
                    }
                }
            }
            _ => v.clone(),
        };
        self.rebased
            .borrow_mut()
            .insert(key, (v.clone(), result.clone()));
        result
    }

    pub(crate) fn advance(
        &self,
        eng: &Rc<Engine>,
        edges: &HashMap<String, Edge>,
    ) -> Option<Rc<Engine>> {
        // Declared first so the terminal boundary includes destruction of the
        // existing registry and invalidation scratch on success or fallback.
        // The ordinal names the next reused transition, not a unique attempt.
        #[cfg(feature = "runtime-diagnostics")]
        let mut advance_diagnostic = crate::evaluation_diagnostics::AdvanceSpan::new(
            self.reused_rounds.get().saturating_add(1),
        );
        let registry = eng.env.registry_snapshot();
        if eng.env.diag_len() > 0
            || registry.iter().any(|r| {
                r.borrow()
                    .slots
                    .iter()
                    .any(|(_, s)| !matches!(s.state, SlotState::Ok | SlotState::Absent))
            })
        {
            return None;
        }
        let prior_records: FxHashMap<String, Inst> = eng
            .prev
            .borrow()
            .as_ref()
            .and_then(|p| p.frozen_registry.borrow().clone())
            .unwrap_or_default()
            .iter()
            .map(|r| (path_str(&r.borrow().path, None), r.clone()))
            .collect();
        // Each prefix is a slice of its record's one canonical spelling. Store
        // segment boundaries while formatting; parsing delimiters afterwards
        // would be wrong for quoted keys and native bare root names.
        let registry_paths = RecordPaths::of(&registry)?;
        if !registry_paths.distinct() {
            return None;
        }
        let snap = eng.snap.borrow();
        let old_edges = snap
            .as_ref()
            .map(|s| invert_edges(&s.edges))
            .unwrap_or_default();
        let new_edges = invert_edges(edges);
        // Classification and invalidation only inspect the dependency graph.
        // Its key text can serve the temporary reverse index without copies.
        let reads = eng.reads.borrow();
        let mut reverse =
            Readers::with_capacity(reads.len(), reads.values().map(|deps| deps.len()).sum())?;
        let mut pending: Vec<Cow<'_, str>> = Vec::new();
        for (reader, deps) in reads.iter() {
            let index = reverse.reader(reader);
            for dep in deps.iter() {
                reverse.insert(dep, index);
                if let Some(s) = dep.strip_prefix("edge:") {
                    let mut parts = s.splitn(3, '|');
                    let key = format!("{}|{}", parts.next()?, parts.next()?);
                    let target = parts.next()?;
                    let a = old_edges.get(key.as_str()).and_then(|i| i.get(target));
                    let b = new_edges.get(key.as_str()).and_then(|i| i.get(target));
                    if a.map(Vec::as_slice).unwrap_or(&[]) != b.map(Vec::as_slice).unwrap_or(&[]) {
                        pending.push(Cow::Borrowed(dep.as_str()));
                    }
                } else if dep.as_str() == "round:nested" {
                    pending.push(Cow::Borrowed(dep.as_str()));
                } else if dep.as_str() == "round:reference" {
                    let prefix = reader.strip_prefix("root:").unwrap_or(reader.as_str());
                    let value = eng
                        .slots_by_key
                        .borrow()
                        .get(reader)
                        .and_then(|(r, n)| r.borrow().slot(n).map(|s| s.value.clone()))
                        .or_else(|| eng.env.root(prefix));
                    if reader.starts_with("const:")
                        || value.as_ref().is_some_and(|v| {
                            snapshot_result(v, eng, prefix, &mut FxHashSet::default())
                        })
                    {
                        pending.push(Cow::Borrowed(reader.as_str()));
                    }
                } else if let Some(key) = dep.strip_prefix("snapshot:") {
                    let current = eng.query_slot_shared(key);
                    let equal = current.is_some_and(|(r, n)| {
                        let r = r.borrow();
                        let Some(old) = prior_records.get(&path_str(&r.path, None)) else {
                            return false;
                        };
                        let old = old.borrow();
                        match (old.slot(&n), r.slot(&n)) {
                            (Some(a), Some(b)) => a.state == b.state && same(&a.value, &b.value),
                            _ => false,
                        }
                    });
                    if !equal {
                        pending.push(Cow::Borrowed(dep.as_str()));
                    }
                }
            }
        }
        // Classification is complete; these indices must not overlap the
        // descendant index and the copied frozen value layer below.
        drop(prior_records);
        drop(old_edges);
        drop(new_edges);
        drop(snap);
        let forced = pending.iter().map(|key| key.as_ref().to_owned()).collect();
        let mut invalid = FxHashSet::default();
        let mut dropped = FxHashSet::default();
        let mut roots = HashSet::new();
        let mut dirty = FxHashSet::default();
        while let Some(key) = pending.pop() {
            // Duplicate insertions can still grow the set before lookup. Keep
            // that behavior: its later iteration determines reset/Drop order.
            if !invalid.insert(key.as_ref().to_owned()) {
                continue;
            }
            if key.starts_with("const:") {
                return None;
            }
            pending.extend(reverse.of(key.as_ref()).map(Cow::Borrowed));
            let prefix = if let Some(name) = key.strip_prefix("root:") {
                roots.insert(name.to_string());
                Some(path_str(&[Seg::Name(name.into())], None))
            } else {
                eng.query_slot_shared(&key).map(|(inst, name)| {
                    let mut current = Some(inst.clone());
                    while let Some(i) = current {
                        dirty.insert(address(&i));
                        current = i.borrow().parent.clone();
                    }
                    let member = Seg::Name(name);
                    path_str_iter(
                        inst.borrow().path.iter().chain(std::iter::once(&member)),
                        None,
                    )
                })
            };
            if let Some(place) = prefix.as_deref() {
                for inst in registry_paths.under(place).map(|i| &registry[i]) {
                    if dropped.insert(address(inst)) {
                        for (n, _) in &inst.borrow().slots {
                            pending.push(Cow::Owned(Engine::slot_key(inst, n)));
                        }
                    }
                }
            }
        }
        // Keep the registry owner, but release classification scratch before
        // freezing or replacing any dependencies for the next round.
        drop(registry_paths);
        drop(pending);
        drop(reverse);
        drop(reads);
        let mut rebound = false;
        for (name, _) in eng.env.roots_vec() {
            rebound |= roots.contains(&name);
            if rebound && !roots.contains(&name) {
                return None;
            }
        }
        #[cfg(feature = "runtime-diagnostics")]
        advance_diagnostic.classified();
        let snapshot = self.freeze(eng, &registry)?;
        #[cfg(feature = "runtime-diagnostics")]
        advance_diagnostic.frozen();
        self.revisions.begin(eng, &invalid, &forced, &dropped);
        for inst in &registry {
            if dropped.contains(&address(inst)) {
                for (n, _) in &inst.borrow().slots {
                    let key = Engine::slot_key(inst, n);
                    eng.remove_query_reads(&key);
                    eng.remove_query_slot(&key);
                }
            }
        }
        for key in &invalid {
            if let Some((inst, name)) = eng.query_slot_shared(key) {
                let mut i = inst.borrow_mut();
                let s = i.slot_mut(&name)?;
                if s.compute.is_some() {
                    s.state = SlotState::Unforced;
                    s.value = Value::Undef;
                    self.invalidated_slots.set(self.invalidated_slots.get() + 1);
                }
            }
            eng.remove_query_reads(key);
        }
        eng.env.registry_retain(|r| !dropped.contains(&address(r)));
        *self.clean.borrow_mut() = registry
            .iter()
            .map(address)
            .filter(|id| !dirty.contains(id) && !dropped.contains(id))
            .collect();
        for root in &roots {
            eng.env.remove_root(root);
        }
        *eng.round_roots.borrow_mut() = Some(roots);
        eng.deferred_slots.borrow_mut().clear();
        eng.deferred_roots.borrow_mut().clear();
        eng.phase.set(1);
        *eng.snap.borrow_mut() = None;
        *eng.queried.borrow_mut() = eng
            .reads
            .borrow()
            .values()
            .flat_map(|deps| deps.iter())
            .filter_map(|dep| {
                let tail = dep.strip_prefix("edge:")?;
                let mut parts = tail.splitn(3, '|');
                Some(format!("{}|{}", parts.next()?, parts.next()?))
            })
            .collect();
        eng.ref_index.borrow_mut().clear();
        eng.computing_edges.borrow_mut().clear();
        eng.edge_bases.borrow_mut().clear();
        for reset in eng.round_resets.borrow().iter() {
            reset();
        }
        self.rebased.borrow_mut().clear();
        *eng.prev.borrow_mut() = Some(snapshot.clone());
        for (name, value) in eng.env.roots_vec() {
            eng.env.set_root(&name, self.value(&value, eng));
        }
        self.retained_records
            .set(self.retained_records.get() + registry.len() - dropped.len());
        self.reused_rounds.set(self.reused_rounds.get() + 1);
        #[cfg(feature = "runtime-diagnostics")]
        advance_diagnostic.accepted();
        Some(snapshot)
    }

    /// The round as the next one can reach it. A round obtains a frozen record
    /// only through a `$referrers` answer, which names a registered record of a
    /// type some `$referrers` expression names; from there it reads that
    /// record's values, down into the records it contains, and nothing else:
    /// no member of a frozen record is evaluated, so no parent link is
    /// followed, and an ordinary reference resolves in the live round. So
    /// only those records are copied, without parents, and an answer's path is
    /// looked up among them instead of walked from frozen roots.
    fn freeze(&self, eng: &Rc<Engine>, registry: &[Inst]) -> Option<Rc<Engine>> {
        let tagger = eng.env.tagger.borrow().clone();
        let frozen = Engine::bare_with_queries(eng.env.clone(), eng.query_pool());
        *eng.env.tagger.borrow_mut() = tagger;
        *frozen.programs.borrow_mut() = eng.programs.borrow().clone();
        *frozen.prev.borrow_mut() = eng.prev.borrow().clone();
        *frozen.snap_refs.borrow_mut() = eng.snap_refs.borrow().clone();
        *frozen.inverse_refs.borrow_mut() = eng.inverse_refs.borrow().clone();
        let mut copies = CopyMemo::default();
        for r in registry {
            let named = r
                .borrow()
                .type_name
                .as_ref()
                .is_some_and(|t| self.types.contains(t));
            if named {
                self.copy(&Value::Rec(r.clone()), eng, &frozen, &mut copies)?;
            }
        }
        // The copies in the order they were made: candidates in registry
        // order, each followed by the records it contains.
        let registry = copies.order;
        let mut index = FxHashMap::default();
        for r in &registry {
            if index
                .insert(path_str(&r.borrow().path, None), r.clone())
                .is_some()
            {
                return None;
            }
        }
        *frozen.frozen_roots.borrow_mut() = Some(vec![]);
        *frozen.frozen_index.borrow_mut() = Some(index);
        *frozen.frozen_set.borrow_mut() = registry.iter().map(address).collect();
        // Snapshot navigation uses record slots directly. Only observed reads
        // need comparison at a later boundary; no full field-key index here.
        *frozen.frozen_registry.borrow_mut() = Some(registry);
        Some(frozen)
    }
    fn copy(
        &self,
        raw: &Value,
        eng: &Engine,
        frozen: &Rc<Engine>,
        copies: &mut CopyMemo,
    ) -> Option<Value> {
        let v = self.value(raw, eng);
        if let Some(c) = copies.get(&v) {
            return Some(c);
        }
        Some(match &v {
            Value::Rec(inst) => {
                if eng.owner_of(inst).is_some() {
                    return Some(v);
                }
                let b = inst.borrow();
                let r = record_instance(RecInst {
                    type_name: b.type_name.clone(),
                    rt: b.rt.clone(),
                    path: b.path.clone(),
                    ps: RefCell::new(None),
                    parent: None,
                    slots: Vec::new(),
                    entry_order: b.entry_order.clone(),
                    extras: Vec::new(),
                    menv: b.menv.clone(),
                });
                copies.records.insert(address(inst), r.clone());
                copies.order.push(r.clone());
                let mut slots = Vec::with_capacity(b.slots.len());
                for (name, s) in &b.slots {
                    if !matches!(s.state, SlotState::Ok | SlotState::Absent) {
                        return None;
                    }
                    slots.push((
                        name.clone(),
                        Slot {
                            kind: s.kind,
                            hidden: s.hidden,
                            state: s.state,
                            value: self.copy(&s.value, eng, frozen, copies)?,
                            compute: None,
                        },
                    ));
                }
                let extras: Option<Vec<_>> = b
                    .extras
                    .iter()
                    .map(|(k, v)| Some((k.clone(), self.copy(v, eng, frozen, copies)?)))
                    .collect();
                {
                    let mut r = r.borrow_mut();
                    r.slots = slots;
                    r.extras = extras?;
                }
                Value::Rec(r)
            }
            // Nothing in a plain array or map can change or be re-identified in a
            // later round, and nothing mutates one once it is built: the snapshot
            // shares it instead of copying it.
            Value::Arr(_) | Value::Map(_) if plain(&v) => v.clone(),
            Value::Arr(a) => {
                let b = a.borrow();
                #[cfg(feature = "runtime-diagnostics")]
                let diagnostic_array = crate::retention_diagnostics::ArrayAttempt::start(
                    crate::retention_diagnostics::ArraySite::SnapshotCopy,
                    Some(b.items.len()),
                );
                let r = Rc::new(RefCell::new(ArrV {
                    items: vec![],
                    path: b.path.clone(),
                }));
                copies.arrays.insert(Rc::as_ptr(a) as usize, r.clone());
                let mut items = Vec::with_capacity(b.items.len());
                for value in &b.items {
                    items.push(self.copy(value, eng, frozen, copies)?);
                }
                r.borrow_mut().items = items;
                #[cfg(feature = "runtime-diagnostics")]
                {
                    let a = r.borrow();
                    diagnostic_array.finish(a.items.len(), a.items.capacity());
                }
                Value::Arr(r)
            }
            Value::Map(m) => {
                let b = m.borrow();
                let r = Rc::new(RefCell::new(MapV {
                    entries: Default::default(),
                    path: b.path.clone(),
                }));
                copies.maps.insert(Rc::as_ptr(m) as usize, r.clone());
                if b.entries.is_shared() {
                    let mut values = Vec::with_capacity(b.entries.len());
                    for value in b.entries.values() {
                        values.push(self.copy(value, eng, frozen, copies)?);
                    }
                    r.borrow_mut().entries = b.entries.with_values(values);
                } else {
                    let entries: Option<Vec<_>> = b
                        .entries
                        .iter()
                        .map(|(k, v)| Some((k.clone(), self.copy(v, eng, frozen, copies)?)))
                        .collect();
                    r.borrow_mut().entries = entries?.into_iter().collect();
                }
                Value::Map(r)
            }
            Value::Ref(p)
                if eng
                    .round_refs
                    .borrow()
                    .contains_key(&(Rc::as_ptr(p) as usize)) =>
            {
                // A frozen answer has its own identity: live cache rebasing must
                // never move it to the next round's owner.
                let path = Rc::new(p.as_ref().clone());
                if let Some((_, owner)) = eng.snap_refs.borrow().get(&(Rc::as_ptr(p) as usize)) {
                    frozen
                        .snap_refs
                        .borrow_mut()
                        .insert(Rc::as_ptr(&path) as usize, (path.clone(), owner.clone()));
                }
                frozen
                    .inverse_refs
                    .borrow_mut()
                    .insert(Rc::as_ptr(&path) as usize, path.clone());
                copies.refs.insert(Rc::as_ptr(p) as usize, path.clone());
                Value::Ref(path)
            }
            Value::Ref(_)
            | Value::JObj(_)
            | Value::Int(_)
            | Value::Float(_)
            | Value::Bool(_)
            | Value::Str(_)
            | Value::Null
            | Value::Absent
            | Value::Undef
            | Value::Q(_)
            | Value::Range(_) => v.clone(),
            _ => return None,
        })
    }
}

// Rust-native snapshot, callback and lifetime boundaries. Language behavior
// remains covered by the shared reference-round corpus.
#[cfg(test)]
#[path = "../../tests/private/round_advance_test.rs"]
mod tests;