← Back to Pull requests

tail: keep following moved descriptor when watch is lost #17002

Open
mattsu2020 opened this pull request with 247 lines diff across 2 files
View on GitHub
mattsu2020 mattsu2020 commented on Nov 29, 2026 22:30 UTC
Author

Split out from #9093.

When following by descriptor (tail -f), moving a file out of its watched directory or on backends that do not emit RenameMode::Both drops the watch on that file, so further appends stop being printed while events for other files arrive.

Track moved open descriptors in orphans so they are read on subsequent events and timeouts, guard the file-replacement reopen branch with follow_name(), and add a regression test.

Diff: 247 lines (+218 / -29) across 2 files Reviewer: sylvestre Review duration: 6549m
All Vouch review confidence checks passed
Residual risk 0.03 = Change Risk (0.37) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.37 · 247 lines diff across 2 files
0.37
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.94 · 5 substantive comment(s)
0.94
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
92%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.330
Real PR Conversation Timeline
14 items
sylvestre sylvestre commented on code on Nov 30, 2026 20:51 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -479,8 +480,15 @@ impl Observer {
                 }
             }
             EventKind::Remove(RemoveKind::File | RemoveKind::Any)
-                | EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
-                if self.follow_name() {
+                | EventKind::Modify(ModifyKind::Name(RenameMode::From | RenameMode::Any)) => {

adding RenameMode::Any here also changes the -F path below: on macOS a replaced file would now be reported as gone and its reader reset.
is it expected? if not, please limit it to the descriptor case

sylvestre sylvestre commented on code on Nov 30, 2026 20:51 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -479,8 +480,15 @@ impl Observer {
                 }
             }
             EventKind::Remove(RemoveKind::File | RemoveKind::Any)
-                | EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
-                if self.follow_name() {
+                | EventKind::Modify(ModifyKind::Name(RenameMode::From | RenameMode::Any)) => {
+                if self.follow_descriptor() && self.files.get(event_path).reader.is_some() {

with this, the follow_descriptor_retry() branch below is no longer reached when a reader exists, so tail -f --retry f; rm f behaves differently now.
intended? please add a test for it

sylvestre sylvestre commented on code on Nov 30, 2026 20:51 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -557,7 +565,17 @@ impl Observer {
 
                     // Unwatch old path and watch new path
                     let _ = self.watcher_rx.as_mut().unwrap().unwatch(event_path);
-                    self.watcher_rx.as_mut().unwrap().watch_with_parent(new_path)?;
+                    self.orphans.retain(|path| path != event_path);
+                    if self
+                        .watcher_rx
+                        .as_mut()
+                        .unwrap()
+                        .watch_with_parent(new_path)
+                        .is_err()

this ignores every error, not just a missing path. could you please only handle NotFound and keep the ? for the rest?

sylvestre sylvestre commented on code on Nov 30, 2026 20:51 UTC
Code Review
tests/by-util/test_tail.rs:1
@@ -2255,6 +2255,38 @@ fn test_follow_descriptor_vs_rename1() {
     }
 }
 
+#[uutests::wasi_ignore(TailFollowDisabled)]
+#[test]
+#[cfg(unix)]
+fn test_follow_descriptor_moved_while_other_file_changes() {

does this test fail on main? with inotify the watch on the inode should survive the move

sylvestre sylvestre commented on Nov 30, 2026 21:07 UTC
Contributor

thanks for picking this up!
This can't land yet: adding RenameMode::Any and reordering the Remove arm also change -F and -f --retry, and no test covers that (details inline). Please also check that the new test fails without the fix.

mattsu2020 mattsu2020 commented on code on Nov 30, 2026 23:11 UTC
Code Review
tests/by-util/test_tail.rs:1
@@ -2255,6 +2255,38 @@ fn test_follow_descriptor_vs_rename1() {
     }
 }
 
+#[uutests::wasi_ignore(TailFollowDisabled)]
+#[test]
+#[cfg(unix)]
+fn test_follow_descriptor_moved_while_other_file_changes() {

On Linux, watch_with_parent non-recursively watches the parent directory rather than the file inode.
As a result, when a file is moved to moved/f, only RenameMode::From is emitted and no subsequent append events are received at the destination—causing this to fail on main as well.

mattsu2020 mattsu2020 commented on code on Nov 30, 2026 23:12 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -557,7 +565,17 @@ impl Observer {
 
                     // Unwatch old path and watch new path
                     let _ = self.watcher_rx.as_mut().unwrap().unwatch(event_path);
-                    self.watcher_rx.as_mut().unwrap().watch_with_parent(new_path)?;
+                    self.orphans.retain(|path| path != event_path);
+                    if self
+                        .watcher_rx
+                        .as_mut()
+                        .unwrap()
+                        .watch_with_parent(new_path)
+                        .is_err()

fixed it

mattsu2020 mattsu2020 commented on code on Nov 30, 2026 23:12 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -479,8 +480,15 @@ impl Observer {
                 }
             }
             EventKind::Remove(RemoveKind::File | RemoveKind::Any)
-                | EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
-                if self.follow_name() {
+                | EventKind::Modify(ModifyKind::Name(RenameMode::From | RenameMode::Any)) => {
+                if self.follow_descriptor() && self.files.get(event_path).reader.is_some() {

fixed it

mattsu2020 mattsu2020 commented on code on Nov 30, 2026 23:12 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -479,8 +480,15 @@ impl Observer {
                 }
             }
             EventKind::Remove(RemoveKind::File | RemoveKind::Any)
-                | EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
-                if self.follow_name() {
+                | EventKind::Modify(ModifyKind::Name(RenameMode::From | RenameMode::Any)) => {

fixed it

sylvestre sylvestre commented on code on Dec 01, 2026 15:15 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -36,14 +36,27 @@ impl WatcherRx {
 
     /// Wrapper for `notify::Watcher::watch` to also add the parent directory of `path` if necessary.
     fn watch_with_parent(&mut self, path: &Path) -> UResult<()> {
+        self.watch_with_parent_inner(path, false)?;
+        Ok(())
+    }
+
+    /// Like `watch_with_parent`, but returns `Ok(false)` when the target path
+    /// disappears before it can be watched instead of returning an error.
+    fn try_watch_with_parent(&mut self, path: &Path) -> UResult<bool> {
+        self.watch_with_parent_inner(path, true)
+    }
+
+    fn watch_with_parent_inner(&mut self, path: &Path, ignore_not_found: bool) -> UResult<bool> {

5 functions (watch, watch_inner, watch_with_parent, try_watch_with_parent, watch_with_parent_inner) for one caller is a lot
could watch_with_parent just return the UResult<bool> and callers ignore it?

mattsu2020 mattsu2020 commented on code on Dec 01, 2026 22:24 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -36,14 +36,27 @@ impl WatcherRx {
 
     /// Wrapper for `notify::Watcher::watch` to also add the parent directory of `path` if necessary.
     fn watch_with_parent(&mut self, path: &Path) -> UResult<()> {
+        self.watch_with_parent_inner(path, false)?;
+        Ok(())
+    }
+
+    /// Like `watch_with_parent`, but returns `Ok(false)` when the target path
+    /// disappears before it can be watched instead of returning an error.
+    fn try_watch_with_parent(&mut self, path: &Path) -> UResult<bool> {
+        self.watch_with_parent_inner(path, true)
+    }
+
+    fn watch_with_parent_inner(&mut self, path: &Path, ignore_not_found: bool) -> UResult<bool> {

fixed it

codspeed[bot] codspeed[bot] commented on Dec 02, 2026 05:12 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will improve performance by 11.19%

<details>
<summary><b>1 warning, 1 note</b></summary>

:warning: 128 benchmarks are dominated by system calls

> System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

> Learn more about system calls

> See affected benchmarks

:information_source: 1 benchmark has no flamegraph

> The flamegraph wasn't generated: most of the time was spent in runtime internals, which would leave nothing useful to analyze.

> See affected benchmarks

</details>

⚡ 3 improved benchmarks
✅ 420 untouched benchmarks
⏩ 78 skipped benchmarks[^skipped]

Performance Changes

| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ⚡ | CPU Simulation | [` socket_addrs_direct[100000] ](https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Atail_follow_moved_descriptor?uri=src%2Fuu%2Fhostname%2Fbenches%2Fhostname_bench.rs%3A%3Asocket_addrs_direct%255B100000%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 132.1 µs | 105.2 µs | +25.53% |
| ⚡ | CPU Simulation | [
hostname_ip_lookup[100000] ](https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Atail_follow_moved_descriptor?uri=src%2Fuu%2Fhostname%2Fbenches%2Fhostname_bench.rs%3A%3Ahostname_ip_lookup%255B100000%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 573.3 µs | 545 µs | +5.2% |
| ⚡ | CPU Simulation |
true_single_call | 1.4 µs | 1.4 µs | +4.08% |

[!TIP]

Curious why performance improved? Comment @codspeedbot explain why performance improved` on this PR, or directly use the CodSpeed MCP with your agent.

---

<sub>Comparing <code>mattsu2020:tail_follow_moved_descriptor</code> (d0a7b6c) with <code>main</code> (ba3f47d)[^unexpected-base]</sub>

<a href="https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Atail_follow_moved_descriptor?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>

[^skipped]: 78 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
[^unexpected-base]: No successful run was found on <code>main</code> (ff93e0c) during the generation of this report, so ba3f47d was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

sylvestre sylvestre commented on code on Dec 02, 2026 18:25 UTC
Code Review
src/uu/tail/src/follow/watch.rs:1
@@ -68,18 +69,23 @@ impl WatcherRx {
             }
         }
         if path.is_relative() {
-            path = path.canonicalize()?;
+            path = match path.canonicalize() {
+                Ok(canonical) => canonical,
+                Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+                Err(err) => return Err(err.into()),
+            };
         }
 
         // for syscalls: 2x "inotify_add_watch" ("filename" and ".") and 1x "inotify_rm_watch"
-        self.watch(&path, RecursiveMode::NonRecursive)?;
-        Ok(())
+        self.watch(&path, RecursiveMode::NonRecursive)
     }
 
-    fn watch(&mut self, path: &Path, mode: RecursiveMode) -> UResult<()> {
-        self.watcher
-            .watch(path, mode)
-            .map_err(|err| USimpleError::new(1, err.to_string()))
+    fn watch(&mut self, path: &Path, mode: RecursiveMode) -> UResult<bool> {
+        match self.watcher.watch(path, mode) {
+            Ok(()) => Ok(true),
+            Err(err) if is_notify_not_found(&err) => Ok(false),

now every caller ignores NotFound, e.g. the initial watch_with_parent in start drops the false and the file is neither watched nor in orphans.
should it be pushed to orphans there too?

Reviewers
Assignees
mattsu2020 mattsu2020
Labels
risk: low confidence: 92.4% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 37.4% (MEDIUM) · Higher = larger blast radius
37.4%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 92.4% · Lower = rushed or shallow review
92.4%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 2.8% · Safe to merge
2.8%