Skip to main content

rpi_cli/host/
catalog.rs

1//! Bounded asynchronous access to one blocking SQLite/ownership worker.
2//!
3//! Successful mutation responses follow the SQLite commit. Dropping a waiting
4//! client future does not undo a queued command: inspect by stable Agent ID and
5//! use epoch/revision guards before retrying. This is not a prompt submission,
6//! durable input acknowledgement, or exactly-once tool execution API.
7
8use super::lifecycle::{LifecycleAdmission, LifecycleReceipt, LifecycleRequest, LifecycleState};
9use super::recovery::Bindings;
10#[cfg(unix)]
11use super::recovery::Membership;
12use super::{
13    registry::Registry, AgentId, AgentMode, AgentSpec, AgentState, CatalogError, CatalogResult,
14    ControlScopeId, EffectiveTimeouts, HostConfig, HostEpoch, RequestId, TimeoutOverrides,
15};
16use serde::{Deserialize, Serialize};
17use std::{num::NonZeroUsize, path::PathBuf, sync::Arc};
18use tokio::sync::{mpsc, oneshot};
19
20pub const MAX_PAGE_SIZE: usize = 128;
21const COMMAND_CAPACITY: usize = 64;
22pub(crate) const MAX_RECORD_BYTES: usize = 128 * 1024;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26pub struct CatalogGuard {
27    pub epoch: HostEpoch,
28    pub revision: u64,
29}
30
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct AgentRecord {
34    pub spec: AgentSpec,
35    pub state: AgentState,
36    pub revision: u64,
37    /// Retained when a new instance classifies old state; PID is not identity.
38    pub last_epoch: HostEpoch,
39}
40
41impl AgentRecord {
42    pub(crate) fn validate(&self) -> CatalogResult<()> {
43        self.spec.validate()?;
44        self.state.validate_for(self.spec.mode)?;
45        if self.revision == 0 || self.revision > i64::MAX as u64 {
46            return Err(CatalogError::InvalidRecord("revision outside stored range"));
47        }
48        Ok(())
49    }
50}
51
52#[derive(Clone, Debug, Serialize, Deserialize)]
53pub struct AgentPage {
54    pub agents: Vec<AgentRecord>,
55    /// Keyset pagination, not a snapshot across concurrently changing pages.
56    pub next_cursor: Option<AgentId>,
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
60pub struct CatalogStatus {
61    pub epoch: HostEpoch,
62    pub registered: usize,
63    pub resident: usize,
64    /// Records reporting Running/WaitingApproval, not a model/tool barrier or
65    /// proof that already-closing external work has stopped.
66    pub executing: usize,
67    /// Includes startup and cleanup; the reaper must not treat these as idle.
68    pub busy: usize,
69    pub mini: usize,
70    pub max_agents: Option<usize>,
71}
72
73type Reply<T> = oneshot::Sender<CatalogResult<T>>;
74
75#[derive(Clone, Copy, PartialEq, Eq)]
76pub(super) enum TransitionSource {
77    Explicit,
78    IdleUnload,
79    AttachRestore,
80}
81
82enum Command {
83    Register {
84        spec: Box<AgentSpec>,
85        reply: Reply<AgentRecord>,
86    },
87    Get {
88        id: AgentId,
89        reply: Reply<AgentRecord>,
90    },
91    List {
92        after: Option<AgentId>,
93        limit: usize,
94        reply: Reply<AgentPage>,
95    },
96    Transition {
97        id: AgentId,
98        guard: CatalogGuard,
99        next: AgentState,
100        source: TransitionSource,
101        reply: Reply<AgentRecord>,
102    },
103    Status {
104        reply: Reply<CatalogStatus>,
105    },
106    Limit {
107        limit: Option<NonZeroUsize>,
108        reply: Reply<()>,
109    },
110    PrepareLifecycle {
111        request: Box<LifecycleRequest>,
112        reply: Reply<LifecycleAdmission>,
113    },
114    FinishLifecycle {
115        result: Box<(LifecycleRequest, LifecycleState)>,
116        reply: Reply<LifecycleReceipt>,
117    },
118    LifecycleReceipt {
119        scope: ControlScopeId,
120        request_id: RequestId,
121        reply: Reply<Option<LifecycleReceipt>>,
122    },
123    #[cfg(unix)]
124    RecoveryMembers {
125        configured: Vec<AgentId>,
126        reply: Reply<Membership>,
127    },
128    #[cfg(unix)]
129    RememberMembers {
130        loaded: Vec<AgentId>,
131        reply: Reply<()>,
132    },
133    Shutdown {
134        reply: Reply<()>,
135    },
136}
137
138/// Administrative state only. Does not create Agent backends or stop external
139/// tools. The eventual service owner must drain actual backends before shutdown.
140#[derive(Clone)]
141pub struct HostCatalog {
142    sender: mpsc::Sender<Command>,
143    epoch: HostEpoch,
144    config: Arc<HostConfig>,
145}
146
147impl HostCatalog {
148    pub async fn open(directory: PathBuf, config: HostConfig) -> CatalogResult<Self> {
149        Self::open_with_recovery(directory, config, Bindings::new()).await
150    }
151
152    pub(super) async fn open_with_recovery(
153        directory: PathBuf,
154        config: HostConfig,
155        bindings: Bindings,
156    ) -> CatalogResult<Self> {
157        config.validate()?;
158        if !directory.is_absolute() {
159            return Err(
160                super::HostError::InvalidInput("registry directory must be absolute").into(),
161            );
162        }
163        let policy = Arc::new(config.clone());
164        let (sender, mut receiver) = mpsc::channel(COMMAND_CAPACITY);
165        let (ready, started) = oneshot::channel();
166        std::thread::Builder::new()
167            .name("rpi-host-registry".into())
168            .spawn(move || {
169                let mut registry = match Registry::open(&directory, config, bindings) {
170                    Ok(registry) => registry,
171                    Err(error) => {
172                        let _ = ready.send(Err(error));
173                        return;
174                    }
175                };
176                if ready.send(Ok(registry.epoch())).is_err() {
177                    return;
178                }
179                let mut shutdown = None;
180                while let Some(command) = receiver.blocking_recv() {
181                    match command {
182                        Command::Register { spec, reply } => {
183                            let _ = reply.send(registry.register(*spec));
184                        }
185                        Command::Get { id, reply } => {
186                            let _ = reply.send(registry.get(id));
187                        }
188                        Command::List {
189                            after,
190                            limit,
191                            reply,
192                        } => {
193                            let _ = reply.send(registry.list(after, limit));
194                        }
195                        Command::Transition {
196                            id,
197                            guard,
198                            next,
199                            source,
200                            reply,
201                        } => {
202                            let _ = reply.send(registry.transition(id, guard, next, source));
203                        }
204                        Command::Status { reply } => {
205                            let _ = reply.send(registry.status());
206                        }
207                        Command::Limit { limit, reply } => {
208                            let _ = reply.send(registry.set_limit(limit));
209                        }
210                        Command::PrepareLifecycle { request, reply } => {
211                            let _ = reply.send(registry.prepare_lifecycle(*request));
212                        }
213                        Command::FinishLifecycle { result, reply } => {
214                            let (request, status) = *result;
215                            let _ = reply.send(registry.finish_lifecycle(request, status));
216                        }
217                        Command::LifecycleReceipt {
218                            scope,
219                            request_id,
220                            reply,
221                        } => {
222                            let _ = reply.send(registry.lifecycle_receipt(scope, request_id));
223                        }
224                        #[cfg(unix)]
225                        Command::RecoveryMembers { configured, reply } => {
226                            let _ = reply.send(registry.recovery_members(&configured));
227                        }
228                        #[cfg(unix)]
229                        Command::RememberMembers { loaded, reply } => {
230                            let _ = reply.send(registry.remember_members(&loaded));
231                        }
232                        Command::Shutdown { reply } => {
233                            shutdown = Some(reply);
234                            break;
235                        }
236                    }
237                }
238                // Release SQLite, reservations and inherited lock references
239                // before acknowledging; unlock errors cannot become a success ACK.
240                let cleanup = registry.shutdown();
241                if let Some(reply) = shutdown {
242                    let _ = reply.send(cleanup);
243                }
244            })?;
245        let epoch = started.await.map_err(|_| CatalogError::WorkerStopped)??;
246        Ok(Self {
247            sender,
248            epoch,
249            config: policy,
250        })
251    }
252
253    pub(super) fn resolve_timeouts(
254        &self,
255        overrides: TimeoutOverrides,
256    ) -> CatalogResult<EffectiveTimeouts> {
257        Ok(self.config.resolve_timeouts(overrides)?)
258    }
259
260    pub(super) fn idle_timeout(&self) -> Option<std::time::Duration> {
261        self.config
262            .host_idle_timeout_ms
263            .map(|ms| std::time::Duration::from_millis(ms.get()))
264    }
265
266    pub fn epoch(&self) -> HostEpoch {
267        self.epoch
268    }
269
270    pub fn guard(&self, record: &AgentRecord) -> CatalogGuard {
271        CatalogGuard {
272            epoch: self.epoch,
273            revision: record.revision,
274        }
275    }
276
277    async fn call<T>(&self, make: impl FnOnce(Reply<T>) -> Command) -> CatalogResult<T> {
278        let (reply, result) = oneshot::channel();
279        self.sender
280            .send(make(reply))
281            .await
282            .map_err(|_| CatalogError::WorkerStopped)?;
283        result.await.map_err(|_| CatalogError::WorkerStopped)?
284    }
285
286    pub async fn register(&self, spec: AgentSpec) -> CatalogResult<AgentRecord> {
287        spec.validate()?;
288        // Bound queued metadata before moving it to the worker; leave record header room.
289        if serde_json::to_vec(&spec)?.len() > MAX_RECORD_BYTES - 512 {
290            return Err(
291                super::HostError::InvalidInput("Agent metadata exceeds byte budget").into(),
292            );
293        }
294        self.call(|reply| Command::Register {
295            spec: Box::new(spec),
296            reply,
297        })
298        .await
299    }
300
301    pub async fn get(&self, id: AgentId) -> CatalogResult<AgentRecord> {
302        self.call(|reply| Command::Get { id, reply }).await
303    }
304
305    pub async fn list(&self, after: Option<AgentId>, limit: usize) -> CatalogResult<AgentPage> {
306        if limit == 0 || limit > MAX_PAGE_SIZE {
307            return Err(super::HostError::InvalidInput("invalid catalog page size").into());
308        }
309        self.call(|reply| Command::List {
310            after,
311            limit,
312            reply,
313        })
314        .await
315    }
316
317    pub async fn transition(
318        &self,
319        id: AgentId,
320        guard: CatalogGuard,
321        next: AgentState,
322    ) -> CatalogResult<AgentRecord> {
323        self.call(|reply| Command::Transition {
324            id,
325            guard,
326            next,
327            source: TransitionSource::Explicit,
328            reply,
329        })
330        .await
331    }
332
333    pub(super) async fn begin_idle_unload(
334        &self,
335        id: AgentId,
336        guard: CatalogGuard,
337    ) -> CatalogResult<AgentRecord> {
338        self.call(|reply| Command::Transition {
339            id,
340            guard,
341            next: AgentState::Closing,
342            source: TransitionSource::IdleUnload,
343            reply,
344        })
345        .await
346    }
347
348    pub(super) async fn begin_attach_restore(
349        &self,
350        id: AgentId,
351        guard: CatalogGuard,
352    ) -> CatalogResult<AgentRecord> {
353        self.call(|reply| Command::Transition {
354            id,
355            guard,
356            next: AgentState::Starting,
357            source: TransitionSource::AttachRestore,
358            reply,
359        })
360        .await
361    }
362
363    pub async fn status(&self) -> CatalogResult<CatalogStatus> {
364        self.call(|reply| Command::Status { reply }).await
365    }
366
367    /// Runtime policy only; the caller remains responsible for saving Host config.
368    pub async fn set_max_agents(&self, limit: Option<NonZeroUsize>) -> CatalogResult<()> {
369        self.call(|reply| Command::Limit { limit, reply }).await
370    }
371
372    /// Commit administrative custody only. The trusted coordinator must own
373    /// prepare+action+finish independently of a client waiter, and may act ONLY
374    /// when `fresh` is true. This API executes nothing and grants no permission.
375    pub async fn prepare_lifecycle(
376        &self,
377        request: LifecycleRequest,
378    ) -> CatalogResult<LifecycleAdmission> {
379        self.call(|reply| Command::PrepareLifecycle {
380            request: Box::new(request),
381            reply,
382        })
383        .await
384    }
385
386    /// Trusted coordinator publication, never a client-supplied result. A final
387    /// state is immutable; errors require reconciliation rather than replay.
388    pub async fn finish_lifecycle(
389        &self,
390        request: LifecycleRequest,
391        status: LifecycleState,
392    ) -> CatalogResult<LifecycleReceipt> {
393        self.call(|reply| Command::FinishLifecycle {
394            result: Box::new((request, status)),
395            reply,
396        })
397        .await
398    }
399
400    /// No Agent load, action replay, or ownership transfer. Found records pass
401    /// a strict SQLite checkpoint before they are returned as journal evidence.
402    pub async fn lifecycle_receipt(
403        &self,
404        scope: ControlScopeId,
405        request_id: RequestId,
406    ) -> CatalogResult<Option<LifecycleReceipt>> {
407        self.call(|reply| Command::LifecycleReceipt {
408            scope,
409            request_id,
410            reply,
411        })
412        .await
413    }
414
415    #[cfg(unix)]
416    pub(super) async fn recovery_members(
417        &self,
418        configured: Vec<AgentId>,
419    ) -> CatalogResult<Membership> {
420        self.call(|reply| Command::RecoveryMembers { configured, reply })
421            .await
422    }
423
424    #[cfg(unix)]
425    pub(super) async fn remember_members(&self, loaded: Vec<AgentId>) -> CatalogResult<()> {
426        self.call(|reply| Command::RememberMembers { loaded, reply })
427            .await
428    }
429
430    /// Waits for storage/lock cleanup, not for Agent execution cleanup.
431    pub async fn shutdown(&self) -> CatalogResult<()> {
432        self.call(|reply| Command::Shutdown { reply }).await
433    }
434}
435
436pub(crate) fn is_mini(record: &AgentRecord) -> bool {
437    record.spec.mode == AgentMode::Mini
438}
439
440#[cfg(all(test, unix))]
441mod tests {
442    use super::*;
443
444    #[tokio::test]
445    async fn abandoned_lifecycle_reply_does_not_transfer_a_committed_fresh_grant() {
446        let directory = tempfile::tempdir().unwrap();
447        let catalog = HostCatalog::open(directory.path().join("host"), HostConfig::default())
448            .await
449            .unwrap();
450        let request = LifecycleRequest {
451            scope: ControlScopeId::new(),
452            request_id: RequestId::new(),
453            epoch: catalog.epoch(),
454            action: crate::host::lifecycle::LifecycleAction::Create {
455                agent_id: AgentId::new(),
456            },
457        };
458        let (reply, result) = oneshot::channel();
459        drop(result);
460        catalog
461            .sender
462            .send(Command::PrepareLifecycle {
463                request: Box::new(request.clone()),
464                reply,
465            })
466            .await
467            .unwrap();
468        // FIFO observation after the abandoned queued command, not a timing race.
469        let receipt = catalog
470            .lifecycle_receipt(request.scope, request.request_id)
471            .await
472            .unwrap()
473            .unwrap();
474        assert_eq!(receipt.status, LifecycleState::Prepared {});
475        let duplicate = catalog.prepare_lifecycle(request).await.unwrap();
476        assert!(!duplicate.fresh);
477        assert_eq!(duplicate.receipt, receipt);
478        assert_eq!(catalog.status().await.unwrap().registered, 0);
479        catalog.shutdown().await.unwrap();
480    }
481
482    #[tokio::test]
483    async fn abandoned_client_reply_does_not_undo_an_accepted_catalog_mutation() {
484        let directory = tempfile::tempdir().unwrap();
485        let catalog = HostCatalog::open(directory.path().join("host"), HostConfig::default())
486            .await
487            .unwrap();
488        let spec = crate::host::registry_tests::make_spec(AgentMode::Mini);
489        let id = spec.id;
490        let (reply, result) = oneshot::channel();
491        drop(result);
492        catalog
493            .sender
494            .send(Command::Register {
495                spec: Box::new(spec),
496                reply,
497            })
498            .await
499            .unwrap();
500        // FIFO fence after the abandoned command; no timing-dependent abort race.
501        let record = catalog.get(id).await.unwrap();
502        assert_eq!(record.state, AgentState::Registered);
503        assert_eq!(record.revision, 1);
504        assert!(matches!(
505            catalog.register(record.spec).await,
506            Err(CatalogError::AlreadyRegistered)
507        ));
508        catalog.shutdown().await.unwrap();
509    }
510}