hawdb/embedded_store/search_epoch_advance.rs
1// Copyright 2026 Nowledge
2// SPDX-License-Identifier: Apache-2.0
3
4//! Verified, metadata-only advance of the search projection's source graph
5//! commit epoch (#1756). See `docs/SEARCH_PROJECTION_EPOCH_ADVANCE.md`.
6
7use super::*;
8use crate::search::SearchProjectionEpochAdvanceReport;
9use hawdb_core::SearchProjectionEpochAdvanceRefusal;
10
11impl EmbeddedStoreHandle {
12 /// Advances the search projection's source graph commit epoch to
13 /// `target_graph_commit_epoch` without rewriting any projection data file,
14 /// after proving that the graph commits in between changed nothing the
15 /// projection indexes. See
16 /// [`EmbeddedStore::advance_search_projection_source_epoch`].
17 pub fn advance_search_projection_source_epoch(
18 &self,
19 target_graph_commit_epoch: u64,
20 ) -> Result<SearchProjectionEpochAdvanceReport> {
21 let _permit = self.admit_typed_maintenance(RuntimeWorkPriority::Background, 0, 1)?;
22 self.write_store()?
23 .advance_search_projection_source_epoch(target_graph_commit_epoch)
24 }
25}
26
27impl EmbeddedStore {
28 /// Moves the search projection's source graph commit epoch from its
29 /// current value `S` to `target_graph_commit_epoch` (`T`) by publishing
30 /// only a new selector manifest. Payload, lexical, vector, layout and
31 /// snapshot files are reused as they are, so the cost is one manifest
32 /// write (kilobytes) and one directory sync, independent of corpus size.
33 /// An empty apply followed by a checkpoint rewrites the whole projection
34 /// instead.
35 ///
36 /// **Safety contract.** HawDB does not trust the caller. `T` must be the
37 /// current graph commit epoch. Holding the store write lock (this
38 /// `&mut self`) and, for the whole check, the database runtime's read
39 /// guard, which every graph commit needs for writing, HawDB checks its own
40 /// search change log for `(S, T]`. The log must cover the whole range, and
41 /// every commit in it must have an empty projection capture:
42 /// - no node that exists at `T` with a label that maps to a search
43 /// projection kind;
44 /// - no search document deletion;
45 /// - no relational primary-key change, except to tables declared with
46 /// [`EmbeddedStoreOpenOptions::with_non_projection_relational_tables`]
47 /// (counted in `allowed_relational_change_count`);
48 /// - no relational change that cannot be attributed to tables.
49 ///
50 /// Graph commits that only touch non-projection labels, such as import
51 /// bookkeeping, and additive schema statements qualify. Otherwise it
52 /// publishes nothing and returns
53 /// [`HawDBError::SearchProjectionEpochAdvanceRefused`], which is not a
54 /// storage failure: apply or catch up the range normally instead.
55 /// Refusal reasons:
56 /// - `ProjectionChanged`;
57 /// - `ChangeLogGap`: a commit in the range could not be captured, or the
58 /// log was trimmed or begins after a reopen;
59 /// - `RangeUnavailable`: no source epoch, or `T` is not the graph's
60 /// current commit epoch;
61 /// - `UncheckpointedChanges`: a resident projection whose in-memory state
62 /// differs from its last checkpoint.
63 ///
64 /// **Crash safety.** The selector rename is the only commit point, as in
65 /// every projection publication: after a crash or reopen the projection
66 /// is entirely at `S` or entirely at `T`.
67 ///
68 /// Covers the resident projection (as used by
69 /// [`Self::apply_initial_import_projection_delta_and_checkpoint`] and
70 /// [`Self::apply_search_projection_delta_and_checkpoint`]) and incremental
71 /// out-of-core maintenance. `T == S` (the projection is already at the
72 /// current epoch) returns a report with `advanced == false` and writes
73 /// nothing; `T < S` is a semantic error.
74 pub fn advance_search_projection_source_epoch(
75 &mut self,
76 target_graph_commit_epoch: u64,
77 ) -> Result<SearchProjectionEpochAdvanceReport> {
78 let target = target_graph_commit_epoch;
79 if self.incremental_search_enabled() {
80 // A previous response may have been lost after publication.
81 self.refresh_incremental_search_reader()?;
82 let projection = self.out_of_core_search_projection.as_ref().ok_or_else(|| {
83 HawDBError::Semantic("incremental search maintenance is not configured".into())
84 })?;
85 let source = projection.reader.source_graph_commit_epoch();
86 let checked = self.verify_search_projection_epoch_range(source, target)?;
87 let result = projection.reader.advance_source_graph_commit_epoch(target);
88 // Refresh even on error: never infer rollback from an error alone.
89 self.refresh_incremental_search_reader()?;
90 let mut report = result?;
91 report.checked_change_log_entries = checked.checked_change_log_entries;
92 report.allowed_relational_change_count = checked.allowed_relational_change_count;
93 return Ok(report);
94 }
95 let projection = require_search_projection_mut(&mut self.search_projection)?;
96 let durable = projection
97 .index()
98 .projection_freshness()
99 .durable_source_graph_commit_epoch;
100 if projection.uncheckpointed_initial_import_deltas != 0 {
101 return Err(HawDBError::SearchProjectionEpochAdvanceRefused {
102 reason: SearchProjectionEpochAdvanceRefusal::UncheckpointedChanges,
103 source_graph_commit_epoch: durable,
104 target_graph_commit_epoch: target,
105 message:
106 "initial-import pages are applied but not checkpointed; checkpoint them first"
107 .into(),
108 });
109 }
110 let source = projection
111 .index()
112 .projection_freshness()
113 .source_graph_commit_epoch;
114 if source != durable {
115 return Err(HawDBError::SearchProjectionEpochAdvanceRefused {
116 reason: SearchProjectionEpochAdvanceRefusal::UncheckpointedChanges,
117 source_graph_commit_epoch: durable,
118 target_graph_commit_epoch: target,
119 message: "the resident projection's source epoch is not checkpointed; checkpoint it, or apply and checkpoint the range".into(),
120 });
121 }
122 let checked = self.verify_search_projection_epoch_range(source, target)?;
123 let projection = require_search_projection_mut(&mut self.search_projection)?;
124 let mut report = projection
125 .index_mut()
126 .advance_source_graph_commit_epoch(target)?;
127 report.checked_change_log_entries = checked.checked_change_log_entries;
128 report.allowed_relational_change_count = checked.allowed_relational_change_count;
129 Ok(report)
130 }
131
132 fn verify_search_projection_epoch_range(
133 &self,
134 source: Option<u64>,
135 target: u64,
136 ) -> Result<crate::SearchProjectionEpochAdvanceVerification> {
137 let Some(source) = source else {
138 return Err(HawDBError::SearchProjectionEpochAdvanceRefused {
139 reason: SearchProjectionEpochAdvanceRefusal::RangeUnavailable,
140 source_graph_commit_epoch: None,
141 target_graph_commit_epoch: target,
142 message: "the search projection has no source graph commit epoch to advance from"
143 .into(),
144 });
145 };
146 if target < source {
147 return Err(HawDBError::Semantic(format!(
148 "search projection epoch advance target {target} is below the projection's source epoch {source}"
149 )));
150 }
151 self.graph
152 .database()
153 .verify_search_projection_epoch_advance(
154 source,
155 target,
156 &self.non_projection_relational_tables,
157 )
158 }
159}