diff --git a/.github/workflows/release-graphiti-core.yml b/.github/workflows/release-graphiti-core.yml index d02200e135..e04fcf5caa 100644 --- a/.github/workflows/release-graphiti-core.yml +++ b/.github/workflows/release-graphiti-core.yml @@ -61,7 +61,7 @@ jobs: raise SystemExit("fork wheel must contain one METADATA file") metadata = BytesParser().parsebytes(archive.read(metadata_files[0])) if (metadata["Name"], metadata["Version"]) != ( - "archolith-graphiti-core", "0.32.1.post3" + "archolith-graphiti-core", "0.32.1.post4" ): raise SystemExit("fork wheel name or version differs from reviewed release") required_hooks = { diff --git a/graphiti_core/graphiti.py b/graphiti_core/graphiti.py index d7c87a52ad..e39953b2c9 100644 --- a/graphiti_core/graphiti.py +++ b/graphiti_core/graphiti.py @@ -16,7 +16,7 @@ import json import logging -from collections.abc import Iterable, Mapping, Sequence +from collections.abc import Collection, Iterable, Mapping, Sequence from datetime import datetime from time import time from typing import TYPE_CHECKING, Any @@ -2011,6 +2011,7 @@ async def add_episode( resolution_trace: 'ResolutionTrace | None' = None, uuid_seed: str | None = None, prompt_attributes: PromptAttributes = 'all', + uuid_seed_preserve: Collection[str] | None = None, ) -> AddEpisodeResults: """ Process an episode and update the graph. @@ -2083,6 +2084,11 @@ async def add_episode( (default) shows every stored property. 'declared' shows only the attributes that the entity type model of the node declares, and none for a node without a model. Incompatible with concurrent ingestion unless 'all' (ValueError). + uuid_seed_preserve : Collection[str] | None + Optional, only with ``uuid_seed`` (ValueError otherwise). An extracted node whose uuid + is in this set keeps it instead of getting a seeded uuid; its position is still + counted, so the other seeded uuids do not move. For uuids that an extraction hook + assigned on purpose, such as a reserved identity, so that seeding does not undo them. Returns ------- @@ -2121,6 +2127,8 @@ async def add_episode_endpoint(episode_data: EpisodeData): ) if prompt_attributes not in ('all', 'declared'): raise ValueError("prompt_attributes must be 'all' or 'declared'") + if uuid_seed_preserve is not None and uuid_seed is None: + raise ValueError('uuid_seed_preserve needs uuid_seed') start = time() now = utc_now() @@ -2251,7 +2259,11 @@ async def add_episode_endpoint(episode_data: EpisodeData): if uuid_seed is not None: # Seeded uuids follow the extraction order, not the order of task completion. reseed_extraction( - uuid_seed, extracted_nodes, precomputed_edges, node_episode_index_map + uuid_seed, + extracted_nodes, + precomputed_edges, + node_episode_index_map, + preserve=uuid_seed_preserve or (), ) # Hook kwargs are forwarded only when the corresponding hook is diff --git a/graphiti_core/seeded_uuids.py b/graphiti_core/seeded_uuids.py index f7941110a2..cf56292328 100644 --- a/graphiti_core/seeded_uuids.py +++ b/graphiti_core/seeded_uuids.py @@ -14,7 +14,7 @@ limitations under the License. """ -from collections.abc import Sequence +from collections.abc import Collection, Sequence from uuid import NAMESPACE_URL, uuid5 from graphiti_core.edges import EntityEdge @@ -37,14 +37,19 @@ def reseed_extraction( node_episode_index_map: dict[str, list[int]] | None = None, node_kind: str = 'node', edge_kind: str = 'edge', + preserve: Collection[str] = (), ) -> dict[str, str]: """Replace the uuids of freshly extracted nodes and edges with seeded uuids, in list order. Changes the objects in place. The edge endpoints and the keys of `node_episode_index_map` - follow the new node uuids. Returns the map from old to new node uuid. + follow the new node uuids. A node whose uuid is in `preserve` keeps it, and its index is + still used up, so the uuids of the other nodes are the same as without `preserve`. + Returns the map from old to new node uuid; preserved nodes are not in it. """ node_map: dict[str, str] = {} for index, node in enumerate(nodes): + if node.uuid in preserve: + continue new_uuid = seeded_uuid(seed, node_kind, index) node_map[node.uuid] = new_uuid node.uuid = new_uuid diff --git a/pyproject.toml b/pyproject.toml index 5e3007c0e7..52a06a3b92 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "archolith-graphiti-core" description = "A temporal graph building library" -version = "0.32.1.post3" +version = "0.32.1.post4" authors = [ { name = "Paul Paliychuk", email = "paul@getzep.com" }, { name = "Preston Rasmussen", email = "preston@getzep.com" }, diff --git a/tests/test_replay_capture.py b/tests/test_replay_capture.py index aed6dd30da..8e32874ef5 100644 --- a/tests/test_replay_capture.py +++ b/tests/test_replay_capture.py @@ -225,8 +225,17 @@ async def test_unknown_prompt_attributes_policy_is_rejected(): await call_add_episode(graphiti, prompt_attributes='everything') -def stub_pipeline(monkeypatch, graphiti: Graphiti, driver: Mock, previous: list[EpisodicNode]): - """Replace every I/O stage of add_episode. Returns the record of what each stage got.""" +def stub_pipeline( + monkeypatch, + graphiti: Graphiti, + driver: Mock, + previous: list[EpisodicNode], + middle_uuid: str | None = None, +): + """Replace every I/O stage of add_episode. Returns the record of what each stage got. + + `middle_uuid` gives the second extracted node that uuid, as an extraction hook that binds a + reserved identity would.""" record: dict[str, Any] = {} clients = graphiti.clients @@ -236,6 +245,8 @@ def stub_pipeline(monkeypatch, graphiti: Graphiti, driver: Mock, previous: list[ def extraction(episode, *_args, **_kwargs): nodes = [EntityNode(name=name, group_id=GROUP, labels=['Entity']) for name in 'ABC'] + if middle_uuid is not None: + nodes[1].uuid = middle_uuid edges = [ EntityEdge( group_id=GROUP, @@ -362,6 +373,50 @@ async def test_uuid_seed_gives_the_same_uuids_twice_and_none_gives_random(monkey assert plain_a['extracted_nodes'] != plain_b['extracted_nodes'] +async def test_uuid_seed_preserve_keeps_a_reserved_uuid_and_the_other_seeded_uuids(monkeypatch): + runs = [] + for preserve in (None, {'reserved-self'}, {'reserved-self'}): + graphiti, driver = make_graphiti() + record = stub_pipeline(monkeypatch, graphiti, driver, [], middle_uuid='reserved-self') + await call_add_episode(graphiti, uuid_seed='seed-1', uuid_seed_preserve=preserve) + runs.append(record) + + unpreserved, first, second = runs + assert first['extracted_nodes'] == second['extracted_nodes'] + assert first['edges'] == second['edges'] + assert [u for u, _ in unpreserved['extracted_nodes']][1] == seeded_uuid('seed-1', 'node', 1) + + node_uuids = [uuid for uuid, _ in first['extracted_nodes']] + assert node_uuids == [ + seeded_uuid('seed-1', 'node', 0), + 'reserved-self', + seeded_uuid('seed-1', 'node', 2), + ] + assert [(s, t) for _, s, t in first['edges']] == [ + (node_uuids[0], 'reserved-self'), + ('reserved-self', node_uuids[2]), + ] + assert [u for u, _, _ in first['edges']] == [u for u, _, _ in unpreserved['edges']] + assert sorted(first['node_index_map']) == sorted(node_uuids) + + +async def test_uuid_seed_preserve_needs_a_seed(): + graphiti, _ = make_graphiti() + with pytest.raises(ValueError, match='uuid_seed_preserve needs uuid_seed'): + await call_add_episode(graphiti, uuid_seed_preserve={'x'}) + + +def test_reseed_preserve_does_not_move_the_other_uuids(): + def build(): + return [EntityNode(uuid=old, name=old, group_id=GROUP) for old in ('a', 'keep', 'c')] + + plain, kept = build(), build() + reseed_extraction('s', plain) + node_map = reseed_extraction('s', kept, preserve={'keep', 'absent'}) + assert [n.uuid for n in kept] == [plain[0].uuid, 'keep', plain[2].uuid] + assert 'keep' not in node_map + + def test_seeded_uuids_follow_input_order_not_the_old_uuids(): def build(old_uuids): return [ diff --git a/uv.lock b/uv.lock index a23bbe8e3e..49d902398f 100644 --- a/uv.lock +++ b/uv.lock @@ -284,7 +284,7 @@ wheels = [ [[package]] name = "archolith-graphiti-core" -version = "0.32.1.post3" +version = "0.32.1.post4" source = { editable = "." } dependencies = [ { name = "certifi" },