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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5402d17
 
 
 
 
 
 
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
import time
from unittest.mock import AsyncMock, Mock, patch

import pytest

from orka.nodes.memory_reader_node import MemoryReaderNode


class TestMemoryReaderNodeInitialization:
    """Test MemoryReaderNode initialization scenarios."""

    @patch("orka.memory_logger.create_memory_logger")
    @patch("orka.utils.embedder.get_embedder")
    def test_default_initialization(self, mock_get_embedder, mock_create_logger):
        """Test initialization with default parameters."""
        mock_memory_logger = Mock()
        mock_create_logger.return_value = mock_memory_logger
        mock_embedder = Mock()
        mock_get_embedder.return_value = mock_embedder

        node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])

        assert node.node_id == "test_node"
        assert node.memory_logger == mock_memory_logger
        assert node.namespace == "default"
        assert node.limit == 5
        assert node.similarity_threshold == 0.7
        assert node.ef_runtime == 10
        # Embedder may be None if initialization fails
        mock_create_logger.assert_called_once_with(
            backend="redisstack",
            redis_url="redis://localhost:6380/0",
            embedder=None,  # Embedder fails during initialization
            memory_preset=None,
            operation="read",  # Added for operation-aware presets
        )

    @patch("orka.utils.embedder.get_embedder")
    def test_initialization_with_custom_memory_logger(self, mock_get_embedder):
        """Test initialization with custom memory logger."""
        mock_memory_logger = Mock()
        mock_embedder = Mock()
        mock_get_embedder.return_value = mock_embedder

        node = MemoryReaderNode(
            node_id="test_node",
            prompt="test_prompt",
            queue=[],
            memory_logger=mock_memory_logger,
            namespace="custom_ns",
            limit=10,
            similarity_threshold=0.8,
            ef_runtime=20,
        )

        assert node.memory_logger == mock_memory_logger
        assert node.namespace == "custom_ns"
        assert node.limit == 10
        assert node.similarity_threshold == 0.8
        assert node.ef_runtime == 20

    @patch("orka.memory_logger.create_memory_logger")
    @patch("orka.utils.embedder.get_embedder")
    def test_initialization_with_embedder_failure(self, mock_get_embedder, mock_create_logger):
        """Test initialization when embedder creation fails."""
        mock_create_logger.return_value = Mock()
        mock_get_embedder.side_effect = Exception("Embedder failed")

        node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])

        assert node.embedder is None

    @patch("orka.memory_logger.create_memory_logger")
    @patch("orka.utils.embedder.get_embedder")
    def test_initialization_with_redis_url(self, mock_get_embedder, mock_create_logger):
        """Test initialization with custom Redis URL."""
        mock_create_logger.return_value = Mock()
        mock_get_embedder.return_value = Mock()

        node = MemoryReaderNode(
            node_id="test_node",
            prompt="test_prompt",
            queue=[],
            redis_url="redis://custom:6380/1",
            embedding_model="custom_model",
        )

        mock_create_logger.assert_called_once_with(
            backend="redisstack",
            redis_url="redis://custom:6380/1",
            embedder=None,  # Embedder fails during initialization
            memory_preset=None,
            operation="read",  # Added for operation-aware presets
        )
        mock_get_embedder.assert_called_once_with("custom_model")


class TestMemoryReaderNodeRun:
    """Test the main run method of MemoryReaderNode."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.mock_memory_logger = Mock()
            self.mock_embedder = Mock()

            self.node = MemoryReaderNode(
                node_id="test_node",
                prompt="test_prompt",
                queue=[],
                memory_logger=self.mock_memory_logger,
            )
            self.node.embedder = self.mock_embedder

    @pytest.mark.asyncio
    async def test_run_with_empty_query(self):
        """Test run method with empty query."""
        context = {"input": ""}

        result = await self.node.run(context)

        assert result["result"]["memories"] == []
        assert result["result"]["query"] == ""
        assert result["result"]["error"] == "No query provided"

    @pytest.mark.asyncio
    async def test_run_with_no_query(self):
        """Test run method with no query in context."""
        context = {}

        result = await self.node.run(context)

        assert result["result"]["memories"] == []
        assert result["result"]["query"] == ""
        assert result["result"]["error"] == "No query provided"

    @pytest.mark.asyncio
    async def test_run_successful_search(self):
        """Test successful memory search."""
        mock_memories = [
            {
                "content": "Test memory 1",
                "metadata": {"log_type": "memory", "category": "stored"},
                "similarity_score": 0.9,
            },
            {
                "content": "Test memory 2",
                "metadata": {"log_type": "memory", "category": "stored"},
                "similarity_score": 0.8,
            },
        ]
        self.mock_memory_logger.search_memories.return_value = mock_memories

        context = {
            "input": "test query",
            "trace_id": "test_trace",
            "min_importance": 0.5,
        }

        result = await self.node.run(context)

        assert result["result"]["memories"] == mock_memories
        assert result["result"]["query"] == "test query"
        assert result["result"]["backend"] == "redisstack"
        assert result["result"]["search_type"] == "enhanced_vector"
        assert result["result"]["num_results"] == 2

        self.mock_memory_logger.search_memories.assert_called_once_with(
            query="test query",
            num_results=5,
            trace_id="test_trace",
            node_id=None,
            memory_type=None,
            min_importance=0.5,
            log_type="memory",
            namespace="default",
        )

    @pytest.mark.asyncio
    async def test_run_with_filtering(self):
        """Test run method filters out non-stored memories."""
        mock_memories = [
            {
                "content": "Stored memory",
                "metadata": {"log_type": "memory", "category": "stored"},
                "similarity_score": 0.9,
            },
            {
                "content": "Log entry",
                "metadata": {"log_type": "log", "category": "log"},
                "similarity_score": 0.8,
            },
            {
                "content": "Another stored memory",
                "metadata": {"category": "stored"},
                "similarity_score": 0.7,
            },
        ]
        self.mock_memory_logger.search_memories.return_value = mock_memories

        context = {"input": "test query"}
        result = await self.node.run(context)

        # Should filter out the log entry
        assert len(result["result"]["memories"]) == 2
        assert result["result"]["memories"][0]["content"] == "Stored memory"
        assert result["result"]["memories"][1]["content"] == "Another stored memory"

    @pytest.mark.asyncio
    async def test_run_without_search_memories_method(self):
        """Test run method when memory logger doesn't have search_memories."""
        self.mock_memory_logger.search_memories = None
        delattr(self.mock_memory_logger, "search_memories")

        context = {"input": "test query"}
        result = await self.node.run(context)

        assert result["result"]["memories"] == []
        assert result["result"]["query"] == "test query"
        assert result["result"]["backend"] == "redisstack"

    @pytest.mark.asyncio
    async def test_run_with_exception(self):
        """Test run method when search raises exception."""
        self.mock_memory_logger.search_memories.side_effect = Exception("Search failed")

        context = {"input": "test query"}
        result = await self.node.run(context)

        assert result["result"]["memories"] == []
        assert result["result"]["query"] == "test query"
        assert result["result"]["error"] == "Search failed"
        assert result["result"]["backend"] == "redisstack"


class TestMemoryReaderNodeHNSWSearch:
    """Test HNSW hybrid search functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.mock_memory_logger = AsyncMock()

            self.node = MemoryReaderNode(
                node_id="test_node",
                prompt="test_prompt",
                queue=[],
                memory_logger=self.mock_memory_logger,
            )
            # Add optional attributes for enhanced functionality
            self.node.enable_context_search = True
            self.node.enable_temporal_ranking = True

    @pytest.mark.asyncio
    async def test_hnsw_hybrid_search_basic(self):
        """Test basic HNSW hybrid search."""
        mock_results = [
            {"content": "Test result", "similarity_score": 0.9},
        ]
        self.mock_memory_logger.search_memories.return_value = mock_results

        query_embedding = [0.1, 0.2, 0.3]
        conversation_context = []

        results = await self.node._hnsw_hybrid_search(
            query_embedding,
            "test query",
            "test_namespace",
            "test_session",
            conversation_context,
        )

        assert results == mock_results
        self.mock_memory_logger.search_memories.assert_called_once()

    @pytest.mark.asyncio
    async def test_hnsw_hybrid_search_with_context_enhancement(self):
        """Test HNSW search with context enhancement."""
        mock_results = [
            {"content": "Test result", "similarity_score": 0.9},
        ]
        self.mock_memory_logger.search_memories.return_value = mock_results

        conversation_context = [
            {"content": "Previous conversation", "timestamp": time.time()},
        ]

        # Mock the enhancement method
        enhanced_results = [
            {"content": "Test result", "similarity_score": 0.95, "context_score": 0.05},
        ]
        self.node._enhance_with_context_scoring = Mock(return_value=enhanced_results)

        query_embedding = [0.1, 0.2, 0.3]
        results = await self.node._hnsw_hybrid_search(
            query_embedding,
            "test query",
            "test_namespace",
            "test_session",
            conversation_context,
        )

        assert results == enhanced_results
        self.node._enhance_with_context_scoring.assert_called_once_with(
            mock_results,
            conversation_context,
        )

    @pytest.mark.asyncio
    async def test_hnsw_hybrid_search_with_temporal_ranking(self):
        """Test HNSW search with temporal ranking."""
        mock_results = [
            {"content": "Test result", "similarity_score": 0.9, "timestamp": time.time()},
        ]
        self.mock_memory_logger.search_memories.return_value = mock_results

        # Mock the temporal ranking method
        ranked_results = [
            {"content": "Test result", "similarity_score": 0.92, "temporal_factor": 0.8},
        ]
        self.node._apply_temporal_ranking = Mock(return_value=ranked_results)

        query_embedding = [0.1, 0.2, 0.3]
        results = await self.node._hnsw_hybrid_search(
            query_embedding,
            "test query",
            "test_namespace",
            "test_session",
            [],
        )

        assert results == ranked_results
        self.node._apply_temporal_ranking.assert_called_once_with(mock_results)

    @pytest.mark.asyncio
    async def test_hnsw_hybrid_search_without_memory_logger_method(self):
        """Test HNSW search when memory logger doesn't have search_memories."""
        delattr(self.mock_memory_logger, "search_memories")

        query_embedding = [0.1, 0.2, 0.3]
        results = await self.node._hnsw_hybrid_search(
            query_embedding,
            "test query",
            "test_namespace",
            "test_session",
            [],
        )

        assert results == []

    @pytest.mark.asyncio
    async def test_hnsw_hybrid_search_with_exception(self):
        """Test HNSW search exception handling."""
        self.mock_memory_logger.search_memories.side_effect = Exception("Search error")

        query_embedding = [0.1, 0.2, 0.3]
        results = await self.node._hnsw_hybrid_search(
            query_embedding,
            "test query",
            "test_namespace",
            "test_session",
            [],
        )

        assert results == []


class TestMemoryReaderNodeContextScoring:
    """Test context-aware scoring functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            self.node.context_weight = 0.2

    def test_enhance_with_context_scoring_no_context(self):
        """Test context scoring with no context."""
        results = [
            {"content": "Test result", "similarity_score": 0.9},
        ]

        enhanced = self.node._enhance_with_context_scoring(results, [])

        assert enhanced == results

    def test_enhance_with_context_scoring_with_context(self):
        """Test context scoring with conversation context."""
        results = [
            {"content": "machine learning algorithms", "similarity_score": 0.8},
            {"content": "weather forecast today", "similarity_score": 0.7},
        ]

        conversation_context = [
            {"content": "Tell me about machine learning and algorithms"},
            {"content": "What are the best algorithms for classification"},
        ]

        enhanced = self.node._enhance_with_context_scoring(results, conversation_context)

        # First result should get context bonus due to word overlap
        assert enhanced[0]["similarity_score"] > 0.8
        assert "context_score" in enhanced[0]
        assert "original_similarity" in enhanced[0]

        # Results should be sorted by enhanced similarity
        assert enhanced[0]["similarity_score"] >= enhanced[1]["similarity_score"]

    def test_enhance_with_context_scoring_exception_handling(self):
        """Test context scoring exception handling."""
        results = [{"content": "test"}]  # Missing similarity_score
        conversation_context = [{"content": "test context"}]

        # Should not raise exception
        enhanced = self.node._enhance_with_context_scoring(results, conversation_context)

        assert len(enhanced) == 1


class TestMemoryReaderNodeTemporalRanking:
    """Test temporal ranking functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            self.node.temporal_decay_hours = 24.0
            self.node.temporal_weight = 0.1

    def test_apply_temporal_ranking_with_timestamps(self):
        """Test temporal ranking with valid timestamps."""
        current_time = time.time()
        recent_time = current_time - 3600  # 1 hour ago
        old_time = current_time - 86400  # 24 hours ago

        results = [
            {
                "content": "Old result",
                "similarity_score": 0.9,
                "timestamp": old_time,
            },
            {
                "content": "Recent result",
                "similarity_score": 0.8,
                "timestamp": recent_time,
            },
        ]

        with patch("time.time", return_value=current_time):
            ranked = self.node._apply_temporal_ranking(results)

        # Recent result should be boosted
        assert "temporal_factor" in ranked[0]
        assert "temporal_factor" in ranked[1]

        # Results should be re-sorted by temporal-adjusted similarity
        recent_result = next(r for r in ranked if r["content"] == "Recent result")
        old_result = next(r for r in ranked if r["content"] == "Old result")

        assert recent_result["temporal_factor"] > old_result["temporal_factor"]

    def test_apply_temporal_ranking_with_millisecond_timestamps(self):
        """Test temporal ranking with millisecond timestamps."""
        current_time = time.time()
        timestamp_ms = int(current_time * 1000)  # Convert to milliseconds

        results = [
            {
                "content": "Test result",
                "similarity_score": 0.8,
                "timestamp": timestamp_ms,
            },
        ]

        with patch("time.time", return_value=current_time):
            ranked = self.node._apply_temporal_ranking(results)

        assert "temporal_factor" in ranked[0]
        assert ranked[0]["temporal_factor"] > 0

    def test_apply_temporal_ranking_without_timestamps(self):
        """Test temporal ranking with missing timestamps."""
        results = [
            {"content": "Test result", "similarity_score": 0.8},
        ]

        ranked = self.node._apply_temporal_ranking(results)

        # Should return results unchanged
        assert ranked == results

    def test_apply_temporal_ranking_exception_handling(self):
        """Test temporal ranking exception handling."""
        results = [
            {"content": "Test result", "timestamp": "invalid"},
        ]

        # Should not raise exception
        ranked = self.node._apply_temporal_ranking(results)

        assert ranked == results


class TestMemoryReaderNodeMetrics:
    """Test search metrics functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            # Initialize metrics
            self.node._search_metrics = {
                "average_search_time": 0.0,
                "hnsw_searches": 0,
                "legacy_searches": 0,
                "total_results_found": 0,
            }
            self.node.use_hnsw = True
            self.node.hybrid_search_enabled = True

    def test_update_search_metrics_first_search(self):
        """Test updating metrics for first search."""
        self.node._search_metrics["hnsw_searches"] = 1
        self.node._search_metrics["legacy_searches"] = 0

        self.node._update_search_metrics(0.5, 3)

        assert self.node._search_metrics["average_search_time"] == 0.5
        assert self.node._search_metrics["total_results_found"] == 3

    def test_update_search_metrics_multiple_searches(self):
        """Test updating metrics with exponential moving average."""
        self.node._search_metrics["average_search_time"] = 0.4
        self.node._search_metrics["hnsw_searches"] = 5
        self.node._search_metrics["legacy_searches"] = 3

        self.node._update_search_metrics(0.6, 2)

        # Should use exponential moving average: 0.1 * 0.6 + 0.9 * 0.4 = 0.42
        expected_avg = 0.1 * 0.6 + 0.9 * 0.4
        assert abs(self.node._search_metrics["average_search_time"] - expected_avg) < 0.001
        assert self.node._search_metrics["total_results_found"] == 2

    def test_get_search_metrics(self):
        """Test retrieving search metrics."""
        metrics = self.node.get_search_metrics()

        expected_keys = {
            "average_search_time",
            "hnsw_searches",
            "legacy_searches",
            "total_results_found",
            "hnsw_enabled",
            "hybrid_search_enabled",
            "ef_runtime",
            "similarity_threshold",
        }

        assert set(metrics.keys()) == expected_keys
        assert metrics["hnsw_enabled"] == True
        assert metrics["hybrid_search_enabled"] == True
        assert metrics["ef_runtime"] == 10
        assert metrics["similarity_threshold"] == 0.7


class TestMemoryReaderNodeContextExtraction:
    """Test conversation context extraction."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            self.node.context_window_size = 5

    def test_extract_conversation_context_from_previous_outputs(self):
        """Test extracting context from previous outputs."""
        context = {
            "previous_outputs": {
                "agent1": {
                    "response": "This is a response from agent1",
                    "confidence": 0.9,
                },
                "agent2": {
                    "result": "Agent2 result",
                    "status": "success",
                },
                "agent3": "Simple string output",
                "agent4": 42,  # Number output
            },
        }

        with patch("time.time", return_value=1000.0):
            conversation_context = self.node._extract_conversation_context(context)

        assert len(conversation_context) == 4

        # Check agent1 output
        agent1_context = next(c for c in conversation_context if c["agent_id"] == "agent1")
        assert agent1_context["content"] == "This is a response from agent1"
        assert agent1_context["field"] == "response"

        # Check agent2 output
        agent2_context = next(c for c in conversation_context if c["agent_id"] == "agent2")
        assert agent2_context["content"] == "Agent2 result"
        assert agent2_context["field"] == "result"

        # Check simple outputs
        agent3_context = next(c for c in conversation_context if c["agent_id"] == "agent3")
        assert agent3_context["content"] == "Simple string output"
        assert agent3_context["field"] == "direct_output"

    def test_extract_conversation_context_from_direct_fields(self):
        """Test extracting context from direct context fields."""
        context = {
            "conversation": [
                {"content": "Message 1", "timestamp": 1000},
                {"content": "Message 2", "timestamp": 2000},
            ],
            "history": "Previous conversation history",
            "context": "Additional context info",
        }

        conversation_context = self.node._extract_conversation_context(context)

        assert len(conversation_context) == 4

        # Check conversation list items
        msg_contexts = [c for c in conversation_context if c.get("source") == "conversation"]
        assert len(msg_contexts) == 2
        assert msg_contexts[0]["content"] == "Message 1"
        assert msg_contexts[0]["timestamp"] == 1000

        # Check string context fields
        history_context = next(c for c in conversation_context if c.get("source") == "history")
        assert history_context["content"] == "Previous conversation history"

    def test_extract_conversation_context_with_size_limit(self):
        """Test context extraction with size limit."""
        self.node.context_window_size = 2

        context = {
            "previous_outputs": {f"agent{i}": {"response": f"Response {i}"} for i in range(5)},
        }

        with patch("time.time", return_value=1000.0):
            conversation_context = self.node._extract_conversation_context(context)

        # Should be limited to context_window_size
        assert len(conversation_context) == 2

    def test_extract_conversation_context_empty(self):
        """Test context extraction with empty context."""
        context = {}

        conversation_context = self.node._extract_conversation_context(context)

        assert conversation_context == []


class TestMemoryReaderNodeQueryVariations:
    """Test query variation generation."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])

    def test_generate_query_variations_single_word(self):
        """Test query variations for single word."""
        variations = self.node._generate_query_variations("machine")

        expected_variations = [
            "machine",
            "about machine",
            "machine information",
            "what is machine",
            "tell me about machine",
        ]

        assert all(var in variations for var in expected_variations)

    def test_generate_query_variations_two_words(self):
        """Test query variations for two words."""
        variations = self.node._generate_query_variations("machine learning")

        assert "machine learning" in variations
        assert "learning machine" in variations  # Reversed
        assert "about machine learning" in variations
        assert "machine and learning" in variations

    def test_generate_query_variations_multiple_words(self):
        """Test query variations for multiple words."""
        variations = self.node._generate_query_variations("deep neural network architecture")

        assert "deep neural network architecture" in variations
        assert "about deep neural network architecture" in variations
        assert "deep architecture" in variations  # First and last words
        assert "deep neural" in variations  # First two words
        assert "network architecture" in variations  # Last two words

    def test_generate_query_variations_empty_query(self):
        """Test query variations for empty query."""
        variations = self.node._generate_query_variations("")
        assert variations == []

        variations = self.node._generate_query_variations("   ")
        assert variations == []

    def test_generate_enhanced_query_variations_with_context(self):
        """Test enhanced query variations with conversation context."""
        conversation_context = [
            {"content": "I'm interested in machine learning algorithms and classification"},
            {"content": "What are the best approaches for neural networks"},
        ]

        variations = self.node._generate_enhanced_query_variations(
            "deep learning",
            conversation_context,
        )

        # Should include original query
        assert "deep learning" in variations

        # Should include more variations when context is provided
        assert len(variations) > 1

        # Should be limited to 8 variations
        assert len(variations) <= 8

        # Context-enhanced variations may or may not be generated depending on word filtering
        # but we should have some additional variations beyond the original
        basic_variations = self.node._generate_query_variations("deep learning")
        assert len(variations) >= len(basic_variations)

    def test_generate_enhanced_query_variations_no_context(self):
        """Test enhanced query variations without context."""
        variations = self.node._generate_enhanced_query_variations("test query", [])

        # Should include original and basic variations
        assert "test query" in variations
        assert len(variations) > 1

    def test_generate_enhanced_query_variations_empty_query(self):
        """Test enhanced query variations with empty query."""
        variations = self.node._generate_enhanced_query_variations("", [])
        assert len(variations) == 1
        assert variations[0] == ""


class TestMemoryReaderNodeEdgeCases:
    """Test edge cases and error handling."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.mock_memory_logger = Mock()
            self.node = MemoryReaderNode(
                node_id="test_node",
                prompt="test_prompt",
                queue=[],
                memory_logger=self.mock_memory_logger,
            )
            # Add required attributes for edge case testing
            self.node.context_window_size = 5

    @pytest.mark.asyncio
    async def test_run_with_malformed_memories(self):
        """Test run method with malformed memory data."""
        malformed_memories = [
            {"content": "Valid memory", "metadata": {"log_type": "memory"}},
            {"content": "Memory without metadata"},  # Missing metadata
            {"metadata": {"log_type": "memory"}},  # Missing content
            # Note: None values are filtered out by the memory logger search, not by our filtering
        ]
        self.mock_memory_logger.search_memories.return_value = malformed_memories

        context = {"input": "test query"}
        result = await self.node.run(context)

        # Should handle malformed data gracefully
        assert "memories" in result["result"]
        # Malformed data should be handled - may or may not contain errors

    def test_context_scoring_with_malformed_data(self):
        """Test context scoring with malformed data."""
        results = [
            {"content": "test"},  # Missing similarity_score
            {"similarity_score": "invalid"},  # Invalid similarity_score
            {"content": "valid", "similarity_score": 0.8},
        ]

        conversation_context = [
            {"content": "test context"},
            {"invalid": "data"},  # Missing content
            None,  # Null context
        ]

        # Should not raise exception
        enhanced = self.node._enhance_with_context_scoring(results, conversation_context)
        assert len(enhanced) == len(results)

    def test_temporal_ranking_with_invalid_timestamps(self):
        """Test temporal ranking with invalid timestamps."""
        results = [
            {"content": "test1", "timestamp": "invalid_timestamp"},
            {"content": "test2", "timestamp": -1},  # Negative timestamp
            {"content": "test3", "timestamp": None},  # Null timestamp
        ]

        # Should not raise exception
        ranked = self.node._apply_temporal_ranking(results)
        assert len(ranked) == len(results)

    def test_metrics_update_with_invalid_data(self):
        """Test metrics update with invalid data."""
        self.node._search_metrics = {
            "average_search_time": 0.0,
            "hnsw_searches": 0,
            "legacy_searches": 0,
            "total_results_found": 0,
        }

        # Should handle negative or invalid values
        self.node._update_search_metrics(-1, -5)

        # Metrics should still be updated (even if values are unusual)
        assert self.node._search_metrics["total_results_found"] == -5

    def test_context_extraction_with_circular_references(self):
        """Test context extraction with circular reference data."""
        # Create circular reference
        circular_data = {"key": "value"}
        circular_data["self"] = circular_data

        context = {
            "previous_outputs": {
                "agent1": circular_data,
            },
        }

        # Should handle circular references gracefully
        conversation_context = self.node._extract_conversation_context(context)

        # Should extract what it can without crashing
        assert isinstance(conversation_context, list)


class TestMemoryReaderNodeEnhancedKeywordSearch:
    """Test enhanced keyword search functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            # Add missing attributes for enhanced keyword search
            self.node.context_weight = 0.3
            self.node.limit = 5

    @pytest.mark.asyncio
    async def test_enhanced_keyword_search_basic(self):
        """Test basic enhanced keyword search."""
        self.node.memory_logger = AsyncMock()

        # Mock memory logger responses
        self.node.memory_logger.search_memories.return_value = [
            {
                "content": "test content with important keywords",
                "metadata": {"category": "stored"},
                "namespace": "test_namespace",
            }
        ]

        results = await self.node._enhanced_keyword_search(
            "test_namespace",
            "important keywords",
            [],
        )

        assert len(results) == 1
        assert results[0]["content"] == "test content with important keywords"
        assert results[0]["match_type"] == "enhanced_keyword"
        assert results[0]["query_overlap"] > 0

    @pytest.mark.asyncio
    async def test_enhanced_keyword_search_with_context(self):
        """Test enhanced keyword search with conversation context."""
        self.node.memory_logger = AsyncMock()
        self.node.context_weight = 0.3

        # Mock memory logger responses
        self.node.memory_logger.search_memories.return_value = [
            {
                "content": "content with context words and query terms",
                "metadata": {"timestamp": "2023-01-01T00:00:00Z"},
                "namespace": "test_namespace",
            }
        ]

        context = [
            {"content": "previous context words"},
            {"content": "more context information"},
        ]

        results = await self.node._enhanced_keyword_search("test_namespace", "query terms", context)

        assert len(results) == 1
        assert results[0]["context_overlap"] > 0
        assert results[0]["similarity"] > results[0]["query_overlap"] / 2

    @pytest.mark.asyncio
    async def test_enhanced_keyword_search_short_words(self):
        """Test enhanced keyword search with short words."""
        self.node.memory_logger = AsyncMock()

        # Mock memory logger responses
        self.node.memory_logger.search_memories.return_value = [
            {
                "content": "content with a an the",
                "metadata": {},
                "namespace": "test_namespace",
            }
        ]

        # Query with only short words should use all words
        results = await self.node._enhanced_keyword_search("test_namespace", "a an the", [])

        assert len(results) == 1
        assert results[0]["query_overlap"] > 0

    @pytest.mark.asyncio
    async def test_enhanced_keyword_search_redis_error(self):
        """Test enhanced keyword search with Redis errors."""
        self.node.memory_logger = AsyncMock()

        # Mock memory logger error
        self.node.memory_logger.search_memories.side_effect = Exception("Memory logger error")

        results = await self.node._enhanced_keyword_search("test_namespace", "test query", [])

        assert results == []


class TestMemoryReaderNodeContextAwareVectorSearch:
    """Test context-aware vector search functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            # Add missing attributes for context-aware vector search
            self.node.context_weight = 0.3
            self.node.limit = 5
            self.node.enable_context_search = True

    @pytest.mark.asyncio
    async def test_context_aware_vector_search_basic(self):
        """Test basic context-aware vector search."""
        self.node.memory_logger = AsyncMock()
        self.node.embedder = AsyncMock()
        self.node.similarity_threshold = 0.5

        # Mock memory logger responses
        self.node.memory_logger.search_memories.return_value = [
            {
                "content": "test content",
                "metadata": {"category": "stored"},
                "namespace": "test_namespace",
                "vector": [0.1, 0.2, 0.3],
            }
        ]

        # Mock vector operations
        query_embedding = [0.1, 0.2, 0.3]
        with patch.object(self.node, "_cosine_similarity", return_value=0.8):
            results = await self.node._context_aware_vector_search(
                query_embedding,
                "test_namespace",
                [],
                0.5,
            )

        assert len(results) == 1
        assert results[0]["match_type"] == "context_aware_vector"
        assert results[0]["primary_similarity"] == 0.8

    @pytest.mark.asyncio
    async def test_context_aware_vector_search_with_context(self):
        """Test context-aware vector search with conversation context."""
        self.node.memory_logger = AsyncMock()
        self.node.embedder = AsyncMock()
        self.node.enable_context_search = True
        self.node.context_weight = 0.3

        # Mock memory logger responses
        self.node.memory_logger.search_memories.return_value = [
            {
                "content": "test content",
                "metadata": {},
                "namespace": "test_namespace",
                "vector": [0.1, 0.2, 0.3],
            }
        ]

        context = [{"content": "context information"}]

        with patch.object(self.node, "_generate_context_vector", return_value=[0.2, 0.3, 0.4]):
            with patch.object(self.node, "_cosine_similarity", side_effect=[0.7, 0.6]):
                results = await self.node._context_aware_vector_search(
                    [0.1, 0.2, 0.3],
                    "test_namespace",
                    context,
                    0.5,
                )

        assert len(results) == 1
        assert results[0]["primary_similarity"] == 0.7
        assert results[0]["context_similarity"] == 0.6
        assert results[0]["similarity"] > 0.7

    @pytest.mark.asyncio
    async def test_context_aware_vector_search_below_threshold(self):
        """Test context-aware vector search below similarity threshold."""
        self.node.redis = AsyncMock()
        self.node.similarity_threshold = 0.8

        # Mock Redis responses
        self.node.redis.keys.return_value = [b"orka:mem:test1"]
        self.node.redis.hget.side_effect = [
            b"test_namespace",
            b"mock_vector_bytes",
        ]

        with patch("orka.nodes.memory_reader_node.from_bytes") as mock_from_bytes:
            mock_from_bytes.return_value = [0.1, 0.2, 0.3]

            with patch.object(self.node, "_cosine_similarity", return_value=0.3):
                results = await self.node._context_aware_vector_search(
                    [0.1, 0.2, 0.3],
                    "test_namespace",
                    [],
                    0.8,
                )

        assert results == []


class TestMemoryReaderNodeContextVector:
    """Test context vector generation functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])

    @pytest.mark.asyncio
    async def test_generate_context_vector_basic(self):
        """Test basic context vector generation."""
        self.node.embedder = AsyncMock()
        self.node.embedder.encode.return_value = [0.1, 0.2, 0.3]

        context = [
            {"content": "first context item"},
            {"content": "second context item"},
            {"content": "third context item"},
        ]

        result = await self.node._generate_context_vector(context)

        assert result is not None
        assert result == [0.1, 0.2, 0.3]
        self.node.embedder.encode.assert_called_once()

    @pytest.mark.asyncio
    async def test_generate_context_vector_empty(self):
        """Test context vector generation with empty context."""
        result = await self.node._generate_context_vector([])
        assert result is None

        result = await self.node._generate_context_vector(None)
        assert result is None

    @pytest.mark.asyncio
    async def test_generate_context_vector_limit_recent(self):
        """Test context vector generation limits to recent items."""
        self.node.embedder = AsyncMock()
        self.node.embedder.encode.return_value = [0.1, 0.2, 0.3]

        context = [{"content": f"context item {i}"} for i in range(10)]

        await self.node._generate_context_vector(context)

        # Should combine only the last 3 items
        call_args = self.node.embedder.encode.call_args[0][0]
        assert "context item 7" in call_args
        assert "context item 8" in call_args
        assert "context item 9" in call_args
        assert "context item 0" not in call_args

    @pytest.mark.asyncio
    async def test_generate_context_vector_error(self):
        """Test context vector generation with encoder error."""
        self.node.embedder = AsyncMock()
        self.node.embedder.encode.side_effect = Exception("Encoding failed")

        context = [{"content": "test content"}]

        result = await self.node._generate_context_vector(context)
        assert result is None


class TestMemoryReaderNodeContextAwareStreamSearch:
    """Test context-aware stream search functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            self.node.similarity_threshold = 0.5
            self.node.context_weight = 0.3
            self.node.limit = 5

    @pytest.mark.asyncio
    async def test_context_aware_stream_search_basic(self):
        """Test basic context-aware stream search."""
        # Mock Redis client
        mock_redis = AsyncMock()
        mock_redis.xrange.return_value = [
            (
                b"1234567890-0",
                {b"payload": b'{"content": "test content", "metadata": {}}', b"ts": b"1234567890"},
            ),
            (
                b"1234567891-0",
                {b"payload": b'{"content": "other content", "metadata": {}}', b"ts": b"1234567891"},
            ),
        ]
        self.node.memory_logger = AsyncMock()
        self.node.memory_logger.redis = mock_redis
        self.node.embedder = AsyncMock()
        self.node.embedder.encode.side_effect = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]

        query_embedding = [0.1, 0.2, 0.3]

        with patch.object(self.node, "_cosine_similarity", side_effect=[0.8, 0.3]):
            results = await self.node._context_aware_stream_search(
                "test_stream",
                "test query",
                query_embedding,
                [],
                0.5,
            )

        assert len(results) == 1
        assert results[0]["content"] == "test content"
        assert results[0]["match_type"] == "context_aware_stream"
        assert results[0]["primary_similarity"] == 0.8

    @pytest.mark.asyncio
    async def test_context_aware_stream_search_with_context(self):
        """Test context-aware stream search with conversation context."""
        # Mock Redis client
        mock_redis = AsyncMock()
        mock_redis.xrange.return_value = [
            (
                b"1234567890-0",
                {b"payload": b'{"content": "test content", "metadata": {}}', b"ts": b"1234567890"},
            ),
        ]
        self.node.memory_logger = AsyncMock()
        self.node.memory_logger.redis = mock_redis
        self.node.embedder = AsyncMock()
        self.node.enable_context_search = True
        self.node.embedder.encode.return_value = [0.1, 0.2, 0.3]

        context = [{"content": "context information"}]

        with patch.object(self.node, "_generate_context_vector", return_value=[0.2, 0.3, 0.4]):
            with patch.object(self.node, "_cosine_similarity", side_effect=[0.7, 0.6]):
                results = await self.node._context_aware_stream_search(
                    "test_stream",
                    "test query",
                    [0.1, 0.2, 0.3],
                    context,
                    0.5,
                )

        assert len(results) == 1
        assert results[0]["context_similarity"] == 0.6
        assert results[0]["similarity"] > 0.7  # Should include context bonus

    @pytest.mark.asyncio
    async def test_context_aware_stream_search_keyword_bonus(self):
        """Test context-aware stream search with keyword matching bonus."""
        # Mock Redis client
        mock_redis = AsyncMock()
        mock_redis.xrange.return_value = [
            (
                b"1234567890-0",
                {
                    b"payload": b'{"content": "exact match content", "metadata": {}}',
                    b"ts": b"1234567890",
                },
            ),
        ]
        self.node.memory_logger = AsyncMock()
        self.node.memory_logger.redis = mock_redis
        self.node.embedder = AsyncMock()
        self.node.embedder.encode.return_value = [0.1, 0.2, 0.3]

        with patch.object(
            self.node,
            "_cosine_similarity",
            return_value=0.3,
        ):  # Below threshold normally
            results = await self.node._context_aware_stream_search(
                "test_stream",
                "exact match",
                [0.1, 0.2, 0.3],
                [],
                0.5,
            )

        assert len(results) == 1  # Should still be included due to keyword matches
        assert results[0]["keyword_matches"] == 2  # "exact" and "match"
        assert results[0]["similarity"] > 0.3  # Should include keyword bonus

    @pytest.mark.asyncio
    async def test_context_aware_stream_search_malformed_payload(self):
        """Test context-aware stream search with malformed payload."""
        # Mock Redis client
        mock_redis = AsyncMock()
        mock_redis.xrange.return_value = [
            (b"1234567890-0", {b"payload": b"invalid_json{", b"ts": b"1234567890"}),
            (
                b"1234567891-0",
                {b"payload": b'{"content": "valid content", "metadata": {}}', b"ts": b"1234567891"},
            ),
        ]
        self.node.memory_logger = AsyncMock()
        self.node.memory_logger.redis = mock_redis
        self.node.embedder = AsyncMock()
        self.node.embedder.encode.return_value = [0.1, 0.2, 0.3]

        with patch.object(self.node, "_cosine_similarity", return_value=0.8):
            results = await self.node._context_aware_stream_search(
                "test_stream",
                "test query",
                [0.1, 0.2, 0.3],
                [],
                0.5,
            )

        # Should skip malformed entry and return valid one
        assert len(results) == 1
        assert results[0]["content"] == "valid content"

    @pytest.mark.asyncio
    async def test_context_aware_stream_search_redis_error(self):
        """Test context-aware stream search with Redis error."""
        self.node.redis = AsyncMock()
        self.node.redis.xrange.side_effect = Exception("Redis error")

        results = await self.node._context_aware_stream_search(
            "test_stream",
            "test query",
            [0.1, 0.2, 0.3],
            [],
            0.5,
        )

        assert results == []


class TestMemoryReaderNodeHybridScoring:
    """Test hybrid scoring functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            self.node.enable_temporal_ranking = True
            self.node.temporal_decay_hours = 24

    def test_apply_hybrid_scoring_basic(self):
        """Test basic hybrid scoring."""
        memories = [
            {
                "content": "medium length content with reasonable amount of text",
                "similarity": 0.8,
                "metadata": {"category": "stored", "field1": "value1", "field2": "value2"},
                "timestamp": str(time.time() - 3600),  # 1 hour ago
            },
        ]

        result = self.node._apply_hybrid_scoring(memories, "test query", [])

        assert len(result) == 1
        # Final similarity may be boosted or reduced depending on factors
        assert result[0]["similarity"] != 0.8  # Should be modified
        assert "length_factor" in result[0]
        assert "recency_factor" in result[0]
        assert "metadata_factor" in result[0]

    def test_apply_hybrid_scoring_length_factors(self):
        """Test hybrid scoring with different content lengths."""
        memories = [
            {"content": "short", "similarity": 0.8, "metadata": {}},  # Too short
            {"content": " ".join(["word"] * 100), "similarity": 0.8, "metadata": {}},  # Sweet spot
            {"content": " ".join(["word"] * 600), "similarity": 0.8, "metadata": {}},  # Too long
        ]

        result = self.node._apply_hybrid_scoring(memories, "test query", [])

        assert len(result) == 3
        # Sweet spot should have highest score
        assert result[0]["length_factor"] == 1.1  # Sweet spot boost
        # Order should be by final similarity (sweet spot first)
        assert result[0]["content"] == " ".join(["word"] * 100)

    def test_apply_hybrid_scoring_temporal_ranking(self):
        """Test hybrid scoring with temporal ranking."""
        current_time = time.time()
        memories = [
            {
                "content": "recent content",
                "similarity": 0.8,
                "metadata": {},
                "timestamp": str(current_time - 1800),  # 30 minutes ago
            },
            {
                "content": "old content",
                "similarity": 0.8,
                "metadata": {},
                "ts": str((current_time - 86400) * 1000),  # 1 day ago (in milliseconds)
            },
        ]

        result = self.node._apply_hybrid_scoring(memories, "test query", [])

        assert len(result) == 2
        # Recent content should have higher recency factor
        recent_memory = next(m for m in result if m["content"] == "recent content")
        old_memory = next(m for m in result if m["content"] == "old content")

        assert recent_memory["recency_factor"] > old_memory["recency_factor"]

    def test_apply_hybrid_scoring_metadata_quality(self):
        """Test hybrid scoring with metadata quality factors."""
        memories = [
            {
                "content": "content with rich metadata",
                "similarity": 0.8,
                "metadata": {
                    "category": "stored",
                    "field1": "value1",
                    "field2": "value2",
                    "field3": "value3",
                    "field4": "value4",
                },
            },
            {
                "content": "content with minimal metadata",
                "similarity": 0.8,
                "metadata": {"category": "temporary"},
            },
        ]

        result = self.node._apply_hybrid_scoring(memories, "test query", [])

        assert len(result) == 2
        rich_metadata_memory = next(m for m in result if "rich metadata" in m["content"])
        minimal_metadata_memory = next(m for m in result if "minimal metadata" in m["content"])

        # Rich metadata should get higher factor
        assert rich_metadata_memory["metadata_factor"] > minimal_metadata_memory["metadata_factor"]
        # Stored category should get additional boost
        assert rich_metadata_memory["metadata_factor"] >= 1.1 * 1.05

    def test_apply_hybrid_scoring_empty_memories(self):
        """Test hybrid scoring with empty memories list."""
        result = self.node._apply_hybrid_scoring([], "test query", [])
        assert result == []

    def test_apply_hybrid_scoring_error_handling(self):
        """Test hybrid scoring with error scenarios."""
        memories = [
            {
                "content": "test content",
                "similarity": 0.8,
                "metadata": "invalid_metadata_not_dict",  # Invalid metadata
                "timestamp": "invalid_timestamp",  # Invalid timestamp
            },
        ]

        # Should handle errors gracefully
        result = self.node._apply_hybrid_scoring(memories, "test query", [])
        assert len(result) == 1
        # Similarity may be modified by length and other factors even with invalid metadata
        assert result[0]["similarity"] != 0.8  # Should be modified by length factor at least


class TestMemoryReaderNodeFilteringMethods:
    """Test memory filtering functionality."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])

    def test_filter_enhanced_relevant_memories_basic(self):
        """Test basic enhanced relevant memory filtering."""
        self.node.similarity_threshold = 0.5

        memories = [
            {"content": "machine learning algorithms", "similarity": 0.8},
            {"content": "weather forecast today", "similarity": 0.3},
            {"content": "deep learning networks", "similarity": 0.6},
        ]

        filtered = self.node._filter_enhanced_relevant_memories(memories, "machine learning", [])

        # Should include memories with keyword overlap or high similarity
        assert len(filtered) >= 2
        assert any("machine learning" in m["content"] for m in filtered)
        assert any("deep learning" in m["content"] for m in filtered)

    def test_filter_enhanced_relevant_memories_with_context(self):
        """Test enhanced filtering with conversation context."""
        self.node.similarity_threshold = 0.5

        memories = [
            {"content": "neural network architecture", "similarity": 0.4},
            {"content": "cooking recipes", "similarity": 0.2},
        ]

        context = [{"content": "Tell me about neural networks and architecture"}]

        filtered = self.node._filter_enhanced_relevant_memories(memories, "deep learning", context)

        # Should include first memory due to context overlap
        assert len(filtered) >= 1
        assert "neural network" in filtered[0]["content"]

    def test_filter_by_category_enabled(self):
        """Test category filtering when enabled."""
        self.node.memory_category_filter = "stored"

        memories = [
            {"content": "stored memory", "metadata": {"category": "stored"}},
            {"content": "temporary memory", "metadata": {"category": "temporary"}},
            {
                "content": "direct category",
                "category": "stored",
            },  # This won't be found due to elif logic
        ]

        filtered = self.node._filter_by_category(memories)

        # Only metadata-based categories are found due to elif logic in implementation
        assert len(filtered) == 1
        assert filtered[0]["content"] == "stored memory"

    def test_filter_by_category_direct_field(self):
        """Test category filtering with direct category field (no metadata dict)."""
        self.node.memory_category_filter = "stored"

        memories = [
            {
                "content": "direct stored",
                "category": "stored",
                "metadata": "not_a_dict",
            },  # metadata is not dict
            {
                "content": "direct temp",
                "category": "temporary",
                "metadata": "not_a_dict",
            },  # metadata is not dict
        ]

        filtered = self.node._filter_by_category(memories)

        assert len(filtered) == 1
        assert filtered[0]["content"] == "direct stored"

    def test_filter_by_category_disabled(self):
        """Test category filtering when disabled."""
        self.node.memory_category_filter = None

        memories = [
            {"content": "memory1", "metadata": {"category": "stored"}},
            {"content": "memory2", "metadata": {"category": "temporary"}},
        ]

        filtered = self.node._filter_by_category(memories)

        assert len(filtered) == 2  # Should return all memories

    def test_filter_expired_memories_disabled(self):
        """Test expired memory filtering when disabled."""
        self.node.decay_config = {"enabled": False}

        memories = [
            {"content": "expired memory", "metadata": {"expiry_time": 1000}},
            {"content": "active memory", "metadata": {"expiry_time": time.time() * 1000 + 10000}},
        ]

        with patch("time.time", return_value=2000):
            filtered = self.node._filter_expired_memories(memories)

        assert len(filtered) == 2  # Should return all memories

    def test_filter_expired_memories_with_expiry_time(self):
        """Test expired memory filtering with explicit expiry times."""
        self.node.decay_config = {"enabled": True}

        current_time = time.time() * 1000
        memories = [
            {"content": "expired memory", "metadata": {"expiry_time": current_time - 1000}},
            {"content": "active memory", "metadata": {"expiry_time": current_time + 10000}},
            {"content": "direct expiry", "expiry_time": current_time + 5000},
        ]

        with patch("time.time", return_value=current_time / 1000):
            filtered = self.node._filter_expired_memories(memories)

        assert len(filtered) == 2
        assert all(m["content"] in ["active memory", "direct expiry"] for m in filtered)

    def test_filter_expired_memories_with_decay_rules(self):
        """Test expired memory filtering with decay rules."""
        self.node.decay_config = {
            "enabled": True,
            "short_term_hours": 1.0,
            "long_term_hours": 24.0,
        }

        current_time = time.time() * 1000
        old_time = current_time - 7200 * 1000  # 2 hours ago

        memories = [
            {
                "content": "expired short term",
                "metadata": {"memory_type": "short_term", "created_at": str(old_time / 1000)},
            },
            {
                "content": "active long term",
                "metadata": {"memory_type": "long_term", "created_at": str(old_time / 1000)},
            },
        ]

        with patch("time.time", return_value=current_time / 1000):
            filtered = self.node._filter_expired_memories(memories)

        assert len(filtered) == 1
        assert filtered[0]["content"] == "active long term"


class TestMemoryReaderNodeLegacyMethods:
    """Test legacy compatibility methods."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])

    @pytest.mark.asyncio
    async def test_legacy_keyword_search(self):
        """Test legacy keyword search method."""
        with patch.object(
            self.node,
            "_enhanced_keyword_search",
            return_value=[{"test": "result"}],
        ) as mock_enhanced:
            result = await self.node._keyword_search("namespace", "query")

            mock_enhanced.assert_called_once_with("namespace", "query", [])
            assert result == [{"test": "result"}]

    @pytest.mark.asyncio
    async def test_legacy_vector_search(self):
        """Test legacy vector search method."""
        with patch.object(
            self.node,
            "_context_aware_vector_search",
            return_value=[{"test": "result"}],
        ) as mock_vector:
            result = await self.node._vector_search([0.1, 0.2], "namespace", 0.5)

            mock_vector.assert_called_once_with([0.1, 0.2], "namespace", [], 0.5)
            assert result == [{"test": "result"}]

    @pytest.mark.asyncio
    async def test_legacy_stream_search(self):
        """Test legacy stream search method."""
        with patch.object(
            self.node,
            "_context_aware_stream_search",
            return_value=[{"test": "result"}],
        ) as mock_stream:
            result = await self.node._stream_search("stream_key", "query", [0.1, 0.2], 0.5)

            mock_stream.assert_called_once_with("stream_key", "query", [0.1, 0.2], [], 0.5)
            assert result == [{"test": "result"}]

    def test_legacy_filter_relevant_memories(self):
        """Test legacy filter relevant memories method."""
        with patch.object(
            self.node,
            "_filter_enhanced_relevant_memories",
            return_value=[{"test": "result"}],
        ) as mock_filter:
            result = self.node._filter_relevant_memories([{"memory": "data"}], "query")

            mock_filter.assert_called_once_with([{"memory": "data"}], "query", [])
            assert result == [{"test": "result"}]


class TestMemoryReaderNodeCosineSimilarity:
    """Test cosine similarity calculation."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])

    def test_cosine_similarity_identical_vectors(self):
        """Test cosine similarity with identical vectors."""
        vec1 = [1.0, 2.0, 3.0]
        vec2 = [1.0, 2.0, 3.0]

        similarity = self.node._cosine_similarity(vec1, vec2)

        assert abs(similarity - 1.0) < 1e-10

    def test_cosine_similarity_orthogonal_vectors(self):
        """Test cosine similarity with orthogonal vectors."""
        vec1 = [1.0, 0.0, 0.0]
        vec2 = [0.0, 1.0, 0.0]

        similarity = self.node._cosine_similarity(vec1, vec2)

        assert abs(similarity - 0.0) < 1e-10

    def test_cosine_similarity_opposite_vectors(self):
        """Test cosine similarity with opposite vectors."""
        vec1 = [1.0, 2.0, 3.0]
        vec2 = [-1.0, -2.0, -3.0]

        similarity = self.node._cosine_similarity(vec1, vec2)

        assert abs(similarity - (-1.0)) < 1e-10

    def test_cosine_similarity_zero_vectors(self):
        """Test cosine similarity with zero vectors."""
        vec1 = [0.0, 0.0, 0.0]
        vec2 = [1.0, 2.0, 3.0]

        similarity = self.node._cosine_similarity(vec1, vec2)

        assert similarity == 0.0

    def test_cosine_similarity_numpy_arrays(self):
        """Test cosine similarity with numpy arrays."""
        import numpy as np

        vec1 = np.array([1.0, 2.0, 3.0])
        vec2 = np.array([2.0, 4.0, 6.0])

        similarity = self.node._cosine_similarity(vec1, vec2)

        assert abs(similarity - 1.0) < 1e-10

    def test_cosine_similarity_error_handling(self):
        """Test cosine similarity error handling."""
        # Test with invalid input that causes numpy error
        with patch("numpy.dot", side_effect=Exception("Numpy error")):
            similarity = self.node._cosine_similarity([1, 2, 3], [4, 5, 6])
            assert similarity == 0.0


class TestMemoryReaderNodeAdditionalEdgeCases:
    """Test additional edge cases to reach 100% coverage."""

    def setup_method(self):
        """Set up test fixtures."""
        with (
            patch("orka.memory_logger.create_memory_logger"),
            patch(
                "orka.utils.embedder.get_embedder",
            ),
        ):
            self.node = MemoryReaderNode(node_id="test_node", prompt="test_prompt", queue=[])
            self.node.similarity_threshold = 0.5
            self.node.context_weight = 0.3
            self.node.limit = 5
            self.node.enable_context_search = True
            self.node.enable_temporal_ranking = True

    @pytest.mark.asyncio
    async def test_generate_context_vector_empty_content_only(self):
        """Test context vector generation with only empty content."""
        self.node.embedder = AsyncMock()

        context = [
            {"content": ""},  # Empty content
            {"content": "   "},  # Only whitespace
            {"other": "no content field"},  # No content field
        ]

        result = await self.node._generate_context_vector(context)
        assert result is None  # Should return None for no valid content

    @pytest.mark.asyncio
    async def test_stream_search_empty_content_handling(self):
        """Test stream search with empty content in payload."""
        # Mock Redis client
        mock_redis = AsyncMock()
        mock_redis.xrange.return_value = [
            (
                b"1234567890-0",
                {b"payload": b'{"content": "", "metadata": {}}', b"ts": b"1234567890"},
            ),  # Empty content
            (
                b"1234567891-0",
                {b"payload": b'{"content": "valid content", "metadata": {}}', b"ts": b"1234567891"},
            ),
        ]
        self.node.memory_logger = AsyncMock()
        self.node.memory_logger.redis = mock_redis
        self.node.embedder = AsyncMock()
        self.node.embedder.encode.return_value = [0.1, 0.2, 0.3]

        with patch.object(self.node, "_cosine_similarity", return_value=0.8):
            results = await self.node._context_aware_stream_search(
                "test_stream",
                "test query",
                [0.1, 0.2, 0.3],
                [],
                0.5,
            )

        # Should skip empty content and return only valid one
        assert len(results) == 1
        assert results[0]["content"] == "valid content"

    def test_filter_enhanced_relevant_memories_empty_list(self):
        """Test enhanced filtering with empty memories list."""
        result = self.node._filter_enhanced_relevant_memories([], "query", [])
        assert result == []

    def test_filter_enhanced_relevant_memories_no_relevance(self):
        """Test enhanced filtering with no relevant memories."""
        self.node.similarity_threshold = 0.9  # High threshold

        memories = [
            {"content": "completely unrelated content", "similarity": 0.1},
            {"content": "another unrelated item", "similarity": 0.2},
        ]

        result = self.node._filter_enhanced_relevant_memories(memories, "specific query", [])
        assert result == []  # No memories should be relevant

    @pytest.mark.asyncio
    async def test_enhanced_keyword_search_no_namespace_match(self):
        """Test enhanced keyword search with no namespace matches."""
        self.node.redis = AsyncMock()

        # Mock Redis responses with different namespace
        self.node.redis.keys.return_value = [b"orka:mem:test1"]
        self.node.redis.hget.side_effect = [
            b"different_namespace",  # Different namespace
        ]

        results = await self.node._enhanced_keyword_search("target_namespace", "query", [])
        assert results == []

    @pytest.mark.asyncio
    async def test_context_aware_vector_search_no_vector_data(self):
        """Test context-aware vector search with missing vector data."""
        self.node.redis = AsyncMock()

        # Mock Redis responses with no vector data
        self.node.redis.keys.return_value = [b"orka:mem:test1"]
        self.node.redis.hget.side_effect = [
            b"test_namespace",  # namespace
            None,  # No vector data
        ]

        results = await self.node._context_aware_vector_search(
            [0.1, 0.2, 0.3],
            "test_namespace",
            [],
            0.5,
        )
        assert results == []

    def test_apply_hybrid_scoring_no_timestamp(self):
        """Test hybrid scoring with missing timestamp data."""
        memories = [
            {
                "content": "test content",
                "similarity": 0.8,
                "metadata": {},
                # No timestamp or ts field
            },
        ]

        result = self.node._apply_hybrid_scoring(memories, "test query", [])

        assert len(result) == 1
        assert result[0]["recency_factor"] == 1.0  # Should default to 1.0

    def test_apply_hybrid_scoring_invalid_timestamp_format(self):
        """Test hybrid scoring with invalid timestamp format."""
        memories = [
            {
                "content": "test content",
                "similarity": 0.8,
                "metadata": {},
                "timestamp": "not_a_number",
            },
        ]

        result = self.node._apply_hybrid_scoring(memories, "test query", [])

        assert len(result) == 1
        assert result[0]["recency_factor"] == 1.0  # Should fallback to 1.0

    def test_filter_enhanced_relevant_memories_short_query_handling(self):
        """Test enhanced filtering with short query special handling."""
        self.node.similarity_threshold = 0.9  # High threshold

        memories = [
            {"content": "test content here", "similarity": 0.1},  # Low similarity normally
        ]

        # Short query (≤ 20 chars) with word match should be relevant
        result = self.node._filter_enhanced_relevant_memories(memories, "test", [])

        assert len(result) == 1  # Should be included due to short query + word match
        assert result[0]["content"] == "test content here"

    @pytest.mark.asyncio
    async def test_enhanced_keyword_search_metadata_json_error(self):
        """Test enhanced keyword search with JSON parsing error in metadata."""
        # Mock memory logger
        self.node.memory_logger = AsyncMock()
        self.node.memory_logger.search_memories.return_value = [
            {
                "content": "test content with keywords",
                "metadata": "invalid_json{[",  # Invalid JSON
                "namespace": "test_namespace",
            }
        ]

        results = await self.node._enhanced_keyword_search("test_namespace", "keywords", [])

        # Should still work, just with empty metadata
        assert len(results) == 1
        assert results[0]["metadata"] == {}

    def test_apply_hybrid_scoring_various_content_lengths(self):
        """Test hybrid scoring with various content lengths to hit all branches."""
        memories = [
            {"content": "tiny", "similarity": 0.8, "metadata": {}},  # < 10 words
            {"content": " ".join(["word"] * 75), "similarity": 0.8, "metadata": {}},  # 50-200 words
            {"content": " ".join(["word"] * 550), "similarity": 0.8, "metadata": {}},  # > 500 words
            {"content": " ".join(["word"] * 25), "similarity": 0.8, "metadata": {}},  # 10-50 words
        ]

        result = self.node._apply_hybrid_scoring(memories, "test query", [])

        assert len(result) == 4
        # Check different length factors are applied
        tiny_memory = next(m for m in result if m["content"] == "tiny")
        sweet_spot_memory = next(m for m in result if len(m["content"].split()) == 75)
        long_memory = next(m for m in result if len(m["content"].split()) == 550)

        assert tiny_memory["length_factor"] == 0.8  # Too short penalty
        assert sweet_spot_memory["length_factor"] == 1.1  # Sweet spot boost
        assert long_memory["length_factor"] == 0.9  # Too long penalty