File size: 25,440 Bytes
0ae3f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
End-to-end tests for graph cleanup on memory deletion (issue #3245).

Uses a real Kuzu embedded database to verify that graph entities are
correctly cleaned up when memories are deleted. LLM and embedding calls
are mocked to provide deterministic entity extraction.

Tests are skipped automatically if kuzu is not installed.
"""

import shutil
import tempfile
from unittest.mock import MagicMock, patch

import pytest

from mem0.configs.base import MemoryConfig

try:
    import kuzu  # noqa: F401
    _kuzu_available = True
except ImportError:
    _kuzu_available = False

requires_kuzu = pytest.mark.skipif(not _kuzu_available, reason="kuzu is not installed")

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _node_count(kuzu_graph):
    """Return total node count in the Kuzu graph."""
    result = kuzu_graph.execute("MATCH (n:Entity) RETURN count(n) AS cnt")
    rows = list(result.rows_as_dict())
    return int(rows[0]["cnt"])


def _edge_count(kuzu_graph):
    """Return total edge count in the Kuzu graph."""
    result = kuzu_graph.execute("MATCH ()-[r:CONNECTED_TO]->() RETURN count(r) AS cnt")
    rows = list(result.rows_as_dict())
    return int(rows[0]["cnt"])


def _get_edges(kuzu_graph):
    """Return all edges as list of (source, relationship, destination) tuples."""
    result = kuzu_graph.execute(
        "MATCH (s:Entity)-[r:CONNECTED_TO]->(d:Entity) "
        "RETURN s.name AS src, r.name AS rel, d.name AS dst"
    )
    return [(row["src"], row["rel"], row["dst"]) for row in result.rows_as_dict()]


def _get_nodes(kuzu_graph):
    """Return all node names."""
    result = kuzu_graph.execute("MATCH (n:Entity) RETURN n.name AS name, n.user_id AS uid")
    return [(row["name"], row["uid"]) for row in result.rows_as_dict()]


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


class MockVectorMemory:
    """Mimics the object returned by vector_store.get()."""

    def __init__(self, memory_id, payload, score=0.8):
        self.id = memory_id
        self.payload = payload
        self.score = score


@pytest.fixture
def kuzu_graph_memory():
    """
    Create a real Kuzu-backed MemoryGraph with mocked LLM and embedder.
    Yields (graph_memory_instance, kuzu_connection) then cleans up.
    """
    import os

    import kuzu

    tmpdir = tempfile.mkdtemp()
    db_path = os.path.join(tmpdir, "test.kuzu")
    db = kuzu.Database(db_path)
    conn = kuzu.Connection(db)

    # We'll construct the MemoryGraph by bypassing __init__ and setting up manually
    from mem0.memory.kuzu_memory import MemoryGraph

    mg = MemoryGraph.__new__(MemoryGraph)

    # Real Kuzu connection
    mg.db = db
    mg.graph = conn
    mg.node_label = ":Entity"
    mg.rel_label = ":CONNECTED_TO"
    mg.kuzu_create_schema()

    # Deterministic embedding: use one-hot-style vectors per entity name
    # to avoid accidental cosine similarity matches between different entities
    embedding_dims = 64
    mg.embedding_dims = embedding_dims

    _embed_cache = {}
    _embed_counter = [0]

    def deterministic_embed(text):
        """Generate a deterministic, near-orthogonal embedding for each unique text."""
        text_lower = text.lower().strip()
        if text_lower not in _embed_cache:
            # Create a sparse vector — set a unique dimension to 1.0
            vec = [0.0] * embedding_dims
            idx = _embed_counter[0] % embedding_dims
            vec[idx] = 1.0
            # Add small noise to other dims so it's not exactly zero
            import hashlib

            h = hashlib.sha256(text_lower.encode()).digest()
            for i in range(embedding_dims):
                vec[i] += float(h[i % len(h)]) / 25500.0  # tiny noise
            norm = sum(v * v for v in vec) ** 0.5
            _embed_cache[text_lower] = [v / norm for v in vec]
            _embed_counter[0] += 1
        return _embed_cache[text_lower]

    mock_embedder = MagicMock()
    mock_embedder.embed.side_effect = deterministic_embed
    mock_embedder.config.embedding_dims = embedding_dims
    mg.embedding_model = mock_embedder

    # Mock LLM — configured per-test via mock_embedder
    mg.llm = MagicMock()
    mg.llm_provider = "openai"
    mg.user_id = None
    # High threshold so only identical entity names merge, not similar ones
    mg.threshold = 0.99
    mg.config = MagicMock()
    mg.config.graph_store.custom_prompt = None

    yield mg, conn

    # Cleanup
    conn.close()
    shutil.rmtree(tmpdir, ignore_errors=True)


def _setup_llm_for_entities(mg, entities, relations):
    """
    Configure the mock LLM to return specific entities and relations.

    entities: list of {"entity": str, "entity_type": str}
    relations: list of {"source": str, "destination": str, "relationship": str}
    """

    def generate_response(messages, tools):
        # Detect which tool is being called based on tool definition names
        tool_names = []
        for t in tools:
            if isinstance(t, dict):
                fn = t.get("function", t)
                tool_names.append(fn.get("name", ""))
            else:
                tool_names.append(getattr(t, "name", str(t)))

        if any("extract_entities" in n for n in tool_names):
            return {
                "tool_calls": [
                    {
                        "name": "extract_entities",
                        "arguments": {"entities": entities},
                    }
                ]
            }
        elif any("establish" in n or "relation" in n for n in tool_names):
            return {
                "tool_calls": [
                    {
                        "name": "establish_nodes_relations",
                        "arguments": {"entities": relations},
                    }
                ]
            }
        elif any("delete" in n for n in tool_names):
            # For _get_delete_entities_from_search_output during add() — return nothing to delete
            return {"tool_calls": []}
        return {"tool_calls": []}

    mg.llm.generate_response.side_effect = generate_response


# ---------------------------------------------------------------------------
# End-to-end tests
# ---------------------------------------------------------------------------


@requires_kuzu
class TestKuzuGraphDeleteE2E:
    """End-to-end tests using a real Kuzu database."""

    def test_add_creates_nodes_and_edges(self, kuzu_graph_memory):
        """Baseline: verify add() actually creates graph data."""
        mg, conn = kuzu_graph_memory

        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )

        filters = {"user_id": "test_user"}
        mg.add("Alice likes Bob", filters)

        assert _node_count(conn) == 2
        assert _edge_count(conn) == 1
        edges = _get_edges(conn)
        assert ("alice", "likes", "bob") in edges

    def test_delete_removes_edges_created_by_add(self, kuzu_graph_memory):
        """Core test: delete() should remove the relationships that add() created."""
        mg, conn = kuzu_graph_memory

        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )

        filters = {"user_id": "test_user"}
        mg.add("Alice likes Bob", filters)

        assert _edge_count(conn) == 1

        # Now delete using the same text — should remove the relationship
        mg.delete("Alice likes Bob", filters)

        assert _edge_count(conn) == 0
        # Nodes remain (we don't delete nodes on single memory delete)
        assert _node_count(conn) == 2

    def test_delete_only_removes_matching_edges(self, kuzu_graph_memory):
        """delete() should only remove edges matching the extracted relationships."""
        mg, conn = kuzu_graph_memory

        # First add: Alice likes Bob
        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )
        filters = {"user_id": "test_user"}
        mg.add("Alice likes Bob", filters)

        # Second add: Alice knows Charlie
        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Charlie", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Charlie", "relationship": "knows"},
            ],
        )
        mg.add("Alice knows Charlie", filters)

        assert _edge_count(conn) == 2

        # Delete only the "Alice likes Bob" memory
        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )
        mg.delete("Alice likes Bob", filters)

        assert _edge_count(conn) == 1
        edges = _get_edges(conn)
        assert ("alice", "knows", "charlie") in edges
        assert ("alice", "likes", "bob") not in edges

    def test_delete_with_different_user_id_does_not_affect_other_users(self, kuzu_graph_memory):
        """delete() scoped to user_id should not touch another user's graph data."""
        mg, conn = kuzu_graph_memory

        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )

        # Add for user1
        mg.add("Alice likes Bob", {"user_id": "user1"})
        # Add same data for user2
        mg.add("Alice likes Bob", {"user_id": "user2"})

        assert _edge_count(conn) == 2

        # Delete only user1's data
        mg.delete("Alice likes Bob", {"user_id": "user1"})

        assert _edge_count(conn) == 1
        # Remaining edge belongs to user2
        nodes = _get_nodes(conn)
        user2_nodes = [n for n in nodes if n[1] == "user2"]
        assert len(user2_nodes) == 2

    def test_delete_nonexistent_relationship_is_safe(self, kuzu_graph_memory):
        """delete() on data that doesn't exist in the graph should be a no-op."""
        mg, conn = kuzu_graph_memory

        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "hates"},
            ],
        )

        filters = {"user_id": "test_user"}

        # Nothing in the graph yet
        assert _edge_count(conn) == 0
        assert _node_count(conn) == 0

        # Should not raise
        mg.delete("Alice hates Bob", filters)

        assert _edge_count(conn) == 0
        assert _node_count(conn) == 0

    def test_delete_with_llm_failure_does_not_raise(self, kuzu_graph_memory):
        """If LLM fails during entity extraction, delete() should not raise."""
        mg, conn = kuzu_graph_memory

        # Make LLM raise
        mg.llm.generate_response.side_effect = RuntimeError("LLM service down")

        filters = {"user_id": "test_user"}

        # Should not raise
        mg.delete("Alice likes Bob", filters)

    def test_delete_with_empty_entity_extraction(self, kuzu_graph_memory):
        """If LLM returns no entities, delete() should be a no-op."""
        mg, conn = kuzu_graph_memory

        # Add real data
        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )
        filters = {"user_id": "test_user"}
        mg.add("Alice likes Bob", filters)
        assert _edge_count(conn) == 1

        # Now delete but LLM returns no entities
        _setup_llm_for_entities(mg, entities=[], relations=[])
        mg.delete("some text", filters)

        # Data should still be there
        assert _edge_count(conn) == 1

    def test_delete_all_removes_everything_for_user(self, kuzu_graph_memory):
        """delete_all() should remove all nodes/edges for a user (baseline behavior)."""
        mg, conn = kuzu_graph_memory

        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )
        filters = {"user_id": "test_user"}
        mg.add("Alice likes Bob", filters)

        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Bob", "entity_type": "person"},
                {"entity": "Charlie", "entity_type": "person"},
            ],
            relations=[
                {"source": "Bob", "destination": "Charlie", "relationship": "knows"},
            ],
        )
        mg.add("Bob knows Charlie", filters)

        assert _node_count(conn) >= 3
        assert _edge_count(conn) == 2

        mg.delete_all(filters)

        assert _node_count(conn) == 0
        assert _edge_count(conn) == 0

    def test_add_delete_add_cycle(self, kuzu_graph_memory):
        """Verify that add → delete → re-add works correctly."""
        mg, conn = kuzu_graph_memory

        _setup_llm_for_entities(
            mg,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )
        filters = {"user_id": "test_user"}

        # Add
        mg.add("Alice likes Bob", filters)
        assert _edge_count(conn) == 1

        # Delete
        mg.delete("Alice likes Bob", filters)
        assert _edge_count(conn) == 0

        # Re-add
        mg.add("Alice likes Bob", filters)
        assert _edge_count(conn) == 1
        edges = _get_edges(conn)
        assert ("alice", "likes", "bob") in edges


@requires_kuzu
class TestMemoryDeleteWithGraphE2E:
    """
    End-to-end tests for Memory.delete() with graph enabled.

    Uses a real Kuzu database for the graph store and mocks for
    the vector store, LLM, and embedder.
    """

    @pytest.fixture
    def memory_with_graph(self):
        """Create a Memory instance with a real Kuzu graph backend."""
        import os

        import kuzu

        tmpdir = tempfile.mkdtemp()

        with (
            patch("mem0.utils.factory.EmbedderFactory.create") as mock_embedder_factory,
            patch("mem0.utils.factory.VectorStoreFactory.create") as mock_vector_factory,
            patch("mem0.utils.factory.LlmFactory.create") as mock_llm_factory,
            patch("mem0.memory.storage.SQLiteManager") as mock_sqlite,
        ):
            _mem_embed_cache = {}
            _mem_embed_counter = [0]

            def _mem_deterministic_embed(text, *args, **kwargs):
                text_lower = text.lower().strip()
                if text_lower not in _mem_embed_cache:
                    import hashlib

                    vec = [0.0] * 64
                    idx = _mem_embed_counter[0] % 64
                    vec[idx] = 1.0
                    h = hashlib.sha256(text_lower.encode()).digest()
                    for i in range(64):
                        vec[i] += float(h[i % len(h)]) / 25500.0
                    norm = sum(v * v for v in vec) ** 0.5
                    _mem_embed_cache[text_lower] = [v / norm for v in vec]
                    _mem_embed_counter[0] += 1
                return _mem_embed_cache[text_lower]

            mock_embedder = MagicMock()
            mock_embedder.embed.side_effect = _mem_deterministic_embed
            mock_embedder.config.embedding_dims = 64
            mock_embedder_factory.return_value = mock_embedder

            mock_vector_store = MagicMock()
            mock_vector_factory.return_value = mock_vector_store

            mock_llm = MagicMock()
            mock_llm_factory.return_value = mock_llm

            mock_sqlite.return_value = MagicMock()

            from mem0.memory.main import Memory

            config = MemoryConfig()
            memory = Memory(config)

            # Now wire up a real Kuzu graph
            db_path = os.path.join(tmpdir, "test.kuzu")
            db = kuzu.Database(db_path)
            conn = kuzu.Connection(db)

            from mem0.memory.kuzu_memory import MemoryGraph as KuzuMemoryGraph

            graph = KuzuMemoryGraph.__new__(KuzuMemoryGraph)
            graph.db = db
            graph.graph = conn
            graph.node_label = ":Entity"
            graph.rel_label = ":CONNECTED_TO"
            graph.kuzu_create_schema()
            graph.embedding_dims = 64
            graph.embedding_model = mock_embedder
            graph.llm = mock_llm
            graph.llm_provider = "openai"
            graph.user_id = None
            graph.threshold = 0.99
            graph.config = MagicMock()
            graph.config.graph_store.custom_prompt = None

            memory.graph = graph
            memory.enable_graph = True

            yield memory, mock_vector_store, mock_llm, conn

            conn.close()
            shutil.rmtree(tmpdir, ignore_errors=True)

    def test_memory_delete_triggers_graph_cleanup(self, memory_with_graph):
        """
        Full integration: Memory.delete() should clean up both vector store and graph.
        """
        memory, mock_vs, mock_llm, conn = memory_with_graph

        # 1. Manually add entities to the graph (simulating what add() would do)
        _setup_llm_for_memory_graph(
            mock_llm,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )
        memory.graph.add("Alice likes Bob", {"user_id": "user-1"})
        assert _edge_count(conn) == 1

        # 2. Set up mock vector store to return this memory
        mock_vs.get.return_value = MockVectorMemory(
            "mem-1",
            {"data": "Alice likes Bob", "user_id": "user-1", "hash": "abc"},
        )

        # 3. Delete the memory
        result = memory.delete("mem-1")

        assert result == {"message": "Memory deleted successfully!"}

        # 4. Verify graph was cleaned up
        assert _edge_count(conn) == 0

        # 5. Verify vector store was also cleaned up
        mock_vs.delete.assert_called_once_with(vector_id="mem-1")

    def test_memory_delete_with_graph_preserves_other_users_data(self, memory_with_graph):
        """Deleting user1's memory should not affect user2's graph data."""
        memory, mock_vs, mock_llm, conn = memory_with_graph

        _setup_llm_for_memory_graph(
            mock_llm,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )

        # Add data for two users
        memory.graph.add("Alice likes Bob", {"user_id": "user-1"})
        memory.graph.add("Alice likes Bob", {"user_id": "user-2"})
        assert _edge_count(conn) == 2

        # Delete only user-1's memory
        mock_vs.get.return_value = MockVectorMemory(
            "mem-1",
            {"data": "Alice likes Bob", "user_id": "user-1", "hash": "abc"},
        )
        memory.delete("mem-1")

        # user-2's data should be intact
        assert _edge_count(conn) == 1
        nodes = _get_nodes(conn)
        remaining_user_ids = set(uid for _, uid in nodes)
        assert "user-2" in remaining_user_ids

    def test_memory_delete_graph_failure_still_deletes_vector(self, memory_with_graph):
        """If graph cleanup fails, vector store deletion should still proceed."""
        memory, mock_vs, mock_llm, conn = memory_with_graph

        # Make LLM raise during entity extraction (graph cleanup will fail)
        mock_llm.generate_response.side_effect = RuntimeError("LLM exploded")

        mock_vs.get.return_value = MockVectorMemory(
            "mem-1",
            {"data": "Alice likes Bob", "user_id": "user-1", "hash": "abc"},
        )

        result = memory.delete("mem-1")

        assert result == {"message": "Memory deleted successfully!"}
        mock_vs.delete.assert_called_once_with(vector_id="mem-1")

    def test_memory_delete_all_uses_bulk_not_per_memory(self, memory_with_graph):
        """delete_all() should use delete_all() on graph, not per-memory delete()."""
        memory, mock_vs, mock_llm, conn = memory_with_graph

        _setup_llm_for_memory_graph(
            mock_llm,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )
        memory.graph.add("Alice likes Bob", {"user_id": "user-1"})
        assert _edge_count(conn) == 1

        # Set up vector store to return memories for deletion
        mem1 = MockVectorMemory("mem-1", {"data": "Alice likes Bob", "user_id": "user-1"})
        mock_vs.list.return_value = ([mem1], 1)
        mock_vs.get.return_value = mem1

        memory.delete_all(user_id="user-1")

        # After delete_all, graph should be empty (via graph.delete_all)
        assert _edge_count(conn) == 0
        assert _node_count(conn) == 0

    def test_memory_delete_nonexistent_raises_without_graph_side_effects(self, memory_with_graph):
        """Deleting a non-existent memory should raise ValueError without touching graph."""
        memory, mock_vs, mock_llm, conn = memory_with_graph

        # Add some graph data that should NOT be affected
        _setup_llm_for_memory_graph(
            mock_llm,
            entities=[
                {"entity": "Alice", "entity_type": "person"},
                {"entity": "Bob", "entity_type": "person"},
            ],
            relations=[
                {"source": "Alice", "destination": "Bob", "relationship": "likes"},
            ],
        )
        memory.graph.add("Alice likes Bob", {"user_id": "user-1"})
        assert _edge_count(conn) == 1

        # Memory doesn't exist in vector store
        mock_vs.get.return_value = None

        with pytest.raises(ValueError, match="Memory with id non-existent not found"):
            memory.delete("non-existent")

        # Graph data should be untouched
        assert _edge_count(conn) == 1


def _setup_llm_for_memory_graph(mock_llm, entities, relations):
    """Configure mock LLM for the Memory-level graph operations."""

    def generate_response(messages, tools):
        tool_names = []
        for t in tools:
            if isinstance(t, dict):
                fn = t.get("function", t)
                tool_names.append(fn.get("name", ""))
            else:
                tool_names.append(getattr(t, "name", str(t)))

        if any("extract_entities" in n for n in tool_names):
            return {
                "tool_calls": [
                    {
                        "name": "extract_entities",
                        "arguments": {"entities": entities},
                    }
                ]
            }
        elif any("establish" in n or "relation" in n for n in tool_names):
            return {
                "tool_calls": [
                    {
                        "name": "establish_nodes_relations",
                        "arguments": {"entities": relations},
                    }
                ]
            }
        elif any("delete" in n for n in tool_names):
            return {"tool_calls": []}
        return {"tool_calls": []}

    mock_llm.generate_response.side_effect = generate_response