pytest-racekit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pytest_racekit-0.1.0.dist-info/METADATA +169 -0
- pytest_racekit-0.1.0.dist-info/RECORD +25 -0
- pytest_racekit-0.1.0.dist-info/WHEEL +4 -0
- pytest_racekit-0.1.0.dist-info/entry_points.txt +6 -0
- pytest_racekit-0.1.0.dist-info/licenses/LICENSE +201 -0
- racekit/__init__.py +31 -0
- racekit/cli.py +104 -0
- racekit/invariants/__init__.py +1 -0
- racekit/invariants/checks.py +43 -0
- racekit/invariants/result.py +144 -0
- racekit/pg/__init__.py +29 -0
- racekit/pg/force.py +78 -0
- racekit/pg/pause.py +108 -0
- racekit/pg/snapshot.py +79 -0
- racekit/py.typed +0 -0
- racekit/pytest_plugin.py +79 -0
- racekit/race.py +74 -0
- racekit/runner/__init__.py +1 -0
- racekit/runner/aio.py +135 -0
- racekit/runner/capture.py +39 -0
- racekit/runner/gate.py +41 -0
- racekit/runner/rng.py +49 -0
- racekit/runner/rounds.py +82 -0
- racekit/runner/threads.py +142 -0
- racekit/scenarios/__init__.py +155 -0
racekit/runner/aio.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""The asyncio backend: ``await racekit.arun(...)``, the same rounds as ``racekit.run``.
|
|
2
|
+
|
|
3
|
+
One event loop, one task per client per round. Each round:
|
|
4
|
+
|
|
5
|
+
1. every task counts itself as parked and waits on one ``asyncio.Event`` (the gate);
|
|
6
|
+
2. when the last one has parked, the coordinator sets the event and the loop resumes them
|
|
7
|
+
one after another, each noting the time and starting its call;
|
|
8
|
+
3. the coordinator waits for all of them, with a timeout.
|
|
9
|
+
|
|
10
|
+
Differences from the thread backend, all from asyncio itself: tasks are cheap, so many clients
|
|
11
|
+
cost little; the loop resumes tasks in one thread, so there is no GIL contention between them;
|
|
12
|
+
and a hung call can be *cancelled*, which a thread cannot.
|
|
13
|
+
|
|
14
|
+
``prepare``, ``reset`` and ``check`` may be plain or ``async`` functions.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import inspect
|
|
21
|
+
import random
|
|
22
|
+
import time
|
|
23
|
+
from collections.abc import Awaitable, Callable
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from racekit.invariants.result import RoundResult, RunResult
|
|
27
|
+
from racekit.runner import rng
|
|
28
|
+
from racekit.runner.capture import CallRecord
|
|
29
|
+
from racekit.runner.rounds import wants_round
|
|
30
|
+
from racekit.runner.threads import PrepareError, RoundTimeout
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def arun(
|
|
34
|
+
call: Callable[..., Awaitable[Any]],
|
|
35
|
+
*,
|
|
36
|
+
clients: int,
|
|
37
|
+
rounds: int = 1,
|
|
38
|
+
prepare: Callable[[int], Any] | None = None,
|
|
39
|
+
reset: Callable[[], object] | None = None,
|
|
40
|
+
check: Callable[..., object] | None = None,
|
|
41
|
+
seed: int | None = None,
|
|
42
|
+
round_timeout: float = 30.0,
|
|
43
|
+
) -> RunResult:
|
|
44
|
+
"""Like ``racekit.run``, with ``call`` an ``async def`` run as tasks on the current loop."""
|
|
45
|
+
if clients < 2:
|
|
46
|
+
raise ValueError("clients must be at least 2: one client cannot race")
|
|
47
|
+
if rounds < 1:
|
|
48
|
+
raise ValueError("rounds must be at least 1")
|
|
49
|
+
if not inspect.iscoroutinefunction(call):
|
|
50
|
+
raise TypeError("arun needs an async def call; use racekit.run for plain functions")
|
|
51
|
+
if seed is None:
|
|
52
|
+
seed = random.SystemRandom().randrange(2**32)
|
|
53
|
+
|
|
54
|
+
states: list[Any] = []
|
|
55
|
+
if prepare is not None:
|
|
56
|
+
for i in range(clients):
|
|
57
|
+
try:
|
|
58
|
+
states.append(await _maybe_await(prepare(i)))
|
|
59
|
+
except Exception as exc:
|
|
60
|
+
raise PrepareError(f"prepare failed for client {i}: {exc!r}") from exc
|
|
61
|
+
|
|
62
|
+
result = RunResult(seed=seed, clients=clients)
|
|
63
|
+
for number in range(1, rounds + 1):
|
|
64
|
+
if reset is not None:
|
|
65
|
+
await _maybe_await(reset())
|
|
66
|
+
records = await _round(call, clients, states, seed, number, round_timeout)
|
|
67
|
+
this = RoundResult(number, records)
|
|
68
|
+
this.violated, this.check_message = await _check(check, this)
|
|
69
|
+
result.rounds.append(this)
|
|
70
|
+
return result
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def _round(
|
|
74
|
+
call: Callable[..., Awaitable[Any]],
|
|
75
|
+
clients: int,
|
|
76
|
+
states: list[Any],
|
|
77
|
+
seed: int,
|
|
78
|
+
number: int,
|
|
79
|
+
timeout: float,
|
|
80
|
+
) -> list[CallRecord]:
|
|
81
|
+
records = [CallRecord(i) for i in range(clients)]
|
|
82
|
+
gate = asyncio.Event()
|
|
83
|
+
everyone_parked = asyncio.Event()
|
|
84
|
+
parked = 0
|
|
85
|
+
|
|
86
|
+
async def worker(index: int) -> None:
|
|
87
|
+
nonlocal parked
|
|
88
|
+
parked += 1
|
|
89
|
+
if parked == clients:
|
|
90
|
+
everyone_parked.set()
|
|
91
|
+
await gate.wait()
|
|
92
|
+
record = records[index]
|
|
93
|
+
record.released = time.perf_counter()
|
|
94
|
+
rng.set_current(rng.for_call(seed, number, index)) # this task's own context
|
|
95
|
+
try:
|
|
96
|
+
record.value = await (call(index, states[index]) if states else call(index))
|
|
97
|
+
# Exception, not BaseException: cancellation (a timed-out round) must propagate.
|
|
98
|
+
except Exception as exc:
|
|
99
|
+
record.error = exc
|
|
100
|
+
finally:
|
|
101
|
+
record.ended = time.perf_counter()
|
|
102
|
+
|
|
103
|
+
# The loop resumes waiters in the order they were created: shuffle it, as the threads do.
|
|
104
|
+
order = rng.start_order(seed, number, clients)
|
|
105
|
+
by_client = {i: asyncio.create_task(worker(i)) for i in order}
|
|
106
|
+
tasks = [by_client[i] for i in range(clients)]
|
|
107
|
+
await everyone_parked.wait()
|
|
108
|
+
gate.set()
|
|
109
|
+
_, pending = await asyncio.wait(tasks, timeout=timeout)
|
|
110
|
+
if pending:
|
|
111
|
+
for task in pending:
|
|
112
|
+
task.cancel()
|
|
113
|
+
await asyncio.gather(*pending, return_exceptions=True)
|
|
114
|
+
stuck = [i for i, task in enumerate(tasks) if task in pending]
|
|
115
|
+
raise RoundTimeout(
|
|
116
|
+
f"round {number}: {len(pending)} call(s) still running after {timeout:g} s"
|
|
117
|
+
f" (clients {stuck[:10]}); they were cancelled"
|
|
118
|
+
)
|
|
119
|
+
return records
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def _check(check: Callable[..., object] | None, this: RoundResult) -> tuple[bool, str | None]:
|
|
123
|
+
if check is None:
|
|
124
|
+
return False, None
|
|
125
|
+
try:
|
|
126
|
+
outcome = await _maybe_await(check(this) if wants_round(check) else check())
|
|
127
|
+
except AssertionError as exc:
|
|
128
|
+
return True, str(exc) or "AssertionError"
|
|
129
|
+
if outcome is False:
|
|
130
|
+
return True, "check returned False"
|
|
131
|
+
return False, None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def _maybe_await(value: object) -> object:
|
|
135
|
+
return await value if inspect.isawaitable(value) else value
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""What the runner records about one call."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class CallRecord:
|
|
11
|
+
"""One client's call in one round.
|
|
12
|
+
|
|
13
|
+
``released`` and ``ended`` are ``time.perf_counter()`` values: when the worker left the
|
|
14
|
+
barrier and when its call returned or raised. They are comparable within one run only.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
index: int
|
|
18
|
+
released: float = 0.0
|
|
19
|
+
ended: float = 0.0
|
|
20
|
+
value: Any = None
|
|
21
|
+
error: BaseException | None = None
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def ok(self) -> bool:
|
|
25
|
+
return self.error is None
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def latency_ms(self) -> float:
|
|
29
|
+
return (self.ended - self.released) * 1000
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def status(self) -> int | None:
|
|
33
|
+
"""The HTTP status, if the call returned something with an integer ``status_code``.
|
|
34
|
+
|
|
35
|
+
Duck typing keeps the runner free of any HTTP library: httpx and requests responses
|
|
36
|
+
both have ``status_code``.
|
|
37
|
+
"""
|
|
38
|
+
code = getattr(self.value, "status_code", None)
|
|
39
|
+
return code if isinstance(code, int) else None
|
racekit/runner/gate.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""The starting gate: park every worker, then release them together.
|
|
2
|
+
|
|
3
|
+
A ``threading.Barrier`` with one party per worker plus one for the coordinator. Every worker
|
|
4
|
+
is already blocked inside ``wait()`` before the coordinator arrives, so the release costs one
|
|
5
|
+
wake-up per thread rather than one thread start per thread.
|
|
6
|
+
|
|
7
|
+
The release is not instant: Python wakes the threads one after another, and each needs the
|
|
8
|
+
GIL to run. ``spread_ms`` measures how far apart they really left, from each worker's own
|
|
9
|
+
clock reading right after ``wait()`` returns.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Iterable
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Gate:
|
|
20
|
+
def __init__(self, workers: int) -> None:
|
|
21
|
+
self._barrier = threading.Barrier(workers + 1)
|
|
22
|
+
|
|
23
|
+
def wait(self, timeout: float | None = None) -> float:
|
|
24
|
+
"""Block until every party has arrived; return the instant this caller left.
|
|
25
|
+
|
|
26
|
+
Raises ``threading.BrokenBarrierError`` if the gate was aborted or timed out.
|
|
27
|
+
"""
|
|
28
|
+
self._barrier.wait(timeout)
|
|
29
|
+
return time.perf_counter()
|
|
30
|
+
|
|
31
|
+
def abort(self) -> None:
|
|
32
|
+
"""Release everyone still waiting with ``BrokenBarrierError``. Used to shut down."""
|
|
33
|
+
self._barrier.abort()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def spread_ms(released: Iterable[float]) -> float:
|
|
37
|
+
"""Milliseconds between the first and the last worker leaving the gate."""
|
|
38
|
+
times = list(released)
|
|
39
|
+
if len(times) < 2:
|
|
40
|
+
return 0.0
|
|
41
|
+
return (max(times) - min(times)) * 1000
|
racekit/runner/rng.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""``racekit.rng()``: a random generator for the current call, fixed by the run's seed.
|
|
2
|
+
|
|
3
|
+
Each call gets ``random.Random(f"{seed}:{round}:{index}")``. String seeds are hashed with
|
|
4
|
+
SHA-512, so the same seed, round and client always give the same numbers, on any machine and
|
|
5
|
+
in any thread order. That makes a failing round's *inputs* reproducible. Its *timing* is not:
|
|
6
|
+
the operating system decides how threads are scheduled.
|
|
7
|
+
|
|
8
|
+
The current generator lives in a ``ContextVar``: each worker thread has its own context, and
|
|
9
|
+
each asyncio task gets a copy of its creator's, so threads and tasks never see each other's.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import random
|
|
15
|
+
from contextvars import ContextVar
|
|
16
|
+
|
|
17
|
+
_current: ContextVar[random.Random | None] = ContextVar("racekit_rng", default=None)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def rng() -> random.Random:
|
|
21
|
+
"""The random generator of the call running here (this thread or this task).
|
|
22
|
+
|
|
23
|
+
Only valid inside a function passed to ``racekit.run`` or ``racekit.arun``; raises
|
|
24
|
+
``RuntimeError`` elsewhere.
|
|
25
|
+
"""
|
|
26
|
+
generator = _current.get()
|
|
27
|
+
if generator is None:
|
|
28
|
+
raise RuntimeError(
|
|
29
|
+
"racekit.rng() is only available inside a call made by racekit.run or racekit.arun"
|
|
30
|
+
)
|
|
31
|
+
return generator
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def for_call(seed: int, round_number: int, index: int) -> random.Random:
|
|
35
|
+
return random.Random(f"{seed}:{round_number}:{index}")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def start_order(seed: int, round_number: int, clients: int) -> list[int]:
|
|
39
|
+
"""A seeded shuffle of the clients, for the order they are started in this round.
|
|
40
|
+
|
|
41
|
+
A barrier (or an event loop) releases its waiters in much the same order every round, so
|
|
42
|
+
without this, client 0 would nearly always start first and a race that depends on who goes
|
|
43
|
+
first would be caught either almost always or almost never.
|
|
44
|
+
"""
|
|
45
|
+
return random.Random(f"{seed}:{round_number}:order").sample(range(clients), clients)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def set_current(generator: random.Random | None) -> None:
|
|
49
|
+
_current.set(generator)
|
racekit/runner/rounds.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""``racekit.run``: the round loop around the worker pool."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import random
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from racekit.invariants.result import RoundResult, RunResult
|
|
11
|
+
from racekit.runner.threads import WorkerPool
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def run(
|
|
15
|
+
call: Callable[..., Any],
|
|
16
|
+
*,
|
|
17
|
+
clients: int,
|
|
18
|
+
rounds: int = 1,
|
|
19
|
+
prepare: Callable[[int], Any] | None = None,
|
|
20
|
+
reset: Callable[[], object] | None = None,
|
|
21
|
+
check: Callable[..., object] | None = None,
|
|
22
|
+
seed: int | None = None,
|
|
23
|
+
round_timeout: float = 30.0,
|
|
24
|
+
) -> RunResult:
|
|
25
|
+
"""Release ``clients`` calls together, ``rounds`` times, checking the invariant after each.
|
|
26
|
+
|
|
27
|
+
- ``call(i)`` is made once per client per round; ``i`` is the client index. With
|
|
28
|
+
``prepare``, it is ``call(i, state)`` where ``state = prepare(i)``.
|
|
29
|
+
- ``prepare(i)`` runs once per client, in that client's worker thread, before the first
|
|
30
|
+
round and outside the timed window: open connections here.
|
|
31
|
+
- ``reset()`` runs before every round.
|
|
32
|
+
- ``check()`` runs after every round. Returning ``False`` or raising ``AssertionError``
|
|
33
|
+
marks the round as violated; any other return value (``None`` included, so a function
|
|
34
|
+
that only asserts works) passes. Any other exception stops the run: a broken check is a
|
|
35
|
+
bug, not a finding. A check that takes one argument, ``check(round)``, is given the
|
|
36
|
+
round's ``RoundResult``, so it can look at the responses too.
|
|
37
|
+
- ``seed`` fixes ``racekit.rng()`` for every call; a random one is chosen and recorded if
|
|
38
|
+
not given.
|
|
39
|
+
"""
|
|
40
|
+
if clients < 2:
|
|
41
|
+
raise ValueError("clients must be at least 2: one client cannot race")
|
|
42
|
+
if rounds < 1:
|
|
43
|
+
raise ValueError("rounds must be at least 1")
|
|
44
|
+
if seed is None:
|
|
45
|
+
seed = random.SystemRandom().randrange(2**32)
|
|
46
|
+
|
|
47
|
+
result = RunResult(seed=seed, clients=clients)
|
|
48
|
+
pool = WorkerPool(call, clients, prepare, seed, round_timeout)
|
|
49
|
+
pool.start()
|
|
50
|
+
try:
|
|
51
|
+
for number in range(1, rounds + 1):
|
|
52
|
+
if reset is not None:
|
|
53
|
+
reset()
|
|
54
|
+
this = RoundResult(number, pool.run_round(number))
|
|
55
|
+
this.violated, this.check_message = judge(check, this)
|
|
56
|
+
result.rounds.append(this)
|
|
57
|
+
finally:
|
|
58
|
+
pool.close()
|
|
59
|
+
return result
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def judge(check: Callable[..., object] | None, this: RoundResult) -> tuple[bool, str | None]:
|
|
63
|
+
"""Run ``check`` on a finished round: (violated, why). Shared by every round loop."""
|
|
64
|
+
if check is None:
|
|
65
|
+
return False, None
|
|
66
|
+
try:
|
|
67
|
+
outcome = check(this) if wants_round(check) else check()
|
|
68
|
+
except AssertionError as exc:
|
|
69
|
+
return True, str(exc) or "AssertionError"
|
|
70
|
+
if outcome is False:
|
|
71
|
+
return True, "check returned False"
|
|
72
|
+
return False, None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def wants_round(check: Callable[..., object]) -> bool:
|
|
76
|
+
"""Whether ``check`` has a required positional parameter, so it takes the round."""
|
|
77
|
+
try:
|
|
78
|
+
parameters = inspect.signature(check).parameters.values()
|
|
79
|
+
except (TypeError, ValueError): # some builtins have no signature: call them bare
|
|
80
|
+
return False
|
|
81
|
+
positional = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
|
|
82
|
+
return any(p.kind in positional and p.default is p.empty for p in parameters)
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""The thread backend: one long-lived worker thread per client.
|
|
2
|
+
|
|
3
|
+
Workers are started once and reused every round, so thread creation never falls inside the
|
|
4
|
+
race window. Each round:
|
|
5
|
+
|
|
6
|
+
1. the coordinator hands out fresh ``CallRecord``s and arrives at the gate;
|
|
7
|
+
2. every worker leaves the gate, notes the time and makes its call;
|
|
8
|
+
3. every worker arrives at the "done" barrier; the coordinator waits there too, with a timeout.
|
|
9
|
+
|
|
10
|
+
A call that raises is recorded and the worker carries on to the "done" barrier, so one
|
|
11
|
+
failure never strands the others. A call that hangs cannot be stopped (Python threads cannot
|
|
12
|
+
be killed), so the round times out and the run ends with an error naming the stuck clients.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from racekit.runner import rng
|
|
23
|
+
from racekit.runner.capture import CallRecord
|
|
24
|
+
from racekit.runner.gate import Gate
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class PrepareError(RuntimeError):
|
|
28
|
+
"""``prepare`` raised for at least one client, so no round was run."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RoundTimeout(RuntimeError):
|
|
32
|
+
"""At least one call did not finish within ``round_timeout``."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class WorkerPool:
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
call: Callable[..., Any],
|
|
39
|
+
clients: int,
|
|
40
|
+
prepare: Callable[[int], Any] | None,
|
|
41
|
+
seed: int,
|
|
42
|
+
round_timeout: float,
|
|
43
|
+
) -> None:
|
|
44
|
+
self._call = call
|
|
45
|
+
self._clients = clients
|
|
46
|
+
self._prepare = prepare
|
|
47
|
+
self._seed = seed
|
|
48
|
+
self._timeout = round_timeout
|
|
49
|
+
self._ready = threading.Barrier(clients + 1)
|
|
50
|
+
self._gate = Gate(clients)
|
|
51
|
+
self._done = threading.Barrier(clients + 1)
|
|
52
|
+
self._prepare_errors: dict[int, BaseException] = {}
|
|
53
|
+
self._records: list[CallRecord] = []
|
|
54
|
+
self._states: list[Any] = [None] * clients
|
|
55
|
+
# Which client each worker thread runs this round: shuffled per round by the seed.
|
|
56
|
+
self._order = list(range(clients))
|
|
57
|
+
self._round = 0
|
|
58
|
+
self._threads = [
|
|
59
|
+
threading.Thread(target=self._work, args=(i,), name=f"racekit-{i}", daemon=True)
|
|
60
|
+
for i in range(clients)
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
# -- coordinator side ----------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
def start(self) -> None:
|
|
66
|
+
"""Start the workers and wait until each has run ``prepare``."""
|
|
67
|
+
for thread in self._threads:
|
|
68
|
+
thread.start()
|
|
69
|
+
try:
|
|
70
|
+
self._ready.wait(self._timeout)
|
|
71
|
+
except threading.BrokenBarrierError:
|
|
72
|
+
self.close()
|
|
73
|
+
raise PrepareError(
|
|
74
|
+
f"prepare did not finish for every client within {self._timeout:g} s"
|
|
75
|
+
) from None
|
|
76
|
+
if self._prepare_errors:
|
|
77
|
+
self.close()
|
|
78
|
+
first = min(self._prepare_errors)
|
|
79
|
+
raise PrepareError(
|
|
80
|
+
f"prepare failed for {len(self._prepare_errors)} of {self._clients} clients;"
|
|
81
|
+
f" client {first}: {self._prepare_errors[first]!r}"
|
|
82
|
+
) from self._prepare_errors[first]
|
|
83
|
+
|
|
84
|
+
def run_round(self, number: int) -> list[CallRecord]:
|
|
85
|
+
self._round = number
|
|
86
|
+
self._records = [CallRecord(i) for i in range(self._clients)]
|
|
87
|
+
self._order = rng.start_order(self._seed, number, self._clients)
|
|
88
|
+
try:
|
|
89
|
+
self._gate.wait(self._timeout)
|
|
90
|
+
self._done.wait(self._timeout)
|
|
91
|
+
except threading.BrokenBarrierError:
|
|
92
|
+
stuck = [r.index for r in self._records if r.ended == 0.0]
|
|
93
|
+
self.close()
|
|
94
|
+
raise RoundTimeout(
|
|
95
|
+
f"round {number}: {len(stuck)} call(s) still running after"
|
|
96
|
+
f" {self._timeout:g} s (clients {stuck[:10]})"
|
|
97
|
+
) from None
|
|
98
|
+
return self._records
|
|
99
|
+
|
|
100
|
+
def close(self) -> None:
|
|
101
|
+
"""Release every worker that is waiting, so it can exit."""
|
|
102
|
+
self._gate.abort()
|
|
103
|
+
self._done.abort()
|
|
104
|
+
self._ready.abort()
|
|
105
|
+
|
|
106
|
+
# -- worker side ---------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
def _work(self, slot: int) -> None:
|
|
109
|
+
if self._prepare is not None:
|
|
110
|
+
try:
|
|
111
|
+
self._states[slot] = self._prepare(slot)
|
|
112
|
+
except BaseException as exc: # reported by start(); must not strand the others
|
|
113
|
+
self._prepare_errors[slot] = exc
|
|
114
|
+
try:
|
|
115
|
+
self._ready.wait()
|
|
116
|
+
except threading.BrokenBarrierError:
|
|
117
|
+
return
|
|
118
|
+
while True:
|
|
119
|
+
try:
|
|
120
|
+
released = self._gate.wait()
|
|
121
|
+
except threading.BrokenBarrierError:
|
|
122
|
+
return
|
|
123
|
+
# The barrier wakes threads in much the same order every round, so the client a
|
|
124
|
+
# thread runs is shuffled instead: otherwise client 0 would nearly always go first.
|
|
125
|
+
index = self._order[slot]
|
|
126
|
+
record = self._records[index]
|
|
127
|
+
record.released = released
|
|
128
|
+
rng.set_current(rng.for_call(self._seed, self._round, index))
|
|
129
|
+
try:
|
|
130
|
+
if self._prepare is None:
|
|
131
|
+
record.value = self._call(index)
|
|
132
|
+
else:
|
|
133
|
+
record.value = self._call(index, self._states[index])
|
|
134
|
+
except BaseException as exc: # recorded, never raised: the others must not hang
|
|
135
|
+
record.error = exc
|
|
136
|
+
finally:
|
|
137
|
+
record.ended = time.perf_counter()
|
|
138
|
+
rng.set_current(None)
|
|
139
|
+
try:
|
|
140
|
+
self._done.wait()
|
|
141
|
+
except threading.BrokenBarrierError:
|
|
142
|
+
return
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Ready-made races, each a thin layer over ``racekit.run``.
|
|
2
|
+
|
|
3
|
+
- ``duplicate``: the same request several times at once (retries, double clicks).
|
|
4
|
+
- ``lost_update``: many read-modify-write updates at once; checks none went missing.
|
|
5
|
+
- ``interleave``: different named steps at once (pay against cancel).
|
|
6
|
+
|
|
7
|
+
Rounds, reset, seed, spread and the report work exactly as with ``racekit.run``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Callable, Mapping
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from racekit.invariants.result import RoundResult, RunResult
|
|
16
|
+
from racekit.runner.capture import CallRecord
|
|
17
|
+
from racekit.runner.rounds import run
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def duplicate(
|
|
21
|
+
call: Callable[..., Any],
|
|
22
|
+
*,
|
|
23
|
+
copies: int = 5,
|
|
24
|
+
rounds: int = 1,
|
|
25
|
+
prepare: Callable[[int], Any] | None = None,
|
|
26
|
+
reset: Callable[[], object] | None = None,
|
|
27
|
+
check: Callable[..., object] | None = None,
|
|
28
|
+
seed: int | None = None,
|
|
29
|
+
round_timeout: float = 30.0,
|
|
30
|
+
) -> RunResult:
|
|
31
|
+
"""Send the same request ``copies`` times at once, ``rounds`` times.
|
|
32
|
+
|
|
33
|
+
``call()`` takes no client index: every copy is the same request. With ``prepare`` it is
|
|
34
|
+
``call(state)``, each copy with its own state (its own connection, say).
|
|
35
|
+
"""
|
|
36
|
+
if prepare is None:
|
|
37
|
+
return run(
|
|
38
|
+
lambda i: call(),
|
|
39
|
+
clients=copies,
|
|
40
|
+
rounds=rounds,
|
|
41
|
+
reset=reset,
|
|
42
|
+
check=check,
|
|
43
|
+
seed=seed,
|
|
44
|
+
round_timeout=round_timeout,
|
|
45
|
+
)
|
|
46
|
+
return run(
|
|
47
|
+
lambda i, state: call(state),
|
|
48
|
+
clients=copies,
|
|
49
|
+
rounds=rounds,
|
|
50
|
+
prepare=prepare,
|
|
51
|
+
reset=reset,
|
|
52
|
+
check=check,
|
|
53
|
+
seed=seed,
|
|
54
|
+
round_timeout=round_timeout,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def acknowledged(call: CallRecord) -> bool:
|
|
59
|
+
"""A call the service said yes to: it returned, with a 2xx status or no status at all."""
|
|
60
|
+
return call.ok and (call.status is None or 200 <= call.status < 300)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def lost_update(
|
|
64
|
+
apply: Callable[..., Any],
|
|
65
|
+
*,
|
|
66
|
+
read: Callable[[], float],
|
|
67
|
+
clients: int,
|
|
68
|
+
delta: float = 1,
|
|
69
|
+
rounds: int = 1,
|
|
70
|
+
prepare: Callable[[int], Any] | None = None,
|
|
71
|
+
reset: Callable[[], object] | None = None,
|
|
72
|
+
seed: int | None = None,
|
|
73
|
+
round_timeout: float = 30.0,
|
|
74
|
+
) -> RunResult:
|
|
75
|
+
"""``clients`` updates at once, each adding ``delta``; check that none went missing.
|
|
76
|
+
|
|
77
|
+
Before each round (after ``reset``), ``read()`` gives the starting value. After it, the
|
|
78
|
+
value must equal the start plus ``delta`` for every *acknowledged* update (2xx, or no
|
|
79
|
+
exception for non-HTTP calls). Counting only acknowledged updates means a service that
|
|
80
|
+
correctly refuses some updates under contention is not accused of losing them.
|
|
81
|
+
"""
|
|
82
|
+
start: dict[str, float] = {}
|
|
83
|
+
|
|
84
|
+
def reset_and_read() -> None:
|
|
85
|
+
if reset is not None:
|
|
86
|
+
reset()
|
|
87
|
+
start["value"] = read()
|
|
88
|
+
|
|
89
|
+
def check(this: RoundResult) -> None:
|
|
90
|
+
said_yes = sum(acknowledged(c) for c in this.calls)
|
|
91
|
+
expected = start["value"] + delta * said_yes
|
|
92
|
+
actual = read()
|
|
93
|
+
if actual != expected: # not `assert`: see racekit/invariants/checks.py
|
|
94
|
+
raise AssertionError(
|
|
95
|
+
f"{said_yes} updates acknowledged: expected {expected:g}, found {actual:g}"
|
|
96
|
+
f" ({(expected - actual) / delta:g} updates lost)"
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
return run(
|
|
100
|
+
apply,
|
|
101
|
+
clients=clients,
|
|
102
|
+
rounds=rounds,
|
|
103
|
+
prepare=prepare,
|
|
104
|
+
reset=reset_and_read,
|
|
105
|
+
check=check,
|
|
106
|
+
seed=seed,
|
|
107
|
+
round_timeout=round_timeout,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def interleave(
|
|
112
|
+
steps: Mapping[str, Callable[..., Any]],
|
|
113
|
+
*,
|
|
114
|
+
copies: int = 1,
|
|
115
|
+
rounds: int = 1,
|
|
116
|
+
prepare: Callable[[int], Any] | None = None,
|
|
117
|
+
reset: Callable[[], object] | None = None,
|
|
118
|
+
check: Callable[..., object] | None = None,
|
|
119
|
+
seed: int | None = None,
|
|
120
|
+
round_timeout: float = 30.0,
|
|
121
|
+
) -> RunResult:
|
|
122
|
+
"""Release different named steps together: ``copies`` of each, ``rounds`` times.
|
|
123
|
+
|
|
124
|
+
Each step is called with its copy number ``k`` (0 to ``copies - 1``), so copy ``k`` of
|
|
125
|
+
every step can work on the same thing, for example order ``k``. With ``prepare`` the
|
|
126
|
+
call is ``step(k, state)``. The result's ``steps`` names the step each client ran, and the
|
|
127
|
+
report shows statuses per step.
|
|
128
|
+
"""
|
|
129
|
+
if len(steps) < 2:
|
|
130
|
+
raise ValueError("interleave needs at least two steps")
|
|
131
|
+
if copies < 1:
|
|
132
|
+
raise ValueError("copies must be at least 1")
|
|
133
|
+
names = list(steps)
|
|
134
|
+
# Client i runs step names[i % len(names)] on copy i // len(names): pay 0, cancel 0, ...
|
|
135
|
+
plan = [(names[i % len(names)], i // len(names)) for i in range(len(names) * copies)]
|
|
136
|
+
|
|
137
|
+
def call(i: int, *state: Any) -> Any:
|
|
138
|
+
name, k = plan[i]
|
|
139
|
+
return steps[name](k, *state)
|
|
140
|
+
|
|
141
|
+
result = run(
|
|
142
|
+
call,
|
|
143
|
+
clients=len(plan),
|
|
144
|
+
rounds=rounds,
|
|
145
|
+
prepare=prepare,
|
|
146
|
+
reset=reset,
|
|
147
|
+
check=check,
|
|
148
|
+
seed=seed,
|
|
149
|
+
round_timeout=round_timeout,
|
|
150
|
+
)
|
|
151
|
+
result.steps = [name for name, _ in plan]
|
|
152
|
+
return result
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
__all__ = ["acknowledged", "duplicate", "interleave", "lost_update"]
|