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)]
86#[non_exhaustive]
87pub enum ShadowStep {
88 /// Drop any orphan shadow, create a fresh one from the declared DDL.
89 Begin,
90 /// Project the next `SOURCES_PER_CHUNK` sources into the shadow.
91 Fill { after: Option<String> },
92 /// Catch up on writes since `build_start`, then swap. One transaction.
93 ///
94 /// `epoch` is the archive count [`ShadowOutcome::Started`] reported. It
95 /// travels out to the caller and back rather than being remembered by the
96 /// actor: the actor is stateless per command by construction, and a single
97 /// remembered slot would be shared — and silently corrupted — by two
98 /// rebuilds running at once.
99 Swap { build_start: String, epoch: u64 },
100}
101
102/// What a [`ShadowStep`] produced.
103#[derive(Debug, Clone, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum ShadowOutcome {
106 /// `build_start`, and the actor's archive epoch as of the start.
107 Started { build_start: String, epoch: u64 },
108 /// The last `source_id` projected, or `None` when the table is exhausted.
109 Filled { last: Option<String> },
110 /// Rows in the new `links_current`.
111 Swapped { rows: usize },
112}
113
114/// The latest-belief projection, restricted by a `WHERE` on `links`.
115///
116/// Takes the same shape as [`LATEST_BELIEF_PROJECTION`](super::LATEST_BELIEF_PROJECTION)
117/// and exists so the restriction lands **inside** the subquery. Applied outside
118/// it, the window function would still rank every partition in the table and the
119/// chunk would cost as much as the whole rebuild.
120fn projection_where(clause: &str) -> String {
121 format!(
122 r#"
123 SELECT source_id, target_id, edge_type, valid_from,
124 valid_to, weight, properties, recorded_at, branch_id
125 FROM (
126 SELECT source_id, target_id, edge_type, valid_from,
127 valid_to, weight, properties, recorded_at, branch_id,
128 ROW_NUMBER() OVER (
129 PARTITION BY source_id, target_id, edge_type, valid_from, branch_id
130 ORDER BY recorded_at DESC
131 ) AS rn
132 FROM links
133 WHERE {clause}
134 ) WHERE rn = 1
135 "#
136 )
137}
138
139const SHADOW_COLUMNS: &str = "(source_id, target_id, edge_type, valid_from, \
140 valid_to, weight, properties, recorded_at, branch_id)";
141
142/// Create the shadow, and report the transaction time the build starts from.
143///
144/// `build_start` is `MAX(recorded_at)` **before** any chunk runs, so every write
145/// that lands during the build is at or after it and the catch-up pass can find
146/// them all by that one column. Taking it after the first chunk would leave a
147/// gap no later pass could name.
148pub(crate) async fn begin(conn: &libsql::Connection) -> Result<String> {
149 // An orphan from a crashed attempt is dropped rather than reused: its
150 // contents are a projection of a `links` that has since moved on, and there
151 // is no way to tell how far.
152 conn.execute(&format!("DROP TABLE IF EXISTS {SHADOW_TABLE}"), ())
153 .await?;
154 conn.execute(&shadow_ddl(), ()).await?;
155
156 let build_start: Option<String> = conn
157 .query("SELECT MAX(recorded_at) FROM links", ())
158 .await?
159 .next()
160 .await?
161 .and_then(|row| row.get(0).ok());
162
163 // An empty `links` still needs a stamp the catch-up can compare against.
164 // The epoch sentinel is below every canonical timestamp, so the catch-up
165 // sees every row — which on an empty table is none, and on a table written
166 // to during the build is all of them. Correct in both directions.
167 Ok(build_start.unwrap_or_else(|| "0001-01-01T00:00:00.000000Z".to_string()))
168}
169
170/// [`CREATE_LINKS_CURRENT_TABLE`](ddl::CREATE_LINKS_CURRENT_TABLE) with the
171/// table name substituted — primary key, `CHECK`s and all.
172///
173/// Substituted rather than written out, so the shadow cannot drift from the
174/// declared table. See the module header for what happens when it does.
175fn shadow_ddl() -> String {
176 ddl::CREATE_LINKS_CURRENT_TABLE.replacen("links_current", SHADOW_TABLE, 1)
177}
178
179/// Project one chunk of sources into the shadow.
180///
181/// Returns the last `source_id` written, or `None` when there is nothing left.
182pub(crate) async fn fill_chunk(
183 conn: &libsql::Connection,
184 after: Option<&str>,
185) -> Result<Option<String>> {
186 // Keyset pagination over the *distinct* sources, so the boundary is a real
187 // source and a chunk never splits one. `links`'s primary key leads on
188 // `source_id`, so this is an index range scan of at most SOURCES_PER_CHUNK
189 // distinct values rather than a pass over the table.
190 let low = after.unwrap_or("");
191 let high: Option<String> = conn
192 .query(
193 &format!(
194 "SELECT MAX(source_id) FROM ( \
195 SELECT DISTINCT source_id FROM links \
196 WHERE source_id > ?1 ORDER BY source_id LIMIT {SOURCES_PER_CHUNK} \
197 )"
198 ),
199 libsql::params![low],
200 )
201 .await?
202 .next()
203 .await?
204 .and_then(|row| row.get::<Option<String>>(0).ok())
205 .flatten();
206
207 let Some(high) = high else {
208 return Ok(None);
209 };
210
211 conn.execute(
212 &format!(
213 "INSERT INTO {SHADOW_TABLE} {SHADOW_COLUMNS} {projection}",
214 projection = projection_where("source_id > ?1 AND source_id <= ?2")
215 ),
216 libsql::params![low, high.as_str()],
217 )
218 .await?;
219
220 Ok(Some(high))
221}
222
223/// Catch up, then swap. One transaction, and the only moment `links_current` is
224/// not the live table.
225///
226/// `epoch` is the actor's archive count from [`begin`]. If an archive committed
227/// during the build, the shadow is a projection of rows some of which no longer
228/// exist — a *deletion* the catch-up cannot see, because the catch-up finds work
229/// by `recorded_at` and a deleted row has no `recorded_at` to find. Rather than
230/// making the swap verify itself (O(E log E) under the lock, which is the cost
231/// this exists to remove), the rebuild is abandoned and the caller told to
232/// retry. Archives are rare and a retry is cheap; a silently wrong `links_current`
233/// is neither.
234pub(crate) async fn swap(
235 conn: &libsql::Connection,
236 build_start: &str,
237 epoch: u64,
238 epoch_now: u64,
239) -> Result<usize> {
240 if epoch != epoch_now {
241 conn.execute(&format!("DROP TABLE IF EXISTS {SHADOW_TABLE}"), ())
242 .await?;
243 return Err(DbError::RebuildInterrupted {
244 reason: format!(
245 "{} archive session(s) committed during the shadow build; their \
246 deletions are invisible to a catch-up keyed on recorded_at. \
247 Re-run rebuild_current_chunked.",
248 epoch_now - epoch
249 ),
250 });
251 }
252
253 let tx = conn
254 .transaction_with_behavior(libsql::TransactionBehavior::Immediate)
255 .await?;
256
257 // --- catch-up: only the keys written since the build began ---
258 //
259 // Bounded by writes during the rebuild, not by the size of `links`. The
260 // `DELETE` and the re-`INSERT` are both restricted by the same subquery, so
261 // a key written during the build is replaced rather than duplicated.
262 //
263 // `branch_id` is deliberately *not* in this key, and leaving it out is what
264 // keeps the pass correct rather than what breaks it (v12, §15.2). The
265 // `DELETE` clears every lineage's row for a touched edge and the `INSERT`
266 // re-derives every lineage's winner for the same edges, so the pair stays
267 // symmetric. Narrowing the delete by lineage without narrowing the
268 // projection would insert a second lineage's row beside one never removed.
269 let touched = "(source_id, target_id, edge_type, valid_from) IN ( \
270 SELECT source_id, target_id, edge_type, valid_from \
271 FROM links WHERE recorded_at >= ?1)";
272 tx.execute(
273 &format!("DELETE FROM {SHADOW_TABLE} WHERE {touched}"),
274 libsql::params![build_start],
275 )
276 .await?;
277 tx.execute(
278 &format!(
279 "INSERT INTO {SHADOW_TABLE} {SHADOW_COLUMNS} {projection}",
280 projection = projection_where(
281 "(source_id, target_id, edge_type, valid_from) IN ( \
282 SELECT source_id, target_id, edge_type, valid_from \
283 FROM links WHERE recorded_at >= ?1)"
284 )
285 ),
286 libsql::params![build_start],
287 )
288 .await?;
289
290 // --- the swap, in the one order that works ---
291 for stmt in [
292 "DROP TRIGGER IF EXISTS trg_links_current_sync",
293 "DROP TRIGGER IF EXISTS trg_links_single_open",
294 "DROP TABLE links_current",
295 ] {
296 tx.execute(stmt, ()).await?;
297 }
298 tx.execute(
299 &format!("ALTER TABLE {SHADOW_TABLE} RENAME TO links_current"),
300 (),
301 )
302 .await?;
303
304 // The names are free now that the old table is gone, and reusable in this
305 // same transaction (probed). Taken from the crate's own DDL so the rebuilt
306 // indexes cannot differ from the declared ones.
307 for stmt in ddl::CREATE_INDICES {
308 if stmt.contains("links_current") {
309 tx.execute(stmt, ()).await?;
310 }
311 }
312 for trigger in ddl::CREATE_TRIGGERS {
313 if trigger.contains("trg_links_current_sync") || trigger.contains("trg_links_single_open") {
314 tx.execute(trigger, ()).await?;
315 }
316 }
317
318 let rows: i64 = tx
319 .query("SELECT COUNT(*) FROM links_current", ())
320 .await?
321 .next()
322 .await?
323 .and_then(|row| row.get(0).ok())
324 .unwrap_or(0);
325
326 tx.commit().await?;
327 Ok(rows as usize)
328}
329
330#[cfg(test)]
331mod tests {
332 use super::*;
333
334 /// The shadow's DDL must be the declared table's, with only the name changed.
335 ///
336 /// This is the silent failure from the module header, pinned at the cheapest
337 /// possible level. If the substitution ever stops producing a primary key,
338 /// the swap still succeeds and `trg_links_current_sync` breaks on the next
339 /// write — a failure whose symptom appears on an unrelated operation.
340 #[test]
341 fn the_shadow_carries_the_declared_schema_not_just_the_columns() {
342 let ddl = shadow_ddl();
343 assert!(ddl.contains(SHADOW_TABLE), "{ddl}");
344 // Not a pinned literal. The property that matters is that the
345 // shadow's key and the sync trigger's `ON CONFLICT` target are the
346 // *same* columns, so the check reads the target out of the trigger
347 // and asks the shadow for it. Pinning the text instead meant that
348 // widening the key at v12 produced a red test whose fix was to
349 // retype the new spelling — which proves the two were edited
350 // together once, and nothing about whether they still agree.
351 let target = ddl::CREATE_LINKS_CURRENT_SYNC
352 .split_once("ON CONFLICT(")
353 .and_then(|(_, rest)| rest.split_once(')'))
354 .map(|(cols, _)| cols.to_string())
355 .expect("the sync trigger declares an ON CONFLICT target");
356 assert!(
357 ddl.contains(&format!("PRIMARY KEY ({target})")),
358 "the shadow's primary key is not the sync trigger's ON CONFLICT \
359 target ({target}), so the trigger breaks on the first write \
360 after the swap: {ddl}"
361 );
362 assert!(
363 ddl.contains("CHECK"),
364 "the shadow dropped the canonical-timestamp checks: {ddl}"
365 );
366 // Only the table name changed — `links_current` must not survive
367 // anywhere in the shadow's own DDL.
368 assert!(
369 !ddl.replace(SHADOW_TABLE, "").contains("links_current"),
370 "the substitution left a reference to the live table: {ddl}"
371 );
372 }
373
374 /// The chunk restriction has to sit inside the window function's subquery.
375 ///
376 /// Outside it, the projection still ranks every partition in `links` and a
377 /// chunk costs what the whole rebuild costs — the query would be correct and
378 /// the chunking pointless, which is the kind of thing that only shows up in
379 /// a benchmark nobody ran.
380 #[test]
381 fn the_chunk_restriction_is_inside_the_window() {
382 let sql = projection_where("source_id > ?1 AND source_id <= ?2");
383 let inner = sql.find("FROM links").unwrap();
384 let outer = sql.rfind("WHERE rn = 1").unwrap();
385 let clause = sql.find("source_id > ?1").unwrap();
386 assert!(
387 clause > inner && clause < outer,
388 "the restriction landed outside the subquery:\n{sql}"
389 );
390 }
391}