Skip to content

Fix/session sockets - #1717

Merged
wineee merged 2 commits into
linuxdeepin:masterfrom
zorowk:fix/session-sockets
Nov 25, 2026
Merged

wineee merged 2 commits into
linuxdeepin:masterfrom
zorowk:fix/session-sockets

Conversation

@zorowk

@zorowk zorowk commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

#1654

Summary by Sourcery

Stabilize per-user Wayland socket activation and cleanup across session changes, owner handoffs, and logout.

Bug Fixes:

  • Fix Wayland user socket lifecycle handling across repeated registration, owner handover, session shutdown, and logout.
  • Ensure socket activation retries after D-Bus or activation-environment failures.

Enhancements:

  • Tie user Wayland socket enablement to its owning Session instead of the current display user.
  • Improve activation validation, ownership tracking, cleanup safety, and diagnostic logging.
  • Handle session replacement and relogin without exposing stale protocol state.

Documentation:

  • Document user socket lifecycle coverage and session relogin regression scenarios.

Tests:

  • Add protocol coverage for socket registration handover, owner disconnection, session enablement, descendant cleanup, and logout behavior.
  • Add repeated session logout/relogin isolation checks.

Register each user’s Wayland listener at startup and compositor recovery.

- Reuse repeated registrations of the same listener and track its D-Bus owner so disconnects release
  only the matching user socket.

Duplicate received descriptors for WSocket ownership and synchronize child socket enablement with
the owning Session.

Log: preserve user Wayland sockets across desktop switches
PMS: TASK-398167
Influence: user switching, Wayland activation and session teardown
Relogin with a new session ID replaces a desktop and its protocol globals. User socket registration
and logout also need a test that runs independently of output scaling.

- Repeat same-account relogin with new session IDs and check that retiring the old session preserves
  activation of the replacement and each session exposes its own globals.
- Exercise repeated listener registration, owner handover and listener replacement through D-Bus
  with live Wayland clients.
- Verify logout closes registered and descendant socket clients while leaving an unrelated session
  connected.

Keep registry isolation and socket teardown observable across session transitions.

Session registry and user socket integration tests.

Log: cover relogin isolation and user socket lifecycle
PMS: TASK-398167
Influence: same-user relogin, Wayland registry isolation and socket teardown
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Add a Session signal announcing that its clients have closed, so user-socket cleanup can follow Session teardown.

  • src/session/session.cpp L148
  • src/session/session.h L107

API

Expose private Treeland cleanup for releasing a user’s Wayland socket only when it is still the expected socket.

  • src/core/treeland.h L56

Implementation

Register and reuse user Wayland sockets with D-Bus owner tracking, Session-synchronized enablement, and guarded cleanup on owner loss or client shutdown.

  • src/core/treeland.cpp L582-650, L655-665, L670-689 (+2 small edits)

Make systemd socket activation retry failed Wayland registration and environment updates, and reset activation state across compositor recovery and Session changes.

  • src/systemd-socket.cpp L90-97 (+7 small edits)

Log a warning when activating a user’s desktop session fails.

  • src/greeter/greeterproxy.cpp L666-669

Stop changing registered socket enablement when the displayed current user changes; it now follows the owning Session.

  • src/greeter/usermodel.cpp L348 (removed lines)

Documentation

Document the new relogin isolation and standalone user-socket lifecycle coverage in the protocol test index and guide.

  • tests/protocols/INDEX.md L26-28
  • tests/protocols/session-isolation/README.md L86-107

Tests

Exercise same-account relogin with new Session IDs and verify old Session cleanup does not disturb the replacement’s activation or registry isolation.

  • tests/protocols/session-isolation/session-isolation.c L760-783, L962-963
  • tests/protocols/session-isolation/session-isolation.h L50
  • tests/protocols/session-isolation/setup.cpp L283-315

Add an independent D-Bus and Wayland integration test for socket registration, owner handover, Session enablement, replacement, and logout cleanup.

  • tests/protocols/framework/test-accounts-service.cpp L35-39, L88-97 (+5 small edits)
  • tests/protocols/session-isolation/socket-lifecycle-setup.cpp L1-201
  • tests/protocols/session-isolation/socket-lifecycle.c L1-71
  • tests/protocols/session-isolation/socket-lifecycle.h L1-38

Other changes

Files not grouped.

  • tests/protocols/session-isolation/CMakeLists.txt L20-27

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

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

## Individual Comments

### Comment 1
<location path="src/core/treeland.cpp" line_range="600" />
<code_context>
+    }
+    qCDebug(lcTlDBus) << "Releasing Wayland socket for user" << user
+                      << "with" << socket->clients().size() << "clients";
+    account->setWaylandSocket(nullptr);
+}

</code_context>
<issue_to_address>
**Socket is destroyed inside its callback**

When the current owner disconnects or its Session shuts down, `clientsClosed` and `serviceUnregistered` invoke `releaseUserWaylandSocket` through the socket as the connection context. Clearing the account’s last shared reference destroys that socket before the callback returns, so Qt continues signal delivery with a deleted receiver and logout or owner disconnect can crash the compositor.

Defer releasing the final socket reference until after the active signal callback returns.
</issue_to_address>

### Comment 2
<location path="src/core/treeland.cpp" line_range="600" />
<code_context>
+    }
+    qCDebug(lcTlDBus) << "Releasing Wayland socket for user" << user
+                      << "with" << socket->clients().size() << "clients";
+    account->setWaylandSocket(nullptr);
+}

</code_context>
<issue_to_address>
**Descendant listeners outlive logout**

When a descendant listener exists without connected clients when the user socket is released, `releaseUserWaylandSocket` clears the account’s shared pointer without explicitly retiring descendant listeners. A descendant with no connected clients is not collected by `Session::closeClients`, so its listener remains registered after the owning user socket is released and can accept connections after logout.

Track and close/remove descendant listeners as part of releasing the user socket, including descendants with no connected clients.
</issue_to_address>

### Comment 3
<location path="src/core/treeland.cpp" line_range="617" />
<code_context>
+        qCWarning(lcTlDBus) << "Cannot resolve Wayland socket owner" << owner << uid.error();
+        return false;
+    }
+    const auto session = d->server->sessionManager()->sessionForUid(uid.value());
     WSocket *sessionSocket = session ? session->socket() : nullptr;
-    if (!sessionSocket)
</code_context>
<issue_to_address>
**Wrong session owns user listener**

When the account has multiple live sessions with the same UID, `sessionForUid()` returns the first matching session without checking which same-UID session is active. `ActivateWayland()` therefore parents the user listener to that session, so another concurrent or not-yet-removed login for the same account gets the wrong enablement and shutdown lifecycle.

Select the session corresponding to the activation request or explicitly define and enforce a single-session-per-UID policy before associating the listener.
</issue_to_address>

### Comment 4
<location path="tests/protocols/session-isolation/socket-lifecycle-setup.cpp" line_range="50" />
<code_context>
+    if (!socket.create(path))
+        return false;
+    qstrncpy(endpoint.name, path.toUtf8().constData(), sizeof(endpoint.name));
+    endpoint.fd = socket.socketFd();
+    return true;
+}
</code_context>
<issue_to_address>
**Socket lifecycle test cannot register**

When the fixture and C client run in separate processes, as in the protocol-test framework, the fixture writes the compositor process’s descriptor number into shared test state, and the C client passes that number to `QDBusUnixFileDescriptor` without receiving the descriptor itself. The D-Bus call therefore sends an invalid or unrelated client-process descriptor, so registration fails and the lifecycle test cannot exercise its claimed scenarios.

Transfer the listening descriptor to the C client with descriptor-passing support, or perform the D-Bus registration from the fixture process.

Also at `tests/protocols/session-isolation/socket-lifecycle-setup.cpp:117`.
</issue_to_address>

### Comment 5
<location path="src/systemd-socket.cpp" line_range="97" />
<code_context>
+                        ? QStringLiteral("compositor rejected request")
+                        : activated.error().message();
+                    qCWarning(lcSdSocket) << "Failed to activate Wayland socket:" << reason;
+                    scheduleActivateRetry();
                     return;
                 }
</code_context>
<issue_to_address>
**Persistent failures trigger rapid retries**

When the compositor or activation-environment D-Bus service remains unavailable, `scheduleActivateRetry()` schedules another activation after every failed D-Bus call; the timer clears the pending flag before calling `activate()` again, so a persistently unavailable compositor or activation-environment service causes repeated calls and warning logs until the dependency recovers.

Use a bounded or increasing retry delay and rate-limit repeated failure logs while continuing to retry for recovery.
</issue_to_address>

### Comment 6
<location path="tests/protocols/session-isolation/setup.cpp" line_range="302" />
<code_context>
+    sessionB = manager->sessionForId(id);
+    const bool previousInactive = !previous->isActive();
+    // Late cleanup of the old object must not remove or deactivate the new one.
+    manager->removeSession(previous);
+    previous.reset();
+    if (!sessionB || !previousInactive || !retired.expired()
</code_context>
<issue_to_address>
**Late cleanup is never exercised**

When each relogin iteration replaces the existing session for the same username, when `updateActiveUserSession(username, id)` replaces the existing session, `session_test_logout_relogin` calls `manager->removeSession(previous)` at `setup.cpp:302` only after `ensureSession` has already removed and shut down that session. The second call returns at the `isShuttingDown()` guard, so the active-session assertions pass without exercising delayed cleanup against the replacement.

Arrange for the old session’s cleanup to be genuinely deferred until after the replacement is created, then invoke and assert that cleanup.
</issue_to_address>

### Comment 7
<location path="src/core/treeland.cpp" line_range="686" />
<code_context>
             });
+    // Client cleanup needs the socket ancestry to identify security-context descendants.
+    connect(session.get(), &Session::clientsClosed, socket.get(),
+            [this, user, expected = socket.get()] { releaseUserWaylandSocket(user, expected); });

+    qCDebug(lcTlDBus) << "Registered Wayland socket for user" << user
</code_context>
<issue_to_address>
**Session cleanup uses forwarding lambda**

When `Session::clientsClosed` is connected, the `clientsClosed` lambda only forwards to `releaseUserWaylandSocket(user, expected)`, contrary to the member-function-pointer guidance; the signal connection remains a forwarding lambda.

Use a member-function-pointer slot for this connection, keeping the required user and socket context in the receiving object.
</issue_to_address>

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

Comment thread src/core/treeland.cpp Resolved
Comment thread src/core/treeland.cpp Resolved
Comment thread src/core/treeland.cpp Resolved
Comment thread src/systemd-socket.cpp Resolved
Comment thread src/core/treeland.cpp Resolved
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: Groveer, zorowk

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

@wineee
wineee merged commit 6757e47 into linuxdeepin:master Nov 25, 2026
11 of 15 checks passed
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.

4 participants