Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix: close read-side meta-tensor gap and harden the new lock sites

Lincoln Stein93b3110a6b82
diff --git a/invokeai/app/invocations/qwen_image_text_encoder.py b/invokeai/app/invocations/qwen_image_text_encoder.py
index f078d88f67..df46bf81d7 100644
--- a/invokeai/app/invocations/qwen_image_text_encoder.py
+++ b/invokeai/app/invocations/qwen_image_text_encoder.py
@@ -303,19 +303,22 @@ class QwenImageTextEncoderInvocation(BaseInvocation):
bnb_config = BitsAndBytesConfig(load_in_8bit=True)
context.util.signal_progress("Loading Qwen2.5-VL encoder (quantized)")
- with warnings.catch_warnings():
+ # Torch module construction is not thread-safe process-wide (see
+ # _ModelLoadReadWriteLock); serialize with the model-load machinery. The lock is
+ # the OUTER context on purpose: warnings.catch_warnings() swaps the process-global
+ # filter list, so holding it across an unbounded wait for the lock would leave this
+ # thread's filter installed — and clobberable by any other thread's
+ # SilenceWarnings — for the whole duration of someone else's model load.
+ with MODEL_LOAD_LOCK.write_lock(), warnings.catch_warnings():
# BnB int8 internally casts bfloat16→float16; the warning is harmless
warnings.filterwarnings("ignore", message="MatMul8bitLt.*cast.*float16")
- # Torch module construction is not thread-safe process-wide (see
- # _ModelLoadReadWriteLock); serialize with the model-load machinery.
- with MODEL_LOAD_LOCK.write_lock():
- text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained(
- str(encoder_path),
- quantization_config=bnb_config,
- device_map="auto",
- torch_dtype=torch.bfloat16,
- local_files_only=True,
- )
+ text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained(
+ str(encoder_path),
+ quantization_config=bnb_config,
+ device_map="auto",
+ torch_dtype=torch.bfloat16,
+ local_files_only=True,
+ )
device = next(text_encoder.parameters()).device
diff --git a/invokeai/app/invocations/upscale.py b/invokeai/app/invocations/upscale.py
index 1520106d74..410e8f210f 100644
--- a/invokeai/app/invocations/upscale.py
+++ b/invokeai/app/invocations/upscale.py
@@ -54,9 +54,13 @@ class ESRGANInvocation(BaseInvocation, WithMetadata, WithBoard):
"ESRGAN_SRx4_DF2KOST_official-ff704c30.pth",
]:
# x4 RRDBNet model
- # Torch module construction is not thread-safe process-wide (see
- # _ModelLoadReadWriteLock); serialize with the model-load machinery.
- with MODEL_LOAD_LOCK.write_lock():
+ # RRDBNet is plain torch: it *calls* register_parameter but never installs
+ # the accelerate/init_empty_weights patch itself, so it needs the reader
+ # role, not the writer one — it must only be excluded from a concurrent
+ # construction that would strand these parameters on the meta device. Using
+ # the write lock here would additionally block every other worker's VRAM
+ # moves for no benefit. See _ModelLoadReadWriteLock.
+ with MODEL_LOAD_LOCK.read_lock():
rrdbnet_model = RRDBNet(
num_in_ch=3,
num_out_ch=3,
@@ -68,7 +72,7 @@ class ESRGANInvocation(BaseInvocation, WithMetadata, WithBoard):
netscale = 4
elif self.model_name in ["RealESRGAN_x4plus_anime_6B.pth"]:
# x4 RRDBNet model, 6 blocks
- with MODEL_LOAD_LOCK.write_lock():
+ with MODEL_LOAD_LOCK.read_lock():
rrdbnet_model = RRDBNet(
num_in_ch=3,
num_out_ch=3,
@@ -80,7 +84,7 @@ class ESRGANInvocation(BaseInvocation, WithMetadata, WithBoard):
netscale = 4
elif self.model_name in ["RealESRGAN_x2plus.pth"]:
# x2 RRDBNet model
- with MODEL_LOAD_LOCK.write_lock():
+ with MODEL_LOAD_LOCK.read_lock():
rrdbnet_model = RRDBNet(
num_in_ch=3,
num_out_ch=3,
diff --git a/invokeai/app/invocations/wan_denoise.py b/invokeai/app/invocations/wan_denoise.py
index 4a2c9c76c9..e62ceff45a 100644
--- a/invokeai/app/invocations/wan_denoise.py
+++ b/invokeai/app/invocations/wan_denoise.py
@@ -44,6 +44,7 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import LoRAField, WanTransformerField
from invokeai.app.invocations.primitives import LatentsOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, WanVariantType
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.wan_lora_constants import WAN_LORA_TRANSFORMER_PREFIX
@@ -229,7 +230,20 @@ class _ExpertSwapper:
# and now — the cached_model object still owns the tensors.
if outgoing_cached_model is not None:
try:
- outgoing_cached_model.full_unload_from_vram()
+ # full_unload_from_vram() runs load_state_dict(assign=True) -> register_parameter,
+ # so it needs the MODEL_LOAD_LOCK read lock: without it, a construction on
+ # another worker holds the global register_parameter -> meta patch and strands
+ # this expert's weights on the meta device, poisoning the still-cached record.
+ # Safe to acquire here: _release() above dropped both the LoRA and device
+ # contexts, so this thread holds no MODEL_LOAD_LOCK (it is not reentrant).
+ # Note this is narrower than LoadedModelWithoutConfig.__enter__, which also
+ # holds ModelCache._lock: this call can still overlap the cache's own
+ # _offload_unlocked_models on the same record. That race predates this lock
+ # and is deliberately not addressed here. It also means the read lock is held
+ # across a multi-GB VRAM->RAM copy, and MODEL_LOAD_LOCK is write-preferring,
+ # so other workers' VRAM moves queue behind it for the duration.
+ with MODEL_LOAD_LOCK.read_lock():
+ outgoing_cached_model.full_unload_from_vram()
except Exception:
pass
diff --git a/invokeai/backend/image_util/safety_checker.py b/invokeai/backend/image_util/safety_checker.py
index 2b4ee89991..41919ed5c2 100644
--- a/invokeai/backend/image_util/safety_checker.py
+++ b/invokeai/backend/image_util/safety_checker.py
@@ -4,6 +4,10 @@ wraps the safety_checker model. It respects the global "nsfw_checker"
configuration variable, that allows the checker to be supressed.
"""
+import os
+import shutil
+import tempfile
+import threading
from pathlib import Path
import numpy as np
@@ -21,6 +25,11 @@ from invokeai.backend.util.silence_warnings import SilenceWarnings
repo_id = "CompVis/stable-diffusion-safety-checker"
CHECKER_PATH = "core/convert/stable-diffusion-safety-checker"
+# Serializes the lazy init below. Lock ordering: this is acquired BEFORE
+# MODEL_LOAD_LOCK, never after (see _ModelLoadReadWriteLock), matching the
+# service-lock -> MODEL_LOAD_LOCK order used by ImageIndexService.
+_INIT_LOCK = threading.Lock()
+
class SafetyChecker:
"""
@@ -35,27 +44,73 @@ class SafetyChecker:
if cls.safety_checker is not None and cls.feature_extractor is not None:
return
+ # Serialize the whole lazy init. Without this, two session workers both fall
+ # through the check above and race in three ways: they duplicate the download
+ # and the construction, they run save_pretrained() into the same directory
+ # concurrently, and — because the first thread's mkdir + feature-extractor save
+ # makes model_path exist before the weights land — the second can take the
+ # "already downloaded" branch below, fail on the missing weights, and leave
+ # safety_checker as None, which has_nsfw_concept() reports as "not NSFW".
+ with _INIT_LOCK:
+ # Re-check now that we hold the lock: another worker may have finished
+ # while we waited. (Same double-checked pattern as ModelLoader._load_and_cache
+ # and ModelLoadService.load_remote_model.)
+ if cls.safety_checker is not None and cls.feature_extractor is not None:
+ return
+
+ try:
+ model_path = get_config().models_path / CHECKER_PATH
+ if model_path.exists():
+ cls.feature_extractor = AutoImageProcessor.from_pretrained(model_path)
+ # Torch module construction is not thread-safe process-wide (see
+ # _ModelLoadReadWriteLock); serialize with the model-load machinery.
+ with MODEL_LOAD_LOCK.write_lock():
+ cls.safety_checker = StableDiffusionSafetyChecker.from_pretrained(model_path)
+ else:
+ # Download before constructing: from_pretrained(repo_id) would
+ # otherwise hold the process-wide load lock across a multi-GB
+ # network transfer, stalling every other model load.
+ download_path = snapshot_download(repo_id)
+ feature_extractor = AutoImageProcessor.from_pretrained(download_path)
+ # Torch module construction is not thread-safe process-wide (see
+ # _ModelLoadReadWriteLock); serialize with the model-load machinery.
+ with MODEL_LOAD_LOCK.write_lock():
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained(download_path)
+ # Publish the in-memory objects before persisting them: failing to
+ # cache the checker on disk must not leave this run without one.
+ cls.feature_extractor = feature_extractor
+ cls.safety_checker = safety_checker
+ try:
+ cls._persist_checker(feature_extractor, safety_checker, model_path)
+ except Exception as e:
+ logger.warning(f"Could not cache NSFW checker to {model_path}: {str(e)}")
+ except Exception as e:
+ logger.warning(f"Could not load NSFW checker: {str(e)}")
+
+ @classmethod
+ def _persist_checker(cls, feature_extractor, safety_checker, model_path: Path) -> None:
+ """Write the checker into `model_path` atomically.
+
+ `save_pretrained()` creates its own destination, so writing the two objects
+ straight into `model_path` would make that directory exist as soon as the FIRST
+ save lands. Any later failure — a raising construction, a full disk, a killed
+ process — would then leave a weightless directory that the `model_path.exists()`
+ branch of `_load_safety_checker` trusts forever: the image processor loads, the
+ checker doesn't, the exception is swallowed, and `has_nsfw_concept()` reports a
+ missing checker as "not NSFW", so every image ships unblurred and the download is
+ never retried. Staging into a sibling directory and renaming makes the install
+ either complete or absent, never half-present.
+ """
+ model_path.parent.mkdir(parents=True, exist_ok=True)
+ staging = Path(tempfile.mkdtemp(dir=model_path.parent, prefix=f".{model_path.name}.tmp-"))
try:
- model_path = get_config().models_path / CHECKER_PATH
- if model_path.exists():
- cls.feature_extractor = AutoImageProcessor.from_pretrained(model_path)
- # Torch module construction is not thread-safe process-wide (see
- # _ModelLoadReadWriteLock); serialize with the model-load machinery.
- with MODEL_LOAD_LOCK.write_lock():
- cls.safety_checker = StableDiffusionSafetyChecker.from_pretrained(model_path)
- else:
- model_path.mkdir(parents=True, exist_ok=True)
- # Download before constructing: from_pretrained(repo_id) would
- # otherwise hold the process-wide load lock across a multi-GB
- # network transfer, stalling every other model load.
- download_path = snapshot_download(repo_id)
- cls.feature_extractor = AutoImageProcessor.from_pretrained(download_path)
- cls.feature_extractor.save_pretrained(model_path)
- with MODEL_LOAD_LOCK.write_lock():
- cls.safety_checker = StableDiffusionSafetyChecker.from_pretrained(download_path)
- cls.safety_checker.save_pretrained(model_path)
- except Exception as e:
- logger.warning(f"Could not load NSFW checker: {str(e)}")
+ feature_extractor.save_pretrained(staging)
+ safety_checker.save_pretrained(staging)
+ # Atomic on a single filesystem, and staging is a sibling of the target.
+ os.replace(staging, model_path)
+ except Exception:
+ shutil.rmtree(staging, ignore_errors=True)
+ raise
@classmethod
def has_nsfw_concept(cls, image: Image.Image) -> bool:
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.py
index 1c062e2078..1ea5b8251c 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -150,10 +150,24 @@ class _ModelLoadReadWriteLock:
def write_lock(self) -> Generator[None, None, None]:
with self._cond:
self._writers_waiting += 1
- while self._writer_active or self._readers > 0:
- self._cond.wait()
- self._writers_waiting -= 1
- self._writer_active = True
+ acquired = False
+ try:
+ while self._writer_active or self._readers > 0:
+ self._cond.wait()
+ self._writer_active = True
+ acquired = True
+ finally:
+ # Decrement even if wait() raises (e.g. an async exception delivered to
+ # this thread). Leaking the count would leave read_lock's
+ # `_writers_waiting > 0` guard permanently true, blocking every VRAM move
+ # in the process for the rest of its life. read_lock needs no equivalent
+ # guard: it increments only after its wait loop, so a raising wait() there
+ # leaves no state behind.
+ self._writers_waiting -= 1
+ if not acquired:
+ # Giving up without becoming the writer — wake the readers that were
+ # deferring to us, since nothing else will.
+ self._cond.notify_all()
try:
yield
finally:
diff --git a/tests/backend/image_util/test_safety_checker_init_lock.py b/tests/backend/image_util/test_safety_checker_init_lock.py
new file mode 100644
index 0000000000..53fcee2d69
--- /dev/null
+++ b/tests/backend/image_util/test_safety_checker_init_lock.py
@@ -0,0 +1,195 @@
+"""Regression tests for SafetyChecker's lazy init under concurrency.
+
+`_load_safety_checker` is reached from ImageNSFWBlurInvocation on every session worker
+thread. Its check-then-act on two class attributes used to let several workers run the
+whole init body at once, which duplicated the 1.2GB download and construction, wrote
+save_pretrained() into one directory from several threads, and — because the first
+thread's mkdir + feature-extractor save makes model_path exist before the weights land —
+let a second thread take the "already downloaded" branch, fail on the missing weights,
+and leave safety_checker as None. has_nsfw_concept() reports that as "not NSFW", so the
+image ships unblurred.
+"""
+
+import threading
+from typing import Any
+
+import pytest
+
+import invokeai.backend.image_util.safety_checker as safety_checker_module
+from invokeai.backend.image_util.safety_checker import CHECKER_PATH, SafetyChecker
+
+
+class _FakeSaveable:
+ """Stands in for the feature extractor / safety checker; records its saves."""
+
+ def __init__(self, saves: list[Any]) -> None:
+ self._saves = saves
+
+ def save_pretrained(self, path: Any) -> None:
+ self._saves.append(path)
+
+
+def reset_checker():
+ """SafetyChecker caches on class attributes, so restore them around each test."""
+ original = (SafetyChecker.feature_extractor, SafetyChecker.safety_checker)
+ SafetyChecker.feature_extractor = None
+ SafetyChecker.safety_checker = None
+ yield
+ SafetyChecker.feature_extractor, SafetyChecker.safety_checker = original
+
+
+def test_concurrent_lazy_init_downloads_and_constructs_exactly_once(
+ tmp_path, monkeypatch: pytest.MonkeyPatch, reset_checker
+) -> None:
+ downloads: list[str] = []
+ constructions: list[Any] = []
+ saves: list[Any] = []
+ barrier = threading.Barrier(8)
+
+ download_dir = tmp_path / "hf_snapshot"
+ download_dir.mkdir()
+
+ class _FakeConfig:
+ models_path = tmp_path / "models"
+
+ def fake_snapshot_download(repo: str) -> str:
+ downloads.append(repo)
+ # Widen the window a real network transfer would occupy.
+ threading.Event().wait(0.05)
+ return str(download_dir)
+
+ def fake_image_processor_from_pretrained(path: Any) -> _FakeSaveable:
+ return _FakeSaveable(saves)
+
+ def fake_checker_from_pretrained(path: Any) -> _FakeSaveable:
+ constructions.append(path)
+ threading.Event().wait(0.05)
+ return _FakeSaveable(saves)
+
+ monkeypatch.setattr(safety_checker_module, "get_config", lambda: _FakeConfig())
+ monkeypatch.setattr(safety_checker_module, "snapshot_download", fake_snapshot_download)
+ monkeypatch.setattr(
+ safety_checker_module.AutoImageProcessor,
+ "from_pretrained",
+ staticmethod(fake_image_processor_from_pretrained),
+ )
+ monkeypatch.setattr(
+ safety_checker_module.StableDiffusionSafetyChecker,
+ "from_pretrained",
+ staticmethod(fake_checker_from_pretrained),
+ )
+
+ errors: list[BaseException] = []
+
+ def worker() -> None:
+ try:
+ barrier.wait(timeout=10)
+ SafetyChecker._load_safety_checker()
+ except BaseException as e: # noqa: BLE001 - surface anything the thread hit
+ errors.append(e)
+
+ threads = [threading.Thread(target=worker) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=30)
+
+ assert not [t for t in threads if t.is_alive()], "lazy init deadlocked"
+ assert not errors, f"worker threads raised: {errors}"
+
+ # The point of the fix: eight concurrent callers do the work once, not eight times.
+ assert len(downloads) == 1, f"expected a single download, got {len(downloads)}"
+ assert len(constructions) == 1, f"expected a single construction, got {len(constructions)}"
+
+ # And every caller sees a usable checker — none observes the half-initialized state
+ # that would make has_nsfw_concept() silently return False.
+ assert SafetyChecker.safety_checker is not None
+ assert SafetyChecker.feature_extractor is not None
+
+
+def test_failed_download_leaves_no_directory_to_poison_the_next_attempt(
+ tmp_path, monkeypatch: pytest.MonkeyPatch, reset_checker
+) -> None:
+ """A failed download must not create model_path.
+
+ If it does, every later call takes the `model_path.exists()` branch, fails on the
+ absent weights, and the download is never retried for the life of the install.
+ """
+
+ class _FakeConfig:
+ models_path = tmp_path / "models"
+
+ def exploding_snapshot_download(repo: str) -> str:
+ raise RuntimeError("network is down")
+
+ monkeypatch.setattr(safety_checker_module, "get_config", lambda: _FakeConfig())
+ monkeypatch.setattr(safety_checker_module, "snapshot_download", exploding_snapshot_download)
+
+ # Swallowed and logged, per the existing contract.
+ SafetyChecker._load_safety_checker()
+
+ assert SafetyChecker.safety_checker is None
+ assert not (_FakeConfig.models_path / CHECKER_PATH).exists(), (
+ "a failed download left model_path behind; the next attempt will take the "
+ "'already downloaded' branch and never retry"
+ )
+
+
+def test_failed_construction_after_a_good_download_does_not_poison_the_install(
+ tmp_path, monkeypatch: pytest.MonkeyPatch, reset_checker
+) -> None:
+ """The download succeeding is not enough — the *save* must be all-or-nothing.
+
+ `save_pretrained()` creates its own destination, so persisting the feature extractor
+ before the checker is built would make model_path exist with no weights in it. Every
+ later call would then take the `model_path.exists()` branch, fail on the missing
+ weights, swallow the error, and `has_nsfw_concept()` would report the absent checker
+ as "not NSFW" forever, without ever retrying the download.
+ """
+ downloads: list[str] = []
+ saves: list[Any] = []
+
+ download_dir = tmp_path / "hf_snapshot"
+ download_dir.mkdir()
+
+ class _FakeConfig:
+ models_path = tmp_path / "models"
+
+ def fake_snapshot_download(repo: str) -> str:
+ downloads.append(repo)
+ return str(download_dir)
+
+ monkeypatch.setattr(safety_checker_module, "get_config", lambda: _FakeConfig())
+ monkeypatch.setattr(safety_checker_module, "snapshot_download", fake_snapshot_download)
+ monkeypatch.setattr(
+ safety_checker_module.AutoImageProcessor,
+ "from_pretrained",
+ staticmethod(lambda path: _FakeSaveable(saves)),
+ )
+
+ def exploding_checker_from_pretrained(path: Any):
+ raise RuntimeError("truncated safetensors header")
+
+ monkeypatch.setattr(
+ safety_checker_module.StableDiffusionSafetyChecker,
+ "from_pretrained",
+ staticmethod(exploding_checker_from_pretrained),
+ )
+
+ SafetyChecker._load_safety_checker()
+
+ assert SafetyChecker.safety_checker is None
+ model_path = _FakeConfig.models_path / CHECKER_PATH
+ assert not model_path.exists(), (
+ "a failed construction left a weightless model_path behind; the checker is now "
+ "permanently disabled and the download will never be retried"
+ )
+ # No staging directory should survive either.
+ parent = model_path.parent
+ leftovers = list(parent.iterdir()) if parent.exists() else []
+ assert not leftovers, f"staging directory leaked: {leftovers}"
+
+ # And the next attempt must genuinely retry rather than trusting a poisoned dir.
+ SafetyChecker._load_safety_checker()
+ assert len(downloads) == 2, f"expected the second attempt to re-download, got {downloads}"
diff --git a/tests/backend/model_manager/load/model_cache/test_model_load_rw_lock.py b/tests/backend/model_manager/load/model_cache/test_model_load_rw_lock.py
new file mode 100644
index 0000000000..c349ec9440
--- /dev/null
+++ b/tests/backend/model_manager/load/model_cache/test_model_load_rw_lock.py
@@ -0,0 +1,154 @@
+"""Tests for _ModelLoadReadWriteLock's bookkeeping under abnormal exits.
+
+The lock is write-preferring: readers defer while `_writers_waiting > 0`. That makes the
+waiting count load-bearing — if a writer ever leaves it incremented, every VRAM move in the
+process blocks forever, because nothing will bring it back to zero.
+"""
+
+import threading
+
+import pytest
+
+from invokeai.backend.model_manager.load.model_cache.model_cache import _ModelLoadReadWriteLock
+
+
+def test_writer_does_not_leak_waiting_count_when_wait_raises() -> None:
+ """An exception out of `_cond.wait()` must not wedge every future reader."""
+ lock = _ModelLoadReadWriteLock()
+ reader_holding = threading.Event()
+ release_reader = threading.Event()
+
+ def reader() -> None:
+ with lock.read_lock():
+ reader_holding.set()
+ release_reader.wait(timeout=10)
+
+ reader_thread = threading.Thread(target=reader)
+ reader_thread.start()
+ assert reader_holding.wait(timeout=10), "reader never acquired"
+
+ # With a reader resident, the writer is forced into its wait loop. Make that wait raise
+ # the way an async exception delivered to this thread would.
+ original_wait = lock._cond.wait
+
+ def exploding_wait(*args, **kwargs):
+ lock._cond.wait = original_wait # only detonate once
+ raise KeyboardInterrupt("async exception during wait")
+
+ lock._cond.wait = exploding_wait
+
+ with pytest.raises(KeyboardInterrupt):
+ with lock.write_lock():
+ pass
+
+ assert lock._writers_waiting == 0, (
+ "write_lock leaked _writers_waiting after an aborted wait; every subsequent read_lock() would block forever"
+ )
+ assert not lock._writer_active, "aborted writer must not be recorded as active"
+
+ release_reader.set()
+ reader_thread.join(timeout=10)
+ assert not reader_thread.is_alive()
+
+ # The real proof: a fresh reader must still be able to acquire.
+ acquired = threading.Event()
+
+ def late_reader() -> None:
+ with lock.read_lock():
+ acquired.set()
+
+ late = threading.Thread(target=late_reader)
+ late.start()
+ assert acquired.wait(timeout=10), "readers are permanently blocked after the aborted writer"
+ late.join(timeout=10)
+
+
+def test_readers_blocked_by_an_aborted_writer_are_woken() -> None:
+ """A writer that aborts while readers defer to it must notify them.
+
+ The readers are parked in `_cond.wait()` because `_writers_waiting > 0`. Decrementing
+ the count without a notify would leave them asleep until some unrelated event.
+ """
+ lock = _ModelLoadReadWriteLock()
+ resident_holding = threading.Event()
+ release_resident = threading.Event()
+
+ def resident_reader() -> None:
+ with lock.read_lock():
+ resident_holding.set()
+ release_resident.wait(timeout=10)
+
+ resident = threading.Thread(target=resident_reader)
+ resident.start()
+ assert resident_holding.wait(timeout=10)
+
+ # A writer queues up behind the resident reader, so _writers_waiting becomes 1.
+ writer_waiting = threading.Event()
+ writer_failed = threading.Event()
+ original_wait = lock._cond.wait
+
+ def signalling_wait(*args, **kwargs):
+ writer_waiting.set()
+ lock._cond.wait = original_wait
+ raise KeyboardInterrupt("async exception during wait")
+
+ def writer() -> None:
+ lock._cond.wait = signalling_wait
+ try:
+ with lock.write_lock():
+ pass
+ except KeyboardInterrupt:
+ writer_failed.set()
+
+ writer_thread = threading.Thread(target=writer)
+ writer_thread.start()
+ assert writer_waiting.wait(timeout=10), "writer never reached its wait loop"
+ assert writer_failed.wait(timeout=10), "writer did not abort as arranged"
+ writer_thread.join(timeout=10)
+
+ assert lock._writers_waiting == 0
+
+ release_resident.set()
+ resident.join(timeout=10)
+
+ # A reader must now be able to proceed without any further external event.
+ proceeded = threading.Event()
+
+ def deferred_reader() -> None:
+ with lock.read_lock():
+ proceeded.set()
+
+ deferred = threading.Thread(target=deferred_reader)
+ deferred.start()
+ assert proceeded.wait(timeout=10), "reader was not woken after the writer aborted"
+ deferred.join(timeout=10)
+
+
+def test_normal_write_lock_still_serializes_against_readers() -> None:
+ """Guard against the try/finally restructuring breaking the happy path."""
+ lock = _ModelLoadReadWriteLock()
+ observed: list[str] = []
+ writer_done = threading.Event()
+
+ with lock.read_lock():
+ assert lock._readers == 1
+
+ def writer() -> None:
+ with lock.write_lock():
+ observed.append("writer")
+ assert lock._writer_active
+ writer_done.set()
+
+ writer_thread = threading.Thread(target=writer)
+ writer_thread.start()
+ # The writer cannot enter while a reader is resident.
+ assert not writer_done.wait(timeout=0.2)
+ observed.append("reader-exit")
+
+ assert writer_done.wait(timeout=10), "writer never acquired after the reader left"
+ writer_thread.join(timeout=10)
+
+ assert observed == ["reader-exit", "writer"]
+ assert lock._writers_waiting == 0
+ assert not lock._writer_active
+ assert lock._readers == 0