Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ def queue(self, project_id: UUID, session: str, message: dict, conversation_id:
return queued

def dispatch(self, project_id: UUID, session: str | None = None,
agent_session: str | None = None) -> dict | None:
agent_session: str | None = None, *, predecessor: str | None = None) -> dict | None:
"""Start the oldest queued message as this turn's user message.

Dispatching takes the same lock as starting a run, so the project slot
Expand All @@ -308,7 +308,8 @@ def dispatch(self, project_id: UUID, session: str | None = None,
if pending is None:
return None
if agent_session is not None:
self.projects.local.start_agent_session(db, project_id, directory, agent_session)
self.projects.local.start_agent_session(
db, project_id, directory, agent_session, predecessor=predecessor)
index = value['messages'].index(pending)
pending['status'] = 'complete'
reply_id = str(uuid5(UUID(pending['id']), 'assistant'))
Expand Down Expand Up @@ -920,7 +921,8 @@ async def run_chain(chain: Chain, plan: dict) -> None:
# The queue was admitted by the browser. Authorize its
# successor under the still-live project lease of this turn.
dispatched = None if chain.stopped else await asyncio.to_thread(
conversations.dispatch, project_id, run_session, next_session)
conversations.dispatch, project_id, run_session, next_session,
predecessor=run_session)
if dispatched is None:
# Keep admission closed until the empty chain releases
# its lease and synchronously leaves the active slot.
Expand Down Expand Up @@ -1009,20 +1011,28 @@ async def turn_events(project_id: UUID, turn_id: UUID, after: int = 0):
raise ProjectError('这轮回复已结束,请重新读取对话。', 404)
return StreamingResponse(chain.events.follow(after), media_type='text/event-stream')

def refuse_foreign_agent_turn(project_id):
with projects.local.transaction() as db:
if projects.local.active_agent_session(db, project_id):
raise ProjectError('当前工程已有回复正在执行。', 409, code='agent_turn_active')

@router.post('/turns')
async def turn(project_id: UUID, value: Turn, x_opendirector_session: UUID = Header(),
accept_language: str | None = Header(default=None, alias='Accept-Language')):
session = str(x_opendirector_session)
async with admission.setdefault(project_id, asyncio.Lock()):
if project_id in active:
raise ProjectError('当前工程已有回复正在执行。', 409)
await asyncio.to_thread(refuse_foreign_agent_turn, project_id)
plan = await prepare(project_id, value, session, accept_language)
run_session = str(uuid4())
try:
plan['start'] = await asyncio.to_thread(conversations.update, project_id, session,
begin=plan['message'], conversation_id=value.conversationId,
before_begin=revalidate(plan), agent_session=run_session)
except ProjectError as failure:
if failure.code == 'agent_turn_active':
raise
# The message points at a thread that is no longer the active one.
# Clients of this endpoint read that from the stream, so report it
# where they already look instead of as a bare status code.
Expand Down Expand Up @@ -1052,6 +1062,7 @@ async def message(project_id: UUID, value: Turn, x_opendirector_session: UUID =
chain.events.put({'type': 'queued', 'message': queued})
return JSONResponse({'queued': queued, 'chainId': str(chain.id),
'turnId': str(chain.turn)}, status_code=202)
await asyncio.to_thread(refuse_foreign_agent_turn, project_id)
check = revalidate(plan)
if check is not None:
await asyncio.to_thread(check)
Expand Down
23 changes: 20 additions & 3 deletions packages/core/src/opendirector/infrastructure/local_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,28 @@ def take_edit_ownership(self, db, project, session, *, persistent=True):
def agent_session_key(self, session: str) -> str:
return self._AGENT_SESSION_PREFIX + identifier(session)

def start_agent_session(self, db, project_id, path: Path, session: str):
"""Called in the transaction that validates the browser lease and accepts the turn."""
now = time.time()
def active_agent_session(self, db, project_id, *, now=None):
now = time.time() if now is None else now
db.execute("DELETE FROM sessions WHERE expires<=? AND id LIKE ?",
(now, self._AGENT_SESSION_PREFIX + "%"))
return db.execute(
"SELECT id FROM sessions WHERE project_id=? AND id LIKE ? AND expires>?",
(str(project_id), self._AGENT_SESSION_PREFIX + "%", now),
).fetchone()

def start_agent_session(self, db, project_id, path: Path, session: str, *, predecessor: str | None = None):
"""Called in the transaction that validates the browser lease and accepts the turn.

A queued successor may replace `predecessor` in the same transaction so
the project is never left without a live agent session, and a second
process cannot take the slot in between.
"""
now = time.time()
existing = self.active_agent_session(db, project_id, now=now)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

旧 turn 续租失败后,现在只是结束 renewal task;运行本身和 conversations.update(finish=...) 不校验当前 lease。这时这里能把已经过期的项目交给新 turn,旧 turn 恢复后仍能写回。建议失去租约时终止旧执行,并在提交结果时核对同一 lease;补一个所有权已交接、旧 turn 的完成被拒的回归。

if existing is not None:
if predecessor is None or existing["id"] != self.agent_session_key(predecessor):
raise ProjectError("当前工程已有回复正在执行。", 409, code="agent_turn_active")
db.execute("DELETE FROM sessions WHERE id=?", (existing["id"],))
db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?)",
(self.agent_session_key(session), str(project_id), now + self.LEASE_SECONDS, str(path)))

Expand Down
154 changes: 154 additions & 0 deletions tests/test_agent_turn_mutex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
"""A project may run only one agent turn at a time, including across processes (#658)."""
import asyncio
import json
import threading
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4

from fastapi.testclient import TestClient
import pytest

from opendirector.domain.projects import ProjectError
from opendirector.infrastructure.local_projects import LocalProjects
from opendirector.infrastructure.model_configs import ModelConfigs
from opendirector_api import agent
from opendirector_api.main import create_app


pytestmark = pytest.mark.cpu


def _start(store, project_id, path, session):
with store.transaction() as db:
store.start_agent_session(db, project_id, path, session)


def test_two_local_project_instances_cannot_start_overlapping_turns(tmp_path):
first, second = LocalProjects(tmp_path), LocalProjects(tmp_path)
project_id, path = uuid4(), tmp_path / 'projects' / 'demo'
session_a, session_b = str(uuid4()), str(uuid4())
_start(first, project_id, path, session_a)
with pytest.raises(ProjectError) as error:
_start(second, project_id, path, session_b)
assert error.value.status == 409
assert str(error.value) == '当前工程已有回复正在执行。'
with pytest.raises(ProjectError) as same_process:
_start(first, project_id, path, session_b)
assert same_process.value.status == 409
first.release_agent_session(session_a)
_start(second, project_id, path, session_b)


def test_an_expired_agent_session_does_not_block_a_new_turn(tmp_path):
import time
first, second = LocalProjects(tmp_path), LocalProjects(tmp_path)
project_id, path = uuid4(), tmp_path / 'projects' / 'demo'
session_a, session_b = str(uuid4()), str(uuid4())
_start(first, project_id, path, session_a)
with first.transaction() as db:
db.execute(
'UPDATE sessions SET expires=? WHERE id=?',
(time.time() - 1, first.agent_session_key(session_a)),
)
_start(second, project_id, path, session_b)
with first.transaction() as db:
rows = db.execute(
'SELECT id FROM sessions WHERE project_id=? AND id LIKE ? AND expires>?',
(str(project_id), first._AGENT_SESSION_PREFIX + '%', time.time()),
).fetchall()
assert [row['id'] for row in rows] == [second.agent_session_key(session_b)]


def test_a_queued_successor_may_replace_its_predecessor_in_one_transaction(tmp_path):
first, second = LocalProjects(tmp_path), LocalProjects(tmp_path)
project_id, path = uuid4(), tmp_path / 'projects' / 'demo'
session_a, session_b, session_c = str(uuid4()), str(uuid4()), str(uuid4())
_start(first, project_id, path, session_a)
with first.transaction() as db:
first.start_agent_session(db, project_id, path, session_b, predecessor=session_a)
with pytest.raises(ProjectError) as error:
with second.transaction() as db:
second.start_agent_session(db, project_id, path, session_c, predecessor=session_a)
assert error.value.status == 409
first.release_agent_session(session_a)
with pytest.raises(ProjectError):
_start(second, project_id, path, session_c)
first.release_agent_session(session_b)
_start(second, project_id, path, session_c)


def test_agent_sessions_on_different_projects_do_not_conflict(tmp_path):
first, second = LocalProjects(tmp_path), LocalProjects(tmp_path)
path = tmp_path / 'projects' / 'demo'
_start(first, uuid4(), path, str(uuid4()))
_start(second, uuid4(), path, str(uuid4()))


async def _empty_skills(*args):
return []


def _mock_runtime(monkeypatch, stream):
monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream)
monkeypatch.setattr(agent, 'runtime_available', lambda _: True)
monkeypatch.setattr(agent, 'skills', _empty_skills)
config = {'id': str(uuid4()), 'modelId': 'test-model', 'kind': 'agent', 'url': 'http://models.test/v1',
'connectionType': 'api', 'protocol': 'openai', 'authMode': 'none', 'apiKey': ''}
monkeypatch.setattr(ModelConfigs, 'resolve', lambda *args: dict(config))


def _open_project(client, project_id, name='Mutex'):
root = f'/api/creation/projects/{project_id}'
assert client.post(root + '/commands', json={'type': 'project.create', 'projectId': project_id,
'commandId': str(uuid4()), 'payload': {'name': name}}).status_code == 200
assert client.post(root + '/open').status_code == 200
return root + '/assistant'


def test_two_apps_sharing_a_repository_cannot_run_overlapping_turns(tmp_path, monkeypatch):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个用例对跨实例行为很关键,但目前整个文件没有登记到 Python shard manifest,同版 CI 在文件对账处失败。请把它加到合适分片,再确认 CI 实际收集并运行这里的回归。

started, release = threading.Event(), threading.Event()

async def stream(self, run):
started.set()
await asyncio.to_thread(release.wait, 10)
yield {'type': 'delta', 'text': '第一轮'}

_mock_runtime(monkeypatch, stream)
session = str(uuid4())
headers = {'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': session}
project_id = str(uuid4())
first_store, second_store = LocalProjects(tmp_path), LocalProjects(tmp_path)
with TestClient(create_app(first_store), headers=headers) as first, \
TestClient(create_app(second_store), headers=headers) as second:
path = _open_project(first, project_id)
conversation = first.get(path).json()['conversationId']
first_turn, second_turn = str(uuid4()), str(uuid4())
with ThreadPoolExecutor() as pool:
pending = pool.submit(first.post, path + '/turns', json={
'id': first_turn, 'runtime': 'default', 'conversationId': conversation, 'text': '先发'})
assert started.wait(5)
busy = second.post(path + '/turns', json={
'id': second_turn, 'runtime': 'default', 'conversationId': conversation, 'text': '后发'})
assert busy.status_code == 409, busy.text
assert busy.json()['detail'] == '当前工程已有回复正在执行。'
queued = second.post(path + '/messages', json={
'id': str(uuid4()), 'runtime': 'default', 'conversationId': conversation, 'text': '排队'})
assert queued.status_code == 409, queued.text
assert queued.json()['detail'] == '当前工程已有回复正在执行。'
assert first.post(path + f'/turns/{first_turn}/stop').status_code == 200
release.set()
assert pending.result(timeout=5).status_code == 200
async def done(self, run):
yield {'type': 'delta', 'text': '第二轮'}
monkeypatch.setattr(agent.AgentRuntimes, 'stream', done)
accepted = second.post(path + '/turns', json={
'id': str(uuid4()), 'runtime': 'default',
'conversationId': first.get(path).json()['conversationId'], 'text': '后发'})
assert accepted.status_code == 200, accepted.text
saved = first.get(path).json()['messages']
texts = [item['text'] for item in saved if item['role'] == 'user']
assert texts == ['先发', '后发']
disk = next(tmp_path.glob('**/agent-runs/conversation.json'))
on_disk = [item['text'] for item in json.loads(disk.read_text(encoding='utf-8'))['messages']
if item['role'] == 'user']
assert on_disk == ['先发', '后发']
Loading