From d9e3686f3e439c9f9d72d97a34cb8ac949574ceb Mon Sep 17 00:00:00 2001 From: lym953 <10097700+lym953@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:09:15 -0500 Subject: [PATCH 1/3] [SVLS-10070] fix(proxy): remove finished tasks from the Runtime API proxy's JoinSet The proxy in front of the Lambda Runtime API spawns two tasks per invocation into a JoinSet that is joined only at shutdown, so the set grows by two finished tasks per invocation. Remove finished tasks before each spawn, as the lifecycle listener does. Co-Authored-By: Claude Opus 5.5 --- bottlecap/src/proxy/interceptor.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/bottlecap/src/proxy/interceptor.rs b/bottlecap/src/proxy/interceptor.rs index aedd6b7f6..c2e68de66 100644 --- a/bottlecap/src/proxy/interceptor.rs +++ b/bottlecap/src/proxy/interceptor.rs @@ -122,6 +122,16 @@ async fn graceful_shutdown(tasks: Arc>>, shutdown_token: Cance } } +/// A `JoinSet` keeps each finished task until it is joined, so remove them before adding one. +/// Without this, the set grows by two tasks per invocation for the sandbox's lifetime. +fn reap_finished(join_set: &mut JoinSet<()>) { + while let Some(result) = join_set.try_join_next() { + if let Err(e) = result { + error!("PROXY | Task error: {e}"); + } + } +} + async fn record_dsm_consume_from_invocation_next( invocation_processor: &InvocationProcessorHandle, parts: &http::response::Parts, @@ -228,6 +238,7 @@ async fn invocation_next_proxy( TeeBodyWithCompletion::new(intercepted_body); let mut join_set = tasks.lock().await; + reap_finished(&mut join_set); let intercepted_parts_clone = intercepted_parts.clone(); let propagator = Arc::clone(&propagator); join_set.spawn(async move { @@ -321,6 +332,7 @@ async fn invocation_response_proxy( // The outgoing body is what the final user will see. // Which is what AWS Lambda returns, in turn what we want to process. let mut join_set = tasks.lock().await; + reap_finished(&mut join_set); let aws_config_clone = aws_config.clone(); join_set.spawn(async move { if let Ok(body) = outgoing_completion_receiver.await { @@ -572,6 +584,24 @@ mod tests { ); } + #[tokio::test] + async fn test_reap_finished_removes_finished_tasks() { + let mut join_set = JoinSet::new(); + for _ in 0..10 { + join_set.spawn(async {}); + } + // Let the spawned tasks finish. + tokio::task::yield_now().await; + + reap_finished(&mut join_set); + + assert!( + join_set.is_empty(), + "join set holds {} tasks", + join_set.len() + ); + } + #[tokio::test] #[allow(clippy::too_many_lines)] async fn test_noop_proxy() { From 263b912a955e7ed90d6a47f812132384f45f670b Mon Sep 17 00:00:00 2001 From: lym953 <10097700+lym953@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:31:46 -0500 Subject: [PATCH 2/3] [SVLS-10070] test(proxy): check the JoinSet through repeated invocation cycles Replace the helper-only test with one that sends 100 next/response cycles through the proxy's router to a fake Runtime API, then checks that the set holds at most two tasks and that shutdown finishes. Without the calls before each spawn, the set holds 200 tasks and the test fails. Co-Authored-By: Claude Opus 5.5 --- bottlecap/src/proxy/interceptor.rs | 93 ++++++++++++++++++++++++++---- 1 file changed, 81 insertions(+), 12 deletions(-) diff --git a/bottlecap/src/proxy/interceptor.rs b/bottlecap/src/proxy/interceptor.rs index c2e68de66..a650157f8 100644 --- a/bottlecap/src/proxy/interceptor.rs +++ b/bottlecap/src/proxy/interceptor.rs @@ -543,6 +543,7 @@ mod tests { LAMBDA_RUNTIME_SLUG, appsec::processor::Error::FeatureDisabled as AppSecFeatureDisabled, config::Config, tags::provider::Provider, traces::propagation::DatadogCompositePropagator, }; + use tower::ServiceExt; fn test_aws_config(aws_lwa_proxy_lambda_runtime_api: Option) -> AwsConfig { AwsConfig { @@ -585,21 +586,89 @@ mod tests { } #[tokio::test] - async fn test_reap_finished_removes_finished_tasks() { - let mut join_set = JoinSet::new(); - for _ in 0..10 { - join_set.spawn(async {}); + async fn test_invocation_cycles_keep_join_set_bounded() { + // A fake Lambda Runtime API that serves one event per `next` call. + let runtime_api = Router::new() + .route( + "/2018-06-01/runtime/invocation/next", + get(|| async { + ( + [("Lambda-Runtime-Aws-Request-Id", "req")], + r#"{"key":"value"}"#, + ) + }), + ) + .route( + "/2018-06-01/runtime/invocation/{request_id}/response", + post(|_body: Bytes| async { StatusCode::ACCEPTED }), + ); + let runtime_api_listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("failed to bind fake Runtime API"); + let runtime_api_addr = runtime_api_listener + .local_addr() + .expect("failed to read fake Runtime API address"); + tokio::spawn(async move { + axum::serve(runtime_api_listener, runtime_api) + .await + .expect("fake Runtime API failed"); + }); + + let mut aws_config = test_aws_config(None); + aws_config.runtime_api = runtime_api_addr.to_string(); + let propagator = Arc::new(DatadogCompositePropagator::new(Arc::new(Config::default()))); + let tasks = Arc::new(Mutex::new(JoinSet::new())); + let state: InterceptorState = ( + Arc::new(aws_config), + Arc::new(Client::builder(TokioExecutor::new()).build(HttpConnector::new())), + InvocationProcessorHandle::noop(), + None, + propagator, + false, + tasks.clone(), + ); + let router = make_router(state); + + for _ in 0..100 { + let next = Request::builder() + .uri("/2018-06-01/runtime/invocation/next") + .body(Body::empty()) + .expect("failed to build next request"); + let response = router.clone().oneshot(next).await.expect("next failed"); + assert_eq!(response.status(), StatusCode::OK); + // The task for the event runs once the proxy has forwarded the whole body. + response + .into_body() + .collect() + .await + .expect("failed to read event"); + + let result = Request::builder() + .method("POST") + .uri("/2018-06-01/runtime/invocation/req/response") + .body(Body::from(r#"{"ok":true}"#)) + .expect("failed to build response request"); + let response = router + .clone() + .oneshot(result) + .await + .expect("response failed"); + assert_eq!(response.status(), StatusCode::ACCEPTED); + tokio::task::yield_now().await; } - // Let the spawned tasks finish. - tokio::task::yield_now().await; - reap_finished(&mut join_set); + let len = tasks.lock().await.len(); + assert!(len <= 2, "join set holds {len} tasks after 100 invocations"); - assert!( - join_set.is_empty(), - "join set holds {} tasks", - join_set.len() - ); + let shutdown_token = CancellationToken::new(); + shutdown_token.cancel(); + tokio::time::timeout( + Duration::from_secs(5), + graceful_shutdown(tasks.clone(), shutdown_token), + ) + .await + .expect("shutdown did not finish"); + assert!(tasks.lock().await.is_empty()); } #[tokio::test] From 0876a0842886fa6bb8842c43b1b1fb523ee47e23 Mon Sep 17 00:00:00 2001 From: lym953 <10097700+lym953@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:42:25 -0500 Subject: [PATCH 3/3] [SVLS-10070] test(proxy): check memory over many invocations through the Runtime API proxy Add a process-level test that starts the real binary with the proxy on (the Datadog wrapper with Data Streams Monitoring) and runs 3,500 warm invocations, each with five next/response cycles through the proxy. On Linux, RSS must grow at most 3 MiB after a warm-up of 500 invocations. Without the fix, RSS grew 6.4 to 7.0 MiB over the 3,000 measured invocations. Co-Authored-By: Claude Opus 5.5 --- bottlecap/tests/lifecycle_contract_test.rs | 73 ++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/bottlecap/tests/lifecycle_contract_test.rs b/bottlecap/tests/lifecycle_contract_test.rs index 8e3870711..d8f0695c0 100644 --- a/bottlecap/tests/lifecycle_contract_test.rs +++ b/bottlecap/tests/lifecycle_contract_test.rs @@ -289,3 +289,76 @@ async fn universal_instrumentation_memory_stays_bounded() { }) .await; } + +/// Runtime API cycles (next event, then response) through the proxy per invocation. The proxy +/// keeps less memory per leaked task than the lifecycle listener, so one cycle per invocation +/// stays under [`MEMORY_GROWTH_LIMIT_KB`] even with a leak. The proxy does not link its calls to +/// the extension's invocations. +const PROXY_CYCLES_PER_INVOCATION: usize = 5; + +/// The proxy in front of the Lambda Runtime API handles the runtime's calls for the next event +/// and for the response on every invocation. Over many warm invocations, the extension's memory +/// must stay bounded. The Datadog wrapper with Data Streams Monitoring starts the proxy. +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial(bottlecap_ports)] +async fn runtime_api_proxy_memory_stays_bounded() { + let s = Scenario::start(FaultMode::Ok).await; + let bc = s + .bottlecap() + .env("AWS_LAMBDA_EXEC_WRAPPER", "/opt/datadog_wrapper") + .env("DD_DATA_STREAMS_ENABLED", "true") + .spawn(); + // Test-only client towards the local Runtime API proxy. + #[allow(clippy::disallowed_methods)] + let client = reqwest::Client::builder().build().unwrap(); + let base = format!("http://127.0.0.1:{PROXY_PORT}/2018-06-01/runtime/invocation"); + + assert_memory_stays_bounded(&s, bc, async |request_id, deadline| { + for _ in 0..PROXY_CYCLES_PER_INVOCATION { + let next = client.get(format!("{base}/next")).send(); + let response = tokio::time::timeout_at(deadline.into(), next) + .await + .unwrap_or_else(|_| { + panic!("next for {request_id} exceeded the invocation deadline") + }) + .unwrap(); + assert!( + response.status().is_success(), + "next got {}", + response.status() + ); + // The proxy handles the event once its whole body has passed through. + response.bytes().await.unwrap(); + + let result = client + .post(format!("{base}/{request_id}/response")) + .json(&serde_json::json!({"statusCode": 200})) + .send(); + let response = tokio::time::timeout_at(deadline.into(), result) + .await + .unwrap_or_else(|_| { + panic!("response for {request_id} exceeded the invocation deadline") + }) + .unwrap(); + assert!( + response.status().is_success(), + "response got {}", + response.status() + ); + } + + if request_id == "req-1" { + let lines = s.api.request_lines(); + for line in [ + "GET /2018-06-01/runtime/invocation/next".to_string(), + format!("POST /2018-06-01/runtime/invocation/{request_id}/response"), + ] { + assert!( + lines.contains(&line), + "the proxy did not forward {line}: {lines:?}" + ); + } + } + }) + .await; +}