Skip to content

Poll a page's files when the kernel has no native watcher left - #3848

Merged
max-sixty merged 2 commits into
mainfrom
fix/3491-poll-when-inotify-spent
Oct 25, 2026
Merged

max-sixty merged 2 commits into
mainfrom
fix/3491-poll-when-inotify-spent

Conversation

@max-sixty

@max-sixty max-sixty commented Oct 25, 2026 •

Copy link
Copy Markdown
Owner

When the kernel refuses a native file watcher because a per-user inotify limit ran out, FileChanges now starts the same watch with watchfiles' polling and names the limit in one watch-limit note on stderr: fs.inotify.max_user_watches for ENOSPC, and fs.inotify.max_user_instances or RLIMIT_NOFILE for EMFILE, which inotify_init returns for either. Before, the error reached the subscription's owner and ended whichever Leaf process asked next: a page server, the pages follower, or a leaf wait.

fs.inotify.max_user_instances and max_user_watches are per user and shared with every program the user runs (each Claude Code session takes an instance), so no consolidation of Leaf's watchers can promise it a native one. That makes the fallback in FileChanges, the one place every follower creates watchers, the fix for the failure mode. The module header claimed watchfiles owned a polling fallback; watchfiles 1.3.0 polls on its own only under WSL or when inotify is missing (ENOSYS), so the header now says what Leaf does.

Behavior change: test_native_watcher_failure_reaches_its_owner pinned the crash. It is replaced in tests/model/test_native_watch.py, beside the other FileChanges tests, by test_an_exhausted_native_watcher_polls_instead, which covers both limits, checks that the polled subscription still wakes on a write, and checks the note. test_any_other_native_watcher_failure_reaches_its_owner keeps every other watcher error propagating, so a root retired during installation still replans.

How exhaustion is recognized

watchfiles exposes no errno for either refusal, so _LIMITS matches its words. I confirmed both in a Linux container with a private user namespace and lowered /proc/sys/user/max_inotify_*:

  • instances spent: WatchfilesRustInternalError: Error creating recommended watcher: Too many open files (os error 24)
  • watches spent: OSError: OS file watch limit reached. about [...] (Error { kind: MaxFilesWatch, ... }) (notify renames ENOSPC)

In the same container, FileChanges from this branch, with the instance limit at 0 and then the watch limit at 1, printed the note and woke on a write about 0.4 s after the subscription was created. Both refusals arise only while the watcher is created: notify 8.0.0 drops a watch it can't add later (add_watch(...).ok() in inotify.rs), so the restart can't lose a change the native watcher had reported.

What polling costs

Measured on this Mac: CPU time of a process holding one page's subscription (its parent flat, the page recursive) for 30 s under WATCHFILES_FORCE_POLLING=1, on pages from the state home (289 pages):

page entries polling CPU
median 1,486 5.3% of a core
p90 10,624 25%
largest (201 revisions) 73,714 64%

The native watcher on the largest page used 0.01 s over the same 30 s.

So a process that falls back pays for it in CPU, in proportion to its page's whole tree. The page's reading stamps far less of that tree than the watch polls: the page's direct children, page/ and data/, and the entries of other direct subdirectories. That is at most 753 entries on any page here (median 164); the rest is mostly old revisions. Narrowing each page subscription to those inputs would cut polling cost by about two orders of magnitude, and native watch use too. That change reaches _PageChanges.connect, session.Watch.mark and how _existing_roots collapses a missing recursive root, so it is left for its own change.

Scope

This settles the failure mode: a spent limit slows the process that met it rather than ending it. Consolidating page servers into one process, an idle exit for servers, and per-path recursion upstream stay deferred: none of them keeps a host with many sessions under a shared limit, and the first two reach the serving and revival contract.

Closes #3491

This was written by Claude Code on behalf of max-sixty

When the kernel refuses a native file watcher because a per-user inotify
limit ran out (EMFILE for instances, ENOSPC for watches), FileChanges
starts the same watch with watchfiles' polling and notes the limit on
stderr, instead of ending the process that asked.

Behavior change: test_native_watcher_failure_reaches_its_owner pinned
the crash; test_an_exhausted_native_watcher_polls_instead replaces it,
and any other watcher error still reaches the owner.

Closes #3491

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The EMFILE note can send someone to the wrong setting. Linux's inotify_init(2) error table gives the same EMFILE for both the per-user inotify instance limit and the process's open-file limit, while this branch always reports fs.inotify.max_user_instances. The fallback is useful for either cause, but the diagnostic cannot identify which one occurred from this error. The module header, test expectation, and PR description make the same exact-limit claim.

Comment thread src/leaf/file_changes.py Resolved
inotify_init returns EMFILE for the per-user instance limit and for the
process's open-file limit alike, so the note names both rather than
sending the reader to fs.inotify.max_user_instances alone.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@max-sixty
max-sixty merged commit 50d1729 into main Oct 25, 2026
5 checks passed
@max-sixty
max-sixty deleted the fix/3491-poll-when-inotify-spent branch October 25, 2026 03:51
max-sixty added a commit that referenced this pull request Oct 25, 2026
A page's subscription now watches only the directories its reading
reads, rather than the whole page tree. Under the polling fallback from
#3848, the largest page on this Mac (73,714 entries, 73,248 of them
under `revisions/`) costs 6% of a core instead of 61–66%. With a native
watcher, the history under `revisions/` no longer takes inotify watches
toward `max_user_watches`. That matters because notify 8.0.0 drops a
watch it can't add while running (`add_watch(...).ok()`), so a recursive
watch that reached the limit stopped seeing new subdirectories and
raised no error.

### One statement of what a reading reads

`served_state/reading.py` already declared a page's inputs: `page_input`
(which paths inside the page count), `outside_inputs` (the claim, the
claimant's session file, bound files) and `held_page_reading`, which
stamps them. `page_roots(page_dir)` now sits beside `page_input` and
names the directories whose notifications report those inputs:

- the page's parent, non-recursively, which reports the page directory
being replaced;
- the page directory, non-recursively, which reports its direct
children;
- each other direct subdirectory, such as `revisions/`, `runtime/` or
`media/`, non-recursively, since adding or removing an entry moves that
directory's stamp;
- `page/` and `data/` (`TREES`), recursively, since the reading stamps
every file in them.

What each revision holds and the vendored layer's modules are not
inputs, so nothing watches them. `_PageChanges.connect` and
`session.Watch.mark` both subscribe `page_roots`. Each of them used to
spell `{page.parent: False, page: True}` itself; now neither keeps a
list of its own.

### Roots that follow the page's subdirectories

Recursion over the whole page meant a new subdirectory was always
covered. Now each direct subdirectory is a root of its own, so the set
of roots can change. A subdirectory created after the roots were listed
but before the owner took its generation would be reported once,
absorbed into that generation, and never subscribed. Both owners close
that gap the same way. They install the subscription, take the
generation, plan the roots again, and install again if the new plan
differs. A subdirectory created before the generation is then
subscribed, and one created after it wakes the owner, who connects
again. For this, `page_changes(page)` now returns the subscription
together with the generation it was current at. Its four callers
(`follow_events`, `stop_when_service_ends`, `RowPublisher.run` and one
lifetime test's stub) take both from it, where before they called
`mark()` themselves.

`_existing_roots` now subscribes a missing directory's nearest ancestor
without recursion. The ancestor reports the directory's creation, and
every owner subscribes again on that wake. Recursing from the ancestor
only watched whatever else lay beneath it: a page directory deleted
mid-run would put a recursive watch on `pages/`, which holds every page.

### Tests

- `test_a_page_subscription_hears_every_input_its_reading_reads`, for
both the shared page subscription and a session's `Watch`, finds the
reading's inputs by recording every `file_stamp` that `page_reading`
takes, not from a list. It then writes each input in turn and asserts
that the write both wakes the subscription and moves the reading. Writes
inside a revision, to `user-views.json` and to a staging file must do
neither. It also asserts that `page/` and `data/` are the only recursive
roots and that no revision is a root. As a control, dropping the
non-recursive subdirectory roots makes it fail, naming `instructions/`,
`widgets/` and five other directories whose entries then wake nothing.
-
`test_a_page_subscription_takes_in_a_directory_made_while_it_installs`,
for both owners, creates a subdirectory while the native watcher is
being installed and asserts that the subscription handed back includes
it. Removing the plan check after the generation makes it fail for each
owner.
- Behavior changes in existing tests. In two tests a subdirectory is
made after `connect` and then written into; they now connect again
first, as every owner does after a wake.
`test_native_subscription_rearms_a_root_replaced_during_installation`
now expects `connect` to replan within the call. Before, it returned a
stale subscription that the next `connect` replaced. In
`test_native_watch_follows_a_prepared_claim_until_ownership_commits[subscribing]`,
a claim prepared during installation is now subscribed by that same
`mark`, so the test asserts the prepared target is watched instead of
waiting for a wake.

Ran `tests/model/test_native_watch.py`,
`tests/model/test_server_lifetime.py`, `tests/model/test_wait.py`,
`tests/model/test_hooks.py`, the `events --follow` tests in
`tests/model/test_interact_document.py`, and the row, neighbour,
retirement and orphan tests in `tests/process/test_interact_server.py`.
All pass.

### Polling cost, measured

This is the CPU time of a process holding one page's shared subscription
for 30 s with `WATCHFILES_FORCE_POLLING=1`, as #3848 measured it. The
pages are the largest, p90 and median by entry count of the 289 pages
under `~/.local/state/leaf/pages/`. Before and after ran back to back,
twice each, on a host with a load average of about 17–25. "Before" is
main's roots (`{parent: False, page: True}`) through the same
`FileChanges`.

| page | entries | before | after |
|---|---|---|---|
| largest (`guidance-code-survey-e4e7`) | 73,714 | 66.0%, 61.3% | 6.1%,
6.0% |
| p90 (`guidance-code-removal-e4e7`) | 10,495 | 23.3%, 26.6% | 4.9%,
4.4% |
| median (`leaf-organization-review`) | 1,486 | 11.3%, 10.1% | 6.3%,
6.0% |

The largest page's roots now hold about 1,000 entries, not 73,714.
What's left is roughly the same on every page. An empty directory with
the same claim subscription costs 2.1%, and each page subscription also
polls the shared `pages/` (291 entries) and `claims/` (635 entries)
directories, non-recursively, to see its own page directory and claim
file replaced. That floor grows with the number of pages on the machine,
not with the page's own history.

Refs #3491

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Oct 25, 2026
test_a_wait_takes_the_suites_deadline failed because two waits fixed their
own deadline: the margin pins test's `timeout=8000` on the status notice
(#3814) and the exhausted-watcher test's `changes.wait(mark, timeout=10)`
(#3848). Each now takes the suite's deadline, SERVED_TIMEOUT_MS by default
and STATED_TIMEOUT, so a slower host waits longer instead of failing. No
product behavior changed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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.

Leaf's inotify instance use grows with every page server, and running out kills whichever Leaf process asks next

2 participants