From 5ad8f75b87c108c4512fec7e2ea5347401c503a7 Mon Sep 17 00:00:00 2001 From: djj <421774554@qq.com> Date: Wed, 2 Dec 2026 17:42:50 +0800 Subject: [PATCH] [perf] projects: check head snapshot before scanning commit records ## summary - Match `object.get` and `job.get` queries against the loaded head snapshot before falling back to historical commit records, avoiding full-chain `projects.history()` deep copies on current-revision CLI geometry and text readbacks. - Scan shared `projects.records()` lazily for historical revisions and deep-copy only the matched object so cached commit records remain isolated. - Add HTTP and Agent CLI regression coverage asserting current-revision lookups skip commit record scans and historical lookups preserve shared records. Refs: #632 --- .../application/creation_canvas.py | 17 +++- tests/test_cli.py | 93 +++++++++++++++++++ 2 files changed, 107 insertions(+), 3 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 844c5cfa3..46768c6af 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -1023,9 +1023,20 @@ def query_snapshot(self, query): if query.type == 'asset.usage': assets = [a for a in snapshot.assets if query.objectId is None or a.id == query.objectId] return [history.usage(snapshot, a.id) for a in assets[query.offset:query.offset+query.limit]] - snapshots = [snapshot] if query.revision is None else [record.snapshot for record in self.projects.history(query.projectId)] - for state in snapshots: + def find(state): for (kind, object_id), value in object_index(state).items(): - if object_id == query.objectId and (query.type != 'job.get' or kind == 'job') and (query.revision is None or value.revision == query.revision): + if (object_id == query.objectId + and (query.type != 'job.get' or kind == 'job') + and (query.revision is None or value.revision == query.revision)): return value + return None + + found = find(snapshot) + if found is not None: + return found + if query.revision is not None: + for record in self.projects.records(query.projectId): + found = find(record.snapshot) + if found is not None: + return found.model_copy(deep=True) raise ContractError('missing_object', '未找到该对象或历史版本。', query.objectId) diff --git a/tests/test_cli.py b/tests/test_cli.py index 832f76106..0249660b1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -725,3 +725,96 @@ def test_capabilities_names_commands_that_have_no_command_model(help_color): detailed = json.loads(CliRunner().invoke(cli.app, ["capabilities"]).output)["commands"] assert "--asset-id" not in [option.split()[-1] for entry in detailed for option in entry.get("options", ())] assert "--object-id" in [option for entry in detailed for option in entry.get("options", ())] + + +@pytest.mark.parametrize("live", [False, True], ids=["http", "agent"]) +def test_revision_scoped_object_queries_use_head_snapshot_before_shared_records(tmp_path, monkeypatch, live): + import asyncio + from opendirector.agent.tools import AgentTools + from opendirector.application.creation_canvas import CreationCanvas + from opendirector.domain.creation.commands import ObjectQuery + from opendirector.domain.creation.validation import ContractError + from opendirector.infrastructure.creation_projects import CreationProjects + + local = LocalProjects(tmp_path) + projects = CreationProjects(local) + api = TestClient(create_app(local), headers={"X-OpenDirector-Request": "1"}) + original_client = httpx.Client + + def forward(request): + response = api.request(request.method, request.url.path, headers=dict(request.headers), content=request.read()) + return httpx.Response(response.status_code, headers=response.headers, content=response.content) + + monkeypatch.setattr(cli.httpx, "Client", lambda **kwargs: + original_client(**kwargs, transport=httpx.MockTransport(forward))) + project_id, turn_id = uuid4(), uuid4() + runner = CliRunner() + monkeypatch.delenv("OPENDIRECTOR_AGENT_SOCKET", raising=False) + monkeypatch.delenv("OPENDIRECTOR_AGENT_HOST", raising=False) + created = runner.invoke(cli.app, ["--project", str(project_id), "project", "create", "--name", "Head first"]) + assert created.exit_code == 0, created.output + + if live: + session = str(uuid4()) + projects.open(project_id, session) + business = AgentTools(projects, None, ModelConfigs(tmp_path)) + monkeypatch.setenv("OPENDIRECTOR_AGENT_SOCKET", "in-process-test") + monkeypatch.setattr(cli.Client, "call", lambda self, name, arguments, *, identity=None: + asyncio.run(business.execute(project_id, turn_id, session, str(identity or uuid4()), + name, arguments, roots=[], config=None, native_runtime="codex"))) + + def invoke(args, *, content=None, status=0): + result = runner.invoke(cli.app, ["--project", str(project_id), *args], input=content) + assert result.exit_code == status, result.output + return json.loads(result.output) + + first = invoke(["canvas", "text", "create", "--file", "-", "--title", "One", "--x", "10", "--y", "20"], content="v1") + second = invoke(["canvas", "text", "create", "--file", "-", "--title", "Two", "--x", "300", "--y", "20"], content="v1") + first_id, second_id = first["itemId"], second["itemId"] + + monkeypatch.setattr(CreationProjects, "history", + lambda *args, **kwargs: pytest.fail("object.get must not deep-copy full commit history")) + + updated = invoke(["canvas", "text", "update", "--id", first_id, "--file", "-", + "--expected-version", f"canvas_item:{first_id}:1"], content="v2") + assert updated["canvasItems"][0]["revision"] == 2 + + moved = invoke(["creation", "batch", "--operations", json.dumps([{ + "type": "canvas.move", + "payload": {"items": [ + {"itemId": first_id, "position": {"x": 50, "y": 60}}, + {"itemId": second_id, "position": {"x": 400, "y": 60}}, + ]}, + }]), "--expected-version", f"canvas_item:{first_id}:2", "--expected-version", f"canvas_item:{second_id}:1"]) + assert {row["id"]: row["revision"] for row in moved["canvasItems"]} == {first_id: 3, second_id: 2} + + canvas = CreationCanvas(projects) + with monkeypatch.context() as head_only: + head_only.setattr(CreationProjects, "records", + lambda *args, **kwargs: pytest.fail("head revision lookup must not scan commit records")) + current = canvas.query_snapshot(ObjectQuery( + queryId=uuid4(), type="object.get", projectId=project_id, objectId=UUID(first_id), revision=3)) + assert current.position.x == 50 and current.revision == 3 + + before = [record.model_dump_json() for record in projects.records(project_id)] + shared_items = {id(item) for record in projects.records(project_id) for item in record.snapshot.canvasItems} + shared_positions = {id(item.position) for record in projects.records(project_id) for item in record.snapshot.canvasItems} + historical = canvas.query_snapshot(ObjectQuery( + queryId=uuid4(), type="object.get", projectId=project_id, objectId=UUID(first_id), revision=1)) + assert historical.position.x == 10 and historical.revision == 1 + assert id(historical) not in shared_items and id(historical.position) not in shared_positions + assert invoke(["query", "object.get", "--object-id", first_id, "--file", "-"], + content=json.dumps({"revision": 1}))["position"] == {"x": 10.0, "y": 20.0} + failed = runner.invoke(cli.app, ["--project", str(project_id), "query", "object.get", "--object-id", first_id, "--file", "-"], + input=json.dumps({"revision": 99})) + assert failed.exit_code == 1 and failed.exception is not None + assert [record.model_dump_json() for record in projects.records(project_id)] == before + + with pytest.raises(ContractError) as missing: + canvas.query_snapshot(ObjectQuery( + queryId=uuid4(), type="object.get", projectId=project_id, objectId=UUID(first_id), revision=99)) + assert missing.value.issue.code == "missing_object" + with pytest.raises(ContractError) as not_a_job: + canvas.query_snapshot(ObjectQuery( + queryId=uuid4(), type="job.get", projectId=project_id, objectId=UUID(first_id), revision=3)) + assert not_a_job.value.issue.code == "missing_object"