causa_runtime/budget.rs
1//! Reference frame-materialization policy — window budget, compaction seam,
2//! token counter, and the canonical [`FramePolicy`] carrier. These are this
3//! component's budget opinions, not fact-layer invariants. A custom host
4//! composes the kernel's lossless projection (`TurnContext::frame`)
5//! differently.
6//!
7//! The policy orchestrates materialization itself: the fact machine offers
8//! only the lossless projection and never awaits behavior, so compaction
9//! output is frame-local and never written back into fact state.
10
11use causa_kernel::{ContextBlock, ContextFrame, RoundId, TurnContext};
12
13/// Trigger thresholds for frame materialization, in estimated tokens. A pure
14/// value: the trigger check reads only `compaction_trigger`; the full budget
15/// rides along to the compaction implementation via [`CompactionInput`].
16#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
17pub struct WindowBudget {
18 /// Upper bound of the model's context window, in estimated tokens.
19 /// Consulted by compaction implementations, not by the trigger check.
20 pub model_window_limit: usize,
21 /// Estimated-token threshold at or above which [`WindowBudget::should_compact`]
22 /// fires. The default `usize::MAX` means "never trigger".
23 pub compaction_trigger: usize,
24}
25impl WindowBudget {
26 /// Whether frame materialization should compact: true when
27 /// `estimated_tokens` has reached the `compaction_trigger`.
28 pub fn should_compact(&self, estimated_tokens: usize) -> bool {
29 estimated_tokens >= self.compaction_trigger
30 }
31}
32impl Default for WindowBudget {
33 fn default() -> Self {
34 Self {
35 model_window_limit: usize::MAX,
36 compaction_trigger: usize::MAX,
37 }
38 }
39}
40
41/// Input handed to a [`Compaction`] implementation: the blocks to reduce,
42/// the budget in force, and the estimate that tripped the trigger.
43pub struct CompactionInput {
44 /// The current lossless block projection to compact. Input only —
45 /// fact state is never mutated by compaction.
46 pub blocks: Vec<ContextBlock>,
47 /// The [`WindowBudget`] in force, including `model_window_limit` for
48 /// the implementation's use.
49 pub budget: WindowBudget,
50 /// The token estimate that tripped `should_compact`.
51 pub estimated_tokens: usize,
52}
53/// `summary` is host-observation only; if a summary must be model-visible,
54/// the implementation folds it into `blocks` itself — `materialize`
55/// emits `out.blocks` and never appends `summary`.
56pub struct CompactionOutput {
57 /// The replacement block list that `materialize` projects. Frame-local —
58 /// never written back into fact state.
59 pub blocks: Vec<ContextBlock>,
60 /// Host-observation-only summary block, if the implementation produced
61 /// one. Never appended to the frame.
62 pub summary: Option<ContextBlock>,
63 /// True when the output is not a lossless projection of
64 /// [`CompactionInput::blocks`] — content was dropped or condensed.
65 pub truncated: bool,
66}
67
68/// Failure of a [`Compaction`] implementation — the only error it may report.
69#[derive(Debug, thiserror::Error)]
70pub enum CompactionError {
71 /// Compaction failed; carries the implementation-defined reason.
72 #[error("compaction failed: {0}")]
73 Failed(String),
74}
75
76/// Compaction port: reduce a block list to fit the window budget. Async and
77/// host-pluggable; the output is frame-local (see [`CompactionOutput`]) and
78/// never written back into fact state.
79#[async_trait::async_trait]
80pub trait Compaction: Send + Sync {
81 /// Compact `input.blocks` under `input.budget`, returning the
82 /// replacement blocks plus an optional host-only summary.
83 async fn compact(&self, input: CompactionInput) -> Result<CompactionOutput, CompactionError>;
84}
85
86/// Purely synchronous estimation interface; no async_trait needed.
87pub trait TokenCounter: Send + Sync {
88 /// Estimated token count for a block list.
89 fn estimate(&self, blocks: &[ContextBlock]) -> usize;
90 /// Estimated token count for a single JSON value; the executor uses it
91 /// to size tool outputs before limit-based truncation.
92 fn estimate_value(&self, value: &serde_json::Value) -> usize;
93}
94
95/// Error of policy-driven frame materialization: the only fallible step is
96/// the compaction port.
97#[derive(Debug, thiserror::Error)]
98pub enum FrameError {
99 /// The wired [`Compaction`] port failed; carries its error message.
100 #[error("compaction failed: {0}")]
101 CompactionFailed(String),
102}
103
104/// Carrier of the frame-materialization policy: trigger budget, optional
105/// compaction, optional token counter. A runtime value assembled
106/// from port instances — the driver builds and owns it, and it orchestrates
107/// materialization itself, using only the fact machine's public accessors.
108/// Placeholder semantics stay frame-local and non-persisting.
109#[derive(Clone, Default)]
110pub struct FramePolicy {
111 /// Trigger thresholds; the all-`usize::MAX` default never trips
112 /// compaction.
113 pub window_budget: WindowBudget,
114 /// Compaction port applied when the trigger fires; absent means the
115 /// lossless frame is always used.
116 pub compaction: Option<std::sync::Arc<dyn Compaction>>,
117 /// Token counter backing [`FramePolicy::estimate`]; absent means a zero
118 /// estimate, which never triggers compaction.
119 pub token_counter: Option<std::sync::Arc<dyn TokenCounter>>,
120}
121impl std::fmt::Debug for FramePolicy {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 f.debug_struct("FramePolicy")
124 .field("window_budget", &self.window_budget)
125 .field("compaction", &self.compaction.is_some())
126 .field("token_counter", &self.token_counter.is_some())
127 .finish()
128 }
129}
130impl FramePolicy {
131 /// Token estimate for a block list: the supplied counter if any,
132 /// else 0. A zero estimate never trips `should_compact` (default
133 /// `WindowBudget` thresholds are `usize::MAX`), so compaction is
134 /// genuinely opt-in via a wired `TokenCounter`.
135 pub fn estimate(&self, blocks: &[ContextBlock]) -> usize {
136 if let Some(counter) = &self.token_counter {
137 counter.estimate(blocks)
138 } else {
139 0
140 }
141 }
142
143 /// Materialize the model context for `round_id` under this policy.
144 /// Trigger evaluation stays canonical — the same state and the same
145 /// policy always yield the same frame. Compaction output is frame-local
146 /// and never written back into the fact state; the fact machine itself
147 /// only ever offers the lossless projection and never awaits behavior.
148 pub async fn materialize(
149 &self,
150 ctx: &TurnContext,
151 round_id: RoundId,
152 ) -> Result<ContextFrame, FrameError> {
153 let estimated = self.estimate(ctx.blocks());
154 if self.window_budget.should_compact(estimated)
155 && let Some(comp) = &self.compaction
156 {
157 let input = CompactionInput {
158 blocks: ctx.blocks().to_vec(),
159 budget: self.window_budget,
160 estimated_tokens: estimated,
161 };
162 let out = comp
163 .compact(input)
164 .await
165 .map_err(|e| FrameError::CompactionFailed(e.to_string()))?;
166 // Metadata-consistent projection: the lossless frame carries the
167 // deterministic frame identity; only the block list is replaced.
168 let mut frame = ctx.frame(round_id);
169 frame.model_context.blocks = out.blocks;
170 return Ok(frame);
171 }
172 Ok(ctx.frame(round_id))
173 }
174}