Tool Effects and the Action Ledger

Every tool declares what calling it does to the outside world. The runtime uses that declaration to decide whether a failed call may be retried, whether the call is recorded in an action ledger, and what the model is told when a call ends without a result.

Tool effects

Tool::effect() returns a ToolEffect:

EffectMeaningRetried after a retryable errorRecorded in the action ledger
ReadOnlyReads without changing anythingYesNo
IdempotentChanges state; repeating a call leaves the same state as making it onceYesNo
NonIdempotentRepeating a call repeats the change — a payment, an email, an orderNoYes, when a ledger is configured

The default derives the effect from is_read_only(): a read-only tool is ReadOnly, and every other tool is NonIdempotent. A tool that declares nothing is therefore never retried.

Declare the effect with the #[tool] macro, the FunctionTool builder, or a Tool implementation:

use adk_core::{Result, Tool, ToolContext, ToolEffect};
use adk_tool::{AdkError, FunctionTool, tool};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{Value, json};
use std::sync::Arc;

#[derive(Deserialize, JsonSchema)]
struct StatusArgs {
    ticket: String,
    status: String,
}

/// Sets a ticket's status. Setting the same status twice changes nothing.
#[tool(idempotent)]
async fn set_ticket_status(args: StatusArgs) -> std::result::Result<Value, AdkError> {
    Ok(json!({ "ticket": args.ticket, "status": args.status }))
}

let archive = FunctionTool::new("archive_ticket", "Archives a ticket", |_ctx, args| async move {
    Ok(args)
})
.with_effect(ToolEffect::Idempotent);

struct ChargeCard;

#[async_trait::async_trait]
impl Tool for ChargeCard {
    fn name(&self) -> &str {
        "charge_card"
    }
    fn description(&self) -> &str {
        "Charges the customer's card"
    }
    fn effect(&self) -> ToolEffect {
        ToolEffect::NonIdempotent
    }
    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        // Downstream payment APIs deduplicate on this key.
        let key = ctx.idempotency_key();
        Ok(json!({ "charged": args["amount"], "idempotency_key": key }))
    }
}

The payment tools in adk-payments declare payments_checkout_create and payments_checkout_complete as NonIdempotent and pass the call's idempotency key to the commerce backend in the idempotency_key extension field.

Retries

LlmAgent and CodeActAgent retry a failed call under a RetryBudget only when both hold:

  1. The tool's effect is ReadOnly or Idempotent.
  2. The error is retryable — AdkError::is_retryable() is true (rate limited, unavailable, timed out), or the call hit the agent's tool timeout.

The delay before retry n is delay * 2^(n - 1), capped at max_delay, and drawn from the upper half of that range so callers that failed together do not retry in lockstep. Each attempt runs with a fresh tool context, so the state delta and escalation of an attempt that is retried are never committed.

use adk_agent::LlmAgentBuilder;
use adk_core::RetryBudget;
use std::{sync::Arc, time::Duration};

let agent = LlmAgentBuilder::new("support")
    .model(model)
    .tool(Arc::new(SetTicketStatus))
    .default_retry_budget(
        RetryBudget::new(3, Duration::from_millis(200)).with_max_delay(Duration::from_secs(5)),
    )
    .build()?;

Idempotency keys

ToolContext::idempotency_key() identifies one tool call across every attempt and replay.

AgentKeyUnique per
LlmAgent{app}/{user}/{session}/{invocation}/{function_call_id}Model function call; when a provider assigns no call ID, LlmAgent assigns one unique to the model turn
CodeActAgent{app}/{user}/{session}/codeact/{run_id}/{iteration}/{call_id}Tool call of one generated program

A CodeActAgent key names the agent run (run_id, stored in every checkpoint), the model turn whose program made the call (iteration), and the interpreter's call id, which counts the program's tool calls in order:

  • Two identical calls in one program have different call ids, so both execute.
  • A call replayed from a checkpoint — crash recovery from the write-ahead checkpoint, or the resume of a call held for confirmation — runs in a later invocation but resolves to the same key, because the run ID, the turn, and the call id come from the checkpoint and the interpreter snapshot.
  • A program the model regenerates on a later turn or in a new run is a new set of calls with new keys. The ledger does not match calls by tool name or arguments.

The action ledger

An ActionLedger records every NonIdempotent call before it executes and its outcome after. Set one on RunConfig, or on the runner with Runner::builder().action_ledger(...), which installs it on every run whose RunConfig carries none:

use adk_core::{InMemoryActionLedger, RunConfig};
use std::sync::Arc;

let config = RunConfig::builder()
    .action_ledger(Arc::new(InMemoryActionLedger::new()))
    .build();

LlmAgent and CodeActAgent consult the ledger under the call's idempotency key after the governed path authorizes the call and before it executes.

A call held for confirmation and resumed by a later run executes under that run's invocation, so LlmAgent records it under its original identity instead: adk_agent::held_call_ledger_key — {app}/{user}/{session}/held/{function_call_id}/{digest}, where digest is the json_digest of the request's ToolConfirmationRequest::fingerprint(). The resumed call's ToolContext::idempotency_key() answers the same key, so a tool that passes it to a downstream API (a payment provider's idempotency header, for example) sends one key however many runs resume the call. Every resumption of the same held call shares that record, so a call that ran in a run whose result was never saved — the process stopped first — is answered from its record when a later run resumes it with the same decision, instead of running a second time:

Ledger stateBehaviourFunction response
No recordbegin, execute, completeThe tool's result
Completed with a resultNot executed{"status": "already_succeeded", "result_digest": "fnv1a128:…", "detail": "…"}
Completed with an errorNot executed{"status": "already_failed", "error": "…", "detail": "…"}, where error is the text the model was given when the call failed
Begun, never completedNot executed{"status": "outcome_unknown", "detail": "…"}
Read or begin failsNot executed{"error": "tool '…' was not executed: …"}, naming the ledger error's component, category, and code; the message is logged

A call that times out or panics keeps its begun record, so a replay of it after a crash, a timeout, or a cancelled run is answered as outcome_unknown rather than executed a second time.

CodeActAgent raises every ledger answer into the program at the call site, with the response above as the error message — for example {"status":"outcome_unknown","detail":"…"}. Code that catches the error can inspect it; an uncaught one reaches the model with the program's traceback. The ledger stores json_digest digests of the arguments and result — a stable identifier, not a cryptographic hash — never the payloads themselves.

ImplementationCrateSurvives a restart
InMemoryActionLedgeradk-coreNo
SqliteActionLedgeradk-session (sqlite feature)Yes
PostgresActionLedgeradk-session (postgres feature)Yes
RedisActionLedgeradk-session (redis feature)Yes, with server persistence
MongoActionLedgeradk-session (mongodb feature)Yes
Neo4jActionLedgeradk-session (neo4j feature)Yes
FirestoreActionLedgeradk-session (firestore feature)Yes

Every implementation passes the same conformance suite; see Durable Stores for the backend matrix and which store combinations prevent duplicate execution.

[dependencies]
adk-session = { version = "3.0.0", features = ["sqlite"] }
use adk_core::RunConfig;
use adk_session::SqliteActionLedger;
use std::sync::Arc;

let ledger = SqliteActionLedger::new("sqlite:actions.db?mode=rwc").await?;
ledger.migrate().await?;
let config = RunConfig::builder().action_ledger(Arc::new(ledger)).build();

Unknown outcomes

A NonIdempotent call whose side effect may or may not have happened is answered with an outcome-unknown function response instead of an error the model would read as an invitation to try again:

{ "status": "outcome_unknown", "detail": "Tool 'charge_card' timed out after 300s. The call may have taken effect; check its result before calling it again." }
CauseSource
The call hit the agent's tool timeoutLlmAgent, CodeActAgent (the realtime runtimes annotate the status only)
The tool panickedLlmAgent, CodeActAgent
The ledger holds a begun record for the keyLlmAgent, CodeActAgent
The run was cancelled while the call was in flightRunner

Each of these answers carries the outcome_unknown tool result status, which an on_tool_error fallback or an after-tool replacement keeps; a replay answered already_succeeded or already_failed carries succeeded or failed, and not_run when the recorded failure is the kill switch's not run text.

When a run is cancelled — Runner::interrupt() or a cancellation token — the runner persists one function response for every call still in flight, so each call keeps exactly one response and the next turn's model request shows the call and its unknown outcome. adk_core::is_outcome_unknown() recognizes these responses.

A process that stops mid-tool leaves its call with no response at all. Before a recovered session continues, Runner::recover_unanswered_calls(user_id, session_id) appends one response for each such call from the ledger record under its idempotency key — already_succeeded, already_failed, or outcome_unknown when the record has no outcome or there is none — and executes no tool.

Delegation timeouts

Tool::timeout_override() replaces the agent's per-call tool_timeout for one tool:

ValueTimeout applied to each call
None (default)The agent's tool_timeout
Some(None)None; the call runs until it finishes or the run is cancelled
Some(Some(duration))duration

AgentTool returns its own timeout setting, so a delegation is bounded by the agent tool's configuration rather than the parent's five-minute default:

use adk_tool::AgentTool;
use std::time::Duration;

// No per-call limit: the run's own budget and cancellation bound the delegation.
let researcher = AgentTool::new(research_agent.clone());

// A forty-five-minute limit for this delegation only.
let bounded = AgentTool::new(research_agent).timeout(Duration::from_secs(45 * 60));

A delegation that runs past its limit is a failed call with a Timeout error, whichever failure mode the agent tool uses. The calling agent enforces the limit and handles it like any tool timeout: a NonIdempotent delegation, the default, is answered with {"status": "outcome_unknown"} and its ledger record stays begun. A delegation that times out after its agent held a call is not held for that call: the request is withdrawn, so no later decision runs a delegation whose outcome is unknown.