Skip to content

[Feature]: Reduce per-step CPU and terminal latency in the agent loop #6365

Closed as not planned

Description

@analisaperlengkapan

Is there an existing feature request for this?

  • I have searched existing issues and feature requests, and this is not a duplicate.

Problem or Use Case

The agent loop has three avoidable per-step costs that show up as latency on every tool call and as CPU burn on every step. Measured on main (openhands-sdk 1.59.0) in this container with a scripted LLM, so the numbers isolate SDK work:

  1. Terminal tool: a fixed time.sleep(0.1) after every command. TmuxTerminal.clear_screen() (openhands-tools/openhands/tools/terminal/terminal/tmux_terminal.py:355) sends clear then sleeps 100 ms unconditionally, and TerminalSession._ready_for_next_command() (.../terminal/terminal_session.py:430-433) calls it after every command. A warm echo costs 148 ms, of which 91 ms (62%) is that sleep (first call 400 ms). Dropping the sleep to 0.01 s takes the action to 56.6 ms. Raw subprocess.run(["echo"]) is 1.0 ms.

  2. Per-step token recount of the entire history. get_total_token_count(view.events, agent_llm) is called every step from LLMSummarizingCondenser.condensation_requirement() (openhands-sdk/openhands/sdk/context/condenser/llm_summarizing_condenser.py:163) whenever the condenser has a token cap. It re-formats and re-tokenises the whole view: 27-37 ms per step at 240 messages, growing linearly. In a 120-step run with a real context window this is 1018 ms of 1867 ms CPU (55%); the count fires 125 times.

  3. Event log: 2 fsyncs + 2 renames per event. EventLog.append() writes the event via LocalFileStore.write() -> atomic_write_text() (.../sdk/utils/files.py:21-39, one fsync + os.replace) and rewrites the length marker (.../sdk/conversation/event_store.py:320-328, delete + write + rename). That is 2.44-2.69 ms per event; in the 120-step run, 244 appends cost 892 ms of 1511 ms CPU (59%).

Smaller, also measured: LLM.format_messages_for_llm does an unconditional copy.deepcopy of the whole message list (.../sdk/llm/llm.py:3045) = 9.7 ms per call, 15% of CPU.

Desired Behavior

  1. clear_screen() should not sleep a fixed 100 ms. The prompt is already detectable (read_screen() + CMD_OUTPUT_PS1_END); impl.py:255 already polls for it on the interrupt path. Poll for the prompt (or use tmux clear-history synchronously) with a bounded fallback instead of a blind sleep.

  2. Token counting should be incremental. litellm's message count is exactly superadditive by a constant c (count(AuB) = count(A) + count(B) - c; measured c=3 without tools and c=163/168 with tools, constant at all 241 split points for gpt-4o, gpt-4o-mini, claude-3-5-sonnet, gpt-3.5-turbo). Caching per-message counts plus c makes a step that appends one message tokenise only that message: exact (max error 0) and ~50-90x faster on the tokenisation step (507 ms -> 11 ms over 240 growing prefixes here; 57-91x on larger corpora).

  3. Event persistence should batch fsyncs (one per step, or a background flusher) while keeping the crash-durability contract explicit.

  4. format_messages_for_llm should skip the deepcopy when prompt caching is inactive (the copy exists only so _apply_prompt_caching can mutate flags).

Acceptance Criteria

  • A warm single-command terminal action drops from ~148 ms to < ~70 ms on this container, with no change in command output or exit code.
  • A capped-condenser run's per-step token count is exact vs the current get_total_token_count and skips re-tokenising the unchanged prefix.
  • A 120-step run with a real context window shows a measurable CPU reduction in the token-count and event-persist paths (target: > 30% of the current SDK CPU).
  • Event durability semantics are documented (what survives a crash) and unchanged or explicitly re-specified.
  • Existing tests pass; new tests cover prompt-polling fallback and incremental-count equality.

Alternatives Considered

  • Porting the tokenizer or the diff to Rust. Rejected: tiktoken-rs matches litellm's output exactly but has no speedup (Rust 24.2 ms vs litellm 18.4 ms vs python tiktoken 26.0 ms) - the cost is litellm's Python message walk, not the BPE. similar is 4.3-5.9x faster than difflib but not output-identical (74-85 of 2000 random trials differ, and disabling autojunk does not close it), which is a correctness bug for user-visible diff text.
  • Reducing time.sleep(0.1) to a smaller fixed value: works but keeps a magic constant and is fragile on slow panes; polling is the correct fix.
  • Lazifying litellm (import cost ~1.7 s / 114 MB of the 3.5 s / 257 MB import openhands.sdk) is a separate, multi-file refactor (43 top-level importers); out of scope here, its own issue.

Priority / Severity

High - Significant impact on productivity

Estimated Scope

Medium - New feature with moderate complexity

Feature Area

  • Agent API / Core functionality
  • Tools / Tool system
  • Skills / Plugins
  • Agent Server
  • Workspace management
  • Configuration / Settings
  • Examples / Templates
  • Documentation
  • Testing / Development tools
  • Performance / Optimization
  • Integrations (GitHub, APIs, etc.)
  • Other

Technical Implementation Ideas (Optional)

  • clear_screen: replace time.sleep(0.1) with a bounded poll on read_screen() ending in CMD_OUTPUT_PS1_END (mirror the interrupt path in impl.py:255), e.g. poll every 0.02 s up to ~0.5 s, then proceed.
  • Token count: an IncrementalTokenCounter keyed by (model, tool-schema) holding (n_messages, sum_of_singleton_counts, c). On a view that only appends, add the new messages' counts and return sum - (n - 1) * c. Invalidate on condensation or tool-set change. Calibrate c once from a 2-way split.
  • Event log: keep the atomic per-event write for correctness, but move the fsync to a per-step flush (or make it opt-in), so a step does one fsync instead of 2 per event.
  • format_messages_for_llm: if not self.is_caching_prompt_active(): return list(messages) instead of copy.deepcopy(messages).

Additional Context

(1) Terminal: the fixed 100 ms sleep

A warm terminal action spends 100 ms in time.sleep(0.1) inside
TmuxTerminal.clear_screen(), called after every command:

import subprocess, tempfile, time
import openhands.tools.terminal.terminal.tmux_terminal as tt
from openhands.tools.terminal.definition import TerminalAction
import openhands.tools.terminal.impl as term_impl

spawns, sleeps, real_sleep = [], [], time.sleep
_orig = subprocess.Popen.__init__
subprocess.Popen.__init__ = lambda self, a, *x, **k: (
    spawns.append(a[0]), _orig(self, a, *x, **k))[-1]
tt.time.sleep = lambda s: (sleeps.append(s), real_sleep(s))[-1]

ex = term_impl.TerminalExecutor(working_dir=tempfile.mkdtemp())
ex(TerminalAction(command="echo warmup"))          # warm the tmux pane
spawns.clear(); sleeps.clear()
t0 = time.perf_counter(); ex(TerminalAction(command="echo hello"))
print(f"{(time.perf_counter()-t0)*1000:.0f} ms, {len(spawns)} spawns, sleeps={sleeps}")

Observed: 148 ms, 11 spawns, sleeps=[0.1] (first call 400 ms).
With that one sleep set to 0.01 s: 57 ms. Raw
subprocess.run(["echo"]) is 1.0 ms.

(2) Token counting fires every step, but only with a cap

TestLLM reports no context window, so the default condenser has no cap and
never counts. Set one to reproduce a real model:

import json, resource, tempfile
from openhands.sdk import Agent, Conversation, Tool
from openhands.sdk.context.condenser import default_condenser
from openhands.sdk.llm import Message, TextContent, MessageToolCall
from openhands.sdk.testing import TestLLM
from openhands.tools.terminal.definition import TerminalTool
import openhands.sdk.context.condenser.utils as cu
import openhands.sdk.context.condenser.llm_summarizing_condenser as lsc

calls = {"n": 0, "s": 0.0}
_orig = cu.get_total_token_count
def counted(events, llm):
    t = time.perf_counter()
    try: return _orig(events, llm)
    finally: calls["n"] += 1; calls["s"] += time.perf_counter() - t
cu.get_total_token_count = counted
lsc.get_total_token_count = counted      # the condenser imported it by name

def scripted(n):
    out = [Message(role="assistant", content=[TextContent(text=f"step {i}: " + "work " * 60)],
                   tool_calls=[MessageToolCall(id=f"c{i}", name="terminal",
                       arguments=json.dumps({"command": "true"}), origin="completion")])
           for i in range(n)]
    out.append(Message(role="assistant", content=[TextContent(text="done")],
        tool_calls=[MessageToolCall(id="fin", name="finish",
            arguments=json.dumps({"message": "done"}), origin="completion")]))
    return out

def run(cap):
    llm = TestLLM.from_messages(scripted(120))
    llm.max_input_tokens = cap
    agent = Agent(llm=llm, tools=[Tool(name=TerminalTool.name)], condenser=default_condenser(llm))
    conv = Conversation(agent=agent, workspace=tempfile.mkdtemp(), visualizer=None)
    conv.send_message("go")
    c0 = resource.getrusage(resource.RUSAGE_SELF); calls["n"] = 0; calls["s"] = 0.0
    conv.run()
    c1 = resource.getrusage(resource.RUSAGE_SELF)
    cpu = (c1.ru_utime + c1.ru_stime - c0.ru_utime - c0.ru_stime) * 1000
    print(f"cap={cap}: cpu {cpu:.0f} ms, count calls {calls['n']} = {calls['s']*1000:.0f} ms")

run(None)
run(128000)

Observed:

cap=None:   cpu  848 ms, count calls 0   =    0 ms
cap=128000: cpu 1868 ms, count calls 125 = 1005 ms (54% of cpu)

(3) The additivity constant and the exact incremental counter

litellm's message count is exactly superadditive by a constant c
(count(A u B) = count(A) + count(B) - c), so a growing history can be counted
by tokenising only the new message:

import json
from litellm.litellm_core_utils.token_counter import token_counter
from openhands.sdk.llm import LLM, Message, MessageToolCall, TextContent

llm = LLM(model="gpt-4o-mini", api_key="dummy")
msgs = [Message(role="system", content=[TextContent(text="sys")]),
        Message(role="user", content=[TextContent(text="hello")]),
        Message(role="assistant", content=[TextContent(text="calling")],
                tool_calls=[MessageToolCall(id="1", name="terminal",
                    arguments=json.dumps({"command": "ls"}), origin="completion")]),
        Message(role="user", content=[TextContent(text="go on")])]
fm = llm.format_messages_for_llm(msgs)
M = lambda ms: token_counter(model="gpt-4o-mini", messages=ms)

whole = M(fm)
cs = sorted({M(fm[:k]) + M(fm[k:]) - whole for k in range(1, len(fm))})
print("split constants c =", cs)      # one value => additive by c

history = [Message(role="assistant", content=[TextContent(text=f"step {i}: " + "work " * 60)],
                   tool_calls=[MessageToolCall(id=f"c{i}", name="terminal",
                       arguments=json.dumps({"command": "true"}), origin="completion")])
           for i in range(240)]
fm_all = llm.format_messages_for_llm(history)

c = M(fm_all[:1]) + M(fm_all[1:]) - M(fm_all)     # calibrate once
s, n = M(fm_all[:1]), 1                            # cached sum of single-message counts
full_t = inc_t = 0.0; mismatches = 0
for i in range(1, len(fm_all) + 1):
    t = time.perf_counter(); exact = M(fm_all[:i]); full_t += time.perf_counter() - t
    t = time.perf_counter()
    if i > n:
        s += M(fm_all[i - 1: i]); n += 1
    got = s - (n - 1) * c
    inc_t += time.perf_counter() - t
    mismatches += (exact != got)
print(f"mismatches={mismatches}  full {full_t*1000:.0f} ms -> incremental {inc_t*1000:.0f} ms ({full_t/inc_t:.0f}x)")

Observed:

split constants c = [3]
mismatches=0  full 507 ms -> incremental 11 ms (48x)

c is stable at every split point and per model (c=3 without tools,
c=163/168 with tools for gpt-4o, gpt-4o-mini, claude-3-5-sonnet,
gpt-3.5-turbo). The count is exact (mismatches=0) at every prefix. On larger
corpora the same change measures 57-91x.

(4) Event log: 2 fsyncs + 2 renames per event

EventLog.append() -> LocalFileStore.write() -> atomic_write_text()
(openhands-sdk/openhands/sdk/utils/files.py:21-39: one fsync + one
os.replace) plus a marker rewrite (event_store.py:320-328: delete + write +
rename). Appending 102 / 402 / 1602 events takes 249 / 1023 / 4310 ms =
2.4-2.7 ms per event; in the 120-step run above, 244 appends are ~59% of CPU.


OpenHands AI triage

The following comments and acceptance criteria were added by the OpenHands AI agent.

Triage

All four cited hot paths were verified against current main: (1) TmuxTerminal.clear_screen() sleeps an unconditional 100 ms and TerminalSession._ready_for_next_command() invokes it after every command, while the interrupt path in openhands-tools/openhands/tools/terminal/impl.py already establishes the repository's pattern for waiting on the prompt (read_screen() polling for CMD_OUTPUT_PS1_END with a bounded wait); (2) LLMSummarizingCondenser.get_condensation_reasons() calls get_total_token_count(view.events, agent_llm) on every step whenever an effective token cap exists, with no caching in condenser/utils.py; (3) EventLog.append() performs a fsync + os.replace write plus a marker delete/write/rename per event; (4) LLM._begin_chat_messages() deepcopies the whole message list before the prompt-caching flag pass. The performance problem is real and measured, but the evidence is the reporter's synthetic benchmark with a scripted LLM rather than a user report, support ticket, or production impact, so the issue is prioritized low against the backlog.

Scope is limited to the four per-step costs named above. Explicit non-goals: no change to litellm import behavior or packaging; no switch to a Rust tokenizer or a different diff library (the reporter already showed neither is output-identical or faster in the relevant way); no change to the agent loop's semantics, tool definitions, or public event-log API; no behavior change for terminal command output or exit codes.

Acceptance Criteria

  • A warm single-command terminal action on a healthy tmux pane completes measurably faster than on current main with no unconditional fixed sleep on the steady-state path, and command output and exit code are unchanged for a simple command.
  • When the pane does not reach the expected prompt within the bounded wait, the terminal action proceeds via the documented fallback instead of hanging, and this behavior is covered by a test.
  • Per-step token counts from the condenser's token-limit check are exactly equal (integer-for-integer) to the current full get_total_token_count recount for identical event sequences and LLM configuration, covered by a test including messages with tool calls.
  • When a step does not change existing messages (view only appends), the token-limit check does not re-tokenize the unchanged prefix; this is observable in a test (e.g., via counting/tokenization spy or timing) and the cached count is invalidated after condensation and when the tool set changes.
  • Appending an event performs at most one fsync on the steady-state path (verified by observation or test), the number of atomic renames per append does not increase versus current main, and the crash-durability semantics (what survives a crash at each point) are documented in the persistence docs.
  • Each event remains individually atomic: a partially written event file is never observed as a complete event by a reader after any single-append interruption point.
  • With prompt caching inactive, message formatting produces output identical to current main and callers' input Message objects are not mutated, covered by a test; with prompt caching active, behavior is unchanged.
  • Existing test suites for the terminal tool, condenser, event persistence, and LLM formatting pass; new tests cover the prompt-wait fallback and incremental-count equality.

Activity

  1. added
    ready-for-dev
    on Nov 2, 2026
  2. all-hands-bot commented on Nov 2, 2026

    @all-hands-bot
    Collaborator

    #6365 is a broad, multi-part per-step performance feature request bundling four distinct optimizations (terminal clear_screen 100 ms sleep, per-step full-history token recount, per-event fsync/rename in the event log, and an unconditional deepcopy in format_messages_for_llm). No existing issue is an exact or near-exact duplicate of the whole report. However, sub-item 3 (batching/coalescing event-log fsyncs while preserving durability) substantially overlaps with open issue #5402, whose own root-cause analysis describes the same double-fsync-per-event write path and which already has an in-flight PR (#5437). Sub-item 1 (terminal latency) is in the same neighborhood as open #5533 (tmux fixed-sleep readiness) and closed #5714 (0.5 s terminal poll). Because the issue spans several workstreams and none of the existing issues is the same report, this is best treated as overlapping-scope rather than a duplicate; the author would benefit from being pointed at #5402 for the persistence item and #5533 for the terminal item so fixes don't fragment.

    Found 3 possible duplicate issues:

    1. #5402 — Avoid synchronous durable persistence blocking concurrent conversations
    2. #5533 — Tmux can accept commands before slow Bash startup completes
    3. #5714 — [Bug]: Terminal returns short commands only at the next 0.5 s poll

    These may not be exact duplicates, but the scope appears to overlap enough that keeping discussion in one place may be more useful.

    This comment was created by an AI assistant (OpenHands) on behalf of the repository maintainer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementready-for-dev

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions