Files
ds-chat/backend/app/models/message.py
T
ksmithandClaude Sonnet 5 5527b25e52 Fix the real cause of out-of-order messages: now() vs clock_timestamp() (#45)
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>
2026-08-17 13:44:48 -06:00

47 lines
2.3 KiB
Python

import uuid
from datetime import datetime
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Text, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class Message(Base):
__tablename__ = "messages"
__table_args__ = (
CheckConstraint(
"content IS NOT NULL OR image_id IS NOT NULL OR file_id IS NOT NULL",
name="messages_content_or_attachment_required",
),
)
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
room_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("rooms.id"), index=True, nullable=False)
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id"), nullable=False)
# Nullable since Phase "image uploads": a message can be an image with
# no caption. The CheckConstraint above still requires at least one of
# content/image_id/file_id.
content: Mapped[str | None] = mapped_column(Text)
image_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("message_images.id"))
file_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("message_files.id"))
# clock_timestamp(), not now()/func.now() -- the WS handler (ws/chat.py)
# shares one AsyncSession for a whole connection's lifetime, and a
# read-only op (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 the *transaction's* start
# time in that case, not the actual INSERT's -- confirmed live to be the
# actual cause of #45 (a reply sent well after an idle read-only period
# got timestamped to when that period started, sorting it before
# messages that were genuinely sent earlier). clock_timestamp() always
# reflects the real moment of execution regardless of transaction age.
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.clock_timestamp(), index=True, nullable=False
)
edited_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
user = relationship("User")
image = relationship("MessageImage")
file = relationship("MessageFile")