Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy
This commit is contained in:
@@ -9,13 +9,12 @@ from messenger.identity.domain.errors import InvalidUserData
|
||||
from messenger.identity.domain.models import Session, User, token_digest
|
||||
from messenger.identity.domain.values import DisplayName, Password, Username
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
)
|
||||
from messenger.messaging.domain.models import Chat, Receipt
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt, attachment_list
|
||||
from messenger.messaging.domain.values import MessageText
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
|
||||
@@ -90,17 +89,6 @@ def test_message_text_rejects_whitespace() -> None:
|
||||
assert MessageText("").value == ""
|
||||
|
||||
|
||||
def make_chat(*members: object) -> Chat:
|
||||
ids = [uuid4() for _ in members] if members else [uuid4()]
|
||||
return Chat.create(
|
||||
chat_id=uuid4(),
|
||||
title="Чат",
|
||||
member_ids=ids,
|
||||
creator_id=ids[0],
|
||||
created_at=MOMENT,
|
||||
)
|
||||
|
||||
|
||||
def test_chat_requires_creator_in_members() -> None:
|
||||
members = [uuid4(), uuid4()]
|
||||
with pytest.raises(InvalidChatData):
|
||||
@@ -137,87 +125,38 @@ def test_chat_rejects_more_than_hundred_members() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_outsider_cannot_post() -> None:
|
||||
chat = make_chat(1)
|
||||
with pytest.raises(ChatNotFound):
|
||||
chat.post(message_id=uuid4(), sender_id=uuid4(), text="привет", now=MOMENT)
|
||||
|
||||
|
||||
def test_post_never_moves_history_back() -> None:
|
||||
chat = make_chat(1)
|
||||
sender = chat.member_ids[0]
|
||||
first = chat.post(
|
||||
message_id=uuid4(), sender_id=sender, text="первое", now=MOMENT + timedelta(seconds=1)
|
||||
)
|
||||
second = chat.post(message_id=uuid4(), sender_id=sender, text="второе", now=MOMENT)
|
||||
assert second.created_at == first.created_at + timedelta(microseconds=1)
|
||||
assert chat.last_message_at == second.created_at
|
||||
|
||||
|
||||
def test_post_keeps_clock_when_it_is_ahead() -> None:
|
||||
chat = make_chat(1)
|
||||
sender = chat.member_ids[0]
|
||||
first = chat.post(message_id=uuid4(), sender_id=sender, text="первое", now=MOMENT)
|
||||
later = MOMENT + timedelta(seconds=5)
|
||||
second = chat.post(message_id=uuid4(), sender_id=sender, text="второе", now=later)
|
||||
assert first.created_at == MOMENT
|
||||
assert second.created_at == later
|
||||
|
||||
|
||||
def test_post_validates_membership_before_text() -> None:
|
||||
chat = make_chat(1)
|
||||
with pytest.raises(ChatNotFound):
|
||||
chat.post(message_id=uuid4(), sender_id=uuid4(), text="", now=MOMENT)
|
||||
|
||||
|
||||
def test_empty_text_needs_an_attachment() -> None:
|
||||
chat = make_chat(1)
|
||||
sender = chat.member_ids[0]
|
||||
with pytest.raises(InvalidMessageText):
|
||||
chat.post(message_id=uuid4(), sender_id=sender, text="", now=MOMENT)
|
||||
ids = (uuid4(), uuid4())
|
||||
message = chat.post(
|
||||
message_id=uuid4(), sender_id=sender, text="", now=MOMENT, attachment_ids=ids
|
||||
)
|
||||
assert message.attachment_ids == ids
|
||||
with pytest.raises(InvalidMessageText):
|
||||
chat.post(message_id=uuid4(), sender_id=sender, text=" ", now=MOMENT, attachment_ids=ids)
|
||||
attachment_list(MessageText(""), ())
|
||||
assert attachment_list(MessageText(""), ids) == ids
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ids", [[uuid4() for _ in range(11)], [UUID_TWICE, UUID_TWICE]])
|
||||
def test_attachment_list_is_bounded_and_unique(ids: list[UUID]) -> None:
|
||||
chat = make_chat(1)
|
||||
with pytest.raises(InvalidAttachmentList):
|
||||
chat.post(
|
||||
message_id=uuid4(),
|
||||
sender_id=chat.member_ids[0],
|
||||
text="x",
|
||||
now=MOMENT,
|
||||
attachment_ids=ids,
|
||||
)
|
||||
|
||||
|
||||
def test_membership_is_checked_before_attachments() -> None:
|
||||
chat = make_chat(1)
|
||||
with pytest.raises(ChatNotFound):
|
||||
chat.post(
|
||||
message_id=uuid4(),
|
||||
sender_id=uuid4(),
|
||||
text="",
|
||||
now=MOMENT,
|
||||
attachment_ids=[uuid4() for _ in range(11)],
|
||||
)
|
||||
attachment_list(MessageText("x"), ids)
|
||||
|
||||
|
||||
def test_receipt_replays_only_the_same_request() -> None:
|
||||
chat = make_chat(1)
|
||||
message = chat.post(message_id=uuid4(), sender_id=chat.member_ids[0], text="раз", now=MOMENT)
|
||||
message = Message(uuid4(), uuid4(), uuid4(), MessageText("раз"), MOMENT)
|
||||
receipt = Receipt("key-1", b"a" * 32, message)
|
||||
assert receipt.replay(b"a" * 32) is message
|
||||
with pytest.raises(IdempotencyConflict):
|
||||
receipt.replay(b"b" * 32)
|
||||
|
||||
|
||||
def test_posted_message_describes_itself() -> None:
|
||||
message = Message(uuid4(), uuid4(), uuid4(), MessageText("пять"), MOMENT)
|
||||
event = message.posted()
|
||||
assert (event.message_id, event.chat_id, event.sender_id) == (
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
)
|
||||
assert (event.text_length, event.created_at, event.name) == (4, MOMENT, "message.posted")
|
||||
|
||||
|
||||
def test_user_registration_emits_event() -> None:
|
||||
user, event = User.register(
|
||||
user_id=uuid4(),
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"grade4_probe", Path(__file__).resolve().parents[2] / "scripts/probe.py"
|
||||
)
|
||||
assert SPEC is not None and SPEC.loader is not None
|
||||
probe = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(probe)
|
||||
ARGS = SimpleNamespace(
|
||||
label="old", command=[], expect="replace", max_failed_ratio=0.01, max_recovery=10
|
||||
)
|
||||
|
||||
|
||||
def result_of(probes: list[tuple]) -> dict:
|
||||
result = probe.summarize(
|
||||
ARGS, probes, [(99, 2), (101, 2)], {"start": 100, "end": 101, "exit": 0, "load_end": 120}, 2
|
||||
)
|
||||
result["k6"] = {"exit": 0, "failed_ratio": 0, "requests": 100, "dropped_iterations": 0}
|
||||
result["history"] = {"exact_match": True, "unique": True}
|
||||
return result
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("attempts", "recovery", "passed"),
|
||||
[
|
||||
([(100, 503, 20, "old")], None, False),
|
||||
([(100, 503, 20, "old"), (109, 201, 2000, "new")], 11, False),
|
||||
([(100, 503, 20, "old"), (101, 201, 500, "new")], 1.5, True),
|
||||
([(101, 201, 500, "new")], 0, True),
|
||||
([], 0, False),
|
||||
],
|
||||
)
|
||||
def test_recovery_requires_completed_success(attempts: list, recovery: float, passed: bool) -> None:
|
||||
result = result_of([(99, 201, 1, "old"), *attempts])
|
||||
assert result["probe"]["recovery_s"] == recovery
|
||||
assert probe.verdict(ARGS, result)["write_recovery_ok"] is passed
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value", "check"),
|
||||
[("requests", 0, "load_delivered"), ("dropped_iterations", 1, "load_delivered")],
|
||||
)
|
||||
def test_incomplete_load_fails(field: str, value: int, check: str) -> None:
|
||||
result = result_of([(99, 201, 1, "old"), (102, 201, 1, "new")])
|
||||
result["k6"][field] = value
|
||||
assert not probe.verdict(ARGS, result)[check]
|
||||
|
||||
|
||||
def test_missing_lb_sample_fails() -> None:
|
||||
result = result_of([(99, 201, 1, "old"), (102, 201, 1, "new")])
|
||||
result["lb_samples_missing"] = 1
|
||||
assert not probe.verdict(ARGS, result)["lb_observed"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("corruption", ["none", "missing", "duplicate", "changed", "http", "cycle"])
|
||||
def test_full_history_matches_confirmed_bodies(
|
||||
monkeypatch: pytest.MonkeyPatch, corruption: str
|
||||
) -> None:
|
||||
messages = [{"id": str(n), "text": "original"} for n in range(101)]
|
||||
stored = list(reversed(messages))
|
||||
if corruption == "missing":
|
||||
stored.pop()
|
||||
if corruption == "duplicate":
|
||||
stored.append(stored[0])
|
||||
if corruption == "changed":
|
||||
stored[0] = dict(stored[0], text="changed")
|
||||
pages = iter(
|
||||
[
|
||||
(200, "", {"items": stored[:100], "next_cursor": "next"}),
|
||||
(
|
||||
503 if corruption == "http" else 200,
|
||||
"",
|
||||
{"items": stored[100:], "next_cursor": "next" if corruption == "cycle" else None},
|
||||
),
|
||||
]
|
||||
)
|
||||
monkeypatch.setattr(probe, "call", lambda *_a, **_kw: next(pages))
|
||||
result = probe.history_check({"auth": {}}, "chat", messages)
|
||||
assert (result["exact_match"] and result["unique"]) is (corruption == "none")
|
||||
@@ -0,0 +1,69 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def track(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
|
||||
script = Path(__file__).resolve().parents[2] / "scripts/reconcile_track.py"
|
||||
spec = importlib.util.spec_from_file_location("reconcile_measurements", script)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("disturbed", "quiet", "accepted", "discarded"),
|
||||
[
|
||||
([False], True, True, 0),
|
||||
([True, False], True, True, 1),
|
||||
([True, True], True, False, 2),
|
||||
([True], False, False, 1),
|
||||
],
|
||||
)
|
||||
def test_only_clean_measurements_are_accepted(
|
||||
track: ModuleType,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
*,
|
||||
disturbed: list[bool],
|
||||
quiet: bool,
|
||||
accepted: bool,
|
||||
discarded: int,
|
||||
) -> None:
|
||||
reports = [{"cost": {"cpu_seconds": 1}, "attempt": i} for i in range(len(disturbed))]
|
||||
monkeypatch.setattr(track, "sample", lambda: None)
|
||||
monkeypatch.setattr(track, "reconcile", Mock(side_effect=reports))
|
||||
monkeypatch.setattr(track, "screen", Mock(side_effect=[{"disturbed": d} for d in disturbed]))
|
||||
monkeypatch.setattr(track, "wait_quiet", lambda *_: quiet)
|
||||
chosen, rejected = track.measure([], {}, SimpleNamespace(retries=1), set())
|
||||
assert (chosen is not None) == accepted
|
||||
assert len(rejected) == discarded
|
||||
assert all(r["screen"]["disturbed"] for r in rejected)
|
||||
if chosen is not None:
|
||||
assert not chosen["screen"]["disturbed"]
|
||||
assert chosen not in rejected
|
||||
|
||||
|
||||
def test_existing_series_is_preserved_before_docker_access(
|
||||
track: ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setenv("RECONCILE_EVIDENCE_DIR", str(tmp_path))
|
||||
folder = tmp_path / "cost"
|
||||
folder.mkdir()
|
||||
raw = folder / "n1000-shallow-1.json"
|
||||
raw.write_text("previous evidence")
|
||||
query = Mock(side_effect=AssertionError("must not access the stand"))
|
||||
monkeypatch.setattr(track, "psql", query)
|
||||
with pytest.raises(FileExistsError):
|
||||
track.cost(SimpleNamespace(sizes=[1000]))
|
||||
assert raw.read_text() == "previous evidence"
|
||||
query.assert_not_called()
|
||||
|
||||
|
||||
def test_quiet_deadline_is_not_success(track: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(track.time, "monotonic", lambda: 10)
|
||||
assert not track.wait_quiet(SimpleNamespace(quiet_timeout=0), set())
|
||||
@@ -0,0 +1,80 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def scaling(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
|
||||
scripts = Path(__file__).resolve().parents[2] / "scripts"
|
||||
monkeypatch.syspath_prepend(str(scripts))
|
||||
spec = importlib.util.spec_from_file_location("scaling", scripts / "scaling.py")
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_retry_preserves_previous_raw_data(scaling: ModuleType, tmp_path: Path) -> None:
|
||||
base = {"variant": "base", "config": "1x1"}
|
||||
first = scaling.attempt_folder(tmp_path, base, 100, 1)
|
||||
(first / "k6.txt").write_text("failed attempt")
|
||||
second = scaling.attempt_folder(tmp_path, base, 100, 1)
|
||||
assert first != second
|
||||
assert (first / "k6.txt").read_text() == "failed attempt"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("recover", [False, True])
|
||||
def test_disturbed_runs_never_enter_summary(
|
||||
scaling: ModuleType, monkeypatch: pytest.MonkeyPatch, recover: bool
|
||||
) -> None:
|
||||
args = SimpleNamespace(
|
||||
base_env={}, out="unused", retries=1, pause=0, rates="100", rejected=Mock()
|
||||
)
|
||||
rejected = {"raw_dir": "attempt1", "disturbed": True, "saturated": False}
|
||||
accepted = {"raw_dir": "attempt2", "disturbed": False, "saturated": False}
|
||||
monkeypatch.setattr(scaling, "layout", lambda *_: ({}, {}))
|
||||
monkeypatch.setattr(scaling, "apply", lambda *_: {})
|
||||
monkeypatch.setattr(scaling, "deployment", lambda *_: [])
|
||||
monkeypatch.setattr(scaling, "wait_quiet", lambda *_: None)
|
||||
monkeypatch.setattr(
|
||||
scaling, "step", Mock(side_effect=[rejected, accepted if recover else rejected])
|
||||
)
|
||||
output = Mock()
|
||||
if recover:
|
||||
scaling.block(args, output, "1x1", "base", [1])
|
||||
output.writerows.assert_called_once_with([accepted])
|
||||
args.rejected.writerow.assert_called_once_with(rejected)
|
||||
else:
|
||||
with pytest.raises(SystemExit, match="exhausted retries"):
|
||||
scaling.block(args, output, "1x1", "base", [1])
|
||||
output.writerows.assert_not_called()
|
||||
assert args.rejected.writerow.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("fixed", "expected"),
|
||||
[
|
||||
(True, [("4x1", [2]), ("8x0.5", [2]), ("4x1", [3]), ("8x0.5", [3])]),
|
||||
(False, [("4x1", [2, 3]), ("8x0.5", [2, 3])]),
|
||||
],
|
||||
)
|
||||
def test_series_order(
|
||||
scaling: ModuleType,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
fixed: bool,
|
||||
expected: list[tuple[str, list[int]]],
|
||||
) -> None:
|
||||
args = SimpleNamespace(
|
||||
first_repeat=2,
|
||||
repeats=2,
|
||||
configs="4x1,8x0.5",
|
||||
variants=["pinned"],
|
||||
rates="3040,4560" if fixed else None,
|
||||
)
|
||||
block = Mock()
|
||||
monkeypatch.setattr(scaling, "block", block)
|
||||
scaling.series(args, Mock())
|
||||
assert [(call.args[2], list(call.args[4])) for call in block.call_args_list] == expected
|
||||
@@ -46,15 +46,16 @@ def test_timeouts_shrink_inwards_and_shutdown_fits_the_stop_budget() -> None:
|
||||
database = api["DB_ACQUIRE_TIMEOUT_SECONDS"] + api["DB_COMMAND_TIMEOUT_SECONDS"]
|
||||
drain, shutdown = api["DRAIN_SECONDS"], api["SHUTDOWN_TIMEOUT_SECONDS"]
|
||||
print(
|
||||
f"обнаружение {detection} с (зависание {hung} с), окно {drain} с, остановка {shutdown} с,"
|
||||
f" хук {hook} с, stop_grace_period {grace} с; LB server {lb['timeout server']} с >"
|
||||
f"обнаружение {detection} с (зависание {hung} с), окно {drain} с,"
|
||||
f" дообработка {shutdown - drain - 1} с, остановка {shutdown} с, хук {hook} с,"
|
||||
f" stop_grace_period {grace} с; LB server {lb['timeout server']} с >"
|
||||
f" запрос {api['REQUEST_TIMEOUT_SECONDS']} с > БД {database} с;"
|
||||
f" readiness {2 * PING_TIMEOUT_SECONDS} с < check {lb['timeout check']} с"
|
||||
)
|
||||
assert lb["timeout server"] > api["REQUEST_TIMEOUT_SECONDS"] > database
|
||||
assert lb["timeout check"] > 2 * PING_TIMEOUT_SECONDS
|
||||
assert drain > detection
|
||||
assert shutdown - drain >= database
|
||||
assert shutdown - drain - 1 >= database
|
||||
assert shutdown < hook < grace < 10
|
||||
assert lb["hard-stop-after"] < seconds(stand["lb"]["stop_grace_period"])
|
||||
assert (detection, hung) == (1.5, 3.5)
|
||||
|
||||
Reference in New Issue
Block a user