causa_runtime/session/types.rs
1//! The session's public value vocabulary: work identity and state, the
2//! terminal-result shapes, the submit / observe / wait data carriers, the
3//! coordination config, and the error surface.
4//!
5//! Plain data plus the error enum — the coordination behaviour lives in
6//! [`Session`](crate::session::Session) /
7//! [`SessionHandle`](crate::session::SessionHandle) and the private
8//! `execution` core. The identifiers reuse the kernel's `ConversationId` /
9//! `TurnId`; the terminal result reuses the driver's `TurnResult` vocabulary.
10
11use std::time::Duration;
12
13use causa_kernel::{ContentPart, ConversationId, ModelOutput, TurnId, TurnSnapshot};
14
15use crate::driver::{Continuation, PausePoint, TurnInterruption};
16
17/// Identity of one accepted work: the conversation plus the turn id the
18/// session assigned at acceptance.
19///
20/// The pair of existing ids only — no separate agent/work id is introduced.
21/// An `observe` / `wait` for a ref that does not belong to the session is
22/// [`SessionError::NotFound`] (it is never routed to another conversation).
23#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
24pub struct WorkRef {
25 /// The conversation the work belongs to.
26 pub conversation_id: ConversationId,
27 /// The turn id assigned at acceptance; never reused by a later work.
28 pub turn_id: TurnId,
29}
30
31/// The session's management view of a work.
32///
33/// This is the runtime's coordination vocabulary, not a kernel state machine:
34/// the actual execution result is carried by [`FinishedKind`], which reuses
35/// the driver's existing `TurnResult` vocabulary.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum WorkState {
39 /// The session holds the work and its execution resources; the worker has
40 /// not yet begun advancing the runner. `Accepted` does **not** mean the
41 /// model has been called.
42 Accepted,
43 /// The runner is advancing the work. `submit` returns
44 /// [`SessionError::Busy`]; `observe` reads the published view only.
45 Running,
46 /// The complete paused outcome came back to the session. The conversation
47 /// is still busy; only an explicit `resume` continues it.
48 Paused,
49 /// Terminal: the work completed or was interrupted; see
50 /// [`WorkObservation::finished`]. The conversation accepts a next work.
51 Finished,
52 /// Terminal: the worker exited abnormally (panic or runner rejection), so
53 /// no complete outcome exists. The fault reason is retained (see
54 /// [`WorkObservation::fault`]); no recovery scene is fabricated and no
55 /// complete snapshot is invented, because the material may be
56 /// unrecoverable. The conversation refuses new work with
57 /// [`SessionError::Faulted`] until the harness handles it.
58 Faulted,
59}
60
61/// How a terminal work ended — the two terminal `TurnResult` shapes, kept as
62/// (or inside) the driver's own vocabulary rather than copied into new types.
63/// Serialized snake_case, matching the envelope's other enums (`WorkState`,
64/// `CancelOutcome`) rather than the driver's `TurnResult` casing — the
65/// envelope is its own wire shape.
66#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum FinishedKind {
69 /// The model ended the turn; the turn was committed into history.
70 Completed {
71 /// The turn's final model output.
72 final_output: ModelOutput,
73 },
74 /// The turn stopped early; the real aborted facts and the cause were
75 /// retained, and the turn stayed out of completed history.
76 Interrupted {
77 /// Why the turn was interrupted.
78 cause: TurnInterruption,
79 /// The real facts of the aborted turn — the [`TurnSnapshot`] taken
80 /// when the session aborted it. Carried publicly so an interrupted
81 /// work's material is verifiable without reading the
82 /// (completed-only) history, which deliberately excludes it.
83 facts: TurnSnapshot,
84 /// The paused [`Continuation`] retained when a `Paused` work was
85 /// cancelled; `None` for a runner-produced interruption. A cancelled
86 /// work is terminal and not resumable — the continuation is retained
87 /// for inspection.
88 continuation: Option<Continuation>,
89 },
90}
91
92/// What a [`cancel`](crate::session::SessionHandle::cancel) actually did to
93/// the work.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
95#[serde(rename_all = "snake_case")]
96pub enum CancelOutcome {
97 /// The work was still executing and its own control token was fired; the
98 /// terminal state is published when the runner returns (a completion that
99 /// wins the race keeps its result).
100 Signalled,
101 /// The work was paused and was terminated in place with no new external
102 /// call, retaining its committed facts, continuation, and cause.
103 Stopped,
104 /// The work was already `Finished`/`Faulted`; its result was not
105 /// rewritten.
106 AlreadyTerminal,
107}
108
109/// Acceptance receipt for a cancel — the work it targeted and what the cancel
110/// did to it.
111///
112/// Recovery mirror of [`WorkReceipt`]: retrying the same `request_key` resolves
113/// to this receipt without signalling or terminating anything again.
114#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
115pub struct CancelReceipt {
116 /// The work the cancel targeted.
117 pub work: WorkRef,
118 /// What the cancel actually did; see [`CancelOutcome`].
119 pub outcome: CancelOutcome,
120}
121
122/// One submission: the caller-scoped idempotency key plus the new task's
123/// content parts.
124///
125/// The parts commit as one fact block through
126/// [`TurnContext::append_parts`](causa_kernel::TurnContext::append_parts)
127/// (source label `"user"`), exactly as the execution stack expects. There is
128/// no model/tool hot-swapping and no per-submit materials.
129#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
130pub struct SubmitRequest {
131 /// Caller-scoped idempotency key. Repeating it with the same parts returns
132 /// the original [`WorkReceipt`]; reusing it with different parts is
133 /// [`SessionError::Conflict`].
134 pub request_key: String,
135 /// The new task's content; must be non-empty.
136 pub parts: Vec<ContentPart>,
137}
138
139/// Acceptance receipt for a submit — the assigned work and the revision it was
140/// accepted at.
141///
142/// A receipt means *accepted*, not *completed*: the worker may not have called
143/// the model yet. It exists so a lost receipt can be recovered by retrying the
144/// same `request_key`.
145#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
146pub struct WorkReceipt {
147 /// The work the session accepted.
148 pub work: WorkRef,
149 /// The work's revision at acceptance: `0` for a fresh submit; the paused
150 /// revision for a resume.
151 pub accepted_revision: u64,
152}
153
154/// A snapshot of one work's published state.
155///
156/// The revision increments on every observable state change, so a caller can
157/// tell a fresh snapshot from a stale one without holding the session lock.
158#[derive(Debug, Clone)]
159pub struct WorkObservation {
160 /// The observed work.
161 pub work: WorkRef,
162 /// Monotonic revision of this work's published state, starting at `0` for
163 /// `Accepted`.
164 pub revision: u64,
165 /// The current management state.
166 pub state: WorkState,
167 /// Why the work paused, including the hook-prepared calls awaiting a
168 /// decision. Present exactly when `state` is [`WorkState::Paused`].
169 ///
170 /// This is an owned copy from the same observation as `revision`;
171 /// changing it does not change the retained pause. Use its awaiting
172 /// calls to construct a [`crate::resume::ResumeRequest`] and pass this
173 /// revision to `resume`, which rejects decisions for an older pause.
174 pub paused: Option<PausePoint>,
175 /// The terminal result when `state` is [`WorkState::Finished`]; `None`
176 /// otherwise.
177 pub finished: Option<FinishedKind>,
178 /// The fault reason when `state` is [`WorkState::Faulted`]; `None`
179 /// otherwise.
180 pub fault: Option<String>,
181}
182
183/// Why a [`SessionHandle::wait`](crate::session::SessionHandle::wait) returned.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum WaitEnd {
186 /// The wait observed a returnable state (`Paused` / `Finished` /
187 /// `Faulted`).
188 ReachedState,
189 /// The wait's finite timeout elapsed first. The observed state is
190 /// unchanged by the timeout.
191 TimedOut,
192}
193
194/// The result of a finite wait: one consistent snapshot plus why the wait
195/// ended.
196///
197/// Observing `Paused` / `Finished` / `Faulted`, or timing out, is a
198/// *successful* observation — it never mutates the observed work's state.
199#[derive(Debug, Clone)]
200pub struct WaitOutcome {
201 /// The snapshot taken when the wait ended.
202 pub observation: WorkObservation,
203 /// Whether the wait reached a returnable state or timed out.
204 pub end: WaitEnd,
205}
206
207/// Session coordination configuration — not a mirror of `TurnRunOptions`.
208#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
209pub struct SessionConfig {
210 /// Maximum number of works the session retains. `submit` is rejected with
211 /// [`SessionError::CapacityExceeded`] at the ceiling; already-retained
212 /// works stay observable.
213 pub retained_work_capacity: usize,
214 /// Per-work deadline, measured from acceptance (pauses included). `None`
215 /// leaves the existing turn / tool limits as the only bounds. This is wired
216 /// into the work's `RunControl`; deadline enforcement itself stays with the
217 /// driver.
218 pub work_deadline: Option<Duration>,
219}
220
221impl Default for SessionConfig {
222 /// The offline reference defaults: retain 256 works, no work deadline.
223 fn default() -> Self {
224 Self {
225 retained_work_capacity: 256,
226 work_deadline: None,
227 }
228 }
229}
230
231/// Rejections of the session operations.
232///
233/// Request rejections (busy, input, conflict, capacity) are distinct from
234/// internal faults: they leave no accepted work behind, and they do not
235/// consume a request key.
236#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
237pub enum SessionError {
238 /// The referenced work does not belong to this session (unknown or
239 /// foreign).
240 #[error("no such work in this session: {0:?}")]
241 NotFound(WorkRef),
242 /// The session already holds an active work; no queue and no steering.
243 #[error("session is busy with an active work: {active:?}")]
244 Busy {
245 /// The active work the caller must observe, resume, or wait for.
246 active: WorkRef,
247 },
248 /// The request key was reused with different arguments.
249 #[error("request key reused with different arguments")]
250 Conflict,
251 /// The retained-work capacity is exhausted.
252 #[error("session retained-work capacity is exhausted")]
253 CapacityExceeded,
254 /// The submitted input is unusable (e.g. empty parts).
255 #[error("invalid submit input: {0}")]
256 InvalidInput(String),
257 /// The resume named a revision that is not the work's current paused
258 /// revision.
259 #[error("stale revision for work {work:?}: expected {expected}, actual {actual}")]
260 StaleRevision {
261 /// The work whose paused revision was named.
262 work: WorkRef,
263 /// The revision the caller believed was current.
264 expected: u64,
265 /// The work's actual current paused revision.
266 actual: u64,
267 },
268 /// The work is not in a resumable (`Paused`) state.
269 #[error("work is not paused and cannot be resumed: {0:?}")]
270 NotPaused(WorkRef),
271 /// The driver rejected the resume request; nothing executed and the paused
272 /// material is unchanged.
273 #[error("invalid resume request: {0}")]
274 InvalidResume(String),
275 /// The owner has been dropped (or the session closed); no new work is
276 /// accepted. Retained results remain readable, and a same-key replay of an
277 /// already-accepted request still returns its original receipt — only a
278 /// new request is rejected.
279 #[error("session is closed and accepts no new work")]
280 Closed,
281 /// The worker faulted; the session refuses new work until the harness
282 /// handles it.
283 #[error("session worker faulted: {reason}")]
284 Faulted {
285 /// The retained fault reason.
286 reason: String,
287 },
288 /// The checkpoint's configuration description does not match the freshly
289 /// assembled options: restore refuses rather than resuming under a
290 /// swapped model, tool surface, policy, or limits.
291 #[error("checkpoint configuration does not match the assembled options")]
292 ConfigMismatch,
293 /// The checkpoint is not usable by this runtime: an unsupported envelope
294 /// version, or internally inconsistent material (an unregistered paused
295 /// work, a receipt referencing an unknown work, an impossible state).
296 /// The rejection carries the original checkpoint back untouched.
297 #[error("invalid session checkpoint: {0}")]
298 InvalidCheckpoint(String),
299}