Skip to content

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

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:develop/meagle-20260526from
liyigang1:fix/dwatcher-same-inode-keepalive-meagle-20260526
Nov 24, 2026
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:develop/meagle-20260526from
liyigang1:fix/dwatcher-same-inode-keepalive-meagle-20260526

Conversation

@liyigang1

@liyigang1 liyigang1 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor
  1. Root cause: GLib inotify backend shares watch descriptors by inode; when several DWatcher instances watch the same directory through different paths (symlink or bind mount), stopping one cancels the shared inotify watch and leaves the others deaf until the 4s missing-scan of GLib re-adds them (events in between are lost), and the leftover path bucket makes later watchers attach to a dead watch
  2. Fix: add MonitorKeepAliveRegistry counting active watchers by full (st_dev, st_ino); a stopping watcher parks its GFileMonitor without cancel while others for the same inode stay active, and the last one cancels and releases all parked monitors; disconnect the changed handler under the registry lock to avoid concurrent-stop use-after-free; keep a full-width inode key to avoid truncation
  3. Reuse a parked monitor on restart only when the watch type and the creation path both match: GLib builds event child paths from the path used to create the monitor, so reusing one across aliased paths (/home/x vs /data/home/x) makes events carry the old prefix and upper layers drop them; matching reuse still bounds monitor growth
  4. Impact: watchers on aliased paths keep receiving events after one path stops, and always report them under their own path; new watchers work after all watchers for an inode stop; non-local paths fall back to direct cancel without regression

Log: Fix file watcher becoming deaf after stopping one same-inode path

Influence:

  1. Test watching a directory and its symlink together, then stop one watcher; the remaining one still receives create/delete events
  2. Test the event url of a restarted watcher stays under its own path when a monitor of a sibling alias path is parked for the same inode
  3. Test the file manager round trip home -> data disk -> home (two paths of the same inode, the new view starts before the old one stops) keeps receiving events on both views
  4. Test a fresh watcher works after all watchers for an inode stop
  5. Verify non-local paths fall back to direct cancel without regression

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

  1. 根因:GLib的inotify后端按inode共享watch描述符,多条路径(符号链接或 绑定挂载)监视同一目录时,停止其中一条路径会cancel共享订阅,使其它 存活监视器失聪,直到GLib的missing轮询(4秒)重新加回订阅,期间的事件 全部丢失;残留的path桶还会让新建监视器挂到死订阅上
  2. 方案:新增MonitorKeepAliveRegistry按完整(st_dev, st_ino)对活跃监视器 计数,停止方在同inode仍有其它活跃监视器时只寄存GFileMonitor而不cancel, 最后一个活跃者停止时才统一cancel并析构全部寄存监视器;在锁内断开changed 回调避免并发停止的悬垂指针;inode key保留完整宽度避免截断撞key
  3. 仅在watch类型与"建该监视器时的本地路径"都一致时复用寄存监视器: GLib用建监视时的路径字符串拼事件child路径,跨别名路径复用(/home/x与 /data/home/x)会让事件带上旧前缀而被上层丢弃;按路径匹配的复用同样能 避免寄存桶无限增长
  4. 影响:同一inode多路径监视时,停止一条路径不再影响其它路径收事件, 且事件始终落在该监视器自己的路径下;全部停止后新建监视器可正常工作; 非本地路径回退到直接cancel无回归

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

Influence:

  1. 测试同时监视目录及其符号链接,停止其中一个监视器后,剩余的仍能收到事件
  2. 测试同inode别名路径的监视器处于寄存状态时,重启的监视器上报的事件URL 仍在其自身路径下
  3. 测试文件管理器"主目录 -> 数据盘 -> 主目录"往返(同inode两条路径,新视图 先于旧视图销毁而建立)后,两个视图都能正常收到事件
  4. 测试该inode所有监视器停止后,新建监视器正常工作
  5. 验证非本地路径回退到直接cancel,无回归

PMS: Task-398995

Summary by Sourcery

Keep file watchers active and path-correct when multiple aliases reference the same inode.

Bug Fixes:

  • Prevent stopping a watcher on one aliased path from disabling active watchers sharing the same inode.
  • Ensure restarted watchers report events under their own paths and recover correctly after all same-inode watchers stop.
  • Preserve direct cancellation behavior for non-local paths.

Enhancements:

  • Add inode-based monitor keep-alive and safe parked-monitor reuse for shared local watches.

Tests:

  • Add coverage for symlinked same-inode watchers, path-correct monitor restart, watcher recovery, and file-manager path round trips.

1. Root cause: GLib inotify backend shares watch descriptors by inode;
   when several DWatcher instances watch the same directory through
   different paths (symlink or bind mount), stopping one cancels the
   shared inotify watch and leaves the others deaf until the 4s
   missing-scan of GLib re-adds them (events in between are lost), and
   the leftover path bucket makes later watchers attach to a dead watch
2. Fix: add MonitorKeepAliveRegistry counting active watchers by full
   (st_dev, st_ino); a stopping watcher parks its GFileMonitor without
   cancel while others for the same inode stay active, and the last one
   cancels and releases all parked monitors; disconnect the changed
   handler under the registry lock to avoid concurrent-stop
   use-after-free; keep a full-width inode key to avoid truncation
3. Reuse a parked monitor on restart only when the watch type and the
   creation path both match: GLib builds event child paths from the
   path used to create the monitor, so reusing one across aliased paths
   (/home/x vs /data/home/x) makes events carry the old prefix and
   upper layers drop them; matching reuse still bounds monitor growth
4. Impact: watchers on aliased paths keep receiving events after one
   path stops, and always report them under their own path; new
   watchers work after all watchers for an inode stop; non-local paths
   fall back to direct cancel without regression

Log: Fix file watcher becoming deaf after stopping one same-inode path

Influence:
1. Test watching a directory and its symlink together, then stop one
   watcher; the remaining one still receives create/delete events
2. Test the event url of a restarted watcher stays under its own path
   when a monitor of a sibling alias path is parked for the same inode
3. Test the file manager round trip home -> data disk -> home (two
   paths of the same inode, the new view starts before the old one
   stops) keeps receiving events on both views
4. Test a fresh watcher works after all watchers for an inode stop
5. Verify non-local paths fall back to direct cancel without regression

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

1. 根因:GLib的inotify后端按inode共享watch描述符,多条路径(符号链接或
   绑定挂载)监视同一目录时,停止其中一条路径会cancel共享订阅,使其它
   存活监视器失聪,直到GLib的missing轮询(4秒)重新加回订阅,期间的事件
   全部丢失;残留的path桶还会让新建监视器挂到死订阅上
2. 方案:新增MonitorKeepAliveRegistry按完整(st_dev, st_ino)对活跃监视器
   计数,停止方在同inode仍有其它活跃监视器时只寄存GFileMonitor而不cancel,
   最后一个活跃者停止时才统一cancel并析构全部寄存监视器;在锁内断开changed
   回调避免并发停止的悬垂指针;inode key保留完整宽度避免截断撞key
3. 仅在watch类型与"建该监视器时的本地路径"都一致时复用寄存监视器:
   GLib用建监视时的路径字符串拼事件child路径,跨别名路径复用(/home/x与
   /data/home/x)会让事件带上旧前缀而被上层丢弃;按路径匹配的复用同样能
   避免寄存桶无限增长
4. 影响:同一inode多路径监视时,停止一条路径不再影响其它路径收事件,
   且事件始终落在该监视器自己的路径下;全部停止后新建监视器可正常工作;
   非本地路径回退到直接cancel无回归

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

Influence:
1. 测试同时监视目录及其符号链接,停止其中一个监视器后,剩余的仍能收到事件
2. 测试同inode别名路径的监视器处于寄存状态时,重启的监视器上报的事件URL
   仍在其自身路径下
3. 测试文件管理器"主目录 -> 数据盘 -> 主目录"往返(同inode两条路径,新视图
   先于旧视图销毁而建立)后,两个视图都能正常收到事件
4. 测试该inode所有监视器停止后,新建监视器正常工作
5. 验证非本地路径回退到直接cancel,无回归

PMS: Task-398995
@sourcery-ai

sourcery-ai Bot commented Nov 24, 2026

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define the full-width inode key used to identify monitors for the same underlying file across aliased paths.

  • src/dfm-io/dfm-io/private/dwatcher_p.h L16-36, L54

Implementation

Implement the inode-keyed keep-alive registry, monitor parking and path/type-matched reuse, then integrate it with watcher start and stop to preserve shared GLib subscriptions.

  • src/dfm-io/dfm-io/dwatcher.cpp L11-138, L313-322, L347-362 (+5 small edits)

Tests

Add regression tests for aliased-path event delivery, correct event URLs after monitor reuse, clean restart after all watchers stop, and the view-switch round trip.

  • autotests/dfm-io-tests/tst_dfm_io.cpp L6-15, L25-40, L59-204

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 5 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="67" />
<code_context>
+            parked[key].append(ParkedMonitor { monitor, type, path });
+            return true;
+        }
+        refCounts.remove(key);
+        for (const ParkedMonitor &parkedMonitor : parked.value(key))
+            doomed->append(parkedMonitor.monitor);
</code_context>
<issue_to_address>
**New watchers lose filesystem events**

When a new watcher starts for an inode while its last watcher is stopping, `retainOrPark()` removes the final registry entry before `stop()` cancels its monitors, while `start()` creates the replacement monitor before `addActive()` registers it; the cancellation removes GLib's shared watch and the new watcher misses events.

Synchronize monitor creation and registration with final-stop cancellation so a new watcher cannot share a watch that is scheduled for cancellation.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:324-339`, `src/dfm-io/dfm-io/dwatcher.cpp:354-360`.
</issue_to_address>

### Comment 2
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="313" />
<code_context>
         url.append("/");

     d->gfile = DLocalHelper::createGFile(url);
+    d->inodeKey = inodeKeyOf(d->gfile);
+
+    // 复用注册表中同inode、同watch类型且同路径的寄存监视器:避免反复start/stop在兄弟
</code_context>
<issue_to_address>
**Replacement watchers use the wrong inode key**

When the watched path or symlink target changes between `inodeKeyOf()` and `createMonitor()`, `inodeKeyOf()` records the old target while `createMonitor()` attaches to the replacement, so the registry counts and stops the monitor under the wrong inode; cancellation can silence watchers of the replacement.

Key the registry using the inode actually watched by the created monitor, or verify the path identity has not changed before registering it.

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

### Comment 3
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="348" />
<code_context>
-        g_object_unref(d->gmonitor);
-        d->gmonitor = nullptr;
+        QList<GFileMonitor *> doomed;
+        if (MonitorKeepAliveRegistry::instance().retainOrPark(d->inodeKey, d->gmonitor, d->type,
+                                                             localPathOf(d->gfile), this, &doomed)) {
+            // 同inode仍有其它路径在监视:不cancel(会误删GLib共享订阅使存活者永久失聪),
</code_context>
<issue_to_address>
**Revived monitors use the wrong watch type**

When a watcher changes its watch type after starting and its parked monitor is later revived, `stop()` passes the current `d->type` to `retainOrPark()` instead of the type used to create `d->gmonitor`; `reviveParked()` can then match and return a monitor with different monitoring semantics, so the restarted watcher gets the wrong events.

Store the monitor's creation-time watch type and use that type when parking and matching it for revival.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:64`, `src/dfm-io/dfm-io/dwatcher.cpp:91`, `src/dfm-io/dfm-io/dwatcher.cpp:349`.
</issue_to_address>

### Comment 4
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="91-93" />
<code_context>
+        QList<ParkedMonitor> &list = it.value();
+        for (int i = list.size() - 1; i >= 0; --i) {
+            const ParkedMonitor &item = list.at(i);
+            if (item.type == type && item.path == path) {
+                GFileMonitor *monitor = list.takeAt(i).monitor;
+                if (list.isEmpty())
+                    parked.erase(it);
+                ++refCounts[key];
</code_context>
<issue_to_address>
**Reused monitor emits on old thread**

When a monitor is parked in one thread’s main context and a watcher for the same path and type revives it after moving to or starting in another thread, `reviveParked()` can return a monitor created in another thread; GLib dispatches its `changed` signal in the creation thread’s main context, so the reconnected callback emits signals for the new `DWatcher` from the wrong thread.

Store the monitor’s creation context and only revive it when it matches the new watcher’s context; otherwise create a new monitor.

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

### Comment 5
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="64" />
<code_context>
+        if (remaining > 0) {
+            refCounts[key] = remaining;
+            g_signal_handlers_disconnect_by_data(monitor, userData);
+            parked[key].append(ParkedMonitor { monitor, type, path });
+            return true;
+        }
</code_context>
<issue_to_address>
**Parked monitors accumulate for aliases**

When a long-lived watcher shares an inode with repeated watches through distinct paths that are then stopped, `retainOrPark()` keeps each stopped alias monitor in `parked`, while `reviveParked()` only reuses an exact path match; entries for aliases that are not revisited remain retained and consume resources.

Remove or otherwise reclaim parked monitors that cannot be reused while another watcher for the inode remains active.

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

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

parked[key].append(ParkedMonitor { monitor, type, path });
return true;
}
refCounts.remove(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 watchers lose filesystem events

When a new watcher starts for an inode while its last watcher is stopping, retainOrPark() removes the final registry entry before stop() cancels its monitors, while start() creates the replacement monitor before addActive() registers it; the cancellation removes GLib's shared watch and the new watcher misses events.

Synchronize monitor creation and registration with final-stop cancellation so a new watcher cannot share a watch that is scheduled for cancellation.

Also at src/dfm-io/dfm-io/dwatcher.cpp:324-339, src/dfm-io/dfm-io/dwatcher.cpp:354-360.

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

**New watchers lose filesystem events**

When a new watcher starts for an inode while its last watcher is stopping, `retainOrPark()` removes the final registry entry before `stop()` cancels its monitors, while `start()` creates the replacement monitor before `addActive()` registers it; the cancellation removes GLib's shared watch and the new watcher misses events.

Synchronize monitor creation and registration with final-stop cancellation so a new watcher cannot share a watch that is scheduled for cancellation.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:324-339`, `src/dfm-io/dfm-io/dwatcher.cpp:354-360`.

url.append("/");

d->gfile = DLocalHelper::createGFile(url);
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.

🟡 Medium · Replacement watchers use the wrong inode key

When the watched path or symlink target changes between inodeKeyOf() and createMonitor(), inodeKeyOf() records the old target while createMonitor() attaches to the replacement, so the registry counts and stops the monitor under the wrong inode; cancellation can silence watchers of the replacement.

Key the registry using the inode actually watched by the created monitor, or verify the path identity has not changed before registering it.

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

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

**Replacement watchers use the wrong inode key**

When the watched path or symlink target changes between `inodeKeyOf()` and `createMonitor()`, `inodeKeyOf()` records the old target while `createMonitor()` attaches to the replacement, so the registry counts and stops the monitor under the wrong inode; cancellation can silence watchers of the replacement.

Key the registry using the inode actually watched by the created monitor, or verify the path identity has not changed before registering it.

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

g_object_unref(d->gmonitor);
d->gmonitor = nullptr;
QList<GFileMonitor *> doomed;
if (MonitorKeepAliveRegistry::instance().retainOrPark(d->inodeKey, d->gmonitor, d->type,

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 · Revived monitors use the wrong watch type

When a watcher changes its watch type after starting and its parked monitor is later revived, stop() passes the current d->type to retainOrPark() instead of the type used to create d->gmonitor; reviveParked() can then match and return a monitor with different monitoring semantics, so the restarted watcher gets the wrong events.

Store the monitor's creation-time watch type and use that type when parking and matching it for revival.

Also at src/dfm-io/dfm-io/dwatcher.cpp:64, src/dfm-io/dfm-io/dwatcher.cpp:91, src/dfm-io/dfm-io/dwatcher.cpp:349.

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

**Revived monitors use the wrong watch type**

When a watcher changes its watch type after starting and its parked monitor is later revived, `stop()` passes the current `d->type` to `retainOrPark()` instead of the type used to create `d->gmonitor`; `reviveParked()` can then match and return a monitor with different monitoring semantics, so the restarted watcher gets the wrong events.

Store the monitor's creation-time watch type and use that type when parking and matching it for revival.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:64`, `src/dfm-io/dfm-io/dwatcher.cpp:91`, `src/dfm-io/dfm-io/dwatcher.cpp:349`.

Comment on lines +91 to +93
if (item.type == type && item.path == path) {
GFileMonitor *monitor = list.takeAt(i).monitor;
if (list.isEmpty())

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 · Reused monitor emits on old thread

When a monitor is parked in one thread’s main context and a watcher for the same path and type revives it after moving to or starting in another thread, reviveParked() can return a monitor created in another thread; GLib dispatches its changed signal in the creation thread’s main context, so the reconnected callback emits signals for the new DWatcher from the wrong thread.

Store the monitor’s creation context and only revive it when it matches the new watcher’s context; otherwise create a new monitor.

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

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

**Reused monitor emits on old thread**

When a monitor is parked in one thread’s main context and a watcher for the same path and type revives it after moving to or starting in another thread, `reviveParked()` can return a monitor created in another thread; GLib dispatches its `changed` signal in the creation thread’s main context, so the reconnected callback emits signals for the new `DWatcher` from the wrong thread.

Store the monitor’s creation context and only revive it when it matches the new watcher’s context; otherwise create a new monitor.

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

if (remaining > 0) {
refCounts[key] = remaining;
g_signal_handlers_disconnect_by_data(monitor, userData);
parked[key].append(ParkedMonitor { monitor, type, path });

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 · Parked monitors accumulate for aliases

When a long-lived watcher shares an inode with repeated watches through distinct paths that are then stopped, retainOrPark() keeps each stopped alias monitor in parked, while reviveParked() only reuses an exact path match; entries for aliases that are not revisited remain retained and consume resources.

Remove or otherwise reclaim parked monitors that cannot be reused while another watcher for the inode remains active.

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

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

**Parked monitors accumulate for aliases**

When a long-lived watcher shares an inode with repeated watches through distinct paths that are then stopped, `retainOrPark()` keeps each stopped alias monitor in `parked`, while `reviveParked()` only reuses an exact path match; entries for aliases that are not revisited remain retained and consume resources.

Remove or otherwise reclaim parked monitors that cannot be reused while another watcher for the inode remains active.

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

@liyigang1 liyigang1 closed this Nov 24, 2026
@liyigang1 liyigang1 reopened this Nov 24, 2026
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

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

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

@liyigang1

Copy link
Copy Markdown
Contributor Author

/forcemerge

@deepin-bot

deepin-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown

This pr force merged! (status: unstable)

@deepin-bot
deepin-bot Bot merged commit fad5775 into linuxdeepin:develop/meagle-20260526 Nov 24, 2026
30 of 35 checks passed
@liyigang1
liyigang1 deleted the fix/dwatcher-same-inode-keepalive-meagle-20260526 branch November 24, 2026 11:11
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.

3 participants