feat(domain,infra,app): rotation/rétention log.jsonl + lecture paginée (LS6)

Backend uniquement (UI React repoussée à LS7) :
- domain : port ConversationArchive + structs SegmentStats/PageCursor/PageDirection/
  TurnSlice/RotationDecision/RotationThresholds, fn pures rotation_plan/clamp_page_limit
  + consts ; re-exports lib.
- infrastructure : impl ConversationArchive pour FsConversationLog (stats/rotate/page
  + helpers), archive segmentée hors chemin chaud.
- application : ReadConversationPage + DTO + ConversationArchiveProvider (conversation/paginate),
  RotateConversationLog (conversation/rotate), exports mod/lib.
- app-tauri : AppConversationArchiveProvider + wiring (state), rotation détachée dans
  launch_agent + commande read_conversation_page (commands), DTOs (dto),
  commande enregistrée (generate_handler!).
- tests (QA, verts) : conversation_log, conversation_rotate_paginate (nouveau),
  dto (module test). Pivots INV-LS6 et cohérence fold-après-rotation verts.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-22 12:58:40 +02:00
parent f9231422fe
commit 40ca3e522f
13 changed files with 2095 additions and 43 deletions

View File

@ -31,15 +31,18 @@
//! brièvement sur le registre. (P9 ajoutera un `FileGuard` plus large si un besoin
//! réel d'arbitrage lecture/écriture émerge — ici on ne sur-conçoit pas.)
use std::collections::HashMap;
use std::path::PathBuf;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use tokio::io::AsyncWriteExt;
use domain::conversation::ConversationId;
use domain::conversation_log::{ConversationLog, ConversationTurn, TurnId};
use domain::conversation_log::{
clamp_page_limit, ConversationArchive, ConversationLog, ConversationTurn, PageCursor,
PageDirection, SegmentStats, TurnId, TurnSlice, MAX_ARCHIVE_SEGMENTS,
};
use domain::ports::StoreError;
use domain::project::ProjectPath;
@ -108,7 +111,7 @@ impl FsConversationLog {
.clone()
}
/// Lit et parse tout le fil de `conversation`, dans l'ordre d'ajout.
/// Lit et parse tout le **segment actif** de `conversation`, dans l'ordre d'ajout.
///
/// Fichier absent ⇒ `Vec` vide. Une ligne illisible (UTF-8 invalide ou JSON
/// corrompu) est **silencieusement ignorée** : le log survit à une ligne tronquée
@ -117,22 +120,155 @@ impl FsConversationLog {
&self,
conversation: ConversationId,
) -> Result<Vec<ConversationTurn>, StoreError> {
let bytes = match tokio::fs::read(self.log_path(conversation)).await {
Ok(bytes) => bytes,
read_segment(&self.log_path(conversation)).await
}
// ── Rotation & pagination (lot LS6) ──────────────────────────────────────
/// `<base>/<conversationId>/log.<k>.jsonl` — un **segment d'archive** (`k ≥ 1`,
/// `log.1.jsonl` = le plus ancien, indices croissants = plus récents).
fn archive_path(&self, conversation: ConversationId, index: usize) -> PathBuf {
self.conversation_dir(conversation)
.join(format!("log.{index}.jsonl"))
}
/// Liste les **indices** des segments d'archive existants, triés **croissants**
/// (du plus ancien au plus récent). Dossier absent ⇒ `Vec` vide.
async fn archive_indices(
&self,
conversation: ConversationId,
) -> Result<Vec<usize>, StoreError> {
let dir = self.conversation_dir(conversation);
let mut entries = match tokio::fs::read_dir(&dir).await {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(StoreError::Io(e.to_string())),
};
// UTF-8 partiel (ex. fichier tronqué) : on décode en lossy plutôt que d'échouer ;
// une ligne devenue invalide ne parsera simplement pas en JSON et sera ignorée.
let text = String::from_utf8_lossy(&bytes);
let turns = text
.lines()
.filter(|line| !line.trim().is_empty())
// Ligne corrompue/illisible ⇒ skip silencieux (jamais d'erreur dure).
.filter_map(|line| serde_json::from_str::<ConversationTurn>(line).ok())
.collect();
Ok(turns)
let mut indices = Vec::new();
while let Some(entry) = entries
.next_entry()
.await
.map_err(|e| StoreError::Io(e.to_string()))?
{
if let Some(name) = entry.file_name().to_str() {
if let Some(index) = parse_archive_index(name) {
indices.push(index);
}
}
}
indices.sort_unstable();
Ok(indices)
}
/// Lit **tous** les segments d'une conversation, ordre chronologique croissant
/// (archives du plus ancien au plus récent, puis l'actif), avec **dédoublonnage par
/// [`TurnId`]** (première occurrence gagne) — défense contre une tête dupliquée laissée
/// par un crash entre l'écriture d'archive et le swap de l'actif.
async fn read_all_segments(
&self,
conversation: ConversationId,
) -> Result<Vec<ConversationTurn>, StoreError> {
let mut out: Vec<ConversationTurn> = Vec::new();
let mut seen: HashSet<TurnId> = HashSet::new();
for index in self.archive_indices(conversation).await? {
for turn in read_segment(&self.archive_path(conversation, index)).await? {
if seen.insert(turn.id) {
out.push(turn);
}
}
}
for turn in read_segment(&self.log_path(conversation)).await? {
if seen.insert(turn.id) {
out.push(turn);
}
}
Ok(out)
}
/// Backstop [`MAX_ARCHIVE_SEGMENTS`] : supprime **uniquement** le ou les segments
/// d'archive **les plus anciens** au-delà du plafond. Ne touche jamais l'actif ; les
/// archives ne contiennent par construction que des tours `< keep_from` (`< up_to`),
/// donc jamais un tour `≥ up_to`.
async fn enforce_archive_backstop(
&self,
conversation: ConversationId,
) -> Result<(), StoreError> {
let indices = self.archive_indices(conversation).await?;
if indices.len() <= MAX_ARCHIVE_SEGMENTS {
return Ok(());
}
let to_drop = indices.len() - MAX_ARCHIVE_SEGMENTS;
for &index in indices.iter().take(to_drop) {
// Suppression du plus ancien ; absent (course) ⇒ on ignore.
match tokio::fs::remove_file(self.archive_path(conversation, index)).await {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(StoreError::Io(e.to_string())),
}
}
Ok(())
}
}
/// Lit et parse un **segment** (fichier JSONL) donné, dans l'ordre d'ajout.
///
/// Fichier absent ⇒ `Vec` vide. Ligne illisible (UTF-8 invalide / JSON corrompu) ⇒
/// **ignorée** (survit à une ligne tronquée par un crash). Seule une vraie I/O remonte.
async fn read_segment(path: &Path) -> Result<Vec<ConversationTurn>, StoreError> {
let bytes = match tokio::fs::read(path).await {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(StoreError::Io(e.to_string())),
};
let text = String::from_utf8_lossy(&bytes);
let turns = text
.lines()
.filter(|line| !line.trim().is_empty())
.filter_map(|line| serde_json::from_str::<ConversationTurn>(line).ok())
.collect();
Ok(turns)
}
/// Parse l'indice `k` d'un nom de fichier d'archive `log.<k>.jsonl` (`k` entier `≥ 1`).
/// Renvoie `None` pour l'actif (`log.jsonl`), un `.tmp`, ou tout autre nom.
fn parse_archive_index(file_name: &str) -> Option<usize> {
let middle = file_name.strip_prefix("log.")?.strip_suffix(".jsonl")?;
// `log.jsonl` ⇒ middle == "" ⇒ pas un segment d'archive ; un `.tmp` n'a pas ce suffixe.
middle.parse::<usize>().ok().filter(|&k| k >= 1)
}
/// Sérialise les `turns` en JSONL puis les écrit **atomiquement** dans `final_path` via
/// un fichier temporaire `tmp_path` (`write` + `sync_all` + `rename`).
///
/// Le `rename` au sein du même dossier est atomique : un lecteur voit soit l'ancien
/// contenu complet, soit le nouveau, jamais un fichier à moitié écrit.
async fn write_segment_atomic(
tmp_path: &Path,
final_path: &Path,
turns: &[ConversationTurn],
) -> Result<(), StoreError> {
let mut buf = String::new();
for turn in turns {
let line =
serde_json::to_string(turn).map_err(|e| StoreError::Serialization(e.to_string()))?;
buf.push_str(&line);
buf.push('\n');
}
let mut file = tokio::fs::File::create(tmp_path)
.await
.map_err(|e| StoreError::Io(e.to_string()))?;
file.write_all(buf.as_bytes())
.await
.map_err(|e| StoreError::Io(e.to_string()))?;
// Durabilité : forcer le drainage avant le rename (cf. en-tête module).
file.sync_all()
.await
.map_err(|e| StoreError::Io(e.to_string()))?;
drop(file);
tokio::fs::rename(tmp_path, final_path)
.await
.map_err(|e| StoreError::Io(e.to_string()))?;
Ok(())
}
#[async_trait]
@ -209,3 +345,137 @@ impl ConversationLog for FsConversationLog {
Ok(all[start..].to_vec())
}
}
#[async_trait]
impl ConversationArchive for FsConversationLog {
async fn stats(&self, conversation: ConversationId) -> Result<SegmentStats, StoreError> {
// Bon marché : une seule lecture du segment actif ; bytes = taille du fichier,
// turns = lignes valides. Fichier absent ⇒ `{0, 0}`.
let bytes = match tokio::fs::read(self.log_path(conversation)).await {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Ok(SegmentStats {
active_turns: 0,
active_bytes: 0,
})
}
Err(e) => return Err(StoreError::Io(e.to_string())),
};
let active_bytes = bytes.len() as u64;
let text = String::from_utf8_lossy(&bytes);
let active_turns = text
.lines()
.filter(|line| !line.trim().is_empty())
.filter(|line| serde_json::from_str::<ConversationTurn>(line).is_ok())
.count();
Ok(SegmentStats {
active_turns,
active_bytes,
})
}
async fn rotate(
&self,
conversation: ConversationId,
keep_from: TurnId,
) -> Result<(), StoreError> {
// Verrou d'écriture de la conversation (le **même** que `append`) : tenu brièvement,
// hors chemin chaud. Sérialise rotation et appends.
let lock = self.write_lock(conversation);
let _guard = lock.lock().await;
let active = self.read_all(conversation).await?;
// INV-LS6 : on ne garde QUE si `keep_from` est dans l'actif. Absent ⇒ déjà roté ou
// inconnu ⇒ no-op (idempotent, jamais de perte). Position 0 ⇒ tête vide ⇒ no-op.
let Some(idx) = active.iter().position(|t| t.id == keep_from) else {
return Ok(());
};
if idx == 0 {
return Ok(());
}
let head = &active[..idx];
let queue = &active[idx..];
// 1. Écrire la tête froide dans un **nouveau** segment d'archive (le plus récent),
// atomiquement. `head` ne contient que des tours `< keep_from` (INV-LS6).
let next_index = self
.archive_indices(conversation)
.await?
.last()
.map_or(1, |max| max + 1);
let archive_path = self.archive_path(conversation, next_index);
let archive_tmp = with_tmp_suffix(&archive_path);
write_segment_atomic(&archive_tmp, &archive_path, head).await?;
// 2. Réécrire l'actif atomiquement **EN DERNIER** = `[keep_from..fin]`. Point de
// commit : un crash entre (1) et (2) laisse l'actif intact (tête dupliquée dans
// l'archive), jamais de queue perdue — la lecture dédoublonne par TurnId.
let active_path = self.log_path(conversation);
let active_tmp = with_tmp_suffix(&active_path);
write_segment_atomic(&active_tmp, &active_path, queue).await?;
// 3. Backstop : élaguer le(s) segment(s) d'archive le(s) plus ancien(s) au-delà du
// plafond (jamais l'actif, jamais un segment `≥ up_to`).
self.enforce_archive_backstop(conversation).await?;
Ok(())
}
async fn page(
&self,
conversation: ConversationId,
cursor: PageCursor,
limit: usize,
) -> Result<TurnSlice, StoreError> {
let limit = clamp_page_limit(limit);
// Lecture archive-aware + dédoublonnage par TurnId (frontières de segment).
let all = self.read_all_segments(conversation).await?;
let len = all.len();
// Calcul de la fenêtre `[start, end)` (toujours en ordre croissant) + `has_more`
// dans le sens de progression. Page vide pour un fil vide ou une ancre inconnue.
let (start, end, has_more) = match cursor.anchor {
None => match cursor.direction {
// Début du fil (plus anciens).
PageDirection::Forward => {
let end = limit.min(len);
(0, end, end < len)
}
// Fin du fil (plus récents).
PageDirection::Backward => {
let start = len.saturating_sub(limit);
(start, len, start > 0)
}
},
Some(anchor) => match all.iter().position(|t| t.id == anchor) {
// Ancre inconnue ⇒ page vide (jamais d'erreur).
None => (0, 0, false),
Some(pos) => match cursor.direction {
// Strictement après l'ancre, jusqu'à `limit`.
PageDirection::Forward => {
let start = pos + 1;
let end = (start + limit).min(len);
(start, end, end < len)
}
// Les `limit` tours strictement avant l'ancre (les plus proches).
PageDirection::Backward => {
let end = pos;
let start = end.saturating_sub(limit);
(start, end, start > 0)
}
},
},
};
Ok(TurnSlice {
turns: all[start..end].to_vec(),
has_more,
})
}
}
/// Dérive le chemin temporaire `<path>.tmp` d'un fichier de segment (écriture atomique).
fn with_tmp_suffix(path: &Path) -> PathBuf {
let mut name = path.as_os_str().to_owned();
name.push(".tmp");
PathBuf::from(name)
}

View File

@ -18,8 +18,9 @@ use std::path::PathBuf;
use domain::conversation::ConversationId;
use domain::conversation_log::{
bound_handoff_summary, ConversationLog, ConversationTurn, Handoff, HandoffStore,
HandoffSummarizer, ProviderSessionStore, TurnId, TurnRole, HANDOFF_SUMMARY_MAX_CHARS,
bound_handoff_summary, ConversationArchive, ConversationLog, ConversationTurn, Handoff,
HandoffStore, HandoffSummarizer, PageCursor, PageDirection, ProviderSessionStore, TurnId,
TurnRole, HANDOFF_SUMMARY_MAX_CHARS, MAX_ARCHIVE_SEGMENTS, ROTATE_AFTER_BYTES,
};
use domain::input::InputSource;
use domain::ports::StoreError;
@ -1292,3 +1293,558 @@ async fn provider_is_isolated_per_conversation() {
"aucune fuite de c1 dans le providers.json de c2"
);
}
// ===========================================================================
// LS6 — rotation (ConversationArchive) + pagination humaine, I/O réelle.
// Réutilise le scaffolding L2 (TempDir absolu, constructeurs déterministes).
// Convention d'archive : `<conversationId>/log.<k>.jsonl` (k≥1, le plus ancien=1).
// ===========================================================================
/// Liste, triés croissants, les indices `k` des segments d'archive `log.<k>.jsonl`
/// présents sur disque pour `c` (l'actif `log.jsonl` est exclu).
fn archive_segment_indices(tmp: &TempDir, c: ConversationId) -> Vec<usize> {
let dir = tmp.conversation_dir(c);
let mut out = Vec::new();
if let Ok(rd) = std::fs::read_dir(&dir) {
for entry in rd.flatten() {
if let Some(name) = entry.file_name().to_str() {
if let Some(mid) = name
.strip_prefix("log.")
.and_then(|s| s.strip_suffix(".jsonl"))
{
if let Ok(k) = mid.parse::<usize>() {
out.push(k);
}
}
}
}
}
out.sort_unstable();
out
}
/// Écrit un segment d'archive brut `log.<k>.jsonl` (simulation de crash / dédoublonnage).
fn write_raw_archive_segment(
tmp: &TempDir,
c: ConversationId,
k: usize,
turns: &[ConversationTurn],
) {
let dir = tmp.conversation_dir(c);
std::fs::create_dir_all(&dir).unwrap();
let mut buf = String::new();
for t in turns {
buf.push_str(&serde_json::to_string(t).unwrap());
buf.push('\n');
}
std::fs::write(dir.join(format!("log.{k}.jsonl")), buf).unwrap();
}
/// Tous les `.tmp` restant dans le dossier de la conversation (doivent être absents).
fn leftover_tmp_files(tmp: &TempDir, c: ConversationId) -> Vec<String> {
let dir = tmp.conversation_dir(c);
let mut out = Vec::new();
if let Ok(rd) = std::fs::read_dir(&dir) {
for entry in rd.flatten() {
if let Some(name) = entry.file_name().to_str() {
if name.ends_with(".tmp") {
out.push(name.to_owned());
}
}
}
}
out
}
fn ids(turns: &[ConversationTurn]) -> Vec<TurnId> {
turns.iter().map(|t| t.id).collect()
}
/// Enregistre `n` tours (id 1..=n) dans l'actif et renvoie le log.
async fn seed_turns(log: &FsConversationLog, c: ConversationId, n: u128) {
for i in 1..=n {
let role = if i % 2 == 1 {
TurnRole::Prompt
} else {
TurnRole::Response
};
log.append(c, turn(c, turn_id(i), role, &format!("texte du tour {i}")))
.await
.unwrap();
}
}
// --- INV-LS6 : le test pivot -------------------------------------------------
/// INV-LS6 (PIVOT) : après `rotate(keep_from=up_to)`, le curseur `up_to` reste
/// trouvable dans l'ACTIF, donc `ConversationLog::read(since=up_to)` renvoie toujours
/// le bon incrément, et `last(n)` fonctionne. C'est l'invariant qui garantit que la
/// rotation ne casse jamais le fold incrémental du handoff.
#[tokio::test]
async fn inv_ls6_read_since_up_to_survives_rotation() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
seed_turns(&log, c, 10).await;
// up_to = curseur du handoff (tour 5). On rote en gardant tout depuis 5.
let up_to = turn_id(5);
log.rotate(c, up_to).await.expect("rotate ok");
// Le curseur est dans l'actif ⇒ l'incrément strictement postérieur est intact.
let inc = log.read(c, Some(up_to)).await.unwrap();
assert_eq!(
texts(&inc),
(6..=10)
.map(|i| format!("texte du tour {i}"))
.collect::<Vec<_>>(),
"read(since=up_to) renvoie l'incrément 6..=10 après rotation"
);
// last(n) lit bien la fin (archive-unaware mais l'actif contient la queue).
let last3 = log.last(c, 3).await.unwrap();
assert_eq!(ids(&last3), vec![turn_id(8), turn_id(9), turn_id(10)]);
}
// --- archive : déplacement de tête, aucune perte, idempotence ----------------
/// `rotate(keep_from=5)` déplace la tête froide (1..4) dans un segment, garde
/// `[5..10]` dans l'actif, sans perdre aucun tour ( actif+archives = tous).
#[tokio::test]
async fn rotate_moves_cold_head_to_a_segment_without_loss() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
seed_turns(&log, c, 10).await;
log.rotate(c, turn_id(5)).await.expect("rotate ok");
// Un seul segment d'archive créé (le plus ancien = index 1).
assert_eq!(archive_segment_indices(&tmp, c), vec![1]);
// L'actif = [5..10] (keep_from inclus en tête).
let active = log.read(c, None).await.unwrap();
assert_eq!(ids(&active), (5..=10).map(turn_id).collect::<Vec<_>>());
// Aucun tour perdu : la page archive-aware réunit tout, 1..10 en ordre croissant.
let page = log
.page(
c,
PageCursor {
anchor: None,
direction: PageDirection::Forward,
},
200,
)
.await
.unwrap();
assert_eq!(ids(&page.turns), (1..=10).map(turn_id).collect::<Vec<_>>());
assert!(!page.has_more, "10 tours ≤ limit ⇒ pas d'autre page");
}
/// `rotate` est idempotente : un 2e appel avec le même `keep_from` (désormais en tête
/// de l'actif) est un no-op — aucun nouveau segment, actif inchangé.
#[tokio::test]
async fn rotate_is_idempotent() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
seed_turns(&log, c, 10).await;
log.rotate(c, turn_id(5)).await.expect("rotate 1");
let after1 = log.read(c, None).await.unwrap();
let segs1 = archive_segment_indices(&tmp, c);
log.rotate(c, turn_id(5)).await.expect("rotate 2 (no-op)");
let after2 = log.read(c, None).await.unwrap();
let segs2 = archive_segment_indices(&tmp, c);
assert_eq!(ids(&after1), ids(&after2), "actif inchangé au 2e rotate");
assert_eq!(segs1, segs2, "aucun nouveau segment au 2e rotate");
assert_eq!(segs2, vec![1], "toujours exactement un segment");
}
/// `keep_from` absent de l'actif (déjà roté / inconnu) ⇒ no-op, jamais de perte.
#[tokio::test]
async fn rotate_with_unknown_keep_from_is_noop() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
seed_turns(&log, c, 5).await;
log.rotate(c, turn_id(999)).await.expect("rotate noop");
assert!(archive_segment_indices(&tmp, c).is_empty(), "aucun segment");
let active = log.read(c, None).await.unwrap();
assert_eq!(ids(&active), (1..=5).map(turn_id).collect::<Vec<_>>());
}
/// Réécriture de l'actif **atomique** : après rotation, aucun `.tmp` ne traîne et la
/// queue active est intégralement présente (jamais perdue).
#[tokio::test]
async fn rotate_leaves_no_tmp_and_preserves_active_queue() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
seed_turns(&log, c, 8).await;
log.rotate(c, turn_id(4)).await.expect("rotate ok");
assert!(
leftover_tmp_files(&tmp, c).is_empty(),
"aucun .tmp résiduel après écriture atomique : {:?}",
leftover_tmp_files(&tmp, c)
);
let active = log.read(c, None).await.unwrap();
assert_eq!(
ids(&active),
(4..=8).map(turn_id).collect::<Vec<_>>(),
"queue active [4..8] intégralement préservée"
);
}
/// Tête dupliquée (simulation de crash : archive écrite mais actif non swappé) ⇒ la
/// lecture paginée **dédoublonne par TurnId** (chaque tour une seule fois).
#[tokio::test]
async fn page_dedups_duplicated_head_after_crash() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
seed_turns(&log, c, 6).await; // actif = [1..6]
// Crash simulé : un segment d'archive contenant la tête (1..3) est écrit, mais
// l'actif n'a PAS été tronqué (il contient toujours 1..6).
let active_all = log.read(c, None).await.unwrap();
let head: Vec<ConversationTurn> = active_all[..3].to_vec();
write_raw_archive_segment(&tmp, c, 1, &head);
// La page réunit archive(1..3) + actif(1..6) MAIS dédoublonne ⇒ 1..6, pas de doublon.
let page = log
.page(
c,
PageCursor {
anchor: None,
direction: PageDirection::Forward,
},
200,
)
.await
.unwrap();
assert_eq!(
ids(&page.turns),
(1..=6).map(turn_id).collect::<Vec<_>>(),
"dédoublonnage par TurnId : chaque tour une seule fois"
);
}
/// `append` ne déclenche **jamais** la rotation : grossir l'actif au-delà du seuil
/// d'octets sans appeler `rotate` ne crée aucun segment d'archive.
#[tokio::test]
async fn append_never_triggers_rotation_even_over_threshold() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
// Dépasser le seuil d'octets (1 MiB) : ~16 tours de 80 000 caractères.
let big = "m".repeat(80_000);
for i in 1..=16u128 {
log.append(c, turn(c, turn_id(i), TurnRole::Response, &big))
.await
.unwrap();
}
let stats = log.stats(c).await.unwrap();
assert!(
stats.active_bytes > ROTATE_AFTER_BYTES,
"pré-condition : actif au-dessus du seuil d'octets ({})",
stats.active_bytes
);
// Pourtant : aucun segment d'archive (la rotation est hors-chemin, jamais sur append).
assert!(
archive_segment_indices(&tmp, c).is_empty(),
"append ne crée jamais d'archive : {:?}",
archive_segment_indices(&tmp, c)
);
}
// --- pagination humaine ------------------------------------------------------
/// Page vide pour une conversation vide.
#[tokio::test]
async fn page_of_empty_conversation_is_empty() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
let page = log
.page(
c,
PageCursor {
anchor: None,
direction: PageDirection::Forward,
},
50,
)
.await
.unwrap();
assert!(page.turns.is_empty() && !page.has_more);
}
/// Forward depuis le début, Backward depuis la fin, ancré dans les deux sens ;
/// `has_more` correct ; ordre **chronologique croissant** dans chaque page.
#[tokio::test]
async fn page_forward_backward_anchored_and_has_more() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
seed_turns(&log, c, 10).await;
// Forward depuis le début, limit 4 ⇒ [1..4], has_more.
let p = log
.page(
c,
PageCursor {
anchor: None,
direction: PageDirection::Forward,
},
4,
)
.await
.unwrap();
assert_eq!(ids(&p.turns), (1..=4).map(turn_id).collect::<Vec<_>>());
assert!(p.has_more);
// Backward depuis la fin, limit 4 ⇒ [7..10] (ordre croissant !), has_more.
let p = log
.page(
c,
PageCursor {
anchor: None,
direction: PageDirection::Backward,
},
4,
)
.await
.unwrap();
assert_eq!(ids(&p.turns), (7..=10).map(turn_id).collect::<Vec<_>>());
assert!(p.has_more);
// Ancré Forward après le tour 4, limit 3 ⇒ [5,6,7], has_more.
let p = log
.page(
c,
PageCursor {
anchor: Some(turn_id(4)),
direction: PageDirection::Forward,
},
3,
)
.await
.unwrap();
assert_eq!(ids(&p.turns), vec![turn_id(5), turn_id(6), turn_id(7)]);
assert!(p.has_more);
// Ancré Backward avant le tour 4, limit 10 ⇒ [1,2,3], plus rien avant.
let p = log
.page(
c,
PageCursor {
anchor: Some(turn_id(4)),
direction: PageDirection::Backward,
},
10,
)
.await
.unwrap();
assert_eq!(ids(&p.turns), vec![turn_id(1), turn_id(2), turn_id(3)]);
assert!(!p.has_more, "rien avant le tour 1");
// Dernière page Forward (fin atteinte) ⇒ has_more = false.
let p = log
.page(
c,
PageCursor {
anchor: Some(turn_id(7)),
direction: PageDirection::Forward,
},
50,
)
.await
.unwrap();
assert_eq!(ids(&p.turns), vec![turn_id(8), turn_id(9), turn_id(10)]);
assert!(!p.has_more);
}
/// La pagination est **archive-aware** : après rotation, une page peut chevaucher
/// plusieurs segments (archive + actif) et reste en ordre croissant continu.
#[tokio::test]
async fn page_spans_multiple_segments_after_rotation() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
seed_turns(&log, c, 12).await;
log.rotate(c, turn_id(7)).await.expect("rotate"); // archive [1..6], actif [7..12]
// Une page ancrée Forward autour de la frontière archive/actif renvoie un span continu.
let p = log
.page(
c,
PageCursor {
anchor: Some(turn_id(5)),
direction: PageDirection::Forward,
},
4,
)
.await
.unwrap();
// Tours 6 (archive) puis 7,8,9 (actif) : continuité par-delà la frontière de segment.
assert_eq!(
ids(&p.turns),
vec![turn_id(6), turn_id(7), turn_id(8), turn_id(9)]
);
assert!(p.has_more);
}
/// Le **texte complet** d'un tour est préservé (non borné) à la lecture paginée — la
/// borne LS5 ne s'applique qu'au handoff, jamais au log canonique.
#[tokio::test]
async fn page_preserves_full_unbounded_turn_text() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
let big = "Z".repeat(50_000);
log.append(c, turn(c, turn_id(1), TurnRole::Response, &big))
.await
.unwrap();
let p = log
.page(
c,
PageCursor {
anchor: None,
direction: PageDirection::Forward,
},
50,
)
.await
.unwrap();
assert_eq!(p.turns.len(), 1);
assert_eq!(
p.turns[0].text.chars().count(),
50_000,
"texte complet préservé (non borné) à la pagination"
);
}
// --- backstop MAX_ARCHIVE_SEGMENTS ------------------------------------------
/// Au-delà de [`MAX_ARCHIVE_SEGMENTS`] segments, le(s) plus ANCIEN(s) sont supprimés ;
/// l'actif n'est jamais touché et aucun tour `≥ keep_from` n'est archivé/perdu.
#[tokio::test]
async fn rotation_enforces_max_archive_segments_dropping_oldest() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let c = conv_id(1);
let total = 40u128;
seed_turns(&log, c, total).await;
// Roter `MAX_ARCHIVE_SEGMENTS + 3` fois, en avançant keep_from d'un tour à chaque fois.
// Chaque rotation déplace une tête d'un tour ⇒ crée un segment.
let rotations = (MAX_ARCHIVE_SEGMENTS + 3) as u128;
for k in 2..=(1 + rotations) {
log.rotate(c, turn_id(k)).await.expect("rotate ok");
}
// Backstop : jamais plus de MAX_ARCHIVE_SEGMENTS segments sur disque.
let segs = archive_segment_indices(&tmp, c);
assert_eq!(
segs.len(),
MAX_ARCHIVE_SEGMENTS,
"plafonné à MAX_ARCHIVE_SEGMENTS, obtenu {segs:?}"
);
// L'actif n'a pas été touché par le backstop : il commence au dernier keep_from.
let last_keep = 1 + rotations; // = turn_id du dernier keep_from
let active = log.read(c, None).await.unwrap();
assert_eq!(
active.first().map(|t| t.id),
Some(turn_id(last_keep)),
"l'actif commence à keep_from (jamais archivé/supprimé)"
);
assert_eq!(
active.last().map(|t| t.id),
Some(turn_id(total)),
"la fin de l'actif est intacte"
);
// read(since=last_keep) — le curseur survit (INV-LS6) même après backstop.
let inc = log.read(c, Some(turn_id(last_keep))).await.unwrap();
assert_eq!(
inc.first().map(|t| t.id),
Some(turn_id(last_keep + 1)),
"l'incrément après le dernier curseur reste correct"
);
}
// --- cohérence fold-après-rotation (le must-have) ----------------------------
/// COHÉRENCE (must-have) : beaucoup de tours → `rotate(keep_from = up_to)` → encore des
/// tours → un `fold` ultérieur **étend correctement** le handoff. On lit l'actif depuis
/// `up_to` (INV-LS6 : toujours trouvable après rotation), on replie l'incrément, et
/// `up_to` AVANCE. Prouve que la rotation ne casse jamais le fold incrémental réel.
#[tokio::test]
async fn fold_after_rotation_extends_handoff_correctly() {
let tmp = TempDir::new();
let log = FsConversationLog::new(&tmp.project_path());
let summarizer = HeuristicHandoffSummarizer::new();
let c = conv_id(1);
// 1. Tours 1..7 enregistrés PUIS repliés ⇒ handoff.up_to = 7.
seed_turns(&log, c, 7).await;
let first_batch = log.read(c, None).await.unwrap();
let handoff = summarizer.fold(None, &first_batch).await;
let handoff = bound_handoff_summary(handoff, HANDOFF_SUMMARY_MAX_CHARS);
assert_eq!(handoff.up_to, turn_id(7), "curseur = dernier tour replié");
// 2. Plus de tours arrivent (8..15), non encore repliés, écrits dans l'actif.
for i in 8..=15u128 {
let role = if i % 2 == 1 {
TurnRole::Prompt
} else {
TurnRole::Response
};
log.append(c, turn(c, turn_id(i), role, &format!("texte du tour {i}")))
.await
.unwrap();
}
// 3. Rotation au plancher = up_to du handoff (7) : tête froide 1..6 archivée.
log.rotate(c, handoff.up_to).await.expect("rotate ok");
// L'actif commence bien au curseur (INV-LS6) ⇒ le curseur reste trouvable.
assert_eq!(
ids(&log.read(c, None).await.unwrap()),
(7..=15).map(turn_id).collect::<Vec<_>>(),
"actif = [up_to..fin] après rotation"
);
// 4. Fold ultérieur : on lit l'incrément depuis up_to (8..15) DANS L'ACTIF, on replie.
let increment = log.read(c, Some(handoff.up_to)).await.unwrap();
assert_eq!(
ids(&increment),
(8..=15).map(turn_id).collect::<Vec<_>>(),
"read(since=up_to) renvoie l'incrément 8..15 malgré la rotation"
);
let advanced = summarizer.fold(Some(handoff.clone()), &increment).await;
let advanced = bound_handoff_summary(advanced, HANDOFF_SUMMARY_MAX_CHARS);
// up_to a AVANCÉ jusqu'au dernier tour, et le résumé intègre les tours récents.
assert_eq!(
advanced.up_to,
turn_id(15),
"le curseur avance après le fold"
);
assert!(
advanced.summary_md.contains("texte du tour 15"),
"le fold intègre le tour le plus récent : {}",
advanced.summary_md
);
assert_ne!(
advanced.up_to, handoff.up_to,
"la rotation ne fige pas le curseur du handoff"
);
}