Skip to content

perf(sdk): make EventLog.append flat against conversation length - #4856

Closed
alanhuangyoo wants to merge 1 commit into
OpenHands:mainfrom
alanhuangyoo:perf/eventlog-append-flat
Closed

alanhuangyoo wants to merge 1 commit into
OpenHands:mainfrom
alanhuangyoo:perf/eventlog-append-flat

Conversation

@alanhuangyoo

Copy link
Copy Markdown
Contributor

HUMAN:

Ran a long conversation against a local file store and watched the per-append time stop climbing; 3200 appends went from 22s to 1.3s.


AGENT:

Why

Closes #4676 (step 1 of #4671).

EventLog.append listed the whole events directory on every call, inside the lock, to notice writes from another process:

with self._fs.lock(self._lock_path, timeout=LOCK_TIMEOUT_SECONDS):
    disk_length = self._count_events_on_disk()   # self._fs.list(self._dir)

LocalFileStore.list() is worse than a listing. It stats every entry to decide whether to append a trailing /:

files = [os.path.join(path, f) for f in os.listdir(full_path)]
files = [f + "/" if os.path.isdir(self.get_full_path(f)) else f for f in files]

So appending event N costs N stat calls on the run loop's critical path, while holding the lock. At 1600 entries the listing is 0.416 ms and the stats take it to 3.031 ms — 86% of the cost is for a decoration the counter does not read.

Summary

  • append counts the directory only when a marker file cannot prove the count is unchanged.
  • The count is in the marker's filename, not its contents. FileStore.read is served from a cache the class documents as assuming exclusive access, so it cannot see another writer; FileStore.exists goes to the filesystem. Measured below.
  • LocalFileStore.delete no longer logs a failure when evicting a cache entry that was never there, and _scan_and_build_index no longer reports bookkeeping dotfiles as malformed event files.

Why this cannot lose a concurrent write

Only an exact match with our own _length is treated as proof. A missing marker, a marker naming a different count, or a store that cannot answer all fall through to _count_events_on_disk() + _sync_from_disk() unchanged, so the authoritative path is exactly what it is today and the new fast path only ever skips work when nothing has changed.

The marker is written after the event, inside the lock. An append interrupted anywhere in the critical section therefore leaves no marker at all, which costs the next writer a full count rather than letting it trust a stale one. Over-trusting is not reachable.

How to Test

uv run pytest tests/sdk/conversation/test_event_store.py tests/sdk/io/ -q

Full suite:

$ uv run pytest tests/sdk/ -q
6070 passed, 9 skipped, 16 deselected, 10 xfailed in 157.44s

ruff check and ruff format --check are clean on the four changed files.

The measurement the issue asks for

EventLog over LocalFileStore, real MessageEvents with generated ids, mean ms per append by bucket:

events so far before after
400 1.066 0.396
800 2.565 0.428
1200 4.135 0.388
1600 5.701 0.425
2000 7.107 0.394
2400 9.192 0.432
2800 11.863 0.401
3200 12.827 0.385
last / first bucket 12.0x 1.0x
total for 3200 appends 21.78 s 1.30 s

Flat, which is the acceptance criterion. 17x on the total, 33x on the last append.

End-to-end across two real processes

Unit tests share a FileStore object, so they cannot exercise the thing the marker exists for. Parent appends 1, a spawned child process appends 3, parent appends again:

parent wrote 1, len=1
child wrote 3 in a separate process
parent's marker for its own length still valid? False
after parent appends again: len=5   (expect 5)

The parent's probe correctly fails, it re-counts, and the child's events are picked up.

And the asymmetry the design rests on, on the same store:

FileStore.read after an external write:  'written-by-parent'    <- stale, from cache
os.path.exists (what the marker uses):   True

A contents-based marker would have been silently wrong across processes. tests/sdk/io/test_filestore_cache.py::test_exists_sees_an_external_write_but_read_does_not pins that property so the reason for the filename encoding does not get refactored away.

Tests

Six cases in test_event_store.py and three in test_filestore_cache.py. Four of them fail on the parent commit and pass here:

FAILED test_append_does_not_count_the_directory_on_the_fast_path
FAILED test_a_stale_marker_is_not_treated_as_proof
FAILED test_marker_names_do_not_prefix_one_another
FAILED test_bookkeeping_files_are_not_reported_as_malformed

The other two — a second instance still seeing the first's events, and a missing marker falling back to counting — pass either way on purpose: they guard the multi-writer behaviour this change must not cost.

test_marker_names_do_not_prefix_one_another is there because InMemoryFileStore.delete matches by prefix, so .eventlog-count-1 would have deleted .eventlog-count-10. The names carry a .marker suffix so no one is a prefix of another at any count.

The two incidental fixes

Both were found by this change and both reproduce on main:

store = LocalFileStore(tmp)
(tmp / "external.txt").write_text("hi")     # not written through the store
store.delete("external.txt")
# ERROR Error clearing local file store: '.../external.txt'
# ...and the file is gone. The removal succeeded; the KeyError came from evicting
# a cache entry that was never there.

and every EventLog open logs Unrecognized event file name: .eventlog.lock.

Issue Number

Closes #4676

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change

append() listed the whole events directory on every call, inside the lock, to
notice writes from another process. LocalFileStore.list() stats every entry to
decide whether it is a directory, so appending event N cost N stat calls on the
run loop's critical path, and the cost grew with the conversation.

A marker file records the number of events on disk and append only counts when
the marker cannot prove the count is unchanged. The count is in the filename
rather than the contents because FileStore.read is served from a cache that the
class documents as assuming exclusive access, so it cannot see another writer,
while FileStore.exists goes to the filesystem. Only an exact match with our own
length is treated as proof; a missing marker, a marker for another count, or a
store that cannot answer all fall through to the counting path unchanged, so an
interrupted append costs the next writer a full count rather than letting it
trust a stale one.

3200 appends, LocalFileStore, mean ms per append by bucket:

    events    before    after
       400     1.066    0.396
      1600     5.701    0.425
      3200    12.827    0.385
    growth     12.0x     1.0x
     total    21.78s    1.30s

Two things found on the way and fixed here because this change exercises them:

LocalFileStore.delete removed the file and then raised KeyError evicting a cache
entry that was never there, which the handler logged as "Error clearing local
file store" even though the delete had succeeded. Any file written by another
process hit this; the marker hits it on every append.

_scan_and_build_index warned "Unrecognized event file name" for the lock file on
every open. Bookkeeping dotfiles now skip that check instead.
@all-hands-bot

Copy link
Copy Markdown
Collaborator

🚦 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 @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@VascoSch92

VascoSch92 commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Thank you for this, and I'm sorry to be the bearer of annoying news: this landed a few hours ago in #4697

@alanhuangyoo

Copy link
Copy Markdown
Contributor Author

Superseded by #4697, which landed while I was working on this. Closing.

We converged on the same design — the marker naming the count in its filename because FileStore.read is cached and exists is not, and only an exact match with our own length treated as proof — which is what the constraints leave you with. Theirs is the better of the two, and not only because it got there first.

The ordering is wrong in mine. #4697 deletes the old marker before writing the new one, and says why:

Deleting first is deliberate: an interrupted update leaves no marker rather than a stale one claiming to be current.

Mine writes the new marker first and deletes the old one after, so an interruption between the two leaves both on disk. A writer whose _length is the old count would then find its marker, take that as proof nothing changed, and skip the count — with an event already appended. My own docstring claims the opposite of what the code does, which is worse than getting it wrong quietly.

I also went looking for something to still contribute and did not find it. #4697 covers the same two incidental fixes I had — LocalFileStore.delete raising KeyError evicting a cache entry that was never there, and _scan_and_build_index reporting the lock file as a malformed event name — and its cache.pop(full_path, None) is cleaner than my if ... in ... guard. I checked whether pop skips the __delitem__ that decrements current_memory, because that would have been an accounting leak; it does not, cachetools' MutableMapping.pop goes through __delitem__:

after 2 writes:   current_memory=150
after pop('a'):   current_memory=50
after del c['b']: current_memory=0

For whatever it is worth to #4671, my measurement agrees with the one in the new benchmark script — 3200 appends over LocalFileStore went from 21.78s to 1.30s, and per-append from 12.0x growth across the run to flat.

Thanks @VascoSch92.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Perf] EventLog.append lists the entire event directory on every append

3 participants