Skip to content

logging(feat): Document logging and define failure ownership - #748

Merged
tony merged 46 commits into
masterfrom
document-logging
Nov 28, 2026
Merged

tony merged 46 commits into
masterfrom
document-logging

Conversation

@tony

@tony tony commented Aug 22, 2026 •

Copy link
Copy Markdown
Member

Closes #744, closes #866. Builds on #898; supersedes #905 and #906.

Summary

  • Document logger hierarchy, levels, tmux_ fields, handler filters, and caplog checks.
  • Standardize command and object lifecycle extra fields across operations and control mode.
  • Mask environment variable values across tmux_cmd arguments and show-environment tmux_stdout.
  • Escape control characters onto one log line across commands, targets, and identities.
  • Keep propagated failures in exceptions while logging one ERROR on swallowed list failures.
  • Normalize unusable tmux binaries to TmuxCommandNotFound and 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: emit tmux command dispatched and tmux command completed on libtmux.common (replacing libtmux.neo list records and dropping libtmux.client's unused logger) with symmetric environment-value masking across flag clusters, aliases and prefixes, ; chains, { ... } blocks, command carriers, and show-environment tmux_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-valued object_extra() schema for lifecycle operations, including Server.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: attach command_extra() and object_extra() context to control-mode startup DEBUG and timeout-kill WARNING records.

Failure handling

  • src/libtmux/common.py: keep propagated and translated failures in exceptions instead of logging ERROR before raising.
  • src/libtmux/server.py: retain the empty QueryList return on Server.sessions, Server.attached_sessions, and Server.clients while emitting one bounded ERROR on libtmux.server when a failure is swallowed, and keep Server.is_alive() quiet.
  • src/libtmux/common.py, src/libtmux/server.py, src/libtmux/exc.py: translate ENOENT, EACCES, and ENOEXEC launch errors to TmuxCommandNotFound with the OS message and __cause__ preserved, leaving unrelated OSError launches native.

Before (0.69.0 raised raw PermissionError or OSError for non-executable or malformed binaries, logged ERROR before raising, and emitted query DEBUG records on libtmux.neo):

import logging
from libtmux import exc

logging.getLogger("libtmux.neo").setLevel(logging.DEBUG)

try:
    server.raise_if_dead()
except (exc.TmuxCommandNotFound, OSError):
    available = False

After (0.70.x normalizes unusable binaries to TmuxCommandNotFound, keeps raised failures out of ERROR logs, and emits query command records on libtmux.common):

import logging
from libtmux import exc

logging.getLogger("libtmux.common").setLevel(logging.DEBUG)

try:
    server.raise_if_dead()
except exc.TmuxCommandNotFound:
    available = False

Recoverable diagnostics

  • src/libtmux/options.py: emit one aggregate WARNING per malformed terminal-features, terminal-overrides, or command-alias option with tmux_option_skipped.
  • src/libtmux/hooks.py: emit a structured show-hooks parse WARNING without interpolating raw hook lines.

Documentation

  • docs/topics/logging.md, docs/topics/index.md, conftest.py: add the logging topic page and seed caplog in doctest_namespace so examples execute under pytest.
  • CHANGES, MIGRATION, src/libtmux/AGENTS.md: document the 0.70.x failure-channel, libtmux.neo logger, TmuxCommandNotFound, and symmetric environment-masking contracts alongside upgrade examples.

Design decisions

  • command_extra() and redact_stdout() mask ambient environment values symmetrically across -e NAME=value, set-environment, and show-environment tmux_stdout, while DEBUG records 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, hiding DEBUG wire 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.
  • Complete tmux_cmd output remains authoritative; derived tmux_subcommand and tmux_socket extraction stops at unknown global options instead of guessing context, while environment redaction continues past unknown global options.
  • A failure is logged only where libtmux converts it to a fallback result; callers own logging for failures they receive as exceptions.

Test plan

  • Verify command dispatch and completion schemas, 100-line output bounds with line counts, Unicode, control-character escaping, and unknown global options in tests/test_logging.py
  • Verify symmetric C-grammar environment masking across command_extra() and redact_stdout() (including round-trip set_environment + show_environment / getenv, clustered flags, ; chains, { ... } blocks, RB_TREE multiline continuations, and command carriers) in tests/test_logging.py
  • Verify server, session, window, pane, floating-pane, replacement, and Server.kill_session() lifecycle records against live tmux
  • Verify swallowed list failures log once while propagated failures and Server.is_alive() emit no ERROR records
  • Verify missing, non-executable, malformed, and resource-exhausted executable paths preserve TmuxCommandNotFound versus native OSError
  • uv run pytest --reruns=0, uv run ruff format . --check, uv run ruff check ., uv run mypy, and just build-docs (sphinx-build -W) pass across supported tmux releases
  • Verify aggregate warnings for malformed terminal-overrides entries, blank show-hooks output warnings, and forced ControlMode termination warnings

@codecov

codecov Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.62830% with 176 lines in your changes missing coverage. Please review.
✅ Project coverage is 60.37%. Comparing base (9b2a277) to head (396c960).
⚠️ Report is 47 commits behind head on master.

Files with missing lines Patch % Lines
src/libtmux/_internal/log_context.py 71.35% 121 Missing and 44 partials ⚠️
src/libtmux/_internal/control_mode.py 50.00% 4 Missing ⚠️
src/libtmux/common.py 88.23% 2 Missing ⚠️
src/libtmux/options.py 83.33% 2 Missing ⚠️
src/libtmux/_internal/query_list.py 50.00% 1 Missing ⚠️
src/libtmux/hooks.py 0.00% 1 Missing ⚠️
src/libtmux/server.py 93.75% 1 Missing ⚠️
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.
📢 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 changed the title Document logging, and harden the records it emits Document structured logging and define failure ownership Aug 23, 2026
@tony
tony force-pushed the document-logging branch from 6078496 to 8504144 Compare August 23, 2026 17:41
@tony
tony force-pushed the document-logging branch from e9ad992 to f560846 Compare November 7, 2026 02:18
@tony
tony force-pushed the document-logging branch 4 times, most recently from 5704668 to ff2359e Compare November 22, 2026 20:21
@tony tony added the area: logging Logging and redaction label Nov 24, 2026
@tony tony added this to the 0.70.0 milestone Nov 28, 2026
@tony tony changed the title Document structured logging and define failure ownership logging(feat): Document logging and define failure ownership Nov 28, 2026
tony added 11 commits November 28, 2026 16:14
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
tony added 20 commits November 28, 2026 16:14
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: logging Logging and redaction

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tmux_cmd logs unredacted set-environment, buffer, and key values Documentation: how to use internal libtmux logging

1 participant