Skip to content

Close directory watcher descriptor when the handler fails#1773

Open
muk2 wants to merge 1 commit into
apple:mainfrom
muk2:fix/1097-too-many-open-files
Open

Close directory watcher descriptor when the handler fails#1773
muk2 wants to merge 1 commit into
apple:mainfrom
muk2:fix/1097-too-many-open-files

Conversation

@muk2

@muk2 muk2 commented Jun 20, 2026

Copy link
Copy Markdown

Summary

Closes a file-descriptor leak in DirectoryWatcher. The descriptor is opened
before the dispatch source that would normally own and close it is created. If
listing the directory or invoking the handler throws, the function returned
without closing that descriptor, and because the watcher retries roughly once
per second, the leak accumulated over time. This adds a close(descriptor) in
the error path before rethrowing. (The existing cancel-handler close only runs
once the dispatch source has been created, so it does not cover this earlier
failure.)

Testing

  • make check passes (formatting + license headers).
  • Unit tests: DirectoryWatcherTest adds testFailingHandlerDoesNotLeakDescriptors,
    which forces a throwing handler through several retry cycles and asserts the
    descriptor count stays bounded. Full suite (5 tests) passes.

Fixes #1097

DirectoryWatcher._startWatching opens an O_EVTONLY descriptor and then
runs the change handler before creating the DispatchSource that takes
ownership of the descriptor (and closes it on cancellation). If the
handler or contentsOfDirectory call throws, the function returns without
ever creating the dispatch source, leaking the descriptor. Because
startWatching retries roughly once per second whenever the source is
still nil, this leaks one descriptor per second on the long-lived host
daemon, eventually exhausting file descriptors for the whole system and
crashing unrelated host apps with "too many open files".

Close the descriptor on the error path and add a regression test that
verifies a continuously failing handler does not accumulate open fds.

Fixes apple#1097
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.

[Bug]: Running Claude Code in a container crashes apps on the host system with "too many open files"

1 participant