Repository navigation
logging(feat): Document logging and define failure ownership - #748
Merged
Merged
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #748 +/- ##
==========================================
+ Coverage 58.34% 60.37% +2.03%
==========================================
Files 30 31 +1
Lines 4470 4959 +489
Branches 900 1027 +127
==========================================
+ Hits 2608 2994 +386
- Misses 1551 1639 +88
- Partials 311 326 +15 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
tony
force-pushed
the
document-logging
branch
from
November 7, 2026 02:18
e9ad992 to
f560846
Compare
tony
force-pushed
the
document-logging
branch
4 times, most recently
from
November 22, 2026 20:21
5704668 to
ff2359e
Compare
tony
force-pushed
the
document-logging
branch
from
November 25, 2026 08:38
ff2359e to
6d2e8d1
Compare
This was referenced Nov 25, 2026
tony
force-pushed
the
document-logging
branch
from
November 28, 2026 12:49
6d2e8d1 to
034fef5
Compare
tony
force-pushed
the
document-logging
branch
from
November 28, 2026 13:27
034fef5 to
c90cfa8
Compare
This was referenced Nov 28, 2026
why: tmux_cmd reported two different strings depending on which module logged it — the full argument vector in common.py, the arguments alone in neo.py — so a consumer parsing the documented field saw two shapes. The same command line also carried environment values verbatim, putting any token passed as environment= into DEBUG logs. what: - Add _internal/log_context.py: describe_command() walks tmux's global flags per the getopt string in tmux.c, so a flag that takes a value is never read as the subcommand, and redacts environment values - Redact at the seam rather than at each call site, so set-environment and any future env-carrying command are covered; -e stays untouched where tmux treats it as a boolean (select-pane, copy-mode) - Derive tmux_subcommand and a new tmux_socket for every command record - Drop neo.py's duplicate query records, now fully superseded - Log ERROR in raise_if_stderr, where libtmux decides a command failed, carrying the exit code and socket the exception message cannot - Cover the tmux CLI grammar and redaction with table-driven tests
why: Five near-identical blocks hand-rolled the same lifecycle extra dict, each repeating the "coerce to str, omit when None" invariant, so the invariant could drift per call site with nothing to catch it. what: - Route lifecycle records through log_context.object_extra(), which holds that invariant in one place and is unit-tested - Tag session created with tmux_target, which it was missing - Give the hooks parse warning an extra; its %s always interpolated the blank line that triggered it - Drop exc_info from the query_list lookup debug records: a missing field is normal control flow for a filter, not a traceback
why: Closes #744. Nothing in the docs mentioned logging, so the only way to configure it was to read the source and infer a strategy — which is what the reporter had to do while diagnosing libtmux on a platform it does not support. what: - Add docs/topics/logging.md: turning it on, diagnosing a failure, which logger emits what, the full tmux_ field schema, reading records with caplog, and recipes for JSON output and OpenTelemetry - Document the Formatter trap that drops records whose format string names a field they lack, with the defaults= fix - Expose caplog through doctest_namespace so the page's examples run as tests rather than drifting from the code - Record the new tmux_socket key and the failure-record rule in AGENTS
why: Killing a session through Server.kill_session() emitted no lifecycle record while Session.kill() emitted one, so whether the operation appeared in logs depended on which entry point a caller happened to use. what: - Emit the same "session killed" INFO record from Server.kill_session() - Cover it alongside the other lifecycle records
why: The session fixture asked tmux to switch a client even when none was attached, which is a command failure. Now that libtmux logs failures at ERROR, pytest replays that record into the captured-log section of every failing test that uses the fixture, where it reads as the cause of the failure rather than as fixture noise. what: - Attempt the switch only when a client exists; keep the suppression for the race where one detaches in between - Assert fixture setup leaves no ERROR records behind
why: raise_if_stderr() has 85 call sites, so its ERROR record reported common.py for every one of them. That leaves %(filename)s, %(funcName)s, and OpenTelemetry's code.filepath naming the helper rather than the tmux operation that failed — the one thing the record exists to locate. what: - Log with stacklevel=2 so the record names the calling wrapper - Parse bundled global flags: -2Lsock is -2 -L sock to getopt, and the socket was being dropped - Warn once per option rather than once per malformed entry, counting the skipped entries in tmux_option_skipped - Give the control-mode client the same command records as any other tmux subprocess, and warn when one must be killed after declining to exit; fold its two duplicate terminate paths into one
why: The level table listed only parse failures under WARNING, which stopped being the whole story once the control-mode client gained a record for being killed. what: - Name the control-mode kill alongside the parse warnings
why: A tmux command line carries whatever the caller passed it, and send_keys payloads routinely contain newlines. One of those ended the DEBUG record early in any line-oriented log, leaving the rest of the argument to read as a record of its own — 66 of the 10,545 commands a full test run issues already carry control characters. what: - Quote an argument holding control characters into shell $'…' form, which bash and zsh expand back to the original bytes, so the command line still pastes and reproduces the call on a single line - Render terminal escape sequences rather than passing them through to whatever reads the log - Leave object names alone: tmux rejects control characters in them before libtmux logs anything, so there is nothing to guard
why: A command past tmux's own size limit is rejected by tmux, but its whole payload was still written to three records, so one oversized set_buffer() could put hundreds of kilobytes into a DEBUG log. what: - Cap tmux_cmd at MAX_IMSGSIZE, the largest command tmux will run, so every command tmux accepted stays reproducible from its record and only a rejected one arrives shortened - Report the pre-cap length as tmux_cmd_len, matching how the stdout and stderr caps already report theirs
why: tmux_stdout and tmux_stderr hold lists, so a %s in a format string renders a Python repr rather than the lines a reader expects. what: - Show the repr and how to join the lines instead
why: The cap measures the quoted command line while tmux measures the raw one, and quoting expands — a single quote becomes five characters. A payload of 4000 quotes is a command tmux accepts whose record still shortens, so "every command tmux ran is reproducible" was not true. what: - Describe what the cap actually guarantees, and name quote expansion - Point at comparing tmux_cmd_len to spot a shortened record - Filter rather than index in the example, as the page advises
why: The guide, changelog, and package policy still described deleted redaction machinery and repeated generic Python logging recipes. what: - Document operand and output-body omission as the privacy boundary - Describe boundary-only errors and the reduced structured schema - Keep concise activation, formatter, warning, and caplog examples - Collapse the changelog to the branch's net behavior
why: List accessors promise an empty result for tmux failures, but non-executable and malformed binaries escaped as raw OSError values. what: - Translate process-launch OSError values to TmuxCommandNotFound - Cover missing, non-executable, and malformed tmux binaries
why: Caller-controlled lifecycle identities could contain Unicode line separators and split rendered records. what: - Escape non-printable lifecycle identities in object_extra - Exercise the target field with a live tmux session name
why: Resource-related process launch failures were mislabeled as a missing tmux executable and lost their diagnostics. what: - Reserve TmuxCommandNotFound for unavailable executables - Retain other launch errors as LibTmuxException causes
why: tmux 3.3a stores Unicode session names as escaped bytes, so the live delete-by-name step failed before reaching the log assertion. what: - Restore a portable name for the live lifecycle flow - Check the forged target at the shared context boundary
why: The branch replaced released command and output fields with a summary and presented payload omission as a privacy boundary. That reduced diagnostics and made application logging policy a producer concern. what: - Restore complete one-line commands and bounded output snapshots - Stop derived metadata parsing when a global option is unknown - Include bounded exception text where list accessors swallow failures - Document handler filters, formatter field selection, and payload cost
why: Unusable executable paths were normalized for lenient accessors, but the translation discarded the operating-system message and cause. Server.raise_if_dead() also exposed different exception types. what: - Preserve ENOENT, EACCES, and ENOEXEC diagnostics on domain exceptions - Align tmux_cmd and raise_if_dead without changing successful calls - Keep lenient accessors empty and attach their diagnostics - Cover default, missing, non-executable, malformed, and E2BIG cases
why: The branch wrapped every unrelated launch OSError in LibTmuxException. That changed trunk behavior for E2BIG and similar failures even though only unavailable executables need normalization. what: - Re-raise unrelated launch OSError values unchanged from direct APIs - Catch and log those errors only at lenient list boundaries - Document direct and lenient exception behavior - Cover all three list accessors and supported tmux builds
why: Normal lifecycle and option paths emitted structured records without regression coverage for their levels and object context. what: - Cover session creation, replacement, and direct kill records - Cover malformed command aliases and floating-pane creation - Reuse existing integration tests without adding runtime code
why: The guide denied the package NullHandler and placed a customization handler below the documented package logger entry point. what: - Distinguish the NullHandler from application output handlers - Attach the tested handler to the libtmux parent logger - Surface handler ownership in the logging topic index
why: Downstream users need the logging and exception changes summarized at the upgrade boundary. what: - Document structured records and application-owned formatting - Explain failure-channel and unusable-executable migrations - Record handled diagnostics, line-safe context, and the logging guide
why: Query helpers rely on the shared command producer, but no test protected them from restoring duplicate module-level records. what: - Exercise fetch_objs against the real tmux fixture - Require one common-logger dispatch and completion pair
why: v0.54.0 exposed query DEBUG records from libtmux.neo, so moving them to the shared command producer changes logger and event filters. what: - Record the replacement logger and event names - Show the module-specific logging migration
why: The migration snippet swaps one logger name for another, but libtmux.common carries every tmux subprocess rather than list queries alone. what: - Name the wider scope readers inherit with the command logger - Point at the tmux_subcommand handler filter in the logging topic
why: An unusable tmux binary now raises TmuxCommandNotFound rather than PermissionError or OSError, so a handler written for the OS exception stops firing on upgrade with no other signal. what: - Add the 0.63.x section, one subsection per breaking change - Name who each change affects and show the handler and logger updates - Record that an attempted launch keeps its errno on __cause__
why: Restoring full command lines brought environment values back into tmux_cmd, undoing the masking 0.64.0 shipped for #866. what: - Move _redact_env_values and its flag tables into log_context - Mask the command line command_extra puts in tmux_cmd, and expect the masked value in its test - Drop _loggable_cmd, which no caller uses - Restore the os import the socket-path tests in test_server.py use - Drop noqa comments ruff no longer needs
why: Command-line masking only matched canonical subcommand names,
unclustered -e and -t flags, and the first command in argv, while
show-environment returned the same environment values unmasked in
completion DEBUG records and control_mode passed raw target strings.
what:
- Share one global-option scanner in log_context so command_extra stops
derived metadata on unknown options while redaction continues
- Split command lists on standalone and unescaped trailing semicolons,
preserve { ... } blocks, resolve aliases and unambiguous prefixes, and
redact short-flag clusters and command-string carriers per tmux's C
parser across ;, newline, and brace boundaries
- Add redact_stdout for show-environment default RB_TREE order, -s
shell format, single-variable, chained, and carrier forms and wire it
into tmux_cmd completion logs
- Route control_mode's tmux_target through object_extra scalar escaping
- Cover live round trips, RB_TREE continuations, and C-grammar carriers
in test_logging.py and test_common.py
why: docs/topics/logging.md and src/libtmux/AGENTS.md still stated that libtmux never redacts command or output payloads, and omitted why application filters must attach to handlers rather than the parent logger. what: - Document symmetric masking of -e (including new_pane and respawn), set-environment, and show-environment stdout values alongside unredacted wire traces - Add a doctest showing handler vs parent-logger filter placement and note Python 3.11 formatter selection vs 3.12+ replacement records - Remove stale Python 3.10 qualifiers from formatter examples - Align the producer redaction boundary in src/libtmux/AGENTS.md
why: MIGRATION cited 0.62.0 rather than 0.69.0 as the prior behavior baseline, and CHANGES omitted symmetric show-environment and C-grammar masking and mixed Before/After comments in one raise_if_dead snippet. what: - Update the three 0.70.x baseline references in MIGRATION to 0.69.0 - Split the raise_if_dead migration snippet into separate Before and After blocks in CHANGES - Record show-environment stdout masking and C-grammar flag, chain, brace-block, and carrier masking in CHANGES with MyST API links - Trim filler wording and link Handler, Formatter, and Server.is_alive in CHANGES
tony
force-pushed
the
document-logging
branch
from
November 28, 2026 22:19
f8d5ffb to
396c960
Compare
This was referenced Nov 28, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #744, closes #866. Builds on #898; supersedes #905 and #906.
Summary
tmux_fields, handler filters, andcaplogchecks.extrafields across operations and control mode.tmux_cmdarguments andshow-environmenttmux_stdout.ERRORon swallowed list failures.TmuxCommandNotFoundand aggregate malformed option warnings.Changes by area
Command and lifecycle records
src/libtmux/_internal/log_context.py,src/libtmux/common.py,src/libtmux/neo.py,src/libtmux/client.py: emittmux command dispatchedandtmux command completedonlibtmux.common(replacinglibtmux.neolist records and droppinglibtmux.client's unused logger) with symmetric environment-value masking across flag clusters, aliases and prefixes,;chains,{ ... }blocks, command carriers, andshow-environmenttmux_stdout, plus bounded 100-line output snapshots and line counts.src/libtmux/server.py,src/libtmux/session.py,src/libtmux/window.py,src/libtmux/pane.py,src/libtmux/pytest_plugin.py: emit a shared string-valuedobject_extra()schema for lifecycle operations, includingServer.kill_session().src/libtmux/_internal/log_context.py,src/libtmux/_internal/query_list.py: escape control characters in command arguments, object identities, targets, and failed lookup paths so records stay on one line without duplicate tracebacks.src/libtmux/_internal/control_mode.py: attachcommand_extra()andobject_extra()context to control-mode startupDEBUGand timeout-killWARNINGrecords.Failure handling
src/libtmux/common.py: keep propagated and translated failures in exceptions instead of loggingERRORbefore raising.src/libtmux/server.py: retain the emptyQueryListreturn onServer.sessions,Server.attached_sessions, andServer.clientswhile emitting one boundedERRORonlibtmux.serverwhen a failure is swallowed, and keepServer.is_alive()quiet.src/libtmux/common.py,src/libtmux/server.py,src/libtmux/exc.py: translateENOENT,EACCES, andENOEXEClaunch errors toTmuxCommandNotFoundwith the OS message and__cause__preserved, leaving unrelatedOSErrorlaunches native.Before (
0.69.0raised rawPermissionErrororOSErrorfor non-executable or malformed binaries, loggedERRORbefore raising, and emitted queryDEBUGrecords onlibtmux.neo):After (
0.70.xnormalizes unusable binaries toTmuxCommandNotFound, keeps raised failures out ofERRORlogs, and emits query command records onlibtmux.common):Recoverable diagnostics
src/libtmux/options.py: emit one aggregateWARNINGper malformedterminal-features,terminal-overrides, orcommand-aliasoption withtmux_option_skipped.src/libtmux/hooks.py: emit a structuredshow-hooksparseWARNINGwithout interpolating raw hook lines.Documentation
docs/topics/logging.md,docs/topics/index.md,conftest.py: add the logging topic page and seedcaplogindoctest_namespaceso examples execute under pytest.CHANGES,MIGRATION,src/libtmux/AGENTS.md: document the0.70.xfailure-channel,libtmux.neologger,TmuxCommandNotFound, and symmetric environment-masking contracts alongside upgrade examples.Design decisions
command_extra()andredact_stdout()mask ambient environment values symmetrically across-e NAME=value,set-environment, andshow-environmenttmux_stdout, whileDEBUGrecords retain typed keys, buffer data, and bounded output snapshots instead of masking pty payloads unconditionally (common(feat[logging]): Mask typed keys and buffer data in logs #905, hidingDEBUGwire traces across every handler) or adding a process-global redactor callback (common(feat[logging]): Let callers choose the logged argv redactor #906, introducing shared mutable state and blocking per-handler routing). Standard-library handlers, filters, and formatters decide which fields reach each destination.tmux_cmdoutput remains authoritative; derivedtmux_subcommandandtmux_socketextraction stops at unknown global options instead of guessing context, while environment redaction continues past unknown global options.Test plan
tests/test_logging.pycommand_extra()andredact_stdout()(including round-tripset_environment+show_environment/getenv, clustered flags,;chains,{ ... }blocks,RB_TREEmultiline continuations, and command carriers) intests/test_logging.pyServer.kill_session()lifecycle records against live tmuxServer.is_alive()emit noERRORrecordsTmuxCommandNotFoundversus nativeOSErroruv run pytest --reruns=0,uv run ruff format . --check,uv run ruff check .,uv run mypy, andjust build-docs(sphinx-build -W) pass across supported tmux releasesterminal-overridesentries, blankshow-hooksoutput warnings, and forcedControlModetermination warnings