1use chrono::Utc;
8use meerkat_core::lifecycle::InputId;
9
10use crate::identifiers::{LogicalRuntimeId, SupersessionKey};
11use crate::input::{Input, PeerConvention};
12use crate::input_machine::{InputStateMachine, InputStateMachineError};
13use crate::input_state::{InputLifecycleState, InputState, InputTerminalOutcome};
14
15pub fn is_coalescing_eligible(input: &Input) -> bool {
17 matches!(
18 input,
19 Input::ExternalEvent(_)
20 | Input::Peer(crate::input::PeerInput {
21 convention: Some(PeerConvention::ResponseProgress { .. }),
22 ..
23 })
24 )
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Hash)]
29pub struct SupersessionScope {
30 pub runtime_id: LogicalRuntimeId,
31 pub kind: String,
32 pub supersession_key: SupersessionKey,
33}
34
35impl SupersessionScope {
36 pub fn from_input(input: &Input, runtime_id: &LogicalRuntimeId) -> Option<Self> {
38 let key = input.header().supersession_key.as_ref()?;
39 Some(Self {
40 runtime_id: runtime_id.clone(),
41 kind: input.kind_id().0,
42 supersession_key: key.clone(),
43 })
44 }
45}
46
47#[derive(Debug)]
49pub enum CoalescingResult {
50 Standalone,
52 Supersedes {
54 superseded_id: InputId,
56 },
57}
58
59pub fn check_supersession(
61 new_input: &Input,
62 existing_input: &Input,
63 runtime_id: &LogicalRuntimeId,
64) -> CoalescingResult {
65 let new_scope = SupersessionScope::from_input(new_input, runtime_id);
66 let existing_scope = SupersessionScope::from_input(existing_input, runtime_id);
67
68 match (new_scope, existing_scope) {
69 (Some(ns), Some(es)) if ns == es => {
70 CoalescingResult::Supersedes {
72 superseded_id: existing_input.id().clone(),
73 }
74 }
75 _ => CoalescingResult::Standalone,
76 }
77}
78
79pub fn apply_supersession(
81 superseded_state: &mut InputState,
82 superseded_by: InputId,
83) -> Result<(), InputStateMachineError> {
84 InputStateMachine::transition(
85 superseded_state,
86 InputLifecycleState::Superseded,
87 Some(format!("superseded by {superseded_by}")),
88 )?;
89 InputStateMachine::set_terminal_outcome(
90 superseded_state,
91 InputTerminalOutcome::Superseded { superseded_by },
92 );
93 Ok(())
94}
95
96pub fn apply_coalescing(
98 source_state: &mut InputState,
99 aggregate_id: InputId,
100) -> Result<(), InputStateMachineError> {
101 InputStateMachine::transition(
102 source_state,
103 InputLifecycleState::Coalesced,
104 Some(format!("coalesced into {aggregate_id}")),
105 )?;
106 InputStateMachine::set_terminal_outcome(
107 source_state,
108 InputTerminalOutcome::Coalesced { aggregate_id },
109 );
110 Ok(())
111}
112
113pub fn create_aggregate_input(
115 sources: &[&Input],
116 aggregate_id: InputId,
117) -> Option<AggregateDescriptor> {
118 if sources.is_empty() {
119 return None;
120 }
121
122 let source_ids: Vec<InputId> = sources.iter().map(|i| i.id().clone()).collect();
123 let summary = format!("{} coalesced inputs", sources.len());
124
125 Some(AggregateDescriptor {
126 aggregate_id,
127 source_ids,
128 summary,
129 created_at: Utc::now(),
130 })
131}
132
133#[derive(Debug, Clone)]
135pub struct AggregateDescriptor {
136 pub aggregate_id: InputId,
137 pub source_ids: Vec<InputId>,
138 pub summary: String,
139 pub created_at: chrono::DateTime<Utc>,
140}
141
142#[cfg(test)]
143#[allow(clippy::unwrap_used)]
144mod tests {
145 use super::*;
146 use crate::input::*;
147 use chrono::Utc;
148
149 fn make_header_with_supersession(key: Option<&str>) -> InputHeader {
150 InputHeader {
151 id: InputId::new(),
152 timestamp: Utc::now(),
153 source: InputOrigin::External {
154 source_name: "test".into(),
155 },
156 durability: InputDurability::Ephemeral,
157 visibility: InputVisibility::default(),
158 idempotency_key: None,
159 supersession_key: key.map(SupersessionKey::new),
160 correlation_id: None,
161 }
162 }
163
164 #[test]
165 fn external_event_is_coalescing_eligible() {
166 let input = Input::ExternalEvent(ExternalEventInput {
167 header: make_header_with_supersession(None),
168 event_type: "webhook".into(),
169 payload: serde_json::json!({}),
170 });
171 assert!(is_coalescing_eligible(&input));
172 }
173
174 #[test]
175 fn response_progress_is_coalescing_eligible() {
176 let input = Input::Peer(PeerInput {
177 header: make_header_with_supersession(None),
178 convention: Some(PeerConvention::ResponseProgress {
179 request_id: "req-1".into(),
180 phase: ResponseProgressPhase::InProgress,
181 }),
182 body: "progress".into(),
183 });
184 assert!(is_coalescing_eligible(&input));
185 }
186
187 #[test]
188 fn prompt_not_coalescing_eligible() {
189 let input = Input::Prompt(PromptInput {
190 header: make_header_with_supersession(None),
191 text: "hello".into(),
192 turn_metadata: None,
193 });
194 assert!(!is_coalescing_eligible(&input));
195 }
196
197 #[test]
198 fn peer_message_not_coalescing_eligible() {
199 let input = Input::Peer(PeerInput {
200 header: make_header_with_supersession(None),
201 convention: Some(PeerConvention::Message),
202 body: "hello".into(),
203 });
204 assert!(!is_coalescing_eligible(&input));
205 }
206
207 #[test]
208 fn supersession_same_scope() {
209 let runtime = LogicalRuntimeId::new("agent-1");
210 let input1 = Input::ExternalEvent(ExternalEventInput {
211 header: make_header_with_supersession(Some("status")),
212 event_type: "status_update".into(),
213 payload: serde_json::json!({"v": 1}),
214 });
215 let input2 = Input::ExternalEvent(ExternalEventInput {
216 header: make_header_with_supersession(Some("status")),
217 event_type: "status_update".into(),
218 payload: serde_json::json!({"v": 2}),
219 });
220 let result = check_supersession(&input2, &input1, &runtime);
221 assert!(matches!(result, CoalescingResult::Supersedes { .. }));
222 }
223
224 #[test]
225 fn supersession_different_key() {
226 let runtime = LogicalRuntimeId::new("agent-1");
227 let input1 = Input::ExternalEvent(ExternalEventInput {
228 header: make_header_with_supersession(Some("status-a")),
229 event_type: "status_update".into(),
230 payload: serde_json::json!({}),
231 });
232 let input2 = Input::ExternalEvent(ExternalEventInput {
233 header: make_header_with_supersession(Some("status-b")),
234 event_type: "status_update".into(),
235 payload: serde_json::json!({}),
236 });
237 let result = check_supersession(&input2, &input1, &runtime);
238 assert!(matches!(result, CoalescingResult::Standalone));
239 }
240
241 #[test]
242 fn supersession_no_key() {
243 let runtime = LogicalRuntimeId::new("agent-1");
244 let input1 = Input::ExternalEvent(ExternalEventInput {
245 header: make_header_with_supersession(None),
246 event_type: "status_update".into(),
247 payload: serde_json::json!({}),
248 });
249 let input2 = Input::ExternalEvent(ExternalEventInput {
250 header: make_header_with_supersession(None),
251 event_type: "status_update".into(),
252 payload: serde_json::json!({}),
253 });
254 let result = check_supersession(&input2, &input1, &runtime);
255 assert!(matches!(result, CoalescingResult::Standalone));
256 }
257
258 #[test]
259 fn cross_kind_supersession_forbidden() {
260 let runtime = LogicalRuntimeId::new("agent-1");
261 let input1 = Input::ExternalEvent(ExternalEventInput {
262 header: make_header_with_supersession(Some("same-key")),
263 event_type: "type-a".into(),
264 payload: serde_json::json!({}),
265 });
266 let input2 = Input::Prompt(PromptInput {
268 header: make_header_with_supersession(Some("same-key")),
269 text: "hello".into(),
270 turn_metadata: None,
271 });
272 let result = check_supersession(&input2, &input1, &runtime);
273 assert!(matches!(result, CoalescingResult::Standalone));
275 }
276
277 #[test]
278 fn apply_supersession_transitions_state() {
279 let mut state = InputState::new_accepted(InputId::new());
280 let superseder = InputId::new();
281 apply_supersession(&mut state, superseder).unwrap();
282 assert_eq!(state.current_state, InputLifecycleState::Superseded);
283 assert!(matches!(
284 state.terminal_outcome,
285 Some(InputTerminalOutcome::Superseded { .. })
286 ));
287 }
288
289 #[test]
290 fn apply_coalescing_transitions_state() {
291 let mut state = InputState::new_accepted(InputId::new());
292 let aggregate = InputId::new();
293 apply_coalescing(&mut state, aggregate).unwrap();
294 assert_eq!(state.current_state, InputLifecycleState::Coalesced);
295 assert!(matches!(
296 state.terminal_outcome,
297 Some(InputTerminalOutcome::Coalesced { .. })
298 ));
299 }
300
301 #[test]
302 fn create_aggregate_from_sources() {
303 let sources: Vec<Input> = (0..3)
304 .map(|_| {
305 Input::ExternalEvent(ExternalEventInput {
306 header: make_header_with_supersession(None),
307 event_type: "test".into(),
308 payload: serde_json::json!({}),
309 })
310 })
311 .collect();
312 let source_refs: Vec<&Input> = sources.iter().collect();
313 let agg = create_aggregate_input(&source_refs, InputId::new()).unwrap();
314 assert_eq!(agg.source_ids.len(), 3);
315 assert!(agg.summary.contains('3'));
316 }
317
318 #[test]
319 fn create_aggregate_empty_returns_none() {
320 let result = create_aggregate_input(&[], InputId::new());
321 assert!(result.is_none());
322 }
323}