from __future__ import annotations import pytest from backend.dto.common import ApiError from backend.services.character_workflow_service import CharacterWorkflowService from backend.services.node_dependency_context_service import NodeDependencyContextService from backend.services.workflow_service import WorkflowService from core.audit_service import AuditService from core.identity import RequestContext from database.db_helper import Database, DatabaseSettings, SqliteSettings from database.repositories.profile_repository import ProfileRepository from database.repositories.workflow_repository import WorkflowRepository def _fixture(tmp_path): database = Database( DatabaseSettings( backend="sqlite", sqlite=SqliteSettings(path=str(tmp_path / "branch-lineage.sqlite3")), ) ) database.initialize() profiles = ProfileRepository(database) profiles.create( { "profile_id": "profile-branch", "name": "Branch test", "base_prompt": "one character", "appearance_prompt": "black hair", "style_prompt": "anime", "negative_prompt": "low quality", "owner_platform": "webui", "owner_user_id": "system", "status": "active", "metadata": {}, } ) service = WorkflowService( workflow_repository=WorkflowRepository(database), profile_repository=profiles, audit_service=AuditService(database), ) detail = service.create_workflow( "profile-branch", { "workflow_id": "workflow-branch", "workflow_type": "character_gradual", "display_name": "Branch workflow", }, RequestContext.system("branch-test"), ) return database, service, detail.workflow.workflow_id, RequestContext.system("branch-test") def _nodes(service: WorkflowService, workflow_id: str, branch_name: str = "main"): return { node.node_key: node for node in service.list_nodes(workflow_id) if node.branch_name == branch_name } def _confirm_import_and_profile(service: WorkflowService, workflow_id: str, ctx: RequestContext) -> None: CharacterWorkflowService(service).execute_workflow(workflow_id, ctx) profile_brief = _nodes(service, workflow_id)["profile_brief"] service.update_node(profile_brief.node_id, {"status": "completed"}, ctx) def _complete_prompt_plan( service: WorkflowService, workflow_id: str, branch_name: str, ctx: RequestContext, label: str, ) -> None: node = _nodes(service, workflow_id, branch_name)["prompt_plan"] service.update_node( node.node_id, { "prompt": label, "metadata": { **node.metadata, "prompt_plan": { "matrix": [ { "target": "portrait", "positive_prompt": label, } ] }, }, }, ctx, ) service.update_node(node.node_id, {"status": "completed"}, ctx) def _complete_material_bind( service: WorkflowService, workflow_id: str, branch_name: str, ctx: RequestContext, ) -> None: node = _nodes(service, workflow_id, branch_name)["material_bind"] service.update_node( node.node_id, { "metadata": { **node.metadata, "material_bindings": {"selected_material_ids": [], "rules": []}, } }, ctx, ) service.update_node(node.node_id, {"status": "completed"}, ctx) def test_branch_list_keeps_main_and_rejects_unfinished_base(tmp_path) -> None: _database, service, workflow_id, ctx = _fixture(tmp_path) draft = _nodes(service, workflow_id)["profile_brief"] with pytest.raises(ApiError) as captured: service.create_branch( workflow_id, { "branch_name": "draft-branch", "base_branch_name": "main", "base_node_id": draft.node_id, }, ctx, ) assert captured.value.details["reason"] == "workflow_branch_base_not_completed" _confirm_import_and_profile(service, workflow_id, ctx) _complete_prompt_plan(service, workflow_id, "main", ctx, "main portrait") prompt = _nodes(service, workflow_id)["prompt_plan"] branch = service.create_branch( workflow_id, { "branch_name": "green", "base_branch_name": "main", "base_node_id": prompt.node_id, }, ctx, ) assert branch.branch_name == "green" assert [item.branch_name for item in service.list_branches(workflow_id)] == ["main", "green"] copied = _nodes(service, workflow_id, "green") assert copied["profile_brief"].status == "completed" assert copied["profile_brief"].metadata["branch_locked_ancestor"] is True assert copied["prompt_plan"].status == "draft" def test_branch_parent_validation_and_archived_workflow_guard(tmp_path) -> None: _database, service, workflow_id, ctx = _fixture(tmp_path) _confirm_import_and_profile(service, workflow_id, ctx) profile = _nodes(service, workflow_id)["profile_brief"] with pytest.raises(ApiError) as missing_parent: service.create_branch( workflow_id, { "branch_name": "child", "base_branch_name": "missing", "base_node_id": profile.node_id, }, ctx, ) assert missing_parent.value.details["reason"] == "workflow_branch_parent_missing" with pytest.raises(ApiError) as self_parent: service.create_branch( workflow_id, { "branch_name": "self", "base_branch_name": "self", "base_node_id": profile.node_id, }, ctx, ) assert self_parent.value.details["reason"] == "workflow_branch_self_parent" with pytest.raises(ApiError) as bad_status: service.create_branch( workflow_id, { "branch_name": "bad-status", "base_branch_name": "main", "base_node_id": profile.node_id, "status": "deleted", }, ctx, ) assert bad_status.value.details["field"] == "status" service.update_workflow(workflow_id, {"status": "archived"}, ctx) with pytest.raises(ApiError) as archived_node: service.update_node(profile.node_id, {"prompt": "forbidden"}, ctx) assert archived_node.value.details["reason"] == "workflow_archived_read_only" with pytest.raises(ApiError) as archived_branch: service.create_branch( workflow_id, { "branch_name": "after-archive", "base_branch_name": "main", "base_node_id": profile.node_id, }, ctx, ) assert archived_branch.value.details["reason"] == "workflow_archived_read_only" def test_nested_branch_dependencies_resolve_main_then_parent_branch(tmp_path) -> None: _database, service, workflow_id, ctx = _fixture(tmp_path) _confirm_import_and_profile(service, workflow_id, ctx) _complete_prompt_plan(service, workflow_id, "main", ctx, "main portrait") main_prompt = _nodes(service, workflow_id)["prompt_plan"] service.create_branch( workflow_id, { "branch_name": "green", "base_branch_name": "main", "base_node_id": main_prompt.node_id, }, ctx, ) service.switch_branch(workflow_id, "green", ctx) _complete_prompt_plan(service, workflow_id, "green", ctx, "green portrait") _complete_material_bind(service, workflow_id, "green", ctx) green_material = _nodes(service, workflow_id, "green")["material_bind"] service.create_branch( workflow_id, { "branch_name": "blue", "base_branch_name": "green", "base_node_id": green_material.node_id, }, ctx, ) service.switch_branch(workflow_id, "blue", ctx) blue_headshot = _nodes(service, workflow_id, "blue")["headshot"] context = NodeDependencyContextService(service).get_context(blue_headshot.node_id) by_key = {item["node_key"]: item for item in context["dependencies"]} assert context["branch_lineage"] == ["blue", "green", "main"] assert by_key["profile_brief"]["inherited"] is True assert by_key["profile_brief"]["source_branch"] == "main" assert by_key["prompt_plan"]["inherited"] is True assert by_key["prompt_plan"]["source_branch"] == "green" assert by_key["prompt_plan"]["prompt"] == "green portrait" def test_branch_state_switch_restores_branch_specific_stage_inputs(tmp_path) -> None: _database, service, workflow_id, ctx = _fixture(tmp_path) _confirm_import_and_profile(service, workflow_id, ctx) _complete_prompt_plan(service, workflow_id, "main", ctx, "main portrait") main_workflow = service.get_workflow(workflow_id).workflow main_workflow = service.update_workflow( workflow_id, { "metadata": { **main_workflow.metadata, "stage_inputs": {"main-stage": {"image_id": "main-image"}}, } }, ctx, ) main_prompt = _nodes(service, workflow_id)["prompt_plan"] service.create_branch( workflow_id, { "branch_name": "green", "base_branch_name": "main", "base_node_id": main_prompt.node_id, }, ctx, ) green = service.switch_branch(workflow_id, "green", ctx) green = service.update_workflow( workflow_id, { "metadata": { **green.metadata, "stage_inputs": {"green-stage": {"image_id": "green-image"}}, } }, ctx, ) assert green.metadata["stage_inputs"] == {"green-stage": {"image_id": "green-image"}} main_again = service.switch_branch(workflow_id, "main", ctx) assert main_again.metadata["stage_inputs"] == {"main-stage": {"image_id": "main-image"}} assert main_again.metadata["branch_state"]["green"]["stage_inputs"] == { "green-stage": {"image_id": "green-image"} } def test_repository_branch_and_node_copy_is_atomic(tmp_path) -> None: database, service, workflow_id, _ctx = _fixture(tmp_path) repository = WorkflowRepository(database) duplicate_node_id = "node-duplicate" node_payload = { "node_id": duplicate_node_id, "workflow_id": workflow_id, "node_key": "copy-one", "title": "Copy one", "node_type": "planning", "status": "draft", "branch_name": "atomic", "sort_order": 10, "metadata": {}, } with pytest.raises(Exception): repository.create_branch_with_nodes( { "branch_id": "branch-atomic", "workflow_id": workflow_id, "branch_name": "atomic", "base_branch_name": "main", "base_node_id": _nodes(service, workflow_id)["profile_brief"].node_id, "status": "active", "metadata": {}, }, [node_payload, {**node_payload, "node_key": "copy-two"}], ) assert repository.get_branch(workflow_id, "atomic") is None assert repository.get_node(duplicate_node_id) is None