Skip to content

fix(realtime): admit file events before resolving and skip linked directories in walks - #485

Open
fstrasz wants to merge 32 commits into
chunkhound:mainfrom
fstrasz:fix/watcher-link-position
Open

fstrasz wants to merge 32 commits into
chunkhound:mainfrom
fstrasz:fix/watcher-link-position

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Realtime no longer resolves a filesystem event's path before deciding whether to admit it. A directory reached through a junction or symlink is now neither walked nor indexed by realtime, which matches the default startup scan.

Depends on #481, which this branch contains by merge. This PR's own change over #481 is six files, all realtime: realtime/events.py, realtime/pipeline.py, realtime/service.py, realtime_path_filter.py, core/utils/path_utils.py and tests/realtime/test_filter_consistency_realtime_cleanup.py (+378/-49). It has no lines in the ignore engine. The realtime_path_filter.py change is one keyword: should_index(..., check_target=False) judges a path where it sits, which item 5's delete rule needs. Once #481 merges, main is merged in here (the branch is not rebased or force-pushed); the diff then shows only these six files, and the squash merge leaves one commit on main.

Why. npm install links a local file: dependency into node_modules/ as a junction (Windows) or a symlink. #481 made the ignore engine judge a path by where it sits in the tree, but two realtime paths still resolved or followed the link first:

  1. SimpleEventHandler resolved every event's path before the admission filter. A file under root/node_modules/@scope/pkg/ therefore reached the filter as the link's target outside the root, where no root-relative rule applies. It was admitted, then failed at the store with "not in the subpath", about 4 s per file in our logs. Resolving every event first was also the dominant cost of a burst, including for events the filter then rejected.
  2. The polling snapshot and new-directory expansion walked with rglob, which descends junctions.

What changes

  1. Admission before resolve. File events, both sides of a move, and created directories are now judged on their absolute, unresolved path. A rejected event is never resolved. An admitted path is resolved and queued in resolved form, as before. The service's source/filtered/event-pressure bookkeeping keeps a path that is already spelled under the watch root as it is. Mutation keys still use full normalisation.
  2. Walks prune excluded and linked directories. Both walks share one os.walk. It prunes a directory that the ignore rules exclude at its in-tree path, or that is a junction. os.walk already skips symlinks. Junctions are detected by their mount-point reparse tag only, so OneDrive and dedup placeholders, which are reparse points too, stay ordinary directories.

Items 3 and 4 are #481's ignore-engine change (now in chunkhound/utils/gitignore_rules.py), reviewed there. They are described here because item 2's pruning relies on them.

  1. A directory match means nothing beneath it can be included. Every caller reads it that way: the realtime walk and directory events, the Python full-scan walker and its os.walk fallback, and repo-root detection. Pruning on it exposed answers that did not hold:

    • Under git's whitelist idiom (/*, then !/src/), src/ was reported excluded while every file in it was included, so a pruning walk never saw src/.
    • With foo/** then !foo/bar.py, or src/.gitignore holding ** then !keep.py, git keeps the file and the full scan indexes it, but foo/ and src/ were reported excluded, so realtime never saw it. Main gives the same wrong answer; pruning made it matter.

    Per ignore spec, a directory is now excluded when either:

    • git excludes the directory itself. The last pattern that matches it is not a negation; a pattern is matched against the path itself, without pathspec's implicit "and everything below", and a directory pattern (foo/) only against directories. A directory below an excluded directory stays excluded even if a negation matches it, as in git.
    • or a file pattern covers its contents (foo/**, the default **/node_modules/**) and no negation in that spec could match beneath it. Config excludes have no negations, so node_modules is still pruned without being walked.

    So foo/** then !foo/bar.py leaves foo/ walkable, and each file in it is decided on its own. The libgit2 backend's config-exclude layer uses the same rule; libgit2 decides .gitignore files itself.

  2. Files follow git when a negation matches them. The file is then decided as git decides it: the last matching pattern wins, a directory pattern matches only directories, and an excluded parent directory wins. A file that no negation matches keeps pathspec's answer, which is then git's. Before, pathspec matched !foo/bar/ against every file below it, so foo/** then !foo/bar/ re-included foo/bar/x.py, which git ignores.

  3. A link's target is checked before it is queued. Item 1 judged an event only by its unresolved path, so a file link alias.py -> node_modules/pkg/secret.py was admitted as alias.py and queued as secret.py. When resolving changes the path, the target now has to pass the same policy before created or modified work is queued; a created directory is checked with excludes_directory. A rejected event is still never resolved. A delete is judged where the path sits and its target is not checked, so a previously indexed path is still cleaned up.

Items 3 to 5 in this form come from VakninAriel's reviews of #490 and #491, which are stacked on this PR.

Implementation notes.

  • The .gitignore transform emits the same strings as before (foo/ still compiles to foo/**); the "was a directory pattern" flag is carried beside the compiled spec.
  • The engine reads pathspec's compiled pattern objects, which are not public API. fix(realtime): exclude linked directories by their place in the tree #481 bounds pathspec to the majors this is tested against (>=0.12.1,<2). The main test matrix runs the locked 0.12.1; a pathspec-1x CI job installs the newest 1.x over the lock and runs tests/ignore and tests/realtime/test_filter_consistency_realtime_cleanup.py. tests/ignore/test_pathspec_contract.py compares the engine with git check-ignore on rules pathspec alone decides differently, so a pathspec release that changes the pattern shape turns that job red. At runtime the engine then falls back to pathspec's own answers with no pruning, and logs one warning.
  • pathspec 1.x spells the tail of a compiled pattern differently from 0.12 and applies its regexes with re.search; the engine reads both. Before that, under an installed 1.x, any plain or glob line (Thumbs.db, *.log) degraded its whole spec, so no directory was pruned. On Windows, tests/ignore passes at this head under both 0.12.1 and 1.1.1 (tests/ignore plus tests/realtime/test_filter_consistency_realtime_cleanup.py: 46 passed under each).
  • Git's answer for each directory is memoized per compiled spec. The rules never change while the spec lives, so there is nothing to invalidate; the memo is bounded. With 1,806 patterns including * !*/ !*.py, 2,000 file decisions take about 1.8 s (1.7 s at a902b55), and 2,000 directory checks 0.9 s (1.6 s).
  • Still different from git, as on main: **/ and /**/ patterns in a .gitignore. The fallback above also stops pruning config excludes.

Behaviour change, intended. For a watchdog file event, either side of a move, or a created-directory event, an admitted path whose resolved form is outside the root is now rejected and recorded as filtered. Example: root/vendor/pkg linked to a directory outside the repo, where vendor/ is not excluded. Realtime used to queue such files, and the store then rejected each one. The default startup scan (the Rust scanner, WalkBuilder without follow_links) never indexes them. Realtime now agrees with it. The Python fallback walker does follow junctions on Windows, so with CHUNKHOUND_USE_RUST=0 the startup scan and realtime still differ for files behind an included junction, as they did before. Deletes of previously indexed files keep their existing admission exception. Known limit, unchanged from main: new-directory expansion still judges each file it finds by its patterns only. A file symlink inside a new directory that points at an included file outside the root is therefore admitted, as on main. We can follow up on that separately if wanted.

Watchman events do not pass through this admission step: WatchmanRealtimeAdapter spells each path under its subscription scope's logical path, nested junction scopes included, and RealtimeContext admits it. A file in a junction scope that resolves outside the target is still indexed under its logical path, as test_watchman_junction_scope_translation_preserves_logical_path checks; it passes at this head on Windows (-k junction_scope: 3 passed). One change does reach Watchman, and every other backend: new-directory expansion no longer descends a junction found inside a newly created directory (item 2), which rglob did.

Measured at a902b55 on Windows 11, Python 3.13, with stock watchdog. A junction to a real 48,253-entry node_modules was created under the watched root. The handler was wired as the running service wires it (source, filtered, admission and queue callbacks), plus a status consumer that deep-copies each snapshot. Each run handled the first 5,000 of the 48,255 events, because the "before" run would take about 8 minutes in full:

Queued Seconds for 5,000 events ms per event
Before (#481) 0 52.67 10.53
After 0 6.54 1.31

Path.resolve was called 1,400 times for 200 rejected events before, and 0 times after. Without the status consumer, the "after" figure is 0.73 ms per event. Per-event status snapshots account for the rest; realtime has no throttle on them today.

Linking an included vendor/pkg to an outside directory of .py files, then writing a file through the link, queued nothing under the link or its target. An in-tree control file was still queued.

Tests in tests/realtime/test_filter_consistency_realtime_cleanup.py. Tests 1 to 6 each fail with their fix reverted; 7 and 8 are guards:

  1. A file event under an excluded link is not queued (judged at its in-tree position).
  2. A file event under an included link whose target leaves the root is not queued.
  3. The polling snapshot never walks or counts files behind an excluded or an included link, while an in-tree file is still returned.
  4. The polling snapshot keeps a directory that a .gitignore whitelist re-includes. With the old matcher it returned [].
  5. Eleven .gitignore cases, each checked against git check-ignore: the full scan, the polling walk and event admission all agree with git. Ten fail at a902b55; the plain whitelist case already passed there.
  6. A file link to an excluded target is not queued. It fails at a902b55.
  7. The walk never enters an excluded node_modules.
  8. tests/ignore/test_pathspec_contract.py: the compiled pattern objects still have the shape the engine reads.

Run serially on Windows: tests/realtime, the test_realtime_* modules, tests/ignore, every test module that imports the ignore engine or file_patterns, and tests/test_smoke.py. Result: 8 failed, 323 passed, 35 skipped. The same 8 fail without this change, on main plus #481 (test_watchman_relative_root_mapping_and_filtering, three in test_realtime_failures.py, four in test_realtime_functional.py). That was at a902b55.

Full suite at this head (0d4f44f, which includes current main), serially on Windows: 6,146 passed, 509 skipped. Its 33 failures also fail at the previous head 81f1715, except 5 load flakes that pass on rerun, so none is new. At e6b49bb, serially on Windows, tests/realtime, tests/ignore, tests/test_realtime_functional.py and tests/test_watchman_runtime_resources.py: 169 passed, 57 skipped, 0 failed. After #481 was merged in, the pre-review head (2299525) gave 168 passed and 1 failed: test_file_alias_to_excluded_target_is_not_queued. #481's filter now also checks a link's target, so the delete of a link to an excluded file was dropped. e6b49bb judges a delete where the path sits (item 5).

Earlier, full suite at 6e32b20, serially on Windows, against a902b55: 5,382 passed (5,358), 78 failed (88), 75 errors (75), 123 skipped (123). No test fails at 6e32b20 that passes at a902b55. The failures both share are environmental on this machine: uv run chunkhound CLI subprocess timeouts, MCP and daemon smoke tests, the docs-site tests, LLM-configuration tests, and simulate tests that need a newer native module than the one installed here. Upstream's CI workflow on our fork at 6e32b20 is green on every job: https://github.com/fstrasz/chunkhound/actions/runs/43256124453. For #481's head of this round (c20d46f), the fork run (with our Rust toolchain pin and the macOS jobs turned off) passed every code job, including the new pathspec-1x job: https://github.com/fstrasz/chunkhound/actions/runs/45440594707. Its one cancelled job, the macOS docs-site build, got no macOS runner from GitHub.

🤖 Generated with Claude Code, reviewed by FStrasz

fstrasz and others added 3 commits November 6, 2026 10:27
`npm install` links a local `file:` dependency into node_modules/ as a
junction (a symlink elsewhere). The ignore engine resolved every path
before matching, so a file behind that link was matched at its target,
outside the root, where no root-relative rule such as `node_modules/**`
applies. Realtime then indexed it:

- A directory created above the link was walked with rglob, which
  descends the junction, and its files passed the filter and were stored
  under node_modules/.
- A directory event for the link itself was resolved to the target and
  walked from there; every file failed at the store step ("not in the
  subpath").

The startup scan already prunes excluded directories by their in-tree
path, so only realtime was affected.

Ignore rules now match a path by its location under the root, falling
back to the resolved path only when it is not lexically under the root.
A created directory that an ignore rule excludes is dropped before it is
resolved or walked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`npm install` links a local `file:` dependency into node_modules/ as a
junction (a symlink elsewhere). The ignore engine resolved every path
before matching, so a file behind that link was matched at its target,
outside the root, where no root-relative rule such as `node_modules/**`
applies. Realtime then indexed it:

- A directory created above the link was walked with rglob, which
  descends the junction, and its files passed the filter and were stored
  under node_modules/.
- A directory event for the link itself was resolved to the target and
  walked from there; every file failed at the store step ("not in the
  subpath").

The startup scan already prunes excluded directories by their in-tree
path, so only realtime was affected.

Ignore rules now match a path by its location under the root, falling
back to the resolved path only when it is not lexically under the root.
A created directory that an ignore rule excludes is dropped before it is
resolved or walked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ectories in walks

293f8a6 made the ignore engine match a path by its location under the
root, and dropped an excluded created directory before walking it. Two
other realtime paths still resolved or followed a directory link (an npm
junction under node_modules/, or a symlink) before asking where it sits.

A. Admission before resolve. SimpleEventHandler resolved every file
   event's path before the admission filter. A file under
   root/node_modules/@scope/pkg/ then reached the filter as the link's
   target outside the root, where no root-relative rule applies, so it was
   admitted and failed at the store ("not in the subpath"). Resolving
   first also cost about 0.67 ms per event, paid for every event,
   including the ones the filter then rejected.

   File events, both sides of a move, and created directories are now
   judged on their absolute, unresolved path. A rejected event is never
   resolved, and source and filtered events are recorded with that
   unresolved path. Only an admitted path is resolved, and it is still
   queued in resolved form.

   The service's event bookkeeping (source and filtered recording, and
   event-pressure tracking) normalised every path through
   normalize_realtime_path, which resolves it. A path already spelled
   under the watch root is now kept as is there. Anything else is
   normalised as before. The key differs from full normalisation only for
   a path through a link whose target is also in the tree, or one the
   filesystem spells differently (8.3 short names, letter case).

   An admitted path whose resolved form is outside the root is now
   rejected and recorded as filtered. This is an intended behaviour
   change: it makes realtime match the default startup scan. The Rust
   scanner does not follow directory symlinks or junctions, so it never
   indexes such a file. Realtime used to queue it, and the store then
   failed on it ("not in the subpath", about 4 s per file). Example:
   root/vendor/pkg linked to a directory outside the root, where vendor/
   is not excluded. Deletes of previously indexed files keep their
   existing admission exception.

C. Realtime walks. _polling_snapshot and _collect_supported_files used
   rglob, which descends junctions. Both now share one os.walk that
   prunes a directory when the ignore rules exclude it at its in-tree
   path, and also when it is a directory link. os.walk already skips
   symlinks. Junctions are detected by their mount-point reparse tag
   only, because OneDrive and deduplication placeholders are reparse
   points too and are ordinary directories. This also matches the
   default Rust scan. The polling snapshot keeps its 5000-file cap and
   its error tolerance.

   Pruning by directory exposed an older matching bug. IgnoreEngine and
   the config-exclude check matched a directory by its bare name as well
   as its "dir/" form. Under git's whitelist idiom ("/*", then "!/src/"),
   the bare "src" matches "/*" but not the dir-only re-include, so src/
   was reported excluded while every file in it was included. A pruning
   walk then never saw src/ at all. A directory is now matched in its
   "dir/" form only, as git does. Default excludes such as
   **/node_modules/**, node_modules/ and node_modules still match it. The
   Python fallback walker, which prunes through the same engine, gets the
   same correction.

Measured on Windows with stock watchdog. A junction to a 48,253-entry
node_modules was created under the watched root, with the handler wired
as the running service wires it: its source, filtered, admission and
queue callbacks, plus a status callback that deep-copies each snapshot,
as the MCP daemon's does. Both runs handled the first 5,000 of the
48,255 events, because the 293f8a6 run would take about 8 minutes in
full:
  293f8a6: 0 queued, 52.67 s, 10.53 ms per event
  this fix: 0 queued,  6.54 s,  1.31 ms per event
For 200 rejected events, Path.resolve was called 1,400 times at
293f8a6 and 0 times with this fix. Without the status callback the fix
measures 0.73 ms per event; per-event status snapshots, which have no
throttle today, account for the rest.

Linking an included root/vendor/pkg to an outside directory of .py
files, and then writing one more file through the link, queued nothing
under the link or its target. An in-tree control file was still queued.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 7, 2026
…hunkhound#485)

Brings pinned from d0cef153 to a902b55 on fix/watcher-link-position: the
ignore matcher matched a directory by its bare name, so a .gitignore
whitelist (/* then !/src/) pruned src/ entirely, which the new directory
pruning in walks makes live. Applied as the diff d0cef153..a902b55 so
the pushed history of strasz/pinned is not rewritten.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz and others added 3 commits November 12, 2026 08:56
…cluded

Review of the stacked PRs (chunkhound#490, chunkhound#491) found that a file a .gitignore
negation re-includes was dropped by realtime:

  .gitignore      foo/**  then  !foo/bar.py   -> foo/bar.py
  src/.gitignore  **      then  !keep.py      -> src/keep.py

git does not ignore either file, the full scan indexes both, and event
admission accepted them, but excludes_directory() reported foo/ and src/
excluded, so the polling walk and new-directory expansion pruned them and
never saw the file. IgnoreEngine matched a directory in its "dir/" form,
and pathspec matches "foo/" against a contents pattern such as foo/** (or
the root-relative src/** of a nested "**") through an empty tail. Main had
the same wrong answer; this PR made it load-bearing by pruning on it.

A directory match now means its whole subtree is excluded, which is how
every caller uses it (the realtime walk and directory events, the Python
full-scan walker and its os.walk fallback, repo-root detection). Per spec,
in precedence order, a directory is excluded when:

- git excludes the directory itself: the last pattern matching it is not
  a negation, testing "dir/" against patterns written with a trailing "/"
  and the bare "dir" against the rest. foo/ and foo match foo; foo/**
  matches only what is inside it. A directory a negation re-includes is
  still excluded when an ancestor is, as in git.
- or a pattern covers its contents ("dir/" matches, e.g. foo/** or the
  default **/node_modules/**) and no negation in that spec could match
  beneath it. A negation could when it is unanchored (!keep.py, !*.md),
  starts with **/, or its literal prefix lies above or below the
  directory. Config excludes have no negations, so node_modules is still
  pruned without being walked.

So foo/** then !foo/bar.py leaves foo/ walkable, and each file is decided
on its own. The whitelist idiom (/* then !/src/) keeps src/ walkable.

To tell foo/ from foo/** the .gitignore transform now emits dir-only
patterns with their trailing "/" instead of "/**". pathspec matches the
same files for both, except that **/ no longer matches top-level files,
which git does not ignore either.

Files follow git as well: a file a negation re-includes stays excluded
when a parent directory is excluded. "foo/" then "!foo/bar.py" therefore
keeps foo/bar.py excluded in the walk, in event admission and in the
Python full scan, as git does; before, the engine admitted it.

The libgit2 backend's config-exclude layer uses the same rule; libgit2
already applies git semantics to .gitignore directories.

Tests compare the full scan, the polling walk and event admission with
git check-ignore for the two review cases, the dir-only case and the
whitelist idiom, and check that the walk never enters node_modules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
SimpleEventHandler admits a file event by the path the event names, then
queues the resolved path, checking only that it stays under the root. A
file link alias.py -> node_modules/pkg/secret.py was admitted as alias.py
and queued as secret.py, which no later step rechecks, so an excluded file
was indexed.

When resolving changes the path, the target now has to pass the same
policy before created or modified work is queued (a created directory is
checked with excludes_directory). The cheap admission on the unresolved
path stays as it was, so a rejected event is still never resolved. A
delete is not rechecked, so a previously indexed path is still cleaned up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of b359531 found that a negation re-including a directory inside
a contents pattern opened files git ignores:

  foo/**  then  !foo/bar/             -> git ignores foo/bar/x.py
  /a/**   then  !/a/b/                -> git ignores a/b/x.py
  /s/**   with  s/.gitignore !/keep/  -> git ignores s/keep/a.py

foo/** still matches the file itself; !foo/bar/ only re-includes the
directory. pathspec has no notion of that: it matches "!foo/bar/" (as
"!foo/bar/**") against every file below, so the file was re-included.
Before b359531 the walk pruned foo/ and hid this; once foo/ became
walkable, polling and admission gained foo/bar/x.py while the full scan
(git ls-files) left it out.

Files and directories are now decided as git decides them whenever a
negation in the spec matches the path:

- each pattern is matched against the path itself, without pathspec's
  "and everything beneath" tail (the ps_d group in pathspec 0.12), and a
  directory pattern only against directories; the last match wins;
- a path is excluded regardless when a directory above it is excluded.

A path no negation matches keeps pathspec's answer, which is then git's.
The same exact matching decides when a directory is excluded, and the
"contents covered" pruning rule now counts only file patterns, so a
directory pattern such as foo/**/ no longer prunes foo/ itself.

This also brings these cases in line with git (checked against
git ls-files -o --exclude-standard): "*.md then !keep/", "* !*/ !*.py",
"* !**/ !*.py", "* !/**/ !*.py", and "a/b/ then !a/".

The .gitignore transform again emits a directory pattern "foo/" as
"foo/**", byte for byte as before b359531, and carries the "was a
directory pattern" flag beside the compiled spec instead of in the
string. b359531's trailing "/" changed what **/ and /**/ match for the
full scan; that change is reverted (those two still differ from git as
they always have).

Reading pathspec's pattern objects (include, regex, source, ps_d tail)
fails loudly in a guard test, and at runtime degrades to pathspec's own
answers with no pruning and logs one warning, rather than silently
restoring the old behaviour.

Git's answer for each directory is memoized per compiled spec. The rules
never change for the spec's lifetime, so the memo needs no invalidation;
it is bounded and cleared when full. With 1,806 patterns including
"* !*/ !*.py", 2,000 file decisions take about 1.8 s against 1.7 s on
a902b55, and 2,000 directory checks 0.9 s against 1.6 s.

The git-oracle test gains the three review cases, the directory
re-include of a file pattern and the three whitelist variants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

Pushed three commits on top of a902b55 (fast-forward). They fix findings from VakninAriel's reviews of #490 and #491, both stacked on this PR. Each finding traces back to this PR:

  1. Re-included files were dropped by realtime (perf(realtime): decide each excluded directory once, not once per file #490 finding 1, fix(watchman): no watch root for a junction under an excluded directory #491 finding 1), fixed in b359531. With foo/** then !foo/bar.py, or src/.gitignore holding ** then !keep.py, git keeps the file and the full scan indexes it. But the directory check reported foo/ and src/ excluded, so the polling walk and new-directory expansion pruned them. Main gives the same wrong answer; this PR made it matter by pruning on it. A directory match now means nothing beneath it can be included.
  2. A directory re-include re-included its files, found while reviewing that fix, fixed in 6e32b20. foo/** then !foo/bar/ re-included foo/bar/x.py, which git ignores. When a negation matches a path, files and directories are now decided as git decides them.
  3. A link's target was not rechecked (perf(realtime): decide each excluded directory once, not once per file #490 finding 3, fix(watchman): no watch root for a junction under an excluded directory #491 finding 2), fixed in e888fd2. A file link alias.py -> node_modules/pkg/secret.py was admitted as alias.py and queued as secret.py. The target now has to pass the same policy before created or modified work is queued.

Eleven .gitignore cases are now compared with git check-ignore across the full scan, the polling walk and event admission; ten of them fail at a902b55. The full suite, run serially on Windows, has no failures that a902b55 doesn't have too. Upstream's CI workflow on our fork at 6e32b20 is green on every job: https://github.com/fstrasz/chunkhound/actions/runs/43256124453

The description is updated with the rule and the two differences from git that remain, as on main.

#490 and #491 merge this head next. #490 also gets a fix for its own libgit2 finding.

🤖 Generated with Claude Code, reviewed by FStrasz

fstrasz and others added 2 commits November 17, 2026 06:21
Brings in the 21 PRs merged to main since this branch was cut (chunkhound#469 through chunkhound#534). No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in the 24 commits merged to main since this branch was last updated, including chunkhound#534's rust-checks fix. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz and others added 2 commits November 18, 2026 21:46
The watchdog handler already drops a dir_created event when the new
directory is excluded, so an excluded tree is never walked. The Watchman
adapter admitted every dir_created event, so a directory created under
node_modules/ (or any other excluded path) still became dir_index work
on the Watchman backend. It now applies the same excludes_directory
check. dir_deleted is still always admitted, so cleanup is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nk-spelled root in the tree

Review follow-up.

excludes_directory swallowed an ignore-engine error and returned False,
so the failure was invisible and the filter never marked itself
degraded. should_index and excludes_directory now share one guard,
_ignore_rule_matches: the first evaluation error marks the engine
degraded and warns once, whichever caller hit it, so is_degraded reports
it and cleanup keeps rows it can no longer prove are excluded. A filter
with no engine and no recorded failure still means no rule applies.

Watchman builds event paths from the root as it was requested, while
the ignore engine works on the resolved root. When the requested root
is spelled through a link (/var is /private/var on macOS), a path was
not lexically under the engine's root, so it was resolved and a link
under node_modules/ was judged at its target again. RealtimePathFilter
now respells such a path onto the resolved root before matching. Only
the root part changes, so links below the root are still judged where
they sit.

Also documents both cases in _in_tree_path (a link-spelled root, and
`..` collapsed lexically as Git does), and comments the test's private
_winapi junction helper and the rglob walk the walk test relies on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz and others added 9 commits November 19, 2026 04:42
…cluded

Review of the stacked PRs (chunkhound#490, chunkhound#491) found that a file a .gitignore
negation re-includes was dropped by realtime:

  .gitignore      foo/**  then  !foo/bar.py   -> foo/bar.py
  src/.gitignore  **      then  !keep.py      -> src/keep.py

git does not ignore either file, the full scan indexes both, and event
admission accepted them, but excludes_directory() reported foo/ and src/
excluded, so the polling walk and new-directory expansion pruned them and
never saw the file. IgnoreEngine matched a directory in its "dir/" form,
and pathspec matches "foo/" against a contents pattern such as foo/** (or
the root-relative src/** of a nested "**") through an empty tail. Main had
the same wrong answer; this PR made it load-bearing by pruning on it.

A directory match now means its whole subtree is excluded, which is how
every caller uses it (the realtime walk and directory events, the Python
full-scan walker and its os.walk fallback, repo-root detection). Per spec,
in precedence order, a directory is excluded when:

- git excludes the directory itself: the last pattern matching it is not
  a negation, testing "dir/" against patterns written with a trailing "/"
  and the bare "dir" against the rest. foo/ and foo match foo; foo/**
  matches only what is inside it. A directory a negation re-includes is
  still excluded when an ancestor is, as in git.
- or a pattern covers its contents ("dir/" matches, e.g. foo/** or the
  default **/node_modules/**) and no negation in that spec could match
  beneath it. A negation could when it is unanchored (!keep.py, !*.md),
  starts with **/, or its literal prefix lies above or below the
  directory. Config excludes have no negations, so node_modules is still
  pruned without being walked.

So foo/** then !foo/bar.py leaves foo/ walkable, and each file is decided
on its own. The whitelist idiom (/* then !/src/) keeps src/ walkable.

To tell foo/ from foo/** the .gitignore transform now emits dir-only
patterns with their trailing "/" instead of "/**". pathspec matches the
same files for both, except that **/ no longer matches top-level files,
which git does not ignore either.

Files follow git as well: a file a negation re-includes stays excluded
when a parent directory is excluded. "foo/" then "!foo/bar.py" therefore
keeps foo/bar.py excluded in the walk, in event admission and in the
Python full scan, as git does; before, the engine admitted it.

The libgit2 backend's config-exclude layer uses the same rule; libgit2
already applies git semantics to .gitignore directories.

Tests compare the full scan, the polling walk and event admission with
git check-ignore for the two review cases, the dir-only case and the
whitelist idiom, and check that the walk never enters node_modules.

Ported to chunkhound#481 from b359531, found in review of chunkhound#490/chunkhound#491 and carried by
chunkhound#485/chunkhound#490/chunkhound#491. Conflict resolution: IgnoreEngine.matches and
RepoAwareLibgit2Evaluator._cfg_excluded take b359531's rule-based decision;
the lines it replaces here are main's originals rather than the stack's
interim "dir/ form only" lines (a902b55, not in chunkhound#481). The tests are adapted
to chunkhound#481's code: the walk test that needs pipeline._walk_files (chunkhound#485) is left
out, and the git-agreement test also sends a created-directory event for each
directory holding a file git includes, and requires it to be expanded rather
than dropped, which is the case this port fixes in chunkhound#481.

(cherry picked from commit b359531)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of b359531 found that a negation re-including a directory inside
a contents pattern opened files git ignores:

  foo/**  then  !foo/bar/             -> git ignores foo/bar/x.py
  /a/**   then  !/a/b/                -> git ignores a/b/x.py
  /s/**   with  s/.gitignore !/keep/  -> git ignores s/keep/a.py

foo/** still matches the file itself; !foo/bar/ only re-includes the
directory. pathspec has no notion of that: it matches "!foo/bar/" (as
"!foo/bar/**") against every file below, so the file was re-included.
Before b359531 the walk pruned foo/ and hid this; once foo/ became
walkable, polling and admission gained foo/bar/x.py while the full scan
(git ls-files) left it out.

Files and directories are now decided as git decides them whenever a
negation in the spec matches the path:

- each pattern is matched against the path itself, without pathspec's
  "and everything beneath" tail (the ps_d group in pathspec 0.12), and a
  directory pattern only against directories; the last match wins;
- a path is excluded regardless when a directory above it is excluded.

A path no negation matches keeps pathspec's answer, which is then git's.
The same exact matching decides when a directory is excluded, and the
"contents covered" pruning rule now counts only file patterns, so a
directory pattern such as foo/**/ no longer prunes foo/ itself.

This also brings these cases in line with git (checked against
git ls-files -o --exclude-standard): "*.md then !keep/", "* !*/ !*.py",
"* !**/ !*.py", "* !/**/ !*.py", and "a/b/ then !a/".

The .gitignore transform again emits a directory pattern "foo/" as
"foo/**", byte for byte as before b359531, and carries the "was a
directory pattern" flag beside the compiled spec instead of in the
string. b359531's trailing "/" changed what **/ and /**/ match for the
full scan; that change is reverted (those two still differ from git as
they always have).

Reading pathspec's pattern objects (include, regex, source, ps_d tail)
fails loudly in a guard test, and at runtime degrades to pathspec's own
answers with no pruning and logs one warning, rather than silently
restoring the old behaviour.

Git's answer for each directory is memoized per compiled spec. The rules
never change for the spec's lifetime, so the memo needs no invalidation;
it is bounded and cleared when full. With 1,806 patterns including
"* !*/ !*.py", 2,000 file decisions take about 1.8 s against 1.7 s on
a902b55, and 2,000 directory checks 0.9 s against 1.6 s.

The git-oracle test gains the three review cases, the directory
re-include of a file pattern and the three whitelist variants.

Ported to chunkhound#481 from 6e32b20, found in review of b359531 on chunkhound#490/chunkhound#491 and
carried by chunkhound#485/chunkhound#490/chunkhound#491. The engine change applies unchanged. In the
git-agreement test, the case table and the switch to "files" (.py and .md)
come from 6e32b20; the created-directory check added when b359531 was
ported to chunkhound#481 is kept.

(cherry picked from commit 6e32b20)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e workspace

Review of chunkhound#481 found that a repository linked into the workspace lost its
own ignore rules. With workspace/linked pointing at a checkout outside the
workspace, files under linked/ fell back to the workspace policy, so a
pattern from the linked repository's .gitignore no longer applied.

The ignore engine now matches a path where it sits in the workspace, but
both repo-aware evaluators still resolved their repository roots. The
in-tree path workspace/linked/x was never under the resolved root of the
linked repository, so no repository was found for it. Before chunkhound#481 the path
was resolved too, which found the repository but judged links below the
root at their targets.

Each repository is now kept as (where it sits under the workspace, its
resolved root). The nearest repository is chosen by in-tree location, so
a linked repository nested in a workspace that is itself a repository
still wins over the workspace. The path is then mapped onto the chosen
repository's resolved root, where that repository's engine (or its libgit2
handle) matches it. A path under no in-tree location, such as one that was
already resolved, is looked up among the resolved roots as before. Both
evaluators share one helper for this.

Reproduced on Windows with a junction: build_repo_aware_ignore_engine_from_roots
with the repository at workspace/linked, and build_repo_aware_ignore_engine,
whose os.walk detection finds the repository through the junction at
workspace/linked. In both, linked/private.secret.py was not excluded
before this change and is excluded after it. A file the repository does
not ignore stays included.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of chunkhound#481 found that a symlinked file was judged only where it sits.
With src/a.py -> vendor/x.py and vendor/ ignored, src/a.py was rejected
before chunkhound#481, because the ignore engine resolved every path, and admitted
after it. The watchdog handler resolves a file event before admission and
still rejected it, but the polling snapshot and the new-directory expansion
pass the unresolved path to should_index, so they would index the ignored
file's content under the link's name.

That is not intended. The default startup scan does not follow links and
never indexes a symlinked file. So should_index now judges a path where it
sits and, when resolving it changes it (the file or a directory between it
and the root is a link), judges the resolved target as well. This is the
rule the stacked PRs apply in the event handler (e888fd2). A link under an
excluded directory is still rejected where it sits, before its target is
looked at, and only a path that passed is resolved, which costs no more than
before chunkhound#481, when every path was resolved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nternals

Review of chunkhound#481 found that test_pathspec_contract.py asserted pathspec's
internal pattern fields (dir_only, include, exact), so a harmless refactor
could break it. Its purpose is to fail first when a pathspec release changes
the pattern objects ChunkHound reads, which would otherwise degrade the
ignore rules to pathspec's own matching with only a logged warning.

It now builds a tiny repository whose .gitignore pairs a directory pattern
and a contents pattern with negations that git and pathspec alone decide
differently (dir/ then !dir/keep.py; contents/** then !contents/sub/), and
compares the engine's decision for each file with git check-ignore. The
degraded fallback re-includes both files, so the test fails if the rules
cannot be read. It uses two git processes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…valuator

Review of chunkhound#481 noted that RepoAwareLibgit2Evaluator kept both _cfg_spec and
_cfg_rules. The spec is compiled once and the rules are read from it, and
since b359531 nothing reads _cfg_spec after construction: across the
package and the tests its only use was building _cfg_rules on the next
line. It is no longer stored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The pathspec contract test wrote the paths to git check-ignore in text
mode. On Windows that writes "\r\n", so git read each path with a trailing
"\r" and printed it quoted, and the comparison failed on spelling rather
than on what git decided. The paths now go in and out NUL-separated (-z),
as bytes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ories stay pruned

The ignore engine reads pathspec's compiled regexes to decide directories as
git does. It knew only pathspec 0.12's spelling of the tail, the group named
ps_d, that makes a match on a directory also match everything beneath it.
pathspec 1.x spells it "(?:(?P<ps_d>/)|$)" (file or directory) and a bare
"(?P<ps_d>/)" (directory). Under 1.x, any plain or glob line (Thumbs.db,
*.log, /build) therefore degraded its whole spec: no directory was pruned,
and every file was decided by pathspec's own match_file. The lock pins
0.12.1, so CI does not see this, but pathspec>=0.12.1 lets a fresh install
resolve 1.x.

pathspec 1.x also applies its regexes with re.search, and some are
unanchored ("*" compiles to "."). 0.12 anchors every regex, so re.search is
right for both, and the rules now use it at all three sites.

- Both versions' tails map to the end of the path.
- The fallback names the pattern and the installed pathspec version.
- Contract tests read every .gitignore form from the installed pathspec, and
  a Thumbs.db + node_modules/ test keeps ignored directories pruned.

Ported from fstrasz/chunkhound 0b13ace, without that fork's lock change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ories stay pruned

The ignore engine reads pathspec's compiled regexes to decide directories as
git does. It knew only pathspec 0.12's spelling of the tail, the group named
ps_d, that makes a match on a directory also match everything beneath it.
pathspec 1.x spells it "(?:(?P<ps_d>/)|$)" (file or directory) and a bare
"(?P<ps_d>/)" (directory). Under 1.x, any plain or glob line (Thumbs.db,
*.log, /build) therefore degraded its whole spec: no directory was pruned,
and every file was decided by pathspec's own match_file. The lock pins
0.12.1, so CI does not see this, but pathspec>=0.12.1 lets a fresh install
resolve 1.x.

pathspec 1.x also applies its regexes with re.search, and some are
unanchored ("*" compiles to "."). 0.12 anchors every regex, so re.search is
right for both, and the rules now use it at all three sites.

- Both versions' tails map to the end of the path.
- The fallback names the pattern and the installed pathspec version.
- New test: a Thumbs.db + node_modules/ .gitignore keeps ignored directories
  pruned. With the git comparison already in the file, it runs against the
  installed pathspec, whichever version that is.

Ported from fstrasz/chunkhound 0b13ace, without that fork's lock change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… fix/watcher-link-position (chunkhound#485)

Ordinary merge, so the stack carries chunkhound#481's review fixes (c3a7aeb,
5b188ad, 10d03a2, cdfbf58, 4f42f38, ad130d3, 7b755eb, d450191).
The two branches share only 0ab907b/293f8a6d; chunkhound#485's b359531,
6e32b20 and 81f1715 are parallel ports of chunkhound#481's 535466f, 5122b33
and d450191. Five files conflicted:

1. chunkhound/utils/ignore_engine.py (6 hunks): took chunkhound#481's side.
   chunkhound#485's file was a subset of it: chunkhound#481 adds the linked nested
   repository lookup (_repo_locations, _nearest_repo), the in-tree root
   respelling note and the config-exclude rules refactor. chunkhound#485's own
   ignore_engine change from a902b55 (match a directory in its "dir/"
   form only) is already in chunkhound#481's side. Dropped: chunkhound#485's "(TFS 65863)"
   comment tag.
2. chunkhound/services/realtime_path_filter.py (2 hunks): took chunkhound#481's
   side. It reports ignore-engine errors on directories instead of
   returning False (_ignore_rule_matches), respells a link-spelled root
   (_engine_path) and judges a linked file by its target in should_index.
   chunkhound#485's side was the older form of the same code.
3. chunkhound/services/realtime/events.py (1 hunk): took chunkhound#485's side.
   It contains chunkhound#481's change (excludes_directory before queuing a new
   directory) and builds on it: admission on the unresolved path,
   _queue_admitted and _target_admitted (a902b55, e888fd2).
4. tests/ignore/test_pathspec_contract.py (add/add, 3 hunks): took
   chunkhound#481's side, which compares the engine with git check-ignore instead
   of reading pathspec internals (4f42f38, 7b755eb, review request).
5. tests/realtime/test_filter_consistency_realtime_cleanup.py (6 hunks):
   union. chunkhound#481's side, plus chunkhound#485's tests copied verbatim from 81f1715:
   _linked_package_layout and the four tests after it, then
   test_polling_walk_does_not_enter_excluded_node_modules, _file_symlink
   and test_file_alias_to_excluded_target_is_not_queued, with their
   imports (os, typing.Any, pipeline._walk_files). Kept chunkhound#481's newer
   test_scan_walk_and_admission_agree_with_git_on_reincluded_files (it
   also checks new-directory expansion). Dropped chunkhound#481's comment that the
   walk "still descends the link with rglob": chunkhound#485 replaced rglob with a
   pruning os.walk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Summary: The core idea is right and well tested. Two risks to settle first: a possible conflict with Watchman junction handling, and a lot of fragile new code in ignore_engine.py. (Read from the diff and surrounding code; tests not run.)

Strengths

  • Fixes a real, measured problem (about 8x faster per rejected event, no more "not in the subpath" failures).
  • Tests compare against git check-ignore; a pathspec contract test plus a safe fallback (no pruning, one warning) if pathspec's shape changes.
  • _target_admitted closes a real hole, and deletes are exempt so cleanup still works.

Issues

  • Major – possible conflict with Watchman junction scopes. chunkhound/watchman/scope.py:107 (discover_nested_windows_junction_scopes) deliberately watches junctions that resolve outside the target. _queue_admitted (events.py) now drops any event that resolves outside _root, so those events were probably queued before and are now filtered. Please confirm this is intended, or add a test with a Watchman junction scope. The "behaviour change" note only mentions watchdog and the Rust scan.
  • Major – ignore_engine.py depends on pathspec internals. It reads compiled regex text and strips the ps_d tails (_PS_D_TAILS). 1.x support is only checked by hand on Windows; CI runs 0.12.1 only. The fallback silently turns pruning off, which brings back the perf problem. Consider an upper bound or a pathspec 1.x CI job.
  • Major – very large PR. About 370 new lines of git-semantics logic (negation scopes, memo, exact regexes) are mixed in with the realtime fix, stacked on fix(realtime): exclude linked directories by their place in the tree #481 with two more PRs on top. This should be its own PR. The PR also admits remaining differences from git (**/, /**/).
  • Minor – _is_junction (pipeline.py) is only exercised on Windows; Linux CI covers symlinks only.
  • Minor – keep_in_tree_spelling skips resolve(), so keys may differ for case or 8.3 spellings on Windows (the docstring admits it). That could mean duplicate bookkeeping entries, and no test covers it.
  • Minor – excludes_directory does except Exception: return False. This hides engine bugs and fails in the permissive direction; log at debug at least.
  • Minor – extra cost per admitted event. _queue_admitted does a resolve() plus a second policy check whenever the path changes.
  • Minor – process. Includes fix(realtime): exclude linked directories by their place in the tree #481's commit and two merge commits; rebase once fix(realtime): exclude linked directories by their place in the tree #481 lands.

Reusability

  • _in_tree_path is defined twice (events.py, ignore_engine.py). Move one version to core/utils/path_utils.py next to normalize_realtime_path.
  • Junction detection could be shared with watchman/scope.py, which already inspects reparse points.
  • _walk_files uses the private handler._path_filter; pass the RealtimePathFilter instead.
  • Put the git-exact matching in its own module.

Decision: REQUEST CHANGES. Confirm the Watchman junction behaviour, isolate or split out the ignore-engine rewrite, and add pathspec 1.x CI coverage. Direction is good; I'd approve once those are settled.

fstrasz and others added 8 commits November 24, 2026 08:20
…hunkhound#485 review)

The code that derives git's directory and re-include decisions from
pathspec's compiled patterns (_GLOB_CHARS through _spec_excludes_file)
moves unchanged from ignore_engine.py into gitignore_rules.py; the moved
259 lines are byte-identical. ignore_engine.py imports the four names it
uses. No test imports a moved name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…unkhound#485 review)

ignore_engine reads pathspec's compiled regexes, which are not public API.
pyproject bounds pathspec to the majors the contract test covers
(>=0.12.1,<2); uv.lock changes in metadata only and still resolves 0.12.1.
A new pathspec-1x job installs the newest 1.x over the lock and runs
tests/ignore and the realtime cleanup tests, so a 1.x release that changes
the regex shape fails CI instead of silently disabling pruning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ls (chunkhound#485 review)

events._in_tree_path shared a name, not a contract, with
ignore_engine._in_tree_path. It becomes path_utils.lexical_absolute_path,
next to normalize_realtime_path, and events.py calls it. Behaviour is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hunkhound#485 review)

_walk_files reached into a SimpleEventHandler's private _path_filter, and
its two callers built a handler only for that filter and its
_should_index. _polling_snapshot and _collect_supported_files now build a
RealtimePathFilter on the resolved root, as SimpleEventHandler did, and
pass it in. The one direct test call passes the filter.

_normalize_mutation_path's docstring now says the in-tree spelling is for
status bookkeeping only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ink's target

chunkhound#481's RealtimePathFilter.should_index also requires a link's resolved
target to pass the policy, which is right for indexing. chunkhound#485 admits a
watchdog delete on the unresolved path through the same predicate, so
after chunkhound#481 was merged in, deleting alias.py -> node_modules/pkg/secret.py
was filtered and never queued, breaking chunkhound#485's contract that a delete is
still queued for cleanup
(test_file_alias_to_excluded_target_is_not_queued).

should_index gains check_target (default True). _should_admit_event
judges a "deleted" event with check_target=False; created and modified
events still require the target to pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 25, 2026
…luded-dir-memo (chunkhound#490)

Ordinary merge of chunkhound#485 after chunkhound#481 was merged into it, so chunkhound#490 carries
chunkhound#481's review fixes. Three files conflicted:

1. chunkhound/utils/ignore_engine.py: took the chunkhound#485 side. chunkhound#490's file was
   identical to chunkhound#485's head 81f1715 (4467926 is a parallel port of the
   same pathspec 1.x fix), so the conflict came only from the two ports.
2. tests/ignore/test_pathspec_contract.py: took the chunkhound#485 side, for the
   same reason.
3. chunkhound/services/realtime_path_filter.py: hand-merged. Started from
   the chunkhound#485 side (chunkhound#481's rewrite: _ignore_rule_matches, _engine_path,
   _admits) and added chunkhound#490's directory memo to it: _DIR_DECISIONS_MAX,
   _dir_decisions, _dir_decisions_engine, _keep_dir_decisions (off for
   the libgit2 evaluator), _in_tree_under_root and _directory_excluded.
   Two choices that the merge needed and neither side made:
   a. The memo now runs inside _ignore_rule_matches, for directories and
      for a file's parent, instead of inside excludes_directory and
      should_index. An engine error in the memo therefore marks the filter
      degraded and warns once, as chunkhound#481 made every other evaluation do;
      chunkhound#490's version returned False from excludes_directory silently.
   b. _directory_excluded matches each directory as _engine_path spells
      it, as every other match does since chunkhound#481. Without that, a root
      spelled through a link (/var vs /private/var on macOS) would send
      the memo's matches to the link targets, which
      test_linked_package_is_excluded_when_the_root_is_spelled_through_a_link
      checks against.
   _in_tree_root is defined once; both sides defined it identically.

No test ran on this merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 25, 2026
…ction-excluded (chunkhound#491)

Ordinary merge of chunkhound#485 after chunkhound#481 was merged into it, so chunkhound#491 carries
chunkhound#481's review fixes. Two files conflicted, both resolved to the chunkhound#485
side:

1. chunkhound/utils/ignore_engine.py
2. tests/ignore/test_pathspec_contract.py

In both, chunkhound#491's file was identical to chunkhound#485's head 81f1715 (6599cb3 is
a parallel port of the same pathspec 1.x fix), so the conflicts came only
from the two ports. realtime_path_filter.py, watchman.py and the cleanup
tests merged without conflict; chunkhound#491 had not changed
realtime_path_filter.py beyond chunkhound#485.

No test ran on this merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The changes are in 73c47f3, c798c20 and e6b49bb, plus 09e3716 and c20d46f on #481, which #485 now merges (84b7a15). The stack was then merged with current main (#481 0d9253b, #485 0d4f44f).

Majors

  1. Watchman junction scopes and _queue_admitted: Watchman events do not go through _queue_admitted. That
    method belongs to SimpleEventHandler, which only the watchdog backend uses (the polling snapshot and
    new-directory expansion now use a RealtimePathFilter directly). The Watchman adapter spells each path under the scope's
    requested path (scope.requested_path.joinpath(...)) and enqueues it through ingest_realtime_event, which this
    PR does not change. So a junction scope's events are queued under their logical path as before. The existing
    test_watchman_junction_scope_translation_preserves_logical_path covers exactly this: it makes a
    nested_junction scope's file resolve outside the target, feeds the PDU through the adapter, and requires the file
    to be indexed under its logical path. It passes at this head on Windows (-k junction_scope: 3 passed).
    One change does reach Watchman, and the description now says so: new-directory expansion walks with os.walk and
    prunes a junction it finds inside a newly created directory, on every backend. rglob used to descend it.
    Known limit, unchanged from main: new-directory expansion still judges each file it finds by its patterns only, so
    a file symlink inside a new directory that points at an included file outside the root is admitted, as on main.
    We can follow up on that separately if wanted.
  2. pathspec internals: done on fix(realtime): exclude linked directories by their place in the tree #481, where this code lives. pyproject now has pathspec>=0.12.1,<2, and CI has a
    new job that installs the newest pathspec 1.x over the lock and runs tests/ignore and the realtime cleanup tests.
    The main matrix still runs the locked 0.12.1, so both majors are covered on every PR. The contract test compares
    the engine with git check-ignore on rules that pathspec alone decides differently, so if a pathspec release
    changes the regex shape, the engine degrades and that job fails; it does not just log a warning. The job resolves
    the newest 1.x on purpose, so it tests what a fresh install gets. The cost is that it can go red on a pathspec
    release with no ChunkHound change. If you would rather keep CI hermetic, I can pin it to 1.1.1 instead.
    Verified on Windows: tests/ignore plus the realtime cleanup tests, 46 passed under 0.12.1 and 46 under 1.1.1.
    With the 1.x tail spellings removed, the contract test fails under 1.1.1 (2 failed, among them
    assert None is not None for node_modules: the directory is no longer pruned). The new CI job passes on our fork
    (run linked below).
  3. Size and the ignore-engine rewrite: the rewrite now lives only in fix(realtime): exclude linked directories by their place in the tree #481. This branch had its own older copies
    of those commits; it now merges fix(realtime): exclude linked directories by their place in the tree #481 and takes fix(realtime): exclude linked directories by their place in the tree #481's files. Against fix(realtime): exclude linked directories by their place in the tree #481's head, fix(realtime): admit file events before resolving and skip linked directories in walks #485's own change is six files:
    events.py, pipeline.py, service.py, core/utils/path_utils.py, realtime_path_filter.py and the cleanup
    tests (+378/-49), with no change to ignore_engine.py, gitignore_rules.py or the pathspec contract test. The
    realtime_path_filter.py change is one keyword, should_index(..., check_target=False). After the merge, fix(realtime): exclude linked directories by their place in the tree #481's
    filter also checks a link's target, which dropped the delete of a link to an excluded file. A delete is now judged
    where the path sits, so a previously indexed path is still cleaned up
    (test_file_alias_to_excluded_target_is_not_queued). Within fix(realtime): exclude linked directories by their place in the tree #481, the git-exact rule code
    (negation scopes, exact regexes, the directory memo) is moved unchanged into its own module,
    chunkhound/utils/gitignore_rules.py. I did not open a fifth PR for it: you asked for this fix in fix(realtime): exclude linked directories by their place in the tree #481 and have
    reviewed it there, and a separate PR ahead of fix(realtime): exclude linked directories by their place in the tree #481 would deepen the stack. If you still want it reviewed on its
    own, I can open one.
    The **/ and /**/ differences are pathspec's answers and the same as on main; this stack does not touch them. I
    can open an issue for them if you want one tracked.

Minors

  1. _is_junction only on Windows: CI's matrix includes windows-latest, and the cleanup tests make real
    junctions there (symlinks elsewhere), so the junction branch runs in CI. Off Windows a junction cannot exist, and
    the function returns False on its first line. os.path.isjunction would replace it, but it needs Python 3.12 and
    the floor is 3.10.
  2. keep_in_tree_spelling: only the source-event record and the event-pressure tracker use it. Those keys feed
    the status snapshot's hottest-path sample; mutation keys still use full normalisation. So a second spelling of the
    same file (an in-tree link to an in-tree target, or a writer using an 8.3 or different-case name) can split that
    file's pressure count in status, but it does not change what is indexed or under which key. Giving it one key would
    mean carrying the in-tree spelling with every queued event, which I don't think status data warrants. The
    docstring now says it is status bookkeeping only. I did not add a test for this.
  3. excludes_directory swallowing errors: fixed in fix(realtime): exclude linked directories by their place in the tree #481 (c3a7aeb, from your review there), and this branch now
    has fix(realtime): exclude linked directories by their place in the tree #481's version: an evaluation error marks the filter degraded and warns once, as for a file.
    test_ignore_engine_error_on_a_new_directory_marks_the_filter_degraded covers it.
  4. Extra cost per admitted event: an admitted file is still resolved once, as before; the resolve moved from
    before admission to after it, so rejected events no longer pay for it. The second policy check runs only when
    resolving changes the path, which means a link. That check is what keeps alias.py -> ignored/secret.py from
    indexing secret.py.
  5. History: I don't rewrite a pushed PR branch, so I won't rebase it. Once fix(realtime): exclude linked directories by their place in the tree #481 lands I'll merge main into this
    branch. The PR diff then shows only fix(realtime): admit file events before resolving and skip linked directories in walks #485's six files, and the squash merge leaves one commit on main.

Reusability

  1. _in_tree_path twice: the two share a name, not a contract. The one in events.py is only the lexical
    absolute path; the one in ignore_engine.py takes the root and falls back to resolve() for a path outside it.
    The events one is now lexical_absolute_path in core/utils/path_utils.py, next to normalize_realtime_path.
    I left the ignore-engine one, since it does more, and watchman/scope.py's _lexical_absolute_path, which also
    expands ~.
  2. Junction detection shared with watchman/scope.py: left as is. scope.py takes any non-symlink reparse
    point and keeps it if it resolves outside the target. _is_junction matches only the junction tag, on purpose,
    so OneDrive and dedup placeholders stay walkable. Sharing one check would change Watchman scope discovery.
  3. _walk_files and handler._path_filter: _walk_files now takes a RealtimePathFilter. The polling snapshot
    and new-directory expansion build the filter directly, with the same resolved root, and no longer construct a
    SimpleEventHandler just to reach it.
  4. Git-exact matching in its own module: done in fix(realtime): exclude linked directories by their place in the tree #481 (Major 3).

Verification on Windows, run serially. Full suite at 0d4f44f: 6,146 passed, 509 skipped. The 33 failures also fail
at the pushed head 81f1715, except 5 load flakes that pass on rerun, so none is new; they are environmental on this
machine (daemon and MCP subprocess tests, missing API keys, LLM-configuration and SSL-fixture tests). The targeted
run at e6b49bb (tests/realtime, tests/ignore, tests/test_realtime_functional.py and
tests/test_watchman_runtime_resources.py): 169 passed, 57 skipped, 0 failed.
Upstream's CI workflow on our fork at #481's head c20d46f (with our Rust toolchain pin, macOS jobs off): every code
job passed, including the new pathspec 1.x job; the one cancelled job, the macOS docs build, got no runner.
https://github.com/fstrasz/chunkhound/actions/runs/45440594707

🤖 Generated with Claude Code, reviewed by FStrasz

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Summary: The direction is sound and well measured, but I recommend REQUEST CHANGES. The delete-cleanup path may regress, and Watchman delete handling contradicts the PR's own "deletes exempt" claim. The two review agents reported these from the diff. I haven't confirmed them myself, and I ran no tests.

Strengths

  • The problem is real and measured: about 10.5 to 1.3 ms per event for 5,000 events, and no more "not in the subpath" failures.
  • The ignore engine matched git check-ignore in a fuzz run on raw root-level patterns: 1,450 random rule sets on pathspec 0.12.1 and 300 on 1.1.1. That run found no wrong verdicts and no unsafe prunes.
  • Pruning is conservative. A negation that could match beneath a directory blocks pruning, and the fallback never prunes wrongly.
  • The contract test compares against real git.

Issues

Major

  1. Delete lookup may miss indexed rows (events.py on_any_event and _handle_move_event, then pipeline.py:_should_admit_realtime_event). The admission callback now receives the in-tree path spelling, and get_file_by_path(str(file_path)) looks it up in a DB that may be keyed by resolved paths. If the root is spelled through a link, or by 8.3 name or case on Windows, an excluded but previously indexed file is missed. Its stale rows then stay. No test covers this. The lookup should also try the resolved form.
  2. Watchman deletes get check_target=True (adapters/watchman.py _should_admit_event). This contradicts the PR's "deletes exempt" claim and adds a resolve() per event. Pass check_target=False for deleted. The only Watchman test covers dir_created.
  3. Extra resolve() per file in walks (realtime_path_filter.py should_index, used by _polling_snapshot and _collect_supported_files). This costs one extra syscall chain per file on large trees, which cuts against the PR's rationale that rejected events don't pay for resolve.
  4. The pathspec-1x CI job isn't hermetic (.github/workflows/ci.yml). It installs the newest 1.x over the lock, so an upstream release can turn unrelated PRs red. Pin it (the contributor offered 1.1.1). It also repeats the setup of the other jobs.
  5. The pathspec dependency stays fragile (gitignore_rules.py, _PS_D_TAILS). It reads non-public attributes (pattern.regex, .include, .pattern and the ps_d tails).
    • The degraded mode warns once per process through the global _rules_degraded_warned, then degrades silently for later specs.
    • Degraded mode drops pruning, which brings the perf problem back.
  6. The "differs from git only for / and //" claim is unproven. Case-insensitive filesystems, trailing spaces and escapes, and nested .gitignore files are untested. No test pins the boundary.

Minor

  • ignore_engine.py imports underscore-private names (_spec_excludes_dir, _spec_excludes_file, _spec_rules, _SpecRules) from gitignore_rules. Make them public.
  • The dir_decisions memo is a mutable dict inside a frozen dataclass. It has no lock, and its bound is enforced by a crude clear() mid-recursion.
  • Import fallbacks set PathSpec = None # type: ignore, which defers the failure and hides mypy problems. getattr(pattern, "include", _PathspecContractError) uses an exception class as the default, which is odd.
  • PEP 8: three blank lines before class IgnoreEngine, and a local import pathspec inside _exact_regex.
  • _is_junction uses st_reparse_tag, which mypy may flag on non-Windows.
  • Tests lean on internals: the private _walk_files, a monkeypatched os.scandir, service._filtered_event_count, and _winapi.CreateJunction. About 15 narrow tests could be fewer contract tests, per AGENTS.md. Some tests are async but only use asyncio.sleep(0). The ignore-engine side has two tests for 282 lines, with none for negation scopes, the degraded path or memo eviction.
  • dir_created for a link checks only excludes_directory(target), not whether it is a junction.
  • Several docstrings run long without a one-line PEP 257 summary, and _queue_admitted is long.
  • Process: the branch still carries fix(realtime): exclude linked directories by their place in the tree #481's commits and merge commits. The contributor says they'll merge main once fix(realtime): exclude linked directories by their place in the tree #481 lands.

Reusability

  • The lexical-vs-resolved path logic is repeated across ignore_engine.py (_cfg_excluded, matches, _nearest_repo), the realtime filter and pipeline, and watchman/scope.py (_lexical_absolute_path). Consolidate it in core/utils/path_utils.py.
  • Pass RealtimePathFilter through public methods instead of reaching into _engine_root and _in_tree_root.
  • Check whether file_patterns.py and other match_file callers now disagree with the new engine semantics.
  • The contributor's reason for keeping _is_junction separate from the Watchman scope check, which treats any reparse point as a junction, is reasonable.

Decision: REQUEST CHANGES. Fix or disprove items 1 and 2 with a test, and pin the CI job. The rest can follow once #481 lands and this PR shrinks to its six files.

fstrasz and others added 2 commits November 25, 2026 02:51
…ec-1.x CI job (chunkhound#485 review)

Item 2: the Watchman adapter now passes check_target=False for deletes,
as the watchdog handler does. A delete reads no content, so the target of a
link on its way does not decide it.

Item 1: a test shows a delete of an excluded, indexed file is admitted and
its row removed when the root is spelled through a link or in another case:
normalize_path_for_lookup resolves the path and the base before comparing.

Item 4: the pathspec-1.x job installs pathspec==1.1.1 instead of the newest 1.x.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I've handled items 1, 2 and 4 as you asked. Each answer below points to a test that
fails without the change.

1. Delete lookup with a differently spelled root: disproved, with a test.
get_file_by_path does not compare the raw string. It normalizes through normalize_path_for_lookup, which
resolves both the event path and the base directory before taking the relative path. So an excluded file the
index still holds is found and removed even when the root is spelled through a link, or in a different case on
Windows.

test_excluded_indexed_file_is_cleaned_when_the_root_is_spelled_differently[link|case] does this:

  1. Seeds the row under the real root.
  2. Spells the root through a directory link (or in upper case).
  3. Sends a Watchman delete for vendor/stale.py, which the config excludes.
  4. Asserts that the delete is admitted and the row is gone.

The route is the Watchman adapter, then _should_admit_realtime_event, then get_file_by_path. The watchdog
handler uses the same admission callback.

To check that the test guards resolution, I made resolve_path_for_relative return its inputs unresolved. The
[link] case then fails, because the delete is not admitted. The [case] variant still passes under that
mutation: Windows relative_to already compares case-insensitively. So [link] is the case that guards
resolution. I kept [case] because it pins the behaviour you asked about. 8.3 short names go through the same
resolve call, but I have not tested them separately.

2. Watchman deletes: fixed.
_should_admit_event now passes check_target=event_type != "deleted". That matches the watchdog handler, and
a delete no longer pays for a resolve.

test_delete_through_a_linked_directory_is_admitted_alike_by_both_backends sends the same delete to both
backends. The delete is for a never-indexed path under a linked directory whose target is excluded. Before the
fix, watchdog admitted it and Watchman dropped it. Both now admit it.

4. pathspec-1x CI job: pinned to pathspec==1.1.1. The comment above the job now says the pin is moved by
hand.

Checks run locally:

  1. tests/realtime: 112 passed, 28 skipped.
  2. Smoke: 14 passed.
  3. mypy and ruff: no new findings against the previous head.

Fork CI is green on these commits plus a CI-only variant without macOS jobs:
https://github.com/fstrasz/chunkhound/actions/runs/45573198319. The pathspec-1x job prints pathspec 1.1.1.

As you suggested, I'll take up items 3, 5 and 6 and the minor points once #481 lands and this PR is down to its
six files.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants