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