chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,253 @@
|
||||
"""Unit tests for slash-menu candidates assembly (ENG-615)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from unittest.mock import Mock
|
||||
|
||||
from fields.agent_fields import AgentComposerCandidatesResponse
|
||||
from models.agent_config_entities import AgentSoulConfig, DeclaredOutputConfig, DeclaredOutputType
|
||||
from models.dataset import Dataset
|
||||
from services.agent.composer_candidates import (
|
||||
MAX_CANDIDATES_PER_LIST,
|
||||
previous_node_output_candidates,
|
||||
soul_candidates,
|
||||
)
|
||||
|
||||
_GRAPH = {
|
||||
"nodes": [
|
||||
{
|
||||
"id": "start-1",
|
||||
"data": {
|
||||
"type": "start",
|
||||
"title": "START",
|
||||
"variables": [{"variable": "tenders", "type": "file-list"}],
|
||||
},
|
||||
},
|
||||
{"id": "llm-1", "data": {"type": "llm", "title": "LLM"}},
|
||||
{
|
||||
"id": "agent-up",
|
||||
"data": {
|
||||
"type": "agent",
|
||||
"version": "2",
|
||||
"agent_node_kind": "dify_agent",
|
||||
"title": "Upstream Agent",
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": "agent-target",
|
||||
"data": {
|
||||
"type": "agent",
|
||||
"version": "2",
|
||||
"agent_node_kind": "dify_agent",
|
||||
"title": "Target Agent",
|
||||
},
|
||||
},
|
||||
{"id": "end", "data": {"type": "end", "title": "END"}},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "start-1", "target": "llm-1"},
|
||||
{"source": "llm-1", "target": "agent-up"},
|
||||
{"source": "agent-up", "target": "agent-target"},
|
||||
{"source": "agent-target", "target": "end"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _declared_loader(nid: str) -> list[DeclaredOutputConfig] | None:
|
||||
if nid == "agent-up":
|
||||
return [DeclaredOutputConfig(name="summary", type=DeclaredOutputType.STRING)]
|
||||
return None
|
||||
|
||||
|
||||
def _draft_vars(nid: str) -> list[tuple[str, str | None]]:
|
||||
if nid == "llm-1":
|
||||
return [("text", "string")]
|
||||
return []
|
||||
|
||||
|
||||
def _collect(node_id: str, *, system_vars: Iterable[tuple[str, str]] = ()) -> tuple[list[dict[str, object]], bool]:
|
||||
entries, truncated = previous_node_output_candidates(
|
||||
graph=_GRAPH,
|
||||
node_id=node_id,
|
||||
declared_outputs_loader=_declared_loader,
|
||||
draft_variables_loader=_draft_vars,
|
||||
system_variables_loader=lambda: list(system_vars),
|
||||
)
|
||||
return entries, truncated
|
||||
|
||||
|
||||
def test_upstream_outputs_follow_inspector_semantics() -> None:
|
||||
entries, truncated = _collect("agent-target", system_vars=[("query", "string")])
|
||||
|
||||
assert truncated is False
|
||||
by_node = {}
|
||||
for entry in entries:
|
||||
by_node.setdefault(entry["node_id"], []).append(entry)
|
||||
|
||||
# sys vars ride as a pseudo node, run-derived
|
||||
assert by_node["sys"][0]["selector"] == ["sys", "query"]
|
||||
assert by_node["sys"][0]["inferred"] is True
|
||||
# start variables are static graph facts
|
||||
start = by_node["start-1"][0]
|
||||
assert start["selector"] == ["start-1", "tenders"]
|
||||
assert start["name"] == "START/tenders"
|
||||
assert start["inferred"] is False
|
||||
assert start["value_type"] == "file-list"
|
||||
# agent v2 upstream node uses its declared outputs
|
||||
agent = by_node["agent-up"][0]
|
||||
assert agent["output"] == "summary"
|
||||
assert agent["value_type"] == "string"
|
||||
assert agent["inferred"] is False
|
||||
# other kinds fall back to draft variables (inferred)
|
||||
llm = by_node["llm-1"][0]
|
||||
assert llm["output"] == "text"
|
||||
assert llm["inferred"] is True
|
||||
# the target node itself and downstream nodes never appear
|
||||
assert "agent-target" not in by_node
|
||||
assert "end" not in by_node
|
||||
|
||||
|
||||
def test_results_differ_per_node_id() -> None:
|
||||
entries_target, _ = _collect("agent-target")
|
||||
entries_llm, _ = _collect("llm-1")
|
||||
|
||||
assert {e["node_id"] for e in entries_target} == {"start-1", "llm-1", "agent-up"}
|
||||
assert {e["node_id"] for e in entries_llm} == {"start-1"}
|
||||
|
||||
|
||||
def test_historical_agent_version_two_uses_inferred_outputs() -> None:
|
||||
graph = {
|
||||
"nodes": [
|
||||
{"id": "legacy", "data": {"type": "agent", "version": "2", "title": "Legacy"}},
|
||||
{
|
||||
"id": "target",
|
||||
"data": {"type": "agent", "version": "2", "agent_node_kind": "dify_agent"},
|
||||
},
|
||||
],
|
||||
"edges": [{"source": "legacy", "target": "target"}],
|
||||
}
|
||||
declared_loader = Mock(return_value=[DeclaredOutputConfig(name="declared", type=DeclaredOutputType.STRING)])
|
||||
|
||||
entries, _ = previous_node_output_candidates(
|
||||
graph=graph,
|
||||
node_id="target",
|
||||
declared_outputs_loader=declared_loader,
|
||||
draft_variables_loader=lambda node_id: [("legacy_output", "string")] if node_id == "legacy" else [],
|
||||
system_variables_loader=lambda: [],
|
||||
)
|
||||
|
||||
assert [entry["output"] for entry in entries] == ["legacy_output"]
|
||||
declared_loader.assert_not_called()
|
||||
|
||||
|
||||
def test_previous_outputs_capped_and_flagged() -> None:
|
||||
graph = {
|
||||
"nodes": [{"id": "start-1", "data": {"type": "start", "title": "S", "variables": list[object]()}}, {"id": "t"}],
|
||||
"edges": [{"source": "start-1", "target": "t"}],
|
||||
}
|
||||
many: list[tuple[str, str | None]] = [(f"v{i}", "string") for i in range(MAX_CANDIDATES_PER_LIST + 5)]
|
||||
entries, truncated = previous_node_output_candidates(
|
||||
graph=graph,
|
||||
node_id="t",
|
||||
declared_outputs_loader=lambda _nid: None,
|
||||
draft_variables_loader=lambda _nid: [],
|
||||
system_variables_loader=lambda: many,
|
||||
)
|
||||
assert len(entries) == MAX_CANDIDATES_PER_LIST
|
||||
assert truncated is True
|
||||
|
||||
|
||||
def _soul() -> AgentSoulConfig:
|
||||
return AgentSoulConfig.model_validate(
|
||||
{
|
||||
"tools": {
|
||||
"cli_tools": [
|
||||
{"id": "ct-1", "name": "ffmpeg"},
|
||||
{"id": "ct-2", "name": "disabled-one", "enabled": False},
|
||||
],
|
||||
},
|
||||
"knowledge": {
|
||||
"sets": [
|
||||
{
|
||||
"id": "kb-1",
|
||||
"name": "产品知识",
|
||||
"description": "knowledge set",
|
||||
"datasets": [{"id": "ds-1", "name": "旧名"}, {"id": "ds-gone", "name": "已删"}],
|
||||
"query": {"mode": "generated_query"},
|
||||
"retrieval": {"mode": "multiple", "top_k": 4},
|
||||
}
|
||||
]
|
||||
},
|
||||
"human": {"contacts": [{"id": "c-1", "name": "David Hayes", "channel": "email"}]},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_soul_candidates_lists_configured_items_only() -> None:
|
||||
dataset = Dataset(
|
||||
id="ds-1",
|
||||
tenant_id="tenant-1",
|
||||
name="产品手册",
|
||||
description="desc",
|
||||
created_by="account-1",
|
||||
)
|
||||
lists, truncated = soul_candidates(
|
||||
agent_soul=_soul(),
|
||||
dataset_lookup=lambda _ids: {"ds-1": dataset},
|
||||
workspace_tools_loader=lambda: [
|
||||
{"id": "tavily/tavily_search", "name": "tavily_search", "provider": "tavily", "plugin_id": "lg/tavily"}
|
||||
],
|
||||
)
|
||||
|
||||
assert truncated is False
|
||||
assert [item["name"] for item in lists["cli_tools"]] == ["ffmpeg"]
|
||||
# the stable mention id flows through so the frontend can mint [§cli_tool:<id>§]
|
||||
assert [item["id"] for item in lists["cli_tools"]] == ["ct-1"]
|
||||
# Knowledge mentions point at set ids; nested datasets are hydrated for context.
|
||||
knowledge_set = lists["knowledge_sets"][0]
|
||||
assert knowledge_set["id"] == "kb-1"
|
||||
assert knowledge_set["name"] == "产品知识"
|
||||
assert knowledge_set["missing_dataset_ids"] == ["ds-gone"]
|
||||
datasets = {item["id"]: item for item in knowledge_set["datasets"]}
|
||||
assert datasets["ds-1"]["name"] == "产品手册"
|
||||
assert datasets["ds-1"]["missing"] is False
|
||||
assert datasets["ds-gone"]["missing"] is True
|
||||
assert datasets["ds-gone"]["name"] == "已删"
|
||||
assert lists["human_contacts"][0]["id"] == "c-1"
|
||||
assert lists["dify_tools"][0]["id"] == "tavily/tavily_search"
|
||||
|
||||
|
||||
def test_candidates_response_omits_legacy_skill_file_candidates() -> None:
|
||||
response = AgentComposerCandidatesResponse.model_validate(
|
||||
{
|
||||
"variant": "agent_app",
|
||||
"allowed_node_job_candidates": {},
|
||||
"allowed_soul_candidates": {
|
||||
"cli_tools": [],
|
||||
},
|
||||
"capabilities": {"human_roster_available": False},
|
||||
}
|
||||
).model_dump(mode="json")
|
||||
|
||||
assert "skills_files" not in response["allowed_soul_candidates"]
|
||||
|
||||
|
||||
def test_soul_candidates_empty_config_yields_empty_lists() -> None:
|
||||
lists, truncated = soul_candidates(
|
||||
agent_soul=None,
|
||||
dataset_lookup=lambda _ids: {},
|
||||
workspace_tools_loader=lambda: [],
|
||||
)
|
||||
assert truncated is False
|
||||
assert all(value == [] for value in lists.values())
|
||||
|
||||
|
||||
def test_soul_candidates_caps_lists() -> None:
|
||||
lists, truncated = soul_candidates(
|
||||
agent_soul=None,
|
||||
dataset_lookup=lambda _ids: {},
|
||||
workspace_tools_loader=lambda: [{"id": str(i)} for i in range(MAX_CANDIDATES_PER_LIST + 1)],
|
||||
)
|
||||
assert len(lists["dify_tools"]) == MAX_CANDIDATES_PER_LIST
|
||||
assert truncated is True
|
||||
@@ -0,0 +1,360 @@
|
||||
"""Composer saves preserve assets omitted by ordinary configuration edits."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from extensions.storage.storage_type import StorageType
|
||||
from models.agent import (
|
||||
Agent,
|
||||
AgentConfigDraft,
|
||||
AgentConfigDraftType,
|
||||
AgentConfigSnapshot,
|
||||
AgentScope,
|
||||
AgentSource,
|
||||
WorkflowAgentBindingType,
|
||||
WorkflowAgentNodeBinding,
|
||||
)
|
||||
from models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig
|
||||
from models.enums import CreatorUserRole
|
||||
from models.model import AppMode, UploadFile
|
||||
from services.agent.composer_service import AgentComposerService
|
||||
from services.agent_config_service import (
|
||||
AgentConfigService,
|
||||
AgentConfigVersionKind,
|
||||
ConfigPushFileItem,
|
||||
ConfigPushPayload,
|
||||
)
|
||||
from services.entities.agent_entities import ComposerSavePayload
|
||||
from tests.helpers.unit.model_factories import make_account, make_app, make_workflow
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ComposerTarget:
|
||||
tenant_id: str
|
||||
account_id: str
|
||||
agent_id: str
|
||||
draft_id: str
|
||||
app_id: str
|
||||
binding_id: str | None
|
||||
upload_ids: tuple[str, str]
|
||||
|
||||
|
||||
class AssetTargetArgs(TypedDict, closed=True):
|
||||
tenant_id: str
|
||||
agent_id: str
|
||||
user_id: str
|
||||
config_version_id: str
|
||||
config_version_kind: AgentConfigVersionKind
|
||||
|
||||
|
||||
@pytest.fixture(params=[False, True], ids=["agent", "inline-workflow"])
|
||||
def composer_target(request: pytest.FixtureRequest, sqlite_session: Session) -> ComposerTarget:
|
||||
workflow = bool(request.param)
|
||||
tenant_id, account_id, agent_id, snapshot_id, draft_id, app_id = (str(uuid4()) for _ in range(6))
|
||||
agent = Agent(
|
||||
id=agent_id,
|
||||
tenant_id=tenant_id,
|
||||
name="Config files test",
|
||||
app_id=app_id,
|
||||
scope=AgentScope.WORKFLOW_ONLY if workflow else AgentScope.ROSTER,
|
||||
source=AgentSource.WORKFLOW if workflow else AgentSource.AGENT_APP,
|
||||
active_config_snapshot_id=snapshot_id,
|
||||
created_by=account_id,
|
||||
updated_by=account_id,
|
||||
)
|
||||
soul = AgentSoulConfig()
|
||||
snapshot = AgentConfigSnapshot(
|
||||
id=snapshot_id, tenant_id=tenant_id, agent_id=agent_id, version=1, config_snapshot=soul
|
||||
)
|
||||
draft = AgentConfigDraft(
|
||||
id=draft_id,
|
||||
tenant_id=tenant_id,
|
||||
agent_id=agent_id,
|
||||
draft_type=AgentConfigDraftType.DRAFT,
|
||||
base_snapshot_id=snapshot_id,
|
||||
config_snapshot=soul,
|
||||
)
|
||||
sqlite_session.add_all(
|
||||
[
|
||||
agent,
|
||||
snapshot,
|
||||
draft,
|
||||
make_account(account_id=account_id, name="File editor", email="files@example.com"),
|
||||
make_app(app_id=app_id, tenant_id=tenant_id, mode=AppMode.WORKFLOW if workflow else AppMode.AGENT_CHAT),
|
||||
]
|
||||
)
|
||||
binding_id = None
|
||||
if workflow:
|
||||
workflow_id = str(uuid4())
|
||||
backing_app_id = str(uuid4())
|
||||
agent.workflow_id = workflow_id
|
||||
agent.workflow_node_id = "node-1"
|
||||
agent.backing_app_id = backing_app_id
|
||||
binding = WorkflowAgentNodeBinding(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
workflow_id=workflow_id,
|
||||
workflow_version="draft",
|
||||
node_id="node-1",
|
||||
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
|
||||
agent_id=agent_id,
|
||||
current_snapshot_id=snapshot_id,
|
||||
node_job_config=WorkflowNodeJobConfig(),
|
||||
)
|
||||
sqlite_session.add_all(
|
||||
[
|
||||
binding,
|
||||
make_workflow(workflow_id=workflow_id, tenant_id=tenant_id, app_id=app_id),
|
||||
make_app(app_id=backing_app_id, tenant_id=tenant_id, mode=AppMode.AGENT_CHAT),
|
||||
]
|
||||
)
|
||||
sqlite_session.flush()
|
||||
binding_id = binding.id
|
||||
upload_ids = (str(uuid4()), str(uuid4()))
|
||||
for upload_id, name in zip(upload_ids, ["first.md", "second.md"], strict=True):
|
||||
upload = UploadFile(
|
||||
tenant_id=tenant_id,
|
||||
storage_type=StorageType.LOCAL,
|
||||
key=f"uploads/{name}",
|
||||
name=name,
|
||||
size=5,
|
||||
extension="md",
|
||||
mime_type="text/markdown",
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=account_id,
|
||||
created_at=datetime.now(UTC).replace(tzinfo=None),
|
||||
used=False,
|
||||
hash=f"hash-{name}",
|
||||
)
|
||||
upload.id = upload_id
|
||||
sqlite_session.add(upload)
|
||||
sqlite_session.commit()
|
||||
return ComposerTarget(tenant_id, account_id, agent_id, draft_id, app_id, binding_id, upload_ids)
|
||||
|
||||
|
||||
def save_composer(session: Session, target: ComposerTarget, soul: dict[str, object]) -> AgentSoulConfig:
|
||||
payload = ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "workflow" if target.binding_id else "agent_app",
|
||||
"save_strategy": "node_job_only" if target.binding_id else "save_to_current_version",
|
||||
"agent_soul": soul,
|
||||
}
|
||||
)
|
||||
if target.binding_id:
|
||||
state = AgentComposerService.save_workflow_composer(
|
||||
session=session,
|
||||
tenant_id=target.tenant_id,
|
||||
app_id=target.app_id,
|
||||
node_id="node-1",
|
||||
account_id=target.account_id,
|
||||
payload=payload,
|
||||
)
|
||||
else:
|
||||
state = AgentComposerService.save_agent_composer(
|
||||
session=session,
|
||||
tenant_id=target.tenant_id,
|
||||
agent_id=target.agent_id,
|
||||
account_id=target.account_id,
|
||||
payload=payload,
|
||||
)
|
||||
session.commit()
|
||||
return AgentSoulConfig.model_validate(state["agent_soul"])
|
||||
|
||||
|
||||
def asset_target(target: ComposerTarget) -> AssetTargetArgs:
|
||||
return {
|
||||
"tenant_id": target.tenant_id,
|
||||
"agent_id": target.agent_id,
|
||||
"user_id": target.account_id,
|
||||
"config_version_id": target.draft_id,
|
||||
"config_version_kind": AgentConfigVersionKind.DRAFT,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("file_count", [1, 2], ids=["single-bind", "batch-bind"])
|
||||
def test_omitted_files_preserve_bindings_created_after_the_composer_was_read(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
composer_target: ComposerTarget,
|
||||
file_count: int,
|
||||
) -> None:
|
||||
target = composer_target
|
||||
assets = AgentConfigService(session_factory=sqlite_session_factory)
|
||||
with sqlite_session_factory() as stale_session:
|
||||
# Keep the old ORM rows cached while another request binds the files.
|
||||
_cached_agent = stale_session.get(Agent, target.agent_id)
|
||||
_cached_draft = stale_session.get(AgentConfigDraft, target.draft_id)
|
||||
if target.binding_id:
|
||||
_cached_binding = stale_session.get(WorkflowAgentNodeBinding, target.binding_id)
|
||||
if file_count == 1:
|
||||
assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
|
||||
else:
|
||||
assets.push_files_for_console(**asset_target(target), upload_file_ids=list(target.upload_ids))
|
||||
state = save_composer(stale_session, target, {"prompt": {"system_prompt": "An older prompt edit"}})
|
||||
|
||||
assert [item.file_id for item in state.config_files] == list(target.upload_ids[:file_count])
|
||||
assert state.prompt.system_prompt == "An older prompt edit"
|
||||
with sqlite_session_factory() as session:
|
||||
draft = session.get(AgentConfigDraft, target.draft_id)
|
||||
assert draft is not None
|
||||
assert [item.file_id for item in draft.config_snapshot.config_files] == list(target.upload_ids[:file_count])
|
||||
|
||||
|
||||
def test_omitted_files_do_not_restore_an_asset_deleted_after_the_composer_was_read(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
composer_target: ComposerTarget,
|
||||
) -> None:
|
||||
target = composer_target
|
||||
assets = AgentConfigService(session_factory=sqlite_session_factory)
|
||||
assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
|
||||
with sqlite_session_factory() as stale_session:
|
||||
_cached_draft = stale_session.get(AgentConfigDraft, target.draft_id)
|
||||
assets.push_for_console(
|
||||
**asset_target(target), payload=ConfigPushPayload(files=[ConfigPushFileItem(name="first.md")])
|
||||
)
|
||||
state = save_composer(stale_session, target, {"prompt": {"system_prompt": "Keep this edit"}})
|
||||
assert state.config_files == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("delete_existing", [False, True], ids=["keep-batch", "keep-deletion"])
|
||||
def test_omitted_files_do_not_autoflush_a_dirty_cached_snapshot_before_locking(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
composer_target: ComposerTarget,
|
||||
delete_existing: bool,
|
||||
) -> None:
|
||||
target = composer_target
|
||||
assets = AgentConfigService(session_factory=sqlite_session_factory)
|
||||
if delete_existing:
|
||||
assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
|
||||
with sqlite_session_factory() as stale_session:
|
||||
cached = stale_session.get(AgentConfigDraft, target.draft_id)
|
||||
assert cached is not None
|
||||
local_edit = cached.config_snapshot.model_copy(deep=True)
|
||||
local_edit.config_note = "Pending local note"
|
||||
cached.config_snapshot = local_edit
|
||||
if delete_existing:
|
||||
assets.push_for_console(
|
||||
**asset_target(target),
|
||||
payload=ConfigPushPayload(files=[ConfigPushFileItem(name="first.md")]),
|
||||
)
|
||||
else:
|
||||
assets.push_files_for_console(**asset_target(target), upload_file_ids=list(target.upload_ids))
|
||||
result = save_composer(stale_session, target, {"prompt": {"system_prompt": "Ordinary edit"}})
|
||||
assert [file.file_id for file in result.config_files] == ([] if delete_existing else list(target.upload_ids))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("replace_with_file", [False, True], ids=["explicit-clear", "explicit-replace"])
|
||||
def test_explicit_files_keep_complete_replacement_semantics(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
composer_target: ComposerTarget,
|
||||
replace_with_file: bool,
|
||||
) -> None:
|
||||
target = composer_target
|
||||
assets = AgentConfigService(session_factory=sqlite_session_factory)
|
||||
assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
|
||||
files: list[dict[str, str]] = (
|
||||
[{"name": "second.md", "file_kind": "upload_file", "file_id": target.upload_ids[1]}]
|
||||
if replace_with_file
|
||||
else []
|
||||
)
|
||||
with sqlite_session_factory() as session:
|
||||
state = save_composer(
|
||||
session, target, {"prompt": {"system_prompt": "Applied configuration"}, "config_files": files}
|
||||
)
|
||||
assert [item.file_id for item in state.config_files] == ([target.upload_ids[1]] if replace_with_file else [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("composer_target", [True], indirect=True, ids=["inline-workflow"])
|
||||
def test_omitted_files_refresh_a_cached_inline_snapshot_and_binding(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
composer_target: ComposerTarget,
|
||||
) -> None:
|
||||
target = composer_target
|
||||
assert target.binding_id is not None
|
||||
with sqlite_session_factory() as stale_session:
|
||||
stale_agent = stale_session.get(Agent, target.agent_id)
|
||||
stale_binding = stale_session.get(WorkflowAgentNodeBinding, target.binding_id)
|
||||
stale_draft = stale_session.get(AgentConfigDraft, target.draft_id)
|
||||
assert stale_agent is not None
|
||||
assert stale_binding is not None
|
||||
assert stale_draft is not None
|
||||
with sqlite_session_factory() as other_session:
|
||||
save_composer(
|
||||
other_session,
|
||||
target,
|
||||
{
|
||||
"config_files": [
|
||||
{
|
||||
"name": "second.md",
|
||||
"file_kind": "upload_file",
|
||||
"file_id": target.upload_ids[1],
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
state = save_composer(stale_session, target, {"prompt": {"system_prompt": "Next edit"}})
|
||||
assert [item.file_id for item in state.config_files] == [target.upload_ids[1]]
|
||||
|
||||
|
||||
def test_locking_the_latest_draft_keeps_pending_agent_profile_edits(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
composer_target: ComposerTarget,
|
||||
) -> None:
|
||||
target = composer_target
|
||||
assets = AgentConfigService(session_factory=sqlite_session_factory)
|
||||
with sqlite_session_factory() as session:
|
||||
agent = session.get(Agent, target.agent_id)
|
||||
_cached_draft = session.get(AgentConfigDraft, target.draft_id)
|
||||
assert agent is not None
|
||||
agent.name = "Renamed in this transaction"
|
||||
assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
|
||||
draft = AgentComposerService.get_or_create_normal_agent_draft(
|
||||
session=session,
|
||||
tenant_id=target.tenant_id,
|
||||
agent=agent,
|
||||
created_by=target.account_id,
|
||||
)
|
||||
assert agent.name == "Renamed in this transaction"
|
||||
assert [item.file_id for item in draft.config_snapshot.config_files] == [target.upload_ids[0]]
|
||||
session.commit()
|
||||
with sqlite_session_factory() as session:
|
||||
saved_agent = session.get(Agent, target.agent_id)
|
||||
assert saved_agent is not None
|
||||
assert saved_agent.name == "Renamed in this transaction"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("composer_target", [True], indirect=True, ids=["inline-workflow"])
|
||||
def test_inline_composer_shows_file_edits_before_the_next_node_save(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
composer_target: ComposerTarget,
|
||||
) -> None:
|
||||
target = composer_target
|
||||
assets = AgentConfigService(session_factory=sqlite_session_factory)
|
||||
|
||||
def loaded_file_ids(snapshot_id: str | None = None) -> list[str | None]:
|
||||
with sqlite_session_factory() as session:
|
||||
state = AgentComposerService.load_workflow_composer(
|
||||
session=session,
|
||||
tenant_id=target.tenant_id,
|
||||
app_id=target.app_id,
|
||||
node_id="node-1",
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
return [item.file_id for item in AgentSoulConfig.model_validate(state["agent_soul"]).config_files]
|
||||
|
||||
assets.push_files_for_console(**asset_target(target), upload_file_ids=list(target.upload_ids))
|
||||
assert loaded_file_ids() == list(target.upload_ids)
|
||||
with sqlite_session_factory() as session:
|
||||
agent = session.get(Agent, target.agent_id)
|
||||
assert agent is not None
|
||||
bound_snapshot_id = agent.active_config_snapshot_id
|
||||
assert loaded_file_ids(bound_snapshot_id) == []
|
||||
|
||||
assets.push_for_console(
|
||||
**asset_target(target), payload=ConfigPushPayload(files=[ConfigPushFileItem(name="first.md")])
|
||||
)
|
||||
assert loaded_file_ids() == [target.upload_ids[1]]
|
||||
@@ -0,0 +1,274 @@
|
||||
"""Composer save/validate mention rules (ENG-616 §2.4 allowlists)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from services.agent.composer_validator import ComposerConfigValidator
|
||||
from services.agent.errors import InvalidComposerConfigError
|
||||
from services.entities.agent_entities import ComposerSavePayload
|
||||
|
||||
|
||||
def _soul_payload(system_prompt: str) -> ComposerSavePayload:
|
||||
return ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "agent_app",
|
||||
"agent_soul": {"prompt": {"system_prompt": system_prompt}},
|
||||
"save_strategy": "save_to_current_version",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _node_job_payload(workflow_prompt: str) -> ComposerSavePayload:
|
||||
return ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "workflow",
|
||||
"node_job": {"workflow_prompt": workflow_prompt},
|
||||
"save_strategy": "node_job_only",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_soul_prompt_accepts_soul_kinds() -> None:
|
||||
payload = _soul_payload("Use [§skill:s1§] [§file:f1§] [§tool:p/t§] [§cli_tool:c§] [§knowledge:k1§] [§human:h1§]")
|
||||
ComposerConfigValidator.validate_save_payload(payload)
|
||||
|
||||
|
||||
def test_soul_prompt_rejects_node_output_mention() -> None:
|
||||
with pytest.raises(InvalidComposerConfigError, match="mention_kind_not_allowed"):
|
||||
ComposerConfigValidator.validate_save_payload(_soul_payload("Read [§node_output:n1.text§]"))
|
||||
|
||||
|
||||
def test_soul_prompt_rejects_declared_output_mention() -> None:
|
||||
with pytest.raises(InvalidComposerConfigError, match="mention_kind_not_allowed"):
|
||||
ComposerConfigValidator.validate_save_payload(_soul_payload("Produce [§output:report§]"))
|
||||
|
||||
|
||||
def test_node_job_prompt_accepts_job_kinds() -> None:
|
||||
payload = _node_job_payload("Read [§node_output:n1.text:START/text§], produce [§output:report§], ask [§human:h1§]")
|
||||
ComposerConfigValidator.validate_save_payload(payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("token", ["[§skill:s1§]", "[§tool:p/t§]", "[§cli_tool:c§]", "[§knowledge:k1§]"])
|
||||
def test_node_job_prompt_rejects_soul_only_kinds(token: str) -> None:
|
||||
with pytest.raises(InvalidComposerConfigError, match="mention_kind_not_allowed"):
|
||||
ComposerConfigValidator.validate_save_payload(_node_job_payload(f"Use {token}"))
|
||||
|
||||
|
||||
def test_mention_limit_enforced() -> None:
|
||||
prompt = " ".join(f"[§human:h{i}§]" for i in range(201))
|
||||
with pytest.raises(InvalidComposerConfigError, match="mention_limit_exceeded"):
|
||||
ComposerConfigValidator.validate_save_payload(_soul_payload(prompt))
|
||||
|
||||
|
||||
def test_prompt_without_mentions_still_passes() -> None:
|
||||
ComposerConfigValidator.validate_save_payload(_soul_payload("plain prompt, {{var}} and {{#context#}} untouched"))
|
||||
|
||||
|
||||
# ── ENG-617: human must be referenced (hard) ─────────────────────────────────
|
||||
|
||||
|
||||
def _soul_payload_with_human(system_prompt: str) -> ComposerSavePayload:
|
||||
return ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "agent_app",
|
||||
"agent_soul": {
|
||||
"prompt": {"system_prompt": system_prompt},
|
||||
"human": {
|
||||
"contacts": [{"id": "c-1", "name": "David Hayes", "email": "david@acme.com", "channel": "email"}]
|
||||
},
|
||||
},
|
||||
"save_strategy": "save_to_current_version",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_configured_human_without_mention_is_rejected() -> None:
|
||||
with pytest.raises(InvalidComposerConfigError, match="human_involvement_not_referenced"):
|
||||
ComposerConfigValidator.validate_save_payload(_soul_payload_with_human("no human reference here"))
|
||||
|
||||
|
||||
def test_configured_human_referenced_by_id_passes() -> None:
|
||||
ComposerConfigValidator.validate_save_payload(_soul_payload_with_human("ask [§human:c-1§] when unsure"))
|
||||
|
||||
|
||||
def test_configured_human_referenced_by_email_alias_passes() -> None:
|
||||
ComposerConfigValidator.validate_save_payload(_soul_payload_with_human("ask [§human:david@acme.com§]"))
|
||||
|
||||
|
||||
def test_node_job_human_must_be_referenced_too() -> None:
|
||||
payload = ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "workflow",
|
||||
"node_job": {
|
||||
"workflow_prompt": "do the work",
|
||||
"human_contacts": [{"id": "c-2", "name": "Reviewer"}],
|
||||
},
|
||||
"save_strategy": "node_job_only",
|
||||
}
|
||||
)
|
||||
with pytest.raises(InvalidComposerConfigError, match="human_involvement_not_referenced"):
|
||||
ComposerConfigValidator.validate_save_payload(payload)
|
||||
|
||||
assert payload.node_job is not None
|
||||
payload.node_job.workflow_prompt = "escalate to [§human:c-2§]"
|
||||
ComposerConfigValidator.validate_save_payload(payload)
|
||||
|
||||
|
||||
def test_identity_less_human_contact_is_skipped() -> None:
|
||||
payload = ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "agent_app",
|
||||
"agent_soul": {
|
||||
"prompt": {"system_prompt": "plain"},
|
||||
"human": {"contacts": [{"channel": "email"}]},
|
||||
},
|
||||
"save_strategy": "save_to_current_version",
|
||||
}
|
||||
)
|
||||
ComposerConfigValidator.validate_save_payload(payload)
|
||||
|
||||
|
||||
# ── ENG-617: soft findings ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _findings(payload: ComposerSavePayload, **kwargs: set[str] | None) -> dict[str, list[dict[str, object]]]:
|
||||
return ComposerConfigValidator.collect_soft_findings(payload, **kwargs)
|
||||
|
||||
|
||||
def test_dangling_knowledge_mention_becomes_placeholder_with_label() -> None:
|
||||
payload = _soul_payload("ground in [§knowledge:gone-1:旧产品手册§]")
|
||||
findings = _findings(payload)
|
||||
assert findings["knowledge_retrieval_placeholder"] == [{"id": "gone-1", "placeholder_name": "旧产品手册"}]
|
||||
assert findings["warnings"] == []
|
||||
|
||||
|
||||
def test_dangling_knowledge_without_label_gets_fallback_name() -> None:
|
||||
findings = _findings(_soul_payload("see [§knowledge:deadbeef-cafe§]"))
|
||||
assert findings["knowledge_retrieval_placeholder"] == [
|
||||
{"id": "deadbeef-cafe", "placeholder_name": "Knowledge deadbeef"}
|
||||
]
|
||||
|
||||
|
||||
def test_configured_but_deleted_knowledge_set_surfaces_as_placeholder() -> None:
|
||||
payload = ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "agent_app",
|
||||
"agent_soul": {
|
||||
"prompt": {"system_prompt": "see [§knowledge:kb-1:产品手册§]"},
|
||||
"knowledge": {
|
||||
"sets": [
|
||||
{
|
||||
"id": "kb-1",
|
||||
"name": "产品手册",
|
||||
"datasets": [{"id": "ds-1", "name": "产品手册"}],
|
||||
"query": {"mode": "generated_query"},
|
||||
"retrieval": {"mode": "multiple", "top_k": 4},
|
||||
}
|
||||
]
|
||||
},
|
||||
},
|
||||
"save_strategy": "save_to_current_version",
|
||||
}
|
||||
)
|
||||
# configured + current Agent Soul row exists -> clean
|
||||
assert _findings(payload, existing_knowledge_set_ids={"kb-1"})["knowledge_retrieval_placeholder"] == []
|
||||
# configured but removed from the current Agent Soul surface -> placeholder
|
||||
assert _findings(payload, existing_knowledge_set_ids=set())["knowledge_retrieval_placeholder"] == [
|
||||
{"id": "kb-1", "placeholder_name": "产品手册"}
|
||||
]
|
||||
|
||||
|
||||
def test_unresolved_non_knowledge_mentions_warn_target_missing() -> None:
|
||||
findings = _findings(_soul_payload("use [§skill:nope:Ghost Skill§] and [§human:missing§]"))
|
||||
codes = [(w["code"], w["kind"]) for w in findings["warnings"]]
|
||||
assert ("mention_target_missing", "human") in codes
|
||||
assert findings["knowledge_retrieval_placeholder"] == []
|
||||
|
||||
|
||||
def test_provider_all_tools_mention_resolves_against_provider_level_entry() -> None:
|
||||
# `[§tool:<provider>/*§]` = all tools of that provider; it points at a
|
||||
# provider-level config entry (tool_name omitted), so with the entry present
|
||||
# it must produce neither hard error nor warning…
|
||||
payload = ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "agent_app",
|
||||
"agent_soul": {
|
||||
"prompt": {"system_prompt": "use [§tool:duckduckgo/*:DuckDuckGo 全部§] when needed"},
|
||||
"tools": {
|
||||
"dify_tools": [
|
||||
{
|
||||
"plugin_id": "langgenius/duckduckgo",
|
||||
"provider": "duckduckgo",
|
||||
"provider_type": "plugin",
|
||||
"credential_type": "unauthorized",
|
||||
}
|
||||
]
|
||||
},
|
||||
},
|
||||
"save_strategy": "save_to_current_version",
|
||||
}
|
||||
)
|
||||
ComposerConfigValidator.validate_save_payload(payload)
|
||||
assert _findings(payload) == {"warnings": [], "knowledge_retrieval_placeholder": []}
|
||||
|
||||
# …and without any entry of that provider it warns like any dangling mention.
|
||||
dangling = _findings(_soul_payload("use [§tool:duckduckgo/*:DuckDuckGo 全部§]"))
|
||||
assert [(w["code"], w["kind"]) for w in dangling["warnings"]] == [("mention_target_missing", "tool")]
|
||||
|
||||
|
||||
def test_duplicate_cli_tool_ids_rejected() -> None:
|
||||
payload = ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "agent_app",
|
||||
"agent_soul": {
|
||||
"prompt": {"system_prompt": "plain"},
|
||||
"tools": {
|
||||
"cli_tools": [
|
||||
{"id": "ct-1", "name": "ffmpeg"},
|
||||
# disabled entries still occupy the id namespace
|
||||
{"id": "ct-1", "name": "jq", "enabled": False},
|
||||
]
|
||||
},
|
||||
},
|
||||
"save_strategy": "save_to_current_version",
|
||||
}
|
||||
)
|
||||
with pytest.raises(InvalidComposerConfigError, match="duplicate CLI tool id 'ct-1'"):
|
||||
ComposerConfigValidator.validate_save_payload(payload)
|
||||
|
||||
|
||||
def test_save_backfills_missing_cli_tool_ids_and_keeps_existing() -> None:
|
||||
from services.agent.composer_service import _backfill_cli_tool_ids
|
||||
|
||||
payload = ComposerSavePayload.model_validate(
|
||||
{
|
||||
"variant": "agent_app",
|
||||
"agent_soul": {
|
||||
"prompt": {"system_prompt": "plain"},
|
||||
"tools": {"cli_tools": [{"name": "ffmpeg"}, {"id": "ct-1", "name": "jq"}]},
|
||||
},
|
||||
"save_strategy": "save_to_current_version",
|
||||
}
|
||||
)
|
||||
|
||||
_backfill_cli_tool_ids(payload.agent_soul)
|
||||
|
||||
assert payload.agent_soul is not None
|
||||
minted, existing = payload.agent_soul.tools.cli_tools
|
||||
assert existing.id == "ct-1"
|
||||
assert minted.id is not None
|
||||
assert len(minted.id) == 12
|
||||
assert minted.id != "ct-1"
|
||||
|
||||
|
||||
def test_malformed_marker_warns_but_does_not_block() -> None:
|
||||
payload = _soul_payload("hello [§wat:x:y§] world")
|
||||
ComposerConfigValidator.validate_save_payload(payload) # no hard error
|
||||
findings = _findings(payload)
|
||||
assert [w["code"] for w in findings["warnings"]] == ["mention_malformed"]
|
||||
|
||||
|
||||
def test_clean_prompt_yields_empty_findings() -> None:
|
||||
findings = _findings(_soul_payload("plain prompt with {{#context#}} legacy form"))
|
||||
assert findings == {"warnings": [], "knowledge_retrieval_placeholder": []}
|
||||
@@ -0,0 +1,373 @@
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from decimal import Decimal
|
||||
from typing import cast
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import Table
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from sqlalchemy.sql.dml import Delete
|
||||
|
||||
from models.agent import (
|
||||
Agent,
|
||||
AgentConfigDraft,
|
||||
AgentConfigDraftType,
|
||||
AgentConfigRevision,
|
||||
AgentConfigRevisionOperation,
|
||||
AgentConfigSnapshot,
|
||||
AgentConfigVersionKind,
|
||||
AgentDebugConversation,
|
||||
AgentHomeSnapshot,
|
||||
AgentKind,
|
||||
AgentScope,
|
||||
AgentSource,
|
||||
AgentStatus,
|
||||
AgentWorkingResourceStatus,
|
||||
AgentWorkspace,
|
||||
AgentWorkspaceBinding,
|
||||
AgentWorkspaceOwnerType,
|
||||
WorkflowAgentBindingType,
|
||||
WorkflowAgentNodeBinding,
|
||||
)
|
||||
from models.agent_config_entities import AgentSoulConfig
|
||||
from models.enums import AppStatus, ConversationFromSource, ConversationStatus
|
||||
from models.model import App, AppMode, Conversation, Message
|
||||
from services.agent.deletion_service import AgentDeletionInvariantError, AgentDeletionService
|
||||
|
||||
|
||||
def _archived_agent(
|
||||
*,
|
||||
agent_id: str = "agent-1",
|
||||
tenant_id: str = "tenant-1",
|
||||
status: AgentStatus = AgentStatus.ARCHIVED,
|
||||
) -> Agent:
|
||||
return Agent(
|
||||
id=agent_id,
|
||||
tenant_id=tenant_id,
|
||||
name="Agent",
|
||||
description="",
|
||||
role="",
|
||||
agent_kind=AgentKind.DIFY_AGENT,
|
||||
scope=AgentScope.ROSTER,
|
||||
source=AgentSource.AGENT_APP,
|
||||
status=status,
|
||||
)
|
||||
|
||||
|
||||
def test_purge_archived_agent_deletes_complete_aggregate_and_preserves_workflow_binding(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
agent = _archived_agent()
|
||||
snapshot = AgentConfigSnapshot(
|
||||
id="snapshot-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
agent_id=agent.id,
|
||||
version=1,
|
||||
config_snapshot=AgentSoulConfig(),
|
||||
)
|
||||
dangling_binding = WorkflowAgentNodeBinding(
|
||||
id="workflow-binding-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
app_id="missing-app",
|
||||
workflow_id="missing-workflow",
|
||||
workflow_version="old-version",
|
||||
node_id="agent-node",
|
||||
binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
|
||||
agent_id=agent.id,
|
||||
current_snapshot_id=snapshot.id,
|
||||
node_job_config={},
|
||||
)
|
||||
rows = [
|
||||
agent,
|
||||
snapshot,
|
||||
AgentConfigDraft(
|
||||
id="draft-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
agent_id=agent.id,
|
||||
draft_type=AgentConfigDraftType.DRAFT,
|
||||
draft_owner_key="",
|
||||
config_snapshot=AgentSoulConfig(),
|
||||
),
|
||||
AgentConfigDraft(
|
||||
id="build-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
agent_id=agent.id,
|
||||
draft_type=AgentConfigDraftType.DEBUG_BUILD,
|
||||
account_id="account-1",
|
||||
draft_owner_key="account-1",
|
||||
config_snapshot=AgentSoulConfig(),
|
||||
),
|
||||
AgentConfigRevision(
|
||||
id="revision-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
agent_id=agent.id,
|
||||
current_snapshot_id=snapshot.id,
|
||||
revision=1,
|
||||
operation=AgentConfigRevisionOperation.CREATE_VERSION,
|
||||
),
|
||||
AgentDebugConversation(
|
||||
id="debug-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
agent_id=agent.id,
|
||||
app_id="app-1",
|
||||
account_id="account-1",
|
||||
draft_type=AgentConfigDraftType.DRAFT,
|
||||
conversation_id="conversation-1",
|
||||
),
|
||||
AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
agent_id=agent.id,
|
||||
snapshot_ref="home-ref",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
),
|
||||
AgentWorkspaceBinding(
|
||||
id="binding-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
app_id="app-1",
|
||||
workspace_id="workspace-1",
|
||||
agent_id=agent.id,
|
||||
agent_config_version_id=snapshot.id,
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
backend_binding_ref="binding-ref",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
),
|
||||
]
|
||||
sibling = _archived_agent(agent_id="agent-2")
|
||||
other_tenant = _archived_agent(agent_id="agent-3", tenant_id="tenant-2")
|
||||
unrelated_app = App(
|
||||
id="unrelated-app",
|
||||
tenant_id=agent.tenant_id,
|
||||
name="Unrelated",
|
||||
mode=AppMode.WORKFLOW,
|
||||
status=AppStatus.NORMAL,
|
||||
enable_site=True,
|
||||
enable_api=True,
|
||||
)
|
||||
conversation = Conversation(
|
||||
id="conversation-1",
|
||||
app_id=unrelated_app.id,
|
||||
mode=AppMode.AGENT_CHAT,
|
||||
name="Preserved conversation",
|
||||
_inputs={},
|
||||
status=ConversationStatus.NORMAL,
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id="account-1",
|
||||
)
|
||||
preserved_rows = [
|
||||
sibling,
|
||||
other_tenant,
|
||||
AgentConfigDraft(
|
||||
id="sibling-draft",
|
||||
tenant_id=sibling.tenant_id,
|
||||
agent_id=sibling.id,
|
||||
draft_type=AgentConfigDraftType.DRAFT,
|
||||
draft_owner_key="",
|
||||
config_snapshot=AgentSoulConfig(),
|
||||
),
|
||||
AgentHomeSnapshot(
|
||||
id="other-home",
|
||||
tenant_id=other_tenant.tenant_id,
|
||||
agent_id=other_tenant.id,
|
||||
snapshot_ref="other-home-ref",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
),
|
||||
unrelated_app,
|
||||
AgentWorkspace(
|
||||
id="workspace-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
app_id=unrelated_app.id,
|
||||
owner_type=AgentWorkspaceOwnerType.CONVERSATION,
|
||||
owner_id=conversation.id,
|
||||
owner_scope_key="root",
|
||||
backend_workspace_ref="workspace-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
active_guard=1,
|
||||
),
|
||||
conversation,
|
||||
Message(
|
||||
id="message-1",
|
||||
app_id=unrelated_app.id,
|
||||
conversation_id=conversation.id,
|
||||
_inputs={},
|
||||
query="hello",
|
||||
message={"role": "user", "content": "hello"},
|
||||
answer="world",
|
||||
message_unit_price=Decimal(0),
|
||||
answer_unit_price=Decimal(0),
|
||||
currency="USD",
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id="account-1",
|
||||
),
|
||||
]
|
||||
sqlite_session.add_all([*rows, dangling_binding, *preserved_rows])
|
||||
sqlite_session.commit()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.deletion_service.session_factory.create_session",
|
||||
sqlite_session_factory,
|
||||
)
|
||||
|
||||
AgentDeletionService.purge_archived_agents(tenant_id=agent.tenant_id, agent_ids=[agent.id])
|
||||
|
||||
with sqlite_session_factory() as observer_session:
|
||||
for row in rows:
|
||||
assert observer_session.get(type(row), row.id) is None
|
||||
preserved_binding = observer_session.get(WorkflowAgentNodeBinding, dangling_binding.id)
|
||||
assert preserved_binding is not None
|
||||
assert preserved_binding.agent_id == agent.id
|
||||
for row in preserved_rows:
|
||||
assert observer_session.get(type(row), row.id) is not None
|
||||
|
||||
|
||||
def test_purge_bulk_deletes_aggregate_dependencies_before_agent(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
context = MagicMock()
|
||||
session = context.__enter__.return_value
|
||||
session.scalars.return_value.all.return_value = [_archived_agent()]
|
||||
session.scalar.side_effect = [None, None]
|
||||
deleted_tables: list[str] = []
|
||||
|
||||
def record_bulk_delete(statement: object) -> None:
|
||||
if isinstance(statement, Delete):
|
||||
deleted_tables.append(cast(Table, statement.table).name)
|
||||
|
||||
session.execute.side_effect = record_bulk_delete
|
||||
monkeypatch.setattr("services.agent.deletion_service.session_factory.create_session", lambda: context)
|
||||
AgentDeletionService.purge_archived_agents(tenant_id="tenant-1", agent_ids=["agent-1"])
|
||||
|
||||
assert deleted_tables == [
|
||||
cast(Table, model.__table__).name
|
||||
for model in (
|
||||
AgentDebugConversation,
|
||||
AgentConfigRevision,
|
||||
AgentConfigDraft,
|
||||
AgentConfigSnapshot,
|
||||
AgentHomeSnapshot,
|
||||
AgentWorkspaceBinding,
|
||||
Agent,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("invariant", "expected_error"),
|
||||
[
|
||||
("non_archived", "must be ARCHIVED"),
|
||||
("active_binding", "still has ACTIVE Binding"),
|
||||
("active_home", "still has ACTIVE Home Snapshot"),
|
||||
],
|
||||
)
|
||||
def test_purge_rejects_invalid_aggregate_invariants(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
invariant: str,
|
||||
expected_error: str,
|
||||
) -> None:
|
||||
agent = _archived_agent(status=AgentStatus.ACTIVE if invariant == "non_archived" else AgentStatus.ARCHIVED)
|
||||
related: AgentWorkspaceBinding | AgentHomeSnapshot | None = None
|
||||
if invariant == "active_binding":
|
||||
related = AgentWorkspaceBinding(
|
||||
id="binding-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
app_id="app-1",
|
||||
workspace_id="workspace-1",
|
||||
agent_id=agent.id,
|
||||
agent_config_version_id="snapshot-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
backend_binding_ref="binding-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
elif invariant == "active_home":
|
||||
related = AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
agent_id=agent.id,
|
||||
snapshot_ref="home-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
sqlite_session.add(agent)
|
||||
if related is not None:
|
||||
sqlite_session.add(related)
|
||||
sqlite_session.commit()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.deletion_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
|
||||
with pytest.raises(AgentDeletionInvariantError, match=expected_error):
|
||||
AgentDeletionService.purge_archived_agents(tenant_id=agent.tenant_id, agent_ids=[agent.id])
|
||||
|
||||
assert sqlite_session.get(Agent, agent.id) is not None
|
||||
if related is not None:
|
||||
assert sqlite_session.get(type(related), related.id) is not None
|
||||
|
||||
|
||||
def test_purge_is_idempotent_for_empty_missing_and_repeated_ids(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
agent = _archived_agent()
|
||||
sqlite_session.add(agent)
|
||||
sqlite_session.commit()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.deletion_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
|
||||
agent_id = agent.id
|
||||
|
||||
AgentDeletionService.purge_archived_agents(tenant_id=agent.tenant_id, agent_ids=[])
|
||||
assert sqlite_session.get(Agent, agent_id) is not None
|
||||
|
||||
AgentDeletionService.purge_archived_agents(tenant_id=agent.tenant_id, agent_ids=["missing-agent"])
|
||||
assert sqlite_session.get(Agent, agent_id) is not None
|
||||
|
||||
AgentDeletionService.purge_archived_agents(tenant_id=agent.tenant_id, agent_ids=[agent_id, agent_id])
|
||||
assert sqlite_session.get(Agent, agent_id) is None
|
||||
|
||||
AgentDeletionService.purge_archived_agents(tenant_id=agent.tenant_id, agent_ids=[agent_id])
|
||||
assert sqlite_session.get(Agent, agent_id) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure_stage", ["delete", "commit"])
|
||||
def test_purge_failure_rolls_back_complete_aggregate(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
failure_stage: str,
|
||||
) -> None:
|
||||
agent = _archived_agent()
|
||||
draft = AgentConfigDraft(
|
||||
id="draft-1",
|
||||
tenant_id=agent.tenant_id,
|
||||
agent_id=agent.id,
|
||||
draft_type=AgentConfigDraftType.DRAFT,
|
||||
draft_owner_key="",
|
||||
config_snapshot=AgentSoulConfig(),
|
||||
)
|
||||
sqlite_session.add_all([agent, draft])
|
||||
sqlite_session.commit()
|
||||
agent_id = agent.id
|
||||
draft_id = draft.id
|
||||
error = RuntimeError(f"{failure_stage} failed")
|
||||
|
||||
@contextmanager
|
||||
def failing_session() -> Generator[Session]:
|
||||
with sqlite_session_factory() as service_session:
|
||||
failure_method = failure_stage if failure_stage == "commit" else "execute"
|
||||
monkeypatch.setattr(service_session, failure_method, MagicMock(side_effect=error))
|
||||
yield service_session
|
||||
|
||||
monkeypatch.setattr(
|
||||
"services.agent.deletion_service.session_factory.create_session",
|
||||
failing_session,
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
AgentDeletionService.purge_archived_agents(tenant_id=agent.tenant_id, agent_ids=[agent_id])
|
||||
|
||||
assert exc_info.value is error
|
||||
with sqlite_session_factory() as observer_session:
|
||||
assert observer_session.get(Agent, agent_id) is not None
|
||||
assert observer_session.get(AgentConfigDraft, draft_id) is not None
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,465 @@
|
||||
from contextlib import nullcontext
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from dify_agent.client import DifyAgentHTTPError, DifyAgentNotFoundError, DifyAgentTimeoutError
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.agent import (
|
||||
Agent,
|
||||
AgentConfigDraft,
|
||||
AgentConfigDraftType,
|
||||
AgentConfigSnapshot,
|
||||
AgentConfigVersionKind,
|
||||
AgentHomeSnapshot,
|
||||
AgentScope,
|
||||
AgentSource,
|
||||
AgentStatus,
|
||||
AgentWorkingResourceStatus,
|
||||
AgentWorkspace,
|
||||
AgentWorkspaceBinding,
|
||||
AgentWorkspaceOwnerType,
|
||||
)
|
||||
from models.agent_config_entities import AgentSoulConfig
|
||||
from services.agent.errors import (
|
||||
AgentBuildSandboxNotFoundError,
|
||||
AgentHomeSnapshotCreateFailedError,
|
||||
AgentHomeSnapshotTooLargeError,
|
||||
)
|
||||
from services.agent.home_snapshot_service import AgentHomeSnapshotService, validate_home_snapshot_binding
|
||||
from services.agent.workspace_service import AgentWorkspaceBindingGenerationMismatchError
|
||||
from tests.helpers.unit.config_override import apply_config_overrides
|
||||
|
||||
|
||||
def _build_draft(*, home_snapshot_id: str | None = "home-old") -> AgentConfigDraft:
|
||||
return AgentConfigDraft(
|
||||
id="build-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
draft_type=AgentConfigDraftType.DEBUG_BUILD,
|
||||
account_id="account-1",
|
||||
draft_owner_key="account-1",
|
||||
home_snapshot_id=home_snapshot_id,
|
||||
agent_workspace_binding_id="binding-1",
|
||||
config_snapshot=AgentSoulConfig(),
|
||||
)
|
||||
|
||||
|
||||
def _client(*, snapshot_ref: str = "snapshot-ref-1") -> MagicMock:
|
||||
client = MagicMock()
|
||||
client.create_home_snapshot_from_binding_sync.return_value = SimpleNamespace(snapshot_ref=snapshot_ref)
|
||||
return client
|
||||
|
||||
|
||||
def test_home_snapshot_client_outlasts_the_gateway_snapshot_budget(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
apply_config_overrides(monkeypatch, AGENT_BACKEND_BASE_URL="http://agent.example")
|
||||
|
||||
client = AgentHomeSnapshotService._client()
|
||||
|
||||
assert client._timeout == 45.0
|
||||
|
||||
|
||||
def test_validate_home_snapshot_binding_accepts_default_home_without_ledger_lookup(unbound_session: Session) -> None:
|
||||
validate_home_snapshot_binding(
|
||||
session=unbound_session,
|
||||
agent=Agent(
|
||||
tenant_id="tenant-1", name="Agent", scope=AgentScope.ROSTER, source=AgentSource.ROSTER, id="agent-1"
|
||||
),
|
||||
home_snapshot_id=None,
|
||||
)
|
||||
|
||||
|
||||
def _persist_build_binding(
|
||||
session: Session,
|
||||
*,
|
||||
app_id: str,
|
||||
backing_app_id: str | None,
|
||||
base_home_snapshot_id: str | None = "home-old",
|
||||
agent_config_version_id: str = "build-1",
|
||||
agent_config_version_kind: AgentConfigVersionKind = AgentConfigVersionKind.BUILD_DRAFT,
|
||||
) -> None:
|
||||
runtime_app_id = backing_app_id or app_id
|
||||
session.add_all(
|
||||
[
|
||||
Agent(
|
||||
id="agent-1",
|
||||
tenant_id="tenant-1",
|
||||
name="Builder",
|
||||
scope=AgentScope.ROSTER,
|
||||
source=AgentSource.AGENT_APP,
|
||||
status=AgentStatus.ACTIVE,
|
||||
app_id=app_id,
|
||||
backing_app_id=backing_app_id,
|
||||
),
|
||||
AgentWorkspace(
|
||||
id="workspace-1",
|
||||
tenant_id="tenant-1",
|
||||
app_id=runtime_app_id,
|
||||
owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
|
||||
owner_id="build-1",
|
||||
owner_scope_key="root",
|
||||
backend_workspace_ref="workspace-ref-1",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
),
|
||||
AgentWorkspaceBinding(
|
||||
id="binding-1",
|
||||
tenant_id="tenant-1",
|
||||
app_id=runtime_app_id,
|
||||
workspace_id="workspace-1",
|
||||
agent_id="agent-1",
|
||||
base_home_snapshot_id=base_home_snapshot_id,
|
||||
agent_config_version_id=agent_config_version_id,
|
||||
agent_config_version_kind=agent_config_version_kind,
|
||||
backend_binding_ref="binding-ref-1",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
),
|
||||
]
|
||||
)
|
||||
session.commit()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("app_id", "backing_app_id", "expected_runtime_app_id"),
|
||||
[
|
||||
("app-1", None, "app-1"),
|
||||
("workflow-app-1", "runtime-app-1", "runtime-app-1"),
|
||||
],
|
||||
)
|
||||
def test_build_apply_checkpoints_exact_active_binding(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
app_id: str,
|
||||
backing_app_id: str | None,
|
||||
expected_runtime_app_id: str,
|
||||
) -> None:
|
||||
_persist_build_binding(sqlite_session, app_id=app_id, backing_app_id=backing_app_id)
|
||||
client = _client(snapshot_ref="snapshot-ref-2")
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "_client", lambda: nullcontext(client))
|
||||
|
||||
snapshot = AgentHomeSnapshotService.create_for_build_apply(
|
||||
session=sqlite_session,
|
||||
build_draft=_build_draft(),
|
||||
)
|
||||
sqlite_session.flush()
|
||||
|
||||
stored = sqlite_session.scalar(select(AgentHomeSnapshot).where(AgentHomeSnapshot.id == snapshot.id))
|
||||
assert stored is snapshot
|
||||
request = client.create_home_snapshot_from_binding_sync.call_args.args[0]
|
||||
assert request.tenant_id == "tenant-1"
|
||||
assert request.agent_id == "agent-1"
|
||||
assert request.backend_binding_ref == "binding-ref-1"
|
||||
assert snapshot.snapshot_ref == "snapshot-ref-2"
|
||||
workspace = sqlite_session.get(AgentWorkspace, "workspace-1")
|
||||
assert workspace is not None
|
||||
assert workspace.app_id == expected_runtime_app_id
|
||||
|
||||
|
||||
def test_build_apply_forwards_default_home_generation(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
|
||||
_persist_build_binding(sqlite_session, app_id="app-1", backing_app_id=None, base_home_snapshot_id=None)
|
||||
client = _client(snapshot_ref="snapshot-ref-2")
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "_client", lambda: nullcontext(client))
|
||||
|
||||
snapshot = AgentHomeSnapshotService.create_for_build_apply(
|
||||
session=sqlite_session,
|
||||
build_draft=_build_draft(home_snapshot_id=None),
|
||||
)
|
||||
sqlite_session.flush()
|
||||
|
||||
assert snapshot.snapshot_ref == "snapshot-ref-2"
|
||||
assert sqlite_session.get(AgentHomeSnapshot, snapshot.id) is snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("base_home_snapshot_id", "agent_config_version_id", "agent_config_version_kind"),
|
||||
[
|
||||
(None, "build-1", AgentConfigVersionKind.BUILD_DRAFT),
|
||||
("home-old", "build-2", AgentConfigVersionKind.BUILD_DRAFT),
|
||||
("home-old", "build-1", AgentConfigVersionKind.SNAPSHOT),
|
||||
],
|
||||
)
|
||||
def test_build_apply_rejects_binding_from_a_different_generation(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
base_home_snapshot_id: str | None,
|
||||
agent_config_version_id: str,
|
||||
agent_config_version_kind: AgentConfigVersionKind,
|
||||
) -> None:
|
||||
_persist_build_binding(
|
||||
sqlite_session,
|
||||
app_id="app-1",
|
||||
backing_app_id=None,
|
||||
base_home_snapshot_id=base_home_snapshot_id,
|
||||
agent_config_version_id=agent_config_version_id,
|
||||
agent_config_version_kind=agent_config_version_kind,
|
||||
)
|
||||
client = _client(snapshot_ref="snapshot-ref-2")
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "_client", lambda: nullcontext(client))
|
||||
|
||||
with pytest.raises(AgentWorkspaceBindingGenerationMismatchError):
|
||||
AgentHomeSnapshotService.create_for_build_apply(
|
||||
session=sqlite_session,
|
||||
build_draft=_build_draft(),
|
||||
)
|
||||
|
||||
client.create_home_snapshot_from_binding_sync.assert_not_called()
|
||||
|
||||
|
||||
def test_build_apply_fails_fast_without_source_binding(unbound_session: Session) -> None:
|
||||
build_draft = _build_draft()
|
||||
build_draft.agent_workspace_binding_id = None
|
||||
|
||||
with pytest.raises(AgentBuildSandboxNotFoundError):
|
||||
AgentHomeSnapshotService.create_for_build_apply(
|
||||
session=unbound_session,
|
||||
build_draft=build_draft,
|
||||
)
|
||||
|
||||
|
||||
def test_home_snapshot_collection_database_failure_propagates(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
sqlite_session.execute(text(f"DROP TABLE {AgentHomeSnapshot.__tablename__}"))
|
||||
sqlite_session.commit()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.home_snapshot_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
|
||||
with pytest.raises(OperationalError, match="no such table"):
|
||||
AgentHomeSnapshotService.collect_retired_home_snapshot(
|
||||
tenant_id="tenant-1",
|
||||
home_snapshot_id="home-1",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("snapshot_state", ["missing", "active"])
|
||||
def test_home_snapshot_collection_non_retired_target_is_idempotent_noop(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
snapshot_state: str,
|
||||
) -> None:
|
||||
if snapshot_state == "active":
|
||||
sqlite_session.add(
|
||||
AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
snapshot_ref="snapshot-ref-1",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
)
|
||||
sqlite_session.commit()
|
||||
delete = MagicMock()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.home_snapshot_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "delete", delete)
|
||||
|
||||
AgentHomeSnapshotService.collect_retired_home_snapshot(
|
||||
tenant_id="tenant-1",
|
||||
home_snapshot_id="home-1",
|
||||
)
|
||||
|
||||
delete.assert_not_called()
|
||||
rows = sqlite_session.scalars(select(AgentHomeSnapshot).where(AgentHomeSnapshot.id == "home-1")).all()
|
||||
if snapshot_state == "active":
|
||||
assert [row.status for row in rows] == [AgentWorkingResourceStatus.ACTIVE]
|
||||
assert rows[0].retired_at is None
|
||||
else:
|
||||
assert rows == []
|
||||
|
||||
|
||||
def test_home_snapshot_collection_backend_failure_propagates_and_preserves_retired_snapshot(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
snapshot = AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
snapshot_ref="snapshot-ref-1",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
)
|
||||
sqlite_session.add(snapshot)
|
||||
sqlite_session.commit()
|
||||
error = RuntimeError("Agent backend unavailable")
|
||||
delete = MagicMock(side_effect=error)
|
||||
monkeypatch.setattr(
|
||||
"services.agent.home_snapshot_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "delete", delete)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
AgentHomeSnapshotService.collect_retired_home_snapshot(
|
||||
tenant_id="tenant-1",
|
||||
home_snapshot_id=snapshot.id,
|
||||
)
|
||||
|
||||
assert exc_info.value is error
|
||||
stored_snapshot = sqlite_session.get(AgentHomeSnapshot, snapshot.id)
|
||||
assert stored_snapshot is not None
|
||||
assert stored_snapshot.status is AgentWorkingResourceStatus.RETIRED
|
||||
|
||||
|
||||
def test_home_snapshot_collection_ignores_config_references(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
snapshot = AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
snapshot_ref="snapshot-ref-1",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
)
|
||||
draft = _build_draft(home_snapshot_id=snapshot.id)
|
||||
config_snapshot = AgentConfigSnapshot(
|
||||
id="config-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
version=1,
|
||||
home_snapshot_id=snapshot.id,
|
||||
config_snapshot=AgentSoulConfig(),
|
||||
)
|
||||
sqlite_session.add_all([snapshot, draft, config_snapshot])
|
||||
sqlite_session.commit()
|
||||
delete = MagicMock()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.home_snapshot_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "delete", delete)
|
||||
|
||||
AgentHomeSnapshotService.collect_retired_home_snapshot(
|
||||
tenant_id="tenant-1",
|
||||
home_snapshot_id=snapshot.id,
|
||||
)
|
||||
|
||||
delete.assert_called_once_with(snapshot_ref=snapshot.snapshot_ref)
|
||||
assert sqlite_session.get(AgentHomeSnapshot, snapshot.id) is None
|
||||
assert sqlite_session.get(AgentConfigDraft, draft.id) is not None
|
||||
assert sqlite_session.get(AgentConfigSnapshot, config_snapshot.id) is not None
|
||||
|
||||
|
||||
def test_home_snapshot_collection_final_delete_failure_propagates(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
snapshot = AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
snapshot_ref="snapshot-ref-1",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
)
|
||||
sqlite_session.add(snapshot)
|
||||
sqlite_session.commit()
|
||||
sqlite_session.execute(
|
||||
text(
|
||||
"CREATE TRIGGER reject_home_snapshot_delete BEFORE DELETE ON agent_home_snapshots "
|
||||
"BEGIN SELECT RAISE(ABORT, 'home snapshot delete blocked'); END"
|
||||
)
|
||||
)
|
||||
sqlite_session.commit()
|
||||
delete = MagicMock()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.home_snapshot_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "delete", delete)
|
||||
|
||||
with pytest.raises(IntegrityError, match="home snapshot delete blocked"):
|
||||
AgentHomeSnapshotService.collect_retired_home_snapshot(
|
||||
tenant_id="tenant-1",
|
||||
home_snapshot_id="home-1",
|
||||
)
|
||||
|
||||
delete.assert_called_once_with(snapshot_ref="snapshot-ref-1")
|
||||
sqlite_session.rollback()
|
||||
assert sqlite_session.scalar(select(AgentHomeSnapshot).where(AgentHomeSnapshot.id == "home-1")) is not None
|
||||
|
||||
|
||||
def _apply_with_client_error(monkeypatch: pytest.MonkeyPatch, session: Session, error: Exception) -> None:
|
||||
_persist_build_binding(session, app_id="app-1", backing_app_id=None)
|
||||
client = MagicMock()
|
||||
client.create_home_snapshot_from_binding_sync.side_effect = error
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "_client", lambda: nullcontext(client))
|
||||
|
||||
AgentHomeSnapshotService.create_for_build_apply(session=session, build_draft=_build_draft())
|
||||
|
||||
|
||||
def test_build_apply_surfaces_the_backend_message(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
|
||||
error = DifyAgentHTTPError(
|
||||
status_code=502,
|
||||
detail={
|
||||
"code": "home_snapshot_create_failed",
|
||||
"message": "500 snapshot_save_failed: object store unavailable",
|
||||
},
|
||||
)
|
||||
|
||||
with pytest.raises(AgentHomeSnapshotCreateFailedError) as excinfo:
|
||||
_apply_with_client_error(monkeypatch, sqlite_session, error)
|
||||
|
||||
assert excinfo.value.data == {
|
||||
"code": "agent_home_snapshot_create_failed",
|
||||
"message": "500 snapshot_save_failed: object store unavailable",
|
||||
"status": 502,
|
||||
}
|
||||
|
||||
|
||||
def test_build_apply_maps_a_too_large_snapshot_to_413(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
|
||||
error = DifyAgentHTTPError(
|
||||
status_code=413,
|
||||
detail={
|
||||
"code": "home_snapshot_too_large",
|
||||
"message": "home snapshot exceeds the configured limit of 67108864 bytes",
|
||||
},
|
||||
)
|
||||
|
||||
with pytest.raises(AgentHomeSnapshotTooLargeError) as excinfo:
|
||||
_apply_with_client_error(monkeypatch, sqlite_session, error)
|
||||
|
||||
assert excinfo.value.data == {
|
||||
"code": "agent_home_snapshot_too_large",
|
||||
"message": "home snapshot exceeds the configured limit of 67108864 bytes",
|
||||
"status": 413,
|
||||
}
|
||||
|
||||
|
||||
def test_build_apply_surfaces_a_non_dict_backend_detail(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
error = DifyAgentHTTPError(status_code=500, detail="upstream exploded")
|
||||
|
||||
with pytest.raises(AgentHomeSnapshotCreateFailedError) as excinfo:
|
||||
_apply_with_client_error(monkeypatch, sqlite_session, error)
|
||||
|
||||
assert excinfo.value.data == {
|
||||
"code": "agent_home_snapshot_create_failed",
|
||||
"message": "upstream exploded",
|
||||
"status": 502,
|
||||
}
|
||||
|
||||
|
||||
def test_build_apply_surfaces_a_transport_failure(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
|
||||
error = DifyAgentTimeoutError("read timed out after 45.0s")
|
||||
|
||||
with pytest.raises(AgentHomeSnapshotCreateFailedError) as excinfo:
|
||||
_apply_with_client_error(monkeypatch, sqlite_session, error)
|
||||
|
||||
assert excinfo.value.data == {
|
||||
"code": "agent_home_snapshot_create_failed",
|
||||
"message": "read timed out after 45.0s",
|
||||
"status": 502,
|
||||
}
|
||||
|
||||
|
||||
def test_build_apply_still_maps_404_to_a_missing_sandbox(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
error = DifyAgentNotFoundError(status_code=404, detail={"code": "binding_lost", "message": "gone"})
|
||||
|
||||
with pytest.raises(AgentBuildSandboxNotFoundError):
|
||||
_apply_with_client_error(monkeypatch, sqlite_session, error)
|
||||
@@ -0,0 +1,549 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import AbstractContextManager, nullcontext
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
from typing import Unpack, cast
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
|
||||
from dify_agent.protocol.knowledge_fs import (
|
||||
KnowledgeFsBinding,
|
||||
KnowledgeFsCitation,
|
||||
KnowledgeFsCommand,
|
||||
KnowledgeFsCommandName,
|
||||
KnowledgeFsError,
|
||||
KnowledgeFsPrepareRequest,
|
||||
)
|
||||
from sqlalchemy.orm import Session
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from core.app.file_access import FileAccessScope
|
||||
from enums import DeploymentEdition
|
||||
from models.agent import (
|
||||
Agent,
|
||||
AgentConfigSnapshot,
|
||||
AgentScope,
|
||||
AgentSource,
|
||||
AgentStatus,
|
||||
WorkflowAgentBindingType,
|
||||
WorkflowAgentNodeBinding,
|
||||
)
|
||||
from models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig
|
||||
from models.enums import AppStatus
|
||||
from models.knowledge_fs import KnowledgeFSAppSpaceJoinType
|
||||
from models.model import App, AppMode
|
||||
from models.workflow import Workflow
|
||||
from services.agent import knowledge_gateway as gateway
|
||||
from services.agent.knowledge_citations import knowledge_sources_from_tool_part
|
||||
from services.agent.knowledge_spaces import collect_workflow_agent_knowledge_space_ids
|
||||
from services.agent_config_service import AgentConfigTarget, AgentConfigVersionKind
|
||||
from services.knowledge_fs.capability_broker import KnowledgeFSIssuedProductCapability
|
||||
from services.knowledge_fs.errors import KnowledgeFSWorkflowQueryImageReference
|
||||
from services.knowledge_fs.query_images import KnowledgeFSQueryImageMetadata
|
||||
from services.knowledge_fs.runtime import KnowledgeFSRuntime
|
||||
from tests.helpers.unit.config_override import apply_config_overrides
|
||||
from tests.helpers.unit.services.knowledge_fs_services_b_fakes import RecordingCallable
|
||||
|
||||
SPACE = "00000000-0000-4000-8000-000000000001"
|
||||
NODE = "00000000-0000-4000-8000-000000000002"
|
||||
DOC = "00000000-0000-4000-8000-000000000003"
|
||||
BINDING = KnowledgeFsBinding(id="docs", control_space_id=SPACE, name="产品说明")
|
||||
SOUL = AgentSoulConfig.model_validate({"knowledge": {"spaces": [BINDING.model_dump()]}})
|
||||
CONTEXT = DifyExecutionContextLayerConfig(
|
||||
tenant_id="tenant",
|
||||
app_id="app",
|
||||
agent_id="agent",
|
||||
user_id="account",
|
||||
user_from="account",
|
||||
agent_mode="agent_app",
|
||||
invoke_from="published",
|
||||
agent_config_version_id="snapshot",
|
||||
agent_config_version_kind="snapshot",
|
||||
)
|
||||
CITATION = KnowledgeFsCitation(
|
||||
id="kfs_" + "a" * 32,
|
||||
control_space_id=SPACE,
|
||||
space_name=BINDING.name,
|
||||
node_id=NODE,
|
||||
document_asset_id=DOC,
|
||||
artifact_hash="a" * 64,
|
||||
parse_artifact_id="parse",
|
||||
document_version=2,
|
||||
document_title="说明.pdf",
|
||||
)
|
||||
|
||||
|
||||
ISSUED = KnowledgeFSIssuedProductCapability(
|
||||
token="private-token",
|
||||
expires_at=datetime(2026, 7, 21, tzinfo=UTC),
|
||||
operation_id="operation",
|
||||
knowledge_space_id=SPACE,
|
||||
knowledge_space_revision=1,
|
||||
trace_id="trace",
|
||||
authorization_fingerprint="a" * 64,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeBroker:
|
||||
issued: KnowledgeFSIssuedProductCapability = ISSUED
|
||||
issue_interactive_calls: list[dict[str, object]] = field(default_factory=list)
|
||||
|
||||
def issue_interactive(self, **kwargs: object) -> KnowledgeFSIssuedProductCapability:
|
||||
self.issue_interactive_calls.append(kwargs)
|
||||
return self.issued
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeAppCapabilities:
|
||||
"""Issues `issued` unless `issue_failure` is set; records issuance and investigation captures."""
|
||||
|
||||
issued: KnowledgeFSIssuedProductCapability = ISSUED
|
||||
issue_failure: Exception | None = None
|
||||
issue_calls: list[dict[str, object]] = field(default_factory=list)
|
||||
capture_calls: list[dict[str, object]] = field(default_factory=list)
|
||||
|
||||
def issue(self, **kwargs: object) -> KnowledgeFSIssuedProductCapability:
|
||||
self.issue_calls.append(kwargs)
|
||||
if self.issue_failure is not None:
|
||||
raise self.issue_failure
|
||||
return self.issued
|
||||
|
||||
def capture_agent_investigation(self, **kwargs: object) -> dict[str, object]:
|
||||
self.capture_calls.append(kwargs)
|
||||
return {}
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeRuntime:
|
||||
broker: FakeBroker = field(default_factory=FakeBroker)
|
||||
app_capabilities: FakeAppCapabilities = field(default_factory=FakeAppCapabilities)
|
||||
|
||||
|
||||
class CommandArgs(TypedDict, total=False, closed=True):
|
||||
query: str
|
||||
path: str
|
||||
old_path: str
|
||||
new_path: str
|
||||
cursor: str
|
||||
limit: int
|
||||
depth: int
|
||||
node_id: str
|
||||
receipt_id: str
|
||||
item_id: str
|
||||
image_file_ids: list[str]
|
||||
|
||||
|
||||
def request(
|
||||
name: KnowledgeFsCommandName = "spaces",
|
||||
context: DifyExecutionContextLayerConfig = CONTEXT,
|
||||
**args: Unpack[CommandArgs],
|
||||
) -> KnowledgeFsPrepareRequest:
|
||||
cmd = KnowledgeFsCommand.model_validate(
|
||||
{"command_id": uuid4(), "command": name, **({"space": "docs"} if name != "spaces" else {}), **args}
|
||||
)
|
||||
return KnowledgeFsPrepareRequest(
|
||||
execution_context=context,
|
||||
bindings=[BINDING],
|
||||
command=cmd,
|
||||
agent_supports_vision=True,
|
||||
citation=CITATION if cmd.receipt_id else None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def authorized_gateway(monkeypatch: pytest.MonkeyPatch) -> tuple[gateway.AgentKnowledgeGateway, FakeRuntime]:
|
||||
monkeypatch.setattr(gateway.AgentKnowledgeGateway, "_authorize_context", staticmethod(lambda _: SOUL))
|
||||
apply_config_overrides(
|
||||
monkeypatch,
|
||||
DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
|
||||
KNOWLEDGE_FS_ENABLED=True,
|
||||
KNOWLEDGE_FS_BASE_URL="http://kfs:8000",
|
||||
)
|
||||
runtime = FakeRuntime()
|
||||
return gateway.AgentKnowledgeGateway(cast(KnowledgeFSRuntime, runtime)), runtime
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"context",
|
||||
[CONTEXT, CONTEXT.model_copy(update={"agent_config_version_kind": "draft", "invoke_from": "debugger"})],
|
||||
ids=("published", "preview"),
|
||||
)
|
||||
@pytest.mark.parametrize("command", ["search", "spaces"])
|
||||
def test_disabled_feature_blocks_agent_commands_before_capability_issuance(
|
||||
authorized_gateway: tuple[gateway.AgentKnowledgeGateway, FakeRuntime],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
context: DifyExecutionContextLayerConfig,
|
||||
command: KnowledgeFsCommandName,
|
||||
) -> None:
|
||||
service, runtime = authorized_gateway
|
||||
apply_config_overrides(monkeypatch, KNOWLEDGE_FS_ENABLED=False)
|
||||
monkeypatch.setattr(
|
||||
gateway.AgentKnowledgeGateway,
|
||||
"_authorize_context",
|
||||
staticmethod(lambda _: pytest.fail("disabled KnowledgeFS must not read Agent configuration")),
|
||||
)
|
||||
prepared_request = (
|
||||
request("search", context=context, query="hello") if command == "search" else request("spaces", context=context)
|
||||
)
|
||||
|
||||
with pytest.raises(KnowledgeFsError) as error:
|
||||
service.prepare(prepared_request)
|
||||
|
||||
assert error.value.code == "KNOWLEDGE_UNAVAILABLE"
|
||||
assert error.value.status_code == 503
|
||||
assert runtime.app_capabilities.issue_calls == []
|
||||
assert runtime.broker.issue_interactive_calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "args", "operation", "query"),
|
||||
[
|
||||
("capabilities", {}, "getSettings", {}),
|
||||
("search", {"query": "hello"}, "retrieveEvidence", {}),
|
||||
("ls", {"path": "/knowledge"}, "listKnowledgeFs", {"path": "/knowledge", "limit": "10"}),
|
||||
(
|
||||
"tree",
|
||||
{"path": "/knowledge", "cursor": "next", "depth": 3},
|
||||
"treeKnowledgeFs",
|
||||
{"path": "/knowledge", "limit": "10", "cursor": "next", "depth": "3"},
|
||||
),
|
||||
(
|
||||
"find",
|
||||
{"path": "/knowledge", "query": "manual"},
|
||||
"findKnowledgeFs",
|
||||
{"path": "/knowledge", "limit": "10", "nameContains": "manual"},
|
||||
),
|
||||
(
|
||||
"grep",
|
||||
{"path": "/knowledge", "query": "manual"},
|
||||
"grepKnowledgeFs",
|
||||
{"path": "/knowledge", "limit": "10", "q": "manual", "timeoutMs": "5000"},
|
||||
),
|
||||
("cat", {"path": "/knowledge/a", "limit": 5}, "catKnowledgeFs", {"path": "/knowledge/a", "limit": "5"}),
|
||||
("stat", {"path": "/knowledge/a"}, "statKnowledgeFs", {"path": "/knowledge/a"}),
|
||||
(
|
||||
"diff",
|
||||
{"old_path": "/knowledge/a", "new_path": "/knowledge/b"},
|
||||
"diffKnowledgeFs",
|
||||
{"oldPath": "/knowledge/a", "newPath": "/knowledge/b", "mode": "line"},
|
||||
),
|
||||
("open", {"node_id": NODE}, "openNodeKnowledgeFs", {"nodeId": NODE}),
|
||||
("images", {"receipt_id": CITATION.id}, "getDocumentMultimodalManifest", {}),
|
||||
(
|
||||
"image",
|
||||
{"receipt_id": CITATION.id, "item_id": "image-1"},
|
||||
"getDocumentMultimodalAsset",
|
||||
{"variant": "thumbnail", "expectedArtifactHash": CITATION.artifact_hash},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_every_command_maps_to_exact_current_product_contract(
|
||||
authorized_gateway: tuple[gateway.AgentKnowledgeGateway, FakeRuntime],
|
||||
name: KnowledgeFsCommandName,
|
||||
args: CommandArgs,
|
||||
operation: str,
|
||||
query: dict[str, str],
|
||||
) -> None:
|
||||
service, runtime = authorized_gateway
|
||||
result = service.prepare(request(name, **args))
|
||||
assert result.operation == operation
|
||||
assert result.query == query
|
||||
assert result.url is not None
|
||||
assert result.url.startswith(f"http://kfs:8000/knowledge-spaces/{SPACE}/")
|
||||
assert runtime.app_capabilities.issue_calls[-1]["caller_kind"] is KnowledgeFSAppSpaceJoinType.AGENT
|
||||
assert "private-token" not in repr(result)
|
||||
if name == "search":
|
||||
assert result.payload is not None
|
||||
assert result.payload["mode"] == "fast"
|
||||
assert result.payload["includeText"] is True
|
||||
assert "plan" not in result.payload
|
||||
assert "answer" not in result.payload
|
||||
|
||||
|
||||
def test_space_subset_changed_config_and_receipt_scope_fail_closed(
|
||||
authorized_gateway: tuple[gateway.AgentKnowledgeGateway, FakeRuntime],
|
||||
) -> None:
|
||||
service, runtime = authorized_gateway
|
||||
value = request("search", query="x")
|
||||
value.command.space = "another-space"
|
||||
with pytest.raises(KnowledgeFsError, match="Choose an Agent Knowledge Base"):
|
||||
service.prepare(value)
|
||||
value = request()
|
||||
value.bindings = [BINDING.model_copy(update={"name": "swapped"})]
|
||||
with pytest.raises(KnowledgeFsError, match="bindings changed"):
|
||||
service.prepare(value)
|
||||
value = request("image", receipt_id=CITATION.id, item_id="image-1")
|
||||
value.citation = CITATION.model_copy(update={"control_space_id": DOC})
|
||||
with pytest.raises(KnowledgeFsError, match="receipt"):
|
||||
service.prepare(value)
|
||||
value = request("image", receipt_id=CITATION.id, item_id="image-1")
|
||||
value.agent_supports_vision = False
|
||||
with pytest.raises(KnowledgeFsError, match="cannot consume images"):
|
||||
service.prepare(value)
|
||||
assert runtime.app_capabilities.issue_calls == []
|
||||
|
||||
|
||||
def test_classic_bindings_do_not_block_knowledge_fs_authorization(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
authorized_gateway: tuple[gateway.AgentKnowledgeGateway, FakeRuntime],
|
||||
) -> None:
|
||||
soul = AgentSoulConfig.model_validate(
|
||||
{
|
||||
"knowledge": {
|
||||
"spaces": [BINDING.model_dump()],
|
||||
"sets": [
|
||||
{
|
||||
"id": "classic",
|
||||
"name": "Classic Docs",
|
||||
"datasets": [{"id": "dataset-1"}],
|
||||
"query": {"mode": "generated_query"},
|
||||
"retrieval": {"mode": "multiple", "top_k": 3},
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
monkeypatch.setattr(gateway.AgentKnowledgeGateway, "_authorize_context", staticmethod(lambda _: soul))
|
||||
service, runtime = authorized_gateway
|
||||
|
||||
result = service.prepare(request("search", query="hello"))
|
||||
|
||||
assert result.operation == "retrieveEvidence"
|
||||
assert len(runtime.app_capabilities.issue_calls) == 1
|
||||
|
||||
|
||||
def test_preview_never_issues_app_grants_and_revocation_is_rechecked(
|
||||
authorized_gateway: tuple[gateway.AgentKnowledgeGateway, FakeRuntime],
|
||||
) -> None:
|
||||
service, runtime = authorized_gateway
|
||||
preview = CONTEXT.model_copy(update={"agent_config_version_kind": "draft", "invoke_from": "debugger"})
|
||||
service.prepare(request("search", context=preview, query="x"))
|
||||
assert len(runtime.broker.issue_interactive_calls) == 1
|
||||
assert runtime.app_capabilities.issue_calls == []
|
||||
runtime.app_capabilities.issue_failure = PermissionError("revoked")
|
||||
with pytest.raises(PermissionError):
|
||||
service.prepare(request("search", query="x"))
|
||||
assert service.prepare(request()).data == {"spaces": [{"id": "docs", "name": "产品说明", "available": False}]}
|
||||
|
||||
|
||||
def test_preview_query_images_use_current_account_authorization_without_app_grants(
|
||||
authorized_gateway: tuple[gateway.AgentKnowledgeGateway, FakeRuntime], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
service, runtime = authorized_gateway
|
||||
image_id = str(uuid4())
|
||||
validate = RecordingCallable(
|
||||
result=[KnowledgeFSQueryImageMetadata(upload_file_id=image_id, byte_size=10, mime_type="image/png")]
|
||||
)
|
||||
monkeypatch.setattr(gateway, "validate_query_image_references", validate)
|
||||
preview = CONTEXT.model_copy(update={"agent_config_version_kind": "draft", "invoke_from": "debugger"})
|
||||
result = service.prepare(request("search", context=preview, image_file_ids=[image_id]))
|
||||
assert [call.kwargs for call in validate.calls] == [
|
||||
{"tenant_id": "tenant", "account_id": "account", "upload_file_ids": [image_id], "mark_used": False}
|
||||
]
|
||||
assert result.payload is not None
|
||||
assert result.payload["queryImages"] == [{"uploadFileId": image_id}]
|
||||
assert result.payload["query"] == ""
|
||||
assert runtime.app_capabilities.issue_calls == []
|
||||
validate.failure = PermissionError("revoked")
|
||||
with pytest.raises(PermissionError):
|
||||
service.prepare(request("search", context=preview, image_file_ids=[image_id]))
|
||||
|
||||
|
||||
def test_published_query_images_use_file_scope_and_keep_grants_out_of_public_payload(
|
||||
authorized_gateway: tuple[gateway.AgentKnowledgeGateway, FakeRuntime], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from services.knowledge_fs.product_remote import KNOWLEDGE_FS_QUERY_IMAGE_GRANTS_HEADER
|
||||
|
||||
service, _ = authorized_gateway
|
||||
image_id = str(uuid4())
|
||||
file = object()
|
||||
resolve = RecordingCallable(result=file)
|
||||
grant = RecordingCallable(
|
||||
result=KnowledgeFSWorkflowQueryImageReference(
|
||||
upload_file_id=image_id, access_grant="private-image-grant", byte_size=10, mime_type="image/png"
|
||||
)
|
||||
)
|
||||
scope = RecordingCallable[AbstractContextManager[None]](result=nullcontext())
|
||||
monkeypatch.setattr(gateway, "build_from_mapping", resolve)
|
||||
monkeypatch.setattr(gateway, "issue_workflow_query_image_reference", grant)
|
||||
monkeypatch.setattr(gateway, "bind_file_access_scope", scope)
|
||||
context = CONTEXT.model_copy(update={"invoke_from": "web-app"})
|
||||
result = service.prepare(request("search", context=context, query="diagram", image_file_ids=[image_id]))
|
||||
assert resolve.calls[-1].kwargs["mapping"] == {
|
||||
"type": "image",
|
||||
"transfer_method": "local_file",
|
||||
"upload_file_id": image_id,
|
||||
}
|
||||
bound_scope = scope.calls[-1].args[0]
|
||||
assert isinstance(bound_scope, FileAccessScope)
|
||||
assert bound_scope.user_id == "account"
|
||||
assert [call.kwargs for call in grant.calls] == [{"app_id": "app", "tenant_id": "tenant", "file": file}]
|
||||
assert result.payload is not None
|
||||
assert result.payload["queryImages"] == [{"uploadFileId": image_id}]
|
||||
assert result.headers[KNOWLEDGE_FS_QUERY_IMAGE_GRANTS_HEADER]
|
||||
assert "private-image-grant" not in repr(result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sqlite_session", [(App, Agent, WorkflowAgentNodeBinding)], indirect=True)
|
||||
def test_real_context_scope_rejects_foreign_tenant_wrong_agent_and_changed_workflow(
|
||||
sqlite_session: Session, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
sqlite_session.add_all(
|
||||
[
|
||||
App(
|
||||
id="app",
|
||||
tenant_id="tenant",
|
||||
name="Agent",
|
||||
mode=AppMode.AGENT,
|
||||
status=AppStatus.NORMAL,
|
||||
enable_site=True,
|
||||
enable_api=True,
|
||||
max_active_requests=0,
|
||||
),
|
||||
Agent(
|
||||
id="agent",
|
||||
tenant_id="tenant",
|
||||
name="Agent",
|
||||
app_id="app",
|
||||
scope=AgentScope.ROSTER,
|
||||
source=AgentSource.AGENT_APP,
|
||||
),
|
||||
]
|
||||
)
|
||||
sqlite_session.flush()
|
||||
monkeypatch.setattr(gateway.session_factory, "create_session", lambda: nullcontext(sqlite_session))
|
||||
monkeypatch.setattr(gateway, "_account_belongs_to_tenant", lambda *_args, **_kwargs: True)
|
||||
target = AgentConfigTarget(
|
||||
tenant_id="tenant",
|
||||
agent_id="agent",
|
||||
version_id="snapshot",
|
||||
kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
writable=False,
|
||||
version=AgentConfigSnapshot(tenant_id="tenant", agent_id="agent", version=1, config_snapshot=SOUL),
|
||||
agent_soul=SOUL,
|
||||
)
|
||||
monkeypatch.setattr(gateway.AgentConfigService, "resolve_target", lambda *_args, **_kwargs: target)
|
||||
assert gateway.AgentKnowledgeGateway._authorize_context(request()) == SOUL
|
||||
for changes in (
|
||||
{"tenant_id": "foreign"},
|
||||
{"agent_id": "foreign-agent"},
|
||||
{"agent_mode": "workflow_run", "workflow_id": "wf", "node_id": "node"},
|
||||
):
|
||||
with pytest.raises(KnowledgeFsError):
|
||||
gateway.AgentKnowledgeGateway._authorize_context(request(context=CONTEXT.model_copy(update=changes)))
|
||||
monkeypatch.setattr(gateway, "_account_belongs_to_tenant", lambda *_args, **_kwargs: False)
|
||||
with pytest.raises(KnowledgeFsError, match="membership"):
|
||||
gateway.AgentKnowledgeGateway._authorize_context(request())
|
||||
monkeypatch.setattr(gateway, "_account_belongs_to_tenant", lambda *_args, **_kwargs: True)
|
||||
agent = sqlite_session.get(Agent, "agent")
|
||||
assert agent is not None
|
||||
agent.status = AgentStatus.ARCHIVED
|
||||
sqlite_session.flush()
|
||||
with pytest.raises(KnowledgeFsError, match="unavailable"):
|
||||
gateway.AgentKnowledgeGateway._authorize_context(request())
|
||||
|
||||
|
||||
def test_only_trusted_tool_metadata_produces_sources() -> None:
|
||||
content = {"knowledge_results": [{"data": {"items": [{"receipt_id": CITATION.id, "text": "evidence"}]}}]}
|
||||
assert knowledge_sources_from_tool_part({"part_kind": "tool-return", "content": content}) == []
|
||||
part = {
|
||||
"part_kind": "tool-return",
|
||||
"content": content,
|
||||
"metadata": {"knowledge_fs_citations": [CITATION.model_dump(), CITATION.model_dump(), {"id": "forged"}]},
|
||||
}
|
||||
sources = knowledge_sources_from_tool_part(part)
|
||||
assert len(sources) == 1
|
||||
assert sources[0].knowledge_fs_citation == CITATION
|
||||
assert sources[0].content == "evidence"
|
||||
assert sources[0].score is None
|
||||
|
||||
|
||||
def test_workflow_space_union_reads_frozen_snapshots_not_graph_soul(sqlite_session: Session) -> None:
|
||||
other_space = KnowledgeFsBinding(id="other", control_space_id="00000000-0000-4000-8000-000000000009", name="other")
|
||||
other_soul = AgentSoulConfig.model_validate({"knowledge": {"spaces": [other_space.model_dump()]}})
|
||||
|
||||
def binding(node_id: str, agent_id: str, snapshot_id: str, workflow_version: str) -> WorkflowAgentNodeBinding:
|
||||
return WorkflowAgentNodeBinding(
|
||||
tenant_id="tenant",
|
||||
app_id="app",
|
||||
workflow_id="workflow",
|
||||
workflow_version=workflow_version,
|
||||
node_id=node_id,
|
||||
binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
|
||||
agent_id=agent_id,
|
||||
current_snapshot_id=snapshot_id,
|
||||
node_job_config=WorkflowNodeJobConfig(),
|
||||
)
|
||||
|
||||
sqlite_session.add_all(
|
||||
[
|
||||
AgentConfigSnapshot(
|
||||
id="snapshot-1", tenant_id="tenant", agent_id="agent-1", version=1, config_snapshot=SOUL
|
||||
),
|
||||
AgentConfigSnapshot(
|
||||
id="snapshot-2", tenant_id="tenant", agent_id="agent-2", version=1, config_snapshot=SOUL
|
||||
),
|
||||
# A newer snapshot of agent-1 that the published binding does not point at.
|
||||
AgentConfigSnapshot(
|
||||
id="snapshot-1-newer", tenant_id="tenant", agent_id="agent-1", version=2, config_snapshot=other_soul
|
||||
),
|
||||
AgentConfigSnapshot(
|
||||
id="snapshot-draft", tenant_id="tenant", agent_id="agent-3", version=1, config_snapshot=other_soul
|
||||
),
|
||||
binding("node-1", "agent-1", "snapshot-1", "published"),
|
||||
binding("node-2", "agent-2", "snapshot-2", "published"),
|
||||
# The draft copy of the same workflow binds a different Agent.
|
||||
binding("node-1", "agent-3", "snapshot-draft", "draft"),
|
||||
]
|
||||
)
|
||||
sqlite_session.flush()
|
||||
|
||||
workflow = Workflow(tenant_id="tenant", app_id="app", id="workflow", version="published")
|
||||
assert collect_workflow_agent_knowledge_space_ids(session=sqlite_session, workflow=workflow) == (SPACE,)
|
||||
|
||||
|
||||
def test_investigation_capture_reauthorizes_agent_and_keeps_stable_id(
|
||||
authorized_gateway: tuple[gateway.AgentKnowledgeGateway, FakeRuntime],
|
||||
) -> None:
|
||||
from dify_agent.protocol.knowledge_investigation import KnowledgeAttempt, KnowledgeInvestigationPayload
|
||||
|
||||
service, runtime = authorized_gateway
|
||||
report = KnowledgeInvestigationPayload(
|
||||
investigation_id=uuid4(),
|
||||
execution_context=CONTEXT,
|
||||
bindings=[BINDING],
|
||||
query="refund",
|
||||
answer="unknown",
|
||||
status="completed",
|
||||
attempts=[
|
||||
KnowledgeAttempt(
|
||||
command_id=uuid4(),
|
||||
control_space_id=SPACE,
|
||||
command="search",
|
||||
query="refund",
|
||||
outcome="empty",
|
||||
started_at_ms=1,
|
||||
elapsed_ms=4,
|
||||
delivered=True,
|
||||
authorization_fingerprint="a" * 64,
|
||||
)
|
||||
],
|
||||
)
|
||||
service.capture_investigation(report, SPACE)
|
||||
first = runtime.app_capabilities.capture_calls[-1]["payload"]
|
||||
service.capture_investigation(report, SPACE)
|
||||
assert runtime.app_capabilities.capture_calls[-1]["payload"] == first
|
||||
assert isinstance(first, dict)
|
||||
assert first["query"] == "refund"
|
||||
assert len(first["attempts"]) == 1
|
||||
assert runtime.app_capabilities.issue_calls[-1]["caller_kind"] == KnowledgeFSAppSpaceJoinType.AGENT
|
||||
assert runtime.app_capabilities.issue_calls[-1]["operation_id"] == "captureAgentKnowledgeInvestigation"
|
||||
runtime.app_capabilities.issued = ISSUED._replace(authorization_fingerprint="b" * 64)
|
||||
with pytest.raises(KnowledgeFsError, match="authorization changed"):
|
||||
service.capture_investigation(report, SPACE)
|
||||
assert len(runtime.app_capabilities.capture_calls) == 2
|
||||
with pytest.raises(KnowledgeFsError, match="not bound"):
|
||||
service.capture_investigation(report, str(uuid4()))
|
||||
@@ -0,0 +1,61 @@
|
||||
import pytest
|
||||
from dify_agent.protocol.knowledge_fs import KnowledgeFsError
|
||||
|
||||
from core.app.entities.app_invoke_entities import DifyRunContext, InvokeFrom, UserFrom
|
||||
from graphon.model_runtime.entities.model_entities import ModelFeature
|
||||
from models.agent_config_entities import AgentSoulConfig
|
||||
from services.agent import knowledge_runtime_config as mapping
|
||||
from tests.helpers.unit.config_override import apply_config_overrides
|
||||
from tests.helpers.unit.knowledge_fs_core_fakes import RecordingModelFactory, llm_schema
|
||||
|
||||
|
||||
def soul() -> AgentSoulConfig:
|
||||
return AgentSoulConfig.model_validate(
|
||||
{
|
||||
"model": {"plugin_id": "author/plugin", "model_provider": "provider", "model": "model"},
|
||||
"knowledge": {
|
||||
"spaces": [{"id": "docs", "control_space_id": "00000000-0000-4000-8000-000000000001", "name": "Docs"}]
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def run_context() -> DifyRunContext:
|
||||
return DifyRunContext(
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
user_id="user-1",
|
||||
user_from=UserFrom.ACCOUNT,
|
||||
invoke_from=InvokeFrom.DEBUGGER,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("vision", [True, False])
|
||||
def test_knowledge_vision_is_owned_by_agent_model_without_provider_env(
|
||||
monkeypatch: pytest.MonkeyPatch, vision: bool
|
||||
) -> None:
|
||||
apply_config_overrides(monkeypatch, AGENT_SHELL_ENABLED=True)
|
||||
factory = RecordingModelFactory(schema=llm_schema(features=[ModelFeature.VISION] if vision else []))
|
||||
monkeypatch.setattr(mapping, "DifyModelFactory", factory)
|
||||
context = run_context()
|
||||
config = mapping.build_knowledge_fs_layer_config(soul(), run_context=context)
|
||||
assert config is not None
|
||||
assert config.agent_supports_vision is vision
|
||||
assert config.spaces[0].name == "Docs"
|
||||
assert len(factory.run_contexts) == 1
|
||||
assert factory.run_contexts[0] is context
|
||||
assert factory.model_lookups == [("provider", "model")]
|
||||
assert "provider" not in config.model_dump_json()
|
||||
|
||||
|
||||
def test_no_knowledge_has_no_model_or_shell_dependency_and_import_requires_rebind(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
apply_config_overrides(monkeypatch, AGENT_SHELL_ENABLED=False)
|
||||
assert mapping.build_knowledge_fs_layer_config(AgentSoulConfig(), run_context=run_context()) is None
|
||||
with pytest.raises(KnowledgeFsError, match="sandbox shell"):
|
||||
mapping.build_knowledge_fs_layer_config(soul(), run_context=run_context())
|
||||
imported = soul()
|
||||
imported.knowledge.spaces[0].is_missing = True
|
||||
with pytest.raises(KnowledgeFsError, match="Reselect"):
|
||||
mapping.build_knowledge_fs_layer_config(imported, run_context=run_context())
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,133 @@
|
||||
"""Package icon imports persist destination-owned uploads in one transaction."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import zipfile
|
||||
from collections.abc import Callable, Iterator
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from sqlalchemy import event, select
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from extensions.storage.storage_type import StorageType
|
||||
from models.enums import CreatorUserRole
|
||||
from models.model import UploadFile
|
||||
from services.agent.errors import RosterAgentPackageResourceUnavailableError
|
||||
from services.agent.package_resource_importer import AgentPackageResourceImporter
|
||||
from services.agent.roster_package_entities import PackageIcon, PreparedPackageArchive, RosterAgentPackageMember
|
||||
|
||||
|
||||
class RecordingStorage:
|
||||
def __init__(self, *, failure: Exception | None = None) -> None:
|
||||
self.saved: list[tuple[str, bytes]] = []
|
||||
self.failure = failure
|
||||
|
||||
def save(self, filename: str, data: bytes) -> None:
|
||||
if self.failure is not None and len(self.saved) == 1:
|
||||
raise self.failure
|
||||
self.saved.append((filename, data))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def packaged_icons(
|
||||
config_overrides: Callable[..., None],
|
||||
) -> Iterator[tuple[PreparedPackageArchive, list[PackageIcon], dict[str, bytes]]]:
|
||||
config_overrides(STORAGE_TYPE="local")
|
||||
payloads: dict[str, bytes] = {}
|
||||
icons: list[PackageIcon] = []
|
||||
members: dict[str, RosterAgentPackageMember] = {}
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, "w") as package:
|
||||
for index, (extension, color) in enumerate([("png", "red"), ("jpg", "blue")], start=1):
|
||||
image = io.BytesIO()
|
||||
Image.new("RGB", (1, 1), color=color).save(image, format="PNG" if extension == "png" else "JPEG")
|
||||
payload = image.getvalue()
|
||||
icon_id = f"i_{index:06d}"
|
||||
path = f"{icon_id}.{extension}"
|
||||
digest = hashlib.sha256(payload).hexdigest()
|
||||
package.writestr(path, payload)
|
||||
payloads[path] = payload
|
||||
members[path] = RosterAgentPackageMember(size=len(payload), sha256=digest)
|
||||
icons.append(PackageIcon(id=icon_id, path=path, size=len(payload), sha256=digest))
|
||||
with PreparedPackageArchive(archive=archive, members=members) as prepared:
|
||||
yield prepared, icons, payloads
|
||||
|
||||
|
||||
def test_materialize_icons_commits_destination_owned_uploads(
|
||||
packaged_icons: tuple[PreparedPackageArchive, list[PackageIcon], dict[str, bytes]],
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
archive, icons, payloads = packaged_icons
|
||||
storage = RecordingStorage()
|
||||
|
||||
mapping = AgentPackageResourceImporter(storage_backend=storage).materialize_icons(
|
||||
archive=archive, icons=icons, tenant_id="destination", account_id="importer"
|
||||
)
|
||||
|
||||
with sqlite_session_factory() as session:
|
||||
rows = {row.id: row for row in session.scalars(select(UploadFile))}
|
||||
assert set(mapping) == {icon.id for icon in icons}
|
||||
assert set(mapping.values()) == set(rows)
|
||||
assert len(rows) == 2
|
||||
for icon in icons:
|
||||
row = rows[mapping[icon.id]]
|
||||
payload = payloads[icon.path]
|
||||
extension = icon.path.rsplit(".", 1)[1]
|
||||
assert row.tenant_id == "destination"
|
||||
assert row.created_by == "importer"
|
||||
assert row.created_by_role == CreatorUserRole.ACCOUNT
|
||||
assert row.storage_type == StorageType.LOCAL
|
||||
assert row.name == icon.path
|
||||
assert row.size == len(payload)
|
||||
assert row.hash == hashlib.sha3_256(payload).hexdigest()
|
||||
assert row.mime_type == ("image/png" if extension == "png" else "image/jpeg")
|
||||
assert row.key == f"upload_files/destination/{row.id}.{extension}"
|
||||
assert storage.saved == [(rows[mapping[icon.id]].key, payloads[icon.path]) for icon in icons]
|
||||
|
||||
|
||||
def test_materialize_icons_storage_failure_does_not_persist_partial_metadata(
|
||||
packaged_icons: tuple[PreparedPackageArchive, list[PackageIcon], dict[str, bytes]],
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
archive, icons, _ = packaged_icons
|
||||
error = OSError("storage unavailable")
|
||||
storage = RecordingStorage(failure=error)
|
||||
|
||||
with pytest.raises(RosterAgentPackageResourceUnavailableError) as caught:
|
||||
AgentPackageResourceImporter(storage_backend=storage).materialize_icons(
|
||||
archive=archive, icons=icons, tenant_id="destination", account_id="importer"
|
||||
)
|
||||
|
||||
assert caught.value.__cause__ is error
|
||||
with sqlite_session_factory() as session:
|
||||
assert list(session.scalars(select(UploadFile))) == []
|
||||
|
||||
|
||||
def test_materialize_icons_commit_failure_rolls_back_all_uploads(
|
||||
packaged_icons: tuple[PreparedPackageArchive, list[PackageIcon], dict[str, bytes]],
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
archive, icons, _ = packaged_icons
|
||||
storage = RecordingStorage()
|
||||
error = RuntimeError("database commit failed")
|
||||
|
||||
def fail_commit(session: Session) -> None:
|
||||
# Insert the rows in the real transaction before injecting the commit failure.
|
||||
session.flush()
|
||||
raise error
|
||||
|
||||
event.listen(sqlite_session_factory, "before_commit", fail_commit)
|
||||
try:
|
||||
with pytest.raises(RuntimeError) as caught:
|
||||
AgentPackageResourceImporter(storage_backend=storage).materialize_icons(
|
||||
archive=archive, icons=icons, tenant_id="destination", account_id="importer"
|
||||
)
|
||||
finally:
|
||||
event.remove(sqlite_session_factory, "before_commit", fail_commit)
|
||||
|
||||
assert caught.value is error
|
||||
with sqlite_session_factory() as session:
|
||||
assert list(session.scalars(select(UploadFile))) == []
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Unit tests for the prompt mention contract (ENG-616).
|
||||
|
||||
Token form: ``[§<kind>:<id>[:<label>]§]``. Mentions are pointers into the Agent
|
||||
config lists; expansion replaces them with canonical names and the scrub pass
|
||||
guarantees no mention-shaped marker survives to the model.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig, WorkflowPreviousNodeOutputRef
|
||||
from services.agent.prompt_mentions import (
|
||||
MAX_MENTION_REF_ID_LENGTH,
|
||||
NODE_JOB_PROMPT_ALLOWED_KINDS,
|
||||
SOUL_PROMPT_ALLOWED_KINDS,
|
||||
MentionKind,
|
||||
PromptMention,
|
||||
build_node_job_mention_resolver,
|
||||
build_soul_mention_resolver,
|
||||
expand_prompt_mentions,
|
||||
extract_workflow_node_output_selectors,
|
||||
extract_workflow_variable_selectors,
|
||||
normalize_previous_node_output_selector,
|
||||
parse_prompt_mentions,
|
||||
scrub_mention_markers,
|
||||
workflow_previous_node_output_refs_from_selectors,
|
||||
)
|
||||
|
||||
# ── parse ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_parse_extracts_kind_id_and_optional_label() -> None:
|
||||
prompt = "Use [§skill:tender-analyzer%2FSKILL.md:tender-analyzer§] then ask [§human:c-1§]."
|
||||
mentions = parse_prompt_mentions(prompt)
|
||||
|
||||
assert [(m.kind, m.ref_id, m.label) for m in mentions] == [
|
||||
(MentionKind.SKILL, "tender-analyzer%2FSKILL.md", "tender-analyzer"),
|
||||
(MentionKind.HUMAN, "c-1", None),
|
||||
]
|
||||
assert prompt[mentions[0].start : mentions[0].end] == mentions[0].raw
|
||||
|
||||
|
||||
def test_parse_supports_ids_with_slash_and_dot() -> None:
|
||||
mentions = parse_prompt_mentions("[§tool:langgenius/tavily/tavily_search:tavily§] [§node_output:node-1.tenders§]")
|
||||
assert mentions[0].ref_id == "langgenius/tavily/tavily_search"
|
||||
assert mentions[1].ref_id == "node-1.tenders"
|
||||
|
||||
|
||||
def test_parse_supports_legacy_bare_output_tokens() -> None:
|
||||
mentions = parse_prompt_mentions("Use §output:summary:summary§")
|
||||
assert [(mention.kind, mention.ref_id, mention.label) for mention in mentions] == [
|
||||
(MentionKind.OUTPUT, "summary", "summary")
|
||||
]
|
||||
|
||||
|
||||
def test_parse_ignores_legacy_template_forms_and_unknown_kinds() -> None:
|
||||
prompt = "{{var}} {{#context#}} {{#sys.query#}} [§bogus_kind:x§]"
|
||||
assert parse_prompt_mentions(prompt) == []
|
||||
|
||||
|
||||
def test_parse_skips_oversized_id_or_label() -> None:
|
||||
long_id = "x" * (MAX_MENTION_REF_ID_LENGTH + 1)
|
||||
assert parse_prompt_mentions(f"[§skill:{long_id}§]") == []
|
||||
|
||||
|
||||
# ── expand + scrub ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_expand_uses_resolver_and_degrades_unresolved_to_label_then_id() -> None:
|
||||
prompt = "A [§skill:s1:Skill One§] B [§human:h1:EMAIL · DAVE§] C [§knowledge:k1§]"
|
||||
|
||||
def resolver(mention: PromptMention) -> str | None:
|
||||
return "resolved-skill" if mention.kind == MentionKind.SKILL else None
|
||||
|
||||
expanded = expand_prompt_mentions(prompt, resolver)
|
||||
assert expanded == "A resolved-skill B EMAIL · DAVE C k1"
|
||||
assert "[§" not in expanded
|
||||
|
||||
|
||||
def test_expand_scrubs_unknown_kind_tokens_but_keeps_legacy_forms() -> None:
|
||||
prompt = "x [§wat:id-1:Label§] y {{#context#}} z {{#node.var#}}"
|
||||
expanded = expand_prompt_mentions(prompt, lambda _mention: None)
|
||||
# unknown mention-shaped token degraded to its label; legacy forms untouched
|
||||
assert expanded == "x Label y {{#context#}} z {{#node.var#}}"
|
||||
|
||||
|
||||
def test_scrub_degrades_colon_tokens_without_label_to_id_part() -> None:
|
||||
assert scrub_mention_markers("see [§weird_kind:some-id§]") == "see some-id"
|
||||
|
||||
|
||||
def test_expand_empty_prompt_is_noop() -> None:
|
||||
assert expand_prompt_mentions("", lambda _mention: "x") == ""
|
||||
|
||||
|
||||
def test_extract_workflow_variable_selectors_supports_frontend_agent_task_format() -> None:
|
||||
selectors = extract_workflow_variable_selectors(
|
||||
"Read {{#node-1.output#}}, compare {{#start.question#}}, leave {{#context#}} alone."
|
||||
)
|
||||
assert selectors == [("node-1", "output"), ("start", "question")]
|
||||
|
||||
|
||||
def test_extract_workflow_node_output_selectors_supports_current_frontend_markers_only() -> None:
|
||||
selectors = extract_workflow_node_output_selectors(
|
||||
"Read {{#node-1.output#}}, {{#sys.query#}}, [§node_output:legacy-node.report:PREV/report§], "
|
||||
"and {{#node-1.output#}} again."
|
||||
)
|
||||
assert selectors == [("node-1", "output")]
|
||||
|
||||
|
||||
def test_workflow_previous_node_output_refs_from_selectors_materializes_refs() -> None:
|
||||
refs = workflow_previous_node_output_refs_from_selectors([("node-1", "output"), ("node-2", "report", "url")])
|
||||
|
||||
assert refs == [
|
||||
WorkflowPreviousNodeOutputRef(selector=["node-1", "output"], node_id="node-1", output="output"),
|
||||
WorkflowPreviousNodeOutputRef(
|
||||
selector=["node-2", "report", "url"],
|
||||
node_id="node-2",
|
||||
output="report",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# ── soul resolver ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def soul() -> AgentSoulConfig:
|
||||
return AgentSoulConfig.model_validate(
|
||||
{
|
||||
"tools": {
|
||||
"dify_tools": [
|
||||
{
|
||||
"plugin_id": "langgenius/tavily",
|
||||
"provider": "tavily",
|
||||
"provider_type": "plugin",
|
||||
"tool_name": "tavily_search",
|
||||
"credential_type": "unauthorized",
|
||||
},
|
||||
],
|
||||
"cli_tools": [{"id": "ct-1", "name": "ffmpeg"}],
|
||||
},
|
||||
"knowledge": {
|
||||
"sets": [
|
||||
{
|
||||
"id": "kb-1",
|
||||
"name": "产品手册",
|
||||
"datasets": [{"id": "ds-1", "name": "产品手册"}],
|
||||
"query": {"mode": "generated_query"},
|
||||
"retrieval": {"mode": "multiple", "top_k": 4},
|
||||
}
|
||||
]
|
||||
},
|
||||
"human": {"contacts": [{"id": "c-1", "name": "David Hayes", "channel": "email"}]},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_soul_resolver_resolves_each_kind(soul: AgentSoulConfig) -> None:
|
||||
resolver = build_soul_mention_resolver(soul)
|
||||
prompt = (
|
||||
"Use [§tool:tavily/tavily_search:tavily§], run [§cli_tool:ct-1:ffmpeg§], "
|
||||
"ground in [§knowledge:kb-1§], ask [§human:c-1§]."
|
||||
)
|
||||
|
||||
expanded = expand_prompt_mentions(prompt, resolver)
|
||||
|
||||
assert expanded == ("Use tavily_search, run ffmpeg, ground in 产品手册, ask EMAIL · David Hayes.")
|
||||
|
||||
|
||||
def test_soul_resolver_unknown_ids_degrade(soul: AgentSoulConfig) -> None:
|
||||
expanded = expand_prompt_mentions("[§knowledge:missing:旧产品手册§]", build_soul_mention_resolver(soul))
|
||||
assert expanded == "旧产品手册"
|
||||
|
||||
|
||||
def test_soul_resolver_cli_tool_resolves_by_id_and_keeps_name_alias(soul: AgentSoulConfig) -> None:
|
||||
resolver = build_soul_mention_resolver(soul)
|
||||
# id is the contract; the name alias keeps tokens minted before ids existed working
|
||||
assert expand_prompt_mentions("[§cli_tool:ct-1§]", resolver) == "ffmpeg"
|
||||
assert expand_prompt_mentions("[§cli_tool:ffmpeg§]", resolver) == "ffmpeg"
|
||||
# a rename only changes the expansion, never breaks the id reference
|
||||
soul.tools.cli_tools[0].name = "ffmpeg-v7"
|
||||
assert expand_prompt_mentions("[§cli_tool:ct-1§]", build_soul_mention_resolver(soul)) == "ffmpeg-v7"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def soul_with_provider_entry(soul: AgentSoulConfig) -> AgentSoulConfig:
|
||||
# provider-level entry (tool_name omitted) = all tools of the provider
|
||||
soul.tools.dify_tools.append(
|
||||
soul.tools.dify_tools[0].model_copy(
|
||||
update={"plugin_id": "langgenius/duckduckgo", "provider": "duckduckgo", "tool_name": None}
|
||||
)
|
||||
)
|
||||
return soul
|
||||
|
||||
|
||||
def test_soul_resolver_provider_all_tools_mention(soul_with_provider_entry: AgentSoulConfig) -> None:
|
||||
resolver = build_soul_mention_resolver(soul_with_provider_entry)
|
||||
# [§tool:<provider>/*§] = all tools of that provider
|
||||
assert expand_prompt_mentions("Use [§tool:duckduckgo/*:DuckDuckGo 全部§].", resolver) == (
|
||||
"Use all duckduckgo tools."
|
||||
)
|
||||
# plugin-prefixed alias of the same provider
|
||||
assert expand_prompt_mentions("[§tool:langgenius/duckduckgo/duckduckgo/*§]", resolver) == "all duckduckgo tools"
|
||||
# without a provider-level entry the mention dangles -> degrades to label
|
||||
bare = build_soul_mention_resolver(AgentSoulConfig.model_validate({}))
|
||||
assert expand_prompt_mentions("[§tool:duckduckgo/*:DuckDuckGo 全部§]", bare) == "DuckDuckGo 全部"
|
||||
|
||||
|
||||
def test_soul_resolver_single_tool_resolves_via_provider_level_entry(soul_with_provider_entry: AgentSoulConfig) -> None:
|
||||
# one tool offered through the provider-level ("all") entry still resolves
|
||||
resolver = build_soul_mention_resolver(soul_with_provider_entry)
|
||||
assert expand_prompt_mentions("[§tool:duckduckgo/ddg_search§]", resolver) == "ddg_search"
|
||||
|
||||
|
||||
# ── node-job resolver ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def node_job() -> WorkflowNodeJobConfig:
|
||||
return WorkflowNodeJobConfig.model_validate(
|
||||
{
|
||||
"workflow_prompt": "",
|
||||
"previous_node_output_refs": [{"selector": ["start-1", "tenders"], "name": "START/tenders"}],
|
||||
# declared output names are JSON-schema-friendly identifiers (no dots)
|
||||
"declared_outputs": [{"name": "qna_report", "type": "file"}],
|
||||
"human_contacts": [{"id": "c-1", "name": "David Hayes", "channel": "email"}],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_node_job_resolver_resolves_each_kind(node_job: WorkflowNodeJobConfig) -> None:
|
||||
resolver = build_node_job_mention_resolver(node_job)
|
||||
prompt = "Read [§node_output:start-1.tenders§] and produce [§output:qna_report§]; if unsure contact [§human:c-1§]."
|
||||
|
||||
expanded = expand_prompt_mentions(prompt, resolver)
|
||||
|
||||
assert expanded == (
|
||||
"Read START/tenders and produce qna_report (file output; create the file locally, run "
|
||||
"`dify-agent file upload <path>`, then set final_output.qna_report to a `tool_file` mapping "
|
||||
"using the returned `reference`; if replying to the user in natural language, use the returned "
|
||||
"`public_download_url`; do not call final_output before upload succeeds, and do not use the local path, "
|
||||
"filename, URL, or a synthesized dify-file-ref as the reference); "
|
||||
"if unsure contact EMAIL · David Hayes."
|
||||
)
|
||||
|
||||
|
||||
def test_node_job_resolver_accepts_legacy_reversed_output_token(node_job: WorkflowNodeJobConfig) -> None:
|
||||
resolver = build_node_job_mention_resolver(node_job)
|
||||
|
||||
expanded = expand_prompt_mentions("[§qna_report:qna_report:output§]", resolver)
|
||||
|
||||
assert "final_output.qna_report" in expanded
|
||||
|
||||
|
||||
def test_node_job_resolver_exposes_system_text_output() -> None:
|
||||
node_job = WorkflowNodeJobConfig()
|
||||
|
||||
expanded = expand_prompt_mentions("[§output:text§]", build_node_job_mention_resolver(node_job))
|
||||
|
||||
assert expanded == "text (string)"
|
||||
|
||||
|
||||
def test_node_job_resolver_matches_ref_by_node_id_and_output_fields() -> None:
|
||||
node_job = WorkflowNodeJobConfig.model_validate(
|
||||
{"previous_node_output_refs": [{"node_id": "n-2", "output": "text"}]}
|
||||
)
|
||||
expanded = expand_prompt_mentions("[§node_output:n-2.text:LLM/text§]", build_node_job_mention_resolver(node_job))
|
||||
# ref has no display name -> degrade to the mention label
|
||||
assert expanded == "LLM/text"
|
||||
|
||||
|
||||
def test_normalize_previous_node_output_selector_returns_canonical_selector() -> None:
|
||||
assert normalize_previous_node_output_selector(
|
||||
WorkflowPreviousNodeOutputRef(selector=["node-1", "report", "url"])
|
||||
) == ("node-1", "report", "url")
|
||||
assert normalize_previous_node_output_selector(WorkflowPreviousNodeOutputRef(node_id="node-2", output="text")) == (
|
||||
"node-2",
|
||||
"text",
|
||||
)
|
||||
assert normalize_previous_node_output_selector(WorkflowPreviousNodeOutputRef(selector=["node-3", 1])) is None
|
||||
|
||||
|
||||
# ── allowlists ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_per_surface_allowlists_match_design() -> None:
|
||||
assert {
|
||||
MentionKind.SKILL,
|
||||
MentionKind.FILE,
|
||||
MentionKind.TOOL,
|
||||
MentionKind.CLI_TOOL,
|
||||
MentionKind.KNOWLEDGE,
|
||||
MentionKind.HUMAN,
|
||||
} == SOUL_PROMPT_ALLOWED_KINDS
|
||||
assert {MentionKind.NODE_OUTPUT, MentionKind.OUTPUT, MentionKind.HUMAN} == NODE_JOB_PROMPT_ALLOWED_KINDS
|
||||
@@ -0,0 +1,397 @@
|
||||
from contextlib import nullcontext
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.agent import (
|
||||
Agent,
|
||||
AgentConfigVersionKind,
|
||||
AgentHomeSnapshot,
|
||||
AgentKind,
|
||||
AgentScope,
|
||||
AgentSource,
|
||||
AgentStatus,
|
||||
AgentWorkingResourceStatus,
|
||||
AgentWorkspace,
|
||||
AgentWorkspaceBinding,
|
||||
AgentWorkspaceOwnerType,
|
||||
WorkflowAgentBindingType,
|
||||
WorkflowAgentNodeBinding,
|
||||
)
|
||||
from models.enums import AppStatus
|
||||
from models.model import App, AppMode
|
||||
from models.workflow import Workflow, WorkflowType
|
||||
from services.agent.home_snapshot_service import AgentHomeSnapshotService
|
||||
from services.agent.retirement_service import WorkflowAgentRetirementService
|
||||
from services.agent.workspace_service import AgentWorkspaceService
|
||||
|
||||
|
||||
def test_retire_unowned_failure_propagates(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
context = MagicMock()
|
||||
error = RuntimeError("retirement failed")
|
||||
monkeypatch.setattr(
|
||||
"services.agent.retirement_service.session_factory.create_session",
|
||||
lambda: context,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
WorkflowAgentRetirementService,
|
||||
"archive_unowned",
|
||||
MagicMock(side_effect=error),
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
WorkflowAgentRetirementService.retire_unowned(
|
||||
tenant_id="tenant-1",
|
||||
agent_ids=["agent-1"],
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
assert exc_info.value is error
|
||||
|
||||
|
||||
def _workflow_only_agent(*, backing_app_id: str | None = None) -> Agent:
|
||||
return Agent(
|
||||
id="agent-1",
|
||||
tenant_id="tenant-1",
|
||||
name="Inline Agent",
|
||||
description="",
|
||||
role="",
|
||||
agent_kind=AgentKind.DIFY_AGENT,
|
||||
scope=AgentScope.WORKFLOW_ONLY,
|
||||
source=AgentSource.WORKFLOW,
|
||||
status=AgentStatus.ACTIVE,
|
||||
backing_app_id=backing_app_id,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("workflow_version", "pointer_to_owner", "mismatched_key", "expected_status"),
|
||||
[
|
||||
pytest.param(Workflow.VERSION_DRAFT, False, None, AgentStatus.ACTIVE, id="draft-owner"),
|
||||
pytest.param("current-version", True, None, AgentStatus.ACTIVE, id="current-published-owner"),
|
||||
pytest.param("historical-version", False, None, AgentStatus.ACTIVE, id="historical-published-owner"),
|
||||
pytest.param("v1", True, "tenant_id", AgentStatus.ARCHIVED, id="tenant-mismatch"),
|
||||
pytest.param("v1", True, "app_id", AgentStatus.ARCHIVED, id="app-mismatch"),
|
||||
pytest.param("v1", True, "workflow_id", AgentStatus.ARCHIVED, id="workflow-mismatch"),
|
||||
pytest.param("v1", True, "workflow_version", AgentStatus.ARCHIVED, id="version-mismatch"),
|
||||
],
|
||||
)
|
||||
def test_retire_unowned_requires_an_exact_persisted_workflow_owner_key(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
workflow_version: str,
|
||||
pointer_to_owner: bool,
|
||||
mismatched_key: str | None,
|
||||
expected_status: AgentStatus,
|
||||
) -> None:
|
||||
agent = _workflow_only_agent()
|
||||
app = App(
|
||||
id="app-1",
|
||||
tenant_id="tenant-1",
|
||||
name="Workflow",
|
||||
mode=AppMode.WORKFLOW,
|
||||
status=AppStatus.NORMAL,
|
||||
enable_site=True,
|
||||
enable_api=True,
|
||||
)
|
||||
workflow = Workflow.new(
|
||||
tenant_id="workflow-tenant" if mismatched_key == "tenant_id" else "tenant-1",
|
||||
app_id=app.id,
|
||||
type=WorkflowType.WORKFLOW.value,
|
||||
version=workflow_version,
|
||||
graph="{}",
|
||||
features="{}",
|
||||
created_by="account-1",
|
||||
environment_variables=[],
|
||||
conversation_variables=[],
|
||||
rag_pipeline_variables=[],
|
||||
)
|
||||
app.workflow_id = workflow.id if pointer_to_owner else "another-current-workflow"
|
||||
binding_key = {
|
||||
"tenant_id": "tenant-1",
|
||||
"app_id": workflow.app_id,
|
||||
"workflow_id": workflow.id,
|
||||
"workflow_version": workflow.version,
|
||||
}
|
||||
mismatched_values = {
|
||||
"app_id": "app-2",
|
||||
"workflow_id": "workflow-2",
|
||||
"workflow_version": "other-version",
|
||||
}
|
||||
if mismatched_key is not None and mismatched_key != "tenant_id":
|
||||
binding_key[mismatched_key] = mismatched_values[mismatched_key]
|
||||
binding = WorkflowAgentNodeBinding(
|
||||
tenant_id=binding_key["tenant_id"],
|
||||
app_id=binding_key["app_id"],
|
||||
workflow_id=binding_key["workflow_id"],
|
||||
workflow_version=binding_key["workflow_version"],
|
||||
node_id="agent-node",
|
||||
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
|
||||
agent_id=agent.id,
|
||||
current_snapshot_id="config-1",
|
||||
node_job_config={},
|
||||
)
|
||||
sqlite_session.add_all([agent, app, workflow, binding])
|
||||
sqlite_session.commit()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.retirement_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
celery_delay = MagicMock()
|
||||
monkeypatch.setattr("tasks.collect_agent_resources_task.collect_agent_resources.delay", celery_delay)
|
||||
WorkflowAgentRetirementService.retire_unowned(
|
||||
tenant_id="tenant-1",
|
||||
agent_ids=[agent.id],
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
stored_agent = sqlite_session.get(Agent, agent.id)
|
||||
assert stored_agent is not None
|
||||
assert stored_agent.status is expected_status
|
||||
if expected_status is AgentStatus.ACTIVE:
|
||||
celery_delay.assert_not_called()
|
||||
else:
|
||||
celery_delay.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sqlite_session",
|
||||
[(Agent, App, Workflow, WorkflowAgentNodeBinding, AgentHomeSnapshot, AgentWorkspace, AgentWorkspaceBinding)],
|
||||
indirect=True,
|
||||
)
|
||||
def test_retire_unowned_archives_orphan_and_retires_resources(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
agent = _workflow_only_agent(backing_app_id="hidden-app-1")
|
||||
hidden_app = App(
|
||||
id="hidden-app-1",
|
||||
tenant_id="tenant-1",
|
||||
name="Inline Agent runtime",
|
||||
mode=AppMode.AGENT,
|
||||
status=AppStatus.NORMAL,
|
||||
enable_site=True,
|
||||
enable_api=True,
|
||||
)
|
||||
home = AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id=agent.id,
|
||||
snapshot_ref="home-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
workspace = AgentWorkspace(
|
||||
id="workspace-1",
|
||||
tenant_id="tenant-1",
|
||||
app_id=hidden_app.id,
|
||||
owner_type=AgentWorkspaceOwnerType.CONVERSATION,
|
||||
owner_id="conversation-1",
|
||||
owner_scope_key="root",
|
||||
backend_workspace_ref="workspace-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
active_guard=1,
|
||||
)
|
||||
binding = AgentWorkspaceBinding(
|
||||
id="binding-1",
|
||||
tenant_id="tenant-1",
|
||||
app_id=hidden_app.id,
|
||||
workspace_id=workspace.id,
|
||||
agent_id=agent.id,
|
||||
base_home_snapshot_id=home.id,
|
||||
agent_config_version_id="config-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
backend_binding_ref="binding-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
sqlite_session.add_all([agent, hidden_app, home, workspace, binding])
|
||||
sqlite_session.commit()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.retirement_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
cleanup_app = MagicMock()
|
||||
enqueue_collection = MagicMock()
|
||||
monkeypatch.setattr("services.agent.retirement_service.remove_app_and_related_data_task.delay", cleanup_app)
|
||||
monkeypatch.setattr(
|
||||
"services.agent.retirement_service.enqueue_agent_resource_collection",
|
||||
enqueue_collection,
|
||||
)
|
||||
|
||||
WorkflowAgentRetirementService.retire_unowned(
|
||||
tenant_id="tenant-1",
|
||||
agent_ids=[agent.id],
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
stored_agent = sqlite_session.get(Agent, agent.id)
|
||||
stored_binding = sqlite_session.get(AgentWorkspaceBinding, binding.id)
|
||||
stored_workspace = sqlite_session.get(AgentWorkspace, workspace.id)
|
||||
stored_home = sqlite_session.get(AgentHomeSnapshot, home.id)
|
||||
assert stored_agent is not None
|
||||
assert stored_binding is not None
|
||||
assert stored_workspace is not None
|
||||
assert stored_home is not None
|
||||
assert sqlite_session.get(App, hidden_app.id) is None
|
||||
assert stored_agent.status is AgentStatus.ARCHIVED
|
||||
assert stored_binding.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert stored_workspace.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert stored_home.status is AgentWorkingResourceStatus.RETIRED
|
||||
cleanup_app.assert_called_once_with(tenant_id="tenant-1", app_id=hidden_app.id)
|
||||
enqueue_collection.assert_called_once_with(
|
||||
tenant_id="tenant-1",
|
||||
workspace_ids=[workspace.id],
|
||||
binding_ids=[binding.id],
|
||||
home_snapshot_ids=[home.id],
|
||||
purge_agent_ids=[agent.id],
|
||||
)
|
||||
|
||||
|
||||
def test_hidden_app_enqueue_failure_prevents_agent_purge_enqueue(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
context = MagicMock()
|
||||
session = context.__enter__.return_value
|
||||
session.scalars.side_effect = [
|
||||
SimpleNamespace(
|
||||
all=MagicMock(
|
||||
return_value=[
|
||||
SimpleNamespace(backing_app_id="hidden-app-1"),
|
||||
SimpleNamespace(backing_app_id="hidden-app-2"),
|
||||
]
|
||||
)
|
||||
),
|
||||
SimpleNamespace(all=MagicMock(return_value=[])),
|
||||
SimpleNamespace(all=MagicMock(return_value=[])),
|
||||
SimpleNamespace(all=MagicMock(return_value=[])),
|
||||
SimpleNamespace(all=MagicMock(return_value=[])),
|
||||
]
|
||||
monkeypatch.setattr(
|
||||
"services.agent.retirement_service.session_factory.create_session",
|
||||
lambda: context,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
WorkflowAgentRetirementService,
|
||||
"archive_unowned",
|
||||
MagicMock(return_value=["agent-1", "agent-2"]),
|
||||
)
|
||||
monkeypatch.setattr(AgentWorkspaceService, "retire_all_for_app", MagicMock(return_value=[]))
|
||||
monkeypatch.setattr(AgentHomeSnapshotService, "retire_all_for_agent", MagicMock(return_value=[]))
|
||||
error = RuntimeError("broker unavailable")
|
||||
cleanup_app = MagicMock(side_effect=[None, error])
|
||||
monkeypatch.setattr("services.agent.retirement_service.remove_app_and_related_data_task.delay", cleanup_app)
|
||||
enqueue_collection = MagicMock()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.retirement_service.enqueue_agent_resource_collection",
|
||||
enqueue_collection,
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
WorkflowAgentRetirementService.retire_unowned(
|
||||
tenant_id="tenant-1",
|
||||
agent_ids=["agent-1", "agent-2"],
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
assert exc_info.value is error
|
||||
assert [call.kwargs["app_id"] for call in cleanup_app.call_args_list] == ["hidden-app-1", "hidden-app-2"]
|
||||
enqueue_collection.assert_not_called()
|
||||
|
||||
|
||||
def test_retire_unowned_retry_after_hidden_app_enqueue_failure_preserves_full_collector_payload(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
agent = _workflow_only_agent(backing_app_id="hidden-app-1")
|
||||
hidden_app = App(
|
||||
id="hidden-app-1",
|
||||
tenant_id="tenant-1",
|
||||
name="Inline Agent runtime",
|
||||
mode=AppMode.AGENT,
|
||||
status=AppStatus.NORMAL,
|
||||
enable_site=False,
|
||||
enable_api=False,
|
||||
)
|
||||
home = AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id=agent.id,
|
||||
snapshot_ref="home-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
workspace = AgentWorkspace(
|
||||
id="workspace-1",
|
||||
tenant_id="tenant-1",
|
||||
app_id=hidden_app.id,
|
||||
owner_type=AgentWorkspaceOwnerType.CONVERSATION,
|
||||
owner_id="conversation-1",
|
||||
owner_scope_key="root",
|
||||
backend_workspace_ref="workspace-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
active_guard=1,
|
||||
)
|
||||
binding = AgentWorkspaceBinding(
|
||||
id="binding-1",
|
||||
tenant_id="tenant-1",
|
||||
app_id=hidden_app.id,
|
||||
workspace_id=workspace.id,
|
||||
agent_id=agent.id,
|
||||
base_home_snapshot_id=home.id,
|
||||
agent_config_version_id="config-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
backend_binding_ref="binding-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
sqlite_session.add_all([agent, hidden_app, home, workspace, binding])
|
||||
sqlite_session.commit()
|
||||
agent_id = agent.id
|
||||
hidden_app_id = hidden_app.id
|
||||
home_id = home.id
|
||||
workspace_id = workspace.id
|
||||
binding_id = binding.id
|
||||
error = RuntimeError("broker unavailable")
|
||||
cleanup_app = MagicMock(side_effect=[error, None])
|
||||
enqueue_collection = MagicMock()
|
||||
monkeypatch.setattr("services.agent.retirement_service.remove_app_and_related_data_task.delay", cleanup_app)
|
||||
monkeypatch.setattr(
|
||||
"services.agent.retirement_service.enqueue_agent_resource_collection",
|
||||
enqueue_collection,
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
WorkflowAgentRetirementService.retire_unowned(
|
||||
tenant_id="tenant-1",
|
||||
agent_ids=[agent_id],
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
assert exc_info.value is error
|
||||
sqlite_session.expire_all()
|
||||
stored_agent = sqlite_session.get(Agent, agent_id)
|
||||
stored_workspace = sqlite_session.get(AgentWorkspace, workspace_id)
|
||||
stored_binding = sqlite_session.get(AgentWorkspaceBinding, binding_id)
|
||||
stored_home = sqlite_session.get(AgentHomeSnapshot, home_id)
|
||||
assert stored_agent is not None
|
||||
assert stored_workspace is not None
|
||||
assert stored_binding is not None
|
||||
assert stored_home is not None
|
||||
assert stored_agent.status is AgentStatus.ARCHIVED
|
||||
assert sqlite_session.get(App, hidden_app_id) is None
|
||||
assert stored_workspace.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert stored_binding.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert stored_home.status is AgentWorkingResourceStatus.RETIRED
|
||||
enqueue_collection.assert_not_called()
|
||||
|
||||
WorkflowAgentRetirementService.retire_unowned(
|
||||
tenant_id="tenant-1",
|
||||
agent_ids=[agent_id],
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
assert cleanup_app.call_count == 2
|
||||
enqueue_collection.assert_called_once_with(
|
||||
tenant_id="tenant-1",
|
||||
workspace_ids=[workspace_id],
|
||||
binding_ids=[binding_id],
|
||||
home_snapshot_ids=[home_id],
|
||||
purge_agent_ids=[agent_id],
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,165 @@
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.agent import (
|
||||
AgentConfigDraft,
|
||||
AgentConfigDraftType,
|
||||
AgentConfigVersionKind,
|
||||
AgentDebugConversation,
|
||||
AgentWorkspaceBinding,
|
||||
)
|
||||
from models.agent_config_entities import AgentSoulConfig
|
||||
from models.model import App, Conversation
|
||||
from services.agent.runtime_config_service import AgentRuntimeConfigService
|
||||
|
||||
|
||||
def _app() -> App:
|
||||
return App(id="app-1", tenant_id="tenant-1")
|
||||
|
||||
|
||||
def _conversation(*, binding_id: str | None = None) -> Conversation:
|
||||
return Conversation(id="conversation-1", agent_workspace_binding_id=binding_id)
|
||||
|
||||
|
||||
def _soul(prompt: str) -> AgentSoulConfig:
|
||||
return AgentSoulConfig.model_validate(
|
||||
{
|
||||
"prompt": {"system_prompt": prompt},
|
||||
"app_features": {"suggested_questions_after_answer": {"enabled": True}},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _patch_published_soul(monkeypatch: pytest.MonkeyPatch, soul: AgentSoulConfig) -> MagicMock:
|
||||
roster_service = MagicMock()
|
||||
roster_service.return_value.get_published_agent_soul_for_app.return_value = soul
|
||||
monkeypatch.setattr("services.agent.roster_service.AgentRosterService", roster_service)
|
||||
return roster_service
|
||||
|
||||
|
||||
def test_debug_without_mapping_falls_back_to_published_soul(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
published = _soul("published")
|
||||
roster_service = _patch_published_soul(monkeypatch, published)
|
||||
|
||||
result = AgentRuntimeConfigService(sqlite_session).resolve_conversation_soul(
|
||||
app_model=_app(),
|
||||
conversation=_conversation(),
|
||||
account_id="account-1",
|
||||
use_debug_draft=True,
|
||||
)
|
||||
|
||||
assert result == published
|
||||
roster_service.return_value.get_published_agent_soul_for_app.assert_called_once_with(
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
)
|
||||
|
||||
|
||||
def test_debug_without_draft_falls_back_to_published_soul(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
debug_conversation = AgentDebugConversation(
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
account_id="account-1",
|
||||
conversation_id="conversation-1",
|
||||
agent_id="agent-1",
|
||||
draft_type=AgentConfigDraftType.DRAFT,
|
||||
)
|
||||
sqlite_session.add(debug_conversation)
|
||||
sqlite_session.flush()
|
||||
published = _soul("published")
|
||||
_patch_published_soul(monkeypatch, published)
|
||||
|
||||
result = AgentRuntimeConfigService(sqlite_session).resolve_conversation_soul(
|
||||
app_model=_app(),
|
||||
conversation=_conversation(),
|
||||
account_id="account-1",
|
||||
use_debug_draft=True,
|
||||
)
|
||||
|
||||
assert result == published
|
||||
|
||||
|
||||
def test_missing_binding_falls_back_to_published_soul(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
|
||||
published = _soul("published")
|
||||
_patch_published_soul(monkeypatch, published)
|
||||
|
||||
result = AgentRuntimeConfigService(sqlite_session).resolve_conversation_soul(
|
||||
app_model=_app(),
|
||||
conversation=_conversation(binding_id="binding-1"),
|
||||
account_id=None,
|
||||
use_debug_draft=False,
|
||||
)
|
||||
|
||||
assert result == published
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version_kind", [AgentConfigVersionKind.SNAPSHOT, AgentConfigVersionKind.DRAFT])
|
||||
def test_missing_bound_version_falls_back_to_published_soul(
|
||||
version_kind: AgentConfigVersionKind,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
binding = AgentWorkspaceBinding(
|
||||
id="binding-1",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workspace_id="workspace-1",
|
||||
backend_binding_ref="binding-ref-1",
|
||||
agent_id="agent-1",
|
||||
agent_config_version_id="version-1",
|
||||
agent_config_version_kind=version_kind,
|
||||
)
|
||||
sqlite_session.add(binding)
|
||||
sqlite_session.flush()
|
||||
published = _soul("published")
|
||||
_patch_published_soul(monkeypatch, published)
|
||||
|
||||
result = AgentRuntimeConfigService(sqlite_session).resolve_conversation_soul(
|
||||
app_model=_app(),
|
||||
conversation=_conversation(binding_id="binding-1"),
|
||||
account_id=None,
|
||||
use_debug_draft=False,
|
||||
)
|
||||
|
||||
assert result == published
|
||||
|
||||
|
||||
def test_bound_draft_returns_its_soul(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
|
||||
binding = AgentWorkspaceBinding(
|
||||
id="binding-1",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workspace_id="workspace-1",
|
||||
backend_binding_ref="binding-ref-1",
|
||||
agent_id="agent-1",
|
||||
agent_config_version_id="draft-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.DRAFT,
|
||||
)
|
||||
bound = _soul("bound draft")
|
||||
draft = AgentConfigDraft(
|
||||
id="draft-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
draft_type=AgentConfigDraftType.DRAFT,
|
||||
config_snapshot=bound,
|
||||
)
|
||||
sqlite_session.add_all([binding, draft])
|
||||
sqlite_session.flush()
|
||||
sqlite_session.expire_all()
|
||||
roster_service = _patch_published_soul(monkeypatch, _soul("published"))
|
||||
|
||||
result = AgentRuntimeConfigService(sqlite_session).resolve_conversation_soul(
|
||||
app_model=_app(),
|
||||
conversation=_conversation(binding_id="binding-1"),
|
||||
account_id=None,
|
||||
use_debug_draft=False,
|
||||
)
|
||||
|
||||
assert result == bound
|
||||
roster_service.assert_not_called()
|
||||
@@ -0,0 +1,720 @@
|
||||
"""Accounting invariants tested against real SQLAlchemy persistence."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from pydantic import JsonValue
|
||||
from sqlalchemy import event as sqlalchemy_event
|
||||
from sqlalchemy.dialects import postgresql
|
||||
from sqlalchemy.engine import Connection, Engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from sqlalchemy.sql import ClauseElement
|
||||
|
||||
from models.agent import (
|
||||
Agent,
|
||||
AgentConfigVersionKind,
|
||||
AgentScope,
|
||||
AgentSource,
|
||||
AgentWorkspace,
|
||||
AgentWorkspaceBinding,
|
||||
AgentWorkspaceOwnerType,
|
||||
)
|
||||
from models.agent_sandbox_usage import AgentSandboxExecution, AgentSandboxUsageEvent
|
||||
from models.model import App, AppMode
|
||||
from services.agent.runtime_usage_service import SandboxUsageError, SandboxUsageEvent, SandboxUsageService
|
||||
from tests.helpers.unit.config_override import config_overrides_context
|
||||
|
||||
PROJECT = "431de237-596f-4d59-8a85-20a9846bf243"
|
||||
START = "2026-09-20T00:00:00Z"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def metering_config(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
|
||||
monkeypatch.setattr("services.agent.runtime_usage_service.naive_utc_now", lambda: datetime(2026, 9, 21))
|
||||
with config_overrides_context(
|
||||
AGENT_SANDBOX_METERING_ENABLED=True,
|
||||
AGENT_SANDBOX_METERING_PROJECT_ID=PROJECT,
|
||||
AGENT_SANDBOX_METERING_START_AT=START,
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
def provider_event(
|
||||
*,
|
||||
event_id: str = "event-1",
|
||||
execution_id: str = "execution-1",
|
||||
sandbox_id: str = "sandbox-1",
|
||||
duration: int | None = 12345,
|
||||
started_at: str | None = "2026-09-20T00:00:02Z",
|
||||
kind: str = "paused",
|
||||
metadata: dict[str, JsonValue] | None = None,
|
||||
) -> SandboxUsageEvent:
|
||||
return SandboxUsageEvent.model_validate(
|
||||
{
|
||||
"id": event_id,
|
||||
"source": "provider",
|
||||
"type": f"sandbox.lifecycle.{kind}",
|
||||
"sandbox_id": sandbox_id,
|
||||
"execution_id": execution_id,
|
||||
"payload": {
|
||||
"id": event_id,
|
||||
"version": "v2",
|
||||
"type": f"sandbox.lifecycle.{kind}",
|
||||
"timestamp": "2026-09-20T00:00:14.551745815Z",
|
||||
"sandboxId": sandbox_id,
|
||||
"sandboxExecutionId": execution_id,
|
||||
"sandboxTeamId": PROJECT,
|
||||
"sandboxTemplateId": "template-1",
|
||||
"sandboxBuildId": "build-1",
|
||||
"eventData": {
|
||||
"execution": {
|
||||
"started_at": started_at,
|
||||
"execution_time": duration,
|
||||
"memory_mb": 1024,
|
||||
"vcpu_count": 2,
|
||||
},
|
||||
"sandbox_metadata": metadata or {},
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def ingest(*events: SandboxUsageEvent) -> dict[str, int]:
|
||||
return SandboxUsageService.ingest(project_id=PROJECT, events=list(events))
|
||||
|
||||
|
||||
def execution(factory: sessionmaker[Session]) -> AgentSandboxExecution:
|
||||
with factory() as session:
|
||||
return session.scalars(sa.select(AgentSandboxExecution)).one()
|
||||
|
||||
|
||||
def test_duplicate_terminal_and_api_webhook_aliases_count_once(sqlite_session_factory: sessionmaker[Session]) -> None:
|
||||
event = provider_event()
|
||||
assert ingest(event)["accepted"] == 1
|
||||
alias = deepcopy(event.payload)
|
||||
for camel, snake in (
|
||||
("sandboxId", "sandbox_id"),
|
||||
("sandboxExecutionId", "sandbox_execution_id"),
|
||||
("sandboxTeamId", "sandbox_team_id"),
|
||||
("sandboxTemplateId", "sandbox_template_id"),
|
||||
("sandboxBuildId", "sandbox_build_id"),
|
||||
("eventData", "event_data"),
|
||||
):
|
||||
alias[snake] = alias.pop(camel)
|
||||
assert ingest(event.model_copy(update={"payload": alias}))["duplicates"] == 1
|
||||
assert ingest(provider_event(event_id="killed-event", kind="killed"))["accepted"] == 1
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.metered_duration_ms == 12345
|
||||
assert row.quality == "metered"
|
||||
assert row.started_at == datetime(2026, 9, 20, 0, 0, 2)
|
||||
assert row.terminal_event_at == datetime(2026, 9, 20, 0, 0, 14, 551745)
|
||||
|
||||
|
||||
def test_same_sandbox_resume_is_a_new_execution(sqlite_session_factory: sessionmaker[Session]) -> None:
|
||||
ingest(provider_event(), provider_event(event_id="second", execution_id="execution-2", duration=6789))
|
||||
with sqlite_session_factory() as session:
|
||||
assert session.scalar(sa.select(sa.func.sum(AgentSandboxExecution.metered_duration_ms))) == 19134
|
||||
assert session.scalar(sa.select(sa.func.count()).select_from(AgentSandboxExecution)) == 2
|
||||
|
||||
|
||||
def test_state_reports_pending_and_conflict_counts_without_owner_ids() -> None:
|
||||
created = provider_event(event_id="created", kind="created", duration=None, started_at=None)
|
||||
created.payload["eventData"] = dict[str, JsonValue]()
|
||||
ingest(created)
|
||||
assert SandboxUsageService.get_state(project_id=PROJECT)["diagnostics"] == {
|
||||
"unresolved_events": 0,
|
||||
"conflict_events": 0,
|
||||
"open_executions": 1,
|
||||
"unattributed_executions": 1,
|
||||
}
|
||||
ingest(provider_event())
|
||||
ingest(provider_event(duration=1))
|
||||
diagnostics = SandboxUsageService.get_state(project_id=PROJECT)["diagnostics"]
|
||||
assert diagnostics == {
|
||||
"unresolved_events": 0,
|
||||
"conflict_events": 1,
|
||||
"open_executions": 0,
|
||||
"unattributed_executions": 1,
|
||||
}
|
||||
|
||||
|
||||
def test_unknown_duration_stays_null_and_enrichment_is_replayable(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
missing = provider_event(duration=None)
|
||||
ingest(missing)
|
||||
assert ingest(missing)["duplicates"] == 1
|
||||
assert execution(sqlite_session_factory).metered_duration_ms is None
|
||||
assert execution(sqlite_session_factory).quality == "pending"
|
||||
assert ingest(provider_event())["accepted"] == 1
|
||||
assert execution(sqlite_session_factory).metered_duration_ms == 12345
|
||||
assert ingest(missing)["duplicates"] == 1
|
||||
with sqlite_session_factory() as session:
|
||||
event = session.scalars(
|
||||
sa.select(AgentSandboxUsageEvent).where(AgentSandboxUsageEvent.source_event_id == "event-1")
|
||||
).one()
|
||||
assert event.payload["eventData"]["execution"]["execution_time"] is None
|
||||
assert event.payload_versions
|
||||
assert event.resolution["canonical"]["duration_ms"] == 12345
|
||||
|
||||
|
||||
def test_conflicting_event_keeps_both_payloads_and_quarantines_usage(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
ingest(provider_event())
|
||||
assert ingest(provider_event(duration=999))["conflicts"] == 1
|
||||
assert execution(sqlite_session_factory).quality == "conflict"
|
||||
assert execution(sqlite_session_factory).metered_duration_ms == 12345
|
||||
with sqlite_session_factory() as session:
|
||||
event = session.scalars(
|
||||
sa.select(AgentSandboxUsageEvent).where(AgentSandboxUsageEvent.source_event_id == "event-1")
|
||||
).one()
|
||||
assert event.payload_versions[0]["payload"]["eventData"]["execution"]["execution_time"] == 999
|
||||
ingest(provider_event(event_id="new-terminal"))
|
||||
assert execution(sqlite_session_factory).quality == "conflict"
|
||||
|
||||
|
||||
def test_conflicting_executions_never_add_or_overwrite_duration(sqlite_session_factory: sessionmaker[Session]) -> None:
|
||||
ingest(provider_event())
|
||||
assert ingest(provider_event(event_id="other-terminal", duration=1))["conflicts"] == 1
|
||||
assert execution(sqlite_session_factory).metered_duration_ms == 12345
|
||||
|
||||
|
||||
def test_late_start_does_not_reopen_closed_execution(sqlite_session_factory: sessionmaker[Session]) -> None:
|
||||
ingest(provider_event())
|
||||
ingest(provider_event(event_id="start", kind="resumed", duration=None))
|
||||
row = execution(sqlite_session_factory)
|
||||
assert (row.state, row.quality, row.metered_duration_ms) == ("closed", "metered", 12345)
|
||||
|
||||
|
||||
def test_activation_survives_restarts_and_config_changes_are_rejected() -> None:
|
||||
state = SandboxUsageService.get_state(project_id=PROJECT)
|
||||
assert state["started_at"] == START
|
||||
assert SandboxUsageService.get_state(project_id=PROJECT) == state
|
||||
with config_overrides_context(AGENT_SANDBOX_METERING_START_AT="2026-09-21T00:00:00Z"):
|
||||
with pytest.raises(SandboxUsageError, match="immutable"):
|
||||
SandboxUsageService.get_state(project_id=PROJECT)
|
||||
|
||||
|
||||
def test_no_old_data_even_when_terminal_arrives_after_activation(sqlite_session_factory: sessionmaker[Session]) -> None:
|
||||
assert ingest(provider_event(started_at="2026-09-19T23:59:59Z"))["ignored"] == 1
|
||||
with sqlite_session_factory() as session:
|
||||
assert session.scalar(sa.select(sa.func.count()).select_from(AgentSandboxExecution)) == 0
|
||||
assert (
|
||||
session.scalar(
|
||||
sa.select(sa.func.count())
|
||||
.select_from(AgentSandboxUsageEvent)
|
||||
.where(AgentSandboxUsageEvent.source == "provider")
|
||||
)
|
||||
== 0
|
||||
)
|
||||
|
||||
|
||||
def test_t0_filter_cannot_hide_contradictory_existing_metered_event(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
ingest(provider_event())
|
||||
assert ingest(provider_event(started_at="2026-09-19T23:59:59Z"))["conflicts"] == 1
|
||||
assert execution(sqlite_session_factory).quality == "conflict"
|
||||
|
||||
|
||||
def test_unknown_start_proven_before_t0_removes_pending_execution(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
unknown = provider_event(started_at=None, duration=None)
|
||||
ingest(unknown)
|
||||
assert ingest(provider_event(started_at="2026-09-19T23:59:59Z"))["ignored"] == 1
|
||||
ingest(provider_event(event_id="late-start", kind="created", started_at=None, duration=None))
|
||||
with sqlite_session_factory() as session:
|
||||
assert session.scalar(sa.select(sa.func.count()).select_from(AgentSandboxExecution)) == 0
|
||||
|
||||
|
||||
def test_unusable_provider_data_is_visible_but_not_metered(sqlite_session_factory: sessionmaker[Session]) -> None:
|
||||
event = provider_event(started_at=None)
|
||||
assert ingest(event)["accepted"] == 1
|
||||
with sqlite_session_factory() as session:
|
||||
assert session.scalars(sa.select(AgentSandboxExecution)).one().quality == "pending"
|
||||
row = session.scalars(
|
||||
sa.select(AgentSandboxUsageEvent).where(AgentSandboxUsageEvent.source == "provider")
|
||||
).one()
|
||||
assert row.projection_status == "unresolved"
|
||||
|
||||
|
||||
def test_created_without_execution_data_then_terminal_and_late_start(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
created = provider_event(event_id="created", kind="created", duration=None, started_at=None)
|
||||
created.payload["eventData"] = dict[str, JsonValue]()
|
||||
assert ingest(created)["accepted"] == 1
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.started_at is None
|
||||
assert row.state == "open"
|
||||
assert row.metered_duration_ms is None
|
||||
ingest(provider_event())
|
||||
assert execution(sqlite_session_factory).quality == "metered"
|
||||
assert ingest(created)["duplicates"] == 1
|
||||
late = created.model_copy(deep=True, update={"id": "late"})
|
||||
late.payload["id"] = "late"
|
||||
ingest(late)
|
||||
row = execution(sqlite_session_factory)
|
||||
assert (row.state, row.quality, row.metered_duration_ms) == ("closed", "metered", 12345)
|
||||
|
||||
|
||||
def test_missing_provider_project_is_rejected() -> None:
|
||||
event = provider_event()
|
||||
event.payload.pop("sandboxTeamId")
|
||||
with pytest.raises(SandboxUsageError, match="provider_project_mismatch"):
|
||||
ingest(event)
|
||||
|
||||
|
||||
def test_retention_gap_is_saved_without_advancing_checkpoint(sqlite_session_factory: sessionmaker[Session]) -> None:
|
||||
with config_overrides_context(AGENT_SANDBOX_METERING_START_AT="2026-09-01T00:00:00Z"):
|
||||
event = SandboxUsageEvent(
|
||||
id="gap",
|
||||
source="application",
|
||||
type="collector_retention_gap",
|
||||
timestamp=START,
|
||||
payload={
|
||||
"uncovered_start": "2026-09-01T00:00:00Z",
|
||||
"uncovered_end": "2026-09-13T00:00:00Z",
|
||||
"assumed_retention_seconds": 604800,
|
||||
},
|
||||
)
|
||||
assert ingest(event)["accepted"] == 1
|
||||
assert SandboxUsageService.get_state(project_id=PROJECT)["checkpoint_at"] is None
|
||||
with sqlite_session_factory() as session:
|
||||
row = session.scalars(
|
||||
sa.select(AgentSandboxUsageEvent).where(AgentSandboxUsageEvent.source_event_id == "gap")
|
||||
).one()
|
||||
assert row.projection_status == "unresolved"
|
||||
assert row.projection_error_code == "provider_retention_gap"
|
||||
|
||||
|
||||
def test_checkpoint_only_advances_after_completed_scan() -> None:
|
||||
event = SandboxUsageEvent(
|
||||
id="checkpoint-1",
|
||||
source="application",
|
||||
type="collector_checkpoint",
|
||||
timestamp=START,
|
||||
payload={
|
||||
"scan_started_at": START,
|
||||
"window_start": START,
|
||||
"window_end": START,
|
||||
"completed": True,
|
||||
"mode": "full",
|
||||
"pages": 1,
|
||||
"events": 0,
|
||||
},
|
||||
)
|
||||
ingest(event)
|
||||
state = SandboxUsageService.get_state(project_id=PROJECT)
|
||||
assert state["checkpoint_at"] == START
|
||||
assert state["full_scan_at"] == START
|
||||
with pytest.raises(SandboxUsageError, match="invalid_collector_checkpoint"):
|
||||
ingest(event.model_copy(update={"id": "partial", "payload": {**event.payload, "completed": False}}))
|
||||
|
||||
|
||||
def test_forbidden_project_and_reserved_application_events_fail_without_partial_batch(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
with pytest.raises(SandboxUsageError, match="not_allowed"):
|
||||
SandboxUsageService.ingest(project_id="other-project", events=[provider_event()])
|
||||
reserved = SandboxUsageEvent(id="forged", source="application", type="allocation_registered", payload={})
|
||||
with pytest.raises(SandboxUsageError, match="unsupported_application_event"):
|
||||
ingest(provider_event(), reserved)
|
||||
with sqlite_session_factory() as session:
|
||||
assert session.scalar(sa.select(sa.func.count()).select_from(AgentSandboxExecution)) == 0
|
||||
|
||||
|
||||
def test_provider_team_must_match_configured_project() -> None:
|
||||
event = provider_event()
|
||||
event.payload["sandboxTeamId"] = "other-project"
|
||||
with pytest.raises(SandboxUsageError, match="provider_project_mismatch"):
|
||||
ingest(event)
|
||||
|
||||
|
||||
def test_disabled_ingestion_does_not_ack(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
with config_overrides_context(AGENT_SANDBOX_METERING_ENABLED=False):
|
||||
assert SandboxUsageService.get_state(project_id=PROJECT)["enabled"] is False
|
||||
with pytest.raises(SandboxUsageError, match="disabled"):
|
||||
ingest(provider_event())
|
||||
with sqlite_session_factory() as session:
|
||||
assert session.scalar(sa.select(sa.func.count()).select_from(AgentSandboxUsageEvent)) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("timestamp", "error"),
|
||||
[
|
||||
(123, "invalid_timestamp"),
|
||||
("not-a-time", "invalid_timestamp"),
|
||||
("2026-09-20T00:00:14", "timestamp_requires_timezone"),
|
||||
],
|
||||
)
|
||||
def test_invalid_provider_time_rolls_back_entire_batch(
|
||||
timestamp: JsonValue, error: str, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
bad = provider_event(event_id="bad-time", execution_id="bad-execution")
|
||||
bad.payload["timestamp"] = timestamp
|
||||
with pytest.raises(SandboxUsageError, match=error):
|
||||
ingest(provider_event(), bad)
|
||||
with sqlite_session_factory() as session:
|
||||
assert session.scalar(sa.select(sa.func.count()).select_from(AgentSandboxExecution)) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("quantity", [-1, True, 1.5, 2**63])
|
||||
def test_invalid_duration_is_rejected_before_any_accounting(quantity: JsonValue) -> None:
|
||||
event = provider_event()
|
||||
data = event.payload["eventData"]
|
||||
assert isinstance(data, dict)
|
||||
details = data["execution"]
|
||||
assert isinstance(details, dict)
|
||||
details["execution_time"] = quantity
|
||||
with pytest.raises(SandboxUsageError, match="invalid_provider_quantity"):
|
||||
ingest(event)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["id", "sandboxId", "sandboxExecutionId"])
|
||||
def test_raw_identity_cannot_disagree_with_delivery_envelope(field: str) -> None:
|
||||
event = provider_event()
|
||||
event.payload[field] = "different-id"
|
||||
with pytest.raises(SandboxUsageError, match="provider_envelope_mismatch"):
|
||||
ingest(event)
|
||||
|
||||
|
||||
def test_invalid_provider_identifier_without_envelope_hint_is_rejected() -> None:
|
||||
event = provider_event().model_copy(update={"sandbox_id": None})
|
||||
event.payload["sandboxId"] = ""
|
||||
with pytest.raises(SandboxUsageError, match="invalid_provider_identifier"):
|
||||
ingest(event)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("configured_start", "error"),
|
||||
[
|
||||
("invalid", "sandbox_metering_start_not_configured"),
|
||||
("2026-09-20T00:00:00.001Z", "sandbox_metering_start_requires_whole_second"),
|
||||
],
|
||||
)
|
||||
def test_invalid_activation_configuration_cannot_create_ledger_scope(configured_start: str, error: str) -> None:
|
||||
with config_overrides_context(AGENT_SANDBOX_METERING_START_AT=configured_start):
|
||||
with pytest.raises(SandboxUsageError, match=error) as result:
|
||||
SandboxUsageService.get_state(project_id=PROJECT)
|
||||
assert result.value.status_code == 503
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("key", "value"),
|
||||
[
|
||||
("dify.usage_allocation_id", 42),
|
||||
("dify.usage_allocation_id", "invalid-uuid"),
|
||||
("dify.binding_id", 42),
|
||||
("dify.binding_id", "invalid-uuid"),
|
||||
],
|
||||
)
|
||||
def test_invalid_owner_metadata_does_not_discard_metered_usage(
|
||||
key: str, value: JsonValue, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
assert ingest(provider_event(metadata={key: value}))["accepted"] == 1
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.quality == "metered"
|
||||
assert row.metered_duration_ms == 12345
|
||||
assert row.tenant_id is None
|
||||
assert row.attribution_status == "unresolved"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["sandbox", "started_at", "resources"])
|
||||
def test_execution_identity_and_resource_conflicts_preserve_original_usage(
|
||||
change: str, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
ingest(provider_event())
|
||||
different = provider_event(event_id="conflicting-terminal")
|
||||
if change == "sandbox":
|
||||
different = provider_event(event_id="conflicting-terminal", sandbox_id="other-sandbox")
|
||||
elif change == "started_at":
|
||||
different = provider_event(event_id="conflicting-terminal", started_at="2026-09-20T00:00:03Z")
|
||||
else:
|
||||
data = different.payload["eventData"]
|
||||
assert isinstance(data, dict)
|
||||
details = data["execution"]
|
||||
assert isinstance(details, dict)
|
||||
details["vcpu_count"] = 4
|
||||
assert ingest(different)["conflicts"] == 1
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.quality == "conflict"
|
||||
assert row.sandbox_id == "sandbox-1"
|
||||
assert row.vcpu_count == 2
|
||||
assert row.metered_duration_ms == 12345
|
||||
|
||||
|
||||
def test_unsupported_provider_contract_is_visible_without_fabricated_execution(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
event = provider_event()
|
||||
event.payload["version"] = "unsupported"
|
||||
assert ingest(event)["accepted"] == 1
|
||||
with sqlite_session_factory() as session:
|
||||
assert session.scalar(sa.select(sa.func.count()).select_from(AgentSandboxExecution)) == 0
|
||||
row = session.scalars(
|
||||
sa.select(AgentSandboxUsageEvent).where(AgentSandboxUsageEvent.source_event_id == event.id)
|
||||
).one()
|
||||
assert row.projection_status == "unresolved"
|
||||
assert row.projection_error_code == "incomplete_provider_execution"
|
||||
|
||||
|
||||
def business_owner(
|
||||
session: Session,
|
||||
*,
|
||||
binding_id: str | None = None,
|
||||
tenant_id: str | None = None,
|
||||
sandbox_id: str = "sandbox-1",
|
||||
) -> AgentWorkspaceBinding:
|
||||
tenant_id = tenant_id or str(uuid4())
|
||||
app_id, agent_id, workspace_id = (str(uuid4()) for _ in range(3))
|
||||
session.add_all(
|
||||
[
|
||||
App(
|
||||
id=app_id,
|
||||
tenant_id=tenant_id,
|
||||
name="Metering test",
|
||||
description="",
|
||||
mode=AppMode.AGENT,
|
||||
enable_site=False,
|
||||
enable_api=False,
|
||||
max_active_requests=None,
|
||||
),
|
||||
Agent(
|
||||
id=agent_id, tenant_id=tenant_id, name=str(uuid4()), scope=AgentScope.ROSTER, source=AgentSource.ROSTER
|
||||
),
|
||||
AgentWorkspace(
|
||||
id=workspace_id,
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
owner_type=AgentWorkspaceOwnerType.CONVERSATION,
|
||||
owner_id=str(uuid4()),
|
||||
owner_scope_key="root",
|
||||
backend_workspace_ref=sandbox_id,
|
||||
),
|
||||
]
|
||||
)
|
||||
binding = AgentWorkspaceBinding(
|
||||
id=binding_id or str(uuid4()),
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
agent_id=agent_id,
|
||||
workspace_id=workspace_id,
|
||||
agent_config_version_id=str(uuid4()),
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
backend_binding_ref=sandbox_id,
|
||||
)
|
||||
session.add(binding)
|
||||
session.commit()
|
||||
return binding
|
||||
|
||||
|
||||
def owner_metadata(binding: AgentWorkspaceBinding) -> dict[str, JsonValue]:
|
||||
return {
|
||||
"dify.binding_id": binding.id,
|
||||
"dify.tenant_id": binding.tenant_id,
|
||||
"dify.agent_id": binding.agent_id,
|
||||
"dify.workspace_id": binding.workspace_id,
|
||||
}
|
||||
|
||||
|
||||
def test_provider_usage_without_business_rows_remains_metered(sqlite_session_factory: sessionmaker[Session]) -> None:
|
||||
ingest(provider_event(metadata={"dify.binding_id": str(uuid4()), "dify.tenant_id": str(uuid4())}))
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.quality == "metered"
|
||||
assert row.metered_duration_ms == 12345
|
||||
assert row.attribution_status == "unresolved"
|
||||
assert row.tenant_id is None
|
||||
assert row.allocation_id is None
|
||||
|
||||
|
||||
def test_background_attribution_uses_verified_business_chain(
|
||||
sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
binding = business_owner(sqlite_session)
|
||||
ingest(provider_event(metadata=owner_metadata(binding)))
|
||||
row = execution(sqlite_session_factory)
|
||||
assert (row.tenant_id, row.app_id, row.agent_id, row.binding_id, row.workspace_id) == (
|
||||
binding.tenant_id,
|
||||
binding.app_id,
|
||||
binding.agent_id,
|
||||
binding.id,
|
||||
binding.workspace_id,
|
||||
)
|
||||
assert row.attribution_status == "resolved"
|
||||
assert row.allocation_id is None
|
||||
with sqlite_session_factory() as session:
|
||||
assert (
|
||||
session.scalar(
|
||||
sa.select(sa.func.count())
|
||||
.select_from(AgentSandboxUsageEvent)
|
||||
.where(AgentSandboxUsageEvent.event_type == "allocation_registered")
|
||||
)
|
||||
== 0
|
||||
)
|
||||
|
||||
|
||||
def test_duplicate_provider_replay_can_resolve_business_rows_committed_later(
|
||||
sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
binding_id, tenant_id = str(uuid4()), str(uuid4())
|
||||
event = provider_event(metadata={"dify.binding_id": binding_id, "dify.tenant_id": tenant_id})
|
||||
ingest(event)
|
||||
assert execution(sqlite_session_factory).attribution_status == "unresolved"
|
||||
binding = business_owner(sqlite_session, binding_id=binding_id, tenant_id=tenant_id)
|
||||
assert ingest(event)["duplicates"] == 1
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.binding_id == binding.id
|
||||
assert row.attribution_status == "resolved"
|
||||
assert row.metered_duration_ms == 12345
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", ["binding", "workspace", "app", "agent"])
|
||||
def test_deleted_business_rows_do_not_erase_retained_owner_or_usage(
|
||||
missing: str, sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
binding = business_owner(sqlite_session)
|
||||
event = provider_event(metadata=owner_metadata(binding))
|
||||
ingest(event)
|
||||
if missing == "binding":
|
||||
sqlite_session.delete(binding)
|
||||
elif missing == "workspace":
|
||||
sqlite_session.execute(sa.delete(AgentWorkspace).where(AgentWorkspace.id == binding.workspace_id))
|
||||
elif missing == "app":
|
||||
sqlite_session.execute(sa.delete(App).where(App.id == binding.app_id))
|
||||
else:
|
||||
sqlite_session.execute(sa.delete(Agent).where(Agent.id == binding.agent_id))
|
||||
sqlite_session.commit()
|
||||
assert ingest(event)["duplicates"] == 1
|
||||
row = execution(sqlite_session_factory)
|
||||
assert (row.binding_id, row.tenant_id) == (binding.id, binding.tenant_id)
|
||||
assert row.attribution_status == "resolved"
|
||||
assert row.metered_duration_ms == 12345
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"broken_link",
|
||||
[
|
||||
"tenant_metadata",
|
||||
"agent_metadata",
|
||||
"workspace_metadata",
|
||||
"binding_sandbox",
|
||||
"workspace_sandbox",
|
||||
"app_tenant",
|
||||
"agent_tenant",
|
||||
],
|
||||
)
|
||||
def test_unverified_business_chain_never_guesses_an_owner(
|
||||
broken_link: str, sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
binding = business_owner(sqlite_session)
|
||||
metadata = owner_metadata(binding)
|
||||
if broken_link == "tenant_metadata":
|
||||
metadata["dify.tenant_id"] = str(uuid4())
|
||||
elif broken_link in {"agent_metadata", "workspace_metadata"}:
|
||||
metadata[f"dify.{broken_link.removesuffix('_metadata')}_id"] = str(uuid4())
|
||||
elif broken_link == "binding_sandbox":
|
||||
binding.backend_binding_ref = "different-sandbox"
|
||||
elif broken_link == "workspace_sandbox":
|
||||
sqlite_session.execute(
|
||||
sa.update(AgentWorkspace)
|
||||
.where(AgentWorkspace.id == binding.workspace_id)
|
||||
.values(backend_workspace_ref="different-sandbox")
|
||||
)
|
||||
elif broken_link == "app_tenant":
|
||||
sqlite_session.execute(sa.update(App).where(App.id == binding.app_id).values(tenant_id=str(uuid4())))
|
||||
else:
|
||||
sqlite_session.execute(sa.update(Agent).where(Agent.id == binding.agent_id).values(tenant_id=str(uuid4())))
|
||||
sqlite_session.commit()
|
||||
ingest(provider_event(metadata=metadata))
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.quality == "metered"
|
||||
assert row.tenant_id is None
|
||||
assert row.attribution_status == "unresolved"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_value", [None, 42, "invalid-uuid"])
|
||||
def test_bad_attribution_labels_do_not_invalidate_measured_runtime(
|
||||
bad_value: JsonValue, sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
binding = business_owner(sqlite_session)
|
||||
ingest(provider_event(metadata=owner_metadata(binding)))
|
||||
changed = owner_metadata(binding)
|
||||
changed["dify.tenant_id"] = bad_value
|
||||
assert ingest(provider_event(metadata=changed))["accepted"] == 1
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.quality == "metered"
|
||||
assert row.attribution_status == "resolved"
|
||||
assert row.tenant_id == binding.tenant_id
|
||||
assert row.metered_duration_ms == 12345
|
||||
|
||||
|
||||
def test_owner_conflict_does_not_reassign_history_or_discard_project_usage(
|
||||
sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
first, second = business_owner(sqlite_session), business_owner(sqlite_session)
|
||||
ingest(provider_event(metadata=owner_metadata(first)))
|
||||
ingest(provider_event(event_id="other-owner", metadata=owner_metadata(second)))
|
||||
row = execution(sqlite_session_factory)
|
||||
assert row.attribution_status == "conflict"
|
||||
assert row.binding_id == first.id
|
||||
assert row.tenant_id == first.tenant_id
|
||||
assert row.quality == "metered"
|
||||
assert row.metered_duration_ms == 12345
|
||||
|
||||
|
||||
def test_same_sandbox_cannot_change_owner_across_executions(
|
||||
sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
first, second = business_owner(sqlite_session), business_owner(sqlite_session)
|
||||
ingest(provider_event(metadata=owner_metadata(first)))
|
||||
resumed = provider_event(event_id="new-execution", execution_id="execution-2", metadata=owner_metadata(second))
|
||||
ingest(resumed)
|
||||
# A subsequent replay with the original owner cannot erase the conflicting
|
||||
# association. Both physical executions remain counted at project level.
|
||||
ingest(provider_event(event_id="later-event", execution_id="execution-2", metadata=owner_metadata(first)))
|
||||
with sqlite_session_factory() as session:
|
||||
rows = list(
|
||||
session.scalars(sa.select(AgentSandboxExecution).order_by(AgentSandboxExecution.provider_execution_id))
|
||||
)
|
||||
assert [(row.attribution_status, row.binding_id) for row in rows] == [
|
||||
("resolved", first.id),
|
||||
("conflict", None),
|
||||
]
|
||||
assert [row.quality for row in rows] == ["metered", "metered"]
|
||||
assert sum(row.metered_duration_ms or 0 for row in rows) == 24690
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event_type", ["operation_requested", "operation_observed", "allocation_registered"])
|
||||
def test_application_operations_are_no_longer_accepted(event_type: str) -> None:
|
||||
event = SandboxUsageEvent(id="legacy-operation", source="application", type=event_type, payload={})
|
||||
with pytest.raises(SandboxUsageError, match="unsupported_application_event"):
|
||||
ingest(event)
|
||||
|
||||
|
||||
def test_steady_state_lookup_only_selects_without_locking_activation(sqlite_session: Session) -> None:
|
||||
engine = sqlite_session.get_bind()
|
||||
assert isinstance(engine, Engine)
|
||||
initial = SandboxUsageService.get_state(project_id=PROJECT)
|
||||
statements: list[str] = []
|
||||
|
||||
def observe(_connection: Connection, statement: ClauseElement, *_args: object) -> None:
|
||||
statements.append(str(statement.compile(dialect=postgresql.dialect())))
|
||||
|
||||
sqlalchemy_event.listen(engine, "before_execute", observe)
|
||||
try:
|
||||
assert SandboxUsageService.get_state(project_id=PROJECT) == initial
|
||||
finally:
|
||||
sqlalchemy_event.remove(engine, "before_execute", observe)
|
||||
assert statements
|
||||
assert all(statement.lstrip().startswith("SELECT") for statement in statements)
|
||||
assert all("FOR UPDATE" not in statement for statement in statements)
|
||||
@@ -0,0 +1,336 @@
|
||||
"""Unit tests for the Skill package validator/normalizer (ENG-370)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
import pytest
|
||||
|
||||
from services.agent.skill_package_service import NormalizedSkillPackage, SkillPackageError, SkillPackageService
|
||||
from tests.helpers.unit.config_override import apply_config_overrides
|
||||
|
||||
_SKILL_MD = """---
|
||||
name: pdf-toolkit
|
||||
description: Tools for working with PDF files.
|
||||
---
|
||||
|
||||
# PDF Toolkit
|
||||
|
||||
Do things with PDFs.
|
||||
"""
|
||||
|
||||
|
||||
def _zip(members: dict[str, bytes], *, compression: int = zipfile.ZIP_DEFLATED) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", compression=compression) as archive:
|
||||
for name, data in members.items():
|
||||
archive.writestr(name, data)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _normalize(members: dict[str, bytes], *, filename: str = "skill.zip") -> NormalizedSkillPackage:
|
||||
return SkillPackageService().validate_and_normalize(content=_zip(members), filename=filename)
|
||||
|
||||
|
||||
def test_normalize_replaces_invalid_utf8_member_names() -> None:
|
||||
original = _zip(
|
||||
{
|
||||
"SKILL.md": _SKILL_MD.encode(),
|
||||
"scripts/\u00e9.py": b"print('keep payload')\n",
|
||||
"assets/\u00f6.txt": b"valid unicode name",
|
||||
"assets/X.txt": b"legacy encoded name",
|
||||
}
|
||||
)
|
||||
damaged = original.replace(b"\xc3\xa9.py", b"\xffa.py").replace(b"assets/X.txt", b"assets/\x82.txt")
|
||||
service = SkillPackageService()
|
||||
assert service.inspect(content=damaged, filename="skill.zip").name == "pdf-toolkit"
|
||||
normalized = service.validate_and_normalize(content=damaged, filename="skill.zip")
|
||||
with zipfile.ZipFile(io.BytesIO(normalized.archive_bytes)) as archive:
|
||||
assert archive.read("scripts/\ufffda.py") == b"print('keep payload')\n"
|
||||
assert archive.read("assets/\u00f6.txt") == b"valid unicode name"
|
||||
assert archive.read("assets/\u00e9.txt") == b"legacy encoded name"
|
||||
assert archive.testzip() is None
|
||||
|
||||
|
||||
def test_normalize_recovers_zip64_skill_names(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
with monkeypatch.context() as scoped:
|
||||
scoped.setattr(zipfile, "ZIP64_LIMIT", 0)
|
||||
original = _zip({"SKILL.md": _SKILL_MD.encode(), "scripts/\u00e9.py": b"print('ok')\n"})
|
||||
damaged = original.replace(b"\xc3\xa9.py", b"\xffa.py")
|
||||
service = SkillPackageService()
|
||||
assert service.inspect(content=damaged, filename="skill.zip").name == "pdf-toolkit"
|
||||
normalized = service.validate_and_normalize(content=damaged, filename="skill.zip")
|
||||
with zipfile.ZipFile(io.BytesIO(normalized.archive_bytes)) as archive:
|
||||
assert archive.read("scripts/\ufffda.py") == b"print('ok')\n"
|
||||
|
||||
|
||||
def test_replacement_member_names_must_remain_unique() -> None:
|
||||
original = _zip(
|
||||
{
|
||||
"SKILL.md": _SKILL_MD.encode(),
|
||||
"scripts/\u00e9.py": b"one",
|
||||
"scripts/\u00f6.py": b"two",
|
||||
}
|
||||
)
|
||||
damaged = original.replace(b"\xc3\xa9.py", b"\xffa.py").replace(b"\xc3\xb6.py", b"\xfea.py")
|
||||
with pytest.raises(SkillPackageError) as error:
|
||||
SkillPackageService().validate_and_normalize(content=damaged, filename="skill.zip")
|
||||
assert error.value.code == "duplicate_member_path"
|
||||
|
||||
|
||||
def test_replacement_names_do_not_hide_local_header_mismatch() -> None:
|
||||
original = _zip({"SKILL.md": _SKILL_MD.encode(), "\u00e9.py": b"payload"})
|
||||
# Damage only the central name, leaving the local header unchanged.
|
||||
central = original.index(b"PK\x01\x02")
|
||||
damaged = original[:central] + original[central:].replace(b"\xc3\xa9.py", b"\xffa.py")
|
||||
with pytest.raises(SkillPackageError) as error:
|
||||
SkillPackageService().validate_and_normalize(content=damaged, filename="skill.zip")
|
||||
assert error.value.code == "invalid_archive"
|
||||
|
||||
|
||||
def test_normalized_highly_compressible_skill_passes_reinspection() -> None:
|
||||
payload = b"x" * (1024 * 1024)
|
||||
content = _zip({"SKILL.md": _SKILL_MD.encode(), "data.bin": payload}, compression=zipfile.ZIP_STORED)
|
||||
service = SkillPackageService()
|
||||
normalized = service.validate_and_normalize(content=content, filename="skill.zip")
|
||||
inspection = service.inspect(content=normalized.archive_bytes, filename="skill.zip")
|
||||
assert inspection.name == normalized.manifest.name
|
||||
with zipfile.ZipFile(io.BytesIO(normalized.archive_bytes)) as archive:
|
||||
assert archive.getinfo("data.bin").compress_type == zipfile.ZIP_DEFLATED
|
||||
assert archive.read("data.bin") == payload
|
||||
|
||||
|
||||
def test_inspect_reports_uncompressed_size_without_rebuilding(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
members = {"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('hi')\n"}
|
||||
|
||||
def fail_if_called(*_args: object, **_kwargs: object) -> bytes:
|
||||
raise AssertionError("inspection must not rebuild the archive")
|
||||
|
||||
monkeypatch.setattr(SkillPackageService, "_build_normalized_archive", fail_if_called)
|
||||
|
||||
inspection = SkillPackageService().inspect(content=_zip(members), filename="skill.zip")
|
||||
|
||||
assert inspection.name == "pdf-toolkit"
|
||||
assert inspection.uncompressed_size == sum(len(content) for content in members.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefix", ["", "pdf-toolkit/"])
|
||||
@pytest.mark.parametrize("crlf", [False, True])
|
||||
def test_inspection_and_normalization_keep_distinct_size_meanings(prefix: str, crlf: bool) -> None:
|
||||
skill_md = _SKILL_MD.replace("\n", "\r\n") if crlf else _SKILL_MD
|
||||
script = b"print('hi')\n"
|
||||
members = {f"{prefix}SKILL.md": skill_md.encode(), f"{prefix}scripts/run.py": script}
|
||||
if prefix:
|
||||
members["README.md"] = b"ignored outside the selected root"
|
||||
content = _zip(members)
|
||||
service = SkillPackageService()
|
||||
inspection = service.inspect(content=content, filename="skill.zip")
|
||||
normalized = service.validate_and_normalize(content=content, filename="skill.zip")
|
||||
assert inspection.uncompressed_size == sum(len(value) for value in members.values())
|
||||
expected_size = len(_SKILL_MD.encode()) + len(script)
|
||||
assert normalized.manifest.size == expected_size
|
||||
assert normalized.manifest.name == "pdf-toolkit"
|
||||
assert normalized.manifest.description == "Tools for working with PDF files."
|
||||
with zipfile.ZipFile(io.BytesIO(normalized.archive_bytes)) as archive:
|
||||
assert sum(info.file_size for info in archive.infolist()) == expected_size
|
||||
assert archive.read("SKILL.md") == _SKILL_MD.encode()
|
||||
if prefix or crlf:
|
||||
assert inspection.uncompressed_size > normalized.manifest.size
|
||||
|
||||
|
||||
def test_shallowest_skill_md_preferred_during_normalization() -> None:
|
||||
manifest = _normalize({"SKILL.md": _SKILL_MD.encode(), "nested/SKILL.md": _SKILL_MD.encode()}).manifest
|
||||
assert manifest.entry_path == "SKILL.md"
|
||||
assert manifest.files == ["SKILL.md", "nested/SKILL.md"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("prefix", "extra_members"),
|
||||
[
|
||||
pytest.param("", {}, id="root"),
|
||||
pytest.param("pdf-toolkit/", {}, id="single-folder"),
|
||||
pytest.param("pdf-toolkit/", {"README.md": b"bundle notes\n"}, id="root-outsider"),
|
||||
pytest.param("pdf-toolkit/", {".": b"x"}, id="dot-outsider"),
|
||||
pytest.param("pdf-toolkit/", {"bundle/other.txt": b"x"}, id="nested-outsider"),
|
||||
pytest.param("bundle/pdf-toolkit/", {}, id="deep-root"),
|
||||
],
|
||||
)
|
||||
def test_normalization_preserves_selected_skill_contents(prefix: str, extra_members: dict[str, bytes]) -> None:
|
||||
expected = {"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('hi')\n"}
|
||||
original = _zip({**{prefix + path: content for path, content in expected.items()}, **extra_members})
|
||||
package = SkillPackageService().validate_and_normalize(content=original, filename="skill.zip")
|
||||
|
||||
assert package.manifest.name == "pdf-toolkit"
|
||||
assert package.manifest.description == "Tools for working with PDF files."
|
||||
assert package.manifest.size == sum(len(content) for content in expected.values())
|
||||
assert package.manifest.entry_path == "SKILL.md"
|
||||
assert package.manifest.files == sorted(expected)
|
||||
with zipfile.ZipFile(io.BytesIO(package.archive_bytes)) as archive:
|
||||
assert archive.namelist() == sorted(expected)
|
||||
assert {path: archive.read(path) for path in archive.namelist()} == expected
|
||||
assert package.manifest.hash == hashlib.sha256(package.archive_bytes).hexdigest()
|
||||
if prefix:
|
||||
assert package.manifest.hash != hashlib.sha256(original).hexdigest()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("members", "filename", "code"),
|
||||
[
|
||||
({"README.md": b"x"}, "skill.zip", "missing_skill_md"),
|
||||
({"SKILL.md": _SKILL_MD.encode(), ".": b"x"}, "skill.zip", "unsafe_path"),
|
||||
({"SKILL.md": _SKILL_MD.encode()}, "skill.tar", "unsupported_extension"),
|
||||
({"SKILL.md": b""}, "skill.zip", "empty_skill_md"),
|
||||
({"SKILL.md": b"---\ndescription: valid\n---\n# no name here"}, "skill.zip", "missing_skill_name"),
|
||||
({"SKILL.md": b"---\nname: pdf-toolkit\n---\n# no description"}, "skill.zip", "missing_skill_description"),
|
||||
(
|
||||
{"SKILL.md": b"---\nname: PDF Toolkit\ndescription: valid\n---\n# invalid name"},
|
||||
"skill.zip",
|
||||
"invalid_skill_name",
|
||||
),
|
||||
(
|
||||
{"SKILL.md": f"---\nname: pdf-toolkit\ndescription: {'x' * 1025}\n---\n# long".encode()},
|
||||
"skill.zip",
|
||||
"invalid_skill_description",
|
||||
),
|
||||
({"SKILL.md": b"\xff\xfenot utf8"}, "skill.zip", "skill_md_not_utf8"),
|
||||
pytest.param({"SKILL.md": b"# heading-name\n\nbody"}, "skill.zip", "missing_skill_name", id="no-frontmatter"),
|
||||
pytest.param(
|
||||
{
|
||||
"pdf-toolkit/SKILL.md": _SKILL_MD.encode(),
|
||||
"pdf-toolkit/scripts/run.py": b"print('hi')\n",
|
||||
"other-tool/SKILL.md": _SKILL_MD.encode(),
|
||||
},
|
||||
"skill.zip",
|
||||
"files_outside_skill_root",
|
||||
id="multiple-skill-roots",
|
||||
),
|
||||
pytest.param({"../evil.txt": b"x", "SKILL.md": _SKILL_MD.encode()}, "skill.zip", "unsafe_path", id="zip-slip"),
|
||||
pytest.param(
|
||||
{"SKILL.md": b"---\n: : : not yaml\n---\n# x\n"},
|
||||
"skill.zip",
|
||||
"invalid_frontmatter",
|
||||
id="invalid-frontmatter",
|
||||
),
|
||||
pytest.param(
|
||||
{"SKILL.md": b"---\n# heading-wins\nbody"}, "skill.zip", "missing_skill_name", id="unterminated-frontmatter"
|
||||
),
|
||||
pytest.param(
|
||||
{"bundle/pdf-toolkit/SKILL.md": _SKILL_MD.encode(), "README.md": b"x"},
|
||||
"skill.zip",
|
||||
"files_outside_skill_root",
|
||||
id="outside-deep-root",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"pdf-toolkit/SKILL.md": _SKILL_MD.encode(),
|
||||
"pdf-toolkit/scripts/run.py": b"print('x')\n",
|
||||
"pdf-toolkit/scripts/./run.py": b"print('y')\n",
|
||||
},
|
||||
"skill.zip",
|
||||
"duplicate_member_path",
|
||||
id="duplicate-normalized-path",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_invalid_packages_rejected(members: dict[str, bytes], filename: str, code: str) -> None:
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
_normalize(members, filename=filename)
|
||||
assert exc_info.value.code == code
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"description_line",
|
||||
[
|
||||
'description: "Compare before---after reports."',
|
||||
"description: Compare before---after reports.",
|
||||
],
|
||||
)
|
||||
def test_description_keeps_literal_dashes_inside_frontmatter(description_line: str) -> None:
|
||||
skill_md = f"---\nname: toolkit\n{description_line}\n---\n# Instructions\nCompare reports.\n"
|
||||
package = _normalize({"SKILL.md": skill_md.encode()})
|
||||
assert package.manifest.name == "toolkit"
|
||||
assert package.manifest.description == "Compare before---after reports."
|
||||
|
||||
|
||||
def test_opening_delimiter_with_trailing_text_is_not_frontmatter() -> None:
|
||||
skill_md = b"---junk\nname: toolkit\ndescription: valid\n---\n# body\n"
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
_normalize({"SKILL.md": skill_md})
|
||||
assert exc_info.value.code == "missing_skill_name"
|
||||
|
||||
|
||||
def test_non_zip_content_rejected() -> None:
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
SkillPackageService().validate_and_normalize(content=b"not a zip", filename="skill.zip")
|
||||
assert exc_info.value.code == "invalid_archive"
|
||||
|
||||
|
||||
def test_empty_archive_rejected() -> None:
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
SkillPackageService().validate_and_normalize(content=b"", filename="skill.zip")
|
||||
assert exc_info.value.code == "empty_archive"
|
||||
|
||||
|
||||
def test_validate_and_normalize_rejects_skill_md_too_large(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
apply_config_overrides(monkeypatch, SKILL_PACKAGE_MAX_SKILL_MD_BYTES=8)
|
||||
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
_normalize({"SKILL.md": _SKILL_MD.encode()})
|
||||
assert exc_info.value.code == "skill_md_too_large"
|
||||
|
||||
|
||||
def test_validate_and_normalize_rejects_too_many_entries(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
apply_config_overrides(monkeypatch, SKILL_PACKAGE_MAX_ENTRIES=1)
|
||||
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
_normalize({"SKILL.md": _SKILL_MD.encode(), "assets/": b""})
|
||||
assert exc_info.value.code == "too_many_entries"
|
||||
|
||||
|
||||
def test_validate_and_normalize_rejects_archive_too_large_uncompressed(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
apply_config_overrides(monkeypatch, SKILL_PACKAGE_MAX_UNCOMPRESSED_BYTES=32)
|
||||
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
_normalize({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"x" * 33})
|
||||
assert exc_info.value.code == "archive_too_large"
|
||||
|
||||
|
||||
def test_validate_and_normalize_rejects_archive_too_large_uploaded_bytes(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
apply_config_overrides(monkeypatch, UPLOAD_SKILL_FILE_SIZE_LIMIT=1)
|
||||
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
SkillPackageService().validate_and_normalize(content=b"x" * (1024 * 1024 + 1), filename="skill.zip")
|
||||
assert exc_info.value.code == "archive_too_large"
|
||||
|
||||
|
||||
def test_high_compression_ratio_uses_absolute_expansion_limit(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
content = _zip({"SKILL.md": _SKILL_MD.encode(), "data.bin": b"x" * (1024 * 1024)})
|
||||
service = SkillPackageService()
|
||||
assert service.inspect(content=content, filename="skill.zip").name == "pdf-toolkit"
|
||||
apply_config_overrides(monkeypatch, SKILL_PACKAGE_MAX_UNCOMPRESSED_BYTES=1024)
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
service.inspect(content=content, filename="skill.zip")
|
||||
assert exc_info.value.code == "archive_too_large"
|
||||
|
||||
|
||||
def test_validate_and_normalize_maps_member_decompression_failures_to_invalid_archive(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
original_read = zipfile.ZipFile.read
|
||||
|
||||
def corrupted_read(self: zipfile.ZipFile, member: str | zipfile.ZipInfo, pwd: bytes | None = None) -> bytes:
|
||||
filename = member.filename if isinstance(member, zipfile.ZipInfo) else member
|
||||
if filename == "scripts/run.py":
|
||||
raise zlib.error("invalid distance too far back")
|
||||
return original_read(self, member, pwd=pwd)
|
||||
|
||||
monkeypatch.setattr(zipfile.ZipFile, "read", corrupted_read)
|
||||
|
||||
with pytest.raises(SkillPackageError) as exc_info:
|
||||
_normalize({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('x')\n"})
|
||||
assert exc_info.value.code == "invalid_archive"
|
||||
assert exc_info.value.message == "skill archive is not a valid zip"
|
||||
@@ -0,0 +1,612 @@
|
||||
from unittest.mock import ANY, Mock
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.agent import (
|
||||
Agent,
|
||||
AgentConfigSnapshot,
|
||||
AgentScope,
|
||||
AgentSource,
|
||||
AgentStatus,
|
||||
WorkflowAgentBindingType,
|
||||
WorkflowAgentNodeBinding,
|
||||
)
|
||||
from models.agent_config_entities import AgentSoulConfig
|
||||
from models.enums import AppStatus
|
||||
from models.model import App, AppMode
|
||||
from models.workflow import Workflow
|
||||
from services.agent.dsl_service import AgentDslService
|
||||
from services.agent.workflow_publish_service import WorkflowAgentPublishService
|
||||
from tests.helpers.unit.model_factories import make_workflow
|
||||
|
||||
|
||||
def _workflow(*, workflow_id: str = "workflow-1", version: str = Workflow.VERSION_DRAFT) -> Workflow:
|
||||
return make_workflow(workflow_id=workflow_id, version=version)
|
||||
|
||||
|
||||
def _inline_agent(
|
||||
*,
|
||||
agent_id: str,
|
||||
workflow_id: str,
|
||||
node_id: str,
|
||||
tenant_id: str = "tenant-1",
|
||||
) -> Agent:
|
||||
return Agent(
|
||||
id=agent_id,
|
||||
tenant_id=tenant_id,
|
||||
name=f"Inline {agent_id}",
|
||||
scope=AgentScope.WORKFLOW_ONLY,
|
||||
source=AgentSource.WORKFLOW,
|
||||
status=AgentStatus.ACTIVE,
|
||||
app_id="app-1",
|
||||
workflow_id=workflow_id,
|
||||
workflow_node_id=node_id,
|
||||
)
|
||||
|
||||
|
||||
def _snapshot(*, snapshot_id: str, agent_id: str, version: int = 1) -> AgentConfigSnapshot:
|
||||
return AgentConfigSnapshot(
|
||||
id=snapshot_id,
|
||||
tenant_id="tenant-1",
|
||||
agent_id=agent_id,
|
||||
version=version,
|
||||
config_snapshot=AgentSoulConfig(),
|
||||
)
|
||||
|
||||
|
||||
def test_inline_binding_from_another_node_is_cloned(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
|
||||
source_agent = _inline_agent(agent_id="source-agent", workflow_id="workflow-1", node_id="source-node")
|
||||
source_snapshot = _snapshot(snapshot_id="source-snapshot", agent_id=source_agent.id)
|
||||
sqlite_session.add_all([source_agent, source_snapshot])
|
||||
sqlite_session.commit()
|
||||
target_agent = _inline_agent(agent_id="target-agent", workflow_id="workflow-1", node_id="pasted-node")
|
||||
target_snapshot = _snapshot(snapshot_id="target-snapshot", agent_id=target_agent.id)
|
||||
clone = Mock(return_value=(target_agent, target_snapshot))
|
||||
monkeypatch.setattr(AgentDslService, "clone_inline_binding_for_node", clone)
|
||||
|
||||
WorkflowAgentPublishService._sync_agent_binding_for_node(
|
||||
session=sqlite_session,
|
||||
draft_workflow=_workflow(),
|
||||
node_id="pasted-node",
|
||||
node_data={"agent_task": "Summarize the input"},
|
||||
node_binding={
|
||||
"binding_type": WorkflowAgentBindingType.INLINE_AGENT.value,
|
||||
"agent_id": source_agent.id,
|
||||
"current_snapshot_id": source_snapshot.id,
|
||||
},
|
||||
existing_binding=None,
|
||||
account_id="account-1",
|
||||
)
|
||||
sqlite_session.flush()
|
||||
|
||||
clone.assert_called_once()
|
||||
binding = sqlite_session.scalar(
|
||||
select(WorkflowAgentNodeBinding).where(WorkflowAgentNodeBinding.node_id == "pasted-node")
|
||||
)
|
||||
assert binding is not None
|
||||
assert binding.agent_id == "target-agent"
|
||||
assert binding.current_snapshot_id == "target-snapshot"
|
||||
assert binding.node_job_config.workflow_prompt == "Summarize the input"
|
||||
|
||||
|
||||
def test_draft_sync_resolves_roster_agents(sqlite_session: Session) -> None:
|
||||
draft_workflow = _workflow()
|
||||
draft_workflow.graph = (
|
||||
'{"nodes":['
|
||||
'{"id":"node-b","data":{"type":"agent","version":"2","agent_node_kind":"dify_agent",'
|
||||
'"agent_binding":{"binding_type":"roster_agent","agent_id":"agent-b"}}},'
|
||||
'{"id":"node-a","data":{"type":"agent","version":"2","agent_node_kind":"dify_agent",'
|
||||
'"agent_binding":{"binding_type":"roster_agent","agent_id":"agent-a"}}}'
|
||||
'],"edges":[]}'
|
||||
)
|
||||
roster_agents: list[Agent] = []
|
||||
roster_snapshots: list[AgentConfigSnapshot] = []
|
||||
for agent_id in ("agent-a", "agent-b"):
|
||||
roster_agents.append(
|
||||
Agent(
|
||||
id=agent_id,
|
||||
tenant_id="tenant-1",
|
||||
name=f"Roster {agent_id}",
|
||||
scope=AgentScope.ROSTER,
|
||||
source=AgentSource.ROSTER,
|
||||
status=AgentStatus.ACTIVE,
|
||||
active_config_snapshot_id=f"{agent_id}-snapshot",
|
||||
)
|
||||
)
|
||||
roster_snapshots.append(_snapshot(snapshot_id=f"{agent_id}-snapshot", agent_id=agent_id))
|
||||
sqlite_session.add_all([*roster_agents, *roster_snapshots])
|
||||
sqlite_session.commit()
|
||||
|
||||
retirement_candidates = WorkflowAgentPublishService.sync_agent_bindings_for_draft(
|
||||
session=sqlite_session,
|
||||
draft_workflow=draft_workflow,
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
assert retirement_candidates == set()
|
||||
bindings = {
|
||||
binding.node_id: binding
|
||||
for binding in sqlite_session.scalars(
|
||||
select(WorkflowAgentNodeBinding).where(
|
||||
WorkflowAgentNodeBinding.workflow_id == draft_workflow.id,
|
||||
WorkflowAgentNodeBinding.workflow_version == Workflow.VERSION_DRAFT,
|
||||
)
|
||||
).all()
|
||||
}
|
||||
assert set(bindings) == {"node-a", "node-b"}
|
||||
for node_id, agent_id in (("node-a", "agent-a"), ("node-b", "agent-b")):
|
||||
assert bindings[node_id].binding_type == WorkflowAgentBindingType.ROSTER_AGENT
|
||||
assert bindings[node_id].agent_id == agent_id
|
||||
assert bindings[node_id].current_snapshot_id == f"{agent_id}-snapshot"
|
||||
assert bindings[node_id].created_by == "account-1"
|
||||
|
||||
|
||||
def test_restore_replaces_bindings_and_returns_only_replaced_inline_agent(sqlite_session: Session) -> None:
|
||||
existing_inline = WorkflowAgentNodeBinding(
|
||||
id="existing-inline",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="draft-workflow",
|
||||
workflow_version=Workflow.VERSION_DRAFT,
|
||||
node_id="old-inline-node",
|
||||
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
|
||||
agent_id="old-inline-agent",
|
||||
current_snapshot_id="old-inline-snapshot",
|
||||
node_job_config={},
|
||||
created_by="account-1",
|
||||
)
|
||||
existing_roster = WorkflowAgentNodeBinding(
|
||||
id="existing-roster",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="draft-workflow",
|
||||
workflow_version=Workflow.VERSION_DRAFT,
|
||||
node_id="old-roster-node",
|
||||
binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
|
||||
agent_id="old-roster-agent",
|
||||
current_snapshot_id="old-roster-snapshot",
|
||||
node_job_config={},
|
||||
created_by="account-1",
|
||||
)
|
||||
source = WorkflowAgentNodeBinding(
|
||||
id="source-roster",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="published-workflow",
|
||||
workflow_version="2026-07-13 00:00:00",
|
||||
node_id="agent-node",
|
||||
binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
|
||||
agent_id="roster-agent",
|
||||
current_snapshot_id="published-snapshot",
|
||||
node_job_config={"workflow_prompt": "Use the roster agent"},
|
||||
created_by="account-1",
|
||||
)
|
||||
roster_agent = Agent(
|
||||
id="roster-agent",
|
||||
tenant_id="tenant-1",
|
||||
name="Roster Agent",
|
||||
scope=AgentScope.ROSTER,
|
||||
source=AgentSource.ROSTER,
|
||||
status=AgentStatus.ACTIVE,
|
||||
app_id="roster-app",
|
||||
active_config_snapshot_id="published-snapshot",
|
||||
)
|
||||
sqlite_session.add_all([existing_inline, existing_roster, source, roster_agent])
|
||||
sqlite_session.commit()
|
||||
retirement_candidates = WorkflowAgentPublishService.restore_agent_node_bindings_to_draft(
|
||||
session=sqlite_session,
|
||||
source_workflow=_workflow(workflow_id="published-workflow", version="2026-07-13 00:00:00"),
|
||||
draft_workflow=_workflow(workflow_id="draft-workflow"),
|
||||
account_id="account-2",
|
||||
)
|
||||
|
||||
assert sqlite_session.get(WorkflowAgentNodeBinding, existing_inline.id) is None
|
||||
assert sqlite_session.get(WorkflowAgentNodeBinding, existing_roster.id) is None
|
||||
restored = sqlite_session.scalar(
|
||||
select(WorkflowAgentNodeBinding).where(
|
||||
WorkflowAgentNodeBinding.workflow_id == "draft-workflow",
|
||||
WorkflowAgentNodeBinding.node_id == "agent-node",
|
||||
)
|
||||
)
|
||||
assert restored is not None
|
||||
assert restored.workflow_version == Workflow.VERSION_DRAFT
|
||||
assert restored.agent_id == "roster-agent"
|
||||
assert restored.current_snapshot_id == "published-snapshot"
|
||||
assert restored.node_job_config.workflow_prompt == "Use the roster agent"
|
||||
assert retirement_candidates == {"old-inline-agent"}
|
||||
|
||||
|
||||
def test_publish_copy_uses_current_roster_snapshot(sqlite_session: Session) -> None:
|
||||
draft_workflow = _workflow()
|
||||
draft_workflow.graph = (
|
||||
'{"nodes":[{"id":"agent-node","data":{"type":"agent","version":"2",'
|
||||
'"agent_node_kind":"dify_agent"}}],"edges":[]}'
|
||||
)
|
||||
published_workflow = _workflow(workflow_id="published", version="published")
|
||||
binding = WorkflowAgentNodeBinding(
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="workflow-1",
|
||||
workflow_version=Workflow.VERSION_DRAFT,
|
||||
node_id="agent-node",
|
||||
binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
|
||||
agent_id="roster-agent",
|
||||
current_snapshot_id="old-snapshot",
|
||||
node_job_config={},
|
||||
created_by="account-1",
|
||||
)
|
||||
roster_agent = Agent(
|
||||
id="roster-agent",
|
||||
tenant_id="tenant-1",
|
||||
name="Roster Agent",
|
||||
scope=AgentScope.ROSTER,
|
||||
source=AgentSource.ROSTER,
|
||||
status=AgentStatus.ACTIVE,
|
||||
active_config_snapshot_id="active-snapshot",
|
||||
)
|
||||
sqlite_session.add_all([binding, roster_agent, _snapshot(snapshot_id="active-snapshot", agent_id="roster-agent")])
|
||||
sqlite_session.commit()
|
||||
|
||||
WorkflowAgentPublishService.copy_agent_node_bindings_to_published(
|
||||
session=sqlite_session,
|
||||
draft_workflow=draft_workflow,
|
||||
published_workflow=published_workflow,
|
||||
)
|
||||
sqlite_session.flush()
|
||||
|
||||
copied = sqlite_session.scalar(
|
||||
select(WorkflowAgentNodeBinding).where(
|
||||
WorkflowAgentNodeBinding.workflow_id == "published",
|
||||
WorkflowAgentNodeBinding.workflow_version == "published",
|
||||
)
|
||||
)
|
||||
assert copied is not None
|
||||
assert copied.agent_id == "roster-agent"
|
||||
assert copied.current_snapshot_id == "active-snapshot"
|
||||
assert copied.binding_type == WorkflowAgentBindingType.ROSTER_AGENT
|
||||
# Publishing freezes the copied row only; the draft binding keeps its own snapshot.
|
||||
draft_binding = sqlite_session.get(WorkflowAgentNodeBinding, binding.id)
|
||||
assert draft_binding is not None
|
||||
assert draft_binding.current_snapshot_id == "old-snapshot"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sqlite_session",
|
||||
[(App, Agent, WorkflowAgentNodeBinding)],
|
||||
indirect=True,
|
||||
)
|
||||
def test_publish_binding_copy_keeps_previous_published_owner(
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
draft_workflow = _workflow()
|
||||
draft_workflow.graph = (
|
||||
'{"nodes":[{"id":"agent-node","data":{"type":"agent","version":"2",'
|
||||
'"agent_node_kind":"dify_agent"}}],"edges":[]}'
|
||||
)
|
||||
published_workflow = _workflow(workflow_id="published-new", version="published-new")
|
||||
app = App(
|
||||
id="app-1",
|
||||
tenant_id="tenant-1",
|
||||
name="Workflow",
|
||||
description="",
|
||||
mode=AppMode.WORKFLOW,
|
||||
workflow_id="published-previous",
|
||||
status=AppStatus.NORMAL,
|
||||
enable_site=False,
|
||||
enable_api=False,
|
||||
api_rpm=0,
|
||||
api_rph=0,
|
||||
)
|
||||
previous_inline_binding = WorkflowAgentNodeBinding(
|
||||
id="previous-inline-binding",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="published-previous",
|
||||
workflow_version="published-previous",
|
||||
node_id="previous-inline-node",
|
||||
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
|
||||
agent_id="previous-inline-agent",
|
||||
current_snapshot_id="previous-inline-snapshot",
|
||||
node_job_config={},
|
||||
created_by="account-1",
|
||||
)
|
||||
previous_roster_binding = WorkflowAgentNodeBinding(
|
||||
id="previous-roster-binding",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="published-previous",
|
||||
workflow_version="published-previous",
|
||||
node_id="previous-roster-node",
|
||||
binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
|
||||
agent_id="previous-roster-agent",
|
||||
current_snapshot_id="previous-roster-snapshot",
|
||||
node_job_config={},
|
||||
created_by="account-1",
|
||||
)
|
||||
draft_binding = WorkflowAgentNodeBinding(
|
||||
id="draft-binding",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="workflow-1",
|
||||
workflow_version=Workflow.VERSION_DRAFT,
|
||||
node_id="agent-node",
|
||||
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
|
||||
agent_id="draft-inline-agent",
|
||||
current_snapshot_id="draft-inline-snapshot",
|
||||
node_job_config={"workflow_prompt": "work"},
|
||||
created_by="account-1",
|
||||
)
|
||||
sqlite_session.add_all([app, previous_inline_binding, previous_roster_binding, draft_binding])
|
||||
sqlite_session.commit()
|
||||
WorkflowAgentPublishService.copy_agent_node_bindings_to_published(
|
||||
session=sqlite_session,
|
||||
draft_workflow=draft_workflow,
|
||||
published_workflow=published_workflow,
|
||||
)
|
||||
sqlite_session.flush()
|
||||
|
||||
assert sqlite_session.get(WorkflowAgentNodeBinding, previous_inline_binding.id) is previous_inline_binding
|
||||
assert sqlite_session.get(WorkflowAgentNodeBinding, previous_roster_binding.id) is previous_roster_binding
|
||||
copied = sqlite_session.scalar(
|
||||
select(WorkflowAgentNodeBinding).where(
|
||||
WorkflowAgentNodeBinding.workflow_id == "published-new",
|
||||
WorkflowAgentNodeBinding.workflow_version == "published-new",
|
||||
)
|
||||
)
|
||||
assert copied is not None
|
||||
assert copied.agent_id == "draft-inline-agent"
|
||||
assert copied.current_snapshot_id == "draft-inline-snapshot"
|
||||
|
||||
|
||||
def test_inline_binding_reuses_existing_node_owned_agent(sqlite_session: Session) -> None:
|
||||
existing_agent = _inline_agent(agent_id="existing-agent", workflow_id="workflow-1", node_id="pasted-node")
|
||||
existing_snapshot = _snapshot(snapshot_id="existing-snapshot", agent_id=existing_agent.id)
|
||||
existing_binding = WorkflowAgentNodeBinding(
|
||||
id="existing-binding",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="workflow-1",
|
||||
workflow_version=Workflow.VERSION_DRAFT,
|
||||
node_id="pasted-node",
|
||||
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
|
||||
agent_id=existing_agent.id,
|
||||
current_snapshot_id=existing_snapshot.id,
|
||||
node_job_config={},
|
||||
created_by="account-1",
|
||||
)
|
||||
sqlite_session.add_all([existing_agent, existing_snapshot, existing_binding])
|
||||
sqlite_session.commit()
|
||||
|
||||
WorkflowAgentPublishService._sync_agent_binding_for_node(
|
||||
session=sqlite_session,
|
||||
draft_workflow=_workflow(),
|
||||
node_id="pasted-node",
|
||||
node_data={"agent_task": "Summarize"},
|
||||
node_binding={
|
||||
"binding_type": WorkflowAgentBindingType.INLINE_AGENT.value,
|
||||
"agent_id": "unavailable-source-agent",
|
||||
"current_snapshot_id": "unavailable-source-snapshot",
|
||||
},
|
||||
existing_binding=existing_binding,
|
||||
account_id="account-1",
|
||||
)
|
||||
sqlite_session.flush()
|
||||
|
||||
stored = sqlite_session.get(WorkflowAgentNodeBinding, existing_binding.id)
|
||||
assert stored is not None
|
||||
assert stored.agent_id == "existing-agent"
|
||||
assert stored.current_snapshot_id == "existing-snapshot"
|
||||
assert stored.node_job_config.workflow_prompt == "Summarize"
|
||||
|
||||
|
||||
def test_resolve_existing_inline_binding_agent_returns_valid_agent_or_none(
|
||||
monkeypatch: pytest.MonkeyPatch, unbound_session: Session
|
||||
) -> None:
|
||||
binding = WorkflowAgentNodeBinding(
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="workflow-1",
|
||||
workflow_version=Workflow.VERSION_DRAFT,
|
||||
node_id="node-1",
|
||||
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
|
||||
agent_id="agent-1",
|
||||
current_snapshot_id="snapshot-1",
|
||||
node_job_config={},
|
||||
created_by="account-1",
|
||||
)
|
||||
resolved = _inline_agent(agent_id="agent-1", workflow_id="workflow-1", node_id="node-1")
|
||||
resolver = Mock(return_value=resolved)
|
||||
monkeypatch.setattr(WorkflowAgentPublishService, "_resolve_inline_agent_graph_binding", resolver)
|
||||
|
||||
assert (
|
||||
WorkflowAgentPublishService._resolve_existing_inline_binding_agent(
|
||||
session=unbound_session,
|
||||
draft_workflow=_workflow(),
|
||||
node_id="node-1",
|
||||
existing_binding=binding,
|
||||
)
|
||||
is resolved
|
||||
)
|
||||
|
||||
resolver.side_effect = ValueError("stale")
|
||||
assert (
|
||||
WorkflowAgentPublishService._resolve_existing_inline_binding_agent(
|
||||
session=unbound_session,
|
||||
draft_workflow=_workflow(),
|
||||
node_id="node-1",
|
||||
existing_binding=binding,
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_roster_binding_rejects_unpublished_agent(sqlite_session: Session) -> None:
|
||||
sqlite_session.add(
|
||||
Agent(
|
||||
id="decoy-agent",
|
||||
tenant_id="tenant-1",
|
||||
name="Decoy",
|
||||
scope=AgentScope.ROSTER,
|
||||
source=AgentSource.AGENT_APP,
|
||||
status=AgentStatus.ACTIVE,
|
||||
app_id="decoy-app",
|
||||
)
|
||||
)
|
||||
sqlite_session.commit()
|
||||
with pytest.raises(ValueError, match="unavailable or unpublished roster agent"):
|
||||
WorkflowAgentPublishService._resolve_roster_agent_graph_binding(
|
||||
session=sqlite_session,
|
||||
draft_workflow=_workflow(),
|
||||
node_id="agent-node",
|
||||
agent_id="agent-1",
|
||||
)
|
||||
|
||||
|
||||
def test_clone_inline_graph_binding_for_node_clones_source(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
source_agent = _inline_agent(agent_id="source-agent", workflow_id="source-workflow", node_id="source-node")
|
||||
source_snapshot = _snapshot(snapshot_id="source-snapshot", agent_id=source_agent.id)
|
||||
sqlite_session.add_all([source_agent, source_snapshot])
|
||||
sqlite_session.commit()
|
||||
target_agent = _inline_agent(agent_id="target-agent", workflow_id="workflow-1", node_id="target-node")
|
||||
target_snapshot = _snapshot(snapshot_id="target-snapshot", agent_id=target_agent.id)
|
||||
clone = Mock(return_value=(target_agent, target_snapshot))
|
||||
monkeypatch.setattr(AgentDslService, "clone_inline_binding_for_node", clone)
|
||||
|
||||
result = WorkflowAgentPublishService._clone_inline_graph_binding_for_node(
|
||||
session=sqlite_session,
|
||||
draft_workflow=_workflow(),
|
||||
node_id="target-node",
|
||||
source_agent_id="source-agent",
|
||||
source_snapshot_id="source-snapshot",
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
assert result == (target_agent, "target-snapshot")
|
||||
clone.assert_called_once_with(
|
||||
workflow=ANY,
|
||||
node_id="target-node",
|
||||
source_agent=source_agent,
|
||||
source_snapshot=source_snapshot,
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("persist_source_agent", [False, True])
|
||||
def test_clone_inline_graph_binding_for_node_rejects_missing_source(
|
||||
sqlite_session: Session, persist_source_agent: bool
|
||||
) -> None:
|
||||
if persist_source_agent:
|
||||
sqlite_session.add(_inline_agent(agent_id="source-agent", workflow_id="source-workflow", node_id="source-node"))
|
||||
sqlite_session.commit()
|
||||
|
||||
with pytest.raises(ValueError, match="unavailable inline agent|missing inline agent config snapshot"):
|
||||
WorkflowAgentPublishService._clone_inline_graph_binding_for_node(
|
||||
session=sqlite_session,
|
||||
draft_workflow=_workflow(),
|
||||
node_id="target-node",
|
||||
source_agent_id="source-agent",
|
||||
source_snapshot_id="source-snapshot",
|
||||
account_id="account-1",
|
||||
)
|
||||
|
||||
|
||||
def test_restore_clones_inline_binding_owned_by_published_workflow(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
source_agent = _inline_agent(agent_id="published-agent", workflow_id="published-workflow", node_id="agent-node")
|
||||
source_snapshot = _snapshot(snapshot_id="published-snapshot", agent_id=source_agent.id)
|
||||
source = WorkflowAgentNodeBinding(
|
||||
id="published-binding",
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
workflow_id="published-workflow",
|
||||
workflow_version="published",
|
||||
node_id="agent-node",
|
||||
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
|
||||
agent_id=source_agent.id,
|
||||
current_snapshot_id=source_snapshot.id,
|
||||
node_job_config={"workflow_prompt": "work"},
|
||||
created_by="account-1",
|
||||
)
|
||||
sqlite_session.add_all([source_agent, source_snapshot, source])
|
||||
sqlite_session.commit()
|
||||
target_agent = _inline_agent(agent_id="draft-agent", workflow_id="draft-workflow", node_id="agent-node")
|
||||
target_snapshot = _snapshot(snapshot_id="draft-snapshot", agent_id=target_agent.id)
|
||||
clone = Mock(return_value=(target_agent, target_snapshot))
|
||||
monkeypatch.setattr(AgentDslService, "clone_inline_binding_for_node", clone)
|
||||
|
||||
WorkflowAgentPublishService.restore_agent_node_bindings_to_draft(
|
||||
session=sqlite_session,
|
||||
source_workflow=_workflow(workflow_id="published-workflow", version="published"),
|
||||
draft_workflow=_workflow(workflow_id="draft-workflow"),
|
||||
account_id="account-2",
|
||||
)
|
||||
|
||||
clone.assert_called_once()
|
||||
restored = sqlite_session.scalar(
|
||||
select(WorkflowAgentNodeBinding).where(
|
||||
WorkflowAgentNodeBinding.workflow_id == "draft-workflow",
|
||||
WorkflowAgentNodeBinding.workflow_version == Workflow.VERSION_DRAFT,
|
||||
)
|
||||
)
|
||||
assert restored is not None
|
||||
assert restored.agent_id == "draft-agent"
|
||||
assert restored.current_snapshot_id == "draft-snapshot"
|
||||
|
||||
|
||||
def test_output_routes_round_trip_through_sync_projection_and_publication(sqlite_session: Session) -> None:
|
||||
import json
|
||||
|
||||
from models.agent_config_entities import WorkflowNodeJobConfig
|
||||
|
||||
agent = _inline_agent(agent_id="route-agent", workflow_id="workflow-1", node_id="route-node")
|
||||
snapshot = _snapshot(snapshot_id="route-snapshot", agent_id=agent.id)
|
||||
sqlite_session.add_all([agent, snapshot])
|
||||
sqlite_session.flush()
|
||||
routes = {
|
||||
"enabled": True,
|
||||
"routes": [
|
||||
{"id": "accept", "name": "Accepted", "label": "Continue"},
|
||||
{"id": "reject", "name": "Rejected", "label": None},
|
||||
],
|
||||
}
|
||||
node_data = {
|
||||
"type": "agent",
|
||||
"version": "2",
|
||||
"agent_node_kind": "dify_agent",
|
||||
"agent_output_routes": routes,
|
||||
"agent_binding": {"binding_type": "inline_agent", "agent_id": agent.id, "current_snapshot_id": snapshot.id},
|
||||
}
|
||||
workflow = _workflow()
|
||||
workflow.graph = json.dumps({"nodes": [{"id": "route-node", "data": node_data}], "edges": []})
|
||||
WorkflowAgentPublishService.sync_agent_bindings_for_draft(
|
||||
session=sqlite_session, draft_workflow=workflow, account_id="account-1"
|
||||
)
|
||||
projected = WorkflowAgentPublishService.project_draft_bindings_to_graph(
|
||||
session=sqlite_session, draft_workflow=workflow
|
||||
)
|
||||
assert projected["nodes"][0]["data"]["agent_output_routes"] == routes
|
||||
published = _workflow(workflow_id="published-routes", version="published-routes")
|
||||
WorkflowAgentPublishService.copy_agent_node_bindings_to_published(
|
||||
session=sqlite_session, draft_workflow=workflow, published_workflow=published
|
||||
)
|
||||
sqlite_session.flush()
|
||||
frozen = sqlite_session.scalar(
|
||||
select(WorkflowAgentNodeBinding).where(WorkflowAgentNodeBinding.workflow_id == published.id)
|
||||
)
|
||||
assert frozen is not None
|
||||
assert WorkflowNodeJobConfig.model_validate(frozen.node_job_config_dict).output_routes.model_dump() == routes
|
||||
node_data["agent_output_routes"] = {"enabled": False, "routes": routes["routes"]}
|
||||
workflow.graph = json.dumps({"nodes": [{"id": "route-node", "data": node_data}], "edges": []})
|
||||
WorkflowAgentPublishService.sync_agent_bindings_for_draft(
|
||||
session=sqlite_session, draft_workflow=workflow, account_id="account-1"
|
||||
)
|
||||
projected = WorkflowAgentPublishService.project_draft_bindings_to_graph(
|
||||
session=sqlite_session, draft_workflow=workflow
|
||||
)
|
||||
assert projected["nodes"][0]["data"]["agent_output_routes"]["enabled"] is False
|
||||
assert WorkflowNodeJobConfig.model_validate(frozen.node_job_config_dict).output_routes.model_dump() == routes
|
||||
@@ -0,0 +1,707 @@
|
||||
from contextlib import nullcontext
|
||||
from datetime import datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from models.agent import (
|
||||
AgentConfigVersionKind,
|
||||
AgentHomeSnapshot,
|
||||
AgentWorkingResourceStatus,
|
||||
AgentWorkspace,
|
||||
AgentWorkspaceBinding,
|
||||
AgentWorkspaceOwnerType,
|
||||
)
|
||||
from services.agent.workspace_service import (
|
||||
AgentWorkspaceError,
|
||||
AgentWorkspaceNotFoundError,
|
||||
AgentWorkspaceService,
|
||||
WorkspaceOwnerScope,
|
||||
)
|
||||
from tests.helpers.unit.config_override import apply_config_overrides
|
||||
|
||||
|
||||
def _scope() -> WorkspaceOwnerScope:
|
||||
return WorkspaceOwnerScope(
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
owner_type=AgentWorkspaceOwnerType.CONVERSATION,
|
||||
owner_id="conversation-1",
|
||||
)
|
||||
|
||||
|
||||
def _backend_client() -> MagicMock:
|
||||
client = MagicMock()
|
||||
client.create_execution_binding_sync.return_value = SimpleNamespace(
|
||||
binding_ref="binding-ref",
|
||||
workspace_ref="workspace-ref",
|
||||
)
|
||||
return client
|
||||
|
||||
|
||||
def _workspace(
|
||||
*,
|
||||
workspace_id: str = "workspace-1",
|
||||
tenant_id: str = "tenant-1",
|
||||
app_id: str = "app-1",
|
||||
owner_type: AgentWorkspaceOwnerType = AgentWorkspaceOwnerType.CONVERSATION,
|
||||
owner_id: str = "conversation-1",
|
||||
owner_scope_key: str = "root",
|
||||
status: AgentWorkingResourceStatus = AgentWorkingResourceStatus.ACTIVE,
|
||||
updated_at: datetime | None = None,
|
||||
backend_workspace_ref: str = "workspace-ref",
|
||||
) -> AgentWorkspace:
|
||||
row = AgentWorkspace(
|
||||
id=workspace_id,
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
owner_type=owner_type,
|
||||
owner_id=owner_id,
|
||||
owner_scope_key=owner_scope_key,
|
||||
backend_workspace_ref=backend_workspace_ref,
|
||||
status=status,
|
||||
active_guard=1 if status is AgentWorkingResourceStatus.ACTIVE else None,
|
||||
)
|
||||
if updated_at is not None:
|
||||
row.updated_at = updated_at
|
||||
return row
|
||||
|
||||
|
||||
def _binding(
|
||||
*,
|
||||
binding_id: str = "binding-1",
|
||||
tenant_id: str = "tenant-1",
|
||||
app_id: str = "app-1",
|
||||
workspace_id: str = "workspace-1",
|
||||
agent_id: str = "agent-1",
|
||||
status: AgentWorkingResourceStatus = AgentWorkingResourceStatus.ACTIVE,
|
||||
config_kind: AgentConfigVersionKind = AgentConfigVersionKind.SNAPSHOT,
|
||||
updated_at: datetime | None = None,
|
||||
) -> AgentWorkspaceBinding:
|
||||
row = AgentWorkspaceBinding(
|
||||
id=binding_id,
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
workspace_id=workspace_id,
|
||||
agent_id=agent_id,
|
||||
base_home_snapshot_id="home-1",
|
||||
agent_config_version_id="config-1",
|
||||
agent_config_version_kind=config_kind,
|
||||
backend_binding_ref=f"{binding_id}-ref",
|
||||
status=status,
|
||||
)
|
||||
if updated_at is not None:
|
||||
row.updated_at = updated_at
|
||||
return row
|
||||
|
||||
|
||||
def test_workspace_client_honors_the_configured_snapshot_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
apply_config_overrides(
|
||||
monkeypatch,
|
||||
AGENT_BACKEND_BASE_URL="http://agent.example",
|
||||
AGENT_BACKEND_HOME_SNAPSHOT_TIMEOUT_SECONDS=123.5,
|
||||
)
|
||||
|
||||
client = AgentWorkspaceService._client()
|
||||
|
||||
assert client._timeout == 123.5
|
||||
|
||||
|
||||
def test_create_binding_success_persists_new_workspace_and_binding(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
sqlite_session.add(
|
||||
AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
snapshot_ref="home-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
)
|
||||
sqlite_session.commit()
|
||||
client = _backend_client()
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
binding = AgentWorkspaceService.create_binding(
|
||||
session=sqlite_session,
|
||||
scope=_scope(),
|
||||
agent_id="agent-1",
|
||||
base_home_snapshot_id="home-1",
|
||||
agent_config_version_id="config-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
)
|
||||
sqlite_session.commit()
|
||||
|
||||
workspace = sqlite_session.scalar(select(AgentWorkspace))
|
||||
stored_binding = sqlite_session.get(AgentWorkspaceBinding, binding.id)
|
||||
assert workspace is not None
|
||||
assert stored_binding is not None
|
||||
assert binding.workspace_id == workspace.id
|
||||
assert stored_binding.backend_binding_ref == "binding-ref"
|
||||
request = client.create_execution_binding_sync.call_args.args[0]
|
||||
assert request.existing_workspace_ref is None
|
||||
assert request.workspace_id == workspace.id
|
||||
assert request.home_snapshot_ref == "home-ref"
|
||||
|
||||
|
||||
def test_create_binding_without_home_snapshot_uses_backend_default(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
client = _backend_client()
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
binding = AgentWorkspaceService.create_binding(
|
||||
session=sqlite_session,
|
||||
scope=_scope(),
|
||||
agent_id="agent-1",
|
||||
base_home_snapshot_id=None,
|
||||
agent_config_version_id="config-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
)
|
||||
sqlite_session.commit()
|
||||
|
||||
stored_binding = sqlite_session.get(AgentWorkspaceBinding, binding.id)
|
||||
assert stored_binding is not None
|
||||
assert stored_binding.base_home_snapshot_id is None
|
||||
request = client.create_execution_binding_sync.call_args.args[0]
|
||||
assert request.home_snapshot_ref is None
|
||||
|
||||
|
||||
def test_create_binding_rejects_missing_explicit_home_snapshot_before_backend_call(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
client = _backend_client()
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
with pytest.raises(AgentWorkspaceNotFoundError, match="base Home Snapshot is unavailable"):
|
||||
AgentWorkspaceService.create_binding(
|
||||
session=sqlite_session,
|
||||
scope=_scope(),
|
||||
agent_id="agent-1",
|
||||
base_home_snapshot_id="missing-home",
|
||||
agent_config_version_id="config-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
)
|
||||
|
||||
client.create_execution_binding_sync.assert_not_called()
|
||||
|
||||
|
||||
def test_create_second_binding_reuses_existing_workspace(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
workspace = _workspace()
|
||||
first_binding = _binding()
|
||||
home = AgentHomeSnapshot(
|
||||
id="home-1",
|
||||
tenant_id="tenant-1",
|
||||
agent_id="agent-1",
|
||||
snapshot_ref="home-ref",
|
||||
status=AgentWorkingResourceStatus.ACTIVE,
|
||||
)
|
||||
sqlite_session.add_all([workspace, first_binding, home])
|
||||
sqlite_session.commit()
|
||||
client = _backend_client()
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
binding = AgentWorkspaceService.create_binding(
|
||||
session=sqlite_session,
|
||||
scope=_scope(),
|
||||
agent_id="agent-1",
|
||||
base_home_snapshot_id="home-1",
|
||||
agent_config_version_id="config-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
)
|
||||
sqlite_session.commit()
|
||||
|
||||
assert binding.workspace_id == workspace.id
|
||||
assert sqlite_session.scalars(select(AgentWorkspace)).all() == [workspace]
|
||||
assert {row.id for row in sqlite_session.scalars(select(AgentWorkspaceBinding)).all()} == {
|
||||
first_binding.id,
|
||||
binding.id,
|
||||
}
|
||||
request = client.create_execution_binding_sync.call_args.args[0]
|
||||
assert request.existing_workspace_ref == "workspace-ref"
|
||||
assert request.workspace_id == workspace.id
|
||||
|
||||
|
||||
def test_get_active_binding_resolves_exact_participant(sqlite_session: Session) -> None:
|
||||
conversation_workspace = _workspace(workspace_id="workspace-conversation")
|
||||
build_workspace = _workspace(
|
||||
workspace_id="workspace-build",
|
||||
owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
|
||||
owner_id="draft-1",
|
||||
)
|
||||
conversation_binding = _binding(
|
||||
binding_id="binding-conversation",
|
||||
workspace_id=conversation_workspace.id,
|
||||
)
|
||||
build_binding = _binding(
|
||||
binding_id="binding-build",
|
||||
workspace_id=build_workspace.id,
|
||||
config_kind=AgentConfigVersionKind.BUILD_DRAFT,
|
||||
)
|
||||
sqlite_session.add_all([conversation_workspace, build_workspace, conversation_binding, build_binding])
|
||||
sqlite_session.commit()
|
||||
|
||||
resolved = AgentWorkspaceService.get_active_binding(
|
||||
session=sqlite_session,
|
||||
tenant_id="tenant-1",
|
||||
binding_id=conversation_binding.id,
|
||||
expected_owner_scope=_scope(),
|
||||
)
|
||||
|
||||
assert resolved is not None
|
||||
assert resolved.id == conversation_binding.id
|
||||
|
||||
|
||||
def test_get_active_binding_rejects_wrong_owner(sqlite_session: Session) -> None:
|
||||
build_workspace = _workspace(
|
||||
workspace_id="workspace-build",
|
||||
owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
|
||||
owner_id="draft-1",
|
||||
)
|
||||
build_binding = _binding(
|
||||
binding_id="binding-build",
|
||||
workspace_id=build_workspace.id,
|
||||
config_kind=AgentConfigVersionKind.BUILD_DRAFT,
|
||||
)
|
||||
sqlite_session.add_all([build_workspace, build_binding])
|
||||
sqlite_session.commit()
|
||||
|
||||
resolved = AgentWorkspaceService.get_active_binding(
|
||||
session=sqlite_session,
|
||||
tenant_id="tenant-1",
|
||||
binding_id=build_binding.id,
|
||||
expected_owner_scope=_scope(),
|
||||
)
|
||||
|
||||
assert resolved is None
|
||||
|
||||
|
||||
def test_retire_non_final_binding_keeps_workspace_active(sqlite_session: Session) -> None:
|
||||
binding = _binding()
|
||||
other_binding = _binding(binding_id="binding-2", agent_id="agent-2")
|
||||
workspace = _workspace()
|
||||
sqlite_session.add_all([workspace, binding, other_binding])
|
||||
sqlite_session.commit()
|
||||
|
||||
retired_id = AgentWorkspaceService.retire_binding(
|
||||
session=sqlite_session,
|
||||
tenant_id="tenant-1",
|
||||
binding_id=binding.id,
|
||||
)
|
||||
|
||||
assert retired_id == binding.id
|
||||
assert binding.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert binding.retired_at is not None
|
||||
assert workspace.status is AgentWorkingResourceStatus.ACTIVE
|
||||
assert other_binding.status is AgentWorkingResourceStatus.ACTIVE
|
||||
|
||||
|
||||
def test_retire_final_binding_retires_workspace(sqlite_session: Session) -> None:
|
||||
binding = _binding()
|
||||
workspace = _workspace()
|
||||
sqlite_session.add_all([workspace, binding])
|
||||
sqlite_session.commit()
|
||||
|
||||
AgentWorkspaceService.retire_binding(session=sqlite_session, tenant_id="tenant-1", binding_id=binding.id)
|
||||
|
||||
assert binding.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert workspace.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert workspace.active_guard is None
|
||||
assert workspace.retired_at == binding.retired_at
|
||||
|
||||
|
||||
def test_retire_workspace_retires_all_active_bindings(sqlite_session: Session) -> None:
|
||||
workspace = _workspace()
|
||||
bindings = [_binding(), _binding(binding_id="binding-2", agent_id="agent-2")]
|
||||
sqlite_session.add_all([workspace, *bindings])
|
||||
sqlite_session.commit()
|
||||
|
||||
retired_id = AgentWorkspaceService.retire_workspace(
|
||||
session=sqlite_session,
|
||||
tenant_id="tenant-1",
|
||||
workspace_id=workspace.id,
|
||||
)
|
||||
sqlite_session.flush()
|
||||
|
||||
assert retired_id == workspace.id
|
||||
assert workspace.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert all(binding.status is AgentWorkingResourceStatus.RETIRED for binding in bindings)
|
||||
assert all(binding.retired_at == workspace.retired_at for binding in bindings)
|
||||
|
||||
|
||||
def test_resolve_active_binding_for_scope_returns_matching_participant(sqlite_session: Session) -> None:
|
||||
workspace = _workspace(owner_scope_key="node-1:workflow-binding-1")
|
||||
binding = _binding(binding_id="binding-chatflow", workspace_id=workspace.id)
|
||||
sqlite_session.add_all([workspace, binding])
|
||||
sqlite_session.commit()
|
||||
|
||||
resolved = AgentWorkspaceService.resolve_active_binding_for_scope(
|
||||
session=sqlite_session,
|
||||
scope=WorkspaceOwnerScope(
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
owner_type=AgentWorkspaceOwnerType.CONVERSATION,
|
||||
owner_id="conversation-1",
|
||||
owner_scope_key="node-1:workflow-binding-1",
|
||||
),
|
||||
agent_id="agent-1",
|
||||
)
|
||||
|
||||
assert resolved is not None
|
||||
assert resolved.id == binding.id
|
||||
|
||||
|
||||
def test_retire_all_for_conversation_retires_only_matching_conversation_workspaces(
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
matching = _workspace(
|
||||
workspace_id="workspace-chatflow",
|
||||
owner_scope_key="node-1:workflow-binding-1",
|
||||
)
|
||||
other_conversation = _workspace(
|
||||
workspace_id="workspace-other-conversation",
|
||||
owner_id="conversation-2",
|
||||
owner_scope_key="node-2:workflow-binding-2",
|
||||
)
|
||||
workflow_run = _workspace(
|
||||
workspace_id="workspace-workflow-run",
|
||||
owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN,
|
||||
owner_id="run-1",
|
||||
owner_scope_key="node-1:workflow-binding-1",
|
||||
)
|
||||
sqlite_session.add_all([matching, other_conversation, workflow_run])
|
||||
sqlite_session.commit()
|
||||
|
||||
retired_ids = AgentWorkspaceService.retire_all_for_conversation(
|
||||
session=sqlite_session,
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
conversation_id="conversation-1",
|
||||
)
|
||||
|
||||
assert retired_ids == [matching.id]
|
||||
assert matching.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert other_conversation.status is AgentWorkingResourceStatus.ACTIVE
|
||||
assert workflow_run.status is AgentWorkingResourceStatus.ACTIVE
|
||||
|
||||
|
||||
def test_retire_all_for_app_retires_only_active_workspaces_for_that_app(sqlite_session: Session) -> None:
|
||||
active = _workspace(workspace_id="workspace-active", owner_id="conversation-active")
|
||||
already_retired = _workspace(
|
||||
workspace_id="workspace-retired",
|
||||
owner_id="conversation-retired",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
)
|
||||
other_app = _workspace(
|
||||
workspace_id="workspace-other",
|
||||
app_id="app-2",
|
||||
owner_id="conversation-other",
|
||||
)
|
||||
active_binding = _binding(binding_id="binding-active", workspace_id=active.id)
|
||||
other_binding = _binding(
|
||||
binding_id="binding-other",
|
||||
app_id="app-2",
|
||||
workspace_id=other_app.id,
|
||||
)
|
||||
sqlite_session.add_all([active, already_retired, other_app, active_binding, other_binding])
|
||||
sqlite_session.commit()
|
||||
|
||||
retired_ids = AgentWorkspaceService.retire_all_for_app(
|
||||
session=sqlite_session,
|
||||
tenant_id="tenant-1",
|
||||
app_id="app-1",
|
||||
)
|
||||
|
||||
assert retired_ids == [active.id]
|
||||
assert active.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert active_binding.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert already_retired.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert other_app.status is AgentWorkingResourceStatus.ACTIVE
|
||||
assert other_binding.status is AgentWorkingResourceStatus.ACTIVE
|
||||
|
||||
|
||||
def test_collect_binding_without_retired_workspace_destroys_binding_only(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
binding = _binding(status=AgentWorkingResourceStatus.RETIRED)
|
||||
workspace = _workspace()
|
||||
sqlite_session.add_all([workspace, binding])
|
||||
sqlite_session.commit()
|
||||
client = MagicMock()
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
AgentWorkspaceService.collect_retired_binding(tenant_id="tenant-1", binding_id=binding.id)
|
||||
|
||||
request = client.destroy_execution_binding_sync.call_args.args[0]
|
||||
assert request.binding_ref == binding.backend_binding_ref
|
||||
assert request.destroy_workspace is False
|
||||
assert request.workspace_ref is None
|
||||
with sqlite_session_factory() as observer:
|
||||
assert observer.get(AgentWorkspaceBinding, binding.id) is None
|
||||
assert observer.get(AgentWorkspace, workspace.id) is not None
|
||||
|
||||
|
||||
def test_collect_workspace_destroys_workspace_then_remaining_bindings(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
workspace = _workspace(status=AgentWorkingResourceStatus.RETIRED)
|
||||
anchor = _binding(status=AgentWorkingResourceStatus.RETIRED)
|
||||
remaining = _binding(
|
||||
binding_id="binding-2",
|
||||
agent_id="agent-2",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
)
|
||||
anchor.created_at = datetime(2026, 7, 23, 10)
|
||||
remaining.created_at = anchor.created_at + timedelta(minutes=1)
|
||||
sqlite_session.add_all([workspace, anchor, remaining])
|
||||
sqlite_session.commit()
|
||||
client = MagicMock()
|
||||
commit = MagicMock(wraps=sqlite_session.commit)
|
||||
monkeypatch.setattr(
|
||||
"services.agent.workspace_service.session_factory.create_session", lambda: nullcontext(sqlite_session)
|
||||
)
|
||||
monkeypatch.setattr(sqlite_session, "commit", commit)
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
AgentWorkspaceService.collect_retired_workspace(tenant_id="tenant-1", workspace_id=workspace.id)
|
||||
|
||||
requests = [call.args[0] for call in client.destroy_execution_binding_sync.call_args_list]
|
||||
assert len(requests) == 2
|
||||
assert requests[0].binding_ref == anchor.backend_binding_ref
|
||||
assert requests[0].workspace_ref == workspace.backend_workspace_ref
|
||||
assert requests[0].destroy_workspace is True
|
||||
assert requests[1].binding_ref == remaining.backend_binding_ref
|
||||
assert requests[1].destroy_workspace is False
|
||||
assert sqlite_session.get(AgentWorkspace, workspace.id) is None
|
||||
assert sqlite_session.get(AgentWorkspaceBinding, anchor.id) is None
|
||||
assert sqlite_session.get(AgentWorkspaceBinding, remaining.id) is None
|
||||
commit.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sqlite_session", [(AgentWorkspace, AgentWorkspaceBinding)], indirect=True)
|
||||
def test_collect_workspace_remaining_failure_preserves_ledgers_and_replay_converges(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
workspace = _workspace(status=AgentWorkingResourceStatus.RETIRED)
|
||||
anchor = _binding(status=AgentWorkingResourceStatus.RETIRED)
|
||||
remaining = [
|
||||
_binding(
|
||||
binding_id=f"binding-{index}",
|
||||
agent_id=f"agent-{index}",
|
||||
status=AgentWorkingResourceStatus.RETIRED,
|
||||
)
|
||||
for index in (2, 3)
|
||||
]
|
||||
anchor.created_at = datetime(2026, 7, 23, 10)
|
||||
for index, binding in enumerate(remaining, start=1):
|
||||
binding.created_at = anchor.created_at + timedelta(minutes=index)
|
||||
sqlite_session.add_all([workspace, anchor, *remaining])
|
||||
sqlite_session.commit()
|
||||
workspace_id = workspace.id
|
||||
binding_ids = [anchor.id, *(binding.id for binding in remaining)]
|
||||
error = RuntimeError("middle Binding destroy failed")
|
||||
client = MagicMock()
|
||||
client.destroy_execution_binding_sync.side_effect = [None, error, None]
|
||||
monkeypatch.setattr(
|
||||
"services.agent.workspace_service.session_factory.create_session", lambda: nullcontext(sqlite_session)
|
||||
)
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
AgentWorkspaceService.collect_retired_workspace(tenant_id="tenant-1", workspace_id=workspace_id)
|
||||
|
||||
assert exc_info.value is error
|
||||
assert client.destroy_execution_binding_sync.call_count == 3
|
||||
first_attempt = [call.args[0] for call in client.destroy_execution_binding_sync.call_args_list]
|
||||
assert [request.destroy_workspace for request in first_attempt] == [True, False, False]
|
||||
assert sqlite_session.get(AgentWorkspace, workspace_id) is not None
|
||||
assert all(sqlite_session.get(AgentWorkspaceBinding, binding_id) is not None for binding_id in binding_ids)
|
||||
|
||||
client.reset_mock()
|
||||
client.destroy_execution_binding_sync.side_effect = None
|
||||
AgentWorkspaceService.collect_retired_workspace(tenant_id="tenant-1", workspace_id=workspace_id)
|
||||
|
||||
assert client.destroy_execution_binding_sync.call_count == 3
|
||||
assert sqlite_session.get(AgentWorkspace, workspace_id) is None
|
||||
assert all(sqlite_session.get(AgentWorkspaceBinding, binding_id) is None for binding_id in binding_ids)
|
||||
|
||||
|
||||
def test_collect_retired_workspace_without_retired_binding_raises(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
workspace = _workspace(status=AgentWorkingResourceStatus.RETIRED)
|
||||
sqlite_session.add(workspace)
|
||||
sqlite_session.commit()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.workspace_service.session_factory.create_session",
|
||||
lambda: nullcontext(sqlite_session),
|
||||
)
|
||||
|
||||
with pytest.raises(AgentWorkspaceError, match="tenant_id=tenant-1, workspace_id=workspace-1"):
|
||||
AgentWorkspaceService.collect_retired_workspace(
|
||||
tenant_id="tenant-1",
|
||||
workspace_id=workspace.id,
|
||||
)
|
||||
|
||||
|
||||
def test_binding_collection_database_failure_propagates(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
context = MagicMock()
|
||||
session = context.__enter__.return_value
|
||||
error = RuntimeError("database unavailable")
|
||||
session.scalar.side_effect = error
|
||||
monkeypatch.setattr("services.agent.workspace_service.session_factory.create_session", lambda: context)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
AgentWorkspaceService.collect_retired_binding(tenant_id="tenant-1", binding_id="binding-1")
|
||||
|
||||
assert exc_info.value is error
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sqlite_session", [(AgentWorkspace, AgentWorkspaceBinding)], indirect=True)
|
||||
def test_binding_collection_backend_failure_propagates_and_preserves_retired_binding(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
workspace = _workspace()
|
||||
binding = _binding(status=AgentWorkingResourceStatus.RETIRED)
|
||||
sqlite_session.add_all([workspace, binding])
|
||||
sqlite_session.commit()
|
||||
error = RuntimeError("Agent backend unavailable")
|
||||
client = MagicMock()
|
||||
client.destroy_execution_binding_sync.side_effect = error
|
||||
monkeypatch.setattr(
|
||||
"services.agent.workspace_service.session_factory.create_session", lambda: nullcontext(sqlite_session)
|
||||
)
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
AgentWorkspaceService.collect_retired_binding(tenant_id="tenant-1", binding_id=binding.id)
|
||||
|
||||
assert exc_info.value is error
|
||||
stored_binding = sqlite_session.get(AgentWorkspaceBinding, binding.id)
|
||||
assert stored_binding is not None
|
||||
assert stored_binding.status is AgentWorkingResourceStatus.RETIRED
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sqlite_session", [(AgentWorkspace, AgentWorkspaceBinding)], indirect=True)
|
||||
def test_workspace_collection_backend_failure_propagates_and_preserves_retired_resources(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
workspace = _workspace(status=AgentWorkingResourceStatus.RETIRED)
|
||||
anchor = _binding(status=AgentWorkingResourceStatus.RETIRED)
|
||||
sqlite_session.add_all([workspace, anchor])
|
||||
sqlite_session.commit()
|
||||
error = RuntimeError("Agent backend unavailable")
|
||||
client = MagicMock()
|
||||
client.destroy_execution_binding_sync.side_effect = error
|
||||
monkeypatch.setattr(
|
||||
"services.agent.workspace_service.session_factory.create_session", lambda: nullcontext(sqlite_session)
|
||||
)
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
AgentWorkspaceService.collect_retired_workspace(tenant_id="tenant-1", workspace_id=workspace.id)
|
||||
|
||||
assert exc_info.value is error
|
||||
stored_workspace = sqlite_session.get(AgentWorkspace, workspace.id)
|
||||
stored_anchor = sqlite_session.get(AgentWorkspaceBinding, anchor.id)
|
||||
assert stored_workspace is not None
|
||||
assert stored_workspace.status is AgentWorkingResourceStatus.RETIRED
|
||||
assert stored_anchor is not None
|
||||
assert stored_anchor.status is AgentWorkingResourceStatus.RETIRED
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sqlite_session", [(AgentWorkspace, AgentWorkspaceBinding)], indirect=True)
|
||||
def test_workspace_collection_final_delete_failure_propagates(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
workspace = _workspace(status=AgentWorkingResourceStatus.RETIRED)
|
||||
anchor = _binding(status=AgentWorkingResourceStatus.RETIRED)
|
||||
sqlite_session.add_all([workspace, anchor])
|
||||
sqlite_session.commit()
|
||||
error = RuntimeError("database unavailable")
|
||||
commit = MagicMock(side_effect=error)
|
||||
client = MagicMock()
|
||||
monkeypatch.setattr(
|
||||
"services.agent.workspace_service.session_factory.create_session", lambda: nullcontext(sqlite_session)
|
||||
)
|
||||
monkeypatch.setattr(sqlite_session, "commit", commit)
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
AgentWorkspaceService.collect_retired_workspace(tenant_id="tenant-1", workspace_id="workspace-1")
|
||||
|
||||
assert exc_info.value is error
|
||||
client.destroy_execution_binding_sync.assert_called_once()
|
||||
|
||||
|
||||
def test_binding_creation_ignores_unavailable_metering_configuration(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
apply_config_overrides(
|
||||
monkeypatch,
|
||||
AGENT_SANDBOX_METERING_ENABLED=True,
|
||||
AGENT_SANDBOX_METERING_PROJECT_ID="",
|
||||
AGENT_SANDBOX_METERING_START_AT="invalid",
|
||||
)
|
||||
client = _backend_client()
|
||||
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
|
||||
binding = AgentWorkspaceService.create_binding(
|
||||
session=sqlite_session,
|
||||
scope=_scope(),
|
||||
agent_id="agent-1",
|
||||
base_home_snapshot_id=None,
|
||||
agent_config_version_id="config-1",
|
||||
agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
|
||||
)
|
||||
sqlite_session.commit()
|
||||
assert binding.backend_binding_ref == "binding-ref"
|
||||
client.create_execution_binding_sync.assert_called_once()
|
||||
|
||||
|
||||
def test_binding_lookups_ignore_bad_metering_configuration_and_remain_tenant_scoped(
|
||||
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
apply_config_overrides(
|
||||
monkeypatch,
|
||||
AGENT_SANDBOX_METERING_ENABLED=True,
|
||||
AGENT_SANDBOX_METERING_PROJECT_ID="",
|
||||
AGENT_SANDBOX_METERING_START_AT="invalid",
|
||||
)
|
||||
workspace, binding = _workspace(), _binding()
|
||||
sqlite_session.add_all([workspace, binding])
|
||||
sqlite_session.commit()
|
||||
assert (
|
||||
AgentWorkspaceService.get_active_binding(
|
||||
session=sqlite_session,
|
||||
tenant_id=binding.tenant_id,
|
||||
binding_id=binding.id,
|
||||
expected_owner_scope=_scope(),
|
||||
)
|
||||
is binding
|
||||
)
|
||||
assert (
|
||||
AgentWorkspaceService.resolve_active_binding_for_scope(
|
||||
session=sqlite_session,
|
||||
scope=_scope(),
|
||||
agent_id=binding.agent_id,
|
||||
)
|
||||
is binding
|
||||
)
|
||||
assert (
|
||||
AgentWorkspaceService.get_active_binding(
|
||||
session=sqlite_session,
|
||||
tenant_id="another-tenant",
|
||||
binding_id=binding.id,
|
||||
expected_owner_scope=_scope(),
|
||||
)
|
||||
is None
|
||||
)
|
||||
Reference in new issue
Block a user