causa_runtime/session/owner.rs
1//! The session owner — [`Session`] (the non-`Clone` lifecycle anchor) and the
2//! by-value construction rejection it returns.
3//!
4//! The owner holds the private execution core behind an `Arc`; cloneable
5//! [`SessionHandle`]s are minted from it and share the same core.
6
7use std::sync::Arc;
8
9use crate::config::TurnRunOptions;
10use crate::conversation::ConversationState;
11use crate::driver::TurnRunner;
12
13use super::checkpoint::SessionCheckpoint;
14use super::execution::SessionCore;
15use super::handle::SessionHandle;
16use super::types::{SessionConfig, SessionError};
17
18/// Returned by [`Session::new`] when the supplied state is not idle.
19///
20/// A by-value constructor that rejects hands back **all** the inputs it
21/// consumed, not only the state: the caller keeps its [`ConversationState`], its
22/// assembled `runner` and `options`, and its `config` for a later attempt.
23/// Every field is cheap to move back — `runner` is an `Arc`, `options` and
24/// `config` are plain values.
25pub struct SessionBuildRejection {
26 /// Why construction was rejected.
27 pub error: SessionError,
28 /// The state, returned by value.
29 pub state: ConversationState,
30 /// The assembled runner, returned by value.
31 pub runner: Arc<TurnRunner>,
32 /// The assembled run options, returned by value.
33 pub options: TurnRunOptions,
34 /// The session configuration, returned by value.
35 pub config: SessionConfig,
36}
37
38impl std::fmt::Debug for SessionBuildRejection {
39 /// `TurnRunner` carries no `Debug` impl (it holds gateway / executor trait
40 /// objects), so the rejection renders it as an opaque handle and prints
41 /// the rest.
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 f.debug_struct("SessionBuildRejection")
44 .field("error", &self.error)
45 .field("state", &self.state)
46 .field("runner", &"Arc<TurnRunner>")
47 .field("options", &self.options)
48 .field("config", &self.config)
49 .finish()
50 }
51}
52
53/// The session owner: one per conversation, held by the harness.
54///
55/// Non-`Clone` by design — the owner is the lifecycle anchor. Cloneable
56/// [`SessionHandle`]s are the operation entries; they neither own the
57/// lifecycle nor expose the writable state.
58pub struct Session {
59 core: Arc<SessionCore>,
60}
61
62impl std::fmt::Debug for Session {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 f.debug_struct("Session")
65 .field("conversation_id", &self.core.conversation_id())
66 .finish_non_exhaustive()
67 }
68}
69
70impl Session {
71 /// Assemble a session around an already-validated core (the restore
72 /// path — [`SessionCheckpoint::restore`] built the parts).
73 pub(super) fn from_core(core: Arc<SessionCore>) -> Session {
74 Session { core }
75 }
76
77 /// Build an idle session from a validated [`ConversationState`] plus the
78 /// harness's assembled runner and options.
79 ///
80 /// Construction never calls the model or a tool and never starts work; a
81 /// work is admitted only by `submit`. A state with an active turn (or, by
82 /// the aggregate's invariant, a leftover stamp) is rejected, and every
83 /// by-value input (`state`, `runner`, `options`, `config`) comes back in
84 /// [`SessionBuildRejection`].
85 ///
86 /// Every work runs through
87 /// [`TurnRunner::run_in_conversation`](crate::driver::TurnRunner::run_in_conversation),
88 /// which frames the lossless merged history plus the active turn;
89 /// `TurnRunOptions::frame` is deliberately inert on that entry (the driver
90 /// documents the same for its conversation entries), so per-work material
91 /// projection is not wired here.
92 ///
93 /// # Errors
94 ///
95 /// Returns [`SessionBuildRejection`] carrying
96 /// [`SessionError::InvalidInput`] when `state` is not idle.
97 // The rejection carries the whole `ConversationState` plus the assembled
98 // runner / options / config back by value, which is the point of the
99 // contract — boxing it would only move the inputs behind another
100 // allocation.
101 #[allow(clippy::result_large_err)]
102 pub fn new(
103 state: ConversationState,
104 runner: Arc<TurnRunner>,
105 options: TurnRunOptions,
106 config: SessionConfig,
107 ) -> Result<Session, SessionBuildRejection> {
108 if state.active_turn().is_some() || state.sealed_result().is_some() {
109 return Err(SessionBuildRejection {
110 error: SessionError::InvalidInput(
111 "session construction requires an idle state (empty active slot)".into(),
112 ),
113 state,
114 runner,
115 options,
116 config,
117 });
118 }
119 Ok(Session {
120 core: SessionCore::new(state, runner, options, config),
121 })
122 }
123
124 /// A cloneable operation entry into this session.
125 pub fn handle(&self) -> SessionHandle {
126 SessionHandle {
127 core: Arc::clone(&self.core),
128 }
129 }
130
131 /// Export the session's versioned save envelope — the complete idle
132 /// state or the complete paused outcome, every retained work, the
133 /// request-key replay tables, the TurnId allocation progress, and the
134 /// configuration description.
135 ///
136 /// Only a quiescent session exports: while a work is accepted / running
137 /// (a cancel in progress included) the export is
138 /// [`SessionError::Busy`], and a faulted session refuses — no complete
139 /// outcome exists to save. A closed session still exports, recording
140 /// `closed`, so restoring it yields a closed session that replays
141 /// accepted keys and accepts no new work. The envelope is a plain value:
142 /// whether and when to persist it stays with the harness, and
143 /// [`SessionCheckpoint::restore`] is the only way back in. Restore never
144 /// calls the model or a tool, and a restored pause still needs an
145 /// explicit resume under its remaining (not re-granted) deadline.
146 pub fn checkpoint(&self) -> Result<SessionCheckpoint, SessionError> {
147 self.core.checkpoint()
148 }
149
150 /// Shut the session down: stop accepting, then wait for the running work to
151 /// wind down.
152 ///
153 /// Stops acceptance and fires the active work's stop signal, then waits
154 /// until no work is running. The session keeps its retrievable results
155 /// and paused material readable through surviving [`SessionHandle`]s;
156 /// work submitted afterwards reports [`SessionError::Closed`].
157 pub async fn shutdown(&self) {
158 self.core.close();
159 self.core.quiesce().await;
160 }
161}
162
163impl Drop for Session {
164 /// Stops acceptance and sends the stop signal to the active work.
165 ///
166 /// The worker keeps its own `Arc<SessionCore>`, so no strong reference
167 /// cycle exists and the in-flight run still publishes its terminal state
168 /// after the owner is gone. Drop cannot await that wind-down, nor persist
169 /// anything — an explicit `shutdown` covers those.
170 fn drop(&mut self) {
171 self.core.close();
172 }
173}