🔒 The Parallel Execution Race Condition Challenge
When accelerating Playwright test suites using parallel multi-process runners like pytest-xdist (e.g., pytest -n 4 or pytest -n auto), multiple independent Python worker processes execute concurrently. If each worker attempts to authenticate or refresh storage_state.json at startup, severe race conditions occur: multiple workers trigger duplicate login calls simultaneously, leading to rate-limiting (HTTP 429), account session invalidations, or reading corrupted partially-written JSON files. Thread-safe and process-safe authentication locks resolve this friction. By utilizing cross-process file locks via the filelock library and atomic write patterns, one worker acquires the lock, completes authentication, and flushes the storage state safely, while sibling workers wait to consume the freshly generated session.
threading.Lock) only guard threads inside a single process. Multi-worker testing across pytest-xdist forks distinct OS processes requiring system-level file locks.
WITHOUT INTER-PROCESS LOCKING (Corrupted Auth State & Account Rate Limits):
Worker 1 (gw0) ──► Check auth.json (Missing) ──► Trigger UI/API Login ──► Overwrites auth.json
Worker 2 (gw1) ──► Check auth.json (Missing) ──► Trigger UI/API Login ──► Overwrites auth.json
Worker 3 (gw2) ──► Check auth.json (Half-written) ──► json.decoder.JSONDecodeError! (CRASH)
WITH INTER-PROCESS FILELOCKING (Coordinated, Atomic & Single-Flight):
┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. All Workers Request FileLock: FileLock("storage_state.json.lock") │
├─────────────────────────────────────────────────────────────────────────────┤
│ * Worker 1 acquires lock first: │
│ - Inspects if storage_state.json exists and is valid │
│ - Executes single login flow ──► Writes auth.json atomically │
│ - Releases lock │
│ │
│ * Workers 2, 3, & 4 acquire lock sequentially: │
│ - Inspect storage_state.json ──► Found valid & fresh! │
│ - Skip login immediately! │
│ - Initialize BrowserContext directly with cached session │
└─────────────────────────────────────────────────────────────────────────────┘
FileLock context manager to guarantee that only one operating system process enters the login block at any given instant.
import os
import time
import tempfile
from filelock import FileLock
from playwright.sync_api import sync_playwright
storage_dir = os.path.join(tempfile.gettempdir(), "pw_threadsafe_auth")
os.makedirs(storage_dir, exist_ok=True)
auth_file = os.path.join(storage_dir, "session_state.json")
lock_file = os.path.join(storage_dir, "session_state.json.lock")
def ensure_authenticated_session():
"""Acquires an OS-level file lock to ensure only one worker authenticates."""
lock = FileLock(lock_file, timeout=60)
with lock:
# Check if another worker already finished authentication while we waited
if os.path.exists(auth_file):
print("[Worker PID", os.getpid(), "] Session state already generated by peer. Reusing cache.")
return auth_file
print("[Worker PID", os.getpid(), "] Acquired lock! Performing primary authentication...")
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Programmatic API login
res = api.post("/post", data={"user": "nikita_qa", "key": "Secret9921"})
assert res.ok
# Create browser context to export storage state
browser = p.chromium.launch(headless=True)
context = browser.new_context()
context.add_cookies([{
"name": "enterprise_auth_token",
"value": "TOKEN_SECURE_LOCKED_2026",
"domain": "httpbin.org",
"path": "/"
}])
context.storage_state(path=auth_file)
context.close()
browser.close()
api.dispose()
print("[Worker PID", os.getpid(), "] Authentication complete. Lock released.")
return auth_file
# Simulate execution
state_path = ensure_authenticated_session()
print(f"Verified Session State Ready at: {state_path}")
os.replace).
import os
import json
import tempfile
from playwright.sync_api import sync_playwright
def write_storage_state_atomically(context, destination_path: str):
"""Writes storage state to a temporary file and atomically moves it into place."""
target_dir = os.path.dirname(destination_path)
os.makedirs(target_dir, exist_ok=True)
# Step 1: Write to an isolated temporary file in the same filesystem
temp_target = destination_path + f".tmp.{os.getpid()}"
context.storage_state(path=temp_target)
# Step 2: Validate that the temporary file contains valid JSON
with open(temp_target, "r") as f:
data = json.load(f)
assert "cookies" in data and "origins" in data
# Step 3: Atomic filesystem rename (POSIX & Windows atomic replacement)
os.replace(temp_target, destination_path)
print(f"Atomically replaced storage state at: {destination_path}")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
ctx = browser.new_context()
ctx.add_cookies([{"name": "sess", "value": "ATOMIC_TOKEN_1", "domain": "example.com", "path": "/"}])
final_dest = os.path.join(tempfile.gettempdir(), "pw_atomic", "state.json")
write_storage_state_atomically(ctx, final_dest)
ctx.close()
browser.close()
conftest.py using tmp_path_factory and FileLock so parallel workers coordinate seamlessly.
# content of conftest.py
import pytest
from filelock import FileLock
from playwright.sync_api import Playwright, Browser
@pytest.fixture(scope="session")
def session_storage_state(tmp_path_factory, worker_id: str, playwright: Playwright) -> str:
"""Coordinates authentication across parallel pytest-xdist workers."""
# When running single-threaded (no xdist), worker_id is "master"
if worker_id == "master":
root_dir = tmp_path_factory.mktemp("auth_master")
else:
# Multiple workers share the parent temporary directory
root_dir = tmp_path_factory.getbasetemp().parent
state_file = root_dir / "user_storage_state.json"
lock_file = root_dir / "user_storage_state.json.lock"
# Synchronize all xdist workers (gw0, gw1, etc.)
with FileLock(str(lock_file), timeout=60):
if not state_file.is_file():
# First worker inside lock logs in
api = playwright.request.new_context(base_url="https://httpbin.org")
res = api.post("/post", data={"auth": "root_user"})
assert res.ok
browser = playwright.chromium.launch(headless=True)
context = browser.new_context()
context.add_cookies([{
"name": "auth_cookie",
"value": "XDIST_TOKEN_SESSION_99",
"domain": "httpbin.org",
"path": "/"
}])
context.storage_state(path=str(state_file))
context.close()
browser.close()
api.dispose()
return str(state_file)
@pytest.fixture
def authenticated_context(browser: Browser, session_storage_state: str):
"""Provides a fresh context for each test pre-seeded with authenticated state."""
context = browser.new_context(storage_state=session_storage_state)
yield context
context.close()
import os
import json
import time
import tempfile
from filelock import FileLock
from playwright.sync_api import sync_playwright
TOKEN_TTL_SECONDS = 3600 # 1 Hour Token Validity
def get_valid_auth_state(cache_dir: str) -> str:
auth_file = os.path.join(cache_dir, "auth_ttl_state.json")
lock_file = os.path.join(cache_dir, "auth_ttl_state.json.lock")
with FileLock(lock_file, timeout=60):
current_time = time.time()
# Step 1: Check if file exists and token is still within valid TTL threshold
if os.path.exists(auth_file):
with open(auth_file, "r") as f:
state_data = json.load(f)
meta = state_data.get("_metadata", {})
created_at = meta.get("created_at", 0)
# If token has more than 5 minutes of lifetime left, reuse it
if (current_time - created_at) < (TOKEN_TTL_SECONDS - 300):
print("Token cache is fresh. Reusing without network round-trip.")
return auth_file
# Step 2: Token is missing or near expiration -> Perform Single-Flight Renewal
print("Token missing or expired. Performing single-flight authentication...")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
ctx = browser.new_context()
ctx.add_cookies([{
"name": "bearer_sess",
"value": f"TOK_{int(current_time)}",
"domain": "example.com",
"path": "/"
}])
raw_state = ctx.storage_state()
# Embed metadata timestamp to track TTL
raw_state["_metadata"] = {"created_at": current_time}
with open(auth_file, "w") as f:
json.dump(raw_state, f, indent=2)
ctx.close()
browser.close()
return auth_file
test_dir = tempfile.gettempdir()
path_1 = get_valid_auth_state(test_dir)
# Immediate subsequent call reuses valid cache without logging in again
path_2 = get_valid_auth_state(test_dir)
import os
import tempfile
from filelock import FileLock
from playwright.sync_api import sync_playwright
ROLE_CREDENTIALS = {
"admin": {"user": "admin_aarav", "pass": "AdminKey99"},
"manager": {"user": "mgr_pooja", "pass": "ManagerKey88"},
"auditor": {"user": "auditor_guest", "pass": "AuditKey77"}
}
def get_role_storage_state(role: str) -> str:
"""Acquires a role-specific lock so distinct roles authenticate independently."""
base_dir = os.path.join(tempfile.gettempdir(), "pw_roles_lock")
os.makedirs(base_dir, exist_ok=True)
state_path = os.path.join(base_dir, f"{role}_state.json")
lock_path = os.path.join(base_dir, f"{role}_state.json.lock")
with FileLock(lock_path, timeout=60):
if os.path.exists(state_path):
return state_path
print(f"[{role.upper()}] Initializing role credentials under dedicated lock...")
creds = ROLE_CREDENTIALS[role]
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
res = api.post("/post", data=creds)
assert res.ok
browser = p.chromium.launch(headless=True)
ctx = browser.new_context()
ctx.add_cookies([{
"name": "role_cookie",
"value": f"ROLE_TOKEN_{role.upper()}",
"domain": "httpbin.org",
"path": "/"
}])
ctx.storage_state(path=state_path)
ctx.close()
browser.close()
api.dispose()
return state_path
admin_state = get_role_storage_state("admin")
manager_state = get_role_storage_state("manager")
print("Partitioned states successfully created:")
print(f" Admin : {admin_state}")
print(f" Manager : {manager_state}")
asyncio and async_api, protect shared in-memory authentication states using asyncio.Lock() to eliminate coroutine interleaving.
import asyncio
from playwright.async_api import async_playwright
class AsyncAuthManager:
"""Asynchronous in-memory auth state manager guarded by asyncio.Lock."""
def __init__(self):
self._lock = asyncio.Lock()
self._cached_state = None
async def get_storage_state(self, playwright):
async with self._lock:
if self._cached_state is not None:
print("Coroutine retrieved cached in-memory state.")
return self._cached_state
print("Acquired asyncio lock! Generating in-memory storage state...")
browser = await playwright.chromium.launch(headless=True)
context = await browser.new_context()
await context.add_cookies([{
"name": "async_session",
"value": "ASYNC_VERIFIED_9921",
"domain": "example.com",
"path": "/"
}])
self._cached_state = await context.storage_state()
await context.close()
await browser.close()
return self._cached_state
async def main():
async with async_playwright() as p:
auth_mgr = AsyncAuthManager()
# Simulate two concurrent coroutines requesting auth state simultaneously
task1 = asyncio.create_task(auth_mgr.get_storage_state(p))
task2 = asyncio.create_task(auth_mgr.get_storage_state(p))
state1, state2 = await asyncio.gather(task1, task2)
assert state1["cookies"][0]["value"] == "ASYNC_VERIFIED_9921"
assert state2["cookies"][0]["value"] == "ASYNC_VERIFIED_9921"
print("Both coroutines resolved state safely without duplicate browser setups!")
asyncio.run(main())
multiprocessing module simulating 4 concurrent worker processes competing for the same authentication lock.
import os
import time
import tempfile
from multiprocessing import Process
from filelock import FileLock
def worker_task(worker_id: int, shared_lock_path: str, shared_state_path: str):
lock = FileLock(shared_lock_path, timeout=30)
print(f"Worker-{worker_id} (PID {os.getpid()}) attempting to acquire lock...")
with lock:
if os.path.exists(shared_state_path):
print(f" Worker-{worker_id} entered lock: State already exists. Skipped login.")
return
print(f" Worker-{worker_id} entered lock: FIRST! Performing login and writing state...")
time.sleep(0.3) # Simulate network login latency
with open(shared_state_path, "w") as f:
f.write(f'{{"auth_by": "Worker-{worker_id}"}}')
print(f" Worker-{worker_id} released lock.")
if __name__ == "__main__":
temp_dir = tempfile.gettempdir()
lock_file = os.path.join(temp_dir, "contention.lock")
state_file = os.path.join(temp_dir, "contention_state.json")
if os.path.exists(state_file): os.remove(state_file)
if os.path.exists(lock_file): os.remove(lock_file)
processes = [
Process(target=worker_task, args=(i, lock_file, state_file))
for i in range(1, 4)
]
for p in processes: p.start()
for p in processes: p.join()
with open(state_file, "r") as f:
print("Final File Contents:", f.read())
if os.path.exists(state_file): os.remove(state_file)
if os.path.exists(lock_file): os.remove(lock_file)
import os
import time
import tempfile
from filelock import FileLock, Timeout
def acquire_resilient_lock(lock_path: str, max_timeout: int = 20) -> FileLock:
"""Acquires lock with fallback recovery if previous process crashed holding it."""
lock = FileLock(lock_path, timeout=max_timeout)
try:
lock.acquire()
return lock
except Timeout:
print(f"[Warning] Lock acquisition timed out ({max_timeout}s). Checking for stale lock...")
# Inspect lock file age
if os.path.exists(lock_path):
file_age = time.time() - os.path.getmtime(lock_path)
if file_age > max_timeout:
print(f"Purging abandoned stale lock file (Age: {int(file_age)}s)...")
try:
os.remove(lock_path)
except OSError:
pass
# Retry acquisition once
lock.acquire(timeout=max_timeout)
return lock
raise RuntimeError("Failed to acquire lock: resource permanently contested.")
demo_lock_path = os.path.join(tempfile.gettempdir(), "resilient_demo.lock")
active_lock = acquire_resilient_lock(demo_lock_path, max_timeout=5)
print("Resilient lock successfully acquired!")
active_lock.release()
if os.path.exists(demo_lock_path):
os.remove(demo_lock_path)
PARALLEL AUTHENTICATION SYNCHRONIZATION MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Synchronization Mechanism │ Primary Python Library │ Scope & Target Architecture │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ Cross-Process File Locking │ filelock.FileLock │ Inter-process coordination for pytest-xdist workers. │
│ Atomic File Replacement │ os.replace(temp_path, dest) │ POSIX/Windows atomic file switch; prevents partial read.│
│ Session Base Directory │ tmp_path_factory.getbasetemp │ Shared directory accessible across all xdist workers. │
│ In-Memory Coroutine Lock │ asyncio.Lock() │ Playwright async_api coroutine coordination. │
│ Thread Mutex Lock │ threading.Lock() │ Guarding threads inside a single multi-threaded process.│
│ Partitioned Role Locks │ FileLock(f"{role}.lock") │ Enables concurrent login for different personas. │
│ Lock Timeout Recovery │ Timeout exception handler │ Recovers from stranded locks caused by killed CI runs. │
├──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┤
│ BEST PRACTICE EXECUTION SEQUENCE: │
│ 1. Acquire FileLock with timeout (e.g. 60 seconds). │
│ 2. Double-check if storage_state.json exists and is valid (Double-Checked Locking). │
│ 3. If missing/expired: Authenticate via APIRequestContext and write to temp file. │
│ 4. Atomically os.replace temp file to destination storage_state.json. │
│ 5. Release FileLock so pending sibling workers can immediately read valid cached state. │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘