relate-executor 1.3.0

In-memory graph and Cypher physical executor
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
//! Input-keyed memoisation of pure expressions and checks (LABS-1478).
//!
//! A stage asks the same question of the same input many times: on a
//! branching graph the arrival set is a small fraction of the candidate
//! stream, so a check that is a *function of its input alone* is paid once
//! per edge for one answer. [`Memo`] keeps the answers; [`Memoized`] puts
//! one in front of any [`NodePred`] without the kernel loops knowing; the
//! same pieces carry any other pure expression.
//!
//! **The purity contract** (what may be wrapped). The answer is determined
//! by the input key and by state fixed for the stage: one snapshot (a read
//! clause never sees its own writes), the statement's parameters, and a
//! bound proven row-invariant and deterministic by the decoder
//! ([`super::program::bound_is_row_invariant`]). Every
//! [`Admission`](super::program::Admission) program meets it by
//! construction. A check that reads the row (a bound-variable comparison,
//! LABS-1433's boundary pair), a nondeterministic call, or a write clause's
//! own-write view does **not**, and must never be wrapped. An error is
//! never cached: it propagates, so the first erroring input surfaces
//! exactly as it would unmemoised.
//!
//! **Hashing the input can cost more than the expression**, so the key
//! scheme is part of the API, in three tiers, cheapest first. A value
//! constant for the stage needs no memo: the kernels' lazy `prepared` slot
//! already evaluates it once ([`NodePred::admits`]).
//! 1. a direct-indexed table over id keys, no hashing ([`PagedBits`] for
//!    boolean answers);
//! 2. pointer identity of a borrowed, stage-pinned slice (a table plugs in
//!    through [`MemoTable`]; none is needed yet);
//! 3. a wide-value hash, only for expressions whose cost dwarfs it.
//!
//! A cheap expression is never wrapped: the probe would cost as much as
//! the work (ADR-0640 break-even rule).
//!
//! **Cost shape.** Tables follow the keys *touched*, never the row or path
//! count, and report exact bytes ([`MemoTable::heap_bytes`]). Two guards
//! keep a memo from costing more than it saves, both set by a
//! [`MemoPolicy`]: a warm-up (the first inputs of a stage
//! run unmemoised, so a small stage never allocates a table) and a
//! ceiling (past it the stage keeps answering from the function, hits
//! still served). Three safety nets bound the whole: the table's bytes are
//! charged to the retained-container meter (ADR-0463), every memo of a
//! query shares one live-bytes budget ([`MemoLive`], ADR-0657), and a memo
//! whose hit rate is below the policy floor at its one review drops its
//! table and bypasses itself. A refusal or a bypass never fails the
//! query: memoisation is an optimisation, always on.

use relate_core::{NodeId, Result};

use crate::ctx::ExecCtx;
use crate::memory::{memo_budget_bytes, DEFAULT_MEMO_BUDGET_MIB};
use crate::metrics::MemoCounters;
use crate::overlay::{memo_table_ceiling, ExecGraph, MemoLive};

use super::program::NodePred;

/// A memo's tuning: when it starts, when it gives up, how large it may
/// grow. The trigger follows the break-even `N = setup / (hit_rate * cost -
/// probe)`: an expression far costlier than a probe pays after a handful
/// of inputs, a store read after about a thousand. Starting values, to be
/// tuned from measurement.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct MemoPolicy {
    /// Inputs answered by the function before the table is first
    /// allocated: a stage that never gets this far pays one counter
    /// increment per input and nothing else.
    pub(crate) warm_up: u32,
    /// Probes after which the hit rate is reviewed once. A memo over a
    /// large key domain starts cold: its cumulative hit rate after `n`
    /// probes is about the fraction of the domain already seen, so the
    /// review must wait until the table has had time to fill, or it
    /// disables a memo that would have paid (LABS-1478: a 4096 window
    /// disabled the label memo on a 1.6M-node graph).
    pub(crate) window: u32,
    /// Below this hit rate (percent) at the review, the memo drops its
    /// table and bypasses itself: every answer was used once, so the
    /// memo costs more than it saves.
    pub(crate) min_hit_percent: u32,
    /// The table's byte ceiling for this memo.
    pub(crate) max_bytes: usize,
}

impl MemoPolicy {
    /// A store-read check (a label or property test): about 20-100 ns,
    /// under the default budget's table ceiling. Production sites take
    /// [`Self::moderate`] with the statement's configured budget.
    pub(crate) const MODERATE: Self =
        Self::moderate_for(memo_budget_bytes(DEFAULT_MEMO_BUDGET_MIB));

    /// [`Self::MODERATE`] with the table ceiling derived from `live`'s
    /// configured budget (ADR-0657).
    pub(crate) fn moderate(live: &MemoLive) -> Self {
        Self::moderate_for(live.budget())
    }

    const fn moderate_for(budget: u64) -> Self {
        Self {
            warm_up: 1024,
            window: 1 << 20,
            min_hit_percent: 10,
            max_bytes: memo_table_ceiling(budget),
        }
    }
}

/// A stage-local table from an input key to its answer.
pub(crate) trait MemoTable: Default {
    type Key: Copy;
    type Value: Clone;

    fn get(&self, key: Self::Key) -> Option<Self::Value>;
    fn insert(&mut self, key: Self::Key, value: Self::Value);
    /// The table's exact allocation, for the ceiling.
    fn heap_bytes(&self) -> usize;
}

/// Where a memo's bytes are charged: the engine's retained-container
/// meter (ADR-0463), implemented by [`ExecGraph`]. A refusal is not an
/// error to the query: the memo is an optimisation, so it stops growing.
pub(crate) trait MemoMeter {
    /// Add `added` bytes to the memo's running `total`, `Err` when the
    /// configured cap is crossed.
    fn charge(&self, total: &mut u64, added: u64) -> Result<()>;
}

impl MemoMeter for ExecGraph<'_> {
    fn charge(&self, total: &mut u64, added: u64) -> Result<()> {
        self.charge_retained(total, added)
    }
}

/// What a memo did, for PROFILE and tuning: counted after the warm-up.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct MemoStats {
    /// Inputs looked up in the table (warm-up inputs are not probes).
    pub(crate) probes: u64,
    /// Probes answered from the table.
    pub(crate) hits: u64,
    /// Answers stored.
    pub(crate) inserts: u64,
    /// Answers not stored because the meter or the ceiling refused.
    pub(crate) refused: u64,
    /// The table's allocation, bytes.
    pub(crate) bytes: u64,
    /// The memo gave up at its hit-rate review and bypasses itself.
    pub(crate) disabled: bool,
}

#[cfg(test)]
thread_local! {
    /// How many times [`Memo::stats`] ran on this thread: the zero-cost
    /// pin's witness that a non-PROFILE statement never reads a memo.
    pub(crate) static STATS_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

impl MemoStats {
    /// The PROFILE counters of one memo (ADR-0654): the same facts, the
    /// `disabled` flag counted as the sum's `disabled_count`.
    pub(crate) fn counters(self) -> MemoCounters {
        MemoCounters {
            probes: self.probes,
            hits: self.hits,
            inserts: self.inserts,
            refused: self.refused,
            bytes: self.bytes,
            disabled_count: u64::from(self.disabled),
        }
    }
}

/// The memo's lifecycle: one field in place of the separate warm-up
/// counter and frozen/disabled flags the earlier version carried, so the
/// three can no longer disagree.
#[derive(Clone, Copy, Debug)]
enum Phase {
    /// Below the policy's warm-up: the count of inputs answered by the
    /// function so far, each run unmemoised with nothing allocated.
    Warming(u32),
    /// The table is in use and growing.
    Active,
    /// A meter, the ceiling or the query budget refused an insert: the
    /// table stops growing, hits are still served.
    Frozen,
    /// The hit-rate review dropped the table and the memo bypasses
    /// itself.
    Disabled,
}

/// One stage's memo of a pure function over the table's keys — see the
/// module docs for the contract the function must meet.
pub(crate) struct Memo<T: MemoTable> {
    policy: MemoPolicy,
    /// The lifecycle phase: warming, active, frozen or disabled.
    phase: Phase,
    table: T,
    /// The table's running size as charged to the retained-container meter.
    retained: u64,
    /// Whether the one hit-rate review has run. Kept apart from `phase`
    /// because it is orthogonal: a memo can be reviewed while active or
    /// frozen, so it is a latch, not a phase.
    reviewed: bool,
    /// This memo's share of the query's live memo bytes, returned on drop.
    reserved: u64,
    live: MemoLive,
    stats: MemoStats,
}

impl<T: MemoTable> Default for Memo<T> {
    fn default() -> Self {
        Self::new(MemoPolicy::MODERATE, MemoLive::default())
    }
}

impl<T: MemoTable> Drop for Memo<T> {
    fn drop(&mut self) {
        self.release_reserved();
    }
}

/// The node-label memo: a node id to a boolean answer.
pub(crate) type NodeMemo = Memo<PagedBits>;

impl<T: MemoTable> Memo<T> {
    /// A memo under `policy`, counting its bytes against the query's
    /// shared `live` total.
    pub(crate) fn new(policy: MemoPolicy, live: MemoLive) -> Self {
        // A zero ceiling (a zero budget, ADR-0657) bypasses the memo from
        // the first input: no table is allocated and the function runs as
        // without a memo.
        let phase = if policy.max_bytes == 0 {
            Phase::Disabled
        } else {
            Phase::Warming(0)
        };
        Self {
            policy,
            phase,
            table: T::default(),
            retained: 0,
            reviewed: false,
            reserved: 0,
            live,
            stats: MemoStats::default(),
        }
    }

    /// `key`'s answer: the memoised one, or `compute()`'s — remembered
    /// when the stage is warm and the table is under its ceiling. An error
    /// is returned and never remembered.
    pub(crate) fn answer(
        &mut self,
        meter: &impl MemoMeter,
        key: T::Key,
        compute: impl FnOnce() -> Result<T::Value>,
    ) -> Result<T::Value> {
        self.answer_lazy(meter, || Some(key), compute)
    }

    /// [`Self::answer`] for a key that costs something to build: `key` runs
    /// only once the memo is warm and enabled, so a warming or bypassed
    /// memo pays one branch, not the key. `None` (an unkeyable input) is
    /// computed and never remembered.
    pub(crate) fn answer_lazy(
        &mut self,
        meter: &impl MemoMeter,
        key: impl FnOnce() -> Option<T::Key>,
        compute: impl FnOnce() -> Result<T::Value>,
    ) -> Result<T::Value> {
        match self.phase {
            Phase::Disabled => return compute(),
            Phase::Warming(seen) if seen < self.policy.warm_up => {
                self.phase = Phase::Warming(seen + 1);
                return compute();
            }
            // The warm-up is done: this input, and every later one, is a
            // probe.
            Phase::Warming(_) => self.phase = Phase::Active,
            Phase::Active | Phase::Frozen => {}
        }
        let Some(key) = key() else {
            return compute();
        };
        self.stats.probes += 1;
        if let Some(known) = self.table.get(key) {
            self.stats.hits += 1;
            return Ok(known);
        }
        let fresh = compute()?;
        self.remember(meter, key, fresh.clone());
        self.review();
        Ok(fresh)
    }

    /// Store an answer unless the memo is frozen or at its ceiling; charge
    /// the table's growth to the meter, and freeze on a refusal (the
    /// overshoot is at most one page).
    fn remember(&mut self, meter: &impl MemoMeter, key: T::Key, value: T::Value) {
        if self.is_frozen() || self.table.heap_bytes() >= self.policy.max_bytes {
            self.stats.refused += 1;
            return;
        }
        let before = self.table.heap_bytes();
        self.table.insert(key, value);
        self.stats.inserts += 1;
        let grew = self.table.heap_bytes().saturating_sub(before) as u64;
        if grew == 0 {
            return;
        }
        if meter.charge(&mut self.retained, grew).is_err() {
            self.phase = Phase::Frozen;
        }
        self.reserved += grew;
        if self.live.charge(grew) {
            self.phase = Phase::Frozen;
        }
    }

    /// The one hit-rate review, after the policy's window of probes: a
    /// memo whose answers are mostly used once drops its table and
    /// bypasses itself.
    fn review(&mut self) {
        if self.reviewed || self.stats.probes < u64::from(self.policy.window) {
            return;
        }
        self.reviewed = true;
        let floor = u64::from(self.policy.min_hit_percent);
        if self.stats.hits * 100 < self.stats.probes * floor {
            self.table = T::default();
            self.retained = 0;
            self.phase = Phase::Disabled;
            self.release_reserved();
        }
    }

    /// What the memo did so far, with the table's current allocation: the
    /// one stats reader (ADR-0654). It walks the table's size, so it runs
    /// only behind PROFILE's arm ([`crate::exec::record_memos`]) or in a
    /// test, never on the probe path.
    pub(crate) fn stats(&self) -> MemoStats {
        #[cfg(test)]
        STATS_READS.with(|reads| reads.set(reads.get() + 1));
        MemoStats {
            bytes: self.table.heap_bytes() as u64,
            disabled: self.is_disabled(),
            ..self.stats
        }
    }

    /// Whether the table has stopped growing.
    fn is_frozen(&self) -> bool {
        matches!(self.phase, Phase::Frozen)
    }

    /// Whether the memo bypasses itself (a zero ceiling or a failed review).
    fn is_disabled(&self) -> bool {
        matches!(self.phase, Phase::Disabled)
    }

    /// Return this memo's reserved share to the query's live total.
    fn release_reserved(&mut self) {
        self.live.release(self.reserved);
        self.reserved = 0;
    }

    /// The table's exact allocation.
    #[cfg(test)]
    fn heap_bytes(&self) -> usize {
        self.table.heap_bytes()
    }
}

/// Ids per page: 4096, so a page is two 64-word planes (1 KiB).
const PAGE_BITS: u32 = 12;
const PAGE_WORDS: usize = 1 << (PAGE_BITS - 6);
/// Directory entries allowed (ids below 2^28): a larger id is simply not
/// remembered, so a sparse far id cannot grow the directory.
const MAX_PAGES: usize = 1 << 16;

/// One page: which ids are answered, and what the answer is.
struct Page {
    known: [u64; PAGE_WORDS],
    value: [u64; PAGE_WORDS],
}

/// Tier 1: a paged bitmap of boolean answers, 64 node ids per word, two
/// planes (known, value). Pages allocate on first touch, so memory follows
/// the id ranges touched (1 KiB per 4096-id range), never the row or path
/// count; a probe is a directory load and a bit test — no hashing.
#[derive(Default)]
pub(crate) struct PagedBits {
    pages: Vec<Option<Box<Page>>>,
    allocated: usize,
}

impl PagedBits {
    fn split(node: NodeId) -> Option<(usize, usize, u64)> {
        let id = u64::try_from(node).ok()?;
        let page = usize::try_from(id >> PAGE_BITS).ok()?;
        let word = ((id >> 6) as usize) & (PAGE_WORDS - 1);
        (page < MAX_PAGES).then_some((page, word, 1u64 << (id & 63)))
    }
}

impl MemoTable for PagedBits {
    type Key = NodeId;
    type Value = bool;

    fn get(&self, node: NodeId) -> Option<bool> {
        let (page, word, bit) = Self::split(node)?;
        let page = self.pages.get(page)?.as_ref()?;
        (page.known[word] & bit != 0).then(|| page.value[word] & bit != 0)
    }

    fn insert(&mut self, node: NodeId, answer: bool) {
        let Some((page, word, bit)) = Self::split(node) else {
            return;
        };
        if page >= self.pages.len() {
            self.pages.resize_with(page + 1, || None);
        }
        let slot = &mut self.pages[page];
        if slot.is_none() {
            self.allocated += 1;
            *slot = Some(Box::new(Page {
                known: [0; PAGE_WORDS],
                value: [0; PAGE_WORDS],
            }));
        }
        let page = slot.as_mut().expect("page allocated above");
        page.known[word] |= bit;
        if answer {
            page.value[word] |= bit;
        }
    }

    fn heap_bytes(&self) -> usize {
        self.pages.capacity() * std::mem::size_of::<Option<Box<Page>>>()
            + self.allocated * std::mem::size_of::<Page>()
    }
}

/// A [`NodePred`] answered through a [`NodeMemo`]: the wrapped predicate's
/// own `check` is the check, called at most once per distinct node once
/// the stage is warm. The wrapper is `Copy` and monomorphic like the
/// predicate it wraps — the kernel loop's per-candidate call stays static.
#[derive(Clone, Copy)]
pub(crate) struct Memoized<P>(pub(crate) P);

/// The memoised predicate's per-run state: the wrapped predicate's own
/// prepared form beside the memo.
pub(crate) struct MemoState<T> {
    inner: T,
    memo: NodeMemo,
}

impl<T> Drop for MemoState<T> {
    /// Fold the run's memo into the PROFILE total (ADR-0654) when a
    /// PROFILE arm is armed; otherwise nothing is read.
    fn drop(&mut self) {
        crate::exec::record_memos(|| self.memo.stats().counters());
    }
}

impl<P: NodePred> NodePred for Memoized<P> {
    type Prepared = MemoState<P::Prepared>;

    fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared> {
        // The trait's lazy slot defers this call to the first candidate,
        // so a stage with no candidates evaluates nothing, memoised or
        // not — the wrapped predicate keeps its once-per-stage bound.
        Ok(MemoState {
            inner: self.0.prepare(ctx)?,
            memo: {
                let live = ctx.graph.memo_live();
                NodeMemo::new(MemoPolicy::moderate(&live), live)
            },
        })
    }

    fn check(&self, state: &mut Self::Prepared, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        let MemoState { inner, memo } = state;
        memo.answer(ctx.graph, node, || self.0.check(inner, ctx, node))
    }
}

#[cfg(test)]
#[path = "memo_tests.rs"]
mod tests;