You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/10/17 18:36:21 UTC

(maka) branch rust-preview updated: fix(presentation): bound tool fanout by retained bytes

This is an automated email from the ASF dual-hosted git repository.

M4n5ter pushed a commit to branch rust-preview
in repository https://gitbox.apache.org/repos/asf/maka.git


The following commit(s) were added to refs/heads/rust-preview by this push:
     new ece304b1e1 fix(presentation): bound tool fanout by retained bytes
ece304b1e1 is described below

commit ece304b1e13587339935a4fb2136c42d1e09414f
Author: Wang <m4...@gmail.com>
AuthorDate: Sun Oct 18 02:36:14 2026 +0800

    fix(presentation): bound tool fanout by retained bytes
    
    Remove unsupported part and pending-call count limits. Account retained text identity and merged provider metadata within the existing byte budget, preserving acceptance validation and row identity.
    
    Verify complete public history for 129 real service calls and independent item-accepted fanout beyond 256 calls.
    
    Generated-by: Codex
---
 platform/presentation/src/step.rs                  |  72 ++++--
 platform/presentation/src/tools/state.rs           |   2 +-
 platform/presentation/tests/projection.rs          | 247 ++++++++++++++++++++-
 .../native/src/owner/tests/service_tools/storm.rs  |  42 +++-
 4 files changed, 346 insertions(+), 17 deletions(-)

diff --git a/platform/presentation/src/step.rs b/platform/presentation/src/step.rs
index 4540e1a1e8..69ae8f9660 100644
--- a/platform/presentation/src/step.rs
+++ b/platform/presentation/src/step.rs
@@ -54,7 +54,7 @@ pub(super) struct Step {
     model: String,
     parts: Vec<Part>,
     order: Vec<Observed>,
-    text_bytes: usize,
+    retained_bytes: usize,
     limit: usize,
 }
 impl Step {
@@ -65,7 +65,7 @@ impl Step {
             model,
             parts: Vec::new(),
             order: Vec::new(),
-            text_bytes: 0,
+            retained_bytes: 0,
             limit,
         }
     }
@@ -88,12 +88,24 @@ impl Step {
                 text_kind,
                 provider_options,
             } => {
-                if self.order.len() >= 128 {
-                    return Err(ProjectionError::TooLarge);
-                }
                 if self.parts.iter().any(|part| part.provider_id == *id) {
                     return Err(ProjectionError::Invalid("duplicate model part"));
                 }
+                let bytes = serde_json::to_vec(&(
+                    id,
+                    &event.id,
+                    &event.invocation.turn_id,
+                    timestamp,
+                    text_kind,
+                    "",
+                    provider_options,
+                ))
+                .map_err(|_| ProjectionError::TooLarge)?
+                .len();
+                if bytes > self.limit.saturating_sub(self.retained_bytes) {
+                    return Err(ProjectionError::TooLarge);
+                }
+                self.retained_bytes += bytes;
                 self.order.push(Observed::Text(self.parts.len()));
                 self.parts.push(Part {
                     provider_id: id.clone(),
@@ -112,9 +124,6 @@ impl Step {
                 text,
                 provider_options,
             } => {
-                if text.len() > self.limit.saturating_sub(self.text_bytes) {
-                    return Err(ProjectionError::TooLarge);
-                }
                 let part = self
                     .parts
                     .iter_mut()
@@ -123,9 +132,16 @@ impl Step {
                 if part.state != PartState::Open {
                     return Err(ProjectionError::Invalid("delta after part end"));
                 }
-                self.text_bytes += text.len();
+                part.merge_options(
+                    provider_options.as_ref(),
+                    &mut self.retained_bytes,
+                    self.limit,
+                )?;
+                if text.len() > self.limit.saturating_sub(self.retained_bytes) {
+                    return Err(ProjectionError::TooLarge);
+                }
+                self.retained_bytes += text.len();
                 part.text.push_str(text);
-                merge_provider_options(&mut part.options, provider_options.clone());
             }
             ModelEvent::PartFinished {
                 id,
@@ -139,8 +155,12 @@ impl Step {
                 if part.state != PartState::Open {
                     return Err(ProjectionError::Invalid("duplicate part end"));
                 }
+                part.merge_options(
+                    provider_options.as_ref(),
+                    &mut self.retained_bytes,
+                    self.limit,
+                )?;
                 part.state = PartState::Closed;
-                merge_provider_options(&mut part.options, provider_options.clone());
             }
             ModelEvent::Source(source) => self.tool(ModelPart::Source {
                 source: source.clone(),
@@ -168,10 +188,10 @@ impl Step {
         let bytes = serde_json::to_vec(&part)
             .map_err(|_| ProjectionError::TooLarge)?
             .len();
-        if self.order.len() >= 128 || bytes > self.limit.saturating_sub(self.text_bytes) {
+        if bytes > self.limit.saturating_sub(self.retained_bytes) {
             return Err(ProjectionError::TooLarge);
         }
-        self.text_bytes += bytes;
+        self.retained_bytes += bytes;
         self.order.push(Observed::Tool(part));
         Ok(())
     }
@@ -258,6 +278,32 @@ impl Step {
     }
 }
 impl Part {
+    fn merge_options(
+        &mut self,
+        incoming: Option<&Value>,
+        retained_bytes: &mut usize,
+        limit: usize,
+    ) -> Result<(), ProjectionError> {
+        let Some(incoming) = incoming else {
+            return Ok(());
+        };
+        let mut options = self.options.clone();
+        merge_provider_options(&mut options, Some(incoming.clone()));
+        let size = |options: &Option<Value>| {
+            serde_json::to_vec(options)
+                .map(|bytes| bytes.len())
+                .map_err(|_| ProjectionError::TooLarge)
+        };
+        let bytes = retained_bytes.saturating_sub(size(&self.options)?);
+        let new_size = size(&options)?;
+        if new_size > limit.saturating_sub(bytes) {
+            return Err(ProjectionError::TooLarge);
+        }
+        *retained_bytes = bytes + new_size;
+        self.options = options;
+        Ok(())
+    }
+
     fn message(&self, model: &str, options: Option<Value>, interrupted: bool) -> Message {
         let (text, thinking) = match self.kind {
             TextKind::Text => (self.text.clone(), None),
diff --git a/platform/presentation/src/tools/state.rs b/platform/presentation/src/tools/state.rs
index ad6a11df18..5cf4bdc937 100644
--- a/platform/presentation/src/tools/state.rs
+++ b/platform/presentation/src/tools/state.rs
@@ -87,7 +87,7 @@ impl Tools {
         let bytes = serde_json::to_vec(&(operation, &identity, name, &input))
             .map_err(|_| ProjectionError::TooLarge)?
             .len();
-        if self.pending.len() >= 256 || bytes > self.limit.saturating_sub(self.bytes) {
+        if bytes > self.limit.saturating_sub(self.bytes) {
             return Err(ProjectionError::TooLarge);
         }
         self.bytes += bytes;
diff --git a/platform/presentation/tests/projection.rs b/platform/presentation/tests/projection.rs
index 11be4b0f24..fcd19dc4e4 100644
--- a/platform/presentation/tests/projection.rs
+++ b/platform/presentation/tests/projection.rs
@@ -356,7 +356,7 @@ fn completed_and_interrupted_rows_keep_overlay_identity_time() {
 #[test]
 fn malformed_or_oversized_evidence_poison_the_view_instead_of_publishing_partial_success() {
     let mut events = events(InvocationOutcome::Completed);
-    let mut view = InvocationView::new(64).unwrap();
+    let mut view = InvocationView::new(1024).unwrap();
     for event in &events[..3] {
         view.push(event).unwrap();
     }
@@ -367,7 +367,7 @@ fn malformed_or_oversized_evidence_poison_the_view_instead_of_publishing_partial
     else {
         unreachable!()
     };
-    *text = "x".repeat(65);
+    *text = "x".repeat(1025);
     assert!(matches!(
         view.push(&events[3]),
         Err(ProjectionError::TooLarge)
@@ -540,3 +540,246 @@ fn annotated_openings_preserve_source_identity_and_unannotated_batches_stay_aggr
         }
     }
 }
+
+fn project_tool_fanout(count: usize, item_acceptance: bool) -> Vec<maka_presentation::Row> {
+    use maka_agent_facts::model::{ModelFinishReason, ModelToolCall, ToolInput};
+    use maka_agent_facts::tool_call::ToolCallIdentity;
+    let mut original = events(InvocationOutcome::Completed);
+    let mut request = original.remove(1);
+    let opening = original.remove(0);
+    let Fact::ModelRequested {
+        item_acceptance: enabled,
+        ..
+    } = &mut request.event.fact
+    else {
+        unreachable!()
+    };
+    *enabled = item_acceptance;
+    let invocation = opening.event.invocation.clone();
+    let mut view = InvocationView::new(1024 * 1024).unwrap();
+    view.push(&opening).unwrap();
+    view.push(&request).unwrap();
+    let mut sequence = request.sequence;
+    let mut rows = Vec::new();
+    let mut push = |fact| {
+        sequence += 1;
+        rows.extend(
+            view.push(&StoredEvent {
+                sequence,
+                event: RuntimeEvent::new(invocation.clone(), fact),
+            })
+            .unwrap(),
+        );
+    };
+    let calls: Vec<_> = (0..count)
+        .map(|index| ModelToolCall {
+            id: format!("call-{index}"),
+            name: "echo".into(),
+            input: ToolInput::Json(json!({"note":format!("input-{index}")})),
+            provider_options: None,
+            provider_executed: false,
+        })
+        .collect();
+    for call in &calls {
+        push(Fact::ModelObserved {
+            step_id: "step".into(),
+            event: ModelEvent::ToolCall(call.clone()),
+        });
+    }
+    push(Fact::ModelObserved {
+        step_id: "step".into(),
+        event: ModelEvent::Finished {
+            reason: ModelFinishReason::ToolCalls,
+            usage: ModelUsage::default(),
+            provider_options: None,
+        },
+    });
+    push(Fact::ModelCompleted {
+        step_id: "step".into(),
+        output: ModelStep {
+            parts: calls
+                .iter()
+                .cloned()
+                .map(|call| ModelPart::ToolCall { call })
+                .collect(),
+            finish_reason: ModelFinishReason::ToolCalls,
+            usage: ModelUsage::default(),
+            provider_options: None,
+            response_id: None,
+            model: None,
+            timestamp: None,
+        },
+    });
+    for call in calls {
+        let operation_id = format!("step:{}", call.id);
+        push(Fact::ToolDispatched {
+            presentation: None,
+            title: None,
+            operation_id: operation_id.clone(),
+            call: ToolCallIdentity::provider("step".into(), call.id.clone()),
+            name: call.name,
+            input: call.input.as_json().unwrap().clone(),
+        });
+        push(Fact::ToolSettled {
+            operation_id,
+            outcome: maka_agent_facts::event::ToolOutcome::Failed {
+                message: format!("fixture result {}", call.id),
+            },
+        });
+    }
+    rows
+}
+
+#[test]
+fn completion_accepted_fanout_projects_129_original_calls_and_results() {
+    let rows = project_tool_fanout(129, false);
+    let calls: Vec<_> = rows
+        .iter()
+        .filter_map(|row| match &row.message.content {
+            Content::ToolCall { args, .. } => Some(args),
+            _ => None,
+        })
+        .collect();
+    assert_eq!(calls.len(), 129);
+    assert_eq!(calls[0], &json!({"note":"input-0"}));
+    assert_eq!(calls[128], &json!({"note":"input-128"}));
+    let results: Vec<_> = rows
+        .iter()
+        .filter_map(|row| match &row.message.content {
+            Content::ToolResult {
+                content: maka_presentation::ToolContent::Text { text },
+                ..
+            } => Some(text.as_str()),
+            _ => None,
+        })
+        .collect();
+    assert_eq!(results.len(), 129);
+    assert_eq!(results[128], "fixture result call-128");
+}
+
+#[test]
+fn item_accepted_fanout_projects_257_calls_with_distinct_original_positions() {
+    let rows = project_tool_fanout(257, true);
+    let calls: Vec<_> = rows
+        .iter()
+        .filter(|row| matches!(row.message.content, Content::ToolCall { .. }))
+        .collect();
+    assert_eq!(calls.len(), 257);
+    assert!(
+        calls
+            .windows(2)
+            .all(|pair| pair[0].sequence < pair[1].sequence)
+    );
+    assert_eq!(calls[0].sequence, 3328);
+    assert_eq!(calls[256].sequence, 68864);
+    assert!(
+        matches!(&calls[256].message.content, Content::ToolCall { args, .. } if args == &json!({"note":"input-256"}))
+    );
+    let results: Vec<_> = rows
+        .iter()
+        .filter_map(|row| match &row.message.content {
+            Content::ToolResult {
+                content: maka_presentation::ToolContent::Text { text },
+                ..
+            } => Some(text.as_str()),
+            _ => None,
+        })
+        .collect();
+    assert_eq!(results.len(), 257);
+    assert_eq!(results[256], "fixture result call-256");
+}
+
+#[test]
+fn retained_text_metadata_is_bounded_after_start_delta_and_finish() {
+    for stage in ["identity", "start", "delta", "finish"] {
+        let mut source = events(InvocationOutcome::Completed);
+        let mut view = InvocationView::new(4096).unwrap();
+        for event in source.iter().take(2) {
+            view.push(event).unwrap();
+        }
+        let options = Some(json!({"signature":"x".repeat(8192)}));
+        let index = match stage {
+            "identity" | "start" => 2,
+            "delta" => 3,
+            _ => 4,
+        };
+        if stage == "identity" {
+            let Fact::ModelObserved {
+                event: ModelEvent::PartStarted { id, .. },
+                ..
+            } = &mut source[index].event.fact
+            else {
+                unreachable!()
+            };
+            *id = "x".repeat(8192);
+        } else {
+            match &mut source[index].event.fact {
+                Fact::ModelObserved {
+                    event:
+                        ModelEvent::PartStarted {
+                            provider_options, ..
+                        }
+                        | ModelEvent::PartDelta {
+                            provider_options, ..
+                        }
+                        | ModelEvent::PartFinished {
+                            provider_options, ..
+                        },
+                    ..
+                } => *provider_options = options,
+                _ => unreachable!(),
+            }
+        }
+        for event in source.iter().take(index).skip(2) {
+            view.push(event).unwrap();
+        }
+        assert!(
+            matches!(view.push(&source[index]), Err(ProjectionError::TooLarge)),
+            "{stage} metadata must fit the retained byte budget"
+        );
+    }
+
+    // Replacing one option does not retain every former value. Accepted text
+    // options still follow the original completion rather than a new equality rule.
+    let mut source = events(InvocationOutcome::Completed);
+    let invocation = source[0].event.invocation.clone();
+    let mut view = InvocationView::new(4096).unwrap();
+    for event in source.iter().take(3) {
+        view.push(event).unwrap();
+    }
+    let mut sequence = source[2].sequence;
+    for _ in 0..8 {
+        sequence += 1;
+        view.push(&StoredEvent {
+            sequence,
+            event: RuntimeEvent::new(
+                invocation.clone(),
+                Fact::ModelObserved {
+                    step_id: "step".into(),
+                    event: ModelEvent::PartDelta {
+                        id: "provider-part".into(),
+                        text: String::new(),
+                        provider_options: Some(json!({"signature":"x".repeat(1024)})),
+                    },
+                },
+            ),
+        })
+        .unwrap();
+    }
+    for event in source.iter_mut().skip(4).take(3) {
+        sequence += 1;
+        event.sequence = sequence;
+        if let Fact::ModelCompleted { output, .. } = &mut event.event.fact {
+            let ModelPart::Text { text, .. } = &mut output.parts[0] else {
+                unreachable!()
+            };
+            text.clear();
+        }
+        let rows = view.push(event).unwrap();
+        if matches!(event.event.fact, Fact::ModelCompleted { .. }) {
+            assert!(
+                matches!(&rows[0].message.content, Content::Assistant { text, provider_options, .. } if text.is_empty() && provider_options == &Some(json!({"vendor":{"signature":"signed"}})))
+            );
+        }
+    }
+}
diff --git a/plugins/agent/native/src/owner/tests/service_tools/storm.rs b/plugins/agent/native/src/owner/tests/service_tools/storm.rs
index df8b46e3f8..e11ba18b3f 100644
--- a/plugins/agent/native/src/owner/tests/service_tools/storm.rs
+++ b/plugins/agent/native/src/owner/tests/service_tools/storm.rs
@@ -378,14 +378,41 @@ async fn verify(fixture: &Fixture, session: &str, invocation: &str, case: Case)
     // Exact original assistant text through the public, fixed-fence paged history path.
     let mut input = json!({"sessionId":session,"through":through,"position":{"kind":"start"}});
     let mut final_text = String::new();
+    let expected_tools: BTreeMap<_, _> = dispatched
+        .iter()
+        .map(|(operation, index)| {
+            (
+                maka_agent_facts::tool_call::tool_use_id(invocation, operation),
+                *index,
+            )
+        })
+        .collect();
+    let mut result_offsets = BTreeMap::new();
     loop {
-        let page = fixture.query("history", input.clone()).await.unwrap();
+        let page = match fixture.query("history", input.clone()).await {
+            Ok(page) => page,
+            Err(error) => {
+                let preparation = fixture.store.prepare_transcript(session, through, 32).await;
+                panic!("public history failed: {error}; preparation diagnostic: {preparation:?}");
+            }
+        };
         assert_eq!(page["through"], through);
         if page["kind"] == "preparing" {
             tokio::task::yield_now().await;
             continue;
         }
         for chunk in page["chunks"].as_array().unwrap() {
+            if chunk["role"] == "tool_result" && chunk["field"] == "body" {
+                let tool = chunk["tool"]["toolUseId"].as_str().unwrap();
+                let index = expected_tools[tool];
+                let expected = payload(index, case.bytes);
+                let offset = result_offsets.entry(tool.to_owned()).or_insert(0usize);
+                let text = chunk["text"].as_str().unwrap();
+                assert_eq!(chunk["offset"], *offset);
+                assert_eq!(chunk["totalBytes"], expected.len());
+                assert_eq!(text, &expected[*offset..*offset + text.len()]);
+                *offset += text.len();
+            }
             if chunk["role"] == "assistant" && chunk["field"] == "body" {
                 assert_eq!(chunk["offset"], final_text.len());
                 assert_eq!(chunk["totalBytes"], FINAL.len());
@@ -398,6 +425,8 @@ async fn verify(fixture: &Fixture, session: &str, invocation: &str, case: Case)
         input["position"] = json!({"kind":"after","cursor":page["after"]});
     }
     assert_eq!(final_text, FINAL);
+    assert_eq!(result_offsets.len(), case.calls);
+    assert!(result_offsets.values().all(|bytes| *bytes == case.bytes));
     let execution = fixture
         .query(
             "execution",
@@ -700,3 +729,14 @@ async fn real_service_tool_storm() {
 async fn real_service_query_fanout() {
     assert_eq!(run(Case::environment(true)).await["status"], "completed");
 }
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn public_history_preserves_129_real_service_query_results() {
+    let case = Case {
+        calls: 129,
+        bytes: 128,
+        javascript: false,
+        query: true,
+    };
+    assert_eq!(run(case).await["status"], "completed");
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org