agentmux_srv/server/
registry_reconcile.rs1use std::collections::HashMap;
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::time::Duration;
23
24use crate::backend::blockcontroller::{self, STATUS_RUNNING};
25use crate::backend::obj::Block;
26
27use super::AppState;
28
29const LOOK_EVERY: Duration = Duration::from_secs(60);
31
32type Reconciled = HashMap<String, u64>;
34
35fn next_nonce() -> u64 {
38 static NEXT: AtomicU64 = AtomicU64::new(u64::MAX);
39 NEXT.fetch_sub(1, Ordering::Relaxed)
40}
41
42fn should_register(uid: &str, parked: bool, controller_uid: Option<&str>, process_status: &str) -> bool {
45 !parked && controller_uid == Some(uid) && process_status == STATUS_RUNNING
46}
47
48fn process_running(block_id: &str) -> bool {
50 blockcontroller::get_controller(block_id).is_some_and(|c| c.get_runtime_status().shellprocstatus == STATUS_RUNNING)
51}
52
53fn drop_ended(state: &AppState, made: &mut Reconciled, running: impl Fn(&str) -> bool) -> Vec<String> {
55 let ended: Vec<String> = made.keys().filter(|b| !running(b)).cloned().collect();
56 for block_id in &ended {
57 if let Some(nonce) = made.remove(block_id) {
58 state.reactive_handler.unregister_block_if_nonce(block_id, nonce);
59 }
60 }
61 ended
62}
63
64fn reconcile(state: &AppState, made: &mut Reconciled) -> Vec<String> {
67 drop_ended(state, made, process_running);
68 let mut registered = Vec::new();
69 for (uid, block_id) in super::agent_runtime::pane_blocks_by_agent(&state.mstore) {
70 if state.reactive_handler.has_uid_registration(&uid) {
71 continue;
72 }
73 let Some(controller) = blockcontroller::get_controller(&block_id) else {
74 continue;
75 };
76 let parked = state
77 .mstore
78 .get::<Block>(&block_id)
79 .ok()
80 .flatten()
81 .is_some_and(|b| crate::backend::obj::meta_get_bool(&b.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false));
82 let status = controller.get_runtime_status().shellprocstatus;
83 if !should_register(&uid, parked, controller.stable_agent_uid().as_deref(), &status) {
84 continue;
85 }
86 let nonce = next_nonce();
87 if super::jekt_start::make_addressable(state, &uid, &block_id, nonce) {
88 tracing::warn!(agent_uid = %uid, block_id = %block_id, "registry: a running agent was missing from it — registered again");
89 made.insert(block_id, nonce);
90 registered.push(uid);
91 }
92 }
93 registered
94}
95
96pub(crate) fn spawn(state: AppState) {
98 tokio::spawn(async move {
99 let mut made = Reconciled::new();
100 loop {
101 tokio::time::sleep(LOOK_EVERY).await;
102 let looked = state.clone();
103 match tokio::task::spawn_blocking(move || {
104 reconcile(&looked, &mut made);
105 made
106 })
107 .await
108 {
109 Ok(kept) => made = kept,
110 Err(e) => {
111 tracing::warn!("registry reconcile: {e}");
112 made = Reconciled::new();
113 }
114 }
115 }
116 });
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122
123 #[test]
124 fn a_running_agent_whose_controller_carries_its_uid_is_put_back() {
125 assert!(should_register("u1", false, Some("u1"), STATUS_RUNNING));
126 }
127
128 #[test]
129 fn a_parked_stopped_or_look_alike_pane_is_left_alone() {
130 assert!(!should_register("u1", true, Some("u1"), STATUS_RUNNING), "parked");
131 assert!(!should_register("u1", false, Some("u1"), "done"), "its process ended");
132 assert!(!should_register("u1", false, Some("u1"), ""), "no process yet");
133 assert!(!should_register("u1", false, Some("u2"), STATUS_RUNNING), "another agent's controller");
134 assert!(!should_register("u1", false, None, STATUS_RUNNING), "a controller with no agent uid");
135 }
136
137 #[tokio::test]
138 async fn an_agent_with_no_pane_is_not_registered() {
139 let state = super::super::tests::test_state();
140 assert!(reconcile(&state, &mut Reconciled::new()).is_empty());
141 }
142
143 #[tokio::test]
144 async fn an_entry_made_here_goes_when_its_process_ends_but_a_respawns_stays() {
145 let state = super::super::tests::test_state();
146 let tag = uuid::Uuid::new_v4();
147 let (gone, kept) = (format!("blk-gone-{tag}"), format!("blk-kept-{tag}"));
148 let (gone_uid, kept_uid) = (format!("rc-{tag}-a"), format!("rc-{tag}-b"));
149 let (gone_nonce, kept_nonce) = (next_nonce(), next_nonce());
150 let h = &state.reactive_handler;
151 h.register_agent_full("reconcile-a", &gone, None, gone_nonce, None, Some(&gone_uid), "t").unwrap();
152 h.register_agent_full("reconcile-b", &kept, None, kept_nonce - 1, None, Some(&kept_uid), "t").unwrap(); let mut made = Reconciled::from([(gone.clone(), gone_nonce), (kept.clone(), kept_nonce)]);
154
155 let cleared = drop_ended(&state, &mut made, |_| false);
156
157 assert_eq!(cleared.len(), 2);
158 assert!(!h.has_uid_registration(&gone_uid), "the entry made here goes with its process");
159 assert!(h.has_uid_registration(&kept_uid), "an entry that changed hands is not ours to remove");
160 assert!(made.is_empty());
161 }
162}