feat: Phase 3 - Logic Nodes + Conditional Branching
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s

Backend:
- logic_evaluator.py (NEU, 307 Zeilen): Deterministischer Logic Evaluator
  - Vergleichsoperatoren: EQ, NEQ, IN, NOT_IN, GT, LT, GTE, LTE, CONTAINS
  - Logische Operatoren: AND, OR, NOT mit Verschachtelung
  - Resolve signal references (node_id.question_type)
  - Error handling für UNCLEAR/INVALID/NOT_DECIDABLE Signale

- workflow_executor.py (ERWEITERT):
  - execute_logic_node(): Bedingungen evaluieren, Pfade aktivieren/deaktivieren
  - execute_workflow(): BFS-Traversierung mit Edge-Activation statt Sequential
  - _apply_fallback(): 4 Fallback-Strategien (CONSERVATIVE_SKIP, DEFAULT_PATH, UNCERTAINTY_PATH, DOCUMENT_ONLY)
  - _has_active_incoming_edge(): Prüft ob Node erreichbar ist
  - _get_edges_by_label(): Findet then/else/uncertainty Pfade

- workflow_models.py (ERWEITERT):
  - LogicOperator.CONTAINS hinzugefügt

- version.py: 0.9k → 0.9l, workflow 0.3.0 → 0.4.0

Tests:
- test_phase3_logic_evaluator.py (NEU): 20 Unit Tests (alle passing)
  - Comparison operators (EQ, NEQ, IN, GT, LT, CONTAINS)
  - Logical operators (AND, OR, NOT)
  - Nested expressions
  - Error handling (missing refs, UNCLEAR/INVALID signals)

- test_phase2_workflow_executor.py (AKTUALISIERT): 11 Tests (alle passing)
  - execute_node() graph parameter hinzugefügt (Phase 3 requirement)
  - test_execute_node_unknown_type: logic → join (logic jetzt implementiert)

- test_phase3_workflow_branching.py (NEU): Integration Tests vorbereitet
  - Erfordert vollständige DB-Mock-Strategie (wird in E2E-Test nachgeholt)

Phase 2 Backward Compatibility: ✅ Alle Phase 2 Tests bestehen weiterhin

Konzept: .claude/task/Workflow_engine_prompting_engine/konzept_workflow_engine_konsolidated.md
Anforderungsanalyse: .claude/task/Workflow_engine_prompting_engine/phase3_anforderungsanalyse.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 4.6 committed 2026-04-04 08:02:22 +02:00
1 parent 16dc08cd7d
commit 2ce0874dcb
7 files changed
+1735 -41

No files matched your search

+19 -14
View File
@@ -192,24 +192,25 @@ def test_aggregate_results_formatting():
async def test_execute_node_start_end():
"""Test: Start/End Nodes sind No-Ops"""
from workflow_executor import execute_node
from workflow_models import WorkflowNode
from workflow_models import WorkflowNode, WorkflowGraph
start_node = WorkflowNode(id="start", type="start")
end_node = WorkflowNode(id="end", type="end")
context = {"variables": {}, "profile_id": "test"}
catalog = {}
mock_graph = WorkflowGraph(nodes=[], edges=[]) # Phase 3: graph parameter required
async def mock_llm(prompt, model):
return "should not be called"
# Test start
result = await execute_node(start_node, context, catalog, mock_llm)
result = await execute_node(start_node, context, catalog, mock_graph, mock_llm)
assert result.status == NodeStatus.EXECUTED
assert result.analysis_core is None
# Test end
result = await execute_node(end_node, context, catalog, mock_llm)
result = await execute_node(end_node, context, catalog, mock_graph, mock_llm)
assert result.status == NodeStatus.EXECUTED
assert result.analysis_core is None
@@ -218,29 +219,30 @@ async def test_execute_node_start_end():
async def test_execute_node_unknown_type():
"""Test: Unbekannter Node-Typ wirft Fehler"""
from workflow_executor import execute_node
from workflow_models import WorkflowNode
from workflow_models import WorkflowNode, WorkflowGraph
# Phase 2 unterstützt nur start, end, analysis
logic_node = WorkflowNode(id="logic1", type="logic")
# Phase 3: logic is now implemented, test with join instead
join_node = WorkflowNode(id="join1", type="join")
context = {"variables": {}, "profile_id": "test"}
catalog = {}
mock_graph = WorkflowGraph(nodes=[], edges=[])
async def mock_llm(prompt, model):
return ""
result = await execute_node(logic_node, context, catalog, mock_llm)
result = await execute_node(join_node, context, catalog, mock_graph, mock_llm)
# Sollte FAILED sein mit Fehlermeldung
assert result.status == NodeStatus.FAILED
assert "not implemented in Phase 2" in result.error
assert "not implemented" in result.error.lower() or "phase 4" in result.error.lower()
@pytest.mark.asyncio
async def test_execute_node_analysis_simple():
"""Test: Analysis Node ohne Fragenergänzung"""
from workflow_executor import execute_node
from workflow_models import WorkflowNode
from workflow_models import WorkflowNode, WorkflowGraph
node = WorkflowNode(
id="test_node",
@@ -251,6 +253,7 @@ async def test_execute_node_analysis_simple():
context = {"variables": {"name": "Test"}, "profile_id": "test"}
catalog = {}
mock_graph = WorkflowGraph(nodes=[], edges=[])
# Mock LLM
async def mock_llm(prompt, model):
@@ -260,7 +263,7 @@ async def test_execute_node_analysis_simple():
with patch('workflow_executor.load_prompt_template') as mock_load:
mock_load.return_value = "Test prompt for {{name}}"
result = await execute_node(node, context, catalog, mock_llm)
result = await execute_node(node, context, catalog, mock_graph, mock_llm)
assert result.status == NodeStatus.EXECUTED
assert result.analysis_core == "Test analysis content"
@@ -271,7 +274,7 @@ async def test_execute_node_analysis_simple():
async def test_execute_node_analysis_with_questions():
"""Test: Analysis Node mit Fragenergänzung und Normalisierung"""
from workflow_executor import execute_node
from workflow_models import WorkflowNode, QuestionAugmentation
from workflow_models import WorkflowNode, QuestionAugmentation, WorkflowGraph
node = WorkflowNode(
id="test_node",
@@ -294,6 +297,7 @@ async def test_execute_node_analysis_with_questions():
"normalization_rules": None
}
}
mock_graph = WorkflowGraph(nodes=[], edges=[])
# Mock LLM
async def mock_llm(prompt, model):
@@ -309,7 +313,7 @@ Test analysis
with patch('workflow_executor.load_prompt_template') as mock_load:
mock_load.return_value = "Base prompt"
result = await execute_node(node, context, catalog, mock_llm)
result = await execute_node(node, context, catalog, mock_graph, mock_llm)
assert result.status == NodeStatus.EXECUTED
assert result.analysis_core == "Test analysis"
@@ -330,7 +334,7 @@ async def test_execute_node_hybrid_model_override():
Regression-Test für: https://github.com/anthropics/claude-code/issues/XXX
"""
from workflow_executor import execute_node
from workflow_models import WorkflowNode, QuestionAugmentation
from workflow_models import WorkflowNode, QuestionAugmentation, WorkflowGraph
# Node mit ANDEREM Spektrum als Catalog
node = WorkflowNode(
@@ -356,6 +360,7 @@ async def test_execute_node_hybrid_model_override():
"normalization_rules": None
}
}
mock_graph = WorkflowGraph(nodes=[], edges=[])
# Mock LLM gibt "decrease" zurück (gültig für Node, ungültig für Catalog)
async def mock_llm(prompt, model):
@@ -370,7 +375,7 @@ Gewicht gesunken
with patch('workflow_executor.load_prompt_template') as mock_load:
mock_load.return_value = "Base prompt"
result = await execute_node(node, context, catalog, mock_llm)
result = await execute_node(node, context, catalog, mock_graph, mock_llm)
# Assertions: "decrease" muss VALID sein (Node-Spektrum), nicht INVALID (Catalog)
assert result.status == NodeStatus.EXECUTED
@@ -0,0 +1,720 @@
"""
Unit Tests für logic_evaluator.py (Phase 3)
Run with: PYTHONPATH=./backend pytest tests/backend/test_phase3_logic_evaluator.py -v
"""
import pytest
from logic_evaluator import (
evaluate_logic_expression,
resolve_signal_reference,
compare_values
)
from workflow_models import (
LogicExpression,
LogicOperator,
NormalizedSignal,
SignalStatus,
NodeExecutionState,
NodeStatus
)
# ── Comparison Operator Tests ──────────────────────────────────────────────────
def test_evaluate_eq_true():
"""Test: EQ operator - match"""
expression = LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="decrease"
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True
assert error is None
def test_evaluate_eq_false():
"""Test: EQ operator - no match"""
expression = LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="increase"
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is False
assert error is None
def test_evaluate_neq():
"""Test: NEQ operator"""
expression = LogicExpression(
operator=LogicOperator.NEQ,
ref="body.relevanz",
value="stable"
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True
assert error is None
def test_evaluate_in_true():
"""Test: IN operator - value in list"""
expression = LogicExpression(
operator=LogicOperator.IN,
ref="body.prioritaet",
value=["hoch", "mittel"]
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="prioritaet",
raw_value="hoch",
normalized_value="hoch",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True
assert error is None
def test_evaluate_in_false():
"""Test: IN operator - value not in list"""
expression = LogicExpression(
operator=LogicOperator.IN,
ref="body.prioritaet",
value=["hoch", "mittel"]
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="prioritaet",
raw_value="niedrig",
normalized_value="niedrig",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is False
assert error is None
def test_evaluate_gt():
"""Test: GT operator - greater than"""
expression = LogicExpression(
operator=LogicOperator.GT,
ref="body.score",
value=50
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="score",
raw_value="75",
normalized_value="75",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True
assert error is None
def test_evaluate_lt():
"""Test: LT operator - less than"""
expression = LogicExpression(
operator=LogicOperator.LT,
ref="body.score",
value=50
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="score",
raw_value="25",
normalized_value="25",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True
assert error is None
def test_evaluate_contains_string():
"""Test: CONTAINS operator - string contains substring"""
expression = LogicExpression(
operator=LogicOperator.CONTAINS,
ref="body.kategorie",
value="Gewicht"
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="kategorie",
raw_value="Gewichtsverlust positiv",
normalized_value="Gewichtsverlust positiv",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True
assert error is None
# ── Logical Operator Tests ──────────────────────────────────────────────────
def test_evaluate_and_both_true():
"""Test: AND operator - both operands true"""
expression = LogicExpression(
operator=LogicOperator.AND,
operands=[
LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="decrease"
),
LogicExpression(
operator=LogicOperator.EQ,
ref="activity.intensitaet",
value="hoch"
)
]
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
),
"activity": NodeExecutionState(
node_id="activity",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="intensitaet",
raw_value="hoch",
normalized_value="hoch",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True
assert error is None
def test_evaluate_and_one_false():
"""Test: AND operator - one operand false"""
expression = LogicExpression(
operator=LogicOperator.AND,
operands=[
LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="decrease"
),
LogicExpression(
operator=LogicOperator.EQ,
ref="activity.intensitaet",
value="niedrig"
)
]
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
),
"activity": NodeExecutionState(
node_id="activity",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="intensitaet",
raw_value="hoch",
normalized_value="hoch",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is False
assert error is None
def test_evaluate_or_one_true():
"""Test: OR operator - one operand true"""
expression = LogicExpression(
operator=LogicOperator.OR,
operands=[
LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="decrease"
),
LogicExpression(
operator=LogicOperator.EQ,
ref="activity.intensitaet",
value="niedrig"
)
]
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
),
"activity": NodeExecutionState(
node_id="activity",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="intensitaet",
raw_value="hoch",
normalized_value="hoch",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True
assert error is None
def test_evaluate_or_both_false():
"""Test: OR operator - both operands false"""
expression = LogicExpression(
operator=LogicOperator.OR,
operands=[
LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="increase"
),
LogicExpression(
operator=LogicOperator.EQ,
ref="activity.intensitaet",
value="niedrig"
)
]
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
),
"activity": NodeExecutionState(
node_id="activity",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="intensitaet",
raw_value="hoch",
normalized_value="hoch",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is False
assert error is None
def test_evaluate_not():
"""Test: NOT operator - negation"""
expression = LogicExpression(
operator=LogicOperator.NOT,
operands=[
LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="increase"
)
]
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is True # NOT (decrease == increase) = NOT False = True
assert error is None
# ── Nested Expressions Tests ──────────────────────────────────────────────────
def test_evaluate_nested_and_or():
"""Test: Nested expression - (A AND B) OR C"""
expression = LogicExpression(
operator=LogicOperator.OR,
operands=[
LogicExpression(
operator=LogicOperator.AND,
operands=[
LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="decrease"
),
LogicExpression(
operator=LogicOperator.EQ,
ref="activity.intensitaet",
value="niedrig"
)
]
),
LogicExpression(
operator=LogicOperator.EQ,
ref="nutrition.defizit",
value="hoch"
)
]
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
),
"activity": NodeExecutionState(
node_id="activity",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="intensitaet",
raw_value="hoch", # FALSE für AND-Teil
normalized_value="hoch",
status=SignalStatus.VALID
)
]
),
"nutrition": NodeExecutionState(
node_id="nutrition",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="defizit",
raw_value="hoch", # TRUE für OR-Teil
normalized_value="hoch",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
# (decrease AND niedrig) OR hoch = (True AND False) OR True = False OR True = True
assert result is True
assert error is None
# ── Error Handling Tests ──────────────────────────────────────────────────
def test_evaluate_missing_node():
"""Test: Error handling - node not found"""
expression = LogicExpression(
operator=LogicOperator.EQ,
ref="missing_node.relevanz",
value="decrease"
)
context = {
"node_results": {}
}
result, error = evaluate_logic_expression(expression, context)
assert result is False
assert error is not None
assert "not found" in error.lower()
def test_evaluate_missing_signal():
"""Test: Error handling - signal not found in node"""
expression = LogicExpression(
operator=LogicOperator.EQ,
ref="body.missing_signal",
value="decrease"
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="decrease",
normalized_value="decrease",
status=SignalStatus.VALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is False
assert error is not None
assert "not found" in error.lower()
def test_evaluate_unclear_signal():
"""Test: Error handling - signal has UNCLEAR status"""
expression = LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="decrease"
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="maybe",
normalized_value="unklar",
status=SignalStatus.UNCLEAR
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is False
assert error is not None
assert "unclear" in error.lower() or "status" in error.lower()
def test_evaluate_invalid_signal():
"""Test: Error handling - signal has INVALID status"""
expression = LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="decrease"
)
context = {
"node_results": {
"body": NodeExecutionState(
node_id="body",
status=NodeStatus.EXECUTED,
normalized_signals=[
NormalizedSignal(
question_type="relevanz",
raw_value="invalid_value",
normalized_value=None,
status=SignalStatus.INVALID
)
]
)
}
}
result, error = evaluate_logic_expression(expression, context)
assert result is False
assert error is not None
assert "invalid" in error.lower() or "status" in error.lower()
def test_compare_values_gt_non_numeric():
"""Test: Error handling - GT with non-numeric values"""
result, error = compare_values(LogicOperator.GT, "text", 50)
assert result is False
assert error is not None
assert "cannot compare" in error.lower()
def test_compare_values_in_non_list():
"""Test: Error handling - IN with non-list right value"""
result, error = compare_values(LogicOperator.IN, "value", "not_a_list")
assert result is False
assert error is not None
assert "requires list" in error.lower()
if __name__ == "__main__":
pytest.main([__file__, "-v"])
@@ -0,0 +1,459 @@
"""
Integration Tests für Workflow Branching (Phase 3)
Testet conditional execution mit Logic Nodes.
Run with: PYTHONPATH=./backend pytest tests/backend/test_phase3_workflow_branching.py -v
"""
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from workflow_executor import execute_workflow
from workflow_models import (
WorkflowGraph, WorkflowNode, WorkflowEdge,
LogicExpression, LogicOperator, Condition, FallbackConfig, FallbackStrategy,
QuestionAugmentation, NodeStatus
)
# ── Helper Functions ────────────────────────────────────────────────────────
def create_mock_db():
"""Creates mock DB connection with cursor"""
conn = MagicMock()
cur = MagicMock()
cur.fetchone = MagicMock()
cur.fetchall = MagicMock(return_value=[])
# Mock get_cursor()
def mock_get_cursor(c):
return cur
# Context manager support
conn.__enter__ = MagicMock(return_value=conn)
conn.__exit__ = MagicMock(return_value=None)
return conn, cur, mock_get_cursor
@pytest.mark.asyncio
async def test_simple_if_else_branching():
"""Test: Simple if/else branching - then path taken"""
# Workflow: start → analysis → logic → then_path / else_path → end
workflow_graph = {
"nodes": [
{"id": "start", "type": "start"},
{"id": "analysis", "type": "analysis", "prompt_slug": "test_prompt",
"question_augmentations": [
{"id": "q1", "type": "relevanz", "question": "Relevant?", "answer_spectrum": ["ja", "nein"]}
]},
{"id": "logic", "type": "logic",
"condition": {
"expression": {
"operator": "eq",
"ref": "analysis.relevanz",
"value": "ja"
}
}},
{"id": "then_path", "type": "analysis", "prompt_slug": "then_prompt"},
{"id": "else_path", "type": "analysis", "prompt_slug": "else_prompt"},
{"id": "end", "type": "end"}
],
"edges": [
{"id": "e1", "from": "start", "to": "analysis"},
{"id": "e2", "from": "analysis", "to": "logic"},
{"id": "e3", "from": "logic", "to": "then_path", "label": "then"},
{"id": "e4", "from": "logic", "to": "else_path", "label": "else"},
{"id": "e5", "from": "then_path", "to": "end"},
{"id": "e6", "from": "else_path", "to": "end"}
]
}
# Mock DB
conn, cur, mock_get_cursor = create_mock_db()
cur.fetchone.side_effect = [
{"graph": workflow_graph}, # Workflow definition
{"template": "Test prompt"} # Prompt template
]
cur.fetchall.return_value = [
{"question_type": "relevanz", "answer_spectrum": ["ja", "nein"], "normalization_rules": None}
]
# Mock LLM - returns "ja" signal
async def mock_llm(prompt, model):
return """## Analyse
Test analysis
## Entscheidungsfragen
- Relevanz: ja
"""
with patch('workflow_executor.get_db', return_value=conn):
with patch('workflow_executor.get_cursor', side_effect=mock_get_cursor):
with patch('placeholder_resolver.resolve_placeholders', return_value="Test prompt"):
result = await execute_workflow(
workflow_id="test-workflow",
profile_id="test-profile",
variables={},
openrouter_call_func=mock_llm
)
# Assertions
assert result.status == "completed"
assert len(result.node_states) == 5 # start, analysis, logic, then_path, end (else_path skipped)
# Check which nodes were executed
executed_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.EXECUTED]
skipped_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.SKIPPED]
assert "then_path" in executed_nodes
assert "else_path" in skipped_nodes
# Check aggregation
assert result.aggregated_result["executed_nodes"] == 4 # start, analysis, logic, then_path (end is no-op)
assert result.aggregated_result["skipped_nodes"] == 1 # else_path
@pytest.mark.asyncio
async def test_else_path_taken():
"""Test: Simple if/else branching - else path taken"""
workflow_graph = {
"nodes": [
{"id": "start", "type": "start"},
{"id": "analysis", "type": "analysis", "prompt_slug": "test_prompt",
"question_augmentations": [
{"id": "q1", "type": "relevanz", "question": "Relevant?", "answer_spectrum": ["ja", "nein"]}
]},
{"id": "logic", "type": "logic",
"condition": {
"expression": {
"operator": "eq",
"ref": "analysis.relevanz",
"value": "ja"
}
}},
{"id": "then_path", "type": "analysis", "prompt_slug": "then_prompt"},
{"id": "else_path", "type": "analysis", "prompt_slug": "else_prompt"},
{"id": "end", "type": "end"}
],
"edges": [
{"id": "e1", "from": "start", "to": "analysis"},
{"id": "e2", "from": "analysis", "to": "logic"},
{"id": "e3", "from": "logic", "to": "then_path", "label": "then"},
{"id": "e4", "from": "logic", "to": "else_path", "label": "else"},
{"id": "e5", "from": "then_path", "to": "end"},
{"id": "e6", "from": "else_path", "to": "end"}
]
}
conn, cur = create_mock_db()
cur.fetchone.side_effect = [
{"graph": workflow_graph},
{"template": "Test prompt"}
]
cur.fetchall.return_value = [
{"question_type": "relevanz", "answer_spectrum": ["ja", "nein"], "normalization_rules": None}
]
# Mock LLM - returns "nein" signal (condition false)
async def mock_llm(prompt, model):
return """## Analyse
Test analysis
## Entscheidungsfragen
- Relevanz: nein
"""
with patch('workflow_executor.get_db', return_value=conn):
with patch('placeholder_resolver.resolve_placeholders', return_value="Test prompt"):
result = await execute_workflow(
workflow_id="test-workflow",
profile_id="test-profile",
variables={},
openrouter_call_func=mock_llm
)
# Assertions
executed_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.EXECUTED]
skipped_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.SKIPPED]
assert "else_path" in executed_nodes
assert "then_path" in skipped_nodes
@pytest.mark.asyncio
async def test_and_condition():
"""Test: AND condition - both must be true"""
workflow_graph = {
"nodes": [
{"id": "start", "type": "start"},
{"id": "analysis1", "type": "analysis", "prompt_slug": "test_prompt",
"question_augmentations": [
{"id": "q1", "type": "relevanz", "question": "Relevant?", "answer_spectrum": ["ja", "nein"]}
]},
{"id": "analysis2", "type": "analysis", "prompt_slug": "test_prompt",
"question_augmentations": [
{"id": "q2", "type": "prioritaet", "question": "Priority?", "answer_spectrum": ["hoch", "niedrig"]}
]},
{"id": "logic", "type": "logic",
"condition": {
"expression": {
"operator": "and",
"operands": [
{"operator": "eq", "ref": "analysis1.relevanz", "value": "ja"},
{"operator": "eq", "ref": "analysis2.prioritaet", "value": "hoch"}
]
}
}},
{"id": "then_path", "type": "analysis", "prompt_slug": "then_prompt"},
{"id": "else_path", "type": "analysis", "prompt_slug": "else_prompt"},
{"id": "end", "type": "end"}
],
"edges": [
{"id": "e1", "from": "start", "to": "analysis1"},
{"id": "e2", "from": "analysis1", "to": "analysis2"},
{"id": "e3", "from": "analysis2", "to": "logic"},
{"id": "e4", "from": "logic", "to": "then_path", "label": "then"},
{"id": "e5", "from": "logic", "to": "else_path", "label": "else"},
{"id": "e6", "from": "then_path", "to": "end"},
{"id": "e7", "from": "else_path", "to": "end"}
]
}
conn, cur = create_mock_db()
cur.fetchone.side_effect = [
{"graph": workflow_graph},
{"template": "Test prompt"},
{"template": "Test prompt"}
]
cur.fetchall.return_value = [
{"question_type": "relevanz", "answer_spectrum": ["ja", "nein"], "normalization_rules": None},
{"question_type": "prioritaet", "answer_spectrum": ["hoch", "niedrig"], "normalization_rules": None}
]
# Mock LLM - returns ja AND hoch (both true)
call_count = 0
async def mock_llm(prompt, model):
nonlocal call_count
call_count += 1
if call_count == 1:
return """## Analyse
Analysis 1
## Entscheidungsfragen
- Relevanz: ja
"""
else:
return """## Analyse
Analysis 2
## Entscheidungsfragen
- Prioritaet: hoch
"""
with patch('workflow_executor.get_db', return_value=conn):
with patch('placeholder_resolver.resolve_placeholders', return_value="Test prompt"):
result = await execute_workflow(
workflow_id="test-workflow",
profile_id="test-profile",
variables={},
openrouter_call_func=mock_llm
)
# Assertions: Both true → then path taken
executed_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.EXECUTED]
skipped_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.SKIPPED]
assert "then_path" in executed_nodes
assert "else_path" in skipped_nodes
@pytest.mark.asyncio
async def test_fallback_conservative_skip():
"""Test: Fallback strategy CONSERVATIVE_SKIP"""
workflow_graph = {
"nodes": [
{"id": "start", "type": "start"},
{"id": "analysis", "type": "analysis", "prompt_slug": "test_prompt",
"question_augmentations": [
{"id": "q1", "type": "relevanz", "question": "Relevant?", "answer_spectrum": ["ja", "nein"]}
]},
{"id": "logic", "type": "logic",
"condition": {
"expression": {
"operator": "eq",
"ref": "analysis.relevanz",
"value": "ja"
}
},
"fallback": {
"strategy": "conservative_skip"
}},
{"id": "then_path", "type": "analysis", "prompt_slug": "then_prompt"},
{"id": "else_path", "type": "analysis", "prompt_slug": "else_prompt"},
{"id": "end", "type": "end"}
],
"edges": [
{"id": "e1", "from": "start", "to": "analysis"},
{"id": "e2", "from": "analysis", "to": "logic"},
{"id": "e3", "from": "logic", "to": "then_path", "label": "then"},
{"id": "e4", "from": "logic", "to": "else_path", "label": "else"},
{"id": "e5", "from": "then_path", "to": "end"},
{"id": "e6", "from": "else_path", "to": "end"}
]
}
conn, cur = create_mock_db()
cur.fetchone.side_effect = [
{"graph": workflow_graph},
{"template": "Test prompt"}
]
cur.fetchall.return_value = [
{"question_type": "relevanz", "answer_spectrum": ["ja", "nein"], "normalization_rules": None}
]
# Mock LLM - returns UNCLEAR signal (triggers fallback)
async def mock_llm(prompt, model):
return """## Analyse
Test analysis
## Entscheidungsfragen
- Relevanz: unklar
"""
with patch('workflow_executor.get_db', return_value=conn):
with patch('placeholder_resolver.resolve_placeholders', return_value="Test prompt"):
result = await execute_workflow(
workflow_id="test-workflow",
profile_id="test-profile",
variables={},
openrouter_call_func=mock_llm
)
# Assertions: CONSERVATIVE_SKIP → both paths skipped
skipped_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.SKIPPED]
assert "then_path" in skipped_nodes
assert "else_path" in skipped_nodes
assert result.aggregated_result["skipped_nodes"] == 2
@pytest.mark.asyncio
async def test_fallback_default_path():
"""Test: Fallback strategy DEFAULT_PATH"""
workflow_graph = {
"nodes": [
{"id": "start", "type": "start"},
{"id": "analysis", "type": "analysis", "prompt_slug": "test_prompt",
"question_augmentations": [
{"id": "q1", "type": "relevanz", "question": "Relevant?", "answer_spectrum": ["ja", "nein"]}
]},
{"id": "logic", "type": "logic",
"condition": {
"expression": {
"operator": "eq",
"ref": "analysis.relevanz",
"value": "ja"
}
},
"fallback": {
"strategy": "default_path"
}},
{"id": "then_path", "type": "analysis", "prompt_slug": "then_prompt"},
{"id": "else_path", "type": "analysis", "prompt_slug": "else_prompt"},
{"id": "end", "type": "end"}
],
"edges": [
{"id": "e1", "from": "start", "to": "analysis"},
{"id": "e2", "from": "analysis", "to": "logic"},
{"id": "e3", "from": "logic", "to": "then_path", "label": "then"},
{"id": "e4", "from": "logic", "to": "else_path", "label": "else"},
{"id": "e5", "from": "then_path", "to": "end"},
{"id": "e6", "from": "else_path", "to": "end"}
]
}
conn, cur = create_mock_db()
cur.fetchone.side_effect = [
{"graph": workflow_graph},
{"template": "Test prompt"}
]
cur.fetchall.return_value = [
{"question_type": "relevanz", "answer_spectrum": ["ja", "nein"], "normalization_rules": None}
]
# Mock LLM - returns INVALID signal (triggers fallback)
async def mock_llm(prompt, model):
return """## Analyse
Test analysis
## Entscheidungsfragen
- Relevanz: totally_invalid_value
"""
with patch('workflow_executor.get_db', return_value=conn):
with patch('placeholder_resolver.resolve_placeholders', return_value="Test prompt"):
result = await execute_workflow(
workflow_id="test-workflow",
profile_id="test-profile",
variables={},
openrouter_call_func=mock_llm
)
# Assertions: DEFAULT_PATH → else path taken
executed_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.EXECUTED]
skipped_nodes = [s.node_id for s in result.node_states if s.status == NodeStatus.SKIPPED]
assert "else_path" in executed_nodes
assert "then_path" in skipped_nodes
@pytest.mark.asyncio
async def test_linear_workflow_still_works():
"""Test: Linear workflow (no logic nodes) still works (Phase 2 compatibility)"""
workflow_graph = {
"nodes": [
{"id": "start", "type": "start"},
{"id": "analysis", "type": "analysis", "prompt_slug": "test_prompt"},
{"id": "end", "type": "end"}
],
"edges": [
{"id": "e1", "from": "start", "to": "analysis"},
{"id": "e2", "from": "analysis", "to": "end"}
]
}
conn, cur = create_mock_db()
cur.fetchone.side_effect = [
{"graph": workflow_graph},
{"template": "Test prompt"}
]
cur.fetchall.return_value = []
async def mock_llm(prompt, model):
return "## Analyse\nTest analysis"
with patch('workflow_executor.get_db', return_value=conn):
with patch('placeholder_resolver.resolve_placeholders', return_value="Test prompt"):
result = await execute_workflow(
workflow_id="test-workflow",
profile_id="test-profile",
variables={},
openrouter_call_func=mock_llm
)
# Assertions: All nodes executed
assert result.status == "completed"
assert len(result.node_states) == 3
assert all(s.status == NodeStatus.EXECUTED for s in result.node_states)
assert result.aggregated_result["skipped_nodes"] == 0
if __name__ == "__main__":
pytest.main([__file__, "-v"])