Test Isolation
Parallel tests share a machine, and often a service process. Test isolation keeps a test from seeing state that another test created, whether that test runs at the same time on another worker or ran earlier on the same worker. DAGZ isolates tests per worker in five areas: databases, in-process state, shared resources, ports and warnings.
Databases and message brokers
Each worker reaches its own database, vhost or keyspace. DAGZ rewrites the name in driver-level connect calls, so calling code is unchanged. Packaged drivers cover Postgres, MySQL, Redis, RabbitMQ, MongoDB, Cassandra, ClickHouse and Elasticsearch. See Parallelizing DB tests.
In-process state
A service process that serves several workers keeps one copy of its singletons, caches and queues, so a test sees what
another worker's requests wrote there. The dagz.isolate modules below give each worker its own copy. A call reaches
the copy of the worker whose test sent the request. The main worker, and threads that serve no test, use the main copy:
the one the service builds at startup.
Isolate the state from your dagz_autoload.py init(). Isolation takes effect when the state's module is imported:
| Function | Each worker gets |
|---|---|
classes.isolate_class_instances("module:Class", build, on_reset, *, reset_in_main_workers, soft_reset) | its own instance behind every instance of the class |
module_globals.isolate_module_global("module:global", "module:ctor", build, on_reset) | its own object behind the global the ctor sets |
fields.isolate_class_fields("module:Class.field", *, build, on_reset, reset_in_main_workers, soft_reset) | its own value of the field |
fields.isolate_instance_fields(obj, *fields, build, on_reset, reset_in_main_workers, soft_reset) | its own value of each listed field of obj alone |
work_lists.isolate_work_list("module:Class") | its own items in the list the class makes |
A worker's copy is built on its first use: by build, else from the constructor arguments (classes) or as a deep copy
of the main copy (globals and fields). classes.get_main_isolated_instance(obj),
module_globals.get_main_isolated_global(obj) and fields.get_main_isolated_field_value(obj, field) return the main
copy, and classes.get_isolated_instance_ctor_args(obj) the arguments an isolated class's instance was constructed
with. Pass the class itself in place of its target to isolate a class object the caller already holds, at once:
classes.isolate_class_instances(cls, build=..., on_reset=..., reset_in_main_workers=...). A field's build with a
module parameter also gets the field's module, to build the value from the module's names without importing them in
your autoload: build=lambda owner, module: module.Cache(owner.session).
dagz isolates the cachetools caches itself: every LRUCache, TTLCache, TLRUCache, FIFOCache, LFUCache,
RRCache and MRUCache a service builds, at module level, on an object or inside @cached, gives each worker its own
empty cache from the same constructor arguments. Each soft reset drops a cache code uses directly, the main worker's
included; a cache given to @cachetools.cached survives soft resets and a hard reset drops it, as
functools.lru_cache. In a pytest process, the same resets clear the cache itself. A plain cachetools.Cache and a
subclass with its own __init__ stay shared. A @cachetools.cached function (and every cachetools.func decorator,
which builds on it) computes a missing entry under a cache span, as functools.lru_cache does, so each test that reads
the entry depends on the code that computed it; a plain dict given to it, as cachetools.func's with maxsize=None, is
replaced by an isolated cache, one for all the functions given the same dict and seeded from the dict's entries at the
first one's decoration. Later writes to the dict itself, and its clear(), would not reach those functions' entries:
clear or update the function's cache attribute (or call its cache_clear()) instead.
At the end of each test's teardown, dagz soft-resets every service the test's worker reached: the service drops that
worker's copies and calls on_reset for each. A service that restarts a component mid-test calls
TASK_STATE_TRACKER.reset(True) (from dagz.isolate.task_state_tracker) itself, a hard reset, under the test's
request. A soft reset (is_hard=False) keeps heavy caches such as functools.lru_cache; a hard reset drops them too.
A copy isolated with soft_reset=False (default True) survives soft resets and is dropped only by a hard reset, for
state a test changes only by restarting its component. TASK_STATE_TRACKER.add_reset_callback(callback, soft_reset)
adds a callback of your own, run on every reset when soft_reset, else on hard resets only. The main copy survives a reset,
except for classes and fields isolated with reset_in_main_workers=True; such a field needs a build, and the main
copy's next read builds it. A reset that drops added work items raises DagzDroppedWorkWarning. drain_batches() on a
work list yields one batch per worker, each run as a request of the test that added it.
# dagz_autoload.py
from dagz.isolate.classes import isolate_class_instances
from dagz.isolate.module_globals import get_main_isolated_global, isolate_module_global
from dagz.isolate.work_lists import isolate_work_list
def copy_main_config(config):
main = get_main_isolated_global(config)
return type(main)(main.dump())
def init(in_pytest):
isolate_module_global("myapp.config:_config", "myapp.config:init", build=copy_main_config)
isolate_class_instances("myapp.pool:Pool", reset_in_main_workers=False)
isolate_work_list("myapp.jobs:JobList")
Isolation takes effect in service processes DAGZ runs as apps, and does nothing in pytest processes.
Shared resources
Some tests must touch state that every worker shares: a database by its literal name, or the database server itself.
Mark them @pytest.mark.dagz_main_worker or @pytest.mark.dagz_node_mutex, as described in
Tests that can't be rerouted.
The guards in dagz.isolate.guards find tests that need a marker. Call them from your dagz_autoload.py init(). Each
patches a function so that every call checks the current test's marker:
| Guard | A call from a test without the marker |
|---|---|
assert_main_worker_at("module:function") | raises DagzError |
assert_node_mutex_at("module:function") | raises DagzError |
noop_unless_main_worker_at("module:function") | logs and returns None without running the function |
noop_unless_node_mutex_at("module:function") | logs and returns None without running the function |
assert_main_worker_at and noop_unless_node_mutex_at also take the target as (module_path, func_name).
bypass_subprocess_hooks_at("module:function", *, with_dagz) patches a function whose subprocesses must not belong
to the current test, such as a worker pool that outlives it. It applies the dagz.integ.subproc.bypass_subprocess_hooks
context manager to every call of the function. The subprocesses run with DAGZ enabled when with_dagz is True.
Patch an app's periodic task serving per-worker state with run_per_test_worker_at("module:function"), for
example a timer concluding the events it buffered. Started outside any test, the task would otherwise run
only as the main worker, and the other workers' state would wait. With the patch, a call no test sent would run once as
each worker of the app's node, the main one first; a test's call would run once, as that test's worker.
# dagz_autoload.py
from dagz.isolate.guards import assert_main_worker_at, noop_unless_node_mutex_at
def init(in_pytest):
assert_main_worker_at("myapp.workers.native", "NativeWorker._run_binary")
noop_unless_node_mutex_at("myapp.db", "reset_master")
All guards are no-ops when DAGZ is not active, and when --dagz-disable-sensors disables its sensors.
Ports
dagz.isolate.ports.ParallelPortManager gives each worker its own free port for a named service, picked at random in
the range 10000-32767 on 127.0.0.1.
from dagz.isolate.ports import ParallelPortManager
def test_service():
port = ParallelPortManager().get_port("my_service", stable=True)
With stable=True, the port stays the same for the name during the test and in its subprocesses, through the
PARALLEL_TEST_PORT_<name> environment variable. Stable ports are released when the next test starts.
Warnings
A service that serves several workers raises warnings on behalf of the tests that called it, and keeps running work
they started. dagz.isolate.task_state_tracker.TASK_STATE_TRACKER tracks both per worker in the service process. A
pytest process tracks no work, so work a test leaves running in its own process raises no warning.
A reset turns the work the test left queued or running into a DagzPendingWorkWarning and forgets that work. The
service returns the warnings raised for the test to dagz with the soft reset at the end of the test's teardown, and dagz
raises them again in the test, tagged with the service's command line, where pytest's -W filters decide whether they
fail it.
Filter the warnings of a failed soft reset by their classes: dagz.sensor.errors.DagzResetFailedWarning, a soft reset
that raised, in the test's own process or in a service; dagz.sensor.errors.DagzUnresponsiveAppWarning, a service that
missed its soft reset's deadline, its link closed and its issues for the test dropped.
A module import that starts during a request runs the module's top-level code as the service's startup does: the files, databases and connections it opens, the work it starts and the warnings it raises belong to the service, not to the test whose request reached the import first.
Existing autoloads keep working: dagz.integ.parallel_db still exports assert_main_worker_at and
noop_unless_node_mutex_at, and dagz.integ.parallel_port_manager still exports ParallelPortManager.