macrame/connection.rs
1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3use tokio::sync::{mpsc, oneshot};
4
5use crate::error::{classify, BulkInterrupted, BulkResult, DbError, Result, WriteOp};
6use crate::graph::edge::EdgeAssertion;
7use crate::graph::lineage::LineageShape;
8use crate::integrity::{rebuild_current, RebuildReport};
9use crate::schema::migrations;
10use crate::temporal::archive::{archive, rehydrate, ArchiveReport, RehydrateReport};
11use crate::temporal::interval::Interval;
12use crate::temporal::snapshot::{self, SnapshotCadence};
13use crate::util::clock::FutureStampPolicy;
14use crate::util::clock::{Clock, SystemClock};
15use crate::util::timestamp;
16use crate::vector::ModelName;
17
18/// Rows per chunk on the background write paths (§5.1.5, D-011, D-014, D-058).
19///
20/// The Write Actor holds the sole write connection, so a single large statement
21/// blocks every other writer for its duration. Chunking bounds that stall; the
22/// cost is that a bulk import is *not* atomic across chunks, which is why
23/// all-or-nothing is [`Database::write_bulk_atomic`] — a separate entry point,
24/// with its own command on the actor's protocol — rather than a tuning
25/// parameter here.
26///
27/// # Why these are four constants and not one
28///
29/// Through 0.5.5 this was a single `CHUNK_ROWS = 1000` for all four bulk paths.
30/// The golden rule it was meant to serve is a bound on *duration* — a background
31/// chunk must commit fast enough that an interactive write queued behind it is
32/// not made to wait — and one row count cannot express one duration across paths
33/// whose measured per-row costs differ by 60× (D-058). At 1,000 rows the four
34/// paths took 3.5 ms, 24 ms, 89 ms and 143 ms: the same constant, four answers,
35/// three of them far outside the bound.
36///
37/// Each size below is derived from `benches/budgets.rs`'s `chunk_scaling`
38/// sweep against [`CHUNK_BUDGET`], then verified by measuring that size directly.
39/// They are *measurements of this machine*, not universal constants — D-055's
40/// reasoning about reference hardware applies here too, and re-deriving them on
41/// materially different storage is a `cargo bench` away.
42///
43/// # Sized for the tail, not the median
44///
45/// The first derivation solved `f + c·n = 3 ms` exactly and produced sizes whose
46/// *median* commit was 2.93 ms and whose upper estimate was 2.96 — inside the
47/// bound as reported and outside it for any chunk slower than typical. A latency
48/// bound is a statement about the chunk an unlucky interactive write actually
49/// queues behind, so these solve for ≈2.5 ms instead, leaving the remainder as
50/// headroom for the tail. That costs a few percent of throughput on the two
51/// linear paths and nothing on the two superlinear ones.
52///
53/// As measured by `chunk_budget`, each at its own size: edges **2.39 ms**,
54/// concepts **2.35 ms**, annotations **2.36 ms**, embeddings **2.06 ms**, no
55/// upper estimate above 2.42.
56///
57/// # Known limitation: these are empty-database figures
58///
59/// `chunk_budget` seeds concepts and starts with **no links and no vectors**,
60/// and D-059 established that per-row cost on the edge and embedding paths grows
61/// with the size of the structure being written, not with the chunk. The same
62/// 90-edge chunk takes **9.06 ms** into an 8,000-edge table. So the bound is met
63/// as measured here and *not* met on a populated database.
64///
65/// That gap was published as 47.7 ms until 0.10.0 and attributed to the schema
66/// defect D-059 documents. The defect was fixed by the `v5 → v6` rung and the
67/// figure was never updated. 9.08 ms is a 0.10.0 measurement, not D-059's 8.0 ms
68/// carried forward: `chunk_budget` gained a seeded arm, because until it did,
69/// nothing in the bench suite wrote a chunk into a populated table and this
70/// number was unfalsifiable. It agrees with D-059 once the session is accounted
71/// for — the empty arm read 2.69 and 2.65 ms beside it against the 2.39 ms
72/// published above, so the *ratio* is 3.4× here and 3.35× there.
73///
74/// **The residual is attributed as of 0.11.0 (D-142).** It is not the missing
75/// index, which shipped in 0.5.6; it is the `links_current` write. Dropping the
76/// three `links` insert triggers one at a time puts effectively all of the
77/// growth in `trg_links_current_sync` — the single-open guard contributes none,
78/// the log trigger and the base insert ~0.35 ms of a 4.15 ms rise — and within
79/// that trigger, 89% of the growth is maintenance of `idx_lc_traversal_cover`
80/// and `idx_lc_open_interval` rather than the upsert itself, which costs 0.49 ms
81/// run directly against the same table. Page-cache size, foreign keys and the
82/// fixture's key distribution were each tested and are each not the cause.
83///
84/// Knowing the cause does not by itself change the constant: the expensive index
85/// is D-042's covering index for the traversal, so narrowing it moves cost onto
86/// the read path it exists to protect. Re-deriving these constants against the
87/// D-088 fixture matrix is the named successor.
88///
89/// # These are ceilings as of 0.12.0, not sizes
90///
91/// D-143 re-derived all four against the D-088 matrix and the edge path came
92/// back **20** against a shipped 90 — and 20 would have been wrong at 80,000
93/// edges for the same reason 90 is wrong at 8,000, because per-row cost there
94/// grows with `links_current`. The finding was that no row count can bound a
95/// duration on such a path.
96///
97/// So the chunk loop stopped trying to pick one ahead of time. Each chunk is
98/// timed by the actor and its measured hold chooses the next size; these
99/// constants are the **largest** size that will ever be asked for, and every
100/// derivation below still applies to them as such. A path may run well under its
101/// constant on a populated database and at exactly it on an empty one, and both
102/// are the bound being met rather than a size being missed.
103pub mod chunk_rows {
104 /// Edge assertions (`bulk_import`).
105 ///
106 /// Per-row cost on this path rises with the size of `links_current`, not
107 /// with the chunk (D-059) — so cutting the chunk buys latency and costs
108 /// throughput, ~11% for 1,000 edges. An earlier version of this comment
109 /// claimed it was 3.3× *faster*; that came from multiplying eleven copies of
110 /// a chunk measured into an empty database.
111 ///
112 /// **This size does not meet the 3 ms bound on a populated database.** 90
113 /// edges into an 8,000-edge table take **9.06 ms** — measured, two sessions
114 /// at 9.08 and 9.05, against an empty-table arm of 2.69 and 2.65 beside
115 /// them (D-136).
116 ///
117 /// The reason given here until 0.10.0 — that `trg_links_single_open`'s
118 /// `EXISTS` scans the whole out-degree, "a schema defect with a proven fix,
119 /// recorded in D-059 and not applied here" — described 0.5.5. The fix *was*
120 /// applied, as the `v5 → v6` rung, and took this from 47.7 ms to ~8 ms.
121 /// What survives is the miss: the bound is still exceeded ~3×. Its cause is
122 /// no longer unknown — D-142 attributes it to `trg_links_current_sync`, and
123 /// within that to secondary-index maintenance on `links_current` — and the
124 /// guard this comment used to blame contributes **no** growth at all.
125 ///
126 /// **The constant is unchanged, and that is now a measured decision**
127 /// (D-143). Re-derived against all four D-088 shapes at 8,000 edges, they
128 /// agree that the largest size meeting the bound is **20**. It stays at 90
129 /// because 20 is the same miss at a larger population — per-row cost grows
130 /// with `links_current`, so a constant fitted at 8,000 edges is wrong at
131 /// 80,000 — while the throughput cost of turning eleven chunks into fifty
132 /// is certain and immediate (D-058). The fix is not a row count: it is for
133 /// the chunk loop to stop on elapsed time, **delivered in 0.12.0**. This
134 /// number is now the ceiling that loop starts from and never exceeds; on a
135 /// populated table it converges below it within a chunk or two.
136 ///
137 /// D-134 retired the growth claim on the neighbouring *single-assertion*
138 /// path and did not measure this one; D-136 is why this line now carries a
139 /// measurement rather than a figure quoted from 0.5.6.
140 pub const EDGES: usize = 90;
141
142 /// Concept upserts (`write_concepts`).
143 ///
144 /// Linear at ~23 µs per row, so unlike [`EDGES`] this size *is* a genuine
145 /// throughput sacrifice: 1,000-row chunks ran at 23.6 µs per row against
146 /// ~35 µs here. Paid deliberately — a 1,000-row chunk takes 24 ms, eight
147 /// times the bound.
148 pub const CONCEPTS: usize = 70;
149
150 /// Analytics annotations (`write_analytics_annotations`).
151 ///
152 /// The one path where the old constant was nearly right, and the only bulk
153 /// table with no triggers at all: ~2.5 µs per row, linear, so the bound buys
154 /// a large chunk. 1,000 rows would be 3.5 ms — over, but only just.
155 pub const ANNOTATIONS: usize = 600;
156
157 /// Embedding vectors (`upsert_embeddings`).
158 ///
159 /// The smallest by a wide margin, because DiskANN index maintenance makes an
160 /// embedding the most expensive row in the system. That cost grows with the
161 /// **corpus**, not the chunk (D-059): a fixed 30-vector chunk costs 49 µs per
162 /// vector into an empty corpus and 224 µs into an 8,000-vector one. Graph
163 /// insertion getting dearer as the graph grows is what DiskANN is, so unlike
164 /// [`EDGES`] there is nothing here to fix — but it does mean this size buys
165 /// latency at some throughput, not for free.
166 pub const EMBEDDINGS: usize = 30;
167}
168
169/// What one chunk transaction cost, reported by the actor to the caller-side
170/// chunk loop (0.12.0, W1).
171///
172/// `held` is measured **inside** the actor, around its own transaction, and
173/// therefore excludes the time the command spent queued. That exclusion is the
174/// point: queue time is what strict preemption *does*, and a controller fed
175/// `send + await` would shrink chunks as punishment for the actor correctly
176/// serving an interactive write first.
177///
178/// Crate-internal, along with the command enums that carry it. It was `pub`
179/// through 0.13.32 only because they were (D-206).
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub(crate) struct ChunkOutcome {
182 /// Rows the transaction actually wrote.
183 pub rows: usize,
184 /// How long the actor held the write lock for them.
185 pub held: std::time::Duration,
186}
187
188/// A flag a caller can raise to stop a chunked bulk write (0.13.8, W7.6, D-181).
189///
190/// Cheap to clone and safe to set from any thread, which is the whole point: the
191/// task running the import is the one thing that cannot cancel it. Hand a clone
192/// to whatever *can* — a signal handler, a UI thread, a timeout task — and it
193/// takes effect at the next chunk boundary.
194///
195/// **A boundary, not an abort.** Nothing rolls back and no in-flight
196/// transaction is interrupted: the loop notices between chunks and stops
197/// sending. The chunks that committed stay committed, and
198/// [`BulkInterrupted::written`](crate::BulkInterrupted::written) says how many
199/// rows those were. That is the same per-chunk boundary
200/// [`Database::bulk_import`] already documents, so cancellation adds a reason to
201/// stop and no new failure mode.
202///
203/// Setting it after the last chunk has committed does nothing — a finished
204/// write reports success, because it succeeded.
205#[derive(Clone, Debug, Default)]
206pub struct CancelToken(Arc<std::sync::atomic::AtomicBool>);
207
208impl CancelToken {
209 /// A token that has not been cancelled.
210 pub fn new() -> Self {
211 Self::default()
212 }
213
214 /// Ask the bulk write holding a clone of this token to stop at its next
215 /// chunk boundary. Idempotent; a token never un-cancels.
216 pub fn cancel(&self) {
217 // `Relaxed` on both sides is sufficient and deliberate: nothing is
218 // published *through* this flag. The rows are ordered by the database
219 // and the chunk results by the response channel, so the only thing the
220 // reader needs is to observe the store eventually, which every ordering
221 // guarantees.
222 self.0.store(true, std::sync::atomic::Ordering::Relaxed);
223 }
224
225 /// Whether [`Self::cancel`] has been called on this token or any clone.
226 pub fn is_cancelled(&self) -> bool {
227 self.0.load(std::sync::atomic::Ordering::Relaxed)
228 }
229}
230
231/// One chunk's worth of progress, handed to the callback on
232/// [`BulkControl::on_progress`] (0.13.8, W7.6).
233///
234/// Reported *after* the chunk has committed, so `written` is a count of rows
235/// that are in the database and will stay there even if the next chunk fails.
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub struct BulkProgress {
238 /// Rows committed so far, across every chunk including this one.
239 pub written: usize,
240 /// Rows in the batch the caller passed. `written` reaching this means the
241 /// last chunk has committed.
242 pub total: usize,
243 /// Rows this chunk wrote. Not a constant: the loop resizes chunks against
244 /// [`CHUNK_BUDGET`] as it measures them (D-058).
245 pub rows: usize,
246 /// How long the actor held the write lock for this chunk — the same figure
247 /// the controller steers on. Measured inside the actor, around its own
248 /// transaction, so it excludes the time the command spent queued.
249 pub held: std::time::Duration,
250}
251
252/// Cancellation and progress for the four chunked bulk paths (0.13.8, W7.6,
253/// D-181).
254///
255/// Default is "neither", which is what [`Database::bulk_import`] and its three
256/// siblings pass. The `_with` variants take one of these:
257///
258/// ```no_run
259/// # use macrame::{BulkControl, CancelToken, Database};
260/// # async fn f(db: &Database, edges: Vec<macrame::prelude::EdgeAssertion>) {
261/// let token = CancelToken::new();
262/// let stopper = token.clone();
263/// tokio::spawn(async move {
264/// tokio::time::sleep(std::time::Duration::from_secs(30)).await;
265/// stopper.cancel();
266/// });
267///
268/// let control = BulkControl::new()
269/// .cancel_with(token)
270/// .on_progress(|p| println!("{}/{} rows", p.written, p.total));
271///
272/// match db.bulk_import_with(edges, control).await {
273/// Ok(n) => println!("imported {n}"),
274/// Err(e) => println!("stopped after {}: {}", e.written, e.cause),
275/// }
276/// # }
277/// ```
278///
279/// **The callback runs on the importing task, between chunks.** It is therefore
280/// on the critical path: whatever it does is time the next chunk is not being
281/// sent in. Printing or updating a counter is what it is for; a blocking write
282/// is not, and neither is anything that calls back into the same `Database`,
283/// which would deadlock the loop against a channel it is itself draining.
284#[derive(Default, Clone)]
285pub struct BulkControl {
286 cancel: Option<CancelToken>,
287 on_progress: Option<Arc<dyn Fn(BulkProgress) + Send + Sync>>,
288}
289
290impl std::fmt::Debug for BulkControl {
291 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
292 f.debug_struct("BulkControl")
293 .field("cancel", &self.cancel)
294 .field("on_progress", &self.on_progress.is_some())
295 .finish()
296 }
297}
298
299impl BulkControl {
300 /// Neither cancellation nor progress — what the plain bulk methods pass.
301 pub fn new() -> Self {
302 Self::default()
303 }
304
305 /// Stop at the next chunk boundary when `token` is cancelled.
306 pub fn cancel_with(mut self, token: CancelToken) -> Self {
307 self.cancel = Some(token);
308 self
309 }
310
311 /// Call `f` after every chunk commits. See the note on [`BulkControl`]
312 /// about what this closure is allowed to do.
313 pub fn on_progress(mut self, f: impl Fn(BulkProgress) + Send + Sync + 'static) -> Self {
314 self.on_progress = Some(Arc::new(f));
315 self
316 }
317
318 fn is_cancelled(&self) -> bool {
319 self.cancel.as_ref().is_some_and(CancelToken::is_cancelled)
320 }
321
322 fn report(&self, progress: BulkProgress) {
323 if let Some(f) = &self.on_progress {
324 f(progress);
325 }
326 }
327}
328
329/// Smallest chunk the adaptive loop will fall to (0.12.0, W2).
330///
331/// # A floor is a deliberate, measured violation of [`CHUNK_BUDGET`]
332///
333/// Feedback alone converges to whatever size meets the budget, and on a
334/// populated `links` table that size keeps falling — per-row cost there grows
335/// with the table (D-059, D-142), so there is no size at which the *fixed* cost
336/// of a transaction stops dominating. Left unbounded the loop reaches chunks of
337/// one or two rows, where nearly all the work is `BEGIN`/`COMMIT` and the import
338/// no longer finishes.
339///
340/// 35 is measured, and **re-measured against the loop that uses it** — the
341/// difference matters, because the figure this constant shipped with was an
342/// extrapolation. `examples/chunk_matrix.rs -- converge` runs a 900-edge
343/// `bulk_import` into each of the four D-088 shapes at 8,000 edges and reports
344/// the actor's own per-transaction readings. A 35-row chunk costs **3.11–3.43 ms**
345/// across the four shapes, two sessions, excluding the run-up. The floor misses
346/// the 3 ms bound by 0.1–0.4 ms, not by the ~1.1 ms predicted from the sweep.
347///
348/// The miss is **steady state** — not a one-chunk transient on the way down —
349/// and the defense is the argument [`CHUNK_BUDGET`] is answerable to rather than
350/// the number itself: an interactive assertion arriving at the worst moment
351/// waits ~3.2 ms for the chunk in flight and then runs its own ≤ 5 ms write, so
352/// ~8.2 ms against a 16.7 ms frame.
353///
354/// What the same measurement says about the *size*: on this path at this
355/// population the loop goes `[90, 35, 35, …]` on all four shapes and never picks
356/// anything between. The proportional shrink from a 90-row chunk proposes ~31
357/// rows, which clamps here — so on the edge path the floor is not a safety net
358/// under the controller, it **is** the operating point, and this number is
359/// carrying more weight than a backstop normally would. Re-measure it, not the
360/// controller, when the edge path's per-row cost changes.
361const CHUNK_FLOOR: usize = 35;
362
363/// Size of the next chunk, from what the last one cost (0.12.0, W2).
364///
365/// Pure on purpose — no clock, no database, no actor — so the control law can be
366/// tested for the properties that matter without a fixture. Three regimes:
367///
368/// | last hold | response | why |
369/// |---|---|---|
370/// | over `budget` | shrink to `current · budget / held`, × 0.9 | back off *fast* from a bound already being exceeded; the 0.9 undershoots so the correction does not have to be repeated |
371/// | under `budget / 2` | grow by a quarter of `current`, at least one row | approach the bound *slowly*; the dead band above it stops a size that is merely comfortable from oscillating |
372/// | otherwise | hold | in band, and moving costs more than it buys |
373///
374/// The asymmetry is the whole design. Proportional shrinking converges from
375/// above in one or two steps, which matters because every step over budget is a
376/// latency miss a caller can feel; additive growth cannot overshoot by more than
377/// 25%, which matters because the ceiling is a throughput preference and not a
378/// bound.
379///
380/// `ceiling` is the path's [`chunk_rows`] constant, which is why those constants
381/// keep their values and their derivations: they are no longer the size, they
382/// are the largest size this will ever ask for. `floor` is [`CHUNK_FLOOR`] —
383/// see there for the budget it knowingly misses.
384///
385/// Never returns 0, at any input, including `held == 0` or `current == 0`.
386fn next_chunk_size(
387 current: usize,
388 held: std::time::Duration,
389 budget: std::time::Duration,
390 floor: usize,
391 ceiling: usize,
392) -> usize {
393 let held = held.as_nanos().max(1);
394 let budget_ns = budget.as_nanos().max(1);
395 let current = current.max(1);
396
397 let next = if held > budget_ns {
398 // Integer math, and the `max(1)` matters: a chunk 200× over budget
399 // would otherwise propose 0 and the loop would stop making progress.
400 let scaled = (current as u128) * budget_ns * 9 / (held * 10);
401 (scaled as usize).max(1)
402 } else if held * 2 < budget_ns {
403 // Saturating because `current` is a `usize` and this is the one branch
404 // that adds to it. Nothing sane reaches the boundary; the clamp below
405 // makes the answer correct anyway rather than a debug panic.
406 current.saturating_add((current / 4).max(1))
407 } else {
408 current
409 };
410
411 // Applied last and unconditionally, so a caller that passes a reversed pair
412 // gets the floor rather than a panic — and `max(1)` last of all, because a
413 // chunk of zero rows is the single answer no loop can make progress from.
414 next.clamp(floor.min(ceiling), ceiling).max(1)
415}
416
417/// The latency bound [`chunk_rows`] is derived from (§5.1.5, D-058).
418///
419/// This is the golden rule's actual content. §9 has carried it as a row count
420/// with a duration attached — "chunk commit, 500 rows ≤ 3 ms" — which reads as
421/// two requirements and is one: the duration is the requirement, and the row
422/// count is whatever satisfies it on a given path and machine.
423///
424/// 3 ms is §9's number, kept rather than renegotiated. What it buys, end to end:
425/// an interactive assertion arriving at the worst possible moment waits for the
426/// chunk in flight (≤ 3 ms — the SQLite write lock is not preemptible, so
427/// priority buys the *next* turn and not this one) and then runs its own write
428/// (≤ 5 ms, §9), so ≤ 8 ms
429/// worst case. That fits inside a 60 Hz frame with room, which is the standard
430/// this bound is ultimately answerable to.
431///
432/// # Some operations are exempt, and the exemption is a contract, not an oversight
433///
434/// This was recorded in three separate rustdoc notes and nowhere near the bound
435/// itself, which is where a reader looks for its scope (§8.6). Stated here, with
436/// Wave 3's measurements:
437///
438/// | Path | Bound | Why it cannot be chunked |
439/// |---|---|---|
440/// | [`Database::write_bulk_atomic`] | none — caller-sized `Vec` | D-014: the batch is *one act* under one stamp. Splitting it is the thing the method exists not to do |
441/// | [`Database::archive`] | measured **26.8 ms** for 2,000 archivable edges; see [`Database::archive_windowed`] | D-012: copy-then-delete must be atomic, or a crash between the phases duplicates or loses rows |
442/// | `rebuild_current` | measured **24.6 / 104 / 318 ms** at 4K / 16K / 40K rows in `links` (was "~50 s per 10M edges", which nothing had measured) | D-023: the window between `DELETE` and `INSERT` is the whole of current belief; a reader landing in it sees a graph with no edges and no error |
443/// | [`Database::rehydrate`] | unmeasured; a function of how many rows the caller named | D-012 backwards: the same copy-then-delete atomicity, in the other direction. **A row here since 0.12.9 only because it was previously invisible** — rehydration reported as `archive` and inherited its exemption without anyone deciding on it (W4.3, D-152) |
444/// | [`Database::archive_branch`] | unmeasured; a function of how much one lineage wrote | D-012 again, and D-230's chain: the links, the log entries and the `branches` row leave together or the ledger disagrees with itself about what is currently believed. There is no smaller unit — half a forgotten lineage is a lineage whose reads are answered by its parent |
445/// | the swap turn of [`Database::rebuild_current_chunked`], counted as `shadow_swap` | measured **46.8 ms** at the largest fixture (D-082), and it grows with the table | Index names are global and SQLite has no `ALTER INDEX … RENAME`, so the shadow cannot carry `idx_lc_traversal_cover` while the live table still holds it — all three indexes are built here, under the lock. This is the residual T1.2 could not remove, and there is no smaller unit: half a swapped projection is not a projection. **Exempt since 0.14.16** (W12.16, D-233). The *fill* half keeps its own kind and is deliberately absent from this table, which is what makes a violation there a regression rather than a constant |
446/// | [`Database::checkpoint`] | a function of the WAL's size, which is a function of how long since the last checkpoint — not of anything the caller passes | It is not a transaction at all. `PRAGMA wal_checkpoint` copies frames back into the main file and there is no unit smaller than the frame it is already working in; the caller asked for exactly this, and the alternative to a long checkpoint is a WAL that keeps growing (0.12.13, W5.2, D-156) |
447///
448/// The `archive` figure is end-to-end through this method, so it **includes**
449/// the re-derivation `archive()` runs inside its transaction — but it does not
450/// attribute it, and until D-077 more than half of that re-derivation was an
451/// audit comparing `links_current` against the query that had just filled it.
452/// Note also which variable that cost scales with: `rebuild_within` reprojects
453/// **all of `links`**, so the archive's repair term grows with the *surviving*
454/// table and not with the batch being archived. A budget stated per "100K closed
455/// intervals" ([§9](../docs/architecture/s6-s10-flows-to-dependencies.md)) is
456/// therefore parameterised on the wrong quantity.
457///
458/// The first four are atomic **by contract**, which is why "cap the batch" and
459/// "add a third tier" were both considered and neither was taken: capping breaks the
460/// guarantee the operation exists to provide, and a third tier changes which
461/// caller waits without changing how long the lock is held. What was wrong was
462/// never the exemption — it was that the bound was stated as though it had none.
463///
464/// A caller who needs the latency bound and not the atomicity has
465/// [`Database::bulk_import`], which is the same write chunked at
466/// [`chunk_rows::EDGES`] and explicitly *not* atomic overall (D-011).
467///
468/// # One of them is no longer unbounded (T1.1, D-080)
469///
470/// `archive` was the worst of them, because its hold is a function of *how long
471/// since the last archive* rather than of anything the caller chose.
472/// [`Database::archive_windowed`] runs the same work as N sessions, each
473/// atomic, each its own actor turn. Measured on an 8,000-key fixture with four
474/// generations of superseded history: the longest single hold falls from
475/// **3.3 s to 0.77 s** at one-hour windows, for total wall time that is flat
476/// within this cycle's noise.
477///
478/// The same measurement at 2,000 keys goes the other way — the hold falls
479/// 260 ms → 117 ms while total time rises 260 ms → 671 ms — so windowing is a
480/// trade and not a free improvement. It pays when the backlog is large, which
481/// is when the unwindowed hold is a problem in the first place. `archive` is
482/// kept, not deprecated, for exactly that reason.
483pub const CHUNK_BUDGET: std::time::Duration = std::time::Duration::from_millis(3);
484
485/// Predicted hold above which [`Database::write_bulk_atomic`] warns (T1.3).
486///
487/// 250 ms is fifteen frames at 60 Hz: not a hitch, a visible freeze. It is well
488/// above [`CHUNK_BUDGET`] on purpose — this path is exempt from that bound by
489/// contract, so warning at 3 ms would fire on batches that are working exactly
490/// as designed and train the reader to filter the message out.
491pub const BULK_ATOMIC_WARN_HOLD: std::time::Duration = std::time::Duration::from_millis(250);
492
493/// Roughly how long [`Database::write_bulk_atomic`] will hold the actor for
494/// this batch (T1.3, D-081; re-fitted 0.13.6, W7.5, D-179).
495///
496/// # Two terms, and the batch's shape is no longer one of them
497///
498/// T1.3 asks for "rows × measured per-row cost". Through 0.13.5 that was wrong
499/// in a way worth a paragraph: `write_edges_atomic` opened with a
500/// `reject_overlaps_within` that compared **every pair**, and the quadratic
501/// term's constant depended on the batch's *shape* rather than its size, so two
502/// 20,000-edge batches held the actor for **2.6 s** and **18.1 s** — a size-only
503/// model was off by 7× between them, in the under-predicting direction.
504///
505/// W7.5 sorts and sweeps instead, and the 18.1 s batch now holds for **2.2 s**.
506/// The shape term is gone from the code and therefore from here: measured on
507/// the same machine, the two shapes are within 15% of each other at every size
508/// from 100 to 20,000 rows, which is inside the noise this model claims.
509///
510/// What is left is not flat either, and the second term is why. Per-row cost
511/// rises from ~36 µs at 100 rows to ~111 µs at 20,000, because each insert
512/// maintains indexes and two triggers against a table the batch is itself
513/// growing:
514///
515/// ```text
516/// hold ≈ rows · (7.4 µs + 7.24 µs · ⌊log₂ rows⌋)
517/// ```
518///
519/// # What this is calibrated against, and where it will be wrong
520///
521/// libSQL 0.9.30, one machine, best of three, 100–20,000 rows in both shapes;
522/// within 15% from 500 rows up. Below that it under-predicts by up to 3×, which
523/// is harmless in the same way the old 3× over-prediction was — nothing that
524/// small approaches [`BULK_ATOMIC_WARN_HOLD`].
525///
526/// **The log term reads the batch because the batch is all it has.** It stands
527/// for the depth of a structure the batch is loading, and this signature never
528/// sees the table. That is exact for the bulk import this warns about, and
529/// optimistic for a small batch appended to an already-large table — the same
530/// blind spot the flat per-row model had, now visible instead of averaged away.
531///
532/// It is machine-specific and says nothing about disk. It exists to turn
533/// "uncapped" into an order of magnitude a caller can act on, and should not be
534/// read more precisely than that. `examples/bulk_atomic_diag.rs` prints
535/// predicted against measured, so the model's drift is visible rather than
536/// assumed.
537pub fn estimated_bulk_hold(edges: &[EdgeAssertion]) -> std::time::Duration {
538 let rows = edges.len() as u64;
539 if rows == 0 {
540 return std::time::Duration::ZERO;
541 }
542
543 // Nanoseconds throughout, saturating: a caller who passes a batch large
544 // enough to overflow this has a problem the arithmetic cannot express, and
545 // saturating to ~584 years still crosses every threshold above.
546 let per_row = 7_400u64.saturating_add((rows.ilog2() as u64).saturating_mul(7_240));
547 std::time::Duration::from_nanos(rows.saturating_mul(per_row))
548}
549
550/// Most sessions [`Database::archive_windowed`] will run for one call (T1.1).
551///
552/// A limit exists because the session count is a function of *transaction-time
553/// span divided by window*, and both come from the caller — a one-second window
554/// over a decade of history is ten million actor turns, each opening a
555/// transaction and writing a horizon row. That is not a slow archive, it is a
556/// caller who meant something else.
557///
558/// 4,096 is chosen against the operation it bounds rather than against a clock:
559/// at the measured 26.8 ms for a session with work in it, a full run of this
560/// many is about two minutes of background writing, and the whole point of
561/// windowing is that those two minutes are interruptible. It is a refusal
562/// rather than a clamp — see [`DbError::ArchiveWindow`] for why.
563pub const MAX_ARCHIVE_SESSIONS: usize = 4_096;
564
565/// A concept assertion: the payload of an upsert.
566///
567/// `#[non_exhaustive]` since 0.14.8 for
568/// [`EdgeAssertion`]'s reason: `branch` is the
569/// first field added since it was written, and one break is better than a
570/// recurring one.
571#[derive(Debug, Clone, PartialEq)]
572#[non_exhaustive]
573pub struct ConceptUpsert {
574 pub id: String,
575 pub title: String,
576 pub content: String,
577 pub embedding_model: Option<String>,
578 pub valid_from: String,
579 pub valid_to: String,
580 pub retired: bool,
581 /// The lineage this concept is minted on, or `None` for the trunk (§15.2,
582 /// D-225).
583 ///
584 /// **The rule here is narrower than the edge's, and it is the schema's
585 /// rather than this crate's.** `concepts` is a current-state projection
586 /// keyed by identity — `id` is `NOT NULL UNIQUE` — so two lineages holding
587 /// different beliefs about one concept is two rows with one `id`, which the
588 /// unique index refuses on its own. `trg_concepts_cross_lineage` turns that
589 /// refusal into [`DbError::CrossLineage`] so it says which rule was broken.
590 ///
591 /// So a branch **inherits** its parent's concepts and cannot restate them;
592 /// what this field is for is a concept the branch *mints*, which is the
593 /// case the trunk has no row for. A branch that needs to disagree with its
594 /// parent about a concept's content is asking for the overlay design, which
595 /// is deferred with its reopen trigger named (D-214).
596 pub branch: Option<crate::branch::BranchId>,
597}
598
599impl ConceptUpsert {
600 pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
601 Self {
602 id: id.into(),
603 title: title.into(),
604 content: String::new(),
605 embedding_model: None,
606 valid_from: String::new(),
607 valid_to: timestamp::OPEN_SENTINEL.to_string(),
608 retired: false,
609 branch: None,
610 }
611 }
612
613 pub fn content(mut self, content: impl Into<String>) -> Self {
614 self.content = content.into();
615 self
616 }
617
618 pub fn embedding_model(mut self, model: impl Into<String>) -> Self {
619 self.embedding_model = Some(model.into());
620 self
621 }
622
623 pub fn valid_from(mut self, ts: impl Into<String>) -> Self {
624 self.valid_from = ts.into();
625 self
626 }
627
628 pub fn valid_to(mut self, ts: impl Into<String>) -> Self {
629 self.valid_to = ts.into();
630 self
631 }
632
633 /// Mint this concept on `branch` rather than on the trunk (0.14.8).
634 ///
635 /// See [`branch`](Self::branch) for why a branch may mint a concept and may
636 /// not restate one it inherited.
637 pub fn on_branch(mut self, branch: crate::branch::BranchId) -> Self {
638 self.branch = Some(branch);
639 self
640 }
641
642 /// The lineage this upsert names, spelled out. See
643 /// [`EdgeAssertion::branch_name`](crate::graph::EdgeAssertion).
644 pub(crate) fn branch_name(&self) -> &str {
645 self.branch
646 .as_ref()
647 .map_or(crate::schema::ddl::MAIN_BRANCH, |b| b.as_str())
648 }
649
650 pub fn retired(mut self, retired: bool) -> Self {
651 self.retired = retired;
652 self
653 }
654
655 /// Put the timestamps in canonical form (D-029) before they cross the channel.
656 pub fn normalized(mut self) -> Result<Self> {
657 crate::util::ids::validate_id(&self.id)?;
658 self.valid_from = timestamp::normalize(&self.valid_from)?;
659 self.valid_to = timestamp::normalize(&self.valid_to)?;
660 Ok(self)
661 }
662}
663
664/// One derived analytics result for one concept (§5.4, D-041).
665///
666/// Not a `ConceptUpsert`. The distinction is the whole of D-041: a concept
667/// upsert is a statement about the world and belongs in the ledger, while an
668/// annotation is a function of an algorithm applied to a graph and belongs in
669/// `analytics_annotations`, which carries no log trigger. Writing one as the
670/// other overwrote the concept's `content` with the label and recorded every
671/// analytics rerun as a fresh version of the world.
672#[derive(Debug, Clone, PartialEq, Eq)]
673pub struct Annotation {
674 pub concept_id: String,
675 /// Namespaced by convention, e.g. `louvain.community`, `kcore.shell`.
676 pub label: String,
677 /// JSON-encoded payload. Opaque to this crate.
678 pub value: String,
679}
680
681impl Annotation {
682 pub fn new(
683 concept_id: impl Into<String>,
684 label: impl Into<String>,
685 value: impl Into<String>,
686 ) -> Self {
687 Self {
688 concept_id: concept_id.into(),
689 label: label.into(),
690 value: value.into(),
691 }
692 }
693}
694
695/// Commands sent to the Write Actor on the high-priority channel (UI-driven work).
696pub(crate) enum HighPriCommand {
697 AssertEdge {
698 edge: EdgeAssertion,
699 responder: oneshot::Sender<Result<()>>,
700 },
701 RetireEdge {
702 source: String,
703 target: String,
704 edge_type: String,
705 valid_from: String,
706 valid_to: String,
707 /// The lineage doing the retiring, or `None` for the trunk (0.14.8).
708 branch: Option<crate::branch::BranchId>,
709 responder: oneshot::Sender<Result<()>>,
710 },
711 UpsertConcept {
712 concept: ConceptUpsert,
713 responder: oneshot::Sender<Result<()>>,
714 },
715 WriteBulkAtomic {
716 edges: Vec<EdgeAssertion>,
717 responder: oneshot::Sender<Result<usize>>,
718 },
719 RebuildCurrent {
720 responder: oneshot::Sender<Result<RebuildReport>>,
721 },
722 /// Create a model's embedding table and its DiskANN index (D-037, D-048).
723 ///
724 /// High priority despite being setup work: it is one small transaction, and
725 /// every embedding write for the model blocks on it, so queueing it behind a
726 /// bulk job would stall the thing it gates.
727 RegisterModel {
728 model: ModelName,
729 dim: usize,
730 responder: oneshot::Sender<Result<()>>,
731 },
732 /// Move WAL frames back into the main database file (§4.5, F-30, D-156).
733 ///
734 /// High priority, and for once the reason is not latency: a caller asking
735 /// for a checkpoint is asking for it *now*, usually at the end of a bulk
736 /// load or before taking a copy of the file, and queueing it behind the
737 /// background work it was meant to follow inverts the intent. It is also
738 /// the only command here that is not a transaction.
739 Checkpoint {
740 responder: oneshot::Sender<Result<CheckpointReport>>,
741 },
742 /// Register a lineage (0.14.7, §15.4).
743 ///
744 /// High priority, and not because it is urgent: it is one insert into a
745 /// table with no secondary indices, so it is the cheapest turn the actor
746 /// takes. What makes it high priority is that everything the caller does
747 /// next is a write *on* this branch, and queueing a fork behind a bulk
748 /// import would stall the work it exists to enable — `RegisterModel`'s
749 /// argument, for the same reason.
750 ///
751 /// It goes through the actor rather than the read connection for the
752 /// ordinary reason every write does, plus one specific to it: the duplicate
753 /// and parent checks are only sound if nothing can register a colliding
754 /// name between the check and the insert, and the actor is what makes the
755 /// pair one turn.
756 Fork {
757 name: crate::branch::BranchId,
758 parent: crate::branch::BranchId,
759 responder: oneshot::Sender<Result<crate::branch::Branch>>,
760 },
761 Shutdown {
762 responder: oneshot::Sender<Result<()>>,
763 },
764}
765
766/// What `PRAGMA wal_checkpoint` returned (0.12.13, W5.2, D-156).
767///
768/// The three columns SQLite gives back, named, rather than `()` — a checkpoint
769/// that did nothing and a checkpoint that reclaimed a 400 MB WAL are the same
770/// `Ok(())`, and the difference is the entire reason a caller asked.
771#[derive(Debug, Clone, Copy, PartialEq, Eq)]
772pub struct CheckpointReport {
773 /// `true` when SQLite could not complete the requested mode because a
774 /// reader or writer was in the way.
775 ///
776 /// **This is not an error, and it is not ignorable.** `TRUNCATE` waits for
777 /// readers only as long as `busy_timeout` allows; past that it gives up and
778 /// says so, having possibly still copied frames. A caller checkpointing
779 /// before copying the file away must read this, because a busy checkpoint
780 /// means the main file is not self-contained yet.
781 pub busy: bool,
782 /// Frames left in the WAL at the end. `0` when the checkpoint completed,
783 /// since the mode run is `TRUNCATE`.
784 pub log_frames: u64,
785 /// Frames moved back into the database file.
786 ///
787 /// Read from a `FULL` pass rather than from the `TRUNCATE` — see
788 /// `run_checkpoint` for why a truncating checkpoint cannot report this
789 /// number itself.
790 pub checkpointed_frames: u64,
791}
792
793impl CheckpointReport {
794 /// The WAL was fully reclaimed: nothing blocked, and nothing is left.
795 pub fn is_complete(&self) -> bool {
796 !self.busy && self.log_frames == 0
797 }
798}
799
800/// Commands sent to the Write Actor on the low-priority channel (background work).
801pub(crate) enum LowPriCommand {
802 /// One chunk of **concepts** — a ledger write, logged and versioned.
803 WriteConceptsChunk {
804 chunk: Vec<ConceptUpsert>,
805 responder: oneshot::Sender<Result<ChunkOutcome>>,
806 },
807 /// One chunk of **derived annotations** — off-ledger, no log trigger (D-041).
808 ///
809 /// The pair is named apart deliberately: this variant was `WriteAnalyticsChunk`
810 /// beside a `WriteAnnotationsChunk` that carried concepts, which is the
811 /// crossing D-075 undid.
812 WriteAnalyticsChunk {
813 chunk: Vec<Annotation>,
814 responder: oneshot::Sender<Result<ChunkOutcome>>,
815 },
816 /// One chunk of vectors for one model (§5.9, D-048).
817 ///
818 /// Low priority: embedding is bulk derived work and must never preempt an
819 /// interactive assertion.
820 UpsertEmbeddingChunk {
821 model: ModelName,
822 chunk: Vec<(String, Vec<f32>)>,
823 responder: oneshot::Sender<Result<ChunkOutcome>>,
824 },
825 BulkImportChunk {
826 chunk: Vec<EdgeAssertion>,
827 responder: oneshot::Sender<Result<ChunkOutcome>>,
828 },
829 Archive {
830 cutoff: String,
831 archive_path: PathBuf,
832 responder: oneshot::Sender<Result<ArchiveReport>>,
833 },
834 /// Forget one lineage, moving its whole ledger to the cold file (0.14.13,
835 /// §15.4, D-230).
836 ///
837 /// Low priority for `Archive`'s reason and one of its own: it is bulk
838 /// physical movement holding the write lock for its whole transaction, and
839 /// it is the least urgent write in the crate — the rows it moves belong to
840 /// a lineage nobody is reading.
841 ArchiveBranch {
842 branch: String,
843 archive_path: PathBuf,
844 responder: oneshot::Sender<Result<ArchiveReport>>,
845 },
846 /// Move named concepts back out of the cold file (0.9.0, C3).
847 ///
848 /// Low priority for the same reason `Archive` is: it is bulk physical
849 /// movement with no latency bound, and it holds the write lock for its whole
850 /// transaction.
851 Rehydrate {
852 ids: Vec<String>,
853 archive_path: PathBuf,
854 responder: oneshot::Sender<Result<RehydrateReport>>,
855 },
856 /// Reconstruct the FTS index from `concepts` (§5.9, D-036, D-051).
857 ///
858 /// Low priority: it is maintenance on a derivative table, and a search index
859 /// that is a few seconds stale is a smaller cost than an interactive write
860 /// that waits behind a full reindex.
861 RebuildFts {
862 responder: oneshot::Sender<Result<()>>,
863 },
864 /// Refresh or top up the query planner's statistics (0.12.4, D-149).
865 ///
866 /// Low priority, and not a close call: statistics being a few seconds stale
867 /// costs a plan that was already the plan a moment ago, where preempting an
868 /// interactive assertion costs a caller their latency bound. It is a write —
869 /// it writes `sqlite_stat1` — so it takes the write lock like anything else,
870 /// and `PRAGMA analysis_limit` in `configure` is what keeps the hold a
871 /// function of the index count instead of the table size.
872 Analyze {
873 /// `true` runs `PRAGMA optimize`, which re-analyses only what SQLite
874 /// believes has gone stale; `false` runs `ANALYZE` unconditionally.
875 incremental: bool,
876 responder: oneshot::Sender<Result<()>>,
877 },
878 /// One step of a chunked shadow rebuild (§5.8, T1.2, D-082).
879 ///
880 /// Low priority, and one command per step rather than one per rebuild: the
881 /// whole value of building beside the live table is that the actor returns
882 /// here between chunks. See [`Database::rebuild_current_chunked`].
883 ShadowRebuild {
884 step: crate::integrity::ShadowStep,
885 responder: oneshot::Sender<Result<crate::integrity::ShadowOutcome>>,
886 },
887}
888
889enum LoopCtl {
890 Continue,
891 Break,
892}
893
894/// Primary database handle for Macrame bitemporal ledger.
895///
896/// # Why this is not `Clone`, and what a multi-consumer caller uses instead
897///
898/// **Share it as `Arc<Database>`.** Every method here but one takes `&self`, so
899/// an `Arc` is a complete handle and not a workaround: reads run concurrently
900/// off `read_conn`, writes queue behind the actor's channel exactly as they do
901/// through a `&Database`, and nothing becomes serialised that was not
902/// serialised already. The exception is [`Database::close`], which takes `self`,
903/// so the last owner closes with
904/// `Arc::into_inner(db).expect("last handle").close().await`.
905///
906/// That exception is the whole reason `Clone` is absent. Cloning would have to
907/// duplicate **the right to shut down**, and each field carrying that right
908/// breaks differently when duplicated:
909///
910/// - `writer` is a [`tokio::task::JoinHandle`], which is not `Clone` at all —
911/// so a hand-written impl would have to give the copy a `None`, and
912/// `close()` on that copy returns `Ok(())` without ever checking the actor's
913/// exit status. That status is one of the two reasons [`Drop`] tells callers
914/// to prefer `close()`.
915/// - `cadence_stop` is a [`tokio::sync::watch::Sender`], which **is** `Clone`,
916/// and that is the worse case. Its contract is that *dropping* it stops the
917/// snapshot task; a watch channel closes when the last sender goes, so one
918/// surviving copy keeps that task running against a database that is going
919/// away. Nothing returns an error, which is why this is the argument rather
920/// than the `JoinHandle`.
921/// - `closed` is per-handle, so two copies disagree about whether the ledger
922/// was closed: `Drop` warns about a database that *was* closed, or stays
923/// silent about one that was not.
924///
925/// And the ordering `close()` documents — cadence stopped, actor joined, *then*
926/// the final snapshot, so that no write can land between the fold and the file
927/// — is only enforceable while one handle can perform it. A second `close()`
928/// writes a "final" snapshot with the actor still alive.
929///
930/// So the missing impl is the type saying shutdown has exactly one owner. The
931/// Python binding reached the same shape from the other side and for the same
932/// reason: `PyDatabase` holds a `RwLock<Option<Database>>` rather than a copy
933/// per caller (0.13.30, W11.1, D-203).
934pub struct Database {
935 db: libsql::Database,
936 /// The file this handle opened, kept so [`Database::diagnostic_conn`] can
937 /// open it again under different flags (T5.1, D-091). `archive_path` and
938 /// `snapshots_dir` are derived from it and were previously the only trace
939 /// of it on the struct.
940 path: PathBuf,
941 read_conn: libsql::Connection,
942 highpri_tx: mpsc::Sender<HighPriCommand>,
943 lowpri_tx: mpsc::Sender<LowPriCommand>,
944 clock: Arc<dyn Clock>,
945 archive_path: PathBuf,
946 snapshots_dir: PathBuf,
947 schema_version: u32,
948 /// Kept so [`Database::diagnostic_conn`] can configure the connections it
949 /// mints the same way `open()` configured the internal readers (0.12.16,
950 /// W5.5, D-159). Before that split, each one ran with SQLite's defaults.
951 reader_cache_size: Option<i32>,
952 writer: Option<tokio::task::JoinHandle<()>>,
953 /// Stops the snapshot cadence. Dropping it stops the task too, which is what
954 /// keeps a `Database` that is dropped rather than closed from leaving a task
955 /// running against a connection whose database is going away.
956 cadence_stop: Option<tokio::sync::watch::Sender<bool>>,
957 cadence: Option<tokio::task::JoinHandle<()>>,
958 /// Set by [`Database::close`]. Read only by [`Drop`], which warns when it is
959 /// still false — see that impl for why the omission is worth a warning.
960 closed: bool,
961 /// Shared with the actor (T1.4, T1.2). Held here rather than behind
962 /// `#[cfg(feature = "metrics")]` so `open_inner` has one shape; with the
963 /// feature off the metrics half is a zero-sized type and only
964 /// [`Database::metrics`] is gated — which is also why the field is unread in
965 /// the default build: the actor holds the other `Arc` and does the writing.
966 #[cfg_attr(not(feature = "metrics"), allow(dead_code))]
967 shared: Arc<ActorShared>,
968}
969
970/// What the snapshot cadence should do, for [`Tuning::cadence`].
971///
972/// # Why this is not `Option<SnapshotCadence>`
973///
974/// [`Database::open_with_cadence`] takes `Option<SnapshotCadence>`, where `None`
975/// means *no cadence at all*. Carrying that field into [`Tuning`] unchanged
976/// would have made it the one field in the struct whose `None` is a request to
977/// change the behaviour rather than a request to leave it alone — and since
978/// `Tuning` derives `Default`, `open_tuned(path, Tuning::default())` would then
979/// have silently disabled snapshots, while `open(path)` runs them. Two calls
980/// that read as synonyms, one of which stops writing anchors.
981///
982/// So the tri-state is written out. `Default` is the default cadence, matching
983/// [`Database::open`]; `Disabled` is `open_with_cadence(path, None)`, and has to
984/// be asked for by name.
985#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
986#[non_exhaustive]
987pub enum CadencePolicy {
988 /// [`SnapshotCadence::default`], as [`Database::open`] uses.
989 #[default]
990 Default,
991 /// No cadence task. `close()` is then the only thing that writes an anchor
992 /// (§5.5, D-053).
993 Disabled,
994 /// An explicit cadence.
995 Every(SnapshotCadence),
996}
997
998impl CadencePolicy {
999 /// Collapse to the `Option` the open path has always taken.
1000 fn resolve(self) -> Option<SnapshotCadence> {
1001 match self {
1002 Self::Default => Some(SnapshotCadence::default()),
1003 Self::Disabled => None,
1004 Self::Every(cadence) => Some(cadence),
1005 }
1006 }
1007}
1008
1009/// When SQLite should checkpoint the WAL on its own, for
1010/// [`Tuning::wal_autocheckpoint`] (0.12.14, W5.3, D-157).
1011///
1012/// # Why this is not `Option<u32>`
1013///
1014/// The same reason [`CadencePolicy`] is not `Option<SnapshotCadence>`, and the
1015/// plan for this wave specified `Option<u32>` here too. In a struct that derives
1016/// `Default`, a field whose `None` means *turn the mechanism off* is a field
1017/// that turns the mechanism off for everyone who did not mention it. Absence
1018/// means "leave it alone" everywhere in [`Tuning`], and disabling the automatic
1019/// checkpointer — which is not safe without an explicit
1020/// [`Database::checkpoint`] to replace it — has to be asked for by name.
1021///
1022/// **The default does not change.** 1,000 pages is SQLite's default and stays
1023/// SQLite's default; F-30 is a control-loop perturbation, not a correctness bug,
1024/// and changing a default is a behaviour change for every existing caller.
1025///
1026/// # What disabling it actually buys, measured (0.12.14, W5.3, D-157)
1027///
1028/// F-30 says the automatic checkpointer is an unbudgeted hold *inside* 0.12.0's
1029/// adaptive chunk controller: a checkpoint firing during a chunk transaction is
1030/// charged to that chunk, and since D-146 made the measured hold the input to
1031/// `next_chunk_size`, the controller shrinks in response to work the chunk did
1032/// not do. Three rounds, 6,000 concepts of 1 KB each through `write_concepts`,
1033/// release build:
1034///
1035/// | | longest chunk hold | mean | chunks | over budget | wall |
1036/// |---|---|---|---|---|---|
1037/// | autocheckpoint on (default) | **9.3–10.3 ms** | 2.40–2.44 ms | 125–130 | 24–28 | 304–321 ms |
1038/// | autocheckpoint off | **4.50 ms** | 2.08–2.20 ms | 142–153 | 18–27 | 298–339 ms |
1039///
1040/// **The tail is the finding, and it is real and reproducible.** The longest
1041/// hold roughly halves, and the >10 ms histogram bucket is populated only with
1042/// the checkpointer on — that bucket is the checkpoint, landing inside somebody
1043/// else's transaction and being charged to it. Every round agrees.
1044///
1045/// **What it does not buy is a calmer controller.** `over_budget` overlaps
1046/// between the arms, and total wall time is the same within noise. The
1047/// controller works near the budget boundary either way, because
1048/// [D-090](../docs/architecture/s13-decision-register.md)'s ~0.8 ms
1049/// per-transaction floor and the convergence cost do not go anywhere. So the
1050/// honest statement is that disabling autocheckpoint removes an outlier, not an
1051/// oscillation.
1052///
1053/// **And the cost is deferred, not removed.** The explicit
1054/// [`Database::checkpoint`] at the end of the same fixture moved **8,400–9,100
1055/// frames in 41–45 ms** with the checkpointer off, against **~860 frames in
1056/// 5.5–6.2 ms** with it on. That is the whole trade in one line: the same work,
1057/// moved out of the latency-bounded path and into one hold the caller chose the
1058/// moment for. It is a good trade for a bulk importer and a bad one for an
1059/// interactive process, which is why this is a knob and not a new default.
1060#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1061#[non_exhaustive]
1062pub enum WalCheckpointPolicy {
1063 /// SQLite's own default: checkpoint once the WAL passes 1,000 pages.
1064 #[default]
1065 Default,
1066 /// No automatic checkpointing.
1067 ///
1068 /// **Only correct if you call [`Database::checkpoint`] yourself.** Without
1069 /// one, the WAL grows for the life of the process and the database file is
1070 /// never brought up to date.
1071 Disabled,
1072 /// Checkpoint once the WAL passes this many pages.
1073 ///
1074 /// `0` is not special-cased to [`Self::Disabled`] even though SQLite treats
1075 /// it that way, because a caller who computed a threshold and got zero has
1076 /// a bug, and inheriting SQLite's overload would turn it into a silently
1077 /// unbounded WAL.
1078 EveryPages(u32),
1079}
1080
1081impl WalCheckpointPolicy {
1082 /// The pragma to run, or `None` to leave the connection at SQLite's
1083 /// default.
1084 fn pragma(self) -> Option<String> {
1085 match self {
1086 Self::Default => None,
1087 Self::Disabled => Some("PRAGMA wal_autocheckpoint = 0".to_string()),
1088 Self::EveryPages(pages) => Some(format!("PRAGMA wal_autocheckpoint = {pages}")),
1089 }
1090 }
1091}
1092
1093/// Everything [`Database::open_tuned`] can be told, in one growable struct
1094/// (0.12.12, W5.1, D-155).
1095///
1096/// # Why a struct rather than a fourth constructor
1097///
1098/// There were three — [`Database::open`], [`Database::open_with_cadence`],
1099/// [`Database::open_with_clock`] — and each new knob added one more, with the
1100/// combinatorics of the ones before it. 0.13.0 alone wanted three knobs
1101/// (`wal_autocheckpoint`, and a page cache each for the writer and the
1102/// readers), which is the point at which the naming stops being possible.
1103///
1104/// **`Default` plus functional update is the whole design.** They make a new
1105/// knob an additive change: callers construct with `..Default::default()` and
1106/// keep compiling, and the fields that arrive after them are the ones they did
1107/// not ask about. That is not a hypothetical — W5.1 ships this struct with two
1108/// fields, and W5.3/W5.4 add the three tuning knobs to it without touching a
1109/// caller.
1110///
1111/// # Why this is *not* `#[non_exhaustive]`
1112///
1113/// The plan for this wave specified `#[non_exhaustive]` alongside `Default`,
1114/// on the usual reasoning that the attribute is what makes a struct growable.
1115/// It does not compile: a `#[non_exhaustive]` **struct** cannot be built with
1116/// literal syntax outside its own crate *at all*, and the functional-update
1117/// form is literal syntax, so `Tuning { cadence, ..Default::default() }` is
1118/// `E0639` for every external caller — the exact expression the attribute was
1119/// added to protect. (The rule differs from `#[non_exhaustive]` on an enum,
1120/// which only forces a wildcard arm; [`CadencePolicy`] keeps it for that
1121/// reason.) The two ways to have both are a builder with setters, or plain
1122/// `Default` — and `Default` is chosen because the field-literal form is the
1123/// legible one, and because the growth this needs to survive is *additive*
1124/// fields, which `..Default::default()` already absorbs.
1125///
1126/// The cost is real and worth stating: a caller who writes an exhaustive
1127/// literal, with no `..Default::default()`, breaks when a field is added. That
1128/// is a compile error at the call site with an obvious fix, not a silent
1129/// behaviour change, and it is the price of the readable form.
1130///
1131/// # The three constructors stay
1132///
1133/// They delegate here and are not deprecated. `open(path)` is the right call for
1134/// most callers and should not acquire a warning for being the common case; the
1135/// consolidation is about where the *next* knob goes, not about moving anyone.
1136///
1137/// ```no_run
1138/// # use macrame::prelude::*;
1139/// # async fn f() -> macrame::Result<()> {
1140/// let db = Database::open_tuned(
1141/// "graph.db",
1142/// Tuning {
1143/// cadence: CadencePolicy::Disabled,
1144/// ..Default::default()
1145/// },
1146/// )
1147/// .await?;
1148/// # Ok(()) }
1149/// ```
1150#[derive(Clone, Default)]
1151pub struct Tuning {
1152 /// What the snapshot cadence should do. Defaults to
1153 /// [`SnapshotCadence::default`], as [`Database::open`] does.
1154 pub cadence: CadencePolicy,
1155 /// A clock to stamp `recorded_at` with, for tests (§5.1.2, D-062). `None`
1156 /// is [`SystemClock`]. Floored against the database exactly as
1157 /// [`Database::open_with_clock`] describes — read that before injecting
1158 /// one against a non-empty file.
1159 pub clock: Option<Arc<dyn Clock>>,
1160 /// When SQLite checkpoints the WAL on its own (0.12.14, W5.3, F-30).
1161 ///
1162 /// Applied to the **write connection**, which is the only connection in
1163 /// this crate that commits, and therefore the only one whose autocheckpoint
1164 /// setting can ever fire. Pair [`WalCheckpointPolicy::Disabled`] with an
1165 /// explicit [`Database::checkpoint`] or the WAL grows without bound.
1166 pub wal_autocheckpoint: WalCheckpointPolicy,
1167 /// Page cache for the **write** connection, as SQLite's `cache_size`
1168 /// (0.12.15, W5.4).
1169 ///
1170 /// `None` leaves SQLite's default of −2000, which is −2000 *kibibytes*, or
1171 /// 2 MB. **Negative values are KiB and positive values are pages** — that
1172 /// is SQLite's convention and it is preserved rather than smoothed over,
1173 /// because a caller who knows the pragma should not have to discover that
1174 /// this crate redefined it. `Some(-64_000)` is 64 MB; `Some(64_000)` is
1175 /// 64,000 pages, which at the 4 KiB page size this crate gets is 256 MB.
1176 ///
1177 /// The writer wants a large cache: it is one connection, it holds the write
1178 /// lock while it works, and every page it has to re-read from disk is time
1179 /// no other writer can use.
1180 ///
1181 /// # Unlike the two above, `None` here is not a policy enum
1182 ///
1183 /// Because SQLite's default is a *value* rather than a mechanism. Absence
1184 /// still means "leave it alone" — it just happens that leaving this alone
1185 /// is expressible as not running a pragma, where leaving the automatic
1186 /// checkpointer alone required saying which of two things "alone" meant.
1187 pub writer_cache_size: Option<i32>,
1188 /// Page cache for every **read-only** connection: the shared
1189 /// [`Database::read_conn`], the snapshot cadence's own connection, and
1190 /// (since W5.5) each [`Database::diagnostic_conn`] (0.12.15, W5.4).
1191 ///
1192 /// Same units as [`Self::writer_cache_size`], and the same `None`.
1193 ///
1194 /// Split from the writer's because the profiles are opposite and one number
1195 /// cannot serve both. There is exactly one writer and it is long-lived, so
1196 /// its cache is a fixed cost paid once. Read-only connections are plural —
1197 /// `diagnostic_conn` mints a new one per call — so a large value here is
1198 /// multiplied by however many a caller opens, and the R15 hazard that
1199 /// method documents is about concurrent opens. A single shared number
1200 /// therefore has to be small enough for the multiplied case, which is the
1201 /// wrong size for the one connection that holds the write lock.
1202 pub reader_cache_size: Option<i32>,
1203 /// What to do about a stored `recorded_at` in the future (0.13.5, W7.4,
1204 /// §3.4).
1205 ///
1206 /// The clock floors itself at `MAX(recorded_at)` so stamps stay strictly
1207 /// increasing across restarts, which means one row from the future becomes
1208 /// this process's floor and every stamp it issues inherits it — into rows
1209 /// the next open reads back. Defaults to refusing beyond
1210 /// [`crate::DEFAULT_FUTURE_STAMP_TOLERANCE`], a day.
1211 ///
1212 /// Like [`Self::wal_autocheckpoint`] and unlike the two cache sizes, this
1213 /// is a policy enum rather than an `Option`, for
1214 /// [D-155](../../docs/architecture/s13-decision-register.md)'s reason: it
1215 /// guards an invariant, and a `None` that switches it off would switch it
1216 /// off for every caller who never heard of it.
1217 pub future_stamps: FutureStampPolicy,
1218}
1219
1220// `Clock` is not `Debug` — it is a behavioural trait with two methods and
1221// requiring `Debug` of every implementor to print a handle here would be the
1222// tail wagging the dog. So the field is reported as present-or-absent, which is
1223// the only part of it a reader of a `Tuning` dump can act on.
1224impl Tuning {
1225 /// The `Option<SnapshotCadence>` the three older constructors take, mapped
1226 /// onto the tri-state. `None` there means *disabled*, which is why
1227 /// [`CadencePolicy`] exists — see its docs.
1228 fn from_legacy(cadence: Option<SnapshotCadence>, clock: Option<Arc<dyn Clock>>) -> Self {
1229 Self {
1230 cadence: match cadence {
1231 Some(cadence) => CadencePolicy::Every(cadence),
1232 None => CadencePolicy::Disabled,
1233 },
1234 clock,
1235 wal_autocheckpoint: WalCheckpointPolicy::default(),
1236 writer_cache_size: None,
1237 reader_cache_size: None,
1238 future_stamps: FutureStampPolicy::default(),
1239 }
1240 }
1241}
1242
1243impl std::fmt::Debug for Tuning {
1244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1245 f.debug_struct("Tuning")
1246 .field("cadence", &self.cadence)
1247 .field("clock", &self.clock.as_ref().map(|_| "<injected>"))
1248 .field("wal_autocheckpoint", &self.wal_autocheckpoint)
1249 .field("writer_cache_size", &self.writer_cache_size)
1250 .field("reader_cache_size", &self.reader_cache_size)
1251 .finish()
1252 }
1253}
1254
1255impl Database {
1256 /// Open a database file at `path`, configuring pragmas, running migrations, and spawning the Write Actor.
1257 ///
1258 /// The snapshot cadence runs with [`SnapshotCadence::default`]. Use
1259 /// [`Database::open_with_cadence`] to tune or disable it.
1260 pub async fn open(path: impl AsRef<Path>) -> Result<Self> {
1261 Self::open_with_cadence(path, Some(SnapshotCadence::default())).await
1262 }
1263
1264 /// Open with an explicit snapshot cadence, or `None` to run without one
1265 /// (§5.5, D-053).
1266 ///
1267 /// `None` restores the pre-0.5.5 behaviour, where `close()` is the only
1268 /// thing that ever writes an anchor. That is the right setting for a
1269 /// short-lived process that will not accumulate a delta worth bounding, and
1270 /// for tests that assert on the contents of the snapshot directory.
1271 pub async fn open_with_cadence(
1272 path: impl AsRef<Path>,
1273 cadence: Option<SnapshotCadence>,
1274 ) -> Result<Self> {
1275 Self::open_inner(path.as_ref(), Tuning::from_legacy(cadence, None)).await
1276 }
1277
1278 /// Open with an injected clock (§5.1.2, **defect K**, D-062).
1279 ///
1280 /// The reason this exists is testing: `recorded_at` is the transaction-time
1281 /// axis, and until now every test that wanted to assert on one had to either
1282 /// avoid it or drive a raw connection, because `open()` hardcoded
1283 /// [`SystemClock`]. `FakeClock` has been public and constructed in the test
1284 /// harness since 0.5.2 with nothing to inject it into — the compiler warned
1285 /// about the dead field on every build for three releases.
1286 ///
1287 /// **The clock is floored against the database before the actor starts.**
1288 /// [`Clock::raise_floor`] is called with the newest `recorded_at` in the
1289 /// ledger, so an injected clock cannot issue a stamp below what is already
1290 /// stored — which would abort the next concept write on
1291 /// `trg_concepts_monotonic_ra` rather than merely being odd. This is the
1292 /// step whose absence kept the defect open: the obvious implementation
1293 /// (take an `Arc<dyn Clock>`, use it) produces a `Database` that fails on
1294 /// its first write against any non-empty file.
1295 ///
1296 /// On a fresh database there is no floor, so an injected `FakeClock` issues
1297 /// exactly the stamps it was given.
1298 pub async fn open_with_clock(
1299 path: impl AsRef<Path>,
1300 cadence: Option<SnapshotCadence>,
1301 clock: Arc<dyn Clock>,
1302 ) -> Result<Self> {
1303 Self::open_inner(path.as_ref(), Tuning::from_legacy(cadence, Some(clock))).await
1304 }
1305
1306 /// Open with an explicit [`Tuning`] (0.12.12, W5.1, D-155).
1307 ///
1308 /// The consolidated form of the three constructors above, and the one that
1309 /// grows: every knob 0.13.0 adds arrives as a field here rather than as a
1310 /// fourth `open_*`. See [`Tuning`] for why the struct is
1311 /// `#[non_exhaustive]` and why that makes the growth additive.
1312 pub async fn open_tuned(path: impl AsRef<Path>, tuning: Tuning) -> Result<Self> {
1313 Self::open_inner(path.as_ref(), tuning).await
1314 }
1315
1316 async fn open_inner(path: &Path, tuning: Tuning) -> Result<Self> {
1317 let Tuning {
1318 cadence,
1319 clock: injected,
1320 wal_autocheckpoint,
1321 writer_cache_size,
1322 reader_cache_size,
1323 future_stamps,
1324 } = tuning;
1325 let cadence = cadence.resolve();
1326 let db = libsql::Builder::new_local(path).build().await?;
1327 let write_conn = configure(db.connect()?, writer_cache_size).await?;
1328 // The writer is the only connection that commits, so it is the only one
1329 // whose `wal_autocheckpoint` can ever fire. Setting it on the readers
1330 // would be a pragma with no path to running (0.12.14, W5.3, D-157).
1331 if let Some(pragma) = wal_autocheckpoint.pragma() {
1332 let _ = write_conn.query(&pragma, ()).await?;
1333 }
1334 let read_conn = configure(db.connect()?, reader_cache_size).await?;
1335
1336 // PRAGMA query_only = ON on reader connection (§5.1.2)
1337 read_conn.execute("PRAGMA query_only = ON", ()).await?;
1338
1339 let migration = migrations::run(&write_conn).await?;
1340
1341 let (highpri_tx, highpri_rx) = mpsc::channel(256);
1342 let (lowpri_tx, lowpri_rx) = mpsc::channel(64);
1343
1344 // Floored after `migrations::run`, so the tables the floor is read from
1345 // are guaranteed to exist.
1346 let clock: Arc<dyn Clock> = match injected {
1347 Some(clock) => {
1348 if let Some(floor) =
1349 crate::util::clock::recorded_at_floor(&read_conn, future_stamps).await?
1350 {
1351 clock.raise_floor(floor);
1352 }
1353 clock
1354 }
1355 None => Arc::new(SystemClock::new(&read_conn, future_stamps).await?),
1356 };
1357 let shared = Arc::new(ActorShared::default());
1358 let writer = tokio::spawn(run_writer_actor(
1359 write_conn,
1360 Arc::clone(&clock),
1361 highpri_rx,
1362 lowpri_rx,
1363 Arc::clone(&shared),
1364 ));
1365
1366 let archive_path = derive_archive_path(path);
1367 let snapshots_dir = derive_snapshots_dir(path);
1368
1369 // **The cadence gets its own connection (Wave 4.1).** It used to share
1370 // `read_conn`, on the reasoning that `libsql::Connection` is an
1371 // Arc-backed handle and R15 makes every extra local connection a cost worth
1372 // not paying for nothing. The cost it was not paying for turned out to be
1373 // real: `reconstruct` brackets a fold with `ATTACH cold … DETACH cold`,
1374 // that region is per-connection state, and it is not synchronised. Two
1375 // folds on one connection can therefore interleave so that one DETACHes
1376 // the handle the other is mid-fold on.
1377 //
1378 // Recorded in §8.5 as a hazard rather than a defect because it **did not
1379 // reproduce**: 200 concurrent reconstructions against a 1 ms cadence with
1380 // an archive present produced zero errors, since the cadence anchors at
1381 // `MAX(recorded_at)` and so almost always takes the hot path. Narrow, and
1382 // real — a write landing between `log_head` and the fold opens it.
1383 //
1384 // Separate connections remove the interleaving rather than ordering it,
1385 // which is why this is preferred to a mutex around the region: there is
1386 // no shared state left to race on, and nothing to remember to hold. The
1387 // R15 objection does not apply — that fault is about *concurrent* opens,
1388 // and this is one more sequential open during `open()`.
1389 let (cadence_stop, cadence) = match cadence {
1390 Some(cadence) => {
1391 let cadence_conn = configure(db.connect()?, reader_cache_size).await?;
1392 cadence_conn.execute("PRAGMA query_only = ON", ()).await?;
1393 let (tx, rx) = tokio::sync::watch::channel(false);
1394 let handle = tokio::spawn(snapshot::run_cadence(
1395 cadence_conn,
1396 snapshots_dir.clone(),
1397 archive_path.clone(),
1398 cadence,
1399 rx,
1400 ));
1401 (Some(tx), Some(handle))
1402 }
1403 None => (None, None),
1404 };
1405
1406 let handle = Self {
1407 db,
1408 path: path.to_path_buf(),
1409 read_conn,
1410 highpri_tx,
1411 lowpri_tx,
1412 clock,
1413 archive_path,
1414 snapshots_dir,
1415 schema_version: migrations::current_version(),
1416 reader_cache_size,
1417 writer: Some(writer),
1418 cadence_stop,
1419 cadence,
1420 closed: false,
1421 shared,
1422 };
1423
1424 // **Re-anchor after a migration (Wave 4.4).**
1425 //
1426 // D-043 makes a `SCHEMA_VERSION` bump invalidate every snapshot on disk,
1427 // which is correct — a snapshot is a serialised `MaterializedState` and a
1428 // schema change can change what that means. What was missing is the other
1429 // half: nothing wrote a replacement, so the first `reconstruct` after an
1430 // upgrade skipped every file as incompatible and folded from genesis. On
1431 // a database with a large log that is the difference between reading one
1432 // snapshot and folding the whole history, and the only trace was a
1433 // `warn!` per skipped file.
1434 //
1435 // Written here rather than left to the cadence because the cadence fires
1436 // on log *growth* (D-053): an upgraded database that is then read but not
1437 // written would never re-anchor at all.
1438 //
1439 // Failure is logged, not returned. A missing anchor costs time and no
1440 // information — snapshots are derivative under Doctrine VI — so refusing
1441 // to open a database because its optimisation could not be rebuilt would
1442 // trade a real capability for a performance one.
1443 //
1444 // Gated on the cadence being enabled, as well as on an actual upgrade:
1445 // `open_with_cadence(None)` means *this handle writes no snapshots except
1446 // at close()*, and a one-off write at open would contradict that for a
1447 // caller who asked for the quiet mode precisely to control when files
1448 // appear. They still get an anchor from `close()`.
1449 if migration.upgraded() && handle.cadence.is_some() {
1450 let ts = handle.clock.now();
1451 let archive = handle
1452 .archive_path
1453 .exists()
1454 .then_some(handle.archive_path.as_path());
1455 match snapshot::write_final(&handle.read_conn, &handle.snapshots_dir, &ts, archive)
1456 .await
1457 {
1458 Ok(path) => tracing::info!(
1459 "schema moved v{} -> v{}; re-anchored snapshots at {:?}",
1460 migration.from,
1461 migration.to,
1462 path
1463 ),
1464 Err(e) => tracing::warn!(
1465 "schema moved v{} -> v{} but the re-anchor failed: {e}. \
1466 Reconstruction stays correct and folds from genesis until the \
1467 cadence writes one.",
1468 migration.from,
1469 migration.to
1470 ),
1471 }
1472 }
1473
1474 Ok(handle)
1475 }
1476
1477 /// Read connection handle for queries, traversals, and folds.
1478 pub fn read_conn(&self) -> &libsql::Connection {
1479 &self.read_conn
1480 }
1481
1482 /// The file this handle opened.
1483 pub fn path(&self) -> &Path {
1484 &self.path
1485 }
1486
1487 /// A **new, independently owned, OS-level read-only** connection to this
1488 /// database, for diagnostics (§4.7, T5.1, D-091).
1489 ///
1490 /// # Why this exists when `read_conn()` already does
1491 ///
1492 /// Two different things, and the difference is the point:
1493 ///
1494 /// * `read_conn()` returns a shared `&Connection` carrying
1495 /// `PRAGMA query_only = ON`. That pragma is **per-connection and
1496 /// reversible by its holder in one statement**, so it is a guardrail
1497 /// against accident, not a capability boundary. And because the reference
1498 /// is shared, a caller who runs a long reporting query on it is competing
1499 /// with every traversal and fold in the process.
1500 /// * This returns a connection opened with `SQLITE_OPEN_READ_ONLY`, which is
1501 /// enforced by the engine below the pragma layer, and it is the caller's
1502 /// own.
1503 ///
1504 /// **Measured on libSQL 0.9.30 rather than assumed**
1505 /// (`examples/readonly_open_probe.rs`), against a live WAL database with the
1506 /// write actor running:
1507 ///
1508 /// | | `read_conn()` | `diagnostic_conn()` |
1509 /// |---|---|---|
1510 /// | `SELECT`, `EXPLAIN QUERY PLAN` | allowed | allowed |
1511 /// | `INSERT` | refused | refused |
1512 /// | `PRAGMA query_only = OFF` | **allowed** | allowed |
1513 /// | `INSERT` after that | **allowed** | **refused** |
1514 /// | `ATTACH` an existing file | allowed | allowed |
1515 /// | `INSERT` into the attachment | refused¹ | **refused** |
1516 /// | `ATTACH` a path that does not exist | — | refused (`SQLITE_CANTOPEN`) |
1517 ///
1518 /// The third and fourth rows are the whole difference: turning the pragma
1519 /// off restores writes on `read_conn()` and does not here. That is what
1520 /// "boundary rather than guardrail" means, and it is now a number rather
1521 /// than a claim.
1522 ///
1523 /// ¹ On `read_conn()` that refusal is `query_only` — the same reversible
1524 /// thing as row 2. On `diagnostic_conn()` it is the open flags, and the
1525 /// probe runs it *after* `query_only = OFF` so that the pragma cannot be
1526 /// what is doing the work.
1527 ///
1528 /// # `ATTACH` is permitted, and does not widen the write boundary
1529 ///
1530 /// Checked because `diagnostic_query` (Python) is the only arbitrary-SQL
1531 /// surface this crate exposes, and an attachment is a second `open` whose
1532 /// flags it does not obviously inherit. It does inherit them: the
1533 /// attachment is read-only, and a nonexistent path is `SQLITE_CANTOPEN`
1534 /// rather than a new file, because `SQLITE_OPEN_CREATE` is dropped for the
1535 /// attachment as it is for `main`. So `SQLITE_OPEN_READ_ONLY` bounds the
1536 /// **connection**, not just the one file it names (0.10.0, W4.3).
1537 ///
1538 /// What it does widen is *reading*: an `ATTACH` can name any file the
1539 /// process can open, so this connection is a read surface over the
1540 /// filesystem, not over this database. That is a property of arbitrary SQL
1541 /// rather than of the flags, and it is unchanged by them.
1542 ///
1543 /// # One way this is *more* permissive, which is worth knowing
1544 ///
1545 /// `CREATE TEMP TABLE` **succeeds** here and is refused by `read_conn()`.
1546 /// Temp tables live in a separate temporary database that is writable
1547 /// regardless of how the main one was opened, whereas `query_only` refuses
1548 /// them outright — which is the mechanism [D-050] measured when it removed
1549 /// `TwoPhaseTempTable` for returning `SQLITE_READONLY (8)` on the read
1550 /// connection. So the stronger boundary is not uniformly stronger, and a
1551 /// strategy that needs a temp table has a connection it could run on. That
1552 /// is recorded, not acted on: D-050 removed the strategy for two reasons and
1553 /// this addresses one of them.
1554 ///
1555 /// # Calling this concurrently is R15's shape
1556 ///
1557 /// **This is the one method on `Database` that opens the file.** Everything
1558 /// else runs on connections established once, at `open`. Each call here is
1559 /// a fresh `libsql::Builder::…build()`, so *N* threads calling it at once
1560 /// are *N* concurrent opens — which is exactly the pattern behind
1561 /// [R15](https://github.com/opticsWolf/Macrame#known-risks), the upstream
1562 /// libSQL access violation (`0xC0000005`) that `examples/r15_soak.rs`
1563 /// reproduces and `RUST_TEST_THREADS=1` exists to avoid in the suite.
1564 ///
1565 /// **This is measured, not inferred.** 48 threads sharing one handle and
1566 /// calling only this method: 7 bad runs in 18 — two access violations and
1567 /// five *returned* SQLite errors (`database is locked`, `bad parameter or
1568 /// other API misuse`). With the calls serialised, 0 in 18
1569 /// (`tests_py/probes/r15_diagnostic_path.py`). The returned-error mode is
1570 /// the one to watch for: it looks like a fact about the database, on the
1571 /// method a caller reaches for when they already doubt the typed answer.
1572 ///
1573 /// **Bound this yourself if you call it from more than one thread.** One
1574 /// outstanding open at a time is enough; a mutex around the call costs
1575 /// nothing on a diagnostic path. This method does not do it for you on
1576 /// purpose: serialising behind a lock the caller cannot see would
1577 /// contradict the thing above it — that the connection is *the caller's
1578 /// own* — and it would put a hidden queue in front of the one surface whose
1579 /// job is to answer questions when the typed path is already suspect. The
1580 /// Python binding does bound it, because it wraps this in a method a caller
1581 /// cannot see into (`PyDatabase::diagnostic_rows`); a Rust caller can.
1582 ///
1583 /// # Errors
1584 ///
1585 /// The file must already exist. `SQLITE_OPEN_READ_ONLY` drops
1586 /// `SQLITE_OPEN_CREATE` with it, so a missing file is `SQLITE_CANTOPEN`
1587 /// rather than a fresh empty database — which is the right failure, and is
1588 /// surfaced as a typed error rather than as libSQL's error 14.
1589 pub async fn diagnostic_conn(&self) -> Result<libsql::Connection> {
1590 let fail = |reason: String| DbError::DiagnosticConn {
1591 path: self.path.display().to_string(),
1592 reason,
1593 };
1594 if !self.path.exists() {
1595 return Err(fail(
1596 "the file does not exist, and a read-only open cannot create it".to_string(),
1597 ));
1598 }
1599 let db = libsql::Builder::new_local(&self.path)
1600 .flags(libsql::OpenFlags::SQLITE_OPEN_READ_ONLY)
1601 .build()
1602 .await
1603 .map_err(|e| fail(e.to_string()))?;
1604 let conn = db.connect().map_err(|e| fail(e.to_string()))?;
1605 // Configured since 0.12.16 (W5.5, D-159). Until then this connection
1606 // ran with SQLite's defaults while every other connection in the
1607 // process ran with the crate's — most consequentially a `busy_timeout`
1608 // of 0 against everyone else's 5 s, on the one surface whose job is to
1609 // answer questions when the typed path is already suspect. Only the
1610 // common half: `SQLITE_OPEN_READ_ONLY` cannot set `journal_mode`, and
1611 // the rest govern writes this connection cannot make.
1612 configure_common(&conn, self.reader_cache_size).await?;
1613 Ok(conn)
1614 }
1615
1616 /// Cross-check the snapshot chain against a fold from genesis (§5.5, T5.3,
1617 /// D-092).
1618 ///
1619 /// `write_final` composes onto the previous snapshot, so snapshot *n* is
1620 /// derived from snapshot *n−1* and nothing in the chain ever folds the whole
1621 /// log. An error at any link propagates forward forever and every read
1622 /// agrees with it, because every read descends from it. This is the check
1623 /// that would notice.
1624 ///
1625 /// # When to run it
1626 ///
1627 /// **Not on a schedule this crate chooses.** A genesis fold is precisely the
1628 /// cost snapshots exist to avoid, so running it periodically by default
1629 /// would give every application the bill snapshots were bought to remove —
1630 /// on a database whose log is large enough for snapshots to matter, which is
1631 /// the only kind where this is worth doing. The plan calls it a scheduling
1632 /// problem and it is the caller's schedule: an idle period, a nightly job,
1633 /// or once per *N* anchors, chosen against a log size this crate cannot see.
1634 ///
1635 /// The cadence is deliberately left alone for the same reason — it runs on a
1636 /// connection shared with nothing and a fold there would compete with
1637 /// interactive reads at a moment nobody chose.
1638 ///
1639 /// # It reports; it does not repair
1640 ///
1641 /// A divergence means the snapshots are a wrong **cache**, not that the
1642 /// ledger is corrupt: [Doctrine VI] makes them disposable, so deleting
1643 /// [`Self::snapshots_dir`] restores correctness and costs only speed.
1644 /// Rewriting the file here would destroy the evidence that composition has a
1645 /// defect, which is the only thing this can tell you that you did not
1646 /// already know.
1647 ///
1648 /// Pair it with the actor counters ([`Self::metrics`], D-079) so a
1649 /// divergence found by a scheduled run is visible beside the write latency
1650 /// of the period that produced it.
1651 ///
1652 /// [Doctrine VI]: ../../docs/architecture/s0-s3-foundations.md#doctrine-vi
1653 pub async fn verify_snapshot_chain(&self, ts: &str) -> Result<crate::temporal::ChainCheck> {
1654 let archive = self
1655 .archive_path
1656 .exists()
1657 .then_some(self.archive_path.as_path());
1658 crate::temporal::verify_snapshot_chain(&self.read_conn, ts, archive, &self.snapshots_dir)
1659 .await
1660 }
1661
1662 /// The clock every write is stamped with (§5.1.1).
1663 pub fn clock(&self) -> &Arc<dyn Clock> {
1664 &self.clock
1665 }
1666
1667 /// Schema version this handle opened against.
1668 pub fn schema_version(&self) -> u32 {
1669 self.schema_version
1670 }
1671
1672 /// Cold database path, derived by convention from the main file.
1673 pub fn archive_path(&self) -> &Path {
1674 &self.archive_path
1675 }
1676
1677 /// Snapshot directory, derived by convention from the main file.
1678 pub fn snapshots_dir(&self) -> &Path {
1679 &self.snapshots_dir
1680 }
1681
1682 /// What the write actor has done since this handle was opened (T1.4, D-079).
1683 ///
1684 /// Requires the `metrics` feature. The counters are per-handle and start at
1685 /// zero on `open()` — they are not read from the database, because the thing
1686 /// being measured is *this process's* actor and merging two processes'
1687 /// histograms would produce a number about neither.
1688 ///
1689 /// The intended first question is [`crate::metrics::MetricsSnapshot::budget_violations`]:
1690 ///
1691 /// ```no_run
1692 /// # async fn f(db: ¯ame::Database) {
1693 /// # #[cfg(feature = "metrics")] {
1694 /// for k in db.metrics().budget_violations() {
1695 /// eprintln!("{} broke the 3 ms bound {} times", k.kind, k.over_budget);
1696 /// }
1697 /// # }
1698 /// # }
1699 /// ```
1700 ///
1701 /// Reading this does not stop the actor — see
1702 /// [`crate::metrics::ActorMetrics::snapshot`] for what that costs in
1703 /// consistency, and why the trade goes that way.
1704 #[cfg(feature = "metrics")]
1705 pub fn metrics(&self) -> crate::metrics::MetricsSnapshot {
1706 self.shared.metrics.snapshot()
1707 }
1708
1709 /// The underlying libSQL database, for callers that need their own connection.
1710 ///
1711 /// # Actor containment is a convention above this line, not a guarantee
1712 ///
1713 /// **Kept public, and the honest statement of what that costs (Wave 4.3).**
1714 /// §5.1 says the write actor is the sole writer, and two mechanisms make that
1715 /// true of the handle: every write method goes through a channel, and
1716 /// [`Self::read_conn`] carries `PRAGMA query_only = ON`. **Nothing protects a
1717 /// connection obtained from here.** A caller can open one, write to `links`
1718 /// directly, and the actor will not know — the triggers still fire and the
1719 /// ledger stays internally consistent, but the single-writer property that
1720 /// [`crate::CHUNK_BUDGET`]'s latency argument rests on is gone, and so is the
1721 /// serialisation the overlap guard (D-060) relies on.
1722 ///
1723 /// This is the same shape as the limit stated in §4.2 for that guard, and it
1724 /// is one fact rather than two: **the storage layer permits what this API
1725 /// refuses.** Making it private would not change that — the database file is
1726 /// reachable by any SQLite client on the machine — it would only remove the
1727 /// supported way to do the thing, which is how escape hatches become
1728 /// `unsafe`-adjacent folklore.
1729 ///
1730 /// The free functions [`crate::register_model`] and
1731 /// [`crate::upsert_embedding`] take a bare connection for the same reason and
1732 /// carry the same caveat; prefer [`Self::register_model`] and
1733 /// [`Self::upsert_embeddings`], which go through the actor.
1734 ///
1735 /// # The legitimate-use list is now one item long (T5.1, D-091)
1736 ///
1737 /// It used to read: `EXPLAIN QUERY PLAN` and other diagnostics, read-only
1738 /// reporting queries wanting their own connection rather than sharing the
1739 /// reader, and provoking a guard in a test. The first two are exactly what
1740 /// [`Self::diagnostic_conn`] now does, and it does them behind an OS-level
1741 /// read-only open rather than on a handle that can write. **Use that.**
1742 ///
1743 /// What is left is the one use that genuinely requires write access through
1744 /// a connection the actor does not own: *provoking a guard* — writing the
1745 /// state §4.7 says the storage layer permits and this API refuses, so a test
1746 /// can assert the gap is still where the document says it is. That is the
1747 /// only thing this crate's own suite uses it for.
1748 ///
1749 /// # Why `#[doc(hidden)]` and not a `raw-access` feature
1750 ///
1751 /// T5.1 offers either. The feature is the stronger declaration — it shows up
1752 /// in the consumer's `Cargo.toml`, where a reviewer sees it — and it was
1753 /// **not** taken, for a reason specific to what uses this:
1754 ///
1755 /// Cargo features are additive and cannot be *required* by a test target
1756 /// except through `required-features`, which makes a plain `cargo test`
1757 /// **skip** that binary silently. The binaries that call this are
1758 /// `storage_boundary_tests` and `wave1_regression_tests` — the §4.7
1759 /// tripwires, whose entire job is to fail when a documented gap moves. Gating
1760 /// them behind a feature would mean the ordinary `cargo test` stopped running
1761 /// the tests that enforce the section this item is about, to make a
1762 /// declaration about a hatch. That trade is the wrong way round, and it is
1763 /// the same failure the project already names: a suite that quietly does less
1764 /// than it appears to.
1765 ///
1766 /// So the hatch stays reachable and stops being *discoverable*: it is absent
1767 /// from the docs, and the documented path for every non-write use is
1768 /// [`Self::diagnostic_conn`]. [D-068] is unchanged — removing it would buy
1769 /// the appearance of a guarantee, since the file is reachable by any SQLite
1770 /// client on the machine.
1771 ///
1772 /// [D-068]: ../../docs/architecture/s13-decision-register.md#d-068
1773 // convention (D-068/D-091): `raw()` is #[doc(hidden)] and is NOT exposed by
1774 // any binding. Everything above this line is invisible on docs.rs and
1775 // invisible to a contributor reading the Python surface list, which is where
1776 // the decision to expose it would actually be taken — hence this sentinel and
1777 // its twin in `bindings/python/src/lib.rs` (0.10.0, W4.10). The documented
1778 // path for every non-write use is `diagnostic_conn`.
1779 #[doc(hidden)]
1780 pub fn raw(&self) -> &libsql::Database {
1781 &self.db
1782 }
1783
1784 // -- write surface (§5.1, Appendix A) --
1785 //
1786 // Every method here validates and canonicalises before the value crosses the
1787 // channel, so a bad edge type or a second-precision timestamp is a typed
1788 // error at the call site rather than an engine `CHECK` failure surfacing
1789 // from the far side of an actor with no context attached.
1790 //
1791 // NOTE (§5.1.8, D-028): awaiting one of these waits on a Rust channel, not
1792 // in SQLite, so `busy_timeout` does not bound it. During an in-flight
1793 // `rebuild_current` or `archive` the caller stalls for that transaction's
1794 // duration. Wrap in `tokio::time::timeout` if you need a bound — but a
1795 // timeout is not a cancellation: the command stays queued and commits when
1796 // the actor reaches it.
1797
1798 /// Assert an edge (Doctrine III: a new row, never an update).
1799 ///
1800 /// # One row costs a transaction, so N rows cost N transactions
1801 ///
1802 /// This is the correct method for a caller who genuinely has one edge, and
1803 /// it is the wrong one in a loop. Each call is its own transaction and pays
1804 /// the ~0.8 ms per-transaction floor (D-090) whole, so a thousand edges
1805 /// asserted one at a time spend roughly **0.8 s in transaction overhead
1806 /// alone** — before any of the work — and mint a thousand distinct
1807 /// `recorded_at` stamps for what the caller probably means as one act.
1808 ///
1809 /// There are two bulk forms and the difference between them is the one to
1810 /// get right:
1811 ///
1812 /// - [`Self::bulk_import`] is **chunked** against [`CHUNK_BUDGET`] and
1813 /// atomic per chunk. It amortises the transaction floor across the batch
1814 /// while still yielding to interactive work at every chunk boundary. This
1815 /// is the one a loop should almost always become.
1816 /// - [`Self::write_bulk_atomic`] is one transaction under one stamp and is
1817 /// **the one write with no latency bound** — the hold is a function of
1818 /// `edges.len()`, tabulated in its own docs, and is time every other
1819 /// writer spends waiting. Reach for it when the batch is genuinely one
1820 /// act that must not be observable half-applied, not for speed.
1821 ///
1822 /// The choice is the caller's and neither form is deprecated. Doctrine III
1823 /// makes "one act, one stamp" a semantic claim rather than a performance
1824 /// one, and only the caller knows whether their thousand edges are one act.
1825 pub async fn assert_edge(&self, edge: EdgeAssertion) -> Result<()> {
1826 let edge = edge.normalized()?;
1827 self.high(|responder| HighPriCommand::AssertEdge { edge, responder })
1828 .await
1829 }
1830
1831 /// Close an open interval by asserting its replacement (Doctrine III).
1832 pub async fn retire_edge(
1833 &self,
1834 source: impl Into<String>,
1835 target: impl Into<String>,
1836 edge_type: impl Into<String>,
1837 valid_from: &str,
1838 valid_to: &str,
1839 ) -> Result<()> {
1840 let edge_type = edge_type.into();
1841 crate::graph::edge::validate_edge_type(&edge_type)?;
1842 let valid_from = timestamp::normalize(valid_from)?;
1843 let valid_to = timestamp::normalize(valid_to)?;
1844 let (source, target) = (source.into(), target.into());
1845
1846 self.high(|responder| HighPriCommand::RetireEdge {
1847 source,
1848 target,
1849 edge_type,
1850 valid_from,
1851 valid_to,
1852 branch: None,
1853 responder,
1854 })
1855 .await
1856 }
1857
1858 /// Retire an edge **on a lineage**, which is a different write (0.14.8).
1859 ///
1860 /// The `_on` suffix is the crate's established spelling for the
1861 /// branch-taking variant of a call whose trunk form predates branching —
1862 /// [`query_as_of_edges_on`](crate::temporal::query_as_of_edges_on) is the
1863 /// other one. A sixth positional `Option<BranchId>` on
1864 /// [`Self::retire_edge`] would have made every existing call site read as
1865 /// though it had made a lineage decision it never made.
1866 ///
1867 /// # This closes a row; it does not close *the* row
1868 ///
1869 /// Retiring an edge the branch **inherited** writes the branch's own row at
1870 /// the ancestor's key, carrying the closed interval and this lineage's id.
1871 /// The ancestor's row is untouched, and the read prefers the nearer one, so
1872 /// the edge is gone from this lineage's view and unchanged in its parent's.
1873 /// That is **shadow retirement**, and it is the only retirement across
1874 /// lineages that does not commit the parent corruption
1875 /// [Doctrine III](../../docs/architecture/s0-s3-foundations.md#doctrine-iii)
1876 /// forbids — which is not a rule this method obeys but a shape the ledger
1877 /// cannot express: `links` is append-only and no statement in this crate
1878 /// closes a row in place.
1879 ///
1880 /// `weight` and `properties` are carried over from the visible row rather
1881 /// than restated, which is what makes this a retirement rather than a new
1882 /// assertion that happens to be closed.
1883 ///
1884 /// # Errors
1885 ///
1886 /// - [`DbError::UnknownBranch`] when `branch` is not registered.
1887 /// - [`DbError::NotFound`] when this lineage can see no open row at that
1888 /// `valid_from`. On a branch that includes *never inherited it* and
1889 /// *inherited it and already shadowed it*, which are one answer here
1890 /// because they are one answer to the question asked: there is nothing
1891 /// at that key to retire.
1892 pub async fn retire_edge_on(
1893 &self,
1894 source: impl Into<String>,
1895 target: impl Into<String>,
1896 edge_type: impl Into<String>,
1897 valid_from: &str,
1898 valid_to: &str,
1899 branch: crate::branch::BranchId,
1900 ) -> Result<()> {
1901 let edge_type = edge_type.into();
1902 crate::graph::edge::validate_edge_type(&edge_type)?;
1903 let valid_from = timestamp::normalize(valid_from)?;
1904 let valid_to = timestamp::normalize(valid_to)?;
1905 let (source, target) = (source.into(), target.into());
1906
1907 self.high(|responder| HighPriCommand::RetireEdge {
1908 source,
1909 target,
1910 edge_type,
1911 valid_from,
1912 valid_to,
1913 branch: Some(branch),
1914 responder,
1915 })
1916 .await
1917 }
1918
1919 /// Insert or update a concept.
1920 ///
1921 /// # One row costs a transaction
1922 ///
1923 /// The same trade [`Self::assert_edge`] describes, for the same reason and
1924 /// with the same ~0.8 ms floor (D-090): correct for one concept, wrong in a
1925 /// loop. [`Self::write_concepts`] takes a `Vec` and commits it as one
1926 /// transaction under one stamp.
1927 ///
1928 /// There is no atomic-across-chunks concept path and none is needed to make
1929 /// the choice: `write_concepts` is chunked against [`CHUNK_BUDGET`] and
1930 /// atomic per chunk, so a large `Vec` is cooperative rather than a stall.
1931 /// The responsiveness argument for writing one row at a time therefore does
1932 /// not apply — the bulk form already yields at every chunk boundary.
1933 pub async fn upsert_concept(&self, concept: ConceptUpsert) -> Result<()> {
1934 let concept = concept.normalized()?;
1935 self.high(|responder| HighPriCommand::UpsertConcept { concept, responder })
1936 .await
1937 }
1938
1939 /// A handle on one lineage (§15.4, 0.14.9, [D-226]).
1940 ///
1941 /// Takes `&Arc<Self>` rather than `&self` because the view holds the handle
1942 /// and must not be able to end it: `close` takes `self` by value and an
1943 /// `Arc` cannot surrender that while a clone survives, so the restriction
1944 /// is structural rather than documented. Sharing the handle is already
1945 /// `Arc<Database>` (§5.1.11), so this asks for nothing a caller did not
1946 /// have.
1947 ///
1948 /// Does no I/O and cannot fail. Whether the lineage is *registered* is
1949 /// asked by every operation on the view, which is where
1950 /// [`DbError::UnknownBranch`] names it.
1951 ///
1952 /// [D-226]: ../../docs/architecture/s13-decision-register.md#d-226
1953 pub fn view(
1954 self: &std::sync::Arc<Self>,
1955 branch: crate::branch::BranchId,
1956 ) -> crate::branch::BranchView {
1957 crate::branch::BranchView::new(std::sync::Arc::clone(self), branch)
1958 }
1959
1960 /// Cut a new lineage from an existing one (§15.2, §15.4).
1961 ///
1962 /// # A fork is O(1) in rows written
1963 ///
1964 /// One row in `branches`, and nothing else. No ledger table is read, copied
1965 /// or touched: a branch inherits its parent's history by *resolution at
1966 /// read* rather than by owning a copy of it, which is what
1967 /// [`TraversalBuilder::on_branch`](crate::graph::TraversalBuilder::on_branch)
1968 /// resolves and 0.14.6 bounds by the fork point. The cost of that choice is
1969 /// on the read side and is measured — [D-220] for the resolution, [D-223]
1970 /// for the cutoff — and the cost of the alternative would be here, as an
1971 /// O(rows) fork and storage multiplied by branch count (§15.3, option 3).
1972 ///
1973 /// # The fork point is *now*, and that is a bound on this release rather
1974 /// than on the design
1975 ///
1976 /// `forked_at` is stamped from the same clock as every other write, so the
1977 /// new lineage sees its parent's history up to this instant. Forking from a
1978 /// *past* instant is a coherent thing to want and the schema has always
1979 /// allowed it — `branches` carries `forked_at` and `created_at` as separate
1980 /// columns under `CHECK (forked_at <= created_at)` — but it is not in this
1981 /// release and is additive when it is.
1982 ///
1983 /// # What this lineage can do
1984 ///
1985 /// It can be **read**: every traversal entry point takes a branch, and on a
1986 /// forked ledger the read resolves along the ancestry and stops at the fork
1987 /// point. Since 0.14.8 it can also be **written** — [`EdgeAssertion`] and
1988 /// [`ConceptUpsert`] carry a lineage, and [`Self::retire_edge_on`] shadows
1989 /// an inherited edge (D-225). Through 0.14.7 they did not, and a caller who
1990 /// forked and then called `assert_edge` got a successful write **on the
1991 /// trunk**; that is fixed rather than documented now.
1992 ///
1993 /// What a branch still may not do is **restate an inherited concept**.
1994 /// `concepts` is keyed by identity, so that is refused as
1995 /// [`DbError::CrossLineage`] — see [`ConceptUpsert::branch`]. Edges are the
1996 /// thing a lineage may hold its own belief about, and superseding one is a
1997 /// row written *beside* the ancestor's rather than over it.
1998 ///
1999 /// # Errors
2000 ///
2001 /// - [`DbError::UnknownBranch`] when `from` is not registered. Named rather
2002 /// than left to the foreign key, because the caller asked about a branch.
2003 /// - [`DbError::BranchExists`] when `name` is taken — including `"main"`,
2004 /// which every database has from its first migration.
2005 /// - [`DbError::ForkPrecedesParent`] when the clock would place this fork
2006 /// point before the parent's *own* — not before the parent's
2007 /// `created_at`, which is what the schema comment promised until 0.14.7
2008 /// and is not checkable: the trunk's `created_at` is stamped during
2009 /// migration from the wall clock, before an injected clock exists, so
2010 /// that rule refuses every fork on every `FakeClock` database (D-224).
2011 /// Reachable with [`FakeClock`](crate::util::FakeClock), and the one
2012 /// refusal here that no `CHECK` could have made — it is cross-row, and a
2013 /// `CHECK` sees one row.
2014 ///
2015 /// # Example
2016 ///
2017 /// ```no_run
2018 /// # use macrame::prelude::*;
2019 /// # async fn f(db: &Database) -> Result<()> {
2020 /// let alt = db.fork(BranchId::new("turn/17/alt/1")?, BranchId::main()).await?;
2021 /// let seen = TraversalBuilder::new("socrates")
2022 /// .on_branch(alt.id.clone())
2023 /// .execute_ids(db.read_conn(), "2026-08-29T00:00:00.000000Z")
2024 /// .await?;
2025 /// # let _ = seen;
2026 /// # Ok(())
2027 /// # }
2028 /// ```
2029 ///
2030 /// [D-220]: ../../docs/architecture/s13-decision-register.md#d-220
2031 /// [D-223]: ../../docs/architecture/s13-decision-register.md#d-223
2032 pub async fn fork(
2033 &self,
2034 name: crate::branch::BranchId,
2035 from: crate::branch::BranchId,
2036 ) -> Result<crate::branch::Branch> {
2037 self.high(|responder| HighPriCommand::Fork {
2038 name,
2039 parent: from,
2040 responder,
2041 })
2042 .await
2043 }
2044
2045 /// Every lineage the ledger knows about, trunk first (§15.4).
2046 ///
2047 /// Read through [`Self::read_conn`] rather than the write actor, which is
2048 /// the difference between this and [`Self::fork`] and is deliberate:
2049 /// `branches` is append-only, so the only way this listing can be stale is
2050 /// by missing a branch created after it was taken, and a caller who wanted
2051 /// to know about that branch would have had to create it. Queueing a read
2052 /// behind the write actor would make listing branches wait on a bulk import
2053 /// for no answer it could change.
2054 ///
2055 /// A database that has never forked returns exactly one row: the trunk,
2056 /// with no parent and no fork point.
2057 pub async fn branches(&self) -> Result<Vec<crate::branch::Branch>> {
2058 crate::branch::list(self.read_conn()).await
2059 }
2060
2061 /// The beliefs `a` holds that `b` does not (§15.4, 0.14.11, D-228).
2062 ///
2063 /// One [`Divergence`](crate::branch::Divergence) per edge key the two
2064 /// lineages disagree about, in key order: `b` holds no belief about it, or
2065 /// holds one with a different interval or weight. Not symmetric —
2066 /// `diff(b, a)` is the other half, and composing the two is *two* snapshots
2067 /// even though each is one.
2068 ///
2069 /// Read through the read connection rather than the actor, like
2070 /// [`Self::branches`], and taken at one snapshot rather than two: see
2071 /// `graph::lineage::diff_sql` for why that decides the shape of the query.
2072 ///
2073 /// There is no instant parameter. A diff filtered to a valid-time instant
2074 /// cannot report the one divergence that is *about* an instant having
2075 /// passed — a branch that retired an edge its parent still holds open — so
2076 /// this compares the whole of both views.
2077 ///
2078 /// # Errors
2079 ///
2080 /// [`DbError::UnknownBranch`], naming whichever of the two is not
2081 /// registered, and `a` first when neither is.
2082 pub async fn diff(
2083 &self,
2084 a: &crate::branch::BranchId,
2085 b: &crate::branch::BranchId,
2086 ) -> Result<Vec<crate::branch::Divergence>> {
2087 crate::branch::diff(self.read_conn(), a, b).await
2088 }
2089
2090 /// Assert many edges in one transaction under one stamp (D-014).
2091 ///
2092 /// # This is the one write with no latency bound, and here is what it costs
2093 ///
2094 /// The batch is one act under one `recorded_at`, so it cannot be chunked —
2095 /// splitting it is the thing this method exists not to do. That makes the
2096 /// actor's hold a function of `edges.len()`, and until now the only
2097 /// statement of that anywhere was the prose "uncapped" in
2098 /// [`CHUNK_BUDGET`]'s table. A caller who stalls every other writer for
2099 /// eight seconds should have been able to predict it from the signature.
2100 ///
2101 /// Measured on libSQL 0.9.30 (T1.3, D-081), holding the actor for:
2102 ///
2103 /// | rows | hold |
2104 /// |---|---|
2105 /// | 500 | ~34 ms |
2106 /// | 2,000 | ~155 ms |
2107 /// | 10,000 | ~1.0 s |
2108 /// | 20,000 | ~2.6 s |
2109 ///
2110 /// [`estimated_bulk_hold`] is that curve as a function, and this method
2111 /// emits a `tracing::warn!` when it predicts more than
2112 /// [`BULK_ATOMIC_WARN_HOLD`]. **The estimate is a shape, not a promise** —
2113 /// see [`estimated_bulk_hold`] for what it is calibrated against and where
2114 /// it will be wrong.
2115 ///
2116 /// A caller who needs the latency bound and not the atomicity wants
2117 /// [`Self::bulk_import`], which is the same write chunked and explicitly not
2118 /// atomic overall (D-011).
2119 pub async fn write_bulk_atomic(&self, edges: Vec<EdgeAssertion>) -> Result<usize> {
2120 let estimate = estimated_bulk_hold(&edges);
2121 if estimate > BULK_ATOMIC_WARN_HOLD {
2122 // Warned here rather than in the actor, and before the send: this is
2123 // the caller's own task, so the log line lands with their span
2124 // attached and names the call site that chose the batch size. By the
2125 // time the actor has it, the only context left is "a large batch".
2126 tracing::warn!(
2127 rows = edges.len(),
2128 estimated_hold_ms = estimate.as_millis() as u64,
2129 "write_bulk_atomic will hold the write actor for roughly \
2130 {estimate:?} — it is atomic by contract (D-014) and cannot be \
2131 chunked. Every other writer waits that long. Use bulk_import \
2132 if the batch does not need to be all-or-nothing."
2133 );
2134 }
2135
2136 let edges = normalize_all(edges)?;
2137 self.high(|responder| HighPriCommand::WriteBulkAtomic { edges, responder })
2138 .await
2139 }
2140
2141 /// Move the WAL back into the main database file (§4.5, F-30, 0.12.13,
2142 /// W5.2, D-156).
2143 ///
2144 /// Runs `PRAGMA wal_checkpoint(FULL)` and then `(TRUNCATE)` on the write
2145 /// connection, as one actor turn, and returns what SQLite reported. **Read
2146 /// [`CheckpointReport::busy`]** — a checkpoint that could not run is an
2147 /// `Ok` whose WAL is still there.
2148 ///
2149 /// Two passes rather than one because **a truncating checkpoint cannot
2150 /// report its own work**: the counts describe the WAL *after* the
2151 /// operation, and after a truncation there is nothing left to describe, so
2152 /// `TRUNCATE` alone answers `busy=0, log=0, checkpointed=0` on success —
2153 /// indistinguishable from having done nothing. `FULL` supplies the frame
2154 /// count and `TRUNCATE` resets the file; `busy` is the union of the two.
2155 ///
2156 /// # When a caller needs this
2157 ///
2158 /// Three cases, and only three:
2159 ///
2160 /// - **Before copying the database file elsewhere.** In WAL mode the `.db`
2161 /// file alone is not the database; recent commits live in the `-wal`. A
2162 /// complete checkpoint is what makes the main file self-contained.
2163 /// - **At the end of a bulk load that turned the automatic checkpointer
2164 /// off.** That is the pairing this method exists for — see
2165 /// [`Tuning::wal_autocheckpoint`]. Disabling autocheckpoint without
2166 /// calling this leaves a WAL that grows for the life of the process.
2167 /// - **Before a long idle period**, to give back the disk.
2168 ///
2169 /// Nobody else should call it on a timer. SQLite checkpoints automatically
2170 /// every 1,000 pages and that default is not changed by this method
2171 /// existing; a periodic explicit checkpoint on top of it buys nothing and
2172 /// takes the write lock to do so.
2173 ///
2174 /// # It takes the write lock, and it is budget-exempt
2175 ///
2176 /// The hold is a function of how many frames have accumulated, which is a
2177 /// function of how long since the last checkpoint — not of anything passed
2178 /// in. It is on [`CHUNK_BUDGET`]'s exemption table for that reason, and it
2179 /// is the one entry there that is not a transaction: there is no smaller
2180 /// unit to chunk into, because the operation *is* the copy.
2181 pub async fn checkpoint(&self) -> Result<CheckpointReport> {
2182 self.high(|responder| HighPriCommand::Checkpoint { responder })
2183 .await
2184 }
2185
2186 /// Rebuild `links_current` from `links` and verify zero drift (§5.8).
2187 ///
2188 /// One transaction holding the write lock for its whole duration, because
2189 /// [D-023] will not let the `DELETE` and the `INSERT` be split: a reader
2190 /// landing between them would see a graph with no edges and no error.
2191 /// [`Self::rebuild_current_chunked`] is the same result with a different
2192 /// latency profile, and is what a populated database wants.
2193 ///
2194 /// The report's `drift_after` is the audit run inside the same transaction,
2195 /// so a repair that did not converge is reported by the call that made it
2196 /// rather than by the next one to look.
2197 ///
2198 /// [D-023]: ../docs/architecture/s13-decision-register.md#d-023
2199 pub async fn rebuild_current(&self) -> Result<RebuildReport> {
2200 self.high(|responder| HighPriCommand::RebuildCurrent { responder })
2201 .await
2202 }
2203
2204 /// Rebuild `links_current` beside itself, in chunks (§5.8, T1.2, D-082).
2205 ///
2206 /// Same result as [`Self::rebuild_current`], different latency profile.
2207 /// `rebuild_current` is one transaction holding the write lock for its whole
2208 /// duration, because D-023 will not let the `DELETE` and the `INSERT` be
2209 /// split: a reader landing between them sees a graph with no edges and no
2210 /// error. This builds the replacement in a shadow table instead — the live
2211 /// table stays live and trigger-maintained throughout — and swaps it in at
2212 /// the end.
2213 ///
2214 /// Each step is its own actor turn, so an interactive assertion can jump the
2215 /// queue between chunks. That is the whole of the improvement, and it is why
2216 /// the loop is here rather than inside the actor's arm (the same reasoning
2217 /// as [`Self::archive_windowed`] and [`Self::bulk_import`]).
2218 ///
2219 /// # What the swap still costs
2220 ///
2221 /// Not microseconds. Index names are global and SQLite has no `ALTER INDEX
2222 /// … RENAME`, so the shadow cannot be built carrying `links_current`'s index
2223 /// names while `links_current` still holds them — and building it under
2224 /// other names would leave the table permanently indexed under names absent
2225 /// from [`CREATE_INDICES`](crate::schema::ddl::CREATE_INDICES), so the next
2226 /// migration would create a second copy of each.
2227 /// `DROP TABLE` frees the names, so the swap transaction is where
2228 /// the three indexes get built. What the chunking moves off the lock is the
2229 /// **projection** — the window function over all of `links` — which is the
2230 /// O(E log E) term.
2231 ///
2232 /// # When this returns an error rather than a repair
2233 ///
2234 /// [`DbError::RebuildInterrupted`] means an archive committed while the
2235 /// shadow was being built. Its deletions are invisible to a catch-up pass
2236 /// keyed on `recorded_at` — a deleted row has no `recorded_at` left to find
2237 /// it by — so the work is discarded rather than swapped in. `links_current`
2238 /// is untouched and the call can simply be retried.
2239 ///
2240 /// Use [`Self::rebuild_current`] when the repair must be one atomic act, or
2241 /// when nothing else is contending for the actor and the extra turns are
2242 /// pure overhead.
2243 pub async fn rebuild_current_chunked(&self) -> Result<RebuildReport> {
2244 use crate::integrity::{ShadowOutcome, ShadowStep};
2245
2246 // Each `else` arm is unreachable: the actor maps each step to its own
2247 // outcome variant. Written as a refutable pattern rather than an
2248 // `unwrap` so that adding a step cannot turn a mismatch into a panic on
2249 // the write path — and `WriterDroppedResponder` is the honest name for
2250 // "the actor answered with something this cannot use".
2251 let ShadowOutcome::Started { build_start, epoch } =
2252 self.shadow_step(ShadowStep::Begin).await?
2253 else {
2254 return Err(DbError::WriterDroppedResponder);
2255 };
2256
2257 let mut after: Option<String> = None;
2258 loop {
2259 let ShadowOutcome::Filled { last } = self
2260 .shadow_step(ShadowStep::Fill {
2261 after: after.take(),
2262 })
2263 .await?
2264 else {
2265 return Err(DbError::WriterDroppedResponder);
2266 };
2267 match last {
2268 Some(last) => after = Some(last),
2269 None => break,
2270 }
2271 }
2272
2273 let ShadowOutcome::Swapped { rows } = self
2274 .shadow_step(ShadowStep::Swap { build_start, epoch })
2275 .await?
2276 else {
2277 return Err(DbError::WriterDroppedResponder);
2278 };
2279
2280 Ok(RebuildReport {
2281 rows_rebuilt: rows,
2282 // Not audited. The chunked path's whole argument is that the
2283 // expensive work happens off the lock, and `audit_current` is two
2284 // `EXCEPT` passes over the projection — the cost D-077 removed from
2285 // the archive for the same reason. A caller who wants the check has
2286 // `audit_current` on the read connection, where it costs nobody the
2287 // write lock.
2288 drift_after: 0,
2289 })
2290 }
2291
2292 /// Run one step of a chunked rebuild, for a caller doing its own scheduling.
2293 ///
2294 /// [`Self::rebuild_current_chunked`] is this in a loop and is what almost
2295 /// everyone wants. This exists because that loop offers no seam: it drives
2296 /// `Begin`, then `Fill` to exhaustion, then `Swap`, and a caller who needs to
2297 /// do something *between* steps — pace them against a frame budget, abandon
2298 /// a rebuild that has run long enough, or provoke the archive interlock in a
2299 /// test — cannot get in.
2300 ///
2301 /// The obligation that comes with it: `epoch` from
2302 /// [`ShadowOutcome::Started`](crate::integrity::ShadowOutcome) must be handed
2303 /// back to [`ShadowStep::Swap`](crate::integrity::ShadowStep), or the
2304 /// archive interlock is defeated and a stale projection can be swapped in.
2305 /// The looping version cannot get that wrong; this one can.
2306 pub async fn shadow_step(
2307 &self,
2308 step: crate::integrity::ShadowStep,
2309 ) -> Result<crate::integrity::ShadowOutcome> {
2310 self.low(|responder| LowPriCommand::ShadowRebuild { step, responder })
2311 .await
2312 }
2313
2314 /// Import edges on the background channel, chunked (D-011).
2315 ///
2316 /// Atomic *per chunk*, not overall: a failure partway leaves earlier chunks
2317 /// committed. That is the tradeoff [`chunk_rows`] documents — use
2318 /// [`Database::write_bulk_atomic`] when the batch must be all-or-nothing.
2319 ///
2320 /// Chunked adaptively, at most [`chunk_rows::EDGES`] rows at a time: that
2321 /// constant is where the loop starts and the largest chunk it will send, and
2322 /// each chunk's measured hold sizes the next against [`CHUNK_BUDGET`]. It is
2323 /// also faster in total than the larger chunks this used through 0.5.5
2324 /// (D-058).
2325 ///
2326 /// A consequence worth planning for: the chunk boundaries — and so the
2327 /// `recorded_at` stamps this import writes — depend on how fast the machine
2328 /// was, not only on how many edges were passed (§5.1.6).
2329 ///
2330 /// Returns [`BulkInterrupted`] rather than [`DbError`] on failure, because
2331 /// a path that is not all-or-nothing owes its caller the count of what
2332 /// landed (0.13.8, W7.6). `?` into a `Result<_, DbError>` still compiles
2333 /// and drops the count, which is the caller's decision to take.
2334 ///
2335 /// [`Self::bulk_import_with`] adds cancellation and per-chunk progress.
2336 pub async fn bulk_import(&self, edges: Vec<EdgeAssertion>) -> BulkResult<usize> {
2337 self.bulk_import_with(edges, BulkControl::new()).await
2338 }
2339
2340 /// [`Self::bulk_import`] with cancellation and progress (0.13.8, W7.6,
2341 /// D-181).
2342 ///
2343 /// The chunk boundaries this path already has are what make both possible:
2344 /// the loop is between transactions several times a second, which is where
2345 /// a token can be read and a callback run without holding anything.
2346 pub async fn bulk_import_with(
2347 &self,
2348 edges: Vec<EdgeAssertion>,
2349 control: BulkControl,
2350 ) -> BulkResult<usize> {
2351 let edges = normalize_all(edges).map_err(before_any_chunk)?;
2352 self.low_chunked(edges, chunk_rows::EDGES, control, |chunk, responder| {
2353 LowPriCommand::BulkImportChunk { chunk, responder }
2354 })
2355 .await
2356 }
2357
2358 /// Upsert many **concepts** on the background channel, chunked (D-011).
2359 ///
2360 /// This is the bulk concept path, and every row it writes is a ledger write:
2361 /// it versions the concept and lands in `transaction_log`. Derived analytics
2362 /// output does not belong here — see
2363 /// [`Database::write_analytics_annotations`] and D-041.
2364 ///
2365 /// Called `write_annotations` through 0.5.6, from when the two writes were
2366 /// one call. D-041 split them and the name stayed on the wrong one for three
2367 /// releases, so the crate had a `write_annotations` that wrote concepts
2368 /// sitting beside a `write_analytics_annotations` that wrote annotations
2369 /// (D-075).
2370 ///
2371 /// Chunked, so it returns [`BulkInterrupted`] and its `written` count on
2372 /// failure (0.13.8, W7.6); [`Self::write_concepts_with`] adds cancellation
2373 /// and progress.
2374 pub async fn write_concepts(&self, concepts: Vec<ConceptUpsert>) -> BulkResult<usize> {
2375 self.write_concepts_with(concepts, BulkControl::new()).await
2376 }
2377
2378 /// [`Self::write_concepts`] with cancellation and progress (0.13.8, W7.6).
2379 pub async fn write_concepts_with(
2380 &self,
2381 concepts: Vec<ConceptUpsert>,
2382 control: BulkControl,
2383 ) -> BulkResult<usize> {
2384 let concepts: Vec<ConceptUpsert> = concepts
2385 .into_iter()
2386 .map(ConceptUpsert::normalized)
2387 .collect::<Result<_>>()
2388 .map_err(before_any_chunk)?;
2389 self.low_chunked(
2390 concepts,
2391 chunk_rows::CONCEPTS,
2392 control,
2393 |chunk, responder| LowPriCommand::WriteConceptsChunk { chunk, responder },
2394 )
2395 .await
2396 }
2397
2398 /// State as believed at `ts` (§5.5, D-026, D-049).
2399 ///
2400 /// A read: it runs on `read_conn` and never touches the Write Actor, so a
2401 /// reconstruction and a full-speed write-back do not slow each other.
2402 ///
2403 /// Prefer this to calling [`crate::temporal::reconstruct`] directly. The
2404 /// free function takes the archive path and the snapshot directory as
2405 /// arguments, and a caller who passes `None` for the second gets a correct
2406 /// answer that folds the whole log every time — the composition is opt-in
2407 /// at that layer and easy to leave off by accident. Here both come from the
2408 /// handle, so the fast path is the default one.
2409 pub async fn reconstruct(&self, ts: &str) -> Result<crate::temporal::MaterializedState> {
2410 let ts = timestamp::normalize(ts)?;
2411 crate::temporal::reconstruct(
2412 &self.read_conn,
2413 &ts,
2414 Some(&self.archive_path),
2415 Some(&self.snapshots_dir),
2416 )
2417 .await
2418 }
2419
2420 /// Create a model's embedding table and DiskANN index (§5.9, D-048).
2421 ///
2422 /// Idempotent: registering a model that already exists at the same
2423 /// dimension succeeds, and at a different dimension fails with
2424 /// [`DbError::DimMismatch`] naming both, rather than no-opping through
2425 /// `IF NOT EXISTS` and leaving the caller believing the dimension they
2426 /// asked for is the one in force.
2427 ///
2428 /// This issues DDL, which everywhere else in the crate is the migration
2429 /// runner's exclusive business (D-032). The exception is bounded and
2430 /// deliberate: a model's table is created once, by an explicit call, and
2431 /// the alternative — a caller-supplied write connection — is the very thing
2432 /// the Write Actor exists to make impossible.
2433 ///
2434 /// # Latency
2435 ///
2436 /// One small transaction, but it queues like any other write: see §5.1.8.
2437 pub async fn register_model(&self, model: &ModelName, dim: usize) -> Result<()> {
2438 let model = model.clone();
2439 self.high(|responder| HighPriCommand::RegisterModel {
2440 model,
2441 dim,
2442 responder,
2443 })
2444 .await
2445 }
2446
2447 /// Store or replace vectors for `model`, chunked (§5.9, D-011, D-048).
2448 ///
2449 /// The write path for embeddings. Before 0.5.4 there was none:
2450 /// [`crate::vector::upsert_embedding`] takes a raw connection, `read_conn`
2451 /// is `query_only`, and the write connection lives inside the actor — so an
2452 /// application could search vectors it had no way to store.
2453 ///
2454 /// Low priority and chunked at [`chunk_rows::EMBEDDINGS`], because embedding
2455 /// is bulk derived work: a 50,000-vector backfill must yield to an
2456 /// interactive assertion at every chunk boundary. That constant is the
2457 /// smallest of the four by a wide margin — DiskANN index maintenance makes an
2458 /// embedding the most expensive row in the system (D-058). Atomic per chunk, not overall, which
2459 /// is the same trade [`Database::bulk_import`] makes and is safer here than
2460 /// there — an embedding is derived (Doctrine VII), so a partially written
2461 /// batch is recoverable by re-embedding.
2462 ///
2463 /// Fails with [`DbError::ModelNotRegistered`] if `model` has no table, and
2464 /// [`DbError::DimMismatch`] if a vector's length is not the declared
2465 /// dimension. The dimension is read from the schema once per chunk (D-037):
2466 /// the crate keeps no registry of its own to fall out of date.
2467 ///
2468 /// Chunked, so it returns [`BulkInterrupted`] and its `written` count on
2469 /// failure (0.13.8, W7.6). A 50,000-vector backfill is the longest-running
2470 /// write the crate has, which makes it the one most likely to be cancelled
2471 /// — [`Self::upsert_embeddings_with`] is how.
2472 pub async fn upsert_embeddings(
2473 &self,
2474 model: &ModelName,
2475 rows: Vec<(String, Vec<f32>)>,
2476 ) -> BulkResult<usize> {
2477 self.upsert_embeddings_with(model, rows, BulkControl::new())
2478 .await
2479 }
2480
2481 /// [`Self::upsert_embeddings`] with cancellation and progress (0.13.8,
2482 /// W7.6).
2483 pub async fn upsert_embeddings_with(
2484 &self,
2485 model: &ModelName,
2486 rows: Vec<(String, Vec<f32>)>,
2487 control: BulkControl,
2488 ) -> BulkResult<usize> {
2489 self.low_chunked(rows, chunk_rows::EMBEDDINGS, control, |chunk, responder| {
2490 LowPriCommand::UpsertEmbeddingChunk {
2491 model: model.clone(),
2492 chunk,
2493 responder,
2494 }
2495 })
2496 .await
2497 }
2498
2499 /// Reconstruct the concept-text search index from the ledger (§5.9, D-036).
2500 ///
2501 /// The FTS index is derivative: D-036 promises every derivative table can be
2502 /// rebuilt from the ledger tables, and this is that promise made callable
2503 /// for `concepts_fts`. Needed after a restore that skipped the shadow
2504 /// tables, or if the index is ever suspected of drifting from the text —
2505 /// and, as a matter of policy, cheaper to run than to reason about.
2506 ///
2507 /// The work is `INSERT INTO concepts_fts(concepts_fts) VALUES('rebuild')`,
2508 /// which is FTS5's own operation over the content table, so this is not a
2509 /// second implementation of the sync triggers that could disagree with them.
2510 pub async fn rebuild_fts(&self) -> Result<()> {
2511 self.low(|responder| LowPriCommand::RebuildFts { responder })
2512 .await
2513 }
2514
2515 /// Refresh the query planner's statistics (0.12.4, [D-149]).
2516 ///
2517 /// Runs `ANALYZE`, which writes `sqlite_stat1`. **Before 0.12.4 nothing in
2518 /// this crate ever did**, so the planner costed every query against SQLite's
2519 /// built-in defaults — assume ~1M rows, assume each bound equality column
2520 /// divides by ten. That estimate is structural: it depends on how many
2521 /// columns a query binds, not on what the table contains.
2522 ///
2523 /// Which is this schema's own worst defect restated. D-042, D-059 and D-064
2524 /// are three occasions where *a covering index captured a query because it
2525 /// contained the columns, not because it discriminated*, and two of the four
2526 /// declared indices lead on the same column. Statistics are what let the
2527 /// planner tell them apart by measurement instead of by shape.
2528 ///
2529 /// # Cost, and why it is bounded
2530 ///
2531 /// This is a write and it takes the write lock. `PRAGMA analysis_limit`
2532 /// (set per connection, see [`ddl::ANALYSIS_LIMIT`]) caps the rows examined
2533 /// per index. It is scheduled as low-priority work and will not preempt an
2534 /// interactive assertion.
2535 ///
2536 /// **The bound is a constant factor, not an independence** (0.12.23,
2537 /// D-166). This rustdoc said the hold "scales with the number of indices —
2538 /// four — and not with the size of `links_current`", which is measurably
2539 /// wrong: the pragma is worth 3–4× and what remains still grows with the
2540 /// table. Measured, `examples/analyze_hold.rs`: **5.26 ms at 10,000 edges,
2541 /// 19.1 ms at 40,000**, against a 3 ms [`crate::CHUNK_BUDGET`].
2542 ///
2543 /// So this call **misses the budget by ~6× on a moderately sized ledger**,
2544 /// and [`crate::metrics::CommandKind::Analyze`] is deliberately not among
2545 /// the budget-exempt kinds — `metrics().budget_violations()` names it. That
2546 /// is the honest position: the work is low priority and preemptible between
2547 /// commands, but it is one indivisible statement and cannot be chunked, so
2548 /// the hold is what it is. Prefer [`optimize`], which does nothing when
2549 /// nothing has moved.
2550 ///
2551 /// **Since 0.13.24 the counter is this call and not also [`optimize`]**
2552 /// (W10.5, [D-197]). The two shared `CommandKind::Analyze` until then, which
2553 /// is why an `analyze` row in `budget_violations()` used to be unreadable:
2554 /// it could have been an explicit call or a handle close.
2555 ///
2556 /// # When to call it
2557 ///
2558 /// After a bulk import, and after anything that changes a table's shape by
2559 /// an order of magnitude. Prefer [`optimize`] for routine upkeep: it does
2560 /// nothing when nothing has moved, and this does the work unconditionally.
2561 ///
2562 /// Statistics are derived state in the sense Doctrine VI means it — deleting
2563 /// `sqlite_stat1` costs plan quality and no information, and this call
2564 /// rebuilds it.
2565 ///
2566 /// [D-149]: ../docs/architecture/s13-decision-register.md#d-149
2567 /// [`ddl::ANALYSIS_LIMIT`]: crate::schema::ddl::ANALYSIS_LIMIT
2568 /// [`optimize`]: Database::optimize
2569 pub async fn analyze(&self) -> Result<()> {
2570 self.low(|responder| LowPriCommand::Analyze {
2571 incremental: false,
2572 responder,
2573 })
2574 .await
2575 }
2576
2577 /// Re-analyse only what has gone stale (0.12.4, [D-149]).
2578 ///
2579 /// `PRAGMA optimize`. SQLite tracks how far each table has drifted since its
2580 /// last analysis and re-analyses only where it believes the statistics no
2581 /// longer hold — so this is a no-op on an idle database and the full cost of
2582 /// [`analyze`] on one that has changed completely.
2583 ///
2584 /// That property is the whole point: it is safe to call on a schedule, where
2585 /// [`analyze`] is not. `close()` runs it, so a process that opens, works and
2586 /// closes keeps its statistics current without anybody arranging it.
2587 ///
2588 /// # What it costs, measured, and the threshold it applies rather than takes
2589 /// (0.13.24, W10.5, [D-197])
2590 ///
2591 /// `examples/optimize_hold.rs`, on a 40,000-edge ledger: **10.7 ms the
2592 /// first time on a database that has never been analysed** — there is
2593 /// nothing incremental about the first call — and **90–220 µs every time
2594 /// after**, well inside [`crate::CHUNK_BUDGET`].
2595 ///
2596 /// **The staleness test is SQLite's and it is a ratio, not a row count.**
2597 /// Measured by reading `sqlite_stat1` across the call rather than by timing
2598 /// it: growth of 2× and 5× both left the statistics **untouched**, and
2599 /// only at 25× did it re-analyse — for a 460 ms hold. So this is not a
2600 /// cheaper `analyze()` and calling it after a bulk load is not a way to
2601 /// refresh statistics the load invalidated: below the ratio it declines,
2602 /// and above it it costs what [`analyze`] costs. It reports as
2603 /// [`crate::metrics::CommandKind::Optimize`] since 0.13.24, which is what
2604 /// makes those two outcomes distinguishable in the metrics at all.
2605 ///
2606 /// [D-197]: ../docs/architecture/s13-decision-register.md#d-197
2607 ///
2608 /// [D-149]: ../docs/architecture/s13-decision-register.md#d-149
2609 /// [`analyze`]: Database::analyze
2610 pub async fn optimize(&self) -> Result<()> {
2611 self.low(|responder| LowPriCommand::Analyze {
2612 incremental: true,
2613 responder,
2614 })
2615 .await
2616 }
2617
2618 // **There is deliberately no `verify_fts()` (§5.9, D-071).**
2619 //
2620 // `rebuild_fts` is the repair with no way to ask whether it is needed, and
2621 // Wave 5 set out to add the missing half. FTS5 offers `'integrity-check'`,
2622 // which looked like exactly the engine-provided answer this crate prefers.
2623 // It is not: on libSQL 0.9.30 it verifies the index's *internal* consistency
2624 // and not its agreement with the content table. Measured — after
2625 // `'delete-all'` the index matches nothing where it matched ten rows, and
2626 // both `'integrity-check'` and `'integrity-check', 0` still report success.
2627 //
2628 // A `verify_fts()` on that footing would answer "healthy" for an empty
2629 // index, which is worse than having no method at all: it is the shape of
2630 // defect AC, a function that looks like it checks something and does not.
2631 // `an_emptied_fts_index_still_passes_integrity_check` pins the limitation so
2632 // that if a later libSQL fixes it, the test fails and says so.
2633
2634 /// Write derived analytics results on the background channel, chunked
2635 /// (§5.4, D-041).
2636 ///
2637 /// Rows go to `analytics_annotations`, which has no log trigger, so nothing
2638 /// written here reaches `transaction_log` and nothing here versions a
2639 /// concept. Rerunning an algorithm replaces the previous pass rather than
2640 /// recording that the world changed.
2641 ///
2642 /// Low priority and chunked at up to [`chunk_rows::ANNOTATIONS`] — the
2643 /// largest ceiling of the four, because this is the only bulk table carrying
2644 /// no triggers at all
2645 /// and its rows are correspondingly cheap (D-058) — so a 50,000-label Louvain
2646 /// save yields to interactive writes at every chunk boundary and carries the
2647 /// per-chunk fidelity boundary of §5.1.6 — a partially written pass is
2648 /// recoverable by rerunning, which is the property that makes derived state
2649 /// safe to write this way and assertions not.
2650 ///
2651 /// Chunked, so it returns [`BulkInterrupted`] and its `written` count on
2652 /// failure (0.13.8, W7.6); [`Self::write_analytics_annotations_with`] adds
2653 /// cancellation and progress.
2654 pub async fn write_analytics_annotations(
2655 &self,
2656 annotations: Vec<Annotation>,
2657 ) -> BulkResult<usize> {
2658 self.write_analytics_annotations_with(annotations, BulkControl::new())
2659 .await
2660 }
2661
2662 /// [`Self::write_analytics_annotations`] with cancellation and progress
2663 /// (0.13.8, W7.6).
2664 pub async fn write_analytics_annotations_with(
2665 &self,
2666 annotations: Vec<Annotation>,
2667 control: BulkControl,
2668 ) -> BulkResult<usize> {
2669 self.low_chunked(
2670 annotations,
2671 chunk_rows::ANNOTATIONS,
2672 control,
2673 |chunk, responder| LowPriCommand::WriteAnalyticsChunk { chunk, responder },
2674 )
2675 .await
2676 }
2677
2678 /// Move closed intervals and superseded log rows older than `cutoff` to the
2679 /// cold database (§5.7, D-012).
2680 pub async fn archive(&self, cutoff: &str) -> Result<ArchiveReport> {
2681 let cutoff = timestamp::normalize(cutoff)?;
2682 let archive_path = self.archive_path.clone();
2683 self.low(|responder| LowPriCommand::Archive {
2684 cutoff,
2685 archive_path,
2686 responder,
2687 })
2688 .await
2689 }
2690
2691 /// Forget one lineage: move its whole ledger to the cold database and
2692 /// remove the lineage record (0.14.13, §15.4, D-230).
2693 ///
2694 /// The abandonment arm. A conversation tree discards most of what it grows,
2695 /// and [`Self::archive`] cannot reclaim it: that arm is indexed by *time*,
2696 /// so archiving an abandoned branch's recent history means archiving the
2697 /// trunk's recent history with it.
2698 ///
2699 /// **Everything the lineage holds moves in one transaction** — its `links`,
2700 /// its `concepts`, its `transaction_log` entries and its `branches` row —
2701 /// and afterwards the name is unknown: every read and write naming it
2702 /// raises [`DbError::UnknownBranch`]. That is the design's whole shape, and
2703 /// `temporal::archive::archive_branch` records why it has no smaller
2704 /// version.
2705 ///
2706 /// # It refuses more than it accepts, on purpose
2707 ///
2708 /// - The trunk, and a name that is not registered
2709 /// ([`DbError::UnknownBranch`]).
2710 /// - A branch with **descendants**: they read through it, so archiving it
2711 /// would delete rows they still believe.
2712 /// - A branch whose **concepts another lineage's hot link names**. The road
2713 /// map assumed an abandoned branch's rows were "a contiguous archivable
2714 /// set by construction"; a concept is keyed by identity across the whole
2715 /// ledger (D-214), so they are not, and this refusal is what makes them
2716 /// contiguous in the cases it accepts.
2717 ///
2718 /// All but the first return [`DbError::BranchNotArchivable`] with a reason.
2719 ///
2720 /// The lineage record lands in `cold.branches` with an `archived_at`, so a
2721 /// cold row's `branch_id` still resolves to something — in the cold file,
2722 /// which is now the only place it does.
2723 pub async fn archive_branch(&self, branch: crate::branch::BranchId) -> Result<ArchiveReport> {
2724 let branch = branch.as_str().to_string();
2725 let archive_path = self.archive_path.clone();
2726 self.low(|responder| LowPriCommand::ArchiveBranch {
2727 branch,
2728 archive_path,
2729 responder,
2730 })
2731 .await
2732 }
2733
2734 /// Move the named concepts back from the cold database into the hot tables
2735 /// (§2.3, C3).
2736 ///
2737 /// Rehydration is a **physical move back, not a write**: it mints no
2738 /// transaction-time facts and is invisible to both clocks. An id that is not
2739 /// in the cold file is skipped rather than being an error — the caller
2740 /// generally has a list from a cold-side query, and a partially-stale list is
2741 /// the normal case rather than a mistake. The report says how many actually
2742 /// moved.
2743 ///
2744 /// See [`RehydrateReport::rowids_reassigned`] for the one way a rehydrated
2745 /// row can differ from the row that was archived.
2746 pub async fn rehydrate(&self, ids: &[&str]) -> Result<RehydrateReport> {
2747 let ids: Vec<String> = ids.iter().map(|s| (*s).to_string()).collect();
2748 let archive_path = self.archive_path.clone();
2749 self.low(|responder| LowPriCommand::Rehydrate {
2750 ids,
2751 archive_path,
2752 responder,
2753 })
2754 .await
2755 }
2756
2757 /// Archive up to `cutoff` as a sequence of sessions, each covering at most
2758 /// `window` of **transaction** time (T1.1, D-080).
2759 ///
2760 /// `archive(cutoff)` is one transaction whose size is set by how long it has
2761 /// been since the last one, which makes it the least bounded of the three
2762 /// operations exempt from [`CHUNK_BUDGET`] — its hold is a function of
2763 /// operational history rather than of anything a caller chose. This runs the
2764 /// same work as *N* complete sessions, each with its own marker, horizon row
2765 /// and rebuild, and returns one [`ArchiveReport`] per session in order.
2766 ///
2767 /// # D-012 is satisfied per session, and that is what it requires
2768 ///
2769 /// The atomicity D-012 demands is that copy-then-delete never be split — a
2770 /// crash between the phases duplicates or loses rows. *N* small sessions
2771 /// satisfy that exactly as one large one does. The obligation windowing adds
2772 /// is that a partial run leave a coherent intermediate state, which it does:
2773 /// each session commits a valid horizon, so a failure at window *k* leaves a
2774 /// database archived up to boundary *k−1* and nothing in between. **The
2775 /// sequence is not atomic and does not claim to be** — on error, the reports
2776 /// for the sessions that did commit are lost with it, but their effect is
2777 /// not, and re-running with the same `cutoff` completes the job.
2778 ///
2779 /// # Each session is its own actor turn, and that is the entire point
2780 ///
2781 /// This loop lives here, on the handle, rather than inside the actor's
2782 /// `Archive` arm. Putting it there would have produced *N* small
2783 /// transactions inside **one** hold, which shrinks the transaction and
2784 /// changes the latency not at all: the actor is single-threaded, so nothing
2785 /// else writes until its turn returns regardless of how many `COMMIT`s the
2786 /// turn contains. Sending *N* commands returns the actor to its `select!`
2787 /// between sessions, which is where an interactive assertion gets to jump
2788 /// the queue — and it is high-priority, so it does.
2789 ///
2790 /// The same reasoning is why [`Self::bulk_import`] chunks here and not
2791 /// there, and it is the trap T1.2 names for `CREATE TABLE … AS SELECT`.
2792 ///
2793 /// # Choosing a window
2794 ///
2795 /// The bound is on *transaction* time, so the session count is set by how
2796 /// far back the hot file goes, not by how much it holds. A window is
2797 /// rejected rather than clamped if it would need more than
2798 /// [`MAX_ARCHIVE_SESSIONS`] sessions — see [`DbError::ArchiveWindow`].
2799 ///
2800 /// Windows containing nothing archivable are cheap but not free: each still
2801 /// opens a transaction and writes a horizon row. What they no longer do is
2802 /// re-project `links_current`, which `archive_session` now skips when its
2803 /// `DELETE` removed no rows — without that, windowing costs *more* in total
2804 /// than not windowing, because the repair term scales with the surviving
2805 /// table and not with the batch (D-077).
2806 pub async fn archive_windowed(
2807 &self,
2808 cutoff: &str,
2809 window: std::time::Duration,
2810 ) -> Result<Vec<ArchiveReport>> {
2811 let cutoff = timestamp::normalize(cutoff)?;
2812 let boundaries = self.archive_boundaries(&cutoff, window).await?;
2813
2814 let mut reports = Vec::with_capacity(boundaries.len());
2815 for boundary in boundaries {
2816 let archive_path = self.archive_path.clone();
2817 reports.push(
2818 self.low(|responder| LowPriCommand::Archive {
2819 cutoff: boundary,
2820 archive_path,
2821 responder,
2822 })
2823 .await?,
2824 );
2825 }
2826 Ok(reports)
2827 }
2828
2829 /// The cutoffs [`Self::archive_windowed`] will run, ascending, ending at
2830 /// `cutoff` exactly.
2831 ///
2832 /// Read on `read_conn`, not on the actor: this is two `MIN`s and the actor
2833 /// has no reason to hold its lock for them.
2834 ///
2835 /// The lower end comes from the data rather than from the clock. Stepping
2836 /// from some fixed epoch would make the session count a function of the
2837 /// calendar — a database opened yesterday would still be asked to archive
2838 /// 1970 — whereas the oldest `recorded_at` actually present is the earliest
2839 /// boundary that can contain anything.
2840 async fn archive_boundaries(
2841 &self,
2842 cutoff: &str,
2843 window: std::time::Duration,
2844 ) -> Result<Vec<String>> {
2845 // A single session at `cutoff` is exactly `archive(cutoff)`, and it is
2846 // the right answer for an empty hot file: it still writes the horizon
2847 // row, so windowed and unwindowed runs leave the same observable state.
2848 let Some(oldest) = self.oldest_hot_stamp(cutoff).await? else {
2849 return Ok(vec![cutoff.to_string()]);
2850 };
2851
2852 let start = timestamp::parse(&oldest)?;
2853 let end = timestamp::parse(cutoff)?;
2854 let Ok(span) = end.duration_since(start) else {
2855 // Everything in the hot file is at or after the cutoff, so there is
2856 // nothing in range to divide.
2857 return Ok(vec![cutoff.to_string()]);
2858 };
2859
2860 if window.is_zero() {
2861 return Err(DbError::ArchiveWindow {
2862 window,
2863 reason: "a zero-length window never advances past the first boundary".into(),
2864 });
2865 }
2866
2867 // `div_ceil` on nanos: a span of 90 minutes in 60-minute windows is two
2868 // sessions, not one. `as_nanos` is u128, so neither the division nor the
2869 // span can overflow for any timestamp this crate can store.
2870 let sessions = span.as_nanos().div_ceil(window.as_nanos());
2871 if sessions > MAX_ARCHIVE_SESSIONS as u128 {
2872 return Err(DbError::ArchiveWindow {
2873 window,
2874 reason: format!(
2875 "a span of {span:?} would need {sessions} sessions (limit \
2876 {MAX_ARCHIVE_SESSIONS}); widen the window"
2877 ),
2878 });
2879 }
2880
2881 let mut boundaries = Vec::with_capacity(sessions as usize);
2882 for k in 1..sessions {
2883 boundaries.push(timestamp::format(start + window * k as u32));
2884 }
2885 // The last boundary is `cutoff` itself and not `start + n*window`, which
2886 // would overshoot and archive rows the caller excluded.
2887 boundaries.push(cutoff.to_string());
2888 Ok(boundaries)
2889 }
2890
2891 /// Oldest `recorded_at` below `cutoff` in either hot table, or `None`.
2892 async fn oldest_hot_stamp(&self, cutoff: &str) -> Result<Option<String>> {
2893 let mut oldest: Option<String> = None;
2894 for table in ["links", "transaction_log"] {
2895 let found: Option<String> = self
2896 .read_conn
2897 .query(
2898 &format!("SELECT MIN(recorded_at) FROM {table} WHERE recorded_at < ?1"),
2899 libsql::params![cutoff],
2900 )
2901 .await?
2902 .next()
2903 .await?
2904 .and_then(|row| row.get(0).ok());
2905 if let Some(found) = found {
2906 if oldest.as_ref().is_none_or(|o| found < *o) {
2907 oldest = Some(found);
2908 }
2909 }
2910 }
2911 Ok(oldest)
2912 }
2913
2914 /// Send a high-priority command and wait for its answer.
2915 ///
2916 /// The two error mappings here are the whole reason this helper exists.
2917 /// `send` failing means the actor is gone — `WriterUnavailable`. The
2918 /// responder being dropped without an answer means the actor took the
2919 /// command and never replied — `WriterDroppedResponder`, which is a bug in
2920 /// the actor rather than a condition the caller can retry. Both variants
2921 /// existed in `error.rs` from 0.4.5 and neither was ever constructed, so a
2922 /// dead actor and a hung one were both just a caller waiting forever.
2923 async fn high<T>(
2924 &self,
2925 make: impl FnOnce(oneshot::Sender<Result<T>>) -> HighPriCommand,
2926 ) -> Result<T> {
2927 let (tx, rx) = oneshot::channel();
2928 self.highpri_tx
2929 .send(make(tx))
2930 .await
2931 .map_err(|_| DbError::WriterUnavailable)?;
2932 rx.await.map_err(|_| DbError::WriterDroppedResponder)?
2933 }
2934
2935 /// Send each chunk in turn and sum the counts — the shape all four bulk
2936 /// paths share (T3.4, D-086).
2937 ///
2938 /// # This is sequential on purpose, and the purpose is a measurement
2939 ///
2940 /// T3.4 proposed pipelining: send *k* chunks ahead so the actor never finds
2941 /// an empty queue. The reasoning is that awaiting each chunk before building
2942 /// the next leaves the actor idle for a channel round trip every time, which
2943 /// on a 1M-edge import is ~11,000 idle gaps.
2944 ///
2945 /// Both halves of that are true and the conclusion does not follow. The gaps
2946 /// are real; they are also **four orders of magnitude smaller than the work
2947 /// they interrupt**. A tokio mpsc hop is sub-microsecond and a chunk takes
2948 /// 13–21 ms. Implemented and swept at depths 1, 2, 4, 8 and 16 over 20K and
2949 /// 100K edges: every cell landed within 1% of sequential, in both directions
2950 /// — see `examples/pipeline_diag.rs`, which is kept precisely so this is not
2951 /// re-proposed from the same reasoning.
2952 ///
2953 /// So the pipelining was removed and the deduplication kept. It was not free
2954 /// to hold: with chunks in flight, a failure at chunk `i` no longer leaves a
2955 /// **prefix** committed, because `i+1 ..= i+k-1` were already sent and commit
2956 /// anyway. D-011 promises "earlier chunks committed", and paying for that
2957 /// with a weaker recovery story in exchange for nothing measurable is the
2958 /// wrong trade.
2959 ///
2960 /// Sending stops at the first error, so what commits is exactly the prefix
2961 /// before the failure.
2962 /// # The size is now measured, not assumed (0.12.0, W3)
2963 ///
2964 /// Until 0.11.0 the caller pre-split into `chunks(chunk_rows::WHATEVER)` and
2965 /// this loop sent what it was given. That made the constant *the* size, and
2966 /// D-143 is the record of a constant fitted at one population being wrong at
2967 /// another: all four D-088 shapes agreed the largest in-budget edge chunk was
2968 /// **20** against a shipped 90, and 20 would itself have been wrong at 80,000
2969 /// edges, because per-row cost on that path grows with `links_current`.
2970 ///
2971 /// No row count can bound a duration on such a path, so the loop stopped
2972 /// trying to pick one ahead of time. `ceiling` — still the path's
2973 /// [`chunk_rows`] constant, with its derivation intact — is now the largest
2974 /// size this will ever ask for, and each chunk's measured hold chooses the
2975 /// next through `next_chunk_size`.
2976 ///
2977 /// **Feedback, not preemption.** The chunk in flight always commits in full;
2978 /// the SQLite write lock is not preemptible, so nothing here can shorten a
2979 /// transaction already running. A batch of one chunk gets no protection at
2980 /// all, and convergence costs one or two chunks — which is the price of the
2981 /// bound being a duration rather than a promise.
2982 ///
2983 /// The last chunk's outcome is discarded, there being no next chunk to size.
2984 /// The chunk loop behind all four bulk paths.
2985 ///
2986 /// **Every exit carries `written`** (0.13.8, W7.6, D-181). It used to
2987 /// carry it only out of the success arm: the three error paths were `?` on
2988 /// a [`DbError`], which discards the local, so a caller whose 20,000-row
2989 /// import failed in the last chunk learned that it failed and not that
2990 /// 19,000 rows were already in the database. The count was never expensive
2991 /// to keep — it is right there, and the loop needs it anyway to size the
2992 /// next chunk.
2993 async fn low_chunked<T>(
2994 &self,
2995 items: Vec<T>,
2996 ceiling: usize,
2997 control: BulkControl,
2998 make: impl Fn(Vec<T>, oneshot::Sender<Result<ChunkOutcome>>) -> LowPriCommand,
2999 ) -> BulkResult<usize> {
3000 let total = items.len();
3001 let mut items = items.into_iter();
3002 let mut size = ceiling.max(1);
3003 let mut written = 0usize;
3004 loop {
3005 let chunk: Vec<T> = items.by_ref().take(size).collect();
3006 if chunk.is_empty() {
3007 // Emptiness is checked before cancellation on purpose: a token
3008 // raised after the last chunk committed is asking to stop work
3009 // that is already done, and reporting that as a failure would
3010 // make a race between the caller's two threads decide whether a
3011 // complete import counts as one.
3012 return Ok(written);
3013 }
3014 // Between chunks, never inside one. Nothing is rolled back and no
3015 // transaction is interrupted -- the loop simply stops sending, and
3016 // the prefix that committed is the same kind of prefix a failure
3017 // would have left.
3018 if control.is_cancelled() {
3019 return Err(BulkInterrupted {
3020 written,
3021 cause: DbError::BulkCancelled,
3022 });
3023 }
3024 let stop = |cause: DbError| BulkInterrupted { written, cause };
3025 let (tx, rx) = oneshot::channel();
3026 self.lowpri_tx
3027 .send(make(chunk, tx))
3028 .await
3029 .map_err(|_| stop(DbError::WriterUnavailable))?;
3030 let outcome = match rx.await {
3031 Err(_) => return Err(stop(DbError::WriterDroppedResponder)),
3032 Ok(Err(e)) => return Err(stop(e)),
3033 Ok(Ok(outcome)) => outcome,
3034 };
3035 written += outcome.rows;
3036 control.report(BulkProgress {
3037 written,
3038 total,
3039 rows: outcome.rows,
3040 held: outcome.held,
3041 });
3042 size = next_chunk_size(size, outcome.held, CHUNK_BUDGET, CHUNK_FLOOR, ceiling);
3043 }
3044 }
3045
3046 async fn low<T>(
3047 &self,
3048 make: impl FnOnce(oneshot::Sender<Result<T>>) -> LowPriCommand,
3049 ) -> Result<T> {
3050 let (tx, rx) = oneshot::channel();
3051 self.lowpri_tx
3052 .send(make(tx))
3053 .await
3054 .map_err(|_| DbError::WriterUnavailable)?;
3055 rx.await.map_err(|_| DbError::WriterDroppedResponder)?
3056 }
3057
3058 /// Clean shutdown: stop the Write Actor, then write the final snapshot (§5.1.7).
3059 ///
3060 /// Order matters. The snapshot is taken *after* the actor has stopped and
3061 /// been joined, so no write can land between the fold and the file — the
3062 /// anchor it records is the last thing that happened, not the last thing
3063 /// that happened to be visible.
3064 ///
3065 /// A failed snapshot is reported rather than swallowed. It is not a
3066 /// durability loss — the ledger is in the WAL and the log replays without
3067 /// it — but it means the next open starts from an older anchor, and a caller
3068 /// that never hears about it cannot know why startup got slower.
3069 ///
3070 /// **The cadence stops first (§5.5, D-053).** Both it and `write_final` end
3071 /// by running retention over the snapshot directory, and retention deletes
3072 /// files. Letting them overlap would mean one pass enumerating the directory
3073 /// while the other removes from it — not a correctness problem for the
3074 /// ledger, which is why the ordering is stated rather than locked, but a
3075 /// source of spurious warnings and of a final anchor that could be deleted
3076 /// by a cleanup that started before it existed. Stopping the cadence, then
3077 /// the actor, then taking the snapshot leaves exactly one writer at each
3078 /// step.
3079 pub async fn close(mut self) -> Result<()> {
3080 if let Some(stop) = self.cadence_stop.take() {
3081 let _ = stop.send(true);
3082 }
3083 if let Some(handle) = self.cadence.take() {
3084 let _ = handle.await;
3085 }
3086
3087 // Top up the planner's statistics while the actor is still alive to do
3088 // it (0.12.4, D-149). `PRAGMA optimize` re-analyses only what SQLite
3089 // believes has gone stale, so on a database that did nothing this costs
3090 // nothing, and on one that was just bulk-loaded it is the difference
3091 // between the next process planning on measurements and planning on
3092 // built-in guesses.
3093 //
3094 // **Deliberately not fatal.** A failure here costs plan quality on the
3095 // next open and nothing else — no ledger state depends on it — and
3096 // `close()` is where a caller learns whether their *writes* survived.
3097 // Turning a stale-statistics problem into a failed close would bury that
3098 // answer under a much less important one.
3099 if let Err(e) = self.optimize().await {
3100 tracing::warn!(
3101 "PRAGMA optimize failed during close(): {e}. Statistics may be \
3102 stale for the next process; call analyze() to rebuild them. \
3103 Nothing else is affected."
3104 );
3105 }
3106
3107 let (tx, rx) = oneshot::channel();
3108 let _ = self
3109 .highpri_tx
3110 .send(HighPriCommand::Shutdown { responder: tx })
3111 .await;
3112 let _ = rx.await;
3113
3114 // **The writer's exit status is propagated, not discarded (Wave 4.2).**
3115 // It used to be `let _ = handle.await`, so an actor that had died closed
3116 // "successfully" and the caller's last chance to learn that the write
3117 // path was gone was spent silently.
3118 //
3119 // Through 0.13.3 this awaited a `JoinHandle<Result<()>>` and did
3120 // `Ok(res) => res?`, which looked like two failure paths and was one:
3121 // the actor's `Result` could not be `Err` (W7.3, D-177). What remains is
3122 // the branch that can fire — the actor panicked or was aborted — mapped
3123 // by `writer_exit`, which is tested against a real `JoinError`.
3124 //
3125 // Ordered before the final snapshot on purpose: a snapshot written after
3126 // a dead writer records a state the caller has no reason to trust, and
3127 // returning the error while also having written that file is worse than
3128 // not writing it.
3129 if let Some(handle) = self.writer.take() {
3130 writer_exit(handle.await)?;
3131 }
3132
3133 let ts = self.clock.now();
3134 let archive = self
3135 .archive_path
3136 .exists()
3137 .then_some(self.archive_path.as_path());
3138 snapshot::write_final(&self.read_conn, &self.snapshots_dir, &ts, archive).await?;
3139
3140 // Marks the handle closed so `Drop` knows not to complain.
3141 self.closed = true;
3142 Ok(())
3143 }
3144}
3145
3146/// Notes a missed `close()` at `warn!`, and deliberately does **not** assert.
3147///
3148/// **§7.3 offered option B — document `close()` as mandatory and `debug_assert`
3149/// in `Drop` — and Wave 4.2 implemented it, measured the consequence, and
3150/// reduced it to a warning.** The assert fired on roughly thirty tests on its
3151/// first run. That is the signal it was built to produce, and the right reading
3152/// of it was not "thirty tests are wrong".
3153///
3154/// What dropping actually costs is one final snapshot. Nothing else: every
3155/// public write method awaits its responder, so by the time a caller *can* drop
3156/// the handle, every write it issued has already committed; and the cadence stops
3157/// on its own, because `cadence_stop` is a `watch::Sender` whose drop signals the
3158/// task. A snapshot is derivative state under Doctrine VI — disposable,
3159/// reconstructible, and never the only copy of anything. Losing one makes the
3160/// next `reconstruct` fold from an older anchor, which is **slower, not wrong**.
3161///
3162/// A `debug_assert` aborts a test run. Spending that on a performance loss, in a
3163/// project whose own notes say a suite that fails for reasons unrelated to the
3164/// code under test trains people to ignore red, is the wrong trade — and paying
3165/// it in thirty places would have made `close()` look mandatory by ceremony
3166/// rather than by consequence. `close()` remains the right thing to call, and
3167/// the two reasons to call it are now stated where they can be acted on: the
3168/// snapshot, and the writer's `Result`, which only `close()` can return.
3169///
3170/// Option A ("abort the actor and log") stays rejected, for the reason it was
3171/// rejected twice before: `Drop` cannot await, so it cannot drain, and cleanup
3172/// that cannot clean up is worse than none — it looks like cleanup.
3173impl Drop for Database {
3174 fn drop(&mut self) {
3175 if !self.closed {
3176 tracing::warn!(
3177 "Database dropped without close(): the final snapshot was not written, \
3178 so the next reconstruct folds from an older anchor, and the write \
3179 actor's exit status was not checked. Prefer close().await."
3180 );
3181 }
3182 }
3183}
3184
3185/// A failure before the first chunk was sent, which committed nothing.
3186///
3187/// Normalisation runs over the whole batch up front, so its errors are the one
3188/// class the chunk loop never sees — and they are still [`BulkInterrupted`],
3189/// because a caller matching on one error type should not have to match on two
3190/// to find out that nothing landed (0.13.8, W7.6).
3191fn before_any_chunk(cause: DbError) -> BulkInterrupted {
3192 BulkInterrupted { written: 0, cause }
3193}
3194
3195fn normalize_all(edges: Vec<EdgeAssertion>) -> Result<Vec<EdgeAssertion>> {
3196 edges.into_iter().map(EdgeAssertion::normalized).collect()
3197}
3198
3199/// One `FULL` checkpoint for the numbers, then a `TRUNCATE` for the file.
3200///
3201/// # Why `TRUNCATE` and not a mode parameter
3202///
3203/// The four SQLite modes are not four things a caller of *this* crate wants.
3204/// `PASSIVE` is what the automatic checkpointer already runs on its own, so an
3205/// explicit `PASSIVE` asks for something that was going to happen anyway;
3206/// `RESTART` and `FULL` differ from `TRUNCATE` only in whether the WAL file is
3207/// left at its high-water size. The reason W5.2 exists is
3208/// [`Tuning::wal_autocheckpoint`] — a bulk importer turns the automatic
3209/// checkpointer off and calls this once at the end — and what that caller wants
3210/// is the WAL *gone*, not smaller than it was. So the mode is fixed and decided
3211/// here rather than pushed to the caller as a choice they would have to read
3212/// SQLite's documentation to make. If a mode ever needs selecting, that is an
3213/// additive method, not a change to this one.
3214///
3215/// # Why it is two pragmas, which is not the obvious implementation
3216///
3217/// **A successful `TRUNCATE` reports `busy=0, log=0, checkpointed=0`** — the
3218/// counts describe the WAL *after* the operation, and after a truncation there
3219/// is no WAL to describe. Measured, not inferred: on a 387-frame WAL, `PASSIVE`
3220/// returns `0, 387, 387` and `TRUNCATE` on the same file returns `0, 0, 0`. So
3221/// the single-pragma implementation returns a [`CheckpointReport`] whose two
3222/// counts are structurally zero on success, which makes the whole struct a
3223/// less useful `bool`.
3224///
3225/// `FULL` copies every frame back and reports what it moved; the `TRUNCATE`
3226/// that follows finds nothing left to copy and resets the file. The second pass
3227/// is close to free for exactly that reason — it is a file operation, not a
3228/// second copy. `busy` is the **union**: a checkpoint that was blocked in
3229/// either phase did not fully happen, and a caller about to copy the database
3230/// file elsewhere needs the pessimistic answer.
3231///
3232/// # They return rows, so they go through `query()`
3233///
3234/// The same libsql constraint the pragmas in `configure` document: `execute()`
3235/// rejects any statement that yields rows, and these yield the row that is the
3236/// entire point.
3237async fn run_checkpoint(conn: &libsql::Connection) -> Result<CheckpointReport> {
3238 // The columns are `busy, log, checkpointed`. SQLite reports -1 for the two
3239 // counts when the checkpoint could not run; clamped to 0 rather than
3240 // surfaced as a signed count, because `busy` already carries "this did not
3241 // happen" and a negative frame count is not a quantity anyone can use.
3242 //
3243 // A database not in WAL mode returns no row at all. `configure` puts every
3244 // connection this crate opens into WAL, so that is unreachable here — but a
3245 // zeroed report is a better failure than a panic if it stops being.
3246 async fn one(conn: &libsql::Connection, sql: &str) -> Result<(bool, u64, u64)> {
3247 let mut rows = conn.query(sql, ()).await?;
3248 let Some(row) = rows.next().await? else {
3249 return Ok((false, 0, 0));
3250 };
3251 let field = |i: i32| -> u64 { row.get::<i64>(i).unwrap_or(0).max(0) as u64 };
3252 Ok((row.get::<i64>(0).unwrap_or(0) != 0, field(1), field(2)))
3253 }
3254
3255 let (full_busy, _, moved) = one(conn, "PRAGMA wal_checkpoint(FULL)").await?;
3256 let (trunc_busy, log_frames, _) = one(conn, "PRAGMA wal_checkpoint(TRUNCATE)").await?;
3257
3258 Ok(CheckpointReport {
3259 busy: full_busy || trunc_busy,
3260 log_frames,
3261 checkpointed_frames: moved,
3262 })
3263}
3264
3265/// Pragmas that mean something on **any** connection, including one opened
3266/// `SQLITE_OPEN_READ_ONLY` (0.12.16, W5.5, D-159).
3267///
3268/// Both of these are per-connection state that a reader is subject to just as a
3269/// writer is. `busy_timeout` is the one that made this a finding:
3270/// [`Database::diagnostic_conn`] ran with SQLite's default of **0** — return
3271/// `SQLITE_BUSY` immediately — while every other connection in the process
3272/// waited 5 s, so the one surface whose job is to answer questions when the
3273/// typed path is already suspect was also the one most likely to fail with
3274/// "database is locked" under exactly the contention that prompted the
3275/// question.
3276async fn configure_common(conn: &libsql::Connection, cache_size: Option<i32>) -> Result<()> {
3277 // NOTE: `busy_timeout` returns its resulting value as a row, and libsql's
3278 // `execute()` rejects any statement that yields rows ("Execute returned
3279 // rows"). It must be issued through `query()`.
3280 let _ = conn.query("PRAGMA busy_timeout = 5000", ()).await?;
3281 // Per-connection, and split writer from reader since 0.12.15 (W5.4,
3282 // D-158). `None` runs no pragma at all rather than restating SQLite's
3283 // default, so the default remains SQLite's to change.
3284 if let Some(pages) = cache_size {
3285 conn.execute(&format!("PRAGMA cache_size = {pages}"), ())
3286 .await?;
3287 }
3288 Ok(())
3289}
3290
3291/// Pragmas that only mean anything where writes can happen (0.12.16, W5.5).
3292///
3293/// Not run on [`Database::diagnostic_conn`], and the reason is not tidiness:
3294/// `journal_mode = WAL` is a change to the *database file*, which a connection
3295/// opened `SQLITE_OPEN_READ_ONLY` cannot make. The rest —
3296/// `synchronous`, `foreign_keys`, `recursive_triggers`, and the `ANALYZE`
3297/// bound — govern how writes behave, and a connection that cannot write is not
3298/// governed by them.
3299///
3300/// The write connection and the two internal readers all still get these. The
3301/// internal readers are opened from the same read-write `libsql::Database`, so
3302/// the pragmas apply; leaving them out would be a behaviour change made for
3303/// symmetry, which is not a reason.
3304async fn configure_writable(conn: &libsql::Connection) -> Result<()> {
3305 // Returns its resulting value as a row — see the note in `configure_common`.
3306 let _ = conn.query("PRAGMA journal_mode = WAL", ()).await?;
3307 conn.execute("PRAGMA synchronous = NORMAL", ()).await?;
3308 conn.execute("PRAGMA foreign_keys = ON", ()).await?;
3309 conn.execute("PRAGMA recursive_triggers = OFF", ()).await?;
3310 // Bounds every `ANALYZE` this connection will ever run, explicit or
3311 // triggered by `PRAGMA optimize` (D-149). Set here rather than around the
3312 // call sites so the scheduled path is bounded too — that is the half that
3313 // runs with nobody watching. Returns the previous limit as a row, so it goes
3314 // through `query()` for the reason the note above gives.
3315 let _ = conn.query(crate::schema::ddl::ANALYSIS_LIMIT, ()).await?;
3316 Ok(())
3317}
3318
3319/// Full pragma configuration, for a connection that can write.
3320async fn configure(
3321 conn: libsql::Connection,
3322 cache_size: Option<i32>,
3323) -> Result<libsql::Connection> {
3324 configure_writable(&conn).await?;
3325 configure_common(&conn, cache_size).await?;
3326 Ok(conn)
3327}
3328
3329/// Helper to derive the snapshot directory by convention: foo.db -> foo_snapshots/
3330fn derive_snapshots_dir(path: &Path) -> PathBuf {
3331 let mut dir = path.to_path_buf();
3332 let stem = path
3333 .file_stem()
3334 .and_then(|s| s.to_str())
3335 .unwrap_or("macrame");
3336 dir.set_file_name(format!("{stem}_snapshots"));
3337 dir
3338}
3339
3340/// Helper to derive archive database path by convention: foo.db -> foo_archive.db
3341fn derive_archive_path(path: &Path) -> PathBuf {
3342 let mut archive = path.to_path_buf();
3343 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
3344 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("db");
3345 archive.set_file_name(format!("{stem}_archive.{ext}"));
3346 } else {
3347 archive.set_extension("archive.db");
3348 }
3349 archive
3350}
3351
3352/// Dedicated Write Actor event loop prioritizing high-priority UI requests over low-priority background work.
3353///
3354/// # The turn is the unit, not the statement (T1.4)
3355///
3356/// One iteration of this loop is one *hold*: the actor is single-threaded and
3357/// the SQLite write lock is not preemptible, so from the moment a command starts
3358/// executing until it returns, nothing else writes. That is the quantity
3359/// [`CHUNK_BUDGET`] bounds, and so it is the quantity
3360/// [`crate::metrics::ActorMetrics`] measures — deliberately around the whole
3361/// `execute` call rather than inside it. Timing the SQL alone would have
3362/// reported a bound that held while callers waited.
3363///
3364/// Queue depth is sampled *before* the `select!`, so it is the backlog the turn
3365/// found on arrival rather than the one it left behind.
3366///
3367/// # `biased` has no floor, and since 0.12.10 that is measured (W4.4, D-153)
3368///
3369/// `biased` makes the arms poll in declaration order, so high-priority work is
3370/// taken whenever any is ready. Nothing bounds how long that can continue:
3371/// sustained interactive traffic can hold the low tier off indefinitely, and
3372/// through 0.12.9 nothing in the crate could say whether it ever did.
3373/// `record_priority_choice` counts the turns where the choice went against
3374/// queued low-priority work, and the longest unbroken run of them, which is the
3375/// half that distinguishes "prioritised" from "starved".
3376///
3377/// **No forced yield is added here.** Whether one is needed is the question the
3378/// counter answers, and adding a policy now would be fixing a bound nobody has
3379/// observed being hit — the same mistake D-124 was retracted for.
3380///
3381/// # It returns nothing, and used to return a `Result` it could not fail
3382/// (0.13.4, W7.3, §3.5, [D-177])
3383///
3384/// The two exits are `LoopCtl::Break` from [`HighPriCommand::Shutdown`] and the
3385/// `else` arm when both channels are closed. Neither can fail, and neither
3386/// could before: every command's error goes back on that command's own
3387/// responder, where the caller who issued it can act on it. There was no third
3388/// thing for an actor-level `Err` to carry, and none was ever constructed.
3389///
3390/// A `Result` that is structurally always `Ok` is not free. It reads as a
3391/// failure path under review, so `close()`'s `res?` looked like it was doing
3392/// something, and the branch that actually fires — a **panicked** actor,
3393/// reported as a `JoinError` — sat beside it untested. That is the swap this
3394/// change makes: the unfireable branch is gone and the real one is pinned, in
3395/// [`writer_exit`].
3396async fn run_writer_actor(
3397 conn: libsql::Connection,
3398 clock: Arc<dyn Clock>,
3399 mut highpri_rx: mpsc::Receiver<HighPriCommand>,
3400 mut lowpri_rx: mpsc::Receiver<LowPriCommand>,
3401 shared: Arc<ActorShared>,
3402) {
3403 loop {
3404 // Read once and reused by both the depth sample and the starvation
3405 // counter, so the two cannot disagree about what was queued when this
3406 // turn went looking (W4.4, D-153).
3407 let low_queued = lowpri_rx.len();
3408 shared.metrics.record_turn(highpri_rx.len(), low_queued);
3409
3410 let ctl = tokio::select! {
3411 biased;
3412 Some(cmd) = highpri_rx.recv() => {
3413 shared.metrics.record_priority_choice(true, low_queued);
3414 let turn = Turn::start(cmd.kind(), &shared);
3415 cmd.execute(&conn, &*clock, &turn).await
3416 }
3417 Some(cmd) = lowpri_rx.recv() => {
3418 shared.metrics.record_priority_choice(false, low_queued);
3419 let turn = Turn::start(cmd.kind(), &shared);
3420 cmd.execute(&conn, &*clock, &turn).await
3421 }
3422 else => LoopCtl::Break,
3423 };
3424 if matches!(ctl, LoopCtl::Break) {
3425 break;
3426 }
3427 }
3428}
3429
3430/// Turn the write actor's join status into the error `close()` reports.
3431///
3432/// One line of mapping, given a name so it can be tested against a real
3433/// [`tokio::task::JoinError`]. Before 0.13.4 this was inline beside a `res?` on
3434/// an actor `Result` that could only ever be `Ok`, and the arrangement had the
3435/// coverage exactly backwards: the branch that cannot fire was plumbed through
3436/// two signatures, and the branch that does fire — the actor panicked, and the
3437/// caller's writes are going nowhere — had no test at all (W7.3, D-177).
3438///
3439/// Cancellation is folded in with panics deliberately. `JoinError` distinguishes
3440/// them, and nothing in the crate ever aborts this task, so a cancelled writer
3441/// means something outside the crate reached in and stopped it. That is not a
3442/// gentler condition than a panic and must not read as one.
3443fn writer_exit(joined: std::result::Result<(), tokio::task::JoinError>) -> Result<()> {
3444 joined.map_err(|e| DbError::WriterStopped(format!("the write actor did not exit cleanly: {e}")))
3445}
3446
3447/// One command's hold: the timer, its label, and the counters it reports to.
3448///
3449/// # The hold is recorded *before* the caller is answered, and it has to be
3450///
3451/// The obvious placement — time the whole `execute` call from the loop — is
3452/// wrong in a way that only shows up under test. Every arm of `execute` ends by
3453/// sending on a `oneshot`, which wakes the waiting caller; the actor then
3454/// returns to the loop and records. Those are two tasks, so a caller that awaits
3455/// its own write and immediately reads [`Database::metrics`] can be scheduled
3456/// first and see a turn count that does not include the write it just did.
3457///
3458/// Not a correctness bug in the ledger, and it would never have been noticed in
3459/// production — a dashboard sampling every few seconds cannot see the window.
3460/// It makes every test and diagnostic of the counters flaky, which is worse: the
3461/// instrumentation would have been *believed* while being wrong exactly when
3462/// someone tried to check it. `examples/bulk_atomic_diag.rs` was the thing that
3463/// caught it, reporting a 20,000-row batch as a 0 ms hold.
3464///
3465/// So `answer` records and then sends, in that order, and the ordering is the
3466/// method's whole reason to exist. What it costs is that the `oneshot::send`
3467/// itself falls outside the measurement, which is a few nanoseconds against a
3468/// turn measured in microseconds at best.
3469struct Turn<'a> {
3470 kind: crate::metrics::CommandKind,
3471 timer: crate::metrics::HoldTimer,
3472 shared: &'a ActorShared,
3473}
3474
3475/// State the actor owns and a `Turn` needs to reach.
3476///
3477/// `archive_epoch` is here rather than in [`crate::metrics::ActorMetrics`]
3478/// because it is **not** a metric: T1.2's shadow rebuild reads it to decide
3479/// whether its work is still valid, so it has to be present in every build, not
3480/// only under the `metrics` feature. Counting archives happens to be what both
3481/// want; only one of them is allowed to be compiled out.
3482#[derive(Default)]
3483struct ActorShared {
3484 metrics: crate::metrics::ActorMetrics,
3485 archive_epoch: std::sync::atomic::AtomicU64,
3486}
3487
3488impl<'a> Turn<'a> {
3489 fn start(kind: crate::metrics::CommandKind, shared: &'a ActorShared) -> Self {
3490 Self {
3491 kind,
3492 timer: crate::metrics::HoldTimer::start(),
3493 shared,
3494 }
3495 }
3496
3497 fn epoch(&self) -> u64 {
3498 self.shared
3499 .archive_epoch
3500 .load(std::sync::atomic::Ordering::Relaxed)
3501 }
3502
3503 /// Record that an archive session committed.
3504 ///
3505 /// Bumped on **success only**: a failed archive rolls back, so it deletes
3506 /// nothing and invalidates no shadow build.
3507 fn archive_committed(&self) {
3508 self.shared
3509 .archive_epoch
3510 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3511 }
3512
3513 /// Close the hold and hand the result back. Never the other way round.
3514 ///
3515 /// The `let _ =` on the send is deliberate and predates this: a caller that
3516 /// dropped its receiver — `tokio::time::timeout` around a write, which
3517 /// [`Database`]'s write surface explicitly documents — is not an actor
3518 /// error, and the command committed regardless.
3519 fn answer<T>(&self, responder: oneshot::Sender<Result<T>>, res: Result<T>) {
3520 self.shared
3521 .metrics
3522 .record_hold(self.kind, self.timer.elapsed());
3523 let _ = responder.send(res);
3524 }
3525
3526 /// [`answer`](Self::answer) for a chunk: the same reading, handed back to the
3527 /// caller as well as recorded (0.12.0, W1).
3528 ///
3529 /// One `elapsed()` serves both, so the duration the chunk loop sizes against
3530 /// is *the same number* the histogram shows — a controller and a dashboard
3531 /// disagreeing about what a chunk cost would be a bad way to spend a
3532 /// debugging session.
3533 ///
3534 /// The record-then-send ordering documented on [`Turn`] is preserved, and
3535 /// matters here for the same reason: the send wakes the caller, which may be
3536 /// scheduled before this method returns.
3537 fn answer_chunk(&self, responder: oneshot::Sender<Result<ChunkOutcome>>, res: Result<usize>) {
3538 let held = self.timer.elapsed();
3539 self.shared.metrics.record_hold(self.kind, held);
3540 let _ = responder.send(res.map(|rows| ChunkOutcome { rows, held }));
3541 }
3542}
3543
3544const INSERT_LINK: &str = "INSERT INTO links \
3545 (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, \
3546 recorded_at, branch_id) \
3547 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)";
3548
3549/// The parameter row for [`INSERT_LINK`], in one place since 0.14.8.
3550///
3551/// The single-edge path and the chunk path spelled these out separately, which
3552/// was survivable at eight and is not at nine: `branch_id` is the one parameter
3553/// whose omission is *silent* — the column defaults to `'main'`, so a path that
3554/// forgot it would write to the trunk and pass every test that did not fork.
3555/// [`concept_params`] has existed for this reason since D-056.
3556fn edge_params<'a>(edge: &'a EdgeAssertion, stamp: &'a str) -> [libsql::Value; 9] {
3557 [
3558 edge.source.as_str().into(),
3559 edge.target.as_str().into(),
3560 edge.edge_type.as_str().into(),
3561 edge.valid_from.as_str().into(),
3562 edge.valid_to.as_str().into(),
3563 edge.weight.into(),
3564 edge.properties.as_str().into(),
3565 stamp.into(),
3566 edge.branch_name().into(),
3567 ]
3568}
3569
3570/// Shared by the single-concept write and the chunked one, so the two paths
3571/// cannot drift into upserting different column sets — and so the chunk has a
3572/// statement text it can prepare once (D-056).
3573const UPSERT_CONCEPT: &str = "INSERT INTO concepts \
3574 (id, title, content, embedding_model, valid_from, valid_to, recorded_at, retired, \
3575 branch_id) \
3576 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) \
3577 ON CONFLICT(id) DO UPDATE SET \
3578 title = excluded.title, \
3579 content = excluded.content, \
3580 embedding_model = excluded.embedding_model, \
3581 valid_from = excluded.valid_from, \
3582 valid_to = excluded.valid_to, \
3583 recorded_at = excluded.recorded_at, \
3584 retired = excluded.retired";
3585// `branch_id` is deliberately **not** in that `DO UPDATE` list. The column is
3586// provenance and minting happened once (D-214), and
3587// `trg_concepts_branch_immutable` would abort an update that moved it — so
3588// listing it would turn every re-upsert of an inherited concept into a guard
3589// abort instead of the no-op it is. The insert arm carries it; the update arm
3590// leaves the row where it was minted.
3591
3592/// The parameter row for [`UPSERT_CONCEPT`], in one place for the same reason.
3593fn concept_params<'a>(concept: &'a ConceptUpsert, stamp: &'a str) -> [libsql::Value; 9] {
3594 [
3595 concept.id.as_str().into(),
3596 concept.title.as_str().into(),
3597 concept.content.as_str().into(),
3598 concept
3599 .embedding_model
3600 .as_deref()
3601 .map_or(libsql::Value::Null, Into::into),
3602 concept.valid_from.as_str().into(),
3603 concept.valid_to.as_str().into(),
3604 stamp.into(),
3605 (concept.retired as i64).into(),
3606 concept.branch_name().into(),
3607 ]
3608}
3609
3610/// Check every lineage a write names, and decide which shape its guard takes.
3611///
3612/// **One function, two answers, one query per distinct lineage** — and it is
3613/// [`lineage_shape`](crate::graph::lineage::lineage_shape), the same function
3614/// the read path calls, for the same reason it calls it. A write naming a
3615/// branch that is not in `branches` has asked about something that does not
3616/// exist, and answering it by writing to the trunk is [D-069]'s failure in its
3617/// most expensive form: not a right-looking answer to a question that was not
3618/// asked, but a *durable* one.
3619///
3620/// Relying on the foreign key instead would refuse the write — `branch_id`
3621/// `REFERENCES branches(branch_id)` and the key is enforced — but it would
3622/// refuse it as an unqualified "FOREIGN KEY constraint failed" from inside a
3623/// rolled-back transaction, naming neither the column nor the branch. The same
3624/// argument [`classify`](crate::error::classify) makes for annotations and
3625/// edges, one table further along.
3626///
3627/// # The shape is global, so the last answer is every answer
3628///
3629/// [`LineageShape`] is decided by how many rows `branches` holds, which does not
3630/// vary by which branch was asked about. The loop exists for the **existence**
3631/// check; that it also returns a shape is why there is no second query. A batch
3632/// naming one lineage — every batch this crate has written so far — costs
3633/// exactly one round trip on a table with no secondary indices.
3634///
3635/// # Why a trunk write pays for it too
3636///
3637/// `None` resolves to `'main'` here rather than skipping the query, and that is
3638/// not tidiness. Once a second lineage can write, the *trunk's* overlap guard
3639/// is wrong in the other direction — it would be refused for overlapping a
3640/// branch's belief it cannot see — so the shape decision is one every write
3641/// needs, not one that branched writes need. On a database that has never
3642/// forked the answer is [`LineageShape::Trunk`] and the guard is the statement
3643/// it has always been.
3644///
3645/// [D-069]: ../../docs/architecture/s13-decision-register.md
3646async fn check_lineages(conn: &libsql::Connection, names: &[&str]) -> Result<LineageShape> {
3647 let mut shape = LineageShape::Trunk;
3648 for name in names {
3649 shape = crate::graph::lineage::lineage_shape(conn, Some(name)).await?;
3650 }
3651 Ok(shape)
3652}
3653
3654/// The distinct lineages a batch names, in first-seen order.
3655///
3656/// A `Vec` and a linear scan rather than a set: batches name one lineage in
3657/// every case this crate has, the bound is the number of *branches* and not the
3658/// number of rows, and a `BTreeSet` would allocate per batch to deduplicate a
3659/// list of length one.
3660fn distinct_branches(edges: &[EdgeAssertion]) -> Vec<&str> {
3661 let mut out: Vec<&str> = Vec::with_capacity(1);
3662 for edge in edges {
3663 let name = edge.branch_name();
3664 if !out.contains(&name) {
3665 out.push(name);
3666 }
3667 }
3668 if out.is_empty() {
3669 out.push(crate::schema::ddl::MAIN_BRANCH);
3670 }
3671 out
3672}
3673
3674/// The overlap guard's prepared statement, and which question it asks.
3675///
3676/// The two statements take different parameter counts and mean different things
3677/// by the rows they return, so pairing them with the shape here is what stops
3678/// [`check_prepared`] from having to be told twice.
3679struct OverlapGuard {
3680 stmt: libsql::Statement,
3681 shape: LineageShape,
3682}
3683
3684impl OverlapGuard {
3685 /// Prepare once per turn or per chunk, never per row (D-056, §8.8).
3686 async fn prepare(conn: &libsql::Connection, shape: LineageShape) -> Result<Self> {
3687 let sql = match shape {
3688 LineageShape::Trunk => std::borrow::Cow::Borrowed(OVERLAP_CANDIDATES),
3689 LineageShape::Resolved => {
3690 std::borrow::Cow::Owned(crate::graph::lineage::overlap_candidates_resolved())
3691 }
3692 };
3693 Ok(Self {
3694 stmt: conn.prepare(&sql).await?,
3695 shape,
3696 })
3697 }
3698}
3699
3700impl HighPriCommand {
3701 /// The metrics label for this variant (T1.4).
3702 ///
3703 /// Exhaustive for the same reason `execute` is: a new variant that silently
3704 /// borrowed another's label would attribute its holds to the wrong command,
3705 /// and the one question the counters exist to answer is *which* command
3706 /// broke the budget.
3707 fn kind(&self) -> crate::metrics::CommandKind {
3708 use crate::metrics::CommandKind as K;
3709 match self {
3710 HighPriCommand::AssertEdge { .. } => K::AssertEdge,
3711 HighPriCommand::RetireEdge { .. } => K::RetireEdge,
3712 HighPriCommand::UpsertConcept { .. } => K::UpsertConcept,
3713 HighPriCommand::WriteBulkAtomic { .. } => K::WriteBulkAtomic,
3714 HighPriCommand::RebuildCurrent { .. } => K::RebuildCurrent,
3715 HighPriCommand::RegisterModel { .. } => K::RegisterModel,
3716 HighPriCommand::Fork { .. } => K::Fork,
3717 HighPriCommand::Checkpoint { .. } => K::Checkpoint,
3718 HighPriCommand::Shutdown { .. } => K::Shutdown,
3719 }
3720 }
3721
3722 /// Run one command and answer its caller.
3723 ///
3724 /// Deliberately exhaustive — there is no `_` arm. The 0.4.5–0.5.4 actor
3725 /// matched `Shutdown` and `AssertEdge` and sent everything else to
3726 /// `_ => LoopCtl::Continue`, which **dropped the responder**: the caller's
3727 /// `rx.await` resolved to a `RecvError` that no code mapped, so four of six
3728 /// commands were indistinguishable from a hung database. An exhaustive match
3729 /// makes that failure a compile error instead of a runtime silence, which is
3730 /// why adding a variant should break this function.
3731 async fn execute(
3732 self,
3733 conn: &libsql::Connection,
3734 clock: &dyn Clock,
3735 turn: &Turn<'_>,
3736 ) -> LoopCtl {
3737 match self {
3738 HighPriCommand::Shutdown { responder } => {
3739 turn.answer(responder, Ok(()));
3740 return LoopCtl::Break;
3741 }
3742 HighPriCommand::Checkpoint { responder } => {
3743 let res = run_checkpoint(conn).await;
3744 turn.answer(responder, res);
3745 }
3746 HighPriCommand::AssertEdge { edge, responder } => {
3747 let stamp = clock.now();
3748 // Before the guard, because a write naming an unregistered
3749 // lineage should be refused by name rather than by whatever the
3750 // guard happens to find when it looks in the wrong place.
3751 let shape = match check_lineages(conn, &[edge.branch_name()]).await {
3752 Ok(shape) => shape,
3753 Err(e) => {
3754 turn.answer(responder, Err(e));
3755 return LoopCtl::Continue;
3756 }
3757 };
3758 if let Err(e) = reject_overlapping_interval(conn, &edge, shape).await {
3759 turn.answer(responder, Err(e));
3760 return LoopCtl::Continue;
3761 }
3762 let res = match conn.execute(INSERT_LINK, edge_params(&edge, &stamp)).await {
3763 Ok(_) => Ok(()),
3764 Err(e) => Err(classify(
3765 conn,
3766 e,
3767 WriteOp::Edge {
3768 source_id: &edge.source,
3769 target_id: &edge.target,
3770 edge_type: &edge.edge_type,
3771 },
3772 )
3773 .await),
3774 };
3775 turn.answer(responder, res);
3776 }
3777 HighPriCommand::RetireEdge {
3778 source,
3779 target,
3780 edge_type,
3781 valid_from,
3782 valid_to,
3783 branch,
3784 responder,
3785 } => {
3786 let stamp = clock.now();
3787 let name = branch
3788 .as_ref()
3789 .map_or(crate::schema::ddl::MAIN_BRANCH, |b| b.as_str());
3790 let res = match check_lineages(conn, &[name]).await {
3791 Ok(shape) => {
3792 retire_edge(
3793 conn,
3794 &source,
3795 &target,
3796 &edge_type,
3797 &valid_from,
3798 &valid_to,
3799 &stamp,
3800 name,
3801 shape,
3802 )
3803 .await
3804 }
3805 Err(e) => Err(e),
3806 };
3807 turn.answer(responder, res);
3808 }
3809 HighPriCommand::UpsertConcept { concept, responder } => {
3810 let stamp = clock.now();
3811 let res = match check_lineages(conn, &[concept.branch_name()]).await {
3812 Ok(_) => upsert_concept(conn, &concept, &stamp).await,
3813 Err(e) => Err(e),
3814 };
3815 turn.answer(responder, res);
3816 }
3817 HighPriCommand::WriteBulkAtomic { edges, responder } => {
3818 // One stamp for the whole batch (D-014): the rows were asserted
3819 // by one act, and giving them different transaction times would
3820 // invent an ordering the caller never expressed.
3821 let stamp = clock.now();
3822 let res = write_edges_atomic(conn, &edges, &stamp).await;
3823 turn.answer(responder, res);
3824 }
3825 HighPriCommand::RebuildCurrent { responder } => {
3826 turn.answer(responder, rebuild_current(conn).await);
3827 }
3828 HighPriCommand::RegisterModel {
3829 model,
3830 dim,
3831 responder,
3832 } => {
3833 turn.answer(
3834 responder,
3835 crate::vector::register_model(conn, &model, dim).await,
3836 );
3837 }
3838 HighPriCommand::Fork {
3839 name,
3840 parent,
3841 responder,
3842 } => {
3843 // The same clock as every other write, and the same instant in
3844 // both columns: `forked_at` is a transaction-time point in the
3845 // parent's history, and the point this release can fork from is
3846 // now. See `branch::Branch::created_at` for why they are two
3847 // columns anyway.
3848 let stamp = clock.now();
3849 let res = crate::branch::fork(conn, &name, &parent, &stamp).await;
3850 turn.answer(responder, res);
3851 }
3852 }
3853 LoopCtl::Continue
3854 }
3855}
3856
3857impl LowPriCommand {
3858 /// The metrics label for this variant (T1.4). See [`HighPriCommand::kind`].
3859 fn kind(&self) -> crate::metrics::CommandKind {
3860 use crate::metrics::CommandKind as K;
3861 match self {
3862 LowPriCommand::WriteConceptsChunk { .. } => K::WriteConceptsChunk,
3863 LowPriCommand::WriteAnalyticsChunk { .. } => K::WriteAnalyticsChunk,
3864 LowPriCommand::UpsertEmbeddingChunk { .. } => K::UpsertEmbeddingChunk,
3865 LowPriCommand::BulkImportChunk { .. } => K::BulkImportChunk,
3866 LowPriCommand::Archive { .. } => K::Archive,
3867 // Its own counter since 0.12.9 (W4.3, D-152). It reported as
3868 // `K::Archive` from 0.9.0 to 0.12.8 — the budget really is shared,
3869 // but attribution is not budget, and an operator reading a long
3870 // `archive` hold could not tell whether anything had been archived.
3871 // What kept it folded was that a `CommandKind` variant was a
3872 // breaking addition; `#[non_exhaustive]` (W4.2) removed that.
3873 LowPriCommand::Rehydrate { .. } => K::Rehydrate,
3874 // Its own counter from the day it shipped, which is the whole point
3875 // of the paragraph above: `Rehydrate` spent four releases folded
3876 // into `Archive` for a reason that was never good, and the cost of
3877 // unfolding it was a rung's worth of care about declaration order.
3878 LowPriCommand::ArchiveBranch { .. } => K::ArchiveBranch,
3879 LowPriCommand::RebuildFts { .. } => K::RebuildFts,
3880 // Two kinds out of one variant since 0.13.24 (W10.5, D-197). The
3881 // command carries the flag; the counter has to carry it too, or the
3882 // budget exemption for either half is decided about both (D-168).
3883 LowPriCommand::Analyze { incremental, .. } => {
3884 if *incremental {
3885 K::Optimize
3886 } else {
3887 K::Analyze
3888 }
3889 }
3890 // Two kinds out of one variant since 0.14.16 (W12.16, D-233),
3891 // and for D-197's reason one line up: the command carries the step,
3892 // so the counter has to carry it too, or the budget exemption for
3893 // either half is decided about both. Here that is not hypothetical
3894 // — the halves want opposite answers. The swap is over budget by
3895 // construction and the fill chunks are meant to fit, so a merged
3896 // kind's `over_budget` read `N(rebuilds) + regressions` and could
3897 // not be decomposed.
3898 LowPriCommand::ShadowRebuild { step, .. } => match step {
3899 crate::integrity::ShadowStep::Swap { .. } => K::ShadowSwap,
3900 crate::integrity::ShadowStep::Begin | crate::integrity::ShadowStep::Fill { .. } => {
3901 K::ShadowRebuild
3902 }
3903 },
3904 }
3905 }
3906
3907 /// Run one background command and answer its caller.
3908 ///
3909 /// Also exhaustive. The pre-0.5.4 version was a single `LoopCtl::Continue`
3910 /// for *every* variant — every background write silently discarded, its
3911 /// caller waiting forever.
3912 async fn execute(
3913 self,
3914 conn: &libsql::Connection,
3915 clock: &dyn Clock,
3916 turn: &Turn<'_>,
3917 ) -> LoopCtl {
3918 match self {
3919 LowPriCommand::BulkImportChunk { chunk, responder } => {
3920 // A stamp per chunk, not per batch: the chunks commit
3921 // separately, so a shared stamp would claim a simultaneity the
3922 // storage does not have.
3923 let stamp = clock.now();
3924 turn.answer_chunk(responder, write_edges_atomic(conn, &chunk, &stamp).await);
3925 }
3926 LowPriCommand::WriteConceptsChunk { chunk, responder } => {
3927 let stamp = clock.now();
3928 turn.answer_chunk(responder, write_concepts_atomic(conn, &chunk, &stamp).await);
3929 }
3930 LowPriCommand::WriteAnalyticsChunk { chunk, responder } => {
3931 let stamp = clock.now();
3932 turn.answer_chunk(
3933 responder,
3934 write_annotations_atomic(conn, &chunk, &stamp).await,
3935 );
3936 }
3937 LowPriCommand::UpsertEmbeddingChunk {
3938 model,
3939 chunk,
3940 responder,
3941 } => {
3942 // No clock reading: an embedding carries no timestamp on either
3943 // axis. It is a derived artifact of a model applied to content
3944 // (Doctrine VII), and the ledger already records when the
3945 // content changed.
3946 turn.answer_chunk(
3947 responder,
3948 crate::vector::search::upsert_embedding_chunk(conn, &model, &chunk).await,
3949 );
3950 }
3951 LowPriCommand::Archive {
3952 cutoff,
3953 archive_path,
3954 responder,
3955 } => {
3956 // The archive *time*, not the cutoff. `archive_horizon` records
3957 // both and they are different facts — see `archive()` (Wave 4.5).
3958 let archived_at = clock.now();
3959 let res = archive(conn, &cutoff, &archived_at, &archive_path).await;
3960 // Before the answer, so a shadow rebuild that reads the epoch on
3961 // its next turn cannot miss an archive that has already deleted
3962 // rows out from under it (T1.2).
3963 if res.is_ok() {
3964 turn.archive_committed();
3965 }
3966 turn.answer(responder, res);
3967 }
3968 LowPriCommand::ArchiveBranch {
3969 branch,
3970 archive_path,
3971 responder,
3972 } => {
3973 // The wall clock, recorded in `cold.branches.archived_at`: when
3974 // the ledger stopped knowing about the lineage. Not a ledger
3975 // fact and not on either of Doctrine II's timelines — nothing
3976 // was asserted or retired here.
3977 let archived_at = clock.now();
3978 let res = crate::temporal::archive::archive_branch(
3979 conn,
3980 &branch,
3981 &archived_at,
3982 &archive_path,
3983 )
3984 .await;
3985 // `Archive`'s reason exactly: a shadow rebuild reading the epoch
3986 // on its next turn must not miss a session that has already
3987 // deleted rows out from under it (T1.2).
3988 if res.is_ok() {
3989 turn.archive_committed();
3990 }
3991 turn.answer(responder, res);
3992 }
3993 LowPriCommand::Rehydrate {
3994 ids,
3995 archive_path,
3996 responder,
3997 } => {
3998 let refs: Vec<&str> = ids.iter().map(String::as_str).collect();
3999 let res = rehydrate(conn, &refs, &archive_path).await;
4000 // Same reason as `Archive`: rehydration moves rows into `links`'
4001 // parent table, so a shadow rebuild in flight must see the epoch
4002 // move before the caller is answered (T1.2).
4003 if res.is_ok() {
4004 turn.archive_committed();
4005 }
4006 turn.answer(responder, res);
4007 }
4008 LowPriCommand::ShadowRebuild { step, responder } => {
4009 use crate::integrity::{shadow, ShadowOutcome, ShadowStep};
4010 let res = match step {
4011 ShadowStep::Begin => {
4012 shadow::begin(conn)
4013 .await
4014 .map(|build_start| ShadowOutcome::Started {
4015 build_start,
4016 epoch: turn.epoch(),
4017 })
4018 }
4019 ShadowStep::Fill { after } => shadow::fill_chunk(conn, after.as_deref())
4020 .await
4021 .map(|last| ShadowOutcome::Filled { last }),
4022 ShadowStep::Swap { build_start, epoch } => {
4023 shadow::swap(conn, &build_start, epoch, turn.epoch())
4024 .await
4025 .map(|rows| ShadowOutcome::Swapped { rows })
4026 }
4027 };
4028 turn.answer(responder, res);
4029 }
4030 LowPriCommand::RebuildFts { responder } => {
4031 let res = conn
4032 .execute(crate::schema::ddl::REBUILD_CONCEPTS_FTS, ())
4033 .await
4034 .map(|_| ())
4035 .map_err(Into::into);
4036 turn.answer(responder, res);
4037 }
4038 LowPriCommand::Analyze {
4039 incremental,
4040 responder,
4041 } => {
4042 // Both go through `query()`, not `execute()`. `PRAGMA optimize`
4043 // yields rows, and libsql's `execute()` rejects any statement
4044 // that does ("Execute returned rows") — the same trap
4045 // `configure` documents. `ANALYZE` does not yield rows, but is
4046 // issued the same way so the two arms cannot drift into needing
4047 // different call shapes for no visible reason.
4048 let sql = if incremental {
4049 crate::schema::ddl::OPTIMIZE
4050 } else {
4051 crate::schema::ddl::ANALYZE
4052 };
4053 let res = conn.query(sql, ()).await.map(|_| ()).map_err(Into::into);
4054 turn.answer(responder, res);
4055 }
4056 }
4057 LoopCtl::Continue
4058 }
4059}
4060
4061/// Close an open interval by asserting its successor (Doctrine III).
4062///
4063/// Never an `UPDATE`. The replacement row copies weight and properties from
4064/// current belief and differs only in `valid_to` and `recorded_at`, so the
4065/// original assertion survives intact and `reconstruct` at an earlier instant
4066/// still sees the interval open — which is the entire point of a bitemporal
4067/// ledger.
4068// The first of these in the crate proper (0.14.8). All nine are the edge key,
4069// two stamps and the lineage — a struct to carry them would exist for one call
4070// site and would put a name between the caller and parameters it already spells
4071// out positionally at the only place it calls this.
4072#[allow(clippy::too_many_arguments)]
4073async fn retire_edge(
4074 conn: &libsql::Connection,
4075 source: &str,
4076 target: &str,
4077 edge_type: &str,
4078 valid_from: &str,
4079 valid_to: &str,
4080 stamp: &str,
4081 branch: &str,
4082 shape: LineageShape,
4083) -> Result<()> {
4084 let affected = match shape {
4085 // One lineage exists, so `links_current` *is* the visible set and the
4086 // statement is the one this path has always issued. Kept rather than
4087 // folded into the resolved form for [`LineageShape`]'s reason: the
4088 // resolved form is opaque to the planner and costs 3.0x where there is
4089 // nothing to resolve (D-220).
4090 LineageShape::Trunk => conn
4091 .execute(
4092 "INSERT INTO links \
4093 (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
4094 SELECT source_id, target_id, edge_type, valid_from, ?5, weight, properties, ?6 \
4095 FROM links_current \
4096 WHERE source_id = ?1 AND target_id = ?2 AND edge_type = ?3 AND valid_from = ?4",
4097 libsql::params![source, target, edge_type, valid_from, valid_to, stamp],
4098 )
4099 .await
4100 .map_err(DbError::Engine)?,
4101 // Shadow retirement: the row being closed may belong to an ancestor,
4102 // and the row written carries *this* lineage's id. See
4103 // `lineage::retire_from_resolved`.
4104 LineageShape::Resolved => conn
4105 .execute(
4106 &crate::graph::lineage::retire_from_resolved(),
4107 libsql::params![
4108 source, target, edge_type, valid_from, branch, valid_to, stamp
4109 ],
4110 )
4111 .await
4112 .map_err(DbError::Engine)?,
4113 };
4114
4115 if affected == 0 {
4116 return Err(DbError::NotFound(format!(
4117 "{source} -> {target} ({edge_type}) at {valid_from}"
4118 )));
4119 }
4120 Ok(())
4121}
4122
4123async fn upsert_concept(
4124 conn: &libsql::Connection,
4125 concept: &ConceptUpsert,
4126 stamp: &str,
4127) -> Result<()> {
4128 let res = conn
4129 .execute(UPSERT_CONCEPT, concept_params(concept, stamp))
4130 .await;
4131
4132 match res {
4133 Ok(_) => Ok(()),
4134 Err(e) => Err(classify(
4135 conn,
4136 e,
4137 WriteOp::Concept {
4138 id: &concept.id,
4139 recorded_at: stamp,
4140 branch: concept.branch_name(),
4141 },
4142 )
4143 .await),
4144 }
4145}
4146
4147/// Every recorded interval for one relationship key, for [`Interval::overlaps`]
4148/// to judge.
4149///
4150/// **Three equalities and nothing else, deliberately — and the "and nothing
4151/// else" was measured, not assumed.** The first version added
4152/// `AND valid_from < :new_valid_to`, a provably safe narrowing (overlap requires
4153/// `max(start) < min(end)`, so an interval starting at or after the new one's end
4154/// cannot overlap it). It cost **9.8 ms on a 90-edge chunk into a 2,000-edge
4155/// hub**, because it walked the planner straight into D-059's trap:
4156///
4157/// ```text
4158/// with the range: SEARCH links_current USING COVERING INDEX
4159/// idx_lc_traversal_cover (source_id=? AND valid_from<?)
4160/// without it: SEARCH links_current USING COVERING INDEX
4161/// idx_lc_open_interval (source_id=? AND target_id=? AND edge_type=?)
4162/// ```
4163///
4164/// `idx_lc_traversal_cover` leads on `(source_id, valid_from, …)` and contains
4165/// every column this query mentions, so with a `valid_from` range available it
4166/// wins as a covering index while binding **one** equality column — and the
4167/// guard scans the source's entire out-degree. That is the same shape as the
4168/// defect D-059 diagnosed in `trg_links_single_open`, reintroduced by an
4169/// optimisation, one wave after it was fixed.
4170///
4171/// Dropping the range makes the query a pure three-column point lookup that
4172/// `idx_lc_open_interval` serves exactly, and the rows it returns are the
4173/// intervals recorded for one `(source, target, edge_type)` — a version count,
4174/// not an out-degree. **A narrowing predicate is not free if it changes the
4175/// plan**, which is the general lesson and the reason this constant carries its
4176/// own `EXPLAIN` output.
4177const OVERLAP_CANDIDATES: &str = "SELECT valid_from, valid_to FROM links_current \
4178 WHERE source_id = ?1 AND target_id = ?2 AND edge_type = ?3 \
4179 AND valid_from <> ?4";
4180
4181/// Whether this pair is the storage layer's case rather than this guard's.
4182///
4183/// Two **open** intervals overlap — they share every instant from the later
4184/// start onwards — so a naive overlap check reports them, and reporting them
4185/// here would leave `DbError::SingleOpenViolation` constructible by nothing.
4186/// That variant is the more specific error, it is enforced by
4187/// `trg_links_single_open` rather than by this function, and its field names
4188/// were ratified in §1.2. Shadowing it with a general one would be defect Q's
4189/// shape reintroduced by a fix: a typed error that no code path can produce.
4190///
4191/// So the two guards partition the space rather than overlapping it. Both open
4192/// belongs to the trigger. Everything else — open against closed, closed against
4193/// closed — is unguarded at the storage layer and belongs here. That the split
4194/// is exactly the trigger's `WHEN` clause is not a coincidence; it is the
4195/// definition of what was missing.
4196fn defer_to_single_open(proposed: &Interval, existing: &Interval) -> bool {
4197 proposed.is_open() && existing.is_open()
4198}
4199
4200/// Refuse an assertion whose valid-time interval overlaps one already recorded
4201/// for the same `(source, target, edge_type)` — **defect AA, D-060**.
4202///
4203/// `trg_links_single_open` fires only `WHEN NEW.valid_to = '9999-…'`, so it
4204/// guards the open sentinel and nothing else. Two *closed* intervals that
4205/// overlap were accepted without complaint, and `query_as_of_edges` at an
4206/// instant inside both returned one relationship as two edges.
4207///
4208/// **This runs in the write actor, which is what makes it sound.** The obvious
4209/// place is `EdgeAssertion::normalized`, and it cannot go there — `normalized`
4210/// is a pure function with no connection, and doing the read at the API boundary
4211/// instead would leave a check-then-write race between the read and the actor's
4212/// insert. Inside the actor there is one writer by construction (D-014), and for
4213/// the batch paths this runs inside the same transaction as the insert, so the
4214/// window does not exist rather than being small.
4215///
4216/// **What it does not cover, and §4.2 now says so:** raw SQL against the same
4217/// file. The storage layer permits what this API refuses, which is the honest
4218/// cost of not putting the check in a trigger. The alternative was a second
4219/// index probe inside `trg_links_single_open` on every insert — on the path
4220/// D-059 has just finished making fast — for a guarantee that only holds against
4221/// callers who were going through the actor anyway.
4222///
4223/// `valid_from <> ?4` excludes the row being re-asserted. Re-assertion at the
4224/// same `valid_from` is Doctrine III's ordinary case — a new belief about the
4225/// same interval — and is settled by the primary key and the single-open
4226/// trigger, not here.
4227/// The single-assertion path prepares one statement for one check, which is what
4228/// `AssertEdge` needs; the batch path prepares once and calls
4229/// [`check_prepared`] per row.
4230async fn reject_overlapping_interval(
4231 conn: &libsql::Connection,
4232 edge: &EdgeAssertion,
4233 shape: LineageShape,
4234) -> Result<()> {
4235 let guard = OverlapGuard::prepare(conn, shape).await?;
4236 check_prepared(&guard, edge).await
4237}
4238
4239/// The guard's body, against a statement the caller has already prepared.
4240///
4241/// **Split out because preparing per row was worth 10.4 ms on a 90-edge chunk**
4242/// (§8.8) — the same defect D-056 and D-057 diagnosed and fixed for
4243/// `INSERT_LINK`, reintroduced by the Wave 2 guard that was written beside it.
4244/// Measured with and without the guard, on a 2,000-edge hub: 8.65 ms → 19.25 ms,
4245/// and *identical* with and without `idx_lc_open_interval`, which is what
4246/// identified preparation rather than a scan as the cost. A guard that reads an
4247/// index correctly and prepares its statement 90 times is indistinguishable, at
4248/// the call site, from one that scans.
4249///
4250/// `reset()` between rows is not optional: libsql binds and steps without
4251/// resetting, so a reused statement must be returned to its initial state.
4252async fn check_prepared(guard: &OverlapGuard, edge: &EdgeAssertion) -> Result<()> {
4253 let proposed = Interval::new(edge.valid_from.clone(), edge.valid_to.clone());
4254
4255 guard.stmt.reset();
4256 // The resolved form takes a fifth parameter, the writing lineage, and
4257 // returns what that lineage can see; the trunk form takes four and returns
4258 // the table. Binding five to the trunk statement would be an error from
4259 // libsql rather than a wrong answer, which is the failure mode to prefer.
4260 let mut rows = match guard.shape {
4261 LineageShape::Trunk => {
4262 guard
4263 .stmt
4264 .query(libsql::params![
4265 edge.source.as_str(),
4266 edge.target.as_str(),
4267 edge.edge_type.as_str(),
4268 edge.valid_from.as_str()
4269 ])
4270 .await?
4271 }
4272 LineageShape::Resolved => {
4273 guard
4274 .stmt
4275 .query(libsql::params![
4276 edge.source.as_str(),
4277 edge.target.as_str(),
4278 edge.edge_type.as_str(),
4279 edge.valid_from.as_str(),
4280 edge.branch_name()
4281 ])
4282 .await?
4283 }
4284 };
4285
4286 while let Some(row) = rows.next().await? {
4287 let existing = Interval::new(row.get::<String>(0)?, row.get::<String>(1)?);
4288 if defer_to_single_open(&proposed, &existing) {
4289 continue;
4290 }
4291 if proposed.overlaps(&existing) {
4292 return Err(DbError::OverlappingInterval {
4293 overlap: Box::new(crate::error::Overlap {
4294 source_id: edge.source.clone(),
4295 target_id: edge.target.clone(),
4296 edge_type: edge.edge_type.clone(),
4297 valid_from: edge.valid_from.clone(),
4298 valid_to: edge.valid_to.clone(),
4299 existing_from: existing.valid_from,
4300 existing_to: existing.valid_to,
4301 // This guard reads committed rows, so the interval it names
4302 // is one the caller can go and look at (D-180).
4303 within_batch: false,
4304 }),
4305 });
4306 }
4307 }
4308
4309 Ok(())
4310}
4311
4312/// The same guard applied *within* a batch, before any of it is written.
4313///
4314/// The database check cannot see rows that are not in the database yet, so a
4315/// batch carrying two overlapping intervals for one relationship would pass
4316/// every per-row check and commit the overlap in one transaction.
4317///
4318/// # Sorted and swept rather than compared pairwise (0.13.6, W7.5, D-179)
4319///
4320/// This used to compare every pair. At [`chunk_rows::EDGES`] = 90 that is
4321/// nothing, and the chunked paths are the only ones where 90 is the bound —
4322/// [`Database::write_bulk_atomic`] is exempt from [`CHUNK_BUDGET`] by contract,
4323/// so its batch is whatever the caller passed, and the quadratic term is what
4324/// made 20,000 corrections to one relationship's history cost seconds rather
4325/// than milliseconds. Sorting by `(source, target, edge_type, valid_from)` and
4326/// sweeping costs `n log n` and changes nothing a caller can observe except the
4327/// wait.
4328///
4329/// **Adjacent pairs are not sufficient, and that is the whole difficulty.** For
4330/// plain intervals they would be: sort by start, and if any two overlap then
4331/// some neighbouring two overlap. That proof needs every pair to be *eligible*,
4332/// and here two are not — identical `valid_from` is re-assertion rather than
4333/// overlap, and two open intervals belong to `trg_links_single_open`. Skip an
4334/// adjacent pair for either reason and a real overlap can hide behind it:
4335/// `[5,20)`, `[5,6)`, `[7,8)` has the first pair skipped for equal `valid_from`
4336/// and the second not overlapping, while `[5,20)` and `[7,8)` overlap plainly.
4337/// So the sweep carries the widest `valid_to` reached so far instead of looking
4338/// only backwards one step, and carries a second one restricted to closed
4339/// intervals — because an open predecessor is excluded for an open candidate
4340/// and eligible for a closed one, which are different questions with different
4341/// answers.
4342///
4343/// Equal `valid_from` is handled by advancing in runs: everything with the same
4344/// start is checked against the maxima, and only then folded into them, so the
4345/// members of a run never see each other.
4346///
4347/// The report names the *earlier* interval as the existing one, which is the
4348/// pairwise version's input order only by accident. Within a batch neither is
4349/// older in transaction time — they arrive under one stamp — so valid-time order
4350/// is the only ordering that means anything, and it is the one a reader will
4351/// assume the words carry.
4352fn reject_overlaps_within(edges: &[EdgeAssertion]) -> Result<()> {
4353 // Indices, not the edges. The batch is borrowed and its order is the order
4354 // the rows are written in; sorting it would either clone it or reorder the
4355 // caller's data, which is `estimated_bulk_hold`'s reason for grouping too.
4356 let mut order: Vec<u32> = (0..edges.len() as u32).collect();
4357 order.sort_unstable_by(|&i, &j| {
4358 let a = &edges[i as usize];
4359 let b = &edges[j as usize];
4360 (
4361 &a.source,
4362 &a.target,
4363 &a.edge_type,
4364 a.branch_name(),
4365 &a.valid_from,
4366 )
4367 .cmp(&(
4368 &b.source,
4369 &b.target,
4370 &b.edge_type,
4371 b.branch_name(),
4372 &b.valid_from,
4373 ))
4374 });
4375
4376 fn key(e: &EdgeAssertion) -> (&str, &str, &str, &str) {
4377 (
4378 e.source.as_str(),
4379 e.target.as_str(),
4380 e.edge_type.as_str(),
4381 e.branch_name(),
4382 )
4383 }
4384 let at = |k: usize| &edges[order[k] as usize];
4385
4386 let mut group = 0;
4387 while group < order.len() {
4388 let mut group_end = group + 1;
4389 while group_end < order.len() && key(at(group_end)) == key(at(group)) {
4390 group_end += 1;
4391 }
4392
4393 // The furthest `valid_to` reached by anything already swept in this key
4394 // group, and the edge it came from so the error can name it. The second
4395 // one ignores open intervals: an open candidate may not be compared
4396 // against an open predecessor, and the sentinel would otherwise win the
4397 // maximum every time and make every such pair look like an overlap.
4398 let mut widest: Option<&EdgeAssertion> = None;
4399 let mut widest_closed: Option<&EdgeAssertion> = None;
4400
4401 let mut run = group;
4402 while run < group_end {
4403 let mut run_end = run + 1;
4404 while run_end < group_end && at(run_end).valid_from == at(run).valid_from {
4405 run_end += 1;
4406 }
4407
4408 for k in run..run_end {
4409 let e = at(k);
4410 let existing = if e.valid_to == timestamp::OPEN_SENTINEL {
4411 widest_closed
4412 } else {
4413 widest
4414 };
4415 let Some(p) = existing else { continue };
4416 // `Interval::overlaps` is `max(from) < min(to)`, and the sort
4417 // has already settled the max: `p.valid_from <= e.valid_from`.
4418 // What is left is the same predicate with the maximum resolved,
4419 // and it is written out rather than allocating two `Interval`s
4420 // per row to ask the same question.
4421 if e.valid_from < p.valid_to && e.valid_from < e.valid_to {
4422 return Err(DbError::OverlappingInterval {
4423 overlap: Box::new(crate::error::Overlap {
4424 source_id: e.source.clone(),
4425 target_id: e.target.clone(),
4426 edge_type: e.edge_type.clone(),
4427 valid_from: e.valid_from.clone(),
4428 valid_to: e.valid_to.clone(),
4429 existing_from: p.valid_from.clone(),
4430 existing_to: p.valid_to.clone(),
4431 // Nothing here is in the database, and the batch is
4432 // refused whole, so nothing here ever will be. The
4433 // message has to say so (D-180).
4434 within_batch: true,
4435 }),
4436 });
4437 }
4438 }
4439
4440 for k in run..run_end {
4441 let e = at(k);
4442 if widest.is_none_or(|w| e.valid_to > w.valid_to) {
4443 widest = Some(e);
4444 }
4445 if e.valid_to != timestamp::OPEN_SENTINEL
4446 && widest_closed.is_none_or(|w| e.valid_to > w.valid_to)
4447 {
4448 widest_closed = Some(e);
4449 }
4450 }
4451
4452 run = run_end;
4453 }
4454
4455 group = group_end;
4456 }
4457
4458 Ok(())
4459}
4460
4461/// Write every edge or none, under a single stamp.
4462///
4463/// **The statement is prepared once for the whole chunk (§9, D-056).** It used to
4464/// be `tx.execute(INSERT_LINK, …)` per row, which re-prepares on every call — and
4465/// `links` carries two triggers, so each preparation compiles their bodies along
4466/// with the insert.
4467///
4468/// Measured at 500 rows: **≈62 ms → ≈37 ms, a 41% saving.** Preparation was a
4469/// large cost and *not* the dominant one, which the first guess had it as. The
4470/// residual is the triggers themselves: the same 500 rows with
4471/// `trg_links_log_insert` and `trg_links_current_sync` dropped commit in **2.96
4472/// ms**, so trigger amplification is ~92% of what remains. There is no further
4473/// win available here without changing what the ledger records, and Doctrine IV
4474/// is what says it must be recorded. See D-056 for what that implies about §9's
4475/// ≤ 3 ms budget — briefly, 2.96 ms *is* the un-amplified figure, so the budget
4476/// appears to have been set without the amplification its own preamble says is
4477/// included.
4478///
4479/// `reset()` between rows is not optional: libsql's `execute` binds and steps
4480/// without resetting, so a reused statement must be returned to its initial state
4481/// or the second row steps a completed statement.
4482async fn write_edges_atomic(
4483 conn: &libsql::Connection,
4484 edges: &[EdgeAssertion],
4485 stamp: &str,
4486) -> Result<usize> {
4487 if edges.is_empty() {
4488 return Ok(0);
4489 }
4490
4491 // Before the transaction opens: a batch that contradicts itself is refused
4492 // without taking the write lock at all (D-060), and a batch naming a
4493 // lineage that does not exist is refused before it can take the lock at all
4494 // (0.14.8).
4495 reject_overlaps_within(edges)?;
4496 let shape = check_lineages(conn, &distinct_branches(edges)).await?;
4497
4498 let tx = conn
4499 .transaction_with_behavior(libsql::TransactionBehavior::Immediate)
4500 .await?;
4501
4502 // Inside the transaction, so the rows this checks against cannot change
4503 // between the check and the insert.
4504 // One preparation for the whole chunk, not one per row — see
4505 // `check_prepared`, and D-056 for the same lesson learned on `INSERT_LINK`.
4506 let guard = OverlapGuard::prepare(&tx, shape).await?;
4507 for edge in edges {
4508 if let Err(e) = check_prepared(&guard, edge).await {
4509 // Released before the rollback: a live statement on the connection
4510 // is what makes SQLite refuse to end a transaction.
4511 drop(guard);
4512 let _ = tx.rollback().await;
4513 return Err(e);
4514 }
4515 }
4516 drop(guard);
4517
4518 let stmt = tx.prepare(INSERT_LINK).await?;
4519
4520 for edge in edges {
4521 stmt.reset();
4522 let res = stmt.execute(edge_params(edge, stamp)).await;
4523
4524 if let Err(e) = res {
4525 let typed = classify(
4526 &tx,
4527 e,
4528 WriteOp::Edge {
4529 source_id: &edge.source,
4530 target_id: &edge.target,
4531 edge_type: &edge.edge_type,
4532 },
4533 )
4534 .await;
4535 // Released before the rollback: a live statement on the connection
4536 // is exactly what makes SQLite refuse to end a transaction.
4537 drop(stmt);
4538 let _ = tx.rollback().await;
4539 return Err(typed);
4540 }
4541 }
4542
4543 drop(stmt);
4544 tx.commit().await?;
4545 Ok(edges.len())
4546}
4547
4548/// Write every concept or none, under a single stamp.
4549/// Upsert one chunk of derived annotations in a single transaction (D-041).
4550///
4551/// `stamp` is the actor's clock reading, exactly as for every other chunk — but
4552/// it lands in `computed_at`, not in a `recorded_at`, and the difference is not
4553/// cosmetic. `recorded_at` is the transaction-time axis and is subject to
4554/// Doctrine II and the monotonicity guard; `computed_at` is a note about when a
4555/// derivation last ran, on a table the ledger does not see. Rerunning an
4556/// algorithm therefore replaces the row and advances the note, rather than
4557/// versioning a concept the world did not change.
4558///
4559/// # Failures name the concept (0.13.3, W7.2, D-176)
4560///
4561/// This was the one write path in the crate that returned
4562/// [`DbError::Engine`] raw, and the omission looked harmless: the table
4563/// carries no triggers, so none of [`crate::error::AbortKind`]'s guards can
4564/// fire on it and [`classify`] would have returned the same raw error it was
4565/// given. What that reasoning missed is the foreign key onto `concepts`, which
4566/// the engine enforces itself. Annotating a concept that does not exist is the
4567/// one failure a caller can cause here, and it reported as
4568/// `FOREIGN KEY constraint failed` with no row named — out of a chunk of up to
4569/// [`chunk_rows::ANNOTATIONS`].
4570///
4571/// It now goes through [`classify`] with [`WriteOp::Annotation`] like every
4572/// other write, and a missing concept returns [`DbError::NotFound`] carrying
4573/// its id.
4574async fn write_annotations_atomic(
4575 conn: &libsql::Connection,
4576 annotations: &[Annotation],
4577 stamp: &str,
4578) -> Result<usize> {
4579 if annotations.is_empty() {
4580 return Ok(0);
4581 }
4582
4583 let tx = conn
4584 .transaction_with_behavior(libsql::TransactionBehavior::Immediate)
4585 .await?;
4586
4587 let stmt = tx
4588 .prepare(
4589 "INSERT INTO analytics_annotations (concept_id, label, value, computed_at) \
4590 VALUES (?1, ?2, ?3, ?4) \
4591 ON CONFLICT(concept_id, label) DO UPDATE SET \
4592 value = excluded.value, computed_at = excluded.computed_at",
4593 )
4594 .await?;
4595
4596 for a in annotations {
4597 stmt.reset();
4598 let res = stmt
4599 .execute(libsql::params![
4600 a.concept_id.as_str(),
4601 a.label.as_str(),
4602 a.value.as_str(),
4603 stamp
4604 ])
4605 .await;
4606 if let Err(e) = res {
4607 let typed = classify(
4608 &tx,
4609 e,
4610 WriteOp::Annotation {
4611 concept_id: &a.concept_id,
4612 },
4613 )
4614 .await;
4615 drop(stmt);
4616 let _ = tx.rollback().await;
4617 return Err(typed);
4618 }
4619 }
4620
4621 drop(stmt);
4622 tx.commit().await?;
4623 Ok(annotations.len())
4624}
4625
4626async fn write_concepts_atomic(
4627 conn: &libsql::Connection,
4628 concepts: &[ConceptUpsert],
4629 stamp: &str,
4630) -> Result<usize> {
4631 if concepts.is_empty() {
4632 return Ok(0);
4633 }
4634
4635 // Named lineages, before the write lock — `check_lineages`' reason, and the
4636 // shape it also returns is unused here because `concepts` is keyed by
4637 // identity and has no resolution to do (see `ConceptUpsert::branch`).
4638 let mut named: Vec<&str> = Vec::with_capacity(1);
4639 for concept in concepts {
4640 let name = concept.branch_name();
4641 if !named.contains(&name) {
4642 named.push(name);
4643 }
4644 }
4645 check_lineages(conn, &named).await?;
4646
4647 let tx = conn
4648 .transaction_with_behavior(libsql::TransactionBehavior::Immediate)
4649 .await?;
4650
4651 // Prepared once, like the edge chunk (D-056). This no longer routes through
4652 // [`upsert_concept`] — that function prepares per call by construction — but
4653 // it shares that function's statement text and parameter row, so the two
4654 // cannot upsert different columns.
4655 let stmt = tx.prepare(UPSERT_CONCEPT).await?;
4656
4657 for concept in concepts {
4658 stmt.reset();
4659 let res = stmt.execute(concept_params(concept, stamp)).await;
4660
4661 if let Err(e) = res {
4662 let typed = classify(
4663 &tx,
4664 e,
4665 WriteOp::Concept {
4666 id: &concept.id,
4667 recorded_at: stamp,
4668 branch: concept.branch_name(),
4669 },
4670 )
4671 .await;
4672 drop(stmt);
4673 let _ = tx.rollback().await;
4674 return Err(typed);
4675 }
4676 }
4677
4678 drop(stmt);
4679 tx.commit().await?;
4680 Ok(concepts.len())
4681}
4682
4683#[cfg(test)]
4684mod tests {
4685 use super::*;
4686
4687 fn edge(target: &str, micros: usize) -> EdgeAssertion {
4688 EdgeAssertion::new("src", target, "LINKS")
4689 .valid_from(format!("2026-01-01T00:00:00.{micros:06}Z"))
4690 .valid_to(format!("2026-01-01T00:00:00.{:06}Z", micros + 1))
4691 }
4692
4693 /// The estimate must **no longer** depend on the batch's shape (0.13.6).
4694 ///
4695 /// Its dependence on shape was correct for as long as the guard was
4696 /// quadratic and the constant differed 16× between the two paths through
4697 /// its inner loop. W7.5 removed that term, and measurement agrees: 1.94 s
4698 /// and 2.22 s for the two 20,000-edge batches that used to differ by 7×.
4699 /// A model that kept predicting a 7× spread would now be wrong in the
4700 /// *expensive* direction — warning loudly about a batch that is fine.
4701 #[test]
4702 fn two_batches_of_one_size_are_predicted_alike() {
4703 const N: usize = 20_000;
4704 let fanout: Vec<_> = (0..N).map(|i| edge(&format!("t{i:07}"), i)).collect();
4705 let history: Vec<_> = (0..N).map(|i| edge("t0", i)).collect();
4706
4707 assert_eq!(
4708 estimated_bulk_hold(&fanout),
4709 estimated_bulk_hold(&history),
4710 "the guard no longer reads the batch's shape, so neither may this"
4711 );
4712 }
4713
4714 /// Measured on libSQL 0.9.30 after W7.5: 1.94 s and 2.22 s for those two
4715 /// batches, against 2.6 s and 18.1 s before it. This pins that the model
4716 /// still tracks them — a coefficient edited without re-measuring fails here.
4717 #[test]
4718 fn the_estimate_matches_what_was_measured() {
4719 const N: usize = 20_000;
4720 let fanout: Vec<_> = (0..N).map(|i| edge(&format!("t{i:07}"), i)).collect();
4721 let history: Vec<_> = (0..N).map(|i| edge("t0", i)).collect();
4722
4723 for (batch, measured_ms, label) in
4724 [(fanout, 1_936u128, "fanout"), (history, 2_220, "history")]
4725 {
4726 let predicted = estimated_bulk_hold(&batch).as_millis();
4727 let ratio = predicted as f64 / measured_ms as f64;
4728 assert!(
4729 (0.8..1.25).contains(&ratio),
4730 "{label}: predicted {predicted} ms against a measured \
4731 {measured_ms} ms ({ratio:.2}x). Re-run \
4732 examples/bulk_atomic_diag.rs before changing the coefficients."
4733 );
4734 }
4735 }
4736
4737 /// `ilog2` panics on zero, and an empty batch is the caller asking whether
4738 /// a batch they have not built yet would be slow.
4739 #[test]
4740 fn an_empty_batch_estimates_nothing_rather_than_panicking() {
4741 assert_eq!(estimated_bulk_hold(&[]), std::time::Duration::ZERO);
4742 let one = [edge("t0", 0)];
4743 assert_eq!(
4744 estimated_bulk_hold(&one),
4745 std::time::Duration::from_nanos(7_400)
4746 );
4747 }
4748
4749 /// The model is used as a threshold test, so it must not go backwards.
4750 #[test]
4751 fn a_bigger_batch_never_predicts_a_shorter_hold() {
4752 let mut last = std::time::Duration::ZERO;
4753 for n in [1usize, 2, 3, 7, 8, 100, 511, 512, 513, 5_000, 20_000] {
4754 let batch: Vec<_> = (0..n).map(|i| edge(&format!("t{i:07}"), i)).collect();
4755 let now = estimated_bulk_hold(&batch);
4756 assert!(now >= last, "{n} rows predicts {now:?} after {last:?}");
4757 last = now;
4758 }
4759 }
4760
4761 /// The warning threshold sits well above the bound this path is exempt from.
4762 ///
4763 /// Warning at `CHUNK_BUDGET` would fire on batches working exactly as
4764 /// designed — the exemption is a contract (D-014), not a failure — and a
4765 /// warning that fires on correct behaviour gets filtered out, taking the
4766 /// 18-second case with it.
4767 #[test]
4768 fn the_warning_threshold_is_not_the_chunk_budget() {
4769 assert!(BULK_ATOMIC_WARN_HOLD > CHUNK_BUDGET * 10);
4770 }
4771
4772 // -----------------------------------------------------------------------
4773 // reject_overlaps_within — sorted and swept (0.13.6, W7.5, D-179)
4774 //
4775 // The pairwise version was obviously correct and too slow; this one is
4776 // neither, so what follows pins the cases where the obvious fix is wrong
4777 // rather than only the cases the guard already caught.
4778 // -----------------------------------------------------------------------
4779
4780 /// An edge over an explicit interval, all four key columns spelled out.
4781 fn span(target: &str, edge_type: &str, from: usize, to: Option<usize>) -> EdgeAssertion {
4782 let stamp = |n: usize| format!("2026-01-01T00:00:00.{n:06}Z");
4783 EdgeAssertion::new("src", target, edge_type)
4784 .valid_from(stamp(from))
4785 .valid_to(to.map_or_else(|| timestamp::OPEN_SENTINEL.to_string(), stamp))
4786 }
4787
4788 fn closed(from: usize, to: usize) -> EdgeAssertion {
4789 span("t0", "LINKS", from, Some(to))
4790 }
4791
4792 fn open_at(from: usize) -> EdgeAssertion {
4793 span("t0", "LINKS", from, None)
4794 }
4795
4796 /// The case that makes adjacent pairs insufficient.
4797 ///
4798 /// Sort by start and any overlap shows up between neighbours — but only if
4799 /// every neighbouring pair is eligible to be checked. `[5,20)` and `[5,6)`
4800 /// are not: identical `valid_from` is re-assertion. Skip them, and `[5,6)`
4801 /// against `[7,8)` is a clean gap, and the plain overlap between `[5,20)`
4802 /// and `[7,8)` never gets looked at.
4803 #[test]
4804 fn an_overlap_hidden_behind_an_equal_valid_from_is_still_found() {
4805 let batch = vec![closed(5, 20), closed(5, 6), closed(7, 8)];
4806 assert!(matches!(
4807 reject_overlaps_within(&batch),
4808 Err(DbError::OverlappingInterval { .. })
4809 ));
4810 }
4811
4812 /// The same trap in the other direction: skipped for being open.
4813 ///
4814 /// Two open intervals are `trg_links_single_open`'s case and are passed
4815 /// over here. A running maximum that counted them would take the sentinel
4816 /// as the widest reach and report every later open interval as overlapping
4817 /// it — inventing an error rather than missing one, which is why the sweep
4818 /// carries a second maximum restricted to closed intervals.
4819 #[test]
4820 fn two_open_intervals_are_left_to_the_trigger() {
4821 let batch = vec![closed(1, 5), open_at(10), open_at(20)];
4822 assert!(reject_overlaps_within(&batch).is_ok());
4823 }
4824
4825 /// An open interval still overlaps a closed one that reaches past its start.
4826 #[test]
4827 fn an_open_interval_over_a_closed_one_is_an_overlap() {
4828 let batch = vec![closed(1, 50), open_at(10)];
4829 assert!(matches!(
4830 reject_overlaps_within(&batch),
4831 Err(DbError::OverlappingInterval { .. })
4832 ));
4833 }
4834
4835 /// Same `valid_from`, different `valid_to`: a batch correcting itself.
4836 ///
4837 /// Last writer wins by `seq_id`, exactly as it does across batches. The
4838 /// guard has no opinion.
4839 #[test]
4840 fn equal_valid_from_is_re_assertion_not_overlap() {
4841 let batch = vec![closed(5, 20), closed(5, 6), closed(5, 900)];
4842 assert!(reject_overlaps_within(&batch).is_ok());
4843 }
4844
4845 /// Grouping is what makes the sweep sound, so it is pinned rather than read.
4846 #[test]
4847 fn edges_with_different_keys_do_not_see_each_other() {
4848 let batch = vec![
4849 span("t0", "LINKS", 1, Some(50)),
4850 span("t1", "LINKS", 10, Some(60)),
4851 span("t0", "CITES", 10, Some(60)),
4852 span("t0", "LINKS", 50, Some(60)),
4853 ];
4854 assert!(reject_overlaps_within(&batch).is_ok());
4855 }
4856
4857 /// Which of the two the report calls *existing* (0.13.6).
4858 ///
4859 /// Neither is older in transaction time — a batch lands under one stamp —
4860 /// so the pairwise version's answer was its input order, which means
4861 /// nothing. Valid-time order is the only ordering the two intervals have.
4862 #[test]
4863 fn the_report_names_the_earlier_interval_as_the_existing_one() {
4864 let batch = vec![closed(7, 8), closed(5, 20)];
4865 let Err(DbError::OverlappingInterval { overlap }) = reject_overlaps_within(&batch) else {
4866 panic!("the batch overlaps itself");
4867 };
4868 assert!(overlap.valid_from.ends_with(".000007Z"), "{overlap:?}");
4869 assert!(overlap.existing_from.ends_with(".000005Z"), "{overlap:?}");
4870 }
4871
4872 /// A guard whose answer depended on the caller's ordering would be a worse
4873 /// guard than the one it replaced, and sorting is exactly the change that
4874 /// could introduce that.
4875 #[test]
4876 fn the_answer_does_not_depend_on_the_order_the_caller_passed() {
4877 let mut batch = vec![closed(5, 20), closed(5, 6), closed(7, 8)];
4878 batch.reverse();
4879 assert!(reject_overlaps_within(&batch).is_err());
4880
4881 let mut clean = vec![closed(1, 5), closed(5, 6), closed(7, 8), open_at(8)];
4882 clean.reverse();
4883 assert!(reject_overlaps_within(&clean).is_ok());
4884 }
4885
4886 /// §2.6, and the reason the rewrite happened rather than the doc alone.
4887 ///
4888 /// Every edge shares a key, so the old loop reached `Interval::overlaps`
4889 /// on all n(n−1)/2 pairs — 50 million of them here, which is seconds even
4890 /// in release and considerably worse in the debug profile this runs under.
4891 /// The bound is loose on purpose: it is an order of magnitude, not a
4892 /// benchmark, and the only thing it can fail on is the quadratic term
4893 /// coming back.
4894 #[test]
4895 fn one_relationships_whole_history_is_no_longer_quadratic() {
4896 const N: usize = 10_000;
4897 let batch: Vec<_> = (0..N).map(|i| closed(i * 2, i * 2 + 1)).collect();
4898
4899 let started = std::time::Instant::now();
4900 assert!(reject_overlaps_within(&batch).is_ok());
4901 let took = started.elapsed();
4902
4903 assert!(
4904 took < std::time::Duration::from_secs(2),
4905 "{N} same-key edges took {took:?} in the guard"
4906 );
4907 }
4908
4909 // -----------------------------------------------------------------------
4910 // next_chunk_size — the control law (0.12.0, W2)
4911 //
4912 // All of these run without a database, a clock or an actor, which is why
4913 // W2 comes before W3: the loop that will use this function can only be
4914 // tested against a real write, and the properties below cannot be observed
4915 // there without also observing the machine.
4916 // -----------------------------------------------------------------------
4917
4918 use std::time::Duration;
4919
4920 /// `next_chunk_size` with the shipped budget and floor.
4921 fn step_to(current: usize, held_ms: f64, ceiling: usize) -> usize {
4922 next_chunk_size(
4923 current,
4924 Duration::from_nanos((held_ms * 1_000_000.0) as u64),
4925 CHUNK_BUDGET,
4926 CHUNK_FLOOR,
4927 ceiling,
4928 )
4929 }
4930
4931 /// The edge path, which is every test here that does not say otherwise.
4932 fn step(current: usize, held_ms: f64) -> usize {
4933 step_to(current, held_ms, chunk_rows::EDGES)
4934 }
4935
4936 /// Iterate the law against a machine that costs `per_row_us` per row plus a
4937 /// fixed `overhead_ms` per transaction — the two-term model D-142 measured.
4938 fn converge(
4939 start: usize,
4940 per_row_us: f64,
4941 overhead_ms: f64,
4942 ceiling: usize,
4943 steps: usize,
4944 ) -> Vec<usize> {
4945 let mut size = start;
4946 (0..steps)
4947 .map(|_| {
4948 let held = overhead_ms + per_row_us * size as f64 / 1000.0;
4949 size = step_to(size, held, ceiling);
4950 size
4951 })
4952 .collect()
4953 }
4954
4955 /// The reason the shrink is proportional rather than a halving: at 4× over
4956 /// budget, halving needs three steps and every one of them is a latency
4957 /// miss a caller can feel.
4958 ///
4959 /// Run on the annotations path, because it is the only one whose ceiling
4960 /// leaves room to start far above a size that is reachable — on the edge
4961 /// path a 4× miss lands under [`CHUNK_FLOOR`], which is a different test.
4962 #[test]
4963 fn a_chunk_far_over_budget_converges_from_above_in_at_most_two_steps() {
4964 const CEILING: usize = chunk_rows::ANNOTATIONS;
4965 let (per_row_us, overhead_ms) = (20.0, 0.05);
4966 let held = |n: usize| overhead_ms + per_row_us * n as f64 / 1000.0;
4967 assert!(
4968 held(CEILING) > 4.0 * 3.0,
4969 "the start is not far over budget"
4970 );
4971
4972 let trace = converge(CEILING, per_row_us, overhead_ms, CEILING, 4);
4973 let first_in_budget = trace
4974 .iter()
4975 .position(|&n| held(n) <= 3.0)
4976 .expect("never reached the budget");
4977 assert!(
4978 first_in_budget <= 1,
4979 "took {} steps to get under budget: {trace:?}",
4980 first_in_budget + 1
4981 );
4982 }
4983
4984 /// Growth is additive, so a size that is merely comfortable cannot leap the
4985 /// ceiling — and cannot overshoot the budget by more than a quarter.
4986 #[test]
4987 fn growth_is_slow_and_shrinking_is_fast() {
4988 let grown = step(40, 1.0);
4989 assert!(
4990 (41..=50).contains(&grown),
4991 "40 rows at 1 ms should grow by about a quarter, got {grown}"
4992 );
4993 let shrunk = step(90, 9.0);
4994 assert!(
4995 shrunk <= 40,
4996 "90 rows at 3x the budget should shrink proportionally, got {shrunk}"
4997 );
4998 }
4999
5000 /// The dead band. Between `budget / 2` and `budget` the size is right and
5001 /// moving it only costs a re-measurement; without this the law oscillates
5002 /// across the bound forever.
5003 #[test]
5004 fn a_chunk_inside_the_band_is_left_alone() {
5005 for held_ms in [1.6, 2.0, 2.5, 2.9, 3.0] {
5006 assert_eq!(step(60, held_ms), 60, "moved at {held_ms} ms");
5007 }
5008 assert_ne!(step(60, 1.4), 60, "did not grow at well under half budget");
5009 }
5010
5011 /// Both clamps, and the floor's violation stated as a test rather than only
5012 /// as a comment: a populated table drives this to `CHUNK_FLOOR` and holds it
5013 /// there **over budget**, which is [`CHUNK_FLOOR`]'s documented trade.
5014 #[test]
5015 fn the_floor_and_the_ceiling_both_hold() {
5016 // 118 µs/row + 0.03 ms fixed — the populated arm, where 35 rows is
5017 // ~4.1 ms and no size in range meets the bound.
5018 let trace = converge(chunk_rows::EDGES, 118.0, 0.03, chunk_rows::EDGES, 8);
5019 assert!(
5020 trace.iter().all(|&n| n >= CHUNK_FLOOR),
5021 "fell through the floor: {trace:?}"
5022 );
5023 assert_eq!(*trace.last().unwrap(), CHUNK_FLOOR, "settled off the floor");
5024
5025 // A free machine cannot grow past the path's constant.
5026 let fast = converge(CHUNK_FLOOR, 1.0, 0.01, chunk_rows::EDGES, 40);
5027 assert_eq!(*fast.last().unwrap(), chunk_rows::EDGES);
5028 assert!(fast.iter().all(|&n| n <= chunk_rows::EDGES));
5029 }
5030
5031 /// Zero is the one answer that cannot be recovered from: a loop asked for
5032 /// chunks of no rows makes no progress and never finishes. Degenerate
5033 /// inputs included, since `held` is a measurement and measurements arrive
5034 /// from a machine under load.
5035 #[test]
5036 fn the_law_never_returns_zero() {
5037 let cases = [
5038 (0usize, Duration::ZERO),
5039 (0, Duration::from_secs(60)),
5040 (1, Duration::from_secs(60)),
5041 (90, Duration::from_secs(3600)),
5042 (usize::MAX, Duration::from_nanos(1)),
5043 (1, Duration::ZERO),
5044 ];
5045 for (current, held) in cases {
5046 for (floor, ceiling) in [(35, 90), (1, 1), (0, 0), (90, 35)] {
5047 let n = next_chunk_size(current, held, CHUNK_BUDGET, floor, ceiling);
5048 assert!(
5049 n > 0,
5050 "returned 0 for current={current}, held={held:?}, \
5051 floor={floor}, ceiling={ceiling}"
5052 );
5053 }
5054 }
5055 }
5056
5057 /// A zero budget is not a configuration anyone should reach, but it is one
5058 /// division away from a panic, so it is pinned.
5059 #[test]
5060 fn a_zero_budget_shrinks_to_the_floor_rather_than_dividing_by_it() {
5061 assert_eq!(
5062 next_chunk_size(90, Duration::from_millis(1), Duration::ZERO, 35, 90),
5063 35
5064 );
5065 }
5066
5067 /// A panicked write actor is reported, and the report says so (W7.3, D-177).
5068 ///
5069 /// This is the branch `close()` actually has. Through 0.13.3 it sat beside
5070 /// `Ok(res) => res?` on an actor `Result` that could never be `Err`, and the
5071 /// pair looked like two failure paths under review — so the one that cannot
5072 /// fire was carried through two signatures and the one that can had no test.
5073 ///
5074 /// The `JoinError` is real rather than mocked: `JoinError` has no public
5075 /// constructor, and one built by hand would pin the mapping against a value
5076 /// tokio does not produce.
5077 #[tokio::test]
5078 async fn a_writer_that_panicked_is_reported_by_close() {
5079 // Swallow the panic's own output. The task is *meant* to panic, and a
5080 // backtrace in a green suite trains people to skim it.
5081 let prev = std::panic::take_hook();
5082 std::panic::set_hook(Box::new(|_| {}));
5083 let handle = tokio::spawn(async { panic!("the write connection is gone") });
5084 let joined = handle.await;
5085 std::panic::set_hook(prev);
5086
5087 assert!(
5088 joined.is_err(),
5089 "the task must have panicked for this to test anything"
5090 );
5091
5092 match writer_exit(joined) {
5093 Err(DbError::WriterStopped(reason)) => {
5094 assert!(
5095 reason.contains("did not exit cleanly"),
5096 "the message must say what happened: {reason}"
5097 );
5098 }
5099 other => panic!("a panicked actor must be WriterStopped, got {other:?}"),
5100 }
5101 }
5102
5103 /// An actor that ran to completion closes clean.
5104 ///
5105 /// The other half, and the one that must not acquire a failure mode by
5106 /// accident: `run_writer_actor` returns `()`, so the only way this can start
5107 /// reporting an error is if someone gives the actor a `Result` again.
5108 #[tokio::test]
5109 async fn a_writer_that_finished_normally_closes_clean() {
5110 let handle = tokio::spawn(async {});
5111 assert!(writer_exit(handle.await).is_ok());
5112 }
5113
5114 /// A token is a handle to one flag, not a value that is copied (0.13.8,
5115 /// W7.6). The clone the caller keeps and the clone the import holds have to
5116 /// be the same flag, or `cancel()` reaches nothing.
5117 #[test]
5118 fn a_cloned_token_cancels_the_original() {
5119 let token = CancelToken::new();
5120 let held_by_the_import = token.clone();
5121 assert!(!held_by_the_import.is_cancelled());
5122 token.cancel();
5123 assert!(held_by_the_import.is_cancelled());
5124 // And it stays cancelled: there is no un-cancel, deliberately, because
5125 // a token that could be reset would let a second import inherit a
5126 // decision made about the first.
5127 token.cancel();
5128 assert!(held_by_the_import.is_cancelled());
5129 }
5130
5131 /// The default control is the one the plain bulk methods pass, and it must
5132 /// never stop a write.
5133 #[test]
5134 fn the_default_control_neither_cancels_nor_reports() {
5135 let control = BulkControl::new();
5136 assert!(!control.is_cancelled());
5137 // No callback, so this is a no-op rather than a panic on an `unwrap`.
5138 control.report(BulkProgress {
5139 written: 1,
5140 total: 1,
5141 rows: 1,
5142 held: std::time::Duration::ZERO,
5143 });
5144 }
5145
5146 /// The callback receives what it was promised, once per call to `report`.
5147 #[test]
5148 fn progress_reaches_the_callback_unchanged() {
5149 let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
5150 let control = BulkControl::new().on_progress({
5151 let seen = Arc::clone(&seen);
5152 move |p| seen.lock().unwrap().push(p)
5153 });
5154 let sample = BulkProgress {
5155 written: 180,
5156 total: 900,
5157 rows: 90,
5158 held: std::time::Duration::from_millis(12),
5159 };
5160 control.report(sample);
5161 assert_eq!(*seen.lock().unwrap(), vec![sample]);
5162 }
5163}