Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(cdp): reserve output capacity for terminal responses
ldm0fa59adb7b3b1
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rsindex 107c1193e..d36483d41 100644--- a/moli-renderer-v8/src/runtime/page_surface.rs+++ b/moli-renderer-v8/src/runtime/page_surface.rs@@ -3302,7 +3302,7 @@ impl RendererDevToolsSessionOutputHost {RendererProtocolObservation::RuntimeInspector(batch),);self.output_journal- .try_publish_records_and_declare_fence([record])+ .try_publish_terminal_records_and_declare_fence([record]).ok_or(completion)}}@@ -3593,6 +3593,9 @@ impl RendererRuntimeInspectorResponseSender {mod renderer_runtime_inspector_response_channel_tests {use super::*;use crate::page_task_queue::{RendererOwnerWake, RendererOwnerWakeSender};+ use crate::runtime::protocol_output::{+ RendererOutputTransportTestLimits, renderer_output_transport_channel_with_test_limits,+ };use tokio::sync::oneshot::error::TryRecvError;fn output(call_id: i32) -> RendererRuntimeCommandOutput {@@ -3604,6 +3607,40 @@ mod renderer_runtime_inspector_response_channel_tests {)}+ fn output_with_by_value_payload(+ call_id: i32,+ payload_bytes: usize,+ ) -> RendererRuntimeCommandOutput {+ RendererRuntimeCommandOutput::from_inspector_message(+ RendererRuntimeInspectorMessage::protocol(json!({+ "id": call_id,+ "result": {+ "result": {+ "type": "string",+ "value": "x".repeat(payload_bytes),+ }+ },+ })),+ )+ }++ fn observation_publication(+ stream: RendererOutputStreamIdentity,+ sequence: u64,+ ) -> RendererOutputTransportMessage {+ let record = RendererOutputRecord::new_for_test(RendererOutputItem::Observation(+ RendererProtocolObservation::RuntimeLifecycleError {+ text: String::new(),+ execution_context_id: None,+ },+ ));+ RendererOutputPublication::new_for_test(+ RendererOutputCursor::new_for_test(stream, sequence),+ vec![record],+ )+ .into()+ }+#[tokio::test]async fn rotating_response_lease_rejects_old_sender_and_completes_new_sender_once() {let (channel, rx) = RendererRuntimeInspectorResponseChannel::new();@@ -3879,6 +3916,186 @@ mod renderer_runtime_inspector_response_channel_tests {channel.cancel();}+ #[tokio::test]+ async fn session_terminal_response_uses_essential_reserve_after_observation_saturation() {+ let page_id = PageId::new_for_testing(2);+ let stream = RendererOutputStreamIdentity::new_page_for_protocol_test(page_id);+ let limits = RendererOutputTransportTestLimits {+ max_pending_messages: 4,+ max_pending_bytes: 24 * 1024,+ max_observation_messages: 1,+ max_observation_bytes: 4 * 1024,+ max_message_bytes: 16 * 1024,+ };+ let (transport, mut transport_rx) =+ renderer_output_transport_channel_with_test_limits(limits);+ let journal = RendererTurnOutputJournal::new_with_transport(stream, transport.clone());+ assert!(matches!(+ transport_rx.recv().await,+ Some(RendererOutputTransportMessage::StreamControl(+ RendererOutputStreamControl::Opened { stream: opened }+ )) if opened == stream+ ));++ let filler_stream = RendererOutputStreamIdentity::new_shared_worker_for_protocol_test(2002);+ transport+ .send(observation_publication(filler_stream, 1))+ .expect("the first observation should fill its reserved quota");+ assert_eq!(transport.diagnostics().pending_observation_messages, 1);+ assert_eq!(+ transport.diagnostics().pending_observation_bytes,+ limits.max_observation_bytes+ );++ let attachment = RendererAgentAttachmentId::allocate();+ let (channel, receiver) = RendererRuntimeInspectorResponseChannel::new_for_delivery(+ moli_page_types::RendererInspectorResponseDelivery::DevToolsSession,+ );+ assert!(receiver.is_none());+ let sender = channel+ .activate_sender(29, Some(attachment))+ .route_to_devtools_session_output(RendererDevToolsSessionOutputHost::new(+ RendererDevToolsAgentToken::allocate(),+ DevToolsSessionKey::Attached("SID-essential-terminal".to_owned()),+ attachment,+ journal,+ ));+ let settlement_rx = sender+ .take_session_response_settlement_receiver()+ .expect("the session owner should await terminal response admission");++ sender+ .send_output(output_with_by_value_payload(29, 3 * 1024))+ .expect("terminal response should use the essential reserve");+ let settlement = settlement_rx+ .await+ .expect("successful transport admission should settle the session call");+ let (fence, response_succeeded) = settlement.into_parts();+ assert!(response_succeeded);+ assert_eq!(transport.diagnostics().pending_observation_messages, 1);+ assert!(+ transport.diagnostics().admitted_essential_messages >= 3,+ "stream open, terminal response, and its cursor lease should use essential admission"+ );+ assert!(!transport.diagnostics().terminal);++ assert!(matches!(+ transport_rx.recv().await,+ Some(RendererOutputTransportMessage::Publication(publication))+ if publication.cursor().stream() == filler_stream+ ));+ let terminal_publication = match transport_rx+ .recv()+ .await+ .expect("terminal response publication")+ {+ RendererOutputTransportMessage::Publication(publication) => publication,+ other => panic!("expected terminal response publication, got {other:?}"),+ };+ assert_eq!(terminal_publication.cursor(), fence.cursor());+ let [record] = terminal_publication.records() else {+ panic!("terminal response should remain one atomic record");+ };+ let RendererOutputItem::Observation(RendererProtocolObservation::RuntimeInspector(batch)) =+ record.item()+ else {+ panic!("terminal response should remain a Runtime Inspector observation");+ };+ let [RendererRuntimeInspectorMessage::Protocol(response)] = batch.messages.as_slice()+ else {+ panic!("terminal publication should contain exactly one protocol response");+ };+ assert_eq!(response.value()["id"], json!(29));+ assert!(matches!(+ transport_rx.recv().await,+ Some(RendererOutputTransportMessage::CursorLeaseDeclared { cursor, .. })+ if cursor == fence.cursor()+ ));+ drop(fence);+ }++ #[tokio::test]+ async fn rejected_session_terminal_response_does_not_settle_the_frontend_call() {+ let page_id = PageId::new_for_testing(3);+ let stream = RendererOutputStreamIdentity::new_page_for_protocol_test(page_id);+ let (transport, mut transport_rx) =+ renderer_output_transport_channel_with_test_limits(RendererOutputTransportTestLimits {+ max_pending_messages: 1,+ max_pending_bytes: 16 * 1024,+ max_observation_messages: 0,+ max_observation_bytes: 4 * 1024,+ max_message_bytes: 16 * 1024,+ });+ // Keep the essential Opened message pending so the total message+ // budget rejects the following terminal response.+ let journal = RendererTurnOutputJournal::new_with_transport(stream, transport.clone());+ let attachment = RendererAgentAttachmentId::allocate();+ let (channel, receiver) = RendererRuntimeInspectorResponseChannel::new_for_delivery(+ moli_page_types::RendererInspectorResponseDelivery::DevToolsSession,+ );+ assert!(receiver.is_none());+ let sender = channel+ .activate_sender(31, Some(attachment))+ .route_to_devtools_session_output(RendererDevToolsSessionOutputHost::new(+ RendererDevToolsAgentToken::allocate(),+ DevToolsSessionKey::Attached("SID-rejected-terminal".to_owned()),+ attachment,+ journal,+ ));+ let settlement_rx = sender+ .take_session_response_settlement_receiver()+ .expect("the session owner should await terminal response admission");++ let rejected = sender+ .send_output(output(31))+ .expect_err("a full total budget must reject the terminal response");+ assert_eq!(rejected.call_id, 31);+ assert!(transport.diagnostics().terminal);+ assert!(+ settlement_rx.await.is_err(),+ "transport rejection must close rather than satisfy the settlement waiter"+ );+ assert!(channel.try_activate_sender(32, Some(attachment)).is_none());+ assert!(matches!(+ transport_rx.recv().await,+ Some(RendererOutputTransportMessage::StreamControl(+ RendererOutputStreamControl::Opened { stream: opened }+ )) if opened == stream+ ));+ assert_eq!(transport_rx.recv().await, None);+ }++ #[tokio::test]+ async fn unbound_session_terminal_response_is_not_deferred_or_settled() {+ let page_id = PageId::new_for_testing(4);+ let stream = RendererOutputStreamIdentity::new_page_for_protocol_test(page_id);+ let journal = RendererTurnOutputJournal::new(stream);+ let attachment = RendererAgentAttachmentId::allocate();+ let (channel, receiver) = RendererRuntimeInspectorResponseChannel::new_for_delivery(+ moli_page_types::RendererInspectorResponseDelivery::DevToolsSession,+ );+ assert!(receiver.is_none());+ let sender = channel+ .activate_sender(33, Some(attachment))+ .route_to_devtools_session_output(RendererDevToolsSessionOutputHost::new(+ RendererDevToolsAgentToken::allocate(),+ DevToolsSessionKey::Attached("SID-unbound-terminal".to_owned()),+ attachment,+ journal.clone(),+ ));+ let settlement_rx = sender+ .take_session_response_settlement_receiver()+ .expect("the session owner should await terminal response admission");++ let rejected = sender+ .send_output(output(33))+ .expect_err("an unbound transport cannot admit a terminal response");+ assert_eq!(rejected.call_id, 33);+ assert!(settlement_rx.await.is_err());+ assert_eq!(journal.last_published_cursor(), None);+ assert_eq!(journal.pending_len(), 0);+ }+#[tokio::test]async fn rotating_session_lease_rejects_stale_bound_sender_and_publishes_once() {let old_stream =diff --git a/moli-renderer-v8/src/runtime/protocol_output/mod.rs b/moli-renderer-v8/src/runtime/protocol_output/mod.rsindex 6ae4bd07c..afaaa0248 100644--- a/moli-renderer-v8/src/runtime/protocol_output/mod.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/mod.rs@@ -21,13 +21,25 @@ pub use transport::{RendererOutputTransportReceiver, RendererOutputTransportSendError,RendererOutputTransportSender, renderer_output_transport_channel,};+#[cfg(test)]+pub(in crate::runtime) use transport::{+ RendererOutputTransportTestLimits, renderer_output_transport_channel_with_test_limits,+};pub(crate) use turn_journal::RendererTurnOutputJournal;+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+enum RendererOutputPublicationAdmission {+ Observation,+ EssentialOwnerProgress,+ EssentialTerminalResponse,+}+/// Move-owned output frozen at one renderer owner-turn settlement boundary.#[derive(Clone, Debug, PartialEq)]pub struct RendererOutputPublication {cursor: RendererOutputCursor,ordering: RendererOutputPublicationOrdering,+ admission: RendererOutputPublicationAdmission,records: Vec<RendererOutputRecord>,}@@ -52,9 +64,15 @@ impl RendererOutputPublication {!records.is_empty(),"renderer output publications must be non-empty");+ let admission = if records.iter().any(RendererOutputRecord::is_owner_action) {+ RendererOutputPublicationAdmission::EssentialOwnerProgress+ } else {+ RendererOutputPublicationAdmission::Observation+ };Self {cursor,ordering: RendererOutputPublicationOrdering::Unconstrained,+ admission,records,}}@@ -64,6 +82,19 @@ impl RendererOutputPublication {self}+ /// Protects the one terminal response owned by a DevTools session from+ /// ordinary observation backpressure. The response remains a protocol+ /// observation semantically, but command completion depends on admitting+ /// it, so transport must draw from its essential reserve.+ pub(crate) fn with_terminal_response_admission(mut self) -> Self {+ self.admission = RendererOutputPublicationAdmission::EssentialTerminalResponse;+ self+ }++ pub(crate) fn requires_essential_transport_admission(&self) -> bool {+ self.admission != RendererOutputPublicationAdmission::Observation+ }+pub fn cursor(&self) -> RendererOutputCursor {self.cursor}@@ -80,12 +111,6 @@ impl RendererOutputPublication {self.records}- pub(crate) fn contains_owner_action(&self) -> bool {- self.records- .iter()- .any(RendererOutputRecord::is_owner_action)- }-pub(crate) fn transport_charge_bytes(&self) -> usize {let records = self.records.iter().fold(0usize, |total, record| {total.saturating_add(record.transport_charge_bytes())diff --git a/moli-renderer-v8/src/runtime/protocol_output/transport.rs b/moli-renderer-v8/src/runtime/protocol_output/transport.rsindex 74e3d8d97..e226fc3d0 100644--- a/moli-renderer-v8/src/runtime/protocol_output/transport.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/transport.rs@@ -83,7 +83,9 @@ impl RendererOutputTransportMessage {fn admission_class(&self) -> RendererOutputTransportAdmissionClass {match self {- Self::Publication(publication) if !publication.contains_owner_action() => {+ Self::Publication(publication)+ if !publication.requires_essential_transport_admission() =>+ {RendererOutputTransportAdmissionClass::Observation}Self::StreamControl(_)@@ -152,11 +154,11 @@ impl RendererOutputTransportLimits {);assert!(self.max_observation_messages < self.max_pending_messages,- "renderer output transport must reserve messages for control and owner actions"+ "renderer output transport must reserve messages for control, owner actions, and terminal responses");assert!(self.max_observation_bytes < self.max_pending_bytes,- "renderer output transport must reserve bytes for control and owner actions"+ "renderer output transport must reserve bytes for control, owner actions, and terminal responses");assert!(self.max_message_bytes <= self.max_pending_bytes,@@ -524,6 +526,32 @@ fn renderer_output_transport_channel_with_limits()}+#[cfg(test)]+#[derive(Clone, Copy, Debug)]+pub(in crate::runtime) struct RendererOutputTransportTestLimits {+ pub max_pending_messages: usize,+ pub max_pending_bytes: usize,+ pub max_observation_messages: usize,+ pub max_observation_bytes: usize,+ pub max_message_bytes: usize,+}++#[cfg(test)]+pub(in crate::runtime) fn renderer_output_transport_channel_with_test_limits(+ limits: RendererOutputTransportTestLimits,+) -> (+ RendererOutputTransportSender,+ RendererOutputTransportReceiver,+) {+ renderer_output_transport_channel_with_limits(RendererOutputTransportLimits {+ max_pending_messages: limits.max_pending_messages,+ max_pending_bytes: limits.max_pending_bytes,+ max_observation_messages: limits.max_observation_messages,+ max_observation_bytes: limits.max_observation_bytes,+ max_message_bytes: limits.max_message_bytes,+ })+}+#[cfg(test)]mod tests {use std::sync::{Arc, Barrier};diff --git a/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs b/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rsindex cf9f2d129..09c087a9e 100644--- a/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs@@ -190,9 +190,9 @@ impl RendererTurnOutputJournal {/// second completion sequencer. The returned fence names the terminal/// batch itself so the command completion cannot release post-response/// owner actions before protocol ingress admits that batch. `None` means- /// the exact attachment stream was already closed before it could take- /// ownership of the records.- pub(crate) fn try_publish_records_and_declare_fence(+ /// the exact attachment stream was closed, unbound, or rejected the+ /// publication before it could take ownership of the records.+ pub(crate) fn try_publish_terminal_records_and_declare_fence(&self,records: impl IntoIterator<Item = PendingRendererOutputRecord>,) -> Option<RendererOutputFence> {@@ -205,23 +205,22 @@ impl RendererTurnOutputJournal {if state.closed {return None;}+ // A terminal response cannot settle against a deferred publication:+ // the DevTools session has no command-reply fallback if later+ // transport admission fails.+ let transport = state.transport.clone()?;state.records.extend(records);let publication = Self::settle_locked(&mut state)- .expect("newly appended renderer output records must settle");+ .expect("newly appended renderer output records must settle")+ .with_terminal_response_admission();let cursor = publication.cursor();- if let Some(transport) = state.transport.as_ref() {- // Admission failure means the protocol owner has retired or its- // bounded stream is terminal. The journal has nevertheless taken- // ownership at this exact sequence; falling back to another sink- // here could duplicate the response.- let _ = publication.publish_to(transport);- } else {- state.deferred_publications.push(publication);+ // Once this exact publication is rejected, the bounded transport is+ // terminal. Report the rejection to the response authority instead+ // of manufacturing a fence and falsely settling the frontend call.+ if publication.publish_to(&transport).is_err() {+ return None;}- Some(RendererOutputFence::declare(- cursor,- state.transport.clone(),- ))+ Some(RendererOutputFence::declare(cursor, Some(transport)))}fn settle_locked(