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
//! Active graph engine: snapshot backing, dual topology, overlays, and config.
use alloc::{boxed::Box, vec::Vec};
use core::num::NonZeroUsize;
use yoke::Yoke;
use crate::{
artifact::PostgresMetadata,
build::EdgeRow,
builder::EngineBuilder,
catalog::Catalog,
config::Config,
error::{ConfigError, PostgresGraphError, QueryError},
overlay::OverlayState,
rebuild::SnapshotRebuild,
search::SearchPredicate,
sync::{SyncHealth, SyncRow},
topology::{GraphTopology, UniqueAdjacency},
traverse::{TraversalDirection, TraverseLimits, traverse_core_collect, traverse_core_count},
};
/// Runtime status returned by admin/discovery surfaces.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EngineStatus {
/// Node count recorded in Postgres metadata.
pub node_count: u32,
/// Edge count recorded in Postgres metadata.
pub edge_count: u32,
/// Whether the artifact is marked read-only.
pub read_only: bool,
/// Number of overlay edge insertions not yet compacted.
pub overlay_edge_count: usize,
/// Number of tombstoned base edges.
pub tombstoned_edges: usize,
}
/// Yoke cart owning snapshot bytes and parsed metadata.
#[expect(
clippy::redundant_pub_crate,
reason = "shared with private builder module"
)]
pub(crate) struct EngineCart {
/// Owned OXGTOPO bytes backing both topology views.
pub backing: Vec<u8>,
/// Parsed Postgres metadata section.
pub metadata: PostgresMetadata,
}
/// Topology views borrowing the cart backing (lifetime-erased in [`Engine`]).
#[derive(yoke::Yokeable)]
#[yoke(prove_covariant)]
#[expect(
clippy::redundant_pub_crate,
reason = "shared with private builder module"
)]
pub(crate) struct EngineState<'a> {
/// Forward CSR and inbound CSC opened once at build.
pub topology: GraphTopology<'a>,
}
/// Active [`OxGraph`] backend state loaded from OXGTOPO bytes.
pub struct Engine {
/// Yoke-attached topology views and owned snapshot cart.
inner: Yoke<EngineState<'static>, Box<EngineCart>>,
/// Overlay buffers applied on top of the base artifact.
overlay: OverlayState,
/// Operational config mirrored from extension GUCs.
config: Config,
/// Reused BFS scratch (dense epoch marks and frontier queue).
traverse_scratch: crate::traverse::TraverseScratch,
/// Node-unique adjacency (empty until the first unique-profile traverse builds it).
unique_adjacency: UniqueAdjacency,
/// Whether [`Self::unique_adjacency`] has been populated from topology.
unique_cache_built: bool,
}
impl Engine {
/// Constructs an engine from validated yoke state and runtime buffers.
pub(crate) fn from_parts(
inner: Yoke<EngineState<'static>, Box<EngineCart>>,
overlay: OverlayState,
config: Config,
traverse_scratch: crate::traverse::TraverseScratch,
) -> Self {
Self {
inner,
overlay,
config,
traverse_scratch,
unique_adjacency: UniqueAdjacency::default(),
unique_cache_built: false,
}
}
/// Returns the canonical node count from artifact metadata.
#[must_use]
pub fn node_count(&self) -> u32 {
self.inner.backing_cart().metadata.node_count.get()
}
/// Disjoint topology views, unique cache, overlay, and scratch for one BFS query.
///
/// When `needs_unique` is set the node-unique adjacency is built lazily on
/// first use (`O(n + m log d)`) and cached for the snapshot's lifetime; engine
/// open stays `O(n + m)` for topology attach only. The parallel profile never
/// touches the unique cache.
///
/// # Performance
///
/// This method is `O(1)` once the cache is built, `O(n + m log d)` on the
/// first unique-profile query after a snapshot replacement.
pub(crate) fn traverse_workspace_mut(
&mut self,
needs_unique: bool,
) -> (
&GraphTopology<'_>,
&UniqueAdjacency,
&OverlayState,
&mut crate::traverse::TraverseScratch,
) {
if needs_unique && !self.unique_cache_built {
let forward = self.inner.get().topology.forward;
let inbound = self.inner.get().topology.inbound;
self.unique_adjacency = UniqueAdjacency::from_topology(&forward, &inbound);
self.unique_cache_built = true;
}
(
&self.inner.get().topology,
&self.unique_adjacency,
&self.overlay,
&mut self.traverse_scratch,
)
}
/// Loads an engine via [`EngineBuilder`].
///
/// # Errors
///
/// Returns [`PostgresGraphError`] when snapshot validation or topology attach fails.
pub fn from_snapshot_bytes(bytes: &[u8]) -> Result<Self, PostgresGraphError> {
EngineBuilder::new().snapshot_owned(bytes.to_vec()).build()
}
/// Returns operational status for admin surfaces.
#[must_use]
pub fn stats(&self) -> EngineStatus {
let metadata = &self.inner.backing_cart().metadata;
EngineStatus {
node_count: metadata.node_count.get(),
edge_count: metadata.edge_count.get(),
read_only: metadata.is_read_only(),
overlay_edge_count: self.overlay.overlay_edge_count(),
tombstoned_edges: self.overlay.tombstoned_edge_count(),
}
}
/// Returns the active configuration mirror.
#[must_use]
pub const fn config(&self) -> &Config {
&self.config
}
/// Updates configuration after validation.
///
/// # Errors
///
/// Returns [`PostgresGraphError::Config`] when limits or freshness settings are invalid.
pub fn set_config(&mut self, config: Config) -> Result<(), PostgresGraphError> {
config.validate()?;
self.config = config;
Ok(())
}
/// Borrows overlay state for read-only query visibility checks.
#[must_use]
pub const fn overlay(&self) -> &OverlayState {
&self.overlay
}
/// Borrows the overlay buffer for sync replay.
pub const fn overlay_mut(&mut self) -> &mut OverlayState {
&mut self.overlay
}
/// Returns immutable snapshot bytes backing the engine.
#[must_use]
pub fn snapshot_bytes(&self) -> &[u8] {
self.inner.backing_cart().backing.as_slice()
}
/// Returns both topology views opened at engine build.
#[must_use]
pub fn topology(&self) -> &GraphTopology<'_> {
&self.inner.get().topology
}
/// Returns the forward CSR view (outgoing adjacency only).
#[must_use]
pub fn forward(&self) -> &crate::topology::ForwardCsr<'_> {
&self.topology().forward
}
/// Returns the inbound CSC view (incoming adjacency only).
#[must_use]
pub fn inbound(&self) -> &crate::topology::InboundCsc<'_> {
&self.topology().inbound
}
/// Replaces artifact bytes after maintenance rebuild.
///
/// # Errors
///
/// Returns [`PostgresGraphError`] when the replacement snapshot fails validation.
pub fn replace_snapshot_bytes(&mut self, bytes: &[u8]) -> Result<(), PostgresGraphError> {
let engine = EngineBuilder::new()
.snapshot_owned(bytes.to_vec())
.config(self.config.clone())
.overlay(OverlayState::default())
.build()?;
self.inner = engine.inner;
self.overlay.clear();
self.unique_adjacency = UniqueAdjacency::default();
self.unique_cache_built = false;
self.traverse_scratch
.reset_after_snapshot(self.node_count() as usize);
Ok(())
}
/// Breadth-first traversal from one seed node.
///
/// # Errors
///
/// Returns [`PostgresGraphError::Query`] when the seed is out of bounds or limits are zero.
///
/// # Performance
///
/// This method is `O(r + e)` where `r` is nodes discovered up to `result_limit` and `e` is
/// edges examined along the chosen profile; `≤ 1ms` for `n ≤ 10k` on typical chain fixtures.
pub fn traverse(
&mut self,
seed: u32,
limits: TraverseLimits,
direction: TraversalDirection,
) -> Result<Vec<u32>, PostgresGraphError> {
let limits = limits.capped_by(self.config())?;
traverse_core_collect(self, &[seed], limits, direction)
}
/// Breadth-first traversal from multiple seed nodes in one kernel run.
///
/// # Errors
///
/// Returns [`PostgresGraphError::Query`] when every seed is out of bounds or limits are zero.
///
/// # Performance
///
/// Same as [`Self::traverse`] with multiple seeds; one kernel run.
pub fn traverse_from_seeds(
&mut self,
seeds: &[u32],
limits: TraverseLimits,
direction: TraversalDirection,
) -> Result<Vec<u32>, PostgresGraphError> {
let limits = limits.capped_by(self.config())?;
traverse_core_collect(self, seeds, limits, direction)
}
/// Returns visited-node count for one seed without collecting ids.
///
/// # Errors
///
/// Returns [`PostgresGraphError::Query`] when the seed is out of bounds or limits are zero.
///
/// # Performance
///
/// This method is `O(r + e)` without output allocation; matches collect cardinality.
pub fn visited_count(
&mut self,
seed: u32,
limits: TraverseLimits,
direction: TraversalDirection,
) -> Result<usize, PostgresGraphError> {
let limits = limits.capped_by(self.config())?;
traverse_core_count(self, &[seed], limits, direction)
}
/// Searches dense node ids using a simple predicate.
///
/// # Errors
///
/// Returns [`PostgresGraphError::Query`] when the effective limit is zero.
///
/// # Performance
///
/// This method is `O(n)` for `n` canonical nodes until the effective limit is reached.
pub fn search(
&self,
predicate: SearchPredicate,
limit: NonZeroUsize,
) -> Result<Vec<u32>, PostgresGraphError> {
let effective_limit = core::cmp::min(limit.get(), self.config().search_limit as usize);
let effective_limit = NonZeroUsize::new(effective_limit).ok_or(QueryError::LimitZero)?;
let node_bound = self.forward().node_count();
let mut matches = Vec::new();
for node in 0..node_bound {
let node_u32 = u32::try_from(node).map_err(|_| QueryError::NodeIndexOverflow)?;
if !self.node_visible(node_u32) || !predicate.matches(node_u32) {
continue;
}
matches.push(node_u32);
if matches.len() >= effective_limit.get() {
break;
}
}
Ok(matches)
}
/// Applies sync rows to the overlay in sequence order.
///
/// # Errors
///
/// Returns [`PostgresGraphError::Sync`] when row sequence numbers are not monotonic.
pub fn apply_sync_rows(&mut self, rows: &[SyncRow]) -> Result<usize, PostgresGraphError> {
SyncRow::apply_in_order(rows, self.overlay_mut())
}
/// Returns sync overlay health for admin surfaces.
#[must_use]
pub fn sync_health(&self) -> SyncHealth {
let status = self.stats();
SyncHealth {
overlay_edges: status.overlay_edge_count,
tombstoned_edges: status.tombstoned_edges,
tombstoned_nodes: self.overlay().tombstoned_node_count(),
}
}
/// Rebuilds the base artifact from catalog metadata and freshly scanned edge rows.
///
/// # Errors
///
/// Returns [`PostgresGraphError::Config`] when maintenance is disabled, or build/validation
/// errors from catalog planning and snapshot encoding.
pub fn rebuild_from_catalog(
&mut self,
catalog: &Catalog,
edges: &[EdgeRow],
built_at_unix: u64,
) -> Result<(), PostgresGraphError> {
if !self.config().maintenance_enabled {
return Err(ConfigError::MaintenanceDisabled.into());
}
let bytes = SnapshotRebuild::from_catalog_and_edges(catalog, edges, built_at_unix)?;
self.replace_snapshot_bytes(&bytes)
}
/// Returns whether `node` is visible under the active freshness policy.
fn node_visible(&self, node: u32) -> bool {
self.inner
.get()
.topology
.node_visible(node, TraversalDirection::Out, self.overlay())
}
}