Post a message with one statement under the chat lock

Sending a message used to be BEGIN, a SELECT ... FOR UPDATE of the
chat with its members, a lookup of the idempotency key, the insert CTE
and COMMIT. Three of those round trips ran under the chat row lock, and
each one waited for the replica's event loop, so under load the lock
holders sat idle in transaction while everyone else queued behind
them.

The new MessageLog port has one PostgreSQL adapter that does it all in
a single statement with an implicit transaction: lock the chat row
joined with the sender's membership, stamp the message with the later
of the replica clock and the last message plus one microsecond, claim
the key (overwriting it only if it has expired), insert the message
only when the key was claimed, and move last_message_at. The foreign
key from the key to the message is checked at the end of the statement,
so the key may be written first. When the key is already taken the
adapter reads the stored result with a second statement outside the
lock, which also covers a concurrent duplicate that waited for the
first one; the handler then replays it or answers 409 as before.

The chat aggregate no longer takes part in posting, so its post,
membership and last_message_at members and their unit tests are gone;
Message.posted() builds the event. An invalid text is still answered
404 for an outsider: only then the handler reads the membership. A new
API test pins the clock rule against a real database: a lagging
replica clock gets the last stamp plus one microsecond, a clock ahead
is kept. The concurrency, same-key race, expiry and access tests pass
unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-29 01:06:49 +03:00
co-authored by Claude Opus 5.5
parent edc091dbc4
commit 22f0e6244d
8 changed files with 146 additions and 173 deletions
+19
View File
@@ -1,10 +1,13 @@
import asyncio
from datetime import UTC, datetime, timedelta
from urllib.parse import quote
from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, keyed, make_chat, register
from messenger.shared.infrastructure.clock import MonotonicUtcClock
CLIENTS = 10
PER_CLIENT = 10
@@ -60,6 +63,22 @@ async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None:
assert len(set(stamps)) == TOTAL, "created_at внутри чата обязан строго возрастать"
async def test_history_follows_the_clock_but_never_moves_back(
monkeypatch: pytest.MonkeyPatch, client: AsyncClient
) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
base = datetime.now(UTC) + timedelta(minutes=10)
stamps = []
for moment in (base, base - timedelta(minutes=5), base + timedelta(seconds=5)):
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self, moment=moment: moment)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "часы"}, headers=keyed(alice)
)
stamps.append(datetime.fromisoformat(response.json()["created_at"]))
assert stamps == [base, base + timedelta(microseconds=1), base + timedelta(seconds=5)]
async def test_parallel_registration_keeps_username_unique(client: AsyncClient) -> None:
body = {"username": f"race_{uuid4().hex[:12]}", "display_name": "Гонка", "password": PASSWORD}
responses = await asyncio.gather(*(client.post("/api/v1/users", json=body) for _ in range(20)))
+13 -48
View File
@@ -9,12 +9,11 @@ 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,
InvalidChatData,
InvalidMessageText,
)
from messenger.messaging.domain.models import Chat, Receipt
from messenger.messaging.domain.models import Chat, Message, Receipt
from messenger.messaging.domain.values import MessageText
from messenger.shared.infrastructure.clock import MonotonicUtcClock
@@ -87,17 +86,6 @@ def test_message_text_rejects_blank() -> None:
MessageText(raw)
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):
@@ -134,48 +122,25 @@ 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_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(),