1use tea_protocol::ToolCallId;
2use tea_tools::{SchedulerClass, ValidatedToolInvocation};
3
4use crate::{KernelError, KernelErrorCode};
5
6#[derive(Debug, Clone, Copy, Default)]
14pub struct Scheduler;
15
16#[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 #[must_use]
26 pub const fn class(&self) -> SchedulerClass {
27 self.class
28 }
29 #[must_use]
31 pub fn invocations(&self) -> &[&'a ValidatedToolInvocation] {
32 &self.invocations
33 }
34 #[must_use]
36 pub fn allows_parallel(&self) -> bool {
37 self.class.allows_parallel_execution()
38 }
39}
40
41#[derive(Debug, Clone)]
43pub struct SchedulePlan<'a> {
44 lanes: Vec<Lane<'a>>,
45 source_order: Vec<ToolCallId>,
46}
47
48impl<'a> SchedulePlan<'a> {
49 #[must_use]
51 pub fn lanes(&self) -> &[Lane<'a>] {
52 &self.lanes
53 }
54 #[must_use]
56 pub fn len(&self) -> usize {
57 self.source_order.len()
58 }
59 #[must_use]
61 pub fn is_empty(&self) -> bool {
62 self.source_order.is_empty()
63 }
64 #[must_use]
66 pub fn source_order(&self) -> &[ToolCallId] {
67 &self.source_order
68 }
69}
70
71impl Scheduler {
72 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}