mod common;
use causa_kernel::{
ArtifactHint, ArtifactKind, ArtifactRef, ArtifactStore, AttemptNumber, BlockContent,
CallControl, ContextBlock, DynamicToolSource, ModelInvokeErrorKind, ModelOutput, ModelResponse,
ModelStopReason, ModelUsage, ReasoningPayload, SourceError, StoreError, TextPayload, Tool,
ToolCallContext, ToolCallId, ToolCallPayload, ToolDefinition, ToolExecutionError, ToolOutput,
ToolResultPayload, ToolResultStatus, Truncation,
};
use causa_runtime::{
ExecutionOptions, FramePolicy, HookCtx, HookOutcome, RetryPolicy, RunControl, ToolExecutor,
ToolOutputLimits, ToolUseHook, TurnInterruption, TurnPolicy, TurnResult, TurnRunOptions,
TurnRunner, UnknownOutcomeConfig, UnknownOutcomePolicy, WindowBudget,
};
use common::{
DropAllCompaction, EchoTool, FailTool, RecordingGateway, UnknownStopTool, ctrl, ctx, draft,
endturn_output, options_with_limits, runner_with, runner_with_dedup, tooluse_calls_output,
tooluse_output,
};
use serde_json::json;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[tokio::test]
async fn final_assistant_completes_once() {
let c = ctx("t1");
let runner = runner_with(
RecordingGateway::scripted(vec![Ok(endturn_output("final"))]),
vec![],
);
let out = runner.run(c, options_with_limits(5, 10), ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
assert_eq!(out.trace.rounds.len(), 1);
assert_eq!(out.context.blocks().len(), 1);
}
#[tokio::test]
async fn tool_calls_drive_next_frame_and_causality() {
let c = ctx("t1");
let runner = runner_with(
RecordingGateway::scripted(vec![
Ok(tooluse_output("call echo", "echo", json!({"a":1}))),
Ok(endturn_output("done")),
]),
vec![Arc::new(EchoTool)],
);
let out = runner.run(c, options_with_limits(5, 10), ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let blocks = out.context.blocks();
let pos_call = blocks
.iter()
.position(|b| matches!(b.content, BlockContent::ToolCall(_)))
.unwrap();
let pos_result = blocks
.iter()
.position(|b| matches!(b.content, BlockContent::ToolResult(_)))
.unwrap();
assert!(pos_result > pos_call);
}
#[tokio::test]
async fn retry_same_frame_only_attempt_increments_and_no_block_on_failure() {
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![
Err(ModelInvokeErrorKind::Transient),
Ok(endturn_output("ok")),
]);
let runner = runner_with(gw.clone(), vec![]);
let mut cfg = options_with_limits(5, 10);
cfg.policy.retry = RetryPolicy {
max_retries: 1,
retry_timeouts: false,
backoff_base_ms: 0,
backoff_max_ms: 0,
};
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let rec = gw.recorded();
assert_eq!(rec.len(), 2);
assert_eq!(rec[0].invocation_id, rec[1].invocation_id);
assert_eq!(rec[0].frame.frame_id, rec[1].frame.frame_id);
assert_eq!(rec[0].attempt, AttemptNumber(1));
assert_eq!(rec[1].attempt, AttemptNumber(2));
assert_eq!(out.context.blocks().len(), 1);
}
#[tokio::test]
async fn retry_exhaustion_interrupted_and_counts() {
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![
Err(ModelInvokeErrorKind::Transient),
Err(ModelInvokeErrorKind::Transient),
]);
let runner = runner_with(gw.clone(), vec![]);
let mut cfg = options_with_limits(5, 10);
cfg.policy.retry = RetryPolicy {
max_retries: 1,
retry_timeouts: false,
backoff_base_ms: 0,
backoff_max_ms: 0,
};
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::RetryExhausted { .. }
}
));
let rec = gw.recorded();
assert_eq!(rec.len(), 2);
}
#[tokio::test]
async fn tool_failure_is_observation_not_terminal_and_next_round() {
let c = ctx("t1");
let runner = runner_with(
RecordingGateway::scripted(vec![
Ok(tooluse_output("call fail", "fail", json!({}))),
Ok(endturn_output("done after fail")),
]),
vec![Arc::new(FailTool)],
);
let cfg = options_with_limits(5, 10);
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
assert_eq!(out.trace.rounds.len(), 2);
}
#[tokio::test]
async fn dedup_same_batch_rejected_and_parallel_single_failure_not_abort() {
let c = ctx("t1");
let runner = runner_with_dedup(
RecordingGateway::scripted(vec![
Ok(tooluse_calls_output(
"dup",
vec![draft("echo", json!({"x":1})), draft("echo", json!({"x":1}))],
)),
Ok(endturn_output("done")),
]),
vec![Arc::new(EchoTool)],
);
let cfg = options_with_limits(5, 10);
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let last_round = &out.trace.rounds[0];
assert!(last_round.tool_batch.is_some());
let batch = last_round.tool_batch.as_ref().unwrap();
assert_eq!(batch.completion_order.len(), 1);
assert_eq!(batch.calls.len(), 2);
}
#[tokio::test]
async fn unknown_outcome_stop_interrupts() {
let c = ctx("t1");
let runner = runner_with(
RecordingGateway::scripted(vec![Ok(tooluse_output("call unk", "unk", json!({})))]),
vec![Arc::new(UnknownStopTool)],
);
let cfg = options_with_limits(5, 10);
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::UnsafeUnknownOutcome { .. }
}
));
}
#[tokio::test]
async fn same_input_same_fake_output_same_snapshot() {
async fn run_once() -> Vec<ContextBlock> {
let c = ctx("t1");
let runner = runner_with(
RecordingGateway::scripted(vec![
Ok(tooluse_output("hi", "echo", json!({"k":1}))),
Ok(endturn_output("bye")),
]),
vec![Arc::new(EchoTool)],
);
let out = runner.run(c, options_with_limits(5, 10), ctrl()).await;
out.context.snapshot_blocks()
}
let a = run_once().await;
let b = run_once().await;
assert_eq!(
serde_json::to_string(&a).unwrap(),
serde_json::to_string(&b).unwrap()
);
}
#[tokio::test]
async fn token_limits_and_artifact_truncation() {
struct BigTool;
#[async_trait::async_trait]
impl Tool for BigTool {
fn definition(&self) -> ToolDefinition {
ToolDefinition {
name: "big".into(),
description: "big".into(),
parameters: json!({"type":"object"}),
}
}
async fn execute(&self, ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
let big = "a".repeat(1000);
ToolResultPayload {
call_id: ctx.call_id.clone(),
status: ToolResultStatus::Succeeded,
output: ToolOutput::new(json!(big)),
media: Vec::new(),
}
}
}
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![
Ok(tooluse_output("call big", "big", json!({}))),
Ok(endturn_output("done")),
]);
struct MemStore;
#[async_trait::async_trait]
impl ArtifactStore for MemStore {
async fn persist(
&self,
data: &[u8],
_hint: ArtifactHint,
) -> Result<ArtifactRef, StoreError> {
Ok(ArtifactRef {
id: blake3::hash(data).to_hex().to_string()[..8].into(),
size_bytes: data.len(),
kind: ArtifactKind::FullOutput,
persisted: true,
})
}
async fn read(
&self,
_id: &str,
_range: Option<std::ops::Range<u64>>,
) -> Result<Vec<u8>, StoreError> {
Ok(vec![])
}
}
let runner = runner_with(gw, vec![Arc::new(BigTool)]);
let mut cfg = options_with_limits(5, 10);
cfg.execution.tool_output_limits = ToolOutputLimits { max_tokens: 10 };
cfg.execution.artifact_store = Some(Arc::new(MemStore));
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let result_block = out
.context
.blocks()
.iter()
.find(|b| {
matches!(&b.content, BlockContent::ToolResult(r) if r.output.truncation == Truncation::Middle)
})
.expect("truncated");
if let BlockContent::ToolResult(r) = &result_block.content {
assert!(r.output.artifact.is_some());
} else {
panic!()
}
}
#[tokio::test]
async fn parent_cancellation_interrupted() {
let c = ctx("t1");
let token = tokio_util::sync::CancellationToken::new();
token.cancel();
let gw = RecordingGateway::scripted(vec![Ok(endturn_output("should not"))]);
let runner = runner_with(gw, vec![]);
let out = runner
.run(c, options_with_limits(5, 10), RunControl::new(token, None))
.await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::ExplicitCancellation
}
));
}
#[tokio::test]
async fn max_retries_zero_does_single_attempt() {
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![Err(ModelInvokeErrorKind::Transient)]);
let runner = runner_with(gw.clone(), vec![]);
let mut cfg = options_with_limits(5, 10);
cfg.policy.retry = RetryPolicy {
max_retries: 0,
retry_timeouts: false,
backoff_base_ms: 0,
backoff_max_ms: 0,
};
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::RetryExhausted {
last_kind: ModelInvokeErrorKind::Transient,
..
}
}
));
assert_eq!(gw.recorded().len(), 1);
}
#[tokio::test]
async fn turn_deadline_yields_deadline_exceeded() {
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![]);
let runner = runner_with(gw.clone(), vec![]);
let cfg = TurnRunOptions::default();
let ctrl = RunControl::new(
tokio_util::sync::CancellationToken::new(),
Some(std::time::Instant::now() - std::time::Duration::from_secs(1)),
);
let out = runner.run(c, cfg, ctrl).await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::TurnDeadlineExceeded
}
));
assert_eq!(gw.recorded().len(), 0);
}
#[tokio::test]
async fn non_retryable_error_records_round_trace() {
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![Err(ModelInvokeErrorKind::Permanent)]);
let runner = runner_with(gw, vec![]);
let cfg = TurnRunOptions::default();
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::RetryExhausted {
last_kind: ModelInvokeErrorKind::Permanent,
..
}
}
));
assert_eq!(out.trace.rounds.len(), 1);
assert_eq!(out.trace.rounds[0].attempts.len(), 1);
assert!(!out.trace.rounds[0].attempts[0].is_retryable);
assert!(out.trace.rounds[0].attempts[0].kind.is_some());
assert_eq!(out.trace.tool_calls_total, 0);
assert!(out.context.is_sealed());
}
#[tokio::test]
async fn cross_batch_identical_call_does_not_collide() {
let c = ctx("t1");
let same_call = || tooluse_output("retry read", "echo", json!({"path": "A"}));
let gw = RecordingGateway::scripted(vec![
Ok(same_call()),
Ok(same_call()),
Ok(endturn_output("done")),
]);
let runner = runner_with(gw, vec![Arc::new(EchoTool)]);
let cfg = TurnRunOptions::default();
let out = runner.run(c, cfg, ctrl()).await;
assert!(
matches!(out.result, TurnResult::Completed { .. }),
"expected completion, got {:?}",
out.result
);
let call_ids: Vec<_> = out
.context
.blocks()
.iter()
.filter_map(|b| match &b.content {
BlockContent::ToolCall(tc) => Some(tc.call_id.clone()),
_ => None,
})
.collect();
assert_eq!(call_ids.len(), 2);
assert_ne!(call_ids[0], call_ids[1], "round-salted ids must differ");
}
#[tokio::test]
async fn max_tokens_and_refusal_yield_dedicated_causes_without_blocks() {
for (stop, expect) in [
(ModelStopReason::MaxTokens, "max_tokens"),
(ModelStopReason::Refusal, "refusal"),
] {
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![Ok(ModelOutput {
response: ModelResponse {
text: TextPayload::new("cut"),
tool_calls: vec![],
},
usage: None,
stop_reason: stop,
reasoning: None,
})]);
let runner = runner_with(gw, vec![]);
let cfg = TurnRunOptions::default();
let out = runner.run(c, cfg, ctrl()).await;
match (&out.result, expect) {
(TurnResult::Interrupted { cause }, "max_tokens") => {
assert!(matches!(cause, TurnInterruption::ModelMaxTokens))
}
(TurnResult::Interrupted { cause }, "refusal") => {
assert!(matches!(cause, TurnInterruption::ModelRefusal))
}
_ => panic!("unexpected outcome for {expect}"),
}
assert_eq!(out.context.blocks().len(), 0);
assert!(out.context.is_sealed());
assert_eq!(out.trace.rounds.len(), 1);
assert!(out.trace.rounds[0].output_summary.is_some());
}
}
#[tokio::test]
async fn unknown_outcome_continue_continues_turn() {
struct UnknownContinueTool;
#[async_trait::async_trait]
impl Tool for UnknownContinueTool {
fn definition(&self) -> ToolDefinition {
ToolDefinition {
name: "unkc".into(),
description: "unkc".into(),
parameters: json!({"type":"object"}),
}
}
async fn execute(&self, ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
ToolResultPayload {
call_id: ctx.call_id.clone(),
status: ToolResultStatus::UnknownOutcome,
output: ToolOutput::new(json!({"unk": true})),
media: Vec::new(),
}
}
}
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![
Ok(tooluse_output("call unkc", "unkc", json!({}))),
Ok(endturn_output("done")),
]);
let runner = runner_with(gw, vec![Arc::new(UnknownContinueTool)]);
let mut unknown_outcome = UnknownOutcomeConfig::default();
unknown_outcome
.overrides
.insert("unkc".into(), UnknownOutcomePolicy::Continue);
let cfg = TurnRunOptions {
policy: TurnPolicy {
unknown_outcome,
..Default::default()
},
..Default::default()
};
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
assert!(out.context.blocks().iter().any(
|b| matches!(&b.content, BlockContent::ToolResult(r) if r.status == ToolResultStatus::UnknownOutcome)
));
}
#[tokio::test]
async fn hung_tool_stop_policy_interrupts_with_unknown_outcome() {
struct HungTool;
#[async_trait::async_trait]
impl Tool for HungTool {
fn definition(&self) -> ToolDefinition {
ToolDefinition {
name: "hung".into(),
description: "hung".into(),
parameters: json!({"type":"object"}),
}
}
async fn execute(&self, _ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
std::future::pending::<()>().await;
unreachable!()
}
}
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![Ok(tooluse_output("call hung", "hung", json!({})))]);
let runner = runner_with(gw, vec![Arc::new(HungTool)]);
let cfg = TurnRunOptions {
execution: ExecutionOptions {
call_timeout: Some(std::time::Duration::from_millis(50)),
..Default::default()
},
..Default::default()
};
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::UnsafeUnknownOutcome { .. }
}
));
let batch = out.trace.rounds[0].tool_batch.as_ref().unwrap();
assert_eq!(batch.calls[0].status, ToolResultStatus::UnknownOutcome);
}
#[tokio::test]
async fn hung_tool_continue_policy_still_completes() {
struct HungContinueTool;
#[async_trait::async_trait]
impl Tool for HungContinueTool {
fn definition(&self) -> ToolDefinition {
ToolDefinition {
name: "hungc".into(),
description: "hungc".into(),
parameters: json!({"type":"object"}),
}
}
async fn execute(&self, _ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
std::future::pending::<()>().await;
unreachable!()
}
}
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![
Ok(tooluse_output("call hungc", "hungc", json!({}))),
Ok(endturn_output("done")),
]);
let runner = runner_with(gw, vec![Arc::new(HungContinueTool)]);
let mut unknown_outcome = UnknownOutcomeConfig::default();
unknown_outcome
.overrides
.insert("hungc".into(), UnknownOutcomePolicy::Continue);
let cfg = TurnRunOptions {
policy: TurnPolicy {
unknown_outcome,
..Default::default()
},
execution: ExecutionOptions {
call_timeout: Some(std::time::Duration::from_millis(50)),
..Default::default()
},
..Default::default()
};
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
assert_eq!(out.trace.rounds.len(), 2);
}
#[tokio::test]
async fn parallel_batch_partial_failure_does_not_abort() {
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![
Ok(tooluse_calls_output(
"two calls",
vec![draft("echo", json!({"a": 1})), draft("fail", json!({}))],
)),
Ok(endturn_output("done")),
]);
let runner = runner_with(gw, vec![Arc::new(EchoTool), Arc::new(FailTool)]);
let cfg = TurnRunOptions::default();
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let statuses: Vec<_> = out
.context
.blocks()
.iter()
.filter_map(|b| match &b.content {
BlockContent::ToolResult(r) => Some(r.status.clone()),
_ => None,
})
.collect();
assert!(statuses.contains(&ToolResultStatus::Succeeded));
assert!(statuses.contains(&ToolResultStatus::Failed));
}
#[tokio::test]
async fn completion_order_reflects_real_completion() {
struct SlowTool;
#[async_trait::async_trait]
impl Tool for SlowTool {
fn definition(&self) -> ToolDefinition {
ToolDefinition {
name: "slow".into(),
description: "slow".into(),
parameters: json!({"type":"object"}),
}
}
async fn execute(&self, ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
ToolResultPayload {
call_id: ctx.call_id.clone(),
status: ToolResultStatus::Succeeded,
output: ToolOutput::new(json!("slow")),
media: Vec::new(),
}
}
}
let c = ctx("t1");
let gw = RecordingGateway::scripted(vec![
Ok(tooluse_calls_output(
"mixed",
vec![draft("slow", json!({})), draft("echo", json!({}))],
)),
Ok(endturn_output("done")),
]);
let runner = runner_with(gw, vec![Arc::new(SlowTool), Arc::new(EchoTool)]);
let cfg = TurnRunOptions::default();
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let batch = out.trace.rounds[0].tool_batch.as_ref().unwrap();
assert_eq!(batch.calls.len(), 2);
assert_eq!(batch.completion_order.len(), 2);
assert_eq!(batch.calls[0].tool_name, "slow");
assert_eq!(batch.calls[1].tool_name, "echo");
let fast_id = &batch.calls[1].call_id;
assert_eq!(&batch.completion_order[0], fast_id);
assert!(batch.calls[1].duration_ms < batch.calls[0].duration_ms);
}
#[tokio::test]
async fn max_tool_calls_interrupt_records_total() {
let c = ctx("t1");
let two_calls = tooluse_calls_output(
"two",
vec![
draft("echo", json!({"a": 1})),
draft("echo", json!({"a": 1})),
],
);
let gw = RecordingGateway::scripted(vec![Ok(two_calls)]);
let runner = runner_with(gw, vec![Arc::new(EchoTool)]);
let cfg = options_with_limits(5, 1);
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::MaxToolCalls { limit: 1 }
}
));
assert_eq!(out.trace.tool_calls_total, 2);
assert_eq!(out.trace.rounds.len(), 1);
assert!(out.trace.rounds[0].tool_batch.is_none());
}
#[tokio::test]
async fn frame_policy_from_options_shapes_projection_without_touching_facts() {
let mut c = ctx("t1");
c.append_input(TextPayload::new("hello"), "user").unwrap();
struct CountPlusOne;
impl causa_runtime::TokenCounter for CountPlusOne {
fn estimate(&self, blocks: &[ContextBlock]) -> usize {
blocks.len() + 100
}
fn estimate_value(&self, _value: &serde_json::Value) -> usize {
1
}
}
let frame_policy = FramePolicy {
window_budget: WindowBudget {
model_window_limit: 100,
compaction_trigger: 1,
},
compaction: Some(Arc::new(DropAllCompaction)),
token_counter: Some(Arc::new(CountPlusOne)),
};
let gw = RecordingGateway::scripted(vec![Ok(endturn_output("done"))]);
let runner = runner_with(gw.clone(), vec![]);
let cfg = TurnRunOptions {
frame: frame_policy,
..Default::default()
};
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let recorded = gw.recorded();
assert_eq!(recorded.len(), 1);
assert!(recorded[0].frame.model_context.blocks.is_empty());
drop(recorded);
assert_eq!(out.context.blocks().len(), 2);
assert!(matches!(
out.context.blocks()[0].content,
BlockContent::Parts(_)
));
}
struct FailingStore;
#[async_trait::async_trait]
impl ArtifactStore for FailingStore {
async fn persist(&self, _data: &[u8], _hint: ArtifactHint) -> Result<ArtifactRef, StoreError> {
Err(StoreError::Persist("disk full".into()))
}
async fn read(
&self,
_id: &str,
_range: Option<std::ops::Range<u64>>,
) -> Result<Vec<u8>, StoreError> {
Err(StoreError::Read("missing".into()))
}
}
#[tokio::test]
async fn artifact_store_failure_still_truncates_without_artifact() {
let c = ctx("t1");
let big = "x".repeat(400);
let gw = RecordingGateway::scripted(vec![
Ok(tooluse_output("big", "echo", json!({"pad": big}))),
Ok(endturn_output("done")),
]);
let runner = runner_with(gw, vec![Arc::new(EchoTool)]);
let mut cfg = options_with_limits(5, 10);
cfg.execution.tool_output_limits = ToolOutputLimits { max_tokens: 10 };
cfg.execution.artifact_store = Some(Arc::new(FailingStore));
let out = runner.run(c, cfg, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let result_block = out
.context
.blocks()
.iter()
.find(|b| {
matches!(
&b.content,
BlockContent::ToolResult(r) if r.output.truncation == Truncation::Middle
)
})
.expect("truncated");
if let BlockContent::ToolResult(r) = &result_block.content {
assert!(r.output.artifact.is_none());
assert!(r.output.is_truncated());
} else {
panic!()
}
}
struct RecordingStore;
#[async_trait::async_trait]
impl ArtifactStore for RecordingStore {
async fn persist(&self, data: &[u8], _hint: ArtifactHint) -> Result<ArtifactRef, StoreError> {
Ok(ArtifactRef {
id: blake3::hash(data).to_hex().to_string()[..8].into(),
size_bytes: data.len(),
kind: ArtifactKind::FullOutput,
persisted: true,
})
}
async fn read(
&self,
_id: &str,
_range: Option<std::ops::Range<u64>>,
) -> Result<Vec<u8>, StoreError> {
Ok(vec![])
}
}
async fn truncated_echo(
arguments: serde_json::Value,
max_tokens: usize,
store: Option<Arc<dyn ArtifactStore>>,
) -> ToolResultPayload {
let executor = ToolExecutor::from_vec(vec![Arc::new(EchoTool)]);
executor
.execute_with_limits(
ToolCallPayload {
call_id: ToolCallId("probe".into()),
tool_name: "echo".into(),
arguments,
},
CallControl::new(tokio_util::sync::CancellationToken::new(), None),
store,
None,
ToolOutputLimits { max_tokens },
)
.await
}
fn fallback_estimate(value: &serde_json::Value) -> usize {
serde_json::to_string(value)
.map(|s| s.len() / 4)
.unwrap_or(0)
}
#[tokio::test]
async fn truncation_reduces_output_and_reestimates_within_the_limit() {
let original = json!({"echo": {"text": "a".repeat(4000)}});
let before = serde_json::to_string(&original).unwrap().len();
let result = truncated_echo(json!({"text": "a".repeat(4000)}), 100, None).await;
assert_eq!(result.output.truncation, Truncation::Middle);
let after = serde_json::to_string(&result.output.content).unwrap().len();
assert!(
after < before,
"truncation grew output: {before} -> {after} bytes"
);
assert!(
fallback_estimate(&result.output.content) <= 100,
"truncated output re-estimates above the declared limit"
);
}
#[tokio::test]
async fn truncation_holds_for_utf8_and_artifact_spill() {
let result = truncated_echo(
json!({"text": "中文内容".repeat(500)}),
100,
Some(Arc::new(RecordingStore)),
)
.await;
assert_eq!(result.output.truncation, Truncation::Middle);
assert!(result.output.artifact.is_some());
let text = result
.output
.content
.as_str()
.expect("truncated content is a JSON string");
assert!(text.contains("中文"), "kept text is not split mid-char");
assert!(fallback_estimate(&result.output.content) <= 100);
}
#[tokio::test]
async fn tiny_budget_leaves_the_notice_as_the_floor() {
let result = truncated_echo(json!({"text": "a".repeat(4000)}), 10, None).await;
let text = result.output.content.as_str().unwrap();
assert!(text.starts_with("\n...[truncated:"));
assert!(
!text.contains("aaaa"),
"tiny budget still leaked the payload: {text}"
);
}
#[tokio::test]
async fn completed_output_carries_reasoning_and_usage_unchanged() {
let final_output = ModelOutput {
response: ModelResponse {
text: TextPayload::new("final"),
tool_calls: vec![],
},
usage: Some(ModelUsage {
input_tokens: 42,
output_tokens: 7,
cache_read_tokens: Some(11),
cache_write_tokens: Some(3),
reasoning_tokens: Some(5),
}),
stop_reason: ModelStopReason::EndTurn,
reasoning: Some(ReasoningPayload {
text: "thinking".into(),
signature: Some("sig-xyz".into()),
}),
};
let gw = RecordingGateway::scripted(vec![Ok(final_output.clone())]);
let runner = runner_with(gw, vec![]);
let cfg = TurnRunOptions::default();
let out = runner.run(ctx("t1"), cfg, ctrl()).await;
let completed = match out.result {
TurnResult::Completed { final_output } => final_output,
other => panic!("expected completion, got {other:?}"),
};
assert_eq!(
serde_json::to_string(&completed).unwrap(),
serde_json::to_string(&final_output).unwrap()
);
}
#[tokio::test]
async fn hook_that_drops_a_call_interrupts_as_invariant_violation() {
struct DropEverything;
#[async_trait::async_trait]
impl ToolUseHook for DropEverything {
async fn apply(&self, _calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
HookOutcome {
to_execute: vec![],
rejected: vec![],
unknown_decisions: Vec::new(),
}
}
}
let gateway = RecordingGateway::scripted(vec![
Ok(tooluse_output("call echo", "echo", json!({"a": 1}))),
Ok(endturn_output("done")),
]);
let runner = TurnRunner::with_hook(
gateway,
Arc::new(ToolExecutor::from_vec(vec![Arc::new(EchoTool)])),
Arc::new(DropEverything),
);
let out = runner
.run(ctx("t1"), options_with_limits(5, 10), ctrl())
.await;
assert!(matches!(
out.result,
TurnResult::Interrupted {
cause: TurnInterruption::RunnerInvariantViolation { .. }
}
));
assert!(
!out.context
.blocks()
.iter()
.any(|b| matches!(b.content, BlockContent::ToolResult(_))),
"the dropped call must not produce a result"
);
}
#[tokio::test]
async fn dynamic_catalog_refreshes_between_model_rounds() {
struct Catalog {
version: AtomicU64,
}
#[async_trait::async_trait]
impl DynamicToolSource for Catalog {
fn id(&self) -> &str {
"catalog"
}
fn version(&self) -> u64 {
self.version.load(Ordering::SeqCst)
}
async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError> {
Ok(vec![ToolDefinition {
name: format!("tool_v{}", self.version()),
description: String::new(),
parameters: json!({"type": "object"}),
}])
}
async fn invoke(
&self,
call: &ToolCallPayload,
_control: &CallControl,
) -> Result<ToolResultPayload, ToolExecutionError> {
self.version.store(1, Ordering::SeqCst);
Ok(ToolResultPayload {
call_id: call.call_id.clone(),
status: ToolResultStatus::Succeeded,
output: ToolOutput::new(json!("updated")),
media: Vec::new(),
})
}
}
let source = Arc::new(Catalog {
version: AtomicU64::new(0),
});
let executor = Arc::new(ToolExecutor::from_vec(vec![]));
executor.register_dynamic(source).unwrap();
let mut options = options_with_limits(5, 10);
options.invocation.tool_surface = executor.tool_surface().await;
let gateway = RecordingGateway::scripted(vec![
Ok(tooluse_output("", "tool_v0", json!({}))),
Ok(endturn_output("done")),
]);
let runner = TurnRunner::new(gateway.clone(), executor);
let out = runner.run(ctx("catalog"), options, ctrl()).await;
assert!(matches!(out.result, TurnResult::Completed { .. }));
let recorded = gateway.recorded();
assert_eq!(recorded[0].tool_surface.definitions[0].name, "tool_v0");
assert_eq!(
recorded[1].tool_surface.definitions[0].name, "tool_v1",
"second round ran on a stale catalog"
);
}
#[tokio::test]
async fn truncation_never_touches_result_media_references() {
struct ImagingTool;
#[async_trait::async_trait]
impl Tool for ImagingTool {
fn definition(&self) -> ToolDefinition {
ToolDefinition {
name: "imaging".into(),
description: "imaging".into(),
parameters: json!({"type": "object"}),
}
}
async fn execute(&self, ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
ToolResultPayload {
call_id: ctx.call_id.clone(),
status: ToolResultStatus::Succeeded,
output: ToolOutput::new(json!({"chart": "x".repeat(4000)})),
media: vec![causa_kernel::MediaRef::new("image/png", "asset-1")],
}
}
}
let executor = ToolExecutor::from_vec(vec![Arc::new(ImagingTool)]);
let outcome = executor
.execute_with_limits(
ToolCallPayload {
call_id: ToolCallId("probe".into()),
tool_name: "imaging".into(),
arguments: json!({}),
},
CallControl::new(tokio_util::sync::CancellationToken::new(), None),
None,
None,
ToolOutputLimits { max_tokens: 50 },
)
.await;
assert_eq!(outcome.output.truncation, Truncation::Middle);
assert!(
outcome.output.content.to_string().len() < 4000,
"content must shrink"
);
assert_eq!(
outcome.media,
vec![causa_kernel::MediaRef::new("image/png", "asset-1")],
"media references survive truncation untouched"
);
}