macrame/integrity/shadow.rs
1//! Rebuilding `links_current` beside itself, in chunks (T1.2, D-082).
2//!
3//! # What this is for
4//!
5//! `rebuild_current` is one `BEGIN IMMEDIATE … COMMIT` holding the write lock
6//! for its whole duration — measured at 318 ms for 40,000 rows in `links`
7//! (D-077), and D-023 is why it cannot simply be split: the window between the
8//! `DELETE` and the `INSERT` is the entire of current belief, and a reader
9//! landing in it sees a graph with no edges and no error.
10//!
11//! Building the replacement *beside* the live table removes that window. The
12//! live table stays live and trigger-maintained throughout, so readers and
13//! `trg_links_single_open` keep working, and the only moment anything is
14//! unavailable is the swap.
15//!
16//! # Two things about this are easy to get wrong, and one of them is silent
17//!
18//! **`CREATE TABLE … AS SELECT` does not carry the schema.** The obvious way to
19//! make a shadow copies the rows and *nothing else*: no primary key, no `CHECK`
20//! constraints, no indexes. The swap then succeeds, the rename succeeds, and the
21//! next `INSERT INTO links` fails inside `trg_links_current_sync` with `ON
22//! CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint` —
23//! because the conflict target no longer exists. Probed on libSQL 0.9.30; the
24//! projection had stopped being maintained and the only symptom was an error on
25//! an unrelated write. The shadow is therefore created from
26//! [`CREATE_LINKS_CURRENT_TABLE`](crate::schema::ddl::CREATE_LINKS_CURRENT_TABLE)
27//! with the name substituted, so it cannot drift from the declared table.
28//!
29//! **The rename reparses the whole schema.** `ALTER TABLE … RENAME` (SQLite
30//! ≥ 3.25) re-resolves every trigger body, and both `links` triggers name
31//! `links_current` — so the rename fails with `error in trigger
32//! trg_links_current_sync: no such table: main.links_current` while they exist.
33//! Probed. The order that works, also probed, is `DROP TRIGGER` → `DROP TABLE` →
34//! `RENAME` → `CREATE INDEX` → recreate triggers. `PRAGMA legacy_alter_table=ON`
35//! also works and is **not** used: it disables the reference fixups the modern
36//! rename exists to perform.
37//!
38//! # Why the indexes are built inside the swap and not on the shadow
39//!
40//! This is the one place the shape is dictated by SQLite rather than chosen.
41//! Index names are global, so the shadow cannot carry `idx_lc_traversal_cover`
42//! while the live table still holds that name — and SQLite has no `ALTER INDEX
43//! … RENAME`. Building them on the shadow under temporary names would leave
44//! `links_current` permanently indexed under names that do not appear in
45//! [`CREATE_INDICES`](crate::schema::ddl::CREATE_INDICES), so the next migration
46//! would create a **second** copy of each.
47//!
48//! `DROP TABLE links_current` frees the names, and they are reusable within the
49//! same transaction (probed). So the swap pays the index builds, and what the
50//! chunking buys is that the *projection* — the window function over all of
51//! `links`, which is the O(E log E) term — happens outside the lock. That is a
52//! smaller win than "the swap is microseconds", which is what the naive reading
53//! of the shadow idea promises, and it is the real one.
54
55use crate::error::{DbError, Result};
56use crate::schema::ddl;
57
58/// The table the replacement is built in.
59///
60/// One fixed name rather than a unique one per attempt: a crashed rebuild must
61/// leave something a later attempt can recognise and drop, not an accumulating
62/// set of orphans that nothing knows the names of.
63pub(crate) const SHADOW_TABLE: &str = "links_current_shadow";
64
65/// Distinct `source_id`s projected per chunk.
66///
67/// Sized against [`CHUNK_BUDGET`](crate::CHUNK_BUDGET) rather than derived from
68/// it, and the unit is sources rather than rows for a reason that is also a
69/// limitation: the chunk boundary has to be a range the window function can be
70/// restricted to, and `PARTITION BY (source_id, target_id, edge_type,
71/// valid_from)` means a partition never spans a `source_id`. So a source is the
72/// smallest safe unit — and a single hub node with a very large out-degree is
73/// one chunk however long it takes. That case is bounded by the graph, not by
74/// this constant, and no chunking of this shape can fix it.
75pub(crate) const SOURCES_PER_CHUNK: usize = 256;
76
77/// One step of a chunked rebuild, as sent to the actor.
78///
79/// Three commands rather than one because each must be its own **turn** — the
80/// whole point is that the actor returns to its `select!` between chunks, so a
81/// high-priority assertion can jump ahead. A loop inside one command would
82/// produce the same small transactions inside one hold and buy nothing, which is
83/// the same trap [`Database::archive_windowed`](crate::Database::archive_windowed)
84/// avoids.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum ShadowStep {
87 /// Drop any orphan shadow, create a fresh one from the declared DDL.
88 Begin,
89 /// Project the next [`SOURCES_PER_CHUNK`] sources into the shadow.
90 Fill { after: Option<String> },
91 /// Catch up on writes since `build_start`, then swap. One transaction.
92 ///
93 /// `epoch` is the archive count [`ShadowOutcome::Started`] reported. It
94 /// travels out to the caller and back rather than being remembered by the
95 /// actor: the actor is stateless per command by construction, and a single
96 /// remembered slot would be shared — and silently corrupted — by two
97 /// rebuilds running at once.
98 Swap { build_start: String, epoch: u64 },
99}
100
101/// What a [`ShadowStep`] produced.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum ShadowOutcome {
104 /// `build_start`, and the actor's archive epoch as of the start.
105 Started { build_start: String, epoch: u64 },
106 /// The last `source_id` projected, or `None` when the table is exhausted.
107 Filled { last: Option<String> },
108 /// Rows in the new `links_current`.
109 Swapped { rows: usize },
110}
111
112/// The latest-belief projection, restricted by a `WHERE` on `links`.
113///
114/// Takes the same shape as [`LATEST_BELIEF_PROJECTION`](super::LATEST_BELIEF_PROJECTION)
115/// and exists so the restriction lands **inside** the subquery. Applied outside
116/// it, the window function would still rank every partition in the table and the
117/// chunk would cost as much as the whole rebuild.
118fn projection_where(clause: &str) -> String {
119 format!(
120 r#"
121 SELECT source_id, target_id, edge_type, valid_from,
122 valid_to, weight, properties, recorded_at
123 FROM (
124 SELECT source_id, target_id, edge_type, valid_from,
125 valid_to, weight, properties, recorded_at,
126 ROW_NUMBER() OVER (
127 PARTITION BY source_id, target_id, edge_type, valid_from
128 ORDER BY recorded_at DESC
129 ) AS rn
130 FROM links
131 WHERE {clause}
132 ) WHERE rn = 1
133 "#
134 )
135}
136
137const SHADOW_COLUMNS: &str = "(source_id, target_id, edge_type, valid_from, \
138 valid_to, weight, properties, recorded_at)";
139
140/// Create the shadow, and report the transaction time the build starts from.
141///
142/// `build_start` is `MAX(recorded_at)` **before** any chunk runs, so every write
143/// that lands during the build is at or after it and the catch-up pass can find
144/// them all by that one column. Taking it after the first chunk would leave a
145/// gap no later pass could name.
146pub(crate) async fn begin(conn: &libsql::Connection) -> Result<String> {
147 // An orphan from a crashed attempt is dropped rather than reused: its
148 // contents are a projection of a `links` that has since moved on, and there
149 // is no way to tell how far.
150 conn.execute(&format!("DROP TABLE IF EXISTS {SHADOW_TABLE}"), ())
151 .await?;
152 conn.execute(&shadow_ddl(), ()).await?;
153
154 let build_start: Option<String> = conn
155 .query("SELECT MAX(recorded_at) FROM links", ())
156 .await?
157 .next()
158 .await?
159 .and_then(|row| row.get(0).ok());
160
161 // An empty `links` still needs a stamp the catch-up can compare against.
162 // The epoch sentinel is below every canonical timestamp, so the catch-up
163 // sees every row — which on an empty table is none, and on a table written
164 // to during the build is all of them. Correct in both directions.
165 Ok(build_start.unwrap_or_else(|| "0001-01-01T00:00:00.000000Z".to_string()))
166}
167
168/// [`CREATE_LINKS_CURRENT_TABLE`](ddl::CREATE_LINKS_CURRENT_TABLE) with the
169/// table name substituted — primary key, `CHECK`s and all.
170///
171/// Substituted rather than written out, so the shadow cannot drift from the
172/// declared table. See the module header for what happens when it does.
173fn shadow_ddl() -> String {
174 ddl::CREATE_LINKS_CURRENT_TABLE.replacen("links_current", SHADOW_TABLE, 1)
175}
176
177/// Project one chunk of sources into the shadow.
178///
179/// Returns the last `source_id` written, or `None` when there is nothing left.
180pub(crate) async fn fill_chunk(
181 conn: &libsql::Connection,
182 after: Option<&str>,
183) -> Result<Option<String>> {
184 // Keyset pagination over the *distinct* sources, so the boundary is a real
185 // source and a chunk never splits one. `links`'s primary key leads on
186 // `source_id`, so this is an index range scan of at most SOURCES_PER_CHUNK
187 // distinct values rather than a pass over the table.
188 let low = after.unwrap_or("");
189 let high: Option<String> = conn
190 .query(
191 &format!(
192 "SELECT MAX(source_id) FROM ( \
193 SELECT DISTINCT source_id FROM links \
194 WHERE source_id > ?1 ORDER BY source_id LIMIT {SOURCES_PER_CHUNK} \
195 )"
196 ),
197 libsql::params![low],
198 )
199 .await?
200 .next()
201 .await?
202 .and_then(|row| row.get::<Option<String>>(0).ok())
203 .flatten();
204
205 let Some(high) = high else {
206 return Ok(None);
207 };
208
209 conn.execute(
210 &format!(
211 "INSERT INTO {SHADOW_TABLE} {SHADOW_COLUMNS} {projection}",
212 projection = projection_where("source_id > ?1 AND source_id <= ?2")
213 ),
214 libsql::params![low, high.as_str()],
215 )
216 .await?;
217
218 Ok(Some(high))
219}
220
221/// Catch up, then swap. One transaction, and the only moment `links_current` is
222/// not the live table.
223///
224/// `epoch` is the actor's archive count from [`begin`]. If an archive committed
225/// during the build, the shadow is a projection of rows some of which no longer
226/// exist — a *deletion* the catch-up cannot see, because the catch-up finds work
227/// by `recorded_at` and a deleted row has no `recorded_at` to find. Rather than
228/// making the swap verify itself (O(E log E) under the lock, which is the cost
229/// this exists to remove), the rebuild is abandoned and the caller told to
230/// retry. Archives are rare and a retry is cheap; a silently wrong `links_current`
231/// is neither.
232pub(crate) async fn swap(
233 conn: &libsql::Connection,
234 build_start: &str,
235 epoch: u64,
236 epoch_now: u64,
237) -> Result<usize> {
238 if epoch != epoch_now {
239 conn.execute(&format!("DROP TABLE IF EXISTS {SHADOW_TABLE}"), ())
240 .await?;
241 return Err(DbError::RebuildInterrupted {
242 reason: format!(
243 "{} archive session(s) committed during the shadow build; their \
244 deletions are invisible to a catch-up keyed on recorded_at. \
245 Re-run rebuild_current_chunked.",
246 epoch_now - epoch
247 ),
248 });
249 }
250
251 let tx = conn
252 .transaction_with_behavior(libsql::TransactionBehavior::Immediate)
253 .await?;
254
255 // --- catch-up: only the keys written since the build began ---
256 //
257 // Bounded by writes during the rebuild, not by the size of `links`. The
258 // `DELETE` and the re-`INSERT` are both restricted by the same subquery, so
259 // a key written during the build is replaced rather than duplicated.
260 let touched = "(source_id, target_id, edge_type, valid_from) IN ( \
261 SELECT source_id, target_id, edge_type, valid_from \
262 FROM links WHERE recorded_at >= ?1)";
263 tx.execute(
264 &format!("DELETE FROM {SHADOW_TABLE} WHERE {touched}"),
265 libsql::params![build_start],
266 )
267 .await?;
268 tx.execute(
269 &format!(
270 "INSERT INTO {SHADOW_TABLE} {SHADOW_COLUMNS} {projection}",
271 projection = projection_where(
272 "(source_id, target_id, edge_type, valid_from) IN ( \
273 SELECT source_id, target_id, edge_type, valid_from \
274 FROM links WHERE recorded_at >= ?1)"
275 )
276 ),
277 libsql::params![build_start],
278 )
279 .await?;
280
281 // --- the swap, in the one order that works ---
282 for stmt in [
283 "DROP TRIGGER IF EXISTS trg_links_current_sync",
284 "DROP TRIGGER IF EXISTS trg_links_single_open",
285 "DROP TABLE links_current",
286 ] {
287 tx.execute(stmt, ()).await?;
288 }
289 tx.execute(
290 &format!("ALTER TABLE {SHADOW_TABLE} RENAME TO links_current"),
291 (),
292 )
293 .await?;
294
295 // The names are free now that the old table is gone, and reusable in this
296 // same transaction (probed). Taken from the crate's own DDL so the rebuilt
297 // indexes cannot differ from the declared ones.
298 for stmt in ddl::CREATE_INDICES {
299 if stmt.contains("links_current") {
300 tx.execute(stmt, ()).await?;
301 }
302 }
303 for trigger in ddl::CREATE_TRIGGERS {
304 if trigger.contains("trg_links_current_sync") || trigger.contains("trg_links_single_open") {
305 tx.execute(trigger, ()).await?;
306 }
307 }
308
309 let rows: i64 = tx
310 .query("SELECT COUNT(*) FROM links_current", ())
311 .await?
312 .next()
313 .await?
314 .and_then(|row| row.get(0).ok())
315 .unwrap_or(0);
316
317 tx.commit().await?;
318 Ok(rows as usize)
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 /// The shadow's DDL must be the declared table's, with only the name changed.
326 ///
327 /// This is the silent failure from the module header, pinned at the cheapest
328 /// possible level. If the substitution ever stops producing a primary key,
329 /// the swap still succeeds and `trg_links_current_sync` breaks on the next
330 /// write — a failure whose symptom appears on an unrelated operation.
331 #[test]
332 fn the_shadow_carries_the_declared_schema_not_just_the_columns() {
333 let ddl = shadow_ddl();
334 assert!(ddl.contains(SHADOW_TABLE), "{ddl}");
335 assert!(
336 ddl.contains("PRIMARY KEY (source_id, target_id, edge_type, valid_from)"),
337 "the shadow has no primary key, so the sync trigger's ON CONFLICT \
338 target will not exist after the swap: {ddl}"
339 );
340 assert!(
341 ddl.contains("CHECK"),
342 "the shadow dropped the canonical-timestamp checks: {ddl}"
343 );
344 // Only the table name changed — `links_current` must not survive
345 // anywhere in the shadow's own DDL.
346 assert!(
347 !ddl.replace(SHADOW_TABLE, "").contains("links_current"),
348 "the substitution left a reference to the live table: {ddl}"
349 );
350 }
351
352 /// The chunk restriction has to sit inside the window function's subquery.
353 ///
354 /// Outside it, the projection still ranks every partition in `links` and a
355 /// chunk costs what the whole rebuild costs — the query would be correct and
356 /// the chunking pointless, which is the kind of thing that only shows up in
357 /// a benchmark nobody ran.
358 #[test]
359 fn the_chunk_restriction_is_inside_the_window() {
360 let sql = projection_where("source_id > ?1 AND source_id <= ?2");
361 let inner = sql.find("FROM links").unwrap();
362 let outer = sql.rfind("WHERE rn = 1").unwrap();
363 let clause = sql.find("source_id > ?1").unwrap();
364 assert!(
365 clause > inner && clause < outer,
366 "the restriction landed outside the subquery:\n{sql}"
367 );
368 }
369}