nodedb 0.3.0

Local-first, real-time, edge-to-cloud hybrid database for multi-modal workloads
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
// SPDX-License-Identifier: BUSL-1.1

//! `ArrayOp::Put` / `Delete` / `Flush` / `Compact` handlers.

use nodedb_array::types::ArrayId;

use crate::bridge::envelope::{ErrorCode, Response};
use crate::data::executor::core_loop::CoreLoop;
use crate::data::executor::task::ExecutionTask;
use crate::engine::array::wal::{ArrayDeleteCell, ArrayPutCell};

impl CoreLoop {
    pub(in crate::data::executor) fn handle_array_put(
        &mut self,
        task: &ExecutionTask,
        array_id: &ArrayId,
        cells_msgpack: &[u8],
        wal_lsn: u64,
    ) -> Response {
        let cells: Vec<ArrayPutCell> = match zerompk::from_msgpack(cells_msgpack) {
            Ok(c) => c,
            Err(e) => {
                return self.response_error(
                    task,
                    ErrorCode::Internal {
                        detail: format!("array put decode: {e}"),
                    },
                );
            }
        };
        let n = cells.len();
        if let Err(e) = self.array_engine.put_cells(array_id, cells, wal_lsn) {
            return self.response_error(
                task,
                ErrorCode::Internal {
                    detail: format!("array put: {e}"),
                },
            );
        }
        encode_count_response(self, task, "inserted", n)
    }

    pub(in crate::data::executor) fn handle_array_delete(
        &mut self,
        task: &ExecutionTask,
        array_id: &ArrayId,
        coords_msgpack: &[u8],
        wal_lsn: u64,
    ) -> Response {
        let cells: Vec<ArrayDeleteCell> = match zerompk::from_msgpack(coords_msgpack) {
            Ok(c) => c,
            Err(e) => {
                return self.response_error(
                    task,
                    ErrorCode::Internal {
                        detail: format!("array delete decode: {e}"),
                    },
                );
            }
        };
        let n = cells.len();
        if let Err(e) = self.array_engine.delete_cells(array_id, cells, wal_lsn) {
            return self.response_error(
                task,
                ErrorCode::Internal {
                    detail: format!("array delete: {e}"),
                },
            );
        }
        encode_count_response(self, task, "deleted", n)
    }

    pub(in crate::data::executor) fn handle_array_flush(
        &mut self,
        task: &ExecutionTask,
        array_id: &ArrayId,
        wal_lsn: u64,
    ) -> Response {
        // The Control Plane allocated `wal_lsn` from the central WAL
        // writer; the engine just stamps it as the segment's flush
        // watermark.
        if let Err(e) = self.array_engine.flush(array_id, wal_lsn) {
            return self.response_error(
                task,
                ErrorCode::Internal {
                    detail: format!("array flush: {e}"),
                },
            );
        }
        encode_count_response(self, task, "flushed", 1)
    }

    /// `ArrayOp::DropArray` handler — broadcast on `DROP ARRAY` after
    /// the Control-Plane catalog mutation. Releases the per-core store
    /// and removes the on-disk segment directory so a subsequent
    /// `CREATE ARRAY` with the same name (and possibly a different
    /// schema) starts from a clean slate. Idempotent: silently
    /// succeeds when this core never opened the array.
    pub(in crate::data::executor) fn handle_array_drop(
        &mut self,
        task: &ExecutionTask,
        array_id: &ArrayId,
    ) -> Response {
        if let Err(e) = self.array_engine.drop_array(array_id) {
            return self.response_error(
                task,
                ErrorCode::Internal {
                    detail: format!("array drop: {e}"),
                },
            );
        }
        encode_count_response(self, task, "dropped", 1)
    }

    pub(in crate::data::executor) fn handle_array_compact(
        &mut self,
        task: &ExecutionTask,
        array_id: &ArrayId,
        audit_retain_ms: Option<i64>,
    ) -> Response {
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);
        let merged = match self
            .array_engine
            .maybe_compact(array_id, audit_retain_ms, now_ms)
        {
            Ok(m) => m,
            Err(e) => {
                return self.response_error(
                    task,
                    ErrorCode::Internal {
                        detail: format!("array compact: {e}"),
                    },
                );
            }
        };
        encode_count_response(self, task, "compacted", usize::from(merged))
    }
}

fn encode_count_response(core: &CoreLoop, task: &ExecutionTask, key: &str, n: usize) -> Response {
    match super::super::super::response_codec::encode_count(key, n) {
        Ok(bytes) => core.response_with_payload(task, bytes),
        Err(e) => core.response_error(
            task,
            ErrorCode::Internal {
                detail: e.to_string(),
            },
        ),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    use nodedb_array::schema::ArraySchemaBuilder;
    use nodedb_array::schema::attr_spec::{AttrSpec, AttrType};
    use nodedb_array::schema::dim_spec::{DimSpec, DimType};
    use nodedb_array::types::ArrayId;
    use nodedb_array::types::cell_value::value::CellValue;
    use nodedb_array::types::coord::value::CoordValue;
    use nodedb_array::types::domain::{Domain, DomainBound};
    use nodedb_bridge::buffer::RingBuffer;

    use crate::bridge::dispatch::{BridgeRequest, BridgeResponse};
    use crate::bridge::envelope::{PhysicalPlan, Priority, Request, Status};
    use crate::data::executor::core_loop::CoreLoop;
    use crate::engine::array::wal::ArrayPutCell;
    use crate::types::*;
    use nodedb_physical::physical_plan::ArrayOp;

    fn make_request(plan: PhysicalPlan, id: u64) -> Request {
        Request {
            request_id: RequestId::new(id),
            tenant_id: TenantId::new(1),
            database_id: DatabaseId::DEFAULT,
            vshard_id: VShardId::new(0),
            plan,
            deadline: Instant::now() + Duration::from_secs(5),
            priority: Priority::Normal,
            trace_id: TraceId::ZERO,
            consistency: ReadConsistency::Strong,
            idempotency_key: None,
            event_source: crate::event::EventSource::User,
            user_roles: Vec::new(),
            user_id: None,
            statement_digest: None,
        }
    }

    #[test]
    fn array_open_put_flush_smoke() {
        let dir = tempfile::tempdir().unwrap();
        let (req_tx_a, req_rx) = RingBuffer::channel::<BridgeRequest>(64);
        let (resp_tx, resp_rx) = RingBuffer::channel::<BridgeResponse>(64);
        let mut req_tx = req_tx_a;
        let mut resp_rx = resp_rx;
        let mut core = CoreLoop::open(
            0,
            req_rx,
            resp_tx,
            dir.path(),
            Arc::new(nodedb_types::OrdinalClock::new()),
        )
        .unwrap();

        // 2D Int64 array with one Float64 attr.
        let schema = ArraySchemaBuilder::new("smoke")
            .dim(DimSpec::new(
                "x",
                DimType::Int64,
                Domain::new(DomainBound::Int64(0), DomainBound::Int64(15)),
            ))
            .dim(DimSpec::new(
                "y",
                DimType::Int64,
                Domain::new(DomainBound::Int64(0), DomainBound::Int64(15)),
            ))
            .attr(AttrSpec::new("v", AttrType::Float64, true))
            .tile_extents(vec![4, 4])
            .build()
            .unwrap();

        let schema_bytes = zerompk::to_msgpack_vec(&schema).unwrap();
        let schema_hash: u64 = 0xA11CEBEEF;
        let aid = ArrayId::new(TenantId::new(1), "smoke");

        // 1) OpenArray
        req_tx
            .try_push(BridgeRequest {
                inner: make_request(
                    PhysicalPlan::Array(ArrayOp::OpenArray {
                        array_id: aid.clone(),
                        schema_msgpack: schema_bytes.clone(),
                        schema_hash,
                        prefix_bits: 8,
                    }),
                    1,
                ),
            })
            .unwrap();
        core.tick();
        let resp = resp_rx.try_pop().unwrap();
        assert_eq!(
            resp.inner.status,
            Status::Ok,
            "open response: {:?}",
            resp.inner
        );

        // 2) Put one cell
        let cells = vec![ArrayPutCell {
            coord: vec![CoordValue::Int64(1), CoordValue::Int64(2)],
            attrs: vec![CellValue::Float64(3.5)],
            surrogate: nodedb_types::Surrogate::ZERO,
            system_from_ms: 0,
            valid_from_ms: 0,
            valid_until_ms: i64::MAX,
        }];
        let cells_bytes = zerompk::to_msgpack_vec(&cells).unwrap();
        req_tx
            .try_push(BridgeRequest {
                inner: make_request(
                    PhysicalPlan::Array(ArrayOp::Put {
                        array_id: aid.clone(),
                        cells_msgpack: cells_bytes,
                        wal_lsn: 42,
                    }),
                    2,
                ),
            })
            .unwrap();
        core.tick();
        let resp = resp_rx.try_pop().unwrap();
        assert_eq!(
            resp.inner.status,
            Status::Ok,
            "put response: {:?}",
            resp.inner
        );

        // 3) Flush
        req_tx
            .try_push(BridgeRequest {
                inner: make_request(
                    PhysicalPlan::Array(ArrayOp::Flush {
                        array_id: aid.clone(),
                        wal_lsn: 99,
                    }),
                    3,
                ),
            })
            .unwrap();
        core.tick();
        let resp = resp_rx.try_pop().unwrap();
        assert_eq!(
            resp.inner.status,
            Status::Ok,
            "flush response: {:?}",
            resp.inner
        );
    }

    /// `OpenArray` → `Put` → `DropArray` → re-`OpenArray` with a
    /// *different* schema_hash → `Slice` returns zero rows. Without
    /// `drop_array` releasing the per-core store, the second `OpenArray`
    /// would either reject the schema_hash mismatch or surface stale
    /// memtable cells.
    #[test]
    fn array_drop_clears_per_core_state() {
        use nodedb_array::types::cell_value::value::CellValue;

        let dir = tempfile::tempdir().unwrap();
        let (req_tx_a, req_rx) = RingBuffer::channel::<BridgeRequest>(64);
        let (resp_tx, resp_rx) = RingBuffer::channel::<BridgeResponse>(64);
        let mut req_tx = req_tx_a;
        let mut resp_rx = resp_rx;
        let mut core = CoreLoop::open(
            0,
            req_rx,
            resp_tx,
            dir.path(),
            Arc::new(nodedb_types::OrdinalClock::new()),
        )
        .unwrap();

        // v1 schema: one float attr.
        let v1 = ArraySchemaBuilder::new("recyc")
            .dim(DimSpec::new(
                "k",
                DimType::Int64,
                Domain::new(DomainBound::Int64(0), DomainBound::Int64(15)),
            ))
            .attr(AttrSpec::new("qual", AttrType::Float64, true))
            .tile_extents(vec![16])
            .build()
            .unwrap();
        let v1_bytes = zerompk::to_msgpack_vec(&v1).unwrap();
        let aid = ArrayId::new(TenantId::new(1), "recyc");

        // 1) Open v1.
        req_tx
            .try_push(BridgeRequest {
                inner: make_request(
                    PhysicalPlan::Array(ArrayOp::OpenArray {
                        array_id: aid.clone(),
                        schema_msgpack: v1_bytes.clone(),
                        schema_hash: 0xAAAA,
                        prefix_bits: 8,
                    }),
                    1,
                ),
            })
            .unwrap();
        core.tick();
        let resp = resp_rx.try_pop().unwrap();
        assert_eq!(resp.inner.status, Status::Ok, "open v1: {:?}", resp.inner);

        // 2) Put a cell — establishes memtable state.
        let cells = vec![ArrayPutCell {
            coord: vec![CoordValue::Int64(3)],
            attrs: vec![CellValue::Float64(42.0)],
            surrogate: nodedb_types::Surrogate::ZERO,
            system_from_ms: 0,
            valid_from_ms: 0,
            valid_until_ms: i64::MAX,
        }];
        let cells_bytes = zerompk::to_msgpack_vec(&cells).unwrap();
        req_tx
            .try_push(BridgeRequest {
                inner: make_request(
                    PhysicalPlan::Array(ArrayOp::Put {
                        array_id: aid.clone(),
                        cells_msgpack: cells_bytes,
                        wal_lsn: 7,
                    }),
                    2,
                ),
            })
            .unwrap();
        core.tick();
        let resp = resp_rx.try_pop().unwrap();
        assert_eq!(resp.inner.status, Status::Ok, "put v1: {:?}", resp.inner);

        // 3) DropArray — releases per-core store + on-disk segment dir.
        req_tx
            .try_push(BridgeRequest {
                inner: make_request(
                    PhysicalPlan::Array(ArrayOp::DropArray {
                        array_id: aid.clone(),
                    }),
                    3,
                ),
            })
            .unwrap();
        core.tick();
        let resp = resp_rx.try_pop().unwrap();
        assert_eq!(resp.inner.status, Status::Ok, "drop: {:?}", resp.inner);

        // The Control Plane owns the shared array_catalog and unregisters
        // on `DROP ARRAY` *before* scattering `ArrayOp::DropArray`. Mirror
        // that here so the next `OpenArray` registers the new schema_hash
        // rather than colliding with v1's entry.
        {
            let mut cat = core.array_catalog.write().unwrap();
            cat.unregister("recyc");
        }

        // 4) Re-open with a DIFFERENT schema_hash. Without the drop, this
        //    would fail with `SchemaMismatch`. The post-drop state must
        //    accept the new hash.
        req_tx
            .try_push(BridgeRequest {
                inner: make_request(
                    PhysicalPlan::Array(ArrayOp::OpenArray {
                        array_id: aid.clone(),
                        schema_msgpack: v1_bytes,
                        schema_hash: 0xBBBB,
                        prefix_bits: 8,
                    }),
                    4,
                ),
            })
            .unwrap();
        core.tick();
        let resp = resp_rx.try_pop().unwrap();
        assert_eq!(
            resp.inner.status,
            Status::Ok,
            "re-open after drop: {:?}",
            resp.inner
        );
    }
}