Repository navigation
Expand file tree
/
Copy pathdb.rs
More file actions
3507 lines (3176 loc) · 139 KB
/
Copy pathdb.rs
File metadata and controls
3507 lines (3176 loc) · 139 KB
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Public `Minigraf` facade with `WriteTransaction` and `OpenOptions`.
//!
//! This module provides the primary user-facing API for Minigraf:
//! - `Minigraf::open()` / `Minigraf::in_memory()` for database creation
//! - `Minigraf::execute()` for implicit (self-contained) transactions
//! - `Minigraf::begin_write()` / `WriteTransaction` for explicit transactions
//! - `Minigraf::checkpoint()` for manual WAL compaction
use crate::graph::types::{Fact, TxId};
/// Sentinel value used in `materialize_transaction` to signal "no explicit `valid_from`
/// was provided; use the transaction timestamp at commit time."
///
/// `i64::MIN` is chosen because it is not a representable Unix millisecond timestamp
/// in any practical context, avoiding the collision that `0` would have with the Unix
/// epoch (1970-01-01T00:00:00Z), which is a legitimate `valid_from` value.
pub(crate) const VALID_FROM_USE_TX_TIME: i64 = i64::MIN;
use crate::cursor::Cursor;
use crate::error::{ErrorCode, MinigrafError, bail_coded, err_coded};
use crate::graph::FactStorage;
use crate::graph::storage::Snapshot;
use crate::graph::types::Value;
use crate::overrides::{Overridable, check_overrides};
use crate::query::datalog::evaluator::{DEFAULT_MAX_DERIVED_FACTS, DEFAULT_MAX_ITERATIONS};
use crate::query::datalog::executor::DatalogExecutor;
use crate::query::datalog::executor::QueryResult;
use crate::query::datalog::functions::{Functions, UdfError, udf_aggregate, udf_predicate};
use crate::query::datalog::parser::parse_datalog_command;
use crate::query::datalog::parser::statement::{self, Kind};
use crate::query::datalog::prepared::reject_unbound_slots;
use crate::query::datalog::rules::RuleRegistry;
use crate::query::datalog::types::DatalogCommand;
use crate::storage::backend::MemoryBackend;
#[cfg(not(target_arch = "wasm32"))]
use crate::storage::backend::file::{FileBackend, LockMode};
use crate::storage::persistent_facts:
10000
:PersistentFactStorage;
#[cfg(not(target_arch = "wasm32"))]
use crate::wal::WalWriter;
use anyhow::Result;
use std::any::Any;
#[cfg(not(target_arch = "wasm32"))]
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard, RwLock};
// ─── Thread-local reentrant-write detection ─────────────────────────────────
thread_local! {
/// Set to `true` while a `WriteTransaction` is active on this thread.
/// Prevents same-thread deadlock when `db.execute()` is called while
/// a `WriteTransaction` is in progress.
static WRITE_TX_ACTIVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
fn set_write_tx_active(val: bool) {
WRITE_TX_ACTIVE.with(|f| f.set(val));
}
pub(crate) fn is_write_tx_active() -> bool {
WRITE_TX_ACTIVE.with(|f| f.get())
}
// ─── Page cache sizing ─────────────────────────────────────────────────────────
/// Page cache capacity to use for an in-memory (`MemoryBackend`) database.
///
/// `MemoryBackend` serves every read and write directly from RAM and never
/// consults the page cache, so `opts.page_cache_size` — which only affects
/// file-backed databases — is ignored here and zero capacity is always used.
fn memory_page_cache_capacity(_opts: &OpenOptions) -> usize {
0
}
// ─── SyncMode ────────────────────────────────────────────────────────────────
/// Controls how aggressively WAL writes are flushed to disk.
///
/// Independent of [`Minigraf::checkpoint`], which always fsyncs the main
/// `.graph` file regardless of this setting — see [`OpenOptions::synchronous`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncMode {
/// `fdatasync` after every WAL write. Default; matches Minigraf's
/// behavior before this option existed — every committed `transact`/
/// `retract` is durable immediately.
Full,
/// No per-write flush. The WAL entry is still `write_all()`'d — safe
/// across an ordinary process crash — but not forced to disk until the
/// next checkpoint (auto-threshold, explicit `checkpoint()`, or clean
/// close), which fsyncs the main file directly rather than the WAL —
/// the WAL is simply deleted once the main file holds the same data.
/// Data written since the last checkpoint is lost only on OS crash or
/// power loss, not process death. Intended for bulk loaders that can
/// safely re-run from a checkpoint watermark on failure.
///
/// Combined with [`OpenOptions::wal_checkpoint_threshold`] set to
/// `usize::MAX`, nothing is ever forced to disk for the handle's
/// lifetime — no per-write flush, no auto-checkpoint, and no
/// close-time checkpoint (the same sentinel also suppresses that).
/// Callers wanting a bounded durability window should keep an explicit
/// `checkpoint()` call or a finite threshold.
Normal,
}
// ─── OpenOptions ─────────────────────────────────────────────────────────────
/// Configuration options for opening a `Minigraf` database.
///
/// `#[non_exhaustive]`: construct via [`OpenOptions::new`]/[`OpenOptions::default`]
/// plus the builder methods, or `..Default::default()`, not a full struct literal.
/// This is the third field added since 1.0 (`allow_unlocked`, `synchronous`); marking
/// it non-exhaustive now means the next one won't be a breaking change.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OpenOptions {
/// Number of WAL entries committed before an automatic checkpoint is triggered.
///
/// Defaults to 1000. Lower values mean more frequent checkpoints (smaller WAL,
/// more I/O). Higher values mean less frequent checkpoints (larger WAL, less I/O).
///
/// A checkpoint's cost follows the facts written since the last one, not the
/// size of the database (see [`Minigraf::checkpoint`]), and durability does not
/// depend on it: the WAL is crash-durable. Lower values keep the WAL and reopen
/// time small; higher values batch more facts per checkpoint.
///
/// `usize::MAX` turns off every implicit checkpoint: no auto-checkpoint and
/// nothing written to the `.graph` file on close. Only an explicit
/// [`Minigraf::checkpoint`] writes it; until then the WAL holds the pending
/// facts, and the next open replays them.
pub wal_checkpoint_threshold: usize,
/// Number of pages to hold in the LRU page cache. Default: 256 (= 1MB at 4KB pages).
///
/// **File-backed databases only.** In-memory databases (`Minigraf::in_memory`,
/// `open_memory`) ignore this option — `MemoryBackend` serves every read and
/// write directly from RAM and never consults the page cache.
///
/// Every read of a committed page goes through this cache, including on a
/// [`read_only`](Self::read_only) handle. A tool that reads the whole file
/// can keep it resident with `file_size / 4096` pages.
pub page_cache_size: usize,
/// Maximum facts the rules of one query may derive in total; the
/// database's own facts do not count. Defaults to 1_000_000. Stops a
/// runaway recursive rule with `INT-020`; it never limits returned rows.
pub max_derived_facts: usize,
/// Deprecated alias of [`max_derived_facts`](Self::max_derived_facts):
/// the lower of the two applies (#553). Defaults to `usize::MAX`, no
/// limit of its own, so it can lower the limit but not raise it; raise
/// `max_derived_facts` instead. It never limited returned rows.
#[deprecated(
since = "3.0.0",
note = "use `max_derived_facts`; the lower of the two applies"
)]
pub max_results: usize,
/// The most rounds one stratum of a rule query may run (#861). Defaults
/// to 1,000,000, the same as [`max_derived_facts`](Self::max_derived_facts):
/// a stratum only starts another round after deriving a new fact, so at
/// the defaults the derived-facts limit is reached first. A stratum
/// still deriving facts after this many rounds fails with `INT-020`;
/// `0` fails every rule query. Overridden per query by
/// `:max-iterations N`.
pub max_iterations: usize,
/// Open even when the filesystem cannot lock files at all.
///
/// Defaults to `false`, which refuses to open rather than run without the
/// protection the lock provides. Set this only when you know the database
/// has a single writer by other means — for example an NFSv3 mount with no
/// `lockd`, where locking is unavailable rather than merely contended.
///
/// This does **not** override a lock that another handle actually holds.
/// Opening a database twice is refused regardless of this setting.
pub allow_unlocked: bool,
/// Controls WAL write durability. See [`SyncMode`]. Defaults to `SyncMode::Full`.
///
/// The other durability/throughput lever is batching: `begin_write()` +
/// several `execute()` calls + one `commit()` collapses every staged
/// fact into a single WAL write and a single fsync, regardless of this
/// setting.
///
/// No effect on in-memory databases, which have no WAL.
pub synchronous: SyncMode,
/// Open the database read-only. Defaults to `false`.
///
/// Nothing done through the handle writes to the `.graph` file or its WAL:
/// a missing file is an error (`STG-042`) rather than created, a WAL left
/// by a previous session is applied in memory but not checkpointed or
/// deleted, and a format v7 file is read into memory instead of migrated.
/// The handle shows the same data a read-write open would.
///
/// The file is locked in shared mode, so any number of read-only handles,
/// in this process or others, can hold it at once; a read-write open
/// excludes them and they exclude it (`STG-025`/`STG-026`).
///
/// `transact`, `retract`, [`Minigraf::begin_write`],
/// [`Minigraf::checkpoint`] and [`Minigraf::rebuild_indexes`] fail with
/// `API-014`. Queries, cursors, [`Minigraf::fact_log`],
/// [`Minigraf::verify`] and rule registration (which lives in memory) work.
pub read_only: bool,
/// The most bytes one query may hold, or `usize::MAX` (the default) for
/// no limit (#549).
///
/// A query that would hold more fails with `QRY-012` instead, and frees
/// what it held; the database and other queries are unaffected. Each
/// operator that keeps state — a hash join's build side, a negation or
/// `or` table, a distinct set, the groups of an aggregate, the rows of
/// a window, the facts a rule query derives, and the query's entity and
/// ident ids — counts an estimate of its bytes per entry, the same on
/// every platform. Rows passing between operators are not counted, and
/// neither is the answer [`Minigraf::execute`] collects; read a large
/// answer through [`Minigraf::query`]. `0` fails any query that keeps
/// state.
pub query_memory_limit: usize,
/// The most facts a transaction holds in memory on a file database, and
/// so its chunk size (#550). Defaults to 65,536.
///
/// A transaction whose facts would pass it is *large*: it writes them a
/// chunk at a time into the file's index trees and commits as a
/// checkpoint, with no WAL entry, so its memory stays at one chunk
/// whatever its size. At 1M facts the default held 40–55 MiB; 16,384
/// held under 10 MiB but took up to twice as long when the facts were
/// spread over many entities. A large transaction's `tx_id` is the time
/// it became large.
///
/// Kept between 1 and 1,000,000 (the most facts one WAL entry holds). In-memory
/// databases never write chunks; a statement is still read a chunk at a
/// time.
pub transaction_chunk_facts: usize,
/// The query keywords that may override this database's settings (#862).
/// Defaults to [`Overridable::DEFAULTS`], every keyword that could
/// override a setting before the list existed.
///
/// A query using a keyword the list leaves out fails with `API-025`
/// before it runs, from [`Minigraf::execute`], [`Minigraf::query`],
/// [`Minigraf::prepare`] and [`WriteTransaction::execute`]. The list is
/// not stored in the file: each open sets it. See
/// [`OpenOptions::allow_overrides`](Self::allow_overrides) for setting it.
pub allow_overrides: Vec<Overridable>,
}
#[allow(deprecated)] // `max_results`, kept as an alias until it is removed
impl Default for OpenOptions {
fn default() -> Self {
OpenOptions {
wal_checkpoint_threshold: 1000,
page_cache_size: 256,
max_derived_facts: DEFAULT_MAX_DERIVED_FACTS,
max_results: usize::MAX,
max_iterations: DEFAULT_MAX_ITERATIONS,
allow_unlocked: false,
synchronous: SyncMode::Full,
read_only: false,
query_memory_limit: usize::MAX,
transaction_chunk_facts: statement::DEFAULT_TX_CHUNK_FACTS,
allow_overrides: Overridable::DEFAULTS.to_vec(),
}
}
}
impl OpenOptions {
/// Create a new `OpenOptions` with default settings.
pub fn new() -> Self {
Self::default()
}
/// Set the number of WAL entries committed before an automatic checkpoint
/// is triggered. See [`OpenOptions::wal_checkpoint_threshold`].
#[must_use]
pub fn wal_checkpoint_threshold(mut self, n: usize) -> Self {
self.wal_checkpoint_threshold = n;
self
}
/// Set the number of pages to hold in the LRU page cache.
///
/// Each page is 4KB, so the default of 256 pages uses ~1MB of memory.
///
/// **File-backed databases only** — ignored when opening an in-memory
/// database (see [`OpenOptions::page_cache_size`]).
pub fn page_cache_size(mut self, size: usize) -> Self {
self.page_cache_size = size;
self
}
/// Set the maximum facts the rules of one query may derive in total.
///
/// Defaults to 1_000_000. The database's own facts do not count against it,
/// and queries without rules are not limited by it. A query that derives
/// more fails with `INT-020`, which stops a runaway recursive rule. Can be
/// overridden per query with `:max-derived-facts N` in the query vector.
pub fn max_derived_facts(mut self, n: usize) -> Self {
self.max_derived_facts = n;
self
}
/// Deprecated alias of [`max_derived_facts`](Self::max_derived_facts):
/// the lower of the two applies (#553), so it can lower the limit but not
/// raise it above `max_derived_facts`. It never limited the rows a query
/// returns.
#[deprecated(
since = "3.0.0",
note = "use `max_derived_facts`; the lower of the two applies"
)]
#[allow(deprecated)]
pub fn max_results(mut self, n: usize) -> Self {
self.max_results = n;
self
}
/// Set the most rounds one stratum of a rule query may run. See
/// [`OpenOptions::max_iterations`].
#[must_use]
pub fn max_iterations(mut self, n: usize) -> Self {
self.max_iterations = n;
self
}
/// Set the most bytes one query may hold. See
/// [`OpenOptions::query_memory_limit`].
#[must_use]
pub fn query_memory_limit(mut self, bytes: usize) -> Self {
self.query_memory_limit = bytes;
self
}
/// Set the most facts a transaction holds in memory. See
/// [`OpenOptions::transaction_chunk_facts`].
#[must_use]
pub fn transaction_chunk_facts(mut self, facts: usize) -> Self {
self.transaction_chunk_facts = facts;
self
}
/// The limits queries run with; the derived-facts limit is the lower of
/// `max_derived_facts` and its deprecated alias `max_results` (#553).
#[allow(deprecated)]
fn limits(&self) -> crate::query::engine::Limits {
crate::query::engine::Limits {
max_iterations: self.max_iterations,
max_derived_facts: self.max_derived_facts.min(self.max_results),
query_memory: self.query_memory_limit,
}
}
/// Set the query keywords that may override this database's settings.
/// See [`OpenOptions::allow_overrides`](Self::allow_overrides) (the field).
///
/// The list **replaces** the defaults rather than adding to them: an
/// empty list refuses every override keyword with `API-025`, and listing
/// only one refuses the others. To add to the defaults, chain them:
///
/// ```
/// use minigraf::{OpenOptions, Overridable};
///
/// // Refuse every query keyword that overrides a limit.
/// let locked = OpenOptions::new().allow_overrides([]).open_memory().unwrap();
/// locked.execute("(rule [(r ?x) [?x :a 1]])").unwrap();
/// let err = locked
/// .execute("(query [:find ?x :where (r ?x) :max-derived-facts 10])")
/// .unwrap_err();
/// assert_eq!(err.code(), "API-025");
///
/// // The defaults plus anything else (duplicates have no effect).
/// let opts = OpenOptions::new().allow_overrides(
/// Overridable::DEFAULTS.iter().copied().chain([Overridable::MaxResults]),
/// );
/// assert!(opts.allow_overrides.contains(&Overridable::MaxDerivedFacts));
/// ```
#[must_use]
pub fn allow_overrides(mut self, list: impl IntoIterator<Item = Overridable>) -> Self {
self.allow_overrides = list.into_iter().collect();
self
}
/// Open even when the filesystem cannot lock files. See
/// [`OpenOptions::allow_unlocked`] for when this is appropriate.
#[must_use]
pub fn allow_unlocked(mut self, allow: bool) -> Self {
self.allow_unlocked = allow;
self
}
/// Set the WAL durability mode. See [`SyncMode`].
#[must_use]
pub fn synchronous(mut self, mode: SyncMode) -> Self {
self.synchronous = mode;
self
}
/// Open the database read-only. See [`OpenOptions::read_only`].
#[must_use]
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
/// Set the path for a file-backed database.
#[cfg(not(target_arch = "wasm32"))]
pub fn path(self, path: impl AsRef<Path>) -> OpenOptionsWithPath {
OpenOptionsWithPath {
opts: self,
path: path.as_ref().to_path_buf(),
}
}
/// Open an in-memory (non-persistent) database.
///
/// Uses the options set on the builder. WAL-related options are ignored.
///
/// # Errors
///
/// Returns an error if the in-memory storage backend fails to initialise.
pub fn open_memory(self) -> Result<Minigraf, MinigrafError> {
Minigraf::in_memory_with_options(self)
}
}
/// `OpenOptions` combined with a file path, ready to open.
#[cfg(not(target_arch = "wasm32"))]
pub struct OpenOptionsWithPath {
opts: OpenOptions,
path: PathBuf,
}
#[cfg(not(target_arch = "wasm32"))]
impl OpenOptionsWithPath {
/// Open or create the file-backed database.
///
/// # Errors
///
/// Returns an error if the file cannot be opened, the header is corrupt,
/// or WAL replay fails.
pub fn open(self) -> Result<Minigraf, MinigrafError> {
Minigraf::open_with_options(self.path, self.opts)
}
}
// ─── WriteContext ─────────────────────────────────────────────────────────────
/// Internal write context: distinguishes in-memory from file-backed databases.
enum WriteContext {
/// In-memory database: no WAL, no persistence.
Memory,
/// File-backed database: has a WAL sidecar and a persistent storage layer.
#[cfg(not(target_arch = "wasm32"))]
File {
pfs: PersistentFactStorage<FileBackend>,
/// WAL writer. `None` after a checkpoint until the next write.
wal: Option<WalWriter>,
db_path: PathBuf,
/// Count of WAL entries written since the last checkpoint (or since open).
wal_entry_count: usize,
},
/// File-backed database opened with [`OpenOptions::read_only`]: the
/// storage (and with it the shared file lock), and no WAL writer.
#[cfg(not(target_arch = "wasm32"))]
ReadOnly {
pfs: PersistentFactStorage<FileBackend>,
},
}
// ─── IntegrityReport ──────────────────────────────────────────────────────────
/// The result of [`Minigraf::verify`].
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct IntegrityReport {
/// Facts in the committed file (EAVT entries).
pub facts: u64,
/// Pages checked.
pub pages: u64,
/// One structured error per finding; empty when the file is intact.
pub problems: Vec<MinigrafError>,
}
impl IntegrityReport {
/// True if no problem was found.
pub fn is_ok(&self) -> bool {
self.problems.is_empty()
}
}
// ─── Inner ────────────────────────────────────────────────────────────────────
struct Inner {
/// The shared in-memory fact store. Cloning is cheap (Arc-based).
fact_storage: FactStorage,
/// Shared rule registry, persists across all `execute()` calls.
rules: Arc<RwLock<RuleRegistry>>,
/// Function registry for aggregates, window functions and predicates;
/// each query reads a snapshot of it (#180).
functions: Arc<Functions>,
/// Serialises all writes. Holds `WriteContext` which contains the PFS/WAL
/// for file-backed databases.
write_lock: Mutex<WriteContext>,
/// Configuration options.
options: OpenOptions,
}
impl Drop for Inner {
fn drop(&mut self) {
// On clean close, perform a best-effort checkpoint to reduce WAL size.
// Errors are silently ignored (can't propagate from Drop).
// Skip if wal_checkpoint_threshold is usize::MAX — that sentinel suppresses
// all checkpointing (used by benchmarks to keep WAL entries pending),
// including the storage's own save on drop (#476). The WAL holds every
// pending fact, and the next open replays it.
if self.options.read_only {
return;
}
if self.options.wal_checkpoint_threshold == usize::MAX {
#[cfg(not(target_arch = "wasm32"))]
if let Ok(WriteContext::File { pfs, .. }) = self.write_lock.get_mut() {
pfs.discard();
}
return;
}
if let Ok(mut ctx) = self.write_lock.lock() {
let _ = Minigraf::do_checkpoint(&self.fact_storage, &mut ctx);
}
}
}
/// Refuse a write, before it takes a `tx_count`, on a handle where an earlier
/// write failed: a checkpoint (STG-046) or a WAL append (WAL-007). See #390
/// and #513.
fn refuse_if_failed(ctx: &WriteContext) -> Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let WriteContext::File { pfs, wal, .. } = ctx {
if pfs.failed() {
bail_coded!(ErrorCode::Stg046);
}
if wal.as_ref().is_some_and(WalWriter::failed) {
bail_coded!(ErrorCode::Wal007);
}
}
#[cfg(target_arch = "wasm32")]
let _ = ctx;
Ok(())
}
// ─── Fact size validation (moved to WAL serialization) ────────────────────────
// ─── Minigraf ─────────────────────────────────────────────────────────────────
/// The primary embedded graph database handle.
///
/// `Minigraf` is cheap to clone — all clones share the same underlying database.
///
/// # File-backed usage
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))] {
/// use minigraf::db::Minigraf;
///
/// let db = Minigraf::open("mydb.graph").unwrap();
/// db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap();
/// # }
/// ```
///
/// # In-memory usage
/// ```
/// use minigraf::db::Minigraf;
///
/// let db = Minigraf::in_memory().unwrap();
/// db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap();
/// ```
///
/// # Fact Size Limit (file-backed databases only)
///
/// Each fact persisted to a `.graph` file must serialise to at most
/// 4 080 bytes (the per-page capacity limit).
///
/// In practice, `Value::String` content is limited to roughly **3 900–4 000 bytes**
/// depending on entity and attribute name lengths.
///
/// Facts that exceed this limit are rejected at insertion time with a descriptive
/// error. This check does **not** apply to `Minigraf::in_memory()`.
///
/// ## Workarounds for large payloads
///
/// - **External blob reference** — store the payload in a file or object store
/// and record its path, URL, or content-addressed hash as a `Value::String`:
/// ```text
/// (transact [[:doc123 :blob/sha256 "a3f5c9..."]])
/// ```
/// - **Entity decomposition** — split large values across multiple facts using
/// a continuation-entity pattern.
/// - **In-memory database** — `Minigraf::in_memory()` has no fact size limit
/// and is suitable for workloads that do not require persistence.
#[derive(Clone)]
pub struct Minigraf {
inner: Arc<Inner>,
}
impl Minigraf {
// ── Constructors ─────────────────────────────────────────────────────────
/// Open or create a file-backed database with default options.
///
/// A sidecar WAL file (`<path>.wal`) is created alongside the main file.
/// Any existing WAL from a previous crash is replayed automatically.
///
/// # Errors
///
/// Returns an error if the file cannot be opened, the header is corrupt,
/// or WAL replay fails.
#[cfg(not(target_arch = "wasm32"))]
pub fn open(path: impl AsRef<Path>) -> Result<Self, MinigrafError> {
Self::open_with_options(path, OpenOptions::default())
}
/// Open or create a file-backed database with custom options.
///
/// # Errors
///
/// Returns an error if the file cannot be opened, the header is corrupt,
/// or WAL replay fails.
#[cfg(not(target_arch = "wasm32"))]
pub fn open_with_options(
path: impl AsRef<Path>,
opts: OpenOptions,
) -> Result<Self, MinigrafError> {
Self::open_with_options_inner(path, opts).map_err(MinigrafError::from)
}
#[cfg(not(target_arch = "wasm32"))]
fn open_with_options_inner(path: impl AsRef<Path>, opts: OpenOptions) -> Result<Self> {
let db_path = path.as_ref().to_path_buf();
// Derive WAL path: "<db_path>.wal"
let wal_path = Self::wal_path_for(&db_path);
// Open the main .graph file. The WAL's base generation (if a WAL exists)
// decides which meta page to trust when only one is valid.
let mode = if opts.read_only {
LockMode::Shared
} else {
LockMode::Exclusive
};
let backend = FileBackend::open_with(&db_path, opts.allow_unlocked, mode)?;
let wal_base = if wal_path.exists() {
crate::wal::WalReader::open(&wal_path)?.base_generation()
} else {
None
};
let mut pfs = if opts.read_only {
PersistentFactStorage::open_read_only(backend, opts.page_cache_size, wal_base)?
} else {
PersistentFactStorage::open(backend, opts.page_cache_size, wal_base)?
};
// Share the fact storage
let fact_storage = pfs.storage().clone();
// Replay any existing WAL entries before opening the writer
let wal_entry_count = Self::replay_wal(&wal_path, &fact_storage, &pfs)?;
if opts.read_only {
// The WAL was applied in memory; it is neither written nor deleted.
return Ok(Self::from_parts(
fact_storage,
WriteContext::ReadOnly { pfs },
opts,
));
}
// Open the WAL writer only if the WAL file already exists from a previous session.
// Otherwise, create it lazily on the first write.
let wal = if wal_path.exists() {
// A WAL is deleted only after a meta of a later generation than
// its base is durable: the first checkpoint commits one even with
// nothing to write. A large transaction that crashed left pages of
// `g + 1` behind this WAL, and without it a file with one valid
// meta slot would be refused (#550 spec §4.5).
pfs.force_dirty();
Some(WalWriter::open_or_create_at(
&wal_path,
opts.synchronous,
pfs.generation(),
)?)
} else {
None
};
let ctx = WriteContext::File {
pfs,
wal,
db_path,
wal_entry_count,
};
Ok(Self::from_parts(fact_storage, ctx, opts))
}
fn from_parts(fact_storage: FactStorage, ctx: WriteContext, options: OpenOptions) -> Self {
Minigraf {
inner: Arc::new(Inner {
fact_storage,
rules: Arc::new(RwLock::new(RuleRegistry::new())),
functions: Arc::new(Functions::with_builtins()),
write_lock: Mutex::new(ctx),
options,
}),
}
}
/// Fail with API-014 if this handle was opened read-only.
fn reject_if_read_only(&self, op: &str) -> Result<()> {
if self.inner.options.read_only {
bail_coded!(ErrorCode::Api014, op);
}
Ok(())
}
/// Create an in-memory database (no WAL, no persistence). Suitable for tests and REPL.
///
/// # Errors
///
/// Returns an error if the in-memory storage backend fails to initialise.
pub fn in_memory() -> Result<Self, MinigrafError> {
Self::in_memory_with_options(OpenOptions::default())
}
/// Create an in-memory database with custom options.
///
/// Note: WAL-related options are ignored for in-memory databases, as is
/// `page_cache_size` (see [`OpenOptions::page_cache_size`]).
///
/// # Errors
///
/// Returns an error if the in-memory storage backend fails to initialise.
pub fn in_memory_with_options(opts: OpenOptions) -> Result<Self, MinigrafError> {
Self::in_memory_with_options_inner(opts).map_err(MinigrafError::from)
}
fn in_memory_with_options_inner(opts: OpenOptions) -> Result<Self> {
let backend = MemoryBackend::new();
let pfs = PersistentFactStorage::new(backend, memory_page_cache_capacity(&opts))?;
let fact_storage = pfs.storage().clone();
// For in-memory databases we don't need the PFS beyond initialisation;
// we just use the shared FactStorage directly.
drop(pfs);
Ok(Self::from_parts(fact_storage, WriteContext::Memory, opts))
}
// ── WAL replay helper ────────────────────────────────────────────────────
/// Replay any WAL entries that are newer than the main file's checkpoint.
///
/// Returns the number of entries replayed (used to seed `wal_entry_count`).
#[cfg(not(target_arch = "wasm32"))]
fn replay_wal(
wal_path: &Path,
fact_storage: &FactStorage,
pfs: &PersistentFactStorage<FileBackend>,
) -> Result<usize> {
if !wal_path.exists() {
return Ok(0);
}
let mut reader = crate::wal::WalReader::open(wal_path)?;
let entries = reader.read_entries()?;
let last_checkpointed = pfs.last_checkpointed_tx_count();
let mut replayed = 0;
for entry in &entries {
if entry.tx_count <= last_checkpointed {
// Already present in the main file; skip.
continue;
}
let _ = fact_storage.load_facts(entry.facts.iter().cloned())?;
#[allow(clippy::arithmetic_side_effects)]
{
replayed += 1;
}
}
// Re-synchronise tx_counter to the maximum tx_count across all facts
fact_storage.restore_tx_counter()?;
Ok(replayed)
}
// ── Execute ──────────────────────────────────────────────────────────────
/// Execute a Datalog command as a self-contained implicit transaction.
///
/// For file-backed databases, the WAL entry is written **before** facts are
/// applied to the in-memory store. A successful return means the facts are in
/// both the WAL and the in-memory store; a crash after this call returns will
/// replay the facts on next open.
///
/// If the WAL write fails, an error is returned and the in-memory store is
/// left unchanged. The WAL may then end in a partial entry, so later writes
/// through this handle fail with WAL-007 until the database is reopened or
/// a [`checkpoint`](Self::checkpoint) succeeds; reads keep working. Whether
/// the failed transaction is durable is unknown: after a reopen it is there
/// in full or not at all.
///
/// Returns `Err` if called from the same thread that holds an active
/// `WriteTransaction` (use `tx.execute()` instead).
///
/// # Errors
///
/// Returns an error if:
/// - A `WriteTransaction` is already active on **this thread** (deadlock prevention).
/// - Parsing fails.
/// - Execution fails.
/// - WAL write fails (file-backed databases).
pub fn execute(&self, input: &str) -> Result<QueryResult, MinigrafError> {
self.execute_inner(input).map_err(MinigrafError::from)
}
fn execute_inner(&self, input: &str) -> Result<QueryResult> {
// Detect same-thread reentrant write (would deadlock on the Mutex).
if is_write_tx_active() {
bail_coded!(ErrorCode::Int001);
}
if let Some(kind) = statement::kind_of(input) {
return self.execute_statement(input, kind);
}
let cmd = parse_datalog_command(input)?;
match cmd {
DatalogCommand::Query(ref q) => {
check_overrides(q, &self.inner.options.allow_overrides)?;
reject_unbound_slots(q)?;
// Read-only: no lock needed
let snapshot = self.inner.fact_storage.snapshot()?;
self.read_executor(snapshot).execute(cmd)
}
DatalogCommand::Rule(_) => {
// Rule registration is a write: it mutates the shared
// RuleRegistry, so it runs under write_lock (no WAL needed).
let _ctx = self
.inner
.write_lock
.lock()
.map_err(|_| err_coded!(ErrorCode::Api001))?;
let executor = DatalogExecutor::new_with_rules_and_functions(
self.inner.fact_storage.clone(),
self.inner.rules.clone(),
self.inner.functions.clone(),
);
executor.execute(cmd)
}
DatalogCommand::Transact(_) | DatalogCommand::Retract(_) => {
Err(err_coded!(ErrorCode::Api002))
}
}
}
/// Execute a `transact` or `retract` with correct WAL-first ordering:
/// 1. Read the statement (pass 1, #550) and materialize its facts (no storage mutation yet)
/// 2. Allocate tx_count + tx_id and stamp facts
/// 3. Write WAL entry FIRST — if this fails, FactStorage is unchanged
/// 4. Apply facts to shared FactStorage
fn execute_statement(&self, input: &str, kind: Kind) -> Result<QueryResult> {
// Before the lock, as parsing is: a malformed statement never waits.
// Its materialisation and window errors come with its facts, below.
let statement = statement::read_statement(
input,
kind,
crate::graph::types::tx_id_now(),
self.chunk_facts(),
)?;
self.reject_if_read_only(kind.name())?;
{
let mut ctx = self
.inner
.write_lock
.lock()
.map_err(|_| err_coded!(ErrorCode::Api001))?;
#[cfg(not(target_arch = "wasm32"))]
if statement.is_large() && matches!(*ctx, WriteContext::File { .. }) {
return self.execute_large(&mut ctx, statement, kind);
}
let stamped = statement.facts()?;
let is_retract = kind == Kind::Retract;
// Before allocating: a rejected transaction takes no tx_count.
let tx_id = crate::graph::types::tx_id_now();
crate::graph::storage::check_valid_windows(&stamped, tx_id)?;
crate::graph::storage::check_one_window_per_triple(&stamped)?;
refuse_if_failed(&ctx)?;
let tx_count = self.inner.fact_storage.allocate_tx_count();
let stamped: Vec<Fact> = stamped
.into_iter()
.map(|mut f| {
f.tx_id = tx_id;
f.tx_count = tx_count;
// Fix valid_from if it was left as the sentinel
if f.asserted && f.valid_from == VALID_FROM_USE_TX_TIME {
f.valid_from = tx_id.cast_signed();
}
f
})
.collect();
// WAL write includes size validation — no separate check needed.
// Write WAL BEFORE applying to shared FactStorage.
// If this fails, FactStorage is still unchanged — clean rollback.
let should_checkpoint = WriteTransaction::wal_write_stamped_batch(
&mut ctx,
&self.inner.options,
tx_count,
&stamped,
)?;
// WAL succeeded — now apply facts to shared FactStorage, in one
// batch so no query sees part of the transaction (#554).
let _ = self.inner.fact_storage.load_facts(stamped)?;
// Trigger auto-checkpoint AFTER facts are in FactStorage so the
// checkpoint captures the newly written facts.
if should_checkpoint {
Minigraf::do_checkpoint(&self.inner.fact_storage, &mut ctx)?;
}
// Return the same QueryResult the executor would have returned.
if is_retract {
Ok(QueryResult::Retracted(tx_id))
} else {
Ok(QueryResult::Transacted(tx_id))
}
}
}
/// A statement with more facts than one chunk, on a file database (#550
/// spec §4): written a chunk at a time into copy-on-write working trees
/// and committed as a checkpoint, with no WAL entry. Its `tx_id` is the
/// time it became large.
#[cfg(not(target_arch = "wasm32"))]
fn execute_large(
&self,
ctx: &mut WriteContext,
statement: statement::Statement<'_>,
kind: Kind,
) -> Result<QueryResult> {
use crate::storage::persistent_facts::ChunkError;
let chunks = statement.chunks()?;
refuse_if_failed(ctx)?;
let WriteContext::File {
pfs,
wal,
db_path,
wal_entry_count,
} = ctx
else {
bail_coded!(ErrorCode::Int019, "a large statement without a file");
};
// The WAL guard: a crash before the commit point finds a WAL whose
// base is this generation, never an orphan `g + 1` page (§4.5).
Self::open_wal(
wal,
db_path,
self.inner.options.synchronous,
pfs.generation(),
)?;
let mut tx = pfs.begin_large(crate::graph::types::tx_id_now())?;
for chunk in chunks {
let written = match chunk {
Ok(mut chunk) => pfs.write_large_chunk(&mut tx, &mut chunk),
Err(e) => Err(ChunkError::Statement(e)),
};
if let Err(ChunkError::Statement(e) | ChunkError::Failure(e)) = written {
pfs.rollback_large(tx);
return Err(e);
}
}
let tx_id = tx.tx_id();
pfs.commit_large(tx)?;
Self::delete_wal(wal, db_path, wal_entry_count)?;
Ok(match kind {
Kind::Retract => QueryResult::Retracted(tx_id),
Kind::Transact => QueryResult::Transacted(tx_id),
})
}
/// The WAL writer, opening the file (or creating it with the header only,
/// base generation `generation`) if it is not open.
#[cfg(not(target_arch = "wasm32"))]
fn open_wal<'w>(
wal: &'w mut Option<WalWriter>,
db_path: &Path,
sync: SyncMode,
generation: u64,
) -> Result<&'w mut WalWriter> {
if wal.is_none() {
let wal_path = Self::wal_path_for(db_path);
*wal = Some(WalWriter::open_or_create_at(&wal_path, sync, generation)?);
}
wal.as_mut().ok_or_else(|| err_coded!(ErrorCode::Api009))
}
/// The statement chunk size (`OpenOptions::transaction_chunk_facts`).
fn chunk_facts(&self) -> usize {
statement::tx_chunk_facts(self.inner.options.transaction_chunk_facts)
}