zeph_session/condenser.rs
1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! The [`Condenser`] contract for durable, replayable context condensation (spec §8).
5//!
6//! Condensation is distinct from live in-memory compaction (owned by `zeph-context`): it
7//! operates at the event-log level and is recorded as a [`crate::event::SessionEvent::Condensation`]
8//! event so replay can fold the same summary deterministically. This module defines the trait
9//! contract and the [`INV-SP-4`](validate_non_overlap) non-overlap guard; see
10//! [`crate::llm_condenser::LlmCondenser`] for the default implementation.
11
12use zeph_common::memory::AnchoredSummary;
13
14use crate::error::SessionError;
15use crate::event::SessionEventEnvelope;
16use crate::replay::ReconstructedState;
17
18/// The outcome of one condensation pass: the `seq` range it replaced and the resulting summary.
19#[derive(Debug, Clone)]
20pub struct CondensationResult {
21 /// `[inclusive, inclusive]` seq range replaced by `summary`.
22 pub replaced_range: (u64, u64),
23 pub summary: AnchoredSummary,
24 pub tokens_before: u32,
25 pub tokens_after: u32,
26}
27
28/// Computes whether and how to durably condense a session's event log.
29///
30/// Implementors MUST respect INV-SP-4 (spec §8.3): the range returned by [`Self::condense`] must
31/// start strictly after the caller's `last_condensed_seq` — see [`validate_non_overlap`].
32pub trait Condenser: Send + Sync {
33 /// Returns `true` if the reconstructed context has grown enough (relative to
34 /// `budget_used_fraction`, the fraction of the context budget currently consumed) to warrant
35 /// a condensation pass.
36 fn should_condense(
37 &self,
38 state: &ReconstructedState,
39 budget_used_fraction: f64,
40 ) -> impl Future<Output = bool> + Send;
41
42 /// Condense `events` (typically the tail since `last_condensed_seq`), producing a
43 /// [`CondensationResult`] whose `replaced_range` starts strictly after `last_condensed_seq`.
44 ///
45 /// # Errors
46 ///
47 /// Returns an error if summarization fails or the computed range would violate INV-SP-4.
48 fn condense(
49 &self,
50 events: &[SessionEventEnvelope],
51 last_condensed_seq: u64,
52 ) -> impl Future<Output = Result<CondensationResult, SessionError>> + Send;
53}
54
55/// Enforce INV-SP-4: a proposed `(lo, hi)` range must start strictly after `last_condensed_seq`.
56///
57/// Callers (the `Condenser` implementation and `zeph-agent-persistence`'s live-compaction hook)
58/// must call this immediately before emitting a `Condensation`/`Compaction` event, using the
59/// `last_condensed_seq` read from `acp_sessions` at the start of the computation — not a
60/// stale/cached value — to close the read-then-write race the invariant depends on.
61///
62/// `last_condensed_seq == 0` is treated as the sentinel "nothing has ever been condensed" rather
63/// than "seq 0 was already condensed" — event logs are 0-indexed (a session's first event is
64/// `seq == 0`, matching `acp_sessions.last_condensed_seq`'s migration-106 `DEFAULT 0`), so
65/// without this carve-out the very first condensation of every session — which necessarily wants
66/// to start at `lo == 0` — would be permanently rejected as "overlapping" the default. Verified
67/// empirically: `LlmCondenser::condense`'s own doc-mandated caller pattern hit exactly this
68/// before the carve-out was added (spec-068 D-11 end-to-end wiring). Residual gap: a
69/// condensation whose range happens to end exactly at `hi == 0` (only possible when
70/// `keep_recent` leaves just one message event past position 0) leaves `last_condensed_seq == 0`
71/// again, indistinguishable from "never condensed" — narrow enough in practice that resolving it
72/// properly needs an `Option<u64>` schema change; tracked as a follow-up, not blocking here.
73///
74/// # Errors
75///
76/// Returns [`SessionError::CondensationOverlap`] if `last_condensed_seq > 0 && lo <=
77/// last_condensed_seq`.
78pub fn validate_non_overlap(
79 last_condensed_seq: u64,
80 proposed_range: (u64, u64),
81) -> Result<(), SessionError> {
82 let (lo, hi) = proposed_range;
83 if last_condensed_seq > 0 && lo <= last_condensed_seq {
84 return Err(SessionError::CondensationOverlap(format!(
85 "proposed range ({lo}, {hi}) overlaps or precedes last_condensed_seq={last_condensed_seq}"
86 )));
87 }
88 Ok(())
89}
90
91#[cfg(test)]
92mod tests {
93 use super::*;
94
95 #[test]
96 fn test_inv_sp4_no_overlap() {
97 // First condensation over (1, 10) is fine when nothing has been condensed yet.
98 validate_non_overlap(0, (1, 10)).unwrap();
99
100 // A second condensation must start strictly after the first one's end.
101 validate_non_overlap(10, (11, 20)).unwrap();
102
103 // Overlapping or regressive ranges are rejected.
104 assert!(validate_non_overlap(10, (5, 15)).is_err());
105 assert!(validate_non_overlap(10, (10, 20)).is_err());
106 }
107
108 /// Regression test for the sentinel carve-out: the very first condensation of a session
109 /// necessarily starts at `seq == 0` (event logs are 0-indexed) and must not be rejected just
110 /// because `last_condensed_seq`'s default is also `0`.
111 #[test]
112 fn first_ever_condensation_may_start_at_seq_zero() {
113 validate_non_overlap(0, (0, 5)).unwrap();
114 }
115}