Repository navigation
Description
Problem
EventLog.append() calls _count_events_on_disk() on every append, which does a full FileStore.list() of the entire events directory in order to detect whether another process wrote new events while this process was waiting for the lock.
Because every append lists all N files in the directory, each append is O(N) and a full conversation accumulates to O(N²).
This is the remaining half of #3263: that PR (a "Partial fix" of #3134) eliminated the O(N²) deserialization on the read path via _event_cache. The full directory listing on the write path is uncached, and after the read-path fix it is now the largest remaining O(N) cost per step.
Note this one is fundamentally harder than #3263: a read cache is trivially always-valid because events are immutable once written, whereas the value checked here (the on-disk length) is mutable across processes, so there is no trivially-valid cache. That likely explains why it was left out of the read-path fix.
Location
openhands-sdk/openhands/sdk/conversation/event_store.py:143—_count_events_on_disk()called on everyappend()openhands-sdk/openhands/sdk/conversation/event_store.py:175—self._fs.list(self._dir)lists the whole directory
Evidence
Benchmark of N=2000 appends on LocalFileStore (script below). The control merely stubs _count_events_on_disk() to return the in-memory _length to isolate the cost — it is not a proposed fix, since it breaks cross-process sync.
| current (listdir each append) | listdir removed (control) | ||
|---|---|---|---|
| total append time | 7408 ms | 222 ms | 33× slower |
| append #1 | 320 µs | 108 µs | |
| append #2000 | 7266 µs | 115 µs | |
| first→last slowdown | 22.4× | 1.06× (flat) |
Per-append time grows linearly with N (i.e. O(N²) total):
append #500 → 1911 µs
append #1000 → 3587 µs (≈2×)
append #1500 → 5689 µs (≈3×)
append #1999 → 7265 µs (≈4×)
Remote backends (S3/GCS) are affected more severely: every append becomes an O(N) network list call.
Reproduction script
"""Measure EventLog.append() cost vs N (write-path O(N^2) check)."""
import tempfile
import time
from openhands.sdk.conversation.event_store import EventLog
from openhands.sdk.event.condenser import CondensationRequest
from openhands.sdk.io.local import LocalFileStore
def bench(n: int, patch_count: bool):
tmp = tempfile.mkdtemp(prefix="evbench_")
log = EventLog(LocalFileStore(tmp), dir_path="events")
if patch_count:
log._count_events_on_disk = lambda: log._length # type: ignore
durations = []
for _ in range(n):
t0 = time.perf_counter()
log.append(CondensationRequest(source="agent"))
durations.append(time.perf_counter() - t0)
return durations
def summarize(d, label):
n = len(d)
head = sum(d[:100]) / min(100, n)
tail = sum(d[-100:]) / min(100, n)
print(f"\n=== {label} (N={n}) ===")
print(f" total : {sum(d)*1000:8.1f} ms")
print(f" first-100 avg : {head*1e6:8.1f} us/append")
print(f" last-100 avg : {tail*1e6:8.1f} us/append")
print(f" slowdown : {tail/head:6.2f}x")
return sum(d)
if __name__ == "__main__":
N = 2000
c = summarize(bench(N, False), "CURRENT (listdir every append)")
f = summarize(bench(N, True), "CONTROL (in-memory length)")
print(f"\nspeedup: {c/f:.2f}x")Severity
High — largest remaining O(N²) on the write path after #3263; noticeable on long conversations (thousands of steps) and especially on remote storage backends.
Impact of fix
Append drops from O(N) to amortized O(1). The 2000-step case above goes from ~7.4s to ~0.2s.
Suggested fixes
_count_events_on_disk() exists to detect writes by other processes during lock wait, so any fix must preserve that cross-process correctness while removing the hot-path full listdir. A subtlety that blocks the obvious exists()-based O(1) probe: the event filename embeds the event id (event-{idx:05d}-{event_id}.json), so the next slot's exact path cannot be constructed without knowing another process's id, forcing a full directory scan. Options, roughly from least to most invasive:
- Directory mtime fast-path — under the lock, compare the events dir's
mtime(viaget_absolute_path()+os.stat) against a cached stamp; only do the full scan when it changed. O(1) on local, but leaksLocalFileStorespecifics intoEventLogand does not help object stores (no directory mtime). - Length-pointer / head marker — maintain a small deterministic file (e.g.
events/.length) updated under the lock; reads are O(1) on all backends including S3. Cost: one extra small write per append, a back-compat fallback for existing logs without the marker, and excluding it from the scan/count filters. (This does add a non-event file to the directory, so it may not fit the in-memory-only style of perf(sdk): cache deserialized events in EventLog to eliminate O(N²) per-step cost #3263.) - Prefix-scoped list — on remote backends, replace the full list with a list scoped to the
event-{_length:05d}-prefix. Helps S3/GCS but not local (os.listdirstill returns everything). - Rely on the single-writer guarantee —
conversation_leasealready guarantees a single writer per conversation, and the lock serializes appends within a process. If that guarantee is considered authoritative, the per-append cross-process sync may be reducible to an init-time scan plus a lazy rebuild on the existing stale-index path (_get_single_itemalready rebuilds onKeyError). This is the most invasive in terms of assumptions and is really a design-level question.
I have a working patch + benchmark for option 1 and can put together option 2; happy to open a PR once you have a preferred direction — didn't want to pick a storage-format decision on your behalf.
Related issues and PRs
- perf(sdk): cache deserialized events in EventLog to eliminate O(N²) per-step cost #3263 — read-path O(N²) cache fix (direct predecessor, a "Partial fix")
- perf: O(N²) total cost per conversation from full-history re-scan every step #3134 — O(N²) per-step rescan (parent)
- perf: SDK and agent-server performance and correctness issues from profiling investigation #3153 — profiling investigation tracking issue
- fix: add file-based locking to EventLog.append() #1614 — PR that introduced
append()locking +_count_events_on_disk()
Found via a write-path benchmark following up on #3263. openhands-sdk v1.29.2.
Activity
all-hands-bot commentedon Aug 3, 2026
[Automatic Post]: This issue has had no activity for 35 days (labels: enhancement). @enyst @neubig @xingyaoww, could you take a look when you have a chance and help figure out next steps?
Generated by OpenHands automation on behalf of the user.
all-hands-bot commentedon Aug 28, 2026
Proposed closure reason: duplicate.
This reports the same
EventLog.append()performance issue as #4676 — a full directory listing (_count_events_on_disk()) on every append, giving O(N²) on the write path. #4676 is the current ready-for-dev issue tracking this under the streaming epic #4671.Recommend closing as a duplicate of #4676. Please verify before closing.
This comment was generated by an AI agent (OpenHands) on behalf of the user.