use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use causa_kernel::{ContentPart, ConversationId, ModelGateway, Tool};
use causa_runtime::{
ConversationState, ResumeRequest, Session, SessionBuildRejection, SessionCheckpoint,
SessionConfig, SessionError, SessionHandle, SubmitRequest, TurnRunOptions, TurnRunner,
WaitOutcome, WorkObservation, WorkReceipt, WorkRef, WorkState,
};
use super::{PausingInteraction, runner_with};
#[derive(Debug, Clone, Copy)]
pub struct CoordinatorConfig {
pub max_parallel: usize,
pub max_depth: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CreateOrigin {
Root,
Child {
parent: WorkRef,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct CreateRequest {
pub request_key: String,
pub conversation_id: ConversationId,
pub parts: Vec<ContentPart>,
pub origin: CreateOrigin,
pub selection: String,
}
impl CreateRequest {
pub fn root(
conversation_id: &str,
request_key: &str,
parts: Vec<ContentPart>,
selection: &str,
) -> Self {
Self {
request_key: request_key.into(),
conversation_id: ConversationId(conversation_id.into()),
parts,
origin: CreateOrigin::Root,
selection: selection.into(),
}
}
pub fn child(
conversation_id: &str,
request_key: &str,
parts: Vec<ContentPart>,
selection: &str,
parent: &WorkRef,
) -> Self {
Self {
request_key: request_key.into(),
conversation_id: ConversationId(conversation_id.into()),
parts,
origin: CreateOrigin::Child {
parent: parent.clone(),
},
selection: selection.into(),
}
}
}
pub struct SessionParts {
pub state: ConversationState,
pub runner: Arc<TurnRunner>,
pub options: TurnRunOptions,
pub config: SessionConfig,
}
#[derive(Debug)]
pub enum CoordinatorError {
Conflict,
Closed,
ConversationExists(ConversationId),
CapacityExceeded,
DepthExceeded {
depth: u32,
max: u32,
},
UnknownParent(WorkRef),
UnknownConversation(ConversationId),
ConversationMismatch {
expected: ConversationId,
actual: ConversationId,
},
Build(Box<SessionBuildRejection>),
Session(SessionError),
}
impl PartialEq for CoordinatorError {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Conflict, Self::Conflict)
| (Self::Closed, Self::Closed)
| (Self::CapacityExceeded, Self::CapacityExceeded) => true,
(
Self::DepthExceeded { depth: a, max: b },
Self::DepthExceeded { depth: c, max: d },
) => a == c && b == d,
(Self::UnknownParent(a), Self::UnknownParent(b)) => a == b,
(Self::UnknownConversation(a), Self::UnknownConversation(b)) => a == b,
(
Self::ConversationMismatch {
expected: a,
actual: b,
},
Self::ConversationMismatch {
expected: c,
actual: d,
},
) => a == c && b == d,
(Self::ConversationExists(a), Self::ConversationExists(b)) => a == b,
(Self::Build(a), Self::Build(b)) => a.error == b.error,
(Self::Session(a), Self::Session(b)) => a == b,
(Self::Conflict | Self::Closed | Self::CapacityExceeded, _)
| (Self::ConversationExists(_), _)
| (Self::DepthExceeded { .. }, _)
| (Self::UnknownParent(_), _)
| (Self::UnknownConversation(_), _)
| (Self::ConversationMismatch { .. }, _)
| (Self::Build(_), _)
| (Self::Session(_), _) => false,
}
}
}
struct Entry {
request: CreateRequest,
depth: u32,
work: WorkRef,
capacity_work: WorkRef,
receipt: WorkReceipt,
session: Arc<Session>,
handle: SessionHandle,
}
#[derive(Default)]
struct Table {
closed: bool,
by_conversation: HashMap<ConversationId, Entry>,
create_index: HashMap<String, ConversationId>,
}
pub struct Coordinator {
config: CoordinatorConfig,
factory: Box<dyn Fn(&CreateRequest) -> SessionParts + Send + Sync>,
table: Mutex<Table>,
}
impl Coordinator {
pub fn new(
config: CoordinatorConfig,
factory: impl Fn(&CreateRequest) -> SessionParts + Send + Sync + 'static,
) -> Self {
Self {
config,
factory: Box::new(factory),
table: Mutex::new(Table::default()),
}
}
pub fn create(&self, request: CreateRequest) -> Result<WorkReceipt, CoordinatorError> {
let mut table = self
.table
.lock()
.expect("the coordinator table is never poisoned");
if let Some(id) = table.create_index.get(&request.request_key).cloned() {
let entry = table
.by_conversation
.get(&id)
.expect("the create index always points at a registered session");
return if entry.request == request {
Ok(entry.receipt.clone())
} else {
Err(CoordinatorError::Conflict)
};
}
if table.closed {
return Err(CoordinatorError::Closed);
}
if table.by_conversation.contains_key(&request.conversation_id) {
return Err(CoordinatorError::ConversationExists(
request.conversation_id.clone(),
));
}
let depth = match &request.origin {
CreateOrigin::Root => 0,
CreateOrigin::Child { parent } => {
let parent_entry = table
.by_conversation
.get(&parent.conversation_id)
.ok_or_else(|| CoordinatorError::UnknownParent(parent.clone()))?;
if parent_entry.work != *parent {
return Err(CoordinatorError::UnknownParent(parent.clone()));
}
parent_entry.depth + 1
}
};
if depth > self.config.max_depth {
return Err(CoordinatorError::DepthExceeded {
depth,
max: self.config.max_depth,
});
}
if Self::in_use(&table) >= self.config.max_parallel {
return Err(CoordinatorError::CapacityExceeded);
}
let parts = (self.factory)(&request);
if parts.state.conversation_id() != &request.conversation_id {
return Err(CoordinatorError::ConversationMismatch {
expected: request.conversation_id.clone(),
actual: parts.state.conversation_id().clone(),
});
}
let session = Session::new(parts.state, parts.runner, parts.options, parts.config)
.map_err(|rejection| CoordinatorError::Build(Box::new(rejection)))?;
let handle = session.handle();
let receipt = handle
.submit(SubmitRequest {
request_key: request.request_key.clone(),
parts: request.parts.clone(),
})
.map_err(CoordinatorError::Session)?;
table
.create_index
.insert(request.request_key.clone(), request.conversation_id.clone());
table.by_conversation.insert(
request.conversation_id.clone(),
Entry {
depth,
work: receipt.work.clone(),
capacity_work: receipt.work.clone(),
receipt: receipt.clone(),
session: Arc::new(session),
handle,
request,
},
);
Ok(receipt)
}
pub fn handle(&self, id: &ConversationId) -> Result<SessionHandle, CoordinatorError> {
let table = self
.table
.lock()
.expect("the coordinator table is never poisoned");
table
.by_conversation
.get(id)
.map(|entry| entry.handle.clone())
.ok_or_else(|| CoordinatorError::UnknownConversation(id.clone()))
}
pub fn route(&self, work: &WorkRef) -> Result<SessionHandle, CoordinatorError> {
self.handle(&work.conversation_id)
}
pub fn observe(&self, work: &WorkRef) -> Result<WorkObservation, CoordinatorError> {
self.route(work)?
.observe(work)
.map_err(CoordinatorError::Session)
}
pub async fn wait(
&self,
work: &WorkRef,
timeout: Duration,
) -> Result<WaitOutcome, CoordinatorError> {
self.route(work)?
.wait(work, timeout)
.await
.map_err(CoordinatorError::Session)
}
pub fn resume(
&self,
work: &WorkRef,
expected_revision: u64,
request_key: &str,
request: ResumeRequest,
) -> Result<WorkReceipt, CoordinatorError> {
let mut table = self
.table
.lock()
.expect("the coordinator table is never poisoned");
let entry = table
.by_conversation
.get(&work.conversation_id)
.ok_or_else(|| CoordinatorError::UnknownConversation(work.conversation_id.clone()))?;
if table.closed {
return Err(CoordinatorError::Closed);
}
if let Some(receipt) = entry
.handle
.resume_receipt(work, expected_revision, request_key, &request)
.map_err(CoordinatorError::Session)?
{
return Ok(receipt);
}
match entry.handle.observe(work) {
Ok(observation) if observation.state == WorkState::Paused => {
if Self::in_use(&table) >= self.config.max_parallel {
return Err(CoordinatorError::CapacityExceeded);
}
}
Ok(_) => {}
Err(error) => return Err(CoordinatorError::Session(error)),
}
let receipt = entry
.handle
.resume(work, expected_revision, request_key.to_string(), request)
.map_err(CoordinatorError::Session)?;
table
.by_conversation
.get_mut(&work.conversation_id)
.expect("the held table lock preserves the entry")
.capacity_work = work.clone();
Ok(receipt)
}
pub fn checkpoint(&self, id: &ConversationId) -> Result<SessionCheckpoint, CoordinatorError> {
let session = {
let table = self
.table
.lock()
.expect("the coordinator table is never poisoned");
table
.by_conversation
.get(id)
.map(|entry| Arc::clone(&entry.session))
.ok_or_else(|| CoordinatorError::UnknownConversation(id.clone()))?
};
session.checkpoint().map_err(CoordinatorError::Session)
}
pub fn depth_of(&self, work: &WorkRef) -> Option<u32> {
let table = self
.table
.lock()
.expect("the coordinator table is never poisoned");
table
.by_conversation
.get(&work.conversation_id)
.filter(|entry| entry.work == *work)
.map(|entry| entry.depth)
}
pub fn session_count(&self) -> usize {
self.table
.lock()
.expect("the coordinator table is never poisoned")
.by_conversation
.len()
}
pub async fn shutdown(&self) {
let sessions: Vec<Arc<Session>> = {
let mut table = self
.table
.lock()
.expect("the coordinator table is never poisoned");
table.closed = true;
table
.by_conversation
.values()
.map(|entry| Arc::clone(&entry.session))
.collect()
};
for session in sessions {
session.shutdown().await;
}
}
fn in_use(table: &Table) -> usize {
table
.by_conversation
.values()
.filter(|entry| match entry.handle.observe(&entry.capacity_work) {
Ok(observation) => {
matches!(observation.state, WorkState::Accepted | WorkState::Running)
}
Err(_) => true,
})
.count()
}
}
pub struct Profile {
pub gateway: Arc<dyn ModelGateway>,
pub tools: Vec<Arc<dyn Tool>>,
pub pause_on_tool_use: bool,
pub config: SessionConfig,
}
impl Profile {
pub fn completing(gateway: Arc<dyn ModelGateway>) -> Self {
Self {
gateway,
tools: Vec::new(),
pause_on_tool_use: false,
config: SessionConfig::default(),
}
}
pub fn pausing(gateway: Arc<dyn ModelGateway>, tools: Vec<Arc<dyn Tool>>) -> Self {
Self {
gateway,
tools,
pause_on_tool_use: true,
config: SessionConfig::default(),
}
}
pub fn with_tools(mut self, tools: Vec<Arc<dyn Tool>>) -> Self {
self.tools = tools;
self
}
pub fn with_config(mut self, config: SessionConfig) -> Self {
self.config = config;
self
}
}
pub type Profiles = HashMap<&'static str, Profile>;
pub fn profile_factory(
profiles: Profiles,
) -> impl Fn(&CreateRequest) -> SessionParts + Send + Sync + 'static {
move |request: &CreateRequest| {
let profile = profiles
.get(request.selection.as_str())
.unwrap_or_else(|| panic!("no profile wired for selection {:?}", request.selection));
let options = if profile.pause_on_tool_use {
TurnRunOptions {
interaction: Arc::new(PausingInteraction),
..Default::default()
}
} else {
TurnRunOptions::default()
};
SessionParts {
state: ConversationState::new(request.conversation_id.clone()),
runner: Arc::new(runner_with(profile.gateway.clone(), profile.tools.clone())),
options,
config: profile.config.clone(),
}
}
}