Repository navigation
fix(sdk): move durable persistence fsync off the event-loop thread (#5402) - #5437
WenzheWang wants to merge 13 commits into
Conversation
…penHands#5402) Durable conversation persistence ran synchronously on the calling thread: every event append cost two fsync'd atomic writes (event file + length marker) and each base-state save one more. When the agent server runs conversations as coroutines on a single event loop, those fsyncs serialize all concurrent conversations, blowing the concurrent-conversa- tions stress budget. This change introduces group-commit durability for LocalFileStore: - write(2) + atomic rename stay synchronous (data visible immediately, survives process exit); only the fsync moves to a per-store, single-threaded FIFO DurabilityWriter, so ordering is preserved (a marker fsync never precedes the fsync of the event it acknowledges) and per-conversation durability stays independent. - Explicit flush/shutdown boundaries: ConversationState.flush()/close() and FileStore.flush()/close(); LocalConversation flushes at the end of run()/arun() (before any terminal status is published) and closes the writer on close(). - Failure propagation: the first worker error is sticky and re-raised by flush()/close(), and fail-fasts the next write *before* it mutates on-disk state (so an acknowledged write never appears durable when it is not). os.replace failures still raise inline, before any partial state is visible. - Opt-out via LocalFileStore(deferred_durability=False); other FileStore backends are unchanged (no-op defaults). Deterministic tests cover fsync thread attribution, process-exit recovery, fault-injected fsync/os.replace propagation, concurrent ordering/isolation, validation errors, marker consistency mid-flight, and run-end/close flush semantics. A new stress canary asserts /health p95 stays in budget while N conversations actively persist events. Run-permit release ordering (OpenHands#5397/OpenHands#5403/OpenHands#5404) is explicitly out of scope, as is the on-disk format (unchanged).
Merge current main and seal task/write admission before shutdown. Settle initialization and flush work under cancellation, preserve primary errors, and finalize cleanup after drained durability failures. Add deterministic process-exit and lifecycle regression coverage and scheduled-arrival health probes.
⏳ Review waiting on checksThe current head
No action is needed. The scheduled scan retries once every check on the head reports a conclusion. This is an automated check - no AI was used to generate this comment. |
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Review: PR #5437 — move durable persistence fsync off the event-loop thread
Scope gate: this change belongs in this repository (SDK persistence / agent-server shared event loop) and addresses a real defect (#5402). The design is sound: a per-store single-worker FIFO DurabilityWriter, synchronous write + atomic rename with only fsync deferred, explicit flush()/close() boundaries, sticky error propagation, and admission serialized against close. Added tests cover admission/close races, FIFO ordering, sticky errors, late-write rejection, initialization failures and cancellation. I ran ruff (clean), the agent-server conversation tests (129 passed), and the new health-responsiveness canary 6/6.
Blocking
Windows: deferred fsync_file reopens the file read-only, so os.fsync fails.
fsync_file() opens the already-written path with os.O_RDONLY (durability.py:49) and calls os.fsync(fd) (line 53). On Windows, CPython maps os.fsync to the CRT _commit → FlushFileBuffers, whose handle "must have the GENERIC_WRITE access right"; a read-only handle fails with EBADF / ERROR_ACCESS_DENIED. The worker records that as a sticky DurabilityError. Because LocalFileStore defaults to deferred_durability=True, every conversation text write on Windows would then fail at the run/close durability boundary (_flush_durability_at_run_end, _state.close). The pre-PR code fsynced the read-write write handle (file.fileno()), so this is a Windows regression, not a pre-existing limitation. The SDK supports Windows (the agent-server CI matrix includes windows-latest, and sys.platform == "win32" branches exist in the SDK), yet no test exercises the deferred path on Windows — the new test file only skips a process-exit test on non-POSIX. Fix: open with a writable mode such as os.O_RDWR (reopening by path read-only is not guaranteed writable on Windows), or restrict the read-only reopen to POSIX and fsync inline on Windows.
Notes
- Required CI on the exact head is still outstanding: the substantive workflows (Run tests, Agent Server, Pre-commit checks, the stress suite, etc.) currently report
action_required. This matches the PR body, which does not claim all-green CI. - The concurrent-conversations stress test is load-sensitive on this host, but it flaked less often on the PR head than on unmodified
main, so I did not attribute any regression to this change. - No repository AGENTS.md/CONTRIBUTING guidance was found that conflicts with this change.
🔄 CHANGES REQUESTED
Merge current main without rewriting published history. Use writable fsync handles, preserve caller-owned stores, retain inline durability for ownerless helper stores, and clean up owned stores when initialization fails.
Integrate main while preserving its temporary-file helpers. Open Windows fsync handles with read, write and delete sharing, and test replacement during fsync and handle ownership on conversion failure. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
|
@VascoSch92 Could you review the deferred-fsync and run/close lifecycle changes here, given your recent review of the related event-loop persistence path in #5538? I refreshed the Validation section for current head The 12 substantive workflows for this head are still |
|
@neubig PTAL |
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Review: PR #5437 — move durable persistence fsync off the event-loop thread (#5402)
Scope gate: this belongs in this repository (SDK persistence / agent-server shared event loop) and fixes a real, CI-observed defect (#5402, open, ready-for-dev, priority:low). Continuing the technical review.
Prior finding is resolved
My earlier review blocked on fsync_file() reopening the target read-only, which fails on Windows because os.fsync (_commit/FlushFileBuffers) requires a writable handle. At c302aafc this is fixed: _open_fsync_file() uses os.O_RDWR on POSIX and on Windows opens via _winapi.CreateFile(GENERIC_READ|GENERIC_WRITE) with FILE_SHARE_DELETE and correctly transfers handle ownership through msvcrt.open_osfhandle (closing it if conversion fails). The writable-handle contract and the WinAPI flags/ownership boundary are covered by test_deferred_fsync_uses_writable_handle and test_windows_fsync_handle_shares_delete_and_transfers_ownership.
Other changes reviewed
- Caller-owned stores:
ConversationState._owns_fsmeans an injectedFileStoreis flushed, not closed, while a factory-created store is closed on failure — matching the documented ownership and the injected-store resume test. - Helper stores with no lifecycle owner (
rerun_actions,tom_consult) correctly opt intodeferred_durability=False, with tests asserting inline fsync. - Admission/close serialization, single shutdown sentinel, sticky-error propagation, and the run/arun flush boundaries all look sound; no material correctness, security, or compatibility defect found.
Local checks I ran on c302aafc81dc988f631539ba311c2ac8ed194b31: ruff clean; tests/sdk/io + test_custom_file_store + test_rerun_actions 69 passed; tests/sdk/io/test_deferred_durability.py 34 passed; tests/tools/tom_consult 4 passed; tests/agent_server/test_conversation_service.py 131 passed; tests/sdk/conversation 866 passed; the new event-loop responsiveness test 6/6 passes. The stress test_concurrent_conversations assertion is host-load-sensitive here — it fails at a similar rate on unmodified main (5c6e258) as on this head, so I do not attribute it to this change.
Why approval is deferred
No code change is being requested. The repository review guide classifies this as a production-facing bug fix whose failure occurs only through a runtime/integration path and requires authentic before-and-after evidence through the real service entry point; it also says to verify current-head CI, since a prior run is not evidence for a changed head. On the current head the substantive workflows (Run tests, Agent Server, Pre-commit checks, REST API breakage, Persisted settings, the stress job, etc.) are still action_required — none has executed — so the acceptance criteria (agent-server stress workflow green, repeated stress passes) cannot be independently confirmed, and the recorded Linux validation is the author's source-identity run rather than an executed current-head CI result or a native Windows run. Per the guide, this defers approval to a human maintainer / CI gate.
🔄 CHANGES REQUESTED
Integrate main and preserve durable completion for no-run mutations. Drain cancelled persistence work and clean up failed conversation forks. Cover server return boundaries, cancellation and atomic fork ownership. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
|
Updated the main integration to preserve durable completion for no-run messages, navigation and confirmation-policy changes, including cancellation handling and failed-fork cleanup. Validation on Linux: 48 boundary regressions passed, with 8 expected failures against the old implementation. Source-matched runs cover 1,073 focused tests, 14 stress cases and 956 integration tests; the final typing-only changes passed 6 supplementary checks and 2 negative controls. All 8 quality hooks passed. A real Agent Server smoke also passed create/message, policy, navigation, fork and graceful-restart checks without invoking a model. Full GitHub CI still needs to run on the published head before merge. |
Merge main while retaining run-slot and goal recovery behavior. Order deferred fsync by write generation without blocking event loops. Cover replacement races, backlog responsiveness and failed admission. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Review: PR #5437 — move durable persistence fsync off the event-loop thread
Scope gate: this belongs in this repository (SDK persistence + agent-server shared event loop) and targets a real defect (#5402, open, priority:low, ready-for-dev). I re-read the current head 832c8cf2d42010467493e9349cb394950d1ea635, its body/labels, all existing reviews and comments, and the linked issue's current body and labels. The head has moved since the last all-hands-bot review (c302aafc), and a non-bot comment was posted afterwards, so this is a fresh pass.
The design intent is sound and the earlier Windows writable-handle finding is resolved at this head. One new material defect appears in the change itself.
Blocking: one OS thread per LocalFileStore makes resident conversations consume unbounded threads, and exhaustion permanently poisons persistence
DurabilityWriter lazily starts a dedicated, non-joined daemon thread on the first deferred text write (_ensure_thread_locked, durability.py:128) and keeps it until close(). LocalFileStore is constructed per conversation (ConversationState.create → LocalFileStore(persistence_dir, ...), deferred by default), so every conversation that writes its initial base_state.json costs one thread for as long as the conversation stays resident — which the agent server does for the default 20-minute idle TTL, and for the whole process for any conversation that is never evicted. The agent-server concurrency cap (max_concurrent_runs) bounds concurrent runs, not resident stores, so nothing bounds this.
Measured on this head, seeding conversations through the real ConversationService.start_conversation:
| revision | 200 conversations | result |
|---|---|---|
base 7a714f41 |
+7 threads | ok |
head 832c8cf2 |
+207 threads | ok at N=200 |
At the repository's own opt-in scale, this breaks outright:
tests/agent_server/stress/test_conversation_listing.py(N=2000) fails on the head:RuntimeError: can't start new threadraised fromDurabilityWriter._ensure_thread_locked→submit_fsync→atomic_write_text(defer_fsync=...)→LocalFileStore.write→_save_base_state, surfacing asDurabilityError: Deferred durability failed.- The same test passes on base
7a714f41(90.1s, 1 passed). - The same test passes on the head when deferred durability is forced off (
deferred_durability=Falseinjected via a pytest plugin; 97.5s, 1 passed).
That third control isolates the cause to this change rather than host load. Note the PR body records this suite as "14 passed", which does not reproduce here; my sandbox has a low cgroup pids.max (256), so the exact threshold is environment-dependent, but the growth is linear, unbounded, and set by the change, not by the host. Containerized deployments that set a pids limit — as this repo itself does for conversation containers (conversation_container_pids_limit, default 512) — will hit the ceiling with far fewer conversations than the stress test.
The failure mode is also not graceful. The thread-start error is recorded as the writer's sticky error (durability.py:197-198) and raise_if_failed() runs before mutation (local.py:96), so after one transient thread-start failure the store rejects all further writes:
first write raised: RuntimeError: can't start new thread
second write raised: DurabilityError: Deferred durability failed (cause: RuntimeError)
file b exists: False
Because run()/arun() flush and LocalConversation.close() re-raise DurabilityError by design, that conversation's persistence is permanently unusable and the error is delivered to callers on every subsequent run and on close. A transient resource condition is thus promoted to permanent data-path failure.
Suggested direction: give the durability workers a bounded owner instead of one thread per store — e.g. a process-wide shared worker/executor that keeps per-store FIFO ordering (a per-store queue drained by a bounded pool, or a shared writer keyed by store), so the thread count is O(worker pool) rather than O(resident conversations); and do not turn a thread-start failure into a sticky per-store durability failure that blocks all later writes.
Other notes (not blocking)
- Current-head CI is not evidence for this head: on
832c8cf2every substantive workflow (Run tests,Agent Server,Pre-commit checks,REST API breakage,Persisted settings,TypeScript client *, etc.) is stillaction_required; onlyValidate PR descriptionandcheck-pr-artifactshave run. I could not independently confirm the acceptance criteria from CI. tests/agent_server/stress/test_concurrent_conversations.pyis host-load-sensitive here and fails at a similar rate on base7a714f41(3/3 on base) as on this head (1/3), so I do not attribute it to this change.- Local checks on this head:
tests/sdk/io67 passed (includingtest_deferred_durability.py, 48 passed), andtests/agent_server/stress/test_event_loop_responsiveness.py3 passed — the intended off-loop durability behavior does work when thread creation succeeds.
🔄 CHANGES REQUESTED
Merge main and share four daemon workers while preserving per-store FIFO. Retain inline durability when no worker can start without poisoning stores. Drain direct server mutations before acknowledging their completion. Cover resident-store resources, interpreter exit and failure boundaries. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Review: PR #5437 — move durable persistence fsync off the event-loop thread
Scope gate: this belongs in this repository (SDK persistence + agent-server shared event loop) and targets a real defect (#5402, open, priority:low, ready-for-dev). I re-read current head cd38be7275a848b3f8fa1d481c2adfc17c10a4bc, its body/labels, all reviews and comments, and the linked issue. The head has moved since my last review (832c8cf2), so this is a fresh pass.
The prior blocking finding is resolved at this head. One new material defect appears in the fork handling added by this revision.
Blocking: forked children deadlock in flush()/close()
The new revision bounds workers by moving them to a process-wide pool and adds os.register_at_fork(after_in_child=_reset_executor_after_fork). That hook resets only the shared pool. Per-store writer state (_scheduled, _idle, and the store's queue.Queue, including its unfinished_tasks counter) is inherited unchanged by a forked child, while the threads that would drain it do not survive the fork.
Consequences in the child, both permanent:
close()blocks forever atself._idle.wait()(durability.py:325):_idlewas cleared when the store was scheduled and nothing will ever set it again.flush()blocks forever atself._queue.join()(durability.py:308):unfinished_tasksis inherited non-zero and no worker will calltask_done().- Because
_ensure_worker_lockedonly re-submits when_scheduledis False (durability.py:187-188), and_scheduledis inherited True, any write the child performs is queued but never fsync'd.
Reproduced on this head with no monkeypatching, 3/3 runs (fork after a store has queued durability work):
parent scheduled: True qsize: 2605 unfinished: 2606
child scheduled: True unfinished: 2605
RESULT: child close() HUNG on inherited backlog
Reachability: this needs a fork while a store has queued/in-flight fsync work. The agent server does not fork per conversation, but the SDK is an embeddable library and the repository itself runs tests under pytest --forked in CI (.github/workflows/tests.yml, tests-macos.yml). LocalConversation registers atexit.register(self.close), so a child that reaches interpreter exit can also hang there. The author added the fork hook because fork is considered a supported scenario; as written it is incomplete.
Suggested direction: reset the inherited per-store writer state in the child rather than only the pool. For example, register an after_in_child callback that marks _scheduled = False, sets _idle, clears the store's queue (and drops stale generations), or, more simply, avoid relying on a queue whose unfinished_tasks/thread ownership cannot survive fork.
Notes
- Prior finding fixed and verified here: a per-store OS thread no longer scales with the number of conversations. 3000 stores created via
LocalFileStore/deferred writes now add 4 threads total (previously ~1 per store). The listing stress test that failed at832c8cf2passes here (test_conversation_listing.py, 93.9s). test_concurrent_conversations.pyfails on this head, but it fails 3/3 on base0996c33too (base: 0.82-0.97s vs budget ~0.66s; head: 0.64s vs 0.57s), so it is host-load-sensitive and not attributable to this change.- Current-head CI is not evidence for this head: on
cd38be72every substantive workflow (Run tests,Agent Server,Pre-commit checks,REST API breakage,Persisted settings,TypeScript client *, etc.) is stillaction_required; onlyValidate PR descriptionandcheck-pr-artifactshave run. - Local checks on this head:
tests/sdk/io70 passed (incl.test_deferred_durability.py),tests/sdk/conversation+tests/tools/tom_consult882 passed,tests/agent_server/test_event_service.py+tests/sdk/conversation/local/test_custom_file_store.py139 passed, and the stress suite 13 passed / 1 failed (the host-sensitive case above).
🔄 CHANGES REQUESTED
Check process ownership before accessing inherited locks or queues. Keep accepted work in the parent and require fresh stores in children. Cover active and locked writers, fresh child stores and interpreter exit. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Review: PR #5437 — move durable persistence fsync off the event-loop thread
Scope gate: this belongs in this repository (SDK persistence + agent-server shared event loop) and targets a real defect (#5402, currently open with priority:low, ready-for-dev). I re-read the current head ff60e5b5d362c8db9305a23c1204e893a63704a8, its body, labels, all reviews/comments, and the linked issue. The head has moved since my last review (cd38be72), so this is a fresh pass.
Both findings I raised earlier are resolved at this head, and I found no new material defect.
Prior finding 1 (unbounded threads) — fixed
A per-store OS thread no longer scales with the number of conversations. Creating 3000 stores via LocalFileStore + deferred writes now adds 4 threads total (previously ~1 thread per store). The stress test that failed at 832c8cf2 passes here: tests/agent_server/stress/test_conversation_listing.py (N=2000) completed in 75.9s.
Prior finding 2 (forked-child deadlock) — fixed
The new _check_process() PID guards (durability.py, local.py) reject inherited writers/stores in a forked child instead of deadlocking. Verified by reproduction on this head: a fork taken while a store has 3000 queued fsyncs and a blocked fsync callback now leaves the child exiting promptly with RuntimeError: LocalFileStore was inherited across fork (2/2 runs), rather than hanging in close()/flush(). The new tests (test_inherited_durability_rejects_before_locks, test_inherited_conversation_atexit_does_not_hang) pass, including the cases where the child inherits the store lock, the writer lock, and the queue mutex. Reads in the child remain available, and the parent's own in-flight durability work is unaffected.
Notes
- Behavioral change worth calling out for library consumers: with
deferred_durability=True(the default), a forked child can no longer write/flush/close an inheritedLocalFileStore— it raisesRuntimeErrorinstead. This is documented in theLocalFileStoreandDurabilityWriterdocstrings and is the safe choice given inherited locks, so it is not blocking; consumers that fork withoutexecmust construct a new store in the child. test_concurrent_conversations.pystill fails in the stress suite on this head (13 passed / 1 failed), but it also fails 3/3 on base0996c33(base 0.79-0.86s vs budget ~0.67-0.75s; head 0.64s vs 0.57s). It is host-load-sensitive and not attributable to this change.- CI is not evidence for this head: on
ff60e5b5onlyValidate PR descriptionandcheck-pr-artifactshave run; the substantive workflows are still awaiting approval. This review is a code assessment, not a merge-readiness or power-loss-durability claim. - Focused checks run locally on this head:
tests/sdk/io78 passed;tests/sdk/conversation+tests/tools/tom_consult882 passed;tests/agent_server/test_conversation_service.py,test_event_service.py,tests/sdk/conversation/local/test_custom_file_store.py,test_rerun_actions.py286 passed; new fork tests 12 passed; full stress suite 13 passed / 1 pre-existing failure.
✅ APPROVED
Merge main while retaining file-store ownership and durability boundaries. Handle unbound states using the declared None default. Preserve lease cleanup and executor emission failure regressions. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
|
Merge main while retaining condenser availability checks and durable completion. Cover successful and failed condensation flushes alongside refusal cases. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
Merge main while retaining fork cleanup, missing-event recovery and budgets. Settle budget mutations and accepted durability work before completion. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
Merge main 2f48ccb while retaining deferred-durability boundaries. Document local run status and remote exception behavior together. AI assistance was used for this change. Signed-off-by: Wenzhe Wang <w_wenzhe@163.com>
HUMAN:
I’m contributing this change to prevent conversation persistence from blocking the shared agent-server event loop, while preserving persisted formats and REST/WebSocket behavior. Linux validation of the submitted source has passed, including all 14 Agent Server stress tests. Deferred durability work is drained before run()/arun() returns and on close(); terminal-status visibility alone is not a durability acknowledgement. GitHub CI approval and maintainer review remain outstanding.
AGENT:
Why
Fixes #5402. Synchronous fsync on the shared Agent Server event loop blocks unrelated conversations and health requests. This change moves fsync off that thread without changing persisted formats or REST/WebSocket contracts.
Summary
deferred_durability=Falsekeeps the synchronous path; other FileStore backends retain no-op lifecycle defaults.Durability acknowledgment is the completed operation's return, not the first visible event or terminal status. Run-permit release ordering (#5397/#5403/#5404) and server terminal-publication changes remain out of scope. No directory-fsync or OS-crash/power-loss recovery guarantee is added.
How to Test
Head
33e113b431d599606904eeeca7fa0c365110b60bintegrates main60192ed54db73ac658ac1a07462916126c32d3a0. All 1,950 selected source files match the Linux CPU snapshot tested by job526038; formatter patches are empty. The job completed with exit0:0in 9 minutes 7 seconds.pre-commit run --all-filesSuite counts are not additive: the 8 fork and 1 unbound-state cases are subsets of the owner suite. Previous-code controls produced the intended 7 fork failures and 1 unbound-state failure. Three native queued-fsync fork probes rejected inherited work promptly with the fix; all three old-code probes hung until the probe alarm. The merged condense path passes both durability success/failure cases and both unavailable-condenser refusal cases.
Executed commands included:
The runtime reused Linux x86_64/Python 3.12.11 dependencies with task-private 1.58.1 workspace packages and lock-pinned certifi 2026.10.19; it was not a fresh full
uv sync. The focused suite's unawaited_apply_acp_modelwarning remains recorded. Native Windows and power-loss recovery were not tested.Evidence is bound to this published head by unchanged-source identity, not a post-commit rerun. Independent source and evidence review passed. GitHub's substantive workflows still require maintainer authorization; these results do not replace current-head CI or maintainer review.
Type
Notes
AI assistance was used for this change. I have personally reviewed the submitted changes and take responsibility for this contribution.