qbice 0.6.5

The Query-Based Incremental Computation Engine
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
use std::{
    self,
    collections::HashMap,
    sync::{Arc, atomic::AtomicBool},
};

use fxhash::FxBuildHasher;
use parking_lot::RwLock;
use qbice_stable_hash::Compact128;
use qbice_storage::intern::Interned;
use scc::hash_map::Entry;
use tokio::sync::{Notify, futures::OwnedNotified};

use crate::{
    Engine, ExecutionStyle, Query, TrackedEngine,
    config::{Config, WriteTransaction},
    engine::{
        computation_graph::{
            CallerInformation, QueryKind,
            database::{
                NodeDependency, NodeInfo, Observation, Snapshot, Timestamp,
            },
            slow_path::SlowPath,
            tfc_achetype::TransitiveFirewallCallees,
        },
        guard::GuardExt,
    },
    executor::CyclicError,
    query::QueryID,
};

#[derive(Debug, Default)]
pub struct CalleeOrder {
    pub order: Vec<NodeDependency>,
    pub mode: Mode,
}

impl CalleeOrder {
    pub fn push(&mut self, query_id: QueryID) {
        match self.mode {
            Mode::Single => {
                self.order.push(NodeDependency::Single(query_id));
            }

            Mode::Unordered => {
                self.order
                    .last_mut()
                    .unwrap()
                    .as_unordered_mut()
                    .unwrap()
                    .push(query_id);
            }
        }
    }

    pub fn clear(&mut self) {
        self.order.clear();
        self.mode = Mode::Single;
    }

    pub fn start_unordered_group(&mut self) {
        assert!(
            self.mode == Mode::Single,
            "Cannot start unordered callee group when already in unordered \
             mode"
        );
        self.mode = Mode::Unordered;
        self.order.push(NodeDependency::Unordered(Vec::new()));
    }

    pub fn end_unordered_group(&mut self) {
        assert!(
            self.mode == Mode::Unordered,
            "Cannot end unordered callee group when not in unordered mode"
        );
        self.mode = Mode::Single;
    }

    pub fn abort_callee(&mut self, callee: &QueryID) {
        for (i, dep) in self.order.iter_mut().enumerate() {
            match dep {
                NodeDependency::Single(qid) => {
                    if qid == callee {
                        self.order.remove(i);
                        return;
                    }
                }

                NodeDependency::Unordered(qids) => {
                    if let Some(pos) = qids.iter().position(|x| x == callee) {
                        qids.swap_remove(pos);
                        return;
                    }
                }
            }
        }
    }
}

#[derive(Debug, Default, PartialEq, Eq)]
#[repr(u8)]
pub enum Mode {
    #[default]
    Single,

    Unordered,
}

#[derive(Debug, Default)]
pub struct ComputingForwardEdges {
    pub callee_queries:
        scc::HashMap<QueryID, Option<Observation>, FxBuildHasher>,
    pub callee_order: RwLock<CalleeOrder>,
}

impl QueryComputing {
    pub fn register_calee(&self, callee: &QueryID) {
        if self.callee_info.callee_queries.contains_sync(callee) {
            return;
        }

        match self.callee_info.callee_queries.entry_sync(*callee) {
            Entry::Occupied(_) => {}

            Entry::Vacant(vacant_entry) => {
                vacant_entry.insert_entry(None);

                self.callee_info.callee_order.write().push(*callee);
            }
        }
    }

    pub fn start_unordered_callee_group(&self) {
        self.callee_info.callee_order.write().start_unordered_group();
    }

    pub fn end_unordered_callee_group(&self) {
        self.callee_info.callee_order.write().end_unordered_group();
    }

    pub fn abort_callee(&self, callee: &QueryID) {
        assert!(self.callee_info.callee_queries.remove_sync(callee).is_some());

        let mut callee_order = self.callee_info.callee_order.write();

        callee_order.abort_callee(callee);
    }

    pub fn clear_dependencies(&self) {
        self.callee_info.callee_queries.clear_sync();
        self.callee_info.callee_order.write().clear();
    }

    pub fn mark_scc(&self) {
        self.is_in_scc.store(true, std::sync::atomic::Ordering::SeqCst);
    }

    pub fn is_in_scc(&self) -> bool {
        self.is_in_scc.load(std::sync::atomic::Ordering::SeqCst)
    }

    pub fn observe_callee(
        &self,
        callee_target_id: &QueryID,
        seen_value_fingerprint: Compact128,
        seen_transitive_firewall_callees_fingerprint: Compact128,
    ) {
        let mut callee_observation = self
            .callee_info
            .callee_queries
            .get_sync(callee_target_id)
            .expect("callee should have been registered");

        *callee_observation = Some(Observation {
            seen_value_fingerprint,
            seen_transitive_firewall_callees_fingerprint,
        });
    }

    pub const fn query_kind(&self) -> QueryKind { self.query_kind }

    pub fn caller_observe_tfc_callees(
        &self,
        callee_info: &NodeInfo,
        callee_kind: QueryKind,
        callee_id: QueryID,
    ) {
        match callee_kind {
            QueryKind::Input
            | QueryKind::Executable(ExecutionStyle::ExternalInput) => {
                // input queries do not contribute to tfc archetype
            }

            QueryKind::Executable(
                ExecutionStyle::Normal | ExecutionStyle::Projection,
            ) => {
                for q in
                    callee_info.transitive_firewall_callees().iter().copied()
                {
                    let _ = self.tfc.insert_sync(q);
                }
            }
            QueryKind::Executable(ExecutionStyle::Firewall) => {
                let _ = self.tfc.insert_sync(callee_id);
            }
        }
    }
}

impl<C: Config> Engine<C> {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ComputingMode {
    Execute,
    Repair,
}

#[derive(Debug)]
pub struct QueryComputing {
    notify: Arc<Notify>,
    callee_info: ComputingForwardEdges,
    is_in_scc: Arc<AtomicBool>,
    tfc: scc::HashSet<QueryID, FxBuildHasher>,
    query_kind: QueryKind,
}

impl QueryComputing {
    pub fn notified_owned(&self) -> OwnedNotified {
        self.notify.clone().notified_owned()
    }
}

#[derive(Debug)]
pub struct PendingBackwardProjection {
    notify: Arc<Notify>,
}

impl PendingBackwardProjection {
    pub fn notified_owned(&self) -> OwnedNotified {
        self.notify.clone().notified_owned()
    }
}

pub struct BackwardProjectionLockGuard<C: Config> {
    engine: Arc<Engine<C>>,
    query_id: QueryID,
    defused: bool,
}

impl<C: Config> BackwardProjectionLockGuard<C> {
    pub fn done(&mut self) {
        if self.defused {
            return;
        }

        self.defused = true;

        let entry = self
            .engine
            .computation_graph
            .computing
            .backward_projection_lock
            .remove_sync(&self.query_id)
            .expect(
                "the pending backward projection lock guard has dropped and \
                 tried to remove existing lock, but no entry found",
            );

        entry.1.notify.notify_waiters();
    }
}

impl<C: Config> Drop for BackwardProjectionLockGuard<C> {
    fn drop(&mut self) { self.done(); }
}

pub struct Computing<C: Config> {
    computing_lock: scc::HashMap<QueryID, Arc<QueryComputing>, C::BuildHasher>,
    backward_projection_lock:
        scc::HashMap<QueryID, PendingBackwardProjection, C::BuildHasher>,
}

impl<C: Config> Computing<C> {
    pub fn new() -> Self {
        Self {
            computing_lock: scc::HashMap::with_hasher(C::BuildHasher::default()),
            backward_projection_lock: scc::HashMap::with_hasher(
                C::BuildHasher::default(),
            ),
        }
    }
}

pub struct ComputingLockGuard<C: Config> {
    engine: Arc<Engine<C>>,
    this_computing: Arc<QueryComputing>,
    query_id: QueryID,
    defused: bool,
    computing_mode: ComputingMode,
}

impl<C: Config> ComputingLockGuard<C> {
    pub const fn computing_mode(&self) -> ComputingMode { self.computing_mode }

    pub const fn query_computing(&self) -> &Arc<QueryComputing> {
        &self.this_computing
    }
}

impl<C: Config> ComputingLockGuard<C> {
    pub fn done(&mut self) {
        if self.defused {
            return;
        }

        self.defused = true;

        let entry = self
            .engine
            .computation_graph
            .computing
            .computing_lock
            .remove_sync(&self.query_id)
            .expect(
                "the computing lock guard has dropped and tried to remove \
                 existing computing lock, but no entry found",
            );

        entry.1.notify.notify_waiters();
    }
}

impl<C: Config> Drop for ComputingLockGuard<C> {
    fn drop(&mut self) { self.done(); }
}

impl<C: Config> Computing<C> {
    pub fn try_get_query_computing(
        &self,
        query_id: &QueryID,
    ) -> Option<Arc<QueryComputing>> {
        self.computing_lock.read_sync(query_id, |_, v| v.clone())
    }

    pub fn try_get_notified_computing_lock(
        &self,
        query_id: &QueryID,
    ) -> Option<(OwnedNotified, Arc<QueryComputing>)> {
        self.computing_lock
            .read_sync(query_id, |_, v| (v.notified_owned(), v.clone()))
    }
}

pub enum WriteGuard<C: Config> {
    ComputingLockGuard(ComputingLockGuard<C>),
    BackwardProjectionLockGuard(BackwardProjectionLockGuard<C>),
}

impl<C: Config> Engine<C> {
    /// Exit early if a cyclic dependency is detected.
    pub(crate) async fn exit_scc(
        &self,
        callee: &QueryID,
        caller_information: &CallerInformation,
    ) -> Result<bool, CyclicError> {
        let Some((notified, running_state)) = self
            .computation_graph
            .computing
            .try_get_notified_computing_lock(callee)
        else {
            return Ok(true);
        };

        // if there is no caller, we are at the root.
        let Some(query_caller) = caller_information.get_query_caller() else {
            return Ok(true);
        };

        let is_in_scc =
            self.check_cyclic(&running_state, &query_caller.query_id());

        // mark the caller as being in scc
        if is_in_scc {
            let computing = query_caller.computing();
            computing.mark_scc();

            return Err(CyclicError);
        }

        notified.await;

        Ok(false)
    }

    /// Checks whether the stack of computing queries contains a cycle
    #[allow(clippy::needless_pass_by_value)]
    fn check_cyclic_internal(
        &self,
        computing: &QueryComputing,
        target: &QueryID,
    ) -> bool {
        if computing.callee_info.callee_queries.contains_sync(target) {
            computing
                .is_in_scc
                .store(true, std::sync::atomic::Ordering::SeqCst);

            return true;
        }

        let mut found = false;

        // OPTIMIZE: this can be parallelized
        computing.callee_info.callee_queries.iter_sync(|k, _| {
            let Some(state) =
                self.computation_graph.computing.try_get_query_computing(k)
            else {
                return true;
            };

            found |= self.check_cyclic_internal(&state, target);

            true
        });

        if found {
            computing
                .is_in_scc
                .store(true, std::sync::atomic::Ordering::SeqCst);
        }

        found
    }

    /// Checks whether the stack of computing queries contains a cycle
    #[allow(clippy::needless_pass_by_value)]
    pub(super) fn check_cyclic(
        &self,
        running_state: &QueryComputing,
        target: &QueryID,
    ) -> bool {
        self.check_cyclic_internal(running_state, target)
    }

    pub(super) fn is_query_running_in_scc(
        caller: &CallerInformation,
    ) -> Result<(), CyclicError> {
        let Some(query_caller) =
            caller.get_query_caller().and_then(|x| x.try_computing())
        else {
            return Ok(());
        };

        if query_caller.is_in_scc() {
            return Err(CyclicError);
        }

        Ok(())
    }
}

impl<C: Config, Q: Query> Snapshot<C, Q> {
    async fn computing_lock_guard(
        mut self,
        caller_information: &CallerInformation,
    ) -> Option<(Self, ComputingLockGuard<C>)> {
        // we have to double check if we still really need to compute

        let last_verified = self.last_verified().await;

        let (mode, query_kind) = if let Some(last_verified) = last_verified {
            let kind = self.query_kind().await.unwrap();

            if last_verified.0 == caller_information.timestamp() {
                // no need to repair
                return None;
            }

            (ComputingMode::Repair, kind)
        } else {
            let executor =
                self.engine().executor_registry.get_executor_entry::<Q>();

            let style = executor.obtain_execution_style();

            (ComputingMode::Execute, QueryKind::Executable(style))
        };

        let entry = Arc::new(QueryComputing {
            callee_info: ComputingForwardEdges {
                callee_queries: scc::HashMap::with_hasher(
                    FxBuildHasher::default(),
                ),
                callee_order: RwLock::new(CalleeOrder::default()),
            },

            query_kind,
            notify: Arc::new(Notify::new()),
            is_in_scc: Arc::new(AtomicBool::new(false)),
            tfc: scc::HashSet::with_hasher(FxBuildHasher::default()),
        });

        let engine = self.engine().clone();
        let result = match engine
            .computation_graph
            .computing
            .computing_lock
            .entry_sync(*self.query_id())
        {
            Entry::Occupied(entry) => {
                // there's some computing state already try again
                let notified_owned = entry.get().notified_owned();

                drop(entry);
                drop(self);

                // wait for the existing computing to finish
                notified_owned.await;

                return None;
            }

            Entry::Vacant(vacant_entry) => {
                vacant_entry.insert_entry(entry.clone());

                Some(ComputingLockGuard {
                    engine: self.engine().clone(),
                    query_id: *self.query_id(),
                    defused: false,
                    computing_mode: mode,
                    this_computing: entry,
                })
            }
        };

        result.map(|x| (self, x))
    }

    pub(super) async fn get_backward_projection_lock_guard(
        mut self,
        caller_information: &CallerInformation,
    ) -> Option<(Self, BackwardProjectionLockGuard<C>)> {
        let pending_backward_projection =
            PendingBackwardProjection { notify: Arc::new(Notify::new()) };

        let engine = self.engine().clone();

        // double check if we really need to get the lock
        if self
            .pending_backward_projection()
            .await
            .is_none_or(|x| x.0 != caller_information.timestamp())
        {
            return None;
        }

        let result = match engine
            .computation_graph
            .computing
            .backward_projection_lock
            .entry_sync(*self.query_id())
        {
            Entry::Occupied(entry) => {
                let notified = entry.get().notified_owned();

                drop(entry);
                drop(self);

                // wait for the existing backward projection to finish
                notified.await;

                return None;
            }

            Entry::Vacant(vacant_entry) => {
                vacant_entry.insert_entry(pending_backward_projection);

                Some(BackwardProjectionLockGuard {
                    engine: self.engine().clone(),
                    query_id: *self.query_id(),
                    defused: false,
                })
            }
        };

        result.map(|x| (self, x))
    }

    pub(super) async fn get_write_guard(
        self,
        slow_path: SlowPath,
        caller_information: &CallerInformation,
    ) -> Option<(Self, WriteGuard<C>)> {
        match slow_path {
            SlowPath::Compute | SlowPath::Repair => self
                .computing_lock_guard(caller_information)
                .await
                .map(|x| (x.0, WriteGuard::ComputingLockGuard(x.1))),

            SlowPath::BaackwardProjection => self
                .get_backward_projection_lock_guard(caller_information)
                .await
                .map(|x| (x.0, WriteGuard::BackwardProjectionLockGuard(x.1))),
        }
    }
}

impl<C: Config, Q: Query> Snapshot<C, Q> {
    #[allow(clippy::option_option)]
    pub(super) async fn computing_lock_to_clean_query(
        mut self,
        clean_edges: Vec<QueryID>,
        new_tfc: Option<Interned<TransitiveFirewallCallees>>,
        caller_information: &CallerInformation,
        mut lock_guard: ComputingLockGuard<C>,
    ) {
        self.upgrade_to_exclusive().await;
        let timsestamp = caller_information.timestamp();

        async move {
            self.clean_query(clean_edges, new_tfc, timsestamp).await;

            lock_guard.done();
        }
        .guarded()
        .await;
    }

    #[inline(never)]
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn computing_lock_to_computed(
        self,
        query: Q,
        value: Q::Value,
        query_value_fingerprint: Option<Compact128>,
        mut lock_guard: ComputingLockGuard<C>,
        has_pending_backward_projection: bool,
        current_timestamp: Timestamp,
        existing_forward_edges: Option<&[NodeDependency]>,
        continuing_tx: WriteTransaction<C>,
    ) {
        let (query_kind, forward_edge_order, forward_edges, tfc_archetype) = {
            (
                lock_guard.this_computing.query_kind,
                std::mem::take(
                    &mut lock_guard
                        .this_computing
                        .callee_info
                        .callee_order
                        .write()
                        .order,
                ),
                {
                    let mut hash_map = HashMap::with_capacity_and_hasher(
                        lock_guard
                            .this_computing
                            .callee_info
                            .callee_queries
                            .len(),
                        C::BuildHasher::default(),
                    );

                    lock_guard
                        .this_computing
                        .callee_info
                        .callee_queries
                        .iter_sync(|k, v| {
                            if let Some(obs) = v {
                                hash_map.insert(*k, *obs);
                            }

                            true
                        });

                    hash_map
                },
                self.engine().create_tfc_from_scc_hash_set(
                    &lock_guard.this_computing.tfc,
                ),
            )
        };

        self.set_computed(
            query,
            value,
            query_value_fingerprint,
            query_kind,
            forward_edge_order.into(),
            forward_edges,
            tfc_archetype,
            has_pending_backward_projection,
            current_timestamp,
            existing_forward_edges,
            continuing_tx,
        )
        .await;

        lock_guard.done();
    }
}

impl<C: Config> TrackedEngine<C> {
    /// Starts recording the dependency in an "unordered mode".
    ///
    /// ## Safety
    ///
    /// This method is purely for performance optimization. This allows the
    /// engine to concurrently repair the callees during the query repair phase.
    ///
    /// Normally, the engine needs to repair the callees in the order they were
    /// registered to ensure that the casual dependencies are respected (e.g.,
    /// if query `A` says `true`, don't call query `B`).
    ///
    /// However, in some scenarios, those casual dependencies are not necessary,
    /// and the engine can safely repair those queries in any order. For
    /// example, a query that aggregates the results of multiple independent
    /// queries can safely repair those independent queries in any order.
    ///
    /// ## Caution
    ///
    /// This should be used sparingly and only when you are certain that there
    /// are no causal dependencies between the queries being called.
    ///
    /// For example, let's say we have a query ("Divide") that divides two
    /// numbers, and it calls two other input queries ("Numerator" and
    /// "Denominator"). This query panics if the denominator is zero.
    ///
    /// From that, we build an another query ("SafeDivide") that calls "Divide"
    /// but returns `None` if the denominator is zero. In order for "SafeDivide"
    /// to work it checks the value of "Denominator" first, and if it's zero, it
    /// does not call "Divide" because it would panic.
    ///
    /// The above scenario is an example of a causal dependency: the value of
    /// "SafeDivide" depends on the value of "Denominator" to decide whether it
    /// can call "Divide" safely or not. By default, the engine would repair
    /// "Denominator" first, and then "Divide" if "Denominator" result does not
    /// differ.
    ///
    /// ## Panics
    ///
    /// This method will panic if called outside the context of an `Executor`
    /// computing a query or it's already in unordered mode.
    pub unsafe fn start_unordered_callee_group(&self) {
        self.caller
            .get_query_caller()
            .unwrap_or_else(|| {
                panic!(
                    "This method is only available in the context of \
                     `Executor` computing the query"
                )
            })
            .computing()
            .start_unordered_callee_group();
    }

    /// Ends recording the dependency in an "unordered mode".
    ///
    /// ## Safety
    ///
    /// See [`Self::start_unordered_callee_group`] for details.
    ///
    /// ## Panics
    ///
    /// This method will panic if called outside the context of an `Executor`
    /// computing a query or it's not in unordered mode.
    pub unsafe fn end_unordered_callee_group(&self) {
        self.caller
            .get_query_caller()
            .unwrap_or_else(|| {
                panic!(
                    "This method is only available in the context of \
                     `Executor` computing the query"
                )
            })
            .computing()
            .end_unordered_callee_group();
    }
}