File size: 13,501 Bytes
05a3c8b
 
 
 
 
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
474a36a
 
 
 
05a3c8b
 
 
 
 
 
474a36a
05a3c8b
 
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
474a36a
 
 
 
 
05a3c8b
 
 
 
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
474a36a
 
 
 
 
05a3c8b
 
 
 
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
474a36a
 
 
 
05a3c8b
 
 
 
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
 
 
474a36a
05a3c8b
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
474a36a
 
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5402d17
 
05a3c8b
 
 
5402d17
 
05a3c8b
5402d17
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5402d17
 
 
05a3c8b
 
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
474a36a
 
 
05a3c8b
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
 
 
 
 
474a36a
 
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
05a3c8b
 
474a36a
05a3c8b
 
 
474a36a
05a3c8b
 
474a36a
05a3c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
"""Test Join Node Comprehensive."""

import json
from unittest.mock import MagicMock

import pytest

from orka.nodes.join_node import JoinNode


class TestJoinNode:
    """Test cases for JoinNode."""

    def test_init_default_values(self):
        """Test JoinNode initialization with default values."""
        mock_queue = MagicMock()
        mock_memory = MagicMock()

        node = JoinNode(
            node_id="join1",
            prompt="Join results",
            queue=mock_queue,
            memory_logger=mock_memory,
        )

        assert node.node_id == "join1"
        assert node.prompt == "Join results"
        assert node.queue == mock_queue
        assert node.memory_logger == mock_memory
        assert node.group_id is None
        assert node.max_retries == 30
        assert node.output_key == "join1:output"
        assert node._retry_key == "join1:join_retry_count"

    def test_init_custom_values(self):
        """Test JoinNode initialization with custom values."""
        mock_queue = MagicMock()
        mock_memory = MagicMock()

        node = JoinNode(
            node_id="join2",
            prompt="Custom join",
            queue=mock_queue,
            memory_logger=mock_memory,
            group="group123",
            max_retries=50,
        )

        assert node.node_id == "join2"
        assert node.group_id == "group123"
        assert node.max_retries == 50
        assert node.output_key == "join2:output"
        assert node._retry_key == "join2:join_retry_count"

    @pytest.mark.asyncio
    async def test_run_all_agents_completed(self):
        """Test run when all expected agents have completed."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
            group="group1",
        )

        # Mock memory operations for completed scenario
        mock_memory.hget.side_effect = [
            None,  # retry count (first call)
            '{"result": "agent1"}',  # agent1 result
            '{"result": "agent2"}',  # agent2 result
        ]
        mock_memory.hkeys.return_value = ["agent1", "agent2"]
        mock_memory.smembers.return_value = ["agent1", "agent2"]

        input_data = {"fork_group_id": "group1"}
        result = await node.run(input_data)

        assert result["result"]["status"] == "done"
        assert "merged" in result["result"]
        assert result["result"]["merged"]["agent1"] == "agent1"
        assert result["result"]["merged"]["agent2"] == "agent2"

        # Verify cleanup calls
        mock_memory.hdel.assert_any_call("join_retry_counts", "join1:join_retry_count")
        mock_memory.hset.assert_any_call(
            "join_outputs",
            "join1:output",
            json.dumps(result["result"]["merged"]),
        )

    @pytest.mark.asyncio
    async def test_run_agents_pending_first_attempt(self):
        """Test run when some agents are still pending (first attempt)."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
            group="group1",
            max_retries=10,
        )

        # Mock memory operations for pending scenario
        mock_memory.hget.return_value = None  # No retry count yet
        mock_memory.hkeys.return_value = ["agent1"]  # Only agent1 completed
        mock_memory.smembers.return_value = ["agent1", "agent2", "agent3"]  # Expected agents

        input_data = {"fork_group_id": "group1"}
        result = await node.run(input_data)

        assert result["result"]["status"] == "waiting"
        assert result["result"]["pending"] == ["agent2", "agent3"]
        assert result["result"]["received"] == ["agent1"]
        assert result["result"]["retry_count"] == 3
        assert result["result"]["max_retries"] == 10

        # Verify retry count was set
        mock_memory.hset.assert_called_with("join_retry_counts", "join1:join_retry_count", "3")

    @pytest.mark.asyncio
    async def test_run_agents_pending_with_retries(self):
        """Test run when agents are pending and retries are happening."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
            max_retries=10,
        )

        # Mock memory operations for retry scenario
        mock_memory.hget.return_value = "5"  # Current retry count
        mock_memory.hkeys.return_value = ["agent1", "agent2"]
        mock_memory.smembers.return_value = ["agent1", "agent2", "agent3"]

        input_data = {"fork_group_id": "test_group"}
        result = await node.run(input_data)

        assert result["result"]["status"] == "waiting"
        assert result["result"]["pending"] == ["agent3"]
        assert result["result"]["received"] == ["agent1", "agent2"]
        assert result["result"]["retry_count"] == 6
        assert result["result"]["max_retries"] == 10

        # Verify retry count was incremented
        mock_memory.hset.assert_called_with("join_retry_counts", "join1:join_retry_count", "6")

    @pytest.mark.asyncio
    async def test_run_max_retries_exceeded(self):
        """Test run when max retries are exceeded."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
            max_retries=5,
        )

        # Mock memory operations for timeout scenario
        mock_memory.hget.return_value = "5"  # At max retries
        mock_memory.hkeys.return_value = ["agent1"]
        mock_memory.smembers.return_value = ["agent1", "agent2"]

        input_data = {"fork_group_id": "test_group"}
        result = await node.run(input_data)

        assert result["result"]["status"] == "timeout"
        assert result["result"]["pending"] == ["agent2"]
        assert result["result"]["received"] == ["agent1"]
        assert result["result"]["max_retries"] == 5

        # Verify retry count was cleaned up
        mock_memory.hdel.assert_called_with("join_retry_counts", "join1:join_retry_count")

    @pytest.mark.asyncio
    async def test_run_use_default_group_id(self):
        """Test run using default group_id when not provided in input."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
            group="default_group",
        )

        # Mock memory operations
        mock_memory.hget.return_value = None
        mock_memory.hkeys.return_value = []
        mock_memory.smembers.return_value = ["agent1"]

        input_data = {}  # No fork_group_id provided
        result = await node.run(input_data)

        # Should use default group_id
        mock_memory.smembers.assert_called_with("fork_group:default_group")
        assert result["result"]["status"] == "waiting"

    @pytest.mark.asyncio
    async def test_run_handle_byte_strings(self):
        """Test run handles byte strings from Redis correctly."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
        )

        # Mock memory operations returning byte strings (like Redis)
        mock_memory.hget.return_value = None
        mock_memory.hkeys.return_value = [b"agent1", b"agent2"]  # Byte strings
        mock_memory.smembers.return_value = [b"agent1", b"agent2", b"agent3"]  # Byte strings

        input_data = {"fork_group_id": "test_group"}
        result = await node.run(input_data)

        assert result["result"]["status"] == "waiting"
        assert result["result"]["pending"] == ["agent3"]  # Should be decoded
        assert result["result"]["received"] == ["agent1", "agent2"]  # Should be decoded

    def test_complete_method(self):
        """Test _complete method functionality."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
        )

        # Mock data retrieval
        mock_memory.hget.side_effect = [
            '{"result": "data1", "status": "success"}',
            '{"result": "data2", "status": "success"}',
        ]

        fork_targets = ["agent1", "agent2"]
        state_key = "test:state:key"

        result = node._complete(fork_targets, state_key)

        assert result["status"] == "done"
        assert "merged" in result
        assert result["merged"]["agent1"] == "data1"
        assert result["merged"]["agent2"] == "data2"

        # Verify storage and cleanup
        expected_merged = {
            "agent1": "data1",
            "agent2": "data2",
        }
        mock_memory.hset.assert_any_call(
            "join_outputs",
            "join1:output",
            json.dumps(expected_merged),
        )
        mock_memory.hdel.assert_called_with(state_key, "agent1", "agent2")

    def test_complete_method_empty_targets(self):
        """Test _complete method with empty fork targets."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
        )

        fork_targets = []
        state_key = "test:state:key"

        result = node._complete(fork_targets, state_key)

        assert result["status"] == "done"
        assert result["merged"] == {}

        # Should not call hdel with empty targets
        mock_memory.hdel.assert_not_called()

        # Should still store empty result
        mock_memory.hset.assert_called_with(
            "join_results:join1",
            "result",
            json.dumps({"status": "done", "merged": {}}),
        )

    @pytest.mark.asyncio
    async def test_run_json_parsing_in_complete(self):
        """Test that JSON parsing works correctly in _complete method."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
        )

        # Mock for completed scenario that triggers _complete
        mock_memory.hget.side_effect = [
            None,  # retry count
            '{"complex": {"nested": "data"}, "list": [1, 2, 3]}',  # agent1 result
        ]
        mock_memory.hkeys.return_value = ["agent1"]
        mock_memory.smembers.return_value = ["agent1"]

        input_data = {"fork_group_id": "test_group"}
        result = await node.run(input_data)

        assert result["result"]["status"] == "done"
        assert result["result"]["merged"]["agent1"]["complex"]["nested"] == "data"
        assert result["result"]["merged"]["agent1"]["list"] == [1, 2, 3]

    @pytest.mark.asyncio
    async def test_run_state_key_formation(self):
        """Test that the correct state key is used."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
        )

        mock_memory.hget.return_value = None
        mock_memory.hkeys.return_value = []
        mock_memory.smembers.return_value = ["agent1"]

        input_data = {"fork_group_id": "test_group"}
        await node.run(input_data)

        # Verify correct state key is used
        expected_state_key = "waitfor:join_parallel_checks:inputs"
        mock_memory.hkeys.assert_called_with(expected_state_key)

    @pytest.mark.asyncio
    async def test_run_retry_count_edge_cases(self):
        """Test retry count edge cases."""
        mock_memory = MagicMock()
        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=MagicMock(),
            memory_logger=mock_memory,
            max_retries=5,
        )

        # Test exactly at max retries
        mock_memory.hget.return_value = "5"  # At max retries
        mock_memory.hkeys.return_value = []
        mock_memory.smembers.return_value = ["agent1"]

        input_data = {"fork_group_id": "test_group"}
        result = await node.run(input_data)

        # Should timeout since retry_count (6) >= max_retries (5)
        assert result["result"]["status"] == "timeout"

        # Test just under max retries
        mock_memory.hget.return_value = "3"
        result = await node.run(input_data)

        # Should still be waiting since retry_count (4) < max_retries (5)
        assert result["result"]["status"] == "waiting"

    def test_inheritance_from_base_node(self):
        """Test that JoinNode properly inherits from BaseNode."""
        mock_queue = MagicMock()
        mock_memory = MagicMock()

        node = JoinNode(
            node_id="join1",
            prompt="Join test",
            queue=mock_queue,
            memory_logger=mock_memory,
        )

        # Should have BaseNode attributes
        assert hasattr(node, "node_id")
        assert hasattr(node, "prompt")
        assert hasattr(node, "queue")

        # Should be instance of BaseNode
        from orka.nodes.base_node import BaseNode

        assert isinstance(node, BaseNode)