8000 Nothing decides when to forget · Issue #620 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

Nothing decides when to forget #620

Closed
Closed

Description

@Lillecarl

DONE. Both halves are built and gated: huggorm.Watcher decides
what to forget, and huggorm.Notifier notices without being asked.
The adapter was deferred by Carl behind #570 and #569,
and both are done. The last section says what it cost and what
building it proved.

#553 built the mechanism in three parts, and they compose:

cached_files()          what to watch
the diff around         which files belong to which
  one eval_file         (WRONG - see 2026-09-03 below)
forget_file(path)       drop one without dropping the rest

What is missing is the part that NOTICES. A caller must watch the
files itself and hand the closure back, so the "live-reloading
evaluation server" in CLAUDE.md is still a manual reload.

The decision this needs, and it is Carl's

Where the watcher lives is not obvious, and the two answers lead to
materially different work.

  • In the RPC server. The server already owns a state's lifetime,
    its sweeper and its thread. A watch is one more thing on a
    connection, and a client that reconnects finds the state already
    invalidated. It also means a watch cannot exist without a server -
    the in-process binding gets nothing.
  • In huggorm, under both surfaces. A watcher over an
    EvalStateLike works in-process and over RPC. It has to route
    forget_file onto the state's OWN thread, which the async layer
    already does, and it has to decide what happens when a watch
    outlives the client that asked for it.

No C++ either way. inotify is a Python call, and the C++ half is
built.

What it must get right

Forget the CLOSURE, not the file. Measured in #553 and
gated twice: the cache holds no edge from an importer to its import,
so forgetting the changed file alone leaves the importer answering its
old value SILENTLY. The watcher has to keep the closure it recorded at
evaluation time, and forget all of it.

Skip what it cannot stat. cached_files returns what the cache
holds, and one entry is not a file:
«nix-internal»/derivation-internal.nix. A watcher that calls
inotify_add_watch on it fails on every evaluation.

A closure is only recoverable if one evaluation runs at a time.
The diff around eval_file is the closure, and two concurrent
evaluations on one state mix theirs. The affine state this repo
already assumes is what makes the technique work; a watcher that
records closures depends on it, and should say so.

builtins.readFile is invisible. A data file an expression read
is in no cache, so no watch fires for it. A known limit, and it
belongs in the API's docstring rather than in a surprise.

Why it is not "just inotify"

The hard part is not the syscall. It is the bookkeeping: a closure per
evaluated path, an inode that appears in several closures, an editor
that writes by rename so the watch is on the wrong inode, and a
forget that must run on the state's thread rather than the watcher's.

After this

Background eager evaluation, which is the last third of #553.
It needs this one first: eagerly re-evaluating an expression is only
useful if something knows the old answer is stale.

2026-09-03: the diff is not the closure

#553 said the closure is the cached_files diff around one
eval_file. Measured before designing anything, and it is WRONG in
the case that matters: a file two roots share.

shared.nix = 40 + 2
a.nix      = import shared.nix
b.nix      = import shared.nix

diff around a: [a.nix, shared.nix]
diff around b: [b.nix]              <- shared.nix is NOT here

The diff says what an evaluation newly CACHED, not what it READ. a
cached shared.nix first, so b hit the cache and its diff missed
it. Then:

(shared.nix edited to 1 + 1)
forget b's own diff  ->  b answers 42

A watcher holding per-root diffs answers stale, silently, which is
this repo's named failure mode. Nothing in 016's gates could see it:
each test gets a fresh tmp_path, so no file is ever shared.

The policy, measured rather than argued

Record the full cached_files SNAPSHOT taken after each root
evaluates. When a file changes, forget the union of every snapshot
that contained it.

Sound, and the reason is short: a snapshot taken after R evaluated
holds everything cached at that moment, and every file R read was
cached by the time R finished. So snapshot[R] is a superset of R's
closure. It cannot miss.

Measured with a third root added, and it works:

snapshot[a] = [a, shared, «nix-internal»]
snapshot[b] = [a, b, shared, «nix-internal»]
snapshot[c] = [a, b, c, shared, «nix-internal»]

(shared edited)
roots implicated: a, b, c
a -> 2  OK
b -> 2  OK

What it costs, stated rather than hidden

c.nix is 10 + 1. It reads nothing but itself and it is forgotten
anyway, because it was evaluated after shared.nix was already
cached and a snapshot cannot tell a hit from a file never read.

So the cost grows with the order roots are registered in: a root
registered late is implicated by almost any change. At worst this
degenerates to "forget the whole eval cache", which is still strictly
better than resetFileCache() - the fetched flake inputs stay, and
they are the expensive half Carl named.

The exact answer needs libexpr to say which files ONE evaluation read.
It will not (#16), and the two approximations available are
this one and the diff. The diff is cheaper and silently wrong, so it
is not a trade - it is the wrong answer.

What follows for the design

  • The watcher OWNS eval_file and serializes it. A snapshot is only
    a snapshot if nothing else evaluates at the same time, so calling
    the state's eval_file directly bypasses the bookkeeping. That is
    the affinity assumption made load-bearing, and it has to be said in
    the API rather than assumed.
  • NOTICING is separate from BOOKKEEPING. The core takes an explicit
    step - "this path changed, act on it" - so a gate can drive it with
    no sleeps and no event timing. An inotify source is then a thin
    adapter over the same step, and its own commit.
  • Watches go on parent DIRECTORIES, not files. Most editors save by
    rename, which replaces the inode and orphans a file watch.

2026-09-03: the watcher, built

huggorm.Watcher, in packages/huggorm/huggorm/watch.py. Carl chose
the second option above: written against EvalStateLike, so one
object serves an in-process AsyncEvalState and a remote
RPCEvalState alike.

Bookkeeping and noticing are separate, and that is what makes it
gateable:

changed(path)  ->  told a file moved. Stats nothing.
rescan()       ->  stats for itself. No dependency.

Both call the same step, so a gate drives the whole thing with no
sleeps, no timers and no event ordering. An inotify source becomes a
third caller of changed() rather than a rewrite.

It records a SNAPSHOT per root, for the reason measured above. The
watcher OWNS eval_file and takes a lock around it, because a
snapshot is only a snapshot if nothing else evaluates at the same
time. Reaching past the watcher to the state's own eval_file
poisons the bookkeeping, and the class docstring says so rather than
leaving it as a property of the async layer.

The gates

Seven, in tests/test_watch.py. The one that matters is the shared
import, seen to fail by reverting the policy to the diff #553
described:

assert [a.nix] == [a.nix, b.nix]
FAILED test_a_shared_import_forgets_both_roots
1 failed, 277 passed

That one and no others, so it discriminates the policy rather than the
plumbing. b is the root a diff-based watcher misses.

The others cover the base case, rescan finding a change unaided, a
DELETED dependency counting as a change, the virtual cache entry never
being stat-ed, and an unrelated path forgetting nothing - the last
being the control that a watcher forgetting everything on every event
would fail.

287 passed, from 280.

Three limits, named in the module

  • builtins.readFile and builtins.path are in no cache, so no
    change to a data file invalidates anything.
  • A file DISCOVERED by an evaluation is stamped AFTER that evaluation
    read it - nothing knew to watch it before. An edit landing in that
    window becomes the baseline and no rescan fires. It applies only
    the first time a file is seen; an already-watched file keeps its old
    stamp, which errs the safe way. Closing it needs libexpr to say
    what it is about to read, and it will not.
  • rescan() stats THIS machine. The bookkeeping and changed() are
    path-string operations and cross RPC unchanged, but a remote state's
    files are on the server, so a POLLING watcher has to share a
    filesystem with its evaluator.

One gate reaches into a private, on purpose

_forget prunes _seen, so a state living for days stops stat-ing
files no root depends on any more. That changes what the watcher
SPENDS, not what it answers: with the prune removed, every other
assertion in its test still passes, because a stamp for an
unreferenced file can never implicate a root.

So there is nothing in the public surface to hold it to, and the
choice was between reaching in and not gating it at all. Seen to fail:

assert {..inner.nix: (-1, -1)} == {}

a stamp surviving for a file that no longer exists.

What kept this OPEN

The inotify adapter. rescan() is a complete change source and needs
no dependency, so what was left was an upgrade to the NOTICING half
only - and it needed a decision rather than effort: Python has no
stdlib inotify, so it meant a new propagated dependency
(inotify-simple, watchdog) or a ctypes binding written here.
Built at the end of this file.

When it lands: watch parent DIRECTORIES, not files. Most editors save
by rename, which replaces the inode and orphans a watch on the file.

Background eager evaluation (#16) comes after, and needed this
first - re-evaluating eagerly is only useful once something knows the
old answer is stale.

2026-09-03: the adapter is decided and deferred

Two answers from Carl, and the second outranks the first.

asyncinotify, when it is built. Checked against the pinned
nixpkgs before asking, and all four candidates are packaged with no
propagated dependency but python3:

asyncinotify    4.4.4    asyncio-native, an async iterator
inotify-simple  2.0.1    sync; its fd needs wiring to the loop
watchdog        6.0.0    cross-platform, thread-based

asyncinotify wins because this layer is already async and the
adapter becomes a task that iterates events and calls changed().
watchdog buys Darwin at the cost of a thread pool nothing else here
has, and Carl ruled Darwin out: "MacOS should not be considered yet in
the project lifecycle."

It is not next. Carl, 2026-09-03: "It's most important that the
spec and codegen is correct and that all binding+wrapping details are
as consistent as they can be. There's still the primop registration
stuff, backchannels for logging and such that are more import A37B ant than
building out the full file watching code."

So rescan() stays the change source and this task waits. Recorded
here rather than left in a conversation, because the decision is the
part that would otherwise be re-argued.

Both of the things in front of it are done now, and the next section
builds it.

2026-09-03: the adapter, built

DONE. huggorm.Notifier, in packages/huggorm/huggorm/notify.py.
Seven gates in tests/test_notify.py, and the suite went from 320 to
327.

It is the third caller of Watcher.changed(), which is what the
separation in this file was for: noticing was kept apart from
bookkeeping so an inotify source would be an addition rather than a
rewrite, and it is one module that decides nothing about what a
change MEANS.

Notifier(watcher)          owns the inotify handle
  .eval_file(path)         the watcher's, plus a sync() after
  .sync()                  watch set <- watcher.watching()
  .next_change()           one event, acted on, roots answered
  .run()                   next_change() forever
  .directories()           what is watched, for a gate to read

asyncinotify 4.4.4, as decided above, added as a propagated
dependency of huggorm and to the interpreter check and test run
against.

DIRECTORIES, and the gate that says why

This file said it before anything was built: watch parent
directories, not files. A watch follows the INODE, and most editors
save by writing a temporary file and renaming it over the original -
so a file watch survives the save pointing at an inode nobody has,
and never fires again. The rename is a MOVED_TO in the PARENT.

test_a_save_by_rename_wakes_it_too does exactly that, and it
discriminates. With Mask.MOVED_TO taken out of the watch mask:

FAILED tests/test_notify.py::test_a_save_by_rename_wakes_it_too
TimeoutError
1 failed, 316 passed, 10 deselected in 44.10s

One gate. The plain-write test beside it still passed, so the rename
case is tested rather than covered by accident.

The filter, and the two gates on it

A directory watch raises an event for every file in the directory,
and a checkout holds thousands the evaluation never read. _paths
answers only the watched files an event is about, so changed() is
never called for the rest.

Replacing that with "pass every named event through":

FAILED tests/test_notify.py::test_a_save_by_rename_wakes_it_too
FAILED tests/test_notify.py::test_an_unrelated_file_wakes_nothing
AssertionError: assert [] == ['.../outer.nix']
2 failed, 315 passed, 10 deselected in 24.50s

Two, and both for the same reason: the first event to arrive is about
a file no root depends on - the editor's .tmp, or the unrelated
notes.txt - so next_change() answers [] where the root was
expected. The control was written to catch this without waiting for a
non-event, and it does.

A watch-set assertion was not a gate

test_the_virtual_entry_is_never_watched asserted that
«nix-internal» never becomes a watched directory, and that assertion
alone proves nothing. If the marker DID reach add_watch, the call
raises OSError - and sync() turns an OSError into a CHANGE on
purpose, per the section below. So the watch set comes out identical
either way.

Only the ROOT tells them apart, so the test asserts that too:
filtered, the root survives the sync; unfiltered, the sync meant to
start watching it forgets it instead, on every evaluation. With
_watchable returning everything:

FAILED tests/test_notify.py::test_the_virtual_entry_is_never_watched
AssertionError: assert [] == ['.../root.nix']
FAILED tests/test_watch.py::test_the_virtual_cache_entry_is_never_watched
7 failed, 310 passed, 10 deselected

The watch-set half passed under the perturbation, which is the point:
it was written first and it was decoration.

It is also not vacuous, which was checked rather than assumed.
Evaluating derivation on dummy:// really does put
«nix-internal»/derivation-internal.nix in cached_files, so there
is a marker for the filter to drop.

CLOSE_WRITE is not in the mask, on purpose

MODIFY fires once per write(2) and CLOSE_WRITE once per save, so
CLOSE_WRITE is the cheaper subscription. It was rejected: a writer
using mmap never closes anything, so it is also ZERO events for a
real change. Over-reporting costs a call that forgets nothing;
under-reporting is silent staleness, which is the failure this whole
task exists to prevent.

A directory that will not take a watch is a CHANGE

sync() runs after an evaluation, and by then the directory a root's
files live in may be gone. add_watch raises OSError, and the
tempting answer is to skip it - which would leave that root cached
against files that no longer exist, with nothing said. So sync()
calls changed() for every watched file under the missing directory
and returns the roots it forgot. test_a_deleted_directory_is_a_change
holds it.

rm_watch on a dropped watch is the opposite case and IS suppressed:
the watch is gone either way, and there is nothing a caller could do.

How it is gated without sleeping

Five of the seven assert on the WATCH SET, which is a pure function of
what the watcher depends on - evaluate a root, read directories().
No event and no wait.

The two that go end to end wait on the EVENT, not on the clock:
next_change() returns the moment the kernel delivers, and
anyio.fail_after is the deadline that turns a missing event into a
named failure instead of a hang. That is why next_change() and
run() are a pair - a test driving run() could only sleep and hope.

Unmarked, not live

inotify is a kernel interface rather than a daemon, so a build sandbox
has it. These run on every build.

What is left

Background eager evaluation, the last third of #553, and it
needed this: re-evaluating eagerly is only useful once something knows
the old answer is stale. #623 holds it, and the trigger is
already there - Notifier.next_change() answers the roots it forgot,
and nothing consumes that yet.

Migrated from tasks/083-nothing-decides-when-to-forget.md.done.


Assisted-By: Opus 5

Activity

  1. added
    source: huggorm
    on Oct 19, 2026
  2. transferred this issue fromnixidae/huggormon Oct 19, 2026
  3. added theissue type on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source: huggorm

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0