Skip to main content

lash_core/runtime/
lifecycle.rs

1use super::*;
2
3impl LashRuntime {
4    pub fn unregister_plugin_session(&self) -> Result<(), crate::PluginError> {
5        if let Some(session) = self.session.as_ref() {
6            session
7                .plugins()
8                .host()
9                .unregister_session(&self.state.session_id)?;
10        }
11        Ok(())
12    }
13
14    pub(super) async fn from_host_state(
15        policy: SessionPolicy,
16        host: RuntimeHost,
17        services: RuntimeServices,
18        mut state: RuntimeSessionState,
19    ) -> Result<Self, SessionError> {
20        if state.session_id.is_empty() {
21            state.session_id = uuid::Uuid::new_v4().to_string();
22        }
23        // Defaulted state (e.g. `RuntimeSessionState::default()` used
24        // by fresh-session constructors) carries an empty policy.
25        // Fill it in from the caller's policy so tests and hosts that
26        // pass a real policy alongside default state don't trip the explicit
27        // model-spec guard below.
28        let state_policy_was_unconfigured = state.policy.recorded_provider_id().is_empty()
29            && state.policy.model.id.trim().is_empty();
30        if state_policy_was_unconfigured {
31            state.policy = policy.clone();
32        }
33        state.ensure_agent_frame_initialized();
34        let state_policy = state.policy.clone();
35        if let Some(frame) = state.current_agent_frame_mut()
36            && frame.assignment.policy.recorded_provider_id().is_empty()
37            && frame.assignment.policy.model.id.trim().is_empty()
38        {
39            frame.assignment.policy = state_policy;
40        }
41        state.policy = state.effective_policy().clone();
42        state.protocol_turn_options = state.effective_protocol_turn_options().clone();
43        normalize_session_graph(&mut state);
44        let policy = state.effective_policy().clone();
45        if policy.model.id.trim().is_empty() {
46            return Err(SessionError::Protocol(
47                "session policy missing model spec; hosts must supply explicit model metadata"
48                    .to_string(),
49            ));
50        }
51        let mut host = host;
52        // When a persistent backend is wired in, wrap the attachment
53        // store so every `put` records a write-ahead intent row first.
54        // Crashes between put and the next turn commit then surface as
55        // uncommitted manifest rows that GC can reconcile. Ephemeral
56        // (no-store) runtimes use the inner store directly — there's
57        // nothing to reconcile against.
58        if let Some(store) = services.store.clone() {
59            let manifest: Arc<dyn crate::AttachmentManifest> =
60                Arc::new(crate::attachments::PersistenceManifestAdapter(store));
61            let scoped: Arc<dyn crate::AttachmentStore> =
62                Arc::new(crate::SessionScopedAttachmentStore::new(
63                    Arc::clone(&host.core.durability.attachment_store),
64                    manifest,
65                    state.session_id.clone(),
66                ));
67            host.core.durability.attachment_store = scoped;
68        }
69        let services = services
70            .with_attachment_store(Arc::clone(&host.core.durability.attachment_store))
71            .with_process_env_store(Arc::clone(&host.core.durability.process_env_store));
72        let mut session = Session::new(services.clone(), &state.session_id).await?;
73        if let Some(tool_state) = state.tool_state_snapshot.clone() {
74            // Cold rebuild restores the exact persisted tool catalog, adopting
75            // the snapshot's generation. `apply_state` (a delta-apply that
76            // requires `snapshot.generation == base` and bumps) would reject a
77            // session whose surface reached generation ≥ 2 onto a fresh base-1
78            // registry — the worker-rebuild / restart divergence. `restore_state`
79            // adopts the snapshot's generation wholesale, so any generation
80            // rebuilds.
81            let report = session
82                .plugins()
83                .tool_registry()
84                .restore_state(tool_state)
85                .map_err(|err| SessionError::Protocol(err.to_string()))?;
86            if !report.orphaned.is_empty() {
87                tracing::warn!(
88                    session_id = %state.session_id,
89                    orphaned = ?report.orphaned,
90                    "session restored with orphaned tools: no registered source \
91                     resolves them; they are Off until their source returns"
92                );
93            }
94        }
95        session.refresh_tool_catalog().await?;
96        if let Some(snapshot) = state.plugin_snapshot.clone() {
97            session
98                .plugins()
99                .restore(&snapshot)
100                .map_err(|err| SessionError::Protocol(err.to_string()))?;
101        }
102        let protocol_session = Arc::clone(session.plugins().protocol_session());
103        let session_id = state.session_id.clone();
104        protocol_session
105            .restore_session(
106                crate::plugin::ProtocolSessionContext::new(&mut session, &session_id),
107                &state,
108            )
109            .await?;
110        state.discard_runtime_snapshots();
111        session
112            .plugins()
113            .emit_runtime_event(crate::PluginLifecycleEvent::SessionRestored(
114                crate::SessionReadView::from_persisted_state(&state),
115            ))
116            .await;
117        let protocol_turn_options = state.protocol_turn_options.clone();
118        Ok(Self {
119            session: Some(session),
120            policy,
121            host,
122            services,
123            state,
124            runtime_scope_id: Arc::<str>::from(uuid::Uuid::new_v4().to_string()),
125            managed_sessions: Arc::new(Mutex::new(HashMap::new())),
126            managed_turns: Arc::new(Mutex::new(HashMap::new())),
127            protocol_turn_options,
128            shared_token_ledger: Arc::new(std::sync::Mutex::new(Vec::new())),
129            process_sync_needed: Arc::new(AtomicBool::new(false)),
130            turn_phase_probe: None,
131            residency: Residency::default(),
132        })
133    }
134
135    /// Build a runtime for an embedded host with no background worker support.
136    pub async fn from_embedded_state(
137        policy: SessionPolicy,
138        host: EmbeddedRuntimeHost,
139        services: RuntimeServices,
140        state: RuntimeSessionState,
141    ) -> Result<Self, SessionError> {
142        Self::from_host_state(policy, host.into(), services, state).await
143    }
144
145    /// Build a runtime for a host that supports background plugin work.
146    pub async fn from_background_state(
147        policy: SessionPolicy,
148        host: ProcessRuntimeHost,
149        services: RuntimeServices,
150        state: RuntimeSessionState,
151    ) -> Result<Self, SessionError> {
152        Self::from_host_state(policy, host.into(), services, state).await
153    }
154
155    /// Build a runtime for an embedded host with persistent store support.
156    pub async fn from_persistent_embedded_state(
157        policy: SessionPolicy,
158        host: EmbeddedRuntimeHost,
159        services: PersistentRuntimeServices,
160        state: RuntimeSessionState,
161    ) -> Result<Self, SessionError> {
162        Self::from_host_state(policy, host.into(), services.into_runtime_services(), state).await
163    }
164
165    /// Build a runtime for a background-capable host with persistent store support.
166    pub async fn from_persistent_background_state(
167        policy: SessionPolicy,
168        host: ProcessRuntimeHost,
169        services: PersistentRuntimeServices,
170        state: RuntimeSessionState,
171    ) -> Result<Self, SessionError> {
172        Self::from_host_state(policy, host.into(), services.into_runtime_services(), state).await
173    }
174
175    /// Assemble a runtime from already-resolved parts: the single place that maps
176    /// `(store, process_registry)` to the right host/services constructor, applies
177    /// residency, and stamps it onto the runtime.
178    ///
179    /// Every construction path — the live open (`from_environment`), the worker
180    /// rebuild (`EmbeddedRuntimeBuilder::build`), and child-session
181    /// materialization — routes through here so the store/registry wiring and
182    /// residency cannot drift between them. That drift previously shipped: the
183    /// worker rebuild silently kept the full graph and skipped the persisted
184    /// tool-catalog restore that the live path applied.
185    pub(crate) async fn assemble_runtime(
186        policy: SessionPolicy,
187        embedded_host: EmbeddedRuntimeHost,
188        plugin_session: Arc<crate::PluginSession>,
189        store: Option<Arc<dyn crate::store::RuntimePersistence>>,
190        process_registry: Option<Arc<dyn ProcessRegistry>>,
191        mut state: RuntimeSessionState,
192        residency: Residency,
193    ) -> Result<Self, SessionError> {
194        // ActivePathOnly without a store is a data-loss footgun: trimming drops
195        // orphans from RAM with nowhere to reload them from.
196        if matches!(residency, Residency::ActivePathOnly) && store.is_none() {
197            return Err(SessionError::Protocol(
198                "Residency::ActivePathOnly requires a persistent store — \
199                 without one, trimmed orphans are irrecoverable"
200                    .to_string(),
201            ));
202        }
203        // Heal FIRST (against the full resident set), then trim to the residency.
204        // `from_host_state` normalizes again, which is safe on a trimmed graph.
205        normalize_session_graph(&mut state);
206        apply_residency_on_load(&mut state, residency);
207        let mut runtime = match (store, process_registry) {
208            (Some(store), Some(registry)) => {
209                let host = ProcessRuntimeHost::new(embedded_host, registry);
210                let services = PersistentRuntimeServices::new(plugin_session, store);
211                Self::from_persistent_background_state(policy, host, services, state).await?
212            }
213            (Some(store), None) => {
214                let services = PersistentRuntimeServices::new(plugin_session, store);
215                Self::from_persistent_embedded_state(policy, embedded_host, services, state).await?
216            }
217            (None, Some(registry)) => {
218                let host = ProcessRuntimeHost::new(embedded_host, registry);
219                let services = RuntimeServices::new(plugin_session);
220                Self::from_background_state(policy, host, services, state).await?
221            }
222            (None, None) => {
223                let services = RuntimeServices::new(plugin_session);
224                Self::from_embedded_state(policy, embedded_host, services, state).await?
225            }
226        };
227        runtime.residency = residency;
228        Ok(runtime)
229    }
230
231    /// Embedder-preferred constructor: build a `LashRuntime` from a
232    /// shared `RuntimeEnvironment`.
233    ///
234    /// Everything expensive (plugin factories, HTTP client pool, prompt
235    /// template, path resolver) lives on the environment and is
236    /// reused across every runtime the embedder builds. This call is
237    /// O(plugin-session-registration + state-hydration), not
238    /// O(full-infrastructure-init).
239    ///
240    /// * `env` — the shared environment. `env.plugin_host` must be set.
241    /// * `policy` — per-session policy (model, provider, autonomy, turn limits).
242    /// * `state` — persisted session state (empty for a fresh session).
243    /// * `store` — per-session store. `None` builds an embedded runtime
244    ///   with no persistence; `Some` builds a persistent
245    ///   background-capable runtime.
246    pub async fn from_environment(
247        env: &RuntimeEnvironment,
248        policy: SessionPolicy,
249        state: RuntimeSessionState,
250        store: Option<Arc<dyn crate::store::RuntimePersistence>>,
251    ) -> Result<Self, SessionError> {
252        let plugin_host = env.plugin_host.as_ref().ok_or_else(|| {
253            SessionError::Protocol(
254                "RuntimeEnvironment.plugin_host is required for from_environment".to_string(),
255            )
256        })?;
257        let plugin_session = plugin_host
258            .build_session(state.session_id.as_str(), state.plugin_snapshot.as_ref())
259            .map_err(|err| SessionError::Protocol(err.to_string()))?;
260        let mut embedded = EmbeddedRuntimeHost::new(env.core.clone());
261        if let Some(factory) = env.session_store_factory.as_ref() {
262            embedded = embedded.with_session_store_factory(Arc::clone(factory));
263        }
264        if let Some(store) = env.trigger_store.as_ref() {
265            embedded = embedded.with_trigger_store(Arc::clone(store));
266        }
267        let mut runtime = Self::assemble_runtime(
268            policy,
269            embedded,
270            plugin_session,
271            store,
272            env.process_registry.as_ref().cloned(),
273            state,
274            env.residency,
275        )
276        .await?;
277        // Thread the host's process-work poke onto this session's host so the
278        // process admin seam can wake the runner after a successful start.
279        runtime.host.process_work_poke = env.process_work_poke.clone();
280        runtime.host.queued_work_poke = env.queued_work_poke.clone();
281        Ok(runtime)
282    }
283
284    /// Persist any dirty state and drop the runtime, returning a lightweight
285    /// handle the embedder can cache and resume later via
286    /// [`LashRuntime::resume`]. This is the webserver-embedder parking
287    /// primitive: the handle holds only the session id, policy, and store
288    /// reference — no graph nodes, no plugin session, no HTTP client.
289    pub async fn park(mut self) -> Result<ParkedSession, SessionError> {
290        let store = self.services.store.clone().ok_or_else(|| {
291            SessionError::Protocol(
292                "park() requires a persistent runtime (store is not set)".to_string(),
293            )
294        })?;
295        let session_id = self.state.session_id.clone();
296        let policy = self.policy.clone();
297        // Flush any dirty resident state to the store before dropping.
298        let commit = crate::store::RuntimeCommit::persisted_state(&self.state, &[]);
299        let result = store.commit_runtime_state(commit).await.map_err(|err| {
300            SessionError::Protocol(format!("failed to persist runtime state: {err}"))
301        })?;
302        self.state.apply_persisted_commit_result(result);
303        // Drain pending tombstones if any. Under KeepHistory this is a
304        // no-op (tombstones never get added). Under DropOrphans, a future
305        // orphan-trim path would populate the set for Phase 10's vacuum()
306        // design.
307        Ok(ParkedSession {
308            session_id,
309            store,
310            policy,
311        })
312    }
313
314    /// Resume a previously parked session against a shared environment.
315    /// Loads only the active-path graph when
316    /// `env.residency == ActivePathOnly`; under `KeepAll`
317    /// loads the full graph (current behavior).
318    pub async fn resume(
319        parked: ParkedSession,
320        env: &RuntimeEnvironment,
321    ) -> Result<Self, SessionError> {
322        // Under ActivePathOnly, skip the full-graph load: fetch head
323        // metadata + the active-path chain only. Durable impls can
324        // ActivePathOnly is an exact store capability. Stores that do
325        // not support it must return UnsupportedReadScope; resume does
326        // not fall back to a full graph load.
327        let loaded = match env.residency {
328            Residency::KeepAll => {
329                crate::store::load_persisted_session_state(parked.store.as_ref()).await
330            }
331            Residency::ActivePathOnly => {
332                crate::store::load_persisted_session_state_active_path(parked.store.as_ref(), None)
333                    .await
334            }
335        }
336        .map_err(|err| SessionError::Protocol(format!("failed to load runtime state: {err}")))?;
337        let state = loaded.unwrap_or_else(|| RuntimeSessionState {
338            session_id: parked.session_id.clone(),
339            policy: parked.policy.clone(),
340            ..RuntimeSessionState::default()
341        });
342        Self::from_environment(env, parked.policy, state, Some(parked.store)).await
343    }
344
345    /// Opt-in async read for historic (non-active-path) nodes under
346    /// `Residency::ActivePathOnly`. Plugins that walk the full graph
347    /// call this instead of `session_graph().find_node()` so missing
348    /// nodes surface as `Ok(None)` rather than silently missing.
349    pub async fn get_historic_node(
350        &self,
351        node_id: &str,
352    ) -> Result<Option<crate::SessionNodeRecord>, SessionError> {
353        if let Some(node) = self.state.session_graph.find_node(node_id) {
354            return Ok(Some(node.clone()));
355        }
356        let store = self.services.store.clone().ok_or_else(|| {
357            SessionError::Protocol("get_historic_node() requires a persistent runtime".to_string())
358        })?;
359        store
360            .load_node(node_id)
361            .await
362            .map_err(|err| SessionError::Protocol(format!("failed to load historic node: {err}")))
363    }
364
365    /// Store-resident node IDs that are NOT reachable from the current
366    /// leaf — i.e. orphans eligible for tombstoning. lash owns RAM; the
367    /// host owns disk lifecycle, so this is a primitive the host calls
368    /// on its own schedule (e.g. every N turns, or off-peak).
369    ///
370    /// Typical autonomous-agent loop:
371    ///
372    /// ```ignore
373    /// let orphans = runtime.orphaned_node_ids().await?;
374    /// if !orphans.is_empty() {
375    ///     store.tombstone_nodes(&orphans).await;
376    /// }
377    /// // And less often:
378    /// store.vacuum().await;
379    /// ```
380    pub async fn orphaned_node_ids(&self) -> Result<Vec<String>, SessionError> {
381        let store = self.services.store.clone().ok_or_else(|| {
382            SessionError::Protocol("orphaned_node_ids() requires a persistent runtime".to_string())
383        })?;
384        let Some(read) = store
385            .load_session(crate::store::SessionReadScope::FullGraph)
386            .await
387            .map_err(|err| SessionError::Protocol(format!("failed to load full graph: {err}")))?
388        else {
389            return Ok(Vec::new());
390        };
391        let active: std::collections::HashSet<&str> = read
392            .graph
393            .active_path_nodes()
394            .iter()
395            .map(|node| node.node_id.as_str())
396            .collect();
397        Ok(read
398            .graph
399            .nodes
400            .iter()
401            .filter(|node| !active.contains(node.node_id.as_str()))
402            .map(|node| node.node_id.clone())
403            .collect())
404    }
405}