Skip to main content

khive_db/checkpoint/
task_loop.rs

1//! Periodic checkpoint work and pressure-episode transitions.
2
3use std::sync::atomic::Ordering;
4use std::sync::Arc;
5use std::time::Instant;
6
7use crate::pool::ConnectionPool;
8
9#[cfg(unix)]
10use super::{
11    complete_walpin_attribution, run_walpin_housekeeping_if_due, WalpinSidecarState,
12    DEFAULT_SESSION_SWEEP_INTERVAL,
13};
14use super::{
15    crossing_warn, log_tx_age_emission, log_tx_registry_oldest_debug, log_tx_registry_oldest_warn,
16    log_tx_registry_snapshot_warn, log_wal_high_water_warn, note_checkpoint_pressure_observation,
17    note_checkpoint_skipped, off_worker, CheckpointConfig, CheckpointConnection,
18    CheckpointLifecycleEmitter, CheckpointLifecycleOwner, CheckpointPressureEpisode,
19    CheckpointRunTaskGuard, CheckpointSeverityRung, CheckpointSeverityState, CheckpointTick,
20    ReaderCheckoutSweepState, TruncateState, TxAgeSweepState, CHECKPOINT_LIFECYCLE_ENQUEUE_DROPS,
21};
22
23/// Run one due FTS5 maintenance step off this task's Tokio worker thread.
24///
25/// A due step can issue up to `config.merge_pages` pages of synchronous
26/// SQLite incremental-merge I/O against a trigram index over a corpus of
27/// hundreds of thousands of rows — the same class of blocking work the
28/// WAL-pin beacon writes above already move off the worker via
29/// `tokio::task::spawn_blocking`. An ordinary write owner is constructed
30/// inside the blocking closure; the checkpoint file is never lent to FTS DML.
31/// Scheduler state returns on non-panicking paths. A panic surfaces as the
32/// `JoinError`, and the owner settles before releasing its lease.
33pub(super) async fn run_fts_maintenance_off_worker(
34    pool: Arc<ConnectionPool>,
35    config: crate::fts_maintenance::FtsMaintenanceConfig,
36    mut state: crate::fts_maintenance::FtsMaintenanceState,
37    now: Instant,
38) -> Result<
39    (
40        crate::fts_maintenance::FtsMaintenanceState,
41        Result<Option<crate::fts_maintenance::FtsMaintenanceStep>, String>,
42    ),
43    tokio::task::JoinError,
44> {
45    tokio::task::spawn_blocking(move || {
46        let result = pool.run_fts_maintenance(&config, &mut state, now);
47        (state, result)
48    })
49    .await
50}
51
52/// Run the WAL checkpoint background task.
53///
54/// Long-running async task — spawn with `tokio::spawn`. Loops until
55/// `shutdown_rx` observes a change (or its sender is dropped). Callers MUST
56/// hold the paired `tokio::sync::watch::Sender` for the daemon's run scope
57/// and send on it to shut down — do NOT rely on `pool`'s `Arc` refcount
58/// reaching zero; a sibling owner (e.g. `event_store`) holding its own clone
59/// makes that check unreachable (issue #774).
60///
61/// Issues `PRAGMA wal_checkpoint(PASSIVE)` every tick on the task's dedicated
62/// `CheckpointConnection` — never the pool's writer mutex, so a concurrent
63/// `pool.writer()` checkout can never queue behind a checkpoint tick. That
64/// guarantee is admission-only: an armed TRUNCATE still takes SQLite's writer
65/// lock and can block new write transactions, on any connection, for up to
66/// `truncate_busy_timeout` (see `CheckpointConnection`'s contract). The
67/// checkpoint call itself runs on `spawn_blocking`, so that wait never holds
68/// one of the runtime's worker threads. A tick is
69/// `Skipped` when that connection is unavailable or SQLite returns a busy
70/// PASSIVE row without a usable pressure observation. A
71/// WARNING fires once per below→above threshold crossing, not every tick.
72///
73/// `lifecycle_owner` (ADR-094): exactly one task in a multi-backend fan-out
74/// should receive `Some`. That task appends a best-effort
75/// `CheckpointOutcomeRecorded` event on the elevation transition and one
76/// recovery summary when pressure falls back below `warn_pages`. Sustained
77/// elevated ticks aggregate in memory and in `db_diagnostics`; they never
78/// write one primary-store row per checkpoint attempt. `None` explicitly
79/// marks a non-owner. See `crates/khive-db/docs/api/checkpoint.md` for the
80/// full shutdown-mechanism and event-emission design history.
81///
82/// `is_main` (ADR-091 Amendment 3): whether `pool` is the deployment's main
83/// backend. A daemon owning several file-backed backends spawns one task per
84/// backend, each with its own pool and shutdown-channel clone (the sender
85/// broadcasts to every receiver clone alike). Lifecycle ownership is selected
86/// independently through `lifecycle_owner`; `is_main` only controls registry
87/// filtering. See the `tx_filter` construction below.
88pub async fn run_checkpoint_task(
89    pool: Arc<ConnectionPool>,
90    config: CheckpointConfig,
91    lifecycle_owner: Option<CheckpointLifecycleOwner>,
92    mut shutdown_rx: tokio::sync::watch::Receiver<()>,
93    is_main: bool,
94) {
95    let _checkpoint_run_guard = CheckpointRunTaskGuard::start(&pool, config.interval);
96    // This task IS the dedicated checkpoint owner: claim the pool so writer
97    // connections drop the bounded autocheckpoint fallback and routine
98    // checkpoint I/O stays off application commit paths. Pools without a
99    // running checkpoint task never claim and keep SQLite's bounded WAL
100    // reclamation. A failed claim leaves connections on the bounded fallback
101    // — safe, just not the low-latency posture — so it warns and continues.
102    match pool.claim_checkpoint_ownership() {
103        Ok(()) => {
104            if let Err(e) = pool.propagate_checkpoint_claim_to_writer_task().await {
105                tracing::warn!(target: "khive_db::checkpoint",
106                    error = %e,
107                    "checkpoint task could not reach the writer task's connection; it keeps the \
108                     bounded autocheckpoint fallback"
109                );
110            }
111        }
112        Err(e) => {
113            tracing::warn!(target: "khive_db::checkpoint",
114                error = %e,
115                "checkpoint task could not re-apply the ownership pragma on the pooled writer; \
116                 writer connections keep the bounded autocheckpoint fallback unless ownership is \
117                 claimed later"
118            );
119        }
120    }
121    let mut interval = tokio::time::interval(config.interval);
122    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
123    let mut severity_state = CheckpointSeverityState::default();
124    let mut tx_age_state = TxAgeSweepState::default();
125    let mut reader_checkout_state = ReaderCheckoutSweepState::default();
126    let mut was_above_high_water = false;
127    #[cfg(unix)]
128    let legacy_walpin_fallback_interval = DEFAULT_SESSION_SWEEP_INTERVAL;
129    #[cfg(unix)]
130    let mut truncate_state =
131        TruncateState::with_legacy_walpin_fallback(legacy_walpin_fallback_interval);
132    #[cfg(not(unix))]
133    let mut truncate_state = TruncateState::default();
134    let mut lifecycle_emitter = CheckpointLifecycleEmitter::new(lifecycle_owner);
135    // Independent of `severity_state` (which owns the WARN ladder): this
136    // tracks the lifecycle sink's accepted elevation state. A full queue
137    // leaves it unchanged, so an opening or recovery transition is retried
138    // without admitting more than one primary-store write for that edge.
139    let mut event_elevation_open = false;
140    let mut pressure_episode: Option<CheckpointPressureEpisode> = None;
141    // A recovery row whose `try_emit` lost the race against a full queue.
142    // Retried on later ticks (before that tick's own transition handling)
143    // instead of leaving `pressure_episode` open for a stale episode to
144    // absorb the next, genuinely separate, pressure incident (#1857).
145    let mut pending_recovery: Option<khive_storage::CheckpointOutcomeRecordedPayload> = None;
146    let mut was_observed_above_warn = false;
147    // ADR-091 Amendment 3: this task's own backend-scoped view of the
148    // registry. `is_main` selects which `TxOriginFilter` variant applies —
149    // the caller passes `true` for exactly the one checkpoint task covering
150    // the deployment's main backend, so only that task also observes legacy
151    // `Unscoped` spans from any call site not yet threaded to an origin, the
152    // designed never-silently-drop fallback. A secondary backend's task
153    // never falls back to `Unscoped`: those spans belong to the main view or
154    // to no view, never to a database they were never registered against.
155    // `None` only when this pool's own origin isn't `Database` (an in-memory
156    // checkpoint pool) — degrades to "no open span observed" for the tick
157    // rather than panicking a long-running daemon loop on an
158    // assumed-impossible state.
159    let tx_filter = match pool.origin() {
160        khive_storage::tx_registry::TxOrigin::Database(id) => Some(if is_main {
161            khive_storage::tx_registry::TxOriginFilter::Main(id)
162        } else {
163            khive_storage::tx_registry::TxOriginFilter::Secondary(id)
164        }),
165        khive_storage::tx_registry::TxOrigin::Memory
166        | khive_storage::tx_registry::TxOrigin::Unscoped => None,
167    };
168    // ADR-091 Amendment 2 Plank B: the checkpoint pool is only ever wired for
169    // file-backed backends (`checkpoint_pool_for`), so `is_file_backed: true`
170    // is always correct here. `canonical_path()` (not `pool.config().path`)
171    // so the sidecar directory is keyed off the same minted identity every
172    // alias of this backend's configured path converges to.
173    #[cfg(unix)]
174    let mut walpin_state =
175        WalpinSidecarState::new(pool.canonical_path(), true, "daemon", config.interval);
176    #[cfg(unix)]
177    if let Some(sidecar) = walpin_state.as_mut() {
178        sidecar.register_beacon().await;
179    }
180
181    // Opened once here, at task startup; `ensure_open` is a no-op in steady
182    // state and only reopens after a connection-level failure or (for an
183    // in-memory/read-only pool) retries the open on every subsequent tick.
184    let mut checkpoint_conn = CheckpointConnection::new();
185    checkpoint_conn.ensure_open(&pool);
186    // FTS5 segment maintenance uses an admitted write owner at its own
187    // cadence. Each due call performs at most one bounded
188    // merge step on one table and refuses immediately when another writer
189    // owns SQLite's write lock.
190    let mut fts_maintenance_config = crate::fts_maintenance::FtsMaintenanceConfig::from_env();
191    // Secondary backends have independent schemas (for example the code-map
192    // database) and are not required to contain the substrate FTS tables.
193    // Exactly the main backend owns this derived-index maintenance.
194    fts_maintenance_config.enabled &= is_main;
195    let mut fts_maintenance_state =
196        crate::fts_maintenance::FtsMaintenanceState::new(Instant::now());
197
198    loop {
199        // A closed sender (the daemon returning without an explicit send)
200        // makes `changed()` resolve with `Err` immediately, which `select!`
201        // treats as ready — so shutdown is observed either way, not just on
202        // an explicit send.
203        tokio::select! {
204            _ = interval.tick() => {}
205            _ = shutdown_rx.changed() => break,
206        }
207
208        #[cfg(unix)]
209        truncate_state.begin_tick();
210
211        #[cfg(unix)]
212        let mut pending_sidecar_attribution = None;
213
214        let tick = if checkpoint_conn.ensure_open(&pool).is_none() {
215            note_checkpoint_skipped();
216            CheckpointTick::Skipped
217        } else {
218            // `ensure_open` above just confirmed a connection is open. Take
219            // ownership of it so the checkpoint cycle and the FTS maintenance
220            // step below can each move it onto a blocking thread; every path
221            // either restores it to `checkpoint_conn` or lets it drop, which is
222            // the moved-ownership equivalent of the former `drop_connection()`
223            // call.
224            let conn = checkpoint_conn
225                .conn
226                .take()
227                .expect("ensure_open just confirmed a connection is open");
228            match off_worker::run_checkpoint_core_off_worker(
229                Arc::clone(&pool),
230                conn,
231                config.clone(),
232                truncate_state,
233            )
234            .await
235            {
236                Ok((conn, state, Ok(outcome))) => {
237                    truncate_state = state;
238                    #[cfg(unix)]
239                    {
240                        pending_sidecar_attribution = outcome.sidecar_attribution;
241                    }
242                    #[cfg(not(unix))]
243                    let _ = outcome.sidecar_attribution;
244
245                    // Restore the recovery file before starting independent
246                    // FTS work. Only a due tick constructs an admitted writer
247                    // on a blocking thread; other ticks record a no-op.
248                    checkpoint_conn.conn = Some(conn);
249                    let fts_result = if !fts_maintenance_state
250                        .is_due(&fts_maintenance_config, Instant::now())
251                    {
252                        Ok(None)
253                    } else {
254                        match run_fts_maintenance_off_worker(
255                            Arc::clone(&pool),
256                            fts_maintenance_config.clone(),
257                            fts_maintenance_state,
258                            Instant::now(),
259                        )
260                        .await
261                        {
262                            Ok((state, fts_result)) => {
263                                fts_maintenance_state = state;
264                                fts_result
265                            }
266                            Err(join_err) => {
267                                // The step panicked on the blocking thread. The
268                                // scheduler state moved into it is gone; its
269                                // admitted writer has settled. The independent
270                                // checkpoint connection remains usable.
271                                // The checkpoint pragma itself already succeeded.
272                                fts_maintenance_state =
273                                    crate::fts_maintenance::FtsMaintenanceState::new(Instant::now());
274                                Err(format!(
275                                    "bounded FTS5 segment maintenance task panicked: {join_err}"
276                                ))
277                            }
278                        }
279                    };
280
281                    match fts_result {
282                        Ok(Some(step)) => match step.outcome {
283                            crate::fts_maintenance::FtsMaintenanceOutcome::Worked => {
284                                tracing::info!(target: "khive_db::checkpoint",
285                                    table = step.table,
286                                    requested_pages = step.requested_pages,
287                                    segments_before = step.segments_before,
288                                    segments_after = step.segments_after,
289                                    "bounded FTS5 segment maintenance made progress"
290                                );
291                            }
292                            crate::fts_maintenance::FtsMaintenanceOutcome::Busy => {
293                                tracing::debug!(target: "khive_db::checkpoint",
294                                    table = step.table,
295                                    requested_pages = step.requested_pages,
296                                    segments = step.segments_before,
297                                    "bounded FTS5 segment maintenance skipped a busy writer"
298                                );
299                            }
300                            crate::fts_maintenance::FtsMaintenanceOutcome::Noop
301                            | crate::fts_maintenance::FtsMaintenanceOutcome::BelowThreshold => {
302                                tracing::debug!(target: "khive_db::checkpoint",
303                                    table = step.table,
304                                    outcome = ?step.outcome,
305                                    segments = step.segments_before,
306                                    "bounded FTS5 segment maintenance had no work"
307                                );
308                            }
309                        },
310                        Ok(None) => {}
311                        Err(error) => {
312                            // The checkpoint pragma already succeeded. An FTS
313                            // structure/read/merge error is an independent,
314                            // best-effort maintenance failure and must not make
315                            // the task discard an otherwise healthy connection.
316                            tracing::warn!(target: "khive_db::checkpoint",
317                                error = %error,
318                                "bounded FTS5 segment maintenance failed"
319                            );
320                        }
321                    }
322                    match outcome.wal_pages {
323                        Some(wal_pages) => CheckpointTick::Observed(wal_pages),
324                        None => {
325                            note_checkpoint_skipped();
326                            CheckpointTick::Skipped
327                        }
328                    }
329                }
330                Ok((_conn, state, Err(e))) => {
331                    truncate_state = state;
332                    tracing::warn!(target: "khive_db::checkpoint",
333                        error = %e,
334                        "dedicated checkpoint connection failed a pragma; \
335                         dropping it for a fresh reopen next tick"
336                    );
337                    note_checkpoint_skipped();
338                    CheckpointTick::Skipped
339                }
340                Err(panicked) => {
341                    // The cycle panicked: its connection is gone (reopened next tick) and the
342                    // escalation state is the one it was handed, counted as a TRUNCATE attempt.
343                    truncate_state = panicked.truncate_state;
344                    tracing::warn!(target: "khive_db::checkpoint",
345                        error = %panicked.join_error,
346                        "WAL checkpoint cycle panicked on its blocking thread; \
347                         dropping the connection for a fresh reopen next tick"
348                    );
349                    note_checkpoint_skipped();
350                    CheckpointTick::Skipped
351                }
352            }
353        };
354
355        // A no-progress or unmeasured TRUNCATE returns a bounded attribution
356        // request alongside the core outcome. Consume it before any
357        // report-derived decision or ordinary housekeeping for this tick.
358        // The await is intentional: enumeration may perform up to 512
359        // filesystem reads/classifications, so none of that work is allowed
360        // to run on this Tokio worker, while one-pass-per-tick ordering still
361        // requires the result (or an honest worker/enumeration failure) before
362        // the fallback housekeeping arm is considered.
363        #[cfg(unix)]
364        if let Err(error) =
365            complete_walpin_attribution(pending_sidecar_attribution, &mut truncate_state).await
366        {
367            tracing::warn!(target: "khive_db::checkpoint",
368                error = %error,
369                failure_kind = error.kind(),
370                "ADR-091 Amendment 2 Plank B: no-progress sidecar attribution failed"
371            );
372        }
373
374        // ADR-091 Plank 1: age-based sweep over the registry's oldest entry
375        // MUST run on every tick, including a Skipped one — deliberately
376        // BEFORE the Skipped early-continue below. Since the dedicated
377        // checkpoint connection amendment, a `Skipped` tick means that
378        // connection was unavailable or its PASSIVE result was busy, not that
379        // some registered span held the pool's writer mutex (a checkpoint
380        // tick no longer touches it at all) — but the sweep must not go blind for the
381        // duration of that outage, and the two failure surfaces are
382        // independent: a registry span can go stale
383        // (KHIVE_TX_WARN_SECS / KHIVE_TX_MAX_AGE_SECS) while wal_pages sits
384        // well under warn_pages, or while the checkpoint connection itself is
385        // down. Edge-triggered per rung, same debounce idiom as the severity
386        // ladder below, so a sustained stale span logs once per rung rather
387        // than once per tick.
388        reader_checkout_state.sweep_at(&pool, Instant::now());
389        let oldest_tx = tx_filter
390            .as_ref()
391            .and_then(khive_storage::tx_registry::oldest_for);
392        for emission in tx_age_state.observe(
393            oldest_tx.as_ref().map(|s| (s.id, s.age, s.label.clone())),
394            config.tx_warn_secs,
395            config.tx_max_age_secs,
396        ) {
397            log_tx_age_emission(&emission);
398        }
399        // ADR-091 Amendment 2 Plank B: refresh (or clear) this daemon
400        // process's own walpin heartbeat on the same cadence, so its own
401        // pin — if any — is attributable the same way a session's is.
402        #[cfg(unix)]
403        if let Some(sidecar) = walpin_state.as_mut() {
404            sidecar
405                .observe(oldest_tx.clone(), config.tx_warn_secs)
406                .await;
407            let _ = run_walpin_housekeeping_if_due(
408                sidecar,
409                &mut truncate_state,
410                legacy_walpin_fallback_interval,
411            )
412            .await;
413        }
414
415        // Skipped ticks leave crossing state unchanged — a busy tick must not
416        // re-arm the rate limit while WAL pressure is still elevated.
417        let wal_pages = match tick {
418            CheckpointTick::Skipped => continue,
419            CheckpointTick::Observed(n) => n,
420        };
421
422        let above_warn = wal_pages >= config.warn_pages;
423        let above_high_water = wal_pages >= config.high_water_pages;
424        let above_truncate_high_water = wal_pages >= config.truncate_high_water_pages;
425        note_checkpoint_pressure_observation(above_warn, was_observed_above_warn);
426        was_observed_above_warn = above_warn;
427
428        // Per-tick debug for the oldest open entry always fires (cheap —
429        // reuses this tick's already-computed `oldest_tx`); the two
430        // `warn!`-level registry logs below are gated on the SAME crossing
431        // state as the WAL-threshold WARNs above, so sustained pressure
432        // logs once per crossing, not once per tick.
433        log_tx_registry_oldest_debug(wal_pages, oldest_tx.as_ref());
434
435        // ADR-091 severity ladder: INFO on the first below→above crossing,
436        // WARN once `warn_sustained_cycles` consecutive ticks stay elevated.
437        // The oldest-entry registry WARN rides the same INFO edge the old
438        // binary crossing_warn used to gate on.
439        for emission in severity_state.observe_wal_pages(wal_pages, &config) {
440            match emission.rung {
441                CheckpointSeverityRung::Info => {
442                    log_tx_registry_oldest_warn(wal_pages, oldest_tx.as_ref());
443                    tracing::info!(target: "khive_db::checkpoint",
444                        wal_pages = emission.wal_pages,
445                        warn_threshold = emission.threshold_pages,
446                        "WAL page count crossed warn threshold"
447                    );
448                }
449                CheckpointSeverityRung::Warn => {
450                    tracing::warn!(target: "khive_db::checkpoint",
451                        wal_pages = emission.wal_pages,
452                        warn_threshold = emission.threshold_pages,
453                        consecutive_cycles = emission.consecutive_cycles,
454                        "WAL page count failed to drain below warn threshold"
455                    );
456                }
457                CheckpointSeverityRung::Alarm => {
458                    // Never produced by `observe_wal_pages`; see its doc.
459                }
460            }
461        }
462
463        let high_water_crossed = crossing_warn(above_high_water, &mut was_above_high_water);
464        if high_water_crossed {
465            log_tx_registry_snapshot_warn(wal_pages);
466            log_wal_high_water_warn(
467                wal_pages,
468                config.high_water_pages,
469                oldest_tx.as_ref(),
470                config.tx_warn_secs,
471            );
472        }
473
474        // ADR-094/#1838, #1857: one elevation row and one recovery summary
475        // per genuinely continuous episode. Sustained elevated ticks update
476        // only the bounded in-memory aggregate and process diagnostics
477        // above; a dropped recovery handoff must not fold the next,
478        // separate, pressure incident into this episode's aggregate.
479        observe_checkpoint_pressure_tick(
480            above_warn,
481            wal_pages,
482            above_high_water,
483            above_truncate_high_water,
484            &config,
485            &mut event_elevation_open,
486            &mut pressure_episode,
487            &mut pending_recovery,
488            |payload| {
489                lifecycle_emitter
490                    .try_emit(khive_types::EventKind::CheckpointOutcomeRecorded, payload)
491            },
492        );
493    }
494
495    lifecycle_emitter.shutdown().await;
496
497    #[cfg(unix)]
498    if let Some(sidecar) = walpin_state.as_mut() {
499        sidecar.shutdown().await;
500    }
501}
502
503/// Whether a `CheckpointOutcomeRecorded` transition should be enqueued for
504/// this tick. Repeated observations in either state aggregate in memory;
505/// only elevation and recovery edges reach the primary store.
506pub(super) fn checkpoint_outcome_should_emit(above_warn: bool, was_elevated: bool) -> bool {
507    above_warn != was_elevated
508}
509
510/// Advance the pressure-episode/lifecycle-emission state machine for one
511/// observed tick. `try_emit` mirrors [`CheckpointLifecycleEmitter::try_emit`]
512/// — `true` means the row was handed off, `false` means the queue was full
513/// or closed.
514///
515/// #1857: on a dropped recovery handoff (`try_emit` returns `false` while
516/// `above_warn` is `false`), the closed episode's summary is stashed in
517/// `pending_recovery` for retry on later ticks — flushed here before this
518/// tick's own transition is evaluated — instead of leaving
519/// `event_elevation_open` and `pressure_episode` open for the next elevated
520/// tick to silently extend, which would report two separate pressure
521/// incidents as one merged episode.
522#[allow(clippy::too_many_arguments)]
523pub(super) fn observe_checkpoint_pressure_tick(
524    above_warn: bool,
525    wal_pages: u64,
526    above_high_water: bool,
527    above_truncate_high_water: bool,
528    config: &CheckpointConfig,
529    event_elevation_open: &mut bool,
530    pressure_episode: &mut Option<CheckpointPressureEpisode>,
531    pending_recovery: &mut Option<khive_storage::CheckpointOutcomeRecordedPayload>,
532    mut try_emit: impl FnMut(khive_storage::CheckpointOutcomeRecordedPayload) -> bool,
533) {
534    // An undelivered recovery summary is a BARRIER, not merely a retry:
535    // lifecycle consumers assert on the ordered event history (ADR-094), so
536    // a later episode's opening must never be appended ahead of an earlier
537    // episode's recovery. If the retry fails, the in-memory aggregate still
538    // advances below, but no other emission is attempted this tick — a
539    // deferred opening or recovery re-derives from state on a later tick,
540    // after the pending summary has been delivered in order.
541    let pending_blocks_emission = if let Some(payload) = pending_recovery.clone() {
542        if try_emit(payload) {
543            *pending_recovery = None;
544            false
545        } else {
546            true
547        }
548    } else {
549        false
550    };
551
552    if above_warn {
553        match pressure_episode.as_mut() {
554            Some(episode) => episode.observe(wal_pages),
555            None => *pressure_episode = Some(CheckpointPressureEpisode::start(wal_pages)),
556        }
557    } else if !*event_elevation_open {
558        // No elevation row reached the bounded handoff, so from any
559        // consumer's view this episode never opened; discarding it keeps
560        // the delivered history self-consistent. When the discard happens
561        // because the barrier suppressed the opening attempt entirely, the
562        // loss would otherwise be invisible even to the drop counters that
563        // record failed attempts, so it is counted and logged here.
564        if pending_blocks_emission && pressure_episode.is_some() {
565            CHECKPOINT_LIFECYCLE_ENQUEUE_DROPS.fetch_add(1, Ordering::Relaxed);
566            tracing::warn!(target: "khive_db::checkpoint",
567                wal_pages,
568                "checkpoint pressure episode elapsed unreported behind an undelivered recovery summary"
569            );
570        }
571        *pressure_episode = None;
572    }
573
574    if pending_blocks_emission || !checkpoint_outcome_should_emit(above_warn, *event_elevation_open)
575    {
576        return;
577    }
578    let Some(episode) = *pressure_episode else {
579        tracing::warn!(target: "khive_db::checkpoint",
580            above_warn,
581            event_elevation_open = *event_elevation_open,
582            "checkpoint pressure transition has no episode aggregate"
583        );
584        return;
585    };
586    let payload = khive_storage::CheckpointOutcomeRecordedPayload {
587        wal_pages,
588        warn_pages: config.warn_pages,
589        high_water_pages: config.high_water_pages,
590        truncate_high_water_pages: config.truncate_high_water_pages,
591        above_warn,
592        above_high_water,
593        above_truncate_high_water,
594        episode_elevated_ticks: Some(episode.elevated_ticks),
595        episode_peak_wal_pages: Some(episode.peak_wal_pages),
596    };
597    if try_emit(payload.clone()) {
598        *event_elevation_open = above_warn;
599        if !above_warn {
600            *pressure_episode = None;
601        }
602    } else if !above_warn {
603        // The recovery handoff was dropped. Close this episode locally
604        // anyway — `event_elevation_open` MUST NOT stay true, or the next
605        // elevated tick would extend this (already finished) episode's
606        // aggregate instead of starting a fresh one for what is genuinely a
607        // new pressure incident. The dropped summary itself isn't thrown
608        // away: it is stashed in `pending_recovery` and delivered on a
609        // later tick, ahead of (and as a barrier to) every subsequent
610        // emission, so lifecycle ordering survives the retry. The slot is
611        // structurally empty here: a tick that entered with an undelivered
612        // summary returned at the barrier above and never reached this arm.
613        debug_assert!(
614            pending_recovery.is_none(),
615            "recovery emission attempted while an earlier summary was still pending"
616        );
617        *event_elevation_open = false;
618        *pressure_episode = None;
619        *pending_recovery = Some(payload);
620    }
621}