Repository navigation
perf(sdk): make EventLog.append cost flat against conversation length - #4697
Conversation
EventLog.append counted every file in the events directory on each append to detect a second writer, so appending event N cost O(N) directory work while holding the lock that intake also wants. Replace the count with an O(1) probe of a sidecar marker whose name carries the event count. The exact count is still paid whenever the marker cannot prove the log is in sync, so multi-writer behavior is unchanged. Also stop LocalFileStore.delete from raising on a cache miss: a file written by another process was never cached locally, and deleting it logged a spurious ERROR on every cross-process marker handoff.
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
…leak - Shorten the marker comments and docstrings; type LENGTH_MARKER_PATTERN as Final[str]. - Collect the dynamic ClientAction_* classes that test_client_tools_persistence leaves behind. Registering the same client tool name twice creates two same-named classes that are reachable only through reference cycles, so they sit in Action.__subclasses__() until a cyclic collection runs and make the duplicate-class check fail in unrelated later tests. The leak predates this branch: test_client_tools_persistence.py plus test_fork.py already fail together on main. It stayed hidden in full runs because the old O(N) directory listing allocated enough garbage to trigger collection in time; appending without it does not.
|
🚦 CI is currently failing on this PR's latest commit. Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request This is an automated check - no AI was used to generate this comment. |
|
🚦 CI is currently failing on this PR's latest commit. Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request This is an automated check - no AI was used to generate this comment. |
1 similar comment
|
🚦 CI is currently failing on this PR's latest commit. Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request This is an automated check - no AI was used to generate this comment. |
|
🚦 CI is currently failing on this PR's latest commit. Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request This is an automated check - no AI was used to generate this comment. |
Endpoint auditContract: pinned release artifact
Actionable client-only calls (0)none Actionable server-only operations (18)
Documented non-divergences (13)Client calls intentionally absent from the filtered contract (11)
Reason: Operational Agent Server endpoints intentionally excluded from the filtered public release artifact.
Reason: Client-ahead API stacked on the pending Agent Server meta-profiles implementation.
Reason: Client-ahead API stacked on the pending Agent Server pre-flight LLM validation endpoint. Server operations covered by an exposed browser URL (2)
Reason: RemoteWorkspace.startWorkspaceSession exposes these authenticated URLs for browser iframe and file requests; they are not HttpClient method calls. |
|
@all-hands-bot fix the conflicts in this PR |
Co-authored-by: openhands <openhands@all-hands.dev>
|
Resolved the conflicts by merging the latest Pushed merge commit Validation:
Generated by OpenHands AI on behalf of the user. |
|
🤖 OpenHands is reviewing this PR. Head commit: This comment was posted by an AI agent (OpenHands). |
|
This comment was posted by an AI agent (OpenHands). |
HUMAN:
Small perf to make append in log events constant.
AGENT:
Why
EventLog.appendre-counted the whole events directory on every append to notice asecond writer, and it did so while holding the lock intake also waits on.
_count_events_on_disklists the directory and, onLocalFileStore, stats every entry,so appending event N costs O(N). Long conversations get progressively slower to write,
and the cost hides inside persistence rather than in anything that looks like "the agent".
Who the second writer actually is (the issue asks for this first): in this repository
there is exactly one writer per events directory.
ConversationStateowns the onlyEventLogthat appends to a conversation'sevents/;rerun_actionswrites to aseparate directory it creates itself, and the
tom_consultexecutor only reads otherconversations' logs. The guard still covers a second
EventLogopened on the samedirectory in the same process, which
test_event_log_concurrent_writes_serializeddoes deliberately. So this PR keeps the guard and makes it cheap rather than dropping it.
How the marker keeps this O(1)
Why delete the old marker instead of leaving it behind? Leftover markers would
accumulate in
events/forever, and the next fresh load/fork/resume(
_scan_and_build_index) lists that same directory — so it'd be 2x bigger,and the O(N) cost this PR removes just moves to a different call site instead
of disappearing. The delete+write pair is 2 tiny file ops per append (100k
total on a 50k-event log), and that flat cost is exactly the "After" number
in the benchmark table below — not overhead on top of it.
Summary
EventLog.appendnow answers "has anyone appended since we last did?" with a singleexists()probe of a sidecar marker whose name carries the event count. The exactcount is still paid whenever the marker cannot prove the log is in sync, so multi-writer
behavior is unchanged, never weaker.
FileStore.readis cached, so a secondprocess would keep serving its own stale value.
FileStore.existsalways hits the backend.two calls leaves no marker at all and every writer falls back to the exact count.
LocalFileStore.deleteno longer raises on a cache miss. A file written by another processwas never cached locally, and the swallowed
KeyErrorlogged a spuriousERRORon everycross-process marker handoff. Pre-existing, but this change is the first to hit it routinely.
scripts/event_sourcing_benchmarks/bench_append_scaling.py, which measures appendlatency against log length. It synthesizes its own events, so it needs no
--eval-dir.ClientAction_*classestest_client_tools_persistenceleavesbehind. See the note at the bottom: the leak predates this branch, but removing the
directory listing is what stops hiding it.
Issue Number
Fixes #4676
How to Test
1. The acceptance criterion: append cost is flat against log length
cd scripts/event_sourcing_benchmarks python bench_append_scaling.py --events 4000Median
EventLog.append()latency per 400-event bucket, same machine, 4000 events:At 4000 events an append goes from 31.5ms to 1.0ms. Short logs get faster too, because
even a 400-event directory was being listed and stat'd on every append.
2. Two OS processes appending to one event directory
Unit tests share a
FileStore(and its cache) inside one process, so they cannot exercisethe case the sync guard exists for. This script gives each process its own
LocalFileStore,then cold-loads the result in a third:
e2e_multiwriter.py
No lost or duplicated indices, no interleaving damage, and exactly one marker survives.
Run against the pre-fix code it also passes, so this is a parity check, not a new guarantee.
3. Tests
Four new tests in
tests/sdk/conversation/test_event_store.pycover the flat-costguarantee (append must not list the directory as the log grows), a second writer still
being picked up, a legacy log that has no marker, and the scan no longer warning about
sidecar files. One new test in
tests/sdk/io/test_filestore_cache.pycovers thedelete()cache miss.Type
Notes
existing
.eventlog.lock. Nothing in the repo enumerates that directory exceptEventLogitself, which already filters toevent-*.jsonwhen counting. The cold scannow skips dotfiles silently instead of logging
Unrecognized event file namefor them,which also silences the warning
.eventlog.lockhas always produced. One existing testthat counted files in the directory was updated to filter dotfiles rather than only
.lock.test_client_tools_persistenceregisters the same client tool name twice (create, then resume), and each spec builds a
new
ClientAction_*class. Both are reachable only through reference cycles, so they stayin
Action.__subclasses__()until a cyclic collection runs, and the duplicate-name checkin
_get_checked_concrete_subclassesthen fails in unrelated later tests — three forkand state-serialization tests, with
Duplicate class definition ... ClientAction_persist_navigate_to.The leak is pre-existing: on a clean
main, runningtests/sdk/conversation/local/test_client_tools_persistence.pytogether withtests/sdk/conversation/local/test_fork.pyalready fails. Full runs onmainhappened topass because the old O(N) directory listing allocated enough garbage to trigger a
collection in time; appending without it does not, which is how this PR surfaced it.
Confirmed both directions: this branch with
gc.set_threshold(100, 5, 5)is green withoutthe fixture, and
mainwith the fixture fixes the two-file failure. The fix is a teardowngc.collect()plusclear_subclass_cache()in that test module, so the leak stays localregardless of allocation patterns.
tests/sdk/andtests/agent_server/run in a single pytest processproduce 17 failures (
ValueError: Local classes not supported! test_execute_tool.ContextAwareTool).This reproduces identically on a clean
mainfrom justtests/sdk/conversation/local/test_execute_tool.pyplustests/agent_server/test_openapi_discriminator.py, and is unrelated to this change.Both suites pass when run separately, as CI runs them.
🐳 Agent Server images for this PR — GHCR package, pull/run commands, and all pushed tags (click to expand)
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimnikolaik/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:99975b6-pythonRun
All tags pushed for this build
About Multi-Architecture Support
99975b6-python) is a multi-arch manifest supporting both amd64 and arm6499975b6-python-amd64) are also available if needed