relate-executor 1.4.0

In-memory graph and Cypher physical executor
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
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};

use std::sync::{Arc, Mutex};

use relate_catalog::{Catalog, ConstraintDef, IndexDef};
use relate_core::{Namespace, Node, NodeId, RelId, Relationship, Result, Value};

use crate::adjacency::{SealedArena, TypedAdj};
use crate::group_key::GroupKey;
use crate::memory::ChainShape;
use crate::pull_identity::PullIdentityIndex;
use crate::redo::{self, RedoOp};
use crate::store::{Interner, LiveNode, LiveRel, RelTypes};

use constraint_keys::ConstraintKeyIndex;
use count_state::{CountDelta, CountStats};

// The count-only reader's probe shape (LABS-370 round 3, F-1-5): re-exported
// for the recognizer in `exec` — the window itself lives on `Graph`.
pub(crate) use count_state::{CountProbe, LabelSetCount};

/// A live entity addressed by kind: an id alone does not say whether it names
/// a node or a relationship, so every kind-dependent decision takes this pair
/// rather than a bare id beside a separate selector. The maintained
/// constraint-key map stores its holders as one (`graph/constraint_keys`) and
/// the overlay's delete accounting nets a create per kind (`overlay/writes`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum EntityId {
    Node(NodeId),
    Rel(RelId),
}

mod access;
mod accounting;
#[cfg(any(test, feature = "test-hooks"))]
mod build_counter;
#[cfg(test)]
pub(crate) use build_counter::BuildCounter;
mod engine_api;

mod adjacency;
mod apply_redo;
// The research-only heap-census harness (ADR-0476 quarantine shape): the
// testing example of the same name reads it through the research feature.
// Private module with root re-exports only (one public path per item).
#[cfg(feature = "research")]
pub(crate) mod census;
mod chain;
mod conflict;
pub(crate) mod constraint_keys;
mod count_state;
mod declared;
mod degree_stats;
mod degree_stats_estimate;
mod degree_stats_incident;
mod derived_migration;
mod entity_mutation;
mod id_vec;
mod index;
mod index_lookup;
mod index_postings;
mod key_stats;
pub(crate) use key_stats::{
    heavy_count as key_heavy_count, is_admitted as key_value_admitted, PublishedKeyStats,
};
mod label_mutation;
mod label_probe;
mod pair_postings;
mod pin;
mod prop_read;
mod prop_store;
pub use prop_store::{PropFold, PropStore, PublishedRow};
mod query_stats;
#[cfg(feature = "vortex-store")]
mod vortex_store;
pub use pin::SnapshotPin;
#[cfg(test)]
use pin::PIN_ACQUIRE_RETRIES;
#[cfg(test)]
use pin::PIN_CLAIMING;
use pin::{PIN_FREE, PIN_SLOTS};
#[cfg(feature = "vortex-store")]
pub use vortex_store::{attach_vortex_store, VortexStore};
mod rebuild;
mod redo_preflight;
mod rel_postings;
mod restore;
mod schema_api;
mod services;
mod shard;
// Research-only (speed-of-light kernels), quarantined behind the
// non-default `research` cargo feature (ADR-0476): absent from every
// default build and every bundle.
#[cfg(feature = "research")]
pub mod sol;
// Research-only: the live-read family the sol kernel reads (the
// helpers this quarantine used to inline in the module root; the
// qpp half retired with its prototype, ADR-0478).
#[cfg(feature = "research")]
mod research;
#[cfg(test)]
pub(crate) mod test_support;
mod theater;
mod token_changes;
pub use token_changes::AppliedTokenChanges;
mod unposted;
mod vector_matrix;

pub(crate) use declared::{spatial_holds, trigram_count, Extremum, RangeSeek, SpatialSeek};
use declared::{GramIndex, PointIndex, RangeIndex};
#[cfg(test)]
pub(crate) use index::CONTAINS_SAMPLE_BOUND;
use index::{ContainsMemo, Indexes};
// One canonical provenance type (LABS-643): defined beside the planner's
// `PatternStats` contract that consumes it, re-exported so the executor's
// construction sites and tests keep the one path.
#[cfg(test)]
pub(crate) use label_probe::take_label_probe_checks;
pub(crate) use label_probe::LabelProbe;
pub use query_stats::QueryStats;
// One public path (index stays private): the whole-graph index-rebuild
// count the facade's reopen tests read (LABS-1112's empty-replay skip).
#[cfg(feature = "test-hooks")]
#[doc(hidden)]
pub use index::take_index_rebuilds;
// The vector matrix's served-search count (ADR-0705), read by the facade's
// differential test.
#[cfg(feature = "test-hooks")]
#[doc(hidden)]
pub use vector_matrix::take_vector_matrix_serves;
// The adjacency side the `test-hooks` sealed-chunk seam is read by, so the
// storage open tests can name the direction across the crate boundary.
#[cfg(feature = "test-hooks")]
#[doc(hidden)]
pub use adjacency::Side;
#[cfg(test)]
pub(crate) use adjacency::HOP_BATCH;
pub(crate) use adjacency::{HopBuf, PeerHop};
pub use relate_planner::ContainsCount;
pub(crate) use services::StoreServices;

use theater::TheaterData;

/// The core-store map: integer keys, FxHash — SipHash + the default
/// hasher on dense engine-generated ids was profiled as a top-2 cost
/// (LABS-337/LABS-358); ADR-0355's rule: a key that is attacker-writable
/// must not use it.
pub(crate) type CoreMap<K, V> = dashmap::DashMap<K, V, crate::hash_seed::FxBuildHasher>;

/// The store's token resolver (ADR-0541): the facade hands the graph to the
/// planner beside its statistics, so plan-time resolution reads the same
/// interner execution does.
impl relate_names::TokenResolver for Graph {
    fn resolve(&self, name: &str) -> relate_names::Token {
        self.interner.resolve(name)
    }
}

impl Graph {
    /// A node's current live labels in the interned domain (u32 ids) —
    /// the histogram's key domain, read through [`live_version`] rather than
    /// a snapshot-visible one: the histogram is maintained at create time,
    /// inside the writing transaction, where the just-created node is not yet
    /// visible at `commit_ts` (the bug the first version of this read had —
    /// every bump looped over zero labels). The `xmax == 0` convention
    /// matches the rebuild's live-rel scan.
    pub(in crate::graph) fn live_label_ids(&self, node: NodeId) -> Vec<u32> {
        self.nodes
            .get(&node)
            .and_then(|vers| vers.live().map(|v| v.live.labels.clone()))
            .unwrap_or_default()
    }
}

pub(crate) use theater::{apply_show_overlay, DatabasesCatalog, ShowSchema};
pub use theater::{CheckpointTheater, DatabaseEntry, SchemaSnapshot};

/// An exhaustible `i64` id counter shared by the committed graph counters and
/// the overlay scratch counters. Both allocate the current value and advance;
/// both must fail rather than wrap once `i64::MAX` is reached. The two atomic
/// widths exist because the overlay seeds its counters from the graph's.
pub(crate) trait ExhaustibleIdCounter {
    fn try_alloc_id(&self) -> Option<i64>;
}

impl ExhaustibleIdCounter for AtomicI64 {
    fn try_alloc_id(&self) -> Option<i64> {
        // `try_update` is `fetch_update`'s name since Rust 1.95 (the old
        // name is deprecated in 1.99). It retries a lost race itself and
        // returns `Err` only for the closure's `None` — the counter at
        // its ceiling — so `.ok()` is "not allocated".
        self.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| {
            if (0..i64::MAX).contains(&id) {
                Some(id + 1)
            } else {
                None
            }
        })
        .ok()
    }
}

impl ExhaustibleIdCounter for AtomicU64 {
    fn try_alloc_id(&self) -> Option<i64> {
        self.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| {
            (id < i64::MAX as u64).then_some(id + 1)
        })
        .ok()
        .map(|id| id as i64)
    }
}

/// The `DeleteConnectedNode` execution error, shared by every node-delete
/// path so the message never drifts between them. The class token leads the
/// payload: live Neo4j 2026.10.1 reports the
/// `ConstraintVerificationFailed` class (G1001), and the bindings recover
/// it through the one nested-class scan of still-stringly payloads. The
/// token composes from the typed class vocabulary, so its spelling cannot
/// drift from the scan's.
pub(crate) fn delete_connected_node_error() -> relate_core::Error {
    relate_core::Error::execution(format!(
        "{}: DeleteConnectedNode: Cannot delete node with relationships unless DETACH",
        relate_error::NestedErrorClass::ConstraintVerificationFailed.as_str(),
    ))
}

/// The one typed reply for a relationship whose endpoint is not a live node:
/// the create path's semantic error, shared by the overlay's create, the
/// primitive's endpoint validation, and the redo preflight.
pub(crate) fn missing_rel_endpoint_error() -> relate_core::Error {
    relate_core::Error::semantic("cannot create relationship on missing node")
}

/// Allocate the next exhaustible id from `counter`, mapping exhaustion to the
/// caller's `<what> ID exhausted` error.
pub(crate) fn alloc_exhaustible_id(counter: &impl ExhaustibleIdCounter, what: &str) -> Result<i64> {
    counter
        .try_alloc_id()
        .ok_or_else(|| relate_core::Error::execution(format!("{what} ID exhausted")))
}

#[derive(Debug, Clone, Default)]
pub struct Procedure {
    pub name: String,
    pub arg_names: Vec<String>,
    /// Cypher type names (`STRING`, `INTEGER`, `NUMBER`, …) aligned with `arg_names`.
    pub arg_types: Vec<String>,
    pub yield_names: Vec<String>,
    pub rows: Vec<BTreeMap<String, Value>>,
}

use access::{live_version, visible_version};
use chain::{Chain, Ver};
use id_vec::IdVec;

/// The one MVCC version-chain record: node and rel chains share the shape
/// (and, via [`cow`], the copy-on-write policy) through the aliases below.
type NodeVer = Ver<LiveNode>;
type RelVer = Ver<LiveRel>;

pub(crate) fn node_version_stride() -> u64 {
    std::mem::size_of::<NodeVer>() as u64
}

pub(crate) fn rel_version_stride() -> u64 {
    std::mem::size_of::<RelVer>() as u64
}

/// The in-map size of an inline node slot: the row and its birth timestamp.
/// One id slot, including the discriminant. The floor charges the vector
/// of these, not a hash-map entry (ADR-0532).
pub(crate) fn node_slot() -> u64 {
    id_vec::slot::<Chain<LiveNode>>()
}

pub(crate) fn rel_slot() -> u64 {
    id_vec::slot::<Chain<LiveRel>>()
}

pub(crate) fn adj_slot() -> u64 {
    id_vec::slot::<TypedAdj>()
}

/// One sealed span-table id slot, the stride of the sealed arena's dense
/// span array (ADR-0599) — the span table's own one spelling of it.
fn sealed_slot() -> u64 {
    crate::adjacency::span_stride()
}

pub(crate) fn node_value() -> u64 {
    std::mem::size_of::<Chain<LiveNode>>() as u64
}

pub(crate) fn rel_value() -> u64 {
    std::mem::size_of::<Chain<LiveRel>>() as u64
}

fn adj_value() -> u64 {
    std::mem::size_of::<TypedAdj>() as u64
}

/// Copy-on-write over `id`'s slot ([`Chain::cow`]) at the write timestamp.
fn cow<Live: Clone>(write_ts: &AtomicU64, map: &IdVec<Chain<Live>>, id: i64) -> Option<Live> {
    let ts = write_ts.load(Ordering::Acquire);
    map.get_mut(&id)?.cow(ts)
}

#[derive(Debug)]
pub struct Graph {
    /// Which fixed namespace of the store this graph is (ADR-0116 §1, §10).
    /// The executor needs it for namespace-qualified element ids (ADR-0116
    /// §7); `neo4j` is the default so existing construction sites are
    /// unchanged.
    namespace: Namespace,
    /// Store-level services (procedure registry, LOAD CSV policy, preview
    /// set) shared by every namespace graph of a store (ADR-0116 §10) as one
    /// `Arc` bundle. Not a field consumers can reach: the `Arc` identity is
    /// the one-bundle invariant, so access goes through
    /// [`Graph::procedure`], [`Graph::has_procedure`],
    /// [`Graph::register_procedure`], [`Graph::csv_policy`],
    /// [`Graph::preview`], [`Graph::databases`],
    /// [`Graph::configure_load_csv`], [`Graph::configure_preview`] and
    /// [`Graph::share_services_from`].
    services: Arc<StoreServices>,
    /// The attached experimental property store's whole state (ADR-0665):
    /// the shared cell, the publication feed's pending rows, and their
    /// write-lifecycle hooks — the bundle lives beside its contract in
    /// [`prop_store`](super::prop_store).
    attached_store: prop_store::AttachedStore,
    next_node_id: AtomicI64,
    next_rel_id: AtomicI64,
    /// Last published commit (ADR-0012 / ADR-0013). Stored after apply (ADR-0018).
    published_ts: AtomicU64,
    write_ts: AtomicU64,
    in_write: AtomicBool,
    /// The graph's restore phase: one latch, born open and closed once by
    /// `graph/restore.rs::close_restoring` (`finish_restore`, a published
    /// commit, a redo apply). Checkpoint rows install only while it is open
    /// (`graph/restore.rs::check_restoring`). The phase is the refusal's
    /// evidence, never a slot's version-chain shape: a committed
    /// single-version write leaves an `Inline` chain, indistinguishable
    /// from an earlier row of an overlapping legacy part (ADR-0183).
    restoring: AtomicBool,
    record_redo: AtomicBool,
    nodes: IdVec<Chain<LiveNode>>,
    rels: IdVec<Chain<LiveRel>>,
    out_adj: IdVec<TypedAdj>,
    in_adj: IdVec<TypedAdj>,
    /// The sealed tier, one graph-level node-major arena per direction
    /// (ADR-0551 / ADR-0599): a node's compressed chunks and versioned
    /// tombstones. An entry exists only where a fold or a delete's tombstone
    /// landed, so a node that never folds pays nothing; the delta slot stays
    /// 24 bytes.
    sealed_out: SealedArena,
    sealed_in: SealedArena,
    /// LABS-851 (the structure round): the counting operator's count
    /// state — per-type rel counts, (start-label, type, end-label) pair
    /// counts, per-label live node counts, and the total live node
    /// count — as one bundle behind one mutex (the `indexes: Indexes`
    /// precedent), so the windowed-consistency invariant is structural:
    /// the count-only reader holds the one guard across its exactness
    /// check and reads, every bump takes the same guard, and a future
    /// arm's state lands inside the bundle instead of as another
    /// sibling lock. Per-field semantics, charges, and the bump/rebuild
    /// discipline live with the type in `graph/count_state.rs`.
    count_stats: Mutex<CountStats>,
    /// LABS-351: per-(label, rel-type) out-degree histogram, log2-bucketed
    /// (bucket k counts nodes of the label whose out-degree on the rel type
    /// is 2^k..2^(k+1)-1). The mean degree (`rel_type_rows / label_rows`)
    /// lies on the heavy-tailed shape where the hub join applies; the
    /// histogram's tail is the honest degree for start-selection and
    /// gate estimates. This is the HIGH-WATER degree, not the live one:
    /// the typed adjacency keeps tombstoned entries (its chunk length
    /// never shrinks), so the bucket only ever moves up on create — a
    /// floor that can only overestimate and never miss a supernode,
    /// which is exactly the conservative direction a gate needs. The
    /// adjacency rebuild recomputes it from the live rels in one pass.
    /// Estimate state the counting operator never reads — it stays
    /// beside the count bundle, not inside it.
    degree_histograms: Mutex<degree_stats::DegreeHistograms>,
    /// ADR-0439: the maintained, single-version per-constraint committed
    /// tuple map (`unique`/`key` constraints, node and relationship). Unlike
    /// the lazily built postings in [`Indexes`], this map is eagerly current;
    /// `graph/constraint_keys/mod.rs` owns its charge family and
    /// backfill/rebuild lifecycle; `simulation.rs` owns the op classification
    /// and the entity simulation; `seams.rs` the `apply_redo` maintenance;
    /// `ddl.rs` the batch DDL accumulator; `admission.rs` the commit-time
    /// admission probe; `estimate.rs` the entry-growth estimate (one-way: the
    /// admission and estimate sides import the map's vocabulary).
    constraint_keys: Mutex<ConstraintKeyIndex>,
    interner: Interner,
    catalog: Mutex<Catalog>,
    pub(crate) theater: Mutex<TheaterData>,
    /// Exact old definitions whose enforcement was absent from a legacy image/WAL.
    legacy_unenforced: Mutex<HashMap<String, ConstraintDef>>,
    stats: Mutex<QueryStats>,
    /// All lazily maintained index state: the label index, the equality and
    /// declared pair maps, the interned sentinels and the committed index
    /// memory charge — one bundle, [`Indexes`].
    indexes: Indexes,
    /// LABS-643: the committed epoch's memoized sampled `CONTAINS`
    /// estimates — the plan-stats read
    /// ([`Graph::pattern_contains_rows`](crate::Graph::pattern_contains_rows))
    /// answers without a TEXT index by sampling, and the executor's
    /// per-row start-selection estimate must not resample per row. See
    /// [`ContainsMemo`] for the epoch reset and the cap.
    contains_memo: Mutex<ContainsMemo>,
    pending_redo: Mutex<Vec<RedoOp>>,
    /// Source-scoped pull identity (ADR-0080).
    pull_identity: PullIdentityIndex,
    /// ADR-0687: the interned tokens the applied writes changed since the
    /// last publication drained the set, plus whether a schema op landed.
    /// The mutation seams report here while they hold the entity's version;
    /// `Shared`'s commit tail folds the drained set into the per-token
    /// last-changed table.
    changed_tokens: Mutex<AppliedTokenChanges>,
    /// Ids mutated since the last successful checkpoint (ADR-0022).
    dirty_nodes: Mutex<HashSet<NodeId>>,
    dirty_rels: Mutex<HashSet<RelId>>,

    /// In-flight snapshot pins (ADR-0038). Each slot is free / claiming / ts+1.
    pins: Box<[AtomicU64]>,
    pin_cursor: AtomicU64,
    /// Live graph + index logical bytes (ADR-0042).
    used_bytes: AtomicU64,
}

impl Default for Graph {
    fn default() -> Self {
        let interner = Interner::default();
        let indexes = Indexes::new(&interner);
        Self {
            namespace: Namespace::Neo4j,
            services: Arc::new(StoreServices::default()),
            attached_store: Default::default(),
            next_node_id: AtomicI64::new(0),
            next_rel_id: AtomicI64::new(0),
            published_ts: AtomicU64::new(0),
            write_ts: AtomicU64::new(0),
            in_write: AtomicBool::new(false),
            restoring: AtomicBool::new(true),
            record_redo: AtomicBool::new(true),
            nodes: IdVec::default(),
            rels: IdVec::default(),
            out_adj: IdVec::default(),
            in_adj: IdVec::default(),
            sealed_out: SealedArena::default(),
            sealed_in: SealedArena::default(),
            count_stats: Mutex::new(CountStats::default()),
            degree_histograms: Mutex::new(degree_stats::DegreeHistograms::default()),
            constraint_keys: Mutex::new(ConstraintKeyIndex::default()),
            interner,
            catalog: Mutex::new(Catalog::default()),
            theater: Mutex::new(TheaterData::default()),
            indexes,
            contains_memo: Mutex::new(ContainsMemo::default()),
            legacy_unenforced: Mutex::new(HashMap::new()),
            stats: Mutex::new(QueryStats::default()),
            pending_redo: Mutex::new(Vec::new()),
            pull_identity: PullIdentityIndex::default(),
            changed_tokens: Mutex::new(AppliedTokenChanges::default()),
            dirty_nodes: Mutex::new(HashSet::new()),

            dirty_rels: Mutex::new(HashSet::new()),
            pins: (0..PIN_SLOTS).map(|_| AtomicU64::new(PIN_FREE)).collect(),
            pin_cursor: AtomicU64::new(0),
            used_bytes: AtomicU64::new(0),
        }
    }
}

fn visible(xmin: u64, xmax: u64, ts: u64) -> bool {
    xmin != 0 && xmin <= ts && (xmax == 0 || xmax > ts)
}

fn checked_persisted_id(id: i64, what: &str) -> Result<i64> {
    relate_core::validate_persisted_id(id, what)?;
    Ok(id + 1)
}

fn requires_enforced_label(def: &ConstraintDef) -> bool {
    def.kind
        .parse::<relate_model::ConstraintType>()
        .is_ok_and(|kind| kind.is_enforced_label_kind())
}

fn matching_enforced_label(def: &ConstraintDef, c: &relate_model::Constraint) -> bool {
    c.label == def.label
        && c.properties == def.properties
        && def.kind.parse::<relate_model::ConstraintType>() == Ok(c.constraint_type)
        && c.property_type == def.property_type
        && c.constraint_type
            .enforced_label_site()
            .is_some_and(|site| site.is_relationship() == def.relationship)
        && c.enforced_label
            .as_deref()
            .is_some_and(|label| !label.is_empty())
}

/// ADR-0450's one legacy-resolution rule, one row at a time: a field-less
/// catalog row resolves its enforced label from its current-shape twin —
/// the derived record under its own name, whose label the caller holds.
/// A row that already carries the label keeps it, and a field-less row
/// resolves to the same identity its twin would have, so an upgraded
/// store keeps its old skip behavior.
/// [`crate::overlay::catalog::resolve_enforced_labels`] maps this rule
/// over a whole set (the twin's label looked up by name in the derived
/// index); the replay plan's held-row comparison applies it to the one
/// row under a derived name.
pub(crate) fn resolve_enforced_label(def: &mut ConstraintDef, twin_label: Option<&str>) {
    if def.enforced_label.is_none() {
        def.enforced_label = twin_label.map(str::to_string);
    }
}

/// Whether a derived record names an enforced label at all: its kind
/// requires one and the label is present and non-empty. The per-entry core
/// both checkpoint gates share (each keeps its own error mapping).
fn has_enforced_label(c: &relate_model::Constraint) -> bool {
    c.constraint_type.is_enforced_label_kind()
        && c.enforced_label
            .as_deref()
            .is_some_and(|label| !label.is_empty())
}

impl Graph {
    /// Whether the committed current graph type could carry property
    /// default values (CIP-262): the committed-theater half of the
    /// statement boundary's scratch-aware gate
    /// ([`ExecGraph::has_property_defaults`] answers over both
    /// vintages). A false positive only costs one overlay read.
    pub(crate) fn has_property_defaults(&self) -> bool {
        let theater = self.theater.lock().expect("theater lock poisoned");
        spec_has_property_defaults(&theater.current_graph_type)
    }

    /// Which fixed namespace of the store this graph is (ADR-0116 §1).
    pub fn namespace(&self) -> Namespace {
        self.namespace
    }

    /// Set the graph's namespace identity. Called by the store when it
    /// creates or swaps a namespace slot (ADR-0116 §10); not public API.
    #[doc(hidden)]
    pub fn set_namespace(&mut self, namespace: Namespace) {
        self.namespace = namespace;
    }

    pub fn commit_ts(&self) -> u64 {
        self.published_ts.load(Ordering::Acquire)
    }

    /// Whether a base write window is in flight (`begin_write`..
    /// `commit_write` / `apply_redo`): the maintained statistics are
    /// already bumped for it, but the commit is not published yet — a
    /// concurrent reader must not answer from them (the count-only
    /// short-circuit's exactness precondition, LABS-370 v1 follow-up).
    pub(crate) fn in_write_window(&self) -> bool {
        self.in_write.load(Ordering::Acquire)
    }

    pub fn set_commit_ts(&self, ts: u64) {
        self.published_ts.store(ts, Ordering::Release);
    }

    pub fn next_node_id(&self) -> NodeId {
        self.next_node_id.load(Ordering::Relaxed)
    }

    pub fn set_next_node_id(&self, id: NodeId) {
        self.next_node_id.store(id, Ordering::Relaxed);
    }

    pub fn next_rel_id(&self) -> RelId {
        self.next_rel_id.load(Ordering::Relaxed)
    }

    fn mark_node_dirty(&self, id: NodeId) {
        self.dirty_nodes.lock().unwrap().insert(id);
        // The attached store's publication feed (ADR-0665 versioning
        // step 1): the same choke point the checkpoint dirty set reads.
        // One acquire load when nothing is attached — the default path
        // never pays the second mutex for a set nobody drains.
        self.attached_store.mark_dirty(id);
    }

    fn mark_rel_dirty(&self, id: RelId) {
        self.dirty_rels.lock().unwrap().insert(id);
    }

    pub fn set_next_rel_id(&self, id: RelId) {
        self.next_rel_id.store(id, Ordering::Relaxed);
    }

    fn read_ts(&self) -> u64 {
        if self.in_write.load(Ordering::Acquire) {
            self.write_ts.load(Ordering::Acquire)
        } else {
            self.commit_ts()
        }
    }

    /// Begin a write statement: versions get xmin = commit_ts+1 until publish.
    /// Returns `Execution` if the next timestamp is the unsupported sentinel.
    pub fn begin_write(&self) -> Result<()> {
        let ts = self
            .commit_ts()
            .checked_add(1)
            .filter(|ts| *ts < u64::MAX)
            .ok_or_else(|| relate_core::Error::execution("write timestamp exhausted"))?;
        self.begin_write_at(ts)
    }

    /// Begin a write with an explicit txn id (ADR-0015 optimistic snapshot).
    /// Returns `Execution` if `write_ts` is the unsupported sentinel.
    pub fn begin_write_at(&self, write_ts: u64) -> Result<()> {
        if write_ts == u64::MAX {
            return Err(relate_core::Error::execution("write timestamp exhausted"));
        }
        self.in_write.store(true, Ordering::Release);
        self.write_ts.store(write_ts, Ordering::Release);
        self.pending_redo.lock().unwrap().clear();
        self.record_redo.store(true, Ordering::Release);
        self.reset_stats();
        Ok(())
    }

    fn alloc_node_id(&self) -> Result<NodeId> {
        alloc_exhaustible_id(&self.next_node_id, "node")
    }

    fn alloc_rel_id(&self) -> Result<RelId> {
        alloc_exhaustible_id(&self.next_rel_id, "relationship")
    }

    pub fn pending_commit_ts(&self) -> u64 {
        self.write_ts.load(Ordering::Acquire)
    }

    pub fn take_redo(&self) -> Vec<RedoOp> {
        std::mem::take(&mut *self.pending_redo.lock().unwrap())
    }

    /// The write window's one close: publish `commit_ts`, feed the
    /// attached store the rows this commit changed, then the shared
    /// window end — a graph that took a write is live, whatever shape its
    /// version chains hold.
    fn end_write(&self, commit_ts: u64) {
        // ADR-0665's feed ordering: the store's delta holds the
        // publication's rows BEFORE a reader can resolve ts = commit_ts.
        // Storing published_ts first opened a window where a reader
        // resolved the new ts and the store — whose delta was still
        // empty — answered point reads from its pre-commit columns
        // beside the compact records' committed rows: a torn row. The
        // feed's materialization reads the write window's own rows at
        // the passed ts, never published_ts, so this order is the one
        // both halves agree on; a reader at an older ts ignores the
        // newer delta version, exactly as before.
        self.publish_to_prop_store(commit_ts);
        self.set_commit_ts(commit_ts);
        self.close_window();
        self.close_restoring();
    }

    /// Drop the in-flight flag and the buffered redo — the half of the
    /// window's end a commit and an abort share. An abort leaves the restore
    /// phase alone: it never opened a load, and the phase is the load's
    /// guard, not the write's.
    fn close_window(&self) {
        self.in_write.store(false, Ordering::Release);
        self.pending_redo.lock().unwrap().clear();
    }

    /// Publish after WAL fsync.
    pub fn commit_write(&self) {
        self.end_write(self.write_ts.load(Ordering::Acquire));
    }

    pub fn abort_write(&self) {
        let ts = self.write_ts.load(Ordering::Acquire);
        self.nodes.retain(|_, vers| vers.abort(ts));
        self.rels.retain(|_, vers| vers.abort(ts));
        // An aborted write never reaches the attached store's feed.
        self.attached_store.clear();
        self.close_window();
        self.rebuild_adj();
        self.rebuild_indexes();
    }

    pub fn reset_stats(&self) {
        *self.stats.lock().unwrap() = QueryStats::default();
    }

    pub fn node_at(&self, id: NodeId, ts: u64) -> Option<Node> {
        self.nodes
            .get(&id)
            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_node(id, &self.interner)))
    }

    /// Label-only view of a node — no property-map materialization (ADR-0033).
    /// Callers that only need labels avoid `node_at`, which builds the full
    /// property map per node (the profile-hot `CompactProps::to_map` path).
    pub fn node_labels_at(&self, id: NodeId, ts: u64) -> Option<Vec<String>> {
        self.nodes.get(&id).and_then(|vers| {
            visible_version(&vers, ts).map(|v| v.live.label_strings(&self.interner))
        })
    }

    pub fn rel_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
        self.rels
            .get(&id)
            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_rel(id, &self.interner)))
    }

    /// Endpoints only — expand / BFS must not materialize property maps (ADR-0033).
    pub fn rel_ends_at(&self, id: RelId, ts: u64) -> Option<(NodeId, NodeId)> {
        self.rels
            .get(&id)
            .and_then(|vers| visible_version(&vers, ts).map(|v| (v.live.start, v.live.end)))
    }

    /// The rel's LIVE identity — its endpoints and type (round 3,
    /// LABS-370 F-1-2): the live version found by [`live_version`], not
    /// a ts-probe — the maintained-statistics paths run inside the write
    /// window, where a rel created earlier in the same batch is
    /// invisible at `commit_ts` (its xmin > commit_ts) and one deleted
    /// in the batch keeps a live-looking pre-delete version. The type
    /// rides along because a re-used rel id can come back as a different
    /// rel type: a live-incidence match must hold on all three axes,
    /// not the endpoints alone.
    fn rel_live_identity(&self, id: RelId) -> Option<(NodeId, NodeId, u32)> {
        self.rels.get(&id).and_then(|vers| {
            live_version(&vers).map(|v| (v.live.start, v.live.end, v.live.type_id))
        })
    }

    pub fn node_stub_at(&self, id: NodeId, ts: u64) -> Option<Node> {
        self.nodes
            .get(&id)
            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id, &self.interner)))
    }

    pub fn rel_stub_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
        self.rels
            .get(&id)
            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id)))
    }

    pub fn node_prop_at(&self, id: NodeId, ts: u64, key: &str) -> Option<Value> {
        self.interner
            .get_id(key)
            .and_then(|kid| self.node_prop_id_at(id, ts, kid))
    }

    pub fn rel_prop_at(&self, id: RelId, ts: u64, key: &str) -> Option<Value> {
        self.rels.get(&id).and_then(|vers| {
            visible_version(&vers, ts).and_then(|v| v.live.payload.get(&self.interner, key))
        })
    }

    pub fn node_prop_keys_at(&self, id: NodeId, ts: u64) -> Vec<String> {
        self.nodes
            .get(&id)
            .and_then(|vers| {
                visible_version(&vers, ts).map(|v| v.live.props.keys_as_strings(&self.interner))
            })
            .unwrap_or_default()
    }

    pub fn rel_prop_keys_at(&self, id: RelId, ts: u64) -> Vec<String> {
        self.rels
            .get(&id)
            .and_then(|vers| {
                visible_version(&vers, ts).map(|v| v.live.payload.keys(&self.interner))
            })
            .unwrap_or_default()
    }

    pub(crate) fn rel_visible_at(&self, id: RelId, ts: u64) -> bool {
        self.rels
            .get(&id)
            .is_some_and(|vers| visible_version(&vers, ts).is_some())
    }

    pub fn node(&self, id: NodeId) -> Option<Node> {
        self.node_at(id, self.read_ts())
    }

    pub fn rel(&self, id: RelId) -> Option<Relationship> {
        self.rel_at(id, self.read_ts())
    }

    /// Account of the relationship version visible at the read timestamp.
    /// Uses the stored `Triple` / `Other` form, not the materialized map.
    fn visible_rel_account(&self, id: RelId) -> u64 {
        let ts = self.read_ts();
        self.rels
            .get(&id)
            .and_then(|vers| {
                visible_version(&vers, ts).map(|v| crate::memory::live_rel_account_live(v.live))
            })
            .unwrap_or(0)
    }

    fn rel_form(&self, id: RelId) -> Option<crate::store::PayloadForm> {
        let ts = self.read_ts();
        self.rels.get(&id).and_then(|vers| {
            visible_version(&vers, ts).map(|v| v.live.payload.form(&self.interner))
        })
    }

    pub fn node_exists(&self, id: NodeId) -> bool {
        self.node_visible_at(id, self.read_ts())
    }

    pub fn rel_exists(&self, id: RelId) -> bool {
        self.rel_visible_at(id, self.read_ts())
    }

    pub fn live_node_count(&self) -> usize {
        self.all_node_ids().len()
    }

    /// True inside a write that records redo; replay (`apply_redo_inner`) does not.
    fn recording(&self) -> bool {
        self.in_write.load(Ordering::Acquire) && self.record_redo.load(Ordering::Acquire)
    }

    fn push_redo(&self, op: RedoOp) {
        if self.recording() {
            self.pending_redo.lock().unwrap().push(op);
        }
    }

    fn bump_stats(&self, f: impl FnOnce(&mut QueryStats)) {
        f(&mut self.stats.lock().unwrap());
    }

    fn xmin_for_install(&self) -> u64 {
        if self.in_write.load(Ordering::Acquire) {
            self.write_ts.load(Ordering::Acquire)
        } else {
            let ts = self.commit_ts();
            if ts == 0 {
                self.set_commit_ts(1);
                1
            } else {
                ts
            }
        }
    }
}

/// Whether a graph-type spec could carry property default values
/// (CIP-262): any element type's property declares one, or any implied
/// label identifies another node element type (whose chain may inherit
/// one down). The one predicate both vintages of the statement
/// boundary's gate consult -- the committed theater
/// ([`Graph::has_property_defaults`]) and the scratch redo slice
/// ([`ExecGraph::has_property_defaults`]) -- so the two can never
/// answer the same yes/no differently.
pub(crate) fn spec_has_property_defaults(spec: &crate::graph_type::GraphTypeSpec) -> bool {
    let identifying: std::collections::BTreeSet<&str> = spec
        .node_types
        .iter()
        .map(|n| n.identifying_label.as_str())
        .collect();
    spec.node_types.iter().any(|n| {
        n.properties.iter().any(|p| p.default_value.is_some())
            || n.implied_labels
                .iter()
                .any(|l| identifying.contains(l.as_str()))
    }) || spec
        .edge_types
        .iter()
        .any(|e| e.properties.iter().any(|p| p.default_value.is_some()))
}

impl Graph {
    /// The one label-selection policy of the degree and count statistics families:
    /// `None` selects every label, `Some(wanted)` exactly that one.
    pub(crate) fn selects(wanted: Option<u32>, label: u32) -> bool {
        wanted.is_none_or(|wanted| wanted == label)
    }

    /// The one type-selection policy of the degree and count statistics families:
    /// `None` selects every type, `Some(wanted)` the listed ids.
    pub(crate) fn selects_type(wanted: Option<&[u32]>, type_id: u32) -> bool {
        wanted.is_none_or(|wanted| wanted.contains(&type_id))
    }

    pub(crate) fn node_visible_at(&self, id: NodeId, ts: u64) -> bool {
        self.nodes
            .get(&id)
            .is_some_and(|vers| visible_version(&vers, ts).is_some())
    }
}

#[cfg(test)]
mod tests;