返回 CodeWhale
compaction_archive.rs
根目录 / crates / engine / src / compaction_archive.rs
1 //! Model-facing view of the pre-compaction transcript.
2 //!
3 //! Compaction already persists the complete history before replacing it, in
4 //! `artifacts/context-transfer-<checkpoint>.json`. This module turns those
5 //! snapshots into addressable entries. An id hashes the message structure —
6 //! role plus block kinds, block ids and text — so the same message keeps one id
7 //! across cumulative snapshots, while two separate calls that happened to render
8 //! identically stay distinct.
9 //!
10 //! Known limits: thinking blocks are not archived and images render as their
11 //! url only; two messages whose blocks are byte-identical are one entry, so a
12 //! repeated `continue` shows up once; a tool result that a later pruning pass
13 //! rewrote to a stub is a second entry, because its text is no longer the same;
14 //! only the most recent [`MAX_LOAD_BYTES`] of snapshots are loaded; every tool
15 //! call reloads and re-parses the snapshots, so paging through one large entry
16 //! repeats that work; and snapshots are keyed by the engine's session namespace,
17 //! which a sub-agent inherits from its caller, so one archive can hold snapshots
18 //! written by several engines of the same session tree. A snippet marks its hit
19 //! with `<<` and `>>`; text that already contains those characters reads
20 //! ambiguously, and `match_offset` is the precise locator. Ids keep 48 bits, so
21 //! among a million messages a birthday collision is roughly 0.2% likely, and
22 //! `load` keeps the first entry for a repeated id; two executions of one tool
23 //! call that share provider id, name and input are one entry because
24 //! `execution_id` and `caller` stay out of the hash. Each message is masked
25 //! whole, before search or paging, with the credential shapes and the
26 //! currently configured secret values that `codewhale sessions scrub-secrets`
27 //! uses, so a page boundary or snippet marker cannot split a credential past
28 //! the mask; a bare secret absent from current configuration is not masked.
29 //! A `/fork` starts a new session namespace, so the fork cannot read the
30 //! archive its inherited handoff note refers to.
31
32 use std::io::{self, Read};
33 use std::path::Path;
34 use std::time::UNIX_EPOCH;
35
36 use codewhale_models::{ContentBlock, Message};
37 use sha2::{Digest, Sha256};
38
39 pub const TRANSFER_DIR_NAME: &str = "artifacts";
40 const TRANSFER_PREFIX: &str = "context-transfer-";
41 const TRANSFER_SUFFIX: &str = ".json";
42 const ID_HEX_LEN: usize = 12;
43 const MAX_LOAD_BYTES: u64 = 64 * 1024 * 1024;
44
45 /// One addressable message from a pre-compaction snapshot.
46 #[derive(Debug, Clone)]
47 pub struct ArchiveEntry {
48 pub id: String,
49 pub seq: usize,
50 pub role: String,
51 pub at: u64,
52 pub text: String,
53 }
54
55 /// What a load covered, so the tools can say what they could and could not see.
56 #[derive(Debug, Clone)]
57 pub struct ArchiveLoad {
58 pub entries: Vec<ArchiveEntry>,
59 pub snapshots: usize,
60 pub skipped_snapshots: usize,
61 pub truncation_note: Option<String>,
62 pub directory_present: bool,
63 }
64
65 /// Render one message into the plain text an archive entry stores.
66 #[must_use]
67 pub fn render_message(message: &Message) -> String {
68 let mut parts: Vec<String> = Vec::new();
69 for block in &message.content {
70 match block {
71 ContentBlock::Text { text, .. } => {
72 if !text.trim().is_empty() {
73 parts.push(text.clone());
74 }
75 }
76 ContentBlock::ToolUse {
77 id, name, input, ..
78 } => {
79 parts.push(format!("[tool_use {name}#{id}] {input}"));
80 }
81 ContentBlock::ServerToolUse {
82 id, name, input, ..
83 } => {
84 parts.push(format!("[server_tool_use {name}#{id}] {input}"));
85 }
86 ContentBlock::ToolResult {
87 tool_use_id,
88 content,
89 is_error,
90 ..
91 } => {
92 let label = if is_error.unwrap_or(false) {
93 "[tool_result error]"
94 } else {
95 "[tool_result]"
96 };
97 parts.push(format!("{label} {tool_use_id}\n{content}"));
98 }
99 ContentBlock::ToolSearchToolResult {
100 tool_use_id,
101 content,
102 } => {
103 parts.push(format!(
104 "[tool_search_tool_result] {tool_use_id}\n{content}"
105 ));
106 }
107 ContentBlock::CodeExecutionToolResult {
108 tool_use_id,
109 content,
110 } => {
111 parts.push(format!(
112 "[code_execution_tool_result] {tool_use_id}\n{content}"
113 ));
114 }
115 ContentBlock::ImageUrl { image_url } => {
116 parts.push(render_image(&image_url.url));
117 }
118 _ => {}
119 }
120 }
121 parts.join("\n\n")
122 }
123
124 fn render_image(url: &str) -> String {
125 let mut head: String = url.chars().take(120).collect();
126 if head.chars().count() < url.chars().count() {
127 head.push('\u{2026}');
128 }
129 format!("[image] {head}")
130 }
131
132 /// The structural id a message is addressed by.
133 ///
134 /// Hashing the rendered text would fold two separate tool calls that happened to
135 /// render the same, orphaning the second call's result. Hashing the blocks keeps
136 /// a call distinct by its provider id while still giving the same message the
137 /// same id in every cumulative snapshot.
138 #[must_use]
139 pub fn message_id(role: &str, message: &Message) -> String {
140 let mut hasher = Sha256::new();
141 hash_str(&mut hasher, role);
142 for block in &message.content {
143 hasher.update([0u8]);
144 match block {
145 ContentBlock::Text { text, .. } => {
146 hasher.update(b"text");
147 hash_str(&mut hasher, text);
148 }
149 ContentBlock::Thinking { .. } => hasher.update(b"thinking"),
150 ContentBlock::ImageUrl { image_url } => {
151 hasher.update(b"image");
152 hash_str(&mut hasher, &image_url.url);
153 }
154 ContentBlock::ToolUse {
155 id, name, input, ..
156 } => {
157 hasher.update(b"tool_use");
158 hash_str(&mut hasher, id);
159 hash_str(&mut hasher, name);
160 hash_json(&mut hasher, input);
161 }
162 ContentBlock::ServerToolUse {
163 id, name, input, ..
164 } => {
165 hasher.update(b"server_tool_use");
166 hash_str(&mut hasher, id);
167 hash_str(&mut hasher, name);
168 hash_json(&mut hasher, input);
169 }
170 ContentBlock::ToolResult {
171 tool_use_id,
172 content,
173 is_error,
174 content_blocks,
175 ..
176 } => {
177 hasher.update(b"tool_result");
178 hash_str(&mut hasher, tool_use_id);
179 hash_str(&mut hasher, content);
180 hasher.update([u8::from(is_error.unwrap_or(false))]);
181 if let Some(blocks) = content_blocks {
182 for block in blocks {
183 hash_json(&mut hasher, block);
184 }
185 }
186 }
187 ContentBlock::ToolSearchToolResult {
188 tool_use_id,
189 content,
190 } => {
191 hasher.update(b"tool_search_tool_result");
192 hash_str(&mut hasher, tool_use_id);
193 hash_json(&mut hasher, content);
194 }
195 ContentBlock::CodeExecutionToolResult {
196 tool_use_id,
197 content,
198 } => {
199 hasher.update(b"code_execution_tool_result");
200 hash_str(&mut hasher, tool_use_id);
201 hash_json(&mut hasher, content);
202 }
203 ContentBlock::WebSearchToolResult {
204 tool_use_id,
205 content,
206 ..
207 } => {
208 hasher.update(b"web_search_tool_result");
209 hash_str(&mut hasher, tool_use_id);
210 hash_json(&mut hasher, content);
211 }
212 ContentBlock::WebFetchToolResult {
213 tool_use_id,
214 content,
215 ..
216 } => {
217 hasher.update(b"web_fetch_tool_result");
218 hash_str(&mut hasher, tool_use_id);
219 hash_json(&mut hasher, content);
220 }
221 ContentBlock::WebSearchCall { id, kind, .. } => {
222 hasher.update(b"web_search_call");
223 hash_str(&mut hasher, id);
224 hash_str(&mut hasher, kind.as_deref().unwrap_or(""));
225 }
226 ContentBlock::ServerToolCalls { steps } => {
227 hasher.update(b"server_tool_calls");
228 for step in steps {
229 hash_json(&mut hasher, step);
230 }
231 }
232 ContentBlock::File { file_id } => {
233 hasher.update(b"file");
234 hash_str(&mut hasher, file_id);
235 }
236 }
237 }
238 hex12(&hasher.finalize())
239 }
240
241 /// Feed one outer string with its length in front, so two different sequences of
242 /// fields cannot hash the same by bare concatenation (`id="ab" name="c"` versus
243 /// `id="a" name="bc"`).
244 fn hash_str(hasher: &mut Sha256, value: &str) {
245 hasher.update((value.len() as u64).to_le_bytes());
246 hasher.update(value.as_bytes());
247 }
248
249 /// Feed JSON to the hasher as a prefix code: sorted keys, an item count for
250 /// arrays and objects, and a byte length for every string and number. Two equal
251 /// values hash equally and two different values cannot collide by concatenation.
252 /// Strings the caller feeds around a value must be length-prefixed too; see
253 /// [`hash_str`].
254 fn hash_json(hasher: &mut Sha256, value: &serde_json::Value) {
255 match value {
256 serde_json::Value::Null => hasher.update(b"null"),
257 serde_json::Value::Bool(flag) => {
258 hasher.update(if *flag { &b"true"[..] } else { &b"false"[..] })
259 }
260 serde_json::Value::Number(number) => {
261 let text = number.to_string();
262 hasher.update(b"num");
263 hasher.update((text.len() as u64).to_le_bytes());
264 hasher.update(text.as_bytes());
265 }
266 serde_json::Value::String(text) => {
267 hasher.update(b"str");
268 hasher.update((text.len() as u64).to_le_bytes());
269 hasher.update(text.as_bytes());
270 }
271 serde_json::Value::Array(items) => {
272 hasher.update(b"arr");
273 hasher.update((items.len() as u64).to_le_bytes());
274 for item in items {
275 hash_json(hasher, item);
276 }
277 }
278 serde_json::Value::Object(map) => {
279 hasher.update(b"obj");
280 hasher.update((map.len() as u64).to_le_bytes());
281 let mut entries: Vec<(&String, &serde_json::Value)> = map.iter().collect();
282 entries.sort_by(|a, b| a.0.cmp(b.0));
283 for (key, item) in entries {
284 hasher.update((key.len() as u64).to_le_bytes());
285 hasher.update(key.as_bytes());
286 hash_json(hasher, item);
287 }
288 }
289 }
290 }
291
292 fn hex12(digest: &[u8]) -> String {
293 let mut id = String::with_capacity(ID_HEX_LEN);
294 for byte in &digest[..ID_HEX_LEN / 2] {
295 id.push_str(&format!("{byte:02x}"));
296 }
297 id
298 }
299
300 fn is_transfer_snapshot(name: &str) -> bool {
301 name.starts_with(TRANSFER_PREFIX)
302 && name.ends_with(TRANSFER_SUFFIX)
303 && name
304 .chars()
305 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
306 }
307
308 fn snapshot_dir(session_id: &str) -> Option<std::path::PathBuf> {
309 if !codewhale_runtime::artifacts::is_valid_session_id(session_id) {
310 return None;
311 }
312 codewhale_runtime::artifacts::artifact_sessions_root()
313 .map(|root| root.join(session_id).join(TRANSFER_DIR_NAME))
314 }
315
316 struct Snapshot {
317 name: String,
318 bytes: u64,
319 modified: u64,
320 }
321
322 fn list_snapshots(session_id: &str) -> io::Result<(Vec<Snapshot>, bool)> {
323 let Some(dir) = snapshot_dir(session_id) else {
324 return Ok((Vec::new(), false));
325 };
326 let read = match std::fs::read_dir(&dir) {
327 Ok(read) => read,
328 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok((Vec::new(), false)),
329 Err(error) => return Err(error),
330 };
331 let mut snapshots: Vec<Snapshot> = read
332 .flatten()
333 .filter_map(|entry| {
334 let name = entry.file_name().to_string_lossy().to_string();
335 if !is_transfer_snapshot(&name) || !entry.file_type().ok()?.is_file() {
336 return None;
337 }
338 let metadata = entry.metadata().ok()?;
339 let modified = metadata
340 .modified()
341 .ok()
342 .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
343 .map(|elapsed| elapsed.as_secs())
344 .unwrap_or_default();
345 Some(Snapshot {
346 name,
347 bytes: metadata.len(),
348 modified,
349 })
350 })
351 .collect();
352 snapshots.sort_by_key(|snapshot| (snapshot.modified, snapshot.name.clone()));
353 Ok((snapshots, true))
354 }
355
356 fn read_snapshot(session_id: &str, name: &str) -> io::Result<Vec<Message>> {
357 let relative = Path::new(TRANSFER_DIR_NAME).join(name);
358 let file = codewhale_runtime::artifacts::open_session_relative(session_id, &relative, false)?;
359 let mut body = Vec::new();
360 file.open_file()?.read_to_end(&mut body)?;
361 serde_json::from_slice::<Vec<Message>>(&body).map_err(io::Error::other)
362 }
363
364 /// Load every reachable snapshot for this session, oldest first.
365 pub fn load(session_id: &str, secrets: &[String]) -> io::Result<ArchiveLoad> {
366 let (snapshots, directory_present) = list_snapshots(session_id)?;
367 let mut budget = MAX_LOAD_BYTES;
368 let mut selected: Vec<&Snapshot> = Vec::new();
369 let mut skipped = 0usize;
370 let mut budget_skipped = 0usize;
371 let mut unreadable = 0usize;
372 for snapshot in snapshots.iter().rev() {
373 if snapshot.bytes > budget {
374 skipped += 1;
375 budget_skipped += 1;
376 continue;
377 }
378 budget -= snapshot.bytes;
379 selected.push(snapshot);
380 }
381 selected.reverse();
382
383 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
384 let mut entries: Vec<ArchiveEntry> = Vec::new();
385 let mut first_error: Option<String> = None;
386 for snapshot in &selected {
387 let messages = match read_snapshot(session_id, &snapshot.name) {
388 Ok(messages) => messages,
389 Err(error) => {
390 skipped += 1;
391 unreadable += 1;
392 if first_error.is_none() {
393 first_error = Some(format!("{}: {error}", snapshot.name));
394 }
395 continue;
396 }
397 };
398 for (seq, message) in messages.iter().enumerate() {
399 let role = message.role.as_str().to_ascii_lowercase();
400 let text = crate::client::redact_model_bound_text(&render_message(message), secrets);
401 if text.trim().is_empty() {
402 continue;
403 }
404 let id = message_id(&role, message);
405 if !seen.insert(id.clone()) {
406 continue;
407 }
408 entries.push(ArchiveEntry {
409 id,
410 seq,
411 role,
412 at: snapshot.modified,
413 text,
414 });
415 }
416 }
417 entries.sort_by_key(|entry| (entry.at, entry.seq));
418 let mut notes: Vec<String> = Vec::new();
419 if budget_skipped > 0 {
420 notes.push(format!(
421 "{budget_skipped} pre-compaction snapshots exceeded the {MAX_LOAD_BYTES}-byte load budget and were skipped"
422 ));
423 }
424 if unreadable > 0 {
425 notes.push(match &first_error {
426 Some(error) => format!("{unreadable} snapshots could not be decoded (first: {error})"),
427 None => format!("{unreadable} snapshots could not be decoded"),
428 });
429 }
430 Ok(ArchiveLoad {
431 entries,
432 snapshots: selected.len(),
433 skipped_snapshots: skipped,
434 truncation_note: (!notes.is_empty()).then(|| notes.join("; ")),
435 directory_present,
436 })
437 }
438
439 /// Resolve an id, or a unique id prefix, to one archived message.
440 pub fn find_entry<'a>(
441 entries: &'a [ArchiveEntry],
442 reference: &str,
443 ) -> Result<&'a ArchiveEntry, String> {
444 let reference = reference
445 .trim()
446 .trim_start_matches('#')
447 .to_ascii_lowercase();
448 if reference.is_empty() {
449 return Err("an archive id is required".to_string());
450 }
451 if let Some(entry) = entries.iter().find(|entry| entry.id == reference) {
452 return Ok(entry);
453 }
454 let matches: Vec<&ArchiveEntry> = entries
455 .iter()
456 .filter(|entry| entry.id.starts_with(&reference))
457 .collect();
458 match matches.as_slice() {
459 [] => Err(format!(
460 "no archived message matches `{reference}`; use context_archive_search to find one"
461 )),
462 [only] => Ok(*only),
463 several => Err(format!(
464 "`{reference}` is ambiguous: {} archived messages start with it; use more characters",
465 several.len()
466 )),
467 }
468 }
469
470 /// One search hit: the message, where in it the query landed, and a snippet.
471 pub struct SearchHit<'a> {
472 pub entry: &'a ArchiveEntry,
473 pub char_offset: usize,
474 pub snippet: String,
475 }
476
477 /// ASCII-case-insensitive substring search across archived messages.
478 ///
479 /// `char_offset` is a character offset into `entry.text`, so a caller can hand
480 /// it straight to [`slice_chars`]. `skip` pages through further matches while
481 /// `total` keeps counting every hit.
482 #[must_use]
483 pub fn search_entries<'a>(
484 entries: &'a [ArchiveEntry],
485 query: &str,
486 skip: usize,
487 limit: usize,
488 ) -> (Vec<SearchHit<'a>>, usize) {
489 let needle = query.trim().to_ascii_lowercase();
490 if needle.is_empty() {
491 return (Vec::new(), 0);
492 }
493 let mut hits = Vec::new();
494 let mut total = 0usize;
495 for entry in entries {
496 let haystack = entry.text.to_ascii_lowercase();
497 let Some(position) = haystack.find(&needle) else {
498 continue;
499 };
500 total += 1;
501 if total <= skip || hits.len() >= limit {
502 continue;
503 }
504 hits.push(SearchHit {
505 entry,
506 char_offset: entry.text[..position].chars().count(),
507 snippet: snippet(&entry.text, position, needle.len()),
508 });
509 }
510 (hits, total)
511 }
512
513 const SNIPPET_RADIUS_CHARS: usize = 80;
514
515 fn ceil_char_boundary(text: &str, mut index: usize) -> usize {
516 while index < text.len() && !text.is_char_boundary(index) {
517 index += 1;
518 }
519 index
520 }
521
522 /// A short window around one hit, marked so the model can see where it landed.
523 fn snippet(text: &str, byte_position: usize, needle_len: usize) -> String {
524 let start = text[..byte_position]
525 .char_indices()
526 .rev()
527 .nth(SNIPPET_RADIUS_CHARS)
528 .map_or(0, |(index, _)| index);
529 let hit_end = ceil_char_boundary(text, (byte_position + needle_len).min(text.len()));
530 let end = text[hit_end..]
531 .char_indices()
532 .nth(SNIPPET_RADIUS_CHARS)
533 .map_or(text.len(), |(index, _)| index + hit_end);
534 let mut out = String::new();
535 if start > 0 {
536 out.push('…');
537 }
538 out.push_str(&text[start..byte_position]);
539 out.push_str("<<");
540 out.push_str(&text[byte_position..hit_end]);
541 out.push_str(">>");
542 out.push_str(&text[hit_end..end]);
543 if end < text.len() {
544 out.push('…');
545 }
546 out
547 }
548
549 /// Slice `text` by character offset, returning the slice and its total char count.
550 #[must_use]
551 pub fn slice_chars(text: &str, offset: usize, max_chars: usize) -> (String, usize) {
552 let total = text.chars().count();
553 let slice: String = text.chars().skip(offset).take(max_chars).collect();
554 (slice, total)
555 }
556
557 #[cfg(test)]
558 mod tests {
559 use super::{hash_json, hex12};
560 use serde_json::{Map, Value, json};
561 use sha2::{Digest, Sha256};
562
563 fn digest(value: &Value) -> String {
564 let mut hasher = Sha256::new();
565 hash_json(&mut hasher, value);
566 hex12(&hasher.finalize())
567 }
568
569 fn little_endian_text(value: u64) -> String {
570 value
571 .to_le_bytes()
572 .iter()
573 .map(|byte| char::from(*byte))
574 .collect()
575 }
576
577 #[test]
578 fn a_number_cannot_swallow_the_field_after_it() {
579 let long = "x".repeat(291);
580 let tail = format!("str{}{long}", little_endian_text(295));
581 let mut left = Map::new();
582 left.insert(String::new(), json!(1));
583 left.insert(format!("\u{0}a{tail}"), json!(0));
584 let left = Value::Object(left);
585 let right = json!({ "": 10, "a": format!("{long}num0") });
586 assert_ne!(digest(&left), digest(&right));
587 }
588 }
589
589 lines RUST