Skip to main content

uni_store/fork/
scope.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2024-2026 Dragonscale Team
3
4//! `ForkScope` — read-only state shared by every component of a forked
5//! session.
6//!
7//! A `ForkScope` is owned by a forked `Session`'s `UniInner` and carries
8//! everything `StorageManager` and `SchemaManager` need to resolve fork-
9//! aware reads:
10//!
11//! - `fork_info` — registry record, including the dataset → branch map
12//!   used to route Lance reads through the fork's branches.
13//! - `overlay` — `SchemaDelta` merged on top of primary's schema by
14//!   `UniInner::at_fork` at construction time.
15//! - `registry` — back-reference for liveness queries; holders are
16//!   tracked here so drop refuses while sessions are alive.
17//! - `_holder` — RAII guard that decrements the holder count when the
18//!   scope is dropped.
19//!
20//! `fork_info` is wrapped in plain `Arc` (no fork-side mutation today
21//! — datasets only grow through `register_dynamic_branch` which goes
22//! through the registry, not through `fork_info`). `overlay` is wrapped
23//! in `ArcSwap` so fork-local strict-schema additions can be applied
24//! atomically without rebuilding the scope.
25
26// Rust guideline compliant
27
28use std::sync::Arc;
29
30use anyhow::Context;
31use arc_swap::ArcSwap;
32use dashmap::DashMap;
33use tokio::sync::Mutex as AsyncMutex;
34use uni_common::core::fork::{ForkId, ForkInfo, SchemaDelta};
35use uni_common::core::schema::{EdgeTypeMeta, LabelMeta};
36
37use super::registry::{ForkHolderGuard, ForkRegistryHandle};
38
39/// Phase 5a: tag for the fork-local index registry on `ForkScope`.
40/// Phase 5b extends with `Vector` and `FullText` for lossy fusion.
41///
42/// `#[non_exhaustive]` so additional kinds (e.g. inverted-set,
43/// JSON path) can land additively without breaking match sites.
44#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
45#[non_exhaustive]
46pub enum ForkLocalIndexKind {
47    /// Scalar BTree on a property — union fusion (Phase 5a-impl).
48    ScalarBtree,
49    /// Sorted on a property (range / ORDER BY) — k-way merge fusion (Phase 5a-impl).
50    Sorted,
51    /// VID/UID lookup index — fork-first fusion (Phase 5a-impl).
52    VidUid,
53    /// Vector (IVF/HNSW) index — top-k merge + rerank fusion (Phase 5b).
54    Vector,
55    /// Lance native FTS / inverted index — RRF fusion (Phase 5b).
56    FullText,
57}
58
59/// Read-only scope identifying a forked session.
60///
61/// Constructed by `Session::fork(name).build()` (Day 7) via
62/// [`ForkScope::new`]. Once built, both `fork_info` and `overlay` are
63/// immutable for the scope's lifetime — Phase 1 forks are read-only.
64pub struct ForkScope {
65    fork_id: ForkId,
66    fork_info: Arc<ForkInfo>,
67    /// Schema additions on top of primary's schema. Mutable so that
68    /// `Session::fork_schema()` can introduce fork-local labels and
69    /// edge types without touching primary's `catalog/schema.json`.
70    /// `ArcSwap` makes reads cheap and atomic; the `overlay_lock`
71    /// below serializes the read-modify-write on the persistence side.
72    ///
73    /// # Invariant: fork-origin numeric ids are fork-local (L7)
74    ///
75    /// The overlay is frozen at fork time, so a label/edge-type id minted
76    /// inside a fork (via `max(existing)+1`) does not observe primary's
77    /// later additions and **can collide** with a primary id allocated
78    /// after the fork point. This is benign because nothing trusts a
79    /// fork-origin id across the fork↔primary boundary: promote
80    /// (`uni_fork::diff`) re-creates by NAME, primary re-allocates its own
81    /// id, and storage keys rows by label name. A fork-origin numeric id
82    /// MUST NOT be trusted outside the fork's own view.
83    overlay: Arc<ArcSwap<SchemaDelta>>,
84    /// Serializes overlay updates *within a single fork* so two
85    /// concurrent `add_label_to_overlay` calls don't clobber each
86    /// other's persisted state. Held across the registry PUT and the
87    /// `ArcSwap::store`. Cross-fork updates remain parallel.
88    overlay_lock: Arc<AsyncMutex<()>>,
89    registry: Arc<ForkRegistryHandle>,
90    /// Branches created after fork construction, e.g. by
91    /// [`crate::backend::BranchedBackend`] when the fork's writer
92    /// flushes to a label whose dataset wasn't branched at fork-point.
93    /// Consulted alongside `fork_info.datasets` by [`Self::branch_for`]
94    /// so reads on the same session see writes through the same
95    /// branch that produced them. Persisted out-of-band via
96    /// [`ForkRegistryHandle::register_dataset_branch`] so a restart
97    /// recovers the same mapping.
98    dynamic_branches: Arc<DashMap<String, String>>,
99    /// Phase 5a: per-table row count contributed by this fork's
100    /// writes. Bumped by `BranchedBackend` after each successful
101    /// flush. Read by `IndexRebuildManager` to decide whether to
102    /// schedule a fork-local index build for the table. In-memory
103    /// only — a process restart resets the counter, so the trigger
104    /// re-fires on the next flush. The on-disk row count is the
105    /// ground truth; this counter is only a flush-time accumulator.
106    fragment_counts: Arc<DashMap<String, u64>>,
107    /// Phase 5a: registry of completed fork-local index builds.
108    /// Keyed on `(label, column)`; value is the index kind that was
109    /// built. Read by the planner's `fork_index_exists` check to
110    /// decide whether to emit `FusedIndexScan`. Written by the
111    /// `IndexRebuildManager` after a fork-local build completes.
112    /// In-memory only — a restart re-detects existing fork-local
113    /// indexes by listing the fork's branch directory once at
114    /// `Uni::open` time (Phase 5a uses lazy first-touch detection;
115    /// see `repopulate_indexes_from_disk`).
116    fork_local_indexes: Arc<DashMap<(String, String), ForkLocalIndexKind>>,
117    /// RAII guard. Lifetime-tied to this `ForkScope`. Cloning the
118    /// containing `Arc<ForkScope>` does *not* increment the holder
119    /// count — only the constructor does, via `register_holder`.
120    _holder: ForkHolderGuard,
121}
122
123impl std::fmt::Debug for ForkScope {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        f.debug_struct("ForkScope")
126            .field("fork_id", &self.fork_id)
127            .field("fork_name", &self.fork_info.name)
128            .finish_non_exhaustive()
129    }
130}
131
132impl ForkScope {
133    /// Build a new fork scope, registering a holder on `registry`.
134    ///
135    /// `fork_info` must already be in `Active` status; callers should
136    /// have walked the registry's open-or-create flow before invoking.
137    /// `overlay` is the schema delta loaded from
138    /// `catalog/fork_schemas/{fork_id}.json`.
139    #[must_use]
140    pub fn new(
141        fork_info: Arc<ForkInfo>,
142        overlay: SchemaDelta,
143        registry: Arc<ForkRegistryHandle>,
144    ) -> Self {
145        let holder = registry.register_holder(fork_info.id);
146        Self {
147            fork_id: fork_info.id,
148            fork_info,
149            overlay: Arc::new(ArcSwap::from_pointee(overlay)),
150            overlay_lock: Arc::new(AsyncMutex::new(())),
151            registry,
152            dynamic_branches: Arc::new(DashMap::new()),
153            fragment_counts: Arc::new(DashMap::new()),
154            fork_local_indexes: Arc::new(DashMap::new()),
155            _holder: holder,
156        }
157    }
158
159    /// Phase 5a: record `rows_added` rows newly written through this
160    /// fork to `table_name`. Idempotent under repeated calls — the
161    /// counter is monotonically increasing within a process lifetime.
162    pub fn record_fork_fragment(&self, table_name: &str, rows_added: u64) {
163        if rows_added == 0 {
164            return;
165        }
166        self.fragment_counts
167            .entry(table_name.to_string())
168            .and_modify(|c| *c += rows_added)
169            .or_insert(rows_added);
170    }
171
172    /// Phase 5a: current accumulated row count for `table_name` on
173    /// this fork. Returns 0 if the fork has never written to it.
174    #[must_use]
175    pub fn fragment_count(&self, table_name: &str) -> u64 {
176        self.fragment_counts
177            .get(table_name)
178            .map(|r| *r.value())
179            .unwrap_or(0)
180    }
181
182    /// Phase 5a: snapshot of every (table, count) pair recorded on
183    /// this fork. Used by `IndexRebuildManager` to enumerate build
184    /// candidates each polling tick.
185    #[must_use]
186    pub fn all_fragment_counts(&self) -> Vec<(String, u64)> {
187        self.fragment_counts
188            .iter()
189            .map(|r| (r.key().clone(), *r.value()))
190            .collect()
191    }
192
193    /// Phase 5a: register a completed fork-local index build.
194    /// Called by `IndexRebuildManager` after the build lands on
195    /// the fork's branch.
196    pub fn register_fork_local_index(&self, label: &str, column: &str, kind: ForkLocalIndexKind) {
197        self.fork_local_indexes
198            .insert((label.to_string(), column.to_string()), kind);
199    }
200
201    /// Phase 5a: lookup the fork-local index kind for a `(label,
202    /// column)` pair, if one has been built. Returns `None` when
203    /// the planner should fall back to the inherited primary index
204    /// (or to a plain scan).
205    #[must_use]
206    pub fn fork_local_index(&self, label: &str, column: &str) -> Option<ForkLocalIndexKind> {
207        self.fork_local_indexes
208            .get(&(label.to_string(), column.to_string()))
209            .map(|r| *r.value())
210    }
211
212    /// Phase 5a: snapshot of every registered fork-local index.
213    #[must_use]
214    pub fn all_fork_local_indexes(&self) -> Vec<((String, String), ForkLocalIndexKind)> {
215        self.fork_local_indexes
216            .iter()
217            .map(|r| (r.key().clone(), *r.value()))
218            .collect()
219    }
220
221    /// Stable fork identifier.
222    #[must_use]
223    pub fn fork_id(&self) -> ForkId {
224        self.fork_id
225    }
226
227    /// Fork registry record (cheap `Arc::clone`).
228    #[must_use]
229    pub fn fork_info(&self) -> Arc<ForkInfo> {
230        self.fork_info.clone()
231    }
232
233    /// Parent fork id (Phase 3). `None` ⇒ parent is primary.
234    ///
235    /// Used by `UniInner::at_fork` to walk the ancestor chain for
236    /// overlay composition, and by `BranchedBackend` to route
237    /// on-the-fly dataset creation through the parent's branch.
238    #[must_use]
239    pub fn parent_fork_id(&self) -> Option<ForkId> {
240        self.fork_info.parent_fork_id
241    }
242
243    /// Schema delta to merge on top of primary's schema. Returns a
244    /// snapshot of the current overlay; subsequent
245    /// [`Self::add_label_to_overlay`] calls will not affect the
246    /// returned `Arc`.
247    #[must_use]
248    pub fn overlay(&self) -> Arc<SchemaDelta> {
249        self.overlay.load_full()
250    }
251
252    /// Branch name for a given Lance dataset, if this fork has one.
253    ///
254    /// Used by `StorageManager` dataset factories to route reads.
255    /// Consults both the immutable fork-point datasets map (set by
256    /// `finish_create`) and the dynamic-branches map (populated by
257    /// [`Self::register_dynamic_branch`] when a flush hits a dataset
258    /// that wasn't branched at fork-point). Returns `None` only if no
259    /// branch exists on either side — the BranchedBackend then either
260    /// creates one on the fly or surfaces an error.
261    #[must_use]
262    pub fn branch_for(&self, dataset_name: &str) -> Option<String> {
263        if let Some(b) = self.fork_info.datasets.get(dataset_name) {
264            return Some(b.clone());
265        }
266        self.dynamic_branches
267            .get(dataset_name)
268            .map(|r| r.value().clone())
269    }
270
271    /// Record a branch created after fork-point (e.g. for a dataset
272    /// that didn't exist on primary at fork creation, or for
273    /// compaction-only adjacency tables).
274    ///
275    /// In-memory only; the caller is responsible for persisting via
276    /// [`ForkRegistryHandle::register_dataset_branch`] so a restart
277    /// recovers the same mapping. Idempotent — re-registering an
278    /// existing entry is a no-op.
279    pub fn register_dynamic_branch(&self, dataset: String, branch: String) {
280        self.dynamic_branches.insert(dataset, branch);
281    }
282
283    /// Append a label to the fork-local schema overlay and persist
284    /// the new overlay to disk.
285    ///
286    /// Idempotent: if a label with the same name is already in the
287    /// overlay (or in primary's schema, accessible to the caller via
288    /// the merged `SchemaManager` not consulted here), the append
289    /// still records this entry — callers should check for duplicates
290    /// before invoking. The persistence-then-swap order means a
291    /// failed PUT leaves the in-memory `ArcSwap` untouched and the
292    /// returned error surfaces to the caller.
293    ///
294    /// Concurrency: serialized within a single fork by `overlay_lock`
295    /// so two concurrent appends don't clobber each other's
296    /// persisted state.
297    pub async fn add_label_to_overlay(&self, name: String, meta: LabelMeta) -> anyhow::Result<()> {
298        let _guard = self.overlay_lock.lock().await;
299        let mut next = (**self.overlay.load()).clone();
300        next.added_labels.push((name, meta));
301        self.registry
302            .update_schema_overlay(&self.fork_id, &next)
303            .await
304            .with_context(|| format!("persist schema overlay for fork {}", self.fork_id))?;
305        self.overlay.store(Arc::new(next));
306        Ok(())
307    }
308
309    /// Append an edge type to the fork-local schema overlay and
310    /// persist. Same semantics as [`Self::add_label_to_overlay`].
311    pub async fn add_edge_type_to_overlay(
312        &self,
313        name: String,
314        meta: EdgeTypeMeta,
315    ) -> anyhow::Result<()> {
316        let _guard = self.overlay_lock.lock().await;
317        let mut next = (**self.overlay.load()).clone();
318        next.added_edge_types.push((name, meta));
319        self.registry
320            .update_schema_overlay(&self.fork_id, &next)
321            .await
322            .with_context(|| format!("persist schema overlay for fork {}", self.fork_id))?;
323        self.overlay.store(Arc::new(next));
324        Ok(())
325    }
326
327    /// Registry handle (used by admin paths to e.g. compute holder counts).
328    #[must_use]
329    pub fn registry(&self) -> Arc<ForkRegistryHandle> {
330        self.registry.clone()
331    }
332}