Skip to main content

tea_kernel/
scheduler.rs

1use tea_protocol::ToolCallId;
2use tea_tools::{SchedulerClass, ValidatedToolInvocation};
3
4use crate::{KernelError, KernelErrorCode};
5
6/// Effect-aware tool scheduler producing lane assignments only.
7///
8/// The scheduler never executes tools. It partitions validated invocations by
9/// `SchedulerClass` so the kernel can run parallel-safe work concurrently while
10/// serializing mutation and granting exclusive work its own lane. Source order
11/// within a lane is preserved; the kernel commits results in canonical source
12/// order regardless of completion order.
13#[derive(Debug, Clone, Copy, Default)]
14pub struct Scheduler;
15
16/// One scheduler lane containing invocations that share an execution rule.
17#[derive(Debug, Clone)]
18pub struct Lane<'a> {
19    pub(crate) class: SchedulerClass,
20    pub(crate) invocations: Vec<&'a ValidatedToolInvocation>,
21}
22
23impl<'a> Lane<'a> {
24    /// Returns the lane's scheduler class.
25    #[must_use]
26    pub const fn class(&self) -> SchedulerClass {
27        self.class
28    }
29    /// Returns the invocations assigned to this lane in source order.
30    #[must_use]
31    pub fn invocations(&self) -> &[&'a ValidatedToolInvocation] {
32        &self.invocations
33    }
34    /// Returns whether invocations in this lane may execute concurrently.
35    #[must_use]
36    pub fn allows_parallel(&self) -> bool {
37        self.class.allows_parallel_execution()
38    }
39}
40
41/// Immutable plan of lane assignments for one model turn.
42#[derive(Debug, Clone)]
43pub struct SchedulePlan<'a> {
44    lanes: Vec<Lane<'a>>,
45    source_order: Vec<ToolCallId>,
46}
47
48impl<'a> SchedulePlan<'a> {
49    /// Returns the assigned lanes.
50    #[must_use]
51    pub fn lanes(&self) -> &[Lane<'a>] {
52        &self.lanes
53    }
54    /// Returns the count of scheduled invocations.
55    #[must_use]
56    pub fn len(&self) -> usize {
57        self.source_order.len()
58    }
59    /// Returns whether the plan scheduled no invocations.
60    #[must_use]
61    pub fn is_empty(&self) -> bool {
62        self.source_order.is_empty()
63    }
64    /// Returns the canonical source-order tool-call identifiers.
65    #[must_use]
66    pub fn source_order(&self) -> &[ToolCallId] {
67        &self.source_order
68    }
69}
70
71impl Scheduler {
72    /// Partitions validated invocations into scheduler lanes.
73    ///
74    /// # Errors
75    ///
76    /// Returns a `SchedulerConflict` for any invocation whose
77    /// `SchedulerClass::requires_policy()` is true (unknown effects). The
78    /// scheduler never auto-schedules policy-required work.
79    pub fn plan<'a>(
80        &self,
81        invocations: &'a [&'a ValidatedToolInvocation],
82    ) -> Result<SchedulePlan<'a>, KernelError> {
83        if invocations
84            .iter()
85            .any(|invocation| invocation.scheduler_class().requires_policy())
86        {
87            return Err(KernelError::new(
88                KernelErrorCode::SchedulerConflict,
89                "tool invocation requires policy before scheduling",
90            ));
91        }
92        let source_order = invocations
93            .iter()
94            .map(|invocation| *invocation.tool_call_id())
95            .collect();
96        let mut parallel: Vec<&ValidatedToolInvocation> = Vec::new();
97        let mut serial: Vec<&ValidatedToolInvocation> = Vec::new();
98        let mut exclusive: Vec<&ValidatedToolInvocation> = Vec::new();
99        for invocation in invocations {
100            match invocation.scheduler_class() {
101                SchedulerClass::ParallelReadOnly | SchedulerClass::ParallelRetrySafe => {
102                    parallel.push(invocation);
103                }
104                SchedulerClass::Serial => serial.push(invocation),
105                SchedulerClass::Exclusive => exclusive.push(invocation),
106                SchedulerClass::PolicyRequired => {
107                    return Err(KernelError::new(
108                        KernelErrorCode::SchedulerConflict,
109                        "tool invocation requires policy before scheduling",
110                    ));
111                }
112            }
113        }
114        let mut lanes = Vec::new();
115        if !parallel.is_empty() {
116            lanes.push(Lane {
117                class: SchedulerClass::ParallelReadOnly,
118                invocations: parallel,
119            });
120        }
121        if !serial.is_empty() {
122            lanes.push(Lane {
123                class: SchedulerClass::Serial,
124                invocations: serial,
125            });
126        }
127        for invocation in exclusive {
128            lanes.push(Lane {
129                class: SchedulerClass::Exclusive,
130                invocations: vec![invocation],
131            });
132        }
133        Ok(SchedulePlan {
134            lanes,
135            source_order,
136        })
137    }
138}