inotify Misses Config Reloads: 16,384-Event Overflow and Dead Watches

Dark neon cover: a queue of 16,384 event cards with a red overflow arrow and the line 10,208 of 18,400 changes dropped, a broken watch link beside a renamed file, and chips reading atomic deploy 0 / 50 and directory watch 50 / 50

The reload that never fires has two causes, and both are in the kernel’s event stream rather than in the configuration file. One is that inotify merges a burst of changes into a single event, so a watcher that counts events undercounts writes. The other is that a watch is a watch on an inode, not on a path: a deploy that writes a new file and renames it over the old one leaves the watch pointing at the file that no longer exists under that name. This page measures both, on one host, with the kernel’s own counters, and then measures a watcher that survives them.

TL;DR

  • Merging is by mask. 1,000 appends to one file arrived as 1 event under IN_MODIFY, and as 2,000 events under IN_MODIFY | IN_CLOSE_WRITE: 2 per append, never merged.
  • The queue holds the oldest, not the newest. Its 16,384 records held the cookies of the first 8,192 of 18,400 renames, counted from an origin measured before that run; the other 10,208 were dropped behind one IN_Q_OVERFLOW. The queue was full 44.5% of the way through the storm, which took 32.4 ms of wall time in all.
  • A watch on the file dies with the inode. A MODIFY-only watcher saw 0 of 50 atomic deploys and 0 of 50 ConfigMap swaps; a watcher on the directory that names the path saw every one.
  • The fix is a shape, not a timeout. Watch the naming directory as well as the file, re-add when the watch ends, and re-read the file after an overflow: 109 tests cover that shape, and the five states it moves through are checked against the twelve transitions the module allows.

1. The reload that never fires

A service reads its configuration once at start and watches the file for later edits. The first deploy writes a new file and renames it over the old one, so the path now names a different inode while the watcher still waits for a change to the one it met at start. The failure is not that the first deploy worked and later ones stopped: a watcher that acts only on IN_MODIFY and IN_CLOSE_WRITE misses atomic deploys from the first one on – 0 of 200, measured in section 6 – so the reload counter never moves, the log line that should follow a change never appears, and the process keeps serving the configuration from its first minute. Restarting the service re-adds the watch to whatever the path names now, which fixes it until the next deploy.

Two explanations fit that symptom, and the code alone cannot choose between them: either the watcher mishandles an event it receives, or the event it needs never arrives. This page separates the two by counting events at the kernel, not by reading the watcher’s own log, because a watcher that reports nothing is exactly the watcher whose log cannot settle it.

The scenario is one host, one user, one inotify instance per watcher, and no other load. The measured files live under /tmp, which this host mounts as tmpfs, and the counts that could depend on the filesystem – section 4’s burst and paced arms – were repeated on the workspace’s virtiofs with the same numbers, so the merge belongs to the kernel rather than to one filesystem. The host has 2 CPUs: every microsecond figure here compares arms measured on this host in the same run, not a budget for a production node. Table 1 records the host, and which of its limits were read from /proc rather than reached.

ReadingValueHow it was obtained
Kernel6.12.8+uname, recorded by probe 00
Python3.12.16platform, recorded by probe 00
CPUs available2os.cpu_count, recorded by probe 00
Filesystem for the measured filestmpfs/proc/mounts, probe 00
Control filesystemvirtiofs/proc/mounts, probe 00
Open files, soft limit1,024ulimit -n, probe 00
inotify instances, per user128/proc/sys/fs/inotify, read
inotify watches, per user8,192/proc/sys/fs/inotify, read
inotify queue, events16,384/proc/sys/fs/inotify, read
Table 1: the host, and whether each figure was read or reached. The three inotify budgets are read here; section 9 says which of them this run went on to reach.

Production SRE Note: A watcher that logs only what it reloads cannot distinguish “nothing changed” from “the kernel told me nothing”. Count the events at the descriptor, and compare that count with the file’s content hash. The two disagreements in this article – one event for a thousand appends, and zero events for two hundred deploys – are both invisible from the reload log alone.

2. What one read() returns

An inotify descriptor produces a stream of variable-length records. Each record begins with four native-endian 32-bit integers – watch descriptor, mask, cookie, and the length of the name that follows – and continues with the name, NUL-terminated and padded. The header is 16 bytes, which is the kernel’s struct inotify_event quoted from its definition rather than measured here; the measurement that agrees with it is the record with no name at all, which this run read as 16 bytes. The padding is what makes a record larger than the name suggests: the name field is the name plus its NUL, rounded up to a multiple of 16 bytes.

Table 2 is the measurement. A directory watch was asked for files whose names are 1, 15, 16, 31 and 32 bytes long, and the kernel’s own length field was read out of the buffer for each. The record grows at the 16-byte boundary because the name field does.

Name bytesName field bytesWhole record bytes
11632
151632
163248
313248
324864
Table 2: the record a directory watch returns, by name length. Measured by probe 09, reading the kernel’s length field out of the buffer.

A watch on the file itself returns a record with a zero-length name field: 0 name bytes and 16 bytes in total. The watch descriptor already identifies the file, so there is nothing left for the name to say. This is the first place where two watchers on the same file disagree about what an event even contains, and it is why a directory watch is required to tell a deploy’s temporary file from its target by name.

The buffer size is the reader’s choice, not the kernel’s limit. A read of 65,536 bytes returned 2,048 records and left 6,144 for a second call; a read of 1,048,576 bytes returned every queued record at once. Nothing was lost in either case – the queue held what the reader had not taken – which is the distinction section 5 depends on.

Read bufferRecords returnedBytes returnedRecords left for the next read
65,5362,04865,5366,144
1,048,5768,192262,1440
Table 3: one read against a queue holding 8,192 records. The 64 KiB figure is a convention many watchers copy; the kernel returned every queued record when asked for a larger buffer.
from __future__ import annotations
def decode(buffer: bytes) -> tuple[list[Event], int]:
    """Decode a read buffer, returning the events and how many bytes they consumed.

    A trailing record that is shorter than its own header or name field is not decoded:
    the kernel does not produce one, and silently guessing would turn a short read into a
    wrong name. The consumed count lets a caller assert the whole buffer was understood.
    """
    events: list[Event] = []
    offset = 0
    while offset + HEADER.size <= len(buffer):
        wd, mask, cookie, length = HEADER.unpack_from(buffer, offset)
        if length % NAME_ALIGN:
            raise MalformedRecord(f"name length {length} is not a multiple of {NAME_ALIGN}")
        end = offset + HEADER.size + length
        if end > len(buffer):
            break
        raw = buffer[offset + HEADER.size:end]
        name = raw.split(b"\0", 1)[0].decode("utf-8", "replace")
        events.append(Event(wd=wd, mask=mask, cookie=cookie, name=name))
        offset = end
    return events, offset
def parse_events(buffer: bytes) -> list[Event]:
    """Decode a buffer and insist that no bytes were left over."""
    events, consumed = decode(buffer)
    if consumed != len(buffer):
        raise MalformedRecord(f"{len(buffer) - consumed} trailing bytes")
    return events

The code above is the shipped file’s own text, with the imports those two functions use and nothing edited. The file’s docstring, printed with the rest of it in the appendix, carries the measured sizes of Table 2 next to the constants that apply them.

Reader note: A read returns a whole number of records or none; it never splits one. That is why the decoder can stop at the first record that does not fit instead of buffering a fragment – the kernel’s contract makes a partial record a reader bug, not a kernel behaviour.

3. Why this page writes its own bindings

The inotify interface is four libc calls away – inotify_init1, inotify_add_watch, inotify_rm_watch, read – and the appendix’s rawinotify.py is a ctypes binding to exactly those: 127 lines, no dependency, the mask constants written out so the file can be printed as the code that ran. A reader with an application to ship should not start there. Table 4 is what the three maintained libraries offer, next to the helper every probe in this page imports.

LibraryWhat it isRecursiveCoalescingWhat a caller receivesDependency
watchfilesRust’s notify crate behind Python bindingsyesin Rust, over a debounce intervalsets of (change, path)a compiled wheel
watchdogper-OS emitters on observer threadsyesno: one handler call per eventFileSystemEvent objectspure Python
inotify_simplea single-file ctypes binding, with a flag enumnonodecoded events (watch, mask, cookie, name), the overflow among thempure Python, Linux only
rawinotify.py, this pagea ctypes binding to the four callsnonoone dataclass per record: watch, mask, cookie, namenone: the standard library only
Table 4: what a watcher can be built on. The three libraries are described from their own documentation; the last row is the file in the appendix.

The two full-size libraries are the right default for an application, and neither of them can produce this page’s numbers. watchfiles groups changes in Rust before Python sees them, so a count of what it yields is a count of watchfiles‘ policy; watchdog‘s emitters translate records into their own objects – a deploy’s rename arrives as one moved event, built from two kernel records and their cookie – so a count of handler calls is not a count of records. A measurement of the kernel’s behaviour cannot have a library’s decisions inside it, which is why sections 4 and 5 count events at the descriptor itself.

inotify_simple is the nearest miss and the fair objection, and most of it lands: the same idea in one file, events carrying watch, mask, cookie and name, and flags.from_mask() already turning a mask into readable names. What separates it is a rule rather than a feature – the measured layer here was kept to the standard library – plus one thing this page needs from the record: the name length is a field in the header, the probes read it out of the raw buffer themselves, and the event the ctypes helper hands back has four fields, not five. Nor can a set of (change, path) say “the queue dropped events”: IN_Q_OVERFLOW is a record with watch descriptor -1 and no name, and it has to survive decoding to be acted on. The offset arithmetic behind Table 2 is in the file printed in the appendix, so a reader can check it without installing anything.

The state machine in section 11 is worth taking whichever binding feeds it: it repairs three failures in the kernel’s contract, all of which outlive a change of library.

4. One thousand appends, one event – or two thousand

The kernel keeps a queue, not a log. When a new event is generated, it is merged into the last event in the queue if the watch descriptor, the mask and the name are all equal; otherwise it is appended. That single rule explains every count in this section, including the two counts that look contradictory.

Table 5 is the same writer under two masks: each row appends the stated number of times with an open-write-close cycle per append, and reads only after the last append. Under IN_MODIFY alone the burst merges into one record; under IN_MODIFY | IN_CLOSE_WRITE the two masks alternate, no two adjacent records are equal, and nothing merges.

Appends, one fileIN_MODIFY eventsIN_MODIFY | IN_CLOSE_WRITE events
112
10120
1001200
1,00012,000
Table 5: appends against events, by mask. Three runs per row produced identical counts; the writer opened, appended and closed once per iteration.

Two details decide whether a watcher sees one event or many, and neither is a timeout. The first is whether the writer keeps the descriptor open. With one descriptor held open for the whole run, 1,000 writes produced 1 IN_MODIFY event, and the same writes produced 2 events under the wider mask – one merged IN_MODIFY and one IN_CLOSE_WRITE at the close. An application that appends through a held descriptor and an application that appends by opening the file each time are not the same event source, even when they write the same bytes.

The second is whether the changes alternate between files. Writes to two files in turn, 200 appends in all, produced 200 IN_MODIFY events – one per append, because consecutive events carry different watch descriptors and cannot merge. A watcher that reloads on every event therefore pays once per file touched, not once per burst.

The reader’s cadence is the third lever, and it is the one a watcher controls. Table 6 drains the same 100 appends every write, every ten writes and every fifty writes. Draining after each write leaves 100 events. Draining every ten leaves 10: each window of ten merges into one. The writes did not change; only the moment of reading did.

Drain cadenceWindowEvents for 100 appends
after every write1 write100
every tenth write10 writes10
every fiftieth write50 writes2
Table 6: the same 100 appends, read at three cadences, with IN_MODIFY only. A reader that wakes late sees one event per window, not one per write.

What coalescing does not do is delay. With a reader already waiting on the descriptor, an append became readable in 2.3 microseconds at the median and 2.4 at the 95th percentile under the narrow mask; under the wide mask the figures were 2.4 and 2.7 microseconds. Merging happens in the queue behind the reader, not in front of it: the first event of a burst is delivered immediately, and the merges apply to events that arrive before the reader has taken them.

MaskMedian, microseconds95th percentileMaximum
IN_MODIFY2.32.419.1
IN_MODIFY | IN_CLOSE_WRITE2.42.76.8
Table 7: append to readable event, 200 trials per mask, measured from the start of the append to the read returning. On this page’s two-CPU host the pair is a comparison of the two masks, not a latency budget for a production one.

For a watcher, the three levers add up to one conclusion: the number of events is not the number of changes, and no mask makes it so. A reload policy has to be built on a time window, not on an event count, and that is what the debouncer below does. Its two deadlines – a quiet window and a hold limit – cover the two shapes of a burst: one that stops and one that never does.

from __future__ import annotations
def note(self, now: float | None = None) -> None:
    """Record one change. DUE becomes ARMED again: the pending decision is stale."""
    moment = self.clock() if now is None else now
    if self.state is not DebounceState.ARMED:
        self._move(DebounceState.ARMED)
        self._first = moment
    self._last = moment

The method above is the coalescing repair: the first event of a burst is recorded with its clock reading, every later event moves only the quiet deadline, and an event that arrives while the decision is pending goes back to ARMED rather than being dropped. Its other half – the method that decides when the burst is over – is three branches and is printed with the rest of the class in the appendix.

Three states and six transitions are behind those two methods, and section 11 counts them against the guards. The property that matters here is the docstring’s: a change that arrives while a decision is pending starts a new burst rather than being dropped. A debouncer that loses the last write of a burst is the same bug as a watcher that never fires, one window later.

5. The queue is 16,384 events, and it keeps the old ones

A reader that stops reading does not stop the kernel from producing events. The events accumulate in the instance’s queue, and when the queue is full the kernel drops the new events and sets IN_Q_OVERFLOW on the record that follows. This run filled the queue deliberately: 9,200 iterations of a two-rename cycle – a file renamed to a temporary name and back – with no read until the loop finished, so 18,400 renames, each one a MOVED_FROM and a MOVED_TO, and 36,800 events.

The read afterwards returned 16,384 events and one overflow record: the capacity is exactly the value in /proc/sys/fs/inotify/max_queued_events, so the number the kernel advertises is the number the queue held.

ReadingValue
Renames attempted18,400
Events those renames generate36,800
Cookies the queue kept90,280 – 98,471
Renames those cookies are, after the origin1 – 8,192
Records the queue held16,384
Overflow records1
Records returned by the drain16,385
Renames whose events were lost10,208
Share of the changes kept44.5%
Wall time for all 18,400 renames (the storm)32.4 ms
Queue full, at the rate of that storm14.4 ms
Records read by the drained arm36,800
Table 8: the queue under a rename storm, with and without a reader. Probe 02; the drained arm produced no overflow record at all. The two time rows are not the same measurement: the first is the loop’s, the second is the queue’s share of it. The cookie rows are the direct evidence: the origin is the cookie of one rename performed and read before that run.

The cookie range is the evidence, not an inference from a count. Each arm measures its own origin: a file is moved aside and back, and both renames are drained before that arm’s loop, which fixes the counter’s position at that moment, and the loop’s first rename is the cookie after it. The first of the three fills began at cookie 90,279; the drained arm shows the ordering that makes an origin usable – its 18,400 renames arrived as cookies 145,486 to 163,885, one per rename, contiguous, none missing.

An origin measured once and reused across the three fills would have been cheaper to record, and wrong. The origin is a position on a counter that the storm itself advances, so with the first arm’s origin the second fill would read as renames 18,403 – 26,594 and the third as 36,805 – 44,996 – each window shifted by one loop’s 18,400 renames plus the 2 the next arm’s baseline spends before it starts – positions on the counter rather than anything about the queue, which in every fill keeps the first 8,192 renames of its own loop. Probe 02 therefore measures an origin immediately before each arm, and the three windows it records are 1 – 8,192 three times over, from origins 90,279, 108,681 and 127,083.

The queue that overflowed kept cookies 90,280 to 98,471: contiguous, 8,192 of them, starting exactly one above the origin and ending exactly 8,192 above it. Those cookies are renames 1 to 8,192 after the origin, so the queue kept the first 8,192 changes and dropped the 10,208 that came after them – not a sample of them, not an arbitrary block. A watcher that drains an overflowed queue and applies what it reads is applying the state from before the deploys it was asked about.

Only one of the two times in Table 8 is a stopwatch reading, and it is not the queue’s. The 32.4 ms is the loop’s wall time: 9,200 iterations of two renames each, from the first rename to the last rename – the drain that follows is outside the stopwatch. The queue had no room left at the 8,192th rename – 44.5% of the way through the loop – and the remaining 18 ms is the loop still renaming while the kernel refuses what it produces. The 14.4 ms beside it is that share of the wall time, at the rate the same run generated events: 36,800 events in 32.4 ms, 1,135,802 events per second. So the queue bought under half of the storm, and less than half of the wall time that figure suggests.

Both are samples, and the page treats them as samples. Three consecutive runs of the same loop took 28.9 ms to 32.4 ms, and a run measured on this host under a different load can sit well outside that band, because the loop is doing path lookups on a host that is also running everything else here. The 32.4 ms in Table 8 is the first of the three, not a property of the queue and not a constant.

The queue’s capacity in records, in reads, and in time

One record for a one-byte name is 32 bytes, so the conventional 65,536-byte read returns 2,048 records. The queue’s 16,384 records are exactly 8 such reads. That is why a service that reads once per tick and does work per record can fall behind a producer by a factor of thousands: the producer writes records at the speed of the filesystem, and the consumer’s own per-record work is what limits the drain.

The same queue at the storm’s rate: 36,800 events in 32.4 ms is 1,135,802 events per second, so the 16,384 records are 14.4 ms of work at that rate – a shock absorber for a burst, not a backlog.

With a reader draining every 250 iterations, the same loop produced 36,800 records and no overflow, over 18,400 renames. Slow readers are not the problem; readers that stop are.

The operational rule that follows is not “drain faster”. It is that an overflow destroys the mapping from events to changes, and the only trustworthy recovery is to re-read the files the watcher cares about. The reloader below does exactly that: an overflow moves it to a resynchronisation state where it re-arms the watch and compares the file’s content, rather than pretending the surviving events describe the present.

from __future__ import annotations
from .events import Event
def handle_events(self, events: list[Event]) -> State:
    """Feed one read's worth of events through the guards and the debouncer."""
    if self.state is State.IDLE or self.watch is None:
        return self.state
    if any(event.is_overflow for event in events):
        self._move(State.RESYNC, "queue overflow")
        return self.state
    if any(self.watch.owns(event) and event.ends_watch for event in events):
        self._move(State.RESYNC, "watch ended")
        return self.state
    if any(self.watch.matches(event) for event in events):
        self.debouncer.note()
        if self.state is not State.DEBOUNCING:
            self._move(State.DEBOUNCING, "change")
    return self.state

The guards are ordered, and the order is the argument. An overflow is checked first because it invalidates every other event in the same read: the events that survived are older than the overflow, and acting on them before resynchronising would apply a state that the queue itself has already superseded. A watch that ended is checked second, because re-adding it is a precondition for any later event to mean anything. Only then is a matching change allowed to start a debounce.

A single read can carry both failures at once, and the reloader answers them once: the overflow record has no watch descriptor of its own – the kernel reports it against -1 – so it cannot be attributed to a path, and the resync that follows re-arms the watch with the same refresh. That is why the order is overflow, watch, change rather than watch first.

Production SRE Note: If the queue overflows while the configuration is being written, the content on disk is still the truth. Re-read it, hash it, and reload if the hash changed – do not attempt to reconstruct the change from the events that survived, because the ones that would have described it are the ones that were dropped.

6. A rename replaces the inode, and the watch dies with it

An atomic deploy writes a complete file under a temporary name and renames it over the target. The path keeps its name and its permissions; the inode behind the path is a new one. A watch added by path was added to the old inode, and the kernel reports what happened to that inode, not to the name: an IN_ATTRIB, then IN_DELETE_SELF, then IN_IGNORED, after which the watch is gone and the descriptor has nothing left to report.

Table 9 is three watchers against the same 200 deploys. The naive one acts on IN_MODIFY and IN_CLOSE_WRITE and ignores everything else: it saw 0 reloads, because the three lifecycle records arrived once on the first deploy and then the watch was dead, and a write to the path afterwards produced 0 events. The second handles those three masks by adding the watch again on the path: 200 of 200, with 200 re-arms, at a median of 24.3 microseconds from the rename to the event being read. The third never watches the file – it watches the directory and matches the target’s name on IN_MOVED_TO – and saw 200 of 200, at a median of 43 microseconds.

WatcherDeploys seenMissedLatency, medianLatency, 95th percentile
MODIFY and CLOSE_WRITE only0200nonenone
Re-add on DELETE_SELF / IGNORED200024.359.9
Watch the naming directory20004350.6
Table 9: three watchers, 200 atomic deploys each. Probe 03; latency is microseconds from the rename returning to the watcher having read the event.

The directory watcher’s count is larger than its reload count for a reason worth seeing: it received 800 events for 200 deploys. Each deploy produced a MODIFY and a CLOSE_WRITE for the temporary file, then a MOVED_FROM for that temporary name and a MOVED_TO for the target. A directory watcher must filter by name, or it will reload on its own deploy’s staging file.

The naive watcher in Table 9 is three things and nothing else: one add_watch, a loop that acts on two masks, and no branch for the mask that says the watch ended. It is the program anybody writes first, which is why the table records a shape rather than a bug in someone’s careful code.

The re-arm is PathWatch.refresh(), printed with the class in the appendix, and two conditions make it correct rather than merely present. The identity it compares is the pair of device and inode, not the inode alone, because a container mount can change the device under a path that keeps its inode number. And it returns whether anything changed, so the caller can treat a deploy as a reason to reload even when the file’s content is identical – a deploy that changes nothing in the file is still a deploy whose watch moved.

The permanent failure: A watcher that treats IN_IGNORED as noise has, by construction, no code path that re-adds a watch. That is why the failure is permanent rather than intermittent: the first atomic deploy removes the watch and no later code will ever put it back.

7. The ConfigMap swap: a watch on an inode that is no longer the path

Kubernetes publishes a ConfigMap as a chain of symbolic links: app.conf points at ..data/app.conf, and ..data points at a timestamped directory that is replaced on each update. The layout is documented by the project; this article does not run kubelet. It reproduces the layout in a local directory – two symlinks, a timestamped target, and an update that creates a new target, renames a new ..data over the old one, and then removes the directory the old link selected, which is the last step of kubelet’s AtomicWriter – and measures what five watchers see. The probe is 04_symlink.py, printed whole in the appendix; the cleanup is the shutil.rmtree at the end of its update(), so the step this table rests on can be read rather than taken on trust.

The watch added on the path follows the symlink when it is added. It therefore watches the file in the timestamped directory that existed at that moment. The update does not write that file; it changes which directory the name resolves to, and the cleanup then deletes the file the watch is on. So the only records that watcher receives across 50 updates are about its own removal, and they arrive in the first one: an ATTRIB for the link count the unlink changed, DELETE_SELF for the file, and IGNORED as the kernel drops the watch. None of them describes the update that had just been published.

WatcherUpdates seenMissedDetection latencyWhat the cleanup delivers
app.conf, watched by path050neverATTRIB, DELETE_SELF, IGNORED, once
app.conf, re-added on DELETE_SELF500123.6 µs medianre-armed on the path, read the new version
..data, watched by path050neverDELETE, DELETE_SELF, IGNORED, once
config directory, name ..data50074.7 µs mediana DELETE for the old directory’s name, ignored by the name rule
stat the path every 50 ms50049.5 ms medianno event at all – the inode changes
Table 10: probe 04 (04_symlink.py), five watchers against 50 ConfigMap-style updates, each one ending with kubelet’s cleanup. An update counts as seen when a change to its content reached the watcher; “never” is the latency of an event that cannot arrive. The last column is the cleanup’s own record, which is not a reload. Latency for the inotify watchers is microseconds; for the poller it is the time until the next check, which is why the median sits just under the interval.

The directory watcher saw 250 events and reloaded 50 times, every one with the version that had just been deployed: 50 of 50 reads matched. The records were 100 CREATE events – a timestamped directory and a ..data_tmp symlink on each update – 50 MOVED_FROM / MOVED_TO pairs for the ..data rename, and 50 DELETE events as the old directory was removed. The watcher’s rule is a name match: any MOVED_TO whose name is ..data means the path may now resolve somewhere else. The same watch also reports the staging link and the cleanup, which is why the rule is a name and not a count.

The name rule is a few lines of set building in PathWatch.names(), printed with the class in the appendix: the path’s own name covers an atomic deploy, and the first component of the symlink target – ..data – covers the swap that never touches the file the path names. It is sufficient only because the class holds two descriptors and re-arms them together; a name match on a watch that has already died matches nothing.

Re-adding the file watch when it ends is the second row, and it is the shape a service that already watches a file is closest to: 50 re-arms over 50 updates, 50 of 50 reads with the correct version, at a median of 123.6 microseconds from the swap. It survives a real ConfigMap mount because the cleanup is the last step of the same update: by the time DELETE_SELF is read, ..data already points at the new directory, so resolving the path again lands the watch on the new file. It is still the second-best answer because that is a dependency rather than a rule: a publisher that keeps its old directory leaves the watch alive on a stale file, and one that removes the directory before the rename leaves the path dangling, so the re-add fails with ENOENT. The directory watch depends on nothing but the name of the link.

The polling watcher is the honest comparison. It saw every update at a median of 49.5 ms: detection is bounded by the interval, and the interval is paid in wakeups whether anything changed or not. A 50-millisecond poll is a reasonable floor for a configuration file, and it is what a watcher should fall back to when its event source cannot see a change – its second mechanism, not its only one.

That fallback’s cost was measured separately (probe 10), because a poll’s price is easy to assert and easy to get wrong. One stat of the path is 1.01 microseconds at the median over 2,000 calls. A hundred checks at the 50-millisecond interval took 5,017 ms of wall time and 8.6 ms of CPU, against 6.8 ms for a hundred blocked inotify waits given the same timeout: the CPU is not where a poll loses, since most of both figures is the interpreter’s own sleep and wake. The wakeups are: either ticking arm woke 100 times over that span, while one wait with no ticker woke once and spent 0.26 ms of CPU. On a host running many such services that is the difference between sleeping until needed and running a timer for life.

Why a file watch alone is a dependency, not a rule

The path config/app.conf is a symlink. inotify_add_watch resolves it once, at add time; nothing in the interface reports that the chain now resolves elsewhere. What a watch on that file can deliver is about the file: its own modification, and its deletion when the directory holding it is removed. That deletion is the cleanup of the old version, not an announcement of the new one, and it only arrives if the publisher deletes the directory at all. No mask makes a file watch follow a path: the kernel watches objects, and the atomic rename of section 6 is the same case – the replaced object reports its own deletion, and only the directory knows what replaced it.

What the re-add of Table 10’s second row buys is a bet on the publisher’s order – the cleanup must come after the swap – while the directory watch needs nothing but the name the link is renamed to. That watch costs one descriptor and a name comparison; not having it costs 0 content-change events out of 50 updates: no MODIFY, no CLOSE_WRITE, no error, and no log line.

Production SRE Note: A reload watcher for a Kubernetes volume should treat ..data as part of the configuration’s name. The path the application opens is stable; the object behind it is not, and the only inotify event that describes an update is the rename of the link that selects it.

8. Directories are not recursive

There is no recursive watch. A watch on a directory reports events for the directory’s own children and one CREATE with IN_ISDIR when a child directory appears; it reports nothing that happens inside that child. For a configuration tree – conf.d, a directory of includes, a package copied in at deploy time – that difference is the whole problem.

Table 11 uses a tree of 22 directories holding 1,000 files – the root, 20 subdirectories with 50 files each, and one directory the probe’s first arm created. A single watch on the root saw 0 events when a file inside an existing subdirectory was written, and 1 event when a new subdirectory was created – the CREATE with ISDIR, which names the directory but says nothing about its contents. A file then written inside that new directory produced 0 events.

WatcherWatchesFile in existing subdirNew subdir itselfFile in the new subdir
One watch on the root1010
One watch per directory22310
Table 11: a tree of 22 directories and 1,000 files. The recursive watcher cost 0.65 ms to build. Probe 05.

The walk is cheap: 22 directories watched in 0.65 ms, one os.walk pass with an add_watch per directory, printed with the rest of the module in the appendix. What needs code is the directory that appears later, because a package copied in arrives with its files already written, and a watch reports nothing that happened before it existed – so the order is part of the algorithm: add the watch first, then read the directory.

from __future__ import annotations
import os
from pathlib import Path
def snapshot(directory: str | Path) -> list[Path]:
    """Everything inside a directory at the moment its watch was added.

    Read after ``add_watch``, never before: a watch reports only what happens after it
    exists, so the entries written before it are exactly the ones this scan has to find.
    An entry written during the scan is reported twice - here, and by the fresh watch -
    and a caller that compares content pays nothing for that.
    """
    try:
        with os.scandir(directory) as entries:
            return sorted(Path(entry.path) for entry in entries)
    except FileNotFoundError:
        return []

Everything the watch could not have seen is in that read, and everything written after it arrives as an event, so the two reports overlap instead of leaving a hole. The caller gets both – the directories covered, and the entries already inside them that must be read rather than waited for. A test drives the order: a file written before the call is reported by the scan and produces no event, and a file written after it produces the event.

Both functions keep one rule about links: a symbolic link to a directory is not followed. A link back to an ancestor would make the walk endless, and a watch added through a link covers the target, whose events would then arrive under two paths – so a link is reported as an entry to read, not as a directory to cover. The skip list is the same judgement: a .git or __pycache__ directory is one whose events no configuration reloader wants.

9. Three budgets: 128 instances, 8,192 watches, 16,384 events

inotify spends three things, counted in three different units. An instance is one descriptor from inotify_init1; a watch is one descriptor per distinct inode, created by inotify_add_watch; the queue is a count of events per instance. Two of the budgets are per user, not per process, which makes them a capacity question for a service and a shared resource for everything else running as the same user.

This run spent the instance budget in full: 128 descriptors were created, and the next call failed with EMFILE – “Too many open files”, errno 24 – in 0.41 ms. The watch budget was read as 8,192 and taken to 1,024 before being released. That is a deliberate limit of this measurement: the watch count is shared by every process of the user, and spending all of it would stop any other process of that user from adding a watch while the probe held it. Table 12 records read and reached as separate columns rather than merging them.

BudgetRead from /procReached in this runWhat the failure looks like
Instances, per user128128EMFILE on the next inotify_init1
Watches, per user8,1921,024 (released)ENOSPC on the next inotify_add_watch
Queue, events per instance16,38416,384IN_Q_OVERFLOW after the queue fills
Table 12: the three budgets. The instance and queue figures were reached; the watch figure was read and released at 1,024 of 8,192.

The watch budget’s arithmetic matters when sizing a watch tree: 8,192 watches is 8 times the 1,024 this probe spent, and a recursive watch of a large source tree can exhaust it. That is what ENOSPC from inotify_add_watch means – not “no space on disk”, but “this user’s watch budget is spent” – and a watcher that reports it as a disk error sends its operator looking in the wrong place.

None of the three is a duration: an event count, an inode count and a descriptor count cannot be compared with a timeout.

For a service, the practical reading of Table 12 is a capacity plan first: one instance per watcher, one directory watch and one file watch per watched path, and a tree walk whose watch count is the number of directories. Those three figures belong in the start-up log. The queue is the one of the three with a knob on it, and section 10 is about what turning that knob buys.

Production SRE Note: Log the watch count and the instance count at start, and log ENOSPC from add_watch as a capacity event rather than an I/O error. The same call means “this inode is gone” when it returns ENOENT and “this user has spent the watch budget” when it returns ENOSPC; a service that treats both as fatal has made a deploy and a capacity limit indistinguishable.

10. Raising the queue: what sysctl buys, and what it does not

The queue is the one budget with a tuning knob, and the knob is a file. Its ceiling is fs.inotify.max_queued_events – the 16,384 records of Table 12 – and it is raised for the running kernel with sysctl -w fs.inotify.max_queued_events=65536, or by writing the same number into the proc file, and made to survive a reboot by one line in /etc/sysctl.d/inotify.conf – fs.inotify.max_queued_events = 65536 – applied by sysctl --system at boot.

Neither of those is something this run could do, and probe 11 is the record of that. The probe read the value in force from the proc file and then attempted the write, which the kernel refused with EACCES, errno 13: the file is owned by root and writable only by it, and uid 1,000 is not root. That read is the only check this page ran; no write reached the file, so the host’s setting is unchanged. The sysctl binary is present at /usr/sbin/sysctl and not on this user’s PATH, and /etc/sysctl.d does not exist here – so the persistence line above is the distribution convention, not a step this page ran. What follows is priced from Table 8’s measurement rather than from a second run.

Table 13 is that price. Raising the ceiling four times – from 16,384 records to 65,536 – buys four times the events before a storm of the same shape overflows, and costs four times the memory while the queue is full. The time column is the queue’s fill time at the rate section 5 measured: 14.4 ms for the default and 57.7 ms for the raised ceiling, which at that rate is full at the 32,768th rename. The 32.4 ms of wall time in Table 8 is a different figure: the measured 18,400-rename storm’s own loop, and that storm leaves the raised queue 56.2% occupied – 36,800 records written into 65,536. The memory column is arithmetic on the record this page measured for a one-byte name, so it is a floor: the kernel’s own per-event overhead sits on top of it. Nothing here was re-run with the raised ceiling, and the rate itself varies with host load, so the honest reading of the second row is a multiple, not a promise.

Ceiling, recordsQueue full at the measured rateMemory while fullWhat changes
16,38414.4 ms0.5 MiBthe default; section 5’s storm fills it 44.5% of the way in
65,53657.7 ms2.0 MiBfour times the events and four times the time; the same storm is 56.2% of it
Table 13: the queue’s ceiling at two settings. The time column is the queue’s fill time at the rate Table 8 measured; the storm’s own wall time is longer, and the default queue is full part-way through it. The second row is the first multiplied by four, not a second run – and the fill time it multiplies is one sample of three, so the second row is a multiple of this host’s fill time rather than a constant. A host whose events arrive slower moves both rows together.

What the knob buys is a longer deadline, and that is all it buys. At the storm’s rate the window goes from 14.4 ms to 57.7 ms; a reader that stopped for a second is still stopped, and the records that would have described the change are still the ones the queue drops, in the same order, with the same single IN_Q_OVERFLOW to say so. The repair does not change: re-read the file and compare its content, which is what the reloader in section 11 does after every overflow.

Two operational notes go with it. The ceiling is per instance, so a process that opens an instance per connection multiplies the memory column instead of raising it. And the setting is not namespaced: in Kubernetes fs.inotify.* is a node-level sysctl, so it belongs in the node image or a privileged DaemonSet, not in a pod’s securityContext, which can carry only namespaced sysctls.

Two file systems are outside what this page measured, and both break the assumptions above in ways this probe did not run. On NFS, a write made by another client is applied on the server; the local kernel never sees the change in its own VFS, so no local inotify watch fires – the directory watch is no defence there, and the fallback is a poll or the server’s own change notification. In a container, overlayfs copies a lower-layer file up to the upper layer on its first write, and what a watch on the merged path sees across that copy-up depends on the kernel and the overlayfs implementation: current kernels route the event to the overlay inode, which the copy-up preserves, while older kernels and some configurations allocate a new inode and a watch added before the copy-up goes silent – the kernel’s history has repeated fixes in exactly this area. A watch added to the lower or upper directory directly, rather than to the merged path, sees only that layer’s events. So do not carry the ext4 and tmpfs assumptions of this page into a container layer: watch the merged path and verify on the kernel you deploy to. Neither file system was run here – the ones this page measured are the host’s own, named in section 1 – so both are documented behaviour, not numbers from this page.

Production SRE Note: Raise the ceiling when a burst has already been seen to cross it, and keep the resync. The value in /proc/sys/fs/inotify/max_queued_events is what the running kernel enforces, so log it at start next to the watch count – a host whose ceiling was raised last year and a host that was reinstalled from an image without it look identical from inside the process until the first overflow.

11. The design that survives: five states and twelve transitions

The measurements so far describe three ways to lose a change, each with a different repair. Coalescing loses nothing – the file’s content is still the truth – so the repair is a time window. A watch that ends because its inode was replaced needs the watch re-added, to whatever the path now names. An overflow needs a fresh read, because the events that would have described the change were dropped. The reloader below puts those three repairs in one state machine, and its first watch is the directory that names the path, not the file alone.

Table 14 is the machine: 5 states and 12 distinct transitions, written one row per event that drives them. Their (from, to) pairs are the constant in the module, and the tests assert that every transition the code records is in it – so a later edit cannot add a sixth state or a shortcut that skips the re-arm without failing a test.

FromEventToWhy
IDLEstart()ARMEDinstance and both watches exist
ARMEDmatching changeDEBOUNCINGa burst of writes is being collected
ARMEDwatch endedRESYNCthe inode behind the path was replaced
ARMEDoverflowRESYNCthe queue dropped events for every path
DEBOUNCINGwindow closedRELOADINGthe quiet window or hold limit passed
DEBOUNCINGoverflowRESYNCthe queue dropped events for every path
DEBOUNCINGwatch endedRESYNCthe deploy renamed over the file mid-window
RELOADINGcontent readARMEDreloaded, or content was unchanged
RELOADINGread failedRESYNCthe path was missing during the deploy
RELOADINGcallback raisedRESYNCthe new content was rejected, and retried
RELOADINGre-arm failedRESYNCadd_watch refused: ENOSPC, or a dead fd
RELOADINGstop() in the callbackIDLEthe callback shut the reloader down
RESYNCre-arm and readARMEDthe content after the deploy is the truth
ARMEDstop()IDLEthe descriptor is closed
DEBOUNCINGstop()IDLEa pending burst is dropped, not fired
RESYNCstop()IDLEthe descriptor is closed
Table 14: every event path the module allows, one row per event, so the rows outnumber the 12 distinct (from, to) pairs: three pairs are reached by more than one event – a watch that ended and an overflow both land in RESYNC, and so do a read that fails, a callback that raises and a re-arm the kernel refuses. A RESYNC that cannot read the file – missing, or raising EIO – or whose re-arm is refused, stays in RESYNC and retries on the next tick – the state persisting, not a transition – so it has no row.

RELOADING is the state that needs saying out loud. The machine enters it and leaves it inside one tick(): the read, the re-arm and the callback happen before that call returns, so a caller never observes the state and no event can arrive while it is set. That is why no overflow row leaves it – an overflow is read from the descriptor, and a reload in progress is not reading one – while a failed read, a callback that raises and a callback that calls stop() each do, because all three happen inside that same call. So does a re-arm the kernel refuses, and that one is the reason the state is safe to leave for RESYNC rather than a corner to sit in: add_watch answers ENOSPC when this uid’s watch budget is spent, and a watcher that recorded the refusal and stayed in RELOADING would never re-arm, because no later tick visits the state. The docstring at the top of reloader.py carries the same sixteen lines, and a test parses them, compares their pairs with the constant, and counts the pairs that carry more than one event – three.

The recovery itself is _resync(), printed with the class in the appendix. It refreshes the watch before reading, so the descriptor follows the new inode; without that, the recovery would reload once and then be blind again. It compares content rather than trusting the reason, so a resync after an overflow where the file did not change produces no callback, and the reason is logged either way. A read that fails inside a resync – a mount that has gone away raises EIO instead of answering None – is recorded as a failed read and retried on the next tick: the state stays RESYNC, and the exception never reaches the loop that called tick().

Table 15 is the design against the three deploy shapes, next to the naive watcher of section 6, with 50 deploys per cell, all of it measured by probe 07 (07_endtoend.py, printed in the appendix). A reload counts only when the callback received the version that had just been deployed, so a watcher cannot pass by firing on a stale read. The reloader ran at two windows, each with a hold limit of 0.2 s: 0.0 s for the first latency column, which is what the callback costs with no quiet window in front of it, and the 0.05 s window step 3 of the deploy order prescribes for the second. The symlink-swap cell carries kubelet’s cleanup inside the deploy – the previous timestamped directory is removed after the swap, as section 7’s layout does – so the file watch ends on every deploy there: every one of its 50 reloads arrives from RESYNC, and atomic replace delivers 49 of 50 the same way. For both shapes the re-arm is the normal path rather than a fallback. Because that path never opens a window, a run of atomic deploys is reloaded as each new inode is noticed, one reload after another, rather than once per quiet window – which is intended rather than a gap: every one of those reads takes whatever the path names at that moment, so the worst case is two deploys landing inside one turn and sharing a single reload that still ends at the newest content, and the extra callbacks cost time, not correctness.

The two latency columns are one reloader on the same deploys, and the distance between them is the distance between a change and a deploy. An in-place write produces MODIFY and CLOSE_WRITE, so the callback waits out the quiet window: 43.2 µs at 0.0 s becomes 51.4 ms at 0.05 s, which is the window plus the read and the callback. A deploy that replaces the inode gives the window nothing to collect – the watch ends first – and _resync() re-arms and reads on the tick that notices it without ever consulting the debouncer, so the re-armed atomic deploys stay at 100.8 µs and the symlink swap at 146.7 µs with the window set. The exception is the single atomic deploy that arrived as a change rather than as a re-arm, which the per-state count is there to show: it took 196.7 µs at 0.0 s and 51,256.0 µs at 0.05 s, because once a window is open it is a change like any other. So the window buys burst coalescing at a cost that lands only on the shapes that report a change, and a watcher whose recovery is a re-arm never pays it.

That 51,381.3 µs is not the window plus an unexplained remainder. Take the 0.05 s window off it and two costs are left: 43.2 µs of read and callback, which is what the same deploy pays with no window in front of it at all, and 1.34 ms of the probe’s own loop, which advances the reloader once per run_once call of 5 ms and so can find the window closed as much as one turn after it closed – across the 50 deploys the overshoot past the window was 1.38 ms at the median and 4.64 ms at the worst, both inside a single 5 ms turn. The window is therefore the measurable part of that figure and the loop is the granularity the measurement inherits from its own caller, not a property of the reloader.

ShapeNaive seenReloader seenCorrectMedian at 0 sMedian at 50 msvia RESYNC
In-place write50 / 5050 / 505043.2 µs51,381.3 µs0
Atomic replace0 / 5050 / 5050107.6 µs101.5 µs49
Symlink swap + cleanup0 / 5050 / 5050143.5 µs146.7 µs50
Table 15: two designs, three deploy shapes, 50 deploys each, measured by probe 07 (07_endtoend.py). Each seen column is the reloads out of those deploys; Correct counts the callbacks whose content was the version just deployed; the latency columns are medians at a quiet window of 0.0 s and 0.05 s, both with a hold limit of 0.2 s; via RESYNC is how many of the reloader’s reloads arrived from that state. The ConfigMap row includes kubelet’s cleanup after each swap, so its reloads arrive through the re-arm rather than the change window – and the one atomic deploy that arrived through the change window instead took 51,256.0 µs at 0.05 s, one sample against its neighbours’ 100.8 µs.

The last case in this article is the one that has no event to point at. One configuration change was written, and then 18,400 renames in the same directory generated 36,800 events in 44 ms, filling the queue and overflowing it. That figure and section 5’s 32.4 ms are the same 18,400 renames measured by two probes in separate runs – probe 07 runs a reloader beside the loop, probe 02 renames and nothing else – and neither wall time is a constant: probe 02’s three consecutive runs of that loop took 28.9 ms to 32.4 ms, so the figure quoted here is the host’s, not a property of the queue. The naive watcher has no path from that state to a reload; the reloader went to resynchronisation, read the file, saw the new version, called the callback once with the correct content, and returned to ARMED.

The unit suite is 109 tests in 6 files: the record decoder’s malformed inputs, the debouncer’s six transitions against a fake clock, the descriptor wrapper’s error translation, the path watch’s re-arm, the tree walk’s refusal to follow links, and the reloader’s five states against real deploys – atomic replace, symlink swap, a burst that must reload once, an injected overflow, an overflow that arrives with the watch’s own DELETE_SELF in the same read, a failing callback that is retried, one that stops the reloader, an ENOSPC from the re-arm that must reach RESYNC and reload on the next tick, and an EIO from a read taken during a resync, which must stay in RESYNC rather than escape the tick and must recover on the one after it.

Production SRE Note: The design rule is one sentence: a watcher must be able to recover a state it cannot observe. The overflow removes the observation, the rename removes the watch, and the debounce removes the individual change from view – in all three cases the file’s content is the state, and the watcher’s job is to reach it rather than to reconstruct it.

12. Deploy order and the check that proves it

Each step below is verified by a number from this article, and the order matters because each step makes the next one meaningful. Doing them in this order gives every change a before and an after on the same host, rather than a set of settings adopted on faith.

  1. Watch the directory that names the path, not only the file. One directory watch per watched path, plus one watch on the resolved file. Section 6 measured 200 of 200 atomic deploys caught by the directory watch against 0 of 200 for the file-only watcher; the directory is what makes an atomic rename visible at all.
  2. Re-add the watch whenever it ends. Treat IN_DELETE_SELF, IN_MOVE_SELF and IN_IGNORED as one signal and re-add on the path after every one. Section 6 measured 200 re-arms across 200 deploys at a median of 24.3 microseconds, and zero misses.
  3. Debounce on a monotonic clock, with a hold limit. A quiet window of a few tens of milliseconds turns a burst into one reload – 10 events for 100 appends when the reader drains every ten – and the hold limit keeps a stream that never goes quiet from postponing the reload forever. Table 15’s second latency column is what the window costs: an in-place write waits it out, while a deploy that ends the watch is reloaded by the re-arm without entering it.
  4. Re-read the file after any overflow. The queue keeps the oldest events and drops the newest, so the surviving events describe a state older than the one that overflowed: 10,208 of 18,400 changes were lost in section 5’s storm. Re-arm, read, compare content, and log that a resync happened. Raising max_queued_events moves that deadline fourfold at four times the memory and removes none of the need for the read.
  5. Cover the tree with one watch per directory, and add new directories on CREATE with IN_ISDIR, reading each one after its watch is added. A root-only watch saw 0 events for a file inside an existing subdirectory; the recursive watcher covered 22 directories in 0.65 ms.
  6. Verify with content, not with events. Deploy the same version twice and check that the second deploy produces no reload; deploy a new version through each of the three shapes and check that the callback receives it. Section 11’s Table 15 is the shape of that test, and 109 unit tests are the version of it that runs in CI.

The check at the end is deliberately anticlimactic: after a deploy, the watcher’s log should show the reason, the number of arms, and the content hash it loaded. A watcher that logs only “reloaded” cannot answer an incident’s first question – whether the reload happened at all – which is where this page started.

Frequently asked questions

Why does my inotify watcher stop after a deploy?

Because the deploy replaced the inode the watch was added to. The kernel sends IN_DELETE_SELF and IN_IGNORED for the old inode and removes the watch, and a write to the path afterwards produces no event: this run measured 0 events across 200 atomic deploys. The fix is to re-add the watch when either mask arrives.

Does IN_CLOSE_WRITE double the number of events?

It doubles the number of records for an append, not for a held descriptor. 1,000 open-append-close cycles produced 2,000 records under IN_MODIFY | IN_CLOSE_WRITE and 1 under IN_MODIFY, because the two masks alternate and only adjacent identical records merge.

Why did a thousand writes produce one event?

Because nobody read the queue while they happened. The kernel merges a new record into the last one when the watch descriptor, mask and name are equal: 1,000 appends to one file arrived as 1 record in three separate runs. Coalescing is a property of the queue, not a delay.

What is lost when the inotify queue overflows?

The newest events, and any way to know what they were. The queue held 16,384 of the 36,800 records those renames generated, with every survivor among the earlier ones, plus one IN_Q_OVERFLOW: 10,208 of 18,400 renames left no trace at all. Re-read the files you watch and compare content; do not replay the surviving events as if they were current.

Is 16,384 a limit per read or per instance?

Per instance, and it is a count of records. A single read returned 8,192 records when asked for a 1,048,576-byte buffer, and the conventional 65,536-byte read returned 2,048. The ceiling is the queue, not the buffer, and fs.inotify.max_queued_events is where it is set.

Why does add_watch on a ConfigMap path miss updates?

The path is a symlink chain, and inotify_add_watch resolves it once, so the watch sits on the file of one timestamped directory. Content-change events across 50 updates: 0 – no MODIFY, no CLOSE_WRITE. The only records that watcher gets are DELETE_SELF and IGNORED when kubelet’s cleanup removes the old directory, and those say the file it watched is gone, not what replaced it. A watcher on the directory that names the path, matching the ..data rename, saw every one; so did a file watch that re-adds itself on DELETE_SELF, because the cleanup follows the swap – though only while the publisher cleans up. Watch the directory and treat the link rename as the change.

Is polling every 50 ms better than inotify?

It is more robust and slower. A 50-millisecond poll caught 50 of 50 updates at a median of 49.5 ms, against microseconds for the directory watch, and it pays that interval in wakeups whether anything changed or not. Use inotify for latency and a slow poll as the fallback for the changes inotify cannot see.

Does an inotify watch on a directory cover its subdirectories?

No. A single watch on the root saw 0 events for a file written in an existing subdirectory, and one CREATE for a new subdirectory, but nothing for the file written inside it. Cover the tree with one watch per directory, add new directories when the CREATE arrives, and read each new directory once its watch is in place.

Which clock should a debounce window use?

A monotonic clock, in seconds or nanoseconds. It never steps backwards, so a window measured on it cannot be stretched or cut by an adjustment, and it is a clock, not a unit of time that has to be converted before it means anything.

How do I test that a reloader really reloads?

Deploy through all three shapes – in-place, atomic replace, symlink swap – and assert that the callback received the deployed version each time, then run the same version twice and assert that the second run produces no callback. Table 15 is that test at 50 deploys per shape; the module’s suite is its unit-test form, at 109 tests.

TechBobby Engineering writes measured runbooks for production Python. Every figure in this article comes from a probe run on this host, and the tables carry that run’s output; the host’s limits were read from /proc rather than assumed. The 109-test suite is not reprinted here. What the appendix does print is the code those probes import and the probes behind the measurements the body leans on: six watchguard modules, the ctypes helper rawinotify.py, and probes 01_coalesce.py, 02_overflow.py, 03_replace.py, 04_symlink.py and 07_endtoend.py – twelve files in full, with the package’s remaining file only its import list. The code in the body is an excerpt of those files rather than a separate program – each block is the file’s own text for the decision it explains, with only the imports it uses kept and nothing rewritten, and the appendix holds every one of those functions whole, so nothing in the body is the only copy of what ran. The deploy count in Table 15 is that run’s, too.

The ctypes binding every probe imports: rawinotify.py
"""Minimal inotify bindings over ctypes: the four libc calls the probes need.

The standard library has no inotify module, and the probes must not depend on a
third-party package: what the article measures has to be the kernel's behaviour, not
a library's. Each function returns what libc returns, and raises OSError carrying the
current errno, so a probe can report ENOSPC or EMFILE as data rather than crash on it.

The mask values are the kernel's UAPI constants (include/uapi/linux/inotify.h). They
are written out here instead of imported so the file can be printed in the article as
the exact code that ran.
"""
from __future__ import annotations

import ctypes
import os
import struct
from dataclasses import dataclass

LIBC = ctypes.CDLL("libc.so.6", use_errno=True)
LIBC.inotify_init1.argtypes = [ctypes.c_int]
LIBC.inotify_init1.restype = ctypes.c_int
LIBC.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
LIBC.inotify_add_watch.restype = ctypes.c_int
LIBC.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
LIBC.inotify_rm_watch.restype = ctypes.c_int

IN_NONBLOCK = 0o4000
IN_CLOEXEC = 0o2000000

IN_ACCESS = 0x00000001
IN_MODIFY = 0x00000002
IN_ATTRIB = 0x00000004
IN_CLOSE_WRITE = 0x00000008
IN_CLOSE_NOWRITE = 0x00000010
IN_OPEN = 0x00000020
IN_MOVED_FROM = 0x00000040
IN_MOVED_TO = 0x00000080
IN_CREATE = 0x00000100
IN_DELETE = 0x00000200
IN_DELETE_SELF = 0x00000400
IN_MOVE_SELF = 0x00000800
IN_UNMOUNT = 0x00002000
IN_Q_OVERFLOW = 0x00004000
IN_IGNORED = 0x00008000
IN_ONLYDIR = 0x01000000
IN_DONT_FOLLOW = 0x02000000
IN_EXCL_UNLINK = 0x04000000
IN_ISDIR = 0x40000000

WATCH_MASK = (IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_CREATE | IN_DELETE
              | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF)

EVENT = struct.Struct("iIII")


@dataclass(frozen=True)
class RawEvent:
    """One event as the kernel wrote it: a watch descriptor, a mask, a cookie, a name."""

    wd: int
    mask: int
    cookie: int
    name: str


def init(flags: int = IN_NONBLOCK | IN_CLOEXEC) -> int:
    """Create an inotify instance. EMFILE means this user's instance budget is spent."""
    fd = LIBC.inotify_init1(flags)
    if fd < 0:
        raise OSError(ctypes.get_errno(), "inotify_init1")
    return fd


def add_watch(fd: int, path: str, mask: int = WATCH_MASK) -> int:
    """Add a watch and return its descriptor. ENOSPC is the watch budget, ENOENT the path."""
    wd = LIBC.inotify_add_watch(fd, path.encode(), mask)
    if wd < 0:
        raise OSError(ctypes.get_errno(), f"inotify_add_watch({path})")
    return wd


def remove_watch(fd: int, wd: int) -> None:
    if LIBC.inotify_rm_watch(fd, wd) < 0:
        raise OSError(ctypes.get_errno(), f"inotify_rm_watch({wd})")


def read_events(fd: int, size: int = 65536) -> list[RawEvent]:
    """Drain whatever the instance holds, up to ``size`` bytes per read call."""
    events: list[RawEvent] = []
    while True:
        try:
            data = os.read(fd, size)
        except BlockingIOError:
            return events
        if not data:
            return events
        offset = 0
        while offset + EVENT.size <= len(data):
            wd, mask, cookie, length = EVENT.unpack_from(data, offset)
            raw = data[offset + EVENT.size:offset + EVENT.size + length]
            name = raw.split(b"\0", 1)[0].decode("utf-8", "replace")
            events.append(RawEvent(wd, mask, cookie, name))
            offset += EVENT.size + length
        if len(data) < size:
            return events


def drain_until_empty(fd: int) -> list[RawEvent]:
    """Keep reading until a read returns nothing: what a service does each wakeup."""
    out: list[RawEvent] = []
    while True:
        batch = read_events(fd)
        if not batch:
            return out
        out.extend(batch)


def names(mask: int) -> list[str]:
    """Decode a mask into the constant names this file defines, for readable output."""
    table = [(IN_ACCESS, "ACCESS"), (IN_MODIFY, "MODIFY"), (IN_ATTRIB, "ATTRIB"),
             (IN_CLOSE_WRITE, "CLOSE_WRITE"), (IN_CLOSE_NOWRITE, "CLOSE_NOWRITE"),
             (IN_OPEN, "OPEN"), (IN_MOVED_FROM, "MOVED_FROM"), (IN_MOVED_TO, "MOVED_TO"),
             (IN_CREATE, "CREATE"), (IN_DELETE, "DELETE"), (IN_DELETE_SELF, "DELETE_SELF"),
             (IN_MOVE_SELF, "MOVE_SELF"), (IN_UNMOUNT, "UNMOUNT"),
             (IN_Q_OVERFLOW, "Q_OVERFLOW"), (IN_IGNORED, "IGNORED"),
             (IN_ISDIR, "ISDIR")]
    return [label for bit, label in table if mask & bit]
The record format and the decoder: events.py
"""The kernel's event record, decoded.

One ``read()`` from an inotify descriptor returns a sequence of variable-length records:
a 16-byte header of four native-endian 32-bit integers - watch descriptor, mask, cookie,
name length - followed by the name, NUL-terminated and padded to a 16-byte boundary.
This run measured 32 bytes for a 1- to 15-byte name, 48 bytes for 16 to 31, and 64 bytes
for 32: the name field is the name plus its NUL, rounded up to a multiple of 16.

Coalescing is the other half of the format. The kernel merges a new event into the last
one in the queue when the watch descriptor, the mask and the name are all equal, so a
thousand appends to one file that nobody reads can arrive as a single MODIFY. Two events
with different masks - MODIFY then CLOSE_WRITE - are never merged, which is why the mask a
watcher asks for decides whether one append is one event or two.
"""
from __future__ import annotations

import struct
from dataclasses import dataclass

IN_ACCESS = 0x00000001
IN_MODIFY = 0x00000002
IN_ATTRIB = 0x00000004
IN_CLOSE_WRITE = 0x00000008
IN_CLOSE_NOWRITE = 0x00000010
IN_OPEN = 0x00000020
IN_MOVED_FROM = 0x00000040
IN_MOVED_TO = 0x00000080
IN_CREATE = 0x00000100
IN_DELETE = 0x00000200
IN_DELETE_SELF = 0x00000400
IN_MOVE_SELF = 0x00000800
IN_UNMOUNT = 0x00002000
IN_Q_OVERFLOW = 0x00004000
IN_IGNORED = 0x00008000
IN_ONLYDIR = 0x01000000
IN_DONT_FOLLOW = 0x02000000
IN_ISDIR = 0x40000000

# What a watcher of a file or a directory normally needs: content changes, atomic
# renames, creation and deletion, and the three notices that mean the watch itself is
# about to end. IN_IGNORED is included although the kernel sets it by itself, because a
# caller that filters events by mask would otherwise drop the one event that says
# "there is no watch here any more".
CHANGE_MASK = (IN_MODIFY | IN_CLOSE_WRITE | IN_ATTRIB | IN_CREATE | IN_DELETE
               | IN_MOVED_FROM | IN_MOVED_TO)
WATCH_MASK = CHANGE_MASK | IN_DELETE_SELF | IN_MOVE_SELF | IN_IGNORED

HEADER = struct.Struct("iIII")
NAME_ALIGN = 16

_LABELS = (
    (IN_ACCESS, "ACCESS"), (IN_MODIFY, "MODIFY"), (IN_ATTRIB, "ATTRIB"),
    (IN_CLOSE_WRITE, "CLOSE_WRITE"), (IN_CLOSE_NOWRITE, "CLOSE_NOWRITE"),
    (IN_OPEN, "OPEN"), (IN_MOVED_FROM, "MOVED_FROM"), (IN_MOVED_TO, "MOVED_TO"),
    (IN_CREATE, "CREATE"), (IN_DELETE, "DELETE"), (IN_DELETE_SELF, "DELETE_SELF"),
    (IN_MOVE_SELF, "MOVE_SELF"), (IN_UNMOUNT, "UNMOUNT"),
    (IN_Q_OVERFLOW, "Q_OVERFLOW"), (IN_IGNORED, "IGNORED"), (IN_ISDIR, "ISDIR"),
)


class MalformedRecord(ValueError):
    """A buffer whose name length runs past its end or breaks the alignment rule."""


def mask_names(mask: int) -> list[str]:
    """The constant names set in a mask, in definition order."""
    return [label for bit, label in _LABELS if mask & bit]


@dataclass(frozen=True)
class Event:
    """One decoded event: the watch, the mask, the rename cookie and the name."""

    wd: int
    mask: int
    cookie: int
    name: str

    @property
    def is_overflow(self) -> bool:
        return bool(self.mask & IN_Q_OVERFLOW)

    @property
    def is_ignored(self) -> bool:
        return bool(self.mask & IN_IGNORED)

    @property
    def ends_watch(self) -> bool:
        """True when this event says the watch it belongs to no longer exists.

        DELETE_SELF and MOVE_SELF are the object going away; IGNORED is the kernel
        confirming it. Any of the three means a later add_watch is required before the
        path can be reported on again.
        """
        return bool(self.mask & (IN_DELETE_SELF | IN_MOVE_SELF | IN_IGNORED))

    @property
    def is_change(self) -> bool:
        return bool(self.mask & CHANGE_MASK)

    @property
    def is_directory(self) -> bool:
        return bool(self.mask & IN_ISDIR)

    def describes(self) -> str:
        return " ".join(mask_names(self.mask)) or hex(self.mask)


def decode(buffer: bytes) -> tuple[list[Event], int]:
    """Decode a read buffer, returning the events and how many bytes they consumed.

    A trailing record that is shorter than its own header or name field is not decoded:
    the kernel does not produce one, and silently guessing would turn a short read into a
    wrong name. The consumed count lets a caller assert the whole buffer was understood.
    """
    events: list[Event] = []
    offset = 0
    while offset + HEADER.size <= len(buffer):
        wd, mask, cookie, length = HEADER.unpack_from(buffer, offset)
        if length % NAME_ALIGN:
            raise MalformedRecord(f"name length {length} is not a multiple of {NAME_ALIGN}")
        end = offset + HEADER.size + length
        if end > len(buffer):
            break
        raw = buffer[offset + HEADER.size:end]
        name = raw.split(b"\0", 1)[0].decode("utf-8", "replace")
        events.append(Event(wd=wd, mask=mask, cookie=cookie, name=name))
        offset = end
    return events, offset


def parse_events(buffer: bytes) -> list[Event]:
    """Decode a buffer and insist that no bytes were left over."""
    events, consumed = decode(buffer)
    if consumed != len(buffer):
        raise MalformedRecord(f"{len(buffer) - consumed} trailing bytes")
    return events
The descriptor, its errors and its lifetime: inotify.py
"""The inotify descriptor as an object with a lifetime.

Four libc calls are all the kernel interface needs - inotify_init1, inotify_add_watch,
inotify_rm_watch and read - but each returns a C convention that has to be translated:
-1 plus errno into an exception, and a byte buffer into :class:`~watchguard.events.Event`
records. The translation is the whole of this module, and it is kept separate so the
reloader above it never touches ctypes.

Two numbers belong to the user, not to this process: the instance budget (128 on this
host) and the watch budget (8,192), both per uid and shared with every other process of
that uid. A long-lived service that opens one instance and watches a tree must treat
ENOSPC from add_watch as a capacity signal, not as a bug.
"""
from __future__ import annotations

import ctypes
import errno
import os
import select
from pathlib import Path
from types import TracebackType

from .events import WATCH_MASK, Event, decode

IN_NONBLOCK = 0o4000
IN_CLOEXEC = 0o2000000

LIBC = ctypes.CDLL("libc.so.6", use_errno=True)
LIBC.inotify_init1.argtypes = [ctypes.c_int]
LIBC.inotify_init1.restype = ctypes.c_int
LIBC.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
LIBC.inotify_add_watch.restype = ctypes.c_int
LIBC.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
LIBC.inotify_rm_watch.restype = ctypes.c_int

READ_BYTES = 65536


class InotifyError(OSError):
    """An inotify call failed; ``errno`` is the kernel's reason."""


def _translate(where: str) -> InotifyError:
    number = ctypes.get_errno()
    error = InotifyError(number, f"{where}: {os.strerror(number)}")
    return error


class Inotify:
    """One inotify instance: a descriptor, its watches, and a close that is idempotent."""

    def __init__(self, flags: int = IN_NONBLOCK | IN_CLOEXEC) -> None:
        fd = LIBC.inotify_init1(flags)
        if fd < 0:
            raise _translate("inotify_init1")
        self._fd: int | None = fd
        self.watches: dict[int, Path] = {}

    @staticmethod
    def available() -> bool:
        """Whether this platform exposes inotify at all, without leaking a descriptor."""
        try:
            fd = LIBC.inotify_init1(IN_NONBLOCK | IN_CLOEXEC)
        except (OSError, AttributeError):
            return False
        if fd < 0:
            return False
        os.close(fd)
        return True

    def __enter__(self) -> "Inotify":
        return self

    def __exit__(self, kind: type[BaseException] | None, value: BaseException | None,
                 trace: TracebackType | None) -> None:
        self.close()

    @property
    def fd(self) -> int:
        if self._fd is None:
            raise ValueError("this inotify instance is closed")
        return self._fd

    def fileno(self) -> int:
        return self.fd

    def add_watch(self, path: str | Path, mask: int = WATCH_MASK) -> int:
        """Watch a path, following a symbolic link at add time, and return the descriptor.

        The watch is on the inode the path named at this moment. Replacing that inode
        later - a rename over it, or a symlink swap - leaves this watch on the old one;
        the caller learns that from IN_IGNORED / DELETE_SELF and re-adds.
        """
        target = os.fspath(path)
        wd = LIBC.inotify_add_watch(self.fd, os.fsencode(target), mask)
        if wd < 0:
            error = _translate(f"inotify_add_watch({target})")
            if error.errno == errno.ENOENT:
                raise FileNotFoundError(error.errno, error.strerror, target) from None
            if error.errno == errno.ENOSPC:
                raise InotifyError(error.errno,
                                   f"watch budget for uid {os.getuid()} is exhausted: "
                                   f"{target}") from None
            raise error
        self.watches[wd] = Path(target)
        return wd

    def remove_watch(self, wd: int) -> None:
        if LIBC.inotify_rm_watch(self.fd, wd) < 0:
            raise _translate(f"inotify_rm_watch({wd})")
        self.watches.pop(wd, None)

    def read(self, size: int = READ_BYTES) -> list[Event]:
        """Read what is queued, up to ``size`` bytes, without blocking."""
        try:
            data = os.read(self.fd, size)
        except BlockingIOError:
            return []
        if not data:
            return []
        events, _ = decode(data)
        for event in events:
            if event.is_ignored:
                self.watches.pop(event.wd, None)
        return events

    def read_available(self, size: int = READ_BYTES) -> list[Event]:
        """Read until a read returns nothing: what a service does on each wakeup."""
        out: list[Event] = []
        while True:
            batch = self.read(size)
            if not batch:
                return out
            out.extend(batch)

    def wait(self, timeout_s: float | None = None) -> bool:
        """Block until the descriptor is readable. True when something can be read."""
        ready, _, _ = select.select([self.fd], [], [], timeout_s)
        return bool(ready)

    def close(self) -> None:
        if self._fd is not None:
            os.close(self._fd)
            self._fd = None
            self.watches.clear()

    def __del__(self) -> None:                       # pragma: no cover - finaliser
        try:
            self.close()
        except OSError:
            pass
The path watch that re-arms across a deploy: paths.py
"""Watch a path rather than the inode that happened to be behind it.

A watch added by path is a watch on one inode. Two ordinary deploys replace that inode
while the path stays the same:

  * an atomic write - a temporary file renamed over the target;
  * a symlink swap  - the layout kubelet uses for ConfigMaps, where ``app.conf`` points
    at ``..data/app.conf`` and ``..data`` is a symlink that is replaced on every update.

In both cases the old watch reports DELETE_SELF and IGNORED and then nothing: writing to
the path afterwards produces no event, because the path now names a different inode from
the one being watched. This run measured 0 of 200 atomic deploys caught by a watch that
ignored those masks, and 0 of 50 ConfigMap swaps.

:class:`PathWatch` holds two watches - the directory that names the path, and the file the
path resolves to - and keeps the pair meaningful across both deploys by re-adding when the
identity changes. ``names()`` is what makes the directory watch specific: the path's own
name plus the first component of its symlink target, which for a ConfigMap is ``..data``.
"""
from __future__ import annotations

import os
from pathlib import Path

from .events import (IN_CREATE, IN_DELETE, IN_MODIFY, IN_MOVED_FROM, IN_MOVED_TO,
                     WATCH_MASK, Event)
from .inotify import Inotify

Identity = tuple[int, int]


def identity(path: str | Path) -> Identity | None:
    """(st_dev, st_ino) of the file a path resolves to, or None when it is not there.

    The pair rather than the inode alone: two filesystems can hand out the same inode
    number, and a container mount can change the device under a path.
    """
    try:
        info = os.stat(path)
    except OSError:
        return None
    return (info.st_dev, info.st_ino)


class PathWatch:
    """A path watch that can be re-armed, with the events it claims made explicit."""

    def __init__(self, instance: Inotify, path: str | Path, mask: int = WATCH_MASK) -> None:
        self.instance = instance
        self.path = Path(path)
        self.mask = mask
        self.directory = self.path.parent
        self.dir_wd = instance.add_watch(self.directory, mask)
        self.target_wd: int | None = None
        self.identity: Identity | None = None
        self.arms = 0
        self.refresh()

    def refresh(self) -> bool:
        """Re-add the file watch if the path now resolves to a different inode.

        Returns True when anything changed, so a caller can decide that a reload is due
        even before it compares content: after a rename over the file, the new inode is
        the only signal that the content may differ.
        """
        current = identity(self.path)
        if current is not None and current == self.identity and self.target_wd in self.instance.watches:
            return False
        if self.target_wd is not None and self.target_wd in self.instance.watches:
            try:
                self.instance.remove_watch(self.target_wd)
            except OSError:
                pass
        self.target_wd = None
        if current is not None:
            try:
                self.target_wd = self.instance.add_watch(self.path, self.mask)
            except FileNotFoundError:
                self.identity = None
                return True
            self.arms += 1
        self.identity = current
        return True

    def names(self) -> set[str]:
        """The names in the directory that mean this path changed.

        The path's own name covers creating, deleting and renaming over it. The first
        component of a symlink target covers the ConfigMap layout, where the file the
        path names does not itself move: ``..data`` does.
        """
        names = {self.path.name}
        try:
            target = os.readlink(self.path)
        except OSError:
            return names
        for part in Path(target).parts:
            if part not in (".", "..", "/"):
                names.add(part)
                break
        return names

    def owns(self, event: Event) -> bool:
        """Whether the event belongs to one of this watch's descriptors."""
        return event.wd == self.dir_wd or (self.target_wd is not None
                                          and event.wd == self.target_wd)

    def matches(self, event: Event) -> bool:
        """Whether the event is a change to this path's content or identity."""
        if event.is_overflow or not self.owns(event):
            return False
        if event.wd == self.dir_wd:
            if event.is_ignored or not event.name:
                return False
            return bool(event.mask & (IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM
                                      | IN_MOVED_TO)) and event.name in self.names()
        return True
The two deadlines and three states: debounce.py
"""Coalesce a burst of notifications into one decision.

A watcher that reloads on every event does the work twice for one append and a thousand
times for a burst that the kernel already promised to merge. A debouncer fixes that with
two deadlines, and both are needed:

  * the quiet window - fire once no event has arrived for ``window_s``;
  * the hold limit   - fire at most ``hold_s`` after the first event of the burst, so a
    file that is rewritten continuously still reloads, just not once per write.

Three states and six transitions:

    IDLE   --note()-->  ARMED        first event of a burst
    ARMED  --note()-->  ARMED        a later event moves the quiet deadline only
    ARMED  --due()-->   DUE          quiet window elapsed, or hold limit reached
    ARMED  --reset()--> IDLE         a burst the caller has decided to drop
    DUE    --note()-->  ARMED        a change arrived while the decision was pending
    DUE    --reset()--> IDLE         the caller has acted on the decision

A change that arrives while a decision is pending is never dropped: DUE -> ARMED starts a
new burst, and the caller sees the pending decision it has not yet reset as superseded.
"""
from __future__ import annotations

import time
from enum import Enum

ALLOWED_TRANSITIONS = frozenset({
    ("IDLE", "ARMED"), ("ARMED", "ARMED"), ("ARMED", "DUE"), ("ARMED", "IDLE"),
    ("DUE", "ARMED"), ("DUE", "IDLE"),
})


class DebounceState(str, Enum):
    IDLE = "IDLE"
    ARMED = "ARMED"
    DUE = "DUE"


class Debouncer:
    """At most one ``due`` per quiet window, with a ceiling on how long a burst may hold."""

    def __init__(self, window_s: float = 0.05, hold_s: float = 1.0,
                 clock=time.monotonic) -> None:
        if window_s < 0 or hold_s <= 0:
            raise ValueError("window_s must be >= 0 and hold_s > 0")
        self.window_s = window_s
        self.hold_s = hold_s
        self.clock = clock
        self.state = DebounceState.IDLE
        self._first: float | None = None
        self._last: float | None = None
        self.transitions: list[tuple[str, str]] = []

    def _move(self, new: DebounceState) -> None:
        if new.value != self.state.value:
            pair = (self.state.value, new.value)
            if pair not in ALLOWED_TRANSITIONS:
                raise AssertionError(f"illegal debounce transition {pair}")
            self.transitions.append(pair)
        self.state = new

    def note(self, now: float | None = None) -> None:
        """Record one change. DUE becomes ARMED again: the pending decision is stale."""
        moment = self.clock() if now is None else now
        if self.state is not DebounceState.ARMED:
            self._move(DebounceState.ARMED)
            self._first = moment
        self._last = moment

    def due(self, now: float | None = None) -> bool:
        """True once the burst is quiet enough, or has lasted the hold limit."""
        if self.state is not DebounceState.ARMED or self._first is None:
            return self.state is DebounceState.DUE
        moment = self.clock() if now is None else now
        # A clock may read 0.0 - a fake clock in a test, a monotonic clock at boot - and
        # `self._last or moment` would read that 0.0 as "no time recorded" and measure the
        # quiet deadline from the caller's moment instead, which is always zero elapsed.
        last = self._last if self._last is not None else moment
        quiet = moment - last
        held = moment - self._first
        if quiet >= self.window_s or held >= self.hold_s:
            self._move(DebounceState.DUE)
            return True
        return False

    def reset(self) -> None:
        """The caller has acted; start clean."""
        self._move(DebounceState.IDLE)
        self._first = None
        self._last = None

    @property
    def pending(self) -> bool:
        return self.state is DebounceState.DUE
Five states, twelve transitions, and the guards: reloader.py
"""Reload a configuration file once per change, across deploys that replace the inode.

Five states and twelve distinct ``(from, to)`` pairs. The lines below are the events that
drive them, so they outnumber the pairs: three of the twelve are reached by more than one
event (a watch that ended and an overflow both land in RESYNC, and so do a read that fails,
a callback that raises and a re-arm the kernel refuses).

    IDLE       --start()-->                 ARMED    the instance and both watches exist
    ARMED      --change-->                  DEBOUNCING  an event matched this path
    ARMED      --watch ended-->             RESYNC   a deploy replaced or removed the inode
    ARMED      --overflow-->                RESYNC   the queue dropped events for every path
    ARMED      --stop()-->                  IDLE
    DEBOUNCING --window closed-->           RELOADING  the quiet window or hold limit passed
    DEBOUNCING --overflow-->                RESYNC
    DEBOUNCING --watch ended-->             RESYNC
    DEBOUNCING --stop()-->                  IDLE
    RELOADING  --content read-->            ARMED    reloaded, or content unchanged
    RELOADING  --read failed-->             RESYNC   the path was missing during the deploy
    RELOADING  --callback raised-->         RESYNC   the new content was rejected, and retried
    RELOADING  --re-arm failed-->           RESYNC   add_watch refused: ENOSPC, or a dead fd
    RELOADING  --stop() in the callback-->  IDLE     the callback shut the reloader down
    RESYNC     --re-arm + read-->           ARMED    the content after the deploy is the truth
    RESYNC     --stop()-->                  IDLE

RELOADING is a state this machine passes through inside one ``tick()``, not one a loop
sleeps in: :meth:`_apply` reads the file and calls back before ``tick()`` returns. That is
why no overflow line reaches it - an overflow is read from the descriptor, and a reload in
progress is not reading one - and why the only way into IDLE from there is the callback
calling ``stop()``, which :meth:`_apply` allows rather than treating as a reload landing in
a state that no longer exists. What does leave it for another state is a decision inside that
same call: a read that fails, a callback that raises, and a re-arm the kernel refuses all go
to RESYNC, the one state that retries on its own.

A RESYNC that still cannot read the file retries on the next tick, and so does one whose
re-arm is refused - ``add_watch`` answers ENOSPC when the uid's watch budget is spent. Both
are the state staying where it is rather than a pair in :data:`ALLOWED_TRANSITIONS`, so
neither has a line above. A read that raises rather than answering None - EIO from a mount
that has gone away - is the same case, and takes the same exit: recorded, still RESYNC, and
tried again on the next tick.

Two guards exist because the measured failures are two different things: an overflow is
not a change to this path (the queue lost events for all of them), and a watch that ended
must be re-added before any later event can be trusted. A transition that is not in
:data:`ALLOWED_TRANSITIONS` raises in :meth:`_move`, so a future edit cannot quietly add
a sixth state or a jump that skips the re-arm.
"""
from __future__ import annotations

import time
from enum import Enum
from pathlib import Path
from typing import Callable

from .debounce import Debouncer
from .inotify import Inotify
from .paths import PathWatch
from .events import Event


class State(str, Enum):
    IDLE = "IDLE"
    ARMED = "ARMED"
    DEBOUNCING = "DEBOUNCING"
    RELOADING = "RELOADING"
    RESYNC = "RESYNC"


ALLOWED_TRANSITIONS = frozenset({
    ("IDLE", "ARMED"),
    ("ARMED", "DEBOUNCING"), ("ARMED", "RESYNC"), ("ARMED", "IDLE"),
    ("DEBOUNCING", "RELOADING"), ("DEBOUNCING", "RESYNC"), ("DEBOUNCING", "IDLE"),
    ("RELOADING", "ARMED"), ("RELOADING", "RESYNC"), ("RELOADING", "IDLE"),
    ("RESYNC", "ARMED"), ("RESYNC", "IDLE"),
})


class ConfigReloader:
    """Call ``on_reload`` with the file's text when, and only when, it has changed."""

    def __init__(self, path: str | Path, on_reload: Callable[[str], None], *,
                 window_s: float = 0.05, hold_s: float = 1.0,
                 encoding: str = "utf-8", clock=time.monotonic) -> None:
        self.path = Path(path)
        self.on_reload = on_reload
        self.encoding = encoding
        self.clock = clock
        self.debouncer = Debouncer(window_s=window_s, hold_s=hold_s, clock=clock)
        self.instance: Inotify | None = None
        self.watch: PathWatch | None = None
        self.state = State.IDLE
        self.transitions: list[tuple[str, str, float]] = []
        self.content: str | None = None
        self.reloads = 0
        self.last_reason: str | None = None
        self.last_error: str | None = None

    def _move(self, new: State, reason: str) -> None:
        if new is self.state:
            return
        pair = (self.state.value, new.value)
        if pair not in ALLOWED_TRANSITIONS:
            raise AssertionError(f"illegal reloader transition {pair} ({reason})")
        self.transitions.append((self.state.value, new.value, self.clock()))
        self.state = new
        self.last_reason = reason

    def _read(self) -> str | None:
        try:
            return self.path.read_text(encoding=self.encoding, errors="replace")
        except (FileNotFoundError, NotADirectoryError, IsADirectoryError, PermissionError):
            return None

    def start(self) -> bool:
        """Create the instance and both watches. Returns False if already started."""
        if self.state is not State.IDLE:
            return False
        instance = Inotify()
        try:
            watch = PathWatch(instance, self.path)
        except FileNotFoundError:
            instance.close()
            raise
        self.instance = instance
        self.watch = watch
        self.content = self._read()
        self._move(State.ARMED, "start")
        return True

    def stop(self) -> None:
        """Release the descriptor. A pending debounce is dropped, not fired."""
        if self.state is State.IDLE:
            return
        if self.instance is not None:
            self.instance.close()
        self.instance = None
        self._move(State.IDLE, "stop")

    def __enter__(self) -> "ConfigReloader":
        self.start()
        return self

    def __exit__(self, *_: object) -> None:
        self.stop()

    def handle_events(self, events: list[Event]) -> State:
        """Feed one read's worth of events through the guards and the debouncer."""
        if self.state is State.IDLE or self.watch is None:
            return self.state
        if any(event.is_overflow for event in events):
            self._move(State.RESYNC, "queue overflow")
            return self.state
        if any(self.watch.owns(event) and event.ends_watch for event in events):
            self._move(State.RESYNC, "watch ended")
            return self.state
        if any(self.watch.matches(event) for event in events):
            self.debouncer.note()
            if self.state is not State.DEBOUNCING:
                self._move(State.DEBOUNCING, "change")
        return self.state

    def tick(self, now: float | None = None) -> State:
        """Advance whatever is waiting: a due debounce, or a re-arm after a deploy."""
        if self.state is State.RESYNC:
            self._resync()
        elif self.state is State.DEBOUNCING and self.debouncer.due(now):
            self._move(State.RELOADING, "window closed")
            self._apply()
        return self.state

    def _apply(self) -> None:
        # The change may have arrived through the directory watch because the deploy
        # replaced the file: re-arm before reading so the next in-place write is seen by
        # the file watch rather than only by the directory's name matching.
        try:
            if self.watch is not None:
                try:
                    self.watch.refresh()
                except OSError as error:
                    # add_watch can refuse: ENOSPC when this uid's watch budget is spent,
                    # EBADF when the descriptor went away with the instance. A watch that
                    # cannot be re-added is the thing RESYNC exists to retry, so the
                    # decision is to resync - never to stay in RELOADING, which no loop
                    # sleeps in and no later tick visits.
                    self._record_failure(error)
                    self._move(State.RESYNC, "re-arm failed")
                    return
            try:
                content = self._read()
            except OSError as error:
                # _read() answers None for the errors a deploy produces; anything else it
                # raises (EIO on a failing mount, ENAMETOOLONG on a path that grew) reaches
                # here, and is the same decision: read the file again after a re-arm.
                self._record_failure(error)
                self._move(State.RESYNC, "read failed")
                return
            if content is None:
                self._move(State.RESYNC, "read failed")
                return
            if content == self.content:
                self._move(State.ARMED, "unchanged")
                return
            try:
                self.on_reload(content)
            except Exception as error:                # noqa: BLE001 - recorded, retried
                self._record_failure(error)
                if self.state is State.RELOADING:
                    self._move(State.RESYNC, "callback failed")
                return
            self.content = content
            self.reloads += 1
            self.last_error = None
            if self.state is not State.RELOADING:
                # The callback called stop(). The reload happened and is recorded, but
                # there is no state to return to: the descriptor it would have used is
                # closed.
                return
            self._move(State.ARMED, "reloaded")
        finally:
            # DUE -> reset() -> IDLE, on every exit from this call: the debouncer's
            # docstring says the caller resets once it has acted, and a decision that
            # ended in RESYNC or in a stopped reloader was acted on too. Without it the
            # next burst inherits this one's deadlines instead of starting a window.
            self.debouncer.reset()

    def _record_failure(self, error: BaseException) -> None:
        """Keep what failed, in the one format the log and the tests read."""
        self.last_error = f"{type(error).__name__}: {error}"

    def _resync(self) -> None:
        assert self.watch is not None
        try:
            changed = self.watch.refresh()
        except OSError as error:
            # Already in the state that retries: record the refusal and let the next tick
            # try again. Nothing here is a transition, so nothing here can trip _move().
            self._record_failure(error)
            self.last_reason = "re-arm failed"
            return
        try:
            content = self._read()
        except OSError as error:
            # _read() answers None for a missing file and raises for a failing one (EIO on a
            # mount, ENAMETOOLONG on a path that grew). _apply() already treats both as a
            # reason to resync; here the machine is in RESYNC, so the failure is recorded
            # and the state stays where it is for the next tick to retry.
            self._record_failure(error)
            self.last_reason = "read failed"
            return
        if content is None:
            self.last_reason = "still missing"
            return
        if content != self.content or changed:
            if content != self.content:
                try:
                    self.on_reload(content)
                except Exception as error:            # noqa: BLE001 - recorded, retried
                    self._record_failure(error)
                    self.last_reason = "callback failed"
                    return
                self.content = content
                self.reloads += 1
                self.last_error = None
                if self.state is not State.RESYNC:
                    return                      # the callback stopped the reloader
        self.debouncer.reset()
        self._move(State.ARMED, "resynced")

    def run_once(self, timeout_s: float = 0.1) -> State:
        """One loop iteration: resync if needed, read if anything is waiting, then tick."""
        if self.instance is None:
            raise RuntimeError("reloader is not started")
        if self.state is State.RESYNC:
            self.tick()
            return self.state
        if self.instance.wait(timeout_s):
            self.handle_events(self.instance.read())
        self.tick()
        return self.state
The walk and the directories that arrive later: tree.py
"""Cover a directory tree, including the directories that appear after the walk.

inotify has no recursive watch. A watch on a directory reports its own children's events
and one CREATE for a new child directory, and nothing that happens inside that child. The
fix is a walk plus one watch per directory, and then a second rule: when a CREATE with
ISDIR arrives, cover the new directory and its subtree. This run measured a tree of 22
directories covered by 22 watches in 0.65 ms, and a file written into a directory created
after the walk producing zero events.

A watch only reports what happens after it exists, so the second rule has an order: add the
watch first, then read the directory. What was written before the watch is then found by
the read, and what is written after it arrives as an event, so a package copied in as one
directory is covered even though its files were written before anyone could watch them.
"""
from __future__ import annotations

import os
from pathlib import Path
from typing import NamedTuple

from .events import WATCH_MASK
from .inotify import Inotify

DEFAULT_SKIP = ("__pycache__", ".git")


class Coverage(NamedTuple):
    """What one call added, and what was already inside it when the watch arrived.

    ``directories`` are the directories this call added a watch to. ``files`` are the
    entries that were already inside one of them: nothing will ever report those, because
    the watch did not exist when they were written, so the caller has to read them itself.
    Links are reported here too - the walk does not follow them, so a link is an entry to
    read, not a directory to cover.
    """

    directories: list[Path]
    files: list[Path]


def watch_tree(instance: Inotify, root: str | Path, mask: int = WATCH_MASK,
               skip: tuple[str, ...] = DEFAULT_SKIP) -> dict[int, Path]:
    """Add one watch per directory under ``root`` and return descriptor -> directory.

    Symbolic links to directories are not followed: a link back to an ancestor would
    otherwise make the walk endless, and a watch added through a link covers the target,
    whose events would then arrive under two paths. ``os.walk`` already refuses to
    descend into links; this function never passes ``followlinks=True``.
    """
    watched: dict[int, Path] = {}
    base = Path(root)
    if not base.is_dir():
        raise NotADirectoryError(f"{base} is not a directory")
    for directory, children, _ in os.walk(base):
        children[:] = [child for child in children
                       if child not in skip and not os.path.islink(os.path.join(directory, child))]
        try:
            wd = instance.add_watch(directory, mask)
        except FileNotFoundError:
            continue                      # removed between the walk and the add
        watched[wd] = Path(directory)
    return watched


def snapshot(directory: str | Path) -> list[Path]:
    """Everything inside a directory at the moment its watch was added.

    Read after ``add_watch``, never before: a watch reports only what happens after it
    exists, so the entries written before it are exactly the ones this scan has to find.
    An entry written during the scan is reported twice - here, and by the fresh watch -
    and a caller that compares content pays nothing for that.
    """
    try:
        with os.scandir(directory) as entries:
            return sorted(Path(entry.path) for entry in entries)
    except FileNotFoundError:
        return []


def add_new_directories(instance: Inotify, watched: dict[int, Path], mask: int = WATCH_MASK,
                        skip: tuple[str, ...] = DEFAULT_SKIP) -> Coverage:
    """Add watches for directories that appeared after the walk, whole subtrees included.

    Called after a CREATE with ISDIR, this scans the known directories rather than the
    whole tree, then covers each new directory and everything under it. Each directory is
    watched before it is read, and its own subdirectories join the same queue: a directory
    created and filled while this runs is caught either by a scan or by an event, never
    missed between them.
    """
    known = set(watched.values())
    queue: list[Path] = []
    for directory in sorted(known):
        try:
            entries = list(os.scandir(directory))
        except FileNotFoundError:
            continue
        for entry in entries:
            if not entry.is_dir(follow_symlinks=False) or entry.name in skip:
                continue
            path = Path(entry.path)
            if path not in known:
                queue.append(path)

    directories: list[Path] = []
    files: list[Path] = []
    while queue:
        path = queue.pop()
        if path in known:
            continue
        try:
            wd = instance.add_watch(path, mask)
        except FileNotFoundError:
            continue
        watched[wd] = path
        known.add(path)
        directories.append(path)
        for entry in snapshot(path):
            if entry.is_dir() and not entry.is_symlink():
                if entry.name not in skip and entry not in known:
                    queue.append(entry)
            else:
                files.append(entry)
    return Coverage(directories, files)
Probe 01, the append counts of section 4: 01_coalesce.py
"""Probe 01: how many events one change produces, and why the count depends on the mask.

A burst of appends is drained only afterwards, so the kernel's own merge rule is what
decides the count. Two masks are measured side by side, because they are the two choices
a watcher actually makes:

  * MODIFY only - one event per changed file while nobody reads;
  * MODIFY | CLOSE_WRITE - two events per append, because the masks alternate and only
    adjacent identical events are merged.

The control arm repeats the burst on tmpfs and on the workspace's virtiofs: a filesystem
that batched writes could change the count, and the article must not attribute a
filesystem artefact to the kernel.
"""
from __future__ import annotations

import json
import os
import pathlib
import select
import statistics
import time

import rawinotify

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
TMP = pathlib.Path("/tmp")
WORK = HERE.parent / "scratch"

MODIFY = rawinotify.IN_MODIFY
MODIFY_CLOSE = rawinotify.IN_MODIFY | rawinotify.IN_CLOSE_WRITE


def append(path: str, payload: bytes = b"x") -> None:
    fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
    try:
        os.write(fd, payload)
    finally:
        os.close(fd)


def burst(path: str, writes: int, mask: int) -> dict:
    """N appends, then one drain: every append happened before any read."""
    fd = rawinotify.init()
    rawinotify.add_watch(fd, path, mask)
    started = time.perf_counter_ns()
    for _ in range(writes):
        append(path)
    write_ns = time.perf_counter_ns() - started
    events = rawinotify.drain_until_empty(fd)
    os.close(fd)
    return {"writes": writes, "events": len(events), "write_ms": write_ns / 1e6,
            "masks": sorted({hex(event.mask) for event in events})}


def burst_repeated(path: str, writes: int, mask: int, repeats: int = 3) -> dict:
    runs = [burst(path, writes, mask) for _ in range(repeats)]
    return {"writes": writes, "events": [run["events"] for run in runs],
            "write_ms": [round(run["write_ms"], 2) for run in runs]}


def burst_one_fd(path: str, writes: int, mask: int) -> dict:
    """The same count with the writer holding one descriptor open: no CLOSE_WRITE exists."""
    fd = rawinotify.init()
    rawinotify.add_watch(fd, path, mask)
    writer = os.open(path, os.O_WRONLY | os.O_APPEND)
    started = time.perf_counter_ns()
    for _ in range(writes):
        os.write(writer, b"x")
    write_ns = time.perf_counter_ns() - started
    os.close(writer)
    events = rawinotify.drain_until_empty(fd)
    os.close(fd)
    return {"writes": writes, "events": len(events), "write_ms": write_ns / 1e6,
            "masks": sorted({hex(event.mask) for event in events})}


def alternating(directory: str, writes_each: int, mask: int) -> dict:
    left = os.path.join(directory, "left.txt")
    right = os.path.join(directory, "right.txt")
    for path in (left, right):
        open(path, "w").close()
    fd = rawinotify.init()
    left_wd = rawinotify.add_watch(fd, left, mask)
    right_wd = rawinotify.add_watch(fd, right, mask)
    for _ in range(writes_each):
        append(left)
        append(right)
    events = rawinotify.drain_until_empty(fd)
    os.close(fd)
    per_wd = {str(left_wd): 0, str(right_wd): 0}
    for event in events:
        per_wd[str(event.wd)] = per_wd.get(str(event.wd), 0) + 1
    return {"writes_each": writes_each, "writes_total": 2 * writes_each,
            "events": len(events), "per_wd": per_wd}


def paced(path: str, writes: int, gap_ms: float, drain_every: int, mask: int) -> dict:
    fd = rawinotify.init()
    rawinotify.add_watch(fd, path, mask)
    collected = 0
    batches = 0
    started = time.perf_counter_ns()
    for index in range(1, writes + 1):
        append(path)
        time.sleep(gap_ms / 1000)
        if index % drain_every == 0:
            batches += 1
            collected += len(rawinotify.drain_until_empty(fd))
    collected += len(rawinotify.drain_until_empty(fd))
    elapsed_ns = time.perf_counter_ns() - started
    os.close(fd)
    return {"writes": writes, "gap_ms": gap_ms, "drain_every": drain_every, "mask": mask,
            "events": collected, "batches": batches, "elapsed_ms": elapsed_ns / 1e6}


def latency(path: str, mask: int, trials: int = 200) -> dict:
    """Microseconds from the start of one append to the event being readable."""
    fd = rawinotify.init()
    rawinotify.add_watch(fd, path, mask)
    samples: list[float] = []
    for _ in range(trials):
        started = time.perf_counter_ns()
        append(path)
        ready, _, _ = select.select([fd], [], [], 2.0)
        if not ready:
            raise SystemExit("no event within two seconds")
        os.read(fd, 65536)
        samples.append((time.perf_counter_ns() - started) / 1000)
    os.close(fd)
    samples.sort()
    return {"trials": trials, "min_us": round(samples[0], 1),
            "p50_us": round(statistics.median(samples), 1),
            "p95_us": round(samples[int(len(samples) * 0.95) - 1], 1),
            "max_us": round(samples[-1], 1)}


def control(tmp_root: pathlib.Path, virtio_root: pathlib.Path) -> dict:
    out = {}
    for label, root in (("tmpfs", tmp_root), ("virtiofs", virtio_root)):
        path = str(root / f"control_{label}.txt")
        open(path, "w").close()
        out[label] = {
            "burst_100_modify": burst(path, 100, MODIFY)["events"],
            "burst_100_modify_close": burst(path, 100, MODIFY_CLOSE)["events"],
            "paced_20_modify": paced(path, 20, 2, 1, MODIFY)["events"],
        }
    return out


def main() -> None:
    tmp_root = TMP / "tb23_coalesce"
    virtio_root = WORK / "coalesce"
    for root in (tmp_root, virtio_root):
        root.mkdir(parents=True, exist_ok=True)
    target = str(tmp_root / "app.log")
    open(target, "w").close()

    out = {
        "path": target,
        "filesystem": "tmpfs",
        "bursts_modify": [burst_repeated(target, writes, MODIFY) for writes in (1, 10, 100, 1000)],
        "bursts_modify_close": [burst_repeated(target, writes, MODIFY_CLOSE)
                                for writes in (1, 10, 100, 1000)],
        "one_fd_modify": burst_one_fd(target, 1000, MODIFY),
        "one_fd_modify_close": burst_one_fd(target, 1000, MODIFY_CLOSE),
        "alternating_modify": alternating(str(tmp_root), 100, MODIFY),
        "alternating_modify_close": alternating(str(tmp_root), 100, MODIFY_CLOSE),
        "paced_modify": paced(target, 100, 2, 1, MODIFY),
        "paced_modify_close": paced(target, 100, 2, 1, MODIFY_CLOSE),
        "chunk10_modify": paced(target, 100, 2, 10, MODIFY),
        "chunk50_modify": paced(target, 100, 2, 50, MODIFY),
        "latency_modify": latency(target, MODIFY),
        "latency_modify_close": latency(target, MODIFY_CLOSE),
        "control": control(tmp_root, virtio_root),
    }
    (RESULTS / "01_coalesce.json").write_text(json.dumps(out, indent=1))
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
Probe 02, the queue and its overflow in section 5: 02_overflow.py
"""Probe 02: the event queue, its capacity, and what an overflow costs.

One directory watch and a rename loop: every rename produces a MOVED_FROM and a
MOVED_TO with a distinct cookie, and two identical events are never adjacent, so
coalescing cannot hide the count. Two arms:

  * no reader  - the loop runs while nothing drains the instance;
  * drained    - the same loop with a drain every 250 iterations.

The difference is the capacity and the overflow. The cookies say which events survived:
they are issued in order from one counter, so one rename performed and read before a loop
fixes the origin, and every later cookie is the number of renames after it. A kept range of
``baseline+1 .. baseline+8192`` is therefore the first 8,192 renames of that loop and not
merely 8,192 of them - the claim "the queue keeps the oldest" is measured rather than
inferred from how many cookies came back.

The origin belongs to one run, not to the probe: the counter advances while a loop renames,
so an origin measured once and reused would make the second fill read as renames
18,403-26,594 - true of the counter and misleading about the queue, which in each fill keeps
the first 8,192 renames of its own loop. The shift is one loop's 18,400 renames plus the two
that the next arm's own baseline spends before its loop starts. ``main()`` therefore calls
:func:`baseline` again before every arm, and every run's window is ``1 .. 8,192`` for the same
reason. The no-reader arm runs three times, because the fill time is a sample of this host and
not a constant.
"""
from __future__ import annotations

import json
import os
import pathlib
import time

import rawinotify

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
ROOT = pathlib.Path("/tmp") / "tb23_overflow"


def setup() -> str:
    if ROOT.exists():
        for child in ROOT.iterdir():
            child.unlink()
        ROOT.rmdir()
    ROOT.mkdir(parents=True)
    name = str(ROOT / "a")
    open(name, "w").close()
    return name


def baseline(name: str) -> dict:
    """One rename, drained at once: the cookie the first loop rename will follow.

    The counter the kernel issues cookies from is not exposed, so the origin has to be
    measured. This pair of renames is read immediately - nothing is queued behind it, so
    nothing can be dropped - and its higher cookie is the number the loop starts from.
    """
    fd = rawinotify.init()
    rawinotify.add_watch(fd, str(ROOT))
    os.rename(name, name + ".tmp")
    os.rename(name + ".tmp", name)
    events = rawinotify.drain_until_empty(fd)
    os.close(fd)
    cookies = sorted({event.cookie for event in events if event.cookie})
    return {"cookie": cookies[-1] if cookies else None,
            "renames": 2,
            "cookies": len(cookies)}


def loop(name: str, iterations: int, drain_every: int | None, origin: dict) -> dict:
    fd = rawinotify.init()
    rawinotify.add_watch(fd, str(ROOT))
    drained: list[rawinotify.RawEvent] = []
    started = time.perf_counter_ns()
    for index in range(1, iterations + 1):
        os.rename(name, name + ".tmp")
        os.rename(name + ".tmp", name)
        if drain_every and index % drain_every == 0:
            drained.extend(rawinotify.drain_until_empty(fd))
    elapsed_ns = time.perf_counter_ns() - started
    drained.extend(rawinotify.drain_until_empty(fd))
    os.close(fd)
    overflow = [event for event in drained if event.mask & rawinotify.IN_Q_OVERFLOW]
    plain = [event for event in drained if not event.mask & rawinotify.IN_Q_OVERFLOW]
    cookies = sorted({event.cookie for event in plain if event.cookie})
    base = origin["cookie"]
    offset_first = cookies[0] - base if cookies and base is not None else None
    offset_last = cookies[-1] - base if cookies and base is not None else None
    return {
        "renames": iterations * 2,
        "events_read": len(drained),
        "overflow_events": len(overflow),
        "event_capacity_before_overflow": len(plain),
        "cookies": len(cookies),
        "first_cookie": cookies[0] if cookies else None,
        "last_cookie": cookies[-1] if cookies else None,
        "cookie_span": cookies[-1] - cookies[0] + 1 if cookies else None,
        "contiguous_cookies": bool(cookies) and cookies[-1] - cookies[0] + 1 == len(cookies),
        "first_rename_offset": offset_first,
        "last_rename_offset": offset_last,
        "issued_renames": iterations * 2,
        "elapsed_ms": round(elapsed_ns / 1e6, 1),
        "drain_every": drain_every,
    }


def main() -> None:
    name = setup()
    iterations = 9200
    # Three fills of the same queue by the same loop: the arm's timing is a sample, and the
    # spread across these runs is what section 5 and section 10 have to quote honestly. The
    # origin is measured again for each one - two renames drained at once - so each sample's
    # cookie offset counts from its own loop's first rename instead of from the first run's.
    samples = []
    for _ in range(3):
        origin = baseline(name)
        sample = loop(name, iterations, None, origin)
        sample["baseline"] = origin
        samples.append(sample)
    full = samples[0]
    full["elapsed_samples_ms"] = [sample["elapsed_ms"] for sample in samples]
    full["elapsed_min_ms"] = min(full["elapsed_samples_ms"])
    full["elapsed_max_ms"] = max(full["elapsed_samples_ms"])
    full["kept_windows"] = [[sample["first_rename_offset"], sample["last_rename_offset"]]
                            for sample in samples]
    full["sample_origins"] = [sample["baseline"]["cookie"] for sample in samples]
    name = setup()
    origin = baseline(name)
    drained = loop(name, iterations, 250, origin)
    drained["baseline"] = origin
    rest = setup()
    fd = rawinotify.init()
    rawinotify.add_watch(fd, str(ROOT))
    os.rename(rest, rest + ".tmp")
    os.rename(rest + ".tmp", rest)
    after = rawinotify.drain_until_empty(fd)
    os.close(fd)
    out = {
        "iterations": iterations,
        "baseline": samples[0]["baseline"],
        "no_reader": full,
        "drained": drained,
        "queue_empty_after": {"events": len(after), "masks": rawinotify.names(after[0].mask) if after else []},
        "limits": {
            "max_queued_events": int(
                pathlib.Path("/proc/sys/fs/inotify/max_queued_events").read_text().strip()),
        },
    }
    (RESULTS / "02_overflow.json").write_text(json.dumps(out, indent=1))
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
Probe 03, the atomic deploys of section 6: 03_replace.py
"""Probe 03: an atomic deploy replaces the inode, and a file watch dies with it.

Three watchers, the same two hundred deploys, each deploy a rename of a fully written
temporary file over the target:

  * naive   - watch the file, act on MODIFY / CLOSE_WRITE, never look at the other masks;
  * rearm   - watch the file, and when the watch reports DELETE_SELF / IGNORED, add it
              again to the path;
  * namedir - watch the parent directory and match the file's own name on MOVED_TO.

The naive and rearm watchers are asked for the event latency from the rename returning
to the watcher having read the event; the namedir watcher is asked the same.
"""
from __future__ import annotations

import json
import os
import pathlib
import select
import statistics
import time

import rawinotify

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
ROOT = pathlib.Path("/tmp") / "tb23_replace"
MASK = rawinotify.IN_MODIFY | rawinotify.IN_CLOSE_WRITE | rawinotify.IN_ATTRIB \
    | rawinotify.IN_DELETE_SELF | rawinotify.IN_MOVE_SELF | rawinotify.IN_IGNORED


def deploy(target: str, content: bytes) -> None:
    """A deploy as every atomic writer does it: fill a temporary file, then rename it."""
    temporary = target + ".tmp"
    with open(temporary, "wb") as handle:
        handle.write(content)
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(temporary, target)


def wait_event(fd: int, timeout: float = 2.0) -> list[rawinotify.RawEvent]:
    ready, _, _ = select.select([fd], [], [], timeout)
    if not ready:
        return []
    return rawinotify.drain_until_empty(fd)


def naive(target: str, deploys: int) -> dict:
    fd = rawinotify.init()
    rawinotify.add_watch(fd, target, MASK)
    reloads = 0
    masks: dict[str, int] = {}
    latencies: list[float] = []
    for index in range(deploys):
        started = time.perf_counter_ns()
        deploy(target, f"v{index}\n".encode())
        events = wait_event(fd, 0.2)
        for event in events:
            for label in rawinotify.names(event.mask):
                masks[label] = masks.get(label, 0) + 1
        if any(event.mask & (rawinotify.IN_MODIFY | rawinotify.IN_CLOSE_WRITE)
               for event in events):
            reloads += 1
            latencies.append((time.perf_counter_ns() - started) / 1000)
    # After the last deploy: write to the path by name and see whether the dead watch fires.
    with open(target, "a") as handle:
        handle.write("after\n")
    after = rawinotify.drain_until_empty(fd)
    os.close(fd)
    return {"deploys": deploys, "reloads": reloads, "misses": deploys - reloads,
            "masks": masks, "latency_us": summarize(latencies),
            "events_after_dead_watch": len(after)}


def rearm(target: str, deploys: int) -> dict:
    fd = rawinotify.init()
    wd = rawinotify.add_watch(fd, target, MASK)
    reloads = 0
    rearms = 0
    latencies: list[float] = []
    masks: dict[str, int] = {}
    for index in range(deploys):
        started = time.perf_counter_ns()
        deploy(target, f"v{index}\n".encode())
        events = wait_event(fd)
        for event in events:
            for label in rawinotify.names(event.mask):
                masks[label] = masks.get(label, 0) + 1
            if event.mask & (rawinotify.IN_DELETE_SELF | rawinotify.IN_IGNORED
                             | rawinotify.IN_MOVE_SELF):
                new_wd = rawinotify.add_watch(fd, target, MASK)
                rearms += new_wd != wd
                wd = new_wd
        if events:
            reloads += 1
            latencies.append((time.perf_counter_ns() - started) / 1000)
    os.close(fd)
    return {"deploys": deploys, "reloads": reloads, "misses": deploys - reloads,
            "rearms": rearms, "masks": masks, "latency_us": summarize(latencies)}


def namedir(target: str, deploys: int) -> dict:
    directory = os.path.dirname(target)
    name = os.path.basename(target)
    fd = rawinotify.init()
    rawinotify.add_watch(fd, directory, MASK | rawinotify.IN_MOVED_TO
                         | rawinotify.IN_MOVED_FROM)
    reloads = 0
    pairs = 0
    latencies: list[float] = []
    masks: dict[str, int] = {}
    total_events = 0
    for index in range(deploys):
        started = time.perf_counter_ns()
        deploy(target, f"v{index}\n".encode())
        events = wait_event(fd)
        total_events += len(events)
        for event in events:
            for label in rawinotify.names(event.mask):
                masks[label] = masks.get(label, 0) + 1
        moved = [event for event in events
                 if event.mask & rawinotify.IN_MOVED_TO and event.name == name]
        if moved:
            reloads += 1
            latencies.append((time.perf_counter_ns() - started) / 1000)
        cookies = {event.cookie for event in events if event.cookie}
        pairs += len(cookies)
    os.close(fd)
    return {"deploys": deploys, "reloads": reloads, "misses": deploys - reloads,
            "events": total_events, "cookies": pairs, "masks": masks,
            "latency_us": summarize(latencies)}


def summarize(samples: list[float]) -> dict:
    if not samples:
        return {"n": 0}
    ordered = sorted(samples)
    return {"n": len(ordered), "min_us": round(ordered[0], 1),
            "p50_us": round(statistics.median(ordered), 1),
            "p95_us": round(ordered[int(len(ordered) * 0.95) - 1], 1),
            "max_us": round(ordered[-1], 1)}


def main() -> None:
    ROOT.mkdir(parents=True, exist_ok=True)
    target = str(ROOT / "app.conf")
    pathlib.Path(target).write_text("v0\n")
    naive_result = naive(target, 200)
    pathlib.Path(target).write_text("v0\n")
    rearm_result = rearm(target, 200)
    pathlib.Path(target).write_text("v0\n")
    namedir_result = namedir(target, 200)
    out = {"naive": naive_result, "rearm": rearm_result, "namedir": namedir_result,
           "mask_asked": MASK}
    (RESULTS / "03_replace.json").write_text(json.dumps(out, indent=1))
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
Probe 04, the ConfigMap layout, its cleanup and five watchers: 04_symlink.py
"""Probe 04: the Kubernetes ConfigMap layout, reproduced as a local directory tree.

kubelet publishes a ConfigMap as a chain of symlinks:

    config/app.conf  ->  ..data/app.conf
    config/..data    ->  ..2026_11_21_00_00_00_000/

and an update writes a new timestamped directory, renames a new ..data symlink over the
old one, and then removes the timestamped directory the old link selected - the cleanup
step of kubelet's AtomicWriter. The file a process watches by path is not the file the
next update writes, and the file it did watch is deleted once the swap is done.

Five watchers and fifty updates:

  * pathwatch - add_watch("config/app.conf"), which follows the symlink at add time;
  * rearmwatch - the same watch, re-added after DELETE_SELF or IGNORED;
  * datawatch - add_watch("config/..data"), the directory the symlink pointed at;
  * dirwatch  - add_watch("config"), matching any MOVED_TO that names ..data;
  * pollwatch - no inotify: compare (st_dev, st_ino) of the path every 50 ms.

The cleanup is what makes the fourth mask observable: a path watch that would otherwise
report nothing at all reports DELETE_SELF and IGNORED for the old file when its directory
is removed, and a watcher that re-adds on those masks ends up on the new file.
"""
from __future__ import annotations

import json
import os
import pathlib
import select
import shutil
import statistics
import threading
import time

import rawinotify

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
ROOT = pathlib.Path("/tmp") / "tb23_configmap"
MASK = (rawinotify.IN_MODIFY | rawinotify.IN_CLOSE_WRITE | rawinotify.IN_ATTRIB
        | rawinotify.IN_CREATE | rawinotify.IN_DELETE | rawinotify.IN_MOVED_FROM
        | rawinotify.IN_MOVED_TO | rawinotify.IN_DELETE_SELF | rawinotify.IN_MOVE_SELF
        | rawinotify.IN_IGNORED)
# A content change is a write the application could reload from. IN_ATTRIB is a metadata
# event - the cleanup's unlink of the old file changes its link count - and no reload rests
# on it, so it is counted separately rather than as an update seen.
CONTENT = rawinotify.IN_MODIFY | rawinotify.IN_CLOSE_WRITE


def stamp(version: int) -> str:
    return f"..2026_11_21_00_0{version}_00_000"


def build(version: int) -> pathlib.Path:
    if ROOT.exists():
        shutil.rmtree(ROOT)
    config = ROOT / "config"
    config.mkdir(parents=True)
    target = config / stamp(version)
    target.mkdir()
    (target / "app.conf").write_text(f"version={version}\n")
    (config / "..data").symlink_to(stamp(version))
    (config / "app.conf").symlink_to("..data/app.conf")
    return config


def update(config: pathlib.Path, version: int) -> None:
    """One AtomicWriter update: new directory, new contents, ..data_tmp -> ..data, cleanup."""
    target = config / stamp(version)
    target.mkdir()
    (target / "app.conf").write_text(f"version={version}\n")
    temporary = config / "..data_tmp"
    temporary.symlink_to(stamp(version))
    os.replace(temporary, config / "..data")
    # The last step of kubelet's AtomicWriter: the directory the previous link selected is
    # removed. Nothing that was watched inside it survives, and the kernel says so.
    previous = config / stamp(version - 1)
    if previous.is_dir():
        shutil.rmtree(previous)


def wait_event(fd: int, timeout: float = 0.3) -> list[rawinotify.RawEvent]:
    ready, _, _ = select.select([fd], [], [], timeout)
    return rawinotify.drain_until_empty(fd) if ready else []


def count_masks(events: list[rawinotify.RawEvent], masks: dict[str, int]) -> None:
    for event in events:
        for label in rawinotify.names(event.mask):
            masks[label] = masks.get(label, 0) + 1


def pathwatch(updates: int) -> dict:
    config = build(0)
    fd = rawinotify.init()
    rawinotify.add_watch(fd, str(config / "app.conf"), MASK)
    seen = 0
    content = 0
    first_self: int | None = None
    masks: dict[str, int] = {}
    for version in range(1, updates + 1):
        update(config, version)
        events = wait_event(fd)
        seen += len(events)
        content += sum(1 for event in events if event.mask & CONTENT)
        for event in events:
            if event.mask & (rawinotify.IN_DELETE_SELF | rawinotify.IN_IGNORED):
                first_self = first_self or version
        count_masks(events, masks)
    # The watch is gone, so a write to the path the name now resolves to is invisible.
    (config / "app.conf").resolve().write_text("version=edited\n")
    after = wait_event(fd)
    os.close(fd)
    return {"updates": updates, "events": seen, "content_change_events": content,
            "misses": updates - content, "event_masks": masks,
            "first_self_event_update": first_self,
            "events_after_edit_through_path": len(after)}


def rearmwatch(updates: int) -> dict:
    """Re-add on DELETE_SELF/IGNORED, then read the path: the watch follows the new link."""
    config = build(0)
    fd = rawinotify.init()
    rawinotify.add_watch(fd, str(config / "app.conf"), MASK)
    rearms = 0
    reloads = 0
    correct = 0
    latencies: list[float] = []
    for version in range(1, updates + 1):
        started = time.perf_counter_ns()
        update(config, version)
        events = wait_event(fd)
        if any(event.mask & (rawinotify.IN_DELETE_SELF | rawinotify.IN_IGNORED)
               for event in events):
            rearms += 1
            rawinotify.add_watch(fd, str(config / "app.conf"), MASK)
            if config.joinpath("app.conf").read_text() == f"version={version}\n":
                correct += 1
            reloads += 1
            latencies.append((time.perf_counter_ns() - started) / 1000)
    os.close(fd)
    return {"updates": updates, "rearms": rearms, "reloads": reloads,
            "misses": updates - reloads, "versions_read_correctly": correct,
            "latency_us": summarize(latencies)}


def dirwatch(updates: int) -> dict:
    config = build(0)
    fd = rawinotify.init()
    rawinotify.add_watch(fd, str(config), MASK)
    reloads = 0
    correct = 0
    events_total = 0
    masks: dict[str, int] = {}
    latencies: list[float] = []
    for version in range(1, updates + 1):
        started = time.perf_counter_ns()
        update(config, version)
        events = wait_event(fd)
        events_total += len(events)
        count_masks(events, masks)
        if any(event.mask & rawinotify.IN_MOVED_TO and event.name == "..data"
               for event in events):
            reloads += 1
            latencies.append((time.perf_counter_ns() - started) / 1000)
            if (config / "app.conf").read_text() == f"version={version}\n":
                correct += 1
    os.close(fd)
    return {"updates": updates, "reloads": reloads, "misses": updates - reloads,
            "versions_read_correctly": correct, "events": events_total,
            "event_masks": masks, "latency_us": summarize(latencies)}


def datawatch(updates: int) -> dict:
    config = build(0)
    fd = rawinotify.init()
    rawinotify.add_watch(fd, str(config / "..data"), MASK)
    seen = 0
    content = 0
    masks: dict[str, int] = {}
    for version in range(1, updates + 1):
        update(config, version)
        events = wait_event(fd)
        seen += len(events)
        content += sum(1 for event in events if event.mask & CONTENT)
        count_masks(events, masks)
    os.close(fd)
    return {"updates": updates, "events": seen, "content_change_events": content,
            "misses": updates - content, "event_masks": masks}


def pollwatch(updates: int, interval_ms: float = 50.0) -> dict:
    """A poller that is already running: its detection waits for the next check, so the
    latency is spread over the whole interval instead of landing on a stat made right
    after the update."""
    config = build(0)
    path = config / "app.conf"
    stop = threading.Event()
    seen: dict[str, float] = {}
    state = {"inode": os.stat(path).st_ino, "started_ns": 0}

    def poll() -> None:
        while not stop.is_set():
            now = os.stat(path)
            if state["started_ns"] and now.st_ino != state["inode"]:
                seen["latency_us"] = (time.perf_counter_ns() - state["started_ns"]) / 1000
                state["started_ns"] = 0
                state["inode"] = now.st_ino
            time.sleep(interval_ms / 1000)

    worker = threading.Thread(target=poll, daemon=True)
    worker.start()
    latencies: list[float] = []
    reloads = 0
    for version in range(1, updates + 1):
        state["inode"] = os.stat(path).st_ino
        seen.clear()
        state["started_ns"] = time.perf_counter_ns()
        update(config, version)
        deadline = time.perf_counter() + 2.0
        while time.perf_counter() < deadline:
            if "latency_us" in seen:
                latencies.append(seen["latency_us"])
                reloads += 1
                break
            time.sleep(0.001)
        time.sleep(interval_ms / 1000)
    stop.set()
    worker.join(timeout=1)
    return {"updates": updates, "reloads": reloads, "misses": updates - reloads,
            "interval_ms": interval_ms, "latency_us": summarize(latencies)}


def summarize(samples: list[float]) -> dict:
    if not samples:
        return {"n": 0}
    ordered = sorted(samples)
    return {"n": len(ordered), "min_us": round(ordered[0], 1),
            "p50_us": round(statistics.median(ordered), 1),
            "p95_us": round(ordered[int(len(ordered) * 0.95) - 1], 1),
            "max_us": round(ordered[-1], 1)}


def main() -> None:
    out = {
        "updates": 50,
        "pathwatch": pathwatch(50),
        "rearmwatch": rearmwatch(50),
        "dirwatch": dirwatch(50),
        "datawatch": datawatch(50),
        "pollwatch": pollwatch(50),
        "layout": {
            "link": "config/app.conf -> ..data/app.conf",
            "data": "config/..data -> ../..2026_11_21_00_00_00_000",
            "symlink_levels": 2,
            "cleanup": "rmtree of the previous timestamped directory after the swap",
        },
    }
    (RESULTS / "04_symlink.json").write_text(json.dumps(out, indent=1))
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
Probe 07, the deploy shapes, their re-arms, and two windows: 07_endtoend.py
"""Probe 07: three deploy shapes against two designs, fifty of each, at two debounce windows.

The deploy shapes are the three a production system actually uses:

  * in_place       - open the file and write it;
  * atomic_replace - write a temporary file and rename it over the target;
  * symlink_swap   - the Kubernetes ConfigMap layout: a new directory, then a new
                     ..data symlink renamed over the old one, and then the old
                     directory removed, which is the last step of kubelet's
                     AtomicWriter.

The designs are the one this article's probe 03 measured failing and the module this
article ships:

  * naive     - watch the file, act on MODIFY / CLOSE_WRITE, nothing else;
  * watchguard- the ConfigReloader, which watches the naming directory as well and
                re-arms when the file's identity changes.

A reload counts only when the callback receives the version that was deployed, so a
watcher cannot pass by firing on a stale read. The last arm buries one config change in a
rename storm big enough to overflow the queue, which is the case the queue cannot report
and only a re-read can repair.

The symlink-swap arm ends every deploy the way kubelet does, by removing the timestamped
directory the previous link selected. That removal is the one record the file watch gets
from the deploy - DELETE_SELF and IGNORED for the file it was added to - so the reloader
re-arms and reads the new version, and its reloads arrive through RESYNC instead of
through the change window. Reloads are therefore counted by the state they were delivered
from, and the RESYNC transitions are recorded next to the latency.

Every reloader arm runs twice, at two windows: WINDOW_FAST, the 0.0 s window the other
probes use, which shows what a callback costs on its own; and WINDOW_RECOMMENDED, the
0.05 s quiet window the deploy order prescribes. The two differ in where the delay comes
from. An in-place write is a change, so the callback waits out the window before it runs.
A deploy that replaces the inode ends the watch, and the RESYNC that follows re-arms and
reads on the tick it is noticed on, so it never reaches the debouncer and its delay stays
in microseconds whatever the window is. Latency is kept per delivering state for the same
reason: one atomic replace in fifty does arrive through the change window, and how long
that one took is a different fact from how long its forty-nine re-arms took.
"""
from __future__ import annotations

import json
import os
import pathlib
import select
import shutil
import statistics
import sys
import time

import rawinotify

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
MODULE = HERE.parent / "module"
sys.path.insert(0, str(MODULE))

from watchguard import ConfigReloader  # noqa: E402 - after the path is set

ROOT = pathlib.Path("/tmp") / "tb23_endtoend"
DEPLOYS = 50
SHAPES = ("in_place", "atomic_replace", "symlink_swap")
WINDOW_FAST = 0.0            # what every other probe measures with: no quiet window
WINDOW_RECOMMENDED = 0.05    # the quiet window the deploy order tells a reader to set
HOLD_S = 0.2                 # the hold limit is not what these arms vary
DELIVERING = ("RELOADING", "RESYNC")
NAIVE_MASK = rawinotify.IN_MODIFY | rawinotify.IN_CLOSE_WRITE


def layout() -> pathlib.Path:
    """A ConfigMap-shaped tree: config/app.conf -> ..data/app.conf, ..data -> ..stamp/."""
    if ROOT.exists():
        shutil.rmtree(ROOT)
    config = ROOT / "config"
    config.mkdir(parents=True)
    history = config / "..2026_11_21_00_00_00"
    history.mkdir()
    (history / "app.conf").write_text("version=0\n")
    (config / "..data").symlink_to(history.name)
    (config / "app.conf").symlink_to("..data/app.conf")
    return config


def deploy(config: pathlib.Path, shape: str, version: int) -> None:
    path = config / "app.conf"
    text = f"version={version}\n"
    if shape == "in_place":
        path.write_text(text)
    elif shape == "atomic_replace":
        temporary = config / "app.conf.new"
        temporary.write_text(text)
        os.replace(temporary, path)
    elif shape == "symlink_swap":
        history = config / f"..2026_11_21_00_00_{version:02d}"
        history.mkdir()
        (history / "app.conf").write_text(text)
        staged = config / "..data_tmp"
        staged.symlink_to(history.name)
        os.replace(staged, config / "..data")
        # kubelet's AtomicWriter closes a publish by removing the directory the previous
        # link selected. Without it the deploy is a swap nobody cleans up after, and the
        # file watch would outlive the file it is on.
        previous = config / f"..2026_11_21_00_00_{version - 1:02d}"
        if previous.is_dir():
            shutil.rmtree(previous)
    else:
        raise SystemExit(f"unknown shape {shape}")


def naive(config: pathlib.Path, shape: str, deploys: int) -> dict:
    path = config / "app.conf"
    fd = rawinotify.init()
    wd = rawinotify.add_watch(fd, str(path), NAIVE_MASK)
    reloads = 0
    wrong = 0
    for version in range(1, deploys + 1):
        deploy(config, shape, version)
        deadline = time.monotonic() + 0.2
        fired = False
        while time.monotonic() < deadline and not fired:
            ready, _, _ = select.select([fd], [], [], 0.02)
            for event in rawinotify.drain_until_empty(fd) if ready else []:
                if event.wd == wd and event.mask & NAIVE_MASK:
                    fired = True
        if fired:
            reloads += 1
            if path.read_text() != f"version={version}\n":
                wrong += 1
    os.close(fd)
    return {"deploys": deploys, "reloads": reloads, "misses": deploys - reloads,
            "wrong_content": wrong}


def watchguard(config: pathlib.Path, shape: str, deploys: int, window_s: float) -> dict:
    path = config / "app.conf"
    seen: list[str] = []
    delivered = {state: 0 for state in DELIVERING}
    marks: list[tuple[float, str]] = []
    anchor = [0]
    reloader: ConfigReloader

    def on_reload(text: str) -> None:
        # The state the callback is called from says which path delivered the reload:
        # RELOADING is the change window, RESYNC is the re-arm after the watch ended.
        # The delay is taken here, against the deploy that caused it, so it carries the
        # state that produced it instead of being attached to the deploy afterwards.
        state = reloader.state.value
        seen.append(text)
        delivered[state] = delivered.get(state, 0) + 1
        marks.append(((time.perf_counter_ns() - anchor[0]) / 1000, state))

    reloader = ConfigReloader(path, on_reload, window_s=window_s, hold_s=HOLD_S)
    reloader.start()
    for version in range(1, deploys + 1):
        anchor[0] = time.perf_counter_ns()
        deploy(config, shape, version)
        deadline = time.monotonic() + 1.0
        while time.monotonic() < deadline and reloader.reloads < version:
            reloader.run_once(0.005)
    reloader.stop()
    correct = sum(1 for index, text in enumerate(seen, start=1)
                  if text == f"version={index}\n")
    resyncs = sum(1 for _, to_state, _ in reloader.transitions if to_state == "RESYNC")
    return {"deploys": deploys, "window_s": window_s, "hold_s": HOLD_S,
            "reloads": reloader.reloads, "misses": deploys - reloader.reloads,
            "correct_content": correct,
            "latency_us": summarize([latency for latency, _ in marks]),
            "latency_by_state": {state: summarize([latency for latency, from_state in marks
                                                   if from_state == state])
                                 for state in DELIVERING},
            "resyncs": resyncs, "reloads_by_state": delivered,
            "states_exercised": sorted({state for _, state, _ in reloader.transitions})}


def storm(config: pathlib.Path) -> dict:
    """One change, then eighteen thousand events that are not it."""
    path = config / "app.conf"
    seen: list[str] = []
    reloader = ConfigReloader(path, seen.append, window_s=WINDOW_FAST)
    reloader.start()
    path.write_text("version=99\n")
    other = config / "churn"
    other.write_text("x")
    started = time.perf_counter_ns()
    for _ in range(9200):
        os.rename(other, str(other) + ".tmp")
        os.rename(str(other) + ".tmp", other)
    elapsed_ms = (time.perf_counter_ns() - started) / 1e6
    deadline = time.monotonic() + 2.0
    while time.monotonic() < deadline and reloader.reloads == 0:
        reloader.run_once(0.01)
    state = reloader.state.value
    reloader.stop()
    return {"renames": 18400, "storm_ms": round(elapsed_ms, 1),
            "reloads": len(seen), "content": seen[-1].strip() if seen else None,
            "state_after": state}


def summarize(samples: list[float]) -> dict:
    if not samples:
        return {"n": 0}
    ordered = sorted(samples)
    return {"n": len(ordered), "p50_us": round(statistics.median(ordered), 1),
            "p95_us": round(ordered[int(len(ordered) * 0.95) - 1], 1),
            "max_us": round(ordered[-1], 1)}


def main() -> None:
    out: dict[str, object] = {
        "deploys_per_shape": DEPLOYS,
        "window_cfg": {"fast": WINDOW_FAST, "recommended": WINDOW_RECOMMENDED,
                       "hold_s": HOLD_S},
        "naive": {}, "watchguard": {}, "watchguard_50ms": {},
    }
    for shape in SHAPES:
        config = layout()
        out["naive"][shape] = naive(config, shape, DEPLOYS)
        config = layout()
        out["watchguard"][shape] = watchguard(config, shape, DEPLOYS, WINDOW_FAST)
        config = layout()
        out["watchguard_50ms"][shape] = watchguard(config, shape, DEPLOYS,
                                                   WINDOW_RECOMMENDED)
    config = layout()
    out["storm"] = storm(config)
    (RESULTS / "07_endtoend.json").write_text(json.dumps(out, indent=1))
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()

Take the next step


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.