| name | import-bloat |
|---|---|
| description | Find and cut the memory a long-running Python process spends on packages it imports but never uses -- measure each process's import-only footprint, trace which import pulled each package in, map every chain that loads it, cost the fix before writing it, guard the fix with a fresh-interpreter test, and measure the whole set of fixes against one baseline -- with the import-bloat helper. Use when asked why a Python service, agent or worker is so big, to cut memory on CI nodes or small hosts, when a heavy package (eventlet, sqlalchemy, pandas, an SDK) loads in a process that never calls it, when writing or reviewing a lazy-import patch, or before claiming in a commit or plan that such a patch saves memory. |
A Python service's steady-state memory is mostly the code it imported: module objects, functions, classes and the constants built at import time. None of that is shared between processes that were exec'd rather than forked. A fork shares it only until the pages are written, and CPython's reference counting writes to them all the time. So a package that a process loads but never calls costs real memory, in every copy of that process on every host. In OpenStack the whole set of fixes came to 24 to 49 MB per neutron process, and 10 to 24 MB for glance, keystone and placement.
$HOME/bin/import-bloat does the measuring. It is a single
standard-library Python file, so it runs in any virtualenv or container
with that environment's own interpreter. import-bloat --help is the
reference for its subcommands. It reads /proc/self/status, so it needs
Linux.
Compare a process's import-only footprint with its real peak RSS in production or CI. If the two are within about 10%, its memory is mostly code, and this skill will find savings. If the peak is far higher, the memory goes on runtime state and caches, and this skill will not help. A hypervisor agent holding guest state is one such process; a database connection pool is another.
Install the code into one virtualenv or container image, at one version,
and do every measurement in it. If the image is rebuilt between runs, the
code you are measuring changes under you. Tag the image. If anything on
the host prunes images, keep a stopped container on the tag
(docker create --name <x>-pin <tag> true), and remove the container when
the work is done.
Inside a container, mount the helper by its real path, because a mounted symlink would dangle:
docker run --rm -v "$(readlink -f $HOME/bin/import-bloat):/im:ro" -v "$PWD/roles.txt:/roles.txt:ro" \
IMAGE python3 -I /im roles /roles.txt > before.jsonlRun roles, probe and marginal with the environment's own
interpreter, not through the script's #!/usr/bin/env python3, which
would find the host's Python and none of the code. Below, $PY is that
interpreter, such as venv/bin/python or the container's python3.
report and compare only read JSON, so any Python will do.
Always use python -I. Anything imported before the probe starts, by a
sitecustomize, a .pth file or PYTHONPATH, would not be attributed.
roles starts a fresh -I interpreter for each role itself.
One line per process type: a name, then the modules it imports, in order.
# ROLE MODULE [MODULE ...]
python-baseline sys
api-server myapp.wsgi_app myapp.api.v2 myapp.middleware.auth
worker call:myapp.objects.register_all myapp.cmd.worker myapp.drivers.libvirt
- Include the runtime plugins. Services load drivers through stevedore,
entry points or
importutilsafter start-up. An entry point alone misses them. - Reproduce what the entry point does before importing. A
call:pkg.mod.fnentry runs that function, and literal arguments are allowed (call:nova.monkey_patch.patch(backend='threading'), with no spaces). nova's API entry points pick the threading backend first, which keeps eventlet out of the process. Probing only their app factories loaded eventlet and overstated them by 8 MB each. - Skip modules that build the application at import time and need
config files (uWSGI
wsgimodules). Import what their factory imports instead. - A
python-baseline sysrole gives the interpreter's own floor.
$PY -I $HOME/bin/import-bloat roles roles.txt > before.jsonl
$HOME/bin/import-bloat report before.jsonl # per role: anon RSS, modules, errors; then a package table
$HOME/bin/import-bloat report before.jsonl --packages eventlet,sqlalchemy,pecanA row marked ERROR imported only part of its role. Fix the roles line
before trusting that row. Then look for a package in a role that has no
reason to call it. These kinds have paid off:
- A database or web stack in an agent that has no database: sqlalchemy, oslo.db, alembic, pecan, mako.
- Host-level libraries in an API server: pyroute2, os_ken, privileged helpers.
- Optional features imported unconditionally: SAML federation, database migrations that run only when a flag is set, one optional middleware.
- A concurrency library the service has stopped using, usually brought in by a library rather than by the service.
- A whole library loaded for a few constants: a packet-parsing library imported for an ethertype table.
$HOME/bin/import-bloat report before.jsonl --chain eventlet
# worker eventlet <- futurist._utils <- futurist <- oslo_messaging... <- myapp.cmd.workerA chain reads innermost first: the package, then the modules that were
running when it first loaded, back to the role's entry point. It comes
from the stack at the moment of the import, so lazy imports, plugin
loaders and importlib.import_module all show up. A library that only
checks whether a package is installed, with importlib.util.find_spec(),
is not blamed for a later load.
Read the module that does the import, and confirm that the process can never reach the code that uses the package. Something the process does use at runtime does not count, however expensive it is.
The chain shows only the first site, and there is almost always a second. The cut that matters is the last one. Map them all before you write a patch:
- Copy the source trees involved into a scratch directory.
- Make the crudest edit that removes the first site, and keep the module importable.
- Probe again with
--pathpointing at the scratch trees (or install them over the environment), and read the next chain. - Repeat until the package is gone from the role, or the next site is in code you cannot change.
The result is a table of sites: project, file, what it uses the package for, the real fix, and whether that fix changes behaviour. In OpenStack, eventlet reached neutron through futurist, oslo.utils, oslo.messaging, oslo.service, oslo.privsep, ovsdbapp and python-ovs. Fixing futurist, the obvious site, saved nothing on its own. Write the fixes as a chain, and say in each commit message that it saves nothing alone, naming the others.
$PY -I $HOME/bin/import-bloat marginal oslo_config.cfg,requests,cryptography.x509 eventletmarginal imports a base set, then the target, and reports what the
target added. The base must hold what the process loads anyway. Imported
on its own, eventlet measures 22.6 MB; on top of requests and
cryptography, which every service loads, it measures 11 MB. The 11 MB is
the saving. A package's marginal cost is what removing the last import
site would save, not what any single site saves.
The usual fix is to move the import into the function that uses it. Mark
it the way the project already marks such imports; search for
import-outside-toplevel or C0415. Other patterns that worked:
- Look in
sys.modulesinstead of importing when the question is "is this already in use?". For example, "has eventlet monkey-patched this process?" needs no import when eventlet has not been loaded. - Use
importlib.util.find_spec()for "is it installed?", and catchImportError: some projects install import hooks that raise it fromfind_spec. - Select a backend through the project's hook rather than letting a default import the heavy one.
- Move a small helper out of a heavy module, and leave an alias at the old name for out-of-tree callers.
- Spell out a few constants rather than importing a module for them, with a test that they still match the originals.
- Watch for import-time side effects that move with the import. A module that registers objects, options or signal handlers when imported now does so later or not at all. Find who relies on that, and say so in the commit message.
Without a test, the next unrelated import brings the package back. The test process has usually imported most of the project already, so run the check in a new interpreter:
def test_agent_does_not_load_the_db_layer(self):
code = 'import sys, myapp.agent; print("sqlalchemy" in sys.modules)'
out = subprocess.check_output([sys.executable, '-c', code], text=True)
self.assertEqual('False', out.strip())When a dependency still loads the package for its own reasons (a fix in another project that has not merged yet), that test cannot pass yet. Add a second test that checks what your modules hold: no module of yours should have a module-level attribute that is the forbidden module or one of its submodules. That test passes as soon as your fix lands. Skip the first test while the dependency still loads the package, and say why in the skip message.
Prove that each test fails without the fix: restore the original source
from a copy, run the test, put the fix back, and run it again. Use the
mutation-check skill for anything with more than one moving part.
Measure a patch by installing the patched tree over the fixed environment and probing the same roles:
pip install --no-deps --no-build-isolation /path/to/patched/tree # in a copy of the env
$PY -I $HOME/bin/import-bloat roles --roles 'agent|api' roles.txt > after.jsonl
$HOME/bin/import-bloat compare before.jsonl after.jsonl after-without-x.jsonl --packages eventlet,sqlalchemy- Compare every run with the same before run.
comparedoes that. A figure that subtracts from a different run's numbers is how mixed baselines get into commit messages. - Same environment, same roles, same interpreter. A run against an unmodified tree should match the before run to within 1 to 2 MB. That is the noise in every saving you quote.
- pbr projects install their files from git. Mark a copied tree safe
(
git config --global --add safe.directory '*') or a project whose packaging names only its top-level package installs without its subpackages, with no error. SetPBR_VERSIONif there is no git history. - Measure the whole chain together, and give a column per partial set where some fixes are in other projects or not merged yet. The full chain is the claim; the partial columns say what lands when.
- Quote what the probe shows, before and after, in the commit message.
- Per process, not per host. For a per-host figure, multiply each role's saving by its process count, from the host's process list.
- Never add up per-package estimates. Packages share dependencies. The OpenStack scan's first estimate, about 0.5 to 0.85 GB per node, was a sum like that. It was withdrawn once the chain was measured as a whole.
- RSS counts copy-on-write pages in both parent and forked child, so summing RSS across a forked worker pool overstates the shared part.
- The saved pages are mostly cold. Under pressure they are swapped out first. Removing them cuts swap volume, but that alone does not prove it cuts swap thrash.
- tracemalloc cannot attribute this memory. It charges code objects to
importlib, which ends up with about half of everything an import allocates. Usemarginal.