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 overlay: Arc<ArcSwap<SchemaDelta>>,
73 /// Serializes overlay updates *within a single fork* so two
74 /// concurrent `add_label_to_overlay` calls don't clobber each
75 /// other's persisted state. Held across the registry PUT and the
76 /// `ArcSwap::store`. Cross-fork updates remain parallel.
77 overlay_lock: Arc<AsyncMutex<()>>,
78 registry: Arc<ForkRegistryHandle>,
79 /// Branches created after fork construction, e.g. by
80 /// [`crate::backend::BranchedBackend`] when the fork's writer
81 /// flushes to a label whose dataset wasn't branched at fork-point.
82 /// Consulted alongside `fork_info.datasets` by [`Self::branch_for`]
83 /// so reads on the same session see writes through the same
84 /// branch that produced them. Persisted out-of-band via
85 /// [`ForkRegistryHandle::register_dataset_branch`] so a restart
86 /// recovers the same mapping.
87 dynamic_branches: Arc<DashMap<String, String>>,
88 /// Phase 5a: per-table row count contributed by this fork's
89 /// writes. Bumped by `BranchedBackend` after each successful
90 /// flush. Read by `IndexRebuildManager` to decide whether to
91 /// schedule a fork-local index build for the table. In-memory
92 /// only — a process restart resets the counter, so the trigger
93 /// re-fires on the next flush. The on-disk row count is the
94 /// ground truth; this counter is only a flush-time accumulator.
95 fragment_counts: Arc<DashMap<String, u64>>,
96 /// Phase 5a: registry of completed fork-local index builds.
97 /// Keyed on `(label, column)`; value is the index kind that was
98 /// built. Read by the planner's `fork_index_exists` check to
99 /// decide whether to emit `FusedIndexScan`. Written by the
100 /// `IndexRebuildManager` after a fork-local build completes.
101 /// In-memory only — a restart re-detects existing fork-local
102 /// indexes by listing the fork's branch directory once at
103 /// `Uni::open` time (Phase 5a uses lazy first-touch detection;
104 /// see `repopulate_indexes_from_disk`).
105 fork_local_indexes: Arc<DashMap<(String, String), ForkLocalIndexKind>>,
106 /// RAII guard. Lifetime-tied to this `ForkScope`. Cloning the
107 /// containing `Arc<ForkScope>` does *not* increment the holder
108 /// count — only the constructor does, via `register_holder`.
109 _holder: ForkHolderGuard,
110}
111
112impl std::fmt::Debug for ForkScope {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.debug_struct("ForkScope")
115 .field("fork_id", &self.fork_id)
116 .field("fork_name", &self.fork_info.name)
117 .finish_non_exhaustive()
118 }
119}
120
121impl ForkScope {
122 /// Build a new fork scope, registering a holder on `registry`.
123 ///
124 /// `fork_info` must already be in `Active` status; callers should
125 /// have walked the registry's open-or-create flow before invoking.
126 /// `overlay` is the schema delta loaded from
127 /// `catalog/fork_schemas/{fork_id}.json`.
128 #[must_use]
129 pub fn new(
130 fork_info: Arc<ForkInfo>,
131 overlay: SchemaDelta,
132 registry: Arc<ForkRegistryHandle>,
133 ) -> Self {
134 let holder = registry.register_holder(fork_info.id);
135 Self {
136 fork_id: fork_info.id,
137 fork_info,
138 overlay: Arc::new(ArcSwap::from_pointee(overlay)),
139 overlay_lock: Arc::new(AsyncMutex::new(())),
140 registry,
141 dynamic_branches: Arc::new(DashMap::new()),
142 fragment_counts: Arc::new(DashMap::new()),
143 fork_local_indexes: Arc::new(DashMap::new()),
144 _holder: holder,
145 }
146 }
147
148 /// Phase 5a: record `rows_added` rows newly written through this
149 /// fork to `table_name`. Idempotent under repeated calls — the
150 /// counter is monotonically increasing within a process lifetime.
151 pub fn record_fork_fragment(&self, table_name: &str, rows_added: u64) {
152 if rows_added == 0 {
153 return;
154 }
155 self.fragment_counts
156 .entry(table_name.to_string())
157 .and_modify(|c| *c += rows_added)
158 .or_insert(rows_added);
159 }
160
161 /// Phase 5a: current accumulated row count for `table_name` on
162 /// this fork. Returns 0 if the fork has never written to it.
163 #[must_use]
164 pub fn fragment_count(&self, table_name: &str) -> u64 {
165 self.fragment_counts
166 .get(table_name)
167 .map(|r| *r.value())
168 .unwrap_or(0)
169 }
170
171 /// Phase 5a: snapshot of every (table, count) pair recorded on
172 /// this fork. Used by `IndexRebuildManager` to enumerate build
173 /// candidates each polling tick.
174 #[must_use]
175 pub fn all_fragment_counts(&self) -> Vec<(String, u64)> {
176 self.fragment_counts
177 .iter()
178 .map(|r| (r.key().clone(), *r.value()))
179 .collect()
180 }
181
182 /// Phase 5a: register a completed fork-local index build.
183 /// Called by `IndexRebuildManager` after the build lands on
184 /// the fork's branch.
185 pub fn register_fork_local_index(&self, label: &str, column: &str, kind: ForkLocalIndexKind) {
186 self.fork_local_indexes
187 .insert((label.to_string(), column.to_string()), kind);
188 }
189
190 /// Phase 5a: lookup the fork-local index kind for a `(label,
191 /// column)` pair, if one has been built. Returns `None` when
192 /// the planner should fall back to the inherited primary index
193 /// (or to a plain scan).
194 #[must_use]
195 pub fn fork_local_index(&self, label: &str, column: &str) -> Option<ForkLocalIndexKind> {
196 self.fork_local_indexes
197 .get(&(label.to_string(), column.to_string()))
198 .map(|r| *r.value())
199 }
200
201 /// Phase 5a: snapshot of every registered fork-local index.
202 #[must_use]
203 pub fn all_fork_local_indexes(&self) -> Vec<((String, String), ForkLocalIndexKind)> {
204 self.fork_local_indexes
205 .iter()
206 .map(|r| (r.key().clone(), *r.value()))
207 .collect()
208 }
209
210 /// Stable fork identifier.
211 #[must_use]
212 pub fn fork_id(&self) -> ForkId {
213 self.fork_id
214 }
215
216 /// Fork registry record (cheap `Arc::clone`).
217 #[must_use]
218 pub fn fork_info(&self) -> Arc<ForkInfo> {
219 self.fork_info.clone()
220 }
221
222 /// Parent fork id (Phase 3). `None` ⇒ parent is primary.
223 ///
224 /// Used by `UniInner::at_fork` to walk the ancestor chain for
225 /// overlay composition, and by `BranchedBackend` to route
226 /// on-the-fly dataset creation through the parent's branch.
227 #[must_use]
228 pub fn parent_fork_id(&self) -> Option<ForkId> {
229 self.fork_info.parent_fork_id
230 }
231
232 /// Schema delta to merge on top of primary's schema. Returns a
233 /// snapshot of the current overlay; subsequent
234 /// [`Self::add_label_to_overlay`] calls will not affect the
235 /// returned `Arc`.
236 #[must_use]
237 pub fn overlay(&self) -> Arc<SchemaDelta> {
238 self.overlay.load_full()
239 }
240
241 /// Branch name for a given Lance dataset, if this fork has one.
242 ///
243 /// Used by `StorageManager` dataset factories to route reads.
244 /// Consults both the immutable fork-point datasets map (set by
245 /// `finish_create`) and the dynamic-branches map (populated by
246 /// [`Self::register_dynamic_branch`] when a flush hits a dataset
247 /// that wasn't branched at fork-point). Returns `None` only if no
248 /// branch exists on either side — the BranchedBackend then either
249 /// creates one on the fly or surfaces an error.
250 #[must_use]
251 pub fn branch_for(&self, dataset_name: &str) -> Option<String> {
252 if let Some(b) = self.fork_info.datasets.get(dataset_name) {
253 return Some(b.clone());
254 }
255 self.dynamic_branches
256 .get(dataset_name)
257 .map(|r| r.value().clone())
258 }
259
260 /// Record a branch created after fork-point (e.g. for a dataset
261 /// that didn't exist on primary at fork creation, or for
262 /// compaction-only adjacency tables).
263 ///
264 /// In-memory only; the caller is responsible for persisting via
265 /// [`ForkRegistryHandle::register_dataset_branch`] so a restart
266 /// recovers the same mapping. Idempotent — re-registering an
267 /// existing entry is a no-op.
268 pub fn register_dynamic_branch(&self, dataset: String, branch: String) {
269 self.dynamic_branches.insert(dataset, branch);
270 }
271
272 /// Append a label to the fork-local schema overlay and persist
273 /// the new overlay to disk.
274 ///
275 /// Idempotent: if a label with the same name is already in the
276 /// overlay (or in primary's schema, accessible to the caller via
277 /// the merged `SchemaManager` not consulted here), the append
278 /// still records this entry — callers should check for duplicates
279 /// before invoking. The persistence-then-swap order means a
280 /// failed PUT leaves the in-memory `ArcSwap` untouched and the
281 /// returned error surfaces to the caller.
282 ///
283 /// Concurrency: serialized within a single fork by `overlay_lock`
284 /// so two concurrent appends don't clobber each other's
285 /// persisted state.
286 pub async fn add_label_to_overlay(&self, name: String, meta: LabelMeta) -> anyhow::Result<()> {
287 let _guard = self.overlay_lock.lock().await;
288 let mut next = (**self.overlay.load()).clone();
289 next.added_labels.push((name, meta));
290 self.registry
291 .update_schema_overlay(&self.fork_id, &next)
292 .await
293 .with_context(|| format!("persist schema overlay for fork {}", self.fork_id))?;
294 self.overlay.store(Arc::new(next));
295 Ok(())
296 }
297
298 /// Append an edge type to the fork-local schema overlay and
299 /// persist. Same semantics as [`Self::add_label_to_overlay`].
300 pub async fn add_edge_type_to_overlay(
301 &self,
302 name: String,
303 meta: EdgeTypeMeta,
304 ) -> anyhow::Result<()> {
305 let _guard = self.overlay_lock.lock().await;
306 let mut next = (**self.overlay.load()).clone();
307 next.added_edge_types.push((name, meta));
308 self.registry
309 .update_schema_overlay(&self.fork_id, &next)
310 .await
311 .with_context(|| format!("persist schema overlay for fork {}", self.fork_id))?;
312 self.overlay.store(Arc::new(next));
313 Ok(())
314 }
315
316 /// Registry handle (used by admin paths to e.g. compute holder counts).
317 #[must_use]
318 pub fn registry(&self) -> Arc<ForkRegistryHandle> {
319 self.registry.clone()
320 }
321}