| 1 |
""" |
| 2 |
The generation-log protocol: record formats, the ledger, and ``GenerationLog``/``Participant`` behavior, plus a model |
| 3 |
check of the whole protocol under an adversarial scheduler. |
| 4 |
|
| 5 |
The direct tests below exercise ``Snapshot``, ``Ledger``, ``GenerationLog``, and ``Participant`` against a real |
| 6 |
filesystem. The model check that follows runs every participant on its own thread over an in-memory filesystem, and |
| 7 |
every filesystem call hands the turn back to a seeded scheduler that picks which participant runs next, advances a fake |
| 8 |
clock, and sometimes kills the participant it picked. That interleaves the protocol at the granularity of single |
| 9 |
filesystem operations, including inside a commit, and a crash at any of those points leaves exactly what a dead process |
| 10 |
would leave on disk. |
| 11 |
""" |
| 12 |
|
| 13 |
from __future__ import annotations |
| 14 |
|
| 15 |
import os |
| 16 |
import random |
| 17 |
import threading |
| 18 |
from dataclasses import dataclass, field |
| 19 |
from errno import EIO |
| 20 |
from pathlib import Path, PurePosixPath |
| 21 |
from typing import TYPE_CHECKING, Final, Literal |
| 22 |
|
| 23 |
import pytest |
| 24 |
|
| 25 |
from filelock import SoftFileLockProtocolError |
| 26 |
from filelock._soft_rw._protocol import GenerationLog, Ledger, Participant, Snapshot, encode_holder, parse_snapshot |
| 27 |
from filelock._soft_rw._storage import OsFiles |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from collections.abc import Callable |
| 31 |
|
| 32 |
from pytest_mock import MockerFixture |
| 33 |
|
| 34 |
_FIRST = "0123456789abcdef0123456789abcdef" |
| 35 |
_SECOND = "fedcba9876543210fedcba9876543210" |
| 36 |
|
| 37 |
|
| 38 |
def _participant( |
| 39 |
files: OsFiles, |
| 40 |
lock_file: str, |
| 41 |
mode: Literal["read", "write"], |
| 42 |
*, |
| 43 |
stale_threshold: float = 100, |
| 44 |
clock: Callable[[], float] = lambda: 0.0, |
| 45 |
) -> Participant: |
| 46 |
# Each participant gets its own ledger and log, the way separate processes do. |
| 47 |
root = f"{lock_file}.rw" |
| 48 |
return Participant( |
| 49 |
files, |
| 50 |
root, |
| 51 |
mode, |
| 52 |
stale_threshold=stale_threshold, |
| 53 |
clock=clock, |
| 54 |
ledger=Ledger(clock), |
| 55 |
log=GenerationLog(files, lock_file, root), |
| 56 |
) |
| 57 |
|
| 58 |
|
| 59 |
@pytest.fixture |
| 60 |
def lock_file(tmp_path: Path) -> str: |
| 61 |
return str(tmp_path / "x.lock") |
| 62 |
|
| 63 |
|
| 64 |
@pytest.fixture |
| 65 |
def files(lock_file: str) -> OsFiles: |
| 66 |
return OsFiles(lock_file) |
| 67 |
|
| 68 |
|
| 69 |
@pytest.fixture |
| 70 |
def root(lock_file: str) -> str: |
| 71 |
return f"{lock_file}.rw" |
| 72 |
|
| 73 |
|
| 74 |
@pytest.mark.parametrize( |
| 75 |
"snapshot", |
| 76 |
[ |
| 77 |
pytest.param(Snapshot(generation=0, writer=None, readers=frozenset()), id="empty"), |
| 78 |
pytest.param(Snapshot(generation=7, writer=_FIRST, readers=frozenset()), id="writer"), |
| 79 |
pytest.param(Snapshot(generation=12, writer=None, readers=frozenset({_FIRST, _SECOND})), id="readers"), |
| 80 |
], |
| 81 |
) |
| 82 |
def test_snapshot_round_trips(snapshot: Snapshot) -> None: |
| 83 |
assert parse_snapshot(snapshot.encode()) == snapshot |
| 84 |
|
| 85 |
|
| 86 |
@pytest.mark.parametrize( |
| 87 |
"data", |
| 88 |
[ |
| 89 |
pytest.param(b"", id="empty"), |
| 90 |
pytest.param(b"x" * ((1 << 20) + 1), id="oversized"), |
| 91 |
pytest.param("filelock-rw/1\ngeneration=1\nreader=é\n".encode(), id="non-ascii"), |
| 92 |
pytest.param(b"filelock-rw/2\ngeneration=1\n", id="unknown-protocol"), |
| 93 |
pytest.param(b"filelock-rw/1\ngeneration=1", id="no-trailing-newline"), |
| 94 |
pytest.param(b"filelock-rw/1\n", id="no-generation"), |
| 95 |
pytest.param(b"filelock-rw/1\ngeneration=01\n", id="leading-zero"), |
| 96 |
pytest.param(b"filelock-rw/1\ngeneration=1\ngeneration=2\n", id="two-generations"), |
| 97 |
pytest.param(f"filelock-rw/1\ngeneration=1\nwriter={_FIRST}\nwriter={_SECOND}\n".encode(), id="two-writers"), |
| 98 |
pytest.param(f"filelock-rw/1\ngeneration=1\nreader={_FIRST}\nreader={_FIRST}\n".encode(), id="reader-twice"), |
| 99 |
pytest.param(b"filelock-rw/1\ngeneration=1\nwriter=short\n", id="bad-token"), |
| 100 |
pytest.param(b"filelock-rw/1\ngeneration=1\ncolor=blue\n", id="unknown-key"), |
| 101 |
pytest.param(b"filelock-rw/1\ngeneration=1\nno separator\n", id="no-separator"), |
| 102 |
], |
| 103 |
) |
| 104 |
def test_malformed_snapshots_parse_to_none(data: bytes) -> None: |
| 105 |
assert parse_snapshot(data) is None |
| 106 |
|
| 107 |
|
| 108 |
def test_holder_record_keeps_its_length_across_nonces() -> None: |
| 109 |
first = encode_holder(_FIRST, _SECOND) |
| 110 |
second = encode_holder(_FIRST, _FIRST) |
| 111 |
assert len(first) == len(second) |
| 112 |
assert first != second |
| 113 |
assert f"pid={os.getpid()}".encode() in first |
| 114 |
|
| 115 |
|
| 116 |
def test_ledger_measures_how_long_a_value_stays_unchanged() -> None: |
| 117 |
clock = [10.0] |
| 118 |
ledger = Ledger(lambda: clock[0]) |
| 119 |
assert ledger.observe("a", b"1") == pytest.approx(0.0) |
| 120 |
clock[0] = 12.5 |
| 121 |
assert ledger.observe("a", b"1") == pytest.approx(2.5) |
| 122 |
assert ledger.observe("a", b"2") == pytest.approx(0.0) |
| 123 |
clock[0] = 13.0 |
| 124 |
assert ledger.observe("a", None) == pytest.approx(0.0) |
| 125 |
clock[0] = 14.0 |
| 126 |
assert ledger.observe("a", None) == pytest.approx(1.0) |
| 127 |
ledger.forget("a") |
| 128 |
assert ledger.observe("a", None) == pytest.approx(0.0) |
| 129 |
|
| 130 |
|
| 131 |
def test_log_starts_empty(lock_file: str, files: OsFiles, root: str) -> None: |
| 132 |
log = GenerationLog(files, lock_file, root) |
| 133 |
assert log.latest() == Snapshot(generation=0, writer=None, readers=frozenset()) |
| 134 |
|
| 135 |
|
| 136 |
@pytest.mark.requires_hard_links |
| 137 |
def test_commit_refuses_a_generation_that_exists(lock_file: str, files: OsFiles, root: str) -> None: |
| 138 |
files.prepare(root) |
| 139 |
first = GenerationLog(files, lock_file, root) |
| 140 |
second = GenerationLog(files, lock_file, root) |
| 141 |
assert first.latest().generation == 0 |
| 142 |
assert second.latest().generation == 0 |
| 143 |
assert first.commit(Snapshot(generation=1, writer=_FIRST, readers=frozenset())) |
| 144 |
assert not second.commit(Snapshot(generation=1, writer=_SECOND, readers=frozenset())) |
| 145 |
assert second.latest().writer == _FIRST |
| 146 |
assert sorted(entry.name for entry in Path(root, "gen").iterdir()) == [f"{1:020d}"] |
| 147 |
|
| 148 |
|
| 149 |
@pytest.mark.requires_hard_links |
| 150 |
def test_rescan_skips_a_generation_removed_after_listing( |
| 151 |
lock_file: str, files: OsFiles, root: str, mocker: MockerFixture |
| 152 |
) -> None: |
| 153 |
# A listing can name a generation a peer compacts before it is read; the next older one still stands in. |
| 154 |
files.prepare(root) |
| 155 |
log = GenerationLog(files, lock_file, root) |
| 156 |
assert log.commit(Snapshot(generation=1, writer=None, readers=frozenset())) |
| 157 |
assert log.commit(Snapshot(generation=2, writer=_FIRST, readers=frozenset())) |
| 158 |
real_read = OsFiles.read |
| 159 |
latest_path = str(Path(root, "gen", f"{2:020d}")) |
| 160 |
mocker.patch.object(OsFiles, "read", side_effect=lambda path: None if path == latest_path else real_read(path)) |
| 161 |
fresh = GenerationLog(files, lock_file, root) |
| 162 |
assert fresh.latest().generation == 1 |
| 163 |
|
| 164 |
|
| 165 |
def test_malformed_generation_raises(lock_file: str, files: OsFiles, root: str) -> None: |
| 166 |
files.prepare(root) |
| 167 |
Path(root, "gen", f"{1:020d}").write_bytes(b"filelock-rw/1\ngeneration=5\n") |
| 168 |
log = GenerationLog(files, lock_file, root) |
| 169 |
with pytest.raises(SoftFileLockProtocolError, match="malformed generation record") as caught: |
| 170 |
log.latest() |
| 171 |
assert caught.value.claim_name == f"{1:020d}" |
| 172 |
|
| 173 |
|
| 174 |
def test_leave_without_entering_only_drops_the_record(lock_file: str, files: OsFiles) -> None: |
| 175 |
participant = _participant(files, lock_file, "read", stale_threshold=1) |
| 176 |
participant.publish() |
| 177 |
assert Path(f"{lock_file}.rw", "holders", participant.token).exists() |
| 178 |
participant.leave() |
| 179 |
assert not Path(f"{lock_file}.rw", "holders", participant.token).exists() |
| 180 |
assert participant.generation is None |
| 181 |
|
| 182 |
|
| 183 |
@pytest.mark.requires_hard_links |
| 184 |
def test_leave_retries_a_commit_a_peer_won(lock_file: str, files: OsFiles, root: str, mocker: MockerFixture) -> None: |
| 185 |
# A peer can publish the next generation between leave() reading the latest one and linking its successor; the |
| 186 |
# holder then re-reads and commits itself out of whatever the peer published. |
| 187 |
reader = _participant(files, lock_file, "read", stale_threshold=100) |
| 188 |
reader.publish() |
| 189 |
assert reader.advance() |
| 190 |
real_commit = GenerationLog.commit |
| 191 |
lost = [] |
| 192 |
|
| 193 |
def commit_after_a_peer(log: GenerationLog, successor: Snapshot) -> bool: |
| 194 |
if not lost: |
| 195 |
lost.append(successor) |
| 196 |
peer = GenerationLog(files, lock_file, root) |
| 197 |
still_reading = successor.readers | {reader.token} |
| 198 |
assert real_commit(peer, Snapshot(generation=successor.generation, writer=None, readers=still_reading)) |
| 199 |
return real_commit(log, successor) |
| 200 |
|
| 201 |
mocker.patch.object(GenerationLog, "commit", autospec=True, side_effect=commit_after_a_peer) |
| 202 |
reader.leave() |
| 203 |
latest = GenerationLog(files, lock_file, root).latest() |
| 204 |
assert latest.members == frozenset() |
| 205 |
assert latest.generation == lost[0].generation + 1 |
| 206 |
|
| 207 |
|
| 208 |
@pytest.mark.requires_hard_links |
| 209 |
def test_waiting_contender_republishes_a_swept_record(lock_file: str, files: OsFiles, root: str) -> None: |
| 210 |
# A record removed out from under a contender (a sweeper that mistook it, an operator) comes back on its next poll, |
| 211 |
# so peers always have a record to watch by the time the contender is admitted. |
| 212 |
writer = _participant(files, lock_file, "write", stale_threshold=100) |
| 213 |
writer.publish() |
| 214 |
assert writer.advance() |
| 215 |
reader = _participant(files, lock_file, "read", stale_threshold=100) |
| 216 |
reader.publish() |
| 217 |
record = Path(root, "holders", reader.token) |
| 218 |
record.unlink() |
| 219 |
assert not reader.advance() |
| 220 |
assert record.exists() |
| 221 |
|
| 222 |
|
| 223 |
@pytest.mark.requires_hard_links |
| 224 |
def test_waiting_contender_keeps_an_undeletable_record( |
| 225 |
lock_file: str, files: OsFiles, root: str, mocker: MockerFixture |
| 226 |
) -> None: |
| 227 |
# Windows can leave the record in place while refusing the rewrite; the contender carries on. |
| 228 |
reader = _participant(files, lock_file, "read", stale_threshold=100) |
| 229 |
reader.publish() |
| 230 |
mocker.patch.object(OsFiles, "overwrite", return_value=False) |
| 231 |
assert reader.advance() |
| 232 |
assert Path(root, "holders", reader.token).exists() |
| 233 |
|
| 234 |
|
| 235 |
@pytest.mark.requires_hard_links |
| 236 |
def test_blocked_contender_still_evicts_stale_readers(lock_file: str, files: OsFiles, root: str) -> None: |
| 237 |
# A live writer blocks entry, but a dead reader named beside it is evicted anyway so the writer can drain. |
| 238 |
clock = [0.0] |
| 239 |
dead = _participant(files, lock_file, "read", stale_threshold=1, clock=lambda: clock[0]) |
| 240 |
dead.publish() |
| 241 |
assert dead.advance() |
| 242 |
writer = _participant(files, lock_file, "write", stale_threshold=1, clock=lambda: clock[0]) |
| 243 |
writer.publish() |
| 244 |
assert not writer.advance() |
| 245 |
contender = _participant(files, lock_file, "read", stale_threshold=1, clock=lambda: clock[0]) |
| 246 |
contender.publish() |
| 247 |
assert not contender.advance() |
| 248 |
clock[0] = 5.0 |
| 249 |
assert writer.heartbeat() == ("ok", None) # keeps its own nonce fresh, so only the dead reader goes stale |
| 250 |
assert not contender.advance() |
| 251 |
latest = GenerationLog(files, lock_file, root).latest() |
| 252 |
assert latest.writer == writer.token |
| 253 |
assert latest.readers == frozenset() |
| 254 |
|
| 255 |
|
| 256 |
@pytest.mark.requires_hard_links |
| 257 |
def test_writer_admission_after_the_last_reader_leaves_is_a_commit(lock_file: str, files: OsFiles, root: str) -> None: |
| 258 |
# The final grant must publish a generation of its own: a grant read off a snapshot a peer is about to supersede |
| 259 |
# would let an evictor and the resumed writer both hold. |
| 260 |
reader = _participant(files, lock_file, "read") |
| 261 |
reader.publish() |
| 262 |
assert reader.advance() |
| 263 |
writer = _participant(files, lock_file, "write") |
| 264 |
writer.publish() |
| 265 |
assert not writer.advance() |
| 266 |
reader.leave() |
| 267 |
left_at = GenerationLog(files, lock_file, root).latest().generation |
| 268 |
assert writer.advance() |
| 269 |
assert writer.generation == left_at + 1 |
| 270 |
|
| 271 |
|
| 272 |
@pytest.mark.requires_hard_links |
| 273 |
def test_a_commit_reported_lost_that_landed_is_recognized( |
| 274 |
lock_file: str, files: OsFiles, root: str, mocker: MockerFixture |
| 275 |
) -> None: |
| 276 |
# A link that landed but whose identity check failed must not leave the writer blocking on its own token. |
| 277 |
writer = _participant(files, lock_file, "write") |
| 278 |
writer.publish() |
| 279 |
real_link = OsFiles.link |
| 280 |
denied = [] |
| 281 |
|
| 282 |
def link_then_deny(self: OsFiles, source: str, target: str) -> bool: |
| 283 |
landed = real_link(self, source, target) |
| 284 |
if landed and not denied: |
| 285 |
denied.append(target) |
| 286 |
return False |
| 287 |
return landed |
| 288 |
|
| 289 |
mocker.patch.object(OsFiles, "link", autospec=True, side_effect=link_then_deny) |
| 290 |
assert writer.advance() |
| 291 |
# The denied commit entered it at generation 1; the admission it then recognized is a commit of its own. |
| 292 |
assert writer.generation == 2 |
| 293 |
assert len(denied) == 1 |
| 294 |
assert GenerationLog(files, lock_file, root).latest().writer == writer.token |
| 295 |
|
| 296 |
|
| 297 |
@pytest.mark.requires_hard_links |
| 298 |
def test_latest_probes_across_a_compaction_hole(lock_file: str, files: OsFiles, root: str) -> None: |
| 299 |
files.prepare(root) |
| 300 |
log = GenerationLog(files, lock_file, root) |
| 301 |
for generation in range(1, 6): |
| 302 |
assert log.commit(Snapshot(generation=generation, writer=None, readers=frozenset())) |
| 303 |
Path(root, "gen", f"{3:020d}").unlink() |
| 304 |
behind = GenerationLog(files, lock_file, root) |
| 305 |
assert behind.latest().generation == 5 |
| 306 |
|
| 307 |
|
| 308 |
def test_a_listing_naming_only_compacted_generations_fails_closed( |
| 309 |
lock_file: str, files: OsFiles, root: str, mocker: MockerFixture |
| 310 |
) -> None: |
| 311 |
# A client that can see names but read none of them is behind the log by more than the retained window; treating |
| 312 |
# that as an empty log would restart the sequence and fork it. |
| 313 |
files.prepare(root) |
| 314 |
mocker.patch.object(OsFiles, "listdir", return_value=[f"{generation:020d}" for generation in (4, 5)]) |
| 315 |
with pytest.raises(SoftFileLockProtocolError, match="names no readable snapshot"): |
| 316 |
GenerationLog(files, lock_file, root).latest() |
| 317 |
|
| 318 |
|
| 319 |
@pytest.mark.requires_hard_links |
| 320 |
def test_a_listing_compacted_from_under_the_reader_is_taken_again( |
| 321 |
lock_file: str, files: OsFiles, root: str, mocker: MockerFixture |
| 322 |
) -> None: |
| 323 |
# Peers can compact every generation a listing named before this client reads one; a second listing then finds |
| 324 |
# the head rather than failing closed on the first. |
| 325 |
files.prepare(root) |
| 326 |
log = GenerationLog(files, lock_file, root) |
| 327 |
assert log.commit(Snapshot(generation=1, writer=_FIRST, readers=frozenset())) |
| 328 |
real_listdir = OsFiles.listdir |
| 329 |
listings = iter([[f"{generation:020d}" for generation in (4, 5)]]) |
| 330 |
mocker.patch.object(OsFiles, "listdir", side_effect=lambda path: next(listings, None) or real_listdir(path)) |
| 331 |
assert GenerationLog(files, lock_file, root).latest().writer == _FIRST |
| 332 |
|
| 333 |
|
| 334 |
@pytest.mark.requires_hard_links |
| 335 |
def test_heartbeat_ignores_a_broken_successor_record(lock_file: str, files: OsFiles, root: str) -> None: |
| 336 |
# A record nobody can parse breaks every acquire, and that is its own error; it says nothing about whether this |
| 337 |
# holder is alive, so the heartbeat must keep the nonce fresh rather than stop and hand the lock to a peer. |
| 338 |
writer = _participant(files, lock_file, "write") |
| 339 |
writer.publish() |
| 340 |
assert writer.advance() |
| 341 |
Path(root, "gen", f"{2:020d}").write_bytes(b"garbage\n") |
| 342 |
assert writer.heartbeat() == ("ok", None) |
| 343 |
|
| 344 |
|
| 345 |
@pytest.mark.requires_hard_links |
| 346 |
def test_heartbeat_reports_the_refresh_error(lock_file: str, files: OsFiles, mocker: MockerFixture) -> None: |
| 347 |
writer = _participant(files, lock_file, "write") |
| 348 |
writer.publish() |
| 349 |
assert writer.advance() |
| 350 |
error = OSError(EIO, "Input/output error") |
| 351 |
mocker.patch.object(OsFiles, "overwrite", side_effect=error) |
| 352 |
assert writer.heartbeat() == ("transient", error) |
| 353 |
|
| 354 |
|
| 355 |
_STALE_THRESHOLD: Final[float] = 1.0 |
| 356 |
_HEARTBEAT: Final[float] = 0.3 |
| 357 |
_POLL: Final[float] = 0.1 |
| 358 |
#: What one filesystem operation costs. Small against the heartbeat so a live participant's refreshes stay well inside |
| 359 |
#: the stale threshold however the scheduler orders its operations, as they do on a real filesystem. |
| 360 |
_STEP: Final[float] = 0.001 |
| 361 |
#: A runnable participant is scheduled again before this much fake time passes, so only a crashed one goes stale. |
| 362 |
_FAIRNESS: Final[float] = 8 * _STEP |
| 363 |
_ACQUIRE_BUDGET: Final[float] = 120.0 |
| 364 |
_ROOT: Final[str] = "/lock.rw" |
| 365 |
|
| 366 |
|
| 367 |
class _Crashed(BaseException): |
| 368 |
"""Raised inside a participant the scheduler killed; it exits at once and never touches the filesystem again.""" |
| 369 |
|
| 370 |
|
| 371 |
@dataclass |
| 372 |
class _Scheduler: |
| 373 |
""" |
| 374 |
Discrete-event scheduler: a parked participant is runnable once its wake time has passed, the clock only jumps when |
| 375 |
nothing is runnable, and every scheduled operation costs one step. A runnable participant waits at most |
| 376 |
``_FAIRNESS`` before it is picked, so only a crashed participant can ever look stale. |
| 377 |
""" |
| 378 |
|
| 379 |
seed: int |
| 380 |
crash_probability: float |
| 381 |
max_crashes: int |
| 382 |
clock: float = 0.0 |
| 383 |
crashes: int = 0 |
| 384 |
_random: random.Random = field(init=False) |
| 385 |
_condition: threading.Condition = field(default_factory=threading.Condition) |
| 386 |
_expected: int = 0 |
| 387 |
_live: set[int] = field(default_factory=set) |
| 388 |
_parked: dict[int, float] = field(default_factory=dict) |
| 389 |
_turn: int | None = None |
| 390 |
_crashed: set[int] = field(default_factory=set) |
| 391 |
|
| 392 |
def __post_init__(self) -> None: |
| 393 |
self._random = random.Random(self.seed) # ruff: ignore[suspicious-non-cryptographic-random-usage] # a seeded schedule is the point, not entropy |
| 394 |
|
| 395 |
def expect(self) -> None: |
| 396 |
# Counted before the thread starts, so the first step cannot conclude that nobody is left to run. |
| 397 |
with self._condition: |
| 398 |
self._expected += 1 |
| 399 |
|
| 400 |
def register(self) -> None: |
| 401 |
with self._condition: |
| 402 |
self._expected -= 1 |
| 403 |
self._live.add(threading.get_ident()) |
| 404 |
self._condition.notify_all() |
| 405 |
|
| 406 |
def yield_turn(self, wake_at: float | None = None) -> None: |
| 407 |
me = threading.get_ident() |
| 408 |
with self._condition: |
| 409 |
self._parked[me] = self.clock if wake_at is None else wake_at |
| 410 |
self._condition.notify_all() |
| 411 |
while self._turn != me: |
| 412 |
self._condition.wait() |
| 413 |
self._turn = None |
| 414 |
crashed = me in self._crashed |
| 415 |
if crashed: |
| 416 |
raise _Crashed |
| 417 |
|
| 418 |
def sleep(self, seconds: float) -> None: |
| 419 |
self.yield_turn(wake_at=self.clock + seconds) |
| 420 |
|
| 421 |
def finish(self) -> None: |
| 422 |
with self._condition: |
| 423 |
self._live.discard(threading.get_ident()) |
| 424 |
self._parked.pop(threading.get_ident(), None) |
| 425 |
self._condition.notify_all() |
| 426 |
|
| 427 |
def step(self) -> bool: |
| 428 |
"""Run one participant for one filesystem operation; ``False`` once every participant has finished.""" |
| 429 |
with self._condition: |
| 430 |
while self._expected or self._turn is not None or set(self._parked) != self._live: |
| 431 |
self._condition.wait() |
| 432 |
if not self._live: |
| 433 |
return False |
| 434 |
if not (runnable := [ident for ident, wake_at in self._parked.items() if wake_at <= self.clock]): |
| 435 |
self.clock = min(self._parked.values()) |
| 436 |
runnable = [ident for ident, wake_at in self._parked.items() if wake_at <= self.clock] |
| 437 |
starving = [ident for ident in runnable if self.clock - self._parked[ident] >= _FAIRNESS] |
| 438 |
chosen = self._random.choice(sorted(starving or runnable)) |
| 439 |
del self._parked[chosen] |
| 440 |
self.clock += _STEP |
| 441 |
if self.crashes < self.max_crashes and self._random.random() < self.crash_probability: |
| 442 |
self._crashed.add(chosen) |
| 443 |
self.crashes += 1 |
| 444 |
self._turn = chosen |
| 445 |
self._condition.notify_all() |
| 446 |
return True |
| 447 |
|
| 448 |
|
| 449 |
class _MemoryFiles: |
| 450 |
"""An in-memory :class:`~filelock._soft_rw._protocol.Files` whose every call is one scheduler step.""" |
| 451 |
|
| 452 |
def __init__(self, scheduler: _Scheduler, *, stale_listings: float = 0.0) -> None: |
| 453 |
self._scheduler = scheduler |
| 454 |
self.files: dict[str, bytes] = {} |
| 455 |
# An NFS client can serve a directory listing that predates a peer's commit; with this probability a listing |
| 456 |
# comes from some earlier point in the tree's history rather than from now. |
| 457 |
self._stale_listings = stale_listings |
| 458 |
self._random = random.Random(scheduler.seed + 1) # ruff: ignore[suspicious-non-cryptographic-random-usage] # a seeded schedule, not entropy |
| 459 |
self._history: list[list[str]] = [[]] |
| 460 |
|
| 461 |
def _record(self) -> None: |
| 462 |
self._history.append(sorted(self.files)) |
| 463 |
del self._history[:-128] |
| 464 |
|
| 465 |
def read(self, path: str) -> bytes | None: |
| 466 |
self._scheduler.yield_turn() |
| 467 |
return self.files.get(_key(path)) |
| 468 |
|
| 469 |
def create(self, path: str, data: bytes) -> None: |
| 470 |
self._scheduler.yield_turn() |
| 471 |
if _key(path) in self.files: # pragma: no cover # every name created here is a fresh token |
| 472 |
raise FileExistsError(path) |
| 473 |
self.files[_key(path)] = data |
| 474 |
self._record() |
| 475 |
|
| 476 |
def link(self, source: str, target: str) -> bool: |
| 477 |
self._scheduler.yield_turn() |
| 478 |
if _key(target) in self.files or _key(source) not in self.files: |
| 479 |
return False |
| 480 |
self.files[_key(target)] = self.files[_key(source)] |
| 481 |
self._record() |
| 482 |
return True |
| 483 |
|
| 484 |
def overwrite(self, path: str, data: bytes) -> bool: |
| 485 |
self._scheduler.yield_turn() |
| 486 |
if ( |
| 487 |
_key(path) not in self.files |
| 488 |
): # pragma: no cover # only a crashed participant loses its record, and it never writes again |
| 489 |
return False |
| 490 |
self.files[_key(path)] = data |
| 491 |
self._record() |
| 492 |
return True |
| 493 |
|
| 494 |
def unlink(self, path: str) -> None: |
| 495 |
self._scheduler.yield_turn() |
| 496 |
self.files.pop(_key(path), None) |
| 497 |
self._record() |
| 498 |
|
| 499 |
def listdir(self, path: str) -> list[str]: |
| 500 |
self._scheduler.yield_turn() |
| 501 |
names = ( |
| 502 |
self._random.choice(self._history) if self._random.random() < self._stale_listings else sorted(self.files) |
| 503 |
) |
| 504 |
return [PurePosixPath(name).name for name in names if str(PurePosixPath(name).parent) == _key(path)] |
| 505 |
|
| 506 |
def prepare(self, root: str) -> None: # ruff:ignore[unused-method-argument] # nothing to create in memory |
| 507 |
self._scheduler.yield_turn() |
| 508 |
|
| 509 |
|
| 510 |
def _key(path: str) -> str: |
| 511 |
# The protocol joins paths with the host separator; the in-memory tree keys them the POSIX way on every platform. |
| 512 |
return path.replace("\\", "/") |
| 513 |
|
| 514 |
|
| 515 |
@dataclass |
| 516 |
class _Outcome: |
| 517 |
mode: Literal["read", "write"] |
| 518 |
granted_at: int | None = None |
| 519 |
crashed: bool = False |
| 520 |
lost: bool = False |
| 521 |
stuck: bool = False |
| 522 |
|
| 523 |
|
| 524 |
class _Model: |
| 525 |
def __init__(self, scheduler: _Scheduler, *, stale_listings: float = 0.0) -> None: |
| 526 |
self.scheduler = scheduler |
| 527 |
self.files = _MemoryFiles(scheduler, stale_listings=stale_listings) |
| 528 |
self.holding: dict[str, Literal["read", "write"]] = {} |
| 529 |
self.last_granted = 0 |
| 530 |
self.outcomes: list[_Outcome] = [] |
| 531 |
self.threads: list[threading.Thread] = [] |
| 532 |
self.violations: list[str] = [] |
| 533 |
|
| 534 |
def add(self, mode: Literal["read", "write"], hold_beats: int) -> None: |
| 535 |
outcome = _Outcome(mode) |
| 536 |
self.outcomes.append(outcome) |
| 537 |
self.scheduler.expect() |
| 538 |
self.threads.append(threading.Thread(target=self._run, args=(outcome, hold_beats), daemon=True)) |
| 539 |
|
| 540 |
def _run(self, outcome: _Outcome, hold_beats: int) -> None: |
| 541 |
self.scheduler.register() |
| 542 |
participant = Participant( |
| 543 |
self.files, |
| 544 |
_ROOT, |
| 545 |
outcome.mode, |
| 546 |
stale_threshold=_STALE_THRESHOLD, |
| 547 |
clock=lambda: self.scheduler.clock, |
| 548 |
ledger=Ledger(lambda: self.scheduler.clock), |
| 549 |
log=GenerationLog(self.files, "/lock", _ROOT), |
| 550 |
) |
| 551 |
try: |
| 552 |
participant.publish() |
| 553 |
deadline = self.scheduler.clock + _ACQUIRE_BUDGET |
| 554 |
while not participant.advance(): |
| 555 |
if ( |
| 556 |
self.scheduler.clock >= deadline |
| 557 |
): # pragma: no cover # a liveness regression, reported by the assertion |
| 558 |
outcome.stuck = True |
| 559 |
return |
| 560 |
self.scheduler.sleep(_POLL) |
| 561 |
outcome.granted_at = participant.generation |
| 562 |
self._enter(participant.token, outcome.mode, outcome.granted_at) |
| 563 |
for _ in range(hold_beats): |
| 564 |
self.scheduler.sleep(_HEARTBEAT) |
| 565 |
if ( |
| 566 |
participant.heartbeat()[0] != "ok" |
| 567 |
): # pragma: no cover # a live holder evicted: a regression the test reports |
| 568 |
outcome.lost = True |
| 569 |
break |
| 570 |
self.holding.pop(participant.token, None) |
| 571 |
participant.leave() |
| 572 |
except _Crashed: |
| 573 |
outcome.crashed = True |
| 574 |
self.holding.pop(participant.token, None) |
| 575 |
finally: |
| 576 |
self.scheduler.finish() |
| 577 |
|
| 578 |
def _enter(self, token: str, mode: Literal["read", "write"], granted_at: int | None) -> None: |
| 579 |
# Recorded from the participant's thread while it holds the turn, so the check sees a consistent set. |
| 580 |
writers = [held for held in self.holding.values() if held == "write"] |
| 581 |
if ( |
| 582 |
granted_at is None or granted_at <= self.last_granted |
| 583 |
): # pragma: no cover # a forked log, reported by the assertion |
| 584 |
self.violations.append(f"grant at generation {granted_at} after generation {self.last_granted}") |
| 585 |
else: |
| 586 |
self.last_granted = granted_at |
| 587 |
if mode == "write" and self.holding: # pragma: no cover # an exclusion regression, reported by the assertion |
| 588 |
self.violations.append( |
| 589 |
f"writer granted at {self.scheduler.clock:.2f} while {sorted(self.holding.values())}" |
| 590 |
) |
| 591 |
elif mode == "read" and writers: # pragma: no cover # an exclusion regression, reported by the assertion |
| 592 |
self.violations.append(f"reader granted at {self.scheduler.clock:.2f} while a writer holds") |
| 593 |
self.holding[token] = mode |
| 594 |
|
| 595 |
def run(self) -> None: |
| 596 |
for thread in self.threads: |
| 597 |
thread.start() |
| 598 |
while self.scheduler.step(): |
| 599 |
pass |
| 600 |
for thread in self.threads: |
| 601 |
thread.join(timeout=30) |
| 602 |
assert not thread.is_alive() |
| 603 |
|
| 604 |
|
| 605 |
@pytest.mark.parametrize( |
| 606 |
("seed", "crash_probability", "stale_listings"), |
| 607 |
[ |
| 608 |
pytest.param( |
| 609 |
seed, |
| 610 |
probability, |
| 611 |
stale, |
| 612 |
id=f"seed{seed}-{'crashes' if probability else 'clean'}-{'stale-listings' if stale else 'fresh-listings'}", |
| 613 |
) |
| 614 |
for seed in range(24) |
| 615 |
for probability in (0.0 if seed % 3 == 0 else 0.02,) |
| 616 |
for stale in (0.3 if seed % 2 else 0.0,) |
| 617 |
], |
| 618 |
) |
| 619 |
@pytest.mark.timeout(120) |
| 620 |
def test_model_never_overlaps_and_always_progresses(seed: int, crash_probability: float, stale_listings: float) -> None: |
| 621 |
scheduler = _Scheduler(seed=seed, crash_probability=crash_probability, max_crashes=3) |
| 622 |
model = _Model(scheduler, stale_listings=stale_listings) |
| 623 |
rng = random.Random(seed) # ruff: ignore[suspicious-non-cryptographic-random-usage] # a seeded mix of hold lengths, not entropy |
| 624 |
for index in range(8): |
| 625 |
model.add("write" if index % 3 == 0 else "read", hold_beats=rng.randint(1, 4)) |
| 626 |
model.run() |
| 627 |
|
| 628 |
assert model.violations == [] |
| 629 |
survivors = [outcome for outcome in model.outcomes if not outcome.crashed] |
| 630 |
assert [outcome for outcome in survivors if outcome.stuck] == [] |
| 631 |
assert [outcome for outcome in survivors if outcome.lost] == [] |
| 632 |
assert all(outcome.granted_at is not None for outcome in survivors) |
| 633 |
assert scheduler.crashes == sum(outcome.crashed for outcome in model.outcomes) |
| 634 |
|
| 635 |
|
| 636 |
@pytest.mark.parametrize("seed", range(6)) |
| 637 |
@pytest.mark.timeout(120) |
| 638 |
def test_model_janitor_clears_every_crashed_holder(seed: int) -> None: |
| 639 |
# After the crashes, one more writer must be able to enter by evicting whatever the dead left behind, and leave the |
| 640 |
# log naming nobody and the holders directory holding nobody. |
| 641 |
scheduler = _Scheduler(seed=seed, crash_probability=0.05, max_crashes=4) |
| 642 |
model = _Model(scheduler) |
| 643 |
for index in range(6): |
| 644 |
model.add("write" if index % 2 else "read", hold_beats=2) |
| 645 |
model.run() |
| 646 |
assert model.violations == [] |
| 647 |
|
| 648 |
janitor = _Model(_Scheduler(seed=seed + 100, crash_probability=0.0, max_crashes=0)) |
| 649 |
janitor.files.files = model.files.files |
| 650 |
# Held long enough for the sweep to see an orphaned record unchanged for a full threshold and collect it. |
| 651 |
janitor.add("write", hold_beats=8) |
| 652 |
janitor.run() |
| 653 |
assert janitor.violations == [] |
| 654 |
assert janitor.outcomes[0].granted_at is not None |
| 655 |
|
| 656 |
remaining = sorted(model.files.files) |
| 657 |
generations = [name for name in remaining if name.startswith(f"{_ROOT}/gen/") and "/.commit-" not in name] |
| 658 |
assert generations, "the log must keep its latest generation" |
| 659 |
assert not [name for name in remaining if name.startswith(f"{_ROOT}/holders/")] |
| 660 |
latest = model.files.files[generations[-1]] |
| 661 |
assert b"writer=" not in latest |
| 662 |
assert b"reader=" not in latest |
| 663 |
|
| 664 |
|
| 665 |
@pytest.mark.timeout(120) |
| 666 |
def test_fencing_generations_are_strictly_increasing_across_grants() -> None: |
| 667 |
scheduler = _Scheduler(seed=7, crash_probability=0.0, max_crashes=0) |
| 668 |
model = _Model(scheduler) |
| 669 |
for index in range(9): |
| 670 |
model.add("write" if index % 3 == 0 else "read", hold_beats=1) |
| 671 |
model.run() |
| 672 |
assert model.violations == [] |
| 673 |
writers = sorted(outcome.granted_at or 0 for outcome in model.outcomes if outcome.mode == "write") |
| 674 |
assert len(set(writers)) == len(writers) |
| 675 |
for outcome in model.outcomes: |
| 676 |
assert outcome.granted_at is not None |
| 677 |
if outcome.mode == "read": |
| 678 |
assert outcome.granted_at not in writers |