#1872·graphiti

[BUG] add_episode_bulk saves duplicate edges for identical facts across episodes in one batch

Author: hardness1020Created Sep 10, 2026Updated Sep 30, 2026

Bug Description

add_episode_bulk writes two distinct RELATES_TO edges when two episodes in the same batch yield the same fact between the same (deduped) source/target nodes. The same two episodes through sequential add_episode calls produce one edge.

Current vs expected behavior

Current: dedupe_edges_bulk returns both edges and both are saved. Each edge's episodes list also gets the other episode's uuid appended (the fast path mutates the candidate in place), so provenance is wrong on both surviving edges.

Expected: one edge survives with episodes containing every contributing episode ({ep1, ep2}), matching the single-episode add_episode path.

Root cause

resolve_extracted_edge has an exact-fact fast path (graphiti_core/utils/maintenance/edge_operations.py:684-695, added in #929) that returns (resolved, [], []) with an empty duplicates list:

python
for edge in related_edges:
    if (
        edge.source_node_uuid == extracted_edge.source_node_uuid
        and edge.target_node_uuid == extracted_edge.target_node_uuid
        and _normalize_string_exact(edge.fact) == normalized_fact
    ):
        resolved = edge
        if episode is not None and episode.uuid not in resolved.episodes:
            resolved.episodes.append(episode.uuid)
        return resolved, [], []

The LLM path (edge_operations.py:845-847) returns duplicate_edges = [related_edges[idx] for idx in duplicate_fact_ids].

dedupe_edges_bulk (graphiti_core/utils/bulk_utils.py:561-581) discards the resolved edge and builds duplicate_pairs only from the third tuple element:

python
for i, (_, _, duplicates) in enumerate(bulk_edge_resolutions):
    episode, edge, candidates = dedupe_tuples[i]
    for duplicate in duplicates:
        duplicate_pairs.append((edge.uuid, duplicate.uuid))
compressed_map = compress_uuid_map(duplicate_pairs)

So fast-path matches never reach compress_uuid_map, and the exact-duplicate case (the one bulk dedupe exists for) is the one case it cannot see.

The existing test tests/utils/maintenance/test_bulk_utils.py::test_dedupe_edges_bulk_deduplicates_within_episode (from #955) monkeypatches resolve_extracted_edge to return [related] as duplicates, the opposite of the real fast path, so it does not catch this.

Reproduction (no DB, no LLM)

python
import asyncio
from unittest.mock import MagicMock

from graphiti_core.edges import EntityEdge
from graphiti_core.graphiti_types import GraphitiClients
from graphiti_core.nodes import EpisodeType, EpisodicNode
from graphiti_core.utils import bulk_utils
from graphiti_core.utils.datetime_utils import utc_now


def ep(n):
    return EpisodicNode(name=f'ep-{n}', group_id='g', labels=[], source=EpisodeType.message,
                        content='c', source_description='t', created_at=utc_now(), valid_at=utc_now())


def edge(episode):
    return EntityEdge(name='WORKS_AT', fact='Alice works at Acme', group_id='g',
                      source_node_uuid='alice', target_node_uuid='acme',
                      created_at=utc_now(), episodes=[episode.uuid])


async def main():
    llm = MagicMock()
    llm.generate_response = MagicMock(side_effect=AssertionError('LLM must not be called'))
    clients = GraphitiClients.model_construct(driver=MagicMock(), embedder=MagicMock(),
                                              cross_encoder=MagicMock(), llm_client=llm)

    async def fake_embed(embedder, edges):
        for e in edges:
            e.fact_embedding = [1.0, 0.0]
    bulk_utils.create_entity_edge_embeddings = fake_embed

    e1, e2 = ep(1), ep(2)
    a, b = edge(e1), edge(e2)
    out = await bulk_utils.dedupe_edges_bulk(clients, [[a], [b]], [(e1, []), (e2, [])], [], {}, {})
    uuids = {x.uuid for lst in out.values() for x in lst}
    print('distinct edge uuids after bulk dedupe:', len(uuids), '(expected 1)')
    print('edge a episodes:', a.episodes)
    print('edge b episodes:', b.episodes)

asyncio.run(main())

Output on main:

distinct edge uuids after bulk dedupe: 2 (expected 1)
edge a episodes: ['<ep1>', '<ep2>']
edge b episodes: ['<ep2>', '<ep1>']

The LLM client is never called, so this is purely the fast-path contract mismatch.

Environment

  • graphiti-core 0.30.2, main @ 4bd7287
  • Backend-independent (Python-side dedupe logic before any DB write)

Proposed direction

Two changes, both in dedupe_edges_bulk (bulk_utils.py:561-581); no change to resolve_extracted_edge:

  1. Treat a returned resolved edge whose uuid differs from the input edge as a duplicate pair, in addition to the explicit duplicates list. This is the same convention resolve_extracted_edges already uses at edge_operations.py:520 (resolved_edge.uuid == extracted_edge.uuid means "new"; result[2] is ignored there).

  2. After compress_uuid_map, merge episodes from each collapsed edge into its canonical edge. The fast path only appends the episode to the first matching candidate, so with 3+ episodes the edges end up with uneven provenance (on main, 3 identical edges yield [ep0, ep1, ep2], [ep1, ep0], [ep2]). compress_uuid_map picks the lexicographically smallest uuid as survivor, so without the merge the survivor can carry a partial episodes list. The 2-episode case only looks right by accident of the in-place mutation.

python
for i, (resolved, _, duplicates) in enumerate(bulk_edge_resolutions):
    episode, edge, candidates = dedupe_tuples[i]
    if resolved.uuid != edge.uuid:
        duplicate_pairs.append((edge.uuid, resolved.uuid))
    for duplicate in duplicates:
        duplicate_pairs.append((edge.uuid, duplicate.uuid))

compressed_map = compress_uuid_map(duplicate_pairs)
edge_uuid_map = {edge.uuid: edge for edges in extracted_edges for edge in edges}

for uuid, canonical_uuid in compressed_map.items():
    if uuid == canonical_uuid:
        continue
    canonical = edge_uuid_map[canonical_uuid]
    for ep_uuid in edge_uuid_map[uuid].episodes:
        if ep_uuid not in canonical.episodes:
            canonical.episodes.append(ep_uuid)

Roughly 10 lines, one file. No schema or API impact. The union-find is idempotent, so a pair reported by both the uuid check and the duplicates list is harmless. All uuids in compressed_map are in-batch, so the edge_uuid_map lookups cannot miss.

Not proposed: changing the fast path to return [resolved] as duplicates. dedupe_edges_bulk is the only consumer of the third tuple element, and test_resolve_extracted_edge_exact_fact_short_circuit locks in the current [].

Note (pre-existing, out of scope): which edge survives is decided by uuid ordering, so the survivor's created_at and the episode used for _extract_edge_timestamps in the second-stage resolve are nondeterministic. Same is true today for the LLM path.

Tests

New unit tests in tests/utils/maintenance/test_bulk_utils.py using the real resolve_extracted_edge (fast path) with an LLM mock that raises if called:

  • Identical fact across 2 episodes: one surviving uuid across edges_by_episode, both episode lists reference the same object, survivor episodes equals {ep1, ep2} as a set.
  • Identical fact across 3 episodes: same assertions with 3. This is the case the uuid-pair fix alone does not cover; compare episodes as a set, not by order.
  • Same endpoints, different facts (no word overlap, orthogonal embeddings): 2 uuids survive, LLM not called.
  • Strengthen test_dedupe_edges_bulk_deduplicates_within_episode to assert a single surviving uuid; today it only counts comparisons.
  • test_resolve_extracted_edge_exact_fact_short_circuit unchanged.

Related issues / PRs

  • #929 introduced the exact-fact fast path
  • #955 added dedupe_edges_bulk within-episode comparisons and the mocked test that masks this
  • #1771 (dedup write-path review)