Skip to main content

lash_core/runtime/
lifecycle.rs

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