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/18 04:02:27 UTC

(maka) branch rust-preview updated: fix(agent): reject duplicate tool calls in completions

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 fe4dca0803 fix(agent): reject duplicate tool calls in completions
fe4dca0803 is described below

commit fe4dca0803858b47b81b26a5d650919422bbffcb
Author: Wang <m4...@gmail.com>
AuthorDate: Sun Oct 18 12:02:22 2026 +0800

    fix(agent): reject duplicate tool calls in completions
    
    Generated-by: Codex
---
 platform/event-log/tests/bundle/tamper.rs | 30 +++++++++++
 plugins/agent/facts/src/event_write.rs    | 86 +++++++++++++++++++++++++++++++
 2 files changed, 116 insertions(+)

diff --git a/platform/event-log/tests/bundle/tamper.rs b/platform/event-log/tests/bundle/tamper.rs
index e21552a2bb..0c6a0ce9ae 100644
--- a/platform/event-log/tests/bundle/tamper.rs
+++ b/platform/event-log/tests/bundle/tamper.rs
@@ -47,6 +47,36 @@ pub(super) async fn verify_original_proofs(
         staged.close().await.unwrap();
     }
     let mut changed = false;
+    let duplicate_calls = super::frames::rewrite_events(bytes, |event| {
+        if !changed && event["fact"]["kind"] == "model_completed" {
+            let parts = event["fact"]["output"]["parts"].as_array_mut().unwrap();
+            if let Some(call) = parts
+                .iter()
+                .find(|part| part["kind"] == "tool_call")
+                .cloned()
+            {
+                parts.push(call);
+                changed = true;
+            }
+        }
+        true
+    });
+    assert!(changed, "missing completed ToolCall fixture");
+    // rewrite_events repairs the transport digest; canonical submission must
+    // reject the ambiguity before later context proofs can obscure its cause.
+    bundle::inspect(duplicate_calls.as_slice()).await.unwrap();
+    let mut staged = StagedBundle::read(duplicate_calls.as_slice())
+        .await
+        .unwrap();
+    let result = staged.validate_history().await;
+    staged.close().await.unwrap();
+    assert!(
+        matches!(&result,
+            Err(BundleError::Store(StoreError::InvalidTransition(message)))
+                if message.contains("duplicate tool call")),
+        "duplicate completion reached canonical replay: {result:?}"
+    );
+    let mut changed = false;
     let mismatched_dispatch = super::frames::rewrite_events(bytes, |event| {
         if !changed && event["fact"]["kind"] == "tool_dispatched" {
             event["fact"]["input"] = json!({"path":"different-source"});
diff --git a/plugins/agent/facts/src/event_write.rs b/plugins/agent/facts/src/event_write.rs
index 9a78d8d8a0..4caf75719d 100644
--- a/plugins/agent/facts/src/event_write.rs
+++ b/plugins/agent/facts/src/event_write.rs
@@ -63,6 +63,14 @@ impl ProjectionArtifactWrite {
 impl EventWrite {
     pub fn plain(event: RuntimeEvent) -> Result<Self, CommitError> {
         match &event.fact {
+            Fact::ModelCompleted { output, .. } => {
+                let mut ids = std::collections::HashSet::new();
+                for call in output.tool_calls() {
+                    if !ids.insert(call.id.as_str()) {
+                        return Err(CommitError::Rejected("duplicate tool call".into()));
+                    }
+                }
+            }
             Fact::ToolDispatched {
                 title,
                 presentation,
@@ -358,3 +366,81 @@ impl EventWrite {
         &self.projection_artifacts
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::model::{ModelFinishReason, ModelPart, ModelStep, ModelToolCall};
+    use serde_json::json;
+
+    fn call(id: &str, name: &str, provider_executed: bool) -> ModelPart {
+        ModelPart::ToolCall {
+            call: ModelToolCall {
+                id: id.into(),
+                name: name.into(),
+                input: json!({"path":"file"}).into(),
+                provider_options: None,
+                provider_executed,
+            },
+        }
+    }
+
+    fn completion(parts: Vec<ModelPart>) -> RuntimeEvent {
+        RuntimeEvent::new(
+            Invocation {
+                session_id: "session".into(),
+                turn_id: "turn".into(),
+                run_id: "run".into(),
+                invocation_id: "invocation".into(),
+            },
+            Fact::ModelCompleted {
+                step_id: "step".into(),
+                output: ModelStep {
+                    parts,
+                    finish_reason: ModelFinishReason::ToolCalls,
+                    usage: Default::default(),
+                    provider_options: None,
+                    response_id: None,
+                    model: None,
+                    timestamp: None,
+                },
+            },
+        )
+    }
+
+    #[test]
+    fn completion_rejects_duplicate_tool_call_ids_before_submission() {
+        for (first_provider, second_provider, second_name) in [
+            (false, false, "Read"),
+            (false, false, "DifferentTool"),
+            (true, false, "Read"),
+            (false, true, "Read"),
+        ] {
+            let event = completion(vec![
+                call("same-id", "Read", first_provider),
+                call("same-id", second_name, second_provider),
+            ]);
+            assert!(
+                matches!(EventWrite::plain(event), Err(CommitError::Rejected(_))),
+                "duplicate ID formed a submission: {first_provider}/{second_provider}/{second_name}"
+            );
+        }
+    }
+
+    #[test]
+    fn completion_accepts_provider_result_id_reuse_with_distinct_local_call() {
+        let event = completion(vec![
+            call("provider-call", "Read", true),
+            ModelPart::ToolResult {
+                id: "provider-call".into(),
+                name: "Read".into(),
+                output: json!({"content":"provider result"}),
+                is_error: false,
+                provider_options: None,
+            },
+            call("local-call", "Read", false),
+        ]);
+        let submitted = EventWrite::plain(event.clone()).unwrap();
+        assert_eq!(submitted.into_event(), event);
+    }
+}


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