Skip to content

fix: prevent file watcher dead after stopping one of same inode paths - #414

Closed
Johnson-zs wants to merge 1 commit into
linuxdeepin:masterfrom
Johnson-zs:master
Closed

Johnson-zs wants to merge 1 commit into
linuxdeepin:masterfrom
Johnson-zs:master

Conversation

@Johnson-zs

@Johnson-zs Johnson-zs commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Added reference-counted registry to prevent GLib's inotify backend
from canceling shared watch descriptors when multiple paths point
to the same inode (via symlinks or bind mounts). Previously, if two
DWatcher instances monitored the same directory through different
paths (e.g., directory and symlink), stopping one would cancel the
underlying inotify watch, leaving the other watcher permanently deaf.
The new MonitorKeepAliveRegistry tracks active watchers per inode,
only canceling the shared monitor when the last watcher for that inode
stops. This ensures remaining watchers continue receiving events. Two
test cases verify both that stopping one path does not affect others
and that a fresh watcher works after all previous watchers for an inode
are stopped.

Influence:

  1. Test monitoring a directory and its symlink simultaneously, then stop
    one watcher
  2. Verify the remaining watcher still receives file creation/deletion
    events
  3. Test scenario with multiple bind mounts or hard links to same
    directory
  4. Test that after stopping all watchers for an inode, new watchers
    work correctly
  5. Ensure non-local file paths (non-inotify cases) fall back to direct
    cancel without regression

fix: 修复停止同一inode路径之一后文件监视器失效的问题

添加了引用计数注册表,以防止在多个路径指向同一inode(通过符号链接或绑定
挂载)时,GLib的inotify后端取消共享监视描述符。之前,如果两个DWatcher实
例通过不同路径(例如目录和符号链接)监视同一目录,停止其中一个会取消底层
的inotify监视,导致另一个监视器永久失效。新的MonitorKeepAliveRegistry按
inode跟踪活动监视器,仅在该inode的最后一个监视器停止时才取消共享监视器。
这确保了剩余的监视器能继续接收事件。两个测试用例验证了停止一个路径不影响
其他路径,以及在该inode的所有先前监视器停止后,新的监视器仍能正常工作。

Influence:

  1. 测试同时监视目录及其符号链接,然后停止其中一个监视器
  2. 验证剩余的监视器仍能接收文件创建/删除事件
  3. 测试具有多个绑定挂载或硬链接到同一目录的场景
  4. 测试在停止某个inode的所有监视器后,新的监视器能正常工作
  5. 确保非本地文件路径(非inotify情况)回退到直接取消而不会引起回归

Log:

PMS: Task-398995

Summary by Sourcery

Keep file watchers active when multiple paths reference the same inode by coordinating shared monitor lifetime.

Bug Fixes:

  • Prevent stopping one watcher for a shared inode from disabling other active watchers.
  • Ensure new watchers work after all watchers for a shared inode have stopped.

Enhancements:

  • Track active watchers by inode and defer shared monitor cleanup until the final watcher stops.
  • Preserve direct cancellation for paths that cannot use inode-based monitoring.

Tests:

  • Add coverage for symlinked paths sharing an inode, including continued event delivery after stopping one watcher and recovery after stopping all watchers.

Added reference-counted registry to prevent GLib's inotify backend
from canceling shared watch descriptors when multiple paths point
to the same inode (via symlinks or bind mounts). Previously, if two
DWatcher instances monitored the same directory through different
paths (e.g., directory and symlink), stopping one would cancel the
underlying inotify watch, leaving the other watcher permanently deaf.
The new MonitorKeepAliveRegistry tracks active watchers per inode,
only canceling the shared monitor when the last watcher for that inode
stops. This ensures remaining watchers continue receiving events. Two
test cases verify both that stopping one path does not affect others
and that a fresh watcher works after all previous watchers for an inode
are stopped.

Influence:
1. Test monitoring a directory and its symlink simultaneously, then stop
one watcher
2. Verify the remaining watcher still receives file creation/deletion
events
3. Test scenario with multiple bind mounts or hard links to same
directory
4. Test that after stopping all watchers for an inode, new watchers
work correctly
5. Ensure non-local file paths (non-inotify cases) fall back to direct
cancel without regression

fix: 修复停止同一inode路径之一后文件监视器失效的问题

添加了引用计数注册表,以防止在多个路径指向同一inode(通过符号链接或绑定
挂载)时,GLib的inotify后端取消共享监视描述符。之前,如果两个DWatcher实
例通过不同路径(例如目录和符号链接)监视同一目录,停止其中一个会取消底层
的inotify监视,导致另一个监视器永久失效。新的MonitorKeepAliveRegistry按
inode跟踪活动监视器,仅在该inode的最后一个监视器停止时才取消共享监视器。
这确保了剩余的监视器能继续接收事件。两个测试用例验证了停止一个路径不影响
其他路径,以及在该inode的所有先前监视器停止后,新的监视器仍能正常工作。

Influence:
1. 测试同时监视目录及其符号链接,然后停止其中一个监视器
2. 验证剩余的监视器仍能接收文件创建/删除事件
3. 测试具有多个绑定挂载或硬链接到同一目录的场景
4. 测试在停止某个inode的所有监视器后,新的监视器能正常工作
5. 确保非本地文件路径(非inotify情况)回退到直接取消而不会引起回归

Log:

PMS: Task-398995
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: Johnson-zs

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@sourcery-ai

sourcery-ai Bot commented Nov 20, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Track active monitors by inode and defer canceling parked GLib monitors until the last watcher for that inode stops.

  • src/dfm-io/dfm-io/dwatcher.cpp L11-86, L275-278, L285-300 (+3 small edits)
  • src/dfm-io/dfm-io/private/dwatcher_p.h L35

Tests

Add symlink-based regressions for keeping a surviving watcher active and for starting a fresh watcher after all prior watchers stop.

  • autotests/dfm-io-tests/tst_dfm_io.cpp L6-15, L25-31, L50-112

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="289" />
<code_context>
+        if (MonitorKeepAliveRegistry::instance().retainOrPark(d->inodeKey, d->gmonitor, &doomed)) {
+            // 同inode仍有其它路径在监视:不cancel(会误删GLib共享订阅使存活者永久失聪),
+            // 仅断开changed回调静默本对象,监视器交由注册表持有
+            g_signal_handlers_disconnect_by_data(d->gmonitor, this);
+            d->gmonitor = nullptr;
+        } else {
</code_context>
<issue_to_address>
**Concurrent stops crash**

When two watchers for the same inode are stopped concurrently, `retainOrPark()` returns a parked monitor without protecting it from a concurrent final `stop()`, which can cancel and unref it before `g_signal_handlers_disconnect_by_data()` uses it, crashing the process.

Keep a strong reference to the monitor until its signal handler is disconnected, or serialize disconnection with final removal.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:297`.
</issue_to_address>

### Comment 2
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="60" />
<code_context>
+            return true;
+        }
+        refCounts.remove(key);
+        *doomed = parked.value(key);
+        parked.remove(key);
+        return false;
</code_context>
<issue_to_address>
**New watcher stops receiving events**

When a watcher starts while another thread stops the last watcher for the same inode, `start()` creates or registers its monitor while `retainOrPark()` has removed the last count and `stop()` is canceling outside the mutex, so canceling the old monitor disables the shared backend watch and the new watcher stops receiving events.

Serialize start registration and last-monitor cancellation so a new watcher cannot join a watch that is being canceled.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:276-278`, `src/dfm-io/dfm-io/dwatcher.cpp:286-299`.
</issue_to_address>

### Comment 3
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="276" />
<code_context>
     g_signal_connect(d->gmonitor, "changed", G_CALLBACK(&DWatcherPrivate::watchCallback), this);

+    // key在start时缓存:stop时目标可能已被删除重建(inode变化),重stat会减错计数
+    d->inodeKey = inodeKeyOf(d->gfile);
+    MonitorKeepAliveRegistry::instance().addActive(d->inodeKey);
+
</code_context>
<issue_to_address>
**Replacement path cancels active watch**

When the watched path is replaced between monitor creation and the subsequent `stat()`, `inodeKeyOf()` records the replacement inode's key for a monitor still attached to the original inode, so stopping that watcher can cancel the shared watch used by another watcher of the original inode, which then stops receiving events.

Derive the registry key from the inode actually attached to the monitor rather than statting the path after monitor creation.
</issue_to_address>

### Comment 4
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="80-81" />
<code_context>
+    if (!path)
+        return 0;
+    struct stat st;
+    if (::stat(path, &st) != 0)
+        return 0;
+    return (quint64(st.st_dev) << 32) | quint32(st.st_ino);
+}
</code_context>
<issue_to_address>
**Missing files bypass shared registry**

When a file watcher successfully monitors a nonexistent local file through one of multiple paths to the same parent directory, `inodeKeyOf` returns zero for a nonexistent local target, so `stop()` directly cancels its monitor; when GLib monitors that missing file through its parent directory, canceling one alias also removes the shared inotify watch and the other watcher misses the file’s creation.

For local paths whose target does not exist, key the monitor by the inode of the directory GLib watches, or otherwise coordinate cancellation of monitors sharing that parent watch.
</issue_to_address>

### Comment 5
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="82-83" />
<code_context>
+    struct stat st;
+    if (::stat(path, &st) != 0)
+        return 0;
+    return (quint64(st.st_dev) << 32) | quint32(st.st_ino);
+}
+
+}   // namespace
</code_context>
<issue_to_address>
**Colliding inodes retain monitors**

When distinct inodes have the same encoded low 32-bit device and inode values and one watcher remains active, `inodeKeyOf()` truncates `st_dev` and `st_ino` to 32 bits, so distinct inodes share a registry key; stopping one watcher parks its monitor while the unrelated watcher remains active, retaining monitors and kernel watches and potentially exhausting watcher resources.

Use a registry key that preserves the full device and inode values.
</issue_to_address>

### Comment 6
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="56" />
<code_context>
+        const int remaining = refCounts.value(key) - 1;
+        if (remaining > 0) {
+            refCounts[key] = remaining;
+            parked[key].append(monitor);
+            return true;
+        }
</code_context>
<issue_to_address>
**Repeated restarts accumulate monitors**

When one watcher is repeatedly restarted while another watcher for the same inode stays active, `DWatcher::start()` first calls `stop()`, which parks the old monitor whenever another watcher for the inode remains active. Each subsequent restart creates another monitor, so the registry retains one more `GFileMonitor` per restart until the other watcher stops; a long-lived sibling therefore lets repeated restarts grow retained objects without bound.

Avoid retaining a new parked monitor for every restart, for example by deduplicating or reusing retained monitors for that inode.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

if (MonitorKeepAliveRegistry::instance().retainOrPark(d->inodeKey, d->gmonitor, &doomed)) {
// 同inode仍有其它路径在监视:不cancel(会误删GLib共享订阅使存活者永久失聪),
// 仅断开changed回调静默本对象,监视器交由注册表持有
g_signal_handlers_disconnect_by_data(d->gmonitor, this);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Concurrent stops crash

When two watchers for the same inode are stopped concurrently, retainOrPark() returns a parked monitor without protecting it from a concurrent final stop(), which can cancel and unref it before g_signal_handlers_disconnect_by_data() uses it, crashing the process.

Keep a strong reference to the monitor until its signal handler is disconnected, or serialize disconnection with final removal.

Also at src/dfm-io/dfm-io/dwatcher.cpp:297.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at line 289:

**Concurrent stops crash**

When two watchers for the same inode are stopped concurrently, `retainOrPark()` returns a parked monitor without protecting it from a concurrent final `stop()`, which can cancel and unref it before `g_signal_handlers_disconnect_by_data()` uses it, crashing the process.

Keep a strong reference to the monitor until its signal handler is disconnected, or serialize disconnection with final removal.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:297`.

return true;
}
refCounts.remove(key);
*doomed = parked.value(key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · New watcher stops receiving events

When a watcher starts while another thread stops the last watcher for the same inode, start() creates or registers its monitor while retainOrPark() has removed the last count and stop() is canceling outside the mutex, so canceling the old monitor disables the shared backend watch and the new watcher stops receiving events.

Serialize start registration and last-monitor cancellation so a new watcher cannot join a watch that is being canceled.

Also at src/dfm-io/dfm-io/dwatcher.cpp:276-278, src/dfm-io/dfm-io/dwatcher.cpp:286-299.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at line 60:

**New watcher stops receiving events**

When a watcher starts while another thread stops the last watcher for the same inode, `start()` creates or registers its monitor while `retainOrPark()` has removed the last count and `stop()` is canceling outside the mutex, so canceling the old monitor disables the shared backend watch and the new watcher stops receiving events.

Serialize start registration and last-monitor cancellation so a new watcher cannot join a watch that is being canceled.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:276-278`, `src/dfm-io/dfm-io/dwatcher.cpp:286-299`.

g_signal_connect(d->gmonitor, "changed", G_CALLBACK(&DWatcherPrivate::watchCallback), this);

// key在start时缓存:stop时目标可能已被删除重建(inode变化),重stat会减错计数
d->inodeKey = inodeKeyOf(d->gfile);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Replacement path cancels active watch

When the watched path is replaced between monitor creation and the subsequent stat(), inodeKeyOf() records the replacement inode's key for a monitor still attached to the original inode, so stopping that watcher can cancel the shared watch used by another watcher of the original inode, which then stops receiving events.

Derive the registry key from the inode actually attached to the monitor rather than statting the path after monitor creation.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at line 276:

**Replacement path cancels active watch**

When the watched path is replaced between monitor creation and the subsequent `stat()`, `inodeKeyOf()` records the replacement inode's key for a monitor still attached to the original inode, so stopping that watcher can cancel the shared watch used by another watcher of the original inode, which then stops receiving events.

Derive the registry key from the inode actually attached to the monitor rather than statting the path after monitor creation.

Comment on lines +80 to +81
if (::stat(path, &st) != 0)
return 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Missing files bypass shared registry

When a file watcher successfully monitors a nonexistent local file through one of multiple paths to the same parent directory, inodeKeyOf returns zero for a nonexistent local target, so stop() directly cancels its monitor; when GLib monitors that missing file through its parent directory, canceling one alias also removes the shared inotify watch and the other watcher misses the file’s creation.

For local paths whose target does not exist, key the monitor by the inode of the directory GLib watches, or otherwise coordinate cancellation of monitors sharing that parent watch.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at lines 80-81:

**Missing files bypass shared registry**

When a file watcher successfully monitors a nonexistent local file through one of multiple paths to the same parent directory, `inodeKeyOf` returns zero for a nonexistent local target, so `stop()` directly cancels its monitor; when GLib monitors that missing file through its parent directory, canceling one alias also removes the shared inotify watch and the other watcher misses the file’s creation.

For local paths whose target does not exist, key the monitor by the inode of the directory GLib watches, or otherwise coordinate cancellation of monitors sharing that parent watch.

Comment on lines +82 to +83
return (quint64(st.st_dev) << 32) | quint32(st.st_ino);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Colliding inodes retain monitors

When distinct inodes have the same encoded low 32-bit device and inode values and one watcher remains active, inodeKeyOf() truncates st_dev and st_ino to 32 bits, so distinct inodes share a registry key; stopping one watcher parks its monitor while the unrelated watcher remains active, retaining monitors and kernel watches and potentially exhausting watcher resources.

Use a registry key that preserves the full device and inode values.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at lines 82-83:

**Colliding inodes retain monitors**

When distinct inodes have the same encoded low 32-bit device and inode values and one watcher remains active, `inodeKeyOf()` truncates `st_dev` and `st_ino` to 32 bits, so distinct inodes share a registry key; stopping one watcher parks its monitor while the unrelated watcher remains active, retaining monitors and kernel watches and potentially exhausting watcher resources.

Use a registry key that preserves the full device and inode values.

const int remaining = refCounts.value(key) - 1;
if (remaining > 0) {
refCounts[key] = remaining;
parked[key].append(monitor);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Repeated restarts accumulate monitors

When one watcher is repeatedly restarted while another watcher for the same inode stays active, DWatcher::start() first calls stop(), which parks the old monitor whenever another watcher for the inode remains active. Each subsequent restart creates another monitor, so the registry retains one more GFileMonitor per restart until the other watcher stops; a long-lived sibling therefore lets repeated restarts grow retained objects without bound.

Avoid retaining a new parked monitor for every restart, for example by deduplicating or reusing retained monitors for that inode.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at line 56:

**Repeated restarts accumulate monitors**

When one watcher is repeatedly restarted while another watcher for the same inode stays active, `DWatcher::start()` first calls `stop()`, which parks the old monitor whenever another watcher for the inode remains active. Each subsequent restart creates another monitor, so the registry retains one more `GFileMonitor` per restart until the other watcher stops; a long-lived sibling therefore lets repeated restarts grow retained objects without bound.

Avoid retaining a new parked monitor for every restart, for example by deduplicating or reusing retained monitors for that inode.

@Johnson-zs

Copy link
Copy Markdown
Contributor Author

deepin-community/glib2.0@dc7aa53 通过上游补丁解决

@Johnson-zs Johnson-zs closed this Nov 23, 2026
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