diff --git a/openhands-sdk/openhands/sdk/conversation/event_store.py b/openhands-sdk/openhands/sdk/conversation/event_store.py index d36eb0143f9..ddfd38f1366 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,6 +22,10 @@ LOCK_FILE_NAME = ".eventlog.lock" LOCK_TIMEOUT_SECONDS = 30 +# 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 # ``from event_store import ROOT_PARENT_ID`` importers keep working. @@ -196,10 +200,11 @@ def append(self, event: Event) -> int: 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 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: + self._sync_from_disk(disk_length) if evt_id in self._id_to_idx: existing_idx = self._id_to_idx[evt_id] @@ -229,6 +234,7 @@ def append(self, event: Event) -> int: self._id_to_idx[evt_id] = idx self._event_cache[idx] = event self._length += 1 + self._advance_length_marker(idx) return idx except TimeoutError: logger.error( @@ -237,6 +243,33 @@ def append(self, event: Event) -> int: ) 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, so callers must fall back to the + exact count. + """ + 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. + + 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)) + 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: @@ -301,6 +334,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/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: diff --git a/tests/sdk/conversation/test_event_store.py b/tests/sdk/conversation/test_event_store.py index 6035f88a52a..e7fc158ffb3 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: @@ -424,7 +425,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 @@ -555,3 +557,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: