use crate::{
AdkError, ErrorCategory, ErrorComponent, ReadonlyContext, Result, RunConfig, ToolEffect,
ToolResultStatus,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
pub const OUTCOME_UNKNOWN_STATUS: &str = "outcome_unknown";
pub fn outcome_unknown_response(detail: impl Into<String>) -> Value {
serde_json::json!({ "status": OUTCOME_UNKNOWN_STATUS, "detail": detail.into() })
}
pub const NOT_RUN_PREFIX: &str = "not run: ";
pub fn not_run_text(refusal: &AdkError) -> String {
format!("{NOT_RUN_PREFIX}{}", refusal.message)
}
pub fn is_not_run(text: &str) -> bool {
text.starts_with(NOT_RUN_PREFIX)
}
pub fn is_outcome_unknown(response: &Value) -> bool {
response.get("status").and_then(Value::as_str) == Some(OUTCOME_UNKNOWN_STATUS)
}
pub fn json_digest(value: &Value) -> String {
const OFFSET_BASIS: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
const PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013b;
let mut canonical = String::new();
crate::context::write_canonical(value, &mut canonical);
let hash = canonical
.bytes()
.fold(OFFSET_BASIS, |hash, byte| (hash ^ u128::from(byte)).wrapping_mul(PRIME));
format!("fnv1a128:{hash:032x}")
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "camelCase")]
#[non_exhaustive]
pub enum ActionOutcome {
#[serde(rename_all = "camelCase")]
Succeeded {
result_digest: String,
},
#[serde(rename_all = "camelCase")]
Failed {
error: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionRecord {
pub key: String,
pub tool_name: String,
pub args_digest: String,
pub effect: ToolEffect,
pub started_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outcome: Option<ActionOutcome>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub completed_at: Option<DateTime<Utc>>,
}
impl ActionRecord {
pub fn new(
key: impl Into<String>,
tool_name: impl Into<String>,
args: &Value,
effect: ToolEffect,
) -> Self {
Self {
key: key.into(),
tool_name: tool_name.into(),
args_digest: json_digest(args),
effect,
started_at: Utc::now(),
outcome: None,
completed_at: None,
}
}
pub fn is_completed(&self) -> bool {
self.outcome.is_some()
}
}
#[async_trait]
pub trait ActionLedger: std::fmt::Debug + Send + Sync {
async fn begin(&self, record: &ActionRecord) -> Result<()>;
async fn complete(&self, key: &str, outcome: ActionOutcome) -> Result<()>;
async fn get(&self, key: &str) -> Result<Option<ActionRecord>>;
}
pub fn duplicate_key_error(key: &str) -> AdkError {
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
"tool.action_ledger.duplicate_key",
format!(
"action ledger already holds a record for key '{key}'; the call was not executed again"
),
)
}
pub fn missing_key_error(key: &str) -> AdkError {
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::NotFound,
"tool.action_ledger.not_found",
format!("action ledger has no record for key '{key}'; call begin before complete"),
)
}
pub fn already_completed_error(key: &str) -> AdkError {
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
"tool.action_ledger.already_completed",
format!("action ledger record '{key}' already has an outcome; outcomes are write-once"),
)
}
#[derive(Debug, Default)]
pub struct InMemoryActionLedger {
records: tokio::sync::RwLock<HashMap<String, ActionRecord>>,
}
impl InMemoryActionLedger {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl ActionLedger for InMemoryActionLedger {
async fn begin(&self, record: &ActionRecord) -> Result<()> {
let mut records = self.records.write().await;
if records.contains_key(&record.key) {
return Err(duplicate_key_error(&record.key));
}
records.insert(record.key.clone(), record.clone());
Ok(())
}
async fn complete(&self, key: &str, outcome: ActionOutcome) -> Result<()> {
let mut records = self.records.write().await;
let record = records.get_mut(key).ok_or_else(|| missing_key_error(key))?;
if record.outcome.is_some() {
return Err(already_completed_error(key));
}
record.outcome = Some(outcome);
record.completed_at = Some(Utc::now());
Ok(())
}
async fn get(&self, key: &str) -> Result<Option<ActionRecord>> {
Ok(self.records.read().await.get(key).cloned())
}
}
pub fn held_call_ledger_key(
app_name: &str,
user_id: &str,
session_id: &str,
function_call_id: &str,
fingerprint: &str,
) -> String {
let digest = json_digest(&Value::String(fingerprint.to_string()));
format!("{app_name}/{user_id}/{session_id}/held/{function_call_id}/{digest}")
}
#[derive(Debug)]
pub struct LedgeredCall {
ledger: Arc<dyn ActionLedger>,
key: String,
}
#[derive(Debug)]
#[non_exhaustive]
pub struct LedgerAnswer {
pub response: Value,
pub status: ToolResultStatus,
pub cause: Option<AdkError>,
}
pub async fn begin_ledgered_call(
config: &RunConfig,
ctx: &dyn ReadonlyContext,
effect: ToolEffect,
key: String,
name: &str,
args: &Value,
) -> Result<std::result::Result<Option<LedgeredCall>, LedgerAnswer>> {
let ledger = match &config.action_ledger {
Some(ledger) if effect == ToolEffect::NonIdempotent => ledger.clone(),
_ => return Ok(Ok(None)),
};
let mut status = ToolResultStatus::NotRun;
let mut cause = None;
let response = match ledger.get(&key).await {
Ok(Some(record)) => {
status = ToolResultStatus::of_record(record.outcome.as_ref());
match record.outcome {
Some(ActionOutcome::Succeeded { result_digest }) => serde_json::json!({
"status": "already_succeeded",
"result_digest": result_digest,
"detail": format!("this call to '{name}' already completed; it was not executed again"),
}),
Some(ActionOutcome::Failed { error }) => serde_json::json!({
"status": "already_failed",
"error": error,
"detail": format!("this call to '{name}' already failed; it was not executed again"),
}),
_ => {
record_outcome_unknown(config, ctx, name, args, "began_without_outcome")
.await?;
outcome_unknown_response(format!(
"an earlier attempt of this call to '{name}' began but recorded no outcome, so it may have taken effect; it was not executed again"
))
}
}
}
Ok(None) => match ledger.begin(&ActionRecord::new(key.clone(), name, args, effect)).await {
Ok(()) => return Ok(Ok(Some(LedgeredCall { ledger, key }))),
Err(error) => {
tracing::error!(tool.name = %name, error = %error, "action ledger could not record the call");
let response = serde_json::json!({
"error": format!("tool '{name}' was not executed: the action ledger could not record the call: {}", error.redacted())
});
cause = Some(error);
response
}
},
Err(error) => {
tracing::error!(tool.name = %name, error = %error, "action ledger could not be read");
let response = serde_json::json!({
"error": format!("tool '{name}' was not executed: the action ledger could not be read: {}", error.redacted())
});
cause = Some(error);
response
}
};
tracing::warn!(
tool.name = %name,
tool.idempotency_key = %key,
response = %response,
"non-idempotent call answered by the action ledger without executing"
);
Ok(Err(LedgerAnswer { response, status, cause }))
}
pub async fn record_outcome_unknown(
config: &RunConfig,
ctx: &dyn ReadonlyContext,
name: &str,
args: &Value,
cause: &str,
) -> Result<()> {
use crate::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
let Some(trail) = &config.audit else {
return Ok(());
};
let draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, name)
.actor(AuditActor::for_context(ctx))
.args_digest(trail.digest(args))
.outcome(AuditRecordOutcome::OutcomeUnknown)
.ext("cause", Value::String(cause.to_string()))
.ext("sessionId", Value::String(ctx.session_id().to_string()));
trail.record(draft).await
}
impl LedgeredCall {
pub async fn complete(self, name: &str, result: Option<&Value>, error: &str) {
let outcome = match result {
Some(value) => ActionOutcome::Succeeded { result_digest: json_digest(value) },
None => ActionOutcome::Failed { error: error.to_string() },
};
if let Err(error) = self.ledger.complete(&self.key, outcome).await {
tracing::error!(
tool.name = %name,
tool.idempotency_key = %self.key,
error = %error,
"action ledger could not record the outcome; a replay will report it as unknown"
);
}
}
}
pub fn interrupted_call_response(error: &str) -> Value {
outcome_unknown_response(format!(
"{error}. The call may have taken effect; check its result before calling it again."
))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[tokio::test]
async fn in_memory_ledger_round_trips_a_completed_record() {
let ledger = InMemoryActionLedger::new();
let record = ActionRecord::new("k", "pay", &json!({"a": 1}), ToolEffect::NonIdempotent);
ledger.begin(&record).await.unwrap();
assert_eq!(ledger.get("k").await.unwrap(), Some(record.clone()));
let outcome = ActionOutcome::Failed { error: "declined".into() };
ledger.complete("k", outcome.clone()).await.unwrap();
let stored = ledger.get("k").await.unwrap().unwrap();
assert_eq!(stored.outcome, Some(outcome.clone()));
assert!(stored.completed_at.is_some());
let error = ledger.complete("k", outcome).await.unwrap_err();
assert_eq!(error.code, "tool.action_ledger.already_completed");
}
#[tokio::test]
async fn in_memory_ledger_rejects_duplicates_and_unknown_keys() {
let ledger = InMemoryActionLedger::new();
let record = ActionRecord::new("k", "pay", &json!({}), ToolEffect::NonIdempotent);
ledger.begin(&record).await.unwrap();
assert_eq!(
ledger.begin(&record).await.unwrap_err().code,
"tool.action_ledger.duplicate_key"
);
let missing = ledger
.complete("other", ActionOutcome::Succeeded { result_digest: String::new() })
.await
.unwrap_err();
assert!(missing.is_not_found());
assert_eq!(ledger.get("other").await.unwrap(), None);
}
#[test]
fn action_record_serializes_camel_case() {
let mut record = ActionRecord::new("k", "pay", &json!({}), ToolEffect::NonIdempotent);
record.outcome = Some(ActionOutcome::Succeeded { result_digest: "fnv1a128:ab".into() });
let value = serde_json::to_value(&record).unwrap();
assert_eq!(value["toolName"], "pay");
assert_eq!(value["effect"], "non_idempotent");
assert_eq!(value["outcome"], json!({"status": "succeeded", "resultDigest": "fnv1a128:ab"}));
let back: ActionRecord = serde_json::from_value(value).unwrap();
assert_eq!(back, record);
}
#[test]
fn json_digest_ignores_key_order_and_distinguishes_values() {
assert_eq!(json_digest(&json!({"a": 1, "b": 2})), json_digest(&json!({"b": 2, "a": 1})));
assert_ne!(json_digest(&json!({"a": 1})), json_digest(&json!({"a": 2})));
assert_eq!(json_digest(&json!(null)).len(), "fnv1a128:".len() + 32);
assert_eq!(json_digest(&json!({"a": 1})), "fnv1a128:a930e708924ff78dd36054201cd38dc9");
}
}