1use std::collections::hash_map::Entry;
2use std::collections::{HashMap, HashSet, VecDeque};
3
4thread_local! {
5 static DEFERRED_CACHE_INVALIDATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
6}
7
8use super::{RedDBRuntime, RuntimeQueryResult, RuntimeResultCacheEntry};
9
10const RESULT_CACHE_BLOB_NAMESPACE: &str = "runtime.result_cache";
11const RESULT_CACHE_TTL_SECS: u64 = 30;
12const RESULT_CACHE_MAX_ENTRIES: usize = 1000;
13const RESULT_CACHE_ENABLED_KEY: &str = "runtime.result_cache.enabled";
14const RESULT_CACHE_TTL_KEY: &str = "runtime.result_cache.ttl_seconds";
15const RESULT_CACHE_CAPACITY_KEY: &str = "runtime.result_cache.capacity_entries";
16const RESULT_CACHE_PAYLOAD_MAGIC: &[u8; 8] = b"RDRC0002";
17const RESULT_CACHE_WRITE_QUIET_PERIOD: std::time::Duration = std::time::Duration::from_secs(1);
18
19fn trim_result_cache(
20 map: &mut HashMap<String, RuntimeResultCacheEntry>,
21 order: &mut VecDeque<String>,
22 max_entries: usize,
23) -> u64 {
24 let mut evicted = 0u64;
25 while map.len() > max_entries {
26 if let Some(oldest) = order.pop_front() {
27 if map.remove(&oldest).is_some() {
28 evicted += 1;
29 }
30 } else {
31 break;
32 }
33 }
34 evicted
35}
36
37fn result_cache_fingerprint(result: &RuntimeQueryResult) -> String {
38 format!(
39 "{:?}|{}|{}|{}|{}|{:?}",
40 result.result,
41 result.query,
42 result.statement,
43 result.engine,
44 result.affected_rows,
45 result.statement_type
46 )
47}
48
49fn mode_to_byte(mode: reddb_rql::modes::QueryMode) -> u8 {
50 match mode {
51 reddb_rql::modes::QueryMode::Sql => 0,
52 reddb_rql::modes::QueryMode::Gremlin => 1,
53 reddb_rql::modes::QueryMode::Cypher => 2,
54 reddb_rql::modes::QueryMode::Sparql => 3,
55 reddb_rql::modes::QueryMode::Path => 4,
56 reddb_rql::modes::QueryMode::Natural => 5,
57 reddb_rql::modes::QueryMode::Unknown => 255,
58 }
59}
60
61fn mode_from_byte(byte: u8) -> Option<reddb_rql::modes::QueryMode> {
62 match byte {
63 0 => Some(reddb_rql::modes::QueryMode::Sql),
64 1 => Some(reddb_rql::modes::QueryMode::Gremlin),
65 2 => Some(reddb_rql::modes::QueryMode::Cypher),
66 3 => Some(reddb_rql::modes::QueryMode::Sparql),
67 4 => Some(reddb_rql::modes::QueryMode::Path),
68 5 => Some(reddb_rql::modes::QueryMode::Natural),
69 255 => Some(reddb_rql::modes::QueryMode::Unknown),
70 _ => None,
71 }
72}
73
74fn result_cache_static_str(value: &str) -> Option<&'static str> {
75 match value {
76 "select" => Some("select"),
77 "table" => Some("table"),
78 "join" => Some("join"),
79 "materialized-graph" => Some("materialized-graph"),
80 "runtime-red-schema" => Some("runtime-red-schema"),
81 "runtime-fdw" => Some("runtime-fdw"),
82 "runtime-table-rls" => Some("runtime-table-rls"),
83 "runtime-table" => Some("runtime-table"),
84 "runtime-join-rls" => Some("runtime-join-rls"),
85 "runtime-join" => Some("runtime-join"),
86 "runtime-vector" => Some("runtime-vector"),
87 "runtime-hybrid" => Some("runtime-hybrid"),
88 "runtime-secret" => Some("runtime-secret"),
89 "runtime-config" => Some("runtime-config"),
90 "runtime-tenant" => Some("runtime-tenant"),
91 "runtime-explain" => Some("runtime-explain"),
92 "runtime-tree" => Some("runtime-tree"),
93 "runtime-kv" => Some("runtime-kv"),
94 "runtime-queue" => Some("runtime-queue"),
95 _ => None,
96 }
97}
98
99fn write_u32(out: &mut Vec<u8>, value: usize) -> Option<()> {
100 let value = u32::try_from(value).ok()?;
101 out.extend_from_slice(&value.to_le_bytes());
102 Some(())
103}
104
105fn write_string(out: &mut Vec<u8>, value: &str) -> Option<()> {
106 write_u32(out, value.len())?;
107 out.extend_from_slice(value.as_bytes());
108 Some(())
109}
110
111fn write_bytes(out: &mut Vec<u8>, value: &[u8]) -> Option<()> {
112 write_u32(out, value.len())?;
113 out.extend_from_slice(value);
114 Some(())
115}
116
117fn read_u8(input: &mut &[u8]) -> Option<u8> {
118 let (&value, rest) = input.split_first()?;
119 *input = rest;
120 Some(value)
121}
122
123fn read_u32(input: &mut &[u8]) -> Option<usize> {
124 if input.len() < 4 {
125 return None;
126 }
127 let value = u32::from_le_bytes(input[..4].try_into().ok()?) as usize;
128 *input = &input[4..];
129 Some(value)
130}
131
132fn read_u64(input: &mut &[u8]) -> Option<u64> {
133 if input.len() < 8 {
134 return None;
135 }
136 let value = u64::from_le_bytes(input[..8].try_into().ok()?);
137 *input = &input[8..];
138 Some(value)
139}
140
141fn read_string(input: &mut &[u8]) -> Option<String> {
142 let len = read_u32(input)?;
143 if input.len() < len {
144 return None;
145 }
146 let value = String::from_utf8(input[..len].to_vec()).ok()?;
147 *input = &input[len..];
148 Some(value)
149}
150
151fn read_bytes<'a>(input: &mut &'a [u8]) -> Option<&'a [u8]> {
152 let len = read_u32(input)?;
153 if input.len() < len {
154 return None;
155 }
156 let value = &input[..len];
157 *input = &input[len..];
158 Some(value)
159}
160
161fn encode_result_cache_payload(entry: &RuntimeResultCacheEntry) -> Option<Vec<u8>> {
162 let result = &entry.result;
163 if entry.scopes.iter().any(|scope| {
165 reddb_engine::storage::system_collection_names::canonical_or_self(scope).starts_with("red.")
166 }) || result.result.stats.vector.is_some()
167 || result.result.pre_serialized_json.is_some()
168 || result_cache_static_str(result.statement).is_none()
169 || result_cache_static_str(result.engine).is_none()
170 || result_cache_static_str(result.statement_type).is_none()
171 || result.result.records.iter().any(|record| {
172 !record.nodes.is_empty()
173 || !record.edges.is_empty()
174 || !record.paths.is_empty()
175 || !record.vector_results.is_empty()
176 })
177 {
178 return None;
179 }
180
181 let mut out = Vec::new();
182 out.extend_from_slice(RESULT_CACHE_PAYLOAD_MAGIC);
183 out.extend_from_slice(&entry.data_epoch.to_le_bytes());
184 write_string(&mut out, &result.query)?;
185 out.push(mode_to_byte(result.mode));
186 write_string(&mut out, result.statement)?;
187 write_string(&mut out, result.engine)?;
188 out.extend_from_slice(&result.affected_rows.to_le_bytes());
189 write_string(&mut out, result.statement_type)?;
190
191 write_u32(&mut out, result.result.columns.len())?;
192 for column in &result.result.columns {
193 write_string(&mut out, column)?;
194 }
195 out.extend_from_slice(&result.result.stats.nodes_scanned.to_le_bytes());
196 out.extend_from_slice(&result.result.stats.edges_scanned.to_le_bytes());
197 out.extend_from_slice(&result.result.stats.rows_scanned.to_le_bytes());
198 out.extend_from_slice(&result.result.stats.segments_total.to_le_bytes());
199 out.extend_from_slice(&result.result.stats.segments_scanned.to_le_bytes());
200 out.extend_from_slice(&result.result.stats.segments_pruned.to_le_bytes());
201 out.extend_from_slice(&result.result.stats.exec_time_us.to_le_bytes());
202
203 write_u32(&mut out, result.result.records.len())?;
204 for record in &result.result.records {
205 let fields = record.iter_fields().collect::<Vec<_>>();
206 write_u32(&mut out, fields.len())?;
207 for (name, value) in fields {
208 write_string(&mut out, name)?;
209 let mut encoded = Vec::new();
210 reddb_types::value_codec::encode(value, &mut encoded);
211 write_bytes(&mut out, &encoded)?;
212 }
213 }
214
215 write_u32(&mut out, entry.scopes.len())?;
216 for scope in &entry.scopes {
217 write_string(&mut out, scope)?;
218 }
219 Some(out)
220}
221
222fn decode_result_cache_payload(
223 mut input: &[u8],
224) -> Option<(RuntimeQueryResult, HashSet<String>, u64)> {
225 if input.len() < RESULT_CACHE_PAYLOAD_MAGIC.len()
226 || &input[..RESULT_CACHE_PAYLOAD_MAGIC.len()] != RESULT_CACHE_PAYLOAD_MAGIC
227 {
228 return None;
229 }
230 input = &input[RESULT_CACHE_PAYLOAD_MAGIC.len()..];
231 let data_epoch = read_u64(&mut input)?;
232
233 let query = read_string(&mut input)?;
234 let mode = mode_from_byte(read_u8(&mut input)?)?;
235 let statement = result_cache_static_str(&read_string(&mut input)?)?;
236 let engine = result_cache_static_str(&read_string(&mut input)?)?;
237 let affected_rows = read_u64(&mut input)?;
238 let statement_type = result_cache_static_str(&read_string(&mut input)?)?;
239
240 let mut columns = Vec::new();
241 for _ in 0..read_u32(&mut input)? {
242 columns.push(read_string(&mut input)?);
243 }
244 let stats = crate::storage::query::unified::QueryStats {
245 nodes_scanned: read_u64(&mut input)?,
246 edges_scanned: read_u64(&mut input)?,
247 rows_scanned: read_u64(&mut input)?,
248 segments_total: read_u64(&mut input)?,
249 segments_scanned: read_u64(&mut input)?,
250 segments_pruned: read_u64(&mut input)?,
251 exec_time_us: read_u64(&mut input)?,
252 vector: None,
253 };
254
255 let mut records = Vec::new();
256 for _ in 0..read_u32(&mut input)? {
257 let mut record = crate::storage::query::unified::UnifiedRecord::new();
258 for _ in 0..read_u32(&mut input)? {
259 let name = read_string(&mut input)?;
260 let bytes = read_bytes(&mut input)?;
261 let (value, used) = reddb_types::value_codec::decode(bytes).ok()?;
262 if used != bytes.len() {
263 return None;
264 }
265 record.set_owned(name, value);
266 }
267 records.push(record);
268 }
269
270 let mut scopes = HashSet::new();
271 for _ in 0..read_u32(&mut input)? {
272 scopes.insert(read_string(&mut input)?);
273 }
274 if !input.is_empty() {
275 return None;
276 }
277
278 Some((
279 RuntimeQueryResult {
280 query,
281 mode,
282 statement,
283 engine,
284 result: crate::storage::query::unified::UnifiedResult {
285 columns,
286 records,
287 stats,
288 pre_serialized_json: None,
289 },
290 affected_rows,
291 statement_type,
292 bookmark: None,
293 notice: None,
294 },
295 scopes,
296 data_epoch,
297 ))
298}
299
300impl RedDBRuntime {
301 fn invalidate_result_cache_during_wal_capture(&self) {
302 DEFERRED_CACHE_INVALIDATION.with(|pending| pending.set(true));
303 let store = self.inner.db.store();
304 let _publication = store.vault_publication_lock.lock();
305 let _promotion = self.inner.result_blob_promotion.lock();
306 let mut entries = self.inner.result_blob_entries.write();
307 entries.0.clear();
308 entries.1.clear();
309 entries.2 = true;
310 entries.3 = entries.3.wrapping_add(1);
311 entries.4.clear();
312 entries.5 = None;
313 let mut ask = self.inner.ask_answer_cache_entries.write();
314 ask.0.clear();
315 ask.1.clear();
316 self.inner
317 .result_blob_cache
318 .invalidate_namespace_in_memory(RESULT_CACHE_BLOB_NAMESPACE);
319 self.inner
320 .result_blob_cache
321 .invalidate_namespace_in_memory(super::ASK_ANSWER_CACHE_NAMESPACE);
322 }
323
324 pub(super) fn flush_deferred_cache_invalidation(&self) {
325 if DEFERRED_CACHE_INVALIDATION.with(|pending| pending.replace(false)) {
326 self.invalidate_result_cache();
327 }
328 }
329
330 fn result_cache_enabled(&self) -> bool {
331 self.config_bool(RESULT_CACHE_ENABLED_KEY, true)
332 }
333
334 fn result_cache_ttl_secs(&self) -> u64 {
335 self.config_u64(RESULT_CACHE_TTL_KEY, RESULT_CACHE_TTL_SECS)
336 }
337
338 fn result_cache_capacity(&self) -> usize {
339 self.config_u64(RESULT_CACHE_CAPACITY_KEY, RESULT_CACHE_MAX_ENTRIES as u64) as usize
340 }
341
342 fn ensure_result_cache_format(&self) -> Option<u64> {
343 let store = self.inner.db.store();
344 if crate::storage::UnifiedStore::deferred_store_wal_capture_active() {
345 return None;
346 }
347 let _publication = store.vault_publication_lock.lock();
348 let _format = self.inner.result_cache_format_lock.lock();
349 if store.result_cache_format_fenced() {
350 return store.result_cache_read_epoch();
351 }
352 if self.inner.db.path().is_some() && store.is_read_only() {
353 return None;
354 }
355 {
356 let _promotion = self.inner.result_blob_promotion.lock();
357 if self
358 .inner
359 .result_blob_cache
360 .try_invalidate_namespace(RESULT_CACHE_BLOB_NAMESPACE)
361 .is_err()
362 {
363 return None;
364 }
365 }
366 store.ensure_result_cache_epoch().ok()?;
367 if self.inner.db.path().is_some() {
368 if let Some(pager) = store.pager() {
369 let required_version = if store.config().resident_memory_bytes_max.is_some() {
370 reddb_file::file_format::PAGE_RESULT_CACHE_DISK_FILE_VERSION
371 } else {
372 reddb_file::file_format::PAGE_RESULT_CACHE_FILE_VERSION
373 };
374 let version = pager.header().ok()?.version.max(required_version);
375 pager.fence_file_format_version(version).ok()?;
376 } else {
377 self.checkpoint_local().ok()?;
378 #[cfg(test)]
379 self.index_store_ref().mutation_test_hook(
380 "",
381 super::index_store::MutationTestPhase::ResultCacheFormatCheckpointed,
382 );
383 }
384 }
385 store.seal_result_cache_snapshot().ok()?;
386 store.result_cache_read_epoch()
387 }
388
389 pub(super) fn result_cache_snapshot(&self) -> (Option<u64>, u64) {
390 let epoch = if self.result_cache_enabled() {
391 let store = self.inner.db.store();
392 if store.result_cache_format_fenced() {
393 store.result_cache_read_epoch()
394 } else {
395 self.ensure_result_cache_format()
396 }
397 } else {
398 Some(0)
399 };
400 let cache = self.inner.result_blob_entries.read();
401 if cache.6 != 0 || !cache.0.is_empty() || epoch.unwrap_or(0) == 0 {
402 return (epoch, cache.3);
403 }
404 drop(cache);
405 let mut cache = self.inner.result_blob_entries.write();
406 if cache.6 == 0 && cache.0.is_empty() {
407 cache.6 = epoch.unwrap_or(0);
408 }
409 (epoch, cache.3)
410 }
411
412 pub fn result_cache_metrics(&self) -> (u64, u64, u64) {
413 use std::sync::atomic::Ordering::Relaxed;
414 (
415 self.inner.result_cache_hits.load(Relaxed),
416 self.inner.result_cache_misses.load(Relaxed),
417 self.inner.result_cache_evictions.load(Relaxed),
418 )
419 }
420
421 fn record_result_cache_evictions(&self, evicted: u64) {
422 if evicted > 0 {
423 self.inner
424 .result_cache_evictions
425 .fetch_add(evicted, std::sync::atomic::Ordering::Relaxed);
426 }
427 }
428
429 pub(super) fn get_result_cache_entry(
430 &self,
431 key: &str,
432 epoch: Option<u64>,
433 ) -> Option<RuntimeQueryResult> {
434 if !self.result_cache_enabled() {
435 return None;
436 }
437 let hit = self.get_result_cache_entry_inner(key, epoch);
438 let counter = if hit.is_some() {
439 &self.inner.result_cache_hits
440 } else {
441 &self.inner.result_cache_misses
442 };
443 counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
444 hit
445 }
446
447 fn get_result_cache_entry_inner(
448 &self,
449 key: &str,
450 epoch: Option<u64>,
451 ) -> Option<RuntimeQueryResult> {
452 epoch.and_then(|epoch| self.get_blob_result_cache_entry(key, epoch))
453 }
454
455 fn result_cache_entry_reusable(&self, entry: &RuntimeResultCacheEntry) -> bool {
456 let store = self.inner.db.store();
457 let runtime_table_entry = matches!(
458 entry.result.engine,
459 "runtime-table" | "runtime-table-rls" | "runtime-join" | "runtime-join-rls"
460 ) && !entry.scopes.is_empty();
461 if runtime_table_entry
462 && entry
463 .scopes
464 .iter()
465 .any(|scope| !self.inner.index_store.collection_indexes_queryable(scope))
466 {
467 return false;
468 }
469 if !runtime_table_entry
470 || entry
471 .scopes
472 .iter()
473 .any(|scope| store.get_collection(scope).is_none())
474 {
475 return store.result_cache_epoch() == Some(entry.data_epoch);
476 }
477 store.result_cache_unchanged_since(entry.data_epoch, &entry.scopes)
478 }
479
480 fn get_blob_result_cache_entry(&self, key: &str, epoch: u64) -> Option<RuntimeQueryResult> {
481 self.get_blob_result_cache_entry_from_blob_cache(key, epoch)
482 }
483
484 fn get_blob_result_cache_entry_from_blob_cache(
485 &self,
486 key: &str,
487 epoch: u64,
488 ) -> Option<RuntimeQueryResult> {
489 {
490 let cache = self.inner.result_blob_entries.read();
491 if cache.4.contains(key) {
492 let entry = cache.0.get(key)?;
493 return (self.result_cache_entry_reusable(entry)
494 && entry.cached_at.elapsed().as_secs() < self.result_cache_ttl_secs())
495 .then(|| entry.result.clone());
496 }
497 }
498 let revision = self.inner.result_blob_entries.read().3;
503 let hit = self
504 .inner
505 .result_blob_cache
506 .get(RESULT_CACHE_BLOB_NAMESPACE, key)?;
507 {
508 let cache = self.inner.result_blob_entries.read();
509 if cache.3 != revision {
510 return None;
511 }
512 if let Some(entry) = cache.0.get(key) {
513 return self
514 .result_cache_entry_reusable(entry)
515 .then(|| entry.result.clone());
516 }
517 }
518
519 let (result, scopes, data_epoch) = decode_result_cache_payload(hit.value())?;
520 if data_epoch != epoch || self.inner.db.store().result_cache_epoch() != Some(epoch) {
521 return None;
522 }
523 let new_entry = RuntimeResultCacheEntry {
524 result: result.clone(),
525 cached_at: std::time::Instant::now(),
526 scopes,
527 data_epoch,
528 };
529 if !self.result_cache_entry_reusable(&new_entry) {
533 return None;
534 }
535 let mut cache = self.inner.result_blob_entries.write();
536 if cache.3 != revision {
537 return None;
538 }
539 let (ref mut map, ref mut order, ref mut untracked, ..) = *cache;
540 match map.entry(key.to_string()) {
542 Entry::Occupied(mut slot) => {
543 slot.insert(new_entry);
544 }
545 Entry::Vacant(slot) => {
546 order.push_back(slot.key().clone());
547 slot.insert(new_entry);
548 }
549 }
550 let evicted = trim_result_cache(map, order, self.result_cache_capacity());
551 *untracked |= evicted > 0;
552 if evicted > 0 {
553 let (ref map, _, _, _, ref mut volatile_keys, ..) = *cache;
554 volatile_keys.retain(|key| map.contains_key(key));
555 }
556 drop(cache);
557 self.record_result_cache_evictions(evicted);
558 Some(result)
559 }
560
561 pub(super) fn promote_volatile_result_cache_entry(&self) {
565 let store = self.inner.db.store();
566 let Some(_publication) = store.vault_publication_lock.try_lock() else {
567 return;
568 };
569 let Some(_promotion) = self.inner.result_blob_promotion.try_lock() else {
570 return;
571 };
572 let ttl = self.result_cache_ttl_secs();
573 let Some(epoch) = store.result_cache_epoch() else {
574 return;
575 };
576 let candidate = {
577 let cache = self.inner.result_blob_entries.read();
578 if cache
579 .5
580 .is_none_or(|until| std::time::Instant::now() < until)
581 {
582 return;
583 }
584 cache.4.iter().find_map(|key| {
585 let entry = cache.0.get(key)?;
586 (entry.data_epoch == epoch && entry.cached_at.elapsed().as_secs() < ttl)
587 .then(|| (key.clone(), entry.clone()))
588 })
589 };
590 let Some((key, entry)) = candidate else {
591 return;
592 };
593 let remaining =
594 std::time::Duration::from_secs(ttl).saturating_sub(entry.cached_at.elapsed());
595 if remaining.is_zero() {
596 return;
597 }
598 let ttl_ms = u64::try_from(remaining.as_millis())
599 .unwrap_or(u64::MAX)
600 .max(1);
601 let policy = crate::storage::cache::BlobCachePolicy::default()
602 .ttl_ms(ttl_ms)
603 .priority(200);
604 let bytes = encode_result_cache_payload(&entry)
605 .unwrap_or_else(|| result_cache_fingerprint(&entry.result).into_bytes());
606 let put = crate::storage::cache::BlobCachePut::new(bytes)
607 .with_dependencies(entry.scopes.iter().cloned())
608 .with_policy(policy);
609 let result = self
610 .inner
611 .result_blob_cache
612 .put(RESULT_CACHE_BLOB_NAMESPACE, &key, put);
613 let mut cache = self.inner.result_blob_entries.write();
614 if result.is_ok()
615 && cache.4.contains(&key)
616 && cache
617 .0
618 .get(&key)
619 .is_some_and(|current| current.cached_at == entry.cached_at)
620 {
621 cache.4.remove(&key);
622 } else {
623 cache.2 = true;
625 if result.is_err() {
626 cache.5 = Some(std::time::Instant::now() + RESULT_CACHE_WRITE_QUIET_PERIOD);
627 }
628 }
629 cache.3 = cache.3.wrapping_add(1);
630 }
631
632 pub(super) fn put_result_cache_entry(
633 &self,
634 key: &str,
635 entry: RuntimeResultCacheEntry,
636 epoch: Option<u64>,
637 revision: u64,
638 ) {
639 if !self.result_cache_enabled() {
640 return;
641 }
642 if epoch.is_some() {
643 self.put_blob_result_cache_entry(key, entry, revision);
644 }
645 }
646
647 fn put_blob_result_cache_entry(
648 &self,
649 key: &str,
650 entry: RuntimeResultCacheEntry,
651 revision: u64,
652 ) {
653 let store = self.inner.db.store();
654 let Some(_publication) = store.vault_publication_lock.try_lock() else {
658 return;
659 };
660 let _promotion = self.inner.result_blob_promotion.lock();
661 let mut cache = self.inner.result_blob_entries.write();
662 if cache.3 != revision
663 || self.inner.db.store().result_cache_epoch() != Some(entry.data_epoch)
664 {
665 return;
666 }
667 if cache.5.is_none() {
672 cache.5 = Some(std::time::Instant::now() + RESULT_CACHE_WRITE_QUIET_PERIOD);
673 }
674 cache.4.insert(key.to_string());
675 let capacity = self.result_cache_capacity();
676 let (ref mut map, ref mut order, ref mut untracked, ref mut revision, ..) = *cache;
677 match map.entry(key.to_string()) {
679 Entry::Occupied(mut slot) => {
680 slot.insert(entry);
681 }
682 Entry::Vacant(slot) => {
683 order.push_back(slot.key().clone());
684 slot.insert(entry);
685 }
686 }
687 let evicted = trim_result_cache(map, order, capacity);
688 *untracked |= evicted > 0;
689 *revision = revision.wrapping_add(1);
690 if evicted > 0 {
691 let (ref map, _, _, _, ref mut volatile_keys, ..) = *cache;
692 volatile_keys.retain(|key| map.contains_key(key));
693 }
694 drop(cache);
695 self.record_result_cache_evictions(evicted);
696 }
697
698 pub fn invalidate_result_cache(&self) {
699 self.invalidate_result_cache_inner();
700 }
701
702 fn invalidate_blob_result_namespace(&self) -> bool {
703 match self
704 .inner
705 .result_blob_cache
706 .try_invalidate_namespace(RESULT_CACHE_BLOB_NAMESPACE)
707 {
708 Ok(_) => false,
709 Err(error) => {
710 tracing::error!(?error, "failed to persist result-cache invalidation");
711 true
712 }
713 }
714 }
715
716 pub(crate) fn invalidate_result_cache_process_only(&self) {
717 self.invalidate_result_cache_inner();
718 }
719
720 fn invalidate_result_cache_inner(&self) {
721 if crate::storage::UnifiedStore::deferred_store_wal_capture_active() {
722 self.invalidate_result_cache_during_wal_capture();
723 return;
724 }
725 let store = self.inner.db.store();
726 let _publication = store.vault_publication_lock.lock();
727 let _promotion = self.inner.result_blob_promotion.lock();
728 let mut blob_entries = self.inner.result_blob_entries.write();
729 blob_entries.0.clear();
730 blob_entries.1.clear();
731 blob_entries.4.clear();
732 blob_entries.5 = None;
733 if let Some(epoch) = self.inner.db.store().result_cache_epoch() {
734 blob_entries.6 = epoch;
735 }
736 blob_entries.2 = self.invalidate_blob_result_namespace();
737 blob_entries.3 = blob_entries.3.wrapping_add(1);
738 let mut ask_entries = self.inner.ask_answer_cache_entries.write();
739 ask_entries.0.clear();
740 ask_entries.1.clear();
741 self.inner
742 .result_blob_cache
743 .invalidate_namespace(super::ASK_ANSWER_CACHE_NAMESPACE);
744 }
745
746 pub(crate) fn invalidate_result_cache_for_table(&self, table: &str) {
747 #[cfg(test)]
748 self.index_store_ref().mutation_test_hook(
749 table,
750 super::index_store::MutationTestPhase::BeforeResultCacheInvalidation,
751 );
752 if crate::storage::UnifiedStore::deferred_store_wal_capture_active() {
753 self.invalidate_result_cache_during_wal_capture();
754 return;
755 }
756 let store = self.inner.db.store();
757 let _publication = store.vault_publication_lock.lock();
758 let _promotion = self.inner.result_blob_promotion.lock();
759 {
760 let mut blob_entries = self.inner.result_blob_entries.write();
761 let previous_epoch = blob_entries.6;
762 if let Some(epoch) = self.inner.db.store().result_cache_epoch() {
763 if previous_epoch.checked_add(1) == Some(epoch) {
764 for entry in blob_entries.0.values_mut() {
765 if entry.data_epoch == previous_epoch && !entry.scopes.contains(table) {
766 entry.data_epoch = epoch;
767 }
768 }
769 } else if previous_epoch != epoch && !blob_entries.0.is_empty() {
770 blob_entries.5 =
773 Some(std::time::Instant::now() + RESULT_CACHE_WRITE_QUIET_PERIOD);
774 }
775 blob_entries.6 = epoch;
776 }
777 blob_entries.3 = blob_entries.3.wrapping_add(1);
779 let has_match = blob_entries
780 .0
781 .values()
782 .any(|entry| entry.scopes.contains(table));
783 let has_durable_match = blob_entries
784 .0
785 .iter()
786 .any(|(key, entry)| entry.scopes.contains(table) && !blob_entries.4.contains(key));
787 if blob_entries.2 || has_durable_match {
788 blob_entries.0.clear();
789 blob_entries.1.clear();
790 blob_entries.4.clear();
791 blob_entries.2 = self.invalidate_blob_result_namespace();
792 blob_entries.3 = blob_entries.3.wrapping_add(1);
793 } else if has_match {
794 blob_entries
795 .0
796 .retain(|_, entry| !entry.scopes.contains(table));
797 let (ref map, ref mut order, _, ref mut revision, ref mut volatile_keys, ..) =
798 *blob_entries;
799 order.retain(|key| map.contains_key(key));
800 volatile_keys.retain(|key| map.contains_key(key));
801 *revision = revision.wrapping_add(1);
802 }
803 if has_match {
804 blob_entries.5 = Some(std::time::Instant::now() + RESULT_CACHE_WRITE_QUIET_PERIOD);
805 }
806 }
807 let mut ask_entries = self.inner.ask_answer_cache_entries.write();
808 ask_entries.0.clear();
809 ask_entries.1.clear();
810 self.inner
811 .result_blob_cache
812 .invalidate_namespace(super::ASK_ANSWER_CACHE_NAMESPACE);
813 }
814}
815
816#[cfg(test)]
817mod crash_tests {
818 use crate::{RedDBOptions, RedDBRuntime};
819 use std::sync::Arc;
820
821 const CHILD_PATH: &str = "REDDB_RESULT_CACHE_COMMIT_GAP_TEST_PATH";
822 const CHILD_OPERATION: &str = "REDDB_RESULT_CACHE_COMMIT_GAP_TEST_OPERATION";
823
824 #[test]
825 fn payload_without_a_data_epoch_is_not_rehydrated() {
826 assert!(super::decode_result_cache_payload(b"invalid-payload").is_none());
827 }
828
829 #[test]
830 fn result_cache_format_waits_for_wal_capture_to_finish() {
831 let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
832 crate::storage::UnifiedStore::begin_deferred_store_wal_capture();
833 let during_capture = runtime.result_cache_snapshot().0;
834 let actions = crate::storage::UnifiedStore::take_deferred_store_wal_capture();
835 assert!(actions.is_empty());
836 assert_eq!(during_capture, None);
837 assert!(!runtime.db().store().result_cache_format_fenced());
838 assert!(runtime.result_cache_snapshot().0.is_some());
839 assert!(runtime.db().store().result_cache_format_fenced());
840 }
841
842 #[test]
843 fn write_and_control_statements_do_not_initialize_result_cache_format() {
844 let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
845 for sql in [
846 "CREATE TABLE cache_format_gate (id INT)",
847 "INSERT INTO cache_format_gate (id) VALUES (1)",
848 "BEGIN",
849 "ROLLBACK",
850 ] {
851 runtime.execute_query(sql).expect("non-read statement");
852 assert!(!runtime.db().store().result_cache_format_fenced(), "{sql}");
853 }
854 runtime.execute_query("SCRUB").expect("uncached scrub");
855 assert!(!runtime.db().store().result_cache_format_fenced());
856 runtime
857 .execute_query("SELECT * FROM red.stats WHERE collection = 'cache_format_gate'")
858 .expect("computed stats read");
859 assert!(!runtime.db().store().result_cache_format_fenced());
860 runtime.execute_query("SHOW STATS").expect("show stats");
861 assert!(!runtime.db().store().result_cache_format_fenced());
862 runtime
863 .execute_query("SELECT id FROM cache_format_gate")
864 .expect("read statement");
865 assert!(runtime.db().store().result_cache_format_fenced());
866 }
867
868 #[test]
869 fn uncached_native_read_frame_does_not_initialize_result_cache_format() {
870 use crate::runtime::statement_frame::{StatementExecutionFrame, StatementIdentity};
871
872 let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
873 let _frame = StatementExecutionFrame::build(
874 &runtime,
875 StatementIdentity::UncachedText("SEARCH CONTEXT"),
876 )
877 .expect("native read frame");
878 assert!(!runtime.db().store().result_cache_format_fenced());
879 }
880
881 #[test]
882 fn a_statement_leaves_the_durable_tier_to_the_sweeper() {
883 use std::sync::atomic::Ordering;
884 use std::time::Duration;
885
886 let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
887 for sql in [
888 "CREATE TABLE cached_rows (id INT)",
889 "INSERT INTO cached_rows (id) VALUES (1)",
890 ] {
891 runtime.execute_query(sql).expect(sql);
892 }
893 std::thread::sleep(super::RESULT_CACHE_WRITE_QUIET_PERIOD + Duration::from_millis(50));
896 let sql = "SELECT id FROM cached_rows ORDER BY id";
897 runtime.execute_query(sql).expect("read");
898 assert_eq!(
899 runtime.inner.result_blob_entries.read().4.len(),
900 1,
901 "the result waits in memory for the sweeper"
902 );
903
904 let hits = runtime.inner.result_cache_hits.load(Ordering::Relaxed);
905 assert_eq!(
906 runtime
907 .execute_query(sql)
908 .expect("hit")
909 .result
910 .records
911 .len(),
912 1
913 );
914 assert_eq!(
915 runtime.inner.result_cache_hits.load(Ordering::Relaxed),
916 hits + 1,
917 "a result held in memory answers the next statement"
918 );
919
920 std::thread::sleep(super::RESULT_CACHE_WRITE_QUIET_PERIOD + Duration::from_millis(50));
921 runtime.promote_volatile_result_cache_entry();
922 assert!(
923 runtime.inner.result_blob_entries.read().4.is_empty(),
924 "the sweeper moves it to the durable tier"
925 );
926 assert_eq!(
927 runtime
928 .execute_query(sql)
929 .expect("hit")
930 .result
931 .records
932 .len(),
933 1
934 );
935 assert_eq!(
936 runtime.inner.result_cache_hits.load(Ordering::Relaxed),
937 hits + 2
938 );
939 }
940
941 #[test]
942 fn promotion_gate_does_not_block_hits_and_orders_invalidation() {
943 use std::sync::mpsc;
944 use std::time::Duration;
945
946 let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
947 for sql in [
948 "CREATE TABLE promotion_gate (id INT)",
949 "INSERT INTO promotion_gate (id) VALUES (1)",
950 "SELECT id FROM promotion_gate ORDER BY id",
951 "INSERT INTO promotion_gate (id) VALUES (2)",
952 "SELECT id FROM promotion_gate ORDER BY id",
953 ] {
954 runtime.execute_query(sql).expect("prepare volatile result");
955 }
956
957 let guard = runtime.inner.result_blob_promotion.lock();
958 let reader = runtime.clone();
959 let (read_tx, read_rx) = mpsc::channel();
960 let reader_thread = std::thread::spawn(move || {
961 let rows = reader
962 .execute_query("SELECT id FROM promotion_gate ORDER BY id")
963 .expect("cached read")
964 .result
965 .records
966 .len();
967 read_tx.send(rows).expect("report read");
968 });
969 let read = read_rx.recv_timeout(Duration::from_secs(3));
970 drop(guard);
971 reader_thread.join().expect("reader thread");
972 assert_eq!(read.expect("hit blocked by promotion gate"), 2);
973
974 let guard = runtime.inner.result_blob_promotion.lock();
975 let invalidator = runtime.clone();
976 let (started_tx, started_rx) = mpsc::channel();
977 let (done_tx, done_rx) = mpsc::channel();
978 let invalidator_thread = std::thread::spawn(move || {
979 started_tx.send(()).expect("report start");
980 invalidator.invalidate_result_cache_for_table("promotion_gate");
981 done_tx.send(()).expect("report invalidation");
982 });
983 let started = started_rx.recv_timeout(Duration::from_secs(3));
984 let completed_early = done_rx.recv_timeout(Duration::from_millis(100));
985 drop(guard);
986 assert!(started.is_ok(), "invalidation did not start");
987 assert!(
988 matches!(completed_early, Err(mpsc::RecvTimeoutError::Timeout)),
989 "invalidation must wait for an in-flight promotion"
990 );
991 done_rx
992 .recv_timeout(Duration::from_secs(3))
993 .expect("invalidation did not finish");
994 invalidator_thread.join().expect("invalidator thread");
995 let before = runtime.result_cache_metrics();
996 assert_eq!(
997 runtime
998 .execute_query("SELECT id FROM promotion_gate ORDER BY id")
999 .expect("read after invalidation")
1000 .result
1001 .records
1002 .len(),
1003 2
1004 );
1005 assert_eq!(
1006 runtime.result_cache_metrics().1 - before.1,
1007 1,
1008 "invalidation must remove the cached result"
1009 );
1010 }
1011
1012 #[test]
1013 fn durable_cache_publication_and_write_invalidation_do_not_invert_locks() {
1014 use std::sync::mpsc;
1015 use std::time::{Duration, Instant};
1016
1017 let directory = tempfile::tempdir().expect("temporary directory");
1018 let runtime = RedDBRuntime::with_options(RedDBOptions::persistent(
1019 directory.path().join("cache-lock-order.rdb"),
1020 ))
1021 .expect("runtime");
1022 for sql in [
1023 "CREATE TABLE locked_write (id INT)",
1024 "CREATE TABLE cache_fill (id INT)",
1025 "INSERT INTO locked_write (id) VALUES (1)",
1026 "INSERT INTO cache_fill (id) VALUES (1)",
1027 ] {
1028 runtime.execute_query(sql).expect(sql);
1029 }
1030 runtime.result_cache_snapshot();
1031 std::thread::sleep(super::RESULT_CACHE_WRITE_QUIET_PERIOD + Duration::from_millis(50));
1032
1033 let (write_paused_tx, write_paused_rx) = mpsc::channel();
1034 let (resume_write_tx, resume_write_rx) = mpsc::channel();
1035 let writer = runtime.clone();
1036 let (writer_done_tx, writer_done_rx) = mpsc::channel();
1037 let writer_thread = std::thread::spawn(move || {
1038 let store = writer.db().store();
1039 let _publication = store.vault_publication_lock.lock();
1040 write_paused_tx
1041 .send(store.vault_publication_lock.is_owned_by_current_thread())
1042 .expect("report paused writer");
1043 resume_write_rx
1044 .recv_timeout(Duration::from_secs(10))
1045 .expect("resume writer");
1046 writer.invalidate_result_cache_for_table("locked_write");
1047 writer_done_tx.send(()).expect("report writer result");
1048 });
1049 assert!(
1050 write_paused_rx
1051 .recv_timeout(Duration::from_secs(5))
1052 .expect("writer did not reach invalidation"),
1053 "write invalidation must still own the durable publication fence"
1054 );
1055
1056 let cache_filler = runtime.clone();
1057 let (cache_done_tx, cache_done_rx) = mpsc::channel();
1058 let cache_thread = std::thread::spawn(move || {
1059 let result = cache_filler.execute_query("SELECT id FROM cache_fill ORDER BY id");
1060 cache_done_tx
1061 .send(result)
1062 .expect("report cache publication result");
1063 });
1064
1065 let deadline = Instant::now() + Duration::from_secs(2);
1071 while Instant::now() < deadline {
1072 if runtime.inner.result_blob_promotion.try_lock().is_none() {
1073 break;
1074 }
1075 std::thread::sleep(Duration::from_millis(10));
1076 }
1077 resume_write_tx.send(()).expect("resume writer");
1078
1079 let writer_result = writer_done_rx.recv_timeout(Duration::from_secs(3));
1080 let cache_result = cache_done_rx.recv_timeout(Duration::from_secs(3));
1081 assert!(
1082 writer_result.is_ok() && cache_result.is_ok(),
1083 "durable cache publication deadlocked with write invalidation"
1084 );
1085 writer_result.unwrap();
1086 cache_result.unwrap().expect("cache publication result");
1087 writer_thread.join().expect("writer thread");
1088 cache_thread.join().expect("cache thread");
1089 }
1090
1091 #[test]
1092 fn published_write_cannot_return_an_old_in_memory_result() {
1093 use std::sync::mpsc;
1094 use std::time::Duration;
1095
1096 let directory = tempfile::tempdir().expect("temporary directory");
1097 let runtime = RedDBRuntime::with_options(RedDBOptions::persistent(
1098 directory.path().join("live-gap.rdb"),
1099 ))
1100 .expect("runtime");
1101 for sql in [
1102 "CREATE TABLE live_gap (id INT)",
1103 "INSERT INTO live_gap (id) VALUES (1)",
1104 "SELECT id FROM live_gap ORDER BY id",
1105 ] {
1106 runtime.execute_query(sql).expect("prepare cache");
1107 }
1108 let (published_tx, published_rx) = mpsc::channel();
1109 let (resume_tx, resume_rx) = mpsc::channel();
1110 let resume_rx = Arc::new(parking_lot::Mutex::new(resume_rx));
1111 *runtime.index_store_ref().mutation_hook.lock() =
1112 Some(Arc::new(move |collection, phase| {
1113 if collection == "live_gap"
1114 && phase == super::super::index_store::MutationTestPhase::StoragePublished
1115 {
1116 published_tx.send(()).expect("report publication");
1117 resume_rx
1118 .lock()
1119 .recv_timeout(Duration::from_secs(10))
1120 .expect("resume writer");
1121 }
1122 }));
1123 let writer = runtime.clone();
1124 let writer_thread = std::thread::spawn(move || {
1125 writer.execute_query("INSERT INTO live_gap (id) VALUES (2)")
1126 });
1127 published_rx
1128 .recv_timeout(Duration::from_secs(10))
1129 .expect("storage publication");
1130 let reader = runtime.clone();
1131 let (read_tx, read_rx) = mpsc::channel();
1132 let reader_thread = std::thread::spawn(move || {
1133 let rows = reader
1134 .execute_query("SELECT id FROM live_gap ORDER BY id")
1135 .expect("read during publication")
1136 .result
1137 .records
1138 .len();
1139 read_tx.send(rows).expect("report rows");
1140 });
1141 let early = read_rx.recv_timeout(Duration::from_secs(2));
1142 resume_tx.send(()).expect("resume writer");
1143 writer_thread.join().expect("writer thread").expect("write");
1144 let rows = match early {
1145 Ok(rows) => rows,
1146 Err(mpsc::RecvTimeoutError::Timeout) => read_rx
1147 .recv_timeout(Duration::from_secs(10))
1148 .expect("reader finished"),
1149 Err(error) => panic!("reader failed: {error}"),
1150 };
1151 reader_thread.join().expect("reader thread");
1152 assert_eq!(
1153 rows, 2,
1154 "old cached result was returned after storage publication"
1155 );
1156 }
1157
1158 #[test]
1159 fn unrelated_pending_write_keeps_a_cached_read_available() {
1160 use std::sync::mpsc;
1161 use std::time::Duration;
1162
1163 let directory = tempfile::tempdir().expect("temporary directory");
1164 let runtime = RedDBRuntime::with_options(RedDBOptions::persistent(
1165 directory.path().join("pending-unrelated.rdb"),
1166 ))
1167 .expect("runtime");
1168 for sql in [
1169 "CREATE TABLE cached_items (id INT)",
1170 "CREATE TABLE unrelated_items (id INT)",
1171 "INSERT INTO cached_items (id) VALUES (1)",
1172 "INSERT INTO unrelated_items (id) VALUES (1)",
1173 "SELECT id FROM cached_items ORDER BY id",
1174 "SELECT id FROM cached_items ORDER BY id",
1175 ] {
1176 runtime.execute_query(sql).expect(sql);
1177 }
1178 let before = runtime.result_cache_metrics();
1179 runtime
1180 .execute_query("SELECT id FROM cached_items ORDER BY id")
1181 .expect("warm hit");
1182 assert_eq!(runtime.result_cache_metrics().0 - before.0, 1);
1183 let (pending_tx, pending_rx) = mpsc::channel();
1184 let (resume_tx, resume_rx) = mpsc::channel();
1185 let resume_rx = Arc::new(parking_lot::Mutex::new(resume_rx));
1186 runtime
1187 .db()
1188 .store()
1189 .set_result_cache_pending_hook(Some(Arc::new(move || {
1190 pending_tx.send(()).expect("report pending");
1191 resume_rx
1192 .lock()
1193 .recv_timeout(Duration::from_secs(10))
1194 .expect("resume");
1195 })));
1196 let writer = runtime.clone();
1197 let writer_thread = std::thread::spawn(move || {
1198 writer.execute_query("UPDATE unrelated_items SET id = 2 WHERE id = 1")
1199 });
1200 pending_rx
1201 .recv_timeout(Duration::from_secs(10))
1202 .expect("publication pending");
1203 let before = runtime.result_cache_metrics();
1204 let reader = runtime.clone();
1205 let (read_tx, read_rx) = mpsc::channel();
1206 let reader_thread = std::thread::spawn(move || {
1207 read_tx
1208 .send(reader.execute_query("SELECT id FROM cached_items ORDER BY id"))
1209 .unwrap();
1210 });
1211 let result = read_rx.recv_timeout(Duration::from_secs(3));
1212 runtime.db().store().set_result_cache_pending_hook(None);
1213 resume_tx.send(()).expect("resume writer");
1214 writer_thread.join().unwrap().expect("write");
1215 reader_thread.join().unwrap();
1216 assert_eq!(
1217 result
1218 .expect("cached read must not wait")
1219 .expect("read")
1220 .result
1221 .records
1222 .len(),
1223 1
1224 );
1225 assert_eq!(
1226 runtime.result_cache_metrics().0 - before.0,
1227 1,
1228 "unrelated pending write must preserve the hit"
1229 );
1230 }
1231
1232 #[test]
1233 fn committed_insert_before_cache_invalidation_does_not_recover_stale_result() {
1234 if let Some(path) = std::env::var_os(CHILD_PATH) {
1235 let runtime = RedDBRuntime::with_options(RedDBOptions::persistent(path))
1236 .expect("open child database");
1237 let operation = std::env::var(CHILD_OPERATION).expect("child operation");
1238 if operation.starts_with("format_crash:") || operation.starts_with("format_seal:") {
1239 let store = runtime.db().store();
1240 store
1241 .insert_auto(
1242 "format_data",
1243 crate::storage::UnifiedEntity::table_row(
1244 crate::storage::EntityId::new(0),
1245 "format_data",
1246 0,
1247 vec![reddb_types::Value::Integer(42)],
1248 ),
1249 )
1250 .expect("seed durable data");
1251 if let Some(point) = operation.strip_prefix("format_crash:") {
1252 std::env::set_var("REDDB_EMBEDDED_RDB_CRASH_AT", point);
1253 } else {
1254 let point = operation.strip_prefix("format_seal:").unwrap().to_owned();
1255 *runtime.index_store_ref().mutation_hook.lock() = Some(Arc::new(
1256 move |_, phase| {
1257 if phase == super::super::index_store::MutationTestPhase::ResultCacheFormatCheckpointed {
1258 if point == "before" {
1259 std::process::exit(86);
1260 }
1261 std::env::set_var("REDDB_EMBEDDED_RDB_CRASH_AT", &point);
1262 }
1263 },
1264 ));
1265 }
1266 runtime
1267 .execute_query("SELECT * FROM format_data")
1268 .expect("format activation");
1269 panic!("format crash point was not reached");
1270 }
1271 for sql in [
1272 "CREATE TABLE cache_gap (id INT)",
1273 "INSERT INTO cache_gap (id) VALUES (1)",
1274 "SELECT id FROM cache_gap ORDER BY id",
1275 ] {
1276 runtime.execute_query(sql).expect("prepare cache");
1277 }
1278 if operation == "format_fence" {
1279 assert!(runtime.db().store().result_cache_format_fenced());
1280 std::process::exit(86);
1281 }
1282 if operation == "transaction" {
1283 let (key, mut old_entry) = {
1284 let cache = runtime.inner.result_blob_entries.read();
1285 let (key, entry) = cache.0.iter().next().expect("warm original result");
1286 (key.clone(), entry.clone())
1287 };
1288 super::super::execution_context::set_current_connection_id(901);
1289 runtime.execute_query("BEGIN").expect("begin transaction");
1290 runtime
1291 .execute_query("INSERT INTO cache_gap (id) VALUES (2)")
1292 .expect("stage insert");
1293 let reader = runtime.clone();
1294 std::thread::spawn(move || {
1295 super::super::execution_context::set_current_connection_id(902);
1296 let read = reader
1297 .execute_query("SELECT id FROM cache_gap ORDER BY id")
1298 .expect("cache committed view");
1299 assert_eq!(
1300 read.result.records.len(),
1301 1,
1302 "uncommitted row must not be visible"
1303 );
1304 old_entry.data_epoch = reader.db().store().result_cache_epoch().expect("epoch");
1307 let payload =
1308 super::encode_result_cache_payload(&old_entry).expect("encode old result");
1309 reader
1310 .inner
1311 .result_blob_cache
1312 .put(
1313 super::RESULT_CACHE_BLOB_NAMESPACE,
1314 &key,
1315 crate::storage::cache::BlobCachePut::new(payload),
1316 )
1317 .expect("persist old result");
1318 reader.checkpoint().expect("persist cached result");
1319 let hit = reader
1320 .inner
1321 .result_blob_cache
1322 .get(super::RESULT_CACHE_BLOB_NAMESPACE, &key)
1323 .expect("old entry remains");
1324 assert!(super::decode_result_cache_payload(hit.value()).is_some());
1325 })
1326 .join()
1327 .expect("pre-commit reader");
1328 } else {
1329 runtime.checkpoint().expect("persist cached result");
1330 }
1331 let transaction = operation == "transaction";
1332 *runtime.index_store_ref().mutation_hook.lock() = Some(Arc::new(
1333 move |collection, phase| {
1334 if (transaction && phase == super::super::index_store::MutationTestPhase::TransactionWalCommitted)
1335 || (!transaction && collection == "cache_gap"
1336 && phase == super::super::index_store::MutationTestPhase::BeforeResultCacheInvalidation)
1337 {
1338 std::process::exit(86);
1339 }
1340 },
1341 ));
1342 if operation.starts_with("wal_") {
1343 std::env::set_var("REDDB_EMBEDDED_RDB_CRASH_AT", &operation);
1344 }
1345 let sql = match operation.as_str() {
1346 "insert"
1347 | "wal_after_frame_write"
1348 | "wal_after_frame_sync"
1349 | "wal_after_superblock_write" => "INSERT INTO cache_gap (id) VALUES (2)",
1350 "update" => "UPDATE cache_gap SET id = 2 WHERE id = 1",
1351 "delete" => "DELETE FROM cache_gap WHERE id = 1",
1352 "transaction" => "COMMIT",
1353 _ => panic!("unknown operation"),
1354 };
1355 runtime
1356 .execute_query(sql)
1357 .expect("hook must terminate before return");
1358 panic!("storage-published hook was not reached");
1359 }
1360
1361 let dir = tempfile::tempdir().expect("temporary directory");
1362 for (operation, expected) in [
1363 ("insert", Some(vec![1, 2])),
1364 ("update", Some(vec![2])),
1365 ("delete", Some(vec![])),
1366 ("transaction", Some(vec![1, 2])),
1367 ("wal_after_frame_write", None),
1368 ("wal_after_frame_sync", None),
1369 ("wal_after_superblock_write", None),
1370 ] {
1371 let path = dir.path().join(format!("cache-gap-{operation}.rdb"));
1372 let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
1373 .args([
1374 "--exact",
1375 "runtime::result_cache_runtime::crash_tests::committed_insert_before_cache_invalidation_does_not_recover_stale_result",
1376 "--nocapture",
1377 ])
1378 .env(CHILD_PATH, &path)
1379 .env(CHILD_OPERATION, operation)
1380 .output()
1381 .expect("run child");
1382 assert_eq!(
1383 output.status.code(),
1384 Some(if operation.starts_with("wal_") {
1385 173
1386 } else {
1387 86
1388 }),
1389 "{operation} child did not reach crash hook: {}",
1390 String::from_utf8_lossy(&output.stderr)
1391 );
1392 let runtime =
1393 RedDBRuntime::with_options(RedDBOptions::persistent(&path)).expect("reopen");
1394 let before = runtime.result_cache_metrics();
1395 let cached = runtime
1396 .execute_query("SELECT id FROM cache_gap ORDER BY id")
1397 .expect("cached read");
1398 let after = runtime.result_cache_metrics();
1399 let values = |result: &crate::runtime::RuntimeQueryResult| {
1400 result
1401 .result
1402 .records
1403 .iter()
1404 .map(|record| match record.get("id") {
1405 Some(reddb_types::Value::Integer(value)) => *value,
1406 other => panic!("expected id, got {other:?}"),
1407 })
1408 .collect::<Vec<_>>()
1409 };
1410 runtime
1411 .execute_query("SET CONFIG runtime.result_cache.enabled = false")
1412 .expect("disable cache");
1413 let actual = runtime
1414 .execute_query("SELECT id FROM cache_gap ORDER BY id")
1415 .expect("authoritative read");
1416 let actual = values(&actual);
1417 if let Some(expected) = expected {
1418 assert_eq!(actual, expected, "{operation} committed data must survive");
1419 } else {
1420 assert!(
1421 actual == vec![1] || actual == vec![1, 2],
1422 "{operation} recovered a partial write"
1423 );
1424 }
1425 assert_eq!(
1426 values(&cached),
1427 actual,
1428 "{operation} recovered a stale result"
1429 );
1430 if actual != vec![1] {
1431 assert_eq!(
1432 after.1 - before.1,
1433 1,
1434 "{operation} must reject the old L2 entry"
1435 );
1436 }
1437 }
1438 }
1439
1440 #[test]
1441 fn result_cache_format_fences_both_embedded_superblocks() {
1442 use std::io::{Seek, SeekFrom, Write};
1443 let directory = tempfile::tempdir().expect("temporary directory");
1444 let path = directory.path().join("format-fence.rdb");
1445 let status = std::process::Command::new(std::env::current_exe().expect("test executable"))
1446 .args([
1447 "--exact",
1448 "runtime::result_cache_runtime::crash_tests::committed_insert_before_cache_invalidation_does_not_recover_stale_result",
1449 "--nocapture",
1450 ])
1451 .env(CHILD_PATH, &path)
1452 .env(CHILD_OPERATION, "format_fence")
1453 .status()
1454 .expect("run child");
1455 assert_eq!(status.code(), Some(86));
1456 for index in 0..2 {
1457 let copy = directory.path().join(format!("format-fence-{index}.rdb"));
1458 std::fs::copy(&path, ©).expect("copy database");
1459 let mut file = std::fs::OpenOptions::new().write(true).open(©).unwrap();
1460 file.seek(SeekFrom::Start(
1461 index * reddb_file::EMBEDDED_RDB_SUPERBLOCK_SIZE + 64,
1462 ))
1463 .unwrap();
1464 file.write_all(&[0xff]).unwrap();
1465 file.sync_all().unwrap();
1466 drop(file);
1467 let open = crate::storage::EmbeddedRdbArtifact::open(©).expect("other superblock");
1468 let snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&open)
1469 .unwrap()
1470 .unwrap();
1471 assert_eq!(
1472 reddb_file::decode_native_store_header(&snapshot).unwrap(),
1473 reddb_file::STORE_VERSION_CURRENT
1474 );
1475 }
1476 }
1477
1478 #[test]
1479 fn result_cache_format_fence_and_warm_result_survive_restart() {
1480 let directory = tempfile::tempdir().expect("temporary directory");
1481 let path = directory.path().join("warm-fenced.rdb");
1482 {
1483 let runtime =
1484 RedDBRuntime::with_options(RedDBOptions::persistent(&path)).expect("runtime");
1485 for sql in [
1486 "CREATE TABLE warm_fence (id INT)",
1487 "INSERT INTO warm_fence (id) VALUES (1)",
1488 "SELECT id FROM warm_fence ORDER BY id",
1489 ] {
1490 runtime.execute_query(sql).expect(sql);
1491 }
1492 assert!(runtime.db().store().result_cache_format_fenced());
1493 runtime.inner.result_blob_entries.write().5 = Some(std::time::Instant::now());
1494 runtime.promote_volatile_result_cache_entry();
1495 }
1496 let runtime = RedDBRuntime::with_options(RedDBOptions::persistent(&path)).expect("reopen");
1497 assert!(
1498 runtime.db().store().result_cache_format_fenced(),
1499 "durable fence must load before the first query"
1500 );
1501 let before = runtime.result_cache_metrics();
1502 assert_eq!(
1503 runtime
1504 .execute_query("SELECT id FROM warm_fence ORDER BY id")
1505 .expect("read")
1506 .result
1507 .records
1508 .len(),
1509 1
1510 );
1511 assert_eq!(
1512 runtime.result_cache_metrics().0 - before.0,
1513 1,
1514 "valid result must recover warm"
1515 );
1516 }
1517
1518 #[test]
1519 fn result_cache_format_checkpoint_survives_interrupted_publication() {
1520 let directory = tempfile::tempdir().expect("temporary directory");
1521 for (operation, expected_status) in [
1522 ("format_crash:snapshot_after_image_write", 173),
1523 ("format_crash:snapshot_after_image_sync", 173),
1524 ("format_crash:snapshot_after_manifest_write", 173),
1525 ("format_crash:snapshot_after_manifest_sync", 173),
1526 ("format_crash:snapshot_after_superblock_write", 173),
1527 ("format_seal:before", 86),
1528 ("format_seal:wal_after_frame_write", 173),
1529 ("format_seal:wal_after_frame_sync", 173),
1530 ("format_seal:wal_after_superblock_write", 173),
1531 ] {
1532 let path = directory
1533 .path()
1534 .join(format!("{}.rdb", operation.replace(':', "-")));
1535 let status = std::process::Command::new(std::env::current_exe().expect("test executable"))
1536 .args([
1537 "--exact",
1538 "runtime::result_cache_runtime::crash_tests::committed_insert_before_cache_invalidation_does_not_recover_stale_result",
1539 "--nocapture",
1540 ])
1541 .env(CHILD_PATH, &path)
1542 .env(CHILD_OPERATION, operation)
1543 .status().expect("run child");
1544 assert_eq!(status.code(), Some(expected_status), "crash at {operation}");
1545 let runtime = RedDBRuntime::with_options(RedDBOptions::persistent(&path))
1546 .expect("recover database");
1547 assert_eq!(
1548 runtime
1549 .db()
1550 .store()
1551 .get_collection("format_data")
1552 .expect("recovered table")
1553 .count(),
1554 1
1555 );
1556 runtime
1557 .execute_query("SELECT * FROM format_data")
1558 .expect("activate format after recovery");
1559 assert!(runtime.db().store().result_cache_format_fenced());
1560 }
1561 }
1562}