From 771eec81955352e67466ffeac4478e0daff17a26 Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Fri, 28 Aug 2026 10:29:10 +0200 Subject: [PATCH 1/2] perf(sdk): make EventLog.append cost flat against conversation length 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. --- .../openhands/sdk/conversation/event_store.py | 53 ++++++- openhands-sdk/openhands/sdk/io/local.py | 4 +- scripts/event_sourcing_benchmarks/README.md | 3 +- .../bench_append_scaling.py | 142 ++++++++++++++++++ tests/sdk/conversation/test_event_store.py | 83 +++++++++- tests/sdk/io/test_filestore_cache.py | 26 ++++ 6 files changed, 303 insertions(+), 8 deletions(-) create mode 100644 scripts/event_sourcing_benchmarks/bench_append_scaling.py diff --git a/openhands-sdk/openhands/sdk/conversation/event_store.py b/openhands-sdk/openhands/sdk/conversation/event_store.py index 76a6df1c2a7..db9d2f7b676 100644 --- a/openhands-sdk/openhands/sdk/conversation/event_store.py +++ b/openhands-sdk/openhands/sdk/conversation/event_store.py @@ -22,6 +22,13 @@ LOCK_FILE_NAME = ".eventlog.lock" LOCK_TIMEOUT_SECONDS = 30 +# Sidecar marker whose *name* carries the event count the log had when it was +# last written. Detecting another writer by reading a fixed-name counter file +# would not work: ``FileStore.read`` is cached and a second process would keep +# serving its own stale value. ``FileStore.exists`` always hits the backend, so +# putting the count in the name keeps the check O(1) and cache-free. +LENGTH_MARKER_PATTERN = ".eventlog-len-{length}.marker" + # ROOT_PARENT_ID now lives in event.types (single source of truth); it is used # below in _effective_parent_id and re-exported here so existing # ``from event_store import ROOT_PARENT_ID`` importers keep working. @@ -193,10 +200,13 @@ def append(self, event: Event) -> None: try: with self._fs.lock(self._lock_path, timeout=LOCK_TIMEOUT_SECONDS): - # Sync with disk in case another process wrote while we waited - disk_length = self._count_events_on_disk() - if disk_length > self._length: - self._sync_from_disk(disk_length) + # Sync with disk in case another writer appended while we waited. + # The marker answers "nobody has appended since we last did" in + # one stat; only when it cannot, pay for the full listing. + if not self._marker_matches_length(): + disk_length = self._count_events_on_disk() + if disk_length > self._length: + self._sync_from_disk(disk_length) if evt_id in self._id_to_idx: existing_idx = self._id_to_idx[evt_id] @@ -224,7 +234,9 @@ def append(self, event: Event) -> None: self._idx_to_id[self._length] = evt_id self._id_to_idx[evt_id] = self._length self._event_cache[self._length] = event + previous_length = self._length self._length += 1 + self._advance_length_marker(previous_length) except TimeoutError: logger.error( f"Failed to acquire EventLog lock within {LOCK_TIMEOUT_SECONDS}s " @@ -232,6 +244,36 @@ def append(self, event: Event) -> None: ) raise + def _marker_path(self, length: int) -> str: + return f"{self._dir}/{LENGTH_MARKER_PATTERN.format(length=length)}" + + def _marker_matches_length(self) -> bool: + """Whether the marker proves no one has appended since we last did. + + ``False`` is not proof of divergence -- a log written before this + marker existed has none either, and so does one whose writer died + mid-update. Callers must fall back to the exact count, which keeps + this an optimization rather than a change of behavior. + """ + try: + return bool(self._fs.exists(self._marker_path(self._length))) + except Exception as e: + logger.warning("Error reading event count marker in %s: %s", self._dir, e) + return False + + def _advance_length_marker(self, previous_length: int) -> None: + """Move the marker from ``previous_length`` to the current length. + + The old marker goes first on purpose: interrupted between the two + calls, the log is left with no marker at all, which costs every writer + one full listing instead of letting a stale marker claim to be current. + """ + try: + self._fs.delete(self._marker_path(previous_length)) + self._fs.write(self._marker_path(self._length), "") + except Exception as e: + logger.warning("Error updating event count marker in %s: %s", self._dir, e) + def _count_events_on_disk(self) -> int: """Count event files on disk.""" try: @@ -296,6 +338,9 @@ def _scan_and_build_index(self) -> int: idx = int(m.group("idx")) evt_id = m.group("event_id") by_idx[idx] = evt_id + elif name.startswith("."): + # Our own sidecars (lock file, count marker), not event files. + continue else: logger.warning(f"Unrecognized event file name: {name}") diff --git a/openhands-sdk/openhands/sdk/io/local.py b/openhands-sdk/openhands/sdk/io/local.py index 36179470ea3..b31d2700685 100644 --- a/openhands-sdk/openhands/sdk/io/local.py +++ b/openhands-sdk/openhands/sdk/io/local.py @@ -110,7 +110,9 @@ def delete(self, path: str) -> None: if os.path.isfile(full_path): os.remove(full_path) - del self.cache[full_path] + # Tolerate a cache miss: a file written by another process was + # never cached here, and deleting it is not an error. + self.cache.pop(full_path, None) logger.debug(f"Removed local file: {full_path}") elif os.path.isdir(full_path): shutil.rmtree(full_path) diff --git a/scripts/event_sourcing_benchmarks/README.md b/scripts/event_sourcing_benchmarks/README.md index 2ec8f4d7ec3..ce1e523c1b2 100644 --- a/scripts/event_sourcing_benchmarks/README.md +++ b/scripts/event_sourcing_benchmarks/README.md @@ -31,13 +31,14 @@ After extraction, pass the inner run directory as `--eval-dir`. It should contai ## Scripts -All scripts accept `--eval-dir ` pointing to the extracted evaluation run directory. +All scripts accept `--eval-dir ` pointing to the extracted evaluation run directory, except `bench_append_scaling.py`, which synthesizes its own events and needs no data. | Script | Metrics | Usage | |---|---|---| | `bench_persist_latency.py` | Persist latency per event / action cycle | `python bench_persist_latency.py --eval-dir ` | | `bench_replay_and_recovery.py` | Replay time vs. log size, time-to-recover | `python bench_replay_and_recovery.py --eval-dir ` | | `bench_storage_growth.py` | Storage growth and composition | `python bench_storage_growth.py --eval-dir ` | +| `bench_append_scaling.py` | `EventLog.append` latency vs. log length | `python bench_append_scaling.py` | --- diff --git a/scripts/event_sourcing_benchmarks/bench_append_scaling.py b/scripts/event_sourcing_benchmarks/bench_append_scaling.py new file mode 100644 index 00000000000..53da67fd84a --- /dev/null +++ b/scripts/event_sourcing_benchmarks/bench_append_scaling.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +""" +Benchmark: EventLog.append latency vs. conversation length. + +`bench_persist_latency.py` measures the lock-and-write path in isolation, which +is flat by construction. This script measures the whole of `EventLog.append()`, +including the multi-writer disk sync it performs while holding the lock, so any +per-append cost that scales with the number of events already in the log shows +up here. + +Self-contained: it synthesizes events instead of replaying an evaluation run, +so it needs no --eval-dir and runs in seconds. + +Usage: + python bench_append_scaling.py [--events 4000] [--buckets 10] +""" + +import argparse +import gc +import json +import shutil +import statistics +import tempfile +import time + +from openhands.sdk.conversation.event_store import EventLog +from openhands.sdk.event.llm_convertible import MessageEvent +from openhands.sdk.io import LocalFileStore +from openhands.sdk.llm import Message, TextContent + + +# Median persisted event in the SWE-Bench traces is ~1.4KB (see README). +PAYLOAD_BYTES = 1_400 + + +def make_event(idx: int) -> MessageEvent: + return MessageEvent( + id=f"{idx:08x}-0000-0000-0000-000000000000", + llm_message=Message( + role="user", content=[TextContent(text="x" * PAYLOAD_BYTES)] + ), + source="user", + ) + + +def measure_append_latencies(n_events: int) -> list[float]: + """Append `n_events` through the real EventLog path, timing each append.""" + tmpdir = tempfile.mkdtemp(prefix="bench_append_") + try: + fs = LocalFileStore(tmpdir, cache_limit_size=n_events + 100) + log = EventLog(fs) + + latencies: list[float] = [] + for i in range(n_events): + event = make_event(i) + + gc.disable() + t0 = time.perf_counter() + log.append(event) + t1 = time.perf_counter() + gc.enable() + + latencies.append((t1 - t0) * 1000) + return latencies + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +def main(): + import logging + + logging.getLogger("openhands").setLevel(logging.ERROR) + + parser = argparse.ArgumentParser( + description="Benchmark EventLog.append latency vs. conversation length" + ) + parser.add_argument( + "--events", + type=int, + default=4000, + help="Number of events to append (default: 4000)", + ) + parser.add_argument( + "--buckets", + type=int, + default=10, + help="Number of equal-width buckets to report (default: 10)", + ) + parser.add_argument( + "--output", + default="bench_append_scaling_results.json", + help="Output JSON file path", + ) + args = parser.parse_args() + + print(f"Appending {args.events} events through EventLog.append()...\n") + latencies = measure_append_latencies(args.events) + + print(f"{'=' * 62}") + print("RESULTS: Append Latency vs. Log Length") + print(f"{'=' * 62}") + print(f"\n {'Log length at append':<24} {'N':>6} {'Median':>11} {'Mean':>11}") + print(f" {'-' * 56}") + + width = max(1, args.events // args.buckets) + buckets: list[dict] = [] + for start in range(0, args.events, width): + chunk = latencies[start : start + width] + if not chunk: + continue + bucket = { + "start": start, + "end": start + len(chunk), + "n": len(chunk), + "median_ms": statistics.median(chunk), + "mean_ms": statistics.mean(chunk), + } + buckets.append(bucket) + label = f"{bucket['start']:,} - {bucket['end']:,}" + print( + f" {label:<24} {bucket['n']:>6}" + f" {bucket['median_ms']:>9.3f}ms {bucket['mean_ms']:>9.3f}ms" + ) + + first, last = buckets[0]["median_ms"], buckets[-1]["median_ms"] + growth = last / first if first else float("inf") + print(f" {'-' * 56}") + print(f"\n First bucket median: {first:.3f}ms") + print(f" Last bucket median: {last:.3f}ms") + print(f" Growth factor: {growth:.2f}x (1.00x == flat)") + + with open(args.output, "w") as f: + json.dump( + {"n_events": args.events, "buckets": buckets, "growth_factor": growth}, + f, + indent=2, + ) + print(f"\nRaw data saved to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/tests/sdk/conversation/test_event_store.py b/tests/sdk/conversation/test_event_store.py index eb51ae875df..1625738cc5e 100644 --- a/tests/sdk/conversation/test_event_store.py +++ b/tests/sdk/conversation/test_event_store.py @@ -5,7 +5,7 @@ import pytest -from openhands.sdk.conversation.event_store import EventLog +from openhands.sdk.conversation.event_store import LOCK_FILE_NAME, EventLog from openhands.sdk.conversation.persistence_const import ( EVENT_FILE_PATTERN, EVENT_NAME_RE, @@ -14,6 +14,7 @@ from openhands.sdk.event.llm_convertible import MessageEvent from openhands.sdk.io.memory import InMemoryFileStore from openhands.sdk.llm import Message, TextContent +from openhands.sdk.utils.path import posix_path_name def create_test_event(event_id: str, content: str = "Test content") -> MessageEvent: @@ -413,7 +414,8 @@ def test_event_log_concurrent_writes_serialized(): assert log1._length == 1 assert log2._length == 2 - files = [f for f in fs.list("events") if not f.endswith(".lock")] + # Sidecars (lock file, event-count marker) are dotfiles, not events. + files = [f for f in fs.list("events") if not posix_path_name(f).startswith(".")] assert len(files) == 2 @@ -544,3 +546,80 @@ def test_event_log_cold_reload_past_100k_events(): # Appending after reload keeps length accounting consistent. log.append(create_test_event("after-reload", "after")) assert len(log) == n + 1 + + +def test_append_does_not_scan_the_directory_as_the_log_grows(): + """Append cost must not grow with conversation length (issue #4676). + + The multi-writer sync used to count every file in the events directory on + every append, so appending event N cost O(N) directory work while holding + the lock. Listing calls are the proxy for that cost. + """ + fs = InMemoryFileStore() + log = EventLog(fs) + + listings: list[str] = [] + original_list = fs.list + + def counting_list(path: str) -> list[str]: + listings.append(path) + return original_list(path) + + fs.list = counting_list # type: ignore[method-assign] + + for i in range(50): + log.append(create_test_event(f"{i:08x}-0000-0000-0000-000000000000")) + + # The first append has no marker to go on and pays for one listing; every + # later append is answered by the marker alone. + assert len(listings) <= 1, f"append listed the events dir {len(listings)} times" + assert len(log) == 50 + + +def test_append_still_syncs_when_another_writer_appended(): + """A second writer's events are still picked up, marker or not.""" + fs = InMemoryFileStore() + log1 = EventLog(fs) + log2 = EventLog(fs) + + log1.append(create_test_event("00000000-0000-0000-0000-000000000001")) + log1.append(create_test_event("00000000-0000-0000-0000-000000000002")) + + # log2 opened at length 0 and never saw those appends; the marker no longer + # names its length, so it falls back to counting and lands after them. + log2.append(create_test_event("00000000-0000-0000-0000-000000000003")) + + assert log2._length == 3 + assert log2.get_index("00000000-0000-0000-0000-000000000003") == 2 + + +def test_append_syncs_when_marker_is_missing(): + """A log written before the marker existed keeps the exact-count path.""" + fs = InMemoryFileStore() + log = EventLog(fs) + log.append(create_test_event("00000000-0000-0000-0000-000000000001")) + + # Simulate a legacy on-disk log: events present, no marker. + for path in list(fs.files.keys()): + if posix_path_name(path).startswith("."): + del fs.files[path] + + reopened = EventLog(fs) + reopened.append(create_test_event("00000000-0000-0000-0000-000000000002")) + assert len(reopened) == 2 + + # And the marker is re-established for the appends that follow. + assert fs.exists(reopened._marker_path(2)) + + +def test_scan_does_not_warn_about_sidecar_files(caplog): + """The lock file and count marker are ours; they are not malformed events.""" + fs = InMemoryFileStore() + log = EventLog(fs) + log.append(create_test_event("00000000-0000-0000-0000-000000000001")) + fs.write(f"{EVENTS_DIR}/{LOCK_FILE_NAME}", "") + + with caplog.at_level("WARNING"): + EventLog(fs) + + assert "Unrecognized event file name" not in caplog.text diff --git a/tests/sdk/io/test_filestore_cache.py b/tests/sdk/io/test_filestore_cache.py index c08c9f7ee7e..724758855bd 100644 --- a/tests/sdk/io/test_filestore_cache.py +++ b/tests/sdk/io/test_filestore_cache.py @@ -7,6 +7,8 @@ 4. Handling of large numbers of events without OOM """ +import logging +import os import tempfile import time @@ -146,6 +148,30 @@ def test_cache_invalidation_on_delete(): assert full_path not in store.cache +def test_delete_uncached_file_succeeds_quietly(caplog): + """Deleting a file this store never cached is not an error. + + Files written by another process are absent from this store's cache; + evicting them must not raise (and be swallowed into an ERROR log). + """ + with tempfile.TemporaryDirectory() as temp_dir: + store = LocalFileStore(temp_dir, cache_limit_size=10) + + # Written behind the store's back, as another process would. + outside = os.path.join(temp_dir, "outside.txt") + with open(outside, "w") as f: + f.write("content") + + full_path = store.get_full_path("outside.txt") + assert full_path not in store.cache + + with caplog.at_level(logging.ERROR): + store.delete("outside.txt") + + assert not os.path.exists(outside) + assert "Error clearing local file store" not in caplog.text + + def test_cache_directory_deletion(): """Test that cache is cleared when directory is deleted.""" with tempfile.TemporaryDirectory() as temp_dir: From 8bf361d673ceea86c78bafdb004e9b61a4516e5c Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Fri, 28 Aug 2026 12:25:26 +0200 Subject: [PATCH 2/2] Address review: trim comments, Final[str], fix latent class-registry 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. --- .../openhands/sdk/conversation/event_store.py | 26 +++++++------------ .../local/test_client_tools_persistence.py | 20 ++++++++++++++ 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/openhands-sdk/openhands/sdk/conversation/event_store.py b/openhands-sdk/openhands/sdk/conversation/event_store.py index db9d2f7b676..68a9ea118b6 100644 --- a/openhands-sdk/openhands/sdk/conversation/event_store.py +++ b/openhands-sdk/openhands/sdk/conversation/event_store.py @@ -2,7 +2,7 @@ import operator from collections.abc import Callable, Iterator from contextlib import AbstractContextManager, nullcontext -from typing import SupportsIndex, overload +from typing import Final, SupportsIndex, overload from openhands.sdk.conversation.events_list_base import EventsListBase from openhands.sdk.conversation.persistence_const import ( @@ -22,12 +22,9 @@ LOCK_FILE_NAME = ".eventlog.lock" LOCK_TIMEOUT_SECONDS = 30 -# Sidecar marker whose *name* carries the event count the log had when it was -# last written. Detecting another writer by reading a fixed-name counter file -# would not work: ``FileStore.read`` is cached and a second process would keep -# serving its own stale value. ``FileStore.exists`` always hits the backend, so -# putting the count in the name keeps the check O(1) and cache-free. -LENGTH_MARKER_PATTERN = ".eventlog-len-{length}.marker" +# Sidecar marker naming the log's event count, so a writer can check it with one +# ``exists()``. The count lives in the name because ``FileStore.read`` is cached. +LENGTH_MARKER_PATTERN: Final[str] = ".eventlog-len-{length}.marker" # ROOT_PARENT_ID now lives in event.types (single source of truth); it is used # below in _effective_parent_id and re-exported here so existing @@ -200,9 +197,7 @@ def append(self, event: Event) -> None: try: with self._fs.lock(self._lock_path, timeout=LOCK_TIMEOUT_SECONDS): - # Sync with disk in case another writer appended while we waited. - # The marker answers "nobody has appended since we last did" in - # one stat; only when it cannot, pay for the full listing. + # Sync with disk only if the marker cannot rule out another writer if not self._marker_matches_length(): disk_length = self._count_events_on_disk() if disk_length > self._length: @@ -250,10 +245,8 @@ def _marker_path(self, length: int) -> str: def _marker_matches_length(self) -> bool: """Whether the marker proves no one has appended since we last did. - ``False`` is not proof of divergence -- a log written before this - marker existed has none either, and so does one whose writer died - mid-update. Callers must fall back to the exact count, which keeps - this an optimization rather than a change of behavior. + ``False`` is not proof of divergence, so callers must fall back to the + exact count. """ try: return bool(self._fs.exists(self._marker_path(self._length))) @@ -264,9 +257,8 @@ def _marker_matches_length(self) -> bool: def _advance_length_marker(self, previous_length: int) -> None: """Move the marker from ``previous_length`` to the current length. - The old marker goes first on purpose: interrupted between the two - calls, the log is left with no marker at all, which costs every writer - one full listing instead of letting a stale marker claim to be current. + Deleting first is deliberate: an interrupted update leaves no marker + rather than a stale one claiming to be current. """ try: self._fs.delete(self._marker_path(previous_length)) diff --git a/tests/sdk/conversation/local/test_client_tools_persistence.py b/tests/sdk/conversation/local/test_client_tools_persistence.py index 67571add6f9..b217cafc167 100644 --- a/tests/sdk/conversation/local/test_client_tools_persistence.py +++ b/tests/sdk/conversation/local/test_client_tools_persistence.py @@ -1,11 +1,31 @@ """Persistence/resume behavior for client-defined tools on LocalConversation.""" +import gc import uuid from pathlib import Path +import pytest + from openhands.sdk import LLM, Agent, Conversation from openhands.sdk.tool import Tool, client_tool as ct, registry as reg from openhands.sdk.tool.client_tool import ClientToolSpec +from openhands.sdk.utils.models import clear_subclass_cache + + +@pytest.fixture(autouse=True) +def _collect_dynamic_client_tool_classes(): + """Drop the dynamic ``ClientAction_*`` classes these tests define. + + Each client tool spec builds a new class, so a test that registers the same + tool name twice leaves two same-named classes behind. They are only + reachable through reference cycles, so until a cyclic collection runs they + stay in ``Action.__subclasses__()`` and make the duplicate-class check in + ``_get_checked_concrete_subclasses`` fail in *unrelated* later tests. + Collecting on teardown, once the test frame is gone, keeps that leak local. + """ + yield + gc.collect() + clear_subclass_cache() def _make_agent() -> Agent: