fix(persistence): fence thread status writes by owner in the UPDATE (#8486)

* fix(persistence): fence thread status writes by owner in the UPDATE

ThreadMetaRepository.update_status read the row to check ownership and
then updated it by thread_id alone. A row that moved to another owner in
between received the first owner's status. Put the owner condition in
the UPDATE so the check and the write are one statement.

* test(persistence): close the side SQLite connection in the owner-move test

The sqlite3 connection context manager commits but leaves the connection
open, which emits a ResourceWarning on Python 3.13.
This commit is contained in:
Hyeonsang Cho 2026-11-23 07:25:47 +09:00 committed by GitHub
parent 1dafd8a3b4
commit eb48cde892
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 44 additions and 10 deletions

View File

@ -295,13 +295,6 @@ class ThreadMetaRepository(ThreadMetaStore):
scanned += len(batch)
return matches
async def _check_ownership(self, session: AsyncSession, thread_id: str, resolved_user_id: str | None) -> bool:
"""Return True if the row exists and is owned (or filter bypassed)."""
if resolved_user_id is None:
return True # explicit bypass
row = await session.get(ThreadMetaRow, thread_id)
return row is not None and row.user_id == resolved_user_id
async def update_display_name(
self,
thread_id: str,
@ -337,10 +330,14 @@ class ThreadMetaRepository(ThreadMetaStore):
user_id: str | None | _AutoSentinel = AUTO,
) -> None:
resolved_user_id = resolve_user_id(user_id, method_name="ThreadMetaRepository.update_status")
# The owner condition stays in the UPDATE itself. A separate ownership
# read leaves a window in which the row can move to another owner, and
# the write would then land on that owner's thread.
stmt = update(ThreadMetaRow).where(ThreadMetaRow.thread_id == thread_id)
if resolved_user_id is not None:
stmt = stmt.where(ThreadMetaRow.user_id == resolved_user_id)
async with self._sf() as session:
if not await self._check_ownership(session, thread_id, resolved_user_id):
return
await session.execute(update(ThreadMetaRow).where(ThreadMetaRow.thread_id == thread_id).values(status=status, updated_at=datetime.now(UTC)))
await session.execute(stmt.values(status=status, updated_at=datetime.now(UTC)))
await session.commit()
async def update_metadata(

View File

@ -167,6 +167,43 @@ class TestThreadMetaRepository:
record = await repo.get("t1")
assert record["status"] == "busy"
@pytest.mark.anyio
async def test_update_status_never_writes_a_row_that_moved_to_another_owner(self, repo, tmp_path):
import sqlite3
from contextlib import closing
from sqlalchemy import event
from deerflow.persistence.engine import get_engine
await repo.create("t1", user_id="alice")
moved = []
def move_owner_before_status_write(conn, cursor, statement, parameters, context, executemany):
# Another writer moves the thread just before the status write runs.
if not moved and statement.lstrip().upper().startswith("UPDATE THREADS_META"):
moved.append(True)
with closing(sqlite3.connect(tmp_path / "test.db")) as other, other:
other.execute("UPDATE threads_meta SET user_id = 'bob' WHERE thread_id = 't1'")
sync_engine = get_engine().sync_engine
event.listen(sync_engine, "before_cursor_execute", move_owner_before_status_write)
try:
await repo.update_status("t1", "error", user_id="alice")
finally:
event.remove(sync_engine, "before_cursor_execute", move_owner_before_status_write)
assert moved == [True]
record = await repo.get("t1", user_id="bob")
assert record["status"] == "idle"
await repo.update_status("t1", "error", user_id="alice")
assert (await repo.get("t1", user_id="bob"))["status"] == "idle"
await repo.update_status("t1", "busy", user_id="bob")
assert (await repo.get("t1", user_id="bob"))["status"] == "busy"
await repo.update_status("t1", "error", user_id=None)
assert (await repo.get("t1", user_id="bob"))["status"] == "error"
@pytest.mark.anyio
async def test_delete(self, repo):
await repo.create("t1")