Repository navigation
[bugfix] agent: keep one live turn per project across processes (#658) #694
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Birfy
wants to merge
1
commit into
ThinkFlowLab:main
Choose a base branch
from
Birfy:fix/658-cross-process-turn-mutex
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+188
−6
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 == ['先发', '后发'] | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 的完成被拒的回归。