Skip to main content

gadk_session/compaction/
error.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! [`CompactionError`] and its message prefix [`ERR_COMPACTION`].
17
18/// The prefix of every [`CompactionError`]'s message.
19pub const ERR_COMPACTION: &str = "context compaction failed";
20
21/// A compaction failure rather than a failure of the turn itself.
22///
23/// Compaction is bookkeeping: the turn's events are already persisted before it runs, so a
24/// failure costs a smaller prompt later, not the user's answer. It still surfaces; a caller that
25/// would rather log it than fail the turn can tell the two apart with
26/// `AgentError::is_compaction` (gadk-agent).
27#[derive(Debug)]
28pub struct CompactionError {
29    detail: String,
30    source: Option<Box<dyn std::error::Error + Send + Sync>>,
31}
32
33impl CompactionError {
34    /// Display `context compaction failed: <detail>`, no source.
35    pub fn new(detail: impl Into<String>) -> Self {
36        Self {
37            detail: detail.into(),
38            source: None,
39        }
40    }
41
42    /// Wraps `source` with context: Display
43    /// `context compaction failed: <context>: <source>`, and `source()` is `source`.
44    pub fn wrap(
45        context: impl Into<String>,
46        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
47    ) -> Self {
48        let source = source.into();
49        Self {
50            detail: format!("{}: {}", context.into(), source),
51            source: Some(source),
52        }
53    }
54
55    /// The text after the `context compaction failed: ` prefix.
56    pub fn detail(&self) -> &str {
57        &self.detail
58    }
59}
60
61impl std::fmt::Display for CompactionError {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        write!(f, "{ERR_COMPACTION}: {}", self.detail)
64    }
65}
66
67impl std::error::Error for CompactionError {
68    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
69        self.source
70            .as_deref()
71            .map(|e| e as &(dyn std::error::Error + 'static))
72    }
73}
74
75#[cfg(test)]
76#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
77mod tests {
78    use super::*;
79    use std::error::Error as _;
80
81    #[test]
82    fn new_has_go_prefix_and_no_source() {
83        let e = CompactionError::new("post-invocation: compaction panicked: boom");
84        assert_eq!(
85            e.to_string(),
86            "context compaction failed: post-invocation: compaction panicked: boom"
87        );
88        assert_eq!(e.detail(), "post-invocation: compaction panicked: boom");
89        assert!(e.source().is_none());
90    }
91
92    #[test]
93    fn wrap_keeps_the_source_chain() {
94        let e = CompactionError::wrap("failed to append the summary event", "disk full");
95        assert_eq!(
96            e.to_string(),
97            "context compaction failed: failed to append the summary event: disk full"
98        );
99        assert_eq!(e.detail(), "failed to append the summary event: disk full");
100        assert_eq!(e.source().unwrap().to_string(), "disk full");
101        assert!(e.to_string().starts_with(&format!("{ERR_COMPACTION}: ")));
102    }
103}