Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

test: migrate agent workspace and publishing sessions and ORM models to SQLite (#40506)

Asuka Minatoa43583a4a03f
diff --git a/api/tests/unit_tests/services/agent/test_agent_dsl_service.py b/api/tests/unit_tests/services/agent/test_agent_dsl_service.py
index 7c0d5ef5332..c3a069f15d3 100644
--- a/api/tests/unit_tests/services/agent/test_agent_dsl_service.py
+++ b/api/tests/unit_tests/services/agent/test_agent_dsl_service.py
@@ -1,5 +1,4 @@
import json
-from types import SimpleNamespace
from unittest.mock import Mock
import pytest
@@ -8,6 +7,7 @@ from sqlalchemy import select
from sqlalchemy.orm import Session
from graphon.enums import BuiltinNodeTypes
+from models.account import Account
from models.agent import (
Agent,
AgentConfigDraft,
@@ -23,6 +23,10 @@ from models.agent import (
WorkflowAgentNodeBinding,
)
from models.agent_config_entities import AgentConfigFileRefConfig, AgentConfigSkillRefConfig, AgentSoulConfig
+from models.dataset import Dataset
+from models.enums import AppStatus
+from models.model import App, AppMode
+from models.workflow import Workflow, WorkflowType
from services.agent.dsl_entities import (
AGENT_NODE_JOB_DSL_KEY,
AGENT_PACKAGE_REF_KEY,
@@ -30,31 +34,45 @@ from services.agent.dsl_entities import (
AgentPackageMetadata,
make_portable_agent_package,
)
-from services.agent.dsl_service import AgentDslService, is_agent_v2_graph
+from services.agent.dsl_service import AgentDslService, AgentPackageImportResult, is_agent_v2_graph
from services.entities.dsl_entities import DslImportWarning
-def _agent() -> Agent:
+def _agent(
+ *,
+ agent_id: str = "agent-1",
+ app_id: str | None = None,
+ name: str = "Portable Agent",
+ scope: AgentScope = AgentScope.ROSTER,
+ source: AgentSource = AgentSource.AGENT_APP,
+) -> Agent:
agent = Agent(
tenant_id="tenant-1",
- name="Portable Agent",
+ name=name,
description="description",
role="researcher",
- scope=AgentScope.ROSTER,
- source=AgentSource.AGENT_APP,
+ scope=scope,
+ source=source,
status=AgentStatus.ACTIVE,
+ app_id=app_id,
icon_type=AgentIconType.EMOJI,
icon="R",
)
- agent.id = "agent-1"
+ agent.id = agent_id
return agent
-def _snapshot(*, snapshot_id: str = "snapshot-1", soul: AgentSoulConfig | None = None) -> AgentConfigSnapshot:
+def _snapshot(
+ *,
+ snapshot_id: str = "snapshot-1",
+ agent_id: str = "agent-1",
+ version: int = 1,
+ soul: AgentSoulConfig | None = None,
+) -> AgentConfigSnapshot:
snapshot = AgentConfigSnapshot(
tenant_id="tenant-1",
- agent_id="agent-1",
- version=1,
+ agent_id=agent_id,
+ version=version,
home_snapshot_id="home-1",
config_snapshot=soul or AgentSoulConfig(),
created_by="account-1",
@@ -63,6 +81,42 @@ def _snapshot(*, snapshot_id: str = "snapshot-1", soul: AgentSoulConfig | None =
return snapshot
+def _app(*, name: str = "", description: str = "", mode: AppMode = AppMode.AGENT_CHAT) -> App:
+ return App(
+ id="app-1",
+ tenant_id="tenant-1",
+ name=name,
+ description=description,
+ mode=mode,
+ status=AppStatus.NORMAL,
+ enable_site=False,
+ enable_api=False,
+ api_rpm=0,
+ api_rph=0,
+ )
+
+
+def _account() -> Account:
+ account = Account(name="Owner", email="[email protected]")
+ account.id = "account-1"
+ return account
+
+
+def _workflow(*, workflow_id: str = "workflow-1") -> Workflow:
+ return Workflow(
+ id=workflow_id,
+ tenant_id="tenant-1",
+ app_id="app-1",
+ type=WorkflowType.WORKFLOW,
+ version=Workflow.VERSION_DRAFT,
+ graph={"nodes": [], "edges": []},
+ features={},
+ created_by="account-1",
+ environment_variables=[],
+ conversation_variables=[],
+ )
+
+
def _agent_node(node_id: str, binding: object | None = None) -> dict:
data = {"type": BuiltinNodeTypes.AGENT, "version": "2", "agent_node_kind": "dify_agent"}
if binding is not None:
@@ -239,45 +293,45 @@ def test_agent_package_rejects_unknown_schema_version() -> None:
def test_export_agent_app_requires_backing_agent(sqlite_session: Session) -> None:
with pytest.raises(ValueError, match="no active backing Agent"):
- AgentDslService(sqlite_session).export_agent_app(app=SimpleNamespace(tenant_id="tenant-1", id="app-1"))
+ AgentDslService(sqlite_session).export_agent_app(app=_app())
@pytest.mark.parametrize("use_draft", [True, False])
-def test_export_agent_app_uses_draft_or_active_snapshot(use_draft: bool, sqlite_session: Session) -> None:
- agent = _agent()
- agent.app_id = "app-1"
+def test_export_agent_app_uses_draft_or_active_snapshot(sqlite_session: Session, use_draft: bool) -> None:
+ agent = _agent(app_id="app-1")
agent.active_config_snapshot_id = "snapshot-1"
- sqlite_session.add(agent)
+ snapshot = _snapshot(soul=AgentSoulConfig(config_note="snapshot"))
+ rows: list[object] = [agent, snapshot]
if use_draft:
- sqlite_session.add(
+ rows.append(
AgentConfigDraft(
+ id="draft-1",
tenant_id="tenant-1",
agent_id=agent.id,
draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
draft_owner_key="",
config_snapshot=AgentSoulConfig(config_note="draft"),
)
)
- sqlite_session.flush()
- service = AgentDslService(sqlite_session)
- require_snapshot = Mock(return_value=_snapshot(soul=AgentSoulConfig(config_note="snapshot")))
- service._require_snapshot = require_snapshot
+ sqlite_session.add_all(rows)
+ sqlite_session.commit()
- package_ref, packages = service.export_agent_app(app=SimpleNamespace(tenant_id="tenant-1", id="app-1"))
+ package_ref, packages = AgentDslService(sqlite_session).export_agent_app(app=_app())
assert package_ref == "agent_1"
assert packages[package_ref].soul.config_note == ("draft" if use_draft else "snapshot")
- assert require_snapshot.call_count == (0 if use_draft else 1)
def test_export_workflow_packages_deduplicates_shared_agent(sqlite_session: Session) -> None:
graph = {"nodes": [_agent_node("node-1"), _agent_node("node-2")], "edges": []}
bindings = [
WorkflowAgentNodeBinding(
+ id=f"binding-{node_id}",
tenant_id="tenant-1",
app_id="app-1",
workflow_id="workflow-1",
- workflow_version="draft",
+ workflow_version=Workflow.VERSION_DRAFT,
node_id=node_id,
agent_id="agent-1",
current_snapshot_id="snapshot-1",
@@ -287,14 +341,11 @@ def test_export_workflow_packages_deduplicates_shared_agent(sqlite_session: Sess
)
for node_id in ("node-1", "node-2")
]
- sqlite_session.add_all(bindings)
- sqlite_session.flush()
- service = AgentDslService(sqlite_session)
- service._require_agent = Mock(return_value=_agent())
- service._require_snapshot = Mock(return_value=_snapshot())
+ sqlite_session.add_all([_agent(), _snapshot(), *bindings])
+ sqlite_session.commit()
- portable_graph, packages = service.export_workflow_packages(
- workflow=SimpleNamespace(tenant_id="tenant-1", id="workflow-1", version="draft"),
+ portable_graph, packages = AgentDslService(sqlite_session).export_workflow_packages(
+ workflow=_workflow(),
graph=graph,
)
@@ -305,13 +356,12 @@ def test_export_workflow_packages_deduplicates_shared_agent(sqlite_session: Sess
AGENT_PACKAGE_REF_KEY: "agent_1",
}
assert node["data"][AGENT_NODE_JOB_DSL_KEY]["workflow_prompt"] == node["id"]
- assert service._require_agent.call_count == 2
def test_export_workflow_packages_rejects_incomplete_binding(sqlite_session: Session) -> None:
with pytest.raises(ValueError, match="no complete persisted binding"):
AgentDslService(sqlite_session).export_workflow_packages(
- workflow=SimpleNamespace(tenant_id="tenant-1", id="workflow-1", version="draft"),
+ workflow=_workflow(),
graph={"nodes": [_agent_node("node-1")], "edges": []},
)
@@ -352,22 +402,23 @@ def test_import_agent_app_package_creates_config_and_unpublished_draft(
agent = _agent()
agent.active_config_snapshot_id = "snapshot-1"
agent.active_config_is_published = True
+ snapshot = _snapshot(soul=soul)
roster_service = Mock()
- roster_service.create_backing_agent_for_app.return_value = agent
+
+ def create_backing_agent(**_kwargs: object) -> Agent:
+ sqlite_session.add_all([agent, snapshot])
+ sqlite_session.flush()
+ return agent
+
+ roster_service.create_backing_agent_for_app.side_effect = create_backing_agent
monkeypatch.setattr("services.agent.dsl_service.AgentRosterService", Mock(return_value=roster_service))
- service._require_snapshot = Mock(return_value=_snapshot(soul=soul))
- app = SimpleNamespace(
- tenant_id="tenant-1",
- id="app-1",
- name="",
- description="",
- app_model_config=None,
- app_model_config_id=None,
- )
+ app = _app()
+ sqlite_session.add(app)
+ sqlite_session.commit()
result = service.import_agent_app_package(
app=app,
- account=SimpleNamespace(id="account-1"),
+ account=_account(),
package=make_portable_agent_package(_agent(), soul),
)
@@ -375,7 +426,15 @@ def test_import_agent_app_package_creates_config_and_unpublished_draft(
assert agent.active_config_is_published is False
assert app.name == "Portable Agent"
assert app.description == "description"
- assert sqlite_session.scalar(select(AgentConfigDraft).where(AgentConfigDraft.agent_id == agent.id)) is not None
+ assert app.app_model_config_id is not None
+ draft = sqlite_session.scalar(
+ select(AgentConfigDraft).where(
+ AgentConfigDraft.agent_id == agent.id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
+ )
+ )
+ assert draft is not None
+ assert draft.config_snapshot.config_note == "portable"
def test_import_workflow_packages_materializes_every_package_binding_as_inline(sqlite_session: Session) -> None:
@@ -406,7 +465,7 @@ def test_import_workflow_packages_materializes_every_package_binding_as_inline(s
tenant_id="tenant-1",
app_id="app-1",
workflow_id="workflow-1",
- workflow_version="draft",
+ workflow_version=Workflow.VERSION_DRAFT,
node_id="old-node",
binding_type=WorkflowAgentBindingType.INLINE_AGENT,
agent_id="old-inline-agent",
@@ -415,33 +474,34 @@ def test_import_workflow_packages_materializes_every_package_binding_as_inline(s
created_by="account-1",
)
sqlite_session.add(old_binding)
- sqlite_session.flush()
+ sqlite_session.commit()
service = AgentDslService(sqlite_session)
imported_results = [
- SimpleNamespace(
- agent=SimpleNamespace(id=f"inline-agent-{index}"),
- snapshot=SimpleNamespace(id=f"inline-snapshot-{index}"),
+ AgentPackageImportResult(
+ agent=_agent(
+ agent_id=f"inline-agent-{index}",
+ scope=AgentScope.WORKFLOW_ONLY,
+ source=AgentSource.IMPORTED,
+ ),
+ snapshot=_snapshot(
+ snapshot_id=f"inline-snapshot-{index}",
+ agent_id=f"inline-agent-{index}",
+ ),
warnings=[DslImportWarning(code=f"inline-{index}", path="agent", message="inline warning")],
)
for index in range(1, 4)
]
service._create_imported_inline_agent = Mock(side_effect=imported_results)
- workflow = SimpleNamespace(
- tenant_id="tenant-1",
- app_id="app-1",
- id="workflow-1",
- version="draft",
- graph="{}",
- )
+ workflow = _workflow()
result, warnings, retirement_candidates = service.import_workflow_packages(
workflow=workflow,
portable_graph=graph,
raw_packages={"agent_1": package.model_dump(mode="json")},
- account=SimpleNamespace(id="account-1"),
+ account=_account(),
)
- assert sqlite_session.get(WorkflowAgentNodeBinding, "old-binding") is None
+ assert sqlite_session.get(WorkflowAgentNodeBinding, old_binding.id) is None
assert retirement_candidates == {"old-inline-agent"}
assert service._create_imported_inline_agent.call_count == 3
assert [call.kwargs["node_id"] for call in service._create_imported_inline_agent.call_args_list] == [
@@ -460,7 +520,7 @@ def test_import_workflow_packages_materializes_every_package_binding_as_inline(s
assert AGENT_NODE_JOB_DSL_KEY not in result["nodes"][0]["data"]
assert json.loads(workflow.graph) == result
added_bindings = sqlite_session.scalars(
- select(WorkflowAgentNodeBinding).where(WorkflowAgentNodeBinding.workflow_id == "workflow-1")
+ select(WorkflowAgentNodeBinding).where(WorkflowAgentNodeBinding.workflow_id == workflow.id)
).all()
assert len(added_bindings) == 3
assert all(binding.binding_type == WorkflowAgentBindingType.INLINE_AGENT for binding in added_bindings)
@@ -477,23 +537,27 @@ def test_import_workflow_packages_materializes_every_package_binding_as_inline(s
],
)
def test_import_workflow_packages_rejects_invalid_package_binding(
- binding: dict, error: str, sqlite_session: Session
+ sqlite_session: Session, binding: dict, error: str
) -> None:
package = make_portable_agent_package(_agent(), AgentSoulConfig())
with pytest.raises(ValueError, match=error):
AgentDslService(sqlite_session).import_workflow_packages(
- workflow=SimpleNamespace(tenant_id="tenant-1", app_id="app-1", id="workflow-1", version="draft"),
+ workflow=_workflow(),
portable_graph={"nodes": [_agent_node("node-1", binding)], "edges": []},
raw_packages={"agent_1": package.model_dump(mode="json")},
- account=SimpleNamespace(id="account-1"),
+ account=_account(),
)
def test_clone_inline_binding_copies_soul(unbound_session: Session) -> None:
service = AgentDslService(unbound_session)
- target_agent = SimpleNamespace(id="target-agent")
- target_snapshot = SimpleNamespace(id="target-snapshot")
+ target_agent = _agent(
+ agent_id="target-agent",
+ scope=AgentScope.WORKFLOW_ONLY,
+ source=AgentSource.WORKFLOW,
+ )
+ target_snapshot = _snapshot(snapshot_id="target-snapshot", agent_id=target_agent.id)
service._create_workflow_only_agent = Mock(return_value=(target_agent, target_snapshot))
source_agent = _agent()
source_soul = AgentSoulConfig(
@@ -501,8 +565,8 @@ def test_clone_inline_binding_copies_soul(unbound_session: Session) -> None:
config_skills=[AgentConfigSkillRefConfig(name="summarizer", file_id="skill-file-1")],
config_files=[AgentConfigFileRefConfig(name="brief.pdf", file_kind="upload_file", file_id="config-file-1")],
)
- source_snapshot = SimpleNamespace(config_snapshot_dict=source_soul.model_dump(mode="json"))
- workflow = SimpleNamespace(tenant_id="tenant-1", app_id="app-1", id="workflow-1")
+ source_snapshot = _snapshot(soul=source_soul)
+ workflow = _workflow()
result = service.clone_inline_binding_for_node(
workflow=workflow,
@@ -594,12 +658,12 @@ def test_create_imported_inline_agent_uses_import_provenance(unbound_session: Se
warning = DslImportWarning(code="setup", path="agent", message="setup")
service._resolve_package_soul = Mock(return_value=(soul, [warning]))
service._create_workflow_only_agent = Mock(return_value=(_agent(), _snapshot(soul=soul)))
- workflow = SimpleNamespace(tenant_id="tenant-1", id="workflow-1")
+ workflow = _workflow()
result = service._create_imported_inline_agent(
workflow=workflow,
node_id="node-1",
- account=SimpleNamespace(id="account-1"),
+ account=_account(),
package=make_portable_agent_package(_agent(), soul),
package_path="agent_packages.agent_1",
)
@@ -616,11 +680,12 @@ def test_create_workflow_only_agent_sets_backing_app_and_snapshot(
) -> None:
service = AgentDslService(sqlite_session)
roster_service = Mock()
- roster_service.create_hidden_backing_app_for_workflow_agent.return_value = SimpleNamespace(id="backing-app")
+ backing_app = _app()
+ backing_app.id = "backing-app"
+ roster_service.create_hidden_backing_app_for_workflow_agent.return_value = backing_app
monkeypatch.setattr("services.agent.dsl_service.AgentRosterService", Mock(return_value=roster_service))
- service._create_snapshot = Mock(return_value=SimpleNamespace(id="snapshot-1"))
monkeypatch.setattr("services.agent.dsl_service.agent_soul_has_model", Mock(return_value=True))
- workflow = SimpleNamespace(tenant_id="tenant-1", app_id="app-1", id="workflow-1")
+ workflow = _workflow()
agent, snapshot = service._create_workflow_only_agent(
workflow=workflow,
@@ -632,17 +697,22 @@ def test_create_workflow_only_agent_sets_backing_app_and_snapshot(
operation=AgentConfigRevisionOperation.IMPORT_PACKAGE,
)
- assert snapshot.id == "snapshot-1"
+ assert sqlite_session.get(Agent, agent.id) is agent
+ assert sqlite_session.get(AgentConfigSnapshot, snapshot.id) is snapshot
assert agent.scope == AgentScope.WORKFLOW_ONLY
assert agent.backing_app_id == "backing-app"
- assert agent.active_config_snapshot_id == "snapshot-1"
+ assert agent.active_config_snapshot_id == snapshot.id
assert agent.active_config_has_model is True
assert agent.active_config_is_published is True
- assert sqlite_session.get(Agent, agent.id) is agent
+ revision = sqlite_session.scalar(
+ select(AgentConfigRevision).where(AgentConfigRevision.current_snapshot_id == snapshot.id)
+ )
+ assert revision is not None
+ assert revision.operation == AgentConfigRevisionOperation.IMPORT_PACKAGE
def test_resolve_package_soul_preserves_existing_and_marks_missing_knowledge(
- monkeypatch: pytest.MonkeyPatch, unbound_session: Session
+ monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
) -> None:
soul = AgentSoulConfig.model_validate(
{
@@ -664,17 +734,23 @@ def test_resolve_package_soul_preserves_existing_and_marks_missing_knowledge(
},
}
)
- get_dataset_rows = Mock(return_value={"existing": SimpleNamespace(id="existing")})
+ existing_dataset = Dataset(
+ id="existing",
+ tenant_id="tenant-1",
+ name="Existing",
+ created_by="account-1",
+ )
+ get_dataset_rows = Mock(return_value={"existing": existing_dataset})
monkeypatch.setattr("services.agent.dsl_service.get_tenant_knowledge_dataset_rows", get_dataset_rows)
- resolved, warnings = AgentDslService(unbound_session)._resolve_package_soul(
+ resolved, warnings = AgentDslService(sqlite_session)._resolve_package_soul(
tenant_id="tenant-1",
package=make_portable_agent_package(_agent(), soul),
package_path="agent_packages.agent_1",
)
get_dataset_rows.assert_called_once_with(
- session=unbound_session,
+ session=sqlite_session,
tenant_id="tenant-1",
dataset_ids=["existing", "missing"],
)
@@ -710,11 +786,14 @@ def test_resolve_package_soul_preserves_existing_and_marks_missing_knowledge(
def test_create_snapshot_increments_version_and_records_revision(sqlite_session: Session) -> None:
agent = _agent()
- first = _snapshot(snapshot_id="snapshot-1")
- second = _snapshot(snapshot_id="snapshot-2")
- second.version = 2
- sqlite_session.add_all([agent, first, second])
- sqlite_session.flush()
+ sqlite_session.add_all(
+ [
+ agent,
+ _snapshot(snapshot_id="snapshot-1", version=1),
+ _snapshot(snapshot_id="snapshot-2", version=2),
+ ]
+ )
+ sqlite_session.commit()
service = AgentDslService(sqlite_session)
snapshot = service._create_snapshot(
@@ -727,6 +806,7 @@ def test_create_snapshot_increments_version_and_records_revision(sqlite_session:
assert snapshot.version == 3
assert snapshot.home_snapshot_id is None
+ assert sqlite_session.get(AgentConfigSnapshot, snapshot.id) is snapshot
revision = sqlite_session.scalar(
select(AgentConfigRevision).where(AgentConfigRevision.current_snapshot_id == snapshot.id)
)
@@ -735,12 +815,14 @@ def test_create_snapshot_increments_version_and_records_revision(sqlite_session:
def test_unique_roster_name_uses_first_available_suffix(sqlite_session: Session) -> None:
- for index, name in enumerate(("Agent", "Agent import"), start=1):
- agent = _agent()
- agent.id = f"agent-{index}"
- agent.name = name
- sqlite_session.add(agent)
- sqlite_session.flush()
+ sqlite_session.add_all(
+ [
+ _agent(agent_id="agent-1", name="Agent"),
+ _agent(agent_id="agent-2", name="Agent import"),
+ _agent(agent_id="decoy-agent", name="Agent import 2", scope=AgentScope.WORKFLOW_ONLY),
+ ]
+ )
+ sqlite_session.commit()
result = AgentDslService(sqlite_session)._unique_roster_name(tenant_id="tenant-1", requested="Agent")
@@ -748,11 +830,11 @@ def test_unique_roster_name_uses_first_available_suffix(sqlite_session: Session)
def test_require_helpers_and_graph_detection(sqlite_session: Session) -> None:
- service = AgentDslService(sqlite_session)
agent = _agent()
snapshot = _snapshot()
sqlite_session.add_all([agent, snapshot])
- sqlite_session.flush()
+ sqlite_session.commit()
+ service = AgentDslService(sqlite_session)
assert service._require_agent(tenant_id="tenant-1", agent_id="agent-1") is agent
with pytest.raises(ValueError, match="source Agent"):
diff --git a/api/tests/unit_tests/services/agent/test_home_snapshot_service.py b/api/tests/unit_tests/services/agent/test_home_snapshot_service.py
index 3b2a638f692..444959aec09 100644
--- a/api/tests/unit_tests/services/agent/test_home_snapshot_service.py
+++ b/api/tests/unit_tests/services/agent/test_home_snapshot_service.py
@@ -4,6 +4,7 @@ from unittest.mock import MagicMock
import pytest
from dify_agent.client import DifyAgentHTTPError, DifyAgentNotFoundError, DifyAgentTimeoutError
+from sqlalchemy import select
from sqlalchemy.orm import Session
from models.agent import (
@@ -11,11 +12,15 @@ from models.agent import (
AgentConfigDraft,
AgentConfigDraftType,
AgentConfigSnapshot,
+ AgentConfigVersionKind,
AgentHomeSnapshot,
AgentScope,
AgentSource,
AgentStatus,
AgentWorkingResourceStatus,
+ AgentWorkspace,
+ AgentWorkspaceBinding,
+ AgentWorkspaceOwnerType,
)
from models.agent_config_entities import AgentSoulConfig
from services.agent.errors import (
@@ -24,7 +29,7 @@ from services.agent.errors import (
AgentHomeSnapshotTooLargeError,
)
from services.agent.home_snapshot_service import AgentHomeSnapshotService, validate_home_snapshot_binding
-from services.agent.workspace_service import AgentWorkspaceService
+from services.agent.workspace_service import AgentWorkspaceBindingGenerationMismatchError, AgentWorkspaceService
from tests.unit_tests.config_override import apply_config_overrides
@@ -56,24 +61,6 @@ def test_home_snapshot_client_outlasts_the_gateway_snapshot_budget(monkeypatch:
assert client._timeout == 45.0
-def _persist_agent(session: Session, *, app_id: str, backing_app_id: str | None) -> Agent:
- agent = Agent(
- id="agent-1",
- tenant_id="tenant-1",
- name="Snapshot Agent",
- description="",
- role="",
- scope=AgentScope.ROSTER if backing_app_id is None else AgentScope.WORKFLOW_ONLY,
- source=AgentSource.AGENT_APP if backing_app_id is None else AgentSource.WORKFLOW,
- status=AgentStatus.ACTIVE,
- app_id=app_id,
- backing_app_id=backing_app_id,
- )
- session.add(agent)
- session.commit()
- return agent
-
-
def test_validate_home_snapshot_binding_accepts_default_home_without_ledger_lookup(unbound_session: Session) -> None:
validate_home_snapshot_binding(
session=unbound_session,
@@ -82,6 +69,55 @@ def test_validate_home_snapshot_binding_accepts_default_home_without_ledger_look
)
+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"),
[
@@ -96,56 +132,76 @@ def test_build_apply_checkpoints_exact_active_binding(
backing_app_id: str | None,
expected_runtime_app_id: str,
) -> None:
- _persist_agent(sqlite_session, app_id=app_id, backing_app_id=backing_app_id)
- binding = SimpleNamespace(
- backend_binding_ref="binding-ref-1",
- agent_id="agent-1",
- base_home_snapshot_id="home-old",
- agent_config_version_id="build-1",
- agent_config_version_kind="build_draft",
- )
- get_binding = MagicMock(return_value=binding)
+ _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))
- monkeypatch.setattr(AgentWorkspaceService, "get_active_binding", get_binding)
- validate_generation = MagicMock()
- monkeypatch.setattr(AgentWorkspaceService, "validate_binding_generation", validate_generation)
snapshot = AgentHomeSnapshotService.create_for_build_apply(
session=sqlite_session,
build_draft=_build_draft(),
)
+ sqlite_session.flush()
- assert get_binding.call_args.kwargs["binding_id"] == "binding-1"
- assert get_binding.call_args.kwargs["expected_owner_scope"].app_id == expected_runtime_app_id
+ 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"
- assert validate_generation.call_args.kwargs["base_home_snapshot_id"] == "home-old"
+ 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_agent(sqlite_session, app_id="app-1", backing_app_id=None)
- binding = SimpleNamespace(
- backend_binding_ref="binding-ref-1",
- agent_id="agent-1",
- base_home_snapshot_id=None,
- agent_config_version_id="build-1",
- agent_config_version_kind="build_draft",
- )
+ _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")
- validate_generation = MagicMock()
monkeypatch.setattr(AgentHomeSnapshotService, "_client", lambda: nullcontext(client))
- monkeypatch.setattr(AgentWorkspaceService, "get_active_binding", MagicMock(return_value=binding))
- monkeypatch.setattr(AgentWorkspaceService, "validate_binding_generation", validate_generation)
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 validate_generation.call_args.kwargs["base_home_snapshot_id"] is None
+ assert sqlite_session.get(AgentHomeSnapshot, snapshot.id) is snapshot
+
+
+ ("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:
diff --git a/api/tests/unit_tests/services/agent/test_workspace_service.py b/api/tests/unit_tests/services/agent/test_workspace_service.py
index cfa7d56a708..4758a20410a 100644
--- a/api/tests/unit_tests/services/agent/test_workspace_service.py
+++ b/api/tests/unit_tests/services/agent/test_workspace_service.py
@@ -5,7 +5,7 @@ from unittest.mock import MagicMock
import pytest
from sqlalchemy import select
-from sqlalchemy.orm import Session
+from sqlalchemy.orm import Session, sessionmaker
from models.agent import (
AgentConfigVersionKind,
@@ -316,13 +316,14 @@ def test_retire_workspace_retires_all_active_bindings(sqlite_session: Session) -
workspace = _workspace()
bindings = [_binding(), _binding(binding_id="binding-2", agent_id="agent-2")]
sqlite_session.add_all([workspace, *bindings])
- sqlite_session.flush()
+ 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
@@ -422,16 +423,15 @@ def test_retire_all_for_app_retires_only_active_workspaces_for_that_app(sqlite_s
def test_collect_binding_without_retired_workspace_destroys_binding_only(
- monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+ 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(
- "services.agent.workspace_service.session_factory.create_session", lambda: nullcontext(sqlite_session)
- )
monkeypatch.setattr(AgentWorkspaceService, "_client", lambda: nullcontext(client))
AgentWorkspaceService.collect_retired_binding(tenant_id="tenant-1", binding_id=binding.id)
@@ -440,12 +440,14 @@ def test_collect_binding_without_retired_workspace_destroys_binding_only(
assert request.binding_ref == binding.backend_binding_ref
assert request.destroy_workspace is False
assert request.workspace_ref is None
- assert sqlite_session.get(AgentWorkspaceBinding, binding.id) is None
- assert sqlite_session.get(AgentWorkspace, workspace.id) is not 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
+ monkeypatch: pytest.MonkeyPatch,
+ sqlite_session: Session,
) -> None:
workspace = _workspace(status=AgentWorkingResourceStatus.RETIRED)
anchor = _binding(status=AgentWorkingResourceStatus.RETIRED)
diff --git a/api/tests/unit_tests/services/test_workspace_service.py b/api/tests/unit_tests/services/test_workspace_service.py
index 3a63cfc985b..9dc8789ab67 100644
--- a/api/tests/unit_tests/services/test_workspace_service.py
+++ b/api/tests/unit_tests/services/test_workspace_service.py
@@ -1,17 +1,30 @@
from types import SimpleNamespace
-from unittest.mock import MagicMock, call, patch
+from unittest.mock import call, patch
+
+from sqlalchemy.orm import Session
from enums import CloudPlan, DeploymentEdition
-from models.account import Tenant
+from models.account import Tenant, TenantAccountJoin, TenantAccountRole
from services.credit_pool_service import CreditPoolBalance
from services.workspace_service import WorkspaceService
-def test_get_current_workspace_summary_sandbox_uses_trial_only() -> None:
+def _persist_membership(session: Session, *, role: TenantAccountRole) -> Tenant:
tenant = Tenant(name="Workspace")
- membership = SimpleNamespace(role="owner")
- session = MagicMock()
- session.scalar.return_value = membership
+ session.add_all(
+ [
+ tenant,
+ TenantAccountJoin(tenant_id=tenant.id, account_id="account-1", role=role),
+ TenantAccountJoin(tenant_id=tenant.id, account_id="decoy-account", role=TenantAccountRole.NORMAL),
+ TenantAccountJoin(tenant_id="decoy-tenant", account_id="account-1", role=TenantAccountRole.NORMAL),
+ ]
+ )
+ session.commit()
+ return tenant
+
+
+def test_get_current_workspace_summary_sandbox_uses_trial_only(sqlite_session: Session) -> None:
+ tenant = _persist_membership(sqlite_session, role=TenantAccountRole.OWNER)
trial_pool = CreditPoolBalance(
tenant_id=tenant.id,
pool_type="trial",
@@ -29,7 +42,7 @@ def test_get_current_workspace_summary_sandbox_uses_trial_only() -> None:
patch("services.credit_pool_service.CreditPoolService.get_pool", return_value=trial_pool) as get_pool,
patch("services.workspace_service.FeatureService.get_features") as get_features,
):
- result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=session)
+ result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=sqlite_session)
assert result == {
"id": tenant.id,
@@ -39,14 +52,12 @@ def test_get_current_workspace_summary_sandbox_uses_trial_only() -> None:
"credits": 180,
}
get_info.assert_called_once_with(tenant.id, exclude_vector_space=True)
- get_pool.assert_called_once_with(tenant_id=tenant.id, pool_type="trial", session=session)
+ get_pool.assert_called_once_with(tenant_id=tenant.id, pool_type="trial", session=sqlite_session)
get_features.assert_not_called()
-def test_get_current_workspace_summary_falls_back_from_exhausted_paid_pool() -> None:
- tenant = Tenant(name="Workspace")
- session = MagicMock()
- session.scalar.return_value = SimpleNamespace(role="admin")
+def test_get_current_workspace_summary_falls_back_from_exhausted_paid_pool(sqlite_session: Session) -> None:
+ tenant = _persist_membership(sqlite_session, role=TenantAccountRole.ADMIN)
paid_pool = CreditPoolBalance(
tenant_id=tenant.id,
pool_type="paid",
@@ -72,20 +83,18 @@ def test_get_current_workspace_summary_falls_back_from_exhausted_paid_pool() ->
side_effect=[paid_pool, trial_pool],
) as get_pool,
):
- result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=session)
+ result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=sqlite_session)
assert result["plan"] == CloudPlan.TEAM
assert result["credits"] == 60
assert get_pool.call_args_list == [
- call(tenant_id=tenant.id, pool_type="paid", session=session),
- call(tenant_id=tenant.id, pool_type="trial", session=session),
+ call(tenant_id=tenant.id, pool_type="paid", session=sqlite_session),
+ call(tenant_id=tenant.id, pool_type="trial", session=sqlite_session),
]
-def test_get_current_workspace_summary_non_cloud_skips_billing_and_credits() -> None:
- tenant = Tenant(name="Workspace")
- session = MagicMock()
- session.scalar.return_value = SimpleNamespace(role="editor")
+def test_get_current_workspace_summary_non_cloud_skips_billing_and_credits(sqlite_session: Session) -> None:
+ tenant = _persist_membership(sqlite_session, role=TenantAccountRole.EDITOR)
config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
with (
@@ -93,7 +102,7 @@ def test_get_current_workspace_summary_non_cloud_skips_billing_and_credits() ->
patch("services.workspace_service.BillingService.get_info") as get_info,
patch("services.credit_pool_service.CreditPoolService.get_pool") as get_pool,
):
- result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=session)
+ result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=sqlite_session)
assert result == {
"id": tenant.id,