use adk_core::{
AdkIdentity, Agent, AppName, Artifacts, CallbackContext, Content, Event, ExecutionIdentity,
InvocationContext as InvocationContextTrait, InvocationId, Memory, Part, ReadonlyContext,
RequestContext, RunConfig, SecretService, SessionId, UserId,
};
use adk_session::Session as AdkSession;
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, PoisonError, RwLock, atomic::AtomicBool};
pub struct MutableSession {
id: String,
app_name: String,
user_id: String,
state: Arc<RwLock<HashMap<String, serde_json::Value>>>,
events: Arc<RwLock<Vec<Event>>>,
}
impl MutableSession {
pub fn new(mut session: Arc<dyn AdkSession>) -> Self {
let initial_events = match Arc::get_mut(&mut session) {
Some(owned) => owned.take_events(),
None => session.events().all(),
};
Self {
id: session.id().to_string(),
app_name: session.app_name().to_string(),
user_id: session.user_id().to_string(),
state: Arc::new(RwLock::new(session.state().all())),
events: Arc::new(RwLock::new(initial_events)),
}
}
pub fn apply_state_delta(&self, delta: &HashMap<String, serde_json::Value>) {
if delta.is_empty() {
return;
}
let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
for (key, value) in delta {
state.insert(key.clone(), value.clone());
}
}
pub fn append_event(&self, event: Event) {
let mut events = self.events.write().unwrap_or_else(PoisonError::into_inner);
events.push(event);
}
pub fn events_snapshot(&self) -> Vec<Event> {
let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
events.clone()
}
pub fn replace_events(&self, new_events: Vec<Event>) {
let mut events = self.events.write().unwrap_or_else(PoisonError::into_inner);
*events = new_events;
}
pub(crate) fn read_events<R>(&self, read: impl FnOnce(&[Event]) -> R) -> R {
let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
read(&events)
}
pub fn events_len(&self) -> usize {
let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
events.len()
}
pub fn conversation_history_for_agent_impl(
&self,
agent_name: Option<&str>,
branch: &str,
) -> Vec<adk_core::Content> {
match agent_name {
Some(name) => self.project_history(Some(name), OtherAgents::Exclude, branch),
None => self.project_history(None, OtherAgents::AsOwnTurns, branch),
}
}
fn project_history(
&self,
agent_name: Option<&str>,
others: OtherAgents,
branch: &str,
) -> Vec<adk_core::Content> {
let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
let mut history = Vec::new();
let call_ids = adk_core::history::function_call_ids(&events);
let mut compaction_boundary = None;
let mut compacted_at = None;
for event in events.iter().rev() {
if let Some(ref compaction) = event.actions.compaction {
let mut content = compaction.compacted_content.clone();
let origin = adk_core::intra_compaction::is_native_compaction(&content)
.then(|| {
adk_core::history::ProviderOrigin::of_response(
event.llm_response.provider_metadata.as_ref(),
)
})
.flatten();
match &origin {
Some(origin) => adk_core::history::mark_origin(&mut content, Some(origin)),
None => adk_core::history::strip_native(&mut content),
}
let keeps_thinking = origin.is_some()
&& event
.llm_response
.provider_metadata
.as_ref()
.and_then(|metadata| {
metadata.get(crate::intra_compaction::KEEPS_THINKING_KEY)
})
.and_then(serde_json::Value::as_bool)
== Some(true);
if !keeps_thinking {
compacted_at = Some(event.timestamp);
}
history.push(HistoryContent { content, invocation_id: None });
compaction_boundary = Some(compaction.end_timestamp);
break;
}
}
for event in events.iter() {
if event.actions.compaction.is_some() {
continue;
}
if event.llm_response.partial {
continue;
}
if event.actions.tool_confirmation.is_some() {
continue;
}
if let Some(boundary) = compaction_boundary
&& event.timestamp <= boundary
{
continue;
}
if !adk_core::event_belongs_to_branch(branch, &event.branch) {
continue;
}
if adk_core::history::is_tool_branch_event(branch, &event.branch, &call_ids) {
continue;
}
let Some(content) = &event.llm_response.content else {
continue;
};
if adk_core::history::is_system_notice_event(event) {
history.push(HistoryContent {
content: content.clone(),
invocation_id: Some(event.invocation_id.clone()),
});
continue;
}
let other_agent =
agent_name.is_some_and(|name| event.author != "user" && event.author != name);
let mapped_content = match others {
OtherAgents::Exclude if other_agent => continue,
OtherAgents::AsContext if other_agent => {
match adk_core::history::other_agent_context(&event.author, content) {
Some(context) => context,
None => continue,
}
}
OtherAgents::Exclude | OtherAgents::AsContext | OtherAgents::AsOwnTurns => {
let mut mapped_content = content.clone();
mapped_content.role = match (event.author.as_str(), content.role.as_str()) {
("user", _) => "user",
(_, "function" | "tool") => content.role.as_str(),
_ => "model",
}
.to_string();
if compacted_at.is_some_and(|at| event.timestamp < at) {
mapped_content.parts.retain(|part| !matches!(part, Part::Thinking { .. }));
if mapped_content.parts.is_empty() {
continue;
}
}
if mapped_content.role == "model" {
adk_core::history::mark_origin(
&mut mapped_content,
adk_core::history::ProviderOrigin::of_response(
event.llm_response.provider_metadata.as_ref(),
)
.as_ref(),
);
} else {
adk_core::history::strip_native(&mut mapped_content);
}
mapped_content
}
};
history.push(HistoryContent {
content: mapped_content,
invocation_id: Some(event.invocation_id.clone()),
});
}
let long_running = long_running_call_ids(&events);
close_interrupted_tool_calls(answer_resumed_calls(history, &long_running))
}
}
fn long_running_call_ids(events: &[Event]) -> std::collections::HashSet<String> {
let mut ids = std::collections::HashSet::new();
for event in events.iter().filter(|event| !event.long_running_tool_ids.is_empty()) {
for part in event.llm_response.content.iter().flat_map(|content| &content.parts) {
if let Part::FunctionCall { name, id: Some(id), .. } = part
&& event.long_running_tool_ids.iter().any(|listed| listed == id || listed == name)
{
ids.insert(id.clone());
}
}
}
ids
}
#[derive(Clone, Copy)]
enum OtherAgents {
Exclude,
AsContext,
AsOwnTurns,
}
struct HistoryContent {
content: Content,
invocation_id: Option<String>,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct PartLocation {
content: usize,
part: usize,
}
struct PendingFunctionCall {
location: PartLocation,
id: Option<String>,
name: String,
user_turn: usize,
invocation_id: Option<String>,
}
struct HeldAnswer {
response: PartLocation,
id: Option<String>,
name: String,
}
fn close_interrupted_tool_calls(history: Vec<HistoryContent>) -> Vec<Content> {
let mut pending = Vec::<PendingFunctionCall>::new();
let mut removed_parts = std::collections::HashSet::<PartLocation>::new();
let mut responses_after = HashMap::<usize, Vec<(usize, String, PartLocation, Part)>>::new();
let mut held_answers = Vec::<HeldAnswer>::new();
let mut superseded = HashMap::<PartLocation, Part>::new();
let mut user_turn = 0;
for (content_index, history_content) in history.iter().enumerate() {
let content = &history_content.content;
for (part_index, part) in content.parts.iter().enumerate() {
match part {
Part::FunctionCall { name, id, .. } => {
pending.push(PendingFunctionCall {
location: PartLocation { content: content_index, part: part_index },
id: id.clone(),
name: name.clone(),
user_turn,
invocation_id: history_content.invocation_id.clone(),
});
}
Part::FunctionResponse { function_response, id, .. } => {
let matching_index = match id.as_deref() {
Some(response_id) => {
pending.iter().position(|call| call.id.as_deref() == Some(response_id))
}
None => pending
.iter()
.position(|call| {
call.name == function_response.name
&& history_content.invocation_id.is_some()
&& call.invocation_id.as_deref()
== history_content.invocation_id.as_deref()
})
.or_else(|| {
let mut same_name =
pending.iter().enumerate().filter(|(_, call)| {
call.name == function_response.name
&& (call.invocation_id.is_none()
|| history_content.invocation_id.is_none())
});
let first = same_name.next().map(|(index, _)| index);
match (first, same_name.next()) {
(Some(index), None) => Some(index),
_ => None,
}
}),
};
let location = PartLocation { content: content_index, part: part_index };
if let Some(index) = matching_index {
let call = pending.remove(index);
if adk_core::is_confirmation_pending(&function_response.response) {
held_answers.push(HeldAnswer {
response: location,
id: id.clone(),
name: function_response.name.clone(),
});
}
if call.user_turn < user_turn {
removed_parts.insert(location);
let mut insertion_index = call.location.content;
while let Some(next) = history.get(insertion_index + 1) {
if next.content.parts.is_empty()
|| !next
.content
.parts
.iter()
.all(|part| matches!(part, Part::FunctionResponse { .. }))
{
break;
}
insertion_index += 1;
}
responses_after.entry(insertion_index).or_default().push((
call.location.part,
content.role.clone(),
location,
part.clone(),
));
}
} else if let Some(index) = held_answers.iter().rposition(|held| match id {
Some(response_id) => held.id.as_deref() == Some(response_id.as_str()),
None => held.id.is_none() && held.name == function_response.name,
}) {
removed_parts.insert(location);
superseded.insert(held_answers[index].response, part.clone());
if !adk_core::is_confirmation_pending(&function_response.response) {
held_answers.remove(index);
}
} else {
tracing::debug!(
function.name = %function_response.name,
"dropping a function response that answers no retained call"
);
removed_parts.insert(location);
}
}
_ => {}
}
}
if content.role == "user"
&& content.parts.iter().any(|part| !matches!(part, Part::FunctionResponse { .. }))
{
user_turn += 1;
}
}
for call in pending {
if call.user_turn == user_turn {
continue;
}
removed_parts.insert(call.location);
}
let mut normalized = Vec::with_capacity(history.len());
for (content_index, history_content) in history.into_iter().enumerate() {
let mut content = history_content.content;
content.parts = content
.parts
.into_iter()
.enumerate()
.filter_map(|(part_index, part)| {
let location = PartLocation { content: content_index, part: part_index };
if removed_parts.contains(&location) {
return None;
}
Some(superseded.remove(&location).unwrap_or(part))
})
.collect();
if !content.parts.is_empty() {
normalized.push(content);
}
if let Some(mut responses) = responses_after.remove(&content_index) {
responses.sort_by_key(|(call_part, _, _, _)| *call_part);
normalized.extend(responses.into_iter().map(|(_, role, location, response)| {
let response = superseded.remove(&location).unwrap_or(response);
Content { role, parts: vec![response] }
}));
}
}
normalized
}
fn answer_resumed_calls(
mut history: Vec<HistoryContent>,
long_running: &std::collections::HashSet<String>,
) -> Vec<HistoryContent> {
let Some(newest) = history.len().checked_sub(1) else { return history };
let mut answered = std::collections::HashSet::new();
for part in &history[newest].content.parts {
match part {
Part::FunctionResponse { id: Some(id), .. } => {
answered.insert(id.clone());
}
_ => return history,
}
}
if answered.is_empty() || !answered.iter().all(|id| long_running.contains(id)) {
return history;
}
let Some(call_turn) = history[..newest].iter().rposition(|entry| {
entry.content.parts.iter().any(
|part| matches!(part, Part::FunctionCall { id: Some(id), .. } if answered.contains(id)),
)
}) else {
return history;
};
let call_ids: Vec<String> = history[call_turn]
.content
.parts
.iter()
.filter_map(|part| match part {
Part::FunctionCall { id: Some(id), .. } => Some(id.clone()),
_ => None,
})
.collect();
if !answered.iter().all(|id| call_ids.contains(id)) {
return history;
}
let moved_on = history[call_turn + 1..newest]
.iter()
.flat_map(|entry| &entry.content.parts)
.any(|part| match part {
Part::FunctionResponse { id: Some(id), .. } => {
answered.contains(id) || !call_ids.contains(id)
}
_ => true,
});
if !moved_on {
return history;
}
let mut responses: Vec<Option<Part>> = vec![None; call_ids.len()];
for part in history[call_turn + 1..].iter().flat_map(|entry| &entry.content.parts) {
if let Part::FunctionResponse { id: Some(id), .. } = part
&& let Some(position) = call_ids.iter().position(|call_id| call_id == id)
{
responses[position] = Some(part.clone());
}
}
let answer = history.swap_remove(newest);
history.truncate(call_turn + 1);
history.push(HistoryContent {
content: Content {
role: "function".to_string(),
parts: responses.into_iter().flatten().collect(),
},
invocation_id: answer.invocation_id,
});
history
}
impl adk_core::Session for MutableSession {
fn id(&self) -> &str {
&self.id
}
fn app_name(&self) -> &str {
&self.app_name
}
fn user_id(&self) -> &str {
&self.user_id
}
fn state(&self) -> &dyn adk_core::State {
self
}
fn conversation_history(&self) -> Vec<adk_core::Content> {
self.conversation_history_for_agent_impl(None, "")
}
fn conversation_history_for_agent(&self, agent_name: &str) -> Vec<adk_core::Content> {
self.conversation_history_for_agent_impl(Some(agent_name), "")
}
fn conversation_history_scoped(
&self,
agent_name: Option<&str>,
branch: &str,
) -> Vec<adk_core::Content> {
self.conversation_history_for_agent_impl(agent_name, branch)
}
fn conversation_history_with_context(
&self,
agent_name: &str,
branch: &str,
) -> Vec<adk_core::Content> {
self.project_history(Some(agent_name), OtherAgents::AsContext, branch)
}
fn records_invocation_events(&self) -> bool {
true
}
fn held_tool_calls(&self, agent_name: &str, branch: &str) -> Vec<adk_core::HeldToolCall> {
let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
adk_core::held_tool_calls(&events, agent_name, branch)
}
fn workflow_resume_positions(
&self,
workflow: &str,
branch: &str,
) -> Vec<adk_core::WorkflowPosition> {
let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
adk_core::workflow_resume_positions(&events, workflow, branch)
}
}
impl adk_core::State for MutableSession {
fn get(&self, key: &str) -> Option<serde_json::Value> {
let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
state.get(key).cloned()
}
fn set(&mut self, key: String, value: serde_json::Value) {
if let Err(msg) = adk_core::validate_state_key(&key) {
tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
return;
}
let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
state.insert(key, value);
}
fn all(&self) -> HashMap<String, serde_json::Value> {
let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
state.clone()
}
}
pub struct InvocationContext {
identity: ExecutionIdentity,
agent: Arc<dyn Agent>,
user_content: Content,
artifacts: Option<Arc<dyn Artifacts>>,
memory: Option<Arc<dyn Memory>>,
run_config: RunConfig,
ended: Arc<AtomicBool>,
session: Arc<MutableSession>,
request_context: Option<RequestContext>,
shared_state: Option<Arc<adk_core::SharedState>>,
secret_service: Option<Arc<dyn SecretService>>,
cancellation_token: Option<tokio_util::sync::CancellationToken>,
orchestration_root_invocation_id: String,
steering_inbox: Option<adk_core::SteeringInbox>,
}
impl InvocationContext {
pub fn new_typed(
invocation_id: String,
agent: Arc<dyn Agent>,
user_id: UserId,
app_name: AppName,
session_id: SessionId,
user_content: Content,
session: Arc<dyn AdkSession>,
) -> adk_core::Result<Self> {
let orchestration_root_invocation_id = invocation_id.clone();
let identity = ExecutionIdentity {
adk: AdkIdentity { app_name, user_id, session_id },
invocation_id: InvocationId::try_from(invocation_id)?,
branch: String::new(),
agent_name: agent.name().to_string(),
};
Ok(Self {
identity,
agent,
user_content,
artifacts: None,
memory: None,
run_config: RunConfig::default(),
ended: Arc::new(AtomicBool::new(false)),
session: Arc::new(MutableSession::new(session)),
request_context: None,
shared_state: None,
secret_service: None,
cancellation_token: None,
orchestration_root_invocation_id,
steering_inbox: None,
})
}
pub fn new(
invocation_id: String,
agent: Arc<dyn Agent>,
user_id: String,
app_name: String,
session_id: String,
user_content: Content,
session: Arc<dyn AdkSession>,
) -> adk_core::Result<Self> {
Self::new_typed(
invocation_id,
agent,
UserId::try_from(user_id)?,
AppName::try_from(app_name)?,
SessionId::try_from(session_id)?,
user_content,
session,
)
}
pub fn with_mutable_session_typed(
invocation_id: String,
agent: Arc<dyn Agent>,
user_id: UserId,
app_name: AppName,
session_id: SessionId,
user_content: Content,
session: Arc<MutableSession>,
) -> adk_core::Result<Self> {
let orchestration_root_invocation_id = invocation_id.clone();
let identity = ExecutionIdentity {
adk: AdkIdentity { app_name, user_id, session_id },
invocation_id: InvocationId::try_from(invocation_id)?,
branch: String::new(),
agent_name: agent.name().to_string(),
};
Ok(Self {
identity,
agent,
user_content,
artifacts: None,
memory: None,
run_config: RunConfig::default(),
ended: Arc::new(AtomicBool::new(false)),
session,
request_context: None,
shared_state: None,
secret_service: None,
cancellation_token: None,
orchestration_root_invocation_id,
steering_inbox: None,
})
}
pub fn with_mutable_session(
invocation_id: String,
agent: Arc<dyn Agent>,
user_id: String,
app_name: String,
session_id: String,
user_content: Content,
session: Arc<MutableSession>,
) -> adk_core::Result<Self> {
Self::with_mutable_session_typed(
invocation_id,
agent,
UserId::try_from(user_id)?,
AppName::try_from(app_name)?,
SessionId::try_from(session_id)?,
user_content,
session,
)
}
pub fn with_branch(mut self, branch: String) -> Self {
self.identity.branch = branch;
self
}
pub fn with_artifacts(mut self, artifacts: Arc<dyn Artifacts>) -> Self {
self.artifacts = Some(artifacts);
self
}
pub fn with_memory(mut self, memory: Arc<dyn Memory>) -> Self {
self.memory = Some(memory);
self
}
pub fn with_run_config(mut self, config: RunConfig) -> Self {
self.run_config = config;
self
}
pub fn with_request_context(mut self, ctx: RequestContext) -> Self {
self.request_context = Some(ctx);
self
}
pub fn with_shared_state(mut self, shared: Arc<adk_core::SharedState>) -> Self {
self.shared_state = Some(shared);
self
}
pub fn with_secret_service(mut self, service: Arc<dyn SecretService>) -> Self {
self.secret_service = Some(service);
self
}
pub fn with_cancellation_token(mut self, token: tokio_util::sync::CancellationToken) -> Self {
self.cancellation_token = Some(token);
self
}
pub fn with_orchestration_root_invocation_id(mut self, invocation_id: String) -> Self {
self.orchestration_root_invocation_id = invocation_id;
self
}
pub fn with_steering_inbox(mut self, inbox: adk_core::SteeringInbox) -> Self {
self.steering_inbox = Some(inbox);
self
}
pub fn mutable_session(&self) -> &Arc<MutableSession> {
&self.session
}
pub(crate) fn with_user_content(&self, content: Content) -> Self {
Self {
identity: self.identity.clone(),
agent: self.agent.clone(),
user_content: content,
artifacts: self.artifacts.clone(),
memory: self.memory.clone(),
run_config: self.run_config.clone(),
ended: self.ended.clone(),
session: self.session.clone(),
request_context: self.request_context.clone(),
shared_state: self.shared_state.clone(),
secret_service: self.secret_service.clone(),
cancellation_token: self.cancellation_token.clone(),
orchestration_root_invocation_id: self.orchestration_root_invocation_id.clone(),
steering_inbox: self.steering_inbox.clone(),
}
}
}
#[async_trait]
impl ReadonlyContext for InvocationContext {
fn invocation_id(&self) -> &str {
self.identity.invocation_id.as_ref()
}
fn agent_name(&self) -> &str {
self.agent.name()
}
fn user_id(&self) -> &str {
self.request_context.as_ref().map_or(self.identity.adk.user_id.as_ref(), |rc| &rc.user_id)
}
fn app_name(&self) -> &str {
self.identity.adk.app_name.as_ref()
}
fn session_id(&self) -> &str {
self.identity.adk.session_id.as_ref()
}
fn branch(&self) -> &str {
&self.identity.branch
}
fn user_content(&self) -> &Content {
&self.user_content
}
fn acting_context(&self) -> adk_core::ActingContext {
self.run_config.acting_context_for(self.app_name(), self.agent_name(), self.user_id())
}
fn is_authenticated(&self) -> bool {
self.request_context.is_some()
&& self.run_config.acting.subject_kind != adk_core::SubjectKind::Visitor
}
fn state(&self) -> Option<&dyn adk_core::State> {
Some(adk_core::Session::state(self.session.as_ref()))
}
}
#[async_trait]
impl CallbackContext for InvocationContext {
fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
self.artifacts.clone()
}
fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
self.shared_state.clone()
}
}
#[async_trait]
impl InvocationContextTrait for InvocationContext {
fn agent(&self) -> Arc<dyn Agent> {
self.agent.clone()
}
fn memory(&self) -> Option<Arc<dyn Memory>> {
self.memory.clone()
}
fn session(&self) -> &dyn adk_core::Session {
self.session.as_ref()
}
fn run_config(&self) -> &RunConfig {
&self.run_config
}
fn end_invocation(&self) {
self.ended.store(true, std::sync::atomic::Ordering::SeqCst);
}
fn ended(&self) -> bool {
self.ended.load(std::sync::atomic::Ordering::SeqCst)
}
fn is_cancelled(&self) -> bool {
self.cancellation_token
.as_ref()
.is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
}
fn user_scopes(&self) -> Vec<String> {
self.request_context.as_ref().map_or_else(Vec::new, |rc| rc.scopes.clone())
}
fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
self.run_config
.request_metadata
.iter()
.chain(self.request_context.iter().flat_map(|rc| rc.metadata.iter()))
.map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
.collect()
}
fn orchestration_root_invocation_id(&self) -> &str {
&self.orchestration_root_invocation_id
}
fn steering_inbox(&self) -> Option<adk_core::SteeringInbox> {
self.steering_inbox.clone()
}
async fn get_secret(&self, name: &str) -> adk_core::Result<Option<String>> {
let request = adk_core::SecretRequest::new(name)
.with_identity(self.app_name(), self.user_id(), self.session_id())
.with_invocation_id(self.invocation_id());
self.get_secret_for(&request).await
}
async fn get_secret_for(
&self,
request: &adk_core::SecretRequest,
) -> adk_core::Result<Option<String>> {
match &self.secret_service {
Some(service) => service.get_secret_for(request).await.map(Some),
None => Ok(None),
}
}
}
#[cfg(test)]
mod poisoned_lock_tests {
use super::*;
use adk_session::{CreateRequest, InMemorySessionService, SessionService};
#[tokio::test]
async fn a_poisoned_lock_keeps_the_history_and_state() {
let service = InMemorySessionService::new();
let stored = service
.create(CreateRequest {
app_name: "app".to_string(),
user_id: "user".to_string(),
session_id: Some("session".to_string()),
state: HashMap::new(),
})
.await
.unwrap();
let session = Arc::new(MutableSession::new(Arc::from(stored)));
let mut event = Event::new("inv-1");
event.author = "user".to_string();
event.llm_response.content = Some(Content::new("user").with_text("hello"));
session.append_event(event);
session.apply_state_delta(&HashMap::from([(
"topic".to_string(),
serde_json::json!("billing"),
)]));
let holder = Arc::clone(&session);
let _ = std::thread::spawn(move || {
let _events = holder.events.write().unwrap();
let _state = holder.state.write().unwrap();
panic!("poison the session locks");
})
.join();
assert!(session.events.is_poisoned() && session.state.is_poisoned());
let history = adk_core::Session::conversation_history(session.as_ref());
let texts: Vec<_> = history
.iter()
.map(|content| {
(
content.role.as_str(),
content.parts.iter().filter_map(Part::text).collect::<String>(),
)
})
.collect();
assert_eq!(texts, [("user", "hello".to_string())]);
assert_eq!(
adk_core::State::get(session.as_ref(), "topic"),
Some(serde_json::json!("billing"))
);
let mut later = Event::new("inv-1");
later.author = "agent".to_string();
later.llm_response.content = Some(Content::new("model").with_text("hi"));
session.append_event(later);
assert_eq!(session.events_len(), 2, "a write after the panic is kept");
}
}
#[cfg(test)]
mod snapshot_tests {
use super::*;
use adk_session::{Events, State};
use std::sync::atomic::{AtomicUsize, Ordering};
struct CountingSession {
events: Vec<Event>,
state: HashMap<String, serde_json::Value>,
copies: Arc<AtomicUsize>,
takes: Arc<AtomicUsize>,
}
impl CountingSession {
fn new(copies: &Arc<AtomicUsize>, takes: &Arc<AtomicUsize>) -> Self {
let events = ["first", "second"]
.into_iter()
.map(|text| {
let mut event = Event::new("inv-1");
event.author = "user".to_string();
event.llm_response.content = Some(Content::new("user").with_text(text));
event
})
.collect();
Self {
events,
state: HashMap::from([("topic".to_string(), serde_json::json!("billing"))]),
copies: Arc::clone(copies),
takes: Arc::clone(takes),
}
}
}
impl Events for CountingSession {
fn all(&self) -> Vec<Event> {
self.copies.fetch_add(1, Ordering::SeqCst);
self.events.clone()
}
fn len(&self) -> usize {
self.events.len()
}
fn at(&self, index: usize) -> Option<&Event> {
self.events.get(index)
}
}
impl State for CountingSession {
fn get(&self, key: &str) -> Option<serde_json::Value> {
self.state.get(key).cloned()
}
fn set(&mut self, key: String, value: serde_json::Value) {
self.state.insert(key, value);
}
fn all(&self) -> HashMap<String, serde_json::Value> {
self.state.clone()
}
}
impl AdkSession for CountingSession {
fn id(&self) -> &str {
"session"
}
fn app_name(&self) -> &str {
"app"
}
fn user_id(&self) -> &str {
"user"
}
fn state(&self) -> &dyn State {
self
}
fn events(&self) -> &dyn Events {
self
}
fn last_update_time(&self) -> chrono::DateTime<chrono::Utc> {
chrono::Utc::now()
}
fn take_events(&mut self) -> Vec<Event> {
self.takes.fetch_add(1, Ordering::SeqCst);
std::mem::take(&mut self.events)
}
}
fn texts(session: &MutableSession) -> Vec<String> {
session
.events_snapshot()
.iter()
.flat_map(|event| event.llm_response.content.iter().flat_map(|c| c.parts.iter()))
.filter_map(|part| part.text().map(str::to_string))
.collect()
}
#[test]
fn a_session_held_once_moves_its_history() {
let (copies, takes) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
let session = MutableSession::new(Arc::new(CountingSession::new(&copies, &takes)));
assert_eq!((copies.load(Ordering::SeqCst), takes.load(Ordering::SeqCst)), (0, 1));
assert_eq!(texts(&session), ["first", "second"]);
let identity = (
adk_core::Session::id(&session),
adk_core::Session::app_name(&session),
adk_core::Session::user_id(&session),
);
assert_eq!(identity, ("session", "app", "user"));
assert_eq!(adk_core::State::get(&session, "topic"), Some(serde_json::json!("billing")));
}
#[test]
fn a_shared_session_keeps_its_history() {
let (copies, takes) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
let shared: Arc<dyn AdkSession> = Arc::new(CountingSession::new(&copies, &takes));
let session = MutableSession::new(Arc::clone(&shared));
assert_eq!((copies.load(Ordering::SeqCst), takes.load(Ordering::SeqCst)), (1, 0));
assert_eq!(texts(&session), ["first", "second"]);
assert_eq!(shared.events().len(), 2, "the caller's handle keeps its events");
}
}