Skip to content

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

Closed
liyigang1 wants to merge 1 commit into
linuxdeepin:develop/meagle-20260526from
liyigang1:fix/dwatcher-same-inode-keepalive-meagle-20260526
Closed

liyigang1 wants to merge 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

Prevent shared-inode file watchers from becoming inactive when an aliased watcher stops while preserving correct event paths and cleanup behavior.

Bug Fixes:

  • Keep file watchers on aliased paths receiving events when another watcher for the same inode stops.
  • Restore fresh watchers correctly after all monitors for an inode have stopped.
  • Preserve each watcher’s own path in events when parked monitors are reused.

Enhancements:

  • Manage shared local monitors by complete device/inode identity, retaining them while other same-inode watchers remain active and safely cleaning them up after the last watcher stops.
  • Restrict parked-monitor reuse to matching watch types and creation paths, while retaining direct cancellation for non-local paths.

Tests:

  • Add coverage for stopping one of two same-inode watchers, path-safe monitor revival, recovery after all watchers stop, 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 group monitors that refer to the same filesystem object.

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

Implementation

Implement inode-based monitor retention and path/type-matched revival, and integrate the registry lifecycle with watcher start and stop.

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

Tests

Add regression coverage for aliased-path stop behavior, path-correct monitor revival, full-stop recovery, and same-inode view round trips.

  • 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="324" />
<code_context>
+        return true;
+    }

     d->gmonitor = d->createMonitor(d->gfile, d->type);

     if (!d->gmonitor) {
</code_context>
<issue_to_address>
**New watchers lose filesystem events**

When a start overlaps the final stop for the same inode, `start()` creates the GLib monitor before registering it, while `stop()` removes the last count and cancels monitors outside the lock. That cancellation removes the shared watch after the new monitor is created, leaving the new watcher deaf and dropping events.

Synchronize monitor creation and registration with final-stop cancellation so a stop cannot cancel a watch belonging to a concurrent start.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:67`, `src/dfm-io/dfm-io/dwatcher.cpp:339`, `src/dfm-io/dfm-io/dwatcher.cpp:348-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**

When the watched path is replaced between `inodeKeyOf()` and `createMonitor()`, `inodeKeyOf()` records the old inode while `createMonitor()` opens the replacement, so the registry accounts for the monitor under the wrong inode and stopping either group can cancel the replacement’s shared watch, leaving a watcher deaf.

Ensure the registry key identifies the same inode that `createMonitor()` opens, for example by checking the identity after monitor creation and retrying if it changed.

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="349" />
<code_context>
-        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>
**Restarted watchers use the wrong mode**

When the watch type changes while running and the monitor is parked while another watcher keeps the inode active, `stop()` passes the current `d->type` to `retainOrPark()` rather than the type used to create the monitor, so `reviveParked()` can reuse that monitor for a different watch mode and deliver incorrect events.

Record each monitor’s creation type and use that type when parking and matching it for reuse.

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

### Comment 4
<location path="src/dfm-io/dfm-io/dwatcher.cpp" line_range="38" />
<code_context>
+public:
+    static MonitorKeepAliveRegistry &instance()
+    {
+        static MonitorKeepAliveRegistry registry;
+        return registry;
+    }
</code_context>
<issue_to_address>
**Shutdown accesses a destroyed registry**

When a static-lifetime watcher remains running until shutdown and is started after construction, `instance()` initializes the registry after the watcher is constructed, so the registry is destroyed first; the watcher’s destructor then calls `stop()` through the destroyed registry and its mutex, causing undefined behavior during teardown.

Give the registry process lifetime or ensure it is initialized before any static-lifetime watcher can be constructed.
</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 grow without bound**

When a long-lived watcher remains active while transient watchers are started and stopped through many distinct paths to the same inode, each distinct path adds another retained `GFileMonitor`, and `reviveParked` cannot reuse monitors whose paths differ. The retained list is only cleared when the last active watcher stops, so repeated transient watches through new aliases accumulate monitor objects and GLib subscription state for as long as any watcher remains active.

Bound retained state per inode while preserving the shared GLib watch and the path-specific event URLs needed by active or restartable watchers.

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

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

return true;
}

d->gmonitor = d->createMonitor(d->gfile, 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 · New watchers lose filesystem events

When a start overlaps the final stop for the same inode, start() creates the GLib monitor before registering it, while stop() removes the last count and cancels monitors outside the lock. That cancellation removes the shared watch after the new monitor is created, leaving the new watcher deaf and dropping events.

Synchronize monitor creation and registration with final-stop cancellation so a stop cannot cancel a watch belonging to a concurrent start.

Also at src/dfm-io/dfm-io/dwatcher.cpp:67, src/dfm-io/dfm-io/dwatcher.cpp:339, src/dfm-io/dfm-io/dwatcher.cpp:348-360.

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

**New watchers lose filesystem events**

When a start overlaps the final stop for the same inode, `start()` creates the GLib monitor before registering it, while `stop()` removes the last count and cancels monitors outside the lock. That cancellation removes the shared watch after the new monitor is created, leaving the new watcher deaf and dropping events.

Synchronize monitor creation and registration with final-stop cancellation so a stop cannot cancel a watch belonging to a concurrent start.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:67`, `src/dfm-io/dfm-io/dwatcher.cpp:339`, `src/dfm-io/dfm-io/dwatcher.cpp:348-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

When the watched path is replaced between inodeKeyOf() and createMonitor(), inodeKeyOf() records the old inode while createMonitor() opens the replacement, so the registry accounts for the monitor under the wrong inode and stopping either group can cancel the replacement’s shared watch, leaving a watcher deaf.

Ensure the registry key identifies the same inode that createMonitor() opens, for example by checking the identity after monitor creation and retrying if it changed.

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**

When the watched path is replaced between `inodeKeyOf()` and `createMonitor()`, `inodeKeyOf()` records the old inode while `createMonitor()` opens the replacement, so the registry accounts for the monitor under the wrong inode and stopping either group can cancel the replacement’s shared watch, leaving a watcher deaf.

Ensure the registry key identifies the same inode that `createMonitor()` opens, for example by checking the identity after monitor creation and retrying if it changed.

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

d->gmonitor = nullptr;
QList<GFileMonitor *> doomed;
if (MonitorKeepAliveRegistry::instance().retainOrPark(d->inodeKey, d->gmonitor, d->type,
localPathOf(d->gfile), this, &doomed)) {

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 · Restarted watchers use the wrong mode

When the watch type changes while running and the monitor is parked while another watcher keeps the inode active, stop() passes the current d->type to retainOrPark() rather than the type used to create the monitor, so reviveParked() can reuse that monitor for a different watch mode and deliver incorrect events.

Record each monitor’s creation type and use that type when parking and matching it for reuse.

Also at src/dfm-io/dfm-io/dwatcher.cpp:64-65, src/dfm-io/dfm-io/dwatcher.cpp:317.

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

**Restarted watchers use the wrong mode**

When the watch type changes while running and the monitor is parked while another watcher keeps the inode active, `stop()` passes the current `d->type` to `retainOrPark()` rather than the type used to create the monitor, so `reviveParked()` can reuse that monitor for a different watch mode and deliver incorrect events.

Record each monitor’s creation type and use that type when parking and matching it for reuse.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:64-65`, `src/dfm-io/dfm-io/dwatcher.cpp:317`.

public:
static MonitorKeepAliveRegistry &instance()
{
static MonitorKeepAliveRegistry registry;

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 · Shutdown accesses a destroyed registry

When a static-lifetime watcher remains running until shutdown and is started after construction, instance() initializes the registry after the watcher is constructed, so the registry is destroyed first; the watcher’s destructor then calls stop() through the destroyed registry and its mutex, causing undefined behavior during teardown.

Give the registry process lifetime or ensure it is initialized before any static-lifetime watcher can be constructed.

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

**Shutdown accesses a destroyed registry**

When a static-lifetime watcher remains running until shutdown and is started after construction, `instance()` initializes the registry after the watcher is constructed, so the registry is destroyed first; the watcher’s destructor then calls `stop()` through the destroyed registry and its mutex, causing undefined behavior during teardown.

Give the registry process lifetime or ensure it is initialized before any static-lifetime watcher can be constructed.

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 grow without bound

When a long-lived watcher remains active while transient watchers are started and stopped through many distinct paths to the same inode, each distinct path adds another retained GFileMonitor, and reviveParked cannot reuse monitors whose paths differ. The retained list is only cleared when the last active watcher stops, so repeated transient watches through new aliases accumulate monitor objects and GLib subscription state for as long as any watcher remains active.

Bound retained state per inode while preserving the shared GLib watch and the path-specific event URLs needed by active or restartable watchers.

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

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

**Parked monitors grow without bound**

When a long-lived watcher remains active while transient watchers are started and stopped through many distinct paths to the same inode, each distinct path adds another retained `GFileMonitor`, and `reviveParked` cannot reuse monitors whose paths differ. The retained list is only cleared when the last active watcher stops, so repeated transient watches through new aliases accumulate monitor objects and GLib subscription state for as long as any watcher remains active.

Bound retained state per inode while preserving the shared GLib watch and the path-specific event URLs needed by active or restartable watchers.

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

@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 liyigang1 closed this Nov 24, 2026
@liyigang1
liyigang1 deleted the fix/dwatcher-same-inode-keepalive-meagle-20260526 branch November 24, 2026 09:09
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