Private
Public Access
Root cause, confirmed live against Postgres and reproduced end-to-end through two real WebSocket connections: ws/chat.py shares one AsyncSession for a whole connection's lifetime. A read-only action (e.g. a "join" frame's membership check) can leave a transaction open with nothing to commit it until the next write. Postgres's now()/CURRENT_TIMESTAMP returns that transaction's *start* time in that case, not the actual statement's -- so a reply sent after any idle/reading period got timestamped to when the idle period started, sorting it before messages that were genuinely sent earlier. This is independent of the two earlier #45 fixes (missing ORDER BY tiebreakers, a stale-response race on reload) -- both were real bugs, but this was the actual mechanism behind "my message appears before theirs even though theirs was sent first." Switched Message.created_at and MessageReaction.created_at from func.now() to func.clock_timestamp(), which always reflects the actual moment of execution regardless of how long the transaction has been open. Migration is a plain column-default change -- no table rewrite, no lock risk, round-trips cleanly. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
32 lines
1.2 KiB
Python
32 lines
1.2 KiB
Python
import uuid
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import DateTime, ForeignKey, String, UniqueConstraint, func
|
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
|
|
from app.models.base import Base
|
|
|
|
|
|
class MessageReaction(Base):
|
|
__tablename__ = "message_reactions"
|
|
__table_args__ = (
|
|
UniqueConstraint(
|
|
"message_id", "user_id", "emoji",
|
|
name="uq_message_reactions_message_user_emoji",
|
|
),
|
|
)
|
|
|
|
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
|
|
message_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("messages.id"), index=True, nullable=False)
|
|
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id"), nullable=False)
|
|
emoji: Mapped[str] = mapped_column(String(32), nullable=False)
|
|
# clock_timestamp(), not now() -- same transaction-pinning hazard as
|
|
# Message.created_at (see that column's comment); toggle_reaction runs
|
|
# through the same long-lived, shared WS session.
|
|
created_at: Mapped[datetime] = mapped_column(
|
|
DateTime(timezone=True), server_default=func.clock_timestamp(), nullable=False
|
|
)
|
|
|
|
message = relationship("Message")
|
|
user = relationship("User")
|