Every Python team eventually hits the same wall: the test suite passes on one interpreter and explodes on another, or the package installs fine locally and fails in CI because a dependency drifted. The usual prescription is tox — the tool that builds a fresh virtual environment per Python version, installs your package into it with pip, and runs your commands inside. That prescription, however, hides its own cost. A tox.ini accumulates factor-conditioned lines like deps: pytest-cov, inheritance chains like testenv:py{311,312,313}, and [testenv:.pkg] packaging sections that nobody remembers writing. When a run misbehaves, most developers tweak the config blind, because the machinery behind the flags is a black box.

The black box is worth opening. tox 4 is a rewrite — the modern codebase shares almost nothing with the 3.x monolith — and its architecture is unusually instructive: a pluggy-based hook system where even tox’s own commands are plugins, a typed loader layer that treats TOML as a first-class citizen next to INI, and a scheduler that streams subprocess output through dedicated reader threads. Reading it changes how you debug configuration: suddenly why is this env skipped and where did this deps line come from have concrete answers.

This post walks the main branch of tox-dev/tox as of November 2026, following one tox run from argv to exit code. Every file and line number below was verified against the actual tree, and the two diagrams were generated from that same tree.

tox 4 overview architecture: entry point, provision gate, plugin manager, config discovery, env selection and the environment runtime

The overview flow: the entry point parses options and builds a State, config discovery picks a source file, the EnvSelector turns names, labels and factors into ToxEnv objects, and the run commands drive setup and execution through the registered runners.

Reading the overview from left to right:

  • run, L28 — the process entry point wraps everything in ToxHandler.patch_thread(), converts HandledError to exit code -2, and always finishes with SystemExit.
  • provision, L98 — before any command runs, this gate checks min_version and the requires list; if the installed tox is too old, it bootstraps a matching release in a .tox provisioning environment.
  • discover_source, L37 — walks from the working directory upward through five candidate source types to find tox.ini, setup.cfg, pyproject.toml, or a legacy TOML file.
  • TomlLoader, L83 — the native TOML loader keeps values typed end to end, with dedicated to_bool, to_list, to_dict, to_path converters.
  • IniLoader, L69 — the INI loader treats every value as a string, layering factor filtering and {replace} substitution on top before conversion.
  • EnvSelector, L261 — resolves -e, -m labels, -f factors and --skip-env into concrete environment objects, lazily, on first access of State.envs.
  • ToxEnv.setup, L306 — the environment state machine: platform check, optional recreate, _setup_env with one Recreate retry, then journal the result.
  • VirtualEnv, L69 — the Python environment implementation: base_python resolution against installed cpython interpreters, creation through virtualenv, and a Pip installer.
  • run_one, L34 — the lifecycle of a single environment: setup, commands_pre, commands, commands_post, teardown, all classified into a ToxEnvRunResult.
tox 4 detailed architecture: CLI commands, config sources, INI and TOML loaders, session and env selection, ToxEnv core, Python environments, subprocess execution and journaling

The detail view adds the command layer (run, run-parallel, run-sequential, legacy, show-config), both loader families, the packaging front-end for PEP 517 builds, and the execution plus journaling infrastructure.

From Config Files to Typed Values

Configuration begins in discover_source. If the user passed --config-file pointing at a directory, tox tries each of the five _SOURCE_TYPES in order and stops at the first that loads; a file whose required keys are missing (for instance a pyproject.toml with no [tool.tox] table) raises MissingRequiredConfigKeyError and the search continues. With no explicit file, _locate_source scans Path.cwd() and every parent — which is why tox works when invoked from a subdirectory. If nothing loadsable exists, tox does not fail: _create_default_source logs a warning and fabricates an empty ToxIni, so tox -e py312 --devenv .venv still functions in a folder with no config at all.

The two loader families embody opposite philosophies. INI is stringly typed all the way down: IniLoader inherits from both Loader[str] and StrConvert, pulls raw text from a section, then applies filter_for_env (factor.py, L28) to pick the dash-separated variant that matches the current environment name — that is how deps = pytest ; py312: pytest-cov resolves differently per interpreter. Substitution of {replace} expressions and {envvar} lookups happens after filtering, and requirements lines get special parsing through the PythonDeps machinery. TOML, by contrast, arrives already structured: TomlLoader.load_raw navigates dotted paths into the parsed document, and conversion is a matter of validating real bool/list/dict values rather than coercing strings. The practical consequence: in pyproject.toml you can write lists as lists and booleans as booleans, while tox.ini must encode everything in line syntax.

Selecting Environments: Names, Labels, and Factors

State.envs is a lazy property — the EnvSelector (env_select.py, L261) only exists after something asks for it, and building it is where tox merges CLI intent with config reality. _collect_names unions the configured env_list, plugin-extended names from the tox_extend_envs hook, labels, and factor matches; ALL selects every defined environment. Invalid selections get polite treatment: _suggest_known_env uses difflib.get_close_matches to propose the environment you probably meant, and _ensure_env_name_is_path_safe rejects names that would break the .tox directory layout.

For each selected name, _build_run_env (env_select.py, L536) reads the per-env runner key (defaulting from --runner), looks it up in the global REGISTER (register.py, L90), and instantiates it with a ToxCreateArgs bundle of config, options, and journal. A missing runner name splits three ways: the provisioning env re-raises, an explicitly requested env produces a clear “plugin may not be installed” error, and everything else marks the environment unavailable with a warning instead of aborting the run. Package environments — the .pkg siblings that build your sdist or wheel — are wired in a second phase via _define_pkg_env, including rollback logic that removes environments created during a failed packaging attempt.

The pluggy Core: tox Is Mostly Hooks

The Plugin class (manager.py, L49) is a pluggy.PluginManager named "tox" whose hookspecs live in plugin/spec.py. What makes tox 4 unusual is that its own functionality registers through the same mechanism third-party plugins use — the tox-uv project, for instance, plugs the fast uv installer and environment creator in behind those same hooks. _register_plugins (manager.py, L155) registers a tuple of nineteen internal modules — provision, parallel, sequential, legacy, show_config, the packaging modules, and so on — plus the state module, alongside whatever it finds via load_setuptools_entrypoints("tox") for external distributions. A project-local toxfile.py is imported and registered too, with a graceful fallback: if it references hooks this tox version does not know, tox logs a warning and unregisters it rather than crashing.

The hook names read as a lifecycle: tox_add_option extends the CLI parser, tox_add_core_config and tox_add_env_config inject configuration keys, tox_register_tox_env populates the runner registry, tox_before_run_commands and tox_after_run_commands bracket execution, and tox_on_install / tox_env_teardown cover install and cleanup. This design is why every sub-command in session/cmd/ starts with an @impl tox_add_option — there is no central command table; the CLI assembles itself from registered modules during get_options.

From Twenty-Line Entry to Nineteen Plugins: Build Facts

Several engineering choices in the tree deserve attention as facts rather than narrative. The package targets Python >=3.11 and builds with hatchling; the release version never lives in the repo — hatch-vcs derives it from git tags and writes src/tox/version.py at build time (declared as build.hooks.vcs.version-file in pyproject.toml), which is why the file exists in installed distributions but not in the source tree. Startup cost is attacked with a hand-rolled lazy import system: modules like run.py and manager.py declare __lazy_modules__ lists, and importing tox itself defers loading run, config.cli.parse, report, and session.state until first attribute access.

Error classification is explicit and total. In run.py, an expected HandledError logs TypeName| message and exits -2; KeyboardInterrupt exits -2 as well; anything unexpected propagates as a real traceback. Inside one environment, single.py maps Skip to a success exit with a skipped flag, Fail and HandledError to code 1, and any other exception to code 2 — and the per-set exit code is the first non-success across commands_pre, commands, commands_post (single.py, L119).

Process I/O gets dedicated infrastructure: ReadViaThread (read_via_thread.py, L21) spawns one thread per stream, named tox-r-{stream}-{fd}, polling shutdown every 0.05 seconds and optionally draining residue on exit — the same approach CPython’s own subprocess tests use. Parallelism is bounded by parse_num_processes (parallel.py, L113), which accepts all (no limit), auto (CPU count via auto_detect_cpus), or a non-negative integer; sub-processes discover their identity through the TOX_PARALLEL_ENV variable, and 0 disables parallel mode entirely.

Running Environments: Sequential, Parallel, Interruptible

Both run commands funnel into one execute function (common.py, L199). It starts a single scheduler thread named tox-interrupt running _queue_and_wait, which submits environment futures in dependency order (run_order respects depends_on) and waits on completions. The main thread joins that scheduler in one-second slices, so Ctrl+C lands on the main thread: tox ignores further SIGINT, cancels pending futures in reverse order, calls interrupt() on environments still running, and waits for teardown before printing a final report. Output handling differs per mode — parallel runs capture by default (showing a spinner with per-env outcome marks, unless --parallel-live or --parallel-no-spinner says otherwise, and CI environments suppress the spinner automatically), while sequential mode streams live. Results accumulate into ToxEnvRunResult records carrying name, exit code, outcomes, duration, and the ignore_outcome / fail_fast flags, then land in the optional --result-json document via the Journal (journal/main.py, L23).

Beyond run, the command set covers show-config (dumping fully resolved configuration as INI, JSON, or TOML — invaluable for debugging which factor variant won), list-env, depends for dependency traversal, devenv for provisioning a development environment, and legacy for the old command surface. Packaging itself runs through Pep517VenvPackager and its concrete Pep517VirtualEnvPackager (pyproject.py, L694): a dedicated packaging environment hosts the PEP 517 backend, and tox speaks to it as a proper frontend, building sdists and wheels on demand and sharing the built wheel across run environments.

Honest Limits

This tour covers src/tox on main as of late November 2026; the project moves quickly, so line numbers anchor to that snapshot. Several subsystems are only sketched: the journal package’s per-env records, inline-script (pep723) and pylock support, the Windows-specific reader implementations alongside read_via_thread_unix, venv_redirect (letting an environment live at the project’s .venv), and the full substitution grammar in config/loader/replacer.py all deserve their own articles. The provision bootstrap is described at the level of its gate function without walking _get_missing requirement math. The diagrams are generated from hand-built graph JSON over the real tree, so they reflect structure but omit details no diagram can hold — read the linked sources for ground truth. What the tour should leave you with is a debugging reflex: when a run surprises you, show-config reveals the resolved truth, --result-json captures it, and the source under those flags is small enough to read honestly.

Watch PyShine on YouTube

Contents