Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
3
akode-rs/code-mode-host/AGENTS.md
Normal file
3
akode-rs/code-mode-host/AGENTS.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Tests
|
||||
|
||||
Do not use timeouts or sleeps to synchronize tests. Wait for explicit signals or observable state; let the test runner enforce test-case timeouts.
|
||||
13
akode-rs/code-mode-host/BUILD.bazel
Normal file
13
akode-rs/code-mode-host/BUILD.bazel
Normal file
@@ -0,0 +1,13 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
load("//bazel/rules:runtime_package.bzl", "release_binary")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "code-mode-host",
|
||||
crate_name = "akode_code_mode_host",
|
||||
)
|
||||
|
||||
release_binary(
|
||||
binary = ":akode-code-mode-host",
|
||||
# V8 and its libc++ use aligned new and delete, available on macOS 10.13.
|
||||
macos_x86_64_minimum_os = "10.13",
|
||||
)
|
||||
46
akode-rs/code-mode-host/Cargo.toml
Normal file
46
akode-rs/code-mode-host/Cargo.toml
Normal file
@@ -0,0 +1,46 @@
|
||||
[package]
|
||||
name = "akode-code-mode-host"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "akode-code-mode-host"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
name = "akode_code_mode_host"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-http-client = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
axum = { workspace = true, features = ["http1", "tokio", "ws"] }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
akode-code-mode-protocol = { workspace = true }
|
||||
akode-code-mode-runtime = { workspace = true }
|
||||
akode-otel = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
prost = "0.14.3"
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["io-std", "io-util", "macros", "net", "process", "rt", "sync", "time"] }
|
||||
tokio-stream = { workspace = true }
|
||||
tokio-util = { workspace = true, features = ["rt"] }
|
||||
tonic = { workspace = true, features = ["router", "transport", "zstd"] }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
akode-plugin-host = { workspace = true }
|
||||
akode-code-mode = { workspace = true }
|
||||
akode-utils-cargo-bin = { workspace = true }
|
||||
akode-utils-process = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
85
akode-rs/code-mode-host/src/delegate.rs
Normal file
85
akode-rs/code-mode-host/src/delegate.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_code_mode_protocol::CellId;
|
||||
use akode_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use akode_code_mode_protocol::CodeModeSessionDelegate;
|
||||
use akode_code_mode_protocol::NotificationFuture;
|
||||
use akode_code_mode_protocol::ToolInvocationFuture;
|
||||
use akode_code_mode_protocol::host::DelegateRequest;
|
||||
use akode_code_mode_protocol::host::DelegateResponse;
|
||||
use akode_code_mode_protocol::host::SessionId;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::peer::HostPeer;
|
||||
|
||||
pub(super) struct RemoteDelegate {
|
||||
session_id: SessionId,
|
||||
peer: Arc<HostPeer>,
|
||||
}
|
||||
|
||||
impl RemoteDelegate {
|
||||
pub(super) fn new(session_id: SessionId, peer: Arc<HostPeer>) -> Self {
|
||||
Self { session_id, peer }
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for RemoteDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
match self
|
||||
.peer
|
||||
.call(
|
||||
self.session_id.clone(),
|
||||
DelegateRequest::InvokeTool {
|
||||
invocation: invocation.into(),
|
||||
},
|
||||
cancellation_token,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
DelegateResponse::ToolResult { result } => Ok(result),
|
||||
DelegateResponse::NotificationDelivered => {
|
||||
Err("code-mode client returned an invalid tool result".to_string())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
call_id: String,
|
||||
cell_id: CellId,
|
||||
text: String,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
match self
|
||||
.peer
|
||||
.call(
|
||||
self.session_id.clone(),
|
||||
DelegateRequest::Notify {
|
||||
call_id,
|
||||
cell_id: cell_id.into(),
|
||||
text,
|
||||
},
|
||||
cancellation_token,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
DelegateResponse::NotificationDelivered => Ok(()),
|
||||
DelegateResponse::ToolResult { .. } => {
|
||||
Err("code-mode client returned an invalid notification result".to_string())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn cell_closed(&self, cell_id: &CellId) {
|
||||
self.peer
|
||||
.close_cell(self.session_id.clone(), cell_id.clone());
|
||||
}
|
||||
}
|
||||
78
akode-rs/code-mode-host/src/grpc/capacity_tests.rs
Normal file
78
akode-rs/code-mode-host/src/grpc/capacity_tests.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
#![cfg(test)]
|
||||
//! Negotiated callback budgets protect older clients on a shared host.
|
||||
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use akode_code_mode_protocol::host::LEGACY_MAX_PENDING_DELEGATE_CALLS;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tonic::Code;
|
||||
use tonic::Request;
|
||||
|
||||
use super::GrpcCodeModeHost;
|
||||
use super::tests::open_session;
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_callback_capacity_is_isolated_and_reusable() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (legacy_id, _legacy_lease) = open_session(&host).await;
|
||||
let legacy = host.state.session(&legacy_id).expect("legacy session");
|
||||
let legacy_permits = (0..LEGACY_MAX_PENDING_DELEGATE_CALLS)
|
||||
.map(|_| legacy.delegate_permit().expect("legacy callback"))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
legacy.delegate_permit().unwrap_err(),
|
||||
"code-mode session has too many pending delegate calls"
|
||||
);
|
||||
|
||||
let mut lease = host
|
||||
.open_session(Request::new(proto::OpenSessionRequest {
|
||||
max_pending_delegate_calls: Some(2),
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.expect("open capacity-limited session")
|
||||
.into_inner();
|
||||
let event = lease.next().await.expect("opened event").expect("event");
|
||||
let Some(proto::session_event::Event::Opened(opened)) = event.event else {
|
||||
panic!("expected session opening");
|
||||
};
|
||||
let session = host.state.session(&opened.session_id).expect("session");
|
||||
let first = session.delegate_permit().expect("first callback");
|
||||
let second = session.delegate_permit().expect("second callback");
|
||||
assert_eq!(
|
||||
session.delegate_permit().unwrap_err(),
|
||||
"code-mode session has too many pending delegate calls"
|
||||
);
|
||||
|
||||
drop(first);
|
||||
let replacement = session.delegate_permit().expect("reused callback capacity");
|
||||
drop(legacy_permits);
|
||||
let legacy_replacement = legacy.delegate_permit().expect("reused legacy capacity");
|
||||
drop((second, replacement, legacy_replacement));
|
||||
host.close_session(Request::new(proto::CloseSessionRequest {
|
||||
session_id: opened.session_id,
|
||||
}))
|
||||
.await
|
||||
.expect("close new session");
|
||||
host.close_session(Request::new(proto::CloseSessionRequest {
|
||||
session_id: legacy_id,
|
||||
}))
|
||||
.await
|
||||
.expect("close legacy session");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zero_callback_capacity_is_rejected_before_opening_a_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let result = host
|
||||
.open_session(Request::new(proto::OpenSessionRequest {
|
||||
max_pending_delegate_calls: Some(0),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
let Err(error) = result else {
|
||||
panic!("zero callback capacity must be rejected");
|
||||
};
|
||||
assert_eq!(error.code(), Code::InvalidArgument);
|
||||
}
|
||||
205
akode-rs/code-mode-host/src/grpc/conversions.rs
Normal file
205
akode-rs/code-mode-host/src/grpc/conversions.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
use akode_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use akode_code_mode_protocol::CodeModeSessionCellExecutionLimits;
|
||||
use akode_code_mode_protocol::CodeModeToolKind;
|
||||
use akode_code_mode_protocol::ExecuteRequest;
|
||||
use akode_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use akode_code_mode_protocol::ImageDetail;
|
||||
use akode_code_mode_protocol::MissingCodeModeHostDuration;
|
||||
use akode_code_mode_protocol::RuntimeResponse;
|
||||
use akode_code_mode_protocol::ToolDefinition;
|
||||
use akode_code_mode_protocol::WaitOutcome;
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use akode_protocol::ToolName;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tonic::Response;
|
||||
use tonic::Status;
|
||||
|
||||
use super::validation;
|
||||
|
||||
pub(super) fn session_limits(
|
||||
limits: Option<proto::SessionCellExecutionLimits>,
|
||||
) -> Result<CodeModeSessionCellExecutionLimits, Status> {
|
||||
let limits = limits.unwrap_or_default();
|
||||
Ok(CodeModeSessionCellExecutionLimits {
|
||||
max_yield_time_ms: limits.max_yield_time_ms,
|
||||
max_heap_size_bytes: limits
|
||||
.max_heap_size_bytes
|
||||
.map(usize::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| Status::invalid_argument("maximum heap size exceeds this platform"))?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn observation_budget(
|
||||
max_output_tokens: Option<u64>,
|
||||
output_truncation: CodeModeOutputTruncation,
|
||||
) -> Result<Option<usize>, Status> {
|
||||
if output_truncation == CodeModeOutputTruncation::Client {
|
||||
return Ok(None);
|
||||
}
|
||||
max_output_tokens
|
||||
.map(|value| {
|
||||
usize::try_from(value)
|
||||
.map_err(|_| Status::invalid_argument("output budget is too large"))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(super) fn execute_request(request: proto::ExecuteRequest) -> Result<ExecuteRequest, Status> {
|
||||
validation::identifier(&request.tool_call_id, "tool call ID")?;
|
||||
Ok(ExecuteRequest {
|
||||
tool_call_id: request.tool_call_id,
|
||||
source: request.source,
|
||||
enabled_tools: request
|
||||
.enabled_tools
|
||||
.into_iter()
|
||||
.map(tool_definition)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
yield_time_ms: request.yield_time_ms,
|
||||
max_output_tokens: request
|
||||
.max_output_tokens
|
||||
.map(usize::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| Status::invalid_argument("maximum output tokens exceeds this platform"))?,
|
||||
})
|
||||
}
|
||||
|
||||
fn tool_definition(definition: proto::ToolDefinition) -> Result<ToolDefinition, Status> {
|
||||
validation::identifier(&definition.name, "tool definition name")?;
|
||||
let name = definition
|
||||
.tool_name
|
||||
.ok_or_else(|| Status::invalid_argument("tool definition is missing its tool name"))?;
|
||||
validation::tool_name(&name)?;
|
||||
Ok(ToolDefinition {
|
||||
name: definition.name,
|
||||
tool_name: ToolName::new(name.namespace, name.name),
|
||||
description: definition.description,
|
||||
kind: match proto::ToolKind::try_from(definition.kind) {
|
||||
Ok(proto::ToolKind::Function) => CodeModeToolKind::Function,
|
||||
Ok(proto::ToolKind::Freeform) => CodeModeToolKind::Freeform,
|
||||
Ok(proto::ToolKind::Unspecified) | Err(_) => {
|
||||
return Err(Status::invalid_argument(
|
||||
"tool definition has an invalid kind",
|
||||
));
|
||||
}
|
||||
},
|
||||
input_schema: json_field(definition.input_schema_json, "input schema")?,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: json_field(definition.output_schema_json, "output schema")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn json_field(value: Option<Vec<u8>>, field: &str) -> Result<Option<JsonValue>, Status> {
|
||||
value
|
||||
.map(|value| {
|
||||
serde_json::from_slice(&value)
|
||||
.map_err(|error| Status::invalid_argument(format!("invalid tool {field}: {error}")))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Preserves the response's timing; the host handler must record it first.
|
||||
pub(super) fn execution_outcome(
|
||||
response: RuntimeResponse,
|
||||
) -> Result<proto::ExecutionOutcome, MissingCodeModeHostDuration> {
|
||||
let (cell_id, content_items, outcome, code_mode_host_duration) = match response {
|
||||
RuntimeResponse::Yielded {
|
||||
cell_id,
|
||||
content_items,
|
||||
code_mode_host_duration,
|
||||
} => (
|
||||
cell_id,
|
||||
content_items,
|
||||
proto::execution_outcome::Outcome::Yielded(proto::ExecutionYielded {}),
|
||||
code_mode_host_duration,
|
||||
),
|
||||
RuntimeResponse::Terminated {
|
||||
cell_id,
|
||||
content_items,
|
||||
code_mode_host_duration,
|
||||
} => (
|
||||
cell_id,
|
||||
content_items,
|
||||
proto::execution_outcome::Outcome::Terminated(proto::ExecutionTerminated {}),
|
||||
code_mode_host_duration,
|
||||
),
|
||||
RuntimeResponse::Result {
|
||||
cell_id,
|
||||
content_items,
|
||||
error_text,
|
||||
code_mode_host_duration,
|
||||
..
|
||||
} => (
|
||||
cell_id,
|
||||
content_items,
|
||||
proto::execution_outcome::Outcome::Completed(proto::ExecutionCompleted { error_text }),
|
||||
code_mode_host_duration,
|
||||
),
|
||||
};
|
||||
let code_mode_host_duration = code_mode_host_duration.ok_or(MissingCodeModeHostDuration)?;
|
||||
Ok(proto::ExecutionOutcome {
|
||||
cell_id: cell_id.to_string(),
|
||||
content_items: content_items.into_iter().map(content_item).collect(),
|
||||
outcome: Some(outcome),
|
||||
code_mode_host_duration_ns: u64::try_from(code_mode_host_duration.as_nanos())
|
||||
.unwrap_or(u64::MAX),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn wait_response(
|
||||
outcome: WaitOutcome,
|
||||
) -> Result<Response<proto::WaitResponse>, MissingCodeModeHostDuration> {
|
||||
let buffered = outcome.result_buffered_for();
|
||||
let state = match outcome {
|
||||
WaitOutcome::LiveCell(response) => {
|
||||
proto::wait_response::State::LiveCell(execution_outcome(response)?)
|
||||
}
|
||||
WaitOutcome::MissingCell(response) => {
|
||||
proto::wait_response::State::MissingCell(execution_outcome(response)?)
|
||||
}
|
||||
};
|
||||
let mut response = Response::new(proto::WaitResponse { state: Some(state) });
|
||||
if let Some(buffered) = buffered {
|
||||
let nanos = u64::try_from(buffered.as_nanos()).unwrap_or(u64::MAX);
|
||||
response
|
||||
.metadata_mut()
|
||||
.insert(proto::RESULT_BUFFERED_FOR_NS_METADATA, nanos.into());
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn content_item(item: FunctionCallOutputContentItem) -> proto::ContentItem {
|
||||
let item = match item {
|
||||
FunctionCallOutputContentItem::InputText { text } => {
|
||||
proto::content_item::Item::Text(proto::TextContent { text })
|
||||
}
|
||||
FunctionCallOutputContentItem::InputImage { image_url, detail } => {
|
||||
proto::content_item::Item::Image(proto::ImageContent {
|
||||
image_url,
|
||||
detail: detail.map(|detail| {
|
||||
(match detail {
|
||||
ImageDetail::Auto => proto::ImageDetail::Auto,
|
||||
ImageDetail::Low => proto::ImageDetail::Low,
|
||||
ImageDetail::High => proto::ImageDetail::High,
|
||||
ImageDetail::Original => proto::ImageDetail::Original,
|
||||
}) as i32
|
||||
}),
|
||||
})
|
||||
}
|
||||
FunctionCallOutputContentItem::InputAudio { audio_url } => {
|
||||
proto::content_item::Item::Audio(proto::AudioContent { audio_url })
|
||||
}
|
||||
};
|
||||
proto::ContentItem { item: Some(item) }
|
||||
}
|
||||
|
||||
pub(super) fn tool_kind(kind: CodeModeToolKind) -> i32 {
|
||||
match kind {
|
||||
CodeModeToolKind::Function => proto::ToolKind::Function as i32,
|
||||
CodeModeToolKind::Freeform => proto::ToolKind::Freeform as i32,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "conversions_tests.rs"]
|
||||
mod tests;
|
||||
176
akode-rs/code-mode-host/src/grpc/conversions_tests.rs
Normal file
176
akode-rs/code-mode-host/src/grpc/conversions_tests.rs
Normal file
@@ -0,0 +1,176 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_code_mode_protocol::CellId;
|
||||
use akode_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use akode_code_mode_protocol::ImageDetail;
|
||||
use akode_code_mode_protocol::MissingCodeModeHostDuration;
|
||||
use akode_code_mode_protocol::RuntimeResponse;
|
||||
use akode_code_mode_protocol::WaitOutcome;
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tonic::Code;
|
||||
|
||||
use super::execute_request;
|
||||
use super::execution_outcome;
|
||||
use super::wait_response;
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_names_unknown_tool_kinds_and_invalid_json_schemas() {
|
||||
let definition = proto::ToolDefinition {
|
||||
name: "echo".to_string(),
|
||||
tool_name: None,
|
||||
description: String::new(),
|
||||
kind: proto::ToolKind::Function as i32,
|
||||
input_schema_json: None,
|
||||
output_schema_json: None,
|
||||
};
|
||||
let request = |definition| proto::ExecuteRequest {
|
||||
session_id: "session".to_string(),
|
||||
execution_id: "execution".to_string(),
|
||||
tool_call_id: "call".to_string(),
|
||||
source: String::new(),
|
||||
enabled_tools: vec![definition],
|
||||
yield_time_ms: None,
|
||||
max_output_tokens: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
execute_request(request(definition.clone()))
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
Code::InvalidArgument
|
||||
);
|
||||
let definition = proto::ToolDefinition {
|
||||
tool_name: Some(proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: Some("tools".to_string()),
|
||||
}),
|
||||
..definition
|
||||
};
|
||||
assert_eq!(
|
||||
execute_request(request(proto::ToolDefinition {
|
||||
kind: proto::ToolKind::Unspecified as i32,
|
||||
..definition.clone()
|
||||
}))
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
Code::InvalidArgument
|
||||
);
|
||||
assert_eq!(
|
||||
execute_request(request(proto::ToolDefinition {
|
||||
input_schema_json: Some(b"not-json".to_vec()),
|
||||
..definition
|
||||
}))
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
Code::InvalidArgument
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_text_image_audio_and_terminal_error_without_losing_details() {
|
||||
let response = wait_response(WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
code_mode_host_duration: Some(Duration::from_nanos(/*nanos*/ 123_456_789)),
|
||||
cell_id: CellId::new("cell".to_string()),
|
||||
content_items: vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "hello".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image_url: "data:image/png;base64,YQ==".to_string(),
|
||||
detail: Some(ImageDetail::Original),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "data:audio/wav;base64,YQ==".to_string(),
|
||||
},
|
||||
],
|
||||
result_buffered_for: Duration::from_nanos(42),
|
||||
error_text: Some("failed".to_string()),
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response
|
||||
.metadata()
|
||||
.get(proto::RESULT_BUFFERED_FOR_NS_METADATA)
|
||||
.unwrap(),
|
||||
"42"
|
||||
);
|
||||
let state = response.into_inner().state.expect("wait outcome");
|
||||
assert_eq!(
|
||||
state,
|
||||
proto::wait_response::State::LiveCell(proto::ExecutionOutcome {
|
||||
code_mode_host_duration_ns: 123_456_789,
|
||||
cell_id: "cell".to_string(),
|
||||
content_items: vec![
|
||||
proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Text(proto::TextContent {
|
||||
text: "hello".to_string(),
|
||||
})),
|
||||
},
|
||||
proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Image(proto::ImageContent {
|
||||
image_url: "data:image/png;base64,YQ==".to_string(),
|
||||
detail: Some(proto::ImageDetail::Original as i32),
|
||||
})),
|
||||
},
|
||||
proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Audio(proto::AudioContent {
|
||||
audio_url: "data:audio/wav;base64,YQ==".to_string(),
|
||||
})),
|
||||
},
|
||||
],
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(
|
||||
proto::ExecutionCompleted {
|
||||
error_text: Some("failed".to_string()),
|
||||
},
|
||||
)),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_metadata_distinguishes_an_unbuffered_result_from_no_result() {
|
||||
let result = RuntimeResponse::Result {
|
||||
cell_id: CellId::new("cell".to_string()),
|
||||
content_items: Vec::new(),
|
||||
error_text: None,
|
||||
result_buffered_for: Duration::ZERO,
|
||||
code_mode_host_duration: Some(Duration::ZERO),
|
||||
};
|
||||
for (outcome, expected) in [
|
||||
(WaitOutcome::LiveCell(result.clone()), Some("0")),
|
||||
(WaitOutcome::MissingCell(result), None),
|
||||
] {
|
||||
let response = wait_response(outcome).unwrap();
|
||||
let buffered = response
|
||||
.metadata()
|
||||
.get(proto::RESULT_BUFFERED_FOR_NS_METADATA)
|
||||
.map(|value| value.to_str().unwrap());
|
||||
assert_eq!(buffered, expected);
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding must not turn a missing request measurement into measured zero,
|
||||
/// including when no live cell remains to supply output.
|
||||
#[test]
|
||||
fn grpc_encoding_rejects_untimed_runtime_output() {
|
||||
let response = RuntimeResponse::Terminated {
|
||||
cell_id: CellId::new("cell".to_string()),
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: None,
|
||||
};
|
||||
assert_eq!(
|
||||
execution_outcome(response.clone()),
|
||||
Err(MissingCodeModeHostDuration)
|
||||
);
|
||||
for outcome in [
|
||||
WaitOutcome::LiveCell(response.clone()),
|
||||
WaitOutcome::MissingCell(response),
|
||||
] {
|
||||
assert_eq!(
|
||||
wait_response(outcome).unwrap_err(),
|
||||
MissingCodeModeHostDuration
|
||||
);
|
||||
}
|
||||
}
|
||||
131
akode-rs/code-mode-host/src/grpc/delegate.rs
Normal file
131
akode-rs/code-mode-host/src/grpc/delegate.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use akode_code_mode_protocol::CellId;
|
||||
use akode_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use akode_code_mode_protocol::CodeModeSessionDelegate;
|
||||
use akode_code_mode_protocol::NotificationFuture;
|
||||
use akode_code_mode_protocol::ToolInvocationFuture;
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::session::GrpcSession;
|
||||
|
||||
pub(super) struct GrpcDelegate {
|
||||
session: Weak<GrpcSession>,
|
||||
}
|
||||
|
||||
impl GrpcDelegate {
|
||||
pub(super) fn new(session: Weak<GrpcSession>) -> Self {
|
||||
Self { session }
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for GrpcDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let session = self
|
||||
.session
|
||||
.upgrade()
|
||||
.ok_or_else(|| "code-mode session is closed".to_string())?;
|
||||
let _permit = session.delegate_permit()?;
|
||||
let execution_id = session
|
||||
.execution_id(invocation.cell_id.as_str(), &cancellation)
|
||||
.await?;
|
||||
let input_json = invocation
|
||||
.input
|
||||
.as_ref()
|
||||
.map(serde_json::to_vec)
|
||||
.transpose()
|
||||
.map_err(|error| format!("failed to encode code-mode tool input: {error}"))?;
|
||||
let invocation_id = Uuid::new_v4();
|
||||
let (response, receiver) = oneshot::channel();
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation,
|
||||
execution_id,
|
||||
invocation_id,
|
||||
input_json,
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await?;
|
||||
let mut pending = PendingToolCall {
|
||||
session: Arc::clone(&session),
|
||||
id: Some(invocation_id),
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
result = receiver => result
|
||||
.map_err(|_| "code-mode client closed before returning tool output".to_string())?,
|
||||
_ = cancellation.cancelled() => {
|
||||
Err("code mode delegate request cancelled".to_string())
|
||||
}
|
||||
_ = session.closed.cancelled() => {
|
||||
Err("code-mode session closed before returning tool output".to_string())
|
||||
}
|
||||
};
|
||||
if result.is_ok() {
|
||||
pending.id = None;
|
||||
}
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
call_id: String,
|
||||
cell_id: CellId,
|
||||
text: String,
|
||||
cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let session = self
|
||||
.session
|
||||
.upgrade()
|
||||
.ok_or_else(|| "code-mode session is closed".to_string())?;
|
||||
let _permit = session.delegate_permit()?;
|
||||
let execution_id = session
|
||||
.execution_id(cell_id.as_str(), &cancellation)
|
||||
.await?;
|
||||
let notification_id = Uuid::new_v4();
|
||||
session
|
||||
.send_event(
|
||||
proto::session_event::Event::Notification(proto::Notification {
|
||||
notification_id: notification_id.to_string(),
|
||||
execution_id,
|
||||
cell_id: cell_id.to_string(),
|
||||
call_id,
|
||||
text,
|
||||
}),
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
fn cell_closed(&self, cell_id: &CellId) {
|
||||
if let Some(session) = self.session.upgrade() {
|
||||
session.close_cell(cell_id.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingToolCall {
|
||||
session: Arc<GrpcSession>,
|
||||
id: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl Drop for PendingToolCall {
|
||||
fn drop(&mut self) {
|
||||
if let Some(id) = self.id.take() {
|
||||
self.session.cancel_invocation(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
151
akode-rs/code-mode-host/src/grpc/events.rs
Normal file
151
akode-rs/code-mode-host/src/grpc/events.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use akode_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use prost::Message;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::TryAcquireError;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
use tonic::Status;
|
||||
|
||||
use crate::MAX_ACTIVE_CELLS;
|
||||
|
||||
const MAX_BUFFERED_CONTROL_EVENTS: usize = MAX_PENDING_DELEGATE_CALLS * 2 + MAX_ACTIVE_CELLS;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct EventSender {
|
||||
sender: mpsc::UnboundedSender<QueuedEvent>,
|
||||
permits: Arc<Semaphore>,
|
||||
closed: CancellationToken,
|
||||
writer: TaskTracker,
|
||||
}
|
||||
|
||||
struct QueuedEvent {
|
||||
message: proto::SessionEvent,
|
||||
_queue_permit: OwnedSemaphorePermit,
|
||||
_cell_permit: Option<OwnedSemaphorePermit>,
|
||||
}
|
||||
|
||||
impl EventSender {
|
||||
pub(super) fn new(
|
||||
output: mpsc::Sender<Result<proto::SessionEvent, Status>>,
|
||||
closed: CancellationToken,
|
||||
) -> Self {
|
||||
let (sender, mut receiver) = mpsc::unbounded_channel::<QueuedEvent>();
|
||||
let writer_closed = closed.clone();
|
||||
let writer = TaskTracker::new();
|
||||
writer.spawn(async move {
|
||||
loop {
|
||||
let event = tokio::select! {
|
||||
_ = writer_closed.cancelled() => return,
|
||||
event = receiver.recv() => match event {
|
||||
Some(event) => event,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let QueuedEvent {
|
||||
message,
|
||||
_queue_permit,
|
||||
_cell_permit,
|
||||
} = event;
|
||||
tokio::select! {
|
||||
_ = writer_closed.cancelled() => return,
|
||||
result = output.send(Ok(message)) => {
|
||||
if result.is_err() {
|
||||
writer_closed.cancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(_queue_permit);
|
||||
drop(_cell_permit);
|
||||
}
|
||||
});
|
||||
writer.close();
|
||||
Self {
|
||||
sender,
|
||||
permits: Arc::new(Semaphore::new(MAX_BUFFERED_CONTROL_EVENTS)),
|
||||
closed,
|
||||
writer,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn shutdown(&self) {
|
||||
self.closed.cancel();
|
||||
self.writer.wait().await;
|
||||
}
|
||||
|
||||
pub(super) async fn send(
|
||||
&self,
|
||||
event: proto::session_event::Event,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), String> {
|
||||
let message = validate_event(event)?;
|
||||
let permit = tokio::select! {
|
||||
biased;
|
||||
_ = self.closed.cancelled() => {
|
||||
return Err("code-mode session event stream is closed".to_string());
|
||||
}
|
||||
_ = cancellation.cancelled() => {
|
||||
return Err("code-mode session event was cancelled".to_string());
|
||||
}
|
||||
permit = Arc::clone(&self.permits).acquire_owned() => permit
|
||||
.map_err(|_| "code-mode session event queue is closed".to_string())?,
|
||||
};
|
||||
self.enqueue(message, permit, /*cell_permit*/ None)
|
||||
}
|
||||
|
||||
pub(super) fn send_now(
|
||||
&self,
|
||||
event: proto::session_event::Event,
|
||||
cell_permit: Option<OwnedSemaphorePermit>,
|
||||
) -> Result<(), String> {
|
||||
let message = validate_event(event)?;
|
||||
if self.closed.is_cancelled() {
|
||||
return Err("code-mode session event stream is closed".to_string());
|
||||
}
|
||||
match Arc::clone(&self.permits).try_acquire_owned() {
|
||||
Ok(permit) => self.enqueue(message, permit, cell_permit),
|
||||
Err(TryAcquireError::NoPermits) => {
|
||||
self.closed.cancel();
|
||||
Err("code-mode session event queue is full".to_string())
|
||||
}
|
||||
Err(TryAcquireError::Closed) => {
|
||||
self.closed.cancel();
|
||||
Err("code-mode session event queue is closed".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn enqueue(
|
||||
&self,
|
||||
message: proto::SessionEvent,
|
||||
permit: OwnedSemaphorePermit,
|
||||
cell_permit: Option<OwnedSemaphorePermit>,
|
||||
) -> Result<(), String> {
|
||||
self.sender
|
||||
.send(QueuedEvent {
|
||||
message,
|
||||
_queue_permit: permit,
|
||||
_cell_permit: cell_permit,
|
||||
})
|
||||
.map_err(|_| {
|
||||
self.closed.cancel();
|
||||
"code-mode session event stream is closed".to_string()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_event(event: proto::session_event::Event) -> Result<proto::SessionEvent, String> {
|
||||
let message = proto::SessionEvent { event: Some(event) };
|
||||
if message.encoded_len() > MAX_FRAME_BYTES {
|
||||
return Err(format!(
|
||||
"code-mode session event exceeds the {MAX_FRAME_BYTES}-byte gRPC message limit"
|
||||
));
|
||||
}
|
||||
Ok(message)
|
||||
}
|
||||
552
akode-rs/code-mode-host/src/grpc/mod.rs
Normal file
552
akode-rs/code-mode-host/src/grpc/mod.rs
Normal file
@@ -0,0 +1,552 @@
|
||||
mod conversions;
|
||||
mod delegate;
|
||||
mod events;
|
||||
mod routing;
|
||||
mod session;
|
||||
mod validation;
|
||||
mod waits;
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_code_mode_protocol::CellId;
|
||||
use akode_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use akode_code_mode_protocol::CodeModeSession;
|
||||
use akode_code_mode_protocol::CodeModeSessionOptions;
|
||||
use akode_code_mode_protocol::TerminateRequest;
|
||||
use akode_code_mode_protocol::WaitRequest;
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use akode_code_mode_protocol::host::LEGACY_MAX_PENDING_DELEGATE_CALLS;
|
||||
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use akode_protocol::protocol::W3cTraceContext;
|
||||
use futures::Stream;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tonic::Request;
|
||||
use tonic::Response;
|
||||
use tonic::Status;
|
||||
use tracing::Instrument;
|
||||
|
||||
use self::session::GrpcHostState;
|
||||
use self::session::GrpcSession;
|
||||
use self::waits::WaitRegistration;
|
||||
|
||||
type GrpcStream<T> = Pin<Box<dyn Stream<Item = Result<T, Status>> + Send + 'static>>;
|
||||
type GrpcFuture<'a, T> = Pin<Box<dyn Future<Output = Result<Response<T>, Status>> + Send + 'a>>;
|
||||
|
||||
fn trace_context_from_request<T>(request: &Request<T>) -> Option<W3cTraceContext> {
|
||||
request
|
||||
.metadata()
|
||||
.get("traceparent")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(|traceparent| W3cTraceContext {
|
||||
traceparent: Some(traceparent.to_string()),
|
||||
tracestate: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Serves transport-independent, leased code-mode sessions over gRPC.
|
||||
#[derive(Clone)]
|
||||
pub struct GrpcCodeModeHost {
|
||||
state: Arc<GrpcHostState>,
|
||||
process_metrics: Option<Arc<crate::process_metrics::ProcessMetrics>>,
|
||||
}
|
||||
|
||||
impl GrpcCodeModeHost {
|
||||
/// Creates a host with independent session, execution, and callback limits.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Arc::new(GrpcHostState::new()),
|
||||
process_metrics: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses a collector whose resources were prepared before sandbox entry.
|
||||
pub fn with_process_metrics(collector: crate::CodeModeProcessMetricsCollector) -> Self {
|
||||
Self {
|
||||
process_metrics: Some(Arc::new(crate::process_metrics::ProcessMetrics::new(
|
||||
collector,
|
||||
))),
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_session_request(
|
||||
&self,
|
||||
request: proto::OpenSessionRequest,
|
||||
) -> Result<Response<GrpcStream<proto::SessionEvent>>, Status> {
|
||||
let _permit = self.state.request_permit()?;
|
||||
let max_pending_delegate_calls = request
|
||||
.max_pending_delegate_calls
|
||||
.map(|limit| limit as usize)
|
||||
.unwrap_or(LEGACY_MAX_PENDING_DELEGATE_CALLS)
|
||||
.min(MAX_PENDING_DELEGATE_CALLS);
|
||||
if max_pending_delegate_calls == 0 {
|
||||
return Err(Status::invalid_argument(
|
||||
"callback capacity must be positive",
|
||||
));
|
||||
}
|
||||
let limits = conversions::session_limits(request.cell_execution_limits)?;
|
||||
let output_truncation = match request
|
||||
.output_truncation
|
||||
.map(proto::OutputTruncation::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| Status::invalid_argument("unknown code-mode output truncation mode"))?
|
||||
{
|
||||
None | Some(proto::OutputTruncation::Unspecified | proto::OutputTruncation::Client) => {
|
||||
CodeModeOutputTruncation::Client
|
||||
}
|
||||
Some(proto::OutputTruncation::Server) => CodeModeOutputTruncation::Server,
|
||||
};
|
||||
Ok(Response::new(self.state.open_session(
|
||||
CodeModeSessionOptions {
|
||||
cell_execution_limits: limits,
|
||||
output_truncation,
|
||||
},
|
||||
max_pending_delegate_calls,
|
||||
)?))
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.grpc.close_session",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
otel.name = "code_mode_host.grpc.close_session",
|
||||
session.id = %request.session_id,
|
||||
)
|
||||
)]
|
||||
async fn close_session_request(
|
||||
&self,
|
||||
request: proto::CloseSessionRequest,
|
||||
) -> Result<Response<proto::CloseSessionResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
self.state.close_session(&request.session_id).await?;
|
||||
Ok(Response::new(proto::CloseSessionResponse {}))
|
||||
}
|
||||
|
||||
async fn subscribe_request(
|
||||
&self,
|
||||
request: proto::SubscribeToToolCallsRequest,
|
||||
) -> Result<Response<GrpcStream<proto::ToolCall>>, Status> {
|
||||
let _permit = self.state.request_permit()?;
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
Ok(Response::new(session.subscribe(request.tool_names)?))
|
||||
}
|
||||
|
||||
async fn complete_tool_request(
|
||||
&self,
|
||||
request: proto::CompleteToolCallRequest,
|
||||
) -> Result<Response<proto::CompleteToolCallResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
let invocation_id = validation::uuid(&request.invocation_id, "tool invocation ID")?;
|
||||
let result = match request.outcome {
|
||||
Some(proto::complete_tool_call_request::Outcome::Succeeded(result)) => Ok(
|
||||
serde_json::from_slice(&result.output_json).map_err(|error| {
|
||||
Status::invalid_argument(format!("invalid code-mode tool output JSON: {error}"))
|
||||
})?,
|
||||
),
|
||||
Some(proto::complete_tool_call_request::Outcome::Failed(error)) => Err(error.message),
|
||||
None => {
|
||||
return Err(Status::invalid_argument(
|
||||
"tool completion is missing its outcome",
|
||||
));
|
||||
}
|
||||
};
|
||||
session.complete_invocation(invocation_id, result)?;
|
||||
Ok(Response::new(proto::CompleteToolCallResponse {}))
|
||||
}
|
||||
|
||||
async fn acknowledge_notification_request(
|
||||
&self,
|
||||
request: proto::AcknowledgeNotificationRequest,
|
||||
) -> Result<Response<proto::AcknowledgeNotificationResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
self.state.session(&request.session_id)?;
|
||||
validation::uuid(&request.notification_id, "notification ID")?;
|
||||
Ok(Response::new(proto::AcknowledgeNotificationResponse {}))
|
||||
}
|
||||
|
||||
async fn execute_request(
|
||||
&self,
|
||||
request: proto::ExecuteRequest,
|
||||
callback_traceparent: Option<String>,
|
||||
) -> Result<Response<GrpcStream<proto::ExecuteEvent>>, Status> {
|
||||
let received_at = Instant::now();
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
validation::identifier(&request.execution_id, "execution ID")?;
|
||||
let request_permit = self.state.request_permit()?;
|
||||
let execution_id = request.execution_id.clone();
|
||||
let request = conversions::execute_request(request)?;
|
||||
let cell_permit = self.state.cell_permit()?;
|
||||
let yield_signal = session.reserve_execution(&execution_id)?;
|
||||
let mut admission = ExecutionAdmission {
|
||||
session: Arc::clone(&session),
|
||||
execution_id: Some(execution_id.clone()),
|
||||
};
|
||||
let started = tokio::select! {
|
||||
_ = session.closed.cancelled() => {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
result = session.runtime.execute(request, Arc::new(delegate::GrpcDelegate::new(Arc::downgrade(&session))), Some(yield_signal)) => {
|
||||
result.map_err(Status::failed_precondition)?
|
||||
}
|
||||
};
|
||||
let cell_id = started.cell_id.clone();
|
||||
session.admit_execution(
|
||||
execution_id.clone(),
|
||||
cell_id.to_string(),
|
||||
cell_permit,
|
||||
callback_traceparent,
|
||||
)?;
|
||||
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 2);
|
||||
sender
|
||||
.try_send(Ok(proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Started(
|
||||
proto::ExecutionStarted {
|
||||
execution_id,
|
||||
cell_id: cell_id.to_string(),
|
||||
},
|
||||
)),
|
||||
}))
|
||||
.map_err(|_| Status::internal("failed to publish code-mode execution admission"))?;
|
||||
let outcome_span = tracing::Span::current();
|
||||
tokio::spawn(
|
||||
async move {
|
||||
let _request_permit = request_permit;
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = sender.closed() => {}
|
||||
response = started.initial_response() => {
|
||||
// Freeze timing before conversion or transport backpressure.
|
||||
let code_mode_host_duration = received_at.elapsed();
|
||||
let event = response.and_then(|response| {
|
||||
let response = response.with_code_mode_host_duration(code_mode_host_duration);
|
||||
let outcome = conversions::execution_outcome(response)
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Outcome(outcome)),
|
||||
})
|
||||
}).map_err(Status::internal);
|
||||
let _ = sender.send(event).await;
|
||||
}
|
||||
_ = session.closed.cancelled() => {}
|
||||
}
|
||||
}
|
||||
.instrument(outcome_span),
|
||||
);
|
||||
|
||||
let stream = ReceiverStream::new(receiver).inspect(move |event| {
|
||||
if matches!(
|
||||
event,
|
||||
Ok(proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Outcome(_)),
|
||||
})
|
||||
) {
|
||||
admission.disarm();
|
||||
}
|
||||
});
|
||||
Ok(Response::new(Box::pin(stream)))
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.grpc.wait",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
otel.name = "code_mode_host.grpc.wait",
|
||||
session.id = %request.session_id,
|
||||
cell.id = %request.cell_id,
|
||||
wait.id = %request.wait_id,
|
||||
)
|
||||
)]
|
||||
async fn wait_request(
|
||||
&self,
|
||||
request: proto::WaitRequest,
|
||||
) -> Result<Response<proto::WaitResponse>, Status> {
|
||||
let received_at = Instant::now();
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
validation::identifier(&request.cell_id, "cell ID")?;
|
||||
validation::identifier(&request.wait_id, "wait ID")?;
|
||||
let _permit = self.state.request_permit()?;
|
||||
let max_output_tokens = conversions::observation_budget(
|
||||
request.max_output_tokens,
|
||||
session.runtime.output_truncation(),
|
||||
)?;
|
||||
let registration = WaitRegistration::new(Arc::clone(&session), request.wait_id)?;
|
||||
let request = WaitRequest {
|
||||
cell_id: CellId::new(request.cell_id),
|
||||
yield_time_ms: request.yield_time_ms,
|
||||
max_output_tokens,
|
||||
};
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
_ = registration.cancellation().cancelled() => {
|
||||
return Err(Status::cancelled("code-mode wait was cancelled"));
|
||||
}
|
||||
_ = session.closed.cancelled() => {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
outcome = session.runtime.wait(request, Some(registration.yield_signal())) => {
|
||||
outcome.map_err(Status::failed_precondition)?
|
||||
}
|
||||
};
|
||||
let outcome = outcome.with_code_mode_host_duration(received_at.elapsed());
|
||||
conversions::wait_response(outcome).map_err(|error| Status::internal(error.to_string()))
|
||||
}
|
||||
|
||||
async fn cancel_wait_request(
|
||||
&self,
|
||||
request: proto::CancelWaitRequest,
|
||||
) -> Result<Response<proto::CancelWaitResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
validation::identifier(&request.wait_id, "wait ID")?;
|
||||
session.cancel_wait(&request.wait_id).await?;
|
||||
Ok(Response::new(proto::CancelWaitResponse {}))
|
||||
}
|
||||
|
||||
async fn yield_observation_request(
|
||||
&self,
|
||||
request: proto::YieldObservationRequest,
|
||||
) -> Result<Response<proto::YieldObservationResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
match request.observation {
|
||||
Some(proto::yield_observation_request::Observation::ExecutionId(id)) => {
|
||||
session.yield_execution(&id)?;
|
||||
}
|
||||
Some(proto::yield_observation_request::Observation::WaitId(id)) => {
|
||||
session.yield_wait(&id)?;
|
||||
}
|
||||
None => return Err(Status::invalid_argument("missing code-mode observation ID")),
|
||||
}
|
||||
Ok(Response::new(proto::YieldObservationResponse {}))
|
||||
}
|
||||
|
||||
async fn terminate_request(
|
||||
&self,
|
||||
request: proto::TerminateRequest,
|
||||
) -> Result<Response<proto::WaitResponse>, Status> {
|
||||
let received_at = Instant::now();
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
validation::identifier(&request.cell_id, "cell ID")?;
|
||||
let _permit = self.state.request_permit()?;
|
||||
let max_output_tokens = conversions::observation_budget(
|
||||
request.max_output_tokens,
|
||||
session.runtime.output_truncation(),
|
||||
)?;
|
||||
let outcome = session
|
||||
.terminate(TerminateRequest {
|
||||
cell_id: CellId::new(request.cell_id),
|
||||
max_output_tokens,
|
||||
})
|
||||
.await?;
|
||||
let outcome = outcome.with_code_mode_host_duration(received_at.elapsed());
|
||||
conversions::wait_response(outcome).map_err(|error| Status::internal(error.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GrpcCodeModeHost {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeModeHost for GrpcCodeModeHost {
|
||||
fn get_process_metrics<'a, 'async_trait>(
|
||||
&'a self,
|
||||
_request: Request<proto::GetProcessMetricsRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::GetProcessMetricsResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(async move {
|
||||
self.process_metrics
|
||||
.as_ref()
|
||||
.ok_or_else(|| Status::unimplemented("process metrics are unsupported"))?
|
||||
.sample()
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
type OpenSessionStream = GrpcStream<proto::SessionEvent>;
|
||||
type SubscribeToToolCallsStream = GrpcStream<proto::ToolCall>;
|
||||
type ExecuteStream = GrpcStream<proto::ExecuteEvent>;
|
||||
|
||||
fn open_session<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::OpenSessionRequest>,
|
||||
) -> GrpcFuture<'async_trait, Self::OpenSessionStream>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
let trace = trace_context_from_request(&request);
|
||||
let request = request.into_inner();
|
||||
let open_session_span = tracing::info_span!("code_mode_host.grpc.open_session");
|
||||
if let Some(trace) = trace.as_ref() {
|
||||
akode_otel::set_parent_from_w3c_trace_context(&open_session_span, trace);
|
||||
}
|
||||
Box::pin(
|
||||
self.open_session_request(request)
|
||||
.instrument(open_session_span),
|
||||
)
|
||||
}
|
||||
|
||||
fn close_session<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::CloseSessionRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::CloseSessionResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.close_session_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn subscribe_to_tool_calls<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::SubscribeToToolCallsRequest>,
|
||||
) -> GrpcFuture<'async_trait, Self::SubscribeToToolCallsStream>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.subscribe_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn complete_tool_call<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::CompleteToolCallRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::CompleteToolCallResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.complete_tool_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn acknowledge_notification<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::AcknowledgeNotificationRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::AcknowledgeNotificationResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.acknowledge_notification_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn execute<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::ExecuteRequest>,
|
||||
) -> GrpcFuture<'async_trait, Self::ExecuteStream>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
let trace = trace_context_from_request(&request);
|
||||
let request = request.into_inner();
|
||||
let execute_span = tracing::info_span!(
|
||||
"code_mode_host.grpc.execute",
|
||||
otel.name = "code_mode_host.grpc.execute",
|
||||
session.id = %request.session_id,
|
||||
execution.id = %request.execution_id,
|
||||
call_id = %request.tool_call_id,
|
||||
);
|
||||
if let Some(trace) = trace.as_ref() {
|
||||
akode_otel::set_parent_from_w3c_trace_context(&execute_span, trace);
|
||||
}
|
||||
let callback_traceparent =
|
||||
akode_otel::span_w3c_trace_context(&execute_span).and_then(|trace| trace.traceparent);
|
||||
Box::pin(
|
||||
self.execute_request(request, callback_traceparent)
|
||||
.instrument(execute_span),
|
||||
)
|
||||
}
|
||||
|
||||
fn wait<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::WaitRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::WaitResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.wait_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn cancel_wait<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::CancelWaitRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::CancelWaitResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.cancel_wait_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn yield_observation<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::YieldObservationRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::YieldObservationResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.yield_observation_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn terminate<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::TerminateRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::WaitResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.terminate_request(request.into_inner()))
|
||||
}
|
||||
}
|
||||
|
||||
struct ExecutionAdmission {
|
||||
session: Arc<GrpcSession>,
|
||||
execution_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ExecutionAdmission {
|
||||
fn disarm(&mut self) {
|
||||
if let Some(execution_id) = self.execution_id.take() {
|
||||
self.session.retire_execution_observation(&execution_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ExecutionAdmission {
|
||||
fn drop(&mut self) {
|
||||
if let Some(execution_id) = self.execution_id.take() {
|
||||
self.session.abandon_execution(&execution_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "service_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "robustness_tests.rs"]
|
||||
mod robustness_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "capacity_tests.rs"]
|
||||
mod capacity_tests;
|
||||
686
akode-rs/code-mode-host/src/grpc/robustness_tests.rs
Normal file
686
akode-rs/code-mode-host/src/grpc/robustness_tests.rs
Normal file
@@ -0,0 +1,686 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_code_mode_protocol::CellId;
|
||||
use akode_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use akode_code_mode_protocol::CodeModeToolKind;
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use akode_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use akode_protocol::ToolName;
|
||||
use futures::FutureExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::Code;
|
||||
use tonic::Request;
|
||||
use tonic::Status;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::ExecutionAdmission;
|
||||
use super::GrpcCodeModeHost;
|
||||
use super::tests::execute_events;
|
||||
use super::tests::execute_request;
|
||||
use super::tests::open_session;
|
||||
use super::tests::tool;
|
||||
use super::validation::MAX_IDENTIFIER_BYTES;
|
||||
use super::validation::MAX_TOOL_FILTERS;
|
||||
use crate::MAX_ACTIVE_CELLS;
|
||||
use crate::MAX_IN_FLIGHT_REQUESTS;
|
||||
use crate::OUTGOING_CHANNEL_CAPACITY;
|
||||
|
||||
fn assert_invalid<T>(result: Result<T, Status>) {
|
||||
match result {
|
||||
Ok(_) => panic!("expected an oversized gRPC field to be rejected"),
|
||||
Err(error) => assert_eq!(error.code(), Code::InvalidArgument),
|
||||
}
|
||||
}
|
||||
|
||||
fn invocation(cell_id: &str, name: &str) -> CodeModeNestedToolCall {
|
||||
CodeModeNestedToolCall {
|
||||
cell_id: CellId::new(cell_id.to_string()),
|
||||
runtime_tool_call_id: "runtime-call".to_string(),
|
||||
tool_name: ToolName::plain(name),
|
||||
tool_kind: CodeModeToolKind::Function,
|
||||
input: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_oversized_identifiers_and_subscription_filters() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let oversized_id = "x".repeat(MAX_IDENTIFIER_BYTES + 1);
|
||||
|
||||
assert_invalid(
|
||||
host.close_session(Request::new(proto::CloseSessionRequest {
|
||||
session_id: oversized_id.clone(),
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.close_session(Request::new(proto::CloseSessionRequest {
|
||||
session_id: "not-a-uuid".to_string(),
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.complete_tool_call(Request::new(proto::CompleteToolCallRequest {
|
||||
session_id: session_id.clone(),
|
||||
invocation_id: "not-a-uuid".to_string(),
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: b"null".to_vec(),
|
||||
},
|
||||
)),
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.acknowledge_notification(Request::new(proto::AcknowledgeNotificationRequest {
|
||||
session_id: session_id.clone(),
|
||||
notification_id: "not-a-uuid".to_string(),
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.execute(Request::new(execute_request(
|
||||
&session_id,
|
||||
&oversized_id,
|
||||
"text(\"hello\");",
|
||||
)))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: oversized_id,
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![
|
||||
proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: None,
|
||||
};
|
||||
MAX_TOOL_FILTERS + 1
|
||||
],
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
|
||||
assert!(host.state.session(&session_id).is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_execution_before_admission_releases_its_reservation() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
let execution_id = "execution-abandoned-before-admission".to_string();
|
||||
session
|
||||
.reserve_execution(&execution_id)
|
||||
.expect("reserve execution");
|
||||
|
||||
drop(ExecutionAdmission {
|
||||
session: Arc::clone(&session),
|
||||
execution_id: Some(execution_id.clone()),
|
||||
});
|
||||
|
||||
let error = session
|
||||
.admit_execution(
|
||||
execution_id,
|
||||
"cell".to_string(),
|
||||
host.state.cell_permit().expect("reserve cell permit"),
|
||||
/*traceparent*/ None,
|
||||
)
|
||||
.expect_err("abandoned execution must not admit a runtime cell");
|
||||
assert_eq!(error.code(), Code::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_an_unread_buffered_execution_outcome_retires_its_cell() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, mut events) = open_session(&host).await;
|
||||
let execution = host
|
||||
.execute(Request::new(execute_request(
|
||||
&session_id,
|
||||
"execution-abandoned",
|
||||
"await new Promise(() => {});",
|
||||
)))
|
||||
.await
|
||||
.expect("start execution")
|
||||
.into_inner();
|
||||
let _reserved_permits = (0..MAX_IN_FLIGHT_REQUESTS - 1)
|
||||
.map(|_| host.state.request_permit().expect("reserve request permit"))
|
||||
.collect::<Vec<_>>();
|
||||
let _execution_permit = tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async {
|
||||
loop {
|
||||
if let Ok(permit) = host.state.request_permit() {
|
||||
return permit;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("execution outcome should be buffered before dropping its unread stream");
|
||||
|
||||
drop(execution);
|
||||
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), events.next())
|
||||
.await
|
||||
.expect("abandoned cell should close")
|
||||
.expect("cell closed event")
|
||||
.expect("session event"),
|
||||
proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-abandoned".to_string(),
|
||||
cell_id: "1".to_string(),
|
||||
final_tool_call_sequence: 0,
|
||||
})),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_a_session_releases_buffered_cell_permits() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
let mut permits = (0..MAX_ACTIVE_CELLS)
|
||||
.map(|_| {
|
||||
host.state
|
||||
.cell_permit()
|
||||
.expect("reserve active-cell permit")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
session
|
||||
.send_event_now(
|
||||
proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-queued".to_string(),
|
||||
cell_id: "1".to_string(),
|
||||
final_tool_call_sequence: 0,
|
||||
}),
|
||||
permits.pop(),
|
||||
)
|
||||
.expect("queue cell closure");
|
||||
|
||||
host.close_session(Request::new(proto::CloseSessionRequest { session_id }))
|
||||
.await
|
||||
.expect("close session");
|
||||
|
||||
assert!(
|
||||
host.state.cell_permit().is_ok(),
|
||||
"closing a session must release its queued active-cell permits"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_a_lease_after_its_host_shuts_down_closes_the_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, lease) = open_session(&host).await;
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
|
||||
drop(host);
|
||||
drop(lease);
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), session.closed.cancelled())
|
||||
.await
|
||||
.expect("dropping a lease must close its session after the host disappears");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_closure_cancels_pending_termination() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-termination",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.expect("execution outcome").unwrap();
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
let termination = host.terminate(Request::new(proto::TerminateRequest {
|
||||
session_id,
|
||||
cell_id,
|
||||
max_output_tokens: None,
|
||||
}));
|
||||
tokio::pin!(termination);
|
||||
assert!(termination.as_mut().now_or_never().is_none());
|
||||
|
||||
session.closed.cancel();
|
||||
let error = termination
|
||||
.await
|
||||
.expect_err("closed sessions must bound termination");
|
||||
|
||||
assert_eq!(error.code(), Code::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_encoded_tool_invocation_fails_without_closing_its_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let mut subscription = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-oversized",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.unwrap().unwrap();
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
let cancellation = CancellationToken::new();
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
|
||||
let error = session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-oversized".to_string(),
|
||||
Uuid::new_v4(),
|
||||
Some(vec![0; MAX_FRAME_BYTES]),
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.contains("gRPC message limit"));
|
||||
assert!(host.state.session(&session_id).is_ok());
|
||||
assert!(!session.closed.is_cancelled());
|
||||
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
let invocation_id = Uuid::new_v4();
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-oversized".to_string(),
|
||||
invocation_id,
|
||||
Some(b"{}".to_vec()),
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let delivered = subscription.next().await.unwrap().unwrap();
|
||||
assert_eq!(delivered.invocation_id, invocation_id.to_string());
|
||||
assert_eq!(delivered.sequence, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unmatched_tool_subscription_fails_without_closing_its_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let _unrelated = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "other".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-unmatched",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.unwrap().unwrap();
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
let cancellation = CancellationToken::new();
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
|
||||
assert!(
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-unmatched".to_string(),
|
||||
Uuid::new_v4(),
|
||||
Some(b"{}".to_vec()),
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(host.state.session(&session_id).is_ok());
|
||||
assert!(!session.closed.is_cancelled());
|
||||
|
||||
let mut matching = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id,
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
let invocation_id = Uuid::new_v4();
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-unmatched".to_string(),
|
||||
invocation_id,
|
||||
Some(b"{}".to_vec()),
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let delivered = matching.next().await.unwrap().unwrap();
|
||||
assert_eq!(delivered.invocation_id, invocation_id.to_string());
|
||||
assert_eq!(delivered.sequence, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_selected_subscription_retries_another_matching_subscription() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let mut first = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.expect("subscribe first tool stream")
|
||||
.into_inner();
|
||||
let mut second = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.expect("subscribe second tool stream")
|
||||
.into_inner();
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-retry",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.expect("execution outcome").unwrap();
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
let subscriptions = session
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.subscriptions
|
||||
.iter()
|
||||
.map(|subscription| (subscription.id, subscription.sender.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
for (_, sender) in &subscriptions {
|
||||
for _ in 0..OUTGOING_CHANNEL_CAPACITY {
|
||||
sender
|
||||
.try_send(Ok(proto::ToolCall::default()))
|
||||
.expect("fill subscription queue");
|
||||
}
|
||||
}
|
||||
let cancellation = CancellationToken::new();
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
let invocation_id = Uuid::new_v4();
|
||||
let dispatch = session.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-retry".to_string(),
|
||||
invocation_id,
|
||||
/*input_json*/ None,
|
||||
response,
|
||||
&cancellation,
|
||||
);
|
||||
tokio::pin!(dispatch);
|
||||
assert!(dispatch.as_mut().now_or_never().is_none());
|
||||
session
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.subscriptions
|
||||
.retain(|subscription| subscription.id != subscriptions[0].0);
|
||||
|
||||
first.next().await.expect("free first reservation").unwrap();
|
||||
assert!(dispatch.as_mut().now_or_never().is_none());
|
||||
second
|
||||
.next()
|
||||
.await
|
||||
.expect("free surviving reservation")
|
||||
.unwrap();
|
||||
dispatch.await.expect("retry surviving subscription");
|
||||
|
||||
for _ in 1..OUTGOING_CHANNEL_CAPACITY {
|
||||
second.next().await.expect("drain buffered call").unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
second
|
||||
.next()
|
||||
.await
|
||||
.expect("retried invocation")
|
||||
.unwrap()
|
||||
.invocation_id,
|
||||
invocation_id.to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn saturated_subscription_does_not_block_independently_filtered_tools() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let mut slow = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "slow".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut fast = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "fast".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-backpressure",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.unwrap().unwrap();
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
let cancellation = CancellationToken::new();
|
||||
let mut responses = Vec::new();
|
||||
|
||||
for _ in 0..OUTGOING_CHANNEL_CAPACITY {
|
||||
let (response, receiver) = oneshot::channel();
|
||||
responses.push(receiver);
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "slow"),
|
||||
"execution-backpressure".to_string(),
|
||||
Uuid::new_v4(),
|
||||
/*input_json*/ None,
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let blocked_session = Arc::clone(&session);
|
||||
let blocked_cell = cell_id.clone();
|
||||
let blocked_cancellation = cancellation.clone();
|
||||
let (response, receiver) = oneshot::channel();
|
||||
responses.push(receiver);
|
||||
let blocked = tokio::spawn(async move {
|
||||
blocked_session
|
||||
.dispatch_tool(
|
||||
invocation(&blocked_cell, "slow"),
|
||||
"execution-backpressure".to_string(),
|
||||
Uuid::new_v4(),
|
||||
/*input_json*/ None,
|
||||
response,
|
||||
&blocked_cancellation,
|
||||
)
|
||||
.await
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!blocked.is_finished());
|
||||
|
||||
let (response, receiver) = oneshot::channel();
|
||||
responses.push(receiver);
|
||||
let invocation_id = Uuid::new_v4();
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
session.dispatch_tool(
|
||||
invocation(&cell_id, "fast"),
|
||||
"execution-backpressure".to_string(),
|
||||
invocation_id,
|
||||
/*input_json*/ None,
|
||||
response,
|
||||
&cancellation,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("saturated subscription must not block another tool")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fast.next().await.unwrap().unwrap().invocation_id,
|
||||
invocation_id.to_string()
|
||||
);
|
||||
|
||||
slow.next().await.unwrap().unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), blocked)
|
||||
.await
|
||||
.expect("draining the subscription should release its blocked invocation")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_subscriptions_only_retires_sessions_with_unread_calls() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let idle = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
drop(idle);
|
||||
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async {
|
||||
while !session.state.lock().unwrap().subscriptions.is_empty() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("idle subscription should be removed without retiring its session");
|
||||
assert!(host.state.session(&session_id).is_ok());
|
||||
|
||||
let first = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut second = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"execution-subscription-drop",
|
||||
r#"await tools.echo({attempt: 1});"#,
|
||||
);
|
||||
request.yield_time_ms = Some(/*value*/ 10_000);
|
||||
request.enabled_tools = vec![tool("echo")];
|
||||
let (_cell_id, mut execution) = execute_events(&host, request).await;
|
||||
let first_subscription_id = session.state.lock().unwrap().subscriptions[0].id;
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async {
|
||||
loop {
|
||||
let owned = session
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.pending_invocations
|
||||
.values()
|
||||
.any(|invocation| invocation.subscription_id == first_subscription_id);
|
||||
if owned {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("first subscription should own an unread tool call");
|
||||
drop(first);
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async {
|
||||
while host.state.session(&session_id).is_ok() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("losing an unread call must retire its lease without leaving a sequence gap");
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), second.next())
|
||||
.await
|
||||
.expect("other subscriptions should close with their lease")
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), execution.next())
|
||||
.await
|
||||
.expect("execution should retire with its lease")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
253
akode-rs/code-mode-host/src/grpc/routing.rs
Normal file
253
akode-rs/code-mode-host/src/grpc/routing.rs
Normal file
@@ -0,0 +1,253 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use akode_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use akode_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use akode_protocol::ToolName;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use prost::Message;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::Status;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::GrpcStream;
|
||||
use super::conversions;
|
||||
use super::session::GrpcSession;
|
||||
use super::session::PendingInvocation;
|
||||
use super::session::ToolSubscription;
|
||||
use super::validation;
|
||||
use crate::OUTGOING_CHANNEL_CAPACITY;
|
||||
|
||||
const MAX_SUBSCRIPTIONS: usize = 128;
|
||||
|
||||
impl GrpcSession {
|
||||
pub(super) fn subscribe(
|
||||
self: &Arc<Self>,
|
||||
filters: Vec<proto::ToolName>,
|
||||
) -> Result<GrpcStream<proto::ToolCall>, Status> {
|
||||
validation::tool_filters(&filters)?;
|
||||
let id = Uuid::new_v4();
|
||||
let (sender, receiver) = mpsc::channel(OUTGOING_CHANNEL_CAPACITY);
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if self.closed.is_cancelled() {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
if state.subscriptions.len() >= MAX_SUBSCRIPTIONS {
|
||||
return Err(Status::resource_exhausted(
|
||||
"code-mode session has too many tool subscriptions",
|
||||
));
|
||||
}
|
||||
state.subscriptions.push(ToolSubscription {
|
||||
id,
|
||||
filters,
|
||||
sender: sender.clone(),
|
||||
});
|
||||
drop(state);
|
||||
|
||||
let session = Arc::downgrade(self);
|
||||
let closed = self.closed.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = sender.closed() => {}
|
||||
_ = closed.cancelled() => return,
|
||||
}
|
||||
if let Some(session) = session.upgrade() {
|
||||
let abandoned = {
|
||||
let mut state = session.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
state
|
||||
.subscriptions
|
||||
.retain(|subscription| subscription.id != id);
|
||||
state
|
||||
.pending_invocations
|
||||
.extract_if(|_, invocation| invocation.subscription_id == id)
|
||||
.map(|(_, invocation)| invocation)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
if !abandoned.is_empty() {
|
||||
// A buffered call may never have reached the client. Closing
|
||||
// the lease avoids replaying a possibly delivered invocation
|
||||
// or leaving an unfillable execution-sequence gap.
|
||||
session.closed.cancel();
|
||||
}
|
||||
for invocation in abandoned {
|
||||
let _ = invocation.response.send(Err(
|
||||
"code-mode tool subscription closed before returning tool output"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Box::pin(ReceiverStream::new(receiver)))
|
||||
}
|
||||
|
||||
pub(super) async fn dispatch_tool(
|
||||
&self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
execution_id: String,
|
||||
invocation_id: Uuid,
|
||||
input_json: Option<Vec<u8>>,
|
||||
response: oneshot::Sender<Result<JsonValue, String>>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), String> {
|
||||
let cell_id = invocation.cell_id.to_string();
|
||||
let tool_name = proto::ToolName {
|
||||
name: invocation.tool_name.name,
|
||||
namespace: invocation.tool_name.namespace,
|
||||
};
|
||||
let canonical_tool_name =
|
||||
ToolName::new(tool_name.namespace.clone(), tool_name.name.clone())
|
||||
.with_default_namespace();
|
||||
let (sequence, traceparent, subscriptions) = {
|
||||
let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let Some(execution) = state.cells.get(&cell_id) else {
|
||||
return Err("code-mode cell closed before dispatching its tool call".to_string());
|
||||
};
|
||||
let sequence = execution.tool_call_sequence.checked_add(1).ok_or_else(|| {
|
||||
"code-mode execution tool-call sequence was exhausted".to_string()
|
||||
})?;
|
||||
let count = state.subscriptions.len();
|
||||
let subscriptions = (0..count)
|
||||
.map(|offset| &state.subscriptions[(state.next_subscription + offset) % count])
|
||||
.filter(|subscription| {
|
||||
subscription.filters.is_empty()
|
||||
|| subscription.filters.iter().any(|filter| {
|
||||
ToolName::new(filter.namespace.clone(), filter.name.clone())
|
||||
.with_default_namespace()
|
||||
== canonical_tool_name
|
||||
})
|
||||
})
|
||||
.map(|subscription| (subscription.id, subscription.sender.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
(sequence, execution.traceparent.clone(), subscriptions)
|
||||
};
|
||||
// The saved traceparent belongs to the outer execution. Prefer the runtime's
|
||||
// per-tool span so the callback is nested under its invocation, with the
|
||||
// execution context as a fallback when no current span context is available.
|
||||
let traceparent = akode_otel::current_span_w3c_trace_context()
|
||||
.and_then(|trace| trace.traceparent)
|
||||
.or(traceparent);
|
||||
if subscriptions.is_empty() {
|
||||
return Err("no code-mode tool subscription matches the requested tool".to_string());
|
||||
}
|
||||
let mut message = proto::ToolCall {
|
||||
session_id: self.id.to_string(),
|
||||
execution_id,
|
||||
cell_id: cell_id.clone(),
|
||||
invocation_id: invocation_id.to_string(),
|
||||
runtime_tool_call_id: invocation.runtime_tool_call_id,
|
||||
tool_name: Some(tool_name.clone()),
|
||||
tool_kind: conversions::tool_kind(invocation.tool_kind),
|
||||
input_json,
|
||||
sequence,
|
||||
traceparent,
|
||||
};
|
||||
if message.encoded_len() > MAX_FRAME_BYTES {
|
||||
return Err(format!(
|
||||
"code-mode tool invocation exceeds the {MAX_FRAME_BYTES}-byte gRPC message limit"
|
||||
));
|
||||
}
|
||||
|
||||
let mut reservations =
|
||||
subscriptions
|
||||
.into_iter()
|
||||
.map(|(id, sender)| async move {
|
||||
sender.reserve_owned().await.map(|permit| (id, permit))
|
||||
})
|
||||
.collect::<FuturesUnordered<_>>();
|
||||
loop {
|
||||
let (subscription_id, permit) = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => {
|
||||
return Err("code mode delegate request cancelled".to_string());
|
||||
}
|
||||
_ = self.closed.cancelled() => {
|
||||
return Err("code-mode session closed before dispatching its tool call".to_string());
|
||||
}
|
||||
reservation = reservations.next() => match reservation {
|
||||
Some(Ok(reservation)) => reservation,
|
||||
Some(Err(_)) => continue,
|
||||
None => {
|
||||
return Err("matching code-mode tool subscriptions are unavailable".to_string());
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let Some(subscription_index) = state.subscriptions.iter().position(|subscription| {
|
||||
subscription.id == subscription_id && !subscription.sender.is_closed()
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let Some(execution) = state.cells.get_mut(&cell_id) else {
|
||||
return Err("code-mode cell closed before dispatching its tool call".to_string());
|
||||
};
|
||||
let sequence = execution.tool_call_sequence.checked_add(1).ok_or_else(|| {
|
||||
"code-mode execution tool-call sequence was exhausted".to_string()
|
||||
})?;
|
||||
message.sequence = sequence;
|
||||
if message.encoded_len() > MAX_FRAME_BYTES {
|
||||
return Err(format!(
|
||||
"code-mode tool invocation exceeds the {MAX_FRAME_BYTES}-byte gRPC message limit"
|
||||
));
|
||||
}
|
||||
execution.tool_call_sequence = sequence;
|
||||
state.pending_invocations.insert(
|
||||
invocation_id,
|
||||
PendingInvocation {
|
||||
subscription_id,
|
||||
response,
|
||||
},
|
||||
);
|
||||
state.seen_invocations.remember(invocation_id);
|
||||
state.next_subscription = (subscription_index + 1) % state.subscriptions.len();
|
||||
permit.send(Ok(message));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn complete_invocation(
|
||||
&self,
|
||||
invocation_id: Uuid,
|
||||
result: Result<JsonValue, String>,
|
||||
) -> Result<(), Status> {
|
||||
let response = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match state.pending_invocations.remove(&invocation_id) {
|
||||
Some(invocation) => Some(invocation.response),
|
||||
None if state.seen_invocations.contains(&invocation_id) => None,
|
||||
None => {
|
||||
return Err(Status::not_found(format!(
|
||||
"unknown code-mode tool invocation {invocation_id}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(response) = response {
|
||||
let _ = response.send(result);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn cancel_invocation(&self, invocation_id: Uuid) {
|
||||
let pending = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.pending_invocations
|
||||
.remove(&invocation_id);
|
||||
if pending.is_some() {
|
||||
let _ = self.send_event_now(
|
||||
proto::session_event::Event::ToolCallCancelled(proto::ToolCallCancelled {
|
||||
invocation_id: invocation_id.to_string(),
|
||||
}),
|
||||
/*cell_permit*/ None,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
618
akode-rs/code-mode-host/src/grpc/service_tests.rs
Normal file
618
akode-rs/code-mode-host/src/grpc/service_tests.rs
Normal file
@@ -0,0 +1,618 @@
|
||||
use super::GrpcCodeModeHost;
|
||||
use super::GrpcStream;
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use futures::FutureExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tonic::Code;
|
||||
use tonic::Request;
|
||||
|
||||
pub(super) async fn open_session(
|
||||
host: &GrpcCodeModeHost,
|
||||
) -> (String, GrpcStream<proto::SessionEvent>) {
|
||||
let (opened, stream) = open_session_with_truncation(host, /*output_truncation*/ None).await;
|
||||
(opened.session_id, stream)
|
||||
}
|
||||
|
||||
async fn open_session_with_truncation(
|
||||
host: &GrpcCodeModeHost,
|
||||
output_truncation: Option<i32>,
|
||||
) -> (proto::SessionOpened, GrpcStream<proto::SessionEvent>) {
|
||||
let mut stream = host
|
||||
.open_session(Request::new(proto::OpenSessionRequest {
|
||||
max_pending_delegate_calls: None,
|
||||
cell_execution_limits: None,
|
||||
output_truncation,
|
||||
}))
|
||||
.await
|
||||
.expect("open code-mode session")
|
||||
.into_inner();
|
||||
let event = stream
|
||||
.next()
|
||||
.await
|
||||
.expect("session opened event")
|
||||
.expect("session event");
|
||||
let Some(proto::session_event::Event::Opened(opened)) = event.event else {
|
||||
panic!("expected the first session event to open its lease");
|
||||
};
|
||||
(opened, stream)
|
||||
}
|
||||
|
||||
pub(super) fn execute_request(
|
||||
session_id: &str,
|
||||
execution_id: &str,
|
||||
source: &str,
|
||||
) -> proto::ExecuteRequest {
|
||||
proto::ExecuteRequest {
|
||||
session_id: session_id.to_string(),
|
||||
execution_id: execution_id.to_string(),
|
||||
tool_call_id: "outer-call".to_string(),
|
||||
source: source.to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
yield_time_ms: Some(1),
|
||||
max_output_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tool(name: &str) -> proto::ToolDefinition {
|
||||
proto::ToolDefinition {
|
||||
name: name.to_string(),
|
||||
tool_name: Some(proto::ToolName {
|
||||
name: name.to_string(),
|
||||
namespace: None,
|
||||
}),
|
||||
description: String::new(),
|
||||
kind: proto::ToolKind::Function as i32,
|
||||
input_schema_json: None,
|
||||
output_schema_json: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn execute_events(
|
||||
host: &GrpcCodeModeHost,
|
||||
request: proto::ExecuteRequest,
|
||||
) -> (String, GrpcStream<proto::ExecuteEvent>) {
|
||||
let mut stream = host
|
||||
.execute(Request::new(request))
|
||||
.await
|
||||
.expect("execute cell")
|
||||
.into_inner();
|
||||
let event = stream
|
||||
.next()
|
||||
.await
|
||||
.expect("execution started event")
|
||||
.expect("execution event");
|
||||
let Some(proto::execute_event::Event::Started(started)) = event.event else {
|
||||
panic!("expected execution admission before its outcome");
|
||||
};
|
||||
(started.cell_id, stream)
|
||||
}
|
||||
|
||||
fn only_text(items: &[proto::ContentItem]) -> &str {
|
||||
let [
|
||||
proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Text(text)),
|
||||
},
|
||||
] = items
|
||||
else {
|
||||
panic!("expected one text item, got {items:?}");
|
||||
};
|
||||
&text.text
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn execute_stream_starts_immediately_and_wait_preserves_missing_cells() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, mut session_events) = open_session(&host).await;
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"execution-1",
|
||||
r#"text("before"); yield_control(); text("after");"#,
|
||||
);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
let (cell_id, mut execution) = execute_events(&host, request).await;
|
||||
|
||||
let yielded = execution.next().await.unwrap().unwrap();
|
||||
let Some(proto::execute_event::Event::Outcome(yielded_outcome)) = &yielded.event else {
|
||||
panic!("expected execution outcome");
|
||||
};
|
||||
assert_eq!(
|
||||
yielded,
|
||||
proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Outcome(
|
||||
proto::ExecutionOutcome {
|
||||
code_mode_host_duration_ns: yielded_outcome.code_mode_host_duration_ns,
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: vec![proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Text(proto::TextContent {
|
||||
text: "before".to_string(),
|
||||
})),
|
||||
}],
|
||||
outcome: Some(proto::execution_outcome::Outcome::Yielded(
|
||||
proto::ExecutionYielded {},
|
||||
)),
|
||||
}
|
||||
)),
|
||||
}
|
||||
);
|
||||
let completed = host
|
||||
.wait(Request::new(proto::WaitRequest {
|
||||
session_id: session_id.clone(),
|
||||
cell_id: cell_id.clone(),
|
||||
wait_id: "wait-1".to_string(),
|
||||
yield_time_ms: 60_000,
|
||||
max_output_tokens: None,
|
||||
}))
|
||||
.await
|
||||
.expect("wait for completion")
|
||||
.into_inner();
|
||||
let Some(proto::wait_response::State::LiveCell(completed_outcome)) = &completed.state else {
|
||||
panic!("expected live-cell wait outcome");
|
||||
};
|
||||
assert_eq!(
|
||||
completed,
|
||||
proto::WaitResponse {
|
||||
state: Some(proto::wait_response::State::LiveCell(
|
||||
proto::ExecutionOutcome {
|
||||
code_mode_host_duration_ns: completed_outcome.code_mode_host_duration_ns,
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: vec![proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Text(proto::TextContent {
|
||||
text: "after".to_string(),
|
||||
})),
|
||||
}],
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(
|
||||
proto::ExecutionCompleted { error_text: None },
|
||||
)),
|
||||
}
|
||||
)),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
session_events.next().await.unwrap().unwrap(),
|
||||
proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-1".to_string(),
|
||||
cell_id: cell_id.clone(),
|
||||
final_tool_call_sequence: 0,
|
||||
})),
|
||||
}
|
||||
);
|
||||
|
||||
let missing = host
|
||||
.wait(Request::new(proto::WaitRequest {
|
||||
session_id,
|
||||
cell_id: "missing-cell".to_string(),
|
||||
wait_id: "wait-missing".to_string(),
|
||||
yield_time_ms: 1,
|
||||
max_output_tokens: None,
|
||||
}))
|
||||
.await
|
||||
.expect("missing cells remain successful wait outcomes")
|
||||
.into_inner();
|
||||
assert!(matches!(
|
||||
missing.state,
|
||||
Some(proto::wait_response::State::MissingCell(_))
|
||||
));
|
||||
}
|
||||
|
||||
/// Missing, empty, and explicit default namespaces identify the same subscribed tool.
|
||||
#[tokio::test]
|
||||
async fn filtered_subscriptions_match_default_namespace_aliases() {
|
||||
let aliases = [
|
||||
(None, Some("functions".to_string())),
|
||||
(Some(String::new()), None),
|
||||
(Some("functions".to_string()), Some(String::new())),
|
||||
];
|
||||
|
||||
for (tool_namespace, filter_namespace) in aliases {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let mut subscription = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: filter_namespace,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.expect("subscribe with a default-namespace alias")
|
||||
.into_inner();
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"default-namespace",
|
||||
"text(await tools.echo({}));",
|
||||
);
|
||||
request.yield_time_ms = Some(/*value*/ 60_000);
|
||||
let mut enabled_tool = tool("echo");
|
||||
enabled_tool.tool_name = Some(proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: tool_namespace.clone(),
|
||||
});
|
||||
request.enabled_tools = vec![enabled_tool];
|
||||
let (_cell_id, mut execution) = execute_events(&host, request).await;
|
||||
|
||||
let invocation = subscription
|
||||
.next()
|
||||
.await
|
||||
.expect("matching default-namespace invocation")
|
||||
.expect("tool invocation");
|
||||
assert_eq!(
|
||||
invocation.tool_name,
|
||||
Some(proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: tool_namespace,
|
||||
})
|
||||
);
|
||||
host.complete_tool_call(Request::new(proto::CompleteToolCallRequest {
|
||||
session_id,
|
||||
invocation_id: invocation.invocation_id,
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: br#""done""#.to_vec(),
|
||||
},
|
||||
)),
|
||||
}))
|
||||
.await
|
||||
.expect("complete the matching tool call");
|
||||
assert!(matches!(
|
||||
execution.next().await,
|
||||
Some(Ok(proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Outcome(
|
||||
proto::ExecutionOutcome {
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(_)),
|
||||
..
|
||||
}
|
||||
)),
|
||||
}))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn filtered_subscriptions_receive_ordered_calls_and_unary_completions() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, mut session_events) = open_session(&host).await;
|
||||
let mut matching = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut unrelated = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "other".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"execution-tools",
|
||||
r#"text(await tools.echo({value: 1})); text(await tools.echo({value: 2}));"#,
|
||||
);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
request.enabled_tools = vec![tool("echo")];
|
||||
let (cell_id, mut execution) = execute_events(&host, request).await;
|
||||
|
||||
for sequence in [1, 2] {
|
||||
let invocation = matching.next().await.unwrap().unwrap();
|
||||
assert_eq!(invocation.session_id, session_id);
|
||||
assert_eq!(invocation.execution_id, "execution-tools");
|
||||
assert_eq!(invocation.cell_id, cell_id);
|
||||
assert_eq!(invocation.sequence, sequence);
|
||||
assert_eq!(
|
||||
invocation.input_json,
|
||||
Some(format!(r#"{{"value":{sequence}}}"#).into_bytes())
|
||||
);
|
||||
assert!(unrelated.next().now_or_never().is_none());
|
||||
host.complete_tool_call(Request::new(proto::CompleteToolCallRequest {
|
||||
session_id: session_id.clone(),
|
||||
invocation_id: invocation.invocation_id,
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: format!(r#""result-{sequence}""#).into_bytes(),
|
||||
},
|
||||
)),
|
||||
}))
|
||||
.await
|
||||
.expect("complete delegated tool");
|
||||
}
|
||||
|
||||
let outcome = execution.next().await.unwrap().unwrap();
|
||||
assert!(matches!(
|
||||
outcome.event,
|
||||
Some(proto::execute_event::Event::Outcome(
|
||||
proto::ExecutionOutcome {
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(_)),
|
||||
..
|
||||
}
|
||||
))
|
||||
));
|
||||
assert_eq!(
|
||||
session_events.next().await.unwrap().unwrap(),
|
||||
proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-tools".to_string(),
|
||||
cell_id,
|
||||
final_tool_call_sequence: 2,
|
||||
})),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_before_wait_admission_is_preserved() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-wait",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.unwrap().unwrap();
|
||||
|
||||
host.cancel_wait(Request::new(proto::CancelWaitRequest {
|
||||
session_id: session_id.clone(),
|
||||
wait_id: "pre-cancelled".to_string(),
|
||||
}))
|
||||
.await
|
||||
.expect("record cancellation before wait admission");
|
||||
let cancelled = host
|
||||
.wait(Request::new(proto::WaitRequest {
|
||||
session_id: session_id.clone(),
|
||||
cell_id: cell_id.clone(),
|
||||
wait_id: "pre-cancelled".to_string(),
|
||||
yield_time_ms: 60_000,
|
||||
max_output_tokens: Some(0),
|
||||
}))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(cancelled.code(), Code::Cancelled);
|
||||
|
||||
host.terminate(Request::new(proto::TerminateRequest {
|
||||
session_id,
|
||||
cell_id,
|
||||
max_output_tokens: Some(0),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn yield_before_observation_registration_is_remembered() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
for observation in [
|
||||
proto::yield_observation_request::Observation::ExecutionId("exec".to_string()),
|
||||
proto::yield_observation_request::Observation::WaitId("wait".to_string()),
|
||||
] {
|
||||
host.yield_observation(Request::new(proto::YieldObservationRequest {
|
||||
session_id: session_id.clone(),
|
||||
observation: Some(observation),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
assert!(session.reserve_execution("exec").unwrap().is_cancelled());
|
||||
let wait = super::waits::WaitRegistration::new(session, "wait".to_string()).unwrap();
|
||||
assert!(wait.yield_signal().is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notifications_do_not_delay_cell_completion() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, mut session_events) = open_session(&host).await;
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"execution-notify",
|
||||
r#"notify("pending"); text("done");"#,
|
||||
);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
let (cell_id, mut execution) = execute_events(&host, request).await;
|
||||
let event = session_events.next().await.unwrap().unwrap();
|
||||
let Some(proto::session_event::Event::Notification(notification)) = event.event else {
|
||||
panic!("expected pending notification");
|
||||
};
|
||||
assert_eq!(notification.execution_id, "execution-notify");
|
||||
assert_eq!(notification.cell_id, cell_id);
|
||||
assert_eq!(notification.call_id, "outer-call");
|
||||
assert_eq!(notification.text, "pending");
|
||||
assert!(matches!(
|
||||
execution.next().await.unwrap().unwrap().event,
|
||||
Some(proto::execute_event::Event::Outcome(
|
||||
proto::ExecutionOutcome {
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(_)),
|
||||
..
|
||||
}
|
||||
))
|
||||
));
|
||||
assert_eq!(
|
||||
session_events.next().await.unwrap().unwrap(),
|
||||
proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-notify".to_string(),
|
||||
cell_id,
|
||||
final_tool_call_sequence: 0,
|
||||
})),
|
||||
}
|
||||
);
|
||||
host.acknowledge_notification(Request::new(proto::AcknowledgeNotificationRequest {
|
||||
session_id,
|
||||
notification_id: notification.notification_id,
|
||||
}))
|
||||
.await
|
||||
.expect("legacy notification acknowledgments remain accepted");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn output_truncation_is_a_session_setting_and_omitting_it_keeps_legacy_output() {
|
||||
for (output_truncation, bounded_output) in [
|
||||
(None, false),
|
||||
(Some(proto::OutputTruncation::Unspecified.into()), false),
|
||||
(Some(proto::OutputTruncation::Client.into()), false),
|
||||
(Some(proto::OutputTruncation::Server.into()), true),
|
||||
] {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (opened, _lease) = open_session_with_truncation(&host, output_truncation).await;
|
||||
assert_eq!(
|
||||
opened.output_truncation,
|
||||
bounded_output.then_some(proto::OutputTruncation::Server.into()),
|
||||
);
|
||||
let mut request = execute_request(
|
||||
&opened.session_id,
|
||||
"execution",
|
||||
"text('x'.repeat(2 * 1024 * 1024));",
|
||||
);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
let (_, mut execution) = execute_events(&host, request).await;
|
||||
let outcome = execution
|
||||
.next()
|
||||
.await
|
||||
.expect("outcome event")
|
||||
.expect("outcome");
|
||||
let Some(proto::execute_event::Event::Outcome(outcome)) = outcome.event else {
|
||||
panic!("expected execution outcome");
|
||||
};
|
||||
assert!(matches!(
|
||||
outcome.outcome,
|
||||
Some(proto::execution_outcome::Outcome::Completed(_))
|
||||
));
|
||||
assert_eq!(
|
||||
outcome.content_items.iter().any(
|
||||
|item| matches!(&item.item, Some(proto::content_item::Item::Text(text))
|
||||
if text.text.starts_with("[Code Mode session output limit reached: omitted "))
|
||||
),
|
||||
bounded_output
|
||||
);
|
||||
if !bounded_output {
|
||||
assert_eq!(
|
||||
only_text(&outcome.content_items),
|
||||
"x".repeat(2 * 1024 * 1024)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_output_budgets_follow_exec_wait_and_terminate_over_grpc() {
|
||||
for (execution_id, after_yield) in [
|
||||
("failed", "throw '0123456789'.repeat(8);"),
|
||||
(
|
||||
"terminated",
|
||||
"text('0123456789'.repeat(8)); notify('ready to terminate'); await new Promise(() => {});",
|
||||
),
|
||||
] {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (opened, mut lease) =
|
||||
open_session_with_truncation(&host, Some(proto::OutputTruncation::Server.into())).await;
|
||||
let source = format!("text('0123456789'.repeat(4)); yield_control(); {after_yield}");
|
||||
let mut request = execute_request(&opened.session_id, execution_id, &source);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
request.max_output_tokens = Some(5);
|
||||
let (cell_id, mut execution) = execute_events(&host, request).await;
|
||||
let Some(proto::execute_event::Event::Outcome(first)) =
|
||||
execution.next().await.unwrap().unwrap().event
|
||||
else {
|
||||
panic!("expected execution outcome");
|
||||
};
|
||||
assert_eq!(first.cell_id, cell_id);
|
||||
assert!(matches!(
|
||||
first.outcome,
|
||||
Some(proto::execution_outcome::Outcome::Yielded(_))
|
||||
));
|
||||
assert_eq!(
|
||||
only_text(&first.content_items),
|
||||
"Warning: truncated output (original token count: 10)\nTotal output lines: 1\n\n0123456789…5 tokens truncated…0123456789"
|
||||
);
|
||||
|
||||
let response = if execution_id == "failed" {
|
||||
host.wait(Request::new(proto::WaitRequest {
|
||||
session_id: opened.session_id,
|
||||
cell_id: cell_id.clone(),
|
||||
wait_id: "wait-after-yield".to_string(),
|
||||
yield_time_ms: 60_000,
|
||||
max_output_tokens: Some(7),
|
||||
}))
|
||||
.await
|
||||
.expect("script failures are completed results, not RPC failures")
|
||||
.into_inner()
|
||||
} else {
|
||||
// The event is ordered after text in the runtime FIFO, so the
|
||||
// termination observes it without a sleep or racing the cell.
|
||||
assert!(matches!(
|
||||
lease.next().await.unwrap().unwrap().event,
|
||||
Some(proto::session_event::Event::Notification(
|
||||
proto::Notification { text, .. }
|
||||
)) if text == "ready to terminate"
|
||||
));
|
||||
host.terminate(Request::new(proto::TerminateRequest {
|
||||
session_id: opened.session_id,
|
||||
cell_id: cell_id.clone(),
|
||||
max_output_tokens: Some(7),
|
||||
}))
|
||||
.await
|
||||
.expect("terminate with an independent output budget")
|
||||
.into_inner()
|
||||
};
|
||||
let Some(proto::wait_response::State::LiveCell(last)) = response.state else {
|
||||
panic!("expected final observation from the live cell");
|
||||
};
|
||||
let expected_text = if execution_id == "failed" {
|
||||
let Some(proto::execution_outcome::Outcome::Completed(proto::ExecutionCompleted {
|
||||
error_text: Some(diagnostic),
|
||||
})) = &last.outcome
|
||||
else {
|
||||
panic!(
|
||||
"expected completed failure with a diagnostic, got {:?}",
|
||||
last.outcome
|
||||
);
|
||||
};
|
||||
assert_eq!(diagnostic, &"0123456789".repeat(8));
|
||||
"Warning: truncated output (original token count: 24)\nTotal output lines: 2\n\nScript error:\n…17 tokens truncated…67890123456789"
|
||||
} else {
|
||||
assert_eq!(
|
||||
last.outcome,
|
||||
Some(proto::execution_outcome::Outcome::Terminated(
|
||||
proto::ExecutionTerminated {}
|
||||
))
|
||||
);
|
||||
"Warning: truncated output (original token count: 20)\nTotal output lines: 1\n\n01234567890123…13 tokens truncated…67890123456789"
|
||||
};
|
||||
assert_eq!(last.cell_id, cell_id);
|
||||
assert_eq!(only_text(&last.content_items), expected_text);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_output_truncation_is_rejected_before_opening_a_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let result = host
|
||||
.open_session(Request::new(proto::OpenSessionRequest {
|
||||
max_pending_delegate_calls: None,
|
||||
cell_execution_limits: None,
|
||||
output_truncation: Some(42),
|
||||
}))
|
||||
.await;
|
||||
let Err(status) = result else {
|
||||
panic!("unknown truncation mode should be rejected");
|
||||
};
|
||||
assert_eq!(status.code(), Code::InvalidArgument);
|
||||
}
|
||||
487
akode-rs/code-mode-host/src/grpc/session.rs
Normal file
487
akode-rs/code-mode-host/src/grpc/session.rs
Normal file
@@ -0,0 +1,487 @@
|
||||
use std::borrow::Borrow;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::Weak;
|
||||
|
||||
use akode_code_mode_protocol::CellId;
|
||||
use akode_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use akode_code_mode_protocol::CodeModeSession;
|
||||
use akode_code_mode_protocol::CodeModeSessionOptions;
|
||||
use akode_code_mode_protocol::TerminateRequest;
|
||||
use akode_code_mode_protocol::WaitOutcome;
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use akode_code_mode_runtime::InProcessCodeModeSession;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::Status;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::GrpcStream;
|
||||
use super::events::EventSender;
|
||||
use super::validation;
|
||||
use super::waits::ActiveWait;
|
||||
use crate::HostLimits;
|
||||
use crate::MAX_ACTIVE_CELLS;
|
||||
use crate::MAX_IN_FLIGHT_REQUESTS;
|
||||
use crate::MAX_RECENT_REQUEST_IDS;
|
||||
use crate::OUTGOING_CHANNEL_CAPACITY;
|
||||
|
||||
pub(super) struct GrpcHostState {
|
||||
sessions: Mutex<HashMap<Uuid, Arc<GrpcSession>>>,
|
||||
limits: HostLimits,
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
control_permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
pub(super) struct GrpcSession {
|
||||
pub(super) id: Uuid,
|
||||
pub(super) runtime: Arc<InProcessCodeModeSession>,
|
||||
pub(super) closed: CancellationToken,
|
||||
pub(super) state: Mutex<SessionState>,
|
||||
events: EventSender,
|
||||
cells_changed: Notify,
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
client_delegate_permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SessionState {
|
||||
pub(super) cells: HashMap<String, ExecutionState>,
|
||||
pending_executions: HashSet<String>,
|
||||
pending_closures: HashSet<String>,
|
||||
pub(super) seen_executions: BoundedIds,
|
||||
pub(super) execution_yields: HashMap<String, CancellationToken>,
|
||||
pub(super) yielded_executions: BoundedIds,
|
||||
pub(super) subscriptions: Vec<ToolSubscription>,
|
||||
pub(super) next_subscription: usize,
|
||||
pub(super) pending_invocations: HashMap<Uuid, PendingInvocation>,
|
||||
pub(super) seen_invocations: BoundedIds<Uuid>,
|
||||
pub(super) waits: HashMap<String, ActiveWait>,
|
||||
pub(super) seen_waits: BoundedIds,
|
||||
pub(super) cancelled_waits: BoundedIds,
|
||||
pub(super) yielded_waits: BoundedIds,
|
||||
}
|
||||
|
||||
pub(super) struct ExecutionState {
|
||||
pub(super) execution_id: String,
|
||||
pub(super) traceparent: Option<String>,
|
||||
pub(super) tool_call_sequence: u64,
|
||||
permit: OwnedSemaphorePermit,
|
||||
}
|
||||
|
||||
pub(super) struct ToolSubscription {
|
||||
pub(super) id: Uuid,
|
||||
pub(super) filters: Vec<proto::ToolName>,
|
||||
pub(super) sender: mpsc::Sender<Result<proto::ToolCall, Status>>,
|
||||
}
|
||||
|
||||
pub(super) struct PendingInvocation {
|
||||
pub(super) subscription_id: Uuid,
|
||||
pub(super) response: oneshot::Sender<Result<JsonValue, String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BoundedIds<T = String> {
|
||||
ids: HashSet<T>,
|
||||
order: VecDeque<T>,
|
||||
}
|
||||
|
||||
impl GrpcHostState {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: HostLimits::new(),
|
||||
delegate_permits: Arc::new(Semaphore::new(MAX_PENDING_DELEGATE_CALLS)),
|
||||
control_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_REQUESTS)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open_session(
|
||||
self: &Arc<Self>,
|
||||
options: CodeModeSessionOptions,
|
||||
max_pending_delegate_calls: usize,
|
||||
) -> Result<GrpcStream<proto::SessionEvent>, Status> {
|
||||
let id = Uuid::new_v4();
|
||||
let (events, receiver) = mpsc::channel(OUTGOING_CHANNEL_CAPACITY);
|
||||
let closed = CancellationToken::new();
|
||||
let event_sender = EventSender::new(events.clone(), closed.clone());
|
||||
let session = GrpcSession::new(
|
||||
id,
|
||||
event_sender,
|
||||
closed,
|
||||
Arc::clone(&self.delegate_permits),
|
||||
options,
|
||||
max_pending_delegate_calls,
|
||||
);
|
||||
events
|
||||
.try_send(Ok(proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::Opened(proto::SessionOpened {
|
||||
session_id: id.to_string(),
|
||||
output_truncation: match session.runtime.output_truncation() {
|
||||
CodeModeOutputTruncation::Server => {
|
||||
Some(proto::OutputTruncation::Server.into())
|
||||
}
|
||||
CodeModeOutputTruncation::Client => None,
|
||||
},
|
||||
})),
|
||||
}))
|
||||
.map_err(|_| Status::internal("failed to publish the opened code-mode session"))?;
|
||||
let mut sessions = self.sessions.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
sessions.insert(id, Arc::clone(&session));
|
||||
drop(sessions);
|
||||
|
||||
let host = Arc::downgrade(self);
|
||||
tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = events.closed() => {}
|
||||
_ = session.closed.cancelled() => {}
|
||||
}
|
||||
if let Some(host) = host.upgrade() {
|
||||
host.close_lease(id, &session).await;
|
||||
} else {
|
||||
let _ = session.shutdown().await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Box::pin(ReceiverStream::new(receiver)))
|
||||
}
|
||||
|
||||
pub(super) fn session(&self, id: &str) -> Result<Arc<GrpcSession>, Status> {
|
||||
let session_id = validation::uuid(id, "session ID")?;
|
||||
self.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.get(&session_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| Status::not_found(format!("unknown code-mode session {id}")))
|
||||
}
|
||||
|
||||
pub(super) async fn close_session(&self, id: &str) -> Result<(), Status> {
|
||||
let session_id = validation::uuid(id, "session ID")?;
|
||||
let session = self
|
||||
.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&session_id)
|
||||
.ok_or_else(|| Status::not_found(format!("unknown code-mode session {id}")))?;
|
||||
session.shutdown().await
|
||||
}
|
||||
|
||||
async fn close_lease(&self, id: Uuid, expected: &Arc<GrpcSession>) {
|
||||
let session = {
|
||||
let mut sessions = self.sessions.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if sessions
|
||||
.get(&id)
|
||||
.is_some_and(|session| Arc::ptr_eq(session, expected))
|
||||
{
|
||||
sessions.remove(&id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(session) = session {
|
||||
let _ = session.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn request_permit(&self) -> Result<OwnedSemaphorePermit, Status> {
|
||||
self.limits.request_permit().map_err(|_| {
|
||||
Status::resource_exhausted("code-mode host has too many in-flight requests")
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cell_permit(&self) -> Result<OwnedSemaphorePermit, Status> {
|
||||
self.limits
|
||||
.cell_permit()
|
||||
.map_err(|_| Status::resource_exhausted("code-mode host has too many active cells"))
|
||||
}
|
||||
|
||||
pub(super) fn control_permit(&self) -> Result<OwnedSemaphorePermit, Status> {
|
||||
Arc::clone(&self.control_permits)
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| {
|
||||
Status::resource_exhausted("code-mode host has too many in-flight control requests")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl GrpcSession {
|
||||
fn new(
|
||||
id: Uuid,
|
||||
events: EventSender,
|
||||
closed: CancellationToken,
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
options: CodeModeSessionOptions,
|
||||
max_pending_delegate_calls: usize,
|
||||
) -> Arc<Self> {
|
||||
Arc::new_cyclic(|weak: &Weak<Self>| {
|
||||
let failure_session = weak.clone();
|
||||
let failure_handler = Arc::new(move |reason: String| {
|
||||
if let Some(session) = failure_session.upgrade() {
|
||||
tracing::warn!(session_id = %session.id, "code-mode host session failed: {reason}");
|
||||
session.closed.cancel();
|
||||
}
|
||||
});
|
||||
Self {
|
||||
id,
|
||||
runtime: Arc::new(InProcessCodeModeSession::with_options(
|
||||
options,
|
||||
Some(failure_handler),
|
||||
)),
|
||||
closed,
|
||||
state: Mutex::new(SessionState::default()),
|
||||
events,
|
||||
cells_changed: Notify::new(),
|
||||
delegate_permits,
|
||||
client_delegate_permits: Arc::new(Semaphore::new(max_pending_delegate_calls)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn shutdown(&self) -> Result<(), Status> {
|
||||
self.closed.cancel();
|
||||
{
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for wait in state.waits.values() {
|
||||
wait.cancellation.cancel();
|
||||
}
|
||||
state.pending_invocations.clear();
|
||||
state.subscriptions.clear();
|
||||
}
|
||||
let result = self.runtime.shutdown().await.map_err(Status::internal);
|
||||
self.events.shutdown().await;
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.cells
|
||||
.clear();
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) async fn terminate(&self, request: TerminateRequest) -> Result<WaitOutcome, Status> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.closed.cancelled() => {
|
||||
Err(Status::cancelled("code-mode session is closed"))
|
||||
}
|
||||
result = self.runtime.terminate(request) => {
|
||||
result.map_err(Status::failed_precondition)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn reserve_execution(
|
||||
&self,
|
||||
execution_id: &str,
|
||||
) -> Result<CancellationToken, Status> {
|
||||
validation::identifier(execution_id, "execution ID")?;
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if self.closed.is_cancelled() {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
if state.pending_executions.contains(execution_id)
|
||||
|| state
|
||||
.cells
|
||||
.values()
|
||||
.any(|execution| execution.execution_id == execution_id)
|
||||
|| !state.seen_executions.remember(execution_id.to_string())
|
||||
{
|
||||
return Err(Status::already_exists(format!(
|
||||
"code-mode execution ID `{execution_id}` was reused"
|
||||
)));
|
||||
}
|
||||
state.pending_executions.insert(execution_id.to_string());
|
||||
let yield_signal = CancellationToken::new();
|
||||
if state.yielded_executions.remove(execution_id) {
|
||||
yield_signal.cancel();
|
||||
}
|
||||
state
|
||||
.execution_yields
|
||||
.insert(execution_id.to_string(), yield_signal.clone());
|
||||
Ok(yield_signal)
|
||||
}
|
||||
|
||||
pub(super) fn admit_execution(
|
||||
&self,
|
||||
execution_id: String,
|
||||
cell_id: String,
|
||||
permit: OwnedSemaphorePermit,
|
||||
traceparent: Option<String>,
|
||||
) -> Result<(), Status> {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if !state.pending_executions.remove(&execution_id) {
|
||||
return Err(Status::cancelled("code-mode execution was abandoned"));
|
||||
}
|
||||
let Entry::Vacant(entry) = state.cells.entry(cell_id.clone()) else {
|
||||
return Err(Status::internal(
|
||||
"code-mode runtime reused an active cell ID",
|
||||
));
|
||||
};
|
||||
entry.insert(ExecutionState {
|
||||
execution_id,
|
||||
traceparent,
|
||||
tool_call_sequence: 0,
|
||||
permit,
|
||||
});
|
||||
let closed = state.pending_closures.remove(&cell_id);
|
||||
let closed_execution = closed.then(|| state.cells.remove(&cell_id)).flatten();
|
||||
drop(state);
|
||||
self.cells_changed.notify_waiters();
|
||||
if let Some(execution) = closed_execution {
|
||||
self.send_cell_closed(&cell_id, execution);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn abandon_execution(self: &Arc<Self>, execution_id: &str) {
|
||||
let cell_id = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
state.pending_executions.remove(execution_id);
|
||||
state.execution_yields.remove(execution_id);
|
||||
state
|
||||
.cells
|
||||
.iter()
|
||||
.find(|(_, execution)| execution.execution_id == execution_id)
|
||||
.map(|(cell_id, _)| cell_id.clone())
|
||||
};
|
||||
if let Some(cell_id) = cell_id {
|
||||
let session = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
let _ = session.terminate(CellId::new(cell_id).into()).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn execution_id(
|
||||
&self,
|
||||
cell_id: &str,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<String, String> {
|
||||
loop {
|
||||
let changed = self.cells_changed.notified();
|
||||
if let Some(execution_id) = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.cells
|
||||
.get(cell_id)
|
||||
.map(|execution| execution.execution_id.clone())
|
||||
{
|
||||
return Ok(execution_id);
|
||||
}
|
||||
tokio::select! {
|
||||
_ = self.closed.cancelled() => {
|
||||
return Err("code-mode session closed before cell admission".to_string());
|
||||
}
|
||||
_ = cancellation.cancelled() => {
|
||||
return Err("code-mode callback was cancelled before cell admission".to_string());
|
||||
}
|
||||
_ = changed => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn close_cell(&self, cell_id: &str) {
|
||||
let execution = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match state.cells.remove(cell_id) {
|
||||
Some(execution) => Some(execution),
|
||||
None if state.pending_closures.len() < MAX_ACTIVE_CELLS => {
|
||||
state.pending_closures.insert(cell_id.to_string());
|
||||
None
|
||||
}
|
||||
None => {
|
||||
self.closed.cancel();
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(execution) = execution {
|
||||
self.send_cell_closed(cell_id, execution);
|
||||
}
|
||||
}
|
||||
|
||||
fn send_cell_closed(&self, cell_id: &str, execution: ExecutionState) {
|
||||
let _ = self.send_event_now(
|
||||
proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: execution.execution_id,
|
||||
cell_id: cell_id.to_string(),
|
||||
final_tool_call_sequence: execution.tool_call_sequence,
|
||||
}),
|
||||
Some(execution.permit),
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn delegate_permit(&self) -> Result<[OwnedSemaphorePermit; 2], String> {
|
||||
let client = Arc::clone(&self.client_delegate_permits)
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| "code-mode session has too many pending delegate calls".to_string())?;
|
||||
let host = Arc::clone(&self.delegate_permits)
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| "code-mode host has too many pending delegate calls".to_string())?;
|
||||
Ok([client, host])
|
||||
}
|
||||
|
||||
pub(super) async fn send_event(
|
||||
&self,
|
||||
event: proto::session_event::Event,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), String> {
|
||||
self.events.send(event, cancellation).await
|
||||
}
|
||||
|
||||
pub(super) fn send_event_now(
|
||||
&self,
|
||||
event: proto::session_event::Event,
|
||||
cell_permit: Option<OwnedSemaphorePermit>,
|
||||
) -> Result<(), String> {
|
||||
self.events.send_now(event, cell_permit)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> BoundedIds<T>
|
||||
where
|
||||
T: Clone + Eq + Hash,
|
||||
{
|
||||
pub(super) fn remember(&mut self, id: T) -> bool {
|
||||
if !self.ids.insert(id.clone()) {
|
||||
return false;
|
||||
}
|
||||
self.order.push_back(id);
|
||||
while self.order.len() > MAX_RECENT_REQUEST_IDS {
|
||||
if let Some(expired) = self.order.pop_front() {
|
||||
self.ids.remove(&expired);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn contains<Q>(&self, id: &Q) -> bool
|
||||
where
|
||||
T: Borrow<Q>,
|
||||
Q: Eq + Hash + ?Sized,
|
||||
{
|
||||
self.ids.contains(id)
|
||||
}
|
||||
|
||||
pub(super) fn remove<Q>(&mut self, id: &Q) -> bool
|
||||
where
|
||||
T: Borrow<Q>,
|
||||
Q: Eq + Hash + ?Sized,
|
||||
{
|
||||
self.ids.remove(id)
|
||||
}
|
||||
}
|
||||
50
akode-rs/code-mode-host/src/grpc/validation.rs
Normal file
50
akode-rs/code-mode-host/src/grpc/validation.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use akode_code_mode_protocol::grpc as proto;
|
||||
use tonic::Status;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) use akode_code_mode_protocol::grpc::MAX_IDENTIFIER_BYTES;
|
||||
pub(super) const MAX_TOOL_FILTERS: usize = 64;
|
||||
|
||||
pub(super) fn identifier(value: &str, field: &str) -> Result<(), Status> {
|
||||
if value.is_empty() {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"code-mode {field} must not be empty"
|
||||
)));
|
||||
}
|
||||
bounded(value, MAX_IDENTIFIER_BYTES, field)
|
||||
}
|
||||
|
||||
pub(super) fn uuid(value: &str, field: &str) -> Result<Uuid, Status> {
|
||||
identifier(value, field)?;
|
||||
Uuid::parse_str(value)
|
||||
.map_err(|_| Status::invalid_argument(format!("code-mode {field} must be a UUID")))
|
||||
}
|
||||
|
||||
pub(super) fn bounded(value: &str, maximum: usize, field: &str) -> Result<(), Status> {
|
||||
if value.len() > maximum {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"code-mode {field} exceeds {maximum} bytes"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn tool_name(name: &proto::ToolName) -> Result<(), Status> {
|
||||
identifier(&name.name, "tool name")?;
|
||||
if let Some(namespace) = name.namespace.as_deref() {
|
||||
bounded(namespace, MAX_IDENTIFIER_BYTES, "tool namespace")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn tool_filters(filters: &[proto::ToolName]) -> Result<(), Status> {
|
||||
if filters.len() > MAX_TOOL_FILTERS {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"code-mode tool subscription exceeds {MAX_TOOL_FILTERS} filters"
|
||||
)));
|
||||
}
|
||||
for filter in filters {
|
||||
tool_name(filter)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
135
akode-rs/code-mode-host/src/grpc/waits.rs
Normal file
135
akode-rs/code-mode-host/src/grpc/waits.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::Status;
|
||||
|
||||
use super::session::GrpcSession;
|
||||
use super::validation;
|
||||
|
||||
pub(super) struct ActiveWait {
|
||||
pub(super) cancellation: CancellationToken,
|
||||
pub(super) yield_signal: CancellationToken,
|
||||
retired: CancellationToken,
|
||||
}
|
||||
|
||||
pub(super) struct WaitRegistration {
|
||||
session: Arc<GrpcSession>,
|
||||
id: String,
|
||||
cancellation: CancellationToken,
|
||||
yield_signal: CancellationToken,
|
||||
retired: CancellationToken,
|
||||
}
|
||||
|
||||
impl WaitRegistration {
|
||||
pub(super) fn new(session: Arc<GrpcSession>, id: String) -> Result<Self, Status> {
|
||||
validation::identifier(&id, "wait ID")?;
|
||||
let cancellation = CancellationToken::new();
|
||||
let yield_signal = CancellationToken::new();
|
||||
let retired = CancellationToken::new();
|
||||
let mut state = session.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if session.closed.is_cancelled() {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
if state.waits.contains_key(&id) || !state.seen_waits.remember(id.clone()) {
|
||||
return Err(Status::already_exists(format!(
|
||||
"code-mode wait ID `{id}` was reused"
|
||||
)));
|
||||
}
|
||||
if state.cancelled_waits.remove(&id) {
|
||||
state.yielded_waits.remove(&id);
|
||||
return Err(Status::cancelled("code-mode wait was cancelled"));
|
||||
}
|
||||
if state.yielded_waits.remove(&id) {
|
||||
yield_signal.cancel();
|
||||
}
|
||||
state.waits.insert(
|
||||
id.clone(),
|
||||
ActiveWait {
|
||||
cancellation: cancellation.clone(),
|
||||
yield_signal: yield_signal.clone(),
|
||||
retired: retired.clone(),
|
||||
},
|
||||
);
|
||||
drop(state);
|
||||
Ok(Self {
|
||||
session,
|
||||
id,
|
||||
cancellation,
|
||||
yield_signal,
|
||||
retired,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cancellation(&self) -> &CancellationToken {
|
||||
&self.cancellation
|
||||
}
|
||||
|
||||
pub(super) fn yield_signal(&self) -> CancellationToken {
|
||||
self.yield_signal.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WaitRegistration {
|
||||
fn drop(&mut self) {
|
||||
self.session
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.waits
|
||||
.remove(&self.id);
|
||||
self.retired.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl GrpcSession {
|
||||
pub(super) fn yield_execution(&self, id: &str) -> Result<(), Status> {
|
||||
validation::identifier(id, "execution ID")?;
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(signal) = state.execution_yields.get(id) {
|
||||
signal.cancel();
|
||||
} else if !state.seen_executions.contains(id) {
|
||||
state.yielded_executions.remember(id.to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn yield_wait(&self, id: &str) -> Result<(), Status> {
|
||||
validation::identifier(id, "wait ID")?;
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(wait) = state.waits.get(id) {
|
||||
wait.yield_signal.cancel();
|
||||
} else if !state.seen_waits.contains(id) {
|
||||
state.yielded_waits.remember(id.to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn retire_execution_observation(&self, id: &str) {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.execution_yields
|
||||
.remove(id);
|
||||
}
|
||||
|
||||
pub(super) async fn cancel_wait(&self, id: &str) -> Result<(), Status> {
|
||||
validation::identifier(id, "wait ID")?;
|
||||
let active = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(wait) = state.waits.get(id) {
|
||||
Some((wait.cancellation.clone(), wait.retired.clone()))
|
||||
} else {
|
||||
if !state.seen_waits.contains(id) {
|
||||
state.cancelled_waits.remember(id.to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some((cancellation, retired)) = active {
|
||||
cancellation.cancel();
|
||||
retired.cancelled().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
88
akode-rs/code-mode-host/src/grpc_stdio.rs
Normal file
88
akode-rs/code-mode-host/src/grpc_stdio.rs
Normal file
@@ -0,0 +1,88 @@
|
||||
//! Serves one HTTP/2 gRPC connection on stdin/stdout. Stdout contains only protocol
|
||||
//! bytes, and closing the connection stops the host rather than accepting another client.
|
||||
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_server::CodeModeHostServer;
|
||||
use akode_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use futures::StreamExt;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::io::ReadBuf;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::transport::Server;
|
||||
use tonic::transport::server::Connected;
|
||||
|
||||
use crate::GrpcCodeModeHost;
|
||||
|
||||
pub(crate) async fn run(host: GrpcCodeModeHost) -> Result<()> {
|
||||
let closed = CancellationToken::new();
|
||||
let connection = StdioConnection {
|
||||
io: tokio::io::join(tokio::io::stdin(), tokio::io::stdout()),
|
||||
closed: closed.clone(),
|
||||
};
|
||||
// Keep the incoming stream open while the single connection is being served.
|
||||
let incoming = futures::stream::once(async { Ok::<_, io::Error>(connection) })
|
||||
.chain(futures::stream::pending());
|
||||
let server = Server::builder()
|
||||
.add_service(
|
||||
CodeModeHostServer::new(host)
|
||||
.max_decoding_message_size(MAX_FRAME_BYTES)
|
||||
.max_encoding_message_size(MAX_FRAME_BYTES),
|
||||
)
|
||||
.serve_with_incoming(incoming);
|
||||
tokio::select! {
|
||||
result = server => result.context("code-mode gRPC stdio connection failed"),
|
||||
_ = closed.cancelled() => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
struct StdioConnection {
|
||||
io: tokio::io::Join<tokio::io::Stdin, tokio::io::Stdout>,
|
||||
closed: CancellationToken,
|
||||
}
|
||||
|
||||
impl Connected for StdioConnection {
|
||||
type ConnectInfo = ();
|
||||
|
||||
fn connect_info(&self) -> Self::ConnectInfo {}
|
||||
}
|
||||
|
||||
impl AsyncRead for StdioConnection {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for StdioConnection {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.io).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StdioConnection {
|
||||
fn drop(&mut self) {
|
||||
self.closed.cancel();
|
||||
}
|
||||
}
|
||||
71
akode-rs/code-mode-host/src/grpc_transport.rs
Normal file
71
akode-rs/code-mode-host/src/grpc_transport.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use std::io;
|
||||
use std::io::Write as _;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use axum::extract::Request;
|
||||
use axum::http::Method;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::Version;
|
||||
use axum::middleware;
|
||||
use axum::middleware::Next;
|
||||
use axum::routing::get;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_server::CodeModeHostServer;
|
||||
use akode_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use tokio::net::TcpListener;
|
||||
use tonic::service::Routes;
|
||||
use tonic::transport::Server;
|
||||
use tonic::transport::server::TcpIncoming;
|
||||
use tracing::info;
|
||||
|
||||
use crate::GrpcCodeModeHost;
|
||||
|
||||
pub(super) async fn run_tcp_listener(
|
||||
bind_address: SocketAddr,
|
||||
host: GrpcCodeModeHost,
|
||||
) -> Result<()> {
|
||||
let listener = bind_tcp_listener(bind_address).await?;
|
||||
let local_address = listener
|
||||
.local_addr()
|
||||
.context("failed to read code-mode gRPC listen address")?;
|
||||
info!("akode-code-mode-host listening on http://{local_address}");
|
||||
println!("http://{local_address}");
|
||||
io::stdout()
|
||||
.flush()
|
||||
.context("failed to publish code-mode gRPC listen address")?;
|
||||
|
||||
let routes = Routes::new(
|
||||
CodeModeHostServer::new(host)
|
||||
.send_compressed(tonic::codec::CompressionEncoding::Zstd)
|
||||
.max_decoding_message_size(MAX_FRAME_BYTES)
|
||||
.max_encoding_message_size(MAX_FRAME_BYTES),
|
||||
)
|
||||
.into_axum_router()
|
||||
.route("/healthz", get(|| async { StatusCode::OK }))
|
||||
.layer(middleware::from_fn(
|
||||
|request: Request, next: Next| async move {
|
||||
if request.version() != Version::HTTP_2
|
||||
&& (request.method() != Method::GET || request.uri().path() != "/healthz")
|
||||
{
|
||||
return Err(StatusCode::HTTP_VERSION_NOT_SUPPORTED);
|
||||
}
|
||||
|
||||
Ok(next.run(request).await)
|
||||
},
|
||||
));
|
||||
|
||||
Server::builder()
|
||||
.accept_http1(/*accept_http1*/ true)
|
||||
.add_routes(routes.into())
|
||||
.serve_with_incoming(listener)
|
||||
.await
|
||||
.context("code-mode gRPC TCP listener failed")
|
||||
}
|
||||
|
||||
pub(super) async fn bind_tcp_listener(bind_address: SocketAddr) -> Result<TcpIncoming> {
|
||||
let listener = TcpListener::bind(bind_address)
|
||||
.await
|
||||
.with_context(|| format!("failed to bind code-mode gRPC host to {bind_address}"))?;
|
||||
Ok(TcpIncoming::from(listener).with_nodelay(Some(true)))
|
||||
}
|
||||
816
akode-rs/code-mode-host/src/host_tests.rs
Normal file
816
akode-rs/code-mode-host/src/host_tests.rs
Normal file
@@ -0,0 +1,816 @@
|
||||
use std::collections::HashMap;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_code_mode_protocol::CodeModeSessionOptions;
|
||||
use akode_code_mode_protocol::TerminateRequest;
|
||||
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_CAPABILITY;
|
||||
use akode_code_mode_protocol::host::Capability;
|
||||
use akode_code_mode_protocol::host::CapabilitySet;
|
||||
use akode_code_mode_protocol::host::ClientHello;
|
||||
use akode_code_mode_protocol::host::ClientToHost;
|
||||
use akode_code_mode_protocol::host::EncodedFrame;
|
||||
use akode_code_mode_protocol::host::FramedReader;
|
||||
use akode_code_mode_protocol::host::FramedWriter;
|
||||
use akode_code_mode_protocol::host::HandshakeRejectReason;
|
||||
use akode_code_mode_protocol::host::HostHello;
|
||||
use akode_code_mode_protocol::host::HostRequest;
|
||||
use akode_code_mode_protocol::host::HostResponse;
|
||||
use akode_code_mode_protocol::host::HostToClient;
|
||||
use akode_code_mode_protocol::host::LARGE_DELEGATE_CAPACITY_CAPABILITY;
|
||||
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use akode_code_mode_protocol::host::ProtocolVersion;
|
||||
use akode_code_mode_protocol::host::RequestId;
|
||||
use akode_code_mode_protocol::host::SESSION_RESOURCE_LIMITS_CAPABILITY;
|
||||
use akode_code_mode_protocol::host::SessionId;
|
||||
use akode_code_mode_protocol::host::SupportedProtocolVersions;
|
||||
use akode_code_mode_protocol::host::WireContentItem;
|
||||
use akode_code_mode_protocol::host::WireExecuteRequest;
|
||||
use akode_code_mode_protocol::host::WireOutputTruncation;
|
||||
use akode_code_mode_protocol::host::WireResult;
|
||||
use akode_code_mode_protocol::host::WireRuntimeResponse;
|
||||
use akode_code_mode_protocol::host::WireWaitOutcome;
|
||||
use akode_code_mode_protocol::host::WireWaitRequest;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
use super::HostLimits;
|
||||
use super::HostState;
|
||||
use super::MAX_IN_FLIGHT_REQUESTS;
|
||||
use super::MAX_RECENT_REQUEST_IDS;
|
||||
use super::RequestKind;
|
||||
use super::RequestRegistry;
|
||||
use super::SeenSessionIds;
|
||||
use super::peer::HostPeer;
|
||||
use super::run;
|
||||
|
||||
fn client_hello(
|
||||
versions: impl IntoIterator<Item = ProtocolVersion>,
|
||||
required_capabilities: CapabilitySet,
|
||||
) -> ClientToHost {
|
||||
ClientToHost::ClientHello(
|
||||
ClientHello::new(
|
||||
SupportedProtocolVersions::try_new(versions).expect("supported versions"),
|
||||
required_capabilities,
|
||||
CapabilitySet::empty(),
|
||||
)
|
||||
.expect("client hello"),
|
||||
)
|
||||
}
|
||||
|
||||
fn session_id(value: &str) -> SessionId {
|
||||
SessionId::new(value).expect("session ID")
|
||||
}
|
||||
|
||||
fn request_id(value: i64) -> RequestId {
|
||||
RequestId::new(value)
|
||||
}
|
||||
|
||||
async fn decode_frame(frame: EncodedFrame) -> HostToClient {
|
||||
let (reader, writer) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let writer = tokio::spawn(async move {
|
||||
FramedWriter::new(writer)
|
||||
.write_frame(&frame)
|
||||
.await
|
||||
.expect("write encoded frame");
|
||||
});
|
||||
let message = FramedReader::new(reader)
|
||||
.read()
|
||||
.await
|
||||
.expect("read encoded frame")
|
||||
.expect("encoded frame message");
|
||||
writer.await.expect("frame writer task");
|
||||
message
|
||||
}
|
||||
|
||||
fn execute_request(source: &str) -> WireExecuteRequest {
|
||||
WireExecuteRequest {
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: source.to_string(),
|
||||
yield_time_ms: Some(60_000),
|
||||
max_output_tokens: Some(1_000),
|
||||
}
|
||||
}
|
||||
|
||||
async fn next_response(reader: &mut FramedReader<impl AsyncRead + Unpin>) -> HostToClient {
|
||||
loop {
|
||||
match reader
|
||||
.read()
|
||||
.await
|
||||
.expect("host response")
|
||||
.expect("host connected")
|
||||
{
|
||||
HostToClient::CellClosed { .. } => {}
|
||||
message => return message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handshake_and_multiple_session_lifecycles_are_ordered() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("read hello"),
|
||||
Some(HostToClient::HostHello(HostHello::new(
|
||||
ProtocolVersion::V1,
|
||||
CapabilitySet::empty(),
|
||||
)))
|
||||
);
|
||||
|
||||
for (request_id, id) in [
|
||||
(request_id(/*value*/ 1), "session-1"),
|
||||
(request_id(/*value*/ 2), "session-2"),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id,
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id(id),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("open session");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("session ready"),
|
||||
Some(HostToClient::Response {
|
||||
id: request_id,
|
||||
result: WireResult::Ok {
|
||||
value: HostResponse::SessionReady {
|
||||
session_id: session_id(id),
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
for (request_id, id) in [
|
||||
(request_id(/*value*/ 3), "session-1"),
|
||||
(request_id(/*value*/ 4), "session-2"),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id,
|
||||
request: HostRequest::ShutdownSession {
|
||||
session_id: session_id(id),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("shutdown session");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("session closed"),
|
||||
Some(HostToClient::Response {
|
||||
id: request_id,
|
||||
result: WireResult::Ok {
|
||||
value: HostResponse::SessionClosed {
|
||||
session_id: session_id(id),
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
drop(writer);
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disconnect_cancels_a_backpressured_host_writer() {
|
||||
let (host_reader, client_writer) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let (blocked_tx, blocked_rx) = oneshot::channel();
|
||||
let host = tokio::spawn(run(
|
||||
host_reader,
|
||||
BlockingWriter {
|
||||
blocked_tx: Some(blocked_tx),
|
||||
handshake_flushed: false,
|
||||
},
|
||||
));
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write client hello");
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(/*value*/ 1),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id("backpressured-session"),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("write session-open request");
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), blocked_rx)
|
||||
.await
|
||||
.expect("host writer should reach backpressure")
|
||||
.expect("host writer should report backpressure");
|
||||
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write invalid second client hello");
|
||||
|
||||
let error = tokio::time::timeout(Duration::from_secs(1), host)
|
||||
.await
|
||||
.expect("disconnect should cancel the backpressured writer")
|
||||
.expect("host task should finish")
|
||||
.expect_err("a second client hello should fail the connection");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"received a second code-mode client hello"
|
||||
);
|
||||
}
|
||||
|
||||
struct BlockingWriter {
|
||||
blocked_tx: Option<oneshot::Sender<()>>,
|
||||
handshake_flushed: bool,
|
||||
}
|
||||
|
||||
impl AsyncWrite for BlockingWriter {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
_cx: &mut Context<'_>,
|
||||
bytes: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
if self.handshake_flushed {
|
||||
if let Some(blocked_tx) = self.blocked_tx.take() {
|
||||
let _ = blocked_tx.send(());
|
||||
}
|
||||
Poll::Pending
|
||||
} else {
|
||||
Poll::Ready(Ok(bytes.len()))
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
self.handshake_flushed = true;
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn supported_capabilities_are_negotiated_when_optional_or_required() {
|
||||
for capability in [
|
||||
SESSION_RESOURCE_LIMITS_CAPABILITY,
|
||||
BOUNDED_OUTPUT_CAPABILITY,
|
||||
LARGE_DELEGATE_CAPACITY_CAPABILITY,
|
||||
] {
|
||||
let capability = Capability::new(capability).expect("supported capability");
|
||||
let host_capabilities =
|
||||
CapabilitySet::try_new([capability.clone()]).expect("host capabilities");
|
||||
|
||||
for (required, optional) in [
|
||||
(
|
||||
CapabilitySet::empty(),
|
||||
CapabilitySet::try_new([capability]).expect("optional capabilities"),
|
||||
),
|
||||
(host_capabilities.clone(), CapabilitySet::empty()),
|
||||
] {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
writer
|
||||
.write(&ClientToHost::ClientHello(
|
||||
ClientHello::new(
|
||||
SupportedProtocolVersions::try_new([ProtocolVersion::V1])
|
||||
.expect("supported versions"),
|
||||
required,
|
||||
optional,
|
||||
)
|
||||
.expect("client hello"),
|
||||
))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("host hello"),
|
||||
Some(HostToClient::HostHello(HostHello::new(
|
||||
ProtocolVersion::V1,
|
||||
host_capabilities.clone(),
|
||||
)))
|
||||
);
|
||||
|
||||
drop(writer);
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn output_selection_is_per_session() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("host hello"),
|
||||
Some(HostToClient::HostHello(HostHello::new(
|
||||
ProtocolVersion::V1,
|
||||
CapabilitySet::empty(),
|
||||
)))
|
||||
);
|
||||
for (id, name, output_truncation) in [
|
||||
(1, "client", None),
|
||||
(2, "server", Some(WireOutputTruncation::Server)),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(id),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id(name),
|
||||
cell_execution_limits: None,
|
||||
output_truncation,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("open session");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("session ready"),
|
||||
Some(HostToClient::Response {
|
||||
id: request_id(id),
|
||||
result: WireResult::Ok {
|
||||
value: HostResponse::SessionReady {
|
||||
session_id: session_id(name),
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
for (id, name, expected_text, expected_wait) in [
|
||||
(
|
||||
3,
|
||||
"client",
|
||||
"0123456789012345678901234567890123456789",
|
||||
"01234567890123456789012345678901234567890123456789012345678901234567890123456789",
|
||||
),
|
||||
(
|
||||
4,
|
||||
"server",
|
||||
"Warning: truncated output (original token count: 10)\nTotal output lines: 1\n\n0123456789…5 tokens truncated…0123456789",
|
||||
"Warning: truncated output (original token count: 20)\nTotal output lines: 1\n\n01234567890123…13 tokens truncated…67890123456789",
|
||||
),
|
||||
] {
|
||||
let mut request = execute_request(
|
||||
"text('0123456789'.repeat(4)); yield_control(); text('0123456789'.repeat(8));",
|
||||
);
|
||||
request.max_output_tokens = Some(5);
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(id),
|
||||
request: HostRequest::Execute {
|
||||
session_id: session_id(name),
|
||||
request,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("execute");
|
||||
// Admission is sent before start_cell can send its initial result.
|
||||
assert!(matches!(
|
||||
next_response(&mut reader).await,
|
||||
HostToClient::Response {
|
||||
id: actual_id,
|
||||
result: WireResult::Ok { value: HostResponse::ExecutionStarted { .. } },
|
||||
} if actual_id == request_id(id)
|
||||
));
|
||||
let HostToClient::InitialResponse {
|
||||
id: actual_id,
|
||||
result:
|
||||
WireResult::Ok {
|
||||
value:
|
||||
WireRuntimeResponse::Yielded {
|
||||
cell_id,
|
||||
content_items,
|
||||
..
|
||||
},
|
||||
},
|
||||
} = next_response(&mut reader).await
|
||||
else {
|
||||
panic!("expected initial yield");
|
||||
};
|
||||
assert_eq!(actual_id, request_id(id));
|
||||
assert_eq!(
|
||||
content_items,
|
||||
vec![WireContentItem::InputText {
|
||||
text: expected_text.to_string()
|
||||
}]
|
||||
);
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(id + 2),
|
||||
request: HostRequest::Wait {
|
||||
session_id: session_id(name),
|
||||
request: WireWaitRequest {
|
||||
cell_id,
|
||||
yield_time_ms: 60_000,
|
||||
},
|
||||
// A supplied budget only affects Server mode and belongs
|
||||
// to this observation, not the preceding exec.
|
||||
max_output_tokens: Some(7),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("wait");
|
||||
let HostToClient::Response {
|
||||
id: actual_id,
|
||||
result:
|
||||
WireResult::Ok {
|
||||
value:
|
||||
HostResponse::WaitCompleted {
|
||||
outcome:
|
||||
WireWaitOutcome::LiveCell(WireRuntimeResponse::Result {
|
||||
content_items,
|
||||
error_text,
|
||||
..
|
||||
}),
|
||||
},
|
||||
},
|
||||
} = next_response(&mut reader).await
|
||||
else {
|
||||
panic!("expected final wait");
|
||||
};
|
||||
assert_eq!(actual_id, request_id(id + 2));
|
||||
assert_eq!(error_text, None);
|
||||
assert_eq!(
|
||||
content_items,
|
||||
vec![WireContentItem::InputText {
|
||||
text: expected_wait.to_string()
|
||||
}]
|
||||
);
|
||||
}
|
||||
drop(writer);
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incompatible_or_invalid_handshake_is_rejected() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
let version_two = ProtocolVersion::new(/*value*/ 2).expect("protocol version");
|
||||
|
||||
writer
|
||||
.write(&client_hello([version_two], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("rejection"),
|
||||
Some(HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::NoCompatibleVersion {
|
||||
supported_versions: SupportedProtocolVersions::try_new([ProtocolVersion::V1])
|
||||
.expect("host versions"),
|
||||
},
|
||||
})
|
||||
);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(/*value*/ 1),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id("session-1"),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("write invalid first message");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("rejection"),
|
||||
Some(HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::InvalidHello {
|
||||
message: "first message must be connection/hello".to_string(),
|
||||
},
|
||||
})
|
||||
);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_required_capability_is_rejected() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
let capability = Capability::new("required").expect("capability");
|
||||
|
||||
writer
|
||||
.write(&client_hello(
|
||||
[ProtocolVersion::V1],
|
||||
CapabilitySet::try_new([capability.clone()]).expect("capabilities"),
|
||||
))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("rejection"),
|
||||
Some(HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::MissingRequiredCapability { capability },
|
||||
})
|
||||
);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_id_cannot_be_reused_after_shutdown() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 2048);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
reader
|
||||
.read::<HostToClient>()
|
||||
.await
|
||||
.expect("read hello")
|
||||
.expect("host hello");
|
||||
|
||||
let id = session_id("session-1");
|
||||
for (request_id, request) in [
|
||||
(
|
||||
request_id(/*value*/ 1),
|
||||
HostRequest::OpenSession {
|
||||
session_id: id.clone(),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 2),
|
||||
HostRequest::ShutdownSession {
|
||||
session_id: id.clone(),
|
||||
},
|
||||
),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id,
|
||||
request,
|
||||
})
|
||||
.await
|
||||
.expect("session request");
|
||||
reader
|
||||
.read::<HostToClient>()
|
||||
.await
|
||||
.expect("session response")
|
||||
.expect("session response message");
|
||||
}
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(/*value*/ 3),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: id,
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("reuse session ID");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("reuse response"),
|
||||
Some(HostToClient::Response {
|
||||
id: request_id(/*value*/ 3),
|
||||
result: WireResult::Err {
|
||||
message: "code-mode session ID `session-1` was reused".to_string(),
|
||||
},
|
||||
})
|
||||
);
|
||||
drop(writer);
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_history_is_bounded() {
|
||||
let mut requests = RequestRegistry::default();
|
||||
let duplicate = request_id(/*value*/ -1);
|
||||
requests
|
||||
.start(duplicate, RequestKind::OpenSession)
|
||||
.expect("start duplicate probe");
|
||||
assert!(requests.start(duplicate, RequestKind::OpenSession).is_err());
|
||||
requests.finish(duplicate);
|
||||
for value in 1..=MAX_RECENT_REQUEST_IDS as i64 + 100 {
|
||||
let id = request_id(value);
|
||||
requests
|
||||
.start(id, RequestKind::Wait)
|
||||
.expect("start request");
|
||||
requests.cancel(id);
|
||||
requests.finish(id);
|
||||
}
|
||||
assert!(requests.active.is_empty());
|
||||
assert_eq!(requests.recent.len(), MAX_RECENT_REQUEST_IDS);
|
||||
assert_eq!(requests.recent_order.len(), MAX_RECENT_REQUEST_IDS);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_task_panic_disconnects_host() {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(/*max_capacity*/ 1);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
request_tasks: TaskTracker::new(),
|
||||
closing: AtomicBool::new(false),
|
||||
peer: Arc::clone(&peer),
|
||||
};
|
||||
let task = state.request_tasks.spawn(async {
|
||||
panic!("request panic probe");
|
||||
});
|
||||
state.supervise_request_task(task);
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), peer.disconnected())
|
||||
.await
|
||||
.expect("request panic should disconnect host");
|
||||
assert!(
|
||||
peer.failure()
|
||||
.expect("request failure")
|
||||
.contains("request task failed")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn execute_request_id_remains_active_until_initial_response() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*max_capacity*/ 4);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = Arc::new(HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
request_tasks: TaskTracker::new(),
|
||||
closing: AtomicBool::new(false),
|
||||
peer,
|
||||
});
|
||||
let session_id = session_id("session-1");
|
||||
state
|
||||
.open_session(session_id.clone(), CodeModeSessionOptions::default())
|
||||
.expect("open session");
|
||||
let request_id = request_id(/*value*/ 1);
|
||||
|
||||
state
|
||||
.spawn_request(
|
||||
request_id,
|
||||
HostRequest::Execute {
|
||||
session_id: session_id.clone(),
|
||||
request: execute_request("await new Promise(() => {});"),
|
||||
},
|
||||
)
|
||||
.expect("spawn execute request");
|
||||
let started = decode_frame(outgoing_rx.recv().await.expect("execution started frame")).await;
|
||||
let HostToClient::Response {
|
||||
id,
|
||||
result:
|
||||
WireResult::Ok {
|
||||
value: HostResponse::ExecutionStarted { cell_id },
|
||||
},
|
||||
} = started
|
||||
else {
|
||||
panic!("expected execution started response");
|
||||
};
|
||||
assert_eq!(id, request_id);
|
||||
assert!(
|
||||
state
|
||||
.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.active
|
||||
.contains_key(&request_id)
|
||||
);
|
||||
|
||||
state
|
||||
.session(&session_id)
|
||||
.expect("session")
|
||||
.terminate(TerminateRequest {
|
||||
cell_id: cell_id.into(),
|
||||
max_output_tokens: None,
|
||||
})
|
||||
.await
|
||||
.expect("terminate cell");
|
||||
state.disconnect().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_cell_limit_rejects_execute_without_disconnecting() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*max_capacity*/ 1);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: Arc::new(HostLimits {
|
||||
request_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_REQUESTS)),
|
||||
active_cell_permits: Arc::new(Semaphore::new(/*permits*/ 0)),
|
||||
}),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
request_tasks: TaskTracker::new(),
|
||||
closing: AtomicBool::new(false),
|
||||
peer: Arc::clone(&peer),
|
||||
};
|
||||
let session_id = session_id("session-1");
|
||||
state
|
||||
.open_session(session_id.clone(), CodeModeSessionOptions::default())
|
||||
.expect("open session");
|
||||
let request_id = request_id(/*value*/ 1);
|
||||
|
||||
state
|
||||
.handle_request(
|
||||
request_id,
|
||||
HostRequest::Execute {
|
||||
session_id,
|
||||
request: execute_request("text(\"hello\");"),
|
||||
},
|
||||
CancellationToken::new(),
|
||||
CancellationToken::new(),
|
||||
Instant::now(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
decode_frame(outgoing_rx.recv().await.expect("execute response frame")).await,
|
||||
HostToClient::Response {
|
||||
id: request_id,
|
||||
result: WireResult::Err {
|
||||
message: "code-mode host has too many active cells".to_string(),
|
||||
},
|
||||
}
|
||||
);
|
||||
assert!(!peer.is_disconnected());
|
||||
state.disconnect().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_forwarding_panic_disconnects_host() {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(/*max_capacity*/ 1);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
peer.spawn_critical("cell forwarding", async {
|
||||
panic!("cell forwarding panic probe");
|
||||
});
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), peer.disconnected())
|
||||
.await
|
||||
.expect("cell panic should disconnect host");
|
||||
assert!(
|
||||
peer.failure()
|
||||
.expect("cell failure")
|
||||
.contains("cell forwarding task failed")
|
||||
);
|
||||
}
|
||||
798
akode-rs/code-mode-host/src/lib.rs
Normal file
798
akode-rs/code-mode-host/src/lib.rs
Normal file
@@ -0,0 +1,798 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use akode_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use akode_code_mode_protocol::CodeModeSessionCellExecutionLimits;
|
||||
use akode_code_mode_protocol::CodeModeSessionOptions;
|
||||
use akode_code_mode_protocol::TerminateRequest;
|
||||
use akode_code_mode_protocol::WaitRequest;
|
||||
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_CAPABILITY;
|
||||
use akode_code_mode_protocol::host::Capability;
|
||||
use akode_code_mode_protocol::host::CapabilitySet;
|
||||
use akode_code_mode_protocol::host::ClientToHost;
|
||||
use akode_code_mode_protocol::host::EncodedFrame;
|
||||
use akode_code_mode_protocol::host::FramedReader;
|
||||
use akode_code_mode_protocol::host::FramedWriter;
|
||||
use akode_code_mode_protocol::host::HandshakeRejectReason;
|
||||
use akode_code_mode_protocol::host::HostHello;
|
||||
use akode_code_mode_protocol::host::HostRequest;
|
||||
use akode_code_mode_protocol::host::HostResponse;
|
||||
use akode_code_mode_protocol::host::HostToClient;
|
||||
use akode_code_mode_protocol::host::LARGE_DELEGATE_CAPACITY_CAPABILITY;
|
||||
use akode_code_mode_protocol::host::LEGACY_MAX_PENDING_DELEGATE_CALLS;
|
||||
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use akode_code_mode_protocol::host::ProtocolVersion;
|
||||
use akode_code_mode_protocol::host::RequestId;
|
||||
use akode_code_mode_protocol::host::SESSION_RESOURCE_LIMITS_CAPABILITY;
|
||||
use akode_code_mode_protocol::host::SessionId;
|
||||
use akode_code_mode_protocol::host::SupportedProtocolVersions;
|
||||
use akode_code_mode_protocol::host::WireWaitOutcome;
|
||||
use akode_code_mode_protocol::host::YIELD_OBSERVATION_CAPABILITY;
|
||||
use akode_code_mode_runtime::InProcessCodeModeSession;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::TryAcquireError;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
use self::delegate::RemoteDelegate;
|
||||
use self::peer::HostPeer;
|
||||
|
||||
pub use self::grpc::GrpcCodeModeHost;
|
||||
pub use self::process_metrics::CodeModeProcessMetricsCollector;
|
||||
pub use self::transport::DEFAULT_LISTEN_URL;
|
||||
pub use akode_code_mode_protocol::CodeModeProcessMetrics;
|
||||
|
||||
mod delegate;
|
||||
mod grpc;
|
||||
mod grpc_stdio;
|
||||
mod grpc_transport;
|
||||
mod peer;
|
||||
mod process_metrics;
|
||||
mod transport;
|
||||
|
||||
// A host is shared by independent chats and all their subagents.
|
||||
// Test live V8 isolates before increasing this, not just cell permit capacity.
|
||||
const MAX_ACTIVE_CELLS: usize = 2_048;
|
||||
// Leave observation and control headroom during a full callback-completion burst.
|
||||
const MAX_IN_FLIGHT_REQUESTS: usize = MAX_PENDING_DELEGATE_CALLS * 2;
|
||||
const MAX_RECENT_REQUEST_IDS: usize = 4096;
|
||||
const MAX_RECENT_SESSION_IDS: usize = 4096;
|
||||
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
// Allow a full callback-completion burst plus concurrent control messages.
|
||||
const OUTGOING_CHANNEL_CAPACITY: usize = MAX_PENDING_DELEGATE_CALLS * 2;
|
||||
|
||||
enum NegotiatedConnection {
|
||||
Rejected,
|
||||
Accepted { max_pending_delegate_calls: usize },
|
||||
}
|
||||
|
||||
struct HostLimits {
|
||||
request_permits: Arc<Semaphore>,
|
||||
active_cell_permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl HostLimits {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
request_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_REQUESTS)),
|
||||
active_cell_permits: Arc::new(Semaphore::new(MAX_ACTIVE_CELLS)),
|
||||
}
|
||||
}
|
||||
|
||||
fn request_permit(&self) -> Result<OwnedSemaphorePermit, TryAcquireError> {
|
||||
Arc::clone(&self.request_permits).try_acquire_owned()
|
||||
}
|
||||
|
||||
fn cell_permit(&self) -> Result<OwnedSemaphorePermit, TryAcquireError> {
|
||||
Arc::clone(&self.active_cell_permits).try_acquire_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the code-mode host on its configured stdio or gRPC transport.
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.run_main",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(otel.name = "code_mode_host.run_main")
|
||||
)]
|
||||
pub async fn run_main(listen_url: &str) -> Result<()> {
|
||||
transport::run_transport(listen_url, GrpcCodeModeHost::new()).await
|
||||
}
|
||||
|
||||
/// Runs with an optional gRPC metrics collector initialized before sandbox entry.
|
||||
/// The legacy stdio transport remains unchanged.
|
||||
pub async fn run_main_with_process_metrics(
|
||||
listen_url: &str,
|
||||
collector: CodeModeProcessMetricsCollector,
|
||||
) -> Result<()> {
|
||||
transport::run_transport(
|
||||
listen_url,
|
||||
GrpcCodeModeHost::with_process_metrics(collector),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Runs one code-mode host connection over the process standard streams.
|
||||
pub async fn run_stdio() -> Result<()> {
|
||||
run(tokio::io::stdin(), tokio::io::stdout()).await
|
||||
}
|
||||
|
||||
/// Runs one code-mode host connection over an ordered input/output pair.
|
||||
async fn run<R, W>(reader: R, writer: W) -> Result<()>
|
||||
where
|
||||
R: AsyncRead + Send + Unpin + 'static,
|
||||
W: AsyncWrite + Send + Unpin + 'static,
|
||||
{
|
||||
let mut reader = FramedReader::new(reader);
|
||||
let mut writer = FramedWriter::new(writer);
|
||||
let max_pending_delegate_calls = match negotiate(&mut reader, &mut writer).await? {
|
||||
NegotiatedConnection::Rejected => return Ok(()),
|
||||
NegotiatedConnection::Accepted {
|
||||
max_pending_delegate_calls,
|
||||
} => max_pending_delegate_calls,
|
||||
};
|
||||
let (outgoing_tx, outgoing_rx) = mpsc::channel::<EncodedFrame>(OUTGOING_CHANNEL_CAPACITY);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, max_pending_delegate_calls));
|
||||
let state = Arc::new(HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
request_tasks: TaskTracker::new(),
|
||||
closing: AtomicBool::new(false),
|
||||
peer: Arc::clone(&peer),
|
||||
});
|
||||
let writer_disconnected = peer.disconnection_token();
|
||||
let writer_task =
|
||||
tokio::spawn(async move { drive_writer(writer, outgoing_rx, writer_disconnected).await });
|
||||
let writer_peer = Arc::clone(&peer);
|
||||
let writer_supervisor = tokio::spawn(async move {
|
||||
match writer_task.await {
|
||||
Ok(Ok(())) if !writer_peer.is_disconnected() => {
|
||||
writer_peer.fail("code-mode writer task exited unexpectedly".to_string());
|
||||
}
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(err)) => {
|
||||
writer_peer.fail(format!("code-mode writer task failed: {err:#}"));
|
||||
}
|
||||
Err(err) => {
|
||||
writer_peer.fail(format!("code-mode writer task failed: {err}"));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let input_result = async {
|
||||
loop {
|
||||
let message = tokio::select! {
|
||||
biased;
|
||||
_ = peer.disconnected() => break,
|
||||
message = reader.read() => message.context("failed to read code-mode client message")?,
|
||||
};
|
||||
let Some(message) = message else {
|
||||
break;
|
||||
};
|
||||
match message {
|
||||
ClientToHost::ClientHello(_) => {
|
||||
anyhow::bail!("received a second code-mode client hello");
|
||||
}
|
||||
ClientToHost::Request { id, request } => {
|
||||
state.spawn_request(id, request)?;
|
||||
}
|
||||
ClientToHost::CancelRequest { id } => {
|
||||
state.cancel_request(id);
|
||||
}
|
||||
ClientToHost::YieldRequest { id } => {
|
||||
state.yield_request(id);
|
||||
}
|
||||
ClientToHost::DelegateResponse { id, result } => {
|
||||
peer.complete(id, result.into_result()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
|
||||
peer.disconnect();
|
||||
if tokio::time::timeout(SHUTDOWN_TIMEOUT, state.disconnect())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
peer.fail("timed out shutting down code-mode host state".to_string());
|
||||
}
|
||||
drop(state);
|
||||
tokio::time::timeout(SHUTDOWN_TIMEOUT, writer_supervisor)
|
||||
.await
|
||||
.context("timed out supervising code-mode writer task")?
|
||||
.context("code-mode writer supervisor task failed")?;
|
||||
let failure = peer.failure();
|
||||
drop(peer);
|
||||
input_result?;
|
||||
if let Some(failure) = failure {
|
||||
anyhow::bail!(failure);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn drive_writer<W: AsyncWrite + Unpin>(
|
||||
mut writer: FramedWriter<W>,
|
||||
mut outgoing: mpsc::Receiver<EncodedFrame>,
|
||||
disconnected: CancellationToken,
|
||||
) -> Result<()> {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = disconnected.cancelled() => return Ok(()),
|
||||
frame = outgoing.recv() => {
|
||||
let Some(frame) = frame else {
|
||||
return Ok(());
|
||||
};
|
||||
tokio::select! {
|
||||
_ = disconnected.cancelled() => return Ok(()),
|
||||
result = writer.write_frame(&frame) => {
|
||||
result.context("failed to write code-mode host message")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn negotiate<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
reader: &mut FramedReader<R>,
|
||||
writer: &mut FramedWriter<W>,
|
||||
) -> Result<NegotiatedConnection> {
|
||||
let Some(first_message) = reader
|
||||
.read()
|
||||
.await
|
||||
.context("failed to read code-mode client hello")?
|
||||
else {
|
||||
return Ok(NegotiatedConnection::Rejected);
|
||||
};
|
||||
let ClientToHost::ClientHello(client_hello) = first_message else {
|
||||
writer
|
||||
.write(&HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::InvalidHello {
|
||||
message: "first message must be connection/hello".to_string(),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.context("failed to reject invalid code-mode client hello")?;
|
||||
return Ok(NegotiatedConnection::Rejected);
|
||||
};
|
||||
|
||||
let supported_versions = SupportedProtocolVersions::try_new([ProtocolVersion::V1])?;
|
||||
if !client_hello
|
||||
.supported_versions()
|
||||
.contains(ProtocolVersion::V1)
|
||||
{
|
||||
writer
|
||||
.write(&HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::NoCompatibleVersion { supported_versions },
|
||||
})
|
||||
.await
|
||||
.context("failed to reject incompatible code-mode client")?;
|
||||
return Ok(NegotiatedConnection::Rejected);
|
||||
}
|
||||
|
||||
let host_capabilities = CapabilitySet::try_new(
|
||||
[
|
||||
SESSION_RESOURCE_LIMITS_CAPABILITY,
|
||||
YIELD_OBSERVATION_CAPABILITY,
|
||||
BOUNDED_OUTPUT_CAPABILITY,
|
||||
LARGE_DELEGATE_CAPACITY_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(Capability::new)
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.filter(|capability| {
|
||||
client_hello.required_capabilities().contains(capability)
|
||||
|| client_hello.optional_capabilities().contains(capability)
|
||||
}),
|
||||
)?;
|
||||
if let Some(capability) = client_hello
|
||||
.required_capabilities()
|
||||
.iter()
|
||||
.find(|capability| !host_capabilities.contains(capability))
|
||||
{
|
||||
writer
|
||||
.write(&HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::MissingRequiredCapability {
|
||||
capability: capability.clone(),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.context("failed to reject unsupported code-mode capability")?;
|
||||
return Ok(NegotiatedConnection::Rejected);
|
||||
}
|
||||
|
||||
let max_pending_delegate_calls =
|
||||
if host_capabilities.contains(&Capability::new(LARGE_DELEGATE_CAPACITY_CAPABILITY)?) {
|
||||
MAX_PENDING_DELEGATE_CALLS
|
||||
} else {
|
||||
LEGACY_MAX_PENDING_DELEGATE_CALLS
|
||||
};
|
||||
let hello = HostHello::new(ProtocolVersion::V1, host_capabilities);
|
||||
writer
|
||||
.write(&HostToClient::HostHello(hello))
|
||||
.await
|
||||
.context("failed to write code-mode host hello")?;
|
||||
Ok(NegotiatedConnection::Accepted {
|
||||
max_pending_delegate_calls,
|
||||
})
|
||||
}
|
||||
|
||||
struct HostState {
|
||||
sessions: Mutex<HashMap<SessionId, Arc<InProcessCodeModeSession>>>,
|
||||
limits: Arc<HostLimits>,
|
||||
seen_session_ids: Mutex<SeenSessionIds>,
|
||||
requests: Mutex<RequestRegistry>,
|
||||
request_tasks: TaskTracker,
|
||||
closing: AtomicBool,
|
||||
peer: Arc<HostPeer>,
|
||||
}
|
||||
|
||||
impl HostState {
|
||||
fn spawn_request(
|
||||
self: &Arc<Self>,
|
||||
request_id: RequestId,
|
||||
request: HostRequest,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
// Include host admission and scheduling before the runtime observes the request.
|
||||
let received_at = Instant::now();
|
||||
let request_kind = RequestKind::from(&request);
|
||||
let (cancellation, yield_signal) = self
|
||||
.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.start(request_id, request_kind)?;
|
||||
let Ok(permit) = self.limits.request_permit() else {
|
||||
self.respond(
|
||||
request_id,
|
||||
Err("code-mode host has too many in-flight requests".to_string()),
|
||||
);
|
||||
self.finish_request(request_id);
|
||||
return Ok(());
|
||||
};
|
||||
let state = Arc::clone(self);
|
||||
let request_task = self.request_tasks.spawn(async move {
|
||||
let _permit = permit;
|
||||
state
|
||||
.handle_request(request_id, request, cancellation, yield_signal, received_at)
|
||||
.await;
|
||||
state.finish_request(request_id);
|
||||
});
|
||||
self.supervise_request_task(request_task);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn supervise_request_task(&self, task: tokio::task::JoinHandle<()>) {
|
||||
let peer = Arc::clone(&self.peer);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = task.await {
|
||||
peer.fail(format!("code-mode request task failed: {err}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.request",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
otel.name = "code_mode_host.request",
|
||||
request.kind = RequestKind::from(&request).as_str(),
|
||||
request.id = ?request_id,
|
||||
call_id = tracing::field::Empty,
|
||||
)
|
||||
)]
|
||||
async fn handle_request(
|
||||
&self,
|
||||
request_id: RequestId,
|
||||
request: HostRequest,
|
||||
cancellation: CancellationToken,
|
||||
yield_signal: CancellationToken,
|
||||
received_at: Instant,
|
||||
) {
|
||||
if let HostRequest::Execute { request, .. } = &request {
|
||||
tracing::Span::current().record("call_id", request.tool_call_id.as_str());
|
||||
}
|
||||
if self.closing.load(Ordering::Acquire) {
|
||||
self.respond(
|
||||
request_id,
|
||||
Err("code-mode host is shutting down".to_string()),
|
||||
);
|
||||
return;
|
||||
}
|
||||
match request {
|
||||
HostRequest::OpenSession {
|
||||
session_id,
|
||||
cell_execution_limits,
|
||||
output_truncation,
|
||||
} => {
|
||||
let result = CodeModeSessionCellExecutionLimits::try_from(
|
||||
cell_execution_limits.unwrap_or_default(),
|
||||
)
|
||||
.map_err(|error| format!("invalid code-mode session execution limits: {error}"))
|
||||
.and_then(|limits| {
|
||||
self.open_session(
|
||||
session_id.clone(),
|
||||
CodeModeSessionOptions {
|
||||
cell_execution_limits: limits,
|
||||
output_truncation: output_truncation
|
||||
.map(CodeModeOutputTruncation::from)
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.map(|()| HostResponse::SessionReady { session_id });
|
||||
self.respond(request_id, result);
|
||||
}
|
||||
HostRequest::Execute {
|
||||
session_id,
|
||||
request,
|
||||
} => {
|
||||
if cancellation.is_cancelled() {
|
||||
self.respond(request_id, Err("code-mode request cancelled".to_string()));
|
||||
return;
|
||||
}
|
||||
let request = match request.try_into() {
|
||||
Ok(request) => request,
|
||||
Err(err) => {
|
||||
self.respond(
|
||||
request_id,
|
||||
Err(format!("invalid code-mode execute request: {err}")),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let session = match self.session(&session_id) {
|
||||
Ok(session) => session,
|
||||
Err(err) => {
|
||||
self.respond(request_id, Err(err));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Ok(active_cell_permit) = self.limits.cell_permit() else {
|
||||
self.respond(
|
||||
request_id,
|
||||
Err("code-mode host has too many active cells".to_string()),
|
||||
);
|
||||
return;
|
||||
};
|
||||
let delegate = Arc::new(RemoteDelegate::new(
|
||||
session_id.clone(),
|
||||
Arc::clone(&self.peer),
|
||||
));
|
||||
let result = session.execute(request, delegate, Some(yield_signal)).await;
|
||||
match result {
|
||||
Ok(started) => {
|
||||
let cell_id = started.cell_id.clone();
|
||||
self.respond(
|
||||
request_id,
|
||||
Ok(HostResponse::ExecutionStarted {
|
||||
cell_id: cell_id.into(),
|
||||
}),
|
||||
);
|
||||
let initial_response_sent = self.peer.start_cell(
|
||||
session_id,
|
||||
request_id,
|
||||
started,
|
||||
active_cell_permit,
|
||||
received_at,
|
||||
);
|
||||
let _ = initial_response_sent.await;
|
||||
}
|
||||
Err(err) => self.respond(request_id, Err(err)),
|
||||
}
|
||||
}
|
||||
HostRequest::Wait {
|
||||
session_id,
|
||||
request,
|
||||
max_output_tokens,
|
||||
} => {
|
||||
let result = match self.session(&session_id) {
|
||||
Ok(session) => {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => {
|
||||
Err("code-mode request cancelled".to_string())
|
||||
}
|
||||
result = session.wait(WaitRequest {
|
||||
max_output_tokens,
|
||||
..request.into()
|
||||
}, Some(yield_signal)) => result.and_then(|outcome| {
|
||||
let outcome = outcome.with_code_mode_host_duration(received_at.elapsed());
|
||||
Ok(HostResponse::WaitCompleted {
|
||||
outcome: WireWaitOutcome::try_from(outcome)
|
||||
.map_err(|error| error.to_string())?,
|
||||
})
|
||||
}),
|
||||
}
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
self.respond(request_id, result);
|
||||
}
|
||||
HostRequest::Terminate {
|
||||
session_id,
|
||||
cell_id,
|
||||
max_output_tokens,
|
||||
} => {
|
||||
let result = match self.session(&session_id) {
|
||||
Ok(session) => session
|
||||
.terminate(TerminateRequest {
|
||||
cell_id: cell_id.into(),
|
||||
max_output_tokens,
|
||||
})
|
||||
.await
|
||||
.and_then(|outcome| {
|
||||
let outcome =
|
||||
outcome.with_code_mode_host_duration(received_at.elapsed());
|
||||
Ok(HostResponse::WaitCompleted {
|
||||
outcome: WireWaitOutcome::try_from(outcome)
|
||||
.map_err(|error| error.to_string())?,
|
||||
})
|
||||
}),
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
self.respond(request_id, result);
|
||||
}
|
||||
HostRequest::ShutdownSession { session_id } => {
|
||||
let session = self
|
||||
.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&session_id);
|
||||
let result = match session {
|
||||
Some(session) => match session.shutdown().await {
|
||||
Ok(()) => {
|
||||
self.peer.wait_for_session_cells(&session_id).await;
|
||||
Ok(HostResponse::SessionClosed { session_id })
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
None => Err(format!("unknown code-mode session {session_id}")),
|
||||
};
|
||||
self.respond(request_id, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn open_session(
|
||||
&self,
|
||||
session_id: SessionId,
|
||||
options: CodeModeSessionOptions,
|
||||
) -> Result<(), String> {
|
||||
let mut sessions = self.sessions.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if sessions.contains_key(&session_id) {
|
||||
return Err(format!(
|
||||
"code-mode session ID `{session_id}` is already open"
|
||||
));
|
||||
}
|
||||
if self.closing.load(Ordering::Acquire) {
|
||||
return Err("code-mode host is shutting down".to_string());
|
||||
}
|
||||
if !self
|
||||
.seen_session_ids
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remember(session_id.clone())
|
||||
{
|
||||
return Err(format!("code-mode session ID `{session_id}` was reused"));
|
||||
}
|
||||
let peer = Arc::downgrade(&self.peer);
|
||||
let task_failure_handler = Arc::new(move |reason| {
|
||||
if let Some(peer) = peer.upgrade() {
|
||||
peer.fail(reason);
|
||||
}
|
||||
});
|
||||
sessions.insert(
|
||||
session_id,
|
||||
Arc::new(InProcessCodeModeSession::with_options(
|
||||
options,
|
||||
Some(task_failure_handler),
|
||||
)),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn session(&self, session_id: &SessionId) -> Result<Arc<InProcessCodeModeSession>, String> {
|
||||
self.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.get(session_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("unknown code-mode session {session_id}"))
|
||||
}
|
||||
|
||||
fn respond(&self, id: RequestId, result: Result<HostResponse, String>) {
|
||||
self.peer.respond(id, result);
|
||||
}
|
||||
|
||||
fn cancel_request(&self, request_id: RequestId) {
|
||||
self.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.cancel(request_id);
|
||||
}
|
||||
|
||||
fn yield_request(&self, request_id: RequestId) {
|
||||
self.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.yield_observation(request_id);
|
||||
}
|
||||
|
||||
fn finish_request(&self, request_id: RequestId) {
|
||||
self.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.finish(request_id);
|
||||
}
|
||||
|
||||
async fn disconnect(&self) {
|
||||
self.closing.store(true, Ordering::Release);
|
||||
self.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.cancel_all();
|
||||
self.request_tasks.close();
|
||||
self.request_tasks.wait().await;
|
||||
let sessions = self
|
||||
.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.drain()
|
||||
.map(|(_, session)| session)
|
||||
.collect::<Vec<_>>();
|
||||
for session in sessions {
|
||||
let _ = session.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum RequestKind {
|
||||
OpenSession,
|
||||
Execute,
|
||||
Wait,
|
||||
Terminate,
|
||||
ShutdownSession,
|
||||
}
|
||||
|
||||
impl RequestKind {
|
||||
fn from(request: &HostRequest) -> Self {
|
||||
match request {
|
||||
HostRequest::OpenSession { .. } => Self::OpenSession,
|
||||
HostRequest::Execute { .. } => Self::Execute,
|
||||
HostRequest::Wait { .. } => Self::Wait,
|
||||
HostRequest::Terminate { .. } => Self::Terminate,
|
||||
HostRequest::ShutdownSession { .. } => Self::ShutdownSession,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_cancellable(self) -> bool {
|
||||
matches!(self, Self::Execute | Self::Wait)
|
||||
}
|
||||
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::OpenSession => "open_session",
|
||||
Self::Execute => "execute",
|
||||
Self::Wait => "wait",
|
||||
Self::Terminate => "terminate",
|
||||
Self::ShutdownSession => "shutdown_session",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveRequest {
|
||||
kind: RequestKind,
|
||||
cancellation: CancellationToken,
|
||||
yield_signal: CancellationToken,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RequestRegistry {
|
||||
active: HashMap<RequestId, ActiveRequest>,
|
||||
recent: HashSet<RequestId>,
|
||||
recent_order: VecDeque<RequestId>,
|
||||
}
|
||||
|
||||
impl RequestRegistry {
|
||||
fn start(
|
||||
&mut self,
|
||||
request_id: RequestId,
|
||||
kind: RequestKind,
|
||||
) -> Result<(CancellationToken, CancellationToken), anyhow::Error> {
|
||||
if self.active.contains_key(&request_id) || self.recent.contains(&request_id) {
|
||||
anyhow::bail!("duplicate code-mode request ID {request_id:?}");
|
||||
}
|
||||
let cancellation = CancellationToken::new();
|
||||
let yield_signal = CancellationToken::new();
|
||||
self.active.insert(
|
||||
request_id,
|
||||
ActiveRequest {
|
||||
kind,
|
||||
cancellation: cancellation.clone(),
|
||||
yield_signal: yield_signal.clone(),
|
||||
},
|
||||
);
|
||||
Ok((cancellation, yield_signal))
|
||||
}
|
||||
|
||||
fn cancel(&mut self, request_id: RequestId) {
|
||||
if let Some(request) = self.active.get(&request_id)
|
||||
&& request.kind.is_cancellable()
|
||||
{
|
||||
request.cancellation.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn yield_observation(&self, request_id: RequestId) {
|
||||
if let Some(request) = self.active.get(&request_id)
|
||||
&& matches!(request.kind, RequestKind::Execute | RequestKind::Wait)
|
||||
{
|
||||
request.yield_signal.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self, request_id: RequestId) {
|
||||
if self.active.remove(&request_id).is_none() {
|
||||
return;
|
||||
}
|
||||
self.recent.insert(request_id);
|
||||
self.recent_order.push_back(request_id);
|
||||
while self.recent_order.len() > MAX_RECENT_REQUEST_IDS {
|
||||
if let Some(expired) = self.recent_order.pop_front() {
|
||||
self.recent.remove(&expired);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_all(&self) {
|
||||
for request in self.active.values() {
|
||||
request.cancellation.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SeenSessionIds {
|
||||
ids: HashSet<SessionId>,
|
||||
order: VecDeque<SessionId>,
|
||||
}
|
||||
|
||||
impl SeenSessionIds {
|
||||
fn remember(&mut self, session_id: SessionId) -> bool {
|
||||
if !self.ids.insert(session_id.clone()) {
|
||||
return false;
|
||||
}
|
||||
self.order.push_back(session_id);
|
||||
while self.order.len() > MAX_RECENT_SESSION_IDS {
|
||||
if let Some(expired) = self.order.pop_front() {
|
||||
self.ids.remove(&expired);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "host_tests.rs"]
|
||||
mod tests;
|
||||
40
akode-rs/code-mode-host/src/main.rs
Normal file
40
akode-rs/code-mode-host/src/main.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
use clap::Parser;
|
||||
use tracing_subscriber::Layer;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
struct Cli {
|
||||
#[arg(long, hide = true, conflicts_with_all = ["listen"])]
|
||||
codex_ui_plugin_process: bool,
|
||||
|
||||
/// Transport endpoint: `stdio`, `stdio://`, `grpc+stdio://`, or `grpc://IP:PORT`.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "URL",
|
||||
default_value = akode_code_mode_host::DEFAULT_LISTEN_URL
|
||||
)]
|
||||
listen: String,
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn run(cli: Cli) -> anyhow::Result<()> {
|
||||
// Logs stay local: they are written to stderr only.
|
||||
tracing_subscriber::registry()
|
||||
.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_ansi(false)
|
||||
.with_filter(tracing_subscriber::filter::LevelFilter::INFO),
|
||||
)
|
||||
.init();
|
||||
akode_code_mode_host::run_main(&cli.listen).await
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let cli = Cli::parse();
|
||||
if cli.codex_ui_plugin_process {
|
||||
return akode_code_mode_runtime::run_ui_sandbox().map_err(Into::into);
|
||||
}
|
||||
run(cli)
|
||||
}
|
||||
566
akode-rs/code-mode-host/src/peer.rs
Normal file
566
akode-rs/code-mode-host/src/peer.rs
Normal file
@@ -0,0 +1,566 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_code_mode_protocol::CellId;
|
||||
use akode_code_mode_protocol::StartedCell;
|
||||
use akode_code_mode_protocol::host::DelegateRequest;
|
||||
use akode_code_mode_protocol::host::DelegateRequestId;
|
||||
use akode_code_mode_protocol::host::DelegateResponse;
|
||||
use akode_code_mode_protocol::host::EncodedFrame;
|
||||
use akode_code_mode_protocol::host::HostToClient;
|
||||
use akode_code_mode_protocol::host::RequestId;
|
||||
use akode_code_mode_protocol::host::SessionId;
|
||||
use akode_code_mode_protocol::host::WireResult;
|
||||
use akode_code_mode_protocol::host::WireRuntimeResponse;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const CELL_MESSAGE_CAPACITY: usize = 128;
|
||||
|
||||
pub(super) struct HostPeer {
|
||||
outgoing_tx: mpsc::Sender<EncodedFrame>,
|
||||
pending: Mutex<HashMap<DelegateRequestId, PendingDelegate>>,
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
cell_routes: StdMutex<HashMap<(SessionId, CellId), CellRoute>>,
|
||||
cell_routes_changed: Notify,
|
||||
next_request_id: AtomicI64,
|
||||
disconnected: CancellationToken,
|
||||
failure: StdMutex<Option<String>>,
|
||||
}
|
||||
|
||||
struct PendingDelegate {
|
||||
response_tx: oneshot::Sender<Result<DelegateResponse, String>>,
|
||||
dispatched: bool,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
}
|
||||
|
||||
enum CellRoute {
|
||||
Pending(VecDeque<CellMessage>),
|
||||
Active(mpsc::Sender<CellMessage>),
|
||||
}
|
||||
|
||||
enum CellMessage {
|
||||
Delegate {
|
||||
id: DelegateRequestId,
|
||||
request: DelegateRequest,
|
||||
dispatched_tx: oneshot::Sender<Result<(), String>>,
|
||||
},
|
||||
Closed,
|
||||
}
|
||||
|
||||
struct InitialRequest {
|
||||
id: RequestId,
|
||||
received_at: Instant,
|
||||
}
|
||||
|
||||
impl HostPeer {
|
||||
pub(super) fn new(
|
||||
outgoing_tx: mpsc::Sender<EncodedFrame>,
|
||||
max_pending_delegate_calls: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
outgoing_tx,
|
||||
pending: Mutex::new(HashMap::new()),
|
||||
delegate_permits: Arc::new(Semaphore::new(max_pending_delegate_calls)),
|
||||
cell_routes: StdMutex::new(HashMap::new()),
|
||||
cell_routes_changed: Notify::new(),
|
||||
next_request_id: AtomicI64::new(1),
|
||||
disconnected: CancellationToken::new(),
|
||||
failure: StdMutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn send(&self, message: HostToClient) -> Result<(), PeerSendError> {
|
||||
let frame = EncodedFrame::encode(&message)
|
||||
.map_err(|err| PeerSendError::Payload(err.to_string()))?;
|
||||
self.send_frame(frame)
|
||||
}
|
||||
|
||||
pub(super) fn respond(
|
||||
&self,
|
||||
id: RequestId,
|
||||
result: Result<akode_code_mode_protocol::host::HostResponse, String>,
|
||||
) {
|
||||
let message = HostToClient::Response {
|
||||
id,
|
||||
result: WireResult::from_result(result),
|
||||
};
|
||||
if let Err(PeerSendError::Payload(err)) = self.send(message) {
|
||||
let _ = self.send(HostToClient::Response {
|
||||
id,
|
||||
result: WireResult::Err {
|
||||
message: format!("code-mode host response exceeds the IPC frame limit: {err}"),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn initial_response(&self, id: RequestId, result: Result<WireRuntimeResponse, String>) {
|
||||
let message = HostToClient::InitialResponse {
|
||||
id,
|
||||
result: WireResult::from_result(result),
|
||||
};
|
||||
if let Err(PeerSendError::Payload(err)) = self.send(message) {
|
||||
let _ = self.send(HostToClient::InitialResponse {
|
||||
id,
|
||||
result: WireResult::Err {
|
||||
message: format!(
|
||||
"code-mode initial response exceeds the IPC frame limit: {err}"
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn call(
|
||||
self: &Arc<Self>,
|
||||
session_id: SessionId,
|
||||
request: DelegateRequest,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Result<DelegateResponse, String> {
|
||||
if self.disconnected.is_cancelled() {
|
||||
return Err("code-mode client connection closed".to_string());
|
||||
}
|
||||
let Ok(permit) = Arc::clone(&self.delegate_permits).try_acquire_owned() else {
|
||||
return Err("code-mode host has too many pending delegate calls".to_string());
|
||||
};
|
||||
let id = DelegateRequestId::new(self.next_request_id.fetch_add(1, Ordering::Relaxed));
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.pending.lock().await.insert(
|
||||
id,
|
||||
PendingDelegate {
|
||||
response_tx,
|
||||
dispatched: false,
|
||||
_permit: permit,
|
||||
},
|
||||
);
|
||||
let mut pending = PendingDelegateRequest::new(Arc::clone(self), id);
|
||||
let cell_id = match &request {
|
||||
DelegateRequest::InvokeTool { invocation } => invocation.cell_id.clone().into(),
|
||||
DelegateRequest::Notify { cell_id, .. } => cell_id.clone().into(),
|
||||
};
|
||||
let (dispatched_tx, dispatched_rx) = oneshot::channel();
|
||||
if let Err(err) = self.route_cell_message(
|
||||
(session_id, cell_id),
|
||||
CellMessage::Delegate {
|
||||
id,
|
||||
request,
|
||||
dispatched_tx,
|
||||
},
|
||||
) {
|
||||
self.pending.lock().await.remove(&id);
|
||||
pending.disarm();
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let dispatched = tokio::select! {
|
||||
dispatched = dispatched_rx => dispatched.map_err(|_| {
|
||||
"code-mode cell route closed before dispatching delegate request".to_string()
|
||||
})?,
|
||||
_ = self.disconnected.cancelled() => {
|
||||
self.pending.lock().await.remove(&id);
|
||||
pending.disarm();
|
||||
return Err("code-mode client connection closed".to_string());
|
||||
}
|
||||
};
|
||||
if let Err(err) = dispatched {
|
||||
self.pending.lock().await.remove(&id);
|
||||
pending.disarm();
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
response = response_rx => {
|
||||
pending.disarm();
|
||||
response.map_err(|_| {
|
||||
"code-mode client closed before returning delegate output".to_string()
|
||||
})?
|
||||
}
|
||||
_ = cancellation_token.cancelled() => {
|
||||
if self.remove_pending(id).await.is_some() {
|
||||
let _ = self.send(HostToClient::CancelDelegateRequest { id });
|
||||
}
|
||||
pending.disarm();
|
||||
Err("code mode delegate request cancelled".to_string())
|
||||
}
|
||||
_ = self.disconnected.cancelled() => {
|
||||
self.pending.lock().await.remove(&id);
|
||||
pending.disarm();
|
||||
Err("code-mode client connection closed".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn complete(
|
||||
&self,
|
||||
id: DelegateRequestId,
|
||||
response: Result<DelegateResponse, String>,
|
||||
) {
|
||||
if let Some(pending) = self.remove_pending(id).await {
|
||||
let _ = pending.response_tx.send(response);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn start_cell(
|
||||
self: &Arc<Self>,
|
||||
session_id: SessionId,
|
||||
request_id: RequestId,
|
||||
started: StartedCell,
|
||||
active_cell_permit: OwnedSemaphorePermit,
|
||||
received_at: Instant,
|
||||
) -> oneshot::Receiver<()> {
|
||||
let (initial_response_sent_tx, initial_response_sent_rx) = oneshot::channel();
|
||||
let key = (session_id, started.cell_id.clone());
|
||||
let (messages_tx, messages_rx) = mpsc::channel(CELL_MESSAGE_CAPACITY);
|
||||
let previous = self
|
||||
.cell_routes
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(key.clone(), CellRoute::Active(messages_tx.clone()));
|
||||
match previous {
|
||||
Some(CellRoute::Pending(messages)) => {
|
||||
for message in messages {
|
||||
if messages_tx.try_send(message).is_err() {
|
||||
self.disconnect();
|
||||
return initial_response_sent_rx;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(CellRoute::Active(_)) => {
|
||||
self.disconnect();
|
||||
return initial_response_sent_rx;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let peer = Arc::clone(self);
|
||||
self.spawn_critical("cell forwarding", async move {
|
||||
drive_cell(
|
||||
peer,
|
||||
key,
|
||||
InitialRequest {
|
||||
id: request_id,
|
||||
received_at,
|
||||
},
|
||||
started,
|
||||
messages_rx,
|
||||
initial_response_sent_tx,
|
||||
active_cell_permit,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
initial_response_sent_rx
|
||||
}
|
||||
|
||||
pub(super) fn close_cell(&self, session_id: SessionId, cell_id: CellId) {
|
||||
let _ = self.route_cell_message((session_id, cell_id), CellMessage::Closed);
|
||||
}
|
||||
|
||||
pub(super) fn disconnect(&self) {
|
||||
self.disconnected.cancel();
|
||||
}
|
||||
|
||||
pub(super) fn fail(&self, reason: String) {
|
||||
let mut failure = self.failure.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if failure.is_none() {
|
||||
*failure = Some(reason);
|
||||
}
|
||||
drop(failure);
|
||||
self.disconnect();
|
||||
}
|
||||
|
||||
pub(super) fn failure(&self) -> Option<String> {
|
||||
self.failure
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub(super) fn is_disconnected(&self) -> bool {
|
||||
self.disconnected.is_cancelled()
|
||||
}
|
||||
|
||||
pub(super) async fn disconnected(&self) {
|
||||
self.disconnected.cancelled().await;
|
||||
}
|
||||
|
||||
pub(super) fn disconnection_token(&self) -> CancellationToken {
|
||||
self.disconnected.clone()
|
||||
}
|
||||
|
||||
pub(super) async fn wait_for_session_cells(&self, session_id: &SessionId) {
|
||||
loop {
|
||||
let changed = self.cell_routes_changed.notified();
|
||||
if !self
|
||||
.cell_routes
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.keys()
|
||||
.any(|(route_session_id, _)| route_session_id == session_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = changed => {}
|
||||
_ = self.disconnected.cancelled() => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_delegate_if_pending(
|
||||
&self,
|
||||
id: DelegateRequestId,
|
||||
session_id: SessionId,
|
||||
request: DelegateRequest,
|
||||
dispatched_tx: oneshot::Sender<Result<(), String>>,
|
||||
) {
|
||||
let result = {
|
||||
let mut pending = self.pending.lock().await;
|
||||
let Some(pending) = pending.get_mut(&id) else {
|
||||
let _ = dispatched_tx.send(Err(
|
||||
"code-mode delegate request was cancelled before dispatch".to_string(),
|
||||
));
|
||||
return;
|
||||
};
|
||||
match self.send(HostToClient::DelegateRequest {
|
||||
id,
|
||||
session_id,
|
||||
request,
|
||||
}) {
|
||||
Ok(()) => {
|
||||
pending.dispatched = true;
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(err.to_string()),
|
||||
}
|
||||
};
|
||||
let _ = dispatched_tx.send(result);
|
||||
}
|
||||
|
||||
fn route_cell_message(
|
||||
&self,
|
||||
key: (SessionId, CellId),
|
||||
message: CellMessage,
|
||||
) -> Result<(), String> {
|
||||
use std::collections::hash_map::Entry;
|
||||
|
||||
let result = match self
|
||||
.cell_routes
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.entry(key)
|
||||
{
|
||||
Entry::Occupied(mut entry) => match entry.get_mut() {
|
||||
CellRoute::Pending(messages) if messages.len() < CELL_MESSAGE_CAPACITY => {
|
||||
messages.push_back(message);
|
||||
Ok(())
|
||||
}
|
||||
CellRoute::Pending(_) => Err("code-mode cell message queue is full".to_string()),
|
||||
CellRoute::Active(sender) => sender
|
||||
.try_send(message)
|
||||
.map_err(|_| "code-mode cell message queue is unavailable".to_string()),
|
||||
},
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(CellRoute::Pending(VecDeque::from([message])));
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
if result.is_err() {
|
||||
self.disconnect();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn remove_pending(&self, id: DelegateRequestId) -> Option<PendingDelegate> {
|
||||
self.pending.lock().await.remove(&id)
|
||||
}
|
||||
|
||||
pub(super) fn spawn_critical<F>(self: &Arc<Self>, task_name: &'static str, future: F)
|
||||
where
|
||||
F: std::future::Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let task = tokio::spawn(future);
|
||||
let peer = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = task.await {
|
||||
peer.fail(format!("code-mode {task_name} task failed: {err}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn send_frame(&self, frame: EncodedFrame) -> Result<(), PeerSendError> {
|
||||
match self.outgoing_tx.try_send(frame) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||
self.disconnect();
|
||||
Err(PeerSendError::Unavailable(
|
||||
"code-mode host outgoing queue is full".to_string(),
|
||||
))
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||
self.disconnect();
|
||||
Err(PeerSendError::Unavailable(
|
||||
"code-mode client connection closed".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn drive_cell(
|
||||
peer: Arc<HostPeer>,
|
||||
key: (SessionId, CellId),
|
||||
request: InitialRequest,
|
||||
started: StartedCell,
|
||||
mut messages_rx: mpsc::Receiver<CellMessage>,
|
||||
initial_response_sent_tx: oneshot::Sender<()>,
|
||||
_active_cell_permit: OwnedSemaphorePermit,
|
||||
) {
|
||||
let mut initial_response_sent_tx = Some(initial_response_sent_tx);
|
||||
let initial_response = started.initial_response();
|
||||
tokio::pin!(initial_response);
|
||||
let closed = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut initial_response => {
|
||||
// Freeze the request duration before response conversion or delivery.
|
||||
let code_mode_host_duration = request.received_at.elapsed();
|
||||
peer.initial_response(
|
||||
request.id,
|
||||
result.and_then(|response| {
|
||||
let response = response.with_code_mode_host_duration(code_mode_host_duration);
|
||||
WireRuntimeResponse::try_from(response).map_err(|error| error.to_string())
|
||||
}),
|
||||
);
|
||||
if let Some(initial_response_sent_tx) = initial_response_sent_tx.take() {
|
||||
let _ = initial_response_sent_tx.send(());
|
||||
}
|
||||
break false;
|
||||
}
|
||||
message = messages_rx.recv() => match message {
|
||||
Some(CellMessage::Delegate {
|
||||
id,
|
||||
request,
|
||||
dispatched_tx,
|
||||
}) => {
|
||||
peer.send_delegate_if_pending(id, key.0.clone(), request, dispatched_tx).await;
|
||||
}
|
||||
Some(CellMessage::Closed) | None => break true,
|
||||
},
|
||||
_ = peer.disconnected.cancelled() => {
|
||||
peer.remove_cell_route(&key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if closed {
|
||||
let result = initial_response.await;
|
||||
let code_mode_host_duration = request.received_at.elapsed();
|
||||
peer.initial_response(
|
||||
request.id,
|
||||
result.and_then(|response| {
|
||||
let response = response.with_code_mode_host_duration(code_mode_host_duration);
|
||||
WireRuntimeResponse::try_from(response).map_err(|error| error.to_string())
|
||||
}),
|
||||
);
|
||||
if let Some(initial_response_sent_tx) = initial_response_sent_tx.take() {
|
||||
let _ = initial_response_sent_tx.send(());
|
||||
}
|
||||
} else {
|
||||
loop {
|
||||
tokio::select! {
|
||||
message = messages_rx.recv() => match message {
|
||||
Some(CellMessage::Delegate {
|
||||
id,
|
||||
request,
|
||||
dispatched_tx,
|
||||
}) => {
|
||||
peer.send_delegate_if_pending(id, key.0.clone(), request, dispatched_tx).await;
|
||||
}
|
||||
Some(CellMessage::Closed) | None => break,
|
||||
},
|
||||
_ = peer.disconnected.cancelled() => {
|
||||
peer.remove_cell_route(&key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = peer.send(HostToClient::CellClosed {
|
||||
session_id: key.0.clone(),
|
||||
cell_id: (&key.1).into(),
|
||||
});
|
||||
peer.remove_cell_route(&key);
|
||||
}
|
||||
|
||||
impl HostPeer {
|
||||
fn remove_cell_route(&self, key: &(SessionId, CellId)) {
|
||||
let removed = self
|
||||
.cell_routes
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(key);
|
||||
if removed.is_some() {
|
||||
self.cell_routes_changed.notify_waiters();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) enum PeerSendError {
|
||||
Payload(String),
|
||||
Unavailable(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PeerSendError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Payload(message) | Self::Unavailable(message) => formatter.write_str(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingDelegateRequest {
|
||||
peer: Arc<HostPeer>,
|
||||
id: Option<DelegateRequestId>,
|
||||
}
|
||||
|
||||
impl PendingDelegateRequest {
|
||||
fn new(peer: Arc<HostPeer>, id: DelegateRequestId) -> Self {
|
||||
Self { peer, id: Some(id) }
|
||||
}
|
||||
|
||||
fn disarm(&mut self) {
|
||||
self.id = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PendingDelegateRequest {
|
||||
fn drop(&mut self) {
|
||||
let Some(id) = self.id.take() else {
|
||||
return;
|
||||
};
|
||||
let peer = Arc::clone(&self.peer);
|
||||
tokio::spawn(async move {
|
||||
if let Some(pending) = peer.remove_pending(id).await
|
||||
&& pending.dispatched
|
||||
{
|
||||
let _ = peer.send(HostToClient::CancelDelegateRequest { id });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "peer_tests.rs"]
|
||||
mod tests;
|
||||
99
akode-rs/code-mode-host/src/peer_tests.rs
Normal file
99
akode-rs/code-mode-host/src/peer_tests.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_code_mode_protocol::CellId;
|
||||
use akode_code_mode_protocol::RuntimeResponse;
|
||||
use akode_code_mode_protocol::StartedCell;
|
||||
use akode_code_mode_protocol::host::DelegateRequest;
|
||||
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use akode_code_mode_protocol::host::RequestId;
|
||||
use akode_code_mode_protocol::host::SessionId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::oneshot::error::TryRecvError;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::HostPeer;
|
||||
|
||||
fn session_id(value: &str) -> SessionId {
|
||||
SessionId::new(value).expect("session ID")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_cell_reports_when_initial_response_is_enqueued() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*max_capacity*/ 4);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let cell_id = CellId::new("cell-1".to_string());
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
let started = StartedCell::new(cell_id.clone(), response_rx);
|
||||
let active_cell_permits = Arc::new(Semaphore::new(/*permits*/ 1));
|
||||
let active_cell_permit = Arc::clone(&active_cell_permits)
|
||||
.try_acquire_owned()
|
||||
.expect("active cell permit");
|
||||
|
||||
let mut initial_response_sent = peer.start_cell(
|
||||
session_id("session-1"),
|
||||
RequestId::new(/*value*/ 1),
|
||||
started,
|
||||
active_cell_permit,
|
||||
Instant::now(),
|
||||
);
|
||||
assert_eq!(initial_response_sent.try_recv(), Err(TryRecvError::Empty));
|
||||
|
||||
response_tx
|
||||
.send(RuntimeResponse::Result {
|
||||
code_mode_host_duration: None,
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: Vec::new(),
|
||||
result_buffered_for: Duration::ZERO,
|
||||
error_text: None,
|
||||
})
|
||||
.expect("initial response receiver");
|
||||
initial_response_sent
|
||||
.await
|
||||
.expect("initial response completion");
|
||||
outgoing_rx.recv().await.expect("initial response frame");
|
||||
assert_eq!(active_cell_permits.available_permits(), 0);
|
||||
|
||||
peer.close_cell(session_id("session-1"), cell_id);
|
||||
let permit = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
Arc::clone(&active_cell_permits).acquire_owned(),
|
||||
)
|
||||
.await
|
||||
.expect("cell permit should be released")
|
||||
.expect("cell permit semaphore should remain open");
|
||||
drop(permit);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_delegate_limit_rejects_call_without_disconnecting() {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(/*max_capacity*/ 1);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let permits = Arc::clone(&peer.delegate_permits)
|
||||
.acquire_many_owned(MAX_PENDING_DELEGATE_CALLS as u32)
|
||||
.await
|
||||
.expect("delegate permits");
|
||||
|
||||
let result = peer
|
||||
.call(
|
||||
session_id("session-1"),
|
||||
DelegateRequest::Notify {
|
||||
call_id: "call-1".to_string(),
|
||||
cell_id: CellId::new("cell-1".to_string()).into(),
|
||||
text: "hello".to_string(),
|
||||
},
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err("code-mode host has too many pending delegate calls".to_string())
|
||||
);
|
||||
assert!(!peer.is_disconnected());
|
||||
drop(permits);
|
||||
}
|
||||
69
akode-rs/code-mode-host/src/process_metrics.rs
Normal file
69
akode-rs/code-mode-host/src/process_metrics.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
//! Isolates optional synchronous metrics collection from the HTTP/2 driver and
|
||||
//! session admission. A stuck collector occupies at most one detached thread,
|
||||
//! which is never joined during host or Tokio runtime shutdown.
|
||||
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::panic::catch_unwind;
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_code_mode_protocol::CodeModeProcessMetrics;
|
||||
use akode_code_mode_protocol::grpc;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::oneshot;
|
||||
use tonic::Response;
|
||||
use tonic::Status;
|
||||
|
||||
/// Collectors capture any resources they need before the host enters its sandbox.
|
||||
/// They must be bounded, read-only observations that do not acquire execution
|
||||
/// locks. Isolation covers unwinding panics and stalled collection, not process
|
||||
/// aborts, resource exhaustion, or interference through shared state. A collector
|
||||
/// that never returns disables further sampling for this host; it is not retried
|
||||
/// on another thread, and its worker is not joined during Tokio runtime shutdown.
|
||||
pub type CodeModeProcessMetricsCollector =
|
||||
Arc<dyn Fn() -> Result<CodeModeProcessMetrics, String> + Send + Sync>;
|
||||
|
||||
pub(crate) struct ProcessMetrics {
|
||||
collector: CodeModeProcessMetricsCollector,
|
||||
permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl ProcessMetrics {
|
||||
pub(crate) fn new(collector: CodeModeProcessMetricsCollector) -> Self {
|
||||
Self {
|
||||
collector,
|
||||
permits: Arc::new(Semaphore::new(/*permits*/ 1)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn sample(&self) -> Result<Response<grpc::GetProcessMetricsResponse>, Status> {
|
||||
let permit = self
|
||||
.permits
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| Status::resource_exhausted("process metrics collector is busy"))?;
|
||||
let collector = self.collector.clone();
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
// Do not use Tokio's blocking pool: runtime drop joins running blocking
|
||||
// tasks even after the request times out. Dropping this thread's handle
|
||||
// detaches it; the permit still bounds abandoned collection to one thread.
|
||||
std::thread::Builder::new()
|
||||
.name("code-mode-metrics".to_string())
|
||||
.spawn(move || {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| collector()));
|
||||
drop(permit);
|
||||
let _ = sender.send(result);
|
||||
})
|
||||
.map_err(|_| Status::internal("process metrics worker could not start"))?;
|
||||
let snapshot = receiver
|
||||
.await
|
||||
.map_err(|_| Status::internal("process metrics worker ended"))?
|
||||
.map_err(|_| Status::internal("process metrics collector panicked"))?
|
||||
.map_err(|_| Status::internal("process metrics collection failed"))?;
|
||||
Ok(Response::new(grpc::GetProcessMetricsResponse {
|
||||
process_id: snapshot.process_id,
|
||||
process_start_time_seconds: snapshot.process_start_time_seconds,
|
||||
cpu_seconds_total: snapshot.cpu_seconds_total,
|
||||
resident_memory_bytes: snapshot.resident_memory_bytes,
|
||||
}))
|
||||
}
|
||||
}
|
||||
52
akode-rs/code-mode-host/src/transport.rs
Normal file
52
akode-rs/code-mode-host/src/transport.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::grpc_transport;
|
||||
|
||||
/// The default transport retains the standalone host's original stdio behavior.
|
||||
pub const DEFAULT_LISTEN_URL: &str = "stdio";
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
enum ListenTransport {
|
||||
Stdio,
|
||||
GrpcStdio,
|
||||
Grpc(SocketAddr),
|
||||
}
|
||||
|
||||
pub(crate) async fn run_transport(listen_url: &str, host: crate::GrpcCodeModeHost) -> Result<()> {
|
||||
match parse_listen_url(listen_url)? {
|
||||
ListenTransport::Stdio => crate::run_stdio().await,
|
||||
ListenTransport::GrpcStdio => crate::grpc_stdio::run(host).await,
|
||||
ListenTransport::Grpc(bind_address) => {
|
||||
grpc_transport::run_tcp_listener(bind_address, host).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_listen_url(listen_url: &str) -> Result<ListenTransport> {
|
||||
if listen_url == "grpc+stdio://" {
|
||||
return Ok(ListenTransport::GrpcStdio);
|
||||
}
|
||||
if matches!(listen_url, "stdio" | "stdio://") {
|
||||
return Ok(ListenTransport::Stdio);
|
||||
}
|
||||
|
||||
if let Some(socket_addr) = listen_url.strip_prefix("grpc://") {
|
||||
return socket_addr
|
||||
.parse::<SocketAddr>()
|
||||
.map(ListenTransport::Grpc)
|
||||
.with_context(|| {
|
||||
format!("invalid gRPC --listen URL `{listen_url}`; expected `grpc://IP:PORT`")
|
||||
});
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"unsupported --listen URL `{listen_url}`; expected `grpc://IP:PORT`, `grpc+stdio://`, `stdio`, or `stdio://`"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "transport_tests.rs"]
|
||||
mod tests;
|
||||
63
akode-rs/code-mode-host/src/transport_tests.rs
Normal file
63
akode-rs/code-mode-host/src/transport_tests.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::ListenTransport;
|
||||
use super::parse_listen_url;
|
||||
use crate::grpc_transport::bind_tcp_listener;
|
||||
|
||||
#[tokio::test]
|
||||
async fn grpc_listener_disables_nagle() {
|
||||
let bind_address = "127.0.0.1:0"
|
||||
.parse()
|
||||
.expect("gRPC test listener should have a valid bind address");
|
||||
let mut listener = bind_tcp_listener(bind_address)
|
||||
.await
|
||||
.expect("gRPC test listener should bind");
|
||||
let local_addr = listener
|
||||
.local_addr()
|
||||
.expect("gRPC test listener should have a local address");
|
||||
let _client = TcpStream::connect(local_addr)
|
||||
.await
|
||||
.expect("gRPC test client should connect");
|
||||
let nodelay = listener
|
||||
.next()
|
||||
.await
|
||||
.expect("gRPC test listener should accept a connection")
|
||||
.expect("gRPC test listener should return a valid socket")
|
||||
.nodelay()
|
||||
.expect("accepted gRPC socket should expose TCP_NODELAY");
|
||||
|
||||
assert!(nodelay);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_stdio_transports() {
|
||||
assert_eq!(
|
||||
parse_listen_url("stdio").expect("stdio listen URL should parse"),
|
||||
ListenTransport::Stdio
|
||||
);
|
||||
assert_eq!(
|
||||
parse_listen_url("stdio://").expect("stdio URL should parse"),
|
||||
ListenTransport::Stdio
|
||||
);
|
||||
assert_eq!(
|
||||
parse_listen_url("grpc+stdio://").expect("gRPC stdio URL should parse"),
|
||||
ListenTransport::GrpcStdio
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_rejects_invalid_transports() {
|
||||
let invalid_address = parse_listen_url("grpc://localhost:9000")
|
||||
.expect_err("gRPC listener requires an IP address");
|
||||
assert!(
|
||||
invalid_address
|
||||
.to_string()
|
||||
.contains("expected `grpc://IP:PORT`")
|
||||
);
|
||||
|
||||
let unsupported =
|
||||
parse_listen_url("http://127.0.0.1:9000").expect_err("HTTP is not a listen transport");
|
||||
assert!(unsupported.to_string().contains("unsupported --listen URL"));
|
||||
}
|
||||
213
akode-rs/code-mode-host/tests/capacity.rs
Normal file
213
akode-rs/code-mode-host/tests/capacity.rs
Normal file
@@ -0,0 +1,213 @@
|
||||
//! Shared-host capacity, callback completion, and unrelated-session progress.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_code_mode::CellId;
|
||||
use akode_code_mode::CodeModeNestedToolCall;
|
||||
use akode_code_mode::CodeModeSessionDelegate;
|
||||
use akode_code_mode::CodeModeSessionProvider;
|
||||
use akode_code_mode::CodeModeToolKind;
|
||||
use akode_code_mode::ExecuteRequest;
|
||||
use akode_code_mode::FunctionCallOutputContentItem;
|
||||
use akode_code_mode::GrpcCodeModeSessionProvider;
|
||||
use akode_code_mode::NotificationFuture;
|
||||
use akode_code_mode::ProcessOwnedCodeModeSessionProvider;
|
||||
use akode_code_mode::RuntimeResponse;
|
||||
use akode_code_mode::ToolDefinition;
|
||||
use akode_code_mode::ToolInvocationFuture;
|
||||
use akode_code_mode::WaitOutcome;
|
||||
use akode_code_mode::WaitRequest;
|
||||
use akode_protocol::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
|
||||
struct BlockingDelegate {
|
||||
started: Semaphore,
|
||||
release: Semaphore,
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for BlockingDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
_invocation: CodeModeNestedToolCall,
|
||||
cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
self.started.add_permits(1);
|
||||
tokio::select! {
|
||||
permit = self.release.acquire() => {
|
||||
permit.map_err(|error| error.to_string())?.forget();
|
||||
Ok(json!("done"))
|
||||
}
|
||||
_ = cancellation.cancelled() => Err("cancelled".to_string()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
_cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {}
|
||||
}
|
||||
|
||||
#[allow(clippy::expect_used)]
|
||||
async fn assert_shared_capacity(
|
||||
provider: &dyn CodeModeSessionProvider,
|
||||
cells: usize,
|
||||
calls_per_cell: usize,
|
||||
) {
|
||||
let delegate = Arc::new(BlockingDelegate {
|
||||
started: Semaphore::new(/*permits*/ 0),
|
||||
release: Semaphore::new(/*permits*/ 0),
|
||||
});
|
||||
let mut sessions = Vec::new();
|
||||
for _ in 0..2 {
|
||||
sessions.push(
|
||||
provider
|
||||
.create_session()
|
||||
.await
|
||||
.expect("create shared session"),
|
||||
);
|
||||
}
|
||||
let mut pending = Vec::new();
|
||||
for index in 0..cells {
|
||||
let session = &sessions[index % sessions.len()];
|
||||
let request = ExecuteRequest {
|
||||
tool_call_id: format!("capacity-{index}"),
|
||||
enabled_tools: vec![ToolDefinition {
|
||||
name: "block".to_string(),
|
||||
tool_name: ToolName::plain("block"),
|
||||
description: String::new(),
|
||||
kind: CodeModeToolKind::Function,
|
||||
input_schema: None,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: None,
|
||||
}],
|
||||
source: format!(
|
||||
"const results = await Promise.all(Array.from({{length: {calls_per_cell}}}, () => tools.block({{}}))); text(results.length);"
|
||||
),
|
||||
yield_time_ms: Some(1),
|
||||
max_output_tokens: None,
|
||||
};
|
||||
let started = session
|
||||
.execute(request, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("admit cell {index}: {error}"));
|
||||
let cell_id = started.cell_id.clone();
|
||||
let response = started.initial_response().await.expect("initial response");
|
||||
assert!(
|
||||
matches!(response, RuntimeResponse::Yielded { .. }),
|
||||
"{response:?}"
|
||||
);
|
||||
pending.push((Arc::clone(session), cell_id));
|
||||
}
|
||||
let callbacks = cells * calls_per_cell;
|
||||
delegate
|
||||
.started
|
||||
.acquire_many(callbacks as u32)
|
||||
.await
|
||||
.expect("all callbacks started")
|
||||
.forget();
|
||||
|
||||
let probe = sessions[0]
|
||||
.execute(
|
||||
ExecuteRequest {
|
||||
tool_call_id: "unrelated-probe".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: "text('ready');".to_string(),
|
||||
yield_time_ms: Some(60_000),
|
||||
max_output_tokens: None,
|
||||
},
|
||||
delegate.clone(),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("unrelated work admitted")
|
||||
.initial_response()
|
||||
.await
|
||||
.expect("unrelated work completed");
|
||||
assert!(
|
||||
matches!(
|
||||
probe,
|
||||
RuntimeResponse::Result {
|
||||
error_text: None,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{probe:?}"
|
||||
);
|
||||
|
||||
delegate.release.add_permits(callbacks);
|
||||
for (session, cell_id) in pending {
|
||||
let result = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id,
|
||||
yield_time_ms: 60_000,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("collect callback results");
|
||||
let WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
content_items,
|
||||
error_text,
|
||||
..
|
||||
}) = result
|
||||
else {
|
||||
panic!("expected completed cell: {result:?}");
|
||||
};
|
||||
assert_eq!(
|
||||
(content_items, error_text),
|
||||
(
|
||||
vec![FunctionCallOutputContentItem::InputText {
|
||||
text: calls_per_cell.to_string()
|
||||
}],
|
||||
None
|
||||
)
|
||||
);
|
||||
}
|
||||
for session in sessions {
|
||||
session.shutdown().await.expect("close shared session");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stdio_shared_sessions_complete_thousands_of_callbacks() {
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
akode_utils_cargo_bin::cargo_bin("akode-code-mode-host").expect("host binary"),
|
||||
);
|
||||
assert_shared_capacity(&provider, /*cells*/ 256, /*calls_per_cell*/ 16).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grpc_shared_sessions_complete_thousands_of_callbacks() {
|
||||
let host = host::HostHarness::start("grpc://127.0.0.1:0")
|
||||
.await
|
||||
.expect("host");
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
assert_shared_capacity(&provider, /*cells*/ 256, /*calls_per_cell*/ 16).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires resources for 2,048 live V8 isolates and OS threads"]
|
||||
async fn grpc_full_host_capacity() {
|
||||
let host = host::HostHarness::start("grpc://127.0.0.1:0")
|
||||
.await
|
||||
.expect("host");
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
assert_shared_capacity(&provider, /*cells*/ 2_047, /*calls_per_cell*/ 2).await;
|
||||
}
|
||||
1527
akode-rs/code-mode-host/tests/grpc.rs
Normal file
1527
akode-rs/code-mode-host/tests/grpc.rs
Normal file
File diff suppressed because it is too large
Load Diff
320
akode-rs/code-mode-host/tests/grpc/admission_tests.rs
Normal file
320
akode-rs/code-mode-host/tests/grpc/admission_tests.rs
Normal file
@@ -0,0 +1,320 @@
|
||||
//! Initial admission may retry transient failures; established work must not replay.
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_admission_retries_only_transient_failures_and_is_bounded() -> Result<()> {
|
||||
for (code, failures, expected_attempts, succeeds) in [
|
||||
(Code::Unavailable, 1, 2, true),
|
||||
(Code::ResourceExhausted, 1, 2, true),
|
||||
(Code::Unavailable, usize::MAX, 5, false),
|
||||
(Code::InvalidArgument, 1, 1, false),
|
||||
(Code::Unknown, 1, 1, false),
|
||||
] {
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
let count = Arc::clone(&attempts);
|
||||
let app = axum::Router::new()
|
||||
.fallback_service(grpc::code_mode_host_server::CodeModeHostServer::new(
|
||||
akode_code_mode_host::GrpcCodeModeHost::new(),
|
||||
))
|
||||
.layer(axum::middleware::from_fn(
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let count = Arc::clone(&count);
|
||||
async move {
|
||||
if request.uri().path().ends_with("/OpenSession")
|
||||
&& count.fetch_add(1, Ordering::SeqCst) < failures
|
||||
{
|
||||
return tonic::Status::new(code, "transient admission test")
|
||||
.into_http::<axum::body::Body>();
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
},
|
||||
));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("admission test server");
|
||||
}));
|
||||
let provider = GrpcCodeModeSessionProvider::new(format!("http://{address}"));
|
||||
let result = timeout(TEST_TIMEOUT, provider.create_session()).await?;
|
||||
assert_eq!(
|
||||
result.is_ok(),
|
||||
succeeds,
|
||||
"status {code}: {}",
|
||||
result.as_ref().err().cloned().unwrap_or_default()
|
||||
);
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), expected_attempts);
|
||||
if let Ok(session) = result {
|
||||
let response = execute(
|
||||
&session,
|
||||
request("text(42);"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
response,
|
||||
text_response("1", "42", response.code_mode_host_duration())
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
drop(server);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_admission_recovers_after_connection_reset() -> Result<()> {
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
// Drop the first connection with unread HTTP/2 bytes to send TCP RST.
|
||||
// Serve the next connection normally; no timer or launcher mock is needed.
|
||||
let (mut stream, _) = listener.accept().await?;
|
||||
stream.read_exact(&mut [0]).await?;
|
||||
drop(stream);
|
||||
let app = axum::Router::new().fallback_service(
|
||||
grpc::code_mode_host_server::CodeModeHostServer::new(
|
||||
akode_code_mode_host::GrpcCodeModeHost::new(),
|
||||
),
|
||||
);
|
||||
axum::serve(listener, app).await
|
||||
}));
|
||||
let provider = GrpcCodeModeSessionProvider::new(format!("http://{address}"));
|
||||
let session = timeout(TEST_TIMEOUT, provider.create_session())
|
||||
.await?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let response = execute(
|
||||
&session,
|
||||
request("text(42);"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
response,
|
||||
text_response("1", "42", response.code_mode_host_duration())
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
drop(server);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn routing_metadata_is_scoped_to_each_session_on_a_shared_provider() -> Result<()> {
|
||||
use axum::body::Body;
|
||||
use axum::extract::Request;
|
||||
use axum::response::Response;
|
||||
use tonic::codegen::Service;
|
||||
|
||||
let backends = Arc::new(["a", "b"].map(|_| {
|
||||
axum::Router::new().fallback_service(grpc::code_mode_host_server::CodeModeHostServer::new(
|
||||
akode_code_mode_host::GrpcCodeModeHost::new(),
|
||||
))
|
||||
}));
|
||||
let admissions = Arc::new(AtomicUsize::new(0));
|
||||
let rejection = Arc::new(std::sync::Mutex::new(/*t*/ None::<tonic::Status>));
|
||||
let rejected_executions = Arc::new(AtomicUsize::new(0));
|
||||
let next_rejection = Arc::clone(&rejection);
|
||||
let executions = Arc::clone(&rejected_executions);
|
||||
let opens = Arc::clone(&admissions);
|
||||
let app = axum::Router::new().fallback(move |request: Request| {
|
||||
let backends = Arc::clone(&backends);
|
||||
let admissions = Arc::clone(&admissions);
|
||||
let rejection = Arc::clone(&next_rejection);
|
||||
let executions = Arc::clone(&executions);
|
||||
async move {
|
||||
let opening = request.uri().path().ends_with("/OpenSession");
|
||||
let route = request.headers().get("x-code-mode-route");
|
||||
let token = if opening {
|
||||
assert_eq!(
|
||||
route, None,
|
||||
"a new admission must not inherit any session's route"
|
||||
);
|
||||
match admissions.fetch_add(1, Ordering::SeqCst) {
|
||||
0 => {
|
||||
// Even a rejected admission can carry response metadata. The
|
||||
// next attempt must still be free to select another backend.
|
||||
let mut response =
|
||||
tonic::Status::resource_exhausted("full").into_http::<Body>();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-code-mode-route", "rejected".parse().unwrap());
|
||||
return response;
|
||||
}
|
||||
1 => "a",
|
||||
_ => "b",
|
||||
}
|
||||
} else {
|
||||
route
|
||||
.expect("every session RPC needs its routing token")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
};
|
||||
let index = match token {
|
||||
"a" => 0,
|
||||
"b" => 1,
|
||||
_ => panic!("unexpected routing token"),
|
||||
};
|
||||
if token == "a"
|
||||
&& request.uri().path().ends_with("/Execute")
|
||||
&& let Some(error) = rejection.lock().unwrap().as_ref()
|
||||
{
|
||||
executions.fetch_add(1, Ordering::SeqCst);
|
||||
return error.clone().into_http::<Body>();
|
||||
}
|
||||
let mut response: Response = backends[index].clone().call(request).await.unwrap();
|
||||
if opening {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-code-mode-route", ["a", "b"][index].parse().unwrap());
|
||||
}
|
||||
response
|
||||
}
|
||||
});
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let _server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("routing test server");
|
||||
}));
|
||||
let provider = GrpcCodeModeSessionProvider::new(format!("http://{address}"));
|
||||
let parent = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let child = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
for (session, value) in [(&parent, 11), (&child, 22), (&parent, 33)] {
|
||||
let mut req = request(&format!(
|
||||
"await tools.echo({{value: {value}}}); text({value});"
|
||||
));
|
||||
req.enabled_tools = vec![tool("echo")];
|
||||
let actual = execute(session, req, Arc::new(RecordingDelegate::default())).await?;
|
||||
let RuntimeResponse::Result { error_text, .. } = actual else {
|
||||
anyhow::bail!("session did not finish");
|
||||
};
|
||||
assert_eq!(error_text, None);
|
||||
let mut req = request("await new Promise(() => {});");
|
||||
req.yield_time_ms = Some(1);
|
||||
let started = session
|
||||
.execute(
|
||||
req,
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let id = started.cell_id.clone();
|
||||
assert!(matches!(
|
||||
started
|
||||
.initial_response()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?,
|
||||
RuntimeResponse::Yielded { .. }
|
||||
));
|
||||
let outcome = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: id.clone(),
|
||||
yield_time_ms: 1,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert!(matches!(
|
||||
outcome,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Yielded { .. })
|
||||
));
|
||||
session
|
||||
.terminate(id.into())
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
for session in [&parent, &child] {
|
||||
execute(
|
||||
session,
|
||||
request(r#"store("preserved", "original");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
for retired in [false, true] {
|
||||
let mut error = tonic::Status::unavailable("no healthy upstream");
|
||||
if retired {
|
||||
error
|
||||
.metadata_mut()
|
||||
.insert("x-code-mode-route-lost", "true".parse()?);
|
||||
}
|
||||
*rejection.lock().unwrap() = Some(error);
|
||||
let opens_before = opens.load(Ordering::SeqCst);
|
||||
let failures_before = rejected_executions.load(Ordering::SeqCst);
|
||||
execute(
|
||||
&parent,
|
||||
request(r#"store("preserved", "replayed");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.expect_err("the rejected execution must not be replayed");
|
||||
assert_eq!(opens.load(Ordering::SeqCst), opens_before);
|
||||
assert_eq!(
|
||||
rejected_executions.load(Ordering::SeqCst),
|
||||
failures_before + 1
|
||||
);
|
||||
if !retired {
|
||||
*rejection.lock().unwrap() = None;
|
||||
} else {
|
||||
let reset = execute(
|
||||
&parent,
|
||||
request(r#"store("preserved", "must not run");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.expect_err("route loss must report the reset before executing new code");
|
||||
assert!(
|
||||
reset
|
||||
.to_string()
|
||||
.contains("Stored values and running cells were lost")
|
||||
);
|
||||
}
|
||||
// The old lease and callback streams are still open. Only the explicit
|
||||
// route-loss response may replace the parent; the child must keep its state.
|
||||
for (session, expected) in [
|
||||
(&parent, if retired { "undefined" } else { "original" }),
|
||||
(&child, "original"),
|
||||
] {
|
||||
let actual = execute(
|
||||
session,
|
||||
request(r#"text(String(load("preserved")));"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
let RuntimeResponse::Result { cell_id, .. } = &actual else {
|
||||
anyhow::bail!("execution did not finish");
|
||||
};
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response(cell_id.as_str(), expected, actual.code_mode_host_duration())
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
opens.load(Ordering::SeqCst),
|
||||
opens_before + usize::from(retired)
|
||||
);
|
||||
}
|
||||
parent.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
child.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Cancellation of reentrant image getters through the standalone host.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_stops_reentrant_image_getter() -> Result<()> {
|
||||
// Force reentry and JSON fallback at a shallow depth, independent of stack limits.
|
||||
let source = r#"
|
||||
let calls = 0;
|
||||
const deadline = Date.now() + 60000;
|
||||
const value = {
|
||||
get image_url() {
|
||||
switch (++calls) {
|
||||
case 1: image(value); return "";
|
||||
case 2: throw new Error("enter fallback");
|
||||
default:
|
||||
notify("started");
|
||||
while (Date.now() < deadline) {}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
};
|
||||
try { image(value); } catch { text(calls); }
|
||||
"#;
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let other_session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let other_response = execute(
|
||||
&other_session,
|
||||
request(r#"store("alive", "yes"); text("yes");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
other_response,
|
||||
text_response("g2:1", "yes", other_response.code_mode_host_duration())
|
||||
);
|
||||
|
||||
let delegate = Arc::new(RecordingDelegate::default());
|
||||
let mut pending = request(source);
|
||||
pending.yield_time_ms = Some(60_000);
|
||||
let started = session
|
||||
.execute(pending, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let id = started.cell_id.clone();
|
||||
// The second image call enters JSON fallback; wait until its getter is running.
|
||||
timeout(TEST_TIMEOUT, delegate.notification_delivered.notified())
|
||||
.await
|
||||
.context("getter did not signal startup")?;
|
||||
|
||||
let result = timeout(Duration::from_secs(1), session.terminate(id.clone().into()))
|
||||
.await
|
||||
.context("workload did not stop within the cancellation deadline")?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
// The getter would otherwise run for 60 seconds and emit its counter.
|
||||
assert_eq!(
|
||||
result,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
|
||||
code_mode_host_duration: result.code_mode_host_duration(),
|
||||
cell_id: id.clone(),
|
||||
content_items: Vec::new(),
|
||||
})
|
||||
);
|
||||
let initial = timeout(TEST_TIMEOUT, started.initial_response())
|
||||
.await
|
||||
.context("initial termination response did not arrive")?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
initial,
|
||||
RuntimeResponse::Terminated {
|
||||
code_mode_host_duration: initial.code_mode_host_duration(),
|
||||
cell_id: id,
|
||||
content_items: Vec::new(),
|
||||
}
|
||||
);
|
||||
let other_response = execute(
|
||||
&other_session,
|
||||
request(r#"text(load("alive"));"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
other_response,
|
||||
text_response("g2:2", "yes", other_response.code_mode_host_duration())
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
other_session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
100
akode-rs/code-mode-host/tests/grpc/network_policy_tests.rs
Normal file
100
akode-rs/code-mode-host/tests/grpc/network_policy_tests.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
//! Destination admission and account revocation cover the gRPC request lifetime.
|
||||
|
||||
use akode_http_client::DestinationPolicy;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use akode_http_client::NetworkPolicyController;
|
||||
use akode_http_client::OutboundProxyPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn restricted_destination_is_rejected_before_connecting_to_the_code_mode_host() -> Result<()>
|
||||
{
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let controller = NetworkPolicyController::default();
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Restricted {
|
||||
allowed_hosts: ["allowed.example".into()].into()
|
||||
}
|
||||
));
|
||||
let provider = Arc::new(GrpcCodeModeSessionProvider::with_http_client_factory(
|
||||
format!("https://{}", listener.local_addr()?),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(controller.policy()),
|
||||
));
|
||||
let Err(error) = provider.create_session().await else {
|
||||
anyhow::bail!("restricted endpoint created a session")
|
||||
};
|
||||
assert!(
|
||||
error.contains("destination denied by application network policy"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
timeout(Duration::from_millis(/*millis*/ 50), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_change_revokes_active_rpc_and_renews_the_cached_client() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let controller = NetworkPolicyController::default();
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Unrestricted
|
||||
));
|
||||
let provider = GrpcCodeModeSessionProvider::with_http_client_factory(
|
||||
host.endpoint.clone(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(controller.policy()),
|
||||
);
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let mut pending = request("await new Promise(() => {});");
|
||||
pending.yield_time_ms = Some(60_000);
|
||||
let started = session
|
||||
.execute(
|
||||
pending,
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
controller.policy().invalidate();
|
||||
assert!(
|
||||
timeout(TEST_TIMEOUT, started.initial_response())
|
||||
.await
|
||||
.context("account revocation did not interrupt the active RPC")?
|
||||
.is_err()
|
||||
);
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Unrestricted
|
||||
));
|
||||
|
||||
let replacement = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let response = execute(
|
||||
&replacement,
|
||||
request(r#"text("replacement")"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
response,
|
||||
text_response("g2:1", "replacement", response.code_mode_host_duration())
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
replacement.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
217
akode-rs/code-mode-host/tests/grpc/process_metrics_tests.rs
Normal file
217
akode-rs/code-mode-host/tests/grpc/process_metrics_tests.rs
Normal file
@@ -0,0 +1,217 @@
|
||||
//! Process observations are independent of session state and HTTP/2 keepalive.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use akode_code_mode::CodeModeProcessMetrics;
|
||||
use akode_code_mode::CodeModeProcessMetricsSample;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio_stream::wrappers::TcpListenerStream;
|
||||
use tonic::transport::Endpoint;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn metrics_failures_and_deadlines_preserve_sessions_and_keepalive() -> Result<()> {
|
||||
let snapshot = CodeModeProcessMetrics {
|
||||
process_id: 42,
|
||||
process_start_time_seconds: 1_700_000_000.0,
|
||||
cpu_seconds_total: 1.5,
|
||||
resident_memory_bytes: 4096,
|
||||
};
|
||||
let expected = snapshot.clone();
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let collector_calls = calls.clone();
|
||||
let (release, blocked) = std::sync::mpsc::channel::<()>();
|
||||
let blocked = Mutex::new(blocked);
|
||||
let host = akode_code_mode_host::GrpcCodeModeHost::with_process_metrics(Arc::new(move || {
|
||||
match collector_calls.fetch_add(1, Ordering::SeqCst) {
|
||||
0 => Ok(snapshot.clone()),
|
||||
1 => Err("metrics unavailable".to_string()),
|
||||
2 => panic!("collector panic"),
|
||||
_ => {
|
||||
blocked
|
||||
.lock()
|
||||
.unwrap()
|
||||
.recv()
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(snapshot.clone())
|
||||
}
|
||||
}
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let connections = Arc::new(AtomicUsize::new(0));
|
||||
let accepted = connections.clone();
|
||||
let incoming = TcpListenerStream::new(listener).inspect(move |connection| {
|
||||
if connection.is_ok() {
|
||||
accepted.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
tonic::transport::Server::builder()
|
||||
.add_service(grpc::code_mode_host_server::CodeModeHostServer::new(host))
|
||||
.serve_with_incoming(incoming)
|
||||
.await
|
||||
}));
|
||||
// Multiple keepalive intervals elapse while the collector is blocked, even
|
||||
// on this single-threaded runtime. A stalled HTTP/2 driver would lose state.
|
||||
let channel = Endpoint::from_shared(format!("http://{address}"))?
|
||||
.http2_keep_alive_interval(Duration::from_millis(/*millis*/ 50))
|
||||
.keep_alive_timeout(Duration::from_millis(/*millis*/ 100))
|
||||
.keep_alive_while_idle(/*enabled*/ true)
|
||||
.connect()
|
||||
.await?;
|
||||
let provider = GrpcCodeModeSessionProvider::with_channel(channel);
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
execute(
|
||||
&session,
|
||||
request("store('survives', 42);"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
provider
|
||||
.sample_process_metrics()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?,
|
||||
CodeModeProcessMetricsSample::Snapshot(expected)
|
||||
);
|
||||
for cell in 2..=4 {
|
||||
assert!(provider.sample_process_metrics().await.is_err());
|
||||
let response = execute(
|
||||
&session,
|
||||
request("text(load('survives'));"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
response,
|
||||
text_response(&cell.to_string(), "42", response.code_mode_host_duration())
|
||||
);
|
||||
}
|
||||
// A canceled blocked RPC retains its collector quota: no unbounded worker
|
||||
// threads are added, and neither the sample nor overload opens another channel.
|
||||
assert!(provider.sample_process_metrics().await.is_err());
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 4);
|
||||
assert_eq!(connections.load(Ordering::SeqCst), 1);
|
||||
release.send(())?;
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
drop(server);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A running server's collection precondition failure is not local host absence.
|
||||
#[tokio::test]
|
||||
async fn remote_metrics_precondition_is_a_failure() -> Result<()> {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
tonic::transport::Server::builder()
|
||||
.add_service(
|
||||
grpc::code_mode_host_server::CodeModeHostServer::with_interceptor(
|
||||
akode_code_mode_host::GrpcCodeModeHost::new(),
|
||||
|_request| {
|
||||
Err(tonic::Status::failed_precondition(
|
||||
"collector is misconfigured",
|
||||
))
|
||||
},
|
||||
),
|
||||
)
|
||||
.serve_with_incoming(TcpListenerStream::new(listener))
|
||||
.await
|
||||
}));
|
||||
let channel = Endpoint::from_shared(format!("http://{address}"))?
|
||||
.connect()
|
||||
.await?;
|
||||
let provider = GrpcCodeModeSessionProvider::with_channel(channel);
|
||||
let error = provider.sample_process_metrics().await.unwrap_err();
|
||||
assert!(error.contains("collector is misconfigured"), "{error}");
|
||||
drop(server);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A permanently stuck collector is bounded and cannot hang normal runtime drop.
|
||||
#[test]
|
||||
fn stuck_collector_does_not_block_runtime_shutdown() -> Result<()> {
|
||||
const CHILD_ENV: &str = "CODE_MODE_METRICS_SHUTDOWN_TEST_CHILD";
|
||||
if let Some(shutdown_marker) = std::env::var_os(CHILD_ENV) {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
runtime.block_on(async {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let collector_calls = calls.clone();
|
||||
let host =
|
||||
akode_code_mode_host::GrpcCodeModeHost::with_process_metrics(Arc::new(move || {
|
||||
collector_calls.fetch_add(1, Ordering::SeqCst);
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
tonic::transport::Server::builder()
|
||||
.add_service(grpc::code_mode_host_server::CodeModeHostServer::new(host))
|
||||
.serve_with_incoming(TcpListenerStream::new(listener))
|
||||
.await
|
||||
}));
|
||||
let channel = Endpoint::from_shared(format!("http://{address}"))?
|
||||
.connect()
|
||||
.await?;
|
||||
let provider = GrpcCodeModeSessionProvider::with_channel(channel);
|
||||
assert!(provider.sample_process_metrics().await.is_err());
|
||||
let busy = provider.sample_process_metrics().await.unwrap_err();
|
||||
assert!(busy.contains("collector is busy"), "{busy}");
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
drop(server);
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})?;
|
||||
let shutdown_marker = std::path::PathBuf::from(shutdown_marker);
|
||||
std::fs::write(shutdown_marker.with_extension("started"), "")?;
|
||||
drop(runtime);
|
||||
std::fs::write(shutdown_marker, "runtime dropped")?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let directory = tempfile::tempdir()?;
|
||||
let shutdown_marker = directory.path().join("shutdown-completed");
|
||||
let mut child = std::process::Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"process_metrics_tests::stuck_collector_does_not_block_runtime_shutdown",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_ENV, &shutdown_marker)
|
||||
.spawn()?;
|
||||
let shutdown_started = shutdown_marker.with_extension("started");
|
||||
let startup_deadline = std::time::Instant::now() + Duration::from_secs(60);
|
||||
let mut shutdown_deadline = None;
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
assert!(status.success(), "metrics subprocess failed: {status}");
|
||||
assert_eq!(std::fs::read_to_string(shutdown_marker)?, "runtime dropped");
|
||||
return Ok(());
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
if shutdown_deadline.is_none() && shutdown_started.exists() {
|
||||
shutdown_deadline = Some(now + Duration::from_secs(10));
|
||||
}
|
||||
if now >= shutdown_deadline.unwrap_or(startup_deadline) {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
anyhow::ensure!(
|
||||
shutdown_deadline.is_some(),
|
||||
"metrics subprocess startup timed out"
|
||||
);
|
||||
anyhow::bail!("a stuck metrics collector blocked runtime shutdown");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(/*millis*/ 10));
|
||||
}
|
||||
}
|
||||
378
akode-rs/code-mode-host/tests/grpc/session_recovery_tests.rs
Normal file
378
akode-rs/code-mode-host/tests/grpc/session_recovery_tests.rs
Normal file
@@ -0,0 +1,378 @@
|
||||
//! Exercises missing-session recovery while the host's lease streams remain open.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use anyhow::Result;
|
||||
use akode_code_mode::CodeModeOutputTruncation;
|
||||
use akode_code_mode::CodeModeSessionOptions;
|
||||
use akode_code_mode::CodeModeSessionProvider;
|
||||
use akode_code_mode::FunctionCallOutputContentItem;
|
||||
use akode_code_mode::GrpcCodeModeSessionProvider;
|
||||
use akode_code_mode::NoopCodeModeSessionDelegate;
|
||||
use akode_code_mode::RuntimeResponse;
|
||||
use akode_code_mode_host::GrpcCodeModeHost;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_server::CodeModeHostServer;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_stream::wrappers::TcpListenerStream;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use tonic::Code;
|
||||
use tonic::Status;
|
||||
use tonic::transport::Server;
|
||||
|
||||
use super::execute;
|
||||
use super::request;
|
||||
use super::text_response;
|
||||
|
||||
#[tokio::test]
|
||||
async fn quiet_session_reuses_its_worker_connection() -> Result<()> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("http://{}", listener.local_addr()?);
|
||||
let connections = Arc::new(AtomicUsize::new(0));
|
||||
let accepted = Arc::clone(&connections);
|
||||
let incoming = TcpListenerStream::new(listener).inspect(move |_| {
|
||||
accepted.fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
let _server = AbortOnDropHandle::new(tokio::spawn(
|
||||
Server::builder()
|
||||
.add_service(CodeModeHostServer::new(GrpcCodeModeHost::new()))
|
||||
.serve_with_incoming(incoming),
|
||||
));
|
||||
let session = GrpcCodeModeSessionProvider::new(endpoint)
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
execute(
|
||||
&session,
|
||||
request(r#"store("key", "persisted");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(std::time::Duration::from_secs(120)).await;
|
||||
tokio::time::resume();
|
||||
|
||||
let result = execute(
|
||||
&session,
|
||||
request(r#"text(load("key"));"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
result,
|
||||
text_response("2", "persisted", result.code_mode_host_duration())
|
||||
);
|
||||
assert_eq!(connections.load(Ordering::SeqCst), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn last_failed_session_releases_the_shared_connection() -> Result<()> {
|
||||
let reject = Arc::new(AtomicBool::new(false));
|
||||
let reject_next_rpc = Arc::clone(&reject);
|
||||
let service = CodeModeHostServer::with_interceptor(GrpcCodeModeHost::new(), move |req| {
|
||||
if reject_next_rpc.swap(false, Ordering::SeqCst) {
|
||||
Err(Status::not_found("session was lost"))
|
||||
} else {
|
||||
Ok(req)
|
||||
}
|
||||
});
|
||||
let host = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let host_addr = host.local_addr()?;
|
||||
let _server = AbortOnDropHandle::new(tokio::spawn(
|
||||
Server::builder()
|
||||
.add_service(service)
|
||||
.serve_with_incoming(TcpListenerStream::new(host)),
|
||||
));
|
||||
|
||||
// Forward exactly one TCP connection. Its EOF is the worker-release signal.
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(format!("http://{}", listener.local_addr()?));
|
||||
let connection = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let (mut client, _) = listener.accept().await?;
|
||||
drop(listener);
|
||||
let mut host = TcpStream::connect(host_addr).await?;
|
||||
tokio::io::copy_bidirectional(&mut client, &mut host).await
|
||||
}));
|
||||
let first = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let last = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
first.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
let result = execute(
|
||||
&last,
|
||||
request("text('still live')"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
result,
|
||||
text_response("g2:1", "still live", result.code_mode_host_duration())
|
||||
);
|
||||
|
||||
reject.store(true, Ordering::SeqCst);
|
||||
let error = execute(
|
||||
&last,
|
||||
request("text('must not run')"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"gRPC code-mode execution failed: {}",
|
||||
Status::not_found("session was lost")
|
||||
)
|
||||
);
|
||||
tokio::time::timeout(super::TEST_TIMEOUT, connection)
|
||||
.await
|
||||
.expect("last failed session kept its worker connection open")??;
|
||||
drop((first, last, provider));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_missing_sessions_reopen_without_replaying_execution() -> Result<()> {
|
||||
for (code, route_lost, expected_cell, expected_value) in [
|
||||
(Code::NotFound, false, "g2:1", "undefined"),
|
||||
(Code::InvalidArgument, false, "2", "1"),
|
||||
(Code::Unavailable, false, "2", "1"),
|
||||
(Code::Unavailable, true, "2", "1"),
|
||||
] {
|
||||
let rejection = Arc::new(Mutex::new(/*t*/ None));
|
||||
let next_rejection = Arc::clone(&rejection);
|
||||
let request_count = Arc::new(AtomicUsize::new(/*v*/ 0));
|
||||
let count = Arc::clone(&request_count);
|
||||
let service = CodeModeHostServer::with_interceptor(
|
||||
GrpcCodeModeHost::new(),
|
||||
move |request: tonic::Request<()>| {
|
||||
count.fetch_add(/*val*/ 1, Ordering::SeqCst);
|
||||
match next_rejection.lock().unwrap().take() {
|
||||
Some(rejection) => Err(rejection),
|
||||
None => Ok(request),
|
||||
}
|
||||
},
|
||||
);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("http://{}", listener.local_addr()?);
|
||||
let _server = AbortOnDropHandle::new(tokio::spawn(
|
||||
Server::builder()
|
||||
.add_service(service)
|
||||
.serve_with_incoming(TcpListenerStream::new(listener)),
|
||||
));
|
||||
let session = GrpcCodeModeSessionProvider::new(endpoint)
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
session.output_truncation(),
|
||||
CodeModeOutputTruncation::Client
|
||||
);
|
||||
execute(
|
||||
&session,
|
||||
request(r#"store("before", 1);"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Reject the next Execute without closing the lease or subscription streams.
|
||||
let mut failure = Status::new(code, "injected RPC rejection");
|
||||
if route_lost {
|
||||
// A direct host has no proxy route to retire.
|
||||
failure
|
||||
.metadata_mut()
|
||||
.insert("x-code-mode-route-lost", "true".parse()?);
|
||||
}
|
||||
*rejection.lock().unwrap() = Some(failure.clone());
|
||||
let requests_before_rejection = request_count.load(Ordering::SeqCst);
|
||||
let failed = execute(
|
||||
&session,
|
||||
request(r#"store("before", "replayed");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
failed.to_string(),
|
||||
format!("gRPC code-mode execution failed: {failure}")
|
||||
);
|
||||
assert_eq!(
|
||||
request_count.load(Ordering::SeqCst),
|
||||
requests_before_rejection + 1,
|
||||
"the failed call must return without opening a session or replaying Execute"
|
||||
);
|
||||
if code == Code::NotFound {
|
||||
let reset = execute(
|
||||
&session,
|
||||
request(r#"store("before", "must not run");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
reset
|
||||
.to_string()
|
||||
.contains("Stored values and running cells were lost")
|
||||
);
|
||||
}
|
||||
let actual = execute(
|
||||
&session,
|
||||
request(r#"text(String(load("before")))"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response(
|
||||
expected_cell,
|
||||
expected_value,
|
||||
actual.code_mode_host_duration()
|
||||
)
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grpc_session_pins_output_mode_across_recovery_and_shutdown() -> Result<()> {
|
||||
use CodeModeOutputTruncation::Client;
|
||||
use CodeModeOutputTruncation::Server;
|
||||
use axum::body::Body;
|
||||
use axum::extract::Request;
|
||||
use axum::middleware::Next;
|
||||
|
||||
// A Server-capable host honors either choice. A Client-only host ignores the new field.
|
||||
for (initial_host, replacement_host) in [(Server, Server), (Server, Client), (Client, Server)] {
|
||||
let opens = Arc::new(AtomicUsize::new(0));
|
||||
let subscriptions = Arc::new(AtomicUsize::new(0));
|
||||
let subscription_count = Arc::clone(&subscriptions);
|
||||
let app = axum::Router::new()
|
||||
.fallback_service(CodeModeHostServer::new(GrpcCodeModeHost::new()))
|
||||
.layer(axum::middleware::from_fn(
|
||||
move |mut rpc: Request, next: Next| {
|
||||
let opens = Arc::clone(&opens);
|
||||
let subscriptions = Arc::clone(&subscription_count);
|
||||
async move {
|
||||
if rpc.uri().path().ends_with("/OpenSession") {
|
||||
let host = if opens.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
initial_host
|
||||
} else {
|
||||
replacement_host
|
||||
};
|
||||
if host == Client {
|
||||
// No resource limits were requested, so ignoring the output mode
|
||||
// leaves an empty OpenSessionRequest in one uncompressed gRPC frame.
|
||||
rpc.headers_mut().remove("content-length");
|
||||
*rpc.body_mut() = Body::from(&[0_u8; 5][..]);
|
||||
}
|
||||
} else if rpc.uri().path().ends_with("/Execute")
|
||||
&& opens.load(Ordering::SeqCst) == 1
|
||||
{
|
||||
return Status::not_found("session was lost").into_http::<Body>();
|
||||
} else if rpc.uri().path().ends_with("/SubscribeToToolCalls") {
|
||||
subscriptions.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
next.run(rpc).await
|
||||
}
|
||||
},
|
||||
));
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("http://{}", listener.local_addr()?);
|
||||
let _server = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("recovery test host");
|
||||
}));
|
||||
let session = GrpcCodeModeSessionProvider::new(endpoint)
|
||||
.create_session_with_options(CodeModeSessionOptions {
|
||||
output_truncation: Server,
|
||||
..CodeModeSessionOptions::default()
|
||||
})
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(session.output_truncation(), initial_host);
|
||||
|
||||
let delegate = Arc::new(NoopCodeModeSessionDelegate);
|
||||
let failed = execute(&session, request("text('must not run')"), delegate.clone())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(failed.to_string().contains("session was lost"));
|
||||
let reset = execute(
|
||||
&session,
|
||||
request("text('must not replay')"),
|
||||
delegate.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
if initial_host == Server && replacement_host == Client {
|
||||
assert_eq!(
|
||||
reset.to_string(),
|
||||
"gRPC code-mode host changed the session output truncation mode on reconnect"
|
||||
);
|
||||
assert_eq!(
|
||||
subscriptions.load(Ordering::SeqCst),
|
||||
1,
|
||||
"the downgraded binding must not subscribe"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
reset
|
||||
.to_string()
|
||||
.contains("Stored values and running cells were lost")
|
||||
);
|
||||
let source = match initial_host {
|
||||
Client => "text('x'.repeat(2 * 1024 * 1024))",
|
||||
Server => "throw 'begin:' + 'X'.repeat(65 * 1024 * 1024) + ':end'",
|
||||
};
|
||||
let mut observation = request(source);
|
||||
observation.max_output_tokens = Some(5);
|
||||
observation.yield_time_ms = Some(60_000);
|
||||
let response = execute(&session, observation, delegate).await?;
|
||||
match initial_host {
|
||||
Client => assert_eq!(
|
||||
response,
|
||||
text_response(
|
||||
"g2:1",
|
||||
&"x".repeat(2 * 1024 * 1024),
|
||||
response.code_mode_host_duration()
|
||||
)
|
||||
),
|
||||
Server => {
|
||||
let RuntimeResponse::Result {
|
||||
cell_id,
|
||||
content_items,
|
||||
error_text: Some(diagnostic),
|
||||
..
|
||||
} = response
|
||||
else {
|
||||
panic!("expected a script failure");
|
||||
};
|
||||
assert_eq!(cell_id.as_str(), "g2:1");
|
||||
assert_eq!(diagnostic.len(), 64 * 1024);
|
||||
assert!(diagnostic.starts_with("begin:") && diagnostic.ends_with(":end"));
|
||||
assert_eq!(content_items, [
|
||||
"Warning: truncated output (original token count: 262144)\nTotal output lines: 2\n\nScript err…262139 tokens truncated…",
|
||||
"[Code Mode session output limit reached: omitted 67108888 text bytes; discarded 0 text segments, 0 images, 0 audio items]",
|
||||
"XXXXXX:end",
|
||||
].map(|text| FunctionCallOutputContentItem::InputText { text: text.into() }));
|
||||
}
|
||||
}
|
||||
}
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(session.output_truncation(), initial_host);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
353
akode-rs/code-mode-host/tests/grpc_notifications.rs
Normal file
353
akode-rs/code-mode-host/tests/grpc_notifications.rs
Normal file
@@ -0,0 +1,353 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use akode_code_mode::CellId;
|
||||
use akode_code_mode::CodeModeNestedToolCall;
|
||||
use akode_code_mode::CodeModeSession;
|
||||
use akode_code_mode::CodeModeSessionDelegate;
|
||||
use akode_code_mode::CodeModeSessionProvider;
|
||||
use akode_code_mode::ExecuteRequest;
|
||||
use akode_code_mode::FunctionCallOutputContentItem;
|
||||
use akode_code_mode::GrpcCodeModeSessionProvider;
|
||||
use akode_code_mode::NotificationFuture;
|
||||
use akode_code_mode::RuntimeResponse;
|
||||
use akode_code_mode::ToolInvocationFuture;
|
||||
use akode_code_mode::WaitOutcome;
|
||||
use akode_code_mode::WaitRequest;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
#[path = "support/recording_delegate.rs"]
|
||||
mod recording_delegate;
|
||||
|
||||
use host::HostHarness;
|
||||
use recording_delegate::RecordingDelegate;
|
||||
use recording_delegate::cell_id;
|
||||
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
struct BlockingNotificationDelegate {
|
||||
started: Semaphore,
|
||||
release: Semaphore,
|
||||
delivered: Semaphore,
|
||||
cancelled: Semaphore,
|
||||
closed: Semaphore,
|
||||
}
|
||||
|
||||
impl BlockingNotificationDelegate {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
started: Semaphore::new(/*permits*/ 0),
|
||||
release: Semaphore::new(/*permits*/ 0),
|
||||
delivered: Semaphore::new(/*permits*/ 0),
|
||||
cancelled: Semaphore::new(/*permits*/ 0),
|
||||
closed: Semaphore::new(/*permits*/ 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for BlockingNotificationDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
_invocation: CodeModeNestedToolCall,
|
||||
_cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async { Err("unexpected tool invocation".to_string()) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
self.started.add_permits(/*n*/ 1);
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => {
|
||||
self.cancelled.add_permits(/*n*/ 1);
|
||||
Err("notification cancelled".to_string())
|
||||
}
|
||||
permit = self.release.acquire() => {
|
||||
permit
|
||||
.map_err(|_| "notification release closed".to_string())?
|
||||
.forget();
|
||||
self.delivered.add_permits(/*n*/ 1);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {
|
||||
self.closed.add_permits(/*n*/ 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn request(source: &str) -> ExecuteRequest {
|
||||
ExecuteRequest {
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: source.to_string(),
|
||||
yield_time_ms: Some(/*value*/ 5_000),
|
||||
max_output_tokens: Some(/*value*/ 1_000),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_response(
|
||||
cell: &str,
|
||||
value: &str,
|
||||
code_mode_host_duration: Option<Duration>,
|
||||
) -> RuntimeResponse {
|
||||
RuntimeResponse::Result {
|
||||
code_mode_host_duration,
|
||||
cell_id: cell_id(cell),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: value.to_string(),
|
||||
}],
|
||||
result_buffered_for: Duration::ZERO,
|
||||
error_text: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
session: &Arc<dyn CodeModeSession>,
|
||||
request: ExecuteRequest,
|
||||
delegate: Arc<dyn CodeModeSessionDelegate>,
|
||||
) -> Result<RuntimeResponse> {
|
||||
timeout(TEST_TIMEOUT, async {
|
||||
session
|
||||
.execute(request, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?
|
||||
.initial_response()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)
|
||||
})
|
||||
.await
|
||||
.context("timed out executing gRPC code-mode cell")?
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_cells_drain_pending_notifications_before_completion() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let delegate = Arc::new(BlockingNotificationDelegate::new());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
let executing = Arc::clone(&session);
|
||||
let execution_delegate = delegate.clone();
|
||||
let completion = tokio::spawn(async move {
|
||||
execute(
|
||||
&executing,
|
||||
request(r#"notify("notice"); text("done");"#),
|
||||
execution_delegate,
|
||||
)
|
||||
.await
|
||||
});
|
||||
timeout(TEST_TIMEOUT, delegate.started.acquire())
|
||||
.await
|
||||
.context("notification did not start")??
|
||||
.forget();
|
||||
assert!(!completion.is_finished());
|
||||
delegate.release.add_permits(/*n*/ 1);
|
||||
let actual = timeout(TEST_TIMEOUT, completion)
|
||||
.await
|
||||
.context("completed cell did not finish after notification delivery")???;
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response("1", "done", actual.code_mode_host_duration())
|
||||
);
|
||||
timeout(TEST_TIMEOUT, delegate.delivered.acquire())
|
||||
.await
|
||||
.context("completed cell did not deliver its pending notification")??
|
||||
.forget();
|
||||
assert!(delegate.cancelled.try_acquire().is_err());
|
||||
timeout(TEST_TIMEOUT, delegate.closed.acquire())
|
||||
.await
|
||||
.context("completed cell was not retired")??
|
||||
.forget();
|
||||
|
||||
let actual = execute(
|
||||
&session,
|
||||
request(r#"text("still alive");"#),
|
||||
delegate.clone(),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response("2", "still alive", actual.code_mode_host_duration())
|
||||
);
|
||||
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_waits_drain_pending_notifications_before_returning() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let delegate = Arc::new(BlockingNotificationDelegate::new());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let pending = request(r#"yield_control(); notify("notice"); text("done");"#);
|
||||
let cell = session
|
||||
.execute(pending, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let actual = cell.initial_response().await.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
RuntimeResponse::Yielded {
|
||||
code_mode_host_duration: actual.code_mode_host_duration(),
|
||||
cell_id: cell_id("1"),
|
||||
content_items: Vec::new(),
|
||||
}
|
||||
);
|
||||
|
||||
let waiting = Arc::clone(&session);
|
||||
let completion = tokio::spawn(async move {
|
||||
waiting
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id("1"),
|
||||
yield_time_ms: 5_000,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)
|
||||
});
|
||||
timeout(TEST_TIMEOUT, delegate.started.acquire())
|
||||
.await
|
||||
.context("wait notification did not start")??
|
||||
.forget();
|
||||
assert!(!completion.is_finished());
|
||||
delegate.release.add_permits(/*n*/ 1);
|
||||
let actual = timeout(TEST_TIMEOUT, completion)
|
||||
.await
|
||||
.context("wait did not finish after notification delivery")???;
|
||||
assert_eq!(
|
||||
actual,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
code_mode_host_duration: actual.code_mode_host_duration(),
|
||||
cell_id: cell_id("1"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "done".to_string(),
|
||||
}],
|
||||
result_buffered_for: actual.result_buffered_for().unwrap(),
|
||||
error_text: None,
|
||||
})
|
||||
);
|
||||
timeout(TEST_TIMEOUT, delegate.delivered.acquire())
|
||||
.await
|
||||
.context("wait did not deliver its pending notification")??
|
||||
.forget();
|
||||
assert!(delegate.cancelled.try_acquire().is_err());
|
||||
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn termination_cancels_pending_notifications() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let delegate = Arc::new(BlockingNotificationDelegate::new());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let mut pending = request(r#"notify("notice"); await new Promise(() => {});"#);
|
||||
pending.yield_time_ms = Some(/*value*/ 1);
|
||||
let cell = session
|
||||
.execute(pending, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
timeout(TEST_TIMEOUT, delegate.started.acquire())
|
||||
.await
|
||||
.context("notification did not start")??
|
||||
.forget();
|
||||
let actual = cell.initial_response().await.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
RuntimeResponse::Yielded {
|
||||
code_mode_host_duration: actual.code_mode_host_duration(),
|
||||
cell_id: cell_id("1"),
|
||||
content_items: Vec::new(),
|
||||
}
|
||||
);
|
||||
let actual = session
|
||||
.terminate(cell_id("1").into())
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
|
||||
code_mode_host_duration: actual.code_mode_host_duration(),
|
||||
cell_id: cell_id("1"),
|
||||
content_items: Vec::new(),
|
||||
})
|
||||
);
|
||||
timeout(TEST_TIMEOUT, delegate.cancelled.acquire())
|
||||
.await
|
||||
.context("termination did not cancel notification delivery")??
|
||||
.forget();
|
||||
timeout(TEST_TIMEOUT, delegate.closed.acquire())
|
||||
.await
|
||||
.context("terminated cell was not retired")??
|
||||
.forget();
|
||||
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_notification_text_is_delivered_unchanged() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let delegate = Arc::new(RecordingDelegate::default());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
let actual = execute(
|
||||
&session,
|
||||
request(r#"notify("🦀".repeat(512)); text("done");"#),
|
||||
delegate.clone(),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response("1", "done", actual.code_mode_host_duration())
|
||||
);
|
||||
timeout(TEST_TIMEOUT, delegate.notification_delivered.notified())
|
||||
.await
|
||||
.context("oversized notification was not delivered")?;
|
||||
assert_eq!(
|
||||
*delegate
|
||||
.notifications
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner),
|
||||
vec![("call-1".to_string(), cell_id("1"), "🦀".repeat(512),)]
|
||||
);
|
||||
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
178
akode-rs/code-mode-host/tests/grpc_tcp.rs
Normal file
178
akode-rs/code-mode-host/tests/grpc_tcp.rs
Normal file
@@ -0,0 +1,178 @@
|
||||
use std::future::poll_fn;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use axum::http::Request;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::Version;
|
||||
use akode_code_mode_protocol::grpc;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_client::CodeModeHostClient;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use tonic::body::Body;
|
||||
use tonic::codegen::Service;
|
||||
use tonic::transport::Endpoint;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
|
||||
use host::HostHarness;
|
||||
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_serves_http1_healthz() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
|
||||
let response = http1_response(&host.endpoint, request.as_bytes()).await?;
|
||||
|
||||
assert_eq!(response.lines().next(), Some("HTTP/1.1 200 OK"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_rejects_http1_grpc_requests() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let mut request = concat!(
|
||||
"POST /codex.code_mode.v1.CodeModeHost/OpenSession HTTP/1.1\r\n",
|
||||
"Host: localhost\r\n",
|
||||
"Content-Type: application/grpc\r\n",
|
||||
"Content-Length: 5\r\n",
|
||||
"Connection: close\r\n\r\n"
|
||||
)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
request.extend_from_slice(&[0; 5]);
|
||||
let response = http1_response(&host.endpoint, &request).await?;
|
||||
|
||||
assert_eq!(
|
||||
response.lines().next(),
|
||||
Some("HTTP/1.1 505 HTTP Version Not Supported")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_serves_http2_healthz() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let mut channel = Endpoint::from_shared(host.endpoint.clone())
|
||||
.context("gRPC code-mode host published an invalid endpoint")?
|
||||
.connect_timeout(TEST_TIMEOUT)
|
||||
.timeout(TEST_TIMEOUT)
|
||||
.connect()
|
||||
.await
|
||||
.context("failed to connect to gRPC code-mode host health endpoint")?;
|
||||
let request = Request::builder()
|
||||
.uri(format!("{}/healthz", host.endpoint))
|
||||
.body(Body::empty())
|
||||
.context("failed to build gRPC code-mode host health request")?;
|
||||
|
||||
let response = timeout(TEST_TIMEOUT, async {
|
||||
poll_fn(|context| channel.poll_ready(context))
|
||||
.await
|
||||
.context("gRPC code-mode host health channel is unavailable")?;
|
||||
channel
|
||||
.call(request)
|
||||
.await
|
||||
.context("failed to request gRPC code-mode host health")
|
||||
})
|
||||
.await
|
||||
.context("timed out requesting gRPC code-mode host health")??;
|
||||
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn http1_response(endpoint: &str, request: &[u8]) -> Result<String> {
|
||||
let address = endpoint
|
||||
.strip_prefix("http://")
|
||||
.context("gRPC code-mode host URL should use http://")?;
|
||||
|
||||
timeout(TEST_TIMEOUT, async {
|
||||
let mut stream = TcpStream::connect(address)
|
||||
.await
|
||||
.context("failed to connect to gRPC code-mode host")?;
|
||||
stream
|
||||
.write_all(request)
|
||||
.await
|
||||
.context("failed to send HTTP/1.1 request to gRPC code-mode host")?;
|
||||
|
||||
let mut response = String::new();
|
||||
stream
|
||||
.read_to_string(&mut response)
|
||||
.await
|
||||
.context("failed to read HTTP/1.1 response from gRPC code-mode host")?;
|
||||
Ok(response)
|
||||
})
|
||||
.await
|
||||
.context("timed out waiting for HTTP/1.1 response from gRPC code-mode host")?
|
||||
}
|
||||
|
||||
/// Negotiate zstd for capable clients while preserving identity-only clients.
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_opens_a_grpc_session() -> Result<()> {
|
||||
let mut host = Command::new(akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?)
|
||||
.args(["--listen", "grpc://127.0.0.1:0"])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(/*kill_on_drop*/ true)
|
||||
.spawn()
|
||||
.context("failed to start gRPC code-mode host")?;
|
||||
let stdout = host
|
||||
.stdout
|
||||
.take()
|
||||
.context("gRPC code-mode host stdout is unavailable")?;
|
||||
let mut stdout = BufReader::new(stdout);
|
||||
let mut endpoint = String::new();
|
||||
timeout(TEST_TIMEOUT, stdout.read_line(&mut endpoint))
|
||||
.await
|
||||
.context("gRPC code-mode host did not publish its endpoint")??;
|
||||
let endpoint = Endpoint::from_shared(endpoint.trim().to_string())
|
||||
.context("gRPC code-mode host published an invalid endpoint")?
|
||||
.connect_timeout(TEST_TIMEOUT)
|
||||
.timeout(TEST_TIMEOUT);
|
||||
for encoding in [None, Some(tonic::codec::CompressionEncoding::Zstd)] {
|
||||
let mut client = CodeModeHostClient::connect(endpoint.clone())
|
||||
.await
|
||||
.context("failed to connect to gRPC code-mode host")?;
|
||||
if let Some(encoding) = encoding {
|
||||
client = client.accept_compressed(encoding);
|
||||
}
|
||||
let response = client
|
||||
.open_session(grpc::OpenSessionRequest {
|
||||
max_pending_delegate_calls: None,
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
})
|
||||
.await
|
||||
.context("failed to open gRPC code-mode session")?;
|
||||
assert_eq!(
|
||||
response
|
||||
.metadata()
|
||||
.get("grpc-encoding")
|
||||
.map(|value| value.to_str())
|
||||
.transpose()?,
|
||||
encoding.map(|_| "zstd"),
|
||||
);
|
||||
let mut events = response.into_inner();
|
||||
let event = timeout(TEST_TIMEOUT, events.message())
|
||||
.await
|
||||
.context("timed out waiting for gRPC code-mode session event")?
|
||||
.context("failed to read gRPC code-mode session event")?
|
||||
.context("gRPC code-mode session ended before opening")?;
|
||||
assert!(matches!(
|
||||
event.event,
|
||||
Some(grpc::session_event::Event::Opened(opened)) if !opened.session_id.is_empty()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
304
akode-rs/code-mode-host/tests/grpc_timing.rs
Normal file
304
akode-rs/code-mode-host/tests/grpc_timing.rs
Normal file
@@ -0,0 +1,304 @@
|
||||
//! Checks that remote timing measures each observation, not client delays or cell lifetime.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use akode_code_mode::CodeModeSessionProvider;
|
||||
use akode_code_mode::ExecuteRequest;
|
||||
use akode_code_mode::GrpcCodeModeSessionProvider;
|
||||
use akode_code_mode::NoopCodeModeSessionDelegate;
|
||||
use akode_code_mode::ProcessOwnedCodeModeSessionProvider;
|
||||
use akode_code_mode::RuntimeResponse;
|
||||
use akode_code_mode::WaitOutcome;
|
||||
use akode_code_mode::WaitRequest;
|
||||
use akode_code_mode_protocol::grpc;
|
||||
use akode_code_mode_protocol::grpc::code_mode_host_client::CodeModeHostClient;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::time::sleep;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
#[expect(dead_code, reason = "Other suites use the shared cell_id helper.")]
|
||||
#[path = "support/recording_delegate.rs"]
|
||||
mod recording_delegate;
|
||||
|
||||
use host::HostHarness;
|
||||
use recording_delegate::RecordingDelegate;
|
||||
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 20);
|
||||
|
||||
/// Successful and failed JavaScript include computation and timers in their host timing.
|
||||
/// Waiting to read a finished execution must not increase that measurement.
|
||||
#[tokio::test]
|
||||
async fn execution_timing_includes_javascript_but_excludes_delayed_reads() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let mut client = CodeModeHostClient::connect(host.endpoint).await?;
|
||||
let mut events = client
|
||||
.open_session(grpc::OpenSessionRequest {
|
||||
max_pending_delegate_calls: None,
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
})
|
||||
.await?
|
||||
.into_inner();
|
||||
let opened = timeout(TEST_TIMEOUT, events.message())
|
||||
.await??
|
||||
.context("session ended")?;
|
||||
let Some(grpc::session_event::Event::Opened(opened)) = opened.event else {
|
||||
anyhow::bail!("expected session opening event");
|
||||
};
|
||||
|
||||
let endings = ["", "throw new Error('timed failure');"];
|
||||
for (index, suffix) in endings.into_iter().enumerate() {
|
||||
let observed = Instant::now();
|
||||
let mut execution = client
|
||||
.execute(grpc::ExecuteRequest {
|
||||
session_id: opened.session_id.clone(),
|
||||
execution_id: format!("execution-{index}"),
|
||||
tool_call_id: format!("call-{index}"),
|
||||
source: format!(
|
||||
"const until = Date.now() + 150; while (Date.now() < until) {{}} \
|
||||
await new Promise(resolve => setTimeout(resolve, 150)); {suffix}"
|
||||
),
|
||||
enabled_tools: Vec::new(),
|
||||
yield_time_ms: Some(/*value*/ 5_000),
|
||||
max_output_tokens: Some(/*value*/ 1_000),
|
||||
})
|
||||
.await?
|
||||
.into_inner();
|
||||
let started = timeout(TEST_TIMEOUT, execution.message())
|
||||
.await??
|
||||
.context("execution ended")?;
|
||||
let Some(grpc::execute_event::Event::Started(started)) = started.event else {
|
||||
anyhow::bail!("expected execution admission");
|
||||
};
|
||||
let closed = timeout(TEST_TIMEOUT, events.message())
|
||||
.await??
|
||||
.context("session ended")?;
|
||||
assert!(
|
||||
matches!(closed.event, Some(grpc::session_event::Event::CellClosed(closed))
|
||||
if closed.cell_id == started.cell_id)
|
||||
);
|
||||
|
||||
// CellClosed confirms the JS finished before introducing a client-only delay.
|
||||
sleep(Duration::from_millis(/*millis*/ 600)).await;
|
||||
let result = timeout(TEST_TIMEOUT, execution.message())
|
||||
.await??
|
||||
.context("execution ended")?;
|
||||
let Some(grpc::execute_event::Event::Outcome(outcome)) = result.event else {
|
||||
anyhow::bail!("expected execution outcome");
|
||||
};
|
||||
let duration = Duration::from_nanos(outcome.code_mode_host_duration_ns);
|
||||
assert!(duration >= Duration::from_millis(/*millis*/ 250));
|
||||
assert!(duration + Duration::from_millis(/*millis*/ 300) <= observed.elapsed());
|
||||
let Some(grpc::execution_outcome::Outcome::Completed(completed)) = outcome.outcome else {
|
||||
anyhow::bail!("expected completed execution");
|
||||
};
|
||||
if suffix.is_empty() {
|
||||
assert_eq!(completed.error_text, None);
|
||||
} else {
|
||||
assert!(
|
||||
completed
|
||||
.error_text
|
||||
.context("expected JS failure")?
|
||||
.contains("timed failure")
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The process-owned host freezes successful and failed execution timing before
|
||||
/// the client reads its initial response, including JavaScript computation and timers.
|
||||
#[tokio::test]
|
||||
async fn stdio_execution_timing_includes_javascript_but_excludes_delayed_reads() -> Result<()> {
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?,
|
||||
);
|
||||
let delegate = Arc::new(RecordingDelegate::default());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
let endings = ["", "throw new Error('timed failure');"];
|
||||
for (index, suffix) in endings.into_iter().enumerate() {
|
||||
let observed = Instant::now();
|
||||
let started = session
|
||||
.execute(
|
||||
ExecuteRequest {
|
||||
tool_call_id: format!("call-{index}"),
|
||||
source: format!(
|
||||
"const until = Date.now() + 150; while (Date.now() < until) {{}} \
|
||||
await new Promise(resolve => setTimeout(resolve, 150)); \
|
||||
notify('finished'); {suffix}"
|
||||
),
|
||||
enabled_tools: Vec::new(),
|
||||
yield_time_ms: Some(/*value*/ 5_000),
|
||||
max_output_tokens: Some(/*value*/ 1_000),
|
||||
},
|
||||
delegate.clone(),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
timeout(TEST_TIMEOUT, delegate.notification_delivered.notified())
|
||||
.await
|
||||
.context("JS did not report completion of its timed work")?;
|
||||
|
||||
// Delay only after the host has finished the computation and timer.
|
||||
sleep(Duration::from_millis(/*millis*/ 600)).await;
|
||||
let response = timeout(TEST_TIMEOUT, started.initial_response())
|
||||
.await?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = response
|
||||
.code_mode_host_duration()
|
||||
.context("missing stdio exec timing")?;
|
||||
assert!(duration >= Duration::from_millis(/*millis*/ 250));
|
||||
assert!(duration + Duration::from_millis(/*millis*/ 300) <= observed.elapsed());
|
||||
let RuntimeResponse::Result { error_text, .. } = response else {
|
||||
anyhow::bail!("expected completed execution");
|
||||
};
|
||||
if suffix.is_empty() {
|
||||
assert_eq!(error_text, None);
|
||||
} else {
|
||||
let Some(error_text) = error_text else {
|
||||
anyhow::bail!("expected JS failure");
|
||||
};
|
||||
assert!(error_text.contains("timed failure"));
|
||||
}
|
||||
}
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every wait and termination measures its own request, including missing-cell outcomes.
|
||||
/// Earlier execution and background time must not be charged again by later observations.
|
||||
#[tokio::test]
|
||||
async fn observation_timing_excludes_previous_requests_and_background_time() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let providers: [Arc<dyn CodeModeSessionProvider>; 2] = [
|
||||
Arc::new(ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?,
|
||||
)),
|
||||
Arc::new(GrpcCodeModeSessionProvider::new(host.endpoint)),
|
||||
];
|
||||
for provider in providers {
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let started = session
|
||||
.execute(
|
||||
ExecuteRequest {
|
||||
tool_call_id: "call-1".to_string(),
|
||||
source: "await new Promise(() => {});".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
yield_time_ms: Some(/*value*/ 200),
|
||||
max_output_tokens: Some(/*value*/ 1_000),
|
||||
},
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let cell_id = started.cell_id.clone();
|
||||
let initial = started
|
||||
.initial_response()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = initial
|
||||
.code_mode_host_duration()
|
||||
.context("missing exec timing")?;
|
||||
assert!(duration >= Duration::from_millis(/*millis*/ 150));
|
||||
let yielded = RuntimeResponse::Yielded {
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: Some(duration),
|
||||
};
|
||||
assert_eq!(initial, yielded);
|
||||
|
||||
for _ in 0..2 {
|
||||
sleep(Duration::from_millis(/*millis*/ 300)).await;
|
||||
let observed = Instant::now();
|
||||
let outcome = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: 50,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = outcome
|
||||
.code_mode_host_duration()
|
||||
.context("missing wait timing")?;
|
||||
assert!(duration >= Duration::from_millis(/*millis*/ 40));
|
||||
assert!(
|
||||
duration <= observed.elapsed(),
|
||||
"wait included time before its request: {duration:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
outcome,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Yielded {
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: Some(duration),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
let observed = Instant::now();
|
||||
let terminated = session
|
||||
.terminate(cell_id.clone().into())
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = terminated
|
||||
.code_mode_host_duration()
|
||||
.context("missing termination timing")?;
|
||||
assert!(duration <= observed.elapsed());
|
||||
assert_eq!(
|
||||
terminated,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: Some(duration),
|
||||
})
|
||||
);
|
||||
|
||||
let observed = Instant::now();
|
||||
let missing = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: 50,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = missing
|
||||
.code_mode_host_duration()
|
||||
.context("missing absent-cell timing")?;
|
||||
assert!(duration <= observed.elapsed());
|
||||
assert_eq!(
|
||||
missing,
|
||||
WaitOutcome::MissingCell(RuntimeResponse::Result {
|
||||
result_buffered_for: Duration::ZERO,
|
||||
error_text: Some(format!("exec cell {cell_id} not found")),
|
||||
cell_id,
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: Some(duration),
|
||||
})
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
186
akode-rs/code-mode-host/tests/settled.rs
Normal file
186
akode-rs/code-mode-host/tests/settled.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
//! Verifies partial settlement output survives waits on both host transports.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_code_mode::CellId;
|
||||
use akode_code_mode::CodeModeNestedToolCall;
|
||||
use akode_code_mode::CodeModeSessionDelegate;
|
||||
use akode_code_mode::CodeModeSessionProvider;
|
||||
use akode_code_mode::CodeModeToolKind;
|
||||
use akode_code_mode::ExecuteRequest;
|
||||
use akode_code_mode::FunctionCallOutputContentItem;
|
||||
use akode_code_mode::GrpcCodeModeSessionProvider;
|
||||
use akode_code_mode::NotificationFuture;
|
||||
use akode_code_mode::ProcessOwnedCodeModeSessionProvider;
|
||||
use akode_code_mode::RuntimeResponse;
|
||||
use akode_code_mode::ToolDefinition;
|
||||
use akode_code_mode::ToolInvocationFuture;
|
||||
use akode_code_mode::WaitOutcome;
|
||||
use akode_code_mode::WaitRequest;
|
||||
use akode_protocol::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
|
||||
#[derive(Default)]
|
||||
struct SlowDelegate {
|
||||
release: Notify,
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for SlowDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
_invocation: CodeModeNestedToolCall,
|
||||
cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
tokio::select! {
|
||||
_ = self.release.notified() => Ok(json!("slow")),
|
||||
_ = cancellation.cancelled() => Err("cancelled".to_string()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
_cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {}
|
||||
}
|
||||
|
||||
#[allow(clippy::expect_used)]
|
||||
async fn assert_partial_results(provider: &dyn CodeModeSessionProvider) {
|
||||
for consumer in [
|
||||
"for await (const result of as_settled(promises)) text(result);",
|
||||
"await stream_settled(promises, text);",
|
||||
] {
|
||||
let delegate = Arc::new(SlowDelegate::default());
|
||||
let session = provider.create_session().await.expect("create session");
|
||||
let started = session
|
||||
.execute(ExecuteRequest {
|
||||
tool_call_id: "settled".to_string(),
|
||||
enabled_tools: vec![ToolDefinition {
|
||||
name: "slow".to_string(),
|
||||
tool_name: ToolName::plain("slow"),
|
||||
description: String::new(),
|
||||
kind: CodeModeToolKind::Function,
|
||||
input_schema: None,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: None,
|
||||
}],
|
||||
source: format!(
|
||||
r#"const promises = [tools.slow({{}}), Promise.resolve("fast"), Promise.reject("failed")];
|
||||
{consumer}"#
|
||||
),
|
||||
yield_time_ms: Some(/*value*/ 10),
|
||||
max_output_tokens: None,
|
||||
}, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.expect("start cell");
|
||||
let cell_id = started.cell_id.clone();
|
||||
let mut response = started.initial_response().await.expect("initial response");
|
||||
let mut partial = Vec::new();
|
||||
loop {
|
||||
let RuntimeResponse::Yielded { content_items, .. } = response else {
|
||||
panic!("cell completed before the slow tool was released: {response:?}");
|
||||
};
|
||||
partial.extend(content_items.into_iter().map(|item| {
|
||||
let FunctionCallOutputContentItem::InputText { text } = item else {
|
||||
panic!("unexpected output: {item:?}");
|
||||
};
|
||||
serde_json::from_str::<serde_json::Value>(&text).expect("JSON output")
|
||||
}));
|
||||
if partial.len() >= 2 {
|
||||
break;
|
||||
}
|
||||
let WaitOutcome::LiveCell(next) = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: 10,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("wait for partial results")
|
||||
else {
|
||||
panic!("cell disappeared while the slow tool was pending");
|
||||
};
|
||||
response = next;
|
||||
}
|
||||
assert_eq!(
|
||||
partial,
|
||||
[
|
||||
json!({"index": 1, "status": "fulfilled", "value": "fast"}),
|
||||
json!({"index": 2, "status": "rejected", "reason": "failed"}),
|
||||
]
|
||||
);
|
||||
|
||||
delegate.release.notify_one();
|
||||
let completed = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: 5_000,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("wait for completion");
|
||||
assert_eq!(
|
||||
completed,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
code_mode_host_duration: completed.code_mode_host_duration(),
|
||||
cell_id,
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: json!({"index": 0, "status": "fulfilled", "value": "slow"}).to_string(),
|
||||
}],
|
||||
result_buffered_for: completed
|
||||
.result_buffered_for()
|
||||
.expect("completed result includes buffering duration"),
|
||||
error_text: None,
|
||||
})
|
||||
);
|
||||
session.shutdown().await.expect("shutdown session");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settled_results_stream_over_stdio() {
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
akode_utils_cargo_bin::cargo_bin("akode-code-mode-host").expect("host binary"),
|
||||
);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 20),
|
||||
assert_partial_results(&provider),
|
||||
)
|
||||
.await
|
||||
.expect("settlement streaming timed out");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settled_results_stream_over_grpc() {
|
||||
let host = host::HostHarness::start("grpc://127.0.0.1:0")
|
||||
.await
|
||||
.expect("start gRPC host");
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 20),
|
||||
assert_partial_results(&provider),
|
||||
)
|
||||
.await
|
||||
.expect("settlement streaming timed out");
|
||||
}
|
||||
1185
akode-rs/code-mode-host/tests/stdio.rs
Normal file
1185
akode-rs/code-mode-host/tests/stdio.rs
Normal file
File diff suppressed because it is too large
Load Diff
53
akode-rs/code-mode-host/tests/support/host.rs
Normal file
53
akode-rs/code-mode-host/tests/support/host.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
pub(crate) struct HostHarness {
|
||||
pub(crate) _child: Child,
|
||||
pub(crate) endpoint: String,
|
||||
}
|
||||
|
||||
impl HostHarness {
|
||||
pub(crate) async fn start(listen_url: &str) -> Result<Self> {
|
||||
let host_program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child = Command::new(host_program)
|
||||
.args(["--listen", listen_url])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(/*kill_on_drop*/ true)
|
||||
.spawn()
|
||||
.context("failed to start code-mode host")?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.context("code-mode host stdout was not captured")?;
|
||||
let endpoint = timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
BufReader::new(stdout).lines().next_line(),
|
||||
)
|
||||
.await
|
||||
.context("timed out waiting for code-mode host endpoint")??
|
||||
.context("code-mode host exited before publishing its endpoint")?;
|
||||
let expected_scheme = if listen_url.starts_with("grpc://") {
|
||||
"http"
|
||||
} else {
|
||||
"ws"
|
||||
};
|
||||
if !endpoint.starts_with(&format!("{expected_scheme}://127.0.0.1:")) {
|
||||
anyhow::bail!("unexpected code-mode host endpoint `{endpoint}`");
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
_child: child,
|
||||
endpoint,
|
||||
})
|
||||
}
|
||||
}
|
||||
49
akode-rs/code-mode-host/tests/support/large_tool_delegate.rs
Normal file
49
akode-rs/code-mode-host/tests/support/large_tool_delegate.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use akode_code_mode::CellId;
|
||||
use akode_code_mode::CodeModeNestedToolCall;
|
||||
use akode_code_mode::CodeModeSessionDelegate;
|
||||
use akode_code_mode::NotificationFuture;
|
||||
use akode_code_mode::ToolInvocationFuture;
|
||||
use akode_protocol::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(crate) struct LargeToolResultDelegate {
|
||||
pub(crate) started: Semaphore,
|
||||
pub(crate) release: Semaphore,
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for LargeToolResultDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
_cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
if invocation.tool_name == ToolName::plain("fast") {
|
||||
return Ok(json!({ "value": "isolated" }));
|
||||
}
|
||||
assert_eq!(invocation.tool_name, ToolName::plain("large"));
|
||||
self.started.add_permits(/*n*/ 1);
|
||||
self.release
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| "large tool release closed".to_string())?
|
||||
.forget();
|
||||
Ok(json!({ "value": "x".repeat(8 * 1024 * 1024) }))
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
_cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {}
|
||||
}
|
||||
59
akode-rs/code-mode-host/tests/support/recording_delegate.rs
Normal file
59
akode-rs/code-mode-host/tests/support/recording_delegate.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use akode_code_mode::CellId;
|
||||
use akode_code_mode::CodeModeNestedToolCall;
|
||||
use akode_code_mode::CodeModeSessionDelegate;
|
||||
use akode_code_mode::NotificationFuture;
|
||||
use akode_code_mode::ToolInvocationFuture;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RecordingDelegate {
|
||||
pub(crate) invocations: Mutex<Vec<CodeModeNestedToolCall>>,
|
||||
pub(crate) notifications: Mutex<Vec<(String, CellId, String)>>,
|
||||
pub(crate) notification_delivered: Notify,
|
||||
pub(crate) closed_cells: Mutex<Vec<CellId>>,
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for RecordingDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
_cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
self.invocations
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push(invocation);
|
||||
Box::pin(async { Ok(json!({ "value": "output" })) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
call_id: String,
|
||||
cell_id: CellId,
|
||||
text: String,
|
||||
_cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
self.notifications
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push((call_id, cell_id, text));
|
||||
self.notification_delivered.notify_one();
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, cell_id: &CellId) {
|
||||
self.closed_cells
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push(cell_id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cell_id(value: &str) -> CellId {
|
||||
CellId::new(value.to_string())
|
||||
}
|
||||
506
akode-rs/code-mode-host/tests/ui_plugin_wire.rs
Normal file
506
akode-rs/code-mode-host/tests/ui_plugin_wire.rs
Normal file
@@ -0,0 +1,506 @@
|
||||
//! Exercises the child protocol without the parent supervisor or session APIs.
|
||||
|
||||
use anyhow::Context;
|
||||
use akode_plugin_host::PluginProcess;
|
||||
use akode_plugin_host::protocol::MAX_PENDING_PROMISES;
|
||||
use akode_plugin_host::protocol::MAX_SCRIPT_ERROR_BYTES;
|
||||
use akode_plugin_host::protocol::Packet;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::test]
|
||||
async fn child_initializes_invokes_and_closes_an_isolate() -> anyhow::Result<()> {
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = format!("/*{}*/ export default () => 'x'.repeat(5000);", "p".repeat(40 * 1024));
|
||||
for (message, expected) in [
|
||||
(json!({"type": "initialize", "source": source}), json!({"type": "initialized"})),
|
||||
(json!({"type": "dispatch", "id": 0, "export": "default", "returnMode": "maybeAsync"}), json!({"type": "reply", "id": 0, "value": "x".repeat(5000)})),
|
||||
(json!({"type": "close"}), json!({"type": "closed"})),
|
||||
] {
|
||||
send(&mut child, /*instance*/ 7, message).await?;
|
||||
assert_eq!(receive(&mut child).await?, (7, expected));
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
async fn send(
|
||||
child: &mut PluginProcess,
|
||||
instance: u64,
|
||||
message: serde_json::Value,
|
||||
) -> anyhow::Result<()> {
|
||||
let (input, _) = child.pipes();
|
||||
input
|
||||
.send(serde_json::to_vec(&Packet { instance, message })?.into())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(child: &mut PluginProcess) -> anyhow::Result<(u64, serde_json::Value)> {
|
||||
let (_, output) = child.pipes();
|
||||
let packet: Packet<serde_json::Value> = serde_json::from_slice(
|
||||
&output
|
||||
.next()
|
||||
.await
|
||||
.context("plugin child closed stdout")??,
|
||||
)?;
|
||||
Ok((packet.instance, packet.message))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn promise_errors_close_the_isolate_in_both_return_modes() -> anyhow::Result<()> {
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = r#"
|
||||
export function run() {
|
||||
const promise = Promise.reject(Error('tracked failure'));
|
||||
promise.catch(() => {});
|
||||
return promise;
|
||||
}
|
||||
"#;
|
||||
for (instance, return_mode, code) in [
|
||||
(1, "sync", "invalid_result"),
|
||||
(2, "maybeAsync", "execution_failed"),
|
||||
] {
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type": "initialized"}))
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "dispatch", "id": 0, "export": "run", "returnMode": return_mode}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child).await?;
|
||||
assert_eq!(
|
||||
(id, error["type"].as_str(), error["code"].as_str()),
|
||||
(instance, Some("error"), Some(code))
|
||||
);
|
||||
if return_mode == "maybeAsync" {
|
||||
assert!(
|
||||
error["scriptError"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|diagnostic| diagnostic.contains("tracked failure"))
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type": "closed"}))
|
||||
);
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_closes_an_isolate_with_pending_work() -> anyhow::Result<()> {
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = "export function run() { return new Promise(() => {}); }";
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "initialized"}))
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "dispatch", "id": 0, "export": "run", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "pending", "id": 0}))
|
||||
);
|
||||
send(&mut child, /*instance*/ 1, json!({"type": "close"})).await?;
|
||||
assert_eq!(receive(&mut child).await?, (1, json!({"type": "closed"})));
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_dispatch_settles_pending_invocations() -> anyhow::Result<()> {
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = r#"
|
||||
const resolvers = [];
|
||||
export function wait() { return new Promise(resolve => resolvers.push(resolve)); }
|
||||
export function finish() {
|
||||
for (const resolve of resolvers) resolve('done');
|
||||
return 'finished';
|
||||
}
|
||||
"#;
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "initialized"}))
|
||||
);
|
||||
let sync_id = MAX_PENDING_PROMISES as u64;
|
||||
for id in 0..sync_id {
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "dispatch", "id": id, "export": "wait", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "pending", "id": id}))
|
||||
);
|
||||
}
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "dispatch", "id": sync_id, "export": "finish", "returnMode": "sync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(
|
||||
1,
|
||||
json!({"type": "reply", "id": sync_id, "value": "finished"})
|
||||
)
|
||||
);
|
||||
let mut resolved = Vec::new();
|
||||
for _ in 0..sync_id {
|
||||
let (instance, reply) = receive(&mut child).await?;
|
||||
let id = reply["id"].as_u64().unwrap();
|
||||
assert_eq!(
|
||||
(instance, reply),
|
||||
(1, json!({"type": "reply", "id": id, "value": "done"}))
|
||||
);
|
||||
resolved.push(id);
|
||||
}
|
||||
resolved.sort_unstable();
|
||||
assert_eq!(resolved, (0..sync_id).collect::<Vec<_>>());
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn syntax_and_execution_failures_preserve_bounded_script_errors() -> anyhow::Result<()> {
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "initialize", "source": "export default => ;"}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child).await?;
|
||||
assert_eq!(id, 1);
|
||||
assert_eq!(error["code"], "invalid_program");
|
||||
assert_eq!(error["scriptError"]["line"], 1);
|
||||
assert!(error["scriptError"]["column"].is_number());
|
||||
assert_eq!(error["scriptError"]["truncated"], false);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "closed"}))
|
||||
);
|
||||
|
||||
let source = format!(
|
||||
r#"export function fail() {{ throw Error('xxx\u001b[31m' + 'x'.repeat({MAX_SCRIPT_ERROR_BYTES})); }}"#
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 2,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(2, json!({"type": "initialized"}))
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 2,
|
||||
json!({"type": "dispatch", "id": 0, "export": "fail", "returnMode": "sync"}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child).await?;
|
||||
assert_eq!(id, 2);
|
||||
let message = error["scriptError"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("Error: xxx\u{001b}[31m"));
|
||||
assert!(message.len() <= MAX_SCRIPT_ERROR_BYTES);
|
||||
assert_eq!(error["scriptError"]["truncated"], true);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(2, json!({"type": "closed"}))
|
||||
);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loading_restrictions_close_the_isolate() -> anyhow::Result<()> {
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let cases = [
|
||||
(
|
||||
"import 'forbidden';",
|
||||
"invalid_program",
|
||||
"module imports are unavailable",
|
||||
),
|
||||
(
|
||||
"await import('forbidden');",
|
||||
"execution_failed",
|
||||
"Not supported",
|
||||
),
|
||||
("eval('1 + 1');", "execution_failed", "EvalError"),
|
||||
(
|
||||
"new Function('return 1')();",
|
||||
"execution_failed",
|
||||
"EvalError",
|
||||
),
|
||||
(
|
||||
"WebAssembly;",
|
||||
"execution_failed",
|
||||
"WebAssembly is not defined",
|
||||
),
|
||||
(
|
||||
"new ArrayBuffer(1);",
|
||||
"execution_failed",
|
||||
"ArrayBuffer is not defined",
|
||||
),
|
||||
(
|
||||
"new Uint8Array(1);",
|
||||
"execution_failed",
|
||||
"Uint8Array is not defined",
|
||||
),
|
||||
];
|
||||
for (instance, (source, code, diagnostic)) in (1_u64..).zip(cases) {
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child)
|
||||
.await
|
||||
.with_context(|| format!("loading {source}"))?;
|
||||
assert_eq!(
|
||||
(id, error["type"].as_str(), error["code"].as_str()),
|
||||
(instance, Some("error"), Some(code)),
|
||||
"{source}"
|
||||
);
|
||||
assert!(
|
||||
error["scriptError"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|message| message.contains(diagnostic)),
|
||||
"{source}: {error}"
|
||||
);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type": "closed"})),
|
||||
"{source}"
|
||||
);
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
let exit = child.close().await?;
|
||||
result.with_context(|| {
|
||||
format!(
|
||||
"plugin helper exited with {}; stderr: {:?}",
|
||||
exit.status,
|
||||
String::from_utf8_lossy(&exit.stderr_tail)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn isolate_failures_do_not_affect_healthy_peers() -> anyhow::Result<()> {
|
||||
const HEALTHY: u64 = 1;
|
||||
const REJECTING: u64 = 2;
|
||||
const LOOPING: u64 = 3;
|
||||
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = r#"
|
||||
let n = 0;
|
||||
export function count() { return String(++n); }
|
||||
export function caught() {
|
||||
const p = Promise.reject('handled');
|
||||
p.catch(() => {});
|
||||
return 'ok';
|
||||
}
|
||||
export function detached() {
|
||||
Promise.resolve().then(() => { throw Error('detached failure'); });
|
||||
return 'ok';
|
||||
}
|
||||
"#;
|
||||
for instance in [HEALTHY, REJECTING] {
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type": "initialized"}))
|
||||
);
|
||||
}
|
||||
for (instance, export, expected) in [
|
||||
(HEALTHY, "count", "1"),
|
||||
(HEALTHY, "count", "2"),
|
||||
(REJECTING, "caught", "ok"),
|
||||
(REJECTING, "count", "1"),
|
||||
] {
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "dispatch", "id": 0, "export": export, "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(
|
||||
instance,
|
||||
json!({"type": "reply", "id": 0, "value": expected})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
send(
|
||||
&mut child,
|
||||
REJECTING,
|
||||
json!({"type": "dispatch", "id": 0, "export": "detached", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child).await?;
|
||||
assert_eq!(id, REJECTING);
|
||||
assert_eq!(error["code"], "execution_failed");
|
||||
assert!(
|
||||
error["scriptError"]["message"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("detached failure")
|
||||
);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(REJECTING, json!({"type": "closed"}))
|
||||
);
|
||||
|
||||
let source = "export function loop() { while (true) {} }";
|
||||
send(
|
||||
&mut child,
|
||||
LOOPING,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(LOOPING, json!({"type": "initialized"}))
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
LOOPING,
|
||||
json!({"type": "dispatch", "id": 0, "export": "loop", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
send(
|
||||
&mut child,
|
||||
HEALTHY,
|
||||
json!({"type": "dispatch", "id": 0, "export": "count", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(
|
||||
LOOPING,
|
||||
json!({"type": "error", "code": "execution_timed_out", "scriptError": null})
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(LOOPING, json!({"type": "closed"}))
|
||||
);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(HEALTHY, json!({"type": "reply", "id": 0, "value": "3"}))
|
||||
);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closed_instance_can_be_replaced_at_capacity() -> anyhow::Result<()> {
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let limit = akode_plugin_host::MAX_INSTANCES as u64;
|
||||
let initialize = json!({"type":"initialize", "source":"export default () => 'ok'"});
|
||||
for instance in 0..limit {
|
||||
send(&mut child, instance, initialize.clone()).await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type":"initialized"}))
|
||||
);
|
||||
}
|
||||
send(&mut child, /*instance*/ 0, json!({"type":"close"})).await?;
|
||||
assert_eq!(receive(&mut child).await?, (0, json!({"type":"closed"})));
|
||||
send(&mut child, limit, initialize).await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(limit, json!({"type":"initialized"}))
|
||||
);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
28
akode-rs/code-mode-host/tests/ui_sandbox.rs
Normal file
28
akode-rs/code-mode-host/tests/ui_sandbox.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
#[test]
|
||||
fn plugin_arguments_are_parsed_before_startup() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
for arguments in [
|
||||
["--help", "--codex-ui-plugin-process"],
|
||||
["--codex-ui-plugin-process", "--help"],
|
||||
] {
|
||||
let output = akode_utils_process::background_command(&program)
|
||||
.args(arguments)
|
||||
.output()?;
|
||||
assert!(output.status.success());
|
||||
assert!(String::from_utf8(output.stdout)?.contains("Usage:"));
|
||||
}
|
||||
for arguments in [
|
||||
["--unknown", "--codex-ui-plugin-process"],
|
||||
["--codex-ui-plugin-process", "--unknown"],
|
||||
["--listen=stdio", "--codex-ui-plugin-process"],
|
||||
["--codex-ui-plugin-process", "--listen=stdio"],
|
||||
] {
|
||||
let output = akode_utils_process::background_command(&program)
|
||||
.args(arguments)
|
||||
.output()?;
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
assert!(String::from_utf8(output.stderr)?.contains("error:"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user