Skip to main content

causa_kernel/ports/
batch.rs

1//! Controlled tool-batch facts and the processor contract.
2
3use crate::context::block::{MediaRef, TextPayload, ToolCallPayload};
4use crate::context::ids::BlockId;
5use crate::context::ids::{RoundId, TurnId};
6use crate::context::tool_data::{ToolOutput, ToolResultPayload};
7use crate::ports::control::CallControl;
8use crate::ports::tool::ToolCallContext;
9use async_trait::async_trait;
10use std::collections::HashSet;
11
12/// A declaration plus its optional completed result.
13#[derive(Debug)]
14pub struct ToolCallEntry {
15    call: ToolCallContext,
16    result: Option<(BlockId, ToolResultPayload)>,
17}
18
19impl ToolCallEntry {
20    /// Borrows the declaration and effective execution input.
21    pub fn call(&self) -> &crate::ports::tool::ToolCallContext {
22        &self.call
23    }
24
25    /// Mutably borrows the input while this call is still pending.
26    pub fn input_mut(&mut self) -> Option<&mut ToolCallPayload> {
27        self.result.is_none().then_some(&mut self.call.input)
28    }
29
30    /// Borrows the result block ID and result payload when completed.
31    pub fn result(&self) -> Option<(&BlockId, &ToolResultPayload)> {
32        self.result.as_ref().map(|(id, result)| (id, result))
33    }
34
35    /// Mutably borrows output when this call has a result.
36    pub fn output_mut(&mut self) -> Option<&mut ToolOutput> {
37        self.result.as_mut().map(|(_, result)| &mut result.output)
38    }
39
40    /// Mutably borrows result media when this call has a result.
41    pub fn media_mut(&mut self) -> Option<&mut Vec<MediaRef>> {
42        self.result.as_mut().map(|(_, result)| &mut result.media)
43    }
44
45    /// Adds a note to the pending call or completed result as appropriate.
46    pub fn push_note(&mut self, note: TextPayload) {
47        match self.result.as_mut() {
48            Some((_, result)) => result.notes.push(note),
49            None => self.call.result_notes.push(note),
50        }
51    }
52}
53
54/// One tool batch with a completed prefix and pending suffix.
55#[derive(Debug)]
56pub struct ToolBatch {
57    entries: Vec<ToolCallEntry>,
58    completed: usize,
59}
60
61impl ToolBatch {
62    /// Creates a batch from declarations in their original order.
63    pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
64        let mut declarations = HashSet::with_capacity(calls.len());
65        for call in &calls {
66            if !declarations.insert(call.call_block_id) {
67                return Err(BatchError::DuplicateDeclaration(call.call_block_id));
68            }
69        }
70        let batch = Self {
71            entries: calls
72                .into_iter()
73                .map(|call| ToolCallEntry { call, result: None })
74                .collect(),
75            completed: 0,
76        };
77        batch.validate()?;
78        Ok(batch)
79    }
80
81    /// Returns the pending suffix.
82    pub fn calls(&self) -> &[ToolCallEntry] {
83        &self.entries[self.completed..]
84    }
85
86    /// Mutably returns the pending suffix.
87    pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
88        &mut self.entries[self.completed..]
89    }
90
91    /// Returns the completed prefix.
92    pub fn results(&self) -> &[ToolCallEntry] {
93        &self.entries[..self.completed]
94    }
95
96    /// Mutably returns the completed prefix for output editing and ordering.
97    pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
98        &mut self.entries[..self.completed]
99    }
100
101    /// Returns the number of completed entries.
102    pub fn completed_len(&self) -> usize {
103        self.completed
104    }
105
106    /// Returns declaration identities in the batch's current entry order.
107    pub fn declaration_ids(&self) -> Vec<BlockId> {
108        self.entries
109            .iter()
110            .map(|entry| entry.call.call_block_id)
111            .collect()
112    }
113
114    /// Validates the completed-prefix/pending-suffix and identity invariants.
115    pub fn validate(&self) -> Result<(), BatchError> {
116        if self.completed > self.entries.len() {
117            return Err(BatchError::InvalidPartition(format!(
118                "completed count {} exceeds entry count {}",
119                self.completed,
120                self.entries.len()
121            )));
122        }
123        let mut declarations = HashSet::with_capacity(self.entries.len());
124        for entry in &self.entries {
125            let declaration_id = entry.call.call_block_id;
126            if !declarations.insert(declaration_id) {
127                return Err(BatchError::DuplicateDeclaration(declaration_id));
128            }
129        }
130        let mut all_ids = declarations.clone();
131        for (index, entry) in self.entries.iter().enumerate() {
132            let declaration_id = entry.call.call_block_id;
133            match (index < self.completed, &entry.result) {
134                (true, Some((result_id, result))) => {
135                    if result.call_block_id != declaration_id {
136                        return Err(BatchError::MismatchedCall {
137                            expected: declaration_id,
138                            actual: result.call_block_id,
139                        });
140                    }
141                    if !all_ids.insert(*result_id) {
142                        return Err(BatchError::DuplicateResultBlockId(*result_id));
143                    }
144                }
145                (false, None) => {}
146                (true, None) => {
147                    return Err(BatchError::InvalidPartition(format!(
148                        "completed entry {index} has no result"
149                    )));
150                }
151                (false, Some(_)) => {
152                    return Err(BatchError::InvalidPartition(format!(
153                        "pending entry {index} already has a result"
154                    )));
155                }
156            }
157        }
158        Ok(())
159    }
160
161    /// Installs a result at an absolute entry index and advances the prefix.
162    /// A refused result leaves the batch unchanged and is handed back with
163    /// the reason, so a caller can retry or report it without a copy.
164    pub fn resolve_at(
165        &mut self,
166        index: usize,
167        result_block_id: BlockId,
168        mut result: ToolResultPayload,
169    ) -> Result<(), RejectedToolResult> {
170        if let Err(error) = self.check_resolve(index, result_block_id, &result) {
171            return Err(RejectedToolResult { error, result });
172        }
173        let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
174        notes.append(&mut result.notes);
175        result.notes = notes;
176        self.entries[index].result = Some((result_block_id, result));
177        self.entries.swap(index, self.completed);
178        self.completed += 1;
179        Ok(())
180    }
181
182    fn check_resolve(
183        &self,
184        index: usize,
185        result_block_id: BlockId,
186        result: &ToolResultPayload,
187    ) -> Result<(), BatchError> {
188        self.validate()?;
189        if index < self.completed || index >= self.entries.len() {
190            return Err(BatchError::InvalidIndex {
191                index,
192                completed: self.completed,
193                total: self.entries.len(),
194            });
195        }
196        let expected = self.entries[index].call.call_block_id;
197        if result.call_block_id != expected {
198            return Err(BatchError::MismatchedCall {
199                expected,
200                actual: result.call_block_id,
201            });
202        }
203        if self.entries[index].result.is_some() {
204            return Err(BatchError::InvalidPartition(format!(
205                "pending entry {index} already has a result"
206            )));
207        }
208        if self.entries.iter().any(|entry| {
209            entry.call.call_block_id == result_block_id
210                || entry
211                    .result
212                    .as_ref()
213                    .is_some_and(|(id, _)| *id == result_block_id)
214        }) {
215            return Err(BatchError::DuplicateResultBlockId(result_block_id));
216        }
217        Ok(())
218    }
219
220    /// Consumes a fully completed batch into result blocks in current order.
221    pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
222        if let Err(error) = self.validate() {
223            return Err((error, self));
224        }
225        if self.completed != self.entries.len() {
226            let error = BatchError::Incomplete {
227                completed: self.completed,
228                total: self.entries.len(),
229            };
230            return Err((error, self));
231        }
232        Ok(self
233            .entries
234            .into_iter()
235            .map(|entry| entry.result.expect("validated complete entry"))
236            .collect())
237    }
238}
239
240/// Context made available to tool batch processors.
241#[non_exhaustive]
242pub struct ProcessorContext<'a> {
243    /// Turn identity for the active tool batch.
244    pub turn_id: &'a TurnId,
245    /// Model round that declared this batch.
246    pub round_id: RoundId,
247    /// Original declaration order, represented by stable block IDs.
248    pub declaration_order: &'a [BlockId],
249    /// Cooperative cancellation and deadline control.
250    pub control: &'a CallControl,
251}
252impl<'a> ProcessorContext<'a> {
253    /// The context one processor run sees.
254    pub fn new(
255        turn_id: &'a TurnId,
256        round_id: RoundId,
257        declaration_order: &'a [BlockId],
258        control: &'a CallControl,
259    ) -> Self {
260        Self {
261            turn_id,
262            round_id,
263            declaration_order,
264            control,
265        }
266    }
267}
268
269/// Failure to finish a processing phase. Per-call rejection is a result,
270/// and should be recorded on the batch while returning `Ok(())`.
271#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
272#[non_exhaustive]
273pub enum ProcessorError {
274    /// The processor could not complete its phase.
275    #[error("processor failed: {0}")]
276    Failed(String),
277}
278
279/// A pre- or post-processing phase over one exclusively borrowed tool batch.
280#[async_trait]
281pub trait ToolBatchProcessor: Send + Sync {
282    /// Processes the batch in place; errors leave its current materials with
283    /// the caller and stop the chain.
284    async fn process(
285        &self,
286        batch: &mut ToolBatch,
287        ctx: &ProcessorContext<'_>,
288    ) -> Result<(), ProcessorError>;
289}
290
291/// Invalid batch construction, completion, or partition state.
292#[derive(Debug, thiserror::Error)]
293#[non_exhaustive]
294pub enum BatchError {
295    /// A declaration appears more than once in a batch.
296    #[error("duplicate declaration block id: {0:?}")]
297    DuplicateDeclaration(BlockId),
298    /// The requested absolute index is not in the pending suffix.
299    #[error("index {index} is not pending (completed {completed}, total {total})")]
300    InvalidIndex {
301        /// Requested entry index.
302        index: usize,
303        /// Number of entries in the completed prefix.
304        completed: usize,
305        /// Total entry count.
306        total: usize,
307    },
308    /// A result references a different declaration than its entry.
309    #[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
310    MismatchedCall {
311        /// Declaration identity expected by the entry.
312        expected: BlockId,
313        /// Declaration identity carried by the result.
314        actual: BlockId,
315    },
316    /// A result's own block identity collides within the batch.
317    #[error("duplicate result block ID: {0:?}")]
318    DuplicateResultBlockId(BlockId),
319    /// The completed prefix and pending suffix disagree with entry contents.
320    #[error("invalid batch partition: {0}")]
321    InvalidPartition(String),
322    /// Not all entries have results.
323    #[error("batch is incomplete: {completed} of {total} entries completed")]
324    Incomplete {
325        /// Number of completed entries.
326        completed: usize,
327        /// Total number of entries.
328        total: usize,
329    },
330}
331
332/// A result [`ToolBatch::resolve_at`] refused, returned with the reason.
333#[derive(Debug, thiserror::Error)]
334#[error("{error}")]
335#[non_exhaustive]
336pub struct RejectedToolResult {
337    /// Why the batch refused the result.
338    pub error: BatchError,
339    /// The refused result, unchanged.
340    pub result: ToolResultPayload,
341}