Skip to content

Prevent AuthKeyDuplicatedError from concurrent server instances - #172

Merged
chigwell merged 1 commit into
chigwell:mainfrom
marksmeed:feature/session-lock
Aug 19, 2026
Merged

Prevent AuthKeyDuplicatedError from concurrent server instances#172
chigwell merged 1 commit into
chigwell:mainfrom
marksmeed:feature/session-lock

Conversation

@marksmeed

Copy link
Copy Markdown
Contributor

Summary

  • MCP clients (Claude Desktop in particular) can spawn a second telegram-mcp process before the first one exits, e.g. when restarting a connector. Two processes connecting the same Telegram session at once trips AuthKeyDuplicatedError, which can knock out both connections rather than just the newcomer.
  • Adds a per-session, cross-platform (flock/msvcrt) advisory lock (telegram_mcp/singleton.py) acquired before connect(). A second instance racing for the same session waits briefly (default 20s, TELEGRAM_LOCK_GRACE_SECONDS) for the first to release it — covering the connector-restart case — and otherwise exits without ever calling connect(), so the live session is never disturbed.
  • This sits in front of the existing retry-with-backoff AuthKeyDuplicatedError handling in _connect_authorized_client, which is preserved as-is for genuinely transient blips (e.g. a VPN IP change) that aren't caused by a second local instance.

Test plan

  • uv run pytest tests/test_runner.py -v — 11 passed, including new tests for lock contention/release and independent sessions not blocking each other
  • uv run pytest — no new failures introduced (pre-existing failures on this Windows checkout are environment-/platform-specific and unrelated: multi-account fixtures assuming a single account, and tests/test_session_pool.py importing POSIX-only fcntl)

MCP clients (Claude Desktop in particular) can spawn a second telegram-mcp
process before the first one exits, e.g. when restarting a connector. Two
processes connecting the same Telegram session at once trips Telegram's
AuthKeyDuplicatedError, which can kick out both connections.

Add a per-session OS-level advisory lock (flock/msvcrt) that a process
acquires before connecting. A second instance racing for the same session
waits briefly for the first to release it (covers connector restarts) and
otherwise exits without ever calling connect(), so the live session is
never disturbed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@marksmeed
marksmeed force-pushed the feature/session-lock branch from d5fffea to 37e62a2 Compare August 18, 2026 21:38
@chigwell
chigwell merged commit a612943 into chigwell:main Aug 19, 2026
4 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.

2 participants