Spaces:
Running
Running
File size: 65,517 Bytes
eb1c19a 5f8e891 eb1c19a 934f3c4 eb1c19a 5f8e891 eb1c19a 934f3c4 eb1c19a | 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 | """Comprehensive tests for Headroom's memory system.
Tests cover:
- Entity and Relationship graph models
- InMemoryGraphStore operations
- MemorySystem orchestrator
- Memory tool definitions
- LocalBackend integration
Following the patterns established in test_memory_eval.py and test_memory/test_hierarchical.py.
"""
# CRITICAL: Must set TOKENIZERS_PARALLELISM before any imports that might
# trigger sentence_transformers/transformers loading.
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import pytest
# Check if hnswlib is available for LocalBackend tests
try:
from headroom.memory.adapters.hnsw import _check_hnswlib_available
HNSW_AVAILABLE = _check_hnswlib_available()
except ImportError:
HNSW_AVAILABLE = False
from headroom.memory.adapters.graph import InMemoryGraphStore
from headroom.memory.adapters.graph_models import (
Entity,
Relationship,
RelationshipDirection,
Subgraph,
)
from headroom.memory.models import Memory
from headroom.memory.ports import MemorySearchResult as PortsMemorySearchResult
from headroom.memory.system import MemorySearchResult, MemorySystem
from headroom.memory.tools import MEMORY_TOOLS, get_memory_tools, get_tool_names
# =============================================================================
# Fixtures
# =============================================================================
@pytest.fixture
def graph_store():
"""Create a fresh InMemoryGraphStore for testing."""
return InMemoryGraphStore()
@pytest.fixture
def sample_entity():
"""Create a sample entity for testing."""
return Entity(
id="entity-1",
user_id="alice",
name="Project Alpha",
entity_type="project",
description="Main development project",
properties={"status": "active", "priority": 1},
metadata={"source": "test"},
)
@pytest.fixture
def sample_relationship():
"""Create a sample relationship for testing."""
return Relationship(
id="rel-1",
user_id="alice",
source_id="entity-1",
target_id="entity-2",
relation_type="works_on",
weight=0.9,
properties={"role": "lead"},
metadata={"source": "test"},
)
@pytest.fixture
def temp_db_path():
"""Create a temporary database path."""
with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
yield Path(f.name)
# =============================================================================
# TestEntity and TestRelationship - Unit tests for graph models
# =============================================================================
class TestEntity:
"""Tests for Entity dataclass."""
def test_entity_creation_with_defaults(self):
"""Test entity creation with default values."""
entity = Entity()
assert entity.id is not None # Auto-generated UUID
assert entity.user_id == ""
assert entity.name == ""
assert entity.entity_type == "unknown"
assert entity.description is None
assert entity.properties == {}
assert entity.metadata == {}
assert entity.created_at is not None
assert entity.updated_at is not None
def test_entity_creation_with_values(self, sample_entity):
"""Test entity creation with provided values."""
assert sample_entity.id == "entity-1"
assert sample_entity.user_id == "alice"
assert sample_entity.name == "Project Alpha"
assert sample_entity.entity_type == "project"
assert sample_entity.description == "Main development project"
assert sample_entity.properties["status"] == "active"
assert sample_entity.metadata["source"] == "test"
def test_entity_to_dict(self, sample_entity):
"""Test entity serialization to dictionary."""
data = sample_entity.to_dict()
assert data["id"] == "entity-1"
assert data["user_id"] == "alice"
assert data["name"] == "Project Alpha"
assert data["entity_type"] == "project"
assert data["description"] == "Main development project"
assert data["properties"]["status"] == "active"
assert "created_at" in data
assert "updated_at" in data
def test_entity_from_dict(self, sample_entity):
"""Test entity deserialization from dictionary."""
data = sample_entity.to_dict()
restored = Entity.from_dict(data)
assert restored.id == sample_entity.id
assert restored.user_id == sample_entity.user_id
assert restored.name == sample_entity.name
assert restored.entity_type == sample_entity.entity_type
assert restored.description == sample_entity.description
assert restored.properties == sample_entity.properties
def test_entity_roundtrip(self, sample_entity):
"""Test entity serialization roundtrip."""
data = sample_entity.to_dict()
restored = Entity.from_dict(data)
data2 = restored.to_dict()
assert data == data2
class TestRelationship:
"""Tests for Relationship dataclass."""
def test_relationship_creation_with_defaults(self):
"""Test relationship creation with default values."""
rel = Relationship()
assert rel.id is not None # Auto-generated UUID
assert rel.user_id == ""
assert rel.source_id == ""
assert rel.target_id == ""
assert rel.relation_type == "related_to"
assert rel.weight == 1.0
assert rel.properties == {}
assert rel.metadata == {}
def test_relationship_creation_with_values(self, sample_relationship):
"""Test relationship creation with provided values."""
assert sample_relationship.id == "rel-1"
assert sample_relationship.user_id == "alice"
assert sample_relationship.source_id == "entity-1"
assert sample_relationship.target_id == "entity-2"
assert sample_relationship.relation_type == "works_on"
assert sample_relationship.weight == 0.9
assert sample_relationship.properties["role"] == "lead"
def test_relationship_to_dict(self, sample_relationship):
"""Test relationship serialization to dictionary."""
data = sample_relationship.to_dict()
assert data["id"] == "rel-1"
assert data["source_id"] == "entity-1"
assert data["target_id"] == "entity-2"
assert data["relation_type"] == "works_on"
assert data["weight"] == 0.9
assert "created_at" in data
def test_relationship_from_dict(self, sample_relationship):
"""Test relationship deserialization from dictionary."""
data = sample_relationship.to_dict()
restored = Relationship.from_dict(data)
assert restored.id == sample_relationship.id
assert restored.source_id == sample_relationship.source_id
assert restored.target_id == sample_relationship.target_id
assert restored.relation_type == sample_relationship.relation_type
assert restored.weight == sample_relationship.weight
def test_relationship_roundtrip(self, sample_relationship):
"""Test relationship serialization roundtrip."""
data = sample_relationship.to_dict()
restored = Relationship.from_dict(data)
data2 = restored.to_dict()
assert data == data2
class TestSubgraph:
"""Tests for Subgraph dataclass."""
def test_subgraph_creation_empty(self):
"""Test empty subgraph creation."""
subgraph = Subgraph()
assert subgraph.entities == []
assert subgraph.relationships == []
assert subgraph.root_entity_ids == []
def test_subgraph_entity_ids(self):
"""Test entity_ids property."""
entities = [
Entity(id="e1", name="Entity 1"),
Entity(id="e2", name="Entity 2"),
Entity(id="e3", name="Entity 3"),
]
subgraph = Subgraph(entities=entities)
assert subgraph.entity_ids == {"e1", "e2", "e3"}
def test_subgraph_relationship_ids(self):
"""Test relationship_ids property."""
relationships = [
Relationship(id="r1", source_id="e1", target_id="e2"),
Relationship(id="r2", source_id="e2", target_id="e3"),
]
subgraph = Subgraph(relationships=relationships)
assert subgraph.relationship_ids == {"r1", "r2"}
def test_subgraph_get_entity(self):
"""Test get_entity method."""
e1 = Entity(id="e1", name="Entity 1")
e2 = Entity(id="e2", name="Entity 2")
subgraph = Subgraph(entities=[e1, e2])
assert subgraph.get_entity("e1") == e1
assert subgraph.get_entity("e2") == e2
assert subgraph.get_entity("e3") is None
def test_subgraph_get_neighbors(self):
"""Test get_neighbors method."""
e1 = Entity(id="e1", name="Entity 1")
e2 = Entity(id="e2", name="Entity 2")
e3 = Entity(id="e3", name="Entity 3")
r1 = Relationship(id="r1", source_id="e1", target_id="e2")
r2 = Relationship(id="r2", source_id="e1", target_id="e3")
subgraph = Subgraph(entities=[e1, e2, e3], relationships=[r1, r2])
neighbors = subgraph.get_neighbors("e1")
neighbor_ids = {n.id for n in neighbors}
assert neighbor_ids == {"e2", "e3"}
# e2 only connected to e1
neighbors_e2 = subgraph.get_neighbors("e2")
assert len(neighbors_e2) == 1
assert neighbors_e2[0].id == "e1"
def test_subgraph_to_dict(self):
"""Test subgraph serialization."""
e1 = Entity(id="e1", name="Entity 1", user_id="alice", entity_type="person")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
subgraph = Subgraph(
entities=[e1],
relationships=[r1],
root_entity_ids=["e1"],
)
data = subgraph.to_dict()
assert len(data["entities"]) == 1
assert len(data["relationships"]) == 1
assert data["root_entity_ids"] == ["e1"]
def test_subgraph_from_dict(self):
"""Test subgraph deserialization."""
e1 = Entity(id="e1", name="Entity 1", user_id="alice", entity_type="person")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
subgraph = Subgraph(
entities=[e1],
relationships=[r1],
root_entity_ids=["e1"],
)
data = subgraph.to_dict()
restored = Subgraph.from_dict(data)
assert len(restored.entities) == 1
assert restored.entities[0].id == "e1"
assert len(restored.relationships) == 1
assert restored.root_entity_ids == ["e1"]
class TestSubgraphToContext:
"""Tests for Subgraph.to_context() method (from ports.py)."""
def test_to_context_empty_subgraph(self):
"""Test to_context with empty subgraph."""
from headroom.memory.ports import Subgraph as PortsSubgraph
subgraph = PortsSubgraph()
context = subgraph.to_context()
assert context == ""
def test_to_context_entities_only(self):
"""Test to_context with only entities."""
from headroom.memory.ports import Entity as PortsEntity
from headroom.memory.ports import Subgraph as PortsSubgraph
entities = [
PortsEntity(id="e1", name="Alice", entity_type="person", user_id="user1"),
PortsEntity(
id="e2",
name="Project X",
entity_type="project",
user_id="user1",
metadata={"status": "active"},
),
]
subgraph = PortsSubgraph(entities=entities)
context = subgraph.to_context()
assert "Entities:" in context
assert "Alice (person)" in context
assert "Project X (project)" in context
assert "[status=active]" in context
def test_to_context_with_relationships(self):
"""Test to_context with entities and relationships."""
from headroom.memory.ports import Entity as PortsEntity
from headroom.memory.ports import Relationship as PortsRel
from headroom.memory.ports import Subgraph as PortsSubgraph
entities = [
PortsEntity(id="e1", name="Alice", entity_type="person", user_id="user1"),
PortsEntity(id="e2", name="Project X", entity_type="project", user_id="user1"),
]
relationships = [
PortsRel(
source_entity_id="e1",
target_entity_id="e2",
relation_type="works_on",
user_id="user1",
)
]
subgraph = PortsSubgraph(entities=entities, relationships=relationships)
context = subgraph.to_context()
assert "Entities:" in context
assert "Relationships:" in context
assert "Alice --[works_on]--> Project X" in context
def test_to_context_with_weighted_relationships(self):
"""Test to_context with weighted relationships."""
from headroom.memory.ports import Entity as PortsEntity
from headroom.memory.ports import Relationship as PortsRel
from headroom.memory.ports import Subgraph as PortsSubgraph
entities = [
PortsEntity(id="e1", name="Alice", entity_type="person", user_id="user1"),
PortsEntity(id="e2", name="Bob", entity_type="person", user_id="user1"),
]
relationships = [
PortsRel(
source_entity_id="e1",
target_entity_id="e2",
relation_type="knows",
weight=0.8,
user_id="user1",
)
]
subgraph = PortsSubgraph(entities=entities, relationships=relationships)
context = subgraph.to_context()
assert "Alice --[knows]--> Bob" in context
assert "(weight=0.8)" in context
# =============================================================================
# TestInMemoryGraphStore - Integration tests for graph store
# =============================================================================
class TestInMemoryGraphStore:
"""Tests for InMemoryGraphStore."""
@pytest.mark.asyncio
async def test_add_entity(self, graph_store, sample_entity):
"""Test adding an entity."""
await graph_store.add_entity(sample_entity)
retrieved = await graph_store.get_entity(sample_entity.id)
assert retrieved is not None
assert retrieved.id == sample_entity.id
assert retrieved.name == sample_entity.name
@pytest.mark.asyncio
async def test_add_entity_replaces_existing(self, graph_store):
"""Test that adding an entity with same ID replaces it."""
entity1 = Entity(id="e1", user_id="alice", name="Original")
entity2 = Entity(id="e1", user_id="alice", name="Updated")
await graph_store.add_entity(entity1)
await graph_store.add_entity(entity2)
retrieved = await graph_store.get_entity("e1")
assert retrieved.name == "Updated"
assert graph_store.entity_count == 1
@pytest.mark.asyncio
async def test_get_entity_not_found(self, graph_store):
"""Test getting a non-existent entity."""
result = await graph_store.get_entity("nonexistent")
assert result is None
@pytest.mark.asyncio
async def test_delete_entity(self, graph_store, sample_entity):
"""Test deleting an entity."""
await graph_store.add_entity(sample_entity)
deleted = await graph_store.delete_entity(sample_entity.id)
assert deleted is True
retrieved = await graph_store.get_entity(sample_entity.id)
assert retrieved is None
@pytest.mark.asyncio
async def test_delete_entity_not_found(self, graph_store):
"""Test deleting a non-existent entity."""
deleted = await graph_store.delete_entity("nonexistent")
assert deleted is False
@pytest.mark.asyncio
async def test_delete_entity_cascades_relationships(self, graph_store):
"""Test that deleting an entity also deletes its relationships."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
rel = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_relationship(rel)
assert graph_store.relationship_count == 1
await graph_store.delete_entity("e1")
assert graph_store.relationship_count == 0
@pytest.mark.asyncio
async def test_add_relationship(self, graph_store, sample_relationship):
"""Test adding a relationship."""
# First add the entities
e1 = Entity(id="entity-1", user_id="alice", name="Entity 1")
e2 = Entity(id="entity-2", user_id="alice", name="Entity 2")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_relationship(sample_relationship)
assert graph_store.relationship_count == 1
@pytest.mark.asyncio
async def test_get_relationships_outgoing(self, graph_store):
"""Test getting outgoing relationships."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
e3 = Entity(id="e3", user_id="alice", name="Entity 3")
r1 = Relationship(
id="r1", user_id="alice", source_id="e1", target_id="e2", relation_type="a"
)
r2 = Relationship(
id="r2", user_id="alice", source_id="e1", target_id="e3", relation_type="b"
)
r3 = Relationship(
id="r3", user_id="alice", source_id="e2", target_id="e1", relation_type="c"
)
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_entity(e3)
await graph_store.add_relationship(r1)
await graph_store.add_relationship(r2)
await graph_store.add_relationship(r3)
# Get outgoing from e1
outgoing = await graph_store.get_relationships(
"e1", direction=RelationshipDirection.OUTGOING
)
assert len(outgoing) == 2
@pytest.mark.asyncio
async def test_get_relationships_incoming(self, graph_store):
"""Test getting incoming relationships."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
r1 = Relationship(id="r1", user_id="alice", source_id="e2", target_id="e1")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_relationship(r1)
incoming = await graph_store.get_relationships(
"e1", direction=RelationshipDirection.INCOMING
)
assert len(incoming) == 1
assert incoming[0].source_id == "e2"
@pytest.mark.asyncio
async def test_get_relationships_both(self, graph_store):
"""Test getting relationships in both directions."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
e3 = Entity(id="e3", user_id="alice", name="Entity 3")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
r2 = Relationship(id="r2", user_id="alice", source_id="e3", target_id="e1")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_entity(e3)
await graph_store.add_relationship(r1)
await graph_store.add_relationship(r2)
both = await graph_store.get_relationships("e1", direction=RelationshipDirection.BOTH)
assert len(both) == 2
@pytest.mark.asyncio
async def test_get_relationships_with_type_filter(self, graph_store):
"""Test filtering relationships by type."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
e3 = Entity(id="e3", user_id="alice", name="Entity 3")
r1 = Relationship(
id="r1",
user_id="alice",
source_id="e1",
target_id="e2",
relation_type="works_with",
)
r2 = Relationship(
id="r2",
user_id="alice",
source_id="e1",
target_id="e3",
relation_type="manages",
)
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_entity(e3)
await graph_store.add_relationship(r1)
await graph_store.add_relationship(r2)
# Filter by type
works_with = await graph_store.get_relationships("e1", relation_type="works_with")
assert len(works_with) == 1
assert works_with[0].target_id == "e2"
@pytest.mark.asyncio
async def test_delete_relationship(self, graph_store):
"""Test deleting a relationship."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_relationship(r1)
deleted = await graph_store.delete_relationship("r1")
assert deleted is True
assert graph_store.relationship_count == 0
@pytest.mark.asyncio
async def test_delete_relationship_not_found(self, graph_store):
"""Test deleting a non-existent relationship."""
deleted = await graph_store.delete_relationship("nonexistent")
assert deleted is False
@pytest.mark.asyncio
async def test_get_entity_by_name_case_insensitive(self, graph_store):
"""Test case-insensitive entity lookup by name."""
entity = Entity(id="e1", user_id="alice", name="Project Alpha", entity_type="project")
await graph_store.add_entity(entity)
# Exact case
result = await graph_store.get_entity_by_name("alice", "Project Alpha")
assert result is not None
assert result.id == "e1"
# Lowercase
result = await graph_store.get_entity_by_name("alice", "project alpha")
assert result is not None
assert result.id == "e1"
# Uppercase
result = await graph_store.get_entity_by_name("alice", "PROJECT ALPHA")
assert result is not None
assert result.id == "e1"
# Mixed case
result = await graph_store.get_entity_by_name("alice", "pRoJeCt AlPhA")
assert result is not None
assert result.id == "e1"
@pytest.mark.asyncio
async def test_get_entity_by_name_wrong_user(self, graph_store):
"""Test that entity lookup respects user scope."""
entity = Entity(id="e1", user_id="alice", name="Project Alpha")
await graph_store.add_entity(entity)
result = await graph_store.get_entity_by_name("bob", "Project Alpha")
assert result is None
@pytest.mark.asyncio
async def test_query_subgraph_single_hop(self, graph_store):
"""Test querying subgraph with single hop."""
# Create a simple graph: e1 -> e2 -> e3
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
e3 = Entity(id="e3", user_id="alice", name="Entity 3")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
r2 = Relationship(id="r2", user_id="alice", source_id="e2", target_id="e3")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_entity(e3)
await graph_store.add_relationship(r1)
await graph_store.add_relationship(r2)
# Query 1 hop from e1
subgraph = await graph_store.query_subgraph(["e1"], max_hops=1)
assert len(subgraph.entities) == 2 # e1 and e2
assert len(subgraph.relationships) == 1 # r1 only
assert subgraph.root_entity_ids == ["e1"]
@pytest.mark.asyncio
async def test_query_subgraph_multiple_hops(self, graph_store):
"""Test querying subgraph with multiple hops."""
# Create a chain: e1 -> e2 -> e3 -> e4
entities = [Entity(id=f"e{i}", user_id="alice", name=f"Entity {i}") for i in range(1, 5)]
relationships = [
Relationship(id=f"r{i}", user_id="alice", source_id=f"e{i}", target_id=f"e{i + 1}")
for i in range(1, 4)
]
for e in entities:
await graph_store.add_entity(e)
for r in relationships:
await graph_store.add_relationship(r)
# Query 2 hops from e1
subgraph = await graph_store.query_subgraph(["e1"], max_hops=2)
# Should include e1, e2, e3 (not e4)
assert len(subgraph.entities) == 3
entity_ids = {e.id for e in subgraph.entities}
assert entity_ids == {"e1", "e2", "e3"}
@pytest.mark.asyncio
async def test_query_subgraph_with_relation_type_filter(self, graph_store):
"""Test querying subgraph with relation type filter."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
e3 = Entity(id="e3", user_id="alice", name="Entity 3")
r1 = Relationship(
id="r1",
user_id="alice",
source_id="e1",
target_id="e2",
relation_type="works_with",
)
r2 = Relationship(
id="r2",
user_id="alice",
source_id="e1",
target_id="e3",
relation_type="manages",
)
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_entity(e3)
await graph_store.add_relationship(r1)
await graph_store.add_relationship(r2)
# Query only "works_with" relationships
subgraph = await graph_store.query_subgraph(
["e1"], max_hops=1, relation_types=["works_with"]
)
assert len(subgraph.entities) == 2 # e1 and e2
assert len(subgraph.relationships) == 1
assert subgraph.relationships[0].relation_type == "works_with"
@pytest.mark.asyncio
async def test_query_subgraph_multiple_start_entities(self, graph_store):
"""Test querying subgraph from multiple starting entities."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
e3 = Entity(id="e3", user_id="alice", name="Entity 3")
e4 = Entity(id="e4", user_id="alice", name="Entity 4")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e3")
r2 = Relationship(id="r2", user_id="alice", source_id="e2", target_id="e4")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_entity(e3)
await graph_store.add_entity(e4)
await graph_store.add_relationship(r1)
await graph_store.add_relationship(r2)
# Query from both e1 and e2
subgraph = await graph_store.query_subgraph(["e1", "e2"], max_hops=1)
assert len(subgraph.entities) == 4
assert len(subgraph.relationships) == 2
@pytest.mark.asyncio
async def test_find_path_direct_connection(self, graph_store):
"""Test finding a path between directly connected entities."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_relationship(r1)
path = await graph_store.find_path("e1", "e2")
assert path is not None
assert path == ["e1", "e2"]
@pytest.mark.asyncio
async def test_find_path_multi_hop(self, graph_store):
"""Test finding a path through multiple hops."""
# e1 -> e2 -> e3 -> e4
entities = [Entity(id=f"e{i}", user_id="alice", name=f"Entity {i}") for i in range(1, 5)]
relationships = [
Relationship(id=f"r{i}", user_id="alice", source_id=f"e{i}", target_id=f"e{i + 1}")
for i in range(1, 4)
]
for e in entities:
await graph_store.add_entity(e)
for r in relationships:
await graph_store.add_relationship(r)
path = await graph_store.find_path("e1", "e4")
assert path is not None
assert path == ["e1", "e2", "e3", "e4"]
@pytest.mark.asyncio
async def test_find_path_no_path_exists(self, graph_store):
"""Test finding a path when no path exists."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
path = await graph_store.find_path("e1", "e2")
assert path is None
@pytest.mark.asyncio
async def test_find_path_same_entity(self, graph_store):
"""Test finding a path from an entity to itself."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
await graph_store.add_entity(e1)
path = await graph_store.find_path("e1", "e1")
assert path == ["e1"]
@pytest.mark.asyncio
async def test_find_path_max_depth_exceeded(self, graph_store):
"""Test that find_path respects max_depth."""
# Create a chain longer than max_depth
entities = [Entity(id=f"e{i}", user_id="alice", name=f"Entity {i}") for i in range(1, 6)]
relationships = [
Relationship(id=f"r{i}", user_id="alice", source_id=f"e{i}", target_id=f"e{i + 1}")
for i in range(1, 5)
]
for e in entities:
await graph_store.add_entity(e)
for r in relationships:
await graph_store.add_relationship(r)
# Path e1 -> e5 requires 4 hops, but we limit to 2
path = await graph_store.find_path("e1", "e5", max_depth=2)
assert path is None
@pytest.mark.asyncio
async def test_clear_user(self, graph_store):
"""Test clearing all data for a user."""
# Create data for alice
e1 = Entity(id="e1", user_id="alice", name="Alice Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Alice Entity 2")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
# Create data for bob
e3 = Entity(id="e3", user_id="bob", name="Bob Entity")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_entity(e3)
await graph_store.add_relationship(r1)
# Clear alice's data
entities_deleted, relationships_deleted = await graph_store.clear_user("alice")
assert entities_deleted == 2
assert relationships_deleted == 1
# Bob's data should remain
assert await graph_store.get_entity("e3") is not None
assert await graph_store.get_entity("e1") is None
@pytest.mark.asyncio
async def test_get_entities_for_user(self, graph_store):
"""Test getting all entities for a user."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="alice", name="Entity 2")
e3 = Entity(id="e3", user_id="bob", name="Entity 3")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_entity(e3)
alice_entities = await graph_store.get_entities_for_user("alice")
assert len(alice_entities) == 2
bob_entities = await graph_store.get_entities_for_user("bob")
assert len(bob_entities) == 1
@pytest.mark.asyncio
async def test_clear_all(self, graph_store):
"""Test clearing all data from the store."""
e1 = Entity(id="e1", user_id="alice", name="Entity 1")
e2 = Entity(id="e2", user_id="bob", name="Entity 2")
r1 = Relationship(id="r1", user_id="alice", source_id="e1", target_id="e2")
await graph_store.add_entity(e1)
await graph_store.add_entity(e2)
await graph_store.add_relationship(r1)
await graph_store.clear()
assert graph_store.entity_count == 0
assert graph_store.relationship_count == 0
def test_stats(self, graph_store):
"""Test stats method."""
stats = graph_store.stats()
assert "entity_count" in stats
assert "relationship_count" in stats
assert "users_count" in stats
assert stats["entity_count"] == 0
# =============================================================================
# TestMemorySystem - Tests for the orchestrator
# =============================================================================
class MockBackend:
"""Mock backend for testing MemorySystem without real storage."""
def __init__(self):
self._memories: dict[str, Memory] = {}
async def save_memory(
self,
content: str,
user_id: str,
importance: float,
entities: list[str] | None = None,
relationships: list[dict[str, str]] | None = None,
session_id: str | None = None,
metadata: dict[str, Any] | None = None,
# Pre-extraction fields for optimized storage (optional)
facts: list[str] | None = None,
extracted_entities: list[dict[str, str]] | None = None,
extracted_relationships: list[dict[str, str]] | None = None,
background: bool | None = None,
) -> Memory:
memory = Memory(
content=content,
user_id=user_id,
importance=importance,
entity_refs=entities or [],
session_id=session_id,
metadata=metadata or {},
)
self._memories[memory.id] = memory
return memory
async def search_memories(
self,
query: str,
user_id: str,
entities: list[str] | None = None,
include_related: bool = False,
top_k: int = 10,
session_id: str | None = None,
) -> list[MemorySearchResult]:
results = []
for memory in self._memories.values():
if memory.user_id == user_id:
results.append(
MemorySearchResult(
memory=memory,
score=0.9,
)
)
return results[:top_k]
async def update_memory(
self,
memory_id: str,
new_content: str,
reason: str | None = None,
user_id: str | None = None,
) -> Memory:
if memory_id not in self._memories:
raise ValueError(f"Memory not found: {memory_id}")
old_memory = self._memories[memory_id]
new_memory = Memory(
content=new_content,
user_id=old_memory.user_id,
importance=old_memory.importance,
supersedes=memory_id,
)
self._memories[new_memory.id] = new_memory
old_memory.superseded_by = new_memory.id
old_memory.valid_until = datetime.now(timezone.utc).replace(tzinfo=None)
return new_memory
async def delete_memory(
self,
memory_id: str,
reason: str | None = None,
user_id: str | None = None,
) -> bool:
if memory_id in self._memories:
del self._memories[memory_id]
return True
return False
async def get_memory(self, memory_id: str) -> Memory | None:
return self._memories.get(memory_id)
@property
def supports_graph(self) -> bool:
return False
@property
def supports_vector_search(self) -> bool:
return True
@pytest.fixture
def mock_backend():
"""Create a mock backend for testing."""
return MockBackend()
@pytest.fixture
def memory_system(mock_backend):
"""Create a MemorySystem with mock backend."""
return MemorySystem(mock_backend, user_id="alice", session_id="session-1")
class TestMemorySystem:
"""Tests for MemorySystem orchestrator."""
@pytest.mark.asyncio
async def test_handle_memory_save_valid(self, memory_system):
"""Test saving a memory with valid inputs."""
result = await memory_system.handle_memory_save(
content="User prefers Python",
importance=0.8,
entities=["Python"],
)
assert result["success"] is True
assert "memory_id" in result
assert result["content"] == "User prefers Python"
assert result["importance"] == 0.8
@pytest.mark.asyncio
async def test_handle_memory_save_with_metadata(self, memory_system):
"""Test saving a memory with optional metadata."""
result = await memory_system.handle_memory_save(
content="Test content",
importance=0.5,
metadata={"source": "test", "context": "unit-test"},
)
assert result["success"] is True
assert "memory_id" in result
@pytest.mark.asyncio
async def test_handle_memory_save_invalid_importance_high(self, memory_system):
"""Test saving a memory with importance > 1.0."""
result = await memory_system.handle_memory_save(
content="Test content",
importance=1.5,
)
assert result["success"] is False
assert "Invalid importance" in result["error"]
@pytest.mark.asyncio
async def test_handle_memory_save_invalid_importance_low(self, memory_system):
"""Test saving a memory with importance < 0.0."""
result = await memory_system.handle_memory_save(
content="Test content",
importance=-0.1,
)
assert result["success"] is False
assert "Invalid importance" in result["error"]
@pytest.mark.asyncio
async def test_handle_memory_search(self, memory_system, mock_backend):
"""Test searching memories."""
# First save a memory
await mock_backend.save_memory(
content="User prefers Python",
user_id="alice",
importance=0.8,
)
result = await memory_system.handle_memory_search(
query="programming preferences",
top_k=5,
)
assert result["success"] is True
assert result["count"] >= 1
assert len(result["memories"]) >= 1
@pytest.mark.asyncio
async def test_handle_memory_search_empty_results(self, memory_system):
"""Test search with no matching memories."""
result = await memory_system.handle_memory_search(
query="nonexistent topic",
)
# Should succeed but with no results
assert result["success"] is True
assert result["count"] == 0
assert result["memories"] == []
@pytest.mark.asyncio
async def test_handle_memory_update(self, memory_system, mock_backend):
"""Test updating a memory."""
# First save a memory
memory = await mock_backend.save_memory(
content="User prefers Python",
user_id="alice",
importance=0.8,
)
result = await memory_system.handle_memory_update(
memory_id=memory.id,
new_content="User now prefers Rust",
reason="Changed preference",
)
assert result["success"] is True
assert result["old_content"] == "User prefers Python"
assert result["new_content"] == "User now prefers Rust"
@pytest.mark.asyncio
async def test_handle_memory_update_not_found(self, memory_system):
"""Test updating a non-existent memory."""
result = await memory_system.handle_memory_update(
memory_id="nonexistent-id",
new_content="New content",
reason="Test update",
)
assert result["success"] is False
assert "Memory not found" in result["error"]
@pytest.mark.asyncio
async def test_handle_memory_update_wrong_user(self, memory_system, mock_backend):
"""Test updating a memory belonging to another user."""
# Save memory for bob
memory = await mock_backend.save_memory(
content="Bob's memory",
user_id="bob", # Different user
importance=0.5,
)
# Try to update as alice
result = await memory_system.handle_memory_update(
memory_id=memory.id,
new_content="Trying to update",
reason="Test",
)
assert result["success"] is False
assert "Permission denied" in result["error"]
@pytest.mark.asyncio
async def test_handle_memory_delete(self, memory_system, mock_backend):
"""Test deleting a memory."""
memory = await mock_backend.save_memory(
content="Memory to delete",
user_id="alice",
importance=0.5,
)
result = await memory_system.handle_memory_delete(
memory_id=memory.id,
reason="No longer needed",
)
assert result["success"] is True
assert result["deleted_content"] == "Memory to delete"
@pytest.mark.asyncio
async def test_handle_memory_delete_not_found(self, memory_system):
"""Test deleting a non-existent memory."""
result = await memory_system.handle_memory_delete(
memory_id="nonexistent-id",
reason="Test delete",
)
assert result["success"] is False
assert "Memory not found" in result["error"]
@pytest.mark.asyncio
async def test_handle_memory_delete_wrong_user(self, memory_system, mock_backend):
"""Test deleting a memory belonging to another user."""
memory = await mock_backend.save_memory(
content="Bob's memory",
user_id="bob",
importance=0.5,
)
result = await memory_system.handle_memory_delete(
memory_id=memory.id,
reason="Test",
)
assert result["success"] is False
assert "Permission denied" in result["error"]
@pytest.mark.asyncio
async def test_process_tool_call_memory_save(self, memory_system):
"""Test process_tool_call dispatcher for memory_save."""
result = await memory_system.process_tool_call(
"memory_save",
{
"content": "Test content",
"importance": 0.5,
},
)
assert result["success"] is True
@pytest.mark.asyncio
async def test_process_tool_call_memory_search(self, memory_system):
"""Test process_tool_call dispatcher for memory_search."""
result = await memory_system.process_tool_call(
"memory_search",
{"query": "test query"},
)
assert result["success"] is True
@pytest.mark.asyncio
async def test_process_tool_call_unknown_tool(self, memory_system):
"""Test process_tool_call with unknown tool name."""
result = await memory_system.process_tool_call(
"unknown_tool",
{},
)
assert result["success"] is False
assert "Unknown tool" in result["error"]
@pytest.mark.asyncio
async def test_process_tool_call_handles_exception(self, memory_system):
"""Test that process_tool_call handles exceptions gracefully."""
# Missing required argument should cause an exception
result = await memory_system.process_tool_call(
"memory_save",
{
# Missing required "content" field
"importance": 0.5,
},
)
assert result["success"] is False
assert "error" in result
def test_get_tools(self, memory_system):
"""Test that get_tools returns the tool definitions."""
tools = memory_system.get_tools()
assert isinstance(tools, list)
assert len(tools) >= 4 # At least 4 memory tools
def test_properties(self, memory_system):
"""Test MemorySystem properties."""
assert memory_system.user_id == "alice"
assert memory_system.session_id == "session-1"
assert memory_system.supports_vector_search is True
assert memory_system.supports_graph is False
# =============================================================================
# TestMemoryTools - Tests for tool definitions
# =============================================================================
class TestMemoryTools:
"""Tests for memory tool definitions."""
def test_get_memory_tools_returns_list(self):
"""Test that get_memory_tools returns a list."""
tools = get_memory_tools()
assert isinstance(tools, list)
assert len(tools) >= 4
def test_get_memory_tools_returns_copy(self):
"""Test that get_memory_tools returns a copy, not the original."""
tools1 = get_memory_tools()
tools2 = get_memory_tools()
assert tools1 is not tools2
def test_get_tool_names(self):
"""Test that get_tool_names returns correct tool names."""
names = get_tool_names()
assert "memory_save" in names
assert "memory_search" in names
assert "memory_update" in names
assert "memory_delete" in names
def test_tools_have_openai_format(self):
"""Test that tools are in OpenAI function calling format."""
for tool in MEMORY_TOOLS:
assert "type" in tool
assert tool["type"] == "function"
assert "function" in tool
def test_tools_have_required_fields(self):
"""Test that all tools have required fields."""
for tool in MEMORY_TOOLS:
func = tool["function"]
assert "name" in func
assert "description" in func
assert "parameters" in func
params = func["parameters"]
assert "type" in params
assert params["type"] == "object"
assert "properties" in params
def test_memory_save_tool_structure(self):
"""Test memory_save tool has correct structure."""
save_tool = next(t for t in MEMORY_TOOLS if t["function"]["name"] == "memory_save")
params = save_tool["function"]["parameters"]
properties = params["properties"]
# Check required fields exist (category is no longer part of the API)
assert "content" in properties
assert "importance" in properties
assert "entities" in properties
assert "relationships" in properties
# Check required array
assert "required" in params
assert "content" in params["required"]
assert "importance" in params["required"]
def test_memory_search_tool_structure(self):
"""Test memory_search tool has correct structure."""
search_tool = next(t for t in MEMORY_TOOLS if t["function"]["name"] == "memory_search")
params = search_tool["function"]["parameters"]
properties = params["properties"]
assert "query" in properties
assert "entities" in properties
assert "top_k" in properties
# Query is required
assert "query" in params["required"]
def test_memory_update_tool_structure(self):
"""Test memory_update tool has correct structure."""
update_tool = next(t for t in MEMORY_TOOLS if t["function"]["name"] == "memory_update")
params = update_tool["function"]["parameters"]
properties = params["properties"]
assert "memory_id" in properties
assert "new_content" in properties
assert "reason" in properties
# Required fields for update (reason is optional)
assert "memory_id" in params["required"]
assert "new_content" in params["required"]
def test_memory_delete_tool_structure(self):
"""Test memory_delete tool has correct structure."""
delete_tool = next(t for t in MEMORY_TOOLS if t["function"]["name"] == "memory_delete")
params = delete_tool["function"]["parameters"]
properties = params["properties"]
assert "memory_id" in properties
assert "reason" in properties
# Required fields for delete (reason is optional)
assert "memory_id" in params["required"]
def test_tool_descriptions_are_helpful(self):
"""Test that tool descriptions contain useful information."""
for tool in MEMORY_TOOLS:
description = tool["function"]["description"]
# Description should be substantive
assert len(description) > 50
# Should contain guidance on when to use
assert any(
keyword in description.lower() for keyword in ["use", "when", "for", "example"]
)
def test_importance_parameter(self):
"""Test that importance parameter is defined correctly."""
save_tool = next(t for t in MEMORY_TOOLS if t["function"]["name"] == "memory_save")
importance_prop = save_tool["function"]["parameters"]["properties"]["importance"]
# Importance should be a number type
assert importance_prop["type"] == "number"
# =============================================================================
# TestLocalBackend - Integration tests
# =============================================================================
@pytest.mark.skipif(not HNSW_AVAILABLE, reason="hnswlib not available")
class TestLocalBackend:
"""Integration tests for LocalBackend."""
@pytest.fixture
def backend_config(self, temp_db_path):
"""Create backend config with temp database."""
from headroom.memory.backends.local import LocalBackendConfig
return LocalBackendConfig(
db_path=str(temp_db_path),
embedder_model="all-MiniLM-L6-v2",
vector_dimension=384,
)
@pytest.fixture
def backend(self, backend_config):
"""Create LocalBackend instance."""
from headroom.memory.backends.local import LocalBackend
return LocalBackend(backend_config)
@pytest.mark.asyncio
async def test_save_memory_basic(self, backend):
"""Test saving a basic memory."""
memory = await backend.save_memory(
content="User prefers Python",
user_id="alice",
importance=0.8,
)
assert memory is not None
assert memory.content == "User prefers Python"
assert memory.user_id == "alice"
assert memory.importance == 0.8
@pytest.mark.asyncio
async def test_save_memory_with_entities(self, backend):
"""Test saving a memory with entities."""
memory = await backend.save_memory(
content="Alice works at Acme Corp",
user_id="alice",
importance=0.7,
entities=["Alice", "Acme Corp"],
)
assert "Alice" in memory.entity_refs
assert "Acme Corp" in memory.entity_refs
# Verify entities were added to graph
graph = await backend.get_graph()
alice_entity = await graph.get_entity_by_name("alice", "Alice")
acme_entity = await graph.get_entity_by_name("alice", "Acme Corp")
assert alice_entity is not None
assert acme_entity is not None
@pytest.mark.asyncio
async def test_save_memory_with_relationships(self, backend):
"""Test saving a memory with relationships."""
await backend.save_memory(
content="Alice works at Acme Corp",
user_id="alice",
importance=0.7,
entities=["Alice", "Acme Corp"],
relationships=[{"source": "Alice", "target": "Acme Corp", "type": "works_at"}],
)
# Verify relationship was created
graph = await backend.get_graph()
alice_entity = await graph.get_entity_by_name("alice", "Alice")
rels = await graph.get_relationships(alice_entity.id)
assert len(rels) >= 1
works_at_rels = [r for r in rels if r.relation_type == "works_at"]
assert len(works_at_rels) == 1
@pytest.mark.asyncio
async def test_search_memories_basic(self, backend):
"""Test basic memory search."""
# Save some memories
await backend.save_memory(
content="User prefers Python for data science",
user_id="alice",
importance=0.8,
)
await backend.save_memory(
content="User likes JavaScript for web development",
user_id="alice",
importance=0.7,
)
# Search
results = await backend.search_memories(
query="programming language preferences",
user_id="alice",
top_k=5,
)
assert len(results) >= 1
assert all(isinstance(r, PortsMemorySearchResult) for r in results)
@pytest.mark.asyncio
async def test_search_memories_with_entity_filter(self, backend):
"""Test memory search with entity filter."""
await backend.save_memory(
content="Alice manages the Python project",
user_id="user1",
importance=0.7,
entities=["Alice", "Python project"],
)
await backend.save_memory(
content="Bob works on the Java project",
user_id="user1",
importance=0.7,
entities=["Bob", "Java project"],
)
# Search with entity filter
results = await backend.search_memories(
query="project work",
user_id="user1",
entities=["Alice"],
top_k=10,
)
# Results should be related to Alice
assert len(results) >= 1
for r in results:
assert any("alice" in entity.lower() for entity in r.memory.entity_refs) or any(
"alice" in entity.lower() for entity in r.related_entities
)
@pytest.mark.asyncio
async def test_search_memories_graph_expansion(self, backend):
"""Test that search includes graph-expanded results."""
# Create memories with connected entities
await backend.save_memory(
content="Alice manages Project X",
user_id="alice",
importance=0.8,
entities=["Alice", "Project X"],
relationships=[{"source": "Alice", "target": "Project X", "type": "manages"}],
)
await backend.save_memory(
content="Project X uses Python",
user_id="alice",
importance=0.7,
entities=["Project X", "Python"],
relationships=[{"source": "Project X", "target": "Python", "type": "uses"}],
)
# Search should potentially return related memories via graph
results = await backend.search_memories(
query="Alice's work",
user_id="alice",
include_related=True,
top_k=10,
)
# Should have results (graph expansion may include connected memories)
assert len(results) >= 1
@pytest.mark.asyncio
async def test_update_memory_creates_version_chain(self, backend):
"""Test that updating a memory creates a supersession chain."""
# Save original memory
original = await backend.save_memory(
content="User prefers Python",
user_id="alice",
importance=0.8,
)
# Update it
updated = await backend.update_memory(
memory_id=original.id,
new_content="User now prefers Rust",
)
# Check the chain
assert updated.supersedes == original.id
# Original should be marked as superseded
retrieved_original = await backend.get_memory(original.id)
assert retrieved_original.superseded_by == updated.id
assert retrieved_original.is_current is False
@pytest.mark.asyncio
async def test_update_memory_not_found(self, backend):
"""Test updating a non-existent memory raises error."""
with pytest.raises(ValueError, match="not found"):
await backend.update_memory(
memory_id="nonexistent-id",
new_content="New content",
)
@pytest.mark.asyncio
async def test_delete_memory(self, backend):
"""Test deleting a memory."""
memory = await backend.save_memory(
content="Memory to delete",
user_id="alice",
importance=0.5,
)
deleted = await backend.delete_memory(memory.id)
assert deleted is True
# Should be gone
retrieved = await backend.get_memory(memory.id)
assert retrieved is None
@pytest.mark.asyncio
async def test_delete_memory_cleans_up_graph(self, backend):
"""Test that deleting a memory cleans up graph entities."""
memory = await backend.save_memory(
content="Alice works at Acme",
user_id="alice",
importance=0.7,
entities=["Alice", "Acme"],
)
# Verify entities exist
graph = await backend.get_graph()
alice_before = await graph.get_entity_by_name("alice", "Alice")
assert alice_before is not None
# Delete memory
await backend.delete_memory(memory.id)
# Entities created from this memory should be deleted
alice_after = await graph.get_entity_by_name("alice", "Alice")
assert alice_after is None
@pytest.mark.asyncio
async def test_delete_memory_not_found(self, backend):
"""Test deleting a non-existent memory returns False."""
deleted = await backend.delete_memory("nonexistent-id")
assert deleted is False
@pytest.mark.asyncio
async def test_get_memory(self, backend):
"""Test getting a memory by ID."""
memory = await backend.save_memory(
content="Test memory",
user_id="alice",
importance=0.5,
)
retrieved = await backend.get_memory(memory.id)
assert retrieved is not None
assert retrieved.id == memory.id
assert retrieved.content == memory.content
@pytest.mark.asyncio
async def test_get_memory_not_found(self, backend):
"""Test getting a non-existent memory returns None."""
retrieved = await backend.get_memory("nonexistent-id")
assert retrieved is None
@pytest.mark.asyncio
async def test_get_user_memories(self, backend):
"""Test getting all memories for a user."""
# Save memories for alice
await backend.save_memory(content="Alice memory 1", user_id="alice", importance=0.5)
await backend.save_memory(content="Alice memory 2", user_id="alice", importance=0.5)
# Save memory for bob
await backend.save_memory(content="Bob memory", user_id="bob", importance=0.5)
alice_memories = await backend.get_user_memories("alice")
assert len(alice_memories) == 2
@pytest.mark.asyncio
async def test_clear_user(self, backend):
"""Test clearing all data for a user."""
# Save memories with entities
await backend.save_memory(
content="Alice memory",
user_id="alice",
importance=0.5,
entities=["Entity1"],
)
await backend.save_memory(
content="Alice memory 2",
user_id="alice",
importance=0.5,
)
# Save for bob
await backend.save_memory(content="Bob memory", user_id="bob", importance=0.5)
count = await backend.clear_user("alice")
assert count == 2
# Alice's memories should be gone
alice_memories = await backend.get_user_memories("alice")
assert len(alice_memories) == 0
# Bob's should remain
bob_memories = await backend.get_user_memories("bob")
assert len(bob_memories) == 1
@pytest.mark.asyncio
async def test_query_subgraph(self, backend):
"""Test querying subgraph from the backend."""
# Create a graph structure
await backend.save_memory(
content="Alice manages Project X",
user_id="alice",
importance=0.8,
entities=["Alice", "Project X"],
relationships=[{"source": "Alice", "target": "Project X", "type": "manages"}],
)
subgraph = await backend.query_subgraph(
entity_names=["Alice"],
user_id="alice",
max_hops=1,
)
assert len(subgraph.entities) >= 1
entity_names = {e.name.lower() for e in subgraph.entities}
assert "alice" in entity_names
@pytest.mark.asyncio
async def test_properties(self, backend):
"""Test backend property accessors."""
# Force initialization
await backend._ensure_initialized()
assert backend.supports_graph is True
assert backend.supports_vector_search is True
assert backend.supports_text_search is True
@pytest.mark.asyncio
async def test_close(self, backend):
"""Test closing the backend."""
await backend._ensure_initialized()
assert backend._initialized is True
await backend.close()
assert backend._initialized is False
assert backend._hierarchical_memory is None
assert backend._graph is None
# =============================================================================
# Edge Cases and Error Handling
# =============================================================================
class TestEdgeCases:
"""Tests for edge cases and error handling."""
@pytest.mark.asyncio
async def test_empty_content_save(self):
"""Test saving memory with empty content."""
backend = MockBackend()
system = MemorySystem(backend, user_id="alice")
# Empty content should still work (validation is content-level)
result = await system.handle_memory_save(
content="",
importance=0.5,
)
# Should succeed (empty content is allowed)
assert result["success"] is True
@pytest.mark.asyncio
async def test_importance_boundary_values(self):
"""Test importance at exact boundary values."""
backend = MockBackend()
system = MemorySystem(backend, user_id="alice")
# Exactly 0.0
result = await system.handle_memory_save(content="Test", importance=0.0)
assert result["success"] is True
# Exactly 1.0
result = await system.handle_memory_save(content="Test", importance=1.0)
assert result["success"] is True
@pytest.mark.asyncio
async def test_search_top_k_clamping(self):
"""Test that top_k is clamped to valid range."""
backend = MockBackend()
system = MemorySystem(backend, user_id="alice")
# Very large top_k should be clamped
result = await system.handle_memory_search(
query="test",
top_k=1000, # Should be clamped to 50
)
assert result["success"] is True
# Zero top_k should be clamped to 1
result = await system.handle_memory_search(
query="test",
top_k=0,
)
assert result["success"] is True
@pytest.mark.asyncio
async def test_graph_store_thread_safety(self, graph_store):
"""Test that graph store handles concurrent operations."""
import asyncio
# Create entities concurrently
async def add_entity(i: int):
entity = Entity(id=f"e{i}", user_id="alice", name=f"Entity {i}")
await graph_store.add_entity(entity)
await asyncio.gather(*[add_entity(i) for i in range(100)])
assert graph_store.entity_count == 100
@pytest.mark.asyncio
async def test_subgraph_with_nonexistent_entities(self, graph_store):
"""Test querying subgraph with non-existent entity IDs."""
subgraph = await graph_store.query_subgraph(
["nonexistent-1", "nonexistent-2"],
max_hops=2,
)
# Should return empty subgraph
assert len(subgraph.entities) == 0
assert len(subgraph.relationships) == 0
@pytest.mark.asyncio
async def test_find_path_nonexistent_entities(self, graph_store):
"""Test finding path with non-existent entities."""
path = await graph_store.find_path("nonexistent-1", "nonexistent-2")
assert path is None
def test_entity_properties_mutable(self):
"""Test that entity properties dict is mutable."""
entity = Entity(id="e1", properties={"key": "value"})
entity.properties["new_key"] = "new_value"
assert "new_key" in entity.properties
def test_relationship_metadata_mutable(self):
"""Test that relationship metadata dict is mutable."""
rel = Relationship(id="r1", metadata={"key": "value"})
rel.metadata["new_key"] = "new_value"
assert "new_key" in rel.metadata
|