Skip to main content

tracevault_cli/
pending_queue.rs

1//! The offline queue of a session: `pending-<target>.jsonl` in its session
2//! directory, one [`StreamEventRequest`] per line, holding what a hook could
3//! not send.
4//!
5//! Every transcript line is in exactly one place: sent, in the queue, or
6//! still unread in the agent's transcript file. A hook that cannot send lines
7//! it read from a file queues them and moves the file's read offset past
8//! them, so the next hook does not read them again. Earlier releases left the
9//! offset where it was *and* queued the lines, so every failed hook added the
10//! whole unsent end of the transcript to the queue once more, and the queue
11//! (read whole by every hook) grew to gigabytes for a transcript of a few
12//! megabytes.
13//!
14//! A queue is bounded ([`MAX_QUEUE_BYTES`]) and read one record at a time, so
15//! a hook's memory does not depend on how long the server has been
16//! unreachable. Lines that do not fit stay unread in the transcript file,
17//! which is as good a place: the offset stops there until the queue drains.
18//!
19//! A session directory whose queues an earlier release wrote is brought up
20//! to this once ([`upgrade`]): there the lines of a transcript file are both
21//! in the queue, many times, and still ahead of the read offset, so the
22//! queue's copies are dropped.
23
24use crate::program::TOP;
25use std::fs::{self, OpenOptions};
26use std::io::{self, BufRead, Write};
27use std::path::{Path, PathBuf};
28use std::sync::atomic::{AtomicBool, Ordering};
29use std::time::{Duration, SystemTime};
30
31use tracevault_protocol::streaming::{StreamEventRequest, StreamEventType};
32
33/// The most a queue file may hold. Transcript lines that do not fit are left
34/// in the transcript; an event (or a record an agent handed over inline) that
35/// does not fit can be kept nowhere and is dropped, with a warning. A queue
36/// without a bound did that to the machine instead.
37pub const MAX_QUEUE_BYTES: u64 = 32 * 1024 * 1024;
38
39/// How long a claimed queue file must have gone untouched before another
40/// reader takes it over as abandoned. A reader touches its claim with every
41/// record it takes from it, and the longest it can then be busy with one is
42/// a request's timeout (60 s, in `flush`; a hook is killed at 10 s).
43const ABANDONED_AFTER: Duration = Duration::from_secs(300);
44
45/// Whether the transcript lines of a queued record are read again from the
46/// agent's transcript file, going by the `tool` the record names. An absent
47/// `tool` is Claude Code (protocol v1 predates the field).
48pub fn lines_are_reread(tool: Option<&str>) -> bool {
49    use crate::agent::Agent;
50    ![Agent::OpenCode, Agent::Amp]
51        .iter()
52        .any(|a| Some(a.tool_name()) == tool)
53}
54
55/// Put a record that was already in the queue back into it, whatever the
56/// queue's size: a reader that claimed a queue and could not send a record
57/// must not lose it to the bound, which a hook queueing meanwhile may have
58/// used up. It can exceed the bound by no more than what was claimed.
59pub fn requeue(pending_path: &Path, json: &str) -> io::Result<()> {
60    let _lock = queue_lock(pending_path)?;
61    let mut file = OpenOptions::new()
62        .create(true)
63        .append(true)
64        .open(pending_path)?;
65    writeln!(file, "{json}")
66}
67
68/// The lock that orders writes to the queue at `pending_path` with its being
69/// claimed. Without it a writer could open the file, have it claimed, read
70/// and removed, and then write into the removed file: a record nobody will
71/// ever read, whose lines the transcript's offset has moved past.
72pub(crate) fn queue_lock(pending_path: &Path) -> io::Result<fs::File> {
73    // A hidden name: whatever lists a session directory's `pending*` files
74    // must not take the lock for a queue.
75    let name = pending_path
76        .file_name()
77        .map(|n| format!(".{}.lock", n.to_string_lossy()))
78        .unwrap_or_else(|| ".pending.lock".to_string());
79    lock(&pending_path.with_file_name(name))
80}
81
82/// The queue file a directory entry belongs to: the entry itself when it is
83/// a queue, and for a claimed queue (see [`claim`]) the file it was claimed
84/// from, which may not exist while its records wait in the claim.
85pub fn queue_of(entry: &Path) -> Option<PathBuf> {
86    let name = entry.file_name()?.to_str()?;
87    let base = match name.split_once(".draining-") {
88        Some((base, _)) => base,
89        None => name,
90    };
91    base.ends_with(".jsonl").then(|| entry.with_file_name(base))
92}
93
94/// Take the exclusive lock `lock_path` names, waiting for its holder. For
95/// the few file operations a hook must not interleave with another's; the
96/// OS drops the lock when its holder exits, even if killed.
97pub fn lock(lock_path: &Path) -> io::Result<fs::File> {
98    if let Some(dir) = lock_path.parent() {
99        fs::create_dir_all(dir)?;
100    }
101    let file = OpenOptions::new()
102        .create(true)
103        .truncate(false)
104        .write(true)
105        .open(lock_path)?;
106    file.lock()?;
107    Ok(file)
108}
109
110/// `part` without the transcript lines a file still holds: `None` when it is
111/// nothing but lines.
112pub fn without_lines(mut part: StreamEventRequest) -> Option<StreamEventRequest> {
113    if part.event_type == StreamEventType::Transcript {
114        return None;
115    }
116    part.transcript_lines = None;
117    Some(part)
118}
119
120/// Append one record to the queue if it fits; `false` when the queue is full.
121pub fn try_append(pending_path: &Path, json: &str) -> io::Result<bool> {
122    let _lock = queue_lock(pending_path)?;
123    // What readers hold claimed counts too: it may all come back, so a claim
124    // must not make room for as much again.
125    let size =
126        fs::metadata(pending_path).map(|m| m.len()).unwrap_or(0) + claimed_bytes(pending_path);
127    if size + json.len() as u64 + 1 > MAX_QUEUE_BYTES {
128        return Ok(false);
129    }
130    let mut file = OpenOptions::new()
131        .create(true)
132        .append(true)
133        .open(pending_path)?;
134    writeln!(file, "{json}")?;
135    Ok(true)
136}
137
138/// The size of the files claimed from the queue at `pending_path` and not
139/// yet released.
140fn claimed_bytes(pending_path: &Path) -> u64 {
141    let (Some(dir), Some(prefix)) = (pending_path.parent(), claim_prefix(pending_path)) else {
142        return 0;
143    };
144    fs::read_dir(dir)
145        .map(|entries| {
146            entries
147                .filter_map(|e| e.ok())
148                .filter(|e| {
149                    e.file_name()
150                        .to_str()
151                        .is_some_and(|n| n.starts_with(&prefix))
152                })
153                .filter_map(|e| e.metadata().ok())
154                .map(|m| m.len())
155                .sum()
156        })
157        .unwrap_or(0)
158}
159
160/// Append one record to the queue. A full queue drops it and says so once
161/// per process.
162pub fn append(pending_path: &Path, json: &str) -> io::Result<()> {
163    static WARNED: AtomicBool = AtomicBool::new(false);
164    if !try_append(pending_path, json)? && !WARNED.swap(true, Ordering::Relaxed) {
165        eprintln!(
166            "{TOP}: warning: the queue of unsent events {} is full ({} MB); \
167             events of this session are dropped until it is sent",
168            pending_path.display(),
169            MAX_QUEUE_BYTES / (1024 * 1024)
170        );
171    }
172    Ok(())
173}
174
175/// A queue taken out of its place to be read: the file is renamed, so a hook
176/// that queues meanwhile starts a new one, and what the reader does not send
177/// it appends there. The claimed files are removed by [`Claimed::release`]; a
178/// reader that dies first leaves them to be taken over (after
179/// [`ABANDONED_AFTER`]) instead of losing what it held in memory.
180#[derive(Default)]
181pub struct Claimed {
182    files: Vec<PathBuf>,
183}
184
185fn claim_prefix(pending_path: &Path) -> Option<String> {
186    Some(format!("{}.draining-", pending_path.file_name()?.to_str()?))
187}
188
189/// Claim the queue at `pending_path`, together with claims other readers
190/// abandoned (oldest first, as their records are older).
191pub fn claim(pending_path: &Path) -> io::Result<Claimed> {
192    claim_at(pending_path, SystemTime::now())
193}
194
195fn claim_at(pending_path: &Path, now: SystemTime) -> io::Result<Claimed> {
196    let mut files = Vec::new();
197    let (Some(dir), Some(prefix)) = (pending_path.parent(), claim_prefix(pending_path)) else {
198        return Ok(Claimed { files });
199    };
200
201    let mut abandoned: Vec<(SystemTime, PathBuf)> = match fs::read_dir(dir) {
202        Ok(entries) => entries
203            .filter_map(|e| e.ok())
204            .filter(|e| {
205                e.file_name()
206                    .to_str()
207                    .is_some_and(|n| n.starts_with(&prefix))
208            })
209            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
210            .filter(|(modified, _)| {
211                now.duration_since(*modified)
212                    .is_ok_and(|age| age >= ABANDONED_AFTER)
213            })
214            .collect(),
215        Err(e) if e.kind() == io::ErrorKind::NotFound => vec![],
216        Err(e) => return Err(e),
217    };
218    abandoned.sort();
219    for (_, path) in abandoned {
220        // Taken over under a name of our own, so two hooks do not both read it.
221        let mine = dir.join(format!("{prefix}{}", uuid::Uuid::now_v7()));
222        if fs::rename(&path, &mine).is_ok() {
223            touch(&mine);
224            files.push(mine);
225        }
226    }
227
228    let mine = dir.join(format!("{prefix}{}", uuid::Uuid::now_v7()));
229    // Not while a writer is between opening the queue and writing to it.
230    let _lock = queue_lock(pending_path)?;
231    match fs::rename(pending_path, &mine) {
232        Ok(()) => {
233            touch(&mine);
234            files.push(mine);
235        }
236        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
237        Err(e) => return Err(e),
238    }
239    Ok(Claimed { files })
240}
241
242/// A rename keeps the file's modification time, and the age of a claim is
243/// counted from when it was claimed.
244fn touch(path: &Path) {
245    if let Ok(file) = OpenOptions::new().append(true).open(path) {
246        let _ = file.set_modified(SystemTime::now());
247    }
248}
249
250impl Claimed {
251    pub fn is_empty(&self) -> bool {
252        self.files.is_empty()
253    }
254
255    /// This claim followed by `later`'s, read as one.
256    pub fn then(mut self, later: Claimed) -> Claimed {
257        self.files.extend(later.files);
258        self
259    }
260
261    /// The claimed records in order, one at a time.
262    pub fn records(&self) -> impl Iterator<Item = io::Result<String>> + Send + '_ {
263        let mut reader = self.reader();
264        std::iter::from_fn(move || reader.next_record().transpose())
265    }
266
267    /// A reader that knows how far into the claim it is (see [`Reader`]).
268    pub fn reader(&self) -> Reader<'_> {
269        Reader {
270            files: &self.files,
271            file: 0,
272            open: None,
273            offset: 0,
274            last: Position { file: 0, offset: 0 },
275        }
276    }
277
278    /// The same claim, as one on the queue at `pending_path`: files claimed
279    /// from another queue are renamed to claims on this one, in order. For a
280    /// queue that is adopted (a repo switch): from here on its records are
281    /// sent as this queue's, and whoever takes the claim over after its
282    /// reader died must send them there too, not to the target they were
283    /// queued for.
284    pub fn retarget(mut self, pending_path: &Path) -> io::Result<Claimed> {
285        let (Some(dir), Some(prefix)) = (pending_path.parent(), claim_prefix(pending_path)) else {
286            return Ok(self);
287        };
288        for path in &mut self.files {
289            let named_for_it = path
290                .file_name()
291                .and_then(|n| n.to_str())
292                .is_some_and(|n| n.starts_with(&prefix));
293            if !named_for_it {
294                let renamed = dir.join(format!("{prefix}{}", uuid::Uuid::now_v7()));
295                fs::rename(&*path, &renamed)?;
296                *path = renamed;
297            }
298        }
299        Ok(self)
300    }
301
302    /// Give the claim up. With `rest` (where a [`Reader`] stopped) the
303    /// records from there on stay queued, in order and ahead of anything
304    /// queued since; without it every record was dealt with and nothing
305    /// stays.
306    ///
307    /// The rest is not copied back into the queue: each file is left as a
308    /// claim that counts as abandoned at once, cut down to what was not read
309    /// by replacing it in one step. A reader that dies anywhere in this
310    /// leaves every record in exactly one file, so recovery neither loses nor
311    /// repeats one. When nothing else was queued meanwhile, the one file
312    /// left takes the queue's own name again.
313    pub fn finish(self, rest: Option<Position>, pending_path: &Path) -> io::Result<()> {
314        let Some(rest) = rest else {
315            for path in &self.files {
316                let _ = fs::remove_file(path);
317            }
318            return Ok(());
319        };
320        let mut left = Vec::new();
321        for (i, path) in self.files.iter().enumerate() {
322            if i < rest.file {
323                let _ = fs::remove_file(path);
324                continue;
325            }
326            let from = if i == rest.file { rest.offset } else { 0 };
327            if cut(path, from)? {
328                left.push(path);
329            }
330        }
331        if let [only] = left[..] {
332            let _lock = queue_lock(pending_path)?;
333            if !pending_path.exists() && claimed_bytes(pending_path) == file_len(only) {
334                fs::rename(only, pending_path)?;
335            }
336        }
337        Ok(())
338    }
339
340    /// Remove the claimed files: every record was dealt with.
341    pub fn release(self) {
342        for path in &self.files {
343            let _ = fs::remove_file(path);
344        }
345    }
346}
347
348fn file_len(path: &Path) -> u64 {
349    fs::metadata(path).map(|m| m.len()).unwrap_or(0)
350}
351
352/// Leave of the claimed file `path` what starts at byte `from`, as a claim
353/// that counts as abandoned at once (its modification time is the epoch).
354/// `false` when nothing is left and the file is gone. The file is replaced
355/// in one step, never partly written.
356fn cut(path: &Path, from: u64) -> io::Result<bool> {
357    let mut file = match fs::File::open(path) {
358        Ok(f) => f,
359        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
360        Err(e) => return Err(e),
361    };
362    if from >= file.metadata()?.len() {
363        fs::remove_file(path)?;
364        return Ok(false);
365    }
366    if from == 0 {
367        OpenOptions::new()
368            .append(true)
369            .open(path)?
370            .set_modified(SystemTime::UNIX_EPOCH)?;
371        return Ok(true);
372    }
373    // A hidden name, so the half-written file is no claim to anybody.
374    let name = path.file_name().unwrap_or_default().to_string_lossy();
375    let tmp = path.with_file_name(format!(".{name}.rest"));
376    let mut write = || -> io::Result<()> {
377        use std::io::{Seek, SeekFrom};
378        file.seek(SeekFrom::Start(from))?;
379        let mut out = fs::File::create(&tmp)?;
380        io::copy(&mut file, &mut out)?;
381        out.set_modified(SystemTime::UNIX_EPOCH)?;
382        out.sync_all()?;
383        fs::rename(&tmp, path)
384    };
385    write()
386        .inspect_err(|_| {
387            let _ = fs::remove_file(&tmp);
388        })
389        .map(|()| true)
390}
391
392/// Where a [`Reader`] is in a claim: a record's first byte.
393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394pub struct Position {
395    file: usize,
396    offset: u64,
397}
398
399/// Reads a claim's records in order and can tell where the last one it
400/// returned began, which is where a reader that could not send it stops:
401/// [`Claimed::finish`] keeps what is from there on.
402pub struct Reader<'a> {
403    files: &'a [PathBuf],
404    file: usize,
405    open: Option<io::BufReader<fs::File>>,
406    offset: u64,
407    last: Position,
408}
409
410impl Reader<'_> {
411    /// The next record, or `None` at the claim's end. Blank lines are passed
412    /// over. Reading a file marks it as in use (see [`ABANDONED_AFTER`]).
413    pub fn next_record(&mut self) -> io::Result<Option<String>> {
414        loop {
415            let Some(path) = self.files.get(self.file) else {
416                self.last = Position {
417                    file: self.file,
418                    offset: 0,
419                };
420                return Ok(None);
421            };
422            if self.open.is_none() {
423                match fs::File::open(path) {
424                    Ok(f) => self.open = Some(io::BufReader::new(f)),
425                    Err(e) if e.kind() == io::ErrorKind::NotFound => {
426                        self.file += 1;
427                        continue;
428                    }
429                    Err(e) => return Err(e),
430                }
431                self.offset = 0;
432            }
433            let mut line = String::new();
434            let read = self
435                .open
436                .as_mut()
437                .expect("opened above")
438                .read_line(&mut line)?;
439            if read == 0 {
440                self.open = None;
441                self.file += 1;
442                continue;
443            }
444            self.last = Position {
445                file: self.file,
446                offset: self.offset,
447            };
448            self.offset += read as u64;
449            touch(path);
450            let record = line.trim();
451            if !record.is_empty() {
452                return Ok(Some(record.to_string()));
453            }
454        }
455    }
456
457    /// Where the record [`Self::next_record`] returned last began: with
458    /// [`Claimed::finish`], that record and all after it stay queued.
459    pub fn before_last(&self) -> Position {
460        self.last
461    }
462}
463
464/// The two fields that decide what happens to a queued record, read without
465/// building its transcript lines.
466#[derive(serde::Deserialize)]
467struct Head {
468    #[serde(default)]
469    tool: Option<String>,
470    event_type: StreamEventType,
471}
472
473/// One line of a queue an earlier release wrote, as it is kept: `None` for a
474/// blank or unreadable line, and for a record that is only lines of a
475/// transcript file (they are still ahead of the file's read offset); an event
476/// that carries such lines comes back without them.
477pub fn compacted(line: &str) -> Option<String> {
478    let line = line.trim();
479    if line.is_empty() {
480        return None;
481    }
482    let head: Head = serde_json::from_str(line).ok()?;
483    if !lines_are_reread(head.tool.as_deref()) {
484        return Some(line.to_string());
485    }
486    if head.event_type == StreamEventType::Transcript {
487        return None;
488    }
489    let mut record: StreamEventRequest = serde_json::from_str(line).ok()?;
490    if record.transcript_lines.take().is_none() {
491        return Some(line.to_string());
492    }
493    serde_json::to_string(&record).ok()
494}
495
496/// Rewrite the queue at `pending_path` as [`compacted`] keeps it, one record
497/// at a time.
498///
499/// Every claim on the queue is taken over, whatever its age: this runs only
500/// under the directory's upgrade lock and before its mark exists, when no
501/// reader of this release can hold one, so a claim is what a compaction that
502/// was killed left behind, still uncompacted.
503fn compact(pending_path: &Path) -> io::Result<()> {
504    let every_claim = SystemTime::now() + ABANDONED_AFTER + ABANDONED_AFTER;
505    let claimed = claim_at(pending_path, every_claim)?;
506    // Each file is replaced by its compacted self in one step, so a
507    // compaction that is killed leaves files that are either done or not,
508    // and doing a done one again changes nothing.
509    for path in &claimed.files {
510        let name = path.file_name().unwrap_or_default().to_string_lossy();
511        let tmp = path.with_file_name(format!(".{name}.compacting"));
512        let rewrite = || -> io::Result<()> {
513            let mut out = io::BufWriter::new(fs::File::create(&tmp)?);
514            for line in io::BufReader::new(fs::File::open(path)?).lines() {
515                if let Some(kept) = compacted(&line?) {
516                    writeln!(out, "{kept}")?;
517                }
518            }
519            out.into_inner().map_err(|e| e.into_error())?.sync_all()?;
520            fs::rename(&tmp, path)
521        };
522        rewrite().inspect_err(|_| {
523            let _ = fs::remove_file(&tmp);
524        })?;
525    }
526    // Hand everything back, unread.
527    claimed.finish(Some(Position { file: 0, offset: 0 }), pending_path)
528}
529
530/// Marks a session directory whose queues hold every line once (see the
531/// module documentation).
532const UPGRADED: &str = ".queue-v2";
533
534/// Bring the queues of `session_dir` up to "every line in one place", once:
535/// a directory without the mark may hold queues an earlier release wrote,
536/// which are [`compact`]ed. Called before a queue of the directory is read
537/// or written. A new directory has no queue and only gets the mark.
538///
539/// One at a time per directory: a second caller that compacted after the
540/// first had finished would take the lines the first then queued, which are
541/// nowhere else, for an earlier release's.
542pub fn upgrade(session_dir: &Path) -> io::Result<()> {
543    let mark = session_dir.join(UPGRADED);
544    if mark.exists() || !session_dir.is_dir() {
545        return Ok(());
546    }
547    let _lock = lock(&session_dir.join(".queue.lock"))?;
548    if mark.exists() {
549        return Ok(());
550    }
551    // Queues, and queues that exist only as the claim of a compaction that
552    // was killed.
553    let queues: std::collections::BTreeSet<PathBuf> = match fs::read_dir(session_dir) {
554        Ok(entries) => entries
555            .filter_map(|e| e.ok())
556            .filter_map(|e| queue_of(&e.path()))
557            .filter(|p| {
558                p.file_name()
559                    .and_then(|n| n.to_str())
560                    .is_some_and(|n| n.starts_with("pending"))
561            })
562            .collect(),
563        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
564        Err(e) => return Err(e),
565    };
566    for queue in queues {
567        compact(&queue)?;
568    }
569    fs::write(mark, "")
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575
576    fn record(tool: Option<&str>, event_type: StreamEventType, lines: usize) -> StreamEventRequest {
577        StreamEventRequest {
578            protocol_version: 1,
579            tool: tool.map(str::to_string),
580            event_type,
581            session_id: "s".into(),
582            timestamp: chrono::Utc::now(),
583            hook_event_name: Some("PostToolUse".into()),
584            tool_name: Some("Bash".into()),
585            tool_use_id: Some("t1".into()),
586            tool_input: Some(serde_json::json!({"command": "ls"})),
587            tool_response: None,
588            tool_is_error: None,
589            event_index: None,
590            event_uuid: Some(uuid::Uuid::now_v7()),
591            transcript_lines: (lines > 0)
592                .then(|| (0..lines).map(|i| serde_json::json!({"n": i})).collect()),
593            transcript_offset: Some(10),
594            model: None,
595            cwd: None,
596            final_stats: None,
597            flow_id: None,
598            labels: None,
599            params: None,
600            billing_mode: None,
601        }
602    }
603
604    /// How many files `dir` holds, the lock files aside.
605    fn files(dir: &Path) -> usize {
606        fs::read_dir(dir)
607            .unwrap()
608            .filter(|e| {
609                !e.as_ref()
610                    .unwrap()
611                    .file_name()
612                    .to_string_lossy()
613                    .ends_with(".lock")
614            })
615            .count()
616    }
617
618    fn json(r: &StreamEventRequest) -> String {
619        serde_json::to_string(r).unwrap()
620    }
621
622    fn parsed(json: &str) -> StreamEventRequest {
623        serde_json::from_str(json).unwrap()
624    }
625
626    #[test]
627    fn file_agents_reread_their_lines_and_plugin_agents_do_not() {
628        assert!(lines_are_reread(None));
629        assert!(lines_are_reread(Some("claude-code")));
630        assert!(lines_are_reread(Some("codex")));
631        assert!(lines_are_reread(Some("gsd")));
632        assert!(!lines_are_reread(Some("opencode")));
633        assert!(!lines_are_reread(Some("amp")));
634    }
635
636    #[test]
637    fn without_lines_keeps_the_event_and_drops_bare_lines() {
638        let event = record(Some("claude-code"), StreamEventType::ToolUse, 3);
639        let kept = without_lines(event.clone()).unwrap();
640        assert_eq!(kept.transcript_lines, None);
641        assert_eq!(kept.event_uuid, event.event_uuid);
642        assert_eq!(kept.tool_input, event.tool_input);
643
644        let lines = record(Some("claude-code"), StreamEventType::Transcript, 3);
645        assert!(without_lines(lines).is_none());
646    }
647
648    #[test]
649    fn compacted_drops_reread_lines_and_keeps_everything_else() {
650        // Bare lines of a file agent: gone.
651        let lines = record(Some("claude-code"), StreamEventType::Transcript, 5);
652        assert_eq!(compacted(&json(&lines)), None);
653        // Its event: kept, without the lines.
654        let event = record(None, StreamEventType::ToolUse, 5);
655        let kept = parsed(&compacted(&json(&event)).unwrap());
656        assert_eq!(kept.transcript_lines, None);
657        assert_eq!(kept.event_uuid, event.event_uuid);
658        assert_eq!(kept.transcript_offset, event.transcript_offset);
659        // An event without lines: the line as it is.
660        let plain = json(&record(Some("codex"), StreamEventType::SessionEnd, 0));
661        assert_eq!(compacted(&plain).as_deref(), Some(plain.as_str()));
662        // Inline records: untouched, lines and all.
663        let inline = json(&record(Some("amp"), StreamEventType::Transcript, 5));
664        assert_eq!(compacted(&inline).as_deref(), Some(inline.as_str()));
665        // Not a record.
666        assert_eq!(compacted(""), None);
667        assert_eq!(compacted("   "), None);
668        assert_eq!(compacted("{not json"), None);
669    }
670
671    /// A directory an earlier release wrote: every queue in it is compacted,
672    /// once. After that its queues hold each line once and are left alone.
673    #[test]
674    fn upgrade_compacts_every_queue_of_the_directory_once() {
675        let dir = tempfile::tempdir().unwrap();
676        let repo = dir
677            .path()
678            .join("pending-11111111-1111-1111-1111-111111111111.jsonl");
679        let project = dir
680            .path()
681            .join("pending-project-22222222-2222-2222-2222-222222222222.jsonl");
682        let legacy = dir.path().join("pending.jsonl");
683        let lines = json(&record(Some("claude-code"), StreamEventType::Transcript, 4));
684        let event = record(Some("claude-code"), StreamEventType::ToolUse, 4);
685        for queue in [&repo, &project, &legacy] {
686            fs::write(queue, format!("{lines}\n{lines}\n{}\n", json(&event))).unwrap();
687        }
688        fs::write(dir.path().join("metadata.json"), "{}").unwrap();
689
690        upgrade(dir.path()).unwrap();
691
692        for queue in [&repo, &project, &legacy] {
693            let after = fs::read_to_string(queue).unwrap();
694            let records: Vec<&str> = after.lines().collect();
695            assert_eq!(records.len(), 1, "{}", queue.display());
696            assert_eq!(parsed(records[0]).transcript_lines, None);
697        }
698        assert_eq!(
699            fs::read_to_string(dir.path().join("metadata.json")).unwrap(),
700            "{}"
701        );
702
703        // From now on a record with lines is the only copy of them.
704        fs::write(&repo, format!("{lines}\n")).unwrap();
705        upgrade(dir.path()).unwrap();
706        assert_eq!(fs::read_to_string(&repo).unwrap(), format!("{lines}\n"));
707    }
708
709    /// A claim waits for a writer that has the queue open, so nothing is
710    /// written into a file that was already read and removed.
711    #[test]
712    fn a_claim_waits_for_a_write_in_progress() {
713        let dir = tempfile::tempdir().unwrap();
714        let path = dir.path().join("pending-x.jsonl");
715        let first = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
716        let late = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
717        fs::write(&path, format!("{first}\n")).unwrap();
718
719        // A writer: holds the lock, has the file open, has not written yet.
720        let writing = queue_lock(&path).unwrap();
721        let mut open = OpenOptions::new().append(true).open(&path).unwrap();
722        let claimer = {
723            let path = path.clone();
724            std::thread::spawn(move || {
725                let claimed = claim(&path).unwrap();
726                let got: Vec<String> = claimed.records().map(Result::unwrap).collect();
727                claimed.release();
728                got
729            })
730        };
731        std::thread::sleep(Duration::from_millis(200));
732        assert!(!claimer.is_finished(), "the claim waits");
733        writeln!(open, "{late}").unwrap();
734        drop(open);
735        drop(writing);
736
737        assert_eq!(claimer.join().unwrap(), vec![first, late]);
738    }
739
740    #[test]
741    fn a_claim_belongs_to_the_queue_it_was_taken_from() {
742        let dir = Path::new("/s");
743        assert_eq!(
744            queue_of(&dir.join("pending-x.jsonl")),
745            Some(dir.join("pending-x.jsonl"))
746        );
747        assert_eq!(
748            queue_of(&dir.join("pending-x.jsonl.draining-0199")),
749            Some(dir.join("pending-x.jsonl"))
750        );
751        assert_eq!(queue_of(&dir.join(".pending-x.jsonl.lock")), None);
752        assert_eq!(queue_of(&dir.join("metadata.json")), None);
753    }
754
755    /// A claim does not make room: what a reader holds may all come back.
756    #[test]
757    fn a_claimed_queue_still_counts_against_the_bound() {
758        let dir = tempfile::tempdir().unwrap();
759        let path = dir.path().join("pending-x.jsonl");
760        fs::File::create(&path)
761            .unwrap()
762            .set_len(MAX_QUEUE_BYTES - 4)
763            .unwrap();
764        let claimed = claim(&path).unwrap();
765        assert!(!path.exists());
766        assert!(!try_append(&path, "0123456789").unwrap(), "still full");
767        claimed.release();
768        assert!(try_append(&path, "0123456789").unwrap());
769    }
770
771    #[test]
772    fn claims_read_as_one_keep_their_order() {
773        let dir = tempfile::tempdir().unwrap();
774        let older = dir.path().join("pending-project-p.jsonl");
775        let newer = dir.path().join("pending-r.jsonl");
776        let a = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
777        let b = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
778        fs::write(&older, format!("{a}\n")).unwrap();
779        fs::write(&newer, format!("{b}\n")).unwrap();
780        let claimed = claim(&older).unwrap().then(claim(&newer).unwrap());
781        let got: Vec<String> = claimed.records().map(Result::unwrap).collect();
782        assert_eq!(got, vec![a, b]);
783        claimed.release();
784        assert_eq!(files(dir.path()), 0);
785    }
786
787    fn queue_of_three(path: &Path) -> Vec<String> {
788        let records: Vec<String> = (0..3)
789            .map(|_| json(&record(Some("opencode"), StreamEventType::ToolUse, 1)))
790            .collect();
791        fs::write(path, format!("{}\n", records.join("\n"))).unwrap();
792        records
793    }
794
795    fn read_all(path: &Path) -> Vec<String> {
796        let claimed = claim_at(path, SystemTime::now() + ABANDONED_AFTER * 2).unwrap();
797        let got = claimed.records().map(Result::unwrap).collect();
798        claimed
799            .finish(Some(Position { file: 0, offset: 0 }), path)
800            .unwrap();
801        got
802    }
803
804    /// A reader that stops at a record leaves it and the ones after it
805    /// queued, once, under the queue's own name when nothing else is there.
806    #[test]
807    fn finishing_part_way_keeps_exactly_the_rest() {
808        let dir = tempfile::tempdir().unwrap();
809        let path = dir.path().join("pending-x.jsonl");
810        let records = queue_of_three(&path);
811
812        let claimed = claim(&path).unwrap();
813        let mut reader = claimed.reader();
814        assert_eq!(reader.next_record().unwrap().as_ref(), Some(&records[0]));
815        assert_eq!(reader.next_record().unwrap().as_ref(), Some(&records[1]));
816        let stopped = reader.before_last();
817        drop(reader);
818        claimed.finish(Some(stopped), &path).unwrap();
819
820        assert_eq!(
821            fs::read_to_string(&path).unwrap(),
822            format!("{}\n{}\n", records[1], records[2])
823        );
824        assert_eq!(files(dir.path()), 1);
825    }
826
827    /// A reader that dies after reading part of its claim, or while giving
828    /// it up, leaves each record in one file: whoever recovers it reads
829    /// every record once, however often that happens.
830    #[test]
831    fn a_reader_that_dies_leaves_no_record_twice() {
832        let dir = tempfile::tempdir().unwrap();
833        let path = dir.path().join("pending-x.jsonl");
834        let records = queue_of_three(&path);
835
836        for _ in 0..3 {
837            // Reads two records, puts nothing back, and is gone.
838            let claimed = claim_at(&path, SystemTime::now() + ABANDONED_AFTER * 2).unwrap();
839            let mut reader = claimed.reader();
840            reader.next_record().unwrap();
841            reader.next_record().unwrap();
842            drop(reader);
843            std::mem::forget(claimed);
844        }
845        assert_eq!(read_all(&path), records);
846        assert_eq!(read_all(&path), records, "handing back repeats nothing");
847        assert!(file_len(&path) > 0 && files(dir.path()) == 1);
848    }
849
850    /// While something else was queued meanwhile, the rest stays a claim
851    /// that the next reader takes first, at once.
852    #[test]
853    fn the_rest_is_read_ahead_of_what_was_queued_meanwhile() {
854        let dir = tempfile::tempdir().unwrap();
855        let path = dir.path().join("pending-x.jsonl");
856        let records = queue_of_three(&path);
857        let newer = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
858
859        let claimed = claim(&path).unwrap();
860        let mut reader = claimed.reader();
861        reader.next_record().unwrap();
862        let stopped = reader.before_last();
863        drop(reader);
864        assert!(try_append(&path, &newer).unwrap());
865        claimed.finish(Some(stopped), &path).unwrap();
866
867        let next = claim(&path).unwrap();
868        let got: Vec<String> = next.records().map(Result::unwrap).collect();
869        let mut want = records.clone();
870        want.push(newer);
871        assert_eq!(got, want);
872        next.release();
873        assert_eq!(files(dir.path()), 0);
874    }
875
876    /// An adopted queue's files become claims on the queue that adopts it,
877    /// so a recovery sends them where the adoption was sending them.
878    #[test]
879    fn an_adopted_claim_is_recovered_as_the_adopting_queue() {
880        let dir = tempfile::tempdir().unwrap();
881        let project = dir.path().join("pending-project-p.jsonl");
882        let repo = dir.path().join("pending-r.jsonl");
883        let records = queue_of_three(&project);
884
885        let claimed = claim(&project).unwrap().retarget(&repo).unwrap();
886        // The hook dies here.
887        std::mem::forget(claimed);
888
889        let names: Vec<String> = fs::read_dir(dir.path())
890            .unwrap()
891            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
892            .filter(|n| !n.ends_with(".lock"))
893            .collect();
894        assert_eq!(names.len(), 1);
895        assert!(
896            names[0].starts_with("pending-r.jsonl.draining-"),
897            "{names:?}"
898        );
899        assert_eq!(queue_of(&dir.path().join(&names[0])), Some(repo.clone()));
900        assert_eq!(read_all(&repo), records);
901        assert!(read_all(&project).is_empty());
902    }
903
904    #[test]
905    fn a_claimed_record_goes_back_whatever_the_bound() {
906        let dir = tempfile::tempdir().unwrap();
907        let path = dir.path().join("pending-x.jsonl");
908        fs::File::create(&path)
909            .unwrap()
910            .set_len(MAX_QUEUE_BYTES)
911            .unwrap();
912        assert!(!try_append(&path, "new").unwrap());
913        requeue(&path, "claimed").unwrap();
914        assert_eq!(fs::metadata(&path).unwrap().len(), MAX_QUEUE_BYTES + 8);
915    }
916
917    /// A second upgrade waits for the first and then finds the mark, so it
918    /// does not compact what was queued in between.
919    #[test]
920    fn upgrade_waits_for_one_in_progress_and_then_does_nothing() {
921        let dir = tempfile::tempdir().unwrap();
922        let path = dir.path().join("pending-x.jsonl");
923        let lines = json(&record(Some("claude-code"), StreamEventType::Transcript, 4));
924        let held = lock(&dir.path().join(".queue.lock")).unwrap();
925
926        let session_dir = dir.path().to_path_buf();
927        let waiting = std::thread::spawn(move || upgrade(&session_dir));
928        std::thread::sleep(Duration::from_millis(200));
929        assert!(!waiting.is_finished(), "it waits for the lock");
930        // The holder finishes: marks the directory and queues lines.
931        fs::write(dir.path().join(UPGRADED), "").unwrap();
932        fs::write(&path, format!("{lines}\n")).unwrap();
933        drop(held);
934
935        waiting.join().unwrap().unwrap();
936        assert_eq!(fs::read_to_string(&path).unwrap(), format!("{lines}\n"));
937    }
938
939    /// A compaction that was killed leaves the old queue under a claim's
940    /// name. The next upgrade finishes it, however recent the claim, instead
941    /// of marking the directory with the old records still in it.
942    #[test]
943    fn upgrade_finishes_a_compaction_that_was_interrupted() {
944        let dir = tempfile::tempdir().unwrap();
945        let path = dir.path().join("pending-x.jsonl");
946        let lines = json(&record(Some("claude-code"), StreamEventType::Transcript, 4));
947        let event = record(Some("claude-code"), StreamEventType::ToolUse, 4);
948        fs::write(
949            dir.path().join("pending-x.jsonl.draining-killed"),
950            format!("{lines}\n{lines}\n{}\n", json(&event)),
951        )
952        .unwrap();
953
954        upgrade(dir.path()).unwrap();
955
956        let after = fs::read_to_string(&path).unwrap();
957        let records: Vec<&str> = after.lines().collect();
958        assert_eq!(records.len(), 1);
959        assert_eq!(parsed(records[0]).event_uuid, event.event_uuid);
960        assert_eq!(parsed(records[0]).transcript_lines, None);
961        assert!(!dir.path().join("pending-x.jsonl.draining-killed").exists());
962    }
963
964    /// A claim that is still being read is not taken for abandoned.
965    #[test]
966    fn reading_a_claim_keeps_it_from_being_taken_over() {
967        let dir = tempfile::tempdir().unwrap();
968        let path = dir.path().join("pending-x.jsonl");
969        let a = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
970        fs::write(&path, format!("{a}\n{a}\n")).unwrap();
971        let claimed = claim(&path).unwrap();
972        let file = claimed.files[0].clone();
973        let long_ago = SystemTime::now() - ABANDONED_AFTER - Duration::from_secs(60);
974        fs::File::options()
975            .write(true)
976            .open(&file)
977            .unwrap()
978            .set_modified(long_ago)
979            .unwrap();
980
981        let mut records = claimed.records();
982        records.next().unwrap().unwrap();
983        let other = claim(&path).unwrap();
984        assert!(other.is_empty(), "the reader is alive");
985        drop(records);
986        claimed.release();
987    }
988
989    #[test]
990    fn upgrade_of_a_new_or_missing_directory_only_marks_it() {
991        let dir = tempfile::tempdir().unwrap();
992        upgrade(dir.path()).unwrap();
993        let names: Vec<String> = fs::read_dir(dir.path())
994            .unwrap()
995            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
996            .filter(|n| n != ".queue.lock")
997            .collect();
998        assert_eq!(names, [UPGRADED]);
999        upgrade(&dir.path().join("absent")).unwrap();
1000        assert!(!dir.path().join("absent").exists());
1001    }
1002
1003    #[test]
1004    fn compact_shrinks_a_queue_that_repeats_its_transcript() {
1005        let dir = tempfile::tempdir().unwrap();
1006        let path = dir.path().join("pending-x.jsonl");
1007        let event = record(Some("claude-code"), StreamEventType::ToolUse, 2);
1008        let mut content = String::new();
1009        for _ in 0..50 {
1010            let lines = record(Some("claude-code"), StreamEventType::Transcript, 200);
1011            content.push_str(&json(&lines));
1012            content.push('\n');
1013        }
1014        content.push_str(&json(&event));
1015        content.push('\n');
1016        fs::write(&path, &content).unwrap();
1017
1018        compact(&path).unwrap();
1019
1020        let after = fs::read_to_string(&path).unwrap();
1021        let records: Vec<&str> = after.lines().collect();
1022        assert_eq!(records.len(), 1);
1023        assert_eq!(parsed(records[0]).event_uuid, event.event_uuid);
1024        assert!(after.len() < content.len() / 50);
1025        // Nothing of the claim is left behind.
1026        assert_eq!(files(dir.path()), 1);
1027    }
1028
1029    #[test]
1030    fn compact_of_a_missing_queue_creates_nothing() {
1031        let dir = tempfile::tempdir().unwrap();
1032        compact(&dir.path().join("pending-x.jsonl")).unwrap();
1033        assert_eq!(files(dir.path()), 0);
1034    }
1035
1036    #[test]
1037    fn a_claim_takes_the_queue_away_and_records_come_in_order() {
1038        let dir = tempfile::tempdir().unwrap();
1039        let path = dir.path().join("pending-x.jsonl");
1040        let a = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
1041        let b = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
1042        fs::write(&path, format!("{a}\n\n{b}\n")).unwrap();
1043
1044        let claimed = claim(&path).unwrap();
1045        assert!(!path.exists(), "a hook queueing now starts a new file");
1046        let got: Vec<String> = claimed.records().map(Result::unwrap).collect();
1047        assert_eq!(got, vec![a, b]);
1048        claimed.release();
1049        assert_eq!(files(dir.path()), 0);
1050    }
1051
1052    #[test]
1053    fn an_abandoned_claim_is_taken_over_and_a_fresh_one_is_left_alone() {
1054        let dir = tempfile::tempdir().unwrap();
1055        let path = dir.path().join("pending-x.jsonl");
1056        let old = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
1057        let new = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
1058        let other = json(&record(Some("opencode"), StreamEventType::ToolUse, 1));
1059        let abandoned = dir.path().join("pending-x.jsonl.draining-dead");
1060        fs::write(&abandoned, format!("{old}\n")).unwrap();
1061        fs::write(&path, format!("{new}\n")).unwrap();
1062        // Another target's claim is not ours to take.
1063        let foreign = dir.path().join("pending-y.jsonl.draining-dead");
1064        fs::write(&foreign, format!("{other}\n")).unwrap();
1065
1066        // Now: the other reader may still be at work.
1067        let claimed = claim(&path).unwrap();
1068        let got: Vec<String> = claimed.records().map(Result::unwrap).collect();
1069        assert_eq!(got, vec![new.clone()]);
1070        assert!(abandoned.exists());
1071        claimed.release();
1072
1073        // Later: it is taken over, ahead of the queue itself.
1074        fs::write(&path, format!("{new}\n")).unwrap();
1075        let later = SystemTime::now() + ABANDONED_AFTER + Duration::from_secs(1);
1076        let claimed = claim_at(&path, later).unwrap();
1077        let got: Vec<String> = claimed.records().map(Result::unwrap).collect();
1078        assert_eq!(got, vec![old, new]);
1079        assert!(!abandoned.exists());
1080        claimed.release();
1081        assert!(foreign.exists());
1082        assert_eq!(files(dir.path()), 1);
1083    }
1084
1085    #[test]
1086    fn a_full_queue_takes_no_more() {
1087        let dir = tempfile::tempdir().unwrap();
1088        let path = dir.path().join("pending-x.jsonl");
1089        let file = fs::File::create(&path).unwrap();
1090        file.set_len(MAX_QUEUE_BYTES - 10).unwrap();
1091        assert!(!try_append(&path, "0123456789abcdef").unwrap());
1092        append(&path, "0123456789abcdef").unwrap();
1093        assert_eq!(fs::metadata(&path).unwrap().len(), MAX_QUEUE_BYTES - 10);
1094        assert!(try_append(&path, "01234567").unwrap());
1095        assert_eq!(fs::metadata(&path).unwrap().len(), MAX_QUEUE_BYTES - 1);
1096    }
1097}