merry-runtime 0.1.1

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Deterministic compaction window selection and archive-reference planning.

use crate::{
    RuntimeError,
    checkpoint::CheckpointRef,
    compaction::{
        CitationCompactionPolicy, CompactionCoverageBudget, CompactionError, CompactionShape,
        CompactionWindowBudget, CompactionWindowFingerprint, CompactionWindowPlan, RetainedFit,
        retained_turn_fallbacks,
    },
    session::{
        ModelTurnStatus, SessionState,
        checkpoint_window::history::{ModelTurnHistory, covered_payload_tokens},
    },
    token_estimate::ReasoningTokenAccounting,
};
use merry_core::ToolCallId;
use std::collections::BTreeSet;

/// One retention option the planner evaluates.
///
/// `CompletedTurns` keeps that many completed turns raw and covers everything
/// older. `ArchiveOnly` keeps every turn raw and only archives tool results; the
/// runtime installs it without another model call, which is the degradation path
/// when no checkpoint replacement fits the compaction request budget.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RetentionCandidate {
    CompletedTurns(usize),
    ArchiveOnly,
}

impl RetentionCandidate {
    /// Returns what an empty covered window means for this candidate.
    fn empty_coverage_meaning(self) -> EmptyCoverage {
        match self {
            Self::CompletedTurns(_) => EmptyCoverage::NothingToDo,
            // Archiving tool results is a real reduction, so the empty covered set
            // is the requested plan rather than a no-op.
            Self::ArchiveOnly => EmptyCoverage::Reduction,
        }
    }
}

/// What an empty covered window means for one retention candidate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EmptyCoverage {
    /// Nothing to summarize: the caller reports that no compression applies.
    NothingToDo,
    /// Archive-only reduction: the empty covered set is the plan.
    Reduction,
}

/// Result of evaluating one retention candidate.
enum CandidateOutcome {
    Plan(CompactionWindowPlan),
    NothingToDo,
    DoesNotFit,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ToolArchival {
    Preserve,
    Allow,
}

struct RetainedWindowPolicy {
    empty_coverage: EmptyCoverage,
    retained_fit: RetainedFit,
    archival: ToolArchival,
}

impl SessionState {
    pub(super) fn plan_compaction_window_from_turns(
        &self,
        mut policy: CitationCompactionPolicy,
        window_budget: CompactionWindowBudget,
        coverage: CompactionCoverageBudget,
        shape: CompactionShape,
        turns: &[ModelTurnHistory<'_>],
    ) -> Result<Option<CompactionWindowPlan>, RuntimeError> {
        if coverage.max_tokens().is_none()
            && shape.retained_fit() == RetainedFit::Required
            && let Some(preferred) = window_budget.preferred()
        {
            match self.plan_compaction_window_from_turns(policy, preferred, coverage, shape, turns)
            {
                Err(RuntimeError::Compaction {
                    source:
                        CompactionError::MinimumRawTurnCannotFit { .. }
                        | CompactionError::UncompressibleCurrentInput { .. }
                        | CompactionError::NoWindowFitsCompactionRequest,
                }) => policy = policy.with_retained_model_turns(1)?,
                outcome => return outcome,
            }
        }
        debug_assert!(
            window_budget.max_dynamic_body_tokens() <= window_budget.primary_window_tokens()
        );
        let first_open = turns
            .iter()
            .position(|turn| turn.status.is_open())
            .unwrap_or(turns.len());
        if turns[first_open..]
            .iter()
            .any(|turn| !turn.status.is_open())
        {
            return Err(CompactionError::StaleWindow.into());
        }
        let closed_turns = &turns[..first_open];
        let open_turns = &turns[first_open..];

        let fingerprint = self.compaction_window_fingerprint()?;
        let available_completed = closed_turns
            .iter()
            .filter(|turn| turn.status == ModelTurnStatus::Completed)
            .count();
        let mut candidates =
            self.retention_candidates(policy, coverage, shape, closed_turns, available_completed)?;
        // A coverage budget only exists when the runtime already knows a
        // checkpoint replacement does not fit its request. Archiving tool results
        // is then the remaining degradation, because it reduces the request body
        // without spending another model call.
        let bounded_coverage = coverage.max_tokens().is_some();
        if bounded_coverage {
            candidates.push(RetentionCandidate::ArchiveOnly);
        }

        let modes: &[ToolArchival] =
            if !bounded_coverage && shape.retained_fit() == RetainedFit::Required {
                &[ToolArchival::Preserve, ToolArchival::Allow]
            } else {
                &[ToolArchival::Allow]
            };
        let mut last_failure: Option<CompactionError> = None;
        for (archival, candidate) in modes
            .iter()
            .flat_map(|mode| candidates.iter().map(move |candidate| (*mode, *candidate)))
        {
            let (covered, raw_turns, base_tokens) = match candidate {
                RetentionCandidate::CompletedTurns(retained_completed_count) => {
                    let Some(retained_start) =
                        retained_start_for_completed_count(closed_turns, retained_completed_count)
                    else {
                        continue;
                    };
                    let candidate_covered = &closed_turns[..retained_start];
                    if candidate_covered.iter().any(|turn| !turn.items.is_empty()) {
                        (
                            candidate_covered,
                            &turns[retained_start..],
                            window_budget
                                .replacement_fixed_dynamic_body_tokens()
                                .checked_add(window_budget.checkpoint_output_ceiling_tokens())
                                .ok_or(CompactionError::BudgetOverflow)?,
                        )
                    } else {
                        (
                            &closed_turns[..0],
                            turns,
                            window_budget.archive_only_fixed_dynamic_body_tokens(),
                        )
                    }
                }
                RetentionCandidate::ArchiveOnly => (
                    &closed_turns[..0],
                    turns,
                    window_budget.archive_only_fixed_dynamic_body_tokens(),
                ),
            };

            match plan_retained_window(
                window_budget,
                covered,
                raw_turns,
                base_tokens,
                fingerprint,
                RetainedWindowPolicy {
                    empty_coverage: candidate.empty_coverage_meaning(),
                    retained_fit: shape.retained_fit(),
                    archival,
                },
            )? {
                CandidateOutcome::Plan(plan) => return Ok(Some(plan)),
                CandidateOutcome::NothingToDo => return Ok(None),
                CandidateOutcome::DoesNotFit => {
                    if matches!(candidate, RetentionCandidate::CompletedTurns(1)) {
                        let existing_open_archives = existing_archived_tool_call_ids(open_turns);
                        let current_only_tokens = base_tokens
                            .checked_add(projected_turn_tokens(
                                open_turns,
                                &existing_open_archives,
                                window_budget.reasoning_tokens(),
                            )?)
                            .ok_or(CompactionError::BudgetOverflow)?;
                        let estimated_tokens =
                            window_budget.estimate_body_tokens(current_only_tokens);
                        let limit_tokens = window_budget.max_dynamic_body_tokens();
                        let error = if estimated_tokens >= limit_tokens {
                            CompactionError::UncompressibleCurrentInput {
                                estimated_tokens,
                                limit_tokens,
                            }
                        } else {
                            CompactionError::MinimumRawTurnCannotFit { limit_tokens }
                        };
                        last_failure = Some(error);
                    } else if last_failure.is_none() {
                        last_failure = Some(CompactionError::NoWindowFitsCompactionRequest);
                    }
                }
            }
        }

        match last_failure {
            Some(error) => Err(error.into()),
            None => {
                // Every retention candidate needs one completed turn to retain,
                // so an empty candidate list means the history holds no completed
                // turn at all. That case can still be uncompressible when the open
                // turns alone exceed the body budget.
                if available_completed == 0 {
                    let existing_open_archives = existing_archived_tool_call_ids(open_turns);
                    let current_only_tokens = window_budget
                        .archive_only_fixed_dynamic_body_tokens()
                        .checked_add(projected_turn_tokens(
                            open_turns,
                            &existing_open_archives,
                            window_budget.reasoning_tokens(),
                        )?)
                        .ok_or(CompactionError::BudgetOverflow)?;
                    let estimated_tokens = window_budget.estimate_body_tokens(current_only_tokens);
                    let limit_tokens = window_budget.max_dynamic_body_tokens();
                    if estimated_tokens >= limit_tokens {
                        return Err(CompactionError::UncompressibleCurrentInput {
                            estimated_tokens,
                            limit_tokens,
                        }
                        .into());
                    }
                }
                Ok(None)
            }
        }
    }

    /// Returns the retention options to evaluate, in preference order.
    ///
    /// Without a coverage budget the planner keeps the configured retention and
    /// falls back to smaller raw tails when the request body does not fit. With a
    /// budget, the covered window itself must fit one compaction request, so the
    /// planner retains more completed turns until the covered payload fits;
    /// covering less than the configured retention would only grow the payload the
    /// budget just rejected.
    fn retention_candidates(
        &self,
        policy: CitationCompactionPolicy,
        coverage: CompactionCoverageBudget,
        shape: CompactionShape,
        closed_turns: &[ModelTurnHistory<'_>],
        available_completed: usize,
    ) -> Result<Vec<RetentionCandidate>, RuntimeError> {
        let Some(coverage_budget) = coverage.max_tokens() else {
            return Ok(
                retained_turn_fallbacks(policy.retained_model_turns(), available_completed)
                    .into_iter()
                    .map(RetentionCandidate::CompletedTurns)
                    .collect(),
            );
        };
        let configured = policy
            .retained_model_turns()
            .min(available_completed)
            .max(1);
        for retained_completed_count in configured..=available_completed {
            let Some(retained_start) =
                retained_start_for_completed_count(closed_turns, retained_completed_count)
            else {
                continue;
            };
            if covered_payload_tokens(
                &closed_turns[..retained_start],
                shape == CompactionShape::RollingText,
            )? <= coverage_budget
            {
                return Ok(vec![RetentionCandidate::CompletedTurns(
                    retained_completed_count,
                )]);
            }
        }
        Ok(Vec::new())
    }
}

/// Evaluates one covered/retained split against the request body budget.
///
/// Returns the plan when the split fits, `NothingToDo` when an empty covered set
/// means there is nothing to summarize, and `DoesNotFit` when neither the split
/// nor additional tool-result archiving brings the projection under the body
/// budget. `empty_coverage` carries what an empty covered set means for the
/// candidate being evaluated.
fn plan_retained_window(
    window_budget: CompactionWindowBudget,
    covered: &[ModelTurnHistory<'_>],
    raw_turns: &[ModelTurnHistory<'_>],
    base_tokens: u64,
    fingerprint: CompactionWindowFingerprint,
    policy: RetainedWindowPolicy,
) -> Result<CandidateOutcome, RuntimeError> {
    let mut archived_tool_call_ids = existing_archived_tool_call_ids(raw_turns);
    let fits = |archived_tool_call_ids: &BTreeSet<ToolCallId>| {
        retained_projection_fits(
            base_tokens,
            raw_turns,
            archived_tool_call_ids,
            window_budget,
        )
    };

    if fits(&archived_tool_call_ids)? {
        if covered.is_empty() && policy.empty_coverage == EmptyCoverage::NothingToDo {
            return Ok(CandidateOutcome::NothingToDo);
        }
        return Ok(CandidateOutcome::Plan(compaction_window_plan(
            covered,
            raw_turns,
            archived_tool_call_ids,
            fingerprint,
        )?));
    }

    if policy.archival == ToolArchival::Preserve {
        return Ok(CandidateOutcome::DoesNotFit);
    }
    let mut archive_candidates = raw_turns
        .iter()
        .flat_map(ModelTurnHistory::archive_candidates_in_result_order)
        .collect::<Vec<_>>();
    archive_candidates.sort_by_key(|(result_item_id, _)| *result_item_id);
    for (_, call_id) in archive_candidates {
        archived_tool_call_ids.insert(call_id);
        if fits(&archived_tool_call_ids)? {
            return Ok(CandidateOutcome::Plan(compaction_window_plan(
                covered,
                raw_turns,
                archived_tool_call_ids,
                fingerprint,
            )?));
        }
    }

    match policy.retained_fit {
        RetainedFit::Required => Ok(CandidateOutcome::DoesNotFit),
        // Another pass follows, so install the largest covered window instead of
        // reporting that nothing fits. The wait for the budget to hold moves to the
        // caller, which recompiles and decides whether to run one more pass.
        RetainedFit::Deferred => Ok(CandidateOutcome::Plan(compaction_window_plan(
            covered,
            raw_turns,
            existing_archived_tool_call_ids(raw_turns),
            fingerprint,
        )?)),
    }
}

pub(super) fn retained_start_for_completed_count(
    closed_turns: &[ModelTurnHistory<'_>],
    retained_completed_count: usize,
) -> Option<usize> {
    let mut completed_seen = 0;
    closed_turns
        .iter()
        .enumerate()
        .rev()
        .find_map(|(index, turn)| {
            if turn.status == ModelTurnStatus::Completed {
                completed_seen += 1;
                (completed_seen == retained_completed_count).then_some(index)
            } else {
                None
            }
        })
}

pub(super) fn existing_archived_tool_call_ids(
    turns: &[ModelTurnHistory<'_>],
) -> BTreeSet<ToolCallId> {
    turns
        .iter()
        .flat_map(ModelTurnHistory::existing_archived_tool_call_ids)
        .collect()
}

pub(super) fn archived_refs_for_plan(
    turns: &[ModelTurnHistory<'_>],
    plan: &CompactionWindowPlan,
) -> Result<Vec<CheckpointRef>, RuntimeError> {
    let mut found_call_ids = BTreeSet::new();
    let mut refs = Vec::new();
    for turn in turns {
        if !plan.retained_turn_ids().contains(&turn.id) {
            continue;
        }
        for record in &turn.items {
            let Some((result_item_id, call_id, _)) = record.item.tool_result_archive_candidate()
            else {
                continue;
            };
            if plan.archived_tool_call_ids().contains(&call_id) {
                found_call_ids.insert(call_id);
                refs.push((result_item_id, record.reference.clone()));
            }
        }
    }
    if found_call_ids != *plan.archived_tool_call_ids() {
        return Err(CompactionError::StaleWindow.into());
    }
    refs.sort_by_key(|(result_item_id, _)| *result_item_id);
    Ok(refs.into_iter().map(|(_, reference)| reference).collect())
}

pub(super) fn projected_turn_tokens(
    turns: &[ModelTurnHistory<'_>],
    archived_tool_call_ids: &BTreeSet<ToolCallId>,
    reasoning_tokens: ReasoningTokenAccounting,
) -> Result<u64, RuntimeError> {
    turns.iter().try_fold(0_u64, |total, turn| {
        total
            .checked_add(turn.projected_token_estimate(archived_tool_call_ids, reasoning_tokens)?)
            .ok_or_else(|| RuntimeError::from(CompactionError::BudgetOverflow))
    })
}

pub(super) fn retained_projection_fits(
    base_tokens: u64,
    raw_turns: &[ModelTurnHistory<'_>],
    archived_tool_call_ids: &BTreeSet<ToolCallId>,
    window_budget: CompactionWindowBudget,
) -> Result<bool, RuntimeError> {
    let base_tokens = base_tokens
        .checked_add(projected_turn_tokens(
            raw_turns,
            archived_tool_call_ids,
            window_budget.reasoning_tokens(),
        )?)
        .ok_or(CompactionError::BudgetOverflow)?;
    Ok(window_budget.estimate_body_tokens(base_tokens) < window_budget.max_dynamic_body_tokens())
}

pub(super) fn compaction_window_plan(
    covered: &[ModelTurnHistory<'_>],
    raw_turns: &[ModelTurnHistory<'_>],
    archived_tool_call_ids: BTreeSet<ToolCallId>,
    fingerprint: CompactionWindowFingerprint,
) -> Result<CompactionWindowPlan, RuntimeError> {
    Ok(CompactionWindowPlan::new(
        covered.iter().map(|turn| turn.id).collect(),
        raw_turns.iter().map(|turn| turn.id).collect(),
        archived_tool_call_ids,
        covered.last().map(|turn| turn.id),
        fingerprint,
    ))
}