diff --git a/src/crates/assembly/core/src/agentic/execution/round_executor.rs b/src/crates/assembly/core/src/agentic/execution/round_executor.rs index ba2882fbc3..7d92330eb3 100644 --- a/src/crates/assembly/core/src/agentic/execution/round_executor.rs +++ b/src/crates/assembly/core/src/agentic/execution/round_executor.rs @@ -1254,6 +1254,18 @@ impl RoundExecutor { // Check cancellation token before calling stream processing. if cancel_token.is_cancelled() { + // The request was already accepted by the provider, so this + // attempt is as billable as one cancelled mid-send or + // mid-stream and must leave the same ledger evidence. + self.record_attempt_usage( + &context, + &usage_context, + None, + openbitfun_services_core::token_usage::types::ModelRequestOutcome::Cancelled, + context_window, + is_subagent, + ) + .await; Self::complete_model_exchange_trace( trace_config.as_ref(), trace_handle.as_ref(), @@ -7649,6 +7661,93 @@ pub(super) mod tests { assert_eq!(server.requests.lock().unwrap().len(), 1); } + #[tokio::test] + async fn cancellation_racing_stream_open_still_records_the_sent_attempt() { + use crate::service::token_usage::{TimeRange, TokenUsageQuery, TokenUsageService}; + use openbitfun_services_core::token_usage::types::ModelRequestOutcome; + use std::sync::atomic::Ordering; + + // Cancel while the response headers are already buffered but the round + // has not been polled since. Whichever branch observes cancellation, the + // provider accepted the request, so its attempt must reach the ledger. + // `select!` picks randomly between two ready branches; repeat so the + // post-open branch is exercised. + for iteration in 0..16 { + // Delay the headers so polling can pause before they arrive. + let server = RetryTestServer::with_timing_options( + vec![(200, String::new())], + true, + None, + Some((Duration::from_millis(50), Duration::ZERO)), + ); + let dir = tempfile::tempdir().unwrap(); + let ledger = Arc::new( + TokenUsageService::new_in_base_dir(dir.path().join("ledger")) + .await + .unwrap(), + ); + let mut executor = test_round_executor(); + executor.usage_service = Some(ledger.clone()); + let token = CancellationToken::new(); + executor.register_cancel_token("turn-1", token.clone()); + let execution = executor.execute_round( + server.client(), + test_round_context(), + vec![super::AIMessage::user("Cancel at stream open".into())], + None, + None, + ); + tokio::pin!(execution); + tokio::time::timeout(Duration::from_secs(5), async { + while server.requests.lock().unwrap().is_empty() { + tokio::select! { + biased; + _ = &mut execution => panic!("round finished before cancellation"), + _ = tokio::time::sleep(Duration::from_millis(1)) => {} + } + } + while server.opened_streams.load(Ordering::SeqCst) != 1 { + tokio::time::sleep(Duration::from_millis(1)).await; + } + // Let the connection task parse the buffered response head. + tokio::time::sleep(Duration::from_millis(20)).await; + }) + .await + .expect("fixture must open the stream"); + token.cancel(); + let result = tokio::time::timeout(Duration::from_secs(5), execution) + .await + .expect("cancelled round must stop"); + assert!(matches!(result, Err(OpenBitFunError::Cancelled(_)))); + let records = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let records = ledger + .query_records(TokenUsageQuery { + model_id: None, + session_id: None, + time_range: TimeRange::All, + time_zone: None, + limit: None, + offset: None, + include_subagent: true, + }) + .await + .unwrap(); + if !records.is_empty() { + break records; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("iteration {iteration}: cancelled attempt has no record")); + assert_eq!(records.len(), 1); + let attempt = records[0].request_context().unwrap(); + assert_eq!(attempt.outcome, ModelRequestOutcome::Cancelled); + assert!(!records[0].usage_is_known()); + } + } + #[tokio::test] async fn provider_rejections_stop_after_one_request_for_http_and_stream_errors() { for (status, code, category) in [