Skip to content

Commit 5fcaf69

Browse files
fix: compare platform message history cutoff in UTC (#10246)
platform_message_history.created_at stores UTC wall-clock values (written via TimestampMixin's datetime.now(timezone.utc)), but delete_platform_message_offset computed the cutoff from naive local datetime.now(). On hosts outside UTC the comparison was shifted by the local offset, so the wrong slice of history was deleted. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent f0ab10a commit 5fcaf69

2 files changed

Lines changed: 56 additions & 2 deletions

File tree

‎astrbot/core/db/sqlite.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -866,7 +866,8 @@ async def delete_platform_message_offset(
866866
async with self.get_db() as session:
867867
session: AsyncSession
868868
async with session.begin():
869-
now = datetime.now()
869+
# created_at stores UTC wall-clock values, so compare in UTC.
870+
now = datetime.now(timezone.utc)
870871
cutoff_time = now - timedelta(seconds=offset_sec)
871872
await session.execute(
872873
delete(PlatformMessageHistory).where(

‎tests/unit/test_datetime_storage.py‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,13 @@
77
from sqlalchemy import Column, DateTime, MetaData, create_engine, literal, select
88
from sqlmodel import SQLModel
99

10-
from astrbot.core.db.po import ConversationV2, PlatformStat
10+
import astrbot.core.db.sqlite as sqlite_module
11+
from astrbot.core.db.po import (
12+
ConversationV2,
13+
PlatformMessageHistory,
14+
PlatformStat,
15+
)
16+
from astrbot.core.db.sqlite import SQLiteDatabase
1117
from astrbot.core.db.vec_db.faiss_impl.document_storage import BaseDocModel, Document
1218
from astrbot.core.knowledge_base.models import BaseKBModel, KnowledgeBase
1319

@@ -95,3 +101,50 @@ def test_existing_datetime_rows_keep_naive_reads_and_filters(
95101
assert result.isoformat() == "2024-01-02T03:04:05.123456"
96102
finally:
97103
engine.dispose()
104+
105+
106+
@pytest.mark.asyncio
107+
async def test_delete_platform_message_offset_compares_in_utc(
108+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
109+
):
110+
"""The history cutoff must match the UTC wall time stored in created_at.
111+
112+
Args:
113+
tmp_path: Temporary directory for the database file.
114+
monkeypatch: Fixture used to simulate a host in a non-UTC timezone.
115+
"""
116+
now_utc = datetime.now(timezone.utc)
117+
inside_window = (now_utc - timedelta(hours=20)).replace(tzinfo=None)
118+
outside_window = (now_utc - timedelta(hours=30)).replace(tzinfo=None)
119+
120+
db = SQLiteDatabase(str(tmp_path / "history.db"))
121+
await db.initialize()
122+
try:
123+
async with db.get_db() as session:
124+
async with session.begin():
125+
for created_at in (inside_window, outside_window):
126+
session.add(
127+
PlatformMessageHistory(
128+
platform_id="p1",
129+
user_id="u1",
130+
content={},
131+
created_at=created_at,
132+
)
133+
)
134+
135+
class LocalTime(datetime):
136+
"""Simulate a host whose local timezone is UTC+8."""
137+
138+
@classmethod
139+
def now(cls, tz=None):
140+
if tz is None:
141+
return now_utc.replace(tzinfo=None) + timedelta(hours=8)
142+
return now_utc.astimezone(tz)
143+
144+
monkeypatch.setattr(sqlite_module, "datetime", LocalTime)
145+
await db.delete_platform_message_offset("p1", "u1", offset_sec=86400)
146+
147+
rows = await db.get_platform_message_history("p1", "u1")
148+
assert [row.created_at for row in rows] == [outside_window]
149+
finally:
150+
await db.engine.dispose()

0 commit comments

Comments
 (0)