agentmux_srv_core/ambient/
mod.rs1pub mod call;
25pub mod cli_locator;
26pub mod cli;
27pub mod digest;
28pub mod limits;
29pub mod outcome;
30pub mod prompt;
31pub mod purpose;
32pub mod reply;
33pub mod sanitize;
34pub mod spend;
35pub mod tasks;
36pub mod title;
37pub mod validate;
38
39use std::collections::HashMap;
40use std::sync::{Mutex, OnceLock};
41
42use tokio_util::sync::CancellationToken;
43
44#[derive(Debug, Clone, PartialEq, Eq, Hash)]
48pub struct AmbientCallKey {
49 pub entity_id: String,
50 pub purpose: &'static str,
51}
52
53impl AmbientCallKey {
54 pub fn new(entity_id: impl Into<String>, purpose: &'static str) -> Self {
55 Self { entity_id: entity_id.into(), purpose }
56 }
57}
58
59struct InFlight {
60 generation: u64,
61 cancel: CancellationToken,
62}
63
64#[derive(Default)]
65struct GatewayState {
66 inflight: HashMap<AmbientCallKey, InFlight>,
67}
68
69pub struct AmbientGateway {
70 state: Mutex<GatewayState>,
71}
72
73static GATEWAY: OnceLock<AmbientGateway> = OnceLock::new();
74
75pub fn gateway() -> &'static AmbientGateway {
77 GATEWAY.get_or_init(|| AmbientGateway { state: Mutex::new(GatewayState::default()) })
78}
79
80pub enum Admission<'a> {
82 Proceed(AmbientCallGuard<'a>),
87 StaleOnArrival,
90}
91
92impl AmbientGateway {
93 pub fn admit(&self, key: AmbientCallKey, generation: u64) -> Admission<'_> {
100 let mut state = self.state.lock().unwrap();
101 if let Some(existing) = state.inflight.get(&key) {
102 if generation <= existing.generation {
103 return Admission::StaleOnArrival;
104 }
105 existing.cancel.cancel();
106 }
107 let cancel = CancellationToken::new();
108 state.inflight.insert(
109 key.clone(),
110 InFlight { generation, cancel: cancel.clone() },
111 );
112 Admission::Proceed(AmbientCallGuard {
113 gateway: self,
114 key,
115 generation,
116 cancel,
117 })
118 }
119}
120
121pub struct AmbientCallGuard<'a> {
123 gateway: &'a AmbientGateway,
124 key: AmbientCallKey,
125 generation: u64,
126 cancel: CancellationToken,
127}
128
129impl AmbientCallGuard<'_> {
130 pub fn cancellation(&self) -> CancellationToken {
134 self.cancel.clone()
135 }
136}
137
138impl Drop for AmbientCallGuard<'_> {
139 fn drop(&mut self) {
140 let mut state = self.gateway.state.lock().unwrap();
141 if let Some(entry) = state.inflight.get(&self.key) {
144 if entry.generation == self.generation {
145 state.inflight.remove(&self.key);
146 }
147 }
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154
155 fn key(id: &str) -> AmbientCallKey {
156 AmbientCallKey::new(id, "activity_summary")
157 }
158
159 #[test]
160 fn first_request_is_admitted() {
161 let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
162 match gw.admit(key("block-1"), 1) {
163 Admission::Proceed(_) => {}
164 Admission::StaleOnArrival => panic!("first request should be admitted"),
165 };
166 }
167
168 #[test]
169 fn older_or_equal_generation_is_stale_on_arrival() {
170 let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
171 let _guard = match gw.admit(key("block-1"), 5) {
172 Admission::Proceed(g) => g,
173 Admission::StaleOnArrival => panic!("gen 5 should be admitted"),
174 };
175 match gw.admit(key("block-1"), 5) {
176 Admission::StaleOnArrival => {}
177 Admission::Proceed(_) => panic!("equal generation must be rejected"),
178 }
179 match gw.admit(key("block-1"), 3) {
180 Admission::StaleOnArrival => {}
181 Admission::Proceed(_) => panic!("older generation must be rejected"),
182 };
183 }
184
185 #[test]
186 fn newer_generation_cancels_the_older_inflight_request() {
187 let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
188 let guard1 = match gw.admit(key("block-1"), 1) {
189 Admission::Proceed(g) => g,
190 Admission::StaleOnArrival => panic!("gen 1 should be admitted"),
191 };
192 let cancel1 = guard1.cancellation();
193 assert!(!cancel1.is_cancelled());
194
195 let _guard2 = match gw.admit(key("block-1"), 2) {
196 Admission::Proceed(g) => g,
197 Admission::StaleOnArrival => panic!("gen 2 should be admitted"),
198 };
199 assert!(cancel1.is_cancelled(), "admitting gen 2 must cancel gen 1's token");
200 }
201
202 #[test]
203 fn different_keys_do_not_interfere() {
204 let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
205 let guard1 = match gw.admit(key("block-1"), 1) {
206 Admission::Proceed(g) => g,
207 Admission::StaleOnArrival => panic!("block-1 gen 1 should be admitted"),
208 };
209 match gw.admit(key("block-2"), 1) {
210 Admission::Proceed(_) => {}
211 Admission::StaleOnArrival => panic!("block-2 gen 1 should be admitted independently"),
212 }
213 assert!(!guard1.cancellation().is_cancelled(), "unrelated key must not cancel block-1");
214 }
215
216 #[test]
217 fn dropping_the_guard_clears_the_slot_for_a_later_retry_at_the_same_generation() {
218 let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
219 {
220 let _guard = match gw.admit(key("block-1"), 1) {
221 Admission::Proceed(g) => g,
222 Admission::StaleOnArrival => panic!("gen 1 should be admitted"),
223 };
224 } match gw.admit(key("block-1"), 1) {
226 Admission::Proceed(_) => {}
227 Admission::StaleOnArrival => {
228 panic!("gen 1 should be admittable again once the prior call finished")
229 }
230 };
231 }
232
233 #[test]
234 fn stale_guard_dropping_does_not_clear_a_newer_inflight_entry() {
235 let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
236 let guard1 = match gw.admit(key("block-1"), 1) {
237 Admission::Proceed(g) => g,
238 Admission::StaleOnArrival => panic!("gen 1 should be admitted"),
239 };
240 let _guard2 = match gw.admit(key("block-1"), 2) {
241 Admission::Proceed(g) => g,
242 Admission::StaleOnArrival => panic!("gen 2 should be admitted"),
243 };
244 drop(guard1); match gw.admit(key("block-1"), 2) {
246 Admission::StaleOnArrival => {}
247 Admission::Proceed(_) => {
248 panic!("gen 2 is still in flight; dropping the stale gen-1 guard must not clear it")
249 }
250 };
251 }
252}