Skip to content

fix(session): retry desktop startup after conflicting jobs finish - #246

Open
zorowk wants to merge 1 commit into
linuxdeepin:masterfrom
zorowk:fix_loginnodesktop
Open

zorowk wants to merge 1 commit into
linuxdeepin:masterfrom
zorowk:fix_loginnodesktop

Conversation

@zorowk

@zorowk zorowk commented Nov 16, 2026 •

Copy link
Copy Markdown

Desktop startup can conflict with pending shutdown jobs from the previous session.

  • Subscribe to systemd JobRemoved signals and retry desktop startup when pending jobs cause a destructive transaction conflict.
  • Refresh the activation environment before each attempt and wait without a timeout. Exit the login session on other startup errors.

Allow desktop startup to proceed after conflicting shutdown jobs finish.

Log: retry desktop startup after conflicting jobs finish
PMS: TASK-398167
Influence: desktop login and session startup during logout cleanup

Summary by Sourcery

Allow desktop startup to recover from conflicts with jobs left by the previous session.

Bug Fixes:

  • Retry desktop startup when pending shutdown or cleanup jobs cause a destructive systemd transaction conflict, after those jobs settle.

Enhancements:

  • Refresh the activation environment before each startup attempt and exit the login session if startup fails for another error.

Chores:

  • Add a session leader component to manage desktop startup, session-exit monitoring, and leader FIFO handling.

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: 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

@sourcery-ai

sourcery-ai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Expose the SessionLeader startup lifecycle and allow EnvironmentsManager to publish activation variables over a specified D-Bus connection.

  • src/dde-session/environmentsmanager.h L1-25 (4 small edits)
  • src/dde-session/sessionleader.h L1-82

Uses of the API

Replace inline startup and exit handling with SessionLeader, and exit the login session if desktop startup fails.

  • src/dde-session/main.cpp L49-54 (+7 small edits)

Implementation

Wait for previous-session units to settle, retry destructive startup conflicts or bus disconnects, refresh the activation environment before starting the target, and manage exit watching and the leader FIFO.

  • src/dde-session/sessionleader.cpp L1-415

Pass the selected D-Bus connection through environment initialization and environment-unset calls.

  • src/dde-session/environmentsmanager.cpp L149-152 (+5 small edits)

Configuration

Add the SessionLeader implementation and header to the dde-session executable build.

  • src/dde-session/CMakeLists.txt L60-61

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

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

## Individual Comments

### Comment 1
<location path="src/dde-session/main.cpp" line_range="95" />
<code_context>
+    QTimer timeout;
+    timeout.setSingleShot(true);
+    QObject::connect(&timeout, &QTimer::timeout, &waitLoop, &QEventLoop::quit);
+    timeout.start(60000);
+
+    while (timeout.isActive()) {
</code_context>
<issue_to_address>
**Recoverable logins are aborted**

When conflicting shutdown jobs remain active for more than 60 seconds, the timer ends the retry loop, so `startDesktopSession` returns false and `main` exits with `EXIT_FAILURE`, even if the jobs finish shortly afterward.

Do not treat the 60-second timeout as a reason to return false; keep waiting for conflicting shutdown jobs to finish.
</issue_to_address>

### Comment 2
<location path="src/dde-session/main.cpp" line_range="100-101" />
<code_context>
+    while (timeout.isActive()) {
+        jobFinished = false;
+        // Old shutdown tasks may unset the new login's activation environment.
+        EnvironmentsManager().init();
+        const auto error = startSystemdUnit(systemd1, QStringLiteral("dde-session.target"),
+                                           QStringLiteral("replace"));
+        if (!error.isValid())
</code_context>
<issue_to_address>
**Cleanup can erase refreshed environment**

When the previous session's `ExecStopPost` unsets activation variables after the refresh but before the new target is accepted, the shutdown cleanup can unset activation variables after `EnvironmentsManager().init()` but before `StartUnit` succeeds; because no destructive-transaction error occurs, there is no retry to restore them, and desktop services start with missing environment values.

Coordinate the environment refresh with the old session's cleanup so cleanup cannot unset activation variables after the final refresh and before desktop services start.
</issue_to_address>

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

Comment thread src/dde-session/main.cpp Resolved
Comment thread src/dde-session/main.cpp Resolved
@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

🤖 AI 代码审查报告

总体评分: 95 分 (通过阈值: 70分)

Pass


📊 总体评价

项目 结果
审查结论 代码审查通过
评分详情 本次提交修复了桌面启动时因 systemd 冲突作业导致启动失败的问题,通过新增 startDesktopSession 函数实现冲突作业完成后的重试机制。 代码逻辑正确,使用了 QEventLoop 和 qScopeGuard 等现代 Qt 实践,错误处理从 int 返回值改为 QDBusError 更为精确。 四维度均通过,无安全漏洞。存在少量代码质量和性能优化空间:dmService 变量与硬编码单元名不一致、JobRemoved 信号未过滤作业参数可能引发不必要的重试、超时时间魔法数字未命名。

🔍 详细分析

1. 语法逻辑 ✅

评价: 语法正确,逻辑清晰 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['无改进建议']


2. 代码质量 ✅

评价: 代码结构清晰,注释完整 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['将 dde-session.target 作为参数传递给 startDesktopSession,或移除 main() 中多余的 dmService 变量', 'JobRemoved 信号处理器应接收并记录 id、unit、job、result 参数,便于调试和问题定位', '为 60 秒超时添加注释说明其作为安全防护的设计理由', '统一 startSystemdUnit 和 startDesktopSession 的 static 声明']


3. 代码性能 ✅

评价: 性能良好,资源使用合理 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['JobRemoved 处理器应过滤相关作业(如匹配 unit 名称),或至少在重试前添加短暂延迟避免忙循环', '将超时时间提取为命名常量,如 static constexpr int kConflictingJobTimeoutMs = 60000']


4. 代码安全 🔒

评价: 存在0个安全漏洞 ✅ 通过

🔐 发现 0 个安全漏洞

安全漏洞详情:
✅ 未发现安全漏洞

建议: ['无安全改进建议']


💡 改进建议代码示例

// 改进建议:JobRemoved 信号处理器记录参数 + 超时命名常量 + dmService 作为参数传递

static constexpr int kConflictingJobTimeoutMs = 60000;

static bool startDesktopSession(org::freedesktop::systemd1::Manager &systemd1,
                                 const QString &targetUnit = QStringLiteral("dde-session.target"))
{
    QEventLoop waitLoop;
    bool jobFinished = false;
    QObject::connect(&systemd1, &org::freedesktop::systemd1::Manager::JobRemoved,
                     &waitLoop, [&](uint id, const QDBusObjectPath &job,
                                    const QString &unit, const QString &result) {
        qInfo() << "JobRemoved, id:" << id << "unit:" << unit
                << "job:" << job.path() << "result:" << result;
        jobFinished = true;
        waitLoop.quit();
    });

    QDBusPendingReply<> subscribed = systemd1.Subscribe();
    subscribed.waitForFinished();
    if (subscribed.isError()) {
        qWarning() << "failed to subscribe to systemd jobs:" << subscribed.error();
        return false;
    }
    const auto unsubscribe = qScopeGuard([&systemd1] { systemd1.Unsubscribe(); });

    // 60s safety timeout to avoid hanging forever if conflicting jobs never complete
    QTimer timeout;
    timeout.setSingleShot(true);
    QObject::connect(&timeout, &QTimer::timeout, &waitLoop, &QEventLoop::quit);
    timeout.start(kConflictingJobTimeoutMs);

    while (timeout.isActive()) {
        jobFinished = false;
        // Old shutdown tasks may unset the new login's activation environment.
        EnvironmentsManager().init();
        const auto error = startSystemdUnit(systemd1, targetUnit,
                                           QStringLiteral("replace"));
        if (!error.isValid())
            return true;
        if (error.name() != QStringLiteral("org.freedesktop.systemd1.TransactionIsDestructive"))
            return false;

        if (!jobFinished && timeout.isActive())
            waitLoop.exec();
    }

    qWarning() << "desktop startup timed out waiting for conflicting jobs";
    return false;
}

// main() 中调用:
// if (!startDesktopSession(systemdDBus, dmService)) { ... }

本报告由 AI 代码审查工具自动生成

Comment thread src/dde-session/main.cpp Resolved
Comment thread src/dde-session/main.cpp Resolved
@zorowk
zorowk force-pushed the fix_loginnodesktop branch from 67384b5 to 8e86c1a Compare December 2, 2026 08:39
注销后立即重新登录时,旧会话的关闭清理任务可能尚未结束,导致新会话写入激活环境变
量后被旧 ExecStopPost 清除,或因冲突任务和 dbus.service 退出而启动失败。

- 抽离 SessionLeader 类统一管理会话启动、旧会话清理等待、退出监听与 FIFO 保活
- 启动阶段在同一条已订阅的独立命名 D-Bus 连接上完成旧会话清理等待、激活环境变量
  发布与 dde-session.target 启动,避免重连窗口信号丢失与污染全局 sessionBus
- 监听 Disconnected 并在旧连接释放后执行退避重连,在 dbus.service 退出时自动恢复
  重试
- 保留 TransactionIsDestructive 冲突重试并在超时或其他启动错误时退出登录会话,同
  时使用共享指针保护 Leader FIFO 线程生命周期

消除旧会话注销清理与新会话启动之间的竞态,避免重登后无桌面或丢失环境变量。

仅调整 dde-session Leader 启动退出管理及 EnvironmentsManager 传入指定总线连接,
不改动 systemd 单元清理配置。

Log: 等待旧会话清理完成后再初始化环境并启动桌面会话
PMS: TASK-398167
Influence: 注销后快速重新登录及桌面会话启动流程
@zorowk
zorowk force-pushed the fix_loginnodesktop branch from 8e86c1a to e699339 Compare December 2, 2026 08:41
@zorowk
zorowk requested a review from mhduiy December 2, 2026 08:44
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