reddb-io-server 1.40.3

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
//! Admission for standalone UNIQUE indexes (HASH and BTREE), before row/WAL
//! installation.

use super::index_store::{unique_index_key, RegisteredIndex};
use crate::storage::EntityId;
use crate::{RedDBError, RedDBResult, RedDBRuntime};
use reddb_types::Value;
use std::collections::HashSet;

fn matches_target(index: &RegisteredIndex, target: Option<&[String]>) -> bool {
    target.is_none_or(|target| {
        target.len() == index.columns.len()
            && target.iter().all(|column| {
                index
                    .columns
                    .iter()
                    .any(|indexed| indexed.eq_ignore_ascii_case(column))
            })
    })
}

fn index_key(index: &RegisteredIndex, fields: &[(String, Value)]) -> Option<Vec<u8>> {
    // Match the physical writer exactly, including legacy numeric encodings.
    // Logical SQL equality is not its key representation. A composite index
    // keys on every column; a NULL column reserves no key (`unique_index_key`).
    unique_index_key(&index.columns, fields)
}

fn duplicate_key_error(index: &RegisteredIndex, collection: &str) -> RedDBError {
    RedDBError::Query(format!(
        "duplicate key violates unique index '{}' on collection '{}'",
        index.name, collection
    ))
}

impl RedDBRuntime {
    pub(crate) fn has_unique_target(&self, collection: &str, target: &[String]) -> bool {
        self.index_store_ref()
            .unique_indexes(collection)
            .iter()
            .any(|index| matches_target(index, Some(target)))
    }

    pub(crate) fn unique_conflict_id(
        &self,
        collection: &str,
        fields: &[(String, Value)],
        target: Option<&[String]>,
    ) -> RedDBResult<Option<EntityId>> {
        for index in self.index_store_ref().unique_indexes(collection) {
            if !matches_target(&index, target) {
                continue;
            }
            if let Some(key) = index_key(&index, fields) {
                if let Some(id) = self.unique_key_conflict(&index, &key, None)? {
                    return Ok(Some(id));
                }
            }
        }
        Ok(None)
    }

    /// A row other than `exclude` that reserves `key` in `index`. `exclude` is
    /// the version an UPDATE replaces: it never conflicts with its successor.
    fn unique_key_conflict(
        &self,
        index: &RegisteredIndex,
        key: &[u8],
        exclude: Option<EntityId>,
    ) -> RedDBResult<Option<EntityId>> {
        let store = self.db().store();
        let snapshots = self.snapshot_manager();
        let own_xids = self.own_transaction_xids();
        if self.vcs_is_versioned(&index.collection)? {
            let (snapshot, _retention) = self.native_read_snapshot()?;
            let mut conflict = None;
            if let Some(manager) = store.get_collection(&index.collection) {
                manager.try_for_each_entity(usize::MAX, |entity| {
                    if exclude != Some(entity.id)
                        && reddb_engine::transaction::read::entity_reserves_unique_key(
                            &snapshot, entity,
                        )
                    {
                        if let Some(row) = entity.data.as_row() {
                            let fields: Vec<_> = row
                                .iter_fields()
                                .map(|(name, value)| (name.to_string(), value.clone()))
                                .collect();
                            if index_key(index, &fields).as_deref() == Some(key) {
                                conflict = Some(entity.id);
                                return false;
                            }
                        }
                    }
                    true
                })?;
            }
            return Ok(conflict);
        }
        let pocket = index.hash_lookup_name();
        let candidates = self
            .index_store_ref()
            .hash_lookup(&index.collection, &pocket, key)
            .map_err(RedDBError::Internal)?;
        let read_workspace = if !candidates.is_empty() {
            match store.get_collection(&index.collection) {
                Some(manager) if manager.has_backing() => Some(self.reserve_index_scan(&manager)?),
                _ => None,
            }
        } else {
            None
        };
        let read_bytes_max = read_workspace
            .as_ref()
            .map_or(usize::MAX, |(_, limit)| *limit);
        for id in candidates {
            if exclude == Some(id) {
                continue;
            }
            if let Some(entity) = store.try_get(&index.collection, id, read_bytes_max)? {
                if snapshots.row_reserves_unique_key(entity.xmin, entity.xmax, &own_xids) {
                    if snapshots.is_active(entity.xmin) && !own_xids.contains(&entity.xmin) {
                        return Err(RedDBError::Query(format!(
                            "serialization conflict: unique index '{}' is owned by active transaction {}; retry after it resolves",
                            index.name, entity.xmin
                        )));
                    }
                    return Ok(Some(id));
                }
            }
            // Aborted/obsolete physical entries must not reject a replacement.
            // The collection constraint gate is held through this cleanup and
            // the eventual insertion by all row mutation callers.
            self.index_store_ref()
                .hash
                .remove(&index.collection, &pocket, key, id)
                .map_err(|error| RedDBError::Internal(error.to_string()))?;
        }
        Ok(None)
    }

    /// A row in the disk base that reserves a declared `PRIMARY KEY`/`UNIQUE`
    /// key. The contract's resident probe only sees rows still in memory, so
    /// a constraint without a unique index over the same columns must look at
    /// the base as well, or a checkpoint silently drops the constraint.
    ///
    /// A HASH index over exactly these columns narrows the search to its
    /// candidates; the contract's own rule still decides whether a candidate
    /// reserves the key. Without one this costs a bounded pass over the
    /// collection.
    pub(crate) fn cold_constraint_conflict(
        &self,
        collection: &str,
        columns: &[String],
        fields: &[(String, Value)],
        signatures: &[String],
        exclude: Option<EntityId>,
    ) -> RedDBResult<Option<EntityId>> {
        let store = self.db().store();
        let Some(manager) = store.get_collection(collection) else {
            return Ok(None);
        };
        if !manager.has_backing() {
            return Ok(None);
        }
        let snapshots = self.snapshot_manager();
        let own_xids = self.own_transaction_xids();
        let reserves = |entity: &crate::storage::UnifiedEntity| {
            if exclude == Some(entity.id)
                || !snapshots.row_reserves_unique_key(entity.xmin, entity.xmax, &own_xids)
            {
                return false;
            }
            // Same key representation as the resident probe.
            entity.data.as_row().is_some_and(|row| {
                columns.iter().zip(signatures).all(|(column, signature)| {
                    row.get_field(column)
                        .is_some_and(|value| format!("{value:?}") == *signature)
                })
            })
        };
        let candidates = self
            .index_store_ref()
            .list_indices(collection)
            .into_iter()
            .find(|index| {
                matches!(index.method, super::index_store::IndexMethodKind::Hash)
                    && matches_target(index, Some(columns))
            })
            .and_then(|index| Some((index_key(&index, fields)?, index)));
        if let Some((key, index)) = candidates {
            let ids = self
                .index_store_ref()
                .hash_lookup(collection, &index.hash_lookup_name(), &key)
                .map_err(RedDBError::Internal)?;
            if ids.is_empty() {
                return Ok(None);
            }
            // Only after the probe: it reserves its own workspace, and a scan
            // allowance held across it would crowd that out under pressure.
            let (_workspace, read_bytes_max) = self.reserve_index_scan(&manager)?;
            for id in ids {
                if let Some(entity) = store.try_get(collection, id, read_bytes_max)? {
                    if reserves(&entity) {
                        return Ok(Some(id));
                    }
                }
            }
            return Ok(None);
        }
        let (_workspace, read_bytes_max) = self.reserve_index_scan(&manager)?;
        let mut conflict = None;
        manager.try_for_each_entity(read_bytes_max, |entity| {
            if reserves(entity) {
                conflict = Some(entity.id);
            }
            conflict.is_none()
        })?;
        Ok(conflict)
    }

    pub(crate) fn has_unique_batch_conflict(
        &self,
        collection: &str,
        fields: &[(String, Value)],
        accepted: &[Vec<(String, Value)>],
        target: Option<&[String]>,
    ) -> bool {
        self.index_store_ref()
            .unique_indexes(collection)
            .iter()
            .any(|index| {
                matches_target(index, target)
                    && index_key(index, fields).is_some_and(|key| {
                        accepted
                            .iter()
                            .any(|row| index_key(index, row).as_ref() == Some(&key))
                    })
            })
    }

    pub(crate) fn enforce_unique_rows(
        &self,
        collection: &str,
        rows: &[super::mutation::MutationRow],
    ) -> RedDBResult<()> {
        for index in self.index_store_ref().unique_indexes(collection) {
            let mut proposed = HashSet::with_capacity(rows.len());
            for row in rows {
                let Some(key) = index_key(&index, &row.fields) else {
                    continue;
                };
                if self.unique_key_conflict(&index, &key, None)?.is_some() || !proposed.insert(key)
                {
                    return Err(duplicate_key_error(&index, collection));
                }
            }
        }
        Ok(())
    }

    /// Admit the post-images of one UPDATE: `(replaced version, new fields)`.
    /// Each must stay clear of every other live row, and of each other.
    pub(crate) fn enforce_unique_updates(
        &self,
        collection: &str,
        rows: &[(EntityId, Vec<(String, Value)>)],
    ) -> RedDBResult<()> {
        for index in self.index_store_ref().unique_indexes(collection) {
            let mut proposed = HashSet::with_capacity(rows.len());
            for (previous, fields) in rows {
                let Some(key) = index_key(&index, fields) else {
                    continue;
                };
                if self
                    .unique_key_conflict(&index, &key, Some(*previous))?
                    .is_some()
                    || !proposed.insert(key)
                {
                    return Err(duplicate_key_error(&index, collection));
                }
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::{RedDBOptions, RedDBRuntime};
    use reddb_types::Value;

    /// A table whose rows all live in the disk base, like after a restart.
    fn cold_table(ddl: &[&str]) -> (tempfile::TempDir, RedDBRuntime) {
        let directory = tempfile::tempdir().expect("constraint fixture");
        let options = RedDBOptions::persistent(directory.path().join("constraints.rdb"))
            .with_memory_budget(64 * 1024 * 1024)
            .with_storage_profile(
                crate::storage::profile::StorageDeployPreset::PrimaryReplicaDev.selection(),
            )
            .expect("profile");
        let seed = RedDBRuntime::with_options(options.clone()).expect("seed");
        for sql in ddl {
            seed.execute_query(sql).expect(sql);
        }
        seed.flush().expect("seed checkpoint");
        drop(seed);
        let runtime = crate::storage::RedDB::with_disk_residency_for_qualification(|| {
            RedDBRuntime::with_options(options)
        })
        .expect("cold runtime");
        (directory, runtime)
    }

    fn values(runtime: &RedDBRuntime, sql: &str, column: &str) -> Vec<Value> {
        runtime
            .execute_query(sql)
            .expect(sql)
            .result
            .records
            .iter()
            .filter_map(|record| record.get(column).cloned())
            .collect()
    }

    #[test]
    fn an_update_that_keeps_its_key_is_not_refused_for_a_duplicate_it_did_not_create() {
        let (_directory, runtime) = cold_table(&[
            "CREATE TABLE snapshots (id TEXT PRIMARY KEY, seq INTEGER, payload TEXT)",
            "INSERT INTO snapshots (id, seq, payload) VALUES ('0007', 7, 'first'), ('0008', 8, 'kept')",
        ]);
        // An engine that did not check keys against rows on disk let a second
        // row with the same key in. Put one there below the constraint.
        let store = runtime.db().store();
        let manager = store.get_collection("snapshots").expect("collection");
        let mut duplicate = None;
        manager
            .try_for_each_entity(usize::MAX, |entity| {
                let is_seven = entity.data.as_row().is_some_and(|row| {
                    matches!(row.get_field("id"), Some(Value::Text(id)) if id.as_ref() == "0007")
                });
                if is_seven {
                    duplicate = Some(entity.clone());
                }
                !is_seven
            })
            .expect("find the row");
        let mut duplicate = duplicate.expect("row 0007");
        // A row of its own, not another version of the first: its own
        // physical and logical identity.
        let own_id = crate::storage::EntityId::new(900_000);
        duplicate.id = own_id;
        duplicate.set_logical_id(own_id);
        if let crate::storage::EntityKind::TableRow { row_id, .. } = &mut duplicate.kind {
            *row_id = own_id.raw();
        }
        store
            .insert_auto("snapshots", duplicate)
            .expect("legacy duplicate");
        assert_eq!(
            values(&runtime, "SELECT id FROM snapshots WHERE seq = 7", "id").len(),
            2,
            "two rows share the key"
        );

        // The statement leaves `id` as it is on every row it touches.
        let updated = runtime
            .execute_query(
                "UPDATE snapshots SET id = id, payload = NULL WHERE seq < 8 AND payload IS NOT NULL",
            )
            .expect("an unchanged key cannot newly violate its constraint");
        assert_eq!(updated.affected_rows, 2);
        assert!(values(
            &runtime,
            "SELECT payload FROM snapshots WHERE seq = 7",
            "payload"
        )
        .iter()
        .all(|payload| matches!(payload, Value::Null)),);

        // Moving a row onto a key another row holds is still refused,
        let error = runtime
            .execute_query("UPDATE snapshots SET id = '0008' WHERE seq = 7")
            .expect_err("an update must not take a key in use");
        assert!(error.to_string().contains("primary key"), "{error}");
        // and so is inserting the duplicate key again.
        let error = runtime
            .execute_query("INSERT INTO snapshots (id, seq, payload) VALUES ('0007', 7, 'again')")
            .expect_err("the key is taken");
        assert!(error.to_string().contains("primary key"), "{error}");
    }

    #[test]
    fn primary_key_still_rejects_duplicates_of_rows_on_disk() {
        let (_directory, runtime) = cold_table(&[
            "CREATE TABLE accounts (id TEXT PRIMARY KEY, v TEXT)",
            "INSERT INTO accounts (id, v) VALUES ('a', '1'), ('b', '2')",
        ]);
        let error = runtime
            .execute_query("INSERT INTO accounts (id, v) VALUES ('a', 'duplicate')")
            .expect_err("a primary key on disk must still reject its duplicate");
        assert!(error.to_string().contains("primary key"), "{error}");
        // An upsert must find the row on disk and update it, not append.
        runtime
            .execute_query(
                "INSERT INTO accounts (id, v) VALUES ('b', 'upserted') \
                 ON CONFLICT (id) DO UPDATE SET v = 'upserted'",
            )
            .expect("upsert over a row on disk");
        assert_eq!(
            values(&runtime, "SELECT v FROM accounts WHERE id = 'b'", "v"),
            vec![Value::text("upserted")]
        );
        // An UPDATE may not move a row onto a key held on disk either, but
        // rewriting a row under its own key stays legal.
        assert!(runtime
            .execute_query("UPDATE accounts SET id = 'a' WHERE id = 'b'")
            .is_err());
        runtime
            .execute_query("UPDATE accounts SET v = 'again' WHERE id = 'a'")
            .expect("update that keeps its key");
        // A key freed by a delete can be taken again.
        runtime
            .execute_query("DELETE FROM accounts WHERE id = 'a'")
            .expect("delete");
        runtime
            .execute_query("INSERT INTO accounts (id, v) VALUES ('a', 'reborn')")
            .expect("key freed by delete");
        assert_eq!(
            values(&runtime, "SELECT id FROM accounts ORDER BY id", "id"),
            vec![Value::text("a"), Value::text("b")]
        );
    }

    #[test]
    fn a_hash_index_on_the_key_serves_the_constraint_check_on_disk() {
        // The index is not unique: it only narrows the rows the constraint
        // has to look at. The constraint's own rule still decides.
        let (_directory, runtime) = cold_table(&[
            "CREATE TABLE accounts (id TEXT PRIMARY KEY, v TEXT)",
            "CREATE INDEX accounts_id ON accounts (id) USING HASH",
            "INSERT INTO accounts (id, v) VALUES ('a', '1'), ('b', '2')",
        ]);
        let error = runtime
            .execute_query("INSERT INTO accounts (id, v) VALUES ('a', 'duplicate')")
            .expect_err("duplicate primary key on disk");
        assert!(error.to_string().contains("primary key"), "{error}");
        runtime
            .execute_query(
                "INSERT INTO accounts (id, v) VALUES ('b', 'upserted') \
                 ON CONFLICT (id) DO UPDATE SET v = 'upserted'",
            )
            .expect("upsert over a row on disk");
        assert_eq!(
            values(&runtime, "SELECT v FROM accounts WHERE id = 'b'", "v"),
            vec![Value::text("upserted")]
        );
        assert!(runtime
            .execute_query("UPDATE accounts SET id = 'a' WHERE id = 'b'")
            .is_err());
        // Deleting and re-inserting a key inside one transaction, then
        // rolling back, leaves the original row holding it.
        for sql in [
            "BEGIN",
            "DELETE FROM accounts WHERE id = 'a'",
            "INSERT INTO accounts (id, v) VALUES ('a', 'replacement')",
            "ROLLBACK",
        ] {
            runtime.execute_query(sql).expect(sql);
        }
        assert_eq!(
            values(&runtime, "SELECT v FROM accounts WHERE id = 'a'", "v"),
            vec![Value::text("1")]
        );
        runtime
            .execute_query("INSERT INTO accounts (id, v) VALUES ('c', '3')")
            .expect("new key");
        assert_eq!(
            values(&runtime, "SELECT id FROM accounts ORDER BY id", "id").len(),
            3
        );
    }

    #[test]
    fn unique_column_still_rejects_duplicates_of_rows_on_disk() {
        let (_directory, runtime) = cold_table(&[
            "CREATE TABLE members (id INTEGER PRIMARY KEY, email TEXT UNIQUE, org TEXT)",
            "INSERT INTO members (id, email, org) VALUES (1, 'a@x', 'o'), (2, 'b@x', 'o')",
        ]);
        assert!(runtime
            .execute_query("INSERT INTO members (id, email, org) VALUES (3, 'a@x', 'o')")
            .is_err());
        runtime
            .execute_query("INSERT INTO members (id, email, org) VALUES (3, 'c@x', 'o')")
            .expect("a new key is admitted");
        assert_eq!(
            values(&runtime, "SELECT id FROM members ORDER BY id", "id").len(),
            3
        );
    }
}