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, ToolDescription, ToolHints};
9use async_trait::async_trait;
10use std::any::Any;
11use std::collections::HashSet;
12use std::sync::Arc;
13
14/// A declaration plus its optional completed result.
15#[derive(Debug)]
16pub struct ToolCallEntry {
17    call: ToolCallContext,
18    result: Option<(BlockId, ToolResultPayload)>,
19}
20
21impl ToolCallEntry {
22    /// Borrows the declaration and effective execution input.
23    pub fn call(&self) -> &crate::ports::tool::ToolCallContext {
24        &self.call
25    }
26
27    /// Mutably borrows the input while this call is still pending.
28    pub fn input_mut(&mut self) -> Option<&mut ToolCallPayload> {
29        self.result.is_none().then_some(&mut self.call.input)
30    }
31
32    /// Borrows the result block ID and result payload when completed.
33    pub fn result(&self) -> Option<(&BlockId, &ToolResultPayload)> {
34        self.result.as_ref().map(|(id, result)| (id, result))
35    }
36
37    /// Mutably borrows output when this call has a result.
38    pub fn output_mut(&mut self) -> Option<&mut ToolOutput> {
39        self.result.as_mut().map(|(_, result)| &mut result.output)
40    }
41
42    /// Mutably borrows result media when this call has a result.
43    pub fn media_mut(&mut self) -> Option<&mut Vec<MediaRef>> {
44        self.result.as_mut().map(|(_, result)| &mut result.media)
45    }
46
47    /// Adds a note to the pending call or completed result as appropriate.
48    pub fn push_note(&mut self, note: TextPayload) {
49        match self.result.as_mut() {
50            Some((_, result)) => result.notes.push(note),
51            None => self.call.result_notes.push(note),
52        }
53    }
54}
55
56/// One tool batch with a completed prefix and pending suffix.
57///
58/// Each result joins the end of the completed prefix as it is resolved, so
59/// the prefix is in resolution order: with concurrent dispatch, the order the
60/// calls completed in, not the order the model declared them in. That order
61/// is what [`ToolBatch::into_results`] returns and what a runner commits. To
62/// keep declaration order instead, sort [`ToolBatch::results_mut`] by
63/// [`ProcessorContext::declaration_order`] in a processor that runs after
64/// dispatch.
65#[derive(Debug)]
66pub struct ToolBatch {
67    entries: Vec<ToolCallEntry>,
68    completed: usize,
69}
70
71impl ToolBatch {
72    /// Creates a batch from declarations in their original order.
73    pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
74        let mut declarations = HashSet::with_capacity(calls.len());
75        for call in &calls {
76            if !declarations.insert(call.call_block_id) {
77                return Err(BatchError::DuplicateDeclaration(call.call_block_id));
78            }
79        }
80        let batch = Self {
81            entries: calls
82                .into_iter()
83                .map(|call| ToolCallEntry { call, result: None })
84                .collect(),
85            completed: 0,
86        };
87        batch.validate()?;
88        Ok(batch)
89    }
90
91    /// Returns the pending suffix.
92    pub fn calls(&self) -> &[ToolCallEntry] {
93        &self.entries[self.completed..]
94    }
95
96    /// Mutably returns the pending suffix.
97    pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
98        &mut self.entries[self.completed..]
99    }
100
101    /// Returns the completed prefix.
102    pub fn results(&self) -> &[ToolCallEntry] {
103        &self.entries[..self.completed]
104    }
105
106    /// Mutably returns the completed prefix for output editing and ordering.
107    pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
108        &mut self.entries[..self.completed]
109    }
110
111    /// Returns the number of completed entries.
112    pub fn completed_len(&self) -> usize {
113        self.completed
114    }
115
116    /// Returns declaration identities in the batch's current entry order.
117    pub fn declaration_ids(&self) -> Vec<BlockId> {
118        self.entries
119            .iter()
120            .map(|entry| entry.call.call_block_id)
121            .collect()
122    }
123
124    /// Validates the completed-prefix/pending-suffix and identity invariants.
125    pub fn validate(&self) -> Result<(), BatchError> {
126        if self.completed > self.entries.len() {
127            return Err(BatchError::InvalidPartition(format!(
128                "completed count {} exceeds entry count {}",
129                self.completed,
130                self.entries.len()
131            )));
132        }
133        let mut declarations = HashSet::with_capacity(self.entries.len());
134        for entry in &self.entries {
135            let declaration_id = entry.call.call_block_id;
136            if !declarations.insert(declaration_id) {
137                return Err(BatchError::DuplicateDeclaration(declaration_id));
138            }
139        }
140        let mut all_ids = declarations.clone();
141        for (index, entry) in self.entries.iter().enumerate() {
142            let declaration_id = entry.call.call_block_id;
143            match (index < self.completed, &entry.result) {
144                (true, Some((result_id, result))) => {
145                    if result.call_block_id != declaration_id {
146                        return Err(BatchError::MismatchedCall {
147                            expected: declaration_id,
148                            actual: result.call_block_id,
149                        });
150                    }
151                    if !all_ids.insert(*result_id) {
152                        return Err(BatchError::DuplicateResultBlockId(*result_id));
153                    }
154                }
155                (false, None) => {}
156                (true, None) => {
157                    return Err(BatchError::InvalidPartition(format!(
158                        "completed entry {index} has no result"
159                    )));
160                }
161                (false, Some(_)) => {
162                    return Err(BatchError::InvalidPartition(format!(
163                        "pending entry {index} already has a result"
164                    )));
165                }
166            }
167        }
168        Ok(())
169    }
170
171    /// Installs a result at an absolute entry index and advances the prefix.
172    /// A refused result leaves the batch unchanged and is handed back with
173    /// the reason, so a caller can retry or report it without a copy.
174    pub fn resolve_at(
175        &mut self,
176        index: usize,
177        result_block_id: BlockId,
178        mut result: ToolResultPayload,
179    ) -> Result<(), RejectedToolResult> {
180        if let Err(error) = self.check_resolve(index, result_block_id, &result) {
181            return Err(RejectedToolResult { error, result });
182        }
183        let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
184        notes.append(&mut result.notes);
185        result.notes = notes;
186        self.entries[index].result = Some((result_block_id, result));
187        self.entries.swap(index, self.completed);
188        self.completed += 1;
189        Ok(())
190    }
191
192    fn check_resolve(
193        &self,
194        index: usize,
195        result_block_id: BlockId,
196        result: &ToolResultPayload,
197    ) -> Result<(), BatchError> {
198        self.validate()?;
199        if index < self.completed || index >= self.entries.len() {
200            return Err(BatchError::InvalidIndex {
201                index,
202                completed: self.completed,
203                total: self.entries.len(),
204            });
205        }
206        let expected = self.entries[index].call.call_block_id;
207        if result.call_block_id != expected {
208            return Err(BatchError::MismatchedCall {
209                expected,
210                actual: result.call_block_id,
211            });
212        }
213        if self.entries[index].result.is_some() {
214            return Err(BatchError::InvalidPartition(format!(
215                "pending entry {index} already has a result"
216            )));
217        }
218        if self.entries.iter().any(|entry| {
219            entry.call.call_block_id == result_block_id
220                || entry
221                    .result
222                    .as_ref()
223                    .is_some_and(|(id, _)| *id == result_block_id)
224        }) {
225            return Err(BatchError::DuplicateResultBlockId(result_block_id));
226        }
227        Ok(())
228    }
229
230    /// Validates the invariants and that every entry has a result.
231    pub fn validate_complete(&self) -> Result<(), BatchError> {
232        self.validate()?;
233        if self.completed != self.entries.len() {
234            return Err(BatchError::Incomplete {
235                completed: self.completed,
236                total: self.entries.len(),
237            });
238        }
239        Ok(())
240    }
241
242    /// Consumes a fully completed batch into result blocks in current order.
243    pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
244        if let Err(error) = self.validate_complete() {
245            return Err((error, self));
246        }
247        Ok(self
248            .entries
249            .into_iter()
250            .map(|entry| entry.result.expect("validated complete entry"))
251            .collect())
252    }
253}
254
255/// Context made available to tool batch processors.
256#[non_exhaustive]
257pub struct ProcessorContext<'a> {
258    /// Turn identity for the active tool batch.
259    pub turn_id: &'a TurnId,
260    /// Model round that declared this batch.
261    pub round_id: RoundId,
262    /// Original declaration order, represented by stable block IDs. The batch's
263    /// own entry order changes as results are resolved; this does not.
264    pub declaration_order: &'a [BlockId],
265    /// Cooperative cancellation and deadline control.
266    pub control: &'a CallControl,
267    /// The tools bound for this batch, in offer order, with their declared
268    /// hints. The reference executor fixes them when it binds, so they stay
269    /// the same for every processor of the batch. Empty unless set with
270    /// [`ProcessorContext::with_tools`].
271    pub tools: &'a [ToolDescription],
272    /// The host's data for this run, passed through unchanged. `None` unless
273    /// set with [`ProcessorContext::with_data`].
274    pub data: Option<&'a ProcessorData>,
275}
276impl<'a> ProcessorContext<'a> {
277    /// The context one processor run sees, with no bound tools and no host
278    /// data.
279    pub fn new(
280        turn_id: &'a TurnId,
281        round_id: RoundId,
282        declaration_order: &'a [BlockId],
283        control: &'a CallControl,
284    ) -> Self {
285        Self {
286            turn_id,
287            round_id,
288            declaration_order,
289            control,
290            tools: &[],
291            data: None,
292        }
293    }
294
295    /// Sets the bound tools and their hints.
296    pub fn with_tools(mut self, tools: &'a [ToolDescription]) -> Self {
297        self.tools = tools;
298        self
299    }
300
301    /// Sets the host's data for this run.
302    pub fn with_data(mut self, data: &'a ProcessorData) -> Self {
303        self.data = Some(data);
304        self
305    }
306
307    /// The declared hints of the bound tool named `name`, or `None` when no
308    /// bound tool has that name. The reference executor rejects calls to
309    /// unbound names before the first processor runs, so every pending call
310    /// it hands to a processor resolves here.
311    pub fn hints(&self, name: &str) -> Option<&'a ToolHints> {
312        self.tools
313            .iter()
314            .find(|tool| tool.definition.name == name)
315            .map(|tool| &tool.hints)
316    }
317
318    /// The host's data when it is a `T`: `None` when no data is set or it
319    /// holds another type.
320    pub fn data<T: Any>(&self) -> Option<&'a T> {
321        self.data.and_then(ProcessorData::get)
322    }
323}
324
325/// Host data for one run, handed to every tool processor through
326/// [`ProcessorContext::data`].
327///
328/// Processors belong to an executor that serves many runs, so state that
329/// differs from run to run — a permission mode, the acting user — travels
330/// here rather than in the processor. The host chooses the type; a host with
331/// several values passes one struct of its own. Causa passes the value
332/// through and never inspects or copies it, so a host whose state changes
333/// during a run stores a shared handle (an `Arc` around a lock or an atomic)
334/// and a processor reads the current value when it decides each call.
335#[derive(Clone)]
336pub struct ProcessorData(Arc<dyn Any + Send + Sync>);
337
338impl ProcessorData {
339    /// Wraps the host's value.
340    pub fn new<T: Any + Send + Sync>(value: T) -> Self {
341        Self(Arc::new(value))
342    }
343
344    /// The value when it is exactly a `T`, the type given to
345    /// [`ProcessorData::new`]; `None` otherwise.
346    pub fn get<T: Any>(&self) -> Option<&T> {
347        self.0.downcast_ref()
348    }
349}
350
351impl std::fmt::Debug for ProcessorData {
352    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353        f.debug_struct("ProcessorData").finish_non_exhaustive()
354    }
355}
356
357/// Failure to finish a processing phase. Per-call rejection is a result,
358/// and should be recorded on the batch while returning `Ok(())`.
359#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
360#[non_exhaustive]
361pub enum ProcessorError {
362    /// The processor could not complete its phase.
363    #[error("processor failed: {0}")]
364    Failed(String),
365}
366
367/// A pre- or post-processing phase over one exclusively borrowed tool batch.
368#[async_trait]
369pub trait ToolBatchProcessor: Send + Sync {
370    /// Processes the batch in place; errors leave its current materials with
371    /// the caller and stop the chain.
372    async fn process(
373        &self,
374        batch: &mut ToolBatch,
375        ctx: &ProcessorContext<'_>,
376    ) -> Result<(), ProcessorError>;
377}
378
379/// Invalid batch construction, completion, or partition state.
380#[derive(Debug, thiserror::Error)]
381#[non_exhaustive]
382pub enum BatchError {
383    /// A declaration appears more than once in a batch.
384    #[error("duplicate declaration block id: {0:?}")]
385    DuplicateDeclaration(BlockId),
386    /// The requested absolute index is not in the pending suffix.
387    #[error("index {index} is not pending (completed {completed}, total {total})")]
388    #[non_exhaustive]
389    InvalidIndex {
390        /// Requested entry index.
391        index: usize,
392        /// Number of entries in the completed prefix.
393        completed: usize,
394        /// Total entry count.
395        total: usize,
396    },
397    /// A result references a different declaration than its entry.
398    #[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
399    #[non_exhaustive]
400    MismatchedCall {
401        /// Declaration identity expected by the entry.
402        expected: BlockId,
403        /// Declaration identity carried by the result.
404        actual: BlockId,
405    },
406    /// A result's own block identity collides within the batch.
407    #[error("duplicate result block ID: {0:?}")]
408    DuplicateResultBlockId(BlockId),
409    /// The completed prefix and pending suffix disagree with entry contents.
410    #[error("invalid batch partition: {0}")]
411    InvalidPartition(String),
412    /// Not all entries have results.
413    #[error("batch is incomplete: {completed} of {total} entries completed")]
414    #[non_exhaustive]
415    Incomplete {
416        /// Number of completed entries.
417        completed: usize,
418        /// Total number of entries.
419        total: usize,
420    },
421}
422
423/// A result [`ToolBatch::resolve_at`] refused, returned with the reason.
424#[derive(Debug, thiserror::Error)]
425#[error("{error}")]
426#[non_exhaustive]
427pub struct RejectedToolResult {
428    /// Why the batch refused the result.
429    pub error: BatchError,
430    /// The refused result, unchanged.
431    pub result: ToolResultPayload,
432}