Repository navigation
refactor(acp): dedup tool-call progress at the source (O(n²)→O(1)) - #3465
Conversation
ACP persisted one ACPToolCallEvent per ToolCallProgress notification, each carrying the full cumulative output, so a chatty tool call cost O(n^2) storage plus WebSocket relay (and on cloud, O(n^2) proxy relay/persist of every cumulative frame). The regular agent persists exactly one Action + one Observation per tool call. Collapse ACP onto that model. The bridge now persists exactly two events per tool_call_id: one early `started` event (the action) on ToolCallStart and one terminal completed/failed event (the observation) on the first transition into a terminal status. Intermediate ToolCallProgress frames are accumulated silently so the terminal event still carries the final output. _finalize_successful_turn flushes any tool call the server opened but never closed to `completed`, guaranteeing every `started` has a matching terminal observation (no orphaned "running" cards). The downstream tool_call_id merges (RemoteConversation._add_event_unsafe and resume_transcript._terminal_tool_indices) are kept: they now merge the 2-event started->terminal pair into one card -- an O(1) merge, the analog of an Observation superseding its Action -- rather than the old O(n^2) per-frame dedup. Their comments are updated to match. Part of OpenHands/agent-canvas#1025 (epic #988). Pairs with the agent-canvas PR that relaxes the should-render gate to render the running `started` card. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
Paired canvas PR (renders the running |
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
Coverage Report •
|
||||||||||||||||||||||||||||||||||||||||
all-hands-bot
left a comment
There was a problem hiding this comment.
Summary
Solid, well-reasoned refactor. The root cause is correctly identified — emitting one ACPToolCallEvent per cumulative ToolCallProgress frame is O(n²) storage and WebSocket relay — and the fix is clean: collapse to an action→observation pair (one started event on ToolCallStart, one terminal event on the first transition into completed/failed). The backward-compat note in _terminal_tool_indices for pre-refactor persisted logs is good defensive thinking, and the flush of unclosed cards in _finalize_successful_turn closes the invariant neatly.
Two items worth addressing:
_emit_tool_call_event docstring is now stale
Lines 695–699 still say "Called from session_update on each ToolCallStart / ToolCallProgress". After this PR it is called on ToolCallStart and on the first terminal ToolCallProgress only, plus the new _flush_inflight_tool_calls_as_completed path. A one-line update avoids future confusion.
_flush_inflight_tool_calls_as_completed reaches into a private method of _OpenHandsACPBridge
ACPAgent._flush_inflight_tool_calls_as_completed calls self._client._emit_tool_call_event(tc) directly. Both types are module-private (underscore-prefixed) so this works, and _cancel_inflight_tool_calls already follows the same pattern — it's consistent. Flagging purely as a future-cleanup note: moving flush_inflight_as_completed onto _OpenHandsACPBridge itself would co-locate the full single-event lifecycle with the bridge and let ACPAgent call a slightly higher-level method. Not a blocker.
See inline comment for the one concrete suggestion.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
| became_terminal = ( | ||
| target is not None | ||
| and target.get("status") in _TERMINAL_TOOL_CALL_STATUSES | ||
| and prev_status not in _TERMINAL_TOOL_CALL_STATUSES | ||
| ) | ||
| if target is not None and became_terminal: | ||
| self._emit_tool_call_event(target) |
There was a problem hiding this comment.
🟡 Suggestion: became_terminal already includes target is not None as its first conjunct, so the outer guard on line 686 is always true when became_terminal is true and always false when it's false — the two conditions are redundant. Simplifying to if became_terminal: makes the intent clearer and removes the implicit claim that the two checks are independent.
| became_terminal = ( | |
| target is not None | |
| and target.get("status") in _TERMINAL_TOOL_CALL_STATUSES | |
| and prev_status not in _TERMINAL_TOOL_CALL_STATUSES | |
| ) | |
| if target is not None and became_terminal: | |
| self._emit_tool_call_event(target) | |
| became_terminal = ( | |
| target is not None | |
| and target.get("status") in _TERMINAL_TOOL_CALL_STATUSES | |
| and prev_status not in _TERMINAL_TOOL_CALL_STATUSES | |
| ) | |
| if became_terminal: | |
| self._emit_tool_call_event(target) |
all-hands-bot
left a comment
There was a problem hiding this comment.
⚠️ QA Report: PASS WITH ISSUES
Functional QA confirms ACP tool-call progress is collapsed from cumulative progress fan-out to a two-event lifecycle, but the PR currently has one failing CI check.
Does this PR achieve its stated goal?
Yes. The stated goal was to collapse ACP ToolCallProgress persistence from O(n²) cumulative-frame fan-out to O(1) lifecycle events while preserving final output and avoiding orphaned running cards. Using real agent-client-protocol schema notifications against the SDK runtime path, origin/main emitted 5 ACPToolCallEvents for one chatty tool call, while this PR emitted exactly 2 (pending + completed) and the completed event carried the final output. The PR-only orphan flush also converted an in-progress accumulated call to a completed ACPToolCallEvent.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully; no tests/linters were run. |
| CI Status | Python API breakage check), 1 skipped. |
| Functional Verification | ✅ ACP progress collapse, transcript single-card rendering, and orphan flush behavior were exercised. |
Functional Verification
Test 1: Chatty ACP tool call emits lifecycle events instead of every cumulative progress frame
Step 1 — Reproduce / establish baseline (without the fix):
Ran git checkout origin/main && uv run python /tmp/qa_acp_progress.py:
{
"event_count": 5,
"events": [
{"status": "pending", "raw_output": null},
{"status": "in_progress", "raw_output": "chunk-1"},
{"status": "in_progress", "raw_output": "chunk-1
chunk-2"},
{"status": "completed", "raw_output": "chunk-1
chunk-2
final"},
{"status": "completed", "raw_output": "chunk-1
chunk-2
final
redundant-terminal"}
],
"transcript_tool_use_count": 1,
"transcript_contains_redundant_terminal": true
}This confirms the baseline problem: every progress notification, including intermediate cumulative output and redundant terminal output, was emitted as an ACPToolCallEvent.
Step 2 — Apply the PR's changes:
Checked out decc2240ef4c345e91bce5bc3d364c7c6265848e.
Step 3 — Re-run with the fix in place:
Ran git checkout decc2240ef4c345e91bce5bc3d364c7c6265848e && uv run python /tmp/qa_acp_progress.py:
{
"event_count": 2,
"events": [
{"status": "pending", "raw_output": null},
{"status": "completed", "raw_output": "chunk-1
chunk-2
final"}
],
"transcript_tool_use_count": 1,
"transcript_contains_redundant_terminal": false
}This shows the changed behavior works: intermediate in_progress frames and a duplicate terminal frame are no longer emitted, while the terminal event still has the final cumulative output. A follow-up transcript render showed one [TOOL USE: chatty shell command] (completed) card with output lines chunk-1, chunk-2, and final.
Test 2: In-flight ACP tool call can be flushed to a terminal completed event
Step 1 — Reproduce / establish baseline (without the fix):
Ran git checkout origin/main && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_acp_orphan.py:
{
"flush_available": false,
"accumulated_status": "in_progress",
"emitted_events": []
}This establishes the prior state: there was no flush helper, and an accumulated tool call with no closing progress frame remained in_progress.
Step 2 — Apply the PR's changes:
Checked out decc2240ef4c345e91bce5bc3d364c7c6265848e.
Step 3 — Re-run with the fix in place:
Ran git checkout decc2240ef4c345e91bce5bc3d364c7c6265848e && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_acp_orphan.py:
{
"flush_available": true,
"accumulated_status": "completed",
"emitted_events": [
{
"class": "ACPToolCallEvent",
"tool_call_id": "orphan-1",
"status": "completed",
"raw_output": "partial output before prompt returned",
"is_error": false
}
]
}This confirms the PR's orphan-card safeguard works at the SDK runtime level: a non-terminal accumulated tool call is converted to a terminal completed observation with its partial output preserved.
Issues Found
- 🟠 Issue: CI is not currently green:
Python APIinPython API breakage checksis failing (job link). I did not rerun or diagnose CI as part of QA.
This QA review was created by an AI agent (OpenHands) on behalf of the requester.
Final verdict: PASS WITH ISSUES
enyst
left a comment
There was a problem hiding this comment.
Thank you for this! I actually think complexity stuff is fairly important, as we’ve stepped into the era of long running histories.
Just would like to take a moment, please, for us to understand the Python API breakage: why is it failing?
|
@OpenHands Understand this PR and check the Griffe API breakage workflow which fails in CI right now. Why is it failing, and WDYT, is the workflow too strict and maybe we could relax it or is it a real breakage downstream, or? Post your response directly as a comment. |
|
I'm on it! enyst can track my progress at all-hands.dev |
|
I checked the PR diff, the linked ACP issue context, and the failing Python API/Griffe job. Short version: this failure is not caused by the ACP progress-dedup change in this PR. The only reported breakages are:
Those come from the already-merged My take:
So: this PR's ACP change looks unrelated to the CI failure. I would not change this PR for it unless we want to opportunistically include the compatibility shim here; otherwise the right follow-up is either revert/deprecate the OpenHands/OpenHands#3456 removal on This comment was created by an AI agent (OpenHands) on behalf of the requester. |
|
OpenHands encountered an error: Request timeout after 30 seconds to https://drnpzzvchqbqlytn.prod-runtime.all-hands.dev/api/conversations/75ee4c28-d469-4b0c-b82f-810a2425df63/ask_agent See the conversation for more information. |
|
Follow-up: I opened a separate non-draft revert PR from That PR reverts OpenHands/OpenHands#3456 / This comment was created by an AI agent (OpenHands) on behalf of the requester. |
Sorry, my agent dug in and found out that the API breakage wasn’t caused by this PR!
The regular terminal masks every observation via secret_registry.mask_secrets_in_output(); ACP masked nothing, so a subprocess that echoed an injected credential (env, a failing curl printing an Authorization header) landed in the persisted event stream and WebSocket relay in cleartext — the largest credential-leak surface, widened on cloud where subscription tokens are injected. Route ACP output through the registry mask before emitting: - streamed AgentMessageChunk text (on_token + accumulated_text) and AgentThoughtChunk text - tool-call title/raw_input/raw_output/content, masked at ingestion so the started event, the single terminal event (#3465 dedup), and the flush/supersede path all carry masked values and the accumulator never holds plaintext - the joined response_text/thought_text in _finalize_successful_turn (persistence boundary), which also catches secrets split across stream chunks Complete the mask set for the channels that bypass get_secret_value: seed _exported_values for the agent_context.secrets drain and the (deprecated, #3464) acp_env via a new SecretRegistry.track_exported_value with a minimum-length guard so trivially short non-secret config (e.g. VERBOSITY=1) is not masked. The state.secret_registry channel auto-seeds via get_secret_value. A failing masker falls back to the original value (crash-safe), matching the terminal tool contract. The live on_token relay still forwards a secret split mid-value across chunks as fragments; the persisted stream is fully masked. Implements pre-cloud refactor P0-2 (OpenHands/agent-canvas#1023). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The regular terminal masks every observation via secret_registry.mask_secrets_in_output(); ACP masked nothing, so a subprocess that echoed an injected credential (env, a failing curl printing an Authorization header) landed in the persisted event stream and WebSocket relay in cleartext — the largest credential-leak surface, widened on cloud where subscription tokens are injected. Route ACP output through the registry mask before emitting: - streamed AgentMessageChunk text (on_token + accumulated_text) and AgentThoughtChunk text - tool-call title/raw_input/raw_output/content, masked at ingestion so the started event, the single terminal event (#3465 dedup), and the flush/supersede path all carry masked values and the accumulator never holds plaintext - the joined response_text/thought_text in _finalize_successful_turn (persistence boundary), which also catches secrets split across stream chunks The mask set is the registry's _exported_values, seeded by get_secret_value when _start_acp_server reads state.secret_registry — the canonical channel that #3464 routes provider creds and (on the caller/cloud path) agent_context.secrets through. No new SecretRegistry API; the deprecated acp_env / canvas-local drain are out of scope. A failing masker falls back to the original value (crash-safe), matching the terminal tool contract. The live on_token relay still forwards a secret split mid-value across chunks as fragments; the persisted stream is fully masked (follow-up: OpenHands/agent-canvas#1049). Implements pre-cloud refactor P0-2 (OpenHands/agent-canvas#1023). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The regular terminal masks every observation via secret_registry.mask_secrets_in_output(); ACP masked nothing, so a subprocess that echoed an injected credential (env, a failing curl printing an Authorization header) landed in the persisted event stream and WebSocket relay in cleartext — the largest credential-leak surface, widened on cloud where subscription tokens are injected. Bind the registry masker onto the bridge once in _start_acp_server (conversation-stable; a pure read of _exported_values with none of the cross-thread/state-lock hazards that make on_event/on_token per-turn) and route ACP output through it before emitting: - streamed AgentMessageChunk text (on_token + accumulated_text) and AgentThoughtChunk text - tool-call title/raw_input/raw_output/content, masked at ingestion so the started event, the single terminal event (#3465 dedup), and the flush/supersede path all carry masked values and the accumulator never holds plaintext - the ask_agent() fork accumulator + its joined return value, which is relayed to the caller/UI (binding the masker once is what makes this reachable even when ask_agent runs while no turn is active) - the joined response_text/thought_text in _finalize_successful_turn (persistence boundary), which also catches secrets split across chunks The mask set is the registry's _exported_values, seeded by get_secret_value when _start_acp_server reads state.secret_registry — the canonical channel that #3464 routes provider creds and (on the caller/cloud path) agent_context.secrets through. No new SecretRegistry API; the deprecated acp_env / canvas-local drain are out of scope. A failing masker falls back to the original value (crash-safe), matching the terminal tool contract. The live on_token relay still forwards a secret split mid-value across chunks as fragments; the persisted stream is fully masked (follow-up: OpenHands/agent-canvas#1049). Implements pre-cloud refactor P0-2 (OpenHands/agent-canvas#1023). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…penHands#3465) Co-authored-by: Debug Agent <debug@example.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Engel Nyst <engel.nyst@gmail.com>
Problem
ACP persisted every
ToolCallProgressemission, each carrying the full cumulative output (acp_agent.pysession_update;_default_callbackpersists each one). For a chatty tool call that is O(n²) storage + WebSocket relay — and on cloud the proxy relays and persists every cumulative frame across the network, the single biggest relay/storage cost. The regular agent persists exactly one Action + one Observation per tool call, with no per-progress fan-out.Part of OpenHands/agent-canvas#2110 (epic OpenHands/OpenHands#15746). Implements pre-cloud refactor P1-1.
Change
Collapse ACP onto the regular agent's action→observation model. The bridge now persists exactly two events per
tool_call_id:startedevent (the action) onToolCallStart, andcompleted/failedevent (the observation) on the first transition into a terminal status.Intermediate
ToolCallProgressframes are accumulated silently (so the terminal event still carries the final, complete output) but not emitted — this is the O(n²)→O(1) collapse._finalize_successful_turnflushes any tool call the server opened but never closed tocompleted, so everystartedhas a matching terminal observation (no orphaned "running" cards).Downstream merges: kept, not deleted
The original issue suggested deleting the three downstream
tool_call_iddedups. Those dedups serve a second purpose beyond papering over O(n²): they merge a tool call's lifecycle events into one card — exactly the analog of anObservationEventsuperseding itsActionEvent. With the source now emitting astarted+terminalpair (not N cumulative frames), deleting them would render two cards per call. So they are retained but become trivial O(1) two-event merges; their comments are updated to describe the new semantics:RemoteConversation._add_event_unsaferesume_transcript._terminal_tool_indices(The canvas
handle-event-for-uimerge + the should-render gate are handled in the paired agent-canvas PR.)Tests
TestACPToolCallProgressCollapse: started emits once; intermediate progress frames do not emit; full lifecycle emits exactly two events; the terminal event carries the final cumulative output; single-shot terminalToolCallStartemits once; redundant terminal frames don't double-emit; the finalize flush completes orphaned calls.resume_transcripttest asserting astarted→terminalpair renders only the terminal frame (terminal-event semantics).tests/sdk/agent/test_acp_agent.py,tests/sdk/agent/test_acp_dedup_and_truncation.py,tests/sdk/event/test_resume_transcript.py(342 passed);ruff check+ruff formatclean.Pairs with
agent-canvas PR (relaxes the should-render gate to render the running
startedcard): link added in a comment below.🤖 Generated with Claude Code
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:04c6dc0-pythonRun
All tags pushed for this build
About Multi-Architecture Support
04c6dc0-python) is a multi-arch manifest supporting both amd64 and arm6404c6dc0-python-amd64) are also available if needed