Skip to content

Scoping a Server no longer kills it - #728

Merged
tony merged 6 commits into
masterfrom
fix/724-server-kill-on-exit
Nov 27, 2026
Merged

tony merged 6 commits into
masterfrom
fix/724-server-kill-on-exit

Conversation

@tony

@tony tony commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Breaking change. Read Before / After below before merging.

Summary

  • Preserve running tmux servers when leaving with Server() as server:.
  • Add kill_on_exit: bool = False on Server to opt into daemon teardown on exit.
  • Document why Server differs from Session, Window, and Pane in Server, docs/topics/context_managers.md, CHANGES, and MIGRATION.

Fixes #724

Why scoping is not ownership

A Server is a handle on a socket, not a connection. The same handle addresses a daemon whether or not this process started it, and a bare Server() addresses the default socket — usually the tmux the reader has been working in all day. Entering a with block scopes the handle without granting permission to destroy a shared daemon.

Session, Window, and Pane retain their existing context-manager behavior: leaving the block destroys the selected object, including one retrieved from an existing server.

Normal and exceptional exits preserve the selected server, including a daemon started by another client during the block. The native kill-server command destroys every session on that server. tmux may still exit after its last session ends according to exit-empty.

Before / After

Before, leaving an empty with block killed the server (is_alive() returned False) and destroyed every session on that socket:

Server(socket_name="my-work").new_session(session_name="important")

with Server(socket_name="my-work") as server:
    pass

Server(socket_name="my-work").is_alive()

After, leaving the block preserves the server (is_alive() returns True):

Server(socket_name="my-work").new_session(session_name="important")

with Server(socket_name="my-work") as server:
    pass

Server(socket_name="my-work").is_alive()

Opt into teardown explicitly with kill_on_exit=True:

with Server(socket_name="build", kill_on_exit=True) as server:
    server.new_session(session_name="ci")

Design decisions

  • Liveness at __enter__ cannot infer creation ownership: Server.is_alive() returns False on any transient error reaching the socket, so inferring ownership from not self.is_alive() at entry would misclassify an existing server and kill it on exit, while a socket itself carries no provenance of who started the daemon.
  • Explicit teardown matches subprocess.Popen.__exit__ and sqlite3.Connection.__exit__, where scoping does not destroy the underlying process or connection.
  • kill_on_exit is a plain bool defaulting to False, matching action-named flags such as Pane.display_popup(close_on_exit=...) and tmux's remain-on-exit / exit-empty options rather than claiming unverified ownership (owns_server).
  • temp_server remains the doc anchor for the TestServer pytest fixture; isolated temporary-server helpers remain tracked in Add Server.private() context manager #872.

Test plan

  • test_server_context_manager verifies the default preserves a running server, including one started inside the block
  • test_server_context_manager_spares_borrowed_server verifies daemon PID, session ID, and pane process survival across normal and raising exits for pre-existing and mid-block servers
  • test_server_context_manager_spares_the_default_socket verifies bare Server() under $TMUX_TMPDIR
  • test_server_context_manager_kill_on_exit_true and test_server_context_manager_kill_on_exit_true_when_block_started_it verify opt-in teardown
  • Doctests on Server, docs/topics/context_managers.md, and MIGRATION, plus ruff, mypy, and sphinx-build -W
  • Full tmux version matrix in CI

Follow-up, not in this PR

Session.from_session_id, Window.from_window_id, and Pane.from_pane_id still kill their target when used in with; creation-ownership tracking across child scopes remains tracked in #804 and #925.

@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 57.71%. Comparing base (d2a146c) to head (8bf8440).

Files with missing lines Patch % Lines
src/libtmux/server.py 50.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #728      +/-   ##
==========================================
- Coverage   57.72%   57.71%   -0.02%     
==========================================
  Files          29       29              
  Lines        4360     4363       +3     
  Branches      882      882              
==========================================
+ Hits         2517     2518       +1     
- Misses       1533     1535       +2     
  Partials      310      310              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@tony
tony force-pushed the fix/724-server-kill-on-exit branch from 846fb7c to 7ea0444 Compare July 30, 2026 23:29
@tony tony changed the title Server's context manager spares a server it did not start Scoping a Server no longer kills it Jul 30, 2026
@tony

tony commented Jul 30, 2026

Copy link
Copy Markdown
Member Author

Code review

Found 1 issue:

  1. Two sections further down context_managers.md still promise the old behaviour, so the page now contradicts itself. The commit message says it reworked the page "which promised unconditional teardown for all four classes" — two of those promises survive.

## Nested context managers
For complex setups, you can nest contexts to build a whole tmux hierarchy at
once and have every layer torn down for you:
```python
>>> with Server() as server:
... with server.new_session() as session:
... with session.new_window() as window:
... with window.split() as pane:
... pane.send_keys('echo "Hello"')
... # Do work with the pane
... # Everything is cleaned up automatically when exiting contexts
```
This ensures that:
1. The pane is killed when exiting its context
2. The window is killed when exiting its context
3. The session is killed when exiting its context
4. The server is killed when exiting its context
The cleanup happens in reverse order (pane → window → session → server), ensuring proper resource management.

"Nested context managers" still says the block gives you "every layer torn down for you", and item 4 reads "The server is killed when exiting its context". The with Server() as server: example immediately above it now leaves the daemon running.

## Benefits
Reaching for a context manager buys you a few things. Resources clean themselves
up the moment you leave the block, so you never manually call the
{meth}`~libtmux.Server.kill`, {meth}`~libtmux.Session.kill`,
{meth}`~libtmux.Window.kill`, or {meth}`~libtmux.Pane.kill` methods and the code
stays uncluttered. Because cleanup runs on the way out of the block, it fires
even when an exception unwinds the stack — so you don't leak a stray session or

"Benefits" then says "you never manually call the {meth}~libtmux.Server.kill ... methods", which is exactly what a reader now has to do.

The doctests cannot catch this: the nested block asserts no output, so the prose can drift from the behaviour silently. docs/AGENTS.md asks, in its pre-commit checklist, "Do the doctests run, and did you leave every code block, table, error string, and cross-reference exact?"

libtmux/docs/AGENTS.md

Lines 145 to 150 in 7ea0444

named by concept instead?
- Are the advanced and lower-level parts clearly marked opt-in?
- Do the doctests run, and did you leave every code block, table, error
string, and cross-reference exact?
- Did `just build-docs` stay clean — no new warning, no broken
cross-reference?

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

@tony
tony force-pushed the fix/724-server-kill-on-exit branch 4 times, most recently from 60c8056 to 9114092 Compare August 1, 2026 11:41
@tony tony added this to libtmux Nov 1, 2026
@tony tony moved this to In Progress in libtmux Nov 1, 2026
@tony
tony force-pushed the fix/724-server-kill-on-exit branch from 4d60f41 to 9befff4 Compare November 7, 2026 04:04
@tony tony added the behavior-change Fixes a bug by changing observable or documented behaviour; needs a minor release label Nov 21, 2026
@tony
tony force-pushed the fix/724-server-kill-on-exit branch 3 times, most recently from 5eeb4f4 to a3e9d41 Compare November 21, 2026 22:10
@tony tony mentioned this pull request Nov 21, 2026
43 of 62 tasks
@tony
tony force-pushed the fix/724-server-kill-on-exit branch 4 times, most recently from 412efa7 to 0197be4 Compare November 22, 2026 19:23
@tony tony added the area: lifecycle Server start, context managers, ownership, get-or-create, discovery, leases, program lifetime label Nov 24, 2026
@tony tony added this to the 0.69.0 milestone Nov 24, 2026
tony added 2 commits November 25, 2026 02:19
why: A Server is a handle on a socket, not a connection -- the same
handle addresses a daemon whether or not this process started it, and a
bare Server() addresses whichever tmux the caller has open. Scoping one
to a block was destroying it, along with every session in it.

Inferring ownership from is_alive() was considered and rejected. That
predicate folds every way of failing to reach a server into False by
contract, so a transient tmux error at __enter__ would have read as
"this block started it" and killed a daemon that predated the block --
the same bug through a different door. Fixes #724.

what:
- Default kill_on_exit to False; __exit__ kills only when asked
- __enter__ returns self and probes nothing
- Say in the Server docstring that a server, unlike a session, window or
  pane, does not tear itself down, and why
- Rework docs/topics/context_managers.md, which promised unconditional
  teardown for all four classes
- Test the default, the opt-in, and a bare Server() on the default
  socket -- the shape the report was actually about, which the
  TestServer factory cannot reproduce
why: The page promised unconditional teardown for all four classes, so
a reader following it would expect `with Server()` to kill a server it
did not start.

what:
- Say that a `Server` context leaves the daemon running unless it was
  built with `kill_on_exit=True`, and show both.
- Correct the nested-context walkthrough, whose summary still listed
  the server among the layers torn down.
tony added 2 commits November 25, 2026 02:19
why: Scope exit must preserve the daemon and programs selected by a
borrowed handle, including on exceptions and concurrent creation.

what:
- Check daemon and program identity across normal and exceptional exit
- Cover a daemon started by another handle during the scope
- Isolate the default-socket regression and always clean its server
- Document explicit teardown migration and child context ownership
why: Leaving a with Server() block no longer kills the server, which
changes what existing code tears down.

what:
- Add a Breaking changes entry for the new default and kill_on_exit,
  with the migration
@tony
tony force-pushed the fix/724-server-kill-on-exit branch from 0197be4 to e479ae3 Compare November 25, 2026 08:24
tony added 2 commits November 25, 2026 19:17
…ample

Set versionadded and versionchanged directives on Server.kill_on_exit and
Server.__exit__ to 0.69, broaden the MIGRATION baseline to pre-0.69.0
releases, pass kill_on_exit=True in the nested teardown doctest, and link
exit-empty on man.openbsd.org.
@tony
tony merged commit 4797b58 into master Nov 27, 2026
15 checks passed
@tony
tony deleted the fix/724-server-kill-on-exit branch November 27, 2026 01:17
@github-project-automation github-project-automation Bot moved this from In Progress to Done in libtmux Nov 27, 2026
tony added a commit to tmux-python/tmuxp that referenced this pull request Nov 28, 2026
why: Pick up libtmux 0.69.0. Server context managers leave a running
tmux server alive on exit unless kill_on_exit=True is set, @ user
options stay strings in show_option() and show_options(), and empty tmux
format fields hydrate as "" instead of None while unset fields stay
None. tmuxp requires no source changes for the upgrade.

what:
- Bump libtmux ~=0.68.0 -> ~=0.69.0 in pyproject.toml
- Update uv.lock to libtmux 0.69.0 from PyPI (only libtmux moves)

libtmux 0.69.0 (2026-11-27):
- Server.__exit__() preserves running servers unless kill_on_exit=True
  is set (tmux-python/libtmux#728)
- @ user options stay strings in show_option() and show_options()
  (tmux-python/libtmux#826)
- Empty tmux format fields hydrate as "" while unset fields stay None
  (tmux-python/libtmux#900)

See also:
- https://github.com/tmux-python/libtmux/releases/tag/v0.69.0
- https://libtmux.git-pull.com/history/#libtmux-0-69-0-2026-11-27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: lifecycle Server start, context managers, ownership, get-or-create, discovery, leases, program lifetime behavior-change Fixes a bug by changing observable or documented behaviour; needs a minor release

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Server.__exit__ kills any live server, including one it did not start

1 participant