powdb-storage 0.29.2

Slotted-page heap, B+tree indexes, and WAL — pure-Rust storage engine for PowDB
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
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
1001
1002
1003
1004
use rustc_hash::FxHashMap;
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};

const VIEW_FILE: &str = crate::data_dir::VIEW_REGISTRY_FILE;
const VIEW_MAGIC: &[u8; 4] = b"BVIW";
const VIEW_VERSION: u16 = 1;

#[cfg(test)]
thread_local! {
    static VIEW_PERSIST_FAIL_BEFORE_RENAME: std::cell::Cell<bool> =
        const { std::cell::Cell::new(false) };
    static VIEW_PERSIST_FAIL_AFTER_RENAME: std::cell::Cell<bool> =
        const { std::cell::Cell::new(false) };
}

#[cfg(test)]
fn take_view_persist_fail_before_rename() -> bool {
    VIEW_PERSIST_FAIL_BEFORE_RENAME.with(|failpoint| {
        let fail = failpoint.get();
        failpoint.set(false);
        fail
    })
}

#[cfg(test)]
fn take_view_persist_fail_after_rename() -> bool {
    VIEW_PERSIST_FAIL_AFTER_RENAME.with(|failpoint| {
        let fail = failpoint.get();
        failpoint.set(false);
        fail
    })
}

struct ViewPersistError {
    source: io::Error,
    published: bool,
}

impl ViewPersistError {
    fn before_publication(source: io::Error) -> Self {
        Self {
            source,
            published: false,
        }
    }

    fn after_publication(source: io::Error) -> Self {
        Self {
            source,
            published: true,
        }
    }

    fn into_io(self) -> io::Error {
        self.source
    }
}

/// Definition of a materialized view.
#[derive(Debug, Clone)]
pub struct ViewDef {
    /// View name (used as the backing table name too).
    pub name: String,
    /// Source PowQL query text. Re-executed on refresh.
    pub query: String,
    /// Tables this view depends on. Mutations to any of these mark the view
    /// dirty.
    pub depends_on: Vec<String>,
    /// Whether the cached result set is stale.
    pub dirty: bool,
}

/// Registry of all materialized views. Lives alongside the `Catalog` in the
/// `Engine` struct. Provides dirty-tracking and persistence.
pub struct ViewRegistry {
    views: FxHashMap<String, ViewDef>,
    /// Reverse index: base table name → list of view names that depend on it.
    /// Maintained in sync with `views` on every register/unregister.
    deps: FxHashMap<String, Vec<String>>,
    data_dir: PathBuf,
}

impl ViewRegistry {
    /// Create a new empty registry.
    pub fn new(data_dir: &Path) -> Self {
        ViewRegistry {
            views: FxHashMap::default(),
            deps: FxHashMap::default(),
            data_dir: data_dir.to_path_buf(),
        }
    }

    /// Open an existing registry from disk, or return an empty one if no
    /// views file exists.
    pub fn open(data_dir: &Path) -> io::Result<Self> {
        let path = data_dir.join(VIEW_FILE);
        if !path.exists() {
            return Ok(Self::new(data_dir));
        }
        let defs = read_view_file(&path)?;
        let mut reg = Self::new(data_dir);
        for def in defs {
            reg.insert_def(def);
        }
        Ok(reg)
    }

    /// Register a new view. Does NOT create the backing table or run the
    /// query — the executor handles that.
    pub fn register(&mut self, def: ViewDef) -> io::Result<()> {
        if self.views.contains_key(&def.name) {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                format!("view '{}' already exists", def.name),
            ));
        }
        let name = def.name.clone();
        self.insert_def(def);
        if let Err(e) = self.persist_for_lifecycle() {
            if !e.published {
                self.remove_def(&name);
            }
            return Err(e.into_io());
        }
        Ok(())
    }

    /// Remove a view from the registry. Does NOT drop the backing table.
    pub fn unregister(&mut self, name: &str) -> io::Result<()> {
        let def = self.remove_def(name).ok_or_else(|| {
            io::Error::new(io::ErrorKind::NotFound, format!("view '{name}' not found"))
        })?;
        if let Err(e) = self.persist_for_lifecycle() {
            if !e.published {
                self.insert_def(def);
            }
            return Err(e.into_io());
        }
        Ok(())
    }

    /// Look up a view by name.
    pub fn get(&self, name: &str) -> Option<&ViewDef> {
        self.views.get(name)
    }

    /// Check whether `name` is a registered materialized view.
    #[inline]
    pub fn is_view(&self, name: &str) -> bool {
        self.views.contains_key(name)
    }

    /// Mark a view as dirty (needs refresh before next read), writing the flag
    /// through to `views.bin`.
    ///
    /// The flag has to reach disk or it does not exist: it lived in memory
    /// only, so mutating a base table and then exiting the process lost it,
    /// and the view came back CLEAN over pre-mutation rows and served them
    /// forever. Nothing after the restart could notice — the flag is the only
    /// record that a refresh is owed.
    ///
    /// Only the `false` → `true` transition writes. Every subsequent mutation
    /// finds the flag already set and costs nothing, so the price is at most
    /// one small write per refresh cycle rather than one per write statement.
    ///
    /// On a write failure the in-memory flag stays dirty — the safe value —
    /// and the error is returned. Callers must not treat it as success: a view
    /// whose dirty flag was not recorded is exactly the bug above.
    pub fn mark_dirty(&mut self, view_name: &str) -> io::Result<()> {
        let changed = match self.views.get_mut(view_name) {
            Some(def) if !def.dirty => {
                def.dirty = true;
                true
            }
            _ => false,
        };
        if changed {
            self.persist()
        } else {
            Ok(())
        }
    }

    /// Set the dirty flag in memory only, leaving `views.bin` untouched.
    ///
    /// For callers whose whole contract is that they do not modify the
    /// database: engine open marks a view with an unparseable source dirty so
    /// reads report that error instead of serving unrecomputable rows, and a
    /// read-only open does that over a directory it must leave byte-identical
    /// (and which may sit on read-only storage). The state is rederived on
    /// every open, so nothing is lost by not persisting it.
    pub fn mark_dirty_in_memory(&mut self, view_name: &str) {
        if let Some(def) = self.views.get_mut(view_name) {
            def.dirty = true;
        }
    }

    /// Mark a view as clean after a successful refresh, writing the flag
    /// through to `views.bin`.
    ///
    /// The caller must have made the refreshed contents durable first. This
    /// records "the stored rows are current"; if the rows it refers to are
    /// still only buffered, a crash in between leaves a clean flag over stale
    /// rows, which is the wrong-answer direction.
    ///
    /// On a write failure the in-memory flag is put back to dirty so it agrees
    /// with what is still on disk, and the error is returned: an extra refresh
    /// is cheap, a silently stale view is not.
    pub fn mark_clean(&mut self, view_name: &str) -> io::Result<()> {
        let changed = match self.views.get_mut(view_name) {
            Some(def) if def.dirty => {
                def.dirty = false;
                true
            }
            _ => false,
        };
        if !changed {
            return Ok(());
        }
        if let Err(e) = self.persist() {
            if let Some(def) = self.views.get_mut(view_name) {
                def.dirty = true;
            }
            return Err(e);
        }
        Ok(())
    }

    /// Clear the dirty flag in memory only, leaving `views.bin` untouched.
    ///
    /// For a refresh inside an explicit transaction, where there is nothing to
    /// commit yet and so no point at which the refreshed rows are known to be
    /// durable. Leaving the on-disk flag dirty costs one redundant refresh
    /// after the next open and can never serve a stale row.
    pub fn mark_clean_in_memory(&mut self, view_name: &str) {
        if let Some(def) = self.views.get_mut(view_name) {
            def.dirty = false;
        }
    }

    /// Check whether a view needs refresh.
    #[inline]
    pub fn is_dirty(&self, view_name: &str) -> bool {
        self.views.get(view_name).is_some_and(|d| d.dirty)
    }

    /// Mark all views that depend on `table` as dirty, writing the flags
    /// through to `views.bin`. Called by the executor on INSERT/UPDATE/DELETE
    /// on a base table.
    ///
    /// Returns immediately (no-op) when no views exist or no views depend
    /// on the given table — the hot path for tables with no dependents is
    /// a single `FxHashMap::get` returning `None`.
    ///
    /// This runs on every write to a table that does have views, so it must
    /// not put a file write in the write path. It does not: only a view that
    /// is currently clean is a transition, and after the first mutation
    /// following a refresh there are none, so the steady state is a hash
    /// lookup and a scan of a short name list with no allocation and no I/O.
    /// The write happens at most once per refresh cycle.
    ///
    /// Propagation is **transitive**. A view is itself a valid source for
    /// another view, so `V2 as V1` records `V1` in its `depends_on` and the
    /// one-level walk this used to do never reached it: mutating the base
    /// table marked `V1` dirty and left `V2` clean over `V1`'s pre-mutation
    /// contents, permanently, because nothing else ever revisits a clean view.
    /// Only a clean-to-dirty transition is enqueued, so an already-dirty layer
    /// stops the walk and the steady-state cost is unchanged.
    ///
    /// See [`ViewRegistry::mark_dirty`] for why the flag has to be on disk
    /// at all, and for the failure contract.
    #[inline]
    pub fn mark_dependents_dirty(&mut self, table: &str) -> io::Result<()> {
        // Fast exit before anything is cloned: no dependent of `table` is
        // clean, so there is no transition here and none downstream either
        // (a dirty view's own dependents were marked when it went dirty).
        let any_clean = self.deps.get(table).is_some_and(|names| {
            names
                .iter()
                .any(|n| self.views.get(n.as_str()).is_some_and(|d| !d.dirty))
        });
        if !any_clean {
            return Ok(());
        }

        // Walk the dependency graph breadth-first, enqueuing only the views
        // this call actually transitions. `dirty` doubles as the visited set,
        // so a dependency cycle terminates on the second visit instead of
        // looping.
        let mut queue: Vec<String> = vec![table.to_string()];
        while let Some(source) = queue.pop() {
            let names: Vec<String> = self.deps.get(source.as_str()).cloned().unwrap_or_default();
            for name in names {
                match self.views.get_mut(name.as_str()) {
                    Some(def) if !def.dirty => {
                        def.dirty = true;
                        queue.push(name);
                    }
                    _ => {}
                }
            }
        }
        self.persist()
    }

    /// Every view that depends on `source`, directly or through another view.
    ///
    /// Sorted, so a caller that puts these in a message gets a stable order
    /// rather than whatever the hash map happened to yield.
    pub fn dependents_of(&self, source: &str) -> Vec<String> {
        let mut found: Vec<String> = Vec::new();
        let mut queue: Vec<String> = vec![source.to_string()];
        while let Some(current) = queue.pop() {
            for name in self.deps.get(current.as_str()).into_iter().flatten() {
                if !found.iter().any(|seen| seen == name) {
                    found.push(name.clone());
                    queue.push(name.clone());
                }
            }
        }
        found.sort();
        found
    }

    /// List all view names.
    pub fn list_views(&self) -> Vec<&str> {
        self.views.keys().map(|k| k.as_str()).collect()
    }

    /// Validate that every registered materialized view still has its backing
    /// table in the catalog.
    ///
    /// This is deliberately narrower than a full view-health check. A dirty
    /// view, a view whose source table was dropped, or a normal table whose
    /// name is absent from the registry can all be legitimate states handled
    /// elsewhere. The split-brain state this catches is more fundamental:
    /// `views.bin` says a name is a materialized view, but the catalog no
    /// longer has the backing table that stores its rows. Opening such a
    /// database as if it were healthy would turn a failed lifecycle operation
    /// into a delayed, confusing query-time error.
    pub fn validate_backing_tables(&self, catalog: &crate::catalog::Catalog) -> io::Result<()> {
        let mut missing: Vec<&str> = self
            .views
            .keys()
            .map(|name| name.as_str())
            .filter(|name| catalog.schema(name).is_none())
            .collect();
        if missing.is_empty() {
            return Ok(());
        }
        missing.sort_unstable();
        Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "{} registers materialized view{} {} but the catalog has no backing table{}; \
                 restore the missing table file/catalog entry from backup, or repair by \
                 removing/recreating the view after taking an operator-approved copy of the \
                 data directory",
                self.data_dir.join(VIEW_FILE).display(),
                if missing.len() == 1 { "" } else { "s" },
                missing.join(", "),
                if missing.len() == 1 { "" } else { "s" }
            ),
        ))
    }

    // ─── Internal ────────────────────────────────────────────────

    fn insert_def(&mut self, def: ViewDef) {
        let name = def.name.clone();
        for table in &def.depends_on {
            self.deps
                .entry(table.clone())
                .or_default()
                .push(name.clone());
        }
        self.views.insert(name, def);
    }

    fn remove_def(&mut self, name: &str) -> Option<ViewDef> {
        let def = self.views.remove(name)?;
        for table in &def.depends_on {
            if let Some(list) = self.deps.get_mut(table) {
                list.retain(|v| v != name);
                if list.is_empty() {
                    self.deps.remove(table);
                }
            }
        }
        Some(def)
    }

    /// Durable write-temp-then-rename, matching `catalog.rs`.
    ///
    /// The directory fsync after the rename is load-bearing, not ceremony: the
    /// whole point of persisting the dirty flag is that it survives a crash, and
    /// on ext4/xfs a rename can be reordered past a power loss even though the
    /// temp file's own contents were synced. Without it the flag could be
    /// written, acknowledged, and then not be there on the next open, which is
    /// exactly the stale-view bug this file exists to prevent.
    fn persist(&self) -> io::Result<()> {
        self.persist_for_lifecycle()
            .map_err(ViewPersistError::into_io)
    }

    fn persist_for_lifecycle(&self) -> Result<(), ViewPersistError> {
        let path = self.data_dir.join(VIEW_FILE);
        let tmp = self.data_dir.join(format!("{VIEW_FILE}.tmp"));
        let defs: Vec<&ViewDef> = self.views.values().collect();
        write_view_file(&tmp, &defs).map_err(ViewPersistError::before_publication)?;
        #[cfg(test)]
        if take_view_persist_fail_before_rename() {
            return Err(ViewPersistError::before_publication(io::Error::other(
                "injected view registry failure before rename",
            )));
        }
        fs::rename(&tmp, &path).map_err(ViewPersistError::before_publication)?;
        #[cfg(test)]
        if take_view_persist_fail_after_rename() {
            return Err(ViewPersistError::after_publication(io::Error::other(
                "injected view registry failure after rename",
            )));
        }
        crate::catalog::sync_directory(&self.data_dir)
            .map_err(ViewPersistError::after_publication)?;
        Ok(())
    }
}

// ─── Binary format ──────────────────────────────────────────────────────
//
// Layout:
//   magic       [4]    = "BVIW"
//   version     u16    = 1
//   n_views     u32
//   for each view:
//     name_len    u32
//     name        utf8
//     query_len   u32
//     query       utf8
//     n_deps      u16
//     for each dep:
//       dep_len   u32
//       dep_name  utf8
//     dirty       u8

fn write_view_file(path: &Path, defs: &[&ViewDef]) -> io::Result<()> {
    let mut buf: Vec<u8> = Vec::with_capacity(256);
    buf.extend_from_slice(VIEW_MAGIC);
    buf.extend_from_slice(&VIEW_VERSION.to_le_bytes());
    buf.extend_from_slice(&(defs.len() as u32).to_le_bytes());

    for def in defs {
        let name = def.name.as_bytes();
        buf.extend_from_slice(&(name.len() as u32).to_le_bytes());
        buf.extend_from_slice(name);

        let query = def.query.as_bytes();
        buf.extend_from_slice(&(query.len() as u32).to_le_bytes());
        buf.extend_from_slice(query);

        buf.extend_from_slice(&(def.depends_on.len() as u16).to_le_bytes());
        for dep in &def.depends_on {
            let d = dep.as_bytes();
            buf.extend_from_slice(&(d.len() as u32).to_le_bytes());
            buf.extend_from_slice(d);
        }

        buf.push(if def.dirty { 1 } else { 0 });
    }

    let mut f = fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(path)?;
    f.write_all(&buf)?;
    f.sync_data()?;
    Ok(())
}

fn read_view_file(path: &Path) -> io::Result<Vec<ViewDef>> {
    let mut f = fs::File::open(path)?;
    let mut buf = Vec::new();
    f.read_to_end(&mut buf)?;

    let mut pos = 0usize;
    if buf.len() < 10 || &buf[0..4] != VIEW_MAGIC {
        return Err(io::Error::new(io::ErrorKind::InvalidData, "bad view magic"));
    }
    pos += 4;
    let version = u16::from_le_bytes(
        buf[pos..pos + 2]
            .try_into()
            .expect("invariant: buf.len() >= 10 checked above covers the 2-byte version field"),
    );
    pos += 2;
    if version != VIEW_VERSION {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("unsupported view version: {version}"),
        ));
    }
    let n_views = u32::from_le_bytes(
        buf[pos..pos + 4]
            .try_into()
            .expect("invariant: buf.len() >= 10 checked above covers the 4-byte n_views field"),
    ) as usize;
    pos += 4;

    let mut defs = Vec::with_capacity(n_views);
    for _ in 0..n_views {
        let name = read_str(&buf, &mut pos)?;
        let query = read_str(&buf, &mut pos)?;

        let n_deps = read_u16(&buf, &mut pos)? as usize;
        let mut depends_on = Vec::with_capacity(n_deps);
        for _ in 0..n_deps {
            depends_on.push(read_str(&buf, &mut pos)?);
        }

        let dirty = read_u8(&buf, &mut pos)? != 0;
        defs.push(ViewDef {
            name,
            query,
            depends_on,
            dirty,
        });
    }
    Ok(defs)
}

fn read_u8(buf: &[u8], pos: &mut usize) -> io::Result<u8> {
    if *pos >= buf.len() {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "truncated view file",
        ));
    }
    let v = buf[*pos];
    *pos += 1;
    Ok(v)
}

fn read_u16(buf: &[u8], pos: &mut usize) -> io::Result<u16> {
    if *pos + 2 > buf.len() {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "truncated view file",
        ));
    }
    let v = u16::from_le_bytes(
        buf[*pos..*pos + 2]
            .try_into()
            .expect("invariant: bounds checked immediately above (*pos + 2 <= buf.len())"),
    );
    *pos += 2;
    Ok(v)
}

fn read_str(buf: &[u8], pos: &mut usize) -> io::Result<String> {
    if *pos + 4 > buf.len() {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "truncated view file",
        ));
    }
    let len = u32::from_le_bytes(
        buf[*pos..*pos + 4]
            .try_into()
            .expect("invariant: bounds checked immediately above (*pos + 4 <= buf.len())"),
    ) as usize;
    *pos += 4;
    if *pos + len > buf.len() {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "truncated view file",
        ));
    }
    let s = std::str::from_utf8(&buf[*pos..*pos + len])
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "non-utf8 in view file"))?
        .to_string();
    *pos += len;
    Ok(s)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::catalog::Catalog;
    use crate::types::{ColumnDef, Schema, TypeId};

    fn fail_next_view_persist_before_rename() {
        VIEW_PERSIST_FAIL_BEFORE_RENAME.with(|failpoint| failpoint.set(true));
    }

    fn fail_next_view_persist_after_rename() {
        VIEW_PERSIST_FAIL_AFTER_RENAME.with(|failpoint| failpoint.set(true));
    }

    fn temp_registry(name: &str) -> ViewRegistry {
        let dir = std::env::temp_dir().join(format!("powdb_view_{name}_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        ViewRegistry::new(&dir)
    }

    fn one_int_schema(name: &str) -> Schema {
        Schema {
            table_name: name.into(),
            columns: vec![ColumnDef {
                name: "id".into(),
                type_id: TypeId::Int,
                required: true,
                position: 0,
            }],
        }
    }

    #[test]
    fn test_read_view_file_garbage_errors_not_panic() {
        // A truncated or corrupt on-disk view file (read during DB open) must
        // surface an io::Error, never panic the server.
        let dir = std::env::temp_dir().join(format!("powdb_view_garbage_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();

        let cases: Vec<Vec<u8>> = vec![
            vec![],                                   // empty
            b"BVIW".to_vec(),                         // magic only, no version/count
            b"XXXX\x01\x00\x00\x00\x00\x00".to_vec(), // wrong magic, full header len
            // valid header claiming 1 view but no view bytes follow
            {
                let mut v = b"BVIW".to_vec();
                v.extend_from_slice(&VIEW_VERSION.to_le_bytes());
                v.extend_from_slice(&1u32.to_le_bytes());
                v
            },
            // valid header, view name claims a 0xFFFFFFFF-byte string
            {
                let mut v = b"BVIW".to_vec();
                v.extend_from_slice(&VIEW_VERSION.to_le_bytes());
                v.extend_from_slice(&1u32.to_le_bytes());
                v.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
                v
            },
        ];

        for (i, bytes) in cases.iter().enumerate() {
            let p = dir.join(format!("v{i}.bin"));
            std::fs::write(&p, bytes).unwrap();
            let result = read_view_file(&p);
            assert!(
                result.is_err(),
                "expected Err for garbage view file case {i} ({bytes:?}), got Ok"
            );
        }
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn test_register_and_lookup() {
        let mut reg = temp_registry("basic");
        reg.register(ViewDef {
            name: "ActiveUsers".into(),
            query: "User filter .active = true".into(),
            depends_on: vec!["User".into()],
            dirty: false,
        })
        .unwrap();
        assert!(reg.is_view("ActiveUsers"));
        assert!(!reg.is_view("User"));
        let def = reg.get("ActiveUsers").unwrap();
        assert_eq!(def.query, "User filter .active = true");
    }

    #[test]
    fn test_dirty_tracking() {
        let mut reg = temp_registry("dirty");
        reg.register(ViewDef {
            name: "V1".into(),
            query: "T1".into(),
            depends_on: vec!["T1".into()],
            dirty: false,
        })
        .unwrap();
        assert!(!reg.is_dirty("V1"));
        reg.mark_dependents_dirty("T1").unwrap();
        assert!(reg.is_dirty("V1"));
        reg.mark_clean("V1").unwrap();
        assert!(!reg.is_dirty("V1"));
    }

    #[test]
    fn test_dirty_flag_survives_reopen() {
        // The dirty flag used to live in memory only: a mutation marked the
        // view dirty, the process exited, and the reopened registry reported
        // the view CLEAN, so every later read served pre-mutation rows with
        // no refresh and no error. Before the fix this asserted `false` after
        // the first reopen.
        let dir = std::env::temp_dir().join(format!("powdb_view_dirty_rt_{}", std::process::id()));
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        {
            let mut reg = ViewRegistry::new(&dir);
            reg.register(ViewDef {
                name: "V1".into(),
                query: "T1".into(),
                depends_on: vec!["T1".into()],
                dirty: false,
            })
            .unwrap();
            reg.mark_dependents_dirty("T1").unwrap();
        }
        {
            let mut reg = ViewRegistry::open(&dir).unwrap();
            assert!(reg.is_dirty("V1"), "dirty flag must survive process exit");
            reg.mark_clean("V1").unwrap();
        }
        // Clean is equally durable, or every restart would refresh forever.
        let reg = ViewRegistry::open(&dir).unwrap();
        assert!(!reg.is_dirty("V1"), "clean flag must survive process exit");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn test_mark_dependents_dirty_is_idempotent_after_first_transition() {
        // The write path calls this on every mutation, so only the
        // false -> true transition may touch the file. Re-marking an already
        // dirty view must not rewrite it.
        let dir =
            std::env::temp_dir().join(format!("powdb_view_transition_{}", std::process::id()));
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        let mut reg = ViewRegistry::new(&dir);
        reg.register(ViewDef {
            name: "V1".into(),
            query: "T1".into(),
            depends_on: vec!["T1".into()],
            dirty: false,
        })
        .unwrap();
        reg.mark_dependents_dirty("T1").unwrap();
        let path = dir.join(VIEW_FILE);
        assert!(path.exists(), "the transition itself must write the file");
        // Removing the file makes a subsequent write unmissable and needs no
        // mtime resolution or inode plumbing to detect: if any of the repeats
        // below persists, the file comes back.
        std::fs::remove_file(&path).unwrap();
        for _ in 0..100 {
            reg.mark_dependents_dirty("T1").unwrap();
        }
        assert!(
            !path.exists(),
            "re-marking an already dirty view must not rewrite views.bin"
        );
        // The same guard on the clean side: only the true -> false transition
        // writes.
        reg.mark_clean("V1").unwrap();
        assert!(path.exists());
        std::fs::remove_file(&path).unwrap();
        for _ in 0..100 {
            reg.mark_clean("V1").unwrap();
        }
        assert!(!path.exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn test_multi_dependency() {
        let mut reg = temp_registry("multi");
        reg.register(ViewDef {
            name: "V1".into(),
            query: "T1 inner join T2 on .id = .fk".into(),
            depends_on: vec!["T1".into(), "T2".into()],
            dirty: false,
        })
        .unwrap();
        // Mutating either dependency dirties the view
        reg.mark_dependents_dirty("T2").unwrap();
        assert!(reg.is_dirty("V1"));
    }

    #[test]
    fn test_unregister() {
        let mut reg = temp_registry("unreg");
        reg.register(ViewDef {
            name: "V1".into(),
            query: "T1".into(),
            depends_on: vec!["T1".into()],
            dirty: false,
        })
        .unwrap();
        reg.unregister("V1").unwrap();
        assert!(!reg.is_view("V1"));
        // Dependency map is cleaned up — marking T1 dirty doesn't panic
        reg.mark_dependents_dirty("T1").unwrap();
    }

    #[test]
    fn register_rolls_back_memory_when_registry_persist_fails_before_rename() {
        let mut reg = temp_registry("register_fail");
        fail_next_view_persist_before_rename();
        let error = reg
            .register(ViewDef {
                name: "V1".into(),
                query: "T1".into(),
                depends_on: vec!["T1".into()],
                dirty: false,
            })
            .unwrap_err();
        assert!(
            error
                .to_string()
                .contains("injected view registry failure before rename"),
            "expected injected registry failure, got: {error}"
        );
        assert!(
            !reg.is_view("V1"),
            "a failed register must not leave an in-memory ghost view"
        );
        assert!(
            !reg.data_dir.join(VIEW_FILE).exists(),
            "a failed register before rename must not create views.bin"
        );
    }

    #[test]
    fn unregister_rolls_back_memory_when_registry_persist_fails_before_rename() {
        let mut reg = temp_registry("unregister_fail");
        reg.register(ViewDef {
            name: "V1".into(),
            query: "T1".into(),
            depends_on: vec!["T1".into()],
            dirty: false,
        })
        .unwrap();

        fail_next_view_persist_before_rename();
        let error = reg.unregister("V1").unwrap_err();
        assert!(
            error
                .to_string()
                .contains("injected view registry failure before rename"),
            "expected injected registry failure, got: {error}"
        );
        assert!(
            reg.is_view("V1"),
            "a failed unregister must keep the in-memory registry aligned with disk"
        );
        reg.mark_dependents_dirty("T1").unwrap();
        assert!(
            reg.is_dirty("V1"),
            "rollback must also restore dependency edges"
        );

        let reopened = ViewRegistry::open(&reg.data_dir).unwrap();
        assert!(
            reopened.is_view("V1"),
            "the view must still be registered after reopening"
        );
    }

    #[test]
    fn register_keeps_published_memory_when_registry_sync_fails_after_rename() {
        let mut reg = temp_registry("register_after_rename_fail");
        fail_next_view_persist_after_rename();
        let error = reg
            .register(ViewDef {
                name: "V1".into(),
                query: "T1".into(),
                depends_on: vec!["T1".into()],
                dirty: false,
            })
            .unwrap_err();
        assert!(
            error
                .to_string()
                .contains("injected view registry failure after rename"),
            "expected injected post-rename registry failure, got: {error}"
        );
        assert!(
            reg.is_view("V1"),
            "after rename, memory must keep the potentially published register state"
        );
        let reopened = ViewRegistry::open(&reg.data_dir).unwrap();
        assert!(
            reopened.is_view("V1"),
            "the post-rename failure fixture publishes views.bin before returning the error"
        );
    }

    #[test]
    fn unregister_keeps_published_memory_when_registry_sync_fails_after_rename() {
        let mut reg = temp_registry("unregister_after_rename_fail");
        reg.register(ViewDef {
            name: "V1".into(),
            query: "T1".into(),
            depends_on: vec!["T1".into()],
            dirty: false,
        })
        .unwrap();

        fail_next_view_persist_after_rename();
        let error = reg.unregister("V1").unwrap_err();
        assert!(
            error
                .to_string()
                .contains("injected view registry failure after rename"),
            "expected injected post-rename registry failure, got: {error}"
        );
        assert!(
            !reg.is_view("V1"),
            "after rename, memory must keep the potentially published unregister state"
        );
        let reopened = ViewRegistry::open(&reg.data_dir).unwrap();
        assert!(
            !reopened.is_view("V1"),
            "the post-rename failure fixture publishes views.bin before returning the error"
        );
    }

    #[test]
    fn validate_backing_tables_accepts_dirty_views_and_normal_tables() {
        let dir =
            std::env::temp_dir().join(format!("powdb_view_validate_ok_{}", std::process::id()));
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        let mut catalog = Catalog::create(&dir).unwrap();
        catalog.create_table(one_int_schema("Base")).unwrap();
        catalog.create_table(one_int_schema("V")).unwrap();
        catalog.create_table(one_int_schema("Ordinary")).unwrap();

        let mut reg = ViewRegistry::new(&dir);
        reg.register(ViewDef {
            name: "V".into(),
            query: "MissingSource { .id }".into(),
            depends_on: vec!["MissingSource".into()],
            dirty: true,
        })
        .unwrap();

        reg.validate_backing_tables(&catalog)
            .expect("dirty views and ordinary non-view tables are not backing-table damage");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn validate_backing_tables_rejects_registered_view_without_backing_table() {
        let dir = std::env::temp_dir().join(format!(
            "powdb_view_validate_missing_{}",
            std::process::id()
        ));
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        let mut catalog = Catalog::create(&dir).unwrap();
        catalog.create_table(one_int_schema("Base")).unwrap();

        let mut reg = ViewRegistry::new(&dir);
        reg.register(ViewDef {
            name: "V".into(),
            query: "Base { .id }".into(),
            depends_on: vec!["Base".into()],
            dirty: false,
        })
        .unwrap();

        let error = reg.validate_backing_tables(&catalog).unwrap_err();
        let message = error.to_string();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
        assert!(
            message.contains("views.bin")
                && message.contains("materialized view V")
                && message.contains("no backing table")
                && message.contains("restore")
                && message.contains("recreating the view"),
            "missing backing table error must be actionable, got: {message}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn test_persist_and_reopen() {
        let dir = std::env::temp_dir().join(format!("powdb_view_persist_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        {
            let mut reg = ViewRegistry::new(&dir);
            reg.register(ViewDef {
                name: "V1".into(),
                query: "User filter .active = true".into(),
                depends_on: vec!["User".into()],
                dirty: true,
            })
            .unwrap();
        }
        // Reopen
        let reg = ViewRegistry::open(&dir).unwrap();
        assert!(reg.is_view("V1"));
        let def = reg.get("V1").unwrap();
        assert_eq!(def.query, "User filter .active = true");
        assert!(def.dirty);
        assert_eq!(def.depends_on, vec!["User".to_string()]);
    }
}