use async_trait::async_trait;
use serde::{Deserialize, Deserializer, Serialize};
use causa_kernel::{
ContextError, ContextFrame, ConversationId, RoundId, TurnContext, TurnSnapshot, merged_frame,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct TurnSequence(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ConversationVersion(pub u64);
impl ConversationVersion {
pub fn next(self) -> Self {
Self(self.0 + 1)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SealedResult {
Completed,
Interrupted,
Paused,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoryEntry {
pub sequence: TurnSequence,
pub snapshot: TurnSnapshot,
}
impl HistoryEntry {
pub fn snapshot(&self) -> &TurnSnapshot {
&self.snapshot
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ConversationError {
#[error("a turn is already active in this conversation")]
TurnAlreadyActive,
#[error("active turn is already sealed; abort it before starting a new one")]
TurnAlreadySealed,
#[error("no active turn in this conversation")]
NoActiveTurn,
#[error("unknown turn: {0:?}")]
UnknownTurn(causa_kernel::TurnId),
#[error("duplicate turn id: {0:?}")]
DuplicateTurnId(causa_kernel::TurnId),
#[error("turn not completed, cannot commit: {0:?}")]
TurnNotCompleted(causa_kernel::TurnId),
#[error("turn is paused, cannot commit until resumed: {0:?}")]
TurnPaused(causa_kernel::TurnId),
#[error("turn is not paused, cannot resume: {0:?}")]
NotPaused(causa_kernel::TurnId),
#[error("invalid conversation state: {0}")]
InvalidSequence(String),
}
#[derive(Clone, Serialize)]
pub struct ConversationState {
conversation_id: ConversationId,
history: Vec<HistoryEntry>,
#[serde(with = "causa_kernel::option_turn_context_as_snapshot")]
active_turn: Option<TurnContext>,
sealed_result: Option<SealedResult>,
version: ConversationVersion,
}
#[derive(Deserialize)]
struct ConversationStateFields {
conversation_id: ConversationId,
history: Vec<HistoryEntry>,
#[serde(with = "causa_kernel::option_turn_context_as_snapshot")]
active_turn: Option<TurnContext>,
sealed_result: Option<SealedResult>,
version: ConversationVersion,
}
impl<'de> Deserialize<'de> for ConversationState {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let fields = ConversationStateFields::deserialize(deserializer)?;
if let Some(active) = &fields.active_turn
&& fields
.history
.iter()
.any(|entry| entry.snapshot.turn_id == active.turn_id())
{
return Err(serde::de::Error::custom(format!(
"active turn {:?} duplicates a committed history id",
active.turn_id()
)));
}
validate_history(&fields.history).map_err(serde::de::Error::custom)?;
Ok(Self {
conversation_id: fields.conversation_id,
history: fields.history,
active_turn: fields.active_turn,
sealed_result: fields.sealed_result,
version: fields.version,
})
}
}
fn validate_history(entries: &[HistoryEntry]) -> Result<(), ConversationError> {
let mut last_seq = TurnSequence(0);
let mut seen_ids = std::collections::HashSet::new();
for entry in entries {
if entry.sequence < last_seq {
return Err(ConversationError::InvalidSequence(format!(
"turn_sequence not strictly increasing: {:?}",
entry.sequence
)));
}
if !seen_ids.insert(entry.snapshot.turn_id.clone()) {
return Err(ConversationError::InvalidSequence(format!(
"duplicate turn id in history: {:?}",
entry.snapshot.turn_id
)));
}
TurnContext::validate_blocks(&entry.snapshot.turn_id, entry.snapshot.blocks.as_slice())
.map_err(|e: ContextError| ConversationError::InvalidSequence(e.to_string()))?;
last_seq = TurnSequence(entry.sequence.0 + 1);
}
Ok(())
}
impl std::fmt::Debug for ConversationState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConversationState")
.field("conversation_id", &self.conversation_id)
.field("version", &self.version)
.field("history_len", &self.history.len())
.field("next_turn_sequence", &self.next_turn_sequence())
.field("active_turn", &self.active_turn)
.field("sealed_result", &self.sealed_result)
.finish()
}
}
impl ConversationState {
pub fn new(conversation_id: ConversationId) -> Self {
Self {
conversation_id,
history: Vec::new(),
active_turn: None,
sealed_result: None,
version: ConversationVersion(0),
}
}
pub fn next_turn_sequence(&self) -> TurnSequence {
self.history
.last()
.map(|e| TurnSequence(e.sequence.0 + 1))
.unwrap_or(TurnSequence(0))
}
pub fn begin_turn(
&mut self,
turn_id: causa_kernel::TurnId,
) -> Result<&mut TurnContext, ConversationError> {
self.assert_stamp_invariant();
if let Some(active) = &self.active_turn {
return Err(if active.is_sealed() {
ConversationError::TurnAlreadySealed
} else {
ConversationError::TurnAlreadyActive
});
}
if self.history.iter().any(|e| e.snapshot.turn_id == turn_id) {
return Err(ConversationError::DuplicateTurnId(turn_id));
}
self.active_turn = Some(TurnContext::new(turn_id));
self.version = self.version.next();
Ok(self.active_turn.as_mut().expect("just inserted"))
}
pub fn seal_turn(
&mut self,
turn_id: causa_kernel::TurnId,
result: SealedResult,
) -> Result<(), ConversationError> {
self.assert_stamp_invariant();
match self.active_turn.as_mut() {
Some(active) if active.turn_id() == turn_id => {
if result != SealedResult::Paused {
active.seal();
}
self.sealed_result = Some(result);
Ok(())
}
_ => Err(ConversationError::UnknownTurn(turn_id)),
}
}
pub fn active_turn(&self) -> Option<&TurnContext> {
self.active_turn.as_ref()
}
pub fn sealed_result(&self) -> Option<SealedResult> {
self.sealed_result
}
pub fn active_turn_mut(&mut self) -> Option<&mut TurnContext> {
self.active_turn.as_mut()
}
pub fn commit(
&mut self,
turn_id: causa_kernel::TurnId,
) -> Result<HistoryEntry, ConversationError> {
self.assert_stamp_invariant();
match self.active_turn.as_ref() {
Some(active) if active.turn_id() == turn_id => {}
_ => return Err(ConversationError::UnknownTurn(turn_id)),
}
if self.sealed_result == Some(SealedResult::Paused) {
return Err(ConversationError::TurnPaused(turn_id));
}
let active = self.active_turn.as_ref().expect("matched above");
if !active.is_sealed() || self.sealed_result != Some(SealedResult::Completed) {
return Err(ConversationError::TurnNotCompleted(turn_id));
}
let active = self.active_turn.take().expect("matched above");
self.sealed_result = None;
let sequence = self.next_turn_sequence();
let entry = HistoryEntry {
sequence,
snapshot: active.snapshot(),
};
self.history.push(entry.clone());
self.version = self.version.next();
Ok(entry)
}
pub fn abort_turn(
&mut self,
turn_id: causa_kernel::TurnId,
) -> Result<TurnContext, ConversationError> {
self.assert_stamp_invariant();
match self.active_turn.as_ref() {
Some(active) if active.turn_id() == turn_id => {}
_ => return Err(ConversationError::UnknownTurn(turn_id)),
}
let active = self.active_turn.take().expect("matched above");
self.sealed_result = None;
self.version = self.version.next();
Ok(active)
}
pub fn frame(&self, round_id: RoundId) -> Result<ContextFrame, ConversationError> {
let active = match &self.active_turn {
Some(active) => active,
None => return Err(ConversationError::NoActiveTurn),
};
let history: Vec<TurnSnapshot> = self.history.iter().map(|e| e.snapshot.clone()).collect();
Ok(merged_frame(
&self.conversation_id,
&history,
active,
round_id,
))
}
pub fn runner_parts(
&mut self,
) -> (&ConversationId, Vec<TurnSnapshot>, Option<&mut TurnContext>) {
(
&self.conversation_id,
self.history.iter().map(|e| e.snapshot.clone()).collect(),
self.active_turn.as_mut(),
)
}
pub fn from_history(
conversation_id: ConversationId,
entries: Vec<HistoryEntry>,
) -> Result<Self, ConversationError> {
validate_history(&entries)?;
Ok(Self {
conversation_id,
history: entries,
active_turn: None,
sealed_result: None,
version: ConversationVersion(0),
})
}
pub fn history(&self) -> &[HistoryEntry] {
&self.history
}
pub fn history_len(&self) -> usize {
self.history.len()
}
pub fn version(&self) -> ConversationVersion {
self.version
}
pub fn conversation_id(&self) -> &ConversationId {
&self.conversation_id
}
fn assert_stamp_invariant(&self) {
debug_assert!(match self.sealed_result {
None => true,
Some(SealedResult::Paused) => {
self.active_turn.as_ref().is_some_and(|t| !t.is_sealed())
}
Some(_) => self.active_turn.as_ref().is_some_and(|t| t.is_sealed()),
});
}
}
#[async_trait]
pub trait ConversationStore: Send + Sync {
async fn save_entry(
&self,
conversation_id: &ConversationId,
entry: &HistoryEntry,
) -> Result<(), ConversationStoreError>;
async fn load_entries(
&self,
conversation_id: &ConversationId,
) -> Result<Vec<HistoryEntry>, ConversationStoreError>;
}
#[derive(Debug, thiserror::Error)]
pub enum ConversationStoreError {
#[error("conversation not found: {0}")]
NotFound(String),
#[error("io error: {0}")]
Io(String),
#[error("serialization error: {0}")]
Serialization(String),
#[error("corrupted data: {0}")]
Corrupted(String),
}