test(pytest): isolate parallel worker databases

This commit is contained in:
2026-10-12 23:19:30 +03:00
parent 2608bdbdf2
commit 1f29d2cdba
3 changed files with 827 additions and 7 deletions

View File

@@ -1,8 +1,9 @@
# #region Test.PytestEarly.IntegrationDatabase [C:5] [TYPE Module] [SEMANTICS test,pytest,early-hook,postgres,testcontainers,alembic]
# @defgroup Test.PytestEarly Prepare explicitly requested integration databases before application imports.
# @PRE When --run-integration is requested, Docker and Testcontainers are available.
# @POST With --run-integration, DATABASE_URL points at a temporary PostgreSQL database migrated to head before conftest loading.
# @INVARIANT Integration application imports wait until the requested integration DATABASE_URL is installed.
# @defgroup Test.PytestEarly Prepare explicitly requested integration or isolated worker databases before application imports.
# @PRE Integration mode has Docker/Testcontainers, or isolated-worker mode has a private PG descriptor and xdist count.
# @POST Integration DB or each isolated worker DB is migrated before conftest loading; isolated workers have private storage.
# @INVARIANT Ordinary pytest keeps its configured serial SQLite behavior; isolated mode refuses non-PostgreSQL input.
# @INVARIANT A worker database is dropped only after its owner PID exits, owner comment matches, and connections reach zero.
# @INVARIANT Standard pytest uses the configured official timeout plugin without starting or registering a project watchdog.
# @RATIONALE pytest_load_initial_conftests is the earliest supported hook for a command-line plugin.
# It runs before root conftest.py, whose pytest_plugins import the integration fixture modules.
@@ -13,18 +14,52 @@
from __future__ import annotations
import os
import json
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import uuid
_container = None
_database_name: str | None = None
_admin_url: str | None = None
_parallel_pg_context: dict | None = None
_worker_hook_pid: int | None = None
_PARALLEL_PG_OPTION = "--run-isolated-pg-workers"
_PARALLEL_PG_RUN_ENV = "PYTEST_WORKER_PG_RUN_ID"
_PARALLEL_PG_MANIFEST_ENV = "PYTEST_WORKER_PG_RUN_MANIFEST"
_PARALLEL_PG_STORAGE_ENV = "PYTEST_WORKER_PG_STORAGE_ROOT"
_PARALLEL_PG_OWNER_PREFIX = "ss-tools-pytest-worker-pg:v1:"
_WORKER_NAME_RE = re.compile(r"^gw(?:0|[1-9][0-9]*)$")
_DATABASE_NAME_RE = re.compile(r"^ss_test_[0-9a-f]{32}_gw(?:0|[1-9][0-9]*)$")
_MAX_WORKERS = 16
_DB_CONNECT_TIMEOUT_SECONDS = 10
_DB_STATEMENT_TIMEOUT_MS = 60_000
_MIGRATION_TIMEOUT_SECONDS = 180
_WORKER_EXIT_TIMEOUT_SECONDS = 30
def pytest_load_initial_conftests(early_config, parser, args): # noqa: ARG001
"""Install the migrated PostgreSQL URL before any project conftest loads."""
"""Install requested databases before application or test conftests import."""
if _PARALLEL_PG_RUN_ENV in os.environ:
if _PARALLEL_PG_OPTION in args:
_bootstrap_parallel_pg_worker(args)
return
else:
raise RuntimeError("PYTEST_WORKER_PG_NESTED_OR_OPT_IN_MISSING") from None
if _PARALLEL_PG_OPTION in args:
if "--run-integration" in args:
raise RuntimeError("PYTEST_WORKER_PG_INTEGRATION_MODE_CONFLICT") from None
_bootstrap_parallel_pg_controller(early_config, args)
return
if "--run-integration" not in args:
return
@@ -72,8 +107,584 @@ def pytest_load_initial_conftests(early_config, parser, args): # noqa: ARG001
)
def pytest_addoption(parser):
"""Expose the isolated PG opt-in; ordinary pytest remains unchanged."""
parser.addoption(
_PARALLEL_PG_OPTION,
action="store_true",
default=False,
help="Use fresh, run-owned PostgreSQL databases with pytest-xdist workers.",
)
def pytest_configure(config):
"""Set xdist's UID before session start and reject unbound workers."""
if not config.getoption(_PARALLEL_PG_OPTION, default=False):
return
context = _parallel_pg_context
if context is None:
raise RuntimeError("PYTEST_WORKER_PG_BOOTSTRAP_MISSING") from None
if context["role"] == "worker":
return
if config.getoption("numprocesses") != context["worker_count"]:
raise RuntimeError("PYTEST_WORKER_PG_XDIST_COUNT_MISMATCH") from None
configured_uid = getattr(config.option, "testrunuid", None)
if configured_uid not in (None, context["run_id"]):
raise RuntimeError("PYTEST_WORKER_PG_RUN_UID_MISMATCH") from None
config.option.testrunuid = context["run_id"]
def pytest_configure_node(node):
context = _parallel_pg_context
if context is None or context["role"] != "controller":
return
worker_id = node.workerinput.get("workerid")
if worker_id not in context["expected_workers"]:
raise RuntimeError("PYTEST_WORKER_PG_UNKNOWN_WORKER") from None
if worker_id in context["started_workers"]:
raise RuntimeError("PYTEST_WORKER_PG_DUPLICATE_WORKER") from None
context["started_workers"].add(worker_id)
def pytest_testnodedown(node, error): # noqa: ARG001
"""Record the xdist event; cleanup independently confirms PID exit."""
context = _parallel_pg_context
if context is None or context["role"] != "controller":
return
worker_id = getattr(node, "workerinput", {}).get("workerid")
if worker_id not in context["started_workers"]:
context["cleanup_refusal"] = "PYTEST_WORKER_PG_UNREGISTERED_NODE_EXIT"
else:
context["stopped_workers"].add(worker_id)
def _pytest_unconfigure_parallel(config):
context = _parallel_pg_context
if context is None or context["role"] != "controller":
return
try:
allow_unstarted = (
context["started_workers"] != context["expected_workers"]
and context["started_workers"] == context["stopped_workers"]
)
_cleanup_parallel_pg(context, allow_unstarted=allow_unstarted)
except Exception as exc: # fail the run if owned resources cannot be safely reclaimed
session = getattr(config, "_session", None)
if session is not None:
try:
import pytest
session.exitstatus = pytest.ExitCode.INTERNAL_ERROR
except Exception:
pass
_record_cleanup_refusal(context, _safe_error_code(exc))
def _bootstrap_parallel_pg_controller(config, args):
global _parallel_pg_context
if _parallel_pg_context is not None:
raise RuntimeError("PYTEST_WORKER_PG_BOOTSTRAP_REPEATED") from None
if any(name in os.environ for name in (
"PYTEST_XDIST_WORKER", "PYTEST_XDIST_TESTRUNUID", "PYTEST_XDIST_WORKER_COUNT",
)):
raise RuntimeError("PYTEST_WORKER_PG_CONTROLLER_HAS_WORKER_IDENTITY") from None
worker_count = _parse_parallel_worker_count(config, args)
if "--basetemp" in args or any(arg.startswith("--basetemp=") for arg in args):
raise RuntimeError("PYTEST_WORKER_PG_BASETEMP_OVERRIDE_REFUSED") from None
descriptor_path = _private_path_from_env("PG_CONSUMER_CONNECTION_FILE")
descriptor = _read_private_json(descriptor_path)
_validate_source_descriptor(descriptor_path, descriptor)
_validate_database_url(os.environ.get("DATABASE_URL"), descriptor)
run_id = uuid.uuid4().hex
supplied_uid = getattr(config.option, "testrunuid", None)
if supplied_uid not in (None, run_id):
raise RuntimeError("PYTEST_WORKER_PG_RUN_UID_MISMATCH") from None
config.option.testrunuid = run_id
expected_workers = {f"gw{index}" for index in range(worker_count)}
run_root = Path(tempfile.mkdtemp(prefix=f"ss-tools-pytest-pg-{run_id}-", dir="/tmp"))
os.chmod(run_root, 0o700)
_verify_private_directory(run_root)
for name in ("descriptors", "leases", "storage", "workers"):
(run_root / name).mkdir(mode=0o700)
_verify_private_directory(run_root / name)
workers = {}
for worker_id in sorted(expected_workers):
database = f"ss_test_{run_id}_{worker_id}"
if not _DATABASE_NAME_RE.fullmatch(database):
raise RuntimeError("PYTEST_WORKER_PG_DATABASE_NAME_INVALID") from None
worker_descriptor = dict(descriptor)
worker_descriptor["database"] = database
descriptor_file = run_root / "descriptors" / f"{worker_id}.json"
_write_json_exclusive(descriptor_file, worker_descriptor)
storage = run_root / "storage" / worker_id
worker_tmp = run_root / "workers" / worker_id
storage.mkdir(mode=0o700)
worker_tmp.mkdir(mode=0o700)
workers[worker_id] = {
"database": database,
"descriptor": str(descriptor_file),
"owner_marker": f"{_PARALLEL_PG_OWNER_PREFIX}{run_id}:{os.getpid()}:{worker_id}",
"storage": str(storage),
"tmp": str(worker_tmp),
}
manifest = {
"schema_version": 1,
"state": "preparing",
"run_id": run_id,
"controller_pid": os.getpid(),
"controller_start_ticks": _process_start_ticks(os.getpid()),
"source_database": descriptor["database"],
"worker_count": worker_count,
"workers": workers,
}
manifest_path = run_root / "run-manifest.json"
_write_json_exclusive(manifest_path, manifest)
context = {
"role": "controller",
"run_id": run_id,
"run_root": run_root,
"manifest_path": manifest_path,
"manifest": manifest,
"source_descriptor_path": descriptor_path,
"worker_count": worker_count,
"expected_workers": expected_workers,
"started_workers": set(),
"stopped_workers": set(),
"cleanup_refusal": None,
}
_parallel_pg_context = context
try:
_create_and_migrate_worker_databases(context)
manifest["state"] = "ready"
_replace_private_json(manifest_path, manifest)
except Exception as exc:
try:
_cleanup_parallel_pg(context, allow_unstarted=True)
except Exception:
pass
raise RuntimeError(_safe_error_code(exc)) from None
first = workers["gw0"]
first_descriptor = _read_private_json(Path(first["descriptor"]))
os.environ["DATABASE_URL"] = _database_url_from_descriptor(first_descriptor)
os.environ["PG_CONSUMER_CONNECTION_FILE"] = first["descriptor"]
os.environ[_PARALLEL_PG_RUN_ENV] = run_id
os.environ[_PARALLEL_PG_MANIFEST_ENV] = str(manifest_path)
config.option.basetemp = str(run_root / "pytest-basetemp")
def _bootstrap_parallel_pg_worker(args): # noqa: ARG001
global _parallel_pg_context, _worker_hook_pid
current_pid = os.getpid()
if _worker_hook_pid == current_pid or _parallel_pg_context is not None:
raise RuntimeError("PYTEST_WORKER_PG_BOOTSTRAP_REPEATED") from None
run_id = os.environ.get(_PARALLEL_PG_RUN_ENV, "")
manifest_path = _private_path_from_env(_PARALLEL_PG_MANIFEST_ENV)
manifest = _read_private_json(manifest_path)
if (not re.fullmatch(r"[0-9a-f]{32}", run_id)
or manifest.get("schema_version") != 1
or manifest.get("state") != "ready"
or manifest.get("run_id") != run_id):
raise RuntimeError("PYTEST_WORKER_PG_MANIFEST_INVALID") from None
worker_id = os.environ.get("PYTEST_XDIST_WORKER", "")
worker_count = os.environ.get("PYTEST_XDIST_WORKER_COUNT")
_validate_worker_context(manifest, run_id, worker_id, worker_count)
worker_data = manifest["workers"][worker_id]
descriptor_path = Path(worker_data["descriptor"])
descriptor = _read_private_json(descriptor_path)
_validate_worker_descriptor_binding(worker_data, descriptor)
expected_marker = (
f"{_PARALLEL_PG_OWNER_PREFIX}{run_id}:{manifest['controller_pid']}:{worker_id}"
)
if worker_data.get("owner_marker") != expected_marker:
raise RuntimeError("PYTEST_WORKER_PG_OWNER_MARKER_INVALID") from None
lease = {
"run_id": run_id,
"worker_id": worker_id,
"database": worker_data["database"],
"pid": current_pid,
"process_start_ticks": _process_start_ticks(current_pid),
}
lease_path = manifest_path.parent / "leases" / f"{worker_id}.json"
_write_json_exclusive(lease_path, lease)
storage_root = Path(worker_data["storage"])
temp_root = Path(worker_data["tmp"])
_verify_private_directory(storage_root)
_verify_private_directory(temp_root)
_write_json_exclusive(storage_root / ".pytest-worker-owner.json", lease)
os.environ["DATABASE_URL"] = _database_url_from_descriptor(descriptor)
os.environ["PG_CONSUMER_CONNECTION_FILE"] = str(descriptor_path)
os.environ[_PARALLEL_PG_STORAGE_ENV] = str(storage_root)
os.environ["TMPDIR"] = str(temp_root)
tempfile.tempdir = None
_worker_hook_pid = current_pid
_parallel_pg_context = {
"role": "worker", "run_id": run_id, "worker_id": worker_id,
"lease_path": lease_path, "storage_root": storage_root,
}
def _parse_parallel_worker_count(config, args):
values = []
restarts = []
index = 0
while index < len(args):
arg = args[index]
if arg in ("-n", "--numprocesses"):
if index + 1 >= len(args):
raise RuntimeError("PYTEST_WORKER_PG_XDIST_COUNT_MISSING") from None
values.append(args[index + 1])
index += 2
continue
if arg.startswith(("-n=", "--numprocesses=")):
values.append(arg.split("=", 1)[1])
if arg == "--max-worker-restart":
if index + 1 >= len(args):
raise RuntimeError("PYTEST_WORKER_PG_RESTART_VALUE_MISSING") from None
restarts.append(args[index + 1])
index += 2
continue
if arg.startswith("--max-worker-restart="):
restarts.append(arg.split("=", 1)[1])
index += 1
if len(values) != 1:
raise RuntimeError("PYTEST_WORKER_PG_XDIST_COUNT_REQUIRED") from None
if values[0] == "auto":
worker_count = config.hook.pytest_xdist_auto_num_workers(config=config)
elif values[0].isdigit():
worker_count = int(values[0])
else:
raise RuntimeError("PYTEST_WORKER_PG_XDIST_COUNT_INVALID") from None
if (not isinstance(worker_count, int) or isinstance(worker_count, bool)
or not 1 <= worker_count <= _MAX_WORKERS):
raise RuntimeError("PYTEST_WORKER_PG_WORKER_COUNT_OUT_OF_RANGE") from None
if restarts != ["0"]:
raise RuntimeError("PYTEST_WORKER_PG_RESTARTS_MUST_BE_DISABLED") from None
if "--dist=each" in args or any(
args[i] == "each" and i and args[i - 1] == "--dist" for i in range(len(args))
):
raise RuntimeError("PYTEST_WORKER_PG_DIST_EACH_REFUSED") from None
config.option.numprocesses = worker_count
return worker_count
def _validate_worker_context(manifest, run_id, worker_id, worker_count):
count = manifest.get("worker_count")
workers = manifest.get("workers")
if (not isinstance(count, int) or isinstance(count, bool)
or not 1 <= count <= _MAX_WORKERS or not isinstance(workers, dict)):
raise RuntimeError("PYTEST_WORKER_PG_WORKER_MAP_INVALID") from None
expected = {f"gw{index}" for index in range(count)}
if (manifest.get("run_id") != run_id
or os.environ.get("PYTEST_XDIST_TESTRUNUID") != run_id
or worker_id not in expected
or worker_count != str(count)
or set(workers) != expected):
raise RuntimeError("PYTEST_WORKER_PG_WORKER_MAP_INVALID") from None
def _validate_worker_descriptor_binding(worker_data, descriptor):
database = descriptor.get("database") if isinstance(descriptor, dict) else None
if (not isinstance(worker_data, dict) or database != worker_data.get("database")
or not isinstance(database, str) or not _DATABASE_NAME_RE.fullmatch(database)):
raise RuntimeError("PYTEST_WORKER_PG_DESCRIPTOR_BINDING_INVALID") from None
def _validate_worker_lease(lease, run_id, worker_id, database):
if (lease.get("run_id") != run_id or lease.get("worker_id") != worker_id
or lease.get("database") != database or not isinstance(lease.get("pid"), int)
or not isinstance(lease.get("process_start_ticks"), int)):
raise RuntimeError("PYTEST_WORKER_PG_WORKER_LEASE_INVALID") from None
def _validate_source_descriptor(descriptor_path, descriptor):
if not isinstance(descriptor, dict):
raise RuntimeError("PYTEST_WORKER_PG_DESCRIPTOR_INVALID") from None
_verify_private_file(descriptor_path)
required = ("host", "port", "username", "password", "database")
if any(descriptor.get(key) in (None, "") for key in required):
raise RuntimeError("PYTEST_WORKER_PG_DESCRIPTOR_INVALID") from None
def _validate_database_url(raw_url, descriptor):
if not isinstance(raw_url, str) or not raw_url:
raise RuntimeError("PYTEST_WORKER_PG_DATABASE_URL_REQUIRED") from None
try:
from sqlalchemy.engine import make_url
parsed = make_url(raw_url)
except Exception:
raise RuntimeError("PYTEST_WORKER_PG_DATABASE_URL_INVALID") from None
if (parsed.get_backend_name() != "postgresql"
or parsed.username != descriptor.get("username")
or parsed.password != descriptor.get("password")
or parsed.host != descriptor.get("host")
or parsed.port != descriptor.get("port")
or parsed.database != descriptor.get("database")):
raise RuntimeError("PYTEST_WORKER_PG_DATABASE_URL_MISMATCH") from None
def _database_url_from_descriptor(descriptor):
try:
from sqlalchemy.engine import URL
return URL.create(
"postgresql+psycopg2", username=descriptor["username"], password=descriptor["password"],
host=descriptor["host"], port=descriptor["port"], database=descriptor["database"],
query={"connect_timeout": str(_DB_CONNECT_TIMEOUT_SECONDS)},
).render_as_string(hide_password=False)
except Exception:
raise RuntimeError("PYTEST_WORKER_PG_DESCRIPTOR_INVALID") from None
def _create_and_migrate_worker_databases(context):
import psycopg2
from psycopg2 import sql
descriptor = _read_private_json(context["source_descriptor_path"])
admin = psycopg2.connect(
host=descriptor["host"], port=descriptor["port"], user=descriptor["username"],
password=descriptor["password"], dbname=descriptor["database"],
connect_timeout=_DB_CONNECT_TIMEOUT_SECONDS,
)
admin.autocommit = True
try:
with admin.cursor() as cursor:
cursor.execute(
"SELECT current_database(), r.rolcreatedb, r.rolsuper "
"FROM pg_roles AS r WHERE r.rolname = current_user"
)
db_name, can_create, is_super = cursor.fetchone()
if db_name != descriptor["database"] or not (can_create or is_super):
raise RuntimeError("PYTEST_WORKER_PG_ADMIN_AUTHORITY_INVALID") from None
cursor.execute(f"SET statement_timeout = {_DB_STATEMENT_TIMEOUT_MS}")
cursor.execute("SET lock_timeout = 10000")
for worker_id, worker in context["manifest"]["workers"].items():
cursor.execute("SELECT 1 FROM pg_database WHERE datname = %s", (worker["database"],))
if cursor.fetchone() is not None:
raise RuntimeError("PYTEST_WORKER_PG_DATABASE_NAME_ALREADY_EXISTS") from None
for worker_id, worker in context["manifest"]["workers"].items():
database = worker["database"]
cursor.execute(
sql.SQL("CREATE DATABASE {} OWNER {} TEMPLATE template0").format(
sql.Identifier(database), sql.Identifier(descriptor["username"]),
)
)
cursor.execute(
sql.SQL("COMMENT ON DATABASE {} IS {}").format(
sql.Identifier(database), sql.Literal(worker["owner_marker"]),
)
)
child = _read_private_json(Path(worker["descriptor"]))
env = os.environ.copy()
for name in (
"PYTEST_XDIST_WORKER", "PYTEST_XDIST_TESTRUNUID", "PYTEST_XDIST_WORKER_COUNT",
):
env.pop(name, None)
env["DATABASE_URL"] = _database_url_from_descriptor(child)
env["PG_CONSUMER_CONNECTION_FILE"] = worker["descriptor"]
env["PGOPTIONS"] = (
f"-c statement_timeout={_DB_STATEMENT_TIMEOUT_MS} -c lock_timeout=10000"
)
try:
subprocess.run(
[sys.executable, "-m", "alembic", "upgrade", "head"],
cwd=Path(__file__).resolve().parent, env=env, check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=_MIGRATION_TIMEOUT_SECONDS,
)
except subprocess.TimeoutExpired:
raise RuntimeError("PYTEST_WORKER_PG_MIGRATION_TIMEOUT") from None
finally:
admin.close()
def _cleanup_parallel_pg(context, *, allow_unstarted=False):
import psycopg2
from psycopg2 import sql
if context.get("cleanup_refusal"):
raise RuntimeError(context["cleanup_refusal"]) from None
if not allow_unstarted and (
context["started_workers"] != context["expected_workers"]
or context["started_workers"] != context["stopped_workers"]
):
raise RuntimeError("PYTEST_WORKER_PG_WORKERS_NOT_CONFIRMED_STOPPED") from None
manifest = _read_private_json(context["manifest_path"])
_verify_private_directory(context["run_root"])
if context["manifest_path"].parent != context["run_root"]:
raise RuntimeError("PYTEST_WORKER_PG_RUN_ROOT_MISMATCH") from None
if (manifest.get("run_id") != context["run_id"]
or manifest.get("controller_pid") != os.getpid()
or manifest.get("controller_start_ticks") != _process_start_ticks(os.getpid())):
raise RuntimeError("PYTEST_WORKER_PG_CONTROLLER_OWNERSHIP_MISMATCH") from None
for worker_id, worker in manifest["workers"].items():
lease_path = context["run_root"] / "leases" / f"{worker_id}.json"
if not lease_path.exists():
if worker_id in context["started_workers"]:
raise RuntimeError("PYTEST_WORKER_PG_WORKER_LEASE_MISSING") from None
continue
lease = _read_private_json(lease_path)
_validate_worker_lease(lease, context["run_id"], worker_id, worker["database"])
_wait_for_worker_exit(lease["pid"], lease["process_start_ticks"])
descriptor = _read_private_json(context["source_descriptor_path"])
admin = psycopg2.connect(
host=descriptor["host"], port=descriptor["port"], user=descriptor["username"],
password=descriptor["password"], dbname=descriptor["database"],
connect_timeout=_DB_CONNECT_TIMEOUT_SECONDS,
)
admin.autocommit = True
try:
with admin.cursor() as cursor:
cursor.execute(f"SET statement_timeout = {_DB_STATEMENT_TIMEOUT_MS}")
cursor.execute("SET lock_timeout = 10000")
owned = []
for worker_id, worker in manifest["workers"].items():
database = worker["database"]
if not _DATABASE_NAME_RE.fullmatch(database):
raise RuntimeError("PYTEST_WORKER_PG_CLEANUP_NAME_INVALID") from None
row = _wait_for_owned_database_idle(cursor, database, worker["owner_marker"])
if row is None:
if allow_unstarted:
continue
raise RuntimeError("PYTEST_WORKER_PG_DATABASE_MISSING") from None
owned.append(database)
for database in owned:
cursor.execute(sql.SQL("DROP DATABASE {}").format(sql.Identifier(database)))
finally:
admin.close()
shutil.rmtree(context["run_root"])
def _wait_for_worker_exit(pid, start_ticks):
deadline = time.monotonic() + _WORKER_EXIT_TIMEOUT_SECONDS
while _process_is_same(pid, start_ticks):
if time.monotonic() >= deadline:
raise RuntimeError("PYTEST_WORKER_PG_WORKER_EXIT_TIMEOUT") from None
time.sleep(0.1)
def _wait_for_owned_database_idle(cursor, database, owner_marker):
deadline = time.monotonic() + _WORKER_EXIT_TIMEOUT_SECONDS
while True:
cursor.execute(
"SELECT shobj_description(d.oid, 'pg_database'), "
"(SELECT count(*) FROM pg_stat_activity a WHERE a.datname=d.datname) "
"FROM pg_database d WHERE d.datname=%s", (database,),
)
row = cursor.fetchone()
if row is None:
return None
if row[0] != owner_marker:
raise RuntimeError("PYTEST_WORKER_PG_DATABASE_OWNER_MISMATCH") from None
if row[1] == 0:
return row
if time.monotonic() >= deadline:
raise RuntimeError("PYTEST_WORKER_PG_DATABASE_CONNECTIONS_REMAIN") from None
time.sleep(0.1)
def _process_start_ticks(pid):
try:
raw = Path(f"/proc/{int(pid)}/stat").read_text(encoding="ascii")
return int(raw[raw.rfind(")") + 2:].split()[19])
except (OSError, ValueError, IndexError, TypeError):
raise RuntimeError("PYTEST_WORKER_PG_PROCESS_IDENTITY_UNAVAILABLE") from None
def _process_is_same(pid, start_ticks):
try:
raw = Path(f"/proc/{int(pid)}/stat").read_text(encoding="ascii")
actual = int(raw[raw.rfind(")") + 2:].split()[19])
except FileNotFoundError:
return False
except (OSError, ValueError, IndexError, TypeError):
raise RuntimeError("PYTEST_WORKER_PG_PROCESS_IDENTITY_UNAVAILABLE") from None
return actual == int(start_ticks)
def _read_private_json(path):
path = Path(path)
if not path.is_absolute() or path.is_symlink():
raise RuntimeError("PYTEST_WORKER_PG_PRIVATE_PATH_INVALID") from None
_verify_private_file(path)
try:
with path.open("r", encoding="utf-8") as stream:
value = json.load(stream)
except (OSError, ValueError, TypeError):
raise RuntimeError("PYTEST_WORKER_PG_PRIVATE_JSON_INVALID") from None
if not isinstance(value, dict):
raise RuntimeError("PYTEST_WORKER_PG_PRIVATE_JSON_INVALID") from None
return value
def _private_path_from_env(name):
value = os.environ.get(name)
if not value or not Path(value).is_absolute():
raise RuntimeError("PYTEST_WORKER_PG_PRIVATE_PATH_REQUIRED") from None
return Path(value)
def _verify_private_file(path):
info = Path(path).lstat()
if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
or stat.S_IMODE(info.st_mode) != 0o600):
raise RuntimeError("PYTEST_WORKER_PG_PRIVATE_FILE_MODE_INVALID") from None
_verify_private_directory(Path(path).parent)
def _verify_private_directory(path):
info = Path(path).lstat()
if (not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid()
or stat.S_IMODE(info.st_mode) != 0o700):
raise RuntimeError("PYTEST_WORKER_PG_PRIVATE_DIRECTORY_MODE_INVALID") from None
def _write_json_exclusive(path, value):
encoded = json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + b"\n"
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
with os.fdopen(fd, "wb") as stream:
stream.write(encoded)
stream.flush()
os.fsync(stream.fileno())
def _replace_private_json(path, value):
path = Path(path)
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
_write_json_exclusive(temporary, value)
os.replace(temporary, path)
os.chmod(path, 0o600)
def _record_cleanup_refusal(context, code):
try:
manifest = _read_private_json(context["manifest_path"])
manifest["state"] = "cleanup_refused"
manifest["cleanup_error_code"] = code
_replace_private_json(context["manifest_path"], manifest)
except Exception:
pass
def _safe_error_code(exc):
value = str(exc)
if re.fullmatch(r"PYTEST_WORKER_PG_[A-Z0-9_]+", value):
return value
return "PYTEST_WORKER_PG_SETUP_OR_CLEANUP_FAILED"
def pytest_unconfigure(config): # noqa: ARG001
"""Drop the temporary database and stop the container after the test session."""
_pytest_unconfigure_parallel(config)
if _container is None:
return

View File

@@ -22,7 +22,10 @@
# Plain SQLite without FK — silently ignores FK violations, masks bugs.
# Always-on PostgresContainer — 5-10x slower, Docker dependency.
import os
import json
from pathlib import Path
import shutil
import stat
import subprocess
import sys
import tempfile
@@ -42,8 +45,8 @@ os.environ.setdefault("AUTH_SECRET_KEY", "test-secret-key-for-jwt-testing")
_TEST_DB_FILE = tempfile.NamedTemporaryFile(suffix="_ss_tools.db", delete=False)
_TEST_DB_PATH = _TEST_DB_FILE.name
_TEST_DB_FILE.close()
_WORKER_STORAGE_ROOT: Path | None = None
os.environ.setdefault("DATABASE_URL", f"sqlite:///{_TEST_DB_PATH}")
os.environ.setdefault("DATABASE_URL", f"sqlite:///{_TEST_DB_PATH}")
# ── FK enforcement on the global engine ──
@@ -144,6 +147,37 @@ def pytest_unconfigure(config):
os.unlink(_TEST_DB_PATH)
except Exception:
pass
_cleanup_isolated_worker_storage()
def _cleanup_isolated_worker_storage():
if _WORKER_STORAGE_ROOT is None:
return
marker_path = _WORKER_STORAGE_ROOT / ".pytest-worker-owner.json"
try:
marker_info = marker_path.lstat()
if (not stat.S_ISREG(marker_info.st_mode) or marker_info.st_uid != os.getuid()
or stat.S_IMODE(marker_info.st_mode) != 0o600):
raise RuntimeError("PYTEST_WORKER_PG_STORAGE_MARKER_INVALID")
marker = json.loads(marker_path.read_text(encoding="utf-8"))
expected = {
"run_id": os.environ.get("PYTEST_WORKER_PG_RUN_ID"),
"worker_id": os.environ.get("PYTEST_XDIST_WORKER"),
"pid": os.getpid(),
}
if any(marker.get(key) != value for key, value in expected.items()):
raise RuntimeError("PYTEST_WORKER_PG_STORAGE_OWNER_MISMATCH")
for child in _WORKER_STORAGE_ROOT.iterdir():
if child == marker_path:
continue
if child.is_symlink() or child.is_file():
child.unlink()
elif child.is_dir():
shutil.rmtree(child)
else:
raise RuntimeError("PYTEST_WORKER_PG_STORAGE_ENTRY_UNSUPPORTED")
except FileNotFoundError:
raise RuntimeError("PYTEST_WORKER_PG_STORAGE_MARKER_MISSING") from None
@pytest.fixture(scope="session", autouse=True)
@@ -167,11 +201,38 @@ def ensure_git_storage_dirs(ensure_db_tables):
that don't exist in the test environment. This fixture only patches the
Pydantic default so ConfigManager uses the database record when no config exists.
"""
global _WORKER_STORAGE_ROOT
import os
import tempfile
from src.models.storage import StorageConfig
test_root = tempfile.mkdtemp(prefix="ss_tools_test_storage_")
worker_storage = os.environ.get("PYTEST_WORKER_PG_STORAGE_ROOT")
if worker_storage:
test_root = Path(worker_storage)
manifest_path = Path(os.environ.get("PYTEST_WORKER_PG_RUN_MANIFEST", ""))
worker_id = os.environ.get("PYTEST_XDIST_WORKER", "")
run_id = os.environ.get("PYTEST_WORKER_PG_RUN_ID", "")
expected_root = manifest_path.parent / "storage" / worker_id
if (test_root != expected_root or test_root.is_symlink()
or not run_id or not worker_id.startswith("gw")):
raise RuntimeError("PYTEST_WORKER_PG_STORAGE_PATH_INVALID")
_WORKER_STORAGE_ROOT = test_root
marker_path = _WORKER_STORAGE_ROOT / ".pytest-worker-owner.json"
info = marker_path.lstat()
if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
or stat.S_IMODE(info.st_mode) != 0o600):
raise RuntimeError("PYTEST_WORKER_PG_STORAGE_MARKER_INVALID")
marker = json.loads(marker_path.read_text(encoding="utf-8"))
if (marker.get("run_id") != run_id
or marker.get("worker_id") != worker_id
or marker.get("pid") != os.getpid()):
raise RuntimeError("PYTEST_WORKER_PG_STORAGE_OWNER_MISMATCH")
root_info = test_root.lstat()
if (not stat.S_ISDIR(root_info.st_mode) or root_info.st_uid != os.getuid()
or stat.S_IMODE(root_info.st_mode) != 0o700):
raise RuntimeError("PYTEST_WORKER_PG_STORAGE_DIRECTORY_INVALID")
else:
test_root = Path(tempfile.mkdtemp(prefix="ss_tools_test_storage_"))
test_repos = os.path.join(test_root, "repositories")
os.makedirs(test_repos, exist_ok=True)

View File

@@ -0,0 +1,148 @@
# #region Test.PytestWorkerIsolation [C:2] [TYPE Module] [SEMANTICS pytest,xdist,postgres,ownership]
# @BRIEF Verify xdist worker identity is explicit, scheduler-independent, and run-owned.
# @RELATION BINDS_TO -> [Test.PytestEarly.IntegrationDatabase]
# @TEST_EDGE: serial_without_identity -> Typed refusal rather than an unverified pass
# @TEST_EDGE: foreign_or_mismatched_worker -> Reject before database use
# @TEST_EDGE: invalid_descriptor_or_lease -> Reject before accepting worker ownership
from __future__ import annotations
import json
import os
from pathlib import Path
import stat
from types import SimpleNamespace
import pytest
from sqlalchemy import text
import pytest_early
from src.core.database import engine
def test_worker_count_accepts_explicit_auto_and_single_worker():
config = SimpleNamespace(option=SimpleNamespace(numprocesses=None), hook=SimpleNamespace(
pytest_xdist_auto_num_workers=lambda **_: 5,
))
assert pytest_early._parse_parallel_worker_count(
config, ["-n", "auto", "--max-worker-restart=0"],
) == 5
assert config.option.numprocesses == 5
assert pytest_early._parse_parallel_worker_count(
config, ["-n", "1", "--max-worker-restart=0"],
) == 1
for args in (
["--max-worker-restart=0"],
["-n", "auto"],
["-n", "2", "--max-worker-restart=1"],
["-n", "2", "--max-worker-restart=0", "--dist=each"],
):
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_"):
pytest_early._parse_parallel_worker_count(config, args)
def test_worker_bootstrap_returns_before_controller_path(monkeypatch):
calls = []
monkeypatch.setenv("PYTEST_WORKER_PG_RUN_ID", "run-id-from-controller")
monkeypatch.setattr(
pytest_early, "_bootstrap_parallel_pg_worker", lambda args: calls.append("worker"),
)
monkeypatch.setattr(
pytest_early, "_bootstrap_parallel_pg_controller", lambda *args: calls.append("controller"),
)
pytest_early.pytest_load_initial_conftests(
early_config=None, parser=None, args=["--run-isolated-pg-workers"],
)
assert calls == ["worker"]
def test_controller_cleans_prepared_databases_if_no_worker_started(monkeypatch):
context = {
"role": "controller",
"expected_workers": {"gw0", "gw1"},
"started_workers": set(),
"stopped_workers": set(),
}
calls = []
monkeypatch.setattr(pytest_early, "_parallel_pg_context", context)
monkeypatch.setattr(
pytest_early,
"_cleanup_parallel_pg",
lambda received, *, allow_unstarted: calls.append((received, allow_unstarted)),
)
pytest_early._pytest_unconfigure_parallel(SimpleNamespace(_session=None))
assert calls == [(context, True)]
def test_worker_context_accepts_any_declared_gw_and_refuses_foreign_or_serial(monkeypatch):
run_id = "0123456789abcdef0123456789abcdef"
workers = {f"gw{index}": {} for index in range(5)}
manifest = {"run_id": run_id, "worker_count": 5, "workers": workers}
monkeypatch.setenv("PYTEST_XDIST_TESTRUNUID", run_id)
pytest_early._validate_worker_context(manifest, run_id, "gw4", "5")
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_MAP_INVALID"):
pytest_early._validate_worker_context(manifest, run_id, "gw5", "5")
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_MAP_INVALID"):
pytest_early._validate_worker_context(manifest, run_id, "gw4", "4")
monkeypatch.delenv("PYTEST_XDIST_TESTRUNUID")
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_MAP_INVALID"):
pytest_early._validate_worker_context(manifest, run_id, "", None)
def test_worker_descriptor_and_lease_bind_run_identity():
run_id = "0123456789abcdef0123456789abcdef"
worker_id = "gw3"
database = f"ss_test_{run_id}_{worker_id}"
worker = {"database": database}
pytest_early._validate_worker_descriptor_binding(worker, {"database": database})
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_DESCRIPTOR_BINDING_INVALID"):
pytest_early._validate_worker_descriptor_binding(
worker, {"database": database + "_foreign"},
)
lease = {
"run_id": run_id, "worker_id": worker_id, "database": database,
"pid": 12345, "process_start_ticks": 67890,
}
pytest_early._validate_worker_lease(lease, run_id, worker_id, database)
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_LEASE_INVALID"):
pytest_early._validate_worker_lease(lease, run_id, "gw2", database)
def test_serial_execution_is_explicitly_unavailable_and_worker_proof_is_live(monkeypatch):
run_id = os.environ.get("PYTEST_WORKER_PG_RUN_ID")
worker_id = os.environ.get("PYTEST_XDIST_WORKER")
if not run_id or not worker_id:
with pytest.raises(RuntimeError, match="PYTEST_WORKER_PG_WORKER_MAP_INVALID"):
pytest_early._validate_worker_context({}, "", "", None)
else:
manifest = json.loads(Path(os.environ["PYTEST_WORKER_PG_RUN_MANIFEST"]).read_text())
pytest_early._validate_worker_context(
manifest, run_id, worker_id, os.environ.get("PYTEST_XDIST_WORKER_COUNT"),
)
descriptor_path = Path(os.environ["PG_CONSUMER_CONNECTION_FILE"])
descriptor = json.loads(descriptor_path.read_text(encoding="utf-8"))
with engine.connect() as connection:
current_database = connection.execute(text("SELECT current_database()")).scalar_one()
assert current_database == descriptor["database"]
assert current_database.endswith(f"_{worker_id}")
storage_root = Path(os.environ["PYTEST_WORKER_PG_STORAGE_ROOT"])
assert storage_root == Path(manifest["workers"][worker_id]["storage"])
info = storage_root.lstat()
assert stat.S_ISDIR(info.st_mode)
assert info.st_uid == os.getuid()
assert stat.S_IMODE(info.st_mode) == 0o700
lease = json.loads((storage_root / ".pytest-worker-owner.json").read_text())
assert lease["run_id"] == run_id
assert lease["worker_id"] == worker_id
assert lease["pid"] == os.getpid()
# #endregion Test.PytestWorkerIsolation