Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
834 lines (761 loc) · 30.5 KB
/
Copy pathmod.rs
File metadata and controls
834 lines (761 loc) · 30.5 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
/// Storage backend abstraction for cross-platform support.
///
/// This module provides a trait-based abstraction over different storage backends,
/// allowing Minigraf to run on native platforms (file-based), WASM (IndexedDB),
/// and in-memory (testing/embedded).
///
/// Inspired by SQLite's VFS (Virtual File System) architecture.
pub mod backend;
pub(crate) mod btree;
pub mod cache;
pub(crate) mod dict;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod dir_sync;
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) mod fault;
pub(crate) mod freelist;
pub mod index;
pub(crate) mod keys;
pub(crate) mod meta;
pub(crate) mod node;
pub mod packed_pages;
pub(crate) mod page;
pub mod persistent_facts;
pub(crate) mod pins;
pub(crate) mod reader;
pub(crate) mod value_pages;
// `Minigraf::verify` / `rebuild_indexes` walk a file; not built for wasm32.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod verify;
use crate::error::{ErrorCode, bail_coded, err_coded};
use anyhow::Result;
use std::sync::Arc;
/// Read a 4-byte little-endian u32 from `bytes` at `offset`.
fn read_u32_le(bytes: &[u8], offset: usize) -> anyhow::Result<u32> {
Ok(u32::from_le_bytes(
bytes
.get(offset..offset + 4)
.ok_or_else(|| err_coded!(ErrorCode::Int036, offset, offset + 4, bytes.len()))?
.try_into()
.map_err(|_| err_coded!(ErrorCode::Int037, offset, 4))?,
))
}
/// Read an 8-byte little-endian u64 from `bytes` at `offset`.
fn read_u64_le(bytes: &[u8], offset: usize) -> anyhow::Result<u64> {
Ok(u64::from_le_bytes(
bytes
.get(offset..offset + 8)
.ok_or_else(|| err_coded!(ErrorCode::Int036, offset, offset + 8, bytes.len()))?
.try_into()
.map_err(|_| err_coded!(ErrorCode::Int037, offset, 8))?,
))
}
/// Page size for the storage engine (4KB like SQLite)
pub const PAGE_SIZE: usize = 4096;
/// Magic number for .graph files: "MGRF" (Minigraf)
pub const MAGIC_NUMBER: [u8; 4] = *b"MGRF";
/// Current file format version
pub const FORMAT_VERSION: u32 = 8;
/// Oldest file format version this library reads. Older files must first be
/// opened with Minigraf v2.x, which upgrades them to v7 (see STG-028).
pub const MIN_FORMAT_VERSION: u32 = 7;
/// fact_page_format: packed pages (v5+), in the v7 header.
#[cfg(test)]
pub const FACT_PAGE_FORMAT_PACKED: u8 = 0x02;
/// Storage backend trait.
///
/// Implementations provide platform-specific storage mechanisms:
/// - FileBackend: Native filesystem (Linux, macOS, Windows, iOS, Android)
/// - IndexedDbBackend: Browser storage (WASM)
/// - MemoryBackend: In-memory storage (testing, embedded)
pub trait StorageBackend: Send + Sync {
/// Write a page of data at the given page ID.
///
/// Page IDs start at 0. Page 0 is reserved for the file header.
/// Data must be exactly PAGE_SIZE bytes.
fn write_page(&mut self, page_id: u64, data: &[u8]) -> Result<()>;
/// Read a page of data at the given page ID.
///
/// Returns exactly PAGE_SIZE bytes.
fn read_page(&self, page_id: u64) -> Result<Vec<u8>>;
/// Sync all pending writes to stable storage.
///
/// Ensures durability - data is persisted even after crash.
fn sync(&mut self) -> Result<()>;
/// Get the total number of pages in the storage.
fn page_count(&self) -> Result<u64>;
/// True if every page below [`page_count`](Self::page_count) is stored,
/// like a file's length. False for a sparse store that drops free pages
/// (the browser buffer, #440): its `page_count` can be below a meta's.
/// Open and commit check a meta's `page_count` against the store only
/// when this is true (#497).
fn holds_every_page(&self) -> bool {
true
}
/// The bytes past the last whole page, if any: a file whose length is not
/// a multiple of `PAGE_SIZE` ends in a partial page that `page_count`
/// leaves out. Open uses it to tell a torn first write of a new file from
/// a short file that is something else (#506). Backends without a byte
/// length return `None`.
fn partial_page(&self) -> Result<Option<Vec<u8>>> {
Ok(None)
}
/// Close the storage backend.
///
/// Performs final sync and cleanup.
#[allow(dead_code)]
fn close(&mut self) -> Result<()>;
/// Get a human-readable name for this backend (for debugging).
#[allow(dead_code)]
fn backend_name(&self) -> &'static str;
}
/// The format v7 file header (84 bytes in page 0), read only to migrate a v7
/// file to v8. Format v8 replaces it with two meta pages ([`meta`]).
///
/// Layout (all fields little-endian):
/// 0..4 magic ("MGRF")
/// 4..8 version (u32)
/// 8..16 page_count (u64)
/// 16..24 node_count (u64) — reused as fact count
/// 24..32 last_checkpointed_tx_count (u64)
/// 32..40 eavt_root_page (u64)
/// 40..48 aevt_root_page (u64)
/// 48..56 avet_root_page (u64)
/// 56..64 vaet_root_page (u64)
/// 64..68 index_checksum (u32)
/// 68 fact_page_format (u8)
/// 69..72 _padding ([u8; 3])
/// 72..80 fact_page_count (u64) — new in v6
/// 80..84 header_checksum (u32) — new in v7
// Every v7 field is parsed so the layout stays documented in one place; the
// migration reads only some of them.
#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
pub struct LegacyHeaderV7 {
pub magic: [u8; 4],
pub version: u32,
pub page_count: u64,
pub node_count: u64,
pub last_checkpointed_tx_count: u64,
pub eavt_root_page: u64,
pub aevt_root_page: u64,
pub avet_root_page: u64,
pub vaet_root_page: u64,
pub index_checksum: u32,
/// fact_page_format: only 0x02 (packed, `FACT_PAGE_FORMAT_PACKED`) is
/// written or read; v1-v6 files (which could carry 0x00 unset/legacy or
/// 0x01 one-per-page) are rejected outright (STG-028), not migrated.
pub fact_page_format: u8,
pub(crate) _padding: [u8; 3],
/// Number of pages (starting at page 1) holding committed fact data.
pub fact_page_count: u64,
/// CRC32 checksum of the first 80 bytes of the header (excluding this field).
pub header_checksum: u32,
}
impl LegacyHeaderV7 {
/// An empty v7 header, for building v7 fixtures in tests.
#[cfg(test)]
pub fn new() -> Self {
LegacyHeaderV7 {
magic: MAGIC_NUMBER,
version: 7,
page_count: 1, // Just the header page initially
node_count: 0,
last_checkpointed_tx_count: 0,
eavt_root_page: 0,
aevt_root_page: 0,
avet_root_page: 0,
vaet_root_page: 0,
index_checksum: 0,
fact_page_format: FACT_PAGE_FORMAT_PACKED,
_padding: [0; 3],
fact_page_count: 0,
header_checksum: 0,
}
}
/// Serialize the header to bytes (builds v7 fixtures in tests).
#[cfg(test)]
pub fn to_bytes(self) -> Vec<u8> {
let mut b = Vec::with_capacity(84);
b.extend_from_slice(&self.magic);
b.extend_from_slice(&self.version.to_le_bytes());
b.extend_from_slice(&self.page_count.to_le_bytes());
b.extend_from_slice(&self.node_count.to_le_bytes());
b.extend_from_slice(&self.last_checkpointed_tx_count.to_le_bytes());
b.extend_from_slice(&self.eavt_root_page.to_le_bytes());
b.extend_from_slice(&self.aevt_root_page.to_le_bytes());
b.extend_from_slice(&self.avet_root_page.to_le_bytes());
b.extend_from_slice(&self.vaet_root_page.to_le_bytes());
b.extend_from_slice(&self.index_checksum.to_le_bytes());
b.push(self.fact_page_format);
b.extend_from_slice(&self._padding);
b.extend_from_slice(&self.fact_page_count.to_le_bytes());
b.extend_from_slice(&self.header_checksum.to_le_bytes());
b
}
/// Deserialize the header from bytes.
///
/// Accepts only v7+ (84-byte) headers; older versions fail with STG-028.
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
if bytes.len() < 64 {
bail_coded!(ErrorCode::Stg001, bytes.len());
}
let mut magic = [0u8; 4];
magic.copy_from_slice(
bytes
.get(0..4)
.ok_or_else(|| err_coded!(ErrorCode::Int038, "magic bytes"))?,
);
if magic != MAGIC_NUMBER {
bail_coded!(ErrorCode::Stg002);
}
let version = read_u32_le(bytes, 4)?;
if version < MIN_FORMAT_VERSION {
bail_coded!(ErrorCode::Stg028, version, MIN_FORMAT_VERSION);
}
if bytes.len() < 84 {
bail_coded!(ErrorCode::Stg005, bytes.len());
}
let page_count = read_u64_le(bytes, 8)?;
let node_count = read_u64_le(bytes, 16)?;
let last_checkpointed_tx_count = read_u64_le(bytes, 24)?;
let fact_page_count = read_u64_le(bytes, 72)?;
let header_checksum = read_u32_le(bytes, 80)?;
Ok(LegacyHeaderV7 {
magic,
version,
page_count,
node_count,
last_checkpointed_tx_count,
eavt_root_page: read_u64_le(bytes, 32)?,
aevt_root_page: read_u64_le(bytes, 40)?,
avet_root_page: read_u64_le(bytes, 48)?,
vaet_root_page: read_u64_le(bytes, 56)?,
index_checksum: read_u32_le(bytes, 64)?,
fact_page_format: *bytes
.get(68)
.ok_or_else(|| err_coded!(ErrorCode::Int038, "fact_page_format"))?,
_padding: [
*bytes
.get(69)
.ok_or_else(|| err_coded!(ErrorCode::Int038, "padding[0]"))?,
*bytes
.get(70)
.ok_or_else(|| err_coded!(ErrorCode::Int038, "padding[1]"))?,
*bytes
.get(71)
.ok_or_else(|| err_coded!(ErrorCode::Int038, "padding[2]"))?,
],
fact_page_count,
header_checksum,
})
}
/// Recognise page 0 of a v7 file.
///
/// `None` when page 0 does not start with the magic or carries version 8
/// (a damaged or pre-release v8 file). Versions older than 7 fail with
/// STG-028 and newer than 8 with STG-006. A v7 header whose own CRC fails is
/// INT-053.
pub fn detect(page0: &[u8]) -> Result<Option<Self>> {
if page0.get(0..4) != Some(&MAGIC_NUMBER[..]) {
return Ok(None);
}
let version = read_u32_le(page0, 4)?;
if version == FORMAT_VERSION {
return Ok(None);
}
let header = Self::from_bytes(page0)?;
header.validate()?;
if header.header_checksum != Self::checksum_of_bytes(page0) {
bail_coded!(ErrorCode::Int053);
}
Ok(Some(header))
}
/// CRC32 over header bytes 0..80 (the checksum field at 80..84 excluded).
#[cfg(test)]
pub fn checksum(&self) -> u32 {
Self::checksum_of_bytes(&self.to_bytes())
}
fn checksum_of_bytes(bytes: &[u8]) -> u32 {
let mut hasher = crc32fast::Hasher::new();
hasher.update(bytes.get(..80).unwrap_or(bytes));
hasher.finalize()
}
/// Number of v7 fact pages from page 1: the header field, or (for files
/// that predate it) everything below the first index root.
pub fn fact_page_count_or_derived(&self) -> u64 {
if self.fact_page_count > 0 {
return self.fact_page_count;
}
[
self.eavt_root_page,
self.aevt_root_page,
self.avet_root_page,
self.vaet_root_page,
]
.iter()
.filter(|&&p| p > 0)
.copied()
.min()
.unwrap_or(self.page_count)
.saturating_sub(1)
}
/// Validate the header.
pub fn validate(&self) -> Result<()> {
if self.magic != MAGIC_NUMBER {
bail_coded!(ErrorCode::Int039);
}
if self.version < MIN_FORMAT_VERSION {
bail_coded!(ErrorCode::Stg028, self.version, MIN_FORMAT_VERSION);
}
if self.version >= FORMAT_VERSION {
bail_coded!(ErrorCode::Stg006, self.version, FORMAT_VERSION);
}
// Validate logical relationships
if self.page_count == 0 {
bail_coded!(ErrorCode::Stg007);
}
if self.eavt_root_page != 0 && self.eavt_root_page >= self.page_count {
bail_coded!(ErrorCode::Stg008, self.eavt_root_page, self.page_count);
}
if self.fact_page_count > self.page_count {
bail_coded!(ErrorCode::Stg009, self.fact_page_count, self.page_count);
}
Ok(())
}
}
#[cfg(test)]
impl Default for LegacyHeaderV7 {
fn default() -> Self {
Self::new()
}
}
/// Reads committed (checkpointed) facts through the on-disk covering indexes.
///
/// Implemented by [`reader::OnDiskReader`] and set on `FactStorage` after every
/// open, migration and checkpoint. These are the only committed read paths the
/// query layer uses; results are in index order (eid, then iid), not insertion
/// order.
pub trait CommittedReader: Send + Sync {
/// Every committed fact (an EAVT scan).
#[cfg(test)]
fn all_facts(&self) -> Result<Vec<crate::graph::types::Fact>>;
/// Every committed fact of `entity`.
#[cfg(test)]
fn facts_for_entity(
&self,
entity: &crate::graph::types::EntityId,
) -> Result<Vec<crate::graph::types::Fact>>;
/// Every committed fact of `(entity, attribute)`.
#[cfg(test)]
fn facts_for_entity_attribute(
&self,
entity: &crate::graph::types::EntityId,
attribute: &str,
) -> Result<Vec<crate::graph::types::Fact>>;
/// Every committed fact with `attribute` (an AEVT scan).
#[cfg(test)]
fn facts_for_attribute(&self, attribute: &str) -> Result<Vec<crate::graph::types::Fact>>;
/// The committed facts of `scan` that survive net-assert among the
/// committed records with `tx_count <= as_of` (every record when `None`):
/// for each `(e, a, v)`, the assertion of its newest transaction, unless
/// that transaction holds a retraction (#379, #435).
///
/// Applying `net_asserted_facts` to these plus the pending facts gives the
/// same result as applying it to every record, because each pending fact is
/// newer than each committed one and a record can only be hidden by a newer
/// one. This default reads the history and filters it; `OnDiskReader`
/// decides on index keys and translates only the survivors.
#[cfg(test)]
fn live_facts(
&self,
scan: Scan<'_>,
as_of: Option<u64>,
) -> Result<Vec<crate::graph::types::Fact>> {
let history = match scan {
Scan::All => self.all_facts()?,
Scan::Entity(e) => self.facts_for_entity(e)?,
Scan::EntityAttribute(e, a) => self.facts_for_entity_attribute(e, a)?,
Scan::Attribute(a) => self.facts_for_attribute(a)?,
};
let in_window = history
.into_iter()
.filter(|f| as_of.is_none_or(|n| f.tx_count <= n))
.collect();
Ok(crate::graph::storage::net_asserted_facts(in_window))
}
/// Key-level access for the fact log, if this reader has keys.
fn log_source(&self) -> Option<&dyn LogSource> {
None
}
/// Key-level access for the query engine, if this reader has keys.
fn key_source(&self) -> Option<&dyn KeySource> {
None
}
}
/// The fact versions a read keeps, by transaction (#551 plan, decision 3).
#[derive(Debug, Clone)]
pub enum TxBound {
/// Every version.
All,
/// The versions with `tx_count <= n`.
Upto(u64),
/// `:as-of t` where `tx_id` does not rise with `tx_count`: committed
/// keys whose `tx_count` is in one of the sorted, disjoint, inclusive
/// ranges `committed` (the transactions with `tx_id <= t`, from the
/// DICT, which holds one `tx_id` per `tx_count`), and pending and staged
/// facts with `tx_id <= t`.
Timestamp {
t: u64,
committed: Arc<[(u64, u64)]>,
},
}
impl TxBound {
/// The bound of a counter `:as-of`, or of none.
#[cfg(test)]
pub fn of(as_of: Option<u64>) -> Self {
match as_of {
Some(n) => TxBound::Upto(n),
None => TxBound::All,
}
}
/// Whether a committed key of transaction `tx` is kept.
pub fn keeps_key(&self, tx: u64) -> bool {
match self {
TxBound::All => true,
TxBound::Upto(n) => tx <= *n,
TxBound::Timestamp { committed, .. } => {
let i = committed.partition_point(|&(_, last)| last < tx);
committed.get(i).is_some_and(|&(first, _)| first <= tx)
}
}
}
/// The newest transaction before `tx` whose committed keys are kept, if
/// any: where a walk past the newer ones seeks to.
pub fn kept_below(&self, tx: u64) -> Option<u64> {
let below = tx.checked_sub(1)?;
match self {
TxBound::All => Some(below),
TxBound::Upto(n) => Some(below.min(*n)),
TxBound::Timestamp { committed, .. } => {
let i = committed.partition_point(|&(first, _)| first <= below);
let (_, last) = *committed.get(i.checked_sub(1)?)?;
Some(last.min(below))
}
}
}
/// Whether a pending or staged fact is kept.
pub fn keeps_fact(&self, f: &crate::graph::types::Fact) -> bool {
match self {
TxBound::All => true,
TxBound::Upto(n) => f.tx_count <= *n,
TxBound::Timestamp { t, .. } => f.tx_id <= *t,
}
}
}
/// How the `tx_id`s of a generation's transactions run (#551 plan,
/// decision 6).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TxOrder {
/// Whether no `tx_id` is below the one of an earlier `tx_count`.
pub monotonic: bool,
/// The `(tx_count, tx_id)` of the newest transaction, if there is one.
pub last: Option<(u64, u64)>,
}
/// Key-level reads of one committed generation: the dictionary and the live
/// keys of each index (#473 spec §5, §6.1).
///
/// Implemented by [`reader::OnDiskReader`].
pub trait KeySource: Send + Sync {
/// `(next_eid, next_iid)` of this generation: every DICT id is below them.
fn next_ids(&self) -> (u64, u32);
/// The entity id of `entity`, if it has any committed fact.
fn eid_of(&self, entity: &crate::graph::types::EntityId) -> Result<Option<u64>>;
/// The ident id of `ident`, if it is in the dictionary.
fn iid_of(&self, ident: &str) -> Result<Option<u32>>;
/// The entity with id `eid`.
fn uuid_of(&self, eid: u64) -> Result<crate::graph::types::EntityId>;
/// Visit the UUIDs of strictly increasing, distinct committed entity ids.
/// Uses this reader's pinned generation, just as [`Self::uuid_of`] does.
/// An empty slice reads nothing; invalid ordering is `INT-049`.
/// On-disk readers share tree paths.
/// On error, `visit` may have received a prefix; discard partial hints.
fn uuids_of(
&self,
eids: &[u64],
visit: &mut dyn FnMut(u64, crate::graph::types::EntityId) -> Result<()>,
) -> Result<()>;
/// The ident with id `iid`.
fn ident_of(&self, iid: u32) -> Result<String>;
/// The long string stored at `vref`.
fn long_value(&self, vref: keys::ValueRef) -> Result<String>;
/// Where the long string `s` is stored, if a committed fact holds it.
fn long_value_ref(&self, s: &str) -> Result<Option<keys::ValueRef>>;
/// The bytes stored at `vref`: a long string's, or a long set's element
/// encoding (#316).
fn long_bytes(&self, vref: keys::ValueRef) -> Result<Vec<u8>>;
/// Where a long value with these bytes is stored, if a committed fact
/// holds it.
fn long_bytes_ref(&self, bytes: &[u8]) -> Result<Option<keys::ValueRef>>;
/// The `tx_id` of the committed transaction `tx_count`.
fn tx_id_of(&self, tx_count: u64) -> Result<u64>;
/// How this generation's `tx_id`s run; one walk of the DICT's
/// transactions per reader.
fn tx_order(&self) -> Result<TxOrder>;
/// The newest `tx_count` whose `tx_id <= t`, 0 if none. Only for a
/// generation whose `tx_order` is monotonic.
fn last_tx_at(&self, t: u64) -> Result<u64>;
/// Append to `out` the transactions with `tx_id <= t` as sorted,
/// disjoint, inclusive `tx_count` ranges.
fn tx_runs(&self, t: u64, out: &mut Vec<(u64, u64)>) -> Result<()>;
/// Whether an index has any raw key with this prefix, including historical
/// and retracted records. One seek; no search for a live version (#641).
fn any_key(&self, index: keys::Index, prefix: &[u8]) -> Result<bool>;
/// The keys of `index` that start with `prefix` and survive net-assert
/// among the versions `bound` keeps, decoded, appended to `out` in key
/// order.
///
/// Starts after the triple `resume` (from the start when `None`). Stops
/// at the first triple boundary once `max` keys are out, and returns the
/// last whole triple read, to resume after; `None` when the range is done.
/// A triple's decision therefore never spans two calls.
fn live_keys(
&self,
index: keys::Index,
prefix: &[u8],
resume: Option<&[u8]>,
bound: &TxBound,
max: usize,
out: &mut Vec<keys::KeyFact>,
) -> Result<Option<Vec<u8>>>;
}
/// Key-level access to one committed generation, for the fact log (#430).
///
/// Implemented by [`reader::OnDiskReader`]. Only EAVT and AEVT are walked.
pub trait LogSource: KeySource {
/// The `last_checkpointed_tx_count` of this generation: every committed
/// fact has a `tx_count` at or below it.
fn last_tx(&self) -> u64;
/// Visit, in key order, the keys of `index` that start with `prefix` and
/// sort after `after` (all of them when `None`), until `visit` returns false.
fn walk(
&self,
index: keys::Index,
prefix: &[u8],
after: Option<&[u8]>,
visit: &mut dyn FnMut(&[u8]) -> Result<bool>,
) -> Result<()>;
/// Translate `index` keys back into facts.
fn decode(
&self,
index: keys::Index,
keys: &[Vec<u8>],
) -> Result<Vec<crate::graph::types::Fact>>;
}
/// The facts a read covers.
#[derive(Debug, Clone, Copy)]
pub enum Scan<'a> {
/// Every fact.
All,
/// The facts of one entity.
Entity(&'a crate::graph::types::EntityId),
/// The facts of one `(entity, attribute)` pair.
EntityAttribute(&'a crate::graph::types::EntityId, &'a str),
/// The facts with one attribute.
Attribute(&'a str),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_file_header_validation() {
let header = LegacyHeaderV7::new();
assert!(header.validate().is_ok());
let mut invalid = header;
invalid.magic = *b"XXXX";
assert!(invalid.validate().is_err());
}
#[test]
fn test_format_version_is_8() {
assert_eq!(FORMAT_VERSION, 8);
}
#[test]
fn test_validate_accepts_version_7() {
let mut h = LegacyHeaderV7::new();
h.version = 7;
assert!(h.validate().is_ok());
}
#[test]
fn test_validate_rejects_version_8_legacy_header() {
// A v8 file has meta pages, not this header.
let mut h = LegacyHeaderV7::new();
h.version = 8;
assert!(h.validate().is_err());
}
#[test]
fn test_validate_page_count_must_be_positive() {
let mut h = LegacyHeaderV7::new();
h.page_count = 0;
let result = h.validate();
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("page_count"));
}
#[test]
fn test_validate_eavt_root_page_bounds() {
let mut h = LegacyHeaderV7::new();
h.page_count = 10;
h.eavt_root_page = 10; // equal to page_count, should fail
let result = h.validate();
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("eavt_root_page"));
// Should pass when 0
h.eavt_root_page = 0;
assert!(h.validate().is_ok());
// Should pass when valid
h.eavt_root_page = 5;
assert!(h.validate().is_ok());
}
#[test]
fn test_validate_fact_page_count_bounds() {
let mut h = LegacyHeaderV7::new();
h.page_count = 10;
h.fact_page_count = 11; // exceeds page_count
let result = h.validate();
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("fact_page_count"));
// Should pass when within bounds
h.fact_page_count = 5;
assert!(h.validate().is_ok());
}
#[test]
fn test_new_legacy_header_has_version_7() {
assert_eq!(LegacyHeaderV7::new().version, 7);
}
#[test]
fn detect_recognises_only_a_checksummed_v7_header() {
let mut page = vec![0u8; PAGE_SIZE];
assert!(LegacyHeaderV7::detect(&page).unwrap().is_none(), "zeros");
let mut h = LegacyHeaderV7::new();
h.page_count = 3;
h.header_checksum = h.checksum();
page[..84].copy_from_slice(&h.to_bytes());
assert!(LegacyHeaderV7::detect(&page).unwrap().is_some());
// A pre-release v8 single header is not a v7 header.
page[4..8].copy_from_slice(&8u32.to_le_bytes());
assert!(LegacyHeaderV7::detect(&page).unwrap().is_none());
page[4..8].copy_from_slice(&7u32.to_le_bytes());
page[20] ^= 1; // body changed after checksumming
let err = LegacyHeaderV7::detect(&page).unwrap_err();
assert_eq!(crate::error::MinigrafError::from(err).code(), "INT-053");
page[4..8].copy_from_slice(&5u32.to_le_bytes());
let err = LegacyHeaderV7::detect(&page).unwrap_err();
assert_eq!(crate::error::MinigrafError::from(err).code(), "STG-028");
}
#[test]
fn test_file_header_serialization_v7() {
let header = LegacyHeaderV7::new();
let bytes = header.to_bytes();
assert_eq!(bytes.len(), 84);
}
#[test]
fn test_file_header_roundtrip_v7() {
let mut header = LegacyHeaderV7::new();
header.header_checksum = 0xDEAD_BEEF;
let bytes = header.to_bytes();
let parsed = LegacyHeaderV7::from_bytes(&bytes).unwrap();
assert_eq!(parsed.header_checksum, 0xDEAD_BEEF);
}
#[test]
fn test_file_header_v7_byte_layout_all_fields() {
let mut h = LegacyHeaderV7::new();
h.page_count = 0x0102_0304_0506_0708_u64;
h.node_count = 0x1112_1314_1516_1718_u64;
h.last_checkpointed_tx_count = 0x2122_2324_2526_2728_u64;
h.eavt_root_page = 0x3132_3334_3536_3738_u64;
h.aevt_root_page = 0x4142_4344_4546_4748_u64;
h.avet_root_page = 0x5152_5354_5556_5758_u64;
h.vaet_root_page = 0x6162_6364_6566_6768_u64;
h.index_checksum = 0x7172_7374_u32;
h.fact_page_format = 0x02;
h._padding = [0x00; 3];
h.fact_page_count = 0xA1A2_A3A4_A5A6_A7A8_u64;
h.header_checksum = 0xC1C2_C3C4_u32;
let b = h.to_bytes();
assert_eq!(b.len(), 84, "v7 header must be exactly 84 bytes");
assert_eq!(&b[0..4], b"MGRF");
assert_eq!(&b[4..8], &7u32.to_le_bytes());
assert_eq!(&b[8..16], &0x0102_0304_0506_0708_u64.to_le_bytes());
assert_eq!(&b[16..24], &0x1112_1314_1516_1718_u64.to_le_bytes());
assert_eq!(&b[24..32], &0x2122_2324_2526_2728_u64.to_le_bytes());
assert_eq!(&b[32..40], &0x3132_3334_3536_3738_u64.to_le_bytes());
assert_eq!(&b[40..48], &0x4142_4344_4546_4748_u64.to_le_bytes());
assert_eq!(&b[48..56], &0x5152_5354_5556_5758_u64.to_le_bytes());
assert_eq!(&b[56..64], &0x6162_6364_6566_6768_u64.to_le_bytes());
assert_eq!(&b[64..68], &0x7172_7374_u32.to_le_bytes());
assert_eq!(b[68], 0x02);
assert_eq!(&b[69..72], &[0x00u8; 3]);
assert_eq!(&b[72..80], &0xA1A2_A3A4_A5A6_A7A8_u64.to_le_bytes());
assert_eq!(&b[80..84], &0xC1C2_C3C4_u32.to_le_bytes());
}
#[test]
fn test_file_header_v7_truncated_rejected() {
let mut bytes = vec![0u8; 80];
bytes[0..4].copy_from_slice(b"MGRF");
bytes[4..8].copy_from_slice(&7u32.to_le_bytes());
assert!(LegacyHeaderV7::from_bytes(&bytes).is_err());
}
#[test]
fn test_file_header_v7_header_checksum_roundtrip() {
let mut h = LegacyHeaderV7::new();
h.header_checksum = 42;
let bytes = h.to_bytes();
assert_eq!(bytes.len(), 84);
let parsed = LegacyHeaderV7::from_bytes(&bytes).unwrap();
assert_eq!(parsed.header_checksum, 42);
}
// ══ #359: STG-0xx regression tests ═══════════════════════════════════
//
// STG-001/005 guard byte lengths (<64/<84) that the production
// `FileBackend` path never actually produces -- it always hands
// `LegacyHeaderV7::from_bytes` a full `PAGE_SIZE` (4096-byte) buffer,
// whatever the real file's length beyond the minimum one page. These
// codes are only reachable by calling `LegacyHeaderV7::from_bytes` directly
// with a short slice, which `storage` being crate-private makes
// possible only from inside the crate -- hence unit tests here rather
// than an integration test against the public `Minigraf` API.
#[test]
fn from_bytes_too_short_returns_stg_001() {
let bytes = vec![0u8; 10]; // < 64 bytes
let err = LegacyHeaderV7::from_bytes(&bytes).expect_err("10 bytes is too short");
let coded: crate::error::MinigrafError = err.into();
assert_eq!(coded.code(), "STG-001");
}
#[test]
fn from_bytes_v7_too_short_returns_stg_005() {
let mut bytes = vec![0u8; 82]; // >= 80, < 84
bytes[0..4].copy_from_slice(b"MGRF");
bytes[4..8].copy_from_slice(&7u32.to_le_bytes()); // version = 7
let err = LegacyHeaderV7::from_bytes(&bytes).expect_err("82 bytes is too short for v7");
let coded: crate::error::MinigrafError = err.into();
assert_eq!(coded.code(), "STG-005");
}
#[test]
fn from_bytes_pre_v7_returns_stg_028() {
for version in 1u32..=6 {
let mut bytes = LegacyHeaderV7::new().to_bytes();
bytes[4..8].copy_from_slice(&version.to_le_bytes());
let err =
LegacyHeaderV7::from_bytes(&bytes).expect_err("pre-v7 header must be rejected");
let coded: crate::error::MinigrafError = err.into();
assert_eq!(coded.code(), "STG-028");
}
}
#[test]
fn validate_pre_v7_returns_stg_028() {
let mut h = LegacyHeaderV7::new();
h.version = 6;
let err = h.validate().expect_err("v6 must be rejected");
let coded: crate::error::MinigrafError = err.into();
assert_eq!(coded.code(), "STG-028");
}
}