Skip to main content

rpi_cli/host/
administration.rs

1//! Trusted in-process administrative facade. No IPC parser or peer-minted
2//! authority. Intent, native effects and result publication are not atomic;
3//! uncertain work is inspect-only, never automatically replayed.
4use super::{
5    lifecycle::{
6        LifecycleAction, LifecycleFailure, LifecycleReceipt, LifecycleRequest, LifecycleResult,
7        LifecycleState,
8    },
9    ordinary::BackendError,
10    service::{HostService, OwnerPhase, ServiceError, ServiceReservation, StopReservation},
11    AgentId, AgentState, CatalogError, CatalogGuard, ControlScopeId, PreparedProfile, ProfileRef,
12    RequestId, TrustedProfileSet, MAX_TRUSTED_PROFILES,
13};
14use futures::FutureExt;
15use rpi_harness::session::{
16    jsonl::{JsonlSessionStorage, JsonlV4Header},
17    DefaultIdGenerator, SystemClock,
18};
19use std::{
20    collections::{BTreeMap, BTreeSet},
21    num::NonZeroUsize,
22    panic::AssertUnwindSafe,
23    sync::{Arc, Mutex, MutexGuard},
24    time::{SystemTime, UNIX_EPOCH},
25};
26use tokio::sync::watch;
27use tokio_util::sync::CancellationToken;
28
29pub const MAX_ADMINISTRATIVE_JOBS: usize = 64;
30pub type AdministrativeResult = Result<LifecycleReceipt, AdministrativeError>;
31
32/// Fixed labels only: never return private backend diagnostics to a peer.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
34pub enum AdministrativeError {
35    #[error("administrative request is not authorized")]
36    Unauthorized,
37    #[error("administrative request or trusted preflight was rejected")]
38    InvalidRequest,
39    #[error("administrative request conflicts with existing custody")]
40    Conflict,
41    #[error("administrative target was not found")]
42    NotFound,
43    #[error("administrative Host epoch is stale")]
44    StaleEpoch,
45    #[error("administrative Agent revision is stale")]
46    StaleRevision,
47    #[error("administrative target is busy")]
48    Busy,
49    #[error("administrative capacity is exhausted")]
50    Capacity,
51    #[error("Host is stopping")]
52    Stopping,
53    #[error("unbound lifecycle execution is not supported")]
54    Unsupported,
55    #[error("administrative outcome is uncertain; inspect without replaying")]
56    OutcomeUnknown,
57}
58impl From<CatalogError> for AdministrativeError {
59    fn from(error: CatalogError) -> Self {
60        match error {
61            CatalogError::UnknownAgent => Self::NotFound,
62            CatalogError::EpochConflict => Self::StaleEpoch,
63            CatalogError::RevisionConflict { .. } => Self::StaleRevision,
64            CatalogError::AlreadyRegistered
65            | CatalogError::SessionAlreadyRegistered
66            | CatalogError::LifecycleConflict => Self::Conflict,
67            CatalogError::LifecycleBusy => Self::Busy,
68            CatalogError::LifecycleCapacity
69            | CatalogError::Policy(super::HostError::AtCapacity { .. }) => Self::Capacity,
70            _ => Self::OutcomeUnknown,
71        }
72    }
73}
74
75/// Trusted native permissions, all denied by default. Not Deserialize: a
76/// request's scope UUID, profile nonce or JSON cannot mint these rights.
77#[derive(Clone, Copy, Default)]
78pub struct AdministrativePermissions {
79    pub create: bool,
80    pub restore: bool,
81    pub cancel: bool,
82    pub close: bool,
83    pub stop: bool,
84}
85/// Issued by the Host owner, not a client/model. Immutable and deliberately not
86/// Debug/Serialize. Dropping a grant does not revoke an already accepted job.
87pub struct AdministrativeGrant {
88    scope: ControlScopeId,
89    agents: BTreeSet<AgentId>,
90    permissions: AdministrativePermissions,
91}
92impl AdministrativeGrant {
93    pub fn new(
94        scope: ControlScopeId,
95        agents: BTreeSet<AgentId>,
96        permissions: AdministrativePermissions,
97    ) -> Result<Self, AdministrativeError> {
98        if agents.len() > MAX_TRUSTED_PROFILES {
99            return Err(AdministrativeError::InvalidRequest);
100        }
101        Ok(Self {
102            scope,
103            agents,
104            permissions,
105        })
106    }
107    pub fn scope(&self) -> ControlScopeId {
108        self.scope
109    }
110    pub(super) fn can_restore(&self, id: AgentId) -> bool {
111        self.permissions.restore && self.agents.contains(&id)
112    }
113    fn authorize(&self, request: &LifecycleRequest) -> Result<(), AdministrativeError> {
114        let permitted = match request.action {
115            LifecycleAction::Create { .. } | LifecycleAction::CreateProfile { .. } => {
116                self.permissions.create
117            }
118            LifecycleAction::Restore { .. } | LifecycleAction::RestoreProfile { .. } => {
119                self.permissions.restore
120            }
121            LifecycleAction::Cancel { .. } | LifecycleAction::CancelSubmitted { .. } => {
122                self.permissions.cancel
123            }
124            LifecycleAction::Close { .. } => self.permissions.close,
125            LifecycleAction::Stop {} => self.permissions.stop,
126        };
127        if request.scope != self.scope
128            || !permitted
129            || request
130                .action
131                .agent()
132                .is_some_and(|id| !self.agents.contains(&id))
133        {
134            return Err(AdministrativeError::Unauthorized);
135        }
136        request
137            .validate()
138            .map_err(|_| AdministrativeError::InvalidRequest)
139    }
140}
141
142type Key = (ControlScopeId, RequestId);
143type Observer = watch::Receiver<Option<AdministrativeResult>>;
144struct Job {
145    request: LifecycleRequest,
146    observer: Observer,
147}
148struct Inner {
149    service: HostService,
150    profiles: TrustedProfileSet,
151    limit: usize,
152    jobs: Mutex<BTreeMap<Key, Job>>,
153    // At most one immutable, already-checkpointed successful Stop result. The
154    // catalog is then closed, so duplicate Stop cannot query its worker again.
155    settled_receipt: Mutex<Option<LifecycleReceipt>>,
156    // Volatile completion of this owner's fresh Stop, never restored from
157    // history. A NativeSettled receipt alone is not storage/transport exit.
158    stop_completed: CancellationToken,
159}
160impl Inner {
161    fn jobs(&self) -> MutexGuard<'_, BTreeMap<Key, Job>> {
162        self.jobs
163            .lock()
164            .unwrap_or_else(|poison| poison.into_inner())
165    }
166}
167/// Retain for the entire service lifetime. Only one facade can claim a service;
168/// dropping it never hands an epoch's live/uncertain custody to another facade.
169/// The bounded map owns jobs, not waiters. No global mutex is held across await.
170#[derive(Clone)]
171pub struct AdministrativeCoordinator {
172    inner: Arc<Inner>,
173}
174impl AdministrativeCoordinator {
175    pub fn new(
176        service: HostService,
177        profiles: TrustedProfileSet,
178        limit: NonZeroUsize,
179    ) -> Result<Self, AdministrativeError> {
180        if limit.get() > MAX_ADMINISTRATIVE_JOBS {
181            return Err(AdministrativeError::InvalidRequest);
182        }
183        if service.is_stopping() {
184            return Err(AdministrativeError::Stopping);
185        }
186        if !service.claim_administration() {
187            return Err(AdministrativeError::Conflict);
188        }
189        Ok(Self {
190            inner: Arc::new(Inner {
191                service,
192                profiles,
193                limit: limit.get(),
194                jobs: Mutex::new(BTreeMap::new()),
195                settled_receipt: Mutex::new(None),
196                stop_completed: CancellationToken::new(),
197            }),
198        })
199    }
200    pub fn active_jobs(&self) -> usize {
201        self.inner.jobs().len()
202    }
203    pub(crate) fn stop_completed(&self) -> CancellationToken {
204        self.inner.stop_completed.clone()
205    }
206    /// Native owner discovery only, not a client-facing grant/list operation.
207    pub fn profile_references(&self) -> impl ExactSizeIterator<Item = ProfileRef> + '_ {
208        self.inner.profiles.references()
209    }
210
211    fn settled_receipt(
212        &self,
213        request: &LifecycleRequest,
214    ) -> Result<Option<LifecycleReceipt>, AdministrativeError> {
215        let cached = self
216            .inner
217            .settled_receipt
218            .lock()
219            .unwrap_or_else(|poison| poison.into_inner());
220        match cached.as_ref().filter(|receipt| {
221            receipt.request.scope == request.scope
222                && receipt.request.request_id == request.request_id
223        }) {
224            Some(receipt) if receipt.request != *request => Err(AdministrativeError::Conflict),
225            receipt => Ok(receipt.cloned()),
226        }
227    }
228
229    /// Authenticated full-parameter reconciliation, including historical refs
230    /// no longer in the current frozen set. A found row grants no execution.
231    pub async fn receipt(
232        &self,
233        grant: &AdministrativeGrant,
234        request: &LifecycleRequest,
235    ) -> Result<Option<LifecycleReceipt>, AdministrativeError> {
236        grant.authorize(request)?;
237        if let Some(receipt) = self.settled_receipt(request)? {
238            return Ok(Some(receipt));
239        }
240        let receipt = self
241            .inner
242            .service
243            .catalog()
244            .lifecycle_receipt(request.scope, request.request_id)
245            .await?;
246        if receipt
247            .as_ref()
248            .is_some_and(|receipt| receipt.request != *request)
249        {
250            return Err(AdministrativeError::Conflict);
251        }
252        Ok(receipt)
253    }
254    fn existing(
255        &self,
256        request: &LifecycleRequest,
257    ) -> Result<Option<Observer>, AdministrativeError> {
258        let jobs = self.inner.jobs();
259        jobs.get(&(request.scope, request.request_id))
260            .map(|job| {
261                if job.request != *request {
262                    Err(AdministrativeError::Conflict)
263                } else {
264                    Ok(job.observer.clone())
265                }
266            })
267            .transpose()
268    }
269    pub async fn execute(
270        &self,
271        grant: &AdministrativeGrant,
272        request: LifecycleRequest,
273    ) -> AdministrativeResult {
274        grant.authorize(&request)?;
275        if let Some(observer) = self.existing(&request)? {
276            return observe(observer).await;
277        }
278        // Do not resolve the current profile until old custody has been read.
279        let previous = self.receipt(grant, &request).await?;
280        let key = (request.scope, request.request_id);
281        let (observer, sender) = {
282            let mut jobs = self.inner.jobs();
283            if let Some(job) = jobs.get(&key) {
284                if job.request != request {
285                    return Err(AdministrativeError::Conflict);
286                }
287                (job.observer.clone(), None)
288            } else {
289                if let Some(receipt) = previous {
290                    return Ok(receipt);
291                }
292                if jobs.len() >= self.inner.limit {
293                    return Err(AdministrativeError::Capacity);
294                }
295                let (sender, observer) = watch::channel(None);
296                jobs.insert(
297                    key,
298                    Job {
299                        request: request.clone(),
300                        observer: observer.clone(),
301                    },
302                );
303                (observer, Some(sender))
304            }
305        };
306        if let Some(sender) = sender {
307            let owner = self.clone();
308            // No await between claiming the local slot and spawning its owner.
309            tokio::spawn(async move {
310                let result = AssertUnwindSafe(owner.run(request))
311                    .catch_unwind()
312                    .await
313                    .unwrap_or(Err(AdministrativeError::OutcomeUnknown));
314                sender.send_replace(Some(result));
315                owner.inner.jobs().remove(&key);
316            });
317        }
318        observe(observer).await
319    }
320    pub(super) async fn prepare_attach(
321        &self,
322        reference: ProfileRef,
323    ) -> Result<PreparedProfile, BackendError> {
324        self.inner.profiles.prepare(reference).await
325    }
326
327    async fn run(&self, request: LifecycleRequest) -> AdministrativeResult {
328        if let Some(receipt) = self.settled_receipt(&request)? {
329            return Ok(receipt);
330        }
331        let owner = self.clone();
332        let result = if matches!(request.action, LifecycleAction::Stop {}) {
333            self.inner
334                .service
335                .with_stop_reservation(false, move |reserved| {
336                    Box::pin(async move { Ok(owner.run_stop(reserved, request).await) })
337                })
338                .await
339        } else {
340            self.inner
341                .service
342                .with_administration(move |reserved| {
343                    Box::pin(async move { Ok(owner.run_reserved(reserved, request).await) })
344                })
345                .await
346        };
347        result.map_err(|error| match error {
348            ServiceError::Stopping => AdministrativeError::Stopping,
349            _ => AdministrativeError::OutcomeUnknown,
350        })?
351    }
352    async fn preflight(
353        &self,
354        reserved: &ServiceReservation<'_>,
355        request: &LifecycleRequest,
356    ) -> Result<Option<PreparedProfile>, AdministrativeError> {
357        let catalog = reserved.catalog();
358        if request.epoch != catalog.epoch() {
359            return Err(AdministrativeError::StaleEpoch);
360        }
361        match request.action {
362            LifecycleAction::Create { .. } | LifecycleAction::Restore { .. } => {
363                Err(AdministrativeError::Unsupported)
364            }
365            LifecycleAction::CreateProfile { profile }
366            | LifecycleAction::RestoreProfile { profile, .. } => {
367                let prepared = self
368                    .inner
369                    .profiles
370                    .prepare(profile)
371                    .await
372                    .map_err(|_| AdministrativeError::InvalidRequest)?;
373                match request.action {
374                    LifecycleAction::CreateProfile { .. } => {
375                        match catalog.get(profile.agent_id).await {
376                            Err(CatalogError::UnknownAgent) => {}
377                            Ok(_) => return Err(AdministrativeError::Conflict),
378                            Err(error) => return Err(error.into()),
379                        }
380                        super::profile::canonical_workspace(&prepared.spec)
381                            .map_err(|_| AdministrativeError::InvalidRequest)?;
382                        let session = prepared
383                            .spec
384                            .session
385                            .as_ref()
386                            .ok_or(AdministrativeError::InvalidRequest)?;
387                        super::profile::session_parent(&session.path)
388                            .map_err(|_| AdministrativeError::InvalidRequest)?;
389                        match tokio::fs::symlink_metadata(&session.path).await {
390                            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
391                            Ok(_) => return Err(AdministrativeError::Conflict),
392                            Err(_) => return Err(AdministrativeError::InvalidRequest),
393                        }
394                        Ok(Some(prepared))
395                    }
396                    _ => {
397                        let record = catalog.get(profile.agent_id).await?;
398                        if record.spec != prepared.spec {
399                            return Err(AdministrativeError::InvalidRequest);
400                        }
401                        if Some(record.revision) != request.action.revision() {
402                            return Err(AdministrativeError::StaleRevision);
403                        }
404                        if self.inner.service.phase(profile.agent_id).is_some() {
405                            return Err(AdministrativeError::Busy);
406                        }
407                        prepared
408                            .binding
409                            .preflight_session(&prepared.spec)
410                            .await
411                            .map_err(|_| AdministrativeError::InvalidRequest)?;
412                        // A fresh environment, never cached by the frozen set. The
413                        // real restore repeats readonly validation before writer.
414                        Ok(Some(
415                            self.inner
416                                .profiles
417                                .prepare(profile)
418                                .await
419                                .map_err(|_| AdministrativeError::InvalidRequest)?,
420                        ))
421                    }
422                }
423            }
424            _ => Ok(None),
425        }
426    }
427    async fn run_reserved(
428        &self,
429        reserved: ServiceReservation<'_>,
430        request: LifecycleRequest,
431    ) -> AdministrativeResult {
432        // An entry lookup may have seen None before an earlier identical job
433        // finished and vacated the map. Reconcile again inside the reservation,
434        // before stale profile/owner checks can misclassify that duplicate.
435        if let Some(receipt) = reserved
436            .catalog()
437            .lifecycle_receipt(request.scope, request.request_id)
438            .await?
439        {
440            if receipt.request != request {
441                return Err(AdministrativeError::Conflict);
442            }
443            return Ok(receipt);
444        }
445        let prepared = self.preflight(&reserved, &request).await?;
446        let admission = reserved
447            .catalog()
448            .prepare_lifecycle(request.clone())
449            .await?;
450        if !admission.fresh {
451            return Ok(admission.receipt);
452        }
453        // Only this fresh branch may publish an outcome. An uncertain prepare
454        // error above never takes over a visible row or writes a fake Rejected.
455        let result = AssertUnwindSafe(self.act(&reserved, &request, prepared))
456            .catch_unwind()
457            .await;
458        let status = match result {
459            Ok(Ok(result)) => LifecycleState::Succeeded { result },
460            Ok(Err(status)) => status,
461            Err(_) => LifecycleState::Uncertain {
462                code: LifecycleFailure::Internal,
463            },
464        };
465        Ok(reserved.catalog().finish_lifecycle(request, status).await?)
466    }
467    async fn act(
468        &self,
469        reserved: &ServiceReservation<'_>,
470        request: &LifecycleRequest,
471        prepared: Option<PreparedProfile>,
472    ) -> Result<LifecycleResult, LifecycleState> {
473        let guard = CatalogGuard {
474            epoch: request.epoch,
475            revision: request.action.revision().unwrap_or(1),
476        };
477        match request.action {
478            LifecycleAction::CreateProfile { .. } | LifecycleAction::RestoreProfile { .. } => {
479                let prepared = prepared.ok_or_else(internal_uncertain)?;
480                self.load(
481                    reserved,
482                    prepared,
483                    matches!(request.action, LifecycleAction::CreateProfile { .. }),
484                    guard,
485                )
486                .await
487                .map(|revision| LifecycleResult::Loaded { revision })
488                // Creating files/registering/Starting may have happened.
489                .map_err(|_| internal_uncertain())
490            }
491            LifecycleAction::Cancel {
492                agent_id,
493                ticket_id,
494                ..
495            } => reserved
496                .cancel_guarded(agent_id, guard, ticket_id)
497                .await
498                .map(|signalled| LifecycleResult::CancelSignalled { signalled })
499                .map_err(classify_guarded),
500            LifecycleAction::CancelSubmitted {
501                agent_id,
502                submitted_request_id,
503                ..
504            } => reserved
505                .cancel_submitted_guarded(agent_id, guard, submitted_request_id)
506                .await
507                .map(|signalled| LifecycleResult::CancelSignalled { signalled })
508                .map_err(classify_guarded),
509            LifecycleAction::Close { agent_id, .. } => {
510                reserved
511                    .close_guarded(agent_id, guard)
512                    .await
513                    .map_err(classify_guarded)?;
514                let record = reserved
515                    .catalog()
516                    .get(agent_id)
517                    .await
518                    .map_err(|_| internal_uncertain())?;
519                if record.state != AgentState::Closed {
520                    return Err(internal_uncertain());
521                }
522                Ok(LifecycleResult::Closed {
523                    revision: record.revision,
524                })
525            }
526            _ => Err(internal_uncertain()),
527        }
528    }
529    async fn load(
530        &self,
531        reserved: &ServiceReservation<'_>,
532        prepared: PreparedProfile,
533        create: bool,
534        guard: CatalogGuard,
535    ) -> Result<u64, AdministrativeError> {
536        let PreparedProfile {
537            reference,
538            spec,
539            limits,
540            binding,
541        } = prepared;
542        let (record, binding) = if create {
543            let session = spec
544                .session
545                .as_ref()
546                .ok_or(AdministrativeError::InvalidRequest)?;
547            let path = session
548                .path
549                .to_str()
550                .ok_or(AdministrativeError::InvalidRequest)?;
551            let env = binding
552                .execution_environment()
553                .map_err(|_| AdministrativeError::InvalidRequest)?;
554            let created_at = SystemTime::now()
555                .duration_since(UNIX_EPOCH)
556                .map(|elapsed| i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX))
557                .unwrap_or(0);
558            let storage = JsonlSessionStorage::create_new(
559                env,
560                path,
561                JsonlV4Header::new(
562                    session.id.clone(),
563                    created_at,
564                    format!("{}", spec.launch.cwd.display()),
565                    None,
566                    None,
567                    None,
568                ),
569                Arc::new(SystemClock),
570                Arc::new(DefaultIdGenerator::new()),
571            )
572            .await
573            .map_err(|_| AdministrativeError::OutcomeUnknown)?;
574            storage.drain().await;
575            storage.release_writer_lease();
576            binding
577                .preflight_session(&spec)
578                .await
579                .map_err(|_| AdministrativeError::OutcomeUnknown)?;
580            let binding = self
581                .inner
582                .profiles
583                .prepare(reference)
584                .await
585                .map_err(|_| AdministrativeError::OutcomeUnknown)?
586                .binding;
587            (reserved.catalog().register(spec).await?, binding)
588        } else {
589            let record = reserved.catalog().get(spec.id).await?;
590            if record.spec != spec || record.revision != guard.revision {
591                return Err(AdministrativeError::Conflict);
592            }
593            (record, binding)
594        };
595        let id = record.spec.id;
596        reserved
597            .restore_bound(
598                id,
599                if create {
600                    reserved.catalog().guard(&record)
601                } else {
602                    guard
603                },
604                limits,
605                binding,
606            )
607            .await
608            .map_err(|_| AdministrativeError::OutcomeUnknown)?;
609        let loaded = reserved.catalog().get(id).await?;
610        if self.inner.service.phase(id) != Some(OwnerPhase::Live) || !loaded.state.is_resident() {
611            return Err(AdministrativeError::OutcomeUnknown);
612        }
613        Ok(loaded.revision)
614    }
615    async fn run_stop(
616        &self,
617        mut reserved: StopReservation<'_>,
618        request: LifecycleRequest,
619    ) -> AdministrativeResult {
620        let admission = reserved
621            .catalog()
622            .prepare_lifecycle(request.clone())
623            .await?;
624        if !admission.fresh {
625            return Ok(admission.receipt);
626        }
627        // Keep the write reservation even when drain fails or panics, so an
628        // external unconditional shutdown cannot close storage before finish.
629        let settled = AssertUnwindSafe(reserved.settle()).catch_unwind().await;
630        if !matches!(settled, Ok(Ok(()))) {
631            return Ok(reserved
632                .catalog()
633                .finish_lifecycle(request, internal_uncertain())
634                .await?);
635        }
636        let drained = reserved
637            .drain()
638            .await
639            .map_err(|_| AdministrativeError::OutcomeUnknown)?;
640        let receipt = drained
641            .catalog()
642            .finish_lifecycle(
643                request,
644                LifecycleState::Succeeded {
645                    result: LifecycleResult::NativeSettled {},
646                },
647            )
648            .await?;
649        *self
650            .inner
651            .settled_receipt
652            .lock()
653            .unwrap_or_else(|poison| poison.into_inner()) = Some(receipt.clone());
654        drained
655            .close_storage()
656            .await
657            .map_err(|_| AdministrativeError::OutcomeUnknown)?;
658        self.inner.stop_completed.cancel();
659        Ok(receipt)
660    }
661}
662async fn observe(mut observer: Observer) -> AdministrativeResult {
663    loop {
664        let result = observer.borrow().clone();
665        if let Some(result) = result {
666            return result;
667        }
668        observer
669            .changed()
670            .await
671            .map_err(|_| AdministrativeError::OutcomeUnknown)?;
672    }
673}
674fn internal_uncertain() -> LifecycleState {
675    LifecycleState::Uncertain {
676        code: LifecycleFailure::Internal,
677    }
678}
679
680#[cfg(test)]
681#[path = "administration_tests.rs"]
682mod tests;
683fn classify_guarded(error: ServiceError) -> LifecycleState {
684    let code = match error {
685        ServiceError::NotLoaded => LifecycleFailure::NotFound,
686        ServiceError::Busy
687        | ServiceError::AlreadyOwned
688        | ServiceError::Backend(BackendError::Busy) => LifecycleFailure::Busy,
689        ServiceError::Backend(BackendError::GuardRejected(error)) => match error.as_ref() {
690            CatalogError::EpochConflict => LifecycleFailure::StaleEpoch,
691            CatalogError::RevisionConflict { .. } => LifecycleFailure::StaleRevision,
692            _ => return internal_uncertain(),
693        },
694        _ => return internal_uncertain(),
695    };
696    LifecycleState::Rejected { code }
697}