Skip to content

Server shutdown can leak live session resources #1273

Description

@morluto

Problem

When the server shuts down while sessions are still live, the shutdown path disposes the server/service graph without first closing the live KimiCore sessions.

This means Session.close() is not invoked unless each session was explicitly closed before shutdown.

Why this is a resource leak

Session.close() owns session-scoped cleanup, including active turn cancellation, background task shutdown, metadata flushing, session-end hooks, MCP shutdown, and log handle closure.

If server shutdown skips Session.close() for live sessions, those resources do not get their normal cleanup path.

Code-path proof

  1. KimiCore tracks live sessions in this.sessions.
  2. KimiCore.closeSession() closes a single session with session.close(), then removes it from the session map.
  3. The server shutdown path closes WebSocket connections and Fastify, then disposes the DI graph.
  4. CoreProcessService.dispose() marks the service disposed so future RPC calls reject, but it does not close live sessions.
  5. Therefore, any session still present in KimiCore.sessions at server shutdown skips Session.close().

Expected behavior

Server shutdown should close all live sessions before disposing the service graph.

Shutdown should attempt to close every session even if one session close fails, then continue best-effort cleanup after reporting the failure.

Proposed fix

Add a core lifecycle method to close all live sessions and call it during server shutdown before DI disposal.

The fix should include a focused regression test proving:

  • all live sessions are closed and removed;
  • later sessions are still closed if an earlier session close fails.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions