Skip to main content

rpi_cli/host/
lifecycle.rs

1//! Administrative intent/result journal, separate from native prompt admission.
2//! This module never executes an Agent. Only a fresh committed admission permits
3//! the trusted coordinator to attempt an action; duplicate/uncertain work is not
4//! replayed. No credentials, tool payloads or arbitrary result JSON are accepted.
5use super::{
6    AgentId, CatalogError, CatalogResult, ControlScopeId, HostEpoch, ProfileRef, RequestId, RunId,
7};
8use rusqlite::{params, Connection, OptionalExtension, TransactionBehavior};
9use serde::{Deserialize, Serialize};
10
11#[cfg(all(test, unix))]
12#[path = "lifecycle_tests.rs"]
13mod tests;
14
15/// No eviction: losing request identities would permit unsafe replay. Capacity
16/// exhaustion is an explicit pre-effect rejection, not a retention promise.
17pub const MAX_LIFECYCLE_REQUESTS: usize = 1024;
18const MAX_BYTES: usize = 4096;
19
20/// Re-establish durability for visible committed rows, including retry after a
21/// failed/uncertain acknowledgement. An empty read transaction/COMMIT is not a
22/// synchronization barrier. Called only outside transactions by the sole worker.
23/// FULL checkpoint must copy and sync every WAL frame; busy/partial/non-WAL
24/// results cannot grant a fresh execution owner or acknowledge a receipt.
25pub(super) fn checkpoint(connection: &Connection) -> CatalogResult<()> {
26    let (busy, logged, synced): (i64, i64, i64) =
27        connection.query_row("PRAGMA wal_checkpoint(FULL)", [], |row| {
28            Ok((row.get(0)?, row.get(1)?, row.get(2)?))
29        })?;
30    if busy != 0 || logged < 0 || synced < logged {
31        return Err(CatalogError::LifecycleUncertain);
32    }
33    Ok(())
34}
35
36#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct LifecycleRequest {
39    pub scope: ControlScopeId,
40    pub request_id: RequestId,
41    pub epoch: HostEpoch,
42    pub action: LifecycleAction,
43}
44#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
46pub enum LifecycleAction {
47    /// Legacy unbound v2 intent. Retained for receipt compatibility; a profile
48    /// coordinator must not execute it without an immutable configuration ref.
49    Create {
50        agent_id: AgentId,
51    },
52    /// Legacy unbound v2 intent; see `Create`.
53    Restore {
54        agent_id: AgentId,
55        revision: u64,
56    },
57    CreateProfile {
58        profile: ProfileRef,
59    },
60    RestoreProfile {
61        profile: ProfileRef,
62        revision: u64,
63    },
64    /// Exact volatile-ticket native intent retained for historical receipts.
65    Cancel {
66        agent_id: AgentId,
67        revision: u64,
68        ticket_id: RunId,
69    },
70    /// Stable input target, distinct from both this lifecycle request's ID and
71    /// any transient duplicate observer ticket. No recovery or replay implied.
72    CancelSubmitted {
73        agent_id: AgentId,
74        revision: u64,
75        submitted_request_id: RequestId,
76    },
77    Close {
78        agent_id: AgentId,
79        revision: u64,
80    },
81    Stop {},
82}
83impl LifecycleAction {
84    pub(crate) fn agent(&self) -> Option<AgentId> {
85        match self {
86            Self::Create { agent_id }
87            | Self::Restore { agent_id, .. }
88            | Self::Cancel { agent_id, .. }
89            | Self::CancelSubmitted { agent_id, .. }
90            | Self::Close { agent_id, .. } => Some(*agent_id),
91            Self::CreateProfile { profile } | Self::RestoreProfile { profile, .. } => {
92                Some(profile.agent_id)
93            }
94            Self::Stop {} => None,
95        }
96    }
97    pub(crate) fn revision(&self) -> Option<u64> {
98        match self {
99            Self::Restore { revision, .. }
100            | Self::RestoreProfile { revision, .. }
101            | Self::Cancel { revision, .. }
102            | Self::CancelSubmitted { revision, .. }
103            | Self::Close { revision, .. } => Some(*revision),
104            _ => None,
105        }
106    }
107}
108impl LifecycleRequest {
109    pub(crate) fn validate(&self) -> CatalogResult<()> {
110        if self
111            .action
112            .revision()
113            .is_some_and(|n| !(1..=i64::MAX as u64).contains(&n))
114        {
115            return Err(CatalogError::InvalidRecord(
116                "lifecycle revision outside stored range",
117            ));
118        }
119        Ok(())
120    }
121}
122
123#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
125pub enum LifecycleResult {
126    Loaded {
127        revision: u64,
128    },
129    Closed {
130        revision: u64,
131    },
132    /// A cooperative signal only; not proof of execution settlement.
133    CancelSignalled {
134        signalled: bool,
135    },
136    /// Native owners settled; not proof the process or listener has exited.
137    NativeSettled {},
138}
139#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "snake_case")]
141pub enum LifecycleFailure {
142    Unauthorized,
143    InvalidRequest,
144    NotFound,
145    StaleEpoch,
146    StaleRevision,
147    Conflict,
148    Busy,
149    Capacity,
150    PersistenceUncertain,
151    Internal,
152}
153#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
155pub enum LifecycleState {
156    Prepared {},
157    Succeeded {
158        result: LifecycleResult,
159    },
160    /// Known pre-effect rejection, not a generic backend failure.
161    Rejected {
162        code: LifecycleFailure,
163    },
164    /// Action/settlement may have happened. Inspect; never automatically retry.
165    Uncertain {
166        code: LifecycleFailure,
167    },
168    /// Previous owner lost before publishing a result. No replay authority.
169    Interrupted {},
170}
171impl LifecycleState {
172    fn kind(&self) -> &'static str {
173        match self {
174            Self::Prepared {} => "prepared",
175            Self::Succeeded { .. } => "succeeded",
176            Self::Rejected { .. } => "rejected",
177            Self::Uncertain { .. } => "uncertain",
178            Self::Interrupted {} => "interrupted",
179        }
180    }
181}
182#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(deny_unknown_fields)]
184pub struct LifecycleReceipt {
185    pub request: LifecycleRequest,
186    pub status: LifecycleState,
187}
188impl LifecycleReceipt {
189    pub(crate) fn validate(&self) -> CatalogResult<()> {
190        self.request.validate()?;
191        if let LifecycleState::Succeeded { result } = &self.status {
192            let compatible = match (&self.request.action, result) {
193                (
194                    LifecycleAction::Create { .. }
195                    | LifecycleAction::Restore { .. }
196                    | LifecycleAction::CreateProfile { .. }
197                    | LifecycleAction::RestoreProfile { .. },
198                    LifecycleResult::Loaded { revision },
199                )
200                | (LifecycleAction::Close { .. }, LifecycleResult::Closed { revision }) => {
201                    (self.request.action.revision().unwrap_or(1)..=i64::MAX as u64)
202                        .contains(revision)
203                }
204                (
205                    LifecycleAction::Cancel { .. } | LifecycleAction::CancelSubmitted { .. },
206                    LifecycleResult::CancelSignalled { .. },
207                )
208                | (LifecycleAction::Stop {}, LifecycleResult::NativeSettled {}) => true,
209                _ => false,
210            };
211            if !compatible {
212                return Err(CatalogError::InvalidRecord(
213                    "lifecycle result does not match action",
214                ));
215            }
216        }
217        Ok(())
218    }
219}
220#[derive(Clone, Debug)]
221pub struct LifecycleAdmission {
222    pub receipt: LifecycleReceipt,
223    /// Exactly one committed preparer gets true. It is NOT execution success.
224    /// A dropped response does not transfer authority to a duplicate request.
225    pub fresh: bool,
226}
227
228pub(super) fn create_schema(connection: &Connection) -> CatalogResult<()> {
229    connection.execute_batch("CREATE TABLE lifecycle_requests (
230        scope_id TEXT NOT NULL, request_id TEXT NOT NULL, epoch TEXT NOT NULL,
231        agent_id TEXT, status TEXT NOT NULL CHECK(status IN ('prepared','succeeded','rejected','uncertain','interrupted')),
232        data TEXT NOT NULL CHECK(length(CAST(data AS BLOB)) <= 4096),
233        PRIMARY KEY(scope_id,request_id)
234    );
235    CREATE INDEX lifecycle_pending ON lifecycle_requests(status,agent_id);
236    PRAGMA user_version=2;")?;
237    Ok(())
238}
239fn encode(receipt: &LifecycleReceipt) -> CatalogResult<String> {
240    receipt.validate()?;
241    let data = serde_json::to_string(receipt)?;
242    if data.len() > MAX_BYTES {
243        return Err(CatalogError::InvalidRecord(
244            "lifecycle record exceeds byte budget",
245        ));
246    }
247    Ok(data)
248}
249type Stored = (String, String, String, Option<String>, String, String);
250fn decode(row: Stored) -> CatalogResult<LifecycleReceipt> {
251    let (scope, id, epoch, agent, status, data) = row;
252    if data.len() > MAX_BYTES {
253        return Err(CatalogError::InvalidRecord(
254            "lifecycle record exceeds byte budget",
255        ));
256    }
257    let receipt: LifecycleReceipt = serde_json::from_str(&data)?;
258    receipt.validate()?;
259    if scope != receipt.request.scope.to_string()
260        || id != receipt.request.request_id.to_string()
261        || epoch != receipt.request.epoch.to_string()
262        || agent != receipt.request.action.agent().map(|id| id.to_string())
263        || status != receipt.status.kind()
264    {
265        return Err(CatalogError::InvalidRecord(
266            "lifecycle indexed fields do not match receipt",
267        ));
268    }
269    Ok(receipt)
270}
271fn row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Stored> {
272    Ok((
273        row.get(0)?,
274        row.get(1)?,
275        row.get(2)?,
276        row.get(3)?,
277        row.get(4)?,
278        row.get(5)?,
279    ))
280}
281pub(super) fn get(
282    connection: &Connection,
283    scope: ControlScopeId,
284    id: RequestId,
285) -> CatalogResult<Option<LifecycleReceipt>> {
286    connection.query_row("SELECT scope_id,request_id,epoch,agent_id,status,data FROM lifecycle_requests WHERE scope_id=?1 AND request_id=?2", params![scope.to_string(),id.to_string()], row).optional()?.map(decode).transpose()
287}
288fn update(connection: &Connection, receipt: &LifecycleReceipt) -> CatalogResult<()> {
289    let data = encode(receipt)?;
290    if connection.execute(
291        "UPDATE lifecycle_requests SET status=?3,data=?4 WHERE scope_id=?1 AND request_id=?2",
292        params![
293            receipt.request.scope.to_string(),
294            receipt.request.request_id.to_string(),
295            receipt.status.kind(),
296            data
297        ],
298    )? != 1
299    {
300        return Err(CatalogError::UnknownLifecycle);
301    }
302    Ok(())
303}
304/// Called inside the same startup transaction that classifies Agent state and
305/// advances epoch. Validate every bounded row before committing any changes.
306pub(super) fn recover(connection: &Connection, previous: HostEpoch) -> CatalogResult<()> {
307    let count: usize =
308        connection.query_row("SELECT count(*) FROM lifecycle_requests", [], |r| r.get(0))?;
309    if count > MAX_LIFECYCLE_REQUESTS {
310        return Err(CatalogError::InvalidRecord("lifecycle capacity exceeded"));
311    }
312    let mut cursor = (String::new(), String::new());
313    loop {
314        let rows = {
315            let mut statement = connection.prepare("SELECT scope_id,request_id,epoch,agent_id,status,data FROM lifecycle_requests WHERE (scope_id,request_id) > (?1,?2) ORDER BY scope_id,request_id LIMIT 128")?;
316            let rows = statement
317                .query_map(params![cursor.0, cursor.1], row)?
318                .collect::<rusqlite::Result<Vec<_>>>()?;
319            rows
320        };
321        if rows.is_empty() {
322            break;
323        }
324        for row in rows {
325            cursor = (row.0.clone(), row.1.clone());
326            let mut receipt = decode(row)?;
327            if receipt.status == (LifecycleState::Prepared {}) {
328                if receipt.request.epoch != previous {
329                    return Err(CatalogError::InvalidRecord(
330                        "pending lifecycle belongs to another epoch",
331                    ));
332                }
333                receipt.status = LifecycleState::Interrupted {};
334                update(connection, &receipt)?;
335            }
336        }
337    }
338    Ok(())
339}
340pub(super) fn has_pending(connection: &Connection, agent: Option<AgentId>) -> CatalogResult<bool> {
341    let agent = agent.map(|id| id.to_string());
342    Ok(connection.query_row("SELECT EXISTS(SELECT 1 FROM lifecycle_requests WHERE status='prepared' AND (agent_id IS NULL OR ?1 IS NULL OR agent_id=?1))", [&agent], |r| r.get(0))?)
343}
344
345pub(super) fn prepare(
346    connection: &mut Connection,
347    epoch: HostEpoch,
348    request: LifecycleRequest,
349) -> CatalogResult<LifecycleAdmission> {
350    request.validate()?;
351    let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
352    if let Some(receipt) = get(&transaction, request.scope, request.request_id)? {
353        if receipt.request != request {
354            return Err(CatalogError::LifecycleConflict);
355        }
356        return Ok(LifecycleAdmission {
357            receipt,
358            fresh: false,
359        });
360    }
361    if request.epoch != epoch {
362        return Err(CatalogError::EpochConflict);
363    }
364    let count: usize =
365        transaction.query_row("SELECT count(*) FROM lifecycle_requests", [], |r| r.get(0))?;
366    if count >= MAX_LIFECYCLE_REQUESTS {
367        return Err(CatalogError::LifecycleCapacity);
368    }
369    let agent = request.action.agent().map(|id| id.to_string());
370    if has_pending(&transaction, request.action.agent())? {
371        return Err(CatalogError::LifecycleBusy);
372    }
373    if let Some(id) = request.action.agent() {
374        let record = super::registry::find(&transaction, id)?;
375        match (&request.action, record) {
376            (LifecycleAction::Create { .. } | LifecycleAction::CreateProfile { .. }, None) => {}
377            (LifecycleAction::Create { .. } | LifecycleAction::CreateProfile { .. }, Some(_)) => {
378                return Err(CatalogError::AlreadyRegistered)
379            }
380            (_, None) => return Err(CatalogError::UnknownAgent),
381            (_, Some(record)) => {
382                let expected = request.action.revision().unwrap();
383                if expected != record.revision {
384                    return Err(CatalogError::RevisionConflict {
385                        expected,
386                        actual: record.revision,
387                    });
388                }
389            }
390        }
391    }
392    let receipt = LifecycleReceipt {
393        request,
394        status: LifecycleState::Prepared {},
395    };
396    let data = encode(&receipt)?;
397    transaction.execute("INSERT INTO lifecycle_requests (scope_id,request_id,epoch,agent_id,status,data) VALUES (?1,?2,?3,?4,'prepared',?5)", params![receipt.request.scope.to_string(),receipt.request.request_id.to_string(),receipt.request.epoch.to_string(),agent,data])?;
398    // Once a guarded explicit Close is admitted, a crash during native cleanup
399    // must not bring that member back. Whole-Host Stop leaves the set intact.
400    if let LifecycleAction::Close { agent_id, .. } = receipt.request.action {
401        super::recovery::prepare_close(&transaction, agent_id)?;
402    }
403    transaction.commit()?;
404    Ok(LifecycleAdmission {
405        receipt,
406        fresh: true,
407    })
408}
409pub(super) fn finish(
410    connection: &mut Connection,
411    epoch: HostEpoch,
412    request: LifecycleRequest,
413    status: LifecycleState,
414    bindings: &super::recovery::Bindings,
415) -> CatalogResult<LifecycleReceipt> {
416    if matches!(
417        status,
418        LifecycleState::Prepared {} | LifecycleState::Interrupted {}
419    ) {
420        return Err(CatalogError::InvalidRecord(
421            "only terminal lifecycle results can be published",
422        ));
423    }
424    let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
425    let mut receipt = get(&transaction, request.scope, request.request_id)?
426        .ok_or(CatalogError::UnknownLifecycle)?;
427    if receipt.request != request {
428        return Err(CatalogError::LifecycleConflict);
429    }
430    if receipt.status != (LifecycleState::Prepared {}) {
431        return if receipt.status == status {
432            Ok(receipt)
433        } else {
434            Err(CatalogError::LifecycleConflict)
435        };
436    }
437    if request.epoch != epoch {
438        return Err(CatalogError::EpochConflict);
439    }
440    receipt.status = status;
441    update(&transaction, &receipt)?;
442    if let LifecycleAction::Close { agent_id, .. } = request.action {
443        super::recovery::finish_close(
444            &transaction,
445            agent_id,
446            matches!(receipt.status, LifecycleState::Rejected { .. }),
447        )?;
448    }
449    if matches!(
450        receipt.status,
451        LifecycleState::Succeeded {
452            result: LifecycleResult::Loaded { .. }
453        }
454    ) {
455        if let LifecycleAction::CreateProfile { profile }
456        | LifecycleAction::RestoreProfile { profile, .. } = request.action
457        {
458            if let Some(binding) = bindings.get(&profile.agent_id) {
459                super::recovery::set(&transaction, profile.agent_id, *binding)?;
460            }
461        }
462    }
463    transaction.commit()?;
464    Ok(receipt)
465}