Skip to content

Commit 54332ba

Browse files
fix(postgres): default created_at and updated_at to now() so a non-UTC session does not shift them (#79)
timezone('UTC', now()) is a timestamp without zone, and the cast into the timestamptz column reads it in the session TimeZone. In a Europe/Moscow session both columns ended up 3 hours in the past. Same bug as bedrock-python/sqlalchemy-foundation-kit#88.
1 parent fb05698 commit 54332ba

4 files changed

Lines changed: 122 additions & 11 deletions

File tree

‎docs/agents.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,10 @@ Abstract ORM bases — bind them to your own `DeclarativeBase`: `OutboxEventDBBa
394394
`InboxEventDBBase`, `OutboxEventPartitionedDBBase`, `InboxEventPartitionedDBBase`, the
395395
mixin `EventMixin`, and the helpers `get_event_constraints(table_name,
396396
include_created_at_in_unique=False, *, metadata=None)` and `UnConstrainedEnum`.
397+
`created_at` and `updated_at` default to `now()` on the server, and every update sets
398+
`updated_at` to `now()`. Up to 0.3.1 the default was `timezone('UTC', now())`, which a session
399+
not on UTC shifted by its offset; a table created then keeps it until a hand-written migration
400+
changes it ([Migrations & DDL](migrations.md#timestamp-defaults)).
397401

398402
`PostgresOutboxRepository(session, *, model_class, conflict_index_id=None,
399403
conflict_index_idempotency=None, batch_size=1000, error_max_length=2000,

‎docs/migrations.md‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ CREATE TABLE outbox_events (
4949
locked_at TIMESTAMPTZ,
5050
locked_by VARCHAR(255),
5151

52-
created_at TIMESTAMPTZ NOT NULL DEFAULT timezone('UTC', now()),
53-
updated_at TIMESTAMPTZ DEFAULT timezone('UTC', now()),
52+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
53+
updated_at TIMESTAMPTZ DEFAULT now(),
5454

5555
CONSTRAINT ck_outbox_events_attempts_valid CHECK (attempts_made <= max_attempts),
5656
CONSTRAINT ck_outbox_events_completed_status_consistency CHECK (
@@ -124,8 +124,8 @@ CREATE TABLE inbox_events (
124124
locked_at TIMESTAMPTZ,
125125
locked_by VARCHAR(255),
126126

127-
created_at TIMESTAMPTZ NOT NULL DEFAULT timezone('UTC', now()),
128-
updated_at TIMESTAMPTZ DEFAULT timezone('UTC', now()),
127+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
128+
updated_at TIMESTAMPTZ DEFAULT now(),
129129

130130
CONSTRAINT ck_inbox_events_attempts_valid CHECK (attempts_made <= max_attempts),
131131
CONSTRAINT ck_inbox_events_completed_status_consistency CHECK (
@@ -185,6 +185,19 @@ CREATE UNIQUE INDEX idx_outbox_events_p_idempotency_key
185185

186186
`PostgresOutboxRepository` reads the conflict target from `__outbox_conflict_index_idempotency__` (`("idempotency_key", "created_at")` on the partitioned base). Because that target cannot reject a retry on its own, the repository also serializes inserts by `idempotency_key` with an advisory lock — see [Troubleshooting](troubleshooting.md#outbox).
187187

188+
## Timestamp defaults
189+
190+
`created_at` and `updated_at` default to `now()`, the start of the transaction as a `timestamptz`, the same instant whatever the session `TimeZone`, and every update sets `updated_at` to `now()`. Up to 0.3.1 both were `timezone('UTC', now())`, a `timestamp` without zone that a session in another zone read as its local time, so the values were off by the zone's UTC offset. The repositories pass `created_at` from the entity, so through them it was only `updated_at`, plus `created_at` of rows inserted by other code.
191+
192+
The update value comes from the model and is right once you upgrade. The column defaults stay in a table created on 0.3.1 or earlier until a migration changes them. Write it by hand: autogenerate does not find it even with `compare_server_default=True`, because Alembic compares the two defaults by evaluating them on the server, and in a UTC session they are equal. On a partitioned table, altering the parent changes its partitions too.
193+
194+
```python
195+
def upgrade() -> None:
196+
for table in ("outbox_events", "inbox_events"):
197+
for column in ("created_at", "updated_at"):
198+
op.alter_column(table, column, server_default=sa.text("now()"))
199+
```
200+
188201
## SQLAlchemy registration
189202

190203
`omni_box.infra.storage.postgres.orm` does **not** export a shared `Base`. Define your own `DeclarativeBase` and bind the abstract models to it:
@@ -283,12 +296,12 @@ def upgrade() -> None:
283296
"created_at",
284297
sa.DateTime(timezone=True),
285298
nullable=False,
286-
server_default=sa.text("timezone('UTC', now())"),
299+
server_default=sa.text("now()"),
287300
),
288301
sa.Column(
289302
"updated_at",
290303
sa.DateTime(timezone=True),
291-
server_default=sa.text("timezone('UTC', now())"),
304+
server_default=sa.text("now()"),
292305
),
293306
sa.CheckConstraint("attempts_made <= max_attempts", name="ck_outbox_events_attempts_valid"),
294307
# ...other CHECKs and indexes from get_event_constraints("outbox_events")

‎omni_box/infra/storage/postgres/orm.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,13 @@ class EventMixin:
7979
# Timestamps
8080
created_at: Mapped[datetime.datetime] = mapped_column(
8181
DateTime(timezone=True),
82-
server_default=func.timezone("UTC", func.now()),
82+
server_default=func.now(),
8383
nullable=False,
8484
)
8585
updated_at: Mapped[datetime.datetime | None] = mapped_column(
8686
DateTime(timezone=True),
87-
server_default=func.timezone("UTC", func.now()),
88-
onupdate=func.timezone("UTC", func.now()),
87+
server_default=func.now(),
88+
onupdate=func.now(),
8989
)
9090

9191

@@ -230,7 +230,7 @@ class OutboxEventPartitionedDBBase(EventMixin, OutboxColumnsMixin):
230230

231231
created_at: Mapped[datetime.datetime] = mapped_column(
232232
DateTime(timezone=True),
233-
server_default=func.timezone("UTC", func.now()),
233+
server_default=func.now(),
234234
nullable=False,
235235
primary_key=True,
236236
)
@@ -259,7 +259,7 @@ class InboxEventPartitionedDBBase(EventMixin, InboxColumnsMixin):
259259

260260
created_at: Mapped[datetime.datetime] = mapped_column(
261261
DateTime(timezone=True),
262-
server_default=func.timezone("UTC", func.now()),
262+
server_default=func.now(),
263263
nullable=False,
264264
primary_key=True,
265265
)
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
"""created_at and updated_at in a session whose time zone is not UTC."""
2+
3+
from typing import Any
4+
from uuid import uuid4
5+
6+
import pytest
7+
from sqlalchemy import func, insert, select, text
8+
from sqlalchemy.ext.asyncio import AsyncSession
9+
10+
from omni_box.core.models.entities import OutboxEvent
11+
from omni_box.infra.storage.postgres import PostgresOutboxRepository
12+
from omni_box.utils import utc_now
13+
from tests.models import (
14+
Base,
15+
ConcreteInboxEvent,
16+
ConcreteInboxEventPartitioned,
17+
ConcreteOutboxEvent,
18+
ConcreteOutboxEventPartitioned,
19+
)
20+
21+
pytestmark = pytest.mark.integration
22+
23+
# Not UTC, and no daylight saving time since 2014, so the offset is the same all year.
24+
SESSION_TIME_ZONE = "Europe/Moscow"
25+
26+
OUTBOX_COLUMNS: dict[str, Any] = {"aggregate_type": "order", "topic": "orders", "partition_key": "k"}
27+
INBOX_COLUMNS: dict[str, Any] = {"message_id": "msg-1", "consumer_group": "cg-1", "source": "orders"}
28+
29+
30+
@pytest.mark.parametrize(
31+
("model", "kind_columns"),
32+
[
33+
(ConcreteOutboxEvent, OUTBOX_COLUMNS),
34+
(ConcreteOutboxEventPartitioned, OUTBOX_COLUMNS),
35+
(ConcreteInboxEvent, INBOX_COLUMNS),
36+
(ConcreteInboxEventPartitioned, INBOX_COLUMNS),
37+
],
38+
)
39+
async def test__event_tables__non_utc_session__server_defaults_are_insert_instant(
40+
async_session: AsyncSession, model: type[Base], kind_columns: dict[str, Any]
41+
) -> None:
42+
# Arrange
43+
await async_session.execute(text(f"SET LOCAL TIME ZONE '{SESSION_TIME_ZONE}'"))
44+
values = {"id": uuid4(), "event_type": "e", "payload": {}, "scheduled_at": utc_now(), **kind_columns}
45+
if model in (ConcreteOutboxEvent, ConcreteOutboxEventPartitioned):
46+
values["aggregate_id"] = uuid4()
47+
table = model.__table__
48+
49+
# Act
50+
row = (
51+
await async_session.execute(
52+
insert(table)
53+
.values(**values)
54+
.returning(table.c.created_at, table.c.updated_at, func.now().label("transaction_start"))
55+
)
56+
).one()
57+
58+
# Assert
59+
assert row.created_at == row.transaction_start
60+
assert row.updated_at == row.transaction_start
61+
62+
63+
async def test__outbox_repository__non_utc_session__update_sets_updated_at_to_update_instant(
64+
async_session: AsyncSession,
65+
) -> None:
66+
# Arrange
67+
repo = PostgresOutboxRepository(session=async_session, model_class=ConcreteOutboxEvent)
68+
event_id = uuid4()
69+
await repo.create(
70+
OutboxEvent(
71+
id=event_id,
72+
aggregate_type="t",
73+
aggregate_id=uuid4(),
74+
event_type="e",
75+
topic="tp",
76+
partition_key="k",
77+
payload={"p": 1},
78+
)
79+
)
80+
await async_session.commit()
81+
await async_session.execute(text(f"SET LOCAL TIME ZONE '{SESSION_TIME_ZONE}'"))
82+
83+
# Act
84+
await repo.mark_processing(event_id, worker_id="worker-1")
85+
86+
# Assert
87+
row = (
88+
await async_session.execute(
89+
select(ConcreteOutboxEvent.updated_at, func.now().label("transaction_start")).where(
90+
ConcreteOutboxEvent.id == event_id
91+
)
92+
)
93+
).one()
94+
assert row.updated_at == row.transaction_start

0 commit comments

Comments
 (0)