Skip to main content

agentmux_srv_core/backend/
session_archive.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Session archival and cleanup (Phase 3.3 — ultra-long-sessions).
5//!
6//! Responsibilities:
7//!   1. Periodic sweep: archive sessions inactive for `inactive_days` days by
8//!      compressing their FileStore "output" file to `archive_dir/<block_id>.jsonl.gz`
9//!      and freeing the FileStore entry.
10//!
11//! Archives are never deleted: AgentMux keeps agent history forever.
12//!
13//! The sweep archives through the same `archive_session_output` the RPC
14//! handlers in `server/app_api/session.rs` call; those handlers also use
15//! `restore_session_output` and `read_session_output` from this module.
16
17use std::io::{Read, Write};
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21use flate2::Compression;
22use flate2::read::GzDecoder;
23use flate2::write::GzEncoder;
24
25use crate::backend::blockcontroller::session_stats::{
26    META_SESSION_LAST_ACTIVITY_MS, META_SESSION_LINE_COUNT,
27};
28use crate::backend::obj::{Block, MetaMapType};
29use crate::backend::storage::filestore::{FileStore, FileMeta, FileOpts};
30use crate::backend::storage::store::Store;
31use crate::backend::transcript::source::TranscriptSource;
32
33// ---- Meta key constants for archival state ----
34
35/// Unix ms when the session was last archived.
36pub const META_SESSION_ARCHIVED_AT: &str = "session:archived_at";
37/// Byte count before compression (original output size).
38pub const META_SESSION_ARCHIVED_BYTES: &str = "session:archived_bytes";
39/// Absolute path to the `.jsonl.gz` archive file.
40pub const META_SESSION_ARCHIVE_PATH: &str = "session:archive_path";
41
42/// FileStore filename for session output.
43const OUTPUT_FILENAME: &str = "output";
44/// Receive-time sidecar (see `agent_session::TSIDX_FILE`) — archived,
45/// deleted, and restored in lockstep with `output` (codex P2 on PR #2508):
46/// leaving it behind would mis-time a fresh session's lines (new output
47/// restarts at offset 0 under stale entries), and dropping it from the
48/// archive loses the timestamps the sidecar exists to preserve.
49const TSIDX_FILENAME: &str = crate::backend::agent_session::session_io::TSIDX_FILE;
50
51// ---------------------------------------------------------------------------
52// Shared helpers — used by both the RPC handlers and the sweep
53// ---------------------------------------------------------------------------
54
55use agentmux_common::time::now_ms;
56
57/// Compress `data` with gzip and write to `dest_path`.
58fn write_gz(data: &[u8], dest_path: &Path) -> Result<(), String> {
59    let file = std::fs::File::create(dest_path)
60        .map_err(|e| format!("create archive file {}: {e}", dest_path.display()))?;
61    let mut encoder = GzEncoder::new(file, Compression::default());
62    encoder.write_all(data)
63        .map_err(|e| format!("compress: {e}"))?;
64    encoder.finish()
65        .map_err(|e| format!("gz finish: {e}"))?;
66    Ok(())
67}
68
69/// Decompress a `.gz` file and return raw bytes.
70fn read_gz(src_path: &Path) -> Result<Vec<u8>, String> {
71    let file = std::fs::File::open(src_path)
72        .map_err(|e| format!("open archive {}: {e}", src_path.display()))?;
73    let mut decoder = GzDecoder::new(file);
74    let mut out = Vec::new();
75    decoder.read_to_end(&mut out)
76        .map_err(|e| format!("decompress: {e}"))?;
77    Ok(out)
78}
79
80/// Ensure the archive directory exists.
81fn ensure_archive_dir(archive_dir: &Path) -> Result<(), String> {
82    std::fs::create_dir_all(archive_dir)
83        .map_err(|e| format!("create archive dir {}: {e}", archive_dir.display()))
84}
85
86// ---------------------------------------------------------------------------
87// archive_session_output
88// ---------------------------------------------------------------------------
89
90/// Archive the FileStore "output" file for `block_id`:
91///   1. Read bytes from FileStore.
92///   2. Compress to `archive_dir/<block_id>.jsonl.gz`.
93///   3. Delete the FileStore entry to reclaim SQLite space.
94///   4. Write archive meta keys to the block.
95///
96/// Returns `(archived_bytes, archived_at_ms)`.
97/// If the FileStore entry is missing or empty, returns `(0, now_ms)` — no-op.
98///
99/// The bytes come from where the pane reads them ([`TranscriptSource`]): the agent's own zone in the global
100/// transcript store when the block is a defined agent's and the zone has content, else the block's own copy.
101/// Only the block's own files are deleted (the zone holds the agent's whole record and is not this block's to
102/// delete); with no block copy that delete finds nothing.
103pub fn archive_session_output(
104    mstore: &Arc<Store>,
105    filestore: &Arc<FileStore>,
106    block_id: &str,
107    archive_dir: &Path,
108) -> Result<(u64, i64), String> {
109    let global = crate::backend::agent_session::global_transcript_store().map(|g| g.as_ref());
110    archive_session_output_with(mstore, filestore, global, block_id, archive_dir)
111}
112
113/// [`archive_session_output`] with the global transcript store given (tests install none).
114pub fn archive_session_output_with(
115    mstore: &Arc<Store>,
116    filestore: &Arc<FileStore>,
117    global: Option<&FileStore>,
118    block_id: &str,
119    archive_dir: &Path,
120) -> Result<(u64, i64), String> {
121    let source = TranscriptSource::resolve_with(filestore, global, mstore, block_id);
122    // Read existing data from the transcript's source
123    let raw_bytes = match source.fs.read_file(&source.zone, OUTPUT_FILENAME) {
124        Ok(Some(b)) if !b.is_empty() => b,
125        Ok(_) => {
126            // Nothing to archive
127            return Ok((0, now_ms()));
128        }
129        Err(e) => return Err(format!("filestore read: {e}")),
130    };
131
132    let archived_bytes = raw_bytes.len() as u64;
133
134    ensure_archive_dir(archive_dir)?;
135
136    let archive_path = archive_dir.join(format!("{}.jsonl.gz", block_id));
137    write_gz(&raw_bytes, &archive_path)?;
138
139    let archived_at = now_ms();
140
141    // Write archive metadata BEFORE deleting the FileStore entry. If the meta
142    // update fails, the session data is still retrievable from FileStore and
143    // the orphaned .gz can be cleaned up by the next sweep. Deleting first
144    // would orphan the session if the meta write then failed.
145    let mut meta = MetaMapType::new();
146    meta.insert(META_SESSION_ARCHIVED_AT.to_string(), serde_json::json!(archived_at));
147    meta.insert(META_SESSION_ARCHIVED_BYTES.to_string(), serde_json::json!(archived_bytes));
148    meta.insert(
149        META_SESSION_ARCHIVE_PATH.to_string(),
150        serde_json::json!(archive_path.to_string_lossy().as_ref()),
151    );
152
153    let oref_str = format!("block:{}", block_id);
154    if let Err(e) = crate::backend::wcore::object_meta::update_object_meta(mstore, &oref_str, &meta) {
155        // Roll back the archive file so we don't leak disk on retry
156        let _ = std::fs::remove_file(&archive_path);
157        return Err(format!("update_object_meta: {e}"));
158    }
159
160    // Sidecar follows output: archive its bytes next to the .jsonl.gz
161    // (best-effort — auxiliary timing data) before it is deleted below.
162    if let Ok(Some(ts_bytes)) = source.fs.read_file(&source.zone, TSIDX_FILENAME) {
163        if !ts_bytes.is_empty() {
164            let ts_path = archive_dir.join(format!("{}.tsidx.gz", block_id));
165            if let Err(e) = write_gz(&ts_bytes, &ts_path) {
166                tracing::warn!(block_id = %block_id, error = %e, "session_archive: tsidx archive write failed (output archive unaffected)");
167            }
168        }
169    }
170    // Meta is now persisted; safe to reclaim the FileStore entry, with both
171    // sidecars, in one transaction (5a-2b): a restarted session must not
172    // inherit stale offset stamps, and a stale output.idx could pass
173    // read_range's covered_size check by coincidence.
174    if let Err(e) = filestore.delete_files(block_id, &[OUTPUT_FILENAME, TSIDX_FILENAME, "output.idx"]) {
175        tracing::warn!(
176            block_id = %block_id,
177            error = %e,
178            "session_archive: failed to delete filestore entry after archiving (meta already updated)"
179        );
180    }
181
182    tracing::info!(
183        block_id = %block_id,
184        archived_bytes = archived_bytes,
185        archive_path = %archive_path.display(),
186        "session archived"
187    );
188
189    Ok((archived_bytes, archived_at))
190}
191
192// ---------------------------------------------------------------------------
193// restore_session_output
194// ---------------------------------------------------------------------------
195
196/// Restore an archived session back into FileStore:
197///   1. Read `session:archive_path` from block meta.
198///   2. Decompress and write bytes back via `make_file` + `append_data`.
199///   3. Clear archive meta keys (keep the .gz file as backup).
200pub fn restore_session_output(
201    mstore: &Arc<Store>,
202    filestore: &Arc<FileStore>,
203    block_id: &str,
204) -> Result<u64, String> {
205    // Read archive path from block meta
206    let block: Block = mstore
207        .get(block_id)
208        .map_err(|e| format!("mstore.get: {e}"))?
209        .ok_or_else(|| format!("BLOCK_NOT_FOUND: {}", block_id))?;
210
211    let archive_path_str = block
212        .meta
213        .get(META_SESSION_ARCHIVE_PATH)
214        .and_then(|v| v.as_str())
215        .ok_or_else(|| format!("session:archive_path not set for block {}", block_id))?
216        .to_string();
217
218    let archive_path = PathBuf::from(&archive_path_str);
219    let raw_bytes = read_gz(&archive_path)?;
220    let restored_bytes = raw_bytes.len() as u64;
221
222    // Recreate the FileStore entry (may already be gone after archival) in
223    // one transaction (5a-2b): the restored content with a new generation,
224    // and no sidecar left describing whatever `output` held before. A reader
225    // never sees the file missing or half-restored.
226    filestore
227        .replace_file(block_id, OUTPUT_FILENAME, &raw_bytes, &[TSIDX_FILENAME, "output.idx"])
228        .map_err(|e| format!("replace_file: {e}"))?;
229
230    // Restore the tsidx sidecar when its archive exists (best-effort —
231    // pre-sidecar archives simply have none, and restored history without
232    // stamps degrades to the carry-forward day rule, not an error).
233    let ts_path = archive_path
234        .parent()
235        .map(|d| d.join(format!("{}.tsidx.gz", block_id)))
236        .filter(|p| p.exists());
237    if let Some(ts_path) = ts_path {
238        match read_gz(&ts_path) {
239            Ok(ts_bytes) if !ts_bytes.is_empty() => {
240                let created = filestore
241                    .make_file(block_id, TSIDX_FILENAME, FileMeta::default(), FileOpts::default());
242                if created.is_ok() {
243                    if let Err(e) = filestore.append_data(block_id, TSIDX_FILENAME, &ts_bytes) {
244                        tracing::warn!(block_id = %block_id, error = %e, "session_archive: tsidx restore append failed");
245                    }
246                }
247            }
248            Ok(_) => {}
249            Err(e) => {
250                tracing::warn!(block_id = %block_id, error = %e, "session_archive: tsidx restore read failed");
251            }
252        }
253    }
254
255    // Clear archive meta keys (keep the .gz as backup — don't delete it)
256    let mut meta = MetaMapType::new();
257    meta.insert(META_SESSION_ARCHIVED_AT.to_string(), serde_json::Value::Null);
258    meta.insert(META_SESSION_ARCHIVED_BYTES.to_string(), serde_json::Value::Null);
259    meta.insert(META_SESSION_ARCHIVE_PATH.to_string(), serde_json::Value::Null);
260
261    let oref_str = format!("block:{}", block_id);
262    crate::backend::wcore::object_meta::update_object_meta(mstore, &oref_str, &meta)
263        .map_err(|e| format!("update_object_meta: {e}"))?;
264
265    tracing::info!(
266        block_id = %block_id,
267        restored_bytes = restored_bytes,
268        archive_path = %archive_path_str,
269        "session restored"
270    );
271
272    Ok(restored_bytes)
273}
274
275// ---------------------------------------------------------------------------
276// read_session_output — used by session:export
277// ---------------------------------------------------------------------------
278
279/// Read the raw session output bytes, whether from FileStore (live) or archive.
280/// Returns `(bytes, line_count)`.
281///
282/// Live output is read from where the pane reads it ([`TranscriptSource`]): the agent's own zone in the global
283/// transcript store when the block is a defined agent's and the zone has content, else the block's own copy.
284pub fn read_session_output(
285    mstore: &Arc<Store>,
286    filestore: &Arc<FileStore>,
287    block_id: &str,
288) -> Result<(Vec<u8>, u64), String> {
289    let global = crate::backend::agent_session::global_transcript_store().map(|g| g.as_ref());
290    read_session_output_with(mstore, filestore, global, block_id)
291}
292
293/// [`read_session_output`] with the global transcript store given (tests install none).
294pub fn read_session_output_with(
295    mstore: &Arc<Store>,
296    filestore: &Arc<FileStore>,
297    global: Option<&FileStore>,
298    block_id: &str,
299) -> Result<(Vec<u8>, u64), String> {
300    // Check if session is archived
301    let block: Block = mstore
302        .get(block_id)
303        .map_err(|e| format!("mstore.get: {e}"))?
304        .ok_or_else(|| format!("BLOCK_NOT_FOUND: {}", block_id))?;
305
306    let is_archived = block
307        .meta
308        .get(META_SESSION_ARCHIVED_AT)
309        .and_then(|v| v.as_i64())
310        .map(|v| v > 0)
311        .unwrap_or(false);
312
313    let raw_bytes = if is_archived {
314        let archive_path_str = block
315            .meta
316            .get(META_SESSION_ARCHIVE_PATH)
317            .and_then(|v| v.as_str())
318            .ok_or_else(|| "session:archive_path not set".to_string())?
319            .to_string();
320        read_gz(Path::new(&archive_path_str))?
321    } else {
322        let source = TranscriptSource::resolve_with(filestore, global, mstore, block_id);
323        source
324            .fs
325            .read_file(&source.zone, OUTPUT_FILENAME)
326            .map_err(|e| format!("filestore read: {e}"))?
327            .unwrap_or_default()
328    };
329
330    let line_count = bytecount_lines(&raw_bytes);
331    Ok((raw_bytes, line_count))
332}
333
334/// Count non-empty lines in a byte buffer.
335fn bytecount_lines(data: &[u8]) -> u64 {
336    let text = String::from_utf8_lossy(data);
337    text.lines().filter(|l| !l.trim().is_empty()).count() as u64
338}
339
340// ---------------------------------------------------------------------------
341// Default archive directory
342// ---------------------------------------------------------------------------
343
344/// Returns `~/.agentmux/archives/`, or `None` if the home directory cannot be determined.
345pub fn default_archive_dir() -> Option<PathBuf> {
346    // Stays fallible on purpose. bootstrap/background.rs treats None as
347    // "disable the archiver", with an explicit comment saying a relative
348    // fallback would otherwise write archives under the CWD. Routing this
349    // through the infallible get_mux_data_dir() silently defeated that guard.
350    crate::srv_info::agentmux_root().map(|root| root.join("archives"))
351}
352
353// ---------------------------------------------------------------------------
354// SessionArchiver — periodic sweep
355// ---------------------------------------------------------------------------
356
357/// Periodic session archival.
358pub struct SessionArchiver {
359    mstore: Arc<Store>,
360    filestore: Arc<FileStore>,
361    /// Sessions with no activity for this many days get archived.
362    pub inactive_days: u64,
363    /// Directory where `.jsonl.gz` files are written.
364    pub archive_dir: PathBuf,
365}
366
367/// Statistics from a single sweep run.
368#[derive(Debug, Clone, Default)]
369pub struct SessionArchiverStats {
370    pub archived_count: u32,
371    pub bytes_freed: u64,
372}
373
374impl SessionArchiver {
375    pub fn new(
376        mstore: Arc<Store>,
377        filestore: Arc<FileStore>,
378        inactive_days: u64,
379        archive_dir: PathBuf,
380    ) -> Self {
381        Self { mstore, filestore, inactive_days, archive_dir }
382    }
383
384    /// Run one sweep:
385    ///   1. Find all agent blocks inactive for `inactive_days`.
386    ///   2. Archive each one (compress → delete FileStore).
387    pub async fn sweep(&self) -> Result<SessionArchiverStats, String> {
388        let mut stats = SessionArchiverStats::default();
389        let now = now_ms();
390        let cutoff_ms = self.inactive_days as i64 * 86_400_000;
391
392        // Collect all blocks
393        let all_blocks: Vec<Block> = self
394            .mstore
395            .get_all::<Block>()
396            .map_err(|e| format!("get_all blocks: {e}"))?;
397
398        for block in &all_blocks {
399            // Only agent panes
400            let view = block.meta.get("view").and_then(|v| v.as_str()).unwrap_or("");
401            if view != "agent" {
402                continue;
403            }
404
405            // Skip if already archived
406            let archived_at = block
407                .meta
408                .get(META_SESSION_ARCHIVED_AT)
409                .and_then(|v| v.as_i64())
410                .unwrap_or(0);
411            if archived_at > 0 {
412                continue;
413            }
414
415            // Skip if session:last_activity_ms is missing (fresh session)
416            let last_activity = match block
417                .meta
418                .get(META_SESSION_LAST_ACTIVITY_MS)
419                .and_then(|v| v.as_i64())
420            {
421                Some(v) if v > 0 => v,
422                _ => continue,
423            };
424
425            // Skip if session has no lines
426            let line_count = block
427                .meta
428                .get(META_SESSION_LINE_COUNT)
429                .and_then(|v| v.as_u64())
430                .unwrap_or(0);
431            if line_count == 0 {
432                continue;
433            }
434
435            // Check inactivity threshold
436            if now - last_activity < cutoff_ms {
437                continue;
438            }
439
440            // Archive it
441            match archive_session_output(
442                &self.mstore,
443                &self.filestore,
444                &block.oid,
445                &self.archive_dir,
446            ) {
447                Ok((bytes, _)) => {
448                    stats.archived_count += 1;
449                    stats.bytes_freed += bytes;
450                    tracing::info!(
451                        block_id = %block.oid,
452                        bytes_freed = bytes,
453                        "session archiver: auto-archived inactive session"
454                    );
455                }
456                Err(e) => {
457                    tracing::warn!(
458                        block_id = %block.oid,
459                        error = %e,
460                        "session archiver: failed to archive session"
461                    );
462                }
463            }
464        }
465
466        Ok(stats)
467    }
468}
469
470// ---------------------------------------------------------------------------
471// Tests
472// ---------------------------------------------------------------------------
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477    use std::sync::Arc;
478    use crate::backend::storage::filestore::FileStore;
479    use crate::backend::storage::store::Store;
480
481    /// Verify that a block with old last_activity gets archived by the sweeper.
482    /// Uses in-memory stores — no disk I/O needed for this unit test.
483    #[tokio::test]
484    async fn test_sweep_archives_inactive_session() {
485        // Build a temp dir for archives
486        let tmp_dir = tempfile::tempdir().expect("tempdir");
487        let archive_dir = tmp_dir.path().to_path_buf();
488
489        // In-memory FileStore with output data
490        let filestore = Arc::new(
491            FileStore::open_in_memory().expect("filestore"),
492        );
493        // Write a fake "output" file for the block. The ID must be a
494        // valid UUID — `archive_session_output` calls
495        // `update_object_meta`, which parses the ORef
496        // `format!("block:{}", block_id)` via `ORef::parse` and
497        // rejects non-UUID oids. The earlier "blk-sweep-test" string
498        // failed silently inside the sweep's logged-but-suppressed
499        // error path.
500        let block_id_owned = uuid::Uuid::new_v4().to_string();
501        let block_id = block_id_owned.as_str();
502        filestore
503            .make_file(block_id, OUTPUT_FILENAME, FileMeta::default(), FileOpts::default())
504            .expect("make_file");
505        filestore
506            .append_data(block_id, OUTPUT_FILENAME, b"line1\nline2\n")
507            .expect("append_data");
508
509        // In-memory Store
510        let db_dir = tmp_dir.path().join("wdb");
511        std::fs::create_dir_all(&db_dir).unwrap();
512        let mstore = Arc::new(
513            Store::open(&db_dir.join("objects.db")).expect("mstore"),
514        );
515
516        // Insert a fake Block object with required meta
517        use crate::backend::obj::{Block, MetaMapType};
518        let mut meta = MetaMapType::new();
519        meta.insert("view".to_string(), serde_json::json!("agent"));
520        // last_activity 10 days ago (well past the 7-day threshold)
521        let ten_days_ago = now_ms() - 10 * 86_400_000;
522        meta.insert(
523            META_SESSION_LAST_ACTIVITY_MS.to_string(),
524            serde_json::json!(ten_days_ago),
525        );
526        meta.insert(META_SESSION_LINE_COUNT.to_string(), serde_json::json!(2u64));
527
528        let mut block = Block {
529            oid: block_id.to_string(),
530            parentoref: String::new(),
531            version: 1,
532            runtimeopts: None,
533            stickers: None,
534            meta,
535            subblockids: None,
536        };
537        mstore.insert(&mut block).expect("mstore insert");
538
539        // Run the archiver (1-day inactive threshold to keep test fast)
540        let archiver = SessionArchiver::new(
541            mstore.clone(),
542            filestore.clone(),
543            1, // 1 day inactive threshold
544            archive_dir.clone(),
545        );
546
547        let stats = archiver.sweep().await.expect("sweep");
548        assert_eq!(stats.archived_count, 1, "should archive 1 session");
549        assert!(stats.bytes_freed > 0, "should free bytes");
550
551        // Verify the FileStore entry was deleted
552        let remaining = filestore.stat(block_id, OUTPUT_FILENAME).unwrap();
553        assert!(remaining.is_none(), "filestore entry should be deleted after archive");
554
555        // Verify the .gz file was created
556        let gz_path = archive_dir.join(format!("{}.jsonl.gz", block_id));
557        assert!(gz_path.exists(), ".gz file should exist");
558
559        // Verify the block meta was updated
560        let updated_block: Option<Block> = mstore.get(block_id).unwrap();
561        let updated_block = updated_block.expect("block still in store");
562        let archived_at = updated_block
563            .meta
564            .get(META_SESSION_ARCHIVED_AT)
565            .and_then(|v| v.as_i64())
566            .unwrap_or(0);
567        assert!(archived_at > 0, "session:archived_at should be set");
568    }
569
570    #[test]
571    fn test_bytecount_lines() {
572        assert_eq!(bytecount_lines(b""), 0);
573        assert_eq!(bytecount_lines(b"line1\n"), 1);
574        assert_eq!(bytecount_lines(b"line1\nline2\n"), 2);
575        assert_eq!(bytecount_lines(b"  \n\nline3\n"), 1); // blanks excluded
576    }
577
578    #[test]
579    fn test_gz_roundtrip() {
580        let tmp = tempfile::NamedTempFile::new().unwrap();
581        let data = b"hello compressed world\nline2\n";
582        write_gz(data, tmp.path()).unwrap();
583        let out = read_gz(tmp.path()).unwrap();
584        assert_eq!(out, data);
585    }
586
587    // ---- where a block's transcript is read from (single copy first, the block's own copy otherwise) ----
588
589    const SINGLE_DEF: &str = "def-single-copy";
590
591    struct Rig {
592        _dir: tempfile::TempDir,
593        mstore: Arc<Store>,
594        block_fs: Arc<FileStore>,
595        global: FileStore,
596        block_id: String,
597    }
598
599    /// A defined agent's block (`agentId` = [`SINGLE_DEF`]), a block store and a global transcript store, all in memory.
600    fn rig() -> Rig {
601        use crate::backend::obj::{Block, MetaMapType};
602        let dir = tempfile::tempdir().expect("tempdir");
603        let mstore = Arc::new(Store::open(&dir.path().join("objects.db")).expect("mstore"));
604        let block_id = uuid::Uuid::new_v4().to_string();
605        let mut meta = MetaMapType::new();
606        meta.insert("agentId".to_string(), serde_json::json!(SINGLE_DEF));
607        let mut block = Block { oid: block_id.clone(), parentoref: String::new(), version: 1, runtimeopts: None, stickers: None, meta, subblockids: None };
608        mstore.insert(&mut block).expect("insert block");
609        Rig { _dir: dir, mstore, block_fs: Arc::new(FileStore::open_in_memory().unwrap()), global: FileStore::open_in_memory().unwrap(), block_id }
610    }
611
612    fn put(fs: &FileStore, zone: &str, name: &str, bytes: &[u8]) {
613        fs.make_file(zone, name, FileMeta::default(), FileOpts::default()).unwrap();
614        fs.append_data(zone, name, bytes).unwrap();
615    }
616
617    impl Rig {
618        fn zone(&self) -> String {
619            crate::backend::agent_session::agent_current_zone(SINGLE_DEF)
620        }
621        fn export(&self, with_global: bool) -> (Vec<u8>, u64) {
622            read_session_output_with(&self.mstore, &self.block_fs, with_global.then_some(&self.global), &self.block_id).unwrap()
623        }
624    }
625
626    #[test]
627    fn an_export_of_a_defined_agents_block_reads_the_single_copy_when_the_block_has_none() {
628        let r = rig();
629        put(&r.global, &r.zone(), OUTPUT_FILENAME, b"only
630in the zone
631");
632        assert_eq!(r.export(true), (b"only
633in the zone
634".to_vec(), 2));
635    }
636
637    #[test]
638    fn an_export_reads_the_block_copy_when_there_is_no_single_copy() {
639        let r = rig();
640        put(&r.block_fs, &r.block_id, OUTPUT_FILENAME, b"block
641copy
642");
643        assert_eq!(r.export(true), (b"block
644copy
645".to_vec(), 2), "an empty zone: the block's own copy");
646        assert_eq!(r.export(false), (b"block
647copy
648".to_vec(), 2), "no global store: the block's own copy");
649    }
650
651    #[test]
652    fn an_export_reads_the_single_copy_when_the_block_has_one_too() {
653        let r = rig();
654        put(&r.global, &r.zone(), OUTPUT_FILENAME, b"one
655two
656three
657");
658        put(&r.block_fs, &r.block_id, OUTPUT_FILENAME, b"one
659two
660");
661        assert_eq!(r.export(true), (b"one
662two
663three
664".to_vec(), 3), "the copy the pane reads");
665        assert_eq!(r.export(false).0, b"one
666two
667".to_vec(), "without a global store the block's own copy is all there is");
668    }
669
670    #[test]
671    fn a_block_that_is_not_a_defined_agents_reads_its_own_copy() {
672        use crate::backend::obj::{Block, MetaMapType};
673        let r = rig();
674        put(&r.global, &r.zone(), OUTPUT_FILENAME, b"the agent's record
675");
676        let mut meta = MetaMapType::new();
677        meta.insert("view".to_string(), serde_json::json!("term"));
678        let other = uuid::Uuid::new_v4().to_string();
679        let mut block = Block { oid: other.clone(), parentoref: String::new(), version: 1, runtimeopts: None, stickers: None, meta, subblockids: None };
680        r.mstore.insert(&mut block).unwrap();
681        put(&r.block_fs, &other, OUTPUT_FILENAME, b"its own
682");
683        let (bytes, _) = read_session_output_with(&r.mstore, &r.block_fs, Some(&r.global), &other).unwrap();
684        assert_eq!(bytes, b"its own
685".to_vec());
686    }
687
688    #[test]
689    fn an_archive_takes_the_single_copy_and_leaves_the_agents_zone_alone() {
690        let r = rig();
691        let record = b"line one
692line two
693";
694        put(&r.global, &r.zone(), OUTPUT_FILENAME, record);
695        put(&r.global, &r.zone(), TSIDX_FILENAME, b"stamps");
696        let archive_dir = tempfile::tempdir().unwrap();
697        let (bytes, at) = archive_session_output_with(&r.mstore, &r.block_fs, Some(&r.global), &r.block_id, archive_dir.path()).unwrap();
698        assert_eq!(bytes, record.len() as u64);
699        assert!(at > 0);
700        let gz = archive_dir.path().join(format!("{}.jsonl.gz", r.block_id));
701        assert_eq!(read_gz(&gz).unwrap(), record.to_vec(), "the archive holds the single copy");
702        let ts = archive_dir.path().join(format!("{}.tsidx.gz", r.block_id));
703        assert_eq!(read_gz(&ts).unwrap(), b"stamps".to_vec(), "and its receive times");
704        assert_eq!(r.global.read_file(&r.zone(), OUTPUT_FILENAME).unwrap().as_deref(), Some(&record[..]), "the agent's zone is not the block's to delete");
705        // Archived: the export reads the archive, not the zone.
706        assert_eq!(r.export(true), (record.to_vec(), 2));
707    }
708
709    #[test]
710    fn an_archive_of_the_block_copy_is_as_it_was() {
711        let r = rig();
712        put(&r.block_fs, &r.block_id, OUTPUT_FILENAME, b"block
713copy
714");
715        let archive_dir = tempfile::tempdir().unwrap();
716        let (bytes, _) = archive_session_output_with(&r.mstore, &r.block_fs, Some(&r.global), &r.block_id, archive_dir.path()).unwrap();
717        assert_eq!(bytes, 11);
718        assert!(r.block_fs.stat(&r.block_id, OUTPUT_FILENAME).unwrap().is_none(), "the block's copy is deleted");
719        assert_eq!(archive_session_output_with(&r.mstore, &r.block_fs, Some(&r.global), &r.block_id, archive_dir.path()).unwrap().0, 0, "nothing left to archive");
720    }
721}