Skip to main content

rpi_cli/
session_gc.rs

1//! `rpi session gc` — offline compaction of retired stream frames.
2//!
3//! Fork issue DavidHinton-xcpc/pi-rust#14 §4 PR-D (write-side half). A long
4//! session's JSONL is dominated by `assistant_frame` appends that a later
5//! `clear_run` of the same run already retired; the reader no longer indexes
6//! them (#252), but the bytes stay on disk.
7//!
8//! This command strips **only** those frames' payloads; their identity rows
9//! stay on disk so ID reservations and later appends stay consistent. Runs
10//! without a `clear_run` keep
11//! every frame, because `frame_progress::salvage_run_frames` replays them after
12//! a crash. Sequences are never renumbered and the header is kept, so later
13//! appends and older binaries both stay consistent.
14//!
15//! `--dry-run` reports without writing.
16
17use std::path::{Path, PathBuf};
18
19use crate::app::{EXIT_RUNTIME, EXIT_USAGE};
20
21/// Dispatch `rpi session <subcommand>`.
22pub async fn run(args: &[String]) -> i32 {
23    match args.first().map(String::as_str) {
24        Some("gc") => {
25            let rest = &args[1..];
26            if rest.iter().any(|arg| arg == "--help" || arg == "-h") {
27                print_gc_help();
28                return 0;
29            }
30            gc(rest).await
31        }
32        Some("--help" | "-h") | None => {
33            print_help();
34            0
35        }
36        Some(other) => {
37            eprintln!("error: unknown `session` subcommand `{other}`");
38            print_help();
39            EXIT_USAGE
40        }
41    }
42}
43
44fn print_help() {
45    println!("Usage: rpi session <command>");
46    println!();
47    println!("Commands:");
48    println!("  gc [path...] [--dry-run]  Drop payloads of frames a clear_run retired");
49    println!();
50    println!("`gc` without a path uses the session directory for the current project.");
51}
52
53fn print_gc_help() {
54    println!("Usage: rpi session gc [path...] [--dry-run]");
55    println!();
56    println!("Arguments:");
57    println!("  <path>      A session .jsonl file, or a directory to scan");
58    println!("  --dry-run   Report what would be dropped without writing");
59    println!();
60    println!("Only the payloads of `assistant_frame` appends that precede a later clear_run of");
61    println!("the same run are removed; their identity rows stay reserved. Unclear runs keep");
62    println!("every frame (crash salvage).");
63}
64
65async fn gc(args: &[String]) -> i32 {
66    let dry_run = args.iter().any(|arg| arg == "--dry-run");
67    let targets: Vec<&String> = args.iter().filter(|arg| !arg.starts_with("--")).collect();
68    let files = match collect_targets(&targets) {
69        Ok(files) => files,
70        Err(error) => {
71            eprintln!("error: {error}");
72            return EXIT_RUNTIME;
73        }
74    };
75    if files.is_empty() {
76        eprintln!("error: no session files found");
77        return EXIT_RUNTIME;
78    }
79
80    let fs: std::sync::Arc<dyn rpi_tools::FileSystem> =
81        std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(
82            std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
83        ));
84    let mut total_retired = 0usize;
85    let mut total_before = 0usize;
86    let mut total_after = 0usize;
87    let mut failures = 0usize;
88    for file in &files {
89        // A rewrite takes the session's OS file lock first (the same
90        // `<session>.lock` the running CLI claims): a live writer makes gc
91        // refuse instead of racing it. A dry run reads without the lock.
92        let _lock = if dry_run {
93            None
94        } else {
95            match GcSessionLock::acquire(file) {
96                Ok(lock) => Some(lock),
97                Err(error) => {
98                    failures += 1;
99                    eprintln!("error: {}: {error}", file.display());
100                    continue;
101                }
102            }
103        };
104        match rpi_harness::session::jsonl::compact_retired_frames(
105            fs.clone(),
106            &file.to_string_lossy(),
107            dry_run,
108        )
109        .await
110        {
111            Ok(report) => {
112                total_retired += report.retired_frames;
113                total_before += report.bytes_before;
114                total_after += report.bytes_after;
115                let verb = if dry_run { "would drop" } else { "dropped" };
116                if report.would_rewrite() {
117                    println!(
118                        "{}: {verb} {} retired frame row(s); {} -> {} bytes",
119                        file.display(),
120                        report.retired_frames,
121                        report.bytes_before,
122                        report.bytes_after
123                    );
124                } else {
125                    println!("{}: nothing to drop", file.display());
126                }
127            }
128            Err(error) => {
129                failures += 1;
130                eprintln!("error: {}: {error}", file.display());
131            }
132        }
133    }
134    // Summary in a stable, greppable shape.
135    println!(
136        "summary: files={} retired={} bytes={} -> {}{}",
137        files.len(),
138        total_retired,
139        total_before,
140        total_after,
141        if dry_run { " (dry run)" } else { "" }
142    );
143    if failures > 0 {
144        EXIT_RUNTIME
145    } else {
146        0
147    }
148}
149
150/// Resolve arguments to session files. A directory is scanned one level deep
151/// (matching the on-disk `<root>/--<cwd>--/<file>.jsonl` layout). No argument
152/// means the current project's directory under the default session root.
153fn collect_targets(targets: &[&String]) -> Result<Vec<PathBuf>, String> {
154    if targets.is_empty() {
155        let cwd = std::env::current_dir().map_err(|e| format!("could not read cwd: {e}"))?;
156        let root = crate::session::default_session_dir(&cwd);
157        let project = root.join(project_session_dir_name(&cwd));
158        if !project.is_dir() {
159            return Err(format!(
160                "no session directory for this project at {}",
161                project.display()
162            ));
163        }
164        return Ok(jsonl_files_in(&project));
165    }
166
167    let mut files = Vec::new();
168    let mut missing = Vec::new();
169    for target in targets {
170        let path = Path::new(target.as_str());
171        if path.is_dir() {
172            files.extend(jsonl_files_in(path));
173        } else if path.is_file() {
174            files.push(path.to_path_buf());
175        } else {
176            missing.push(target.to_string());
177        }
178    }
179    if !missing.is_empty() {
180        return Err(format!(
181            "no such session file or directory: {}",
182            missing.join(", ")
183        ));
184    }
185    Ok(files)
186}
187
188/// Exclusive advisory lock over one session file for the duration of a gc
189/// rewrite. Same `<session>.lock` layout as `session.rs`'s
190/// `claim_session_lock`, but scoped: dropping the handle releases the lock, so
191/// each compacted file owns it only while it is being rewritten.
192struct GcSessionLock {
193    /// Held for the lock's lifetime; `fs2` releases on close.
194    _file: std::fs::File,
195}
196
197impl GcSessionLock {
198    fn acquire(session_path: &Path) -> Result<GcSessionLock, String> {
199        let canonical =
200            std::fs::canonicalize(session_path).unwrap_or_else(|_| session_path.to_path_buf());
201        let lock_path = PathBuf::from(format!("{}.lock", canonical.display()));
202        let file = std::fs::OpenOptions::new()
203            .create(true)
204            .truncate(false)
205            .write(true)
206            .open(&lock_path)
207            .map_err(|e| format!("open session lock {}: {e}", lock_path.display()))?;
208        if fs2::FileExt::try_lock_exclusive(&file).is_err() {
209            return Err(format!(
210                "session {} is already open in another rpi process",
211                session_path.display()
212            ));
213        }
214        Ok(GcSessionLock { _file: file })
215    }
216}
217
218/// `--<cwd-with-leading-/or-\\-stripped-and-/\\-:-replaced-by-->--`, mirroring the
219/// repo's `jsonlSessionDirectoryName`. Kept local because the harness export
220/// lands in a separate PR; the shape is asserted by the repo's own unit test.
221fn project_session_dir_name(cwd: &Path) -> String {
222    let text = cwd.to_string_lossy();
223    let stripped = text
224        .strip_prefix('/')
225        .or_else(|| text.strip_prefix('\\'))
226        .unwrap_or(&text);
227    let replaced: String = stripped
228        .chars()
229        .map(|c| match c {
230            '/' | '\\' | ':' => '-',
231            other => other,
232        })
233        .collect();
234    format!("--{replaced}--")
235}
236
237fn jsonl_files_in(dir: &Path) -> Vec<PathBuf> {
238    let mut files = Vec::new();
239    let Ok(entries) = std::fs::read_dir(dir) else {
240        return files;
241    };
242    for entry in entries.flatten() {
243        let path = entry.path();
244        if path.is_dir() {
245            if let Ok(inner) = std::fs::read_dir(&path) {
246                for child in inner.flatten() {
247                    push_if_session(&mut files, child.path());
248                }
249            }
250        } else {
251            push_if_session(&mut files, path);
252        }
253    }
254    files.sort();
255    files
256}
257
258fn push_if_session(files: &mut Vec<PathBuf>, path: PathBuf) {
259    let is_jsonl = path.extension().and_then(|e| e.to_str()) == Some("jsonl");
260    let is_companion = path.to_string_lossy().ends_with(".progress.jsonl");
261    if is_jsonl && !is_companion {
262        files.push(path);
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    fn write_session(dir: &Path, name: &str, body: &str) -> PathBuf {
271        std::fs::create_dir_all(dir).unwrap();
272        let path = dir.join(name);
273        let header = rpi_harness::session::jsonl::JsonlV4Header::new(
274            "cli-gc".into(),
275            1,
276            "/cwd".into(),
277            None,
278            None,
279            None,
280        );
281        std::fs::write(
282            &path,
283            format!(
284                "{}{body}",
285                rpi_harness::session::jsonl::encode_header(&header)
286            ),
287        )
288        .unwrap();
289        path
290    }
291
292    #[test]
293    fn review_issue14_cli_scan_skips_progress_companions_and_finds_nested_files() {
294        let temp = tempfile::tempdir().unwrap();
295        let root = temp.path().join("sessions");
296        let project = root.join("--proj--");
297        let nested = write_session(&project, "2026-01-01_a.jsonl", "");
298        let companion = project.join("2026-01-01_a.jsonl.progress.jsonl");
299        std::fs::write(&companion, "{}\n").unwrap();
300        // A file two levels down is outside the documented layout.
301        let deeper = write_session(&project.join("deep"), "b.jsonl", "");
302
303        let files = jsonl_files_in(&root);
304        assert!(files.contains(&nested), "{files:?}");
305        assert!(!files.contains(&companion), "{files:?}");
306        assert!(!files.contains(&deeper), "{files:?}");
307        // Deterministic order so the CLI summary is stable.
308        let mut sorted = files.clone();
309        sorted.sort();
310        assert_eq!(files, sorted);
311    }
312
313    #[test]
314    fn review_issue14_cli_project_dir_name_matches_the_repo_encoding() {
315        // Same cases as the harness's own `directory_name_encoding` test.
316        assert_eq!(
317            project_session_dir_name(Path::new("/home/user/proj")),
318            "--home-user-proj--"
319        );
320        assert_eq!(project_session_dir_name(Path::new("/a/b:c")), "--a-b-c--");
321    }
322
323    #[tokio::test]
324    async fn review_issue14_cli_dry_run_reports_without_writing() {
325        let temp = tempfile::tempdir().unwrap();
326        let dir = temp.path().join("sessions");
327        let mut body = String::new();
328        for (seq, op) in [
329            (1u64, rpi_harness::session::types::AssistantFrameOp::Append),
330            (2, rpi_harness::session::types::AssistantFrameOp::ClearRun),
331        ] {
332            body.push_str(&rpi_harness::session::jsonl::encode_mutation(
333                &rpi_harness::session::types::SessionMutation::Record {
334                    record: rpi_harness::session::types::LaneRecord::AssistantFrame(
335                        rpi_harness::session::types::AssistantFrameRecord {
336                            base: rpi_harness::session::types::RecordBase {
337                                id: format!("f{seq}"),
338                                seq,
339                                lane: "main".into(),
340                                timestamp: seq as i64,
341                            },
342                            run_id: "r".into(),
343                            stream_index: 0,
344                            op,
345                            frame: match op {
346                                rpi_harness::session::types::AssistantFrameOp::Append => {
347                                    Some(serde_json::json!({"text": format!("frame-{seq}")}))
348                                }
349                                _ => None,
350                            },
351                        },
352                    ),
353                },
354            ));
355        }
356        let path = write_session(&dir, "one.jsonl", &body);
357        let original = std::fs::read_to_string(&path).unwrap();
358        let args = vec![path.to_string_lossy().into_owned(), "--dry-run".into()];
359        assert_eq!(gc(&args).await, 0);
360        assert_eq!(
361            std::fs::read_to_string(&path).unwrap(),
362            original,
363            "dry run must not modify the file"
364        );
365
366        // A real run drops exactly the retired append's payload (identity row
367        // stays, per the review #274 P2 contract).
368        let args = vec![path.to_string_lossy().into_owned()];
369        assert_eq!(gc(&args).await, 0);
370        let after = std::fs::read_to_string(&path).unwrap();
371        assert!(!after.contains("frame-1"), "{after}");
372        assert!(after.contains("\"id\":\"f1\""), "{after}");
373        assert!(after.contains("\"f2\""), "{after}");
374    }
375
376    #[tokio::test]
377    async fn review_issue14_cli_reports_missing_paths() {
378        let args = vec!["/definitely/not/a/session".to_string()];
379        assert_eq!(gc(&args).await, EXIT_RUNTIME);
380    }
381
382    #[tokio::test]
383    async fn review_issue14_cli_gc_refuses_a_file_another_writer_locks() {
384        let temp = tempfile::tempdir().unwrap();
385        let body = format!(
386            "{}{}{}",
387            rpi_harness::session::jsonl::encode_mutation(
388                &rpi_harness::session::types::SessionMutation::Record {
389                    record: rpi_harness::session::types::LaneRecord::AssistantFrame(
390                        rpi_harness::session::types::AssistantFrameRecord {
391                            base: rpi_harness::session::types::RecordBase {
392                                id: "f1".into(),
393                                seq: 1,
394                                lane: "main".into(),
395                                timestamp: 1,
396                            },
397                            run_id: "r".into(),
398                            stream_index: 0,
399                            op: rpi_harness::session::types::AssistantFrameOp::Append,
400                            frame: Some(serde_json::json!({"text": "x"})),
401                        },
402                    ),
403                }
404            ),
405            rpi_harness::session::jsonl::encode_mutation(
406                &rpi_harness::session::types::SessionMutation::Record {
407                    record: rpi_harness::session::types::LaneRecord::AssistantFrame(
408                        rpi_harness::session::types::AssistantFrameRecord {
409                            base: rpi_harness::session::types::RecordBase {
410                                id: "f2".into(),
411                                seq: 2,
412                                lane: "main".into(),
413                                timestamp: 2,
414                            },
415                            run_id: "r".into(),
416                            stream_index: 0,
417                            op: rpi_harness::session::types::AssistantFrameOp::ClearRun,
418                            frame: None,
419                        },
420                    ),
421                }
422            ),
423            rpi_harness::session::jsonl::encode_mutation(
424                &rpi_harness::session::types::SessionMutation::Entry {
425                    seq: 3,
426                    timestamp: 3,
427                    lane: Some("main".into()),
428                    entry: rpi_harness::session::types::provisioned_into_entry(
429                        rpi_harness::session::types::ProvisionedEntry {
430                            id: "e3".into(),
431                            kind: rpi_harness::session::types::ProvisionedKind::Message {
432                                message: rpi_ai::UserMessage::new("kept", 3).into(),
433                                terminate: None,
434                            },
435                        },
436                        3,
437                        None,
438                        3,
439                    ),
440                }
441            ),
442        );
443        let path = write_session(&temp.path().join("s"), "locked.jsonl", &body);
444        let lock_path = path.with_file_name("locked.jsonl.lock");
445
446        // A live writer holds the session lock: gc must refuse and leave the
447        // file untouched.
448        let writer = std::fs::OpenOptions::new()
449            .create(true)
450            .write(true)
451            .open(&lock_path)
452            .unwrap();
453        fs2::FileExt::try_lock_exclusive(&writer).unwrap();
454        let args = vec![path.to_string_lossy().into_owned()];
455        let original = std::fs::read_to_string(&path).unwrap();
456        assert_eq!(gc(&args).await, EXIT_RUNTIME);
457        assert_eq!(
458            std::fs::read_to_string(&path).unwrap(),
459            original,
460            "a locked session must not be rewritten"
461        );
462        drop(writer);
463
464        // Once the writer is gone the same gc run succeeds, and it releases
465        // the lock afterwards (a following gc can acquire it again).
466        assert_eq!(gc(&args).await, 0);
467        let again = GcSessionLock::acquire(&path);
468        assert!(again.is_ok(), "gc must release its lock when done");
469    }
470}