diff --git a/.github/workflows/release-graphiti-core.yml b/.github/workflows/release-graphiti-core.yml index 139c068516..d02200e135 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.post2" + "archolith-graphiti-core", "0.32.1.post3" ): raise SystemExit("fork wheel name or version differs from reviewed release") required_hooks = { diff --git a/CHANGELOG.md b/CHANGELOG.md index 18e89f16df..d7eb02b082 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,29 @@ This file covers the Archolith maintenance fork published as The package still imports as `graphiti_core`. For the upstream project's release history, see [getzep/graphiti](https://github.com/getzep/graphiti/releases). +## 0.32.1.post3 — 2026-12-01 + +[Source tag](https://github.com/Archolith/graphiti/tree/v0.32.1.post3) · +[PyPI files](https://pypi.org/project/archolith-graphiti-core/0.32.1.post3/) + +### Added + +Candidate-universe capture for replay (Archolith/menhir#469). Label: `Menhir policy divergence`. +Every default keeps the behavior of today. + +- `add_episode(resolution_trace=...)`: a `ResolutionTrace` that gets the candidate pools of node and + edge resolution (empty pools too), the context episodes (`record_context_episodes`), the endpoint + lookups of edge resolution (`record_endpoint_lookup`) and the exact-name lookups + (`record_name_lookup`). Rejected with concurrent ingestion. +- `add_episode(uuid_seed=...)`: new nodes and edges get uuids from the seed and their position in + the extraction order. `None` keeps `uuid4`. Rejected with concurrent ingestion. +- `add_episode(prompt_attributes='declared')`: the dedupe candidates and the summary and attribute + prompts show only the attributes that the entity type declares. `'all'` (the default) is the + upstream behavior. Rejected with concurrent ingestion. +- A `uuid` tie-break (`ASC`) after the existing order in node and edge similarity and fulltext + search, relevant-edge and invalidation-candidate queries, `EntityNode.get_by_names`, + `EntityNode.get_by_attribute_values` and `retrieve_episodes` (after `created_at`). + ## 0.31.2.post4 — 2026-11-22 [Source tag](https://github.com/Archolith/graphiti/tree/v0.31.2.post4) · diff --git a/graphiti_core/graphiti.py b/graphiti_core/graphiti.py index dca0a68407..d7c87a52ad 100644 --- a/graphiti_core/graphiti.py +++ b/graphiti_core/graphiti.py @@ -96,6 +96,7 @@ RELEVANT_SCHEMA_LIMIT, get_mentioned_nodes, ) +from graphiti_core.seeded_uuids import reseed_extraction, seeded_uuid from graphiti_core.telemetry import capture_event from graphiti_core.tracer import Tracer, create_tracer from graphiti_core.utils.bulk_utils import ( @@ -130,6 +131,7 @@ retrieve_episodes, ) from graphiti_core.utils.maintenance.node_operations import ( + PromptAttributes, _extract_entity_summaries_batch, _identity_type_for_node, extract_attributes_from_nodes, @@ -300,6 +302,11 @@ def _preserved_edge_attribute_names(value: Iterable[str] | None) -> frozenset[st ) +def _kwargs_if(condition: bool, **kwargs: Any) -> dict[str, Any]: + """Keyword arguments to forward only when `condition` holds (typed for pyright).""" + return kwargs if condition else {} + + class Graphiti: # Class-level default so instances that bypass __init__ (subclasses, test # doubles, unpickled-style instances) safely observe "no hook configured" and @@ -699,11 +706,17 @@ def _reject_fork_seams_for_concurrent_ingestion( self, new_episode_uuid: str | None = None, publish_fence: PublishFence | None = None, + resolution_trace: 'ResolutionTrace | None' = None, + uuid_seed: str | None = None, + prompt_attributes: PromptAttributes | None = None, ) -> None: """Raise when a fork seam is in use, because concurrent ingestion does not carry them.""" seams = { 'new_episode_uuid': new_episode_uuid, 'publish_fence': publish_fence, + 'resolution_trace': resolution_trace, + 'uuid_seed': uuid_seed, + 'prompt_attributes': prompt_attributes, 'single_episode_extraction_hook': self.single_episode_extraction_hook, 'identity_gate_hook': self.identity_gate_hook, 'candidate_filter_hook': self.candidate_filter_hook, @@ -1266,6 +1279,7 @@ async def _merge_materialized_endpoint_nodes( identity_properties: dict[str, list[str]] | None = None, clients: GraphitiClients | None = None, trace: 'ResolutionTrace | None' = None, + prompt_attributes: PromptAttributes = 'all', ) -> None: """Fold endpoints materialized by ``extract_edges`` into the resolved node set. @@ -1278,6 +1292,8 @@ async def _merge_materialized_endpoint_nodes( clients = clients or self.clients # Pass `trace` only when it is set, so the serial path makes the calls of today. trace_kwargs: dict[str, Any] = {'trace': trace} if trace is not None else {} + if prompt_attributes != 'all': + trace_kwargs['prompt_attributes'] = prompt_attributes nodes_by_name = {_normalize_string_exact(node.name): node for node in nodes} known_uuids = {node.uuid for node in nodes} @@ -1341,6 +1357,8 @@ async def _extract_and_resolve_edges( identity_properties: dict[str, list[str]] | None = None, clients: GraphitiClients | None = None, trace: 'ResolutionTrace | None' = None, + uuid_seed: str | None = None, + prompt_attributes: PromptAttributes = 'all', ) -> tuple[list[EntityEdge], list[EntityEdge], list[EntityEdge]]: """Extract edges from episode(s) and resolve against the existing graph. @@ -1387,6 +1405,14 @@ async def _extract_and_resolve_edges( strict_edge_types, custom_extraction_instructions, ) + if uuid_seed is not None: + # Edges and endpoint nodes of the separate route get seeded uuids in list order. + reseed_extraction( + uuid_seed, + materialized_nodes, + extracted_edges, + node_kind='endpoint', + ) # Merge only nodes that extract_edges newly materialized — never the full # pre-resolution extracted_nodes list, which also contains deduped duplicates @@ -1402,6 +1428,7 @@ async def _extract_and_resolve_edges( identity_properties=identity_properties, clients=clients, trace=trace, + prompt_attributes=prompt_attributes, ) edges = resolve_edge_pointers(extracted_edges, uuid_map) @@ -1434,6 +1461,7 @@ async def _process_episode_data( clients: GraphitiClients | None = None, publish_fence: PublishFence | None = None, previous_episode_uuids: Sequence[str] | None = None, + uuid_seed: str | None = None, ) -> tuple[list[EpisodicEdge], EpisodicNode]: """Process and save episode data to the graph. @@ -1475,6 +1503,9 @@ async def _process_episode_data( episode_uuids = [ep.uuid for ep in episodes] episodic_edges = build_episodic_edges(nodes, episode_uuids, now, node_episode_index_map) + if uuid_seed is not None: + for index, episodic_edge in enumerate(episodic_edges): + episodic_edge.uuid = seeded_uuid(uuid_seed, 'episodic_edge', index) for ep in episodes: ep.entity_edges = [edge.uuid for edge in entity_edges] if not self.store_raw_episode_content: @@ -1977,6 +2008,9 @@ async def add_episode( new_episode_uuid: str | None = None, publish_fence: PublishFence | None = None, identity_properties: dict[str, list[str]] | None = None, + resolution_trace: 'ResolutionTrace | None' = None, + uuid_seed: str | None = None, + prompt_attributes: PromptAttributes = 'all', ) -> AddEpisodeResults: """ Process an episode and update the graph. @@ -2035,6 +2069,20 @@ async def add_episode( identity_properties : dict[str, list[str]] | None Optional. Map entity type names to attribute names that identify entities. Graphiti extracts these attributes before node resolution. + resolution_trace : ResolutionTrace | None + Optional. Receives what node resolution and edge resolution read: the context + episodes, the candidate pools (empty ones too), the exact-name and endpoint + lookups, and the edge candidates. Passing it does not change the result. + Incompatible with concurrent ingestion (ValueError). + uuid_seed : str | None + Optional. When set, the uuids of the new nodes and edges of this call derive from the + seed and from the position of each item in the extraction order. When None, the + uuids are random as before. Incompatible with concurrent ingestion (ValueError). + prompt_attributes : 'all' | 'declared' + Which stored node attributes the dedupe, attribute and summary prompts show. 'all' + (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). Returns ------- @@ -2071,6 +2119,8 @@ async def add_episode_endpoint(episode_data: EpisodeData): 'publish_fence cannot be combined with saga or update_communities: ' 'they write outside the publish transaction' ) + if prompt_attributes not in ('all', 'declared'): + raise ValueError("prompt_attributes must be 'all' or 'declared'") start = time() now = utc_now() @@ -2090,7 +2140,13 @@ async def add_episode_endpoint(episode_data: EpisodeData): if self._concurrent_ingestion_enabled(group_id): # Fork seams are not supported with concurrent ingestion (fail-closed guard). - self._reject_fork_seams_for_concurrent_ingestion(new_episode_uuid, publish_fence) + self._reject_fork_seams_for_concurrent_ingestion( + new_episode_uuid, + publish_fence, + resolution_trace, + uuid_seed, + prompt_attributes if prompt_attributes != 'all' else None, + ) if update_communities: raise ValueError( 'update_communities=True has no support in concurrent ingestion. ' @@ -2146,6 +2202,8 @@ async def add_episode_endpoint(episode_data: EpisodeData): # The context episodes actually used (the parameter above is only the caller's # request), reported to the publish fence. fence_previous_episode_uuids = [ep.uuid for ep in previous_episodes] + if resolution_trace is not None: + resolution_trace.record_context_episodes(previous_episodes) # Get or create episode if uuid is not None: @@ -2190,6 +2248,11 @@ async def add_episode_endpoint(episode_data: EpisodeData): custom_extraction_instructions, clients=clients, ) + 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 + ) # Hook kwargs are forwarded only when the corresponding hook is # configured; identity_properties is always passed, as upstream does. @@ -2204,6 +2267,15 @@ async def add_episode_endpoint(episode_data: EpisodeData): identity_kwargs['node_pre_resolution_edges'] = precomputed_edges identity_kwargs['identity_properties'] = identity_properties + # The seam kwargs are forwarded only when they are set, so the default path + # makes the calls of today. + trace_kwargs: dict[str, Any] = ( + {'trace': resolution_trace} if resolution_trace is not None else {} + ) + policy_kwargs: dict[str, Any] = ( + {'prompt_attributes': prompt_attributes} if prompt_attributes != 'all' else {} + ) + if identity_properties: identity_nodes = [ node @@ -2220,6 +2292,7 @@ async def add_episode_endpoint(episode_data: EpisodeData): previous_episodes, entity_types, validate_shape=False, + **policy_kwargs, ) nodes, uuid_map, _ = await resolve_extracted_nodes( @@ -2229,6 +2302,8 @@ async def add_episode_endpoint(episode_data: EpisodeData): previous_episodes, entity_types, **identity_kwargs, + **trace_kwargs, + **policy_kwargs, ) # Resolve edges, carrying edges already produced by the combined @@ -2252,6 +2327,9 @@ async def add_episode_endpoint(episode_data: EpisodeData): precomputed_edges=precomputed_edges, identity_properties=identity_properties, clients=clients, + **trace_kwargs, + **policy_kwargs, + **_kwargs_if(uuid_seed is not None, uuid_seed=uuid_seed), ) entity_edges = resolved_edges + invalidated_edges @@ -2265,6 +2343,7 @@ async def add_episode_endpoint(episode_data: EpisodeData): previous_episodes, entity_types, edges=new_edges, + **policy_kwargs, ) # Process and save episode data (including saga association if provided) @@ -2278,6 +2357,7 @@ async def add_episode_endpoint(episode_data: EpisodeData): saga_previous_episode_uuid, node_episode_index_map, clients=clients, + **_kwargs_if(uuid_seed is not None, uuid_seed=uuid_seed), **( {} if publish_fence is None diff --git a/graphiti_core/ingestion/change_set.py b/graphiti_core/ingestion/change_set.py index a133efc1c4..f033815406 100644 --- a/graphiti_core/ingestion/change_set.py +++ b/graphiti_core/ingestion/change_set.py @@ -170,8 +170,28 @@ class ResolutionTrace: ended_by_candidate: set[str] = field(default_factory=set) # The number of model calls that node resolution made for the trace. node_llm_calls: int = 0 + # The uuids of the context (previous) episodes that the call used, in order. + context_episode_uuids: list[str] = field(default_factory=list) + # One entry for each lookup of endpoint nodes by uuid: (requested uuids, found uuids). + endpoint_lookups: list[tuple[list[str], list[str]]] = field(default_factory=list) + # One entry for each exact-name lookup: (names, group ids, found uuids in result order). + name_lookups: list[tuple[list[str], list[str], list[str]]] = field(default_factory=list) _edge_states: dict[int, _EdgeState] = field(default_factory=dict) + def record_context_episodes(self, episodes: list[EpisodicNode]) -> None: + """Record the context (previous) episodes that the call used. A subclass may override.""" + self.context_episode_uuids = [episode.uuid for episode in episodes] + + def record_endpoint_lookup(self, requested_uuids: list[str], found: list[EntityNode]) -> None: + """Record a lookup of endpoint nodes by uuid, with an empty result too.""" + self.endpoint_lookups.append((list(requested_uuids), [node.uuid for node in found])) + + def record_name_lookup( + self, names: list[str], group_ids: list[str], found: list[EntityNode] + ) -> None: + """Record an exact-name node lookup (`get_by_names`), with an empty result too.""" + self.name_lookups.append((list(names), list(group_ids), [node.uuid for node in found])) + def record_node_candidates(self, node_uuid: str, candidates: list[EntityNode]) -> None: seen = self.seen_node_candidates.setdefault(node_uuid, []) for candidate in candidates: diff --git a/graphiti_core/nodes.py b/graphiti_core/nodes.py index f38b76badc..a1bbcc1678 100644 --- a/graphiti_core/nodes.py +++ b/graphiti_core/nodes.py @@ -669,7 +669,10 @@ async def get_by_names( AND n.name IN $names RETURN """ - + get_entity_node_return_query(driver.provider), + + get_entity_node_return_query(driver.provider) + + """ + ORDER BY n.uuid ASC + """, names=unique_names, group_ids=unique_group_ids, routing_='r', @@ -733,6 +736,7 @@ async def get_by_attribute_values( """ + get_entity_node_return_query(driver.provider) + """ + ORDER BY n.uuid ASC LIMIT $limit """ ) diff --git a/graphiti_core/search/search_utils.py b/graphiti_core/search/search_utils.py index 8baf062134..2a26fe3781 100644 --- a/graphiti_core/search/search_utils.py +++ b/graphiti_core/search/search_utils.py @@ -245,7 +245,7 @@ async def edge_fulltext_search( """ + get_entity_edge_return_query(GraphProvider.NEPTUNE) + """ - ORDER BY score DESC LIMIT $limit + ORDER BY score DESC, e.uuid ASC LIMIT $limit """ ) @@ -270,7 +270,7 @@ async def edge_fulltext_search( """ + get_entity_edge_return_query(driver.provider) + """ - ORDER BY score DESC + ORDER BY score DESC, e.uuid ASC LIMIT $limit """ ) @@ -383,7 +383,7 @@ async def edge_similarity_search( r.valid_at AS valid_at, r.invalid_at AS invalid_at, properties(r) AS attributes - ORDER BY i.score DESC + ORDER BY i.score DESC, r.uuid ASC LIMIT $limit """ records, _, _ = await driver.execute_query( @@ -410,7 +410,7 @@ async def edge_similarity_search( """ + get_entity_edge_return_query(driver.provider) + """ - ORDER BY score DESC + ORDER BY score DESC, e.uuid ASC LIMIT $limit """ ) @@ -563,7 +563,7 @@ async def node_fulltext_search( """ + get_entity_node_return_query(driver.provider) + """ - ORDER BY i.score DESC + ORDER BY i.score DESC, n.uuid ASC LIMIT $limit """ ) @@ -586,7 +586,7 @@ async def node_fulltext_search( + filter_query + """ WITH n, score - ORDER BY score DESC + ORDER BY score DESC, n.uuid ASC LIMIT $limit RETURN """ @@ -673,7 +673,7 @@ async def node_similarity_search( """ + get_entity_node_return_query(driver.provider) + """ - ORDER BY i.score DESC + ORDER BY i.score DESC, n.uuid ASC LIMIT $limit """ ) @@ -703,7 +703,7 @@ async def node_similarity_search( """ + get_entity_node_return_query(driver.provider) + """ - ORDER BY score DESC + ORDER BY score DESC, n.uuid ASC LIMIT $limit """ ) @@ -1323,7 +1323,7 @@ async def get_relevant_edges( MATCH ()-[e]->() WHERE id(e) = edge.id WITH edge, e - ORDER BY edge.score DESC + ORDER BY edge.score DESC, e.uuid ASC RETURN edge.uuid AS search_edge_uuid, collect({ uuid: e.uuid, @@ -1366,7 +1366,7 @@ async def get_relevant_edges( + """ AS score WHERE score > $min_score WITH edge, e, score - ORDER BY score DESC + ORDER BY score DESC, e.uuid ASC RETURN edge.uuid AS search_edge_uuid, collect({ @@ -1465,7 +1465,7 @@ async def get_edge_invalidation_candidates( MATCH ()-[e]->() WHERE id(e) = edge.id WITH edge, e - ORDER BY edge.score DESC + ORDER BY edge.score DESC, e.uuid ASC RETURN edge.uuid AS search_edge_uuid, collect({ uuid: e.uuid, @@ -1508,7 +1508,7 @@ async def get_edge_invalidation_candidates( + """ AS score WHERE score > $min_score WITH edge, e, score - ORDER BY score DESC + ORDER BY score DESC, e.uuid ASC RETURN edge.uuid AS search_edge_uuid, collect({ diff --git a/graphiti_core/seeded_uuids.py b/graphiti_core/seeded_uuids.py new file mode 100644 index 0000000000..f7941110a2 --- /dev/null +++ b/graphiti_core/seeded_uuids.py @@ -0,0 +1,62 @@ +""" +Copyright 2024, Zep Software, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +from collections.abc import Sequence +from uuid import NAMESPACE_URL, uuid5 + +from graphiti_core.edges import EntityEdge +from graphiti_core.nodes import EntityNode + + +def seeded_uuid(seed: str, kind: str, index: int) -> str: + """Return the uuid of the `index`-th item of `kind` for `seed`. + + The uuid depends on the seed, the kind and the position of the item in the input + order of the producer. It does not depend on the time or on the order of task completion. + """ + return str(uuid5(NAMESPACE_URL, f'graphiti:uuid_seed:{seed}:{kind}:{index}')) + + +def reseed_extraction( + seed: str, + nodes: Sequence[EntityNode], + edges: Sequence[EntityEdge] | None = None, + node_episode_index_map: dict[str, list[int]] | None = None, + node_kind: str = 'node', + edge_kind: str = 'edge', +) -> 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. + """ + node_map: dict[str, str] = {} + for index, node in enumerate(nodes): + new_uuid = seeded_uuid(seed, node_kind, index) + node_map[node.uuid] = new_uuid + node.uuid = new_uuid + + if node_episode_index_map: + items = [(node_map.get(key, key), value) for key, value in node_episode_index_map.items()] + node_episode_index_map.clear() + node_episode_index_map.update(items) + + for index, edge in enumerate(edges or []): + edge.uuid = seeded_uuid(seed, edge_kind, index) + edge.source_node_uuid = node_map.get(edge.source_node_uuid, edge.source_node_uuid) + edge.target_node_uuid = node_map.get(edge.target_node_uuid, edge.target_node_uuid) + + return node_map diff --git a/graphiti_core/utils/maintenance/edge_operations.py b/graphiti_core/utils/maintenance/edge_operations.py index 1d1412c639..853fab5311 100644 --- a/graphiti_core/utils/maintenance/edge_operations.py +++ b/graphiti_core/utils/maintenance/edge_operations.py @@ -767,6 +767,8 @@ async def resolve_extracted_edges( missing_nodes = await EntityNode.get_by_uuids( driver, list(referenced_node_uuids), group_id=edge_group_id ) + if trace is not None: + trace.record_endpoint_lookup(sorted(referenced_node_uuids), list(missing_nodes)) for node in missing_nodes: uuid_entity_map[node.uuid] = node diff --git a/graphiti_core/utils/maintenance/graph_data_operations.py b/graphiti_core/utils/maintenance/graph_data_operations.py index 68b4eab5ea..339391951d 100644 --- a/graphiti_core/utils/maintenance/graph_data_operations.py +++ b/graphiti_core/utils/maintenance/graph_data_operations.py @@ -112,7 +112,7 @@ async def retrieve_episodes( else EPISODIC_NODE_RETURN ) + """ - ORDER BY e.valid_at DESC, e.created_at DESC + ORDER BY e.valid_at DESC, e.created_at DESC, e.uuid ASC LIMIT $num_episodes """, saga_name=saga, @@ -150,7 +150,7 @@ async def retrieve_episodes( else EPISODIC_NODE_RETURN ) + """ - ORDER BY e.valid_at DESC, e.created_at DESC + ORDER BY e.valid_at DESC, e.created_at DESC, e.uuid ASC LIMIT $num_episodes """ ) diff --git a/graphiti_core/utils/maintenance/node_operations.py b/graphiti_core/utils/maintenance/node_operations.py index 0a1fb5bc0f..d315e3022b 100644 --- a/graphiti_core/utils/maintenance/node_operations.py +++ b/graphiti_core/utils/maintenance/node_operations.py @@ -17,7 +17,7 @@ import logging from collections.abc import Awaitable, Callable from time import time -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal from pydantic import BaseModel @@ -91,6 +91,31 @@ NodeSummaryFilter = Callable[[EntityNode], Awaitable[bool]] +# Which stored node attributes reach prompts. 'all' keeps every stored property (upstream). +# 'declared' keeps only the attributes that the node's entity type model declares. +PromptAttributes = Literal['all', 'declared'] + + +def prompt_attributes_for_node( + node: EntityNode, + entity_types: dict[str, type[BaseModel]] | None, + policy: PromptAttributes = 'all', +) -> dict[str, Any]: + """Return the attributes of `node` that a prompt may show under `policy`.""" + attributes = node.attributes + if policy == 'all': + return attributes + entity_type = _entity_type_for_node(node, entity_types) + if entity_type is None: + return {} + declared = entity_type.model_fields + return {key: value for key, value in (attributes or {}).items() if key in declared} + + +def _kwargs_if(condition: bool, **kwargs: Any) -> dict[str, Any]: + """Keyword arguments to forward only when `condition` holds (typed for pyright).""" + return kwargs if condition else {} + async def extract_nodes( clients: GraphitiClients, @@ -481,6 +506,7 @@ async def _collect_candidate_nodes( existing_nodes_override: list[EntityNode] | None = None, identity_properties: dict[str, list[str]] | None = None, reuse_name_embeddings: bool = False, + trace: 'ResolutionTrace | None' = None, ) -> list[list[EntityNode]]: """Search per extracted name and return ordered candidates for each extracted node. @@ -492,7 +518,10 @@ async def _collect_candidate_nodes( extracted_nodes, identity_properties, ) - exact_name_results = await _collect_exact_name_candidate_nodes(clients, extracted_nodes) + # Pass `trace` only when it is set, so the call of today stays the same. + exact_name_results = await _collect_exact_name_candidate_nodes( + clients, extracted_nodes, **_kwargs_if(trace is not None, trace=trace) + ) search_results = await _semantic_candidate_search( clients, extracted_nodes, reuse_name_embeddings=reuse_name_embeddings ) @@ -563,6 +592,7 @@ async def _lookup_node(node: EntityNode) -> list[EntityNode]: async def _collect_exact_name_candidate_nodes( clients: GraphitiClients, extracted_nodes: list[EntityNode], + trace: 'ResolutionTrace | None' = None, ) -> list[list[EntityNode]]: """Fetch durable exact-name candidates before embedding-based search.""" if not extracted_nodes: @@ -586,6 +616,9 @@ async def _collect_exact_name_candidate_nodes( ) return [[] for _ in extracted_nodes] + if trace is not None: + trace.record_name_lookup(names, group_ids, candidate_nodes) + candidates_by_group_and_name: dict[tuple[str, str], list[EntityNode]] = {} for candidate in candidate_nodes: name_key = _normalize_string_exact(candidate.name) @@ -730,6 +763,7 @@ async def _resolve_with_llm( identity_gate_edges: list[EntityEdge] | None = None, *, clients: GraphitiClients | None = None, + prompt_attributes: PromptAttributes = 'all', ) -> None: """Escalate unresolved nodes to the dedupe prompt so the LLM can select or reject duplicates. @@ -781,7 +815,7 @@ async def _resolve_with_llm( existing_nodes_context = [ { - **candidate.attributes, + **prompt_attributes_for_node(candidate, entity_types, prompt_attributes), 'candidate_id': i, 'name': candidate.name, 'entity_types': candidate.labels, @@ -923,6 +957,7 @@ async def _resolve_unresolved_indices( identity_gate_edges: list[EntityEdge] | None, *, clients: GraphitiClients | None = None, + prompt_attributes: PromptAttributes = 'all', ) -> None: """Resolve the batch's current unresolved indices via the dedupe LLM. @@ -944,6 +979,10 @@ async def _resolve_unresolved_indices( for candidate in candidate_nodes_by_extracted[idx] ] ) + # Pass `prompt_attributes` only when it is not the default, so the call of today stays the same. + policy_kwargs: dict[str, Any] = ( + {'prompt_attributes': prompt_attributes} if prompt_attributes != 'all' else {} + ) try: await _resolve_with_llm( llm_client, @@ -956,6 +995,7 @@ async def _resolve_unresolved_indices( identity_gate_hook=identity_gate_hook, identity_gate_edges=identity_gate_edges, clients=clients, + **policy_kwargs, ) except GraphitiRequestTooLargeError: if len(state.unresolved_indices) == 1: @@ -982,6 +1022,7 @@ async def _resolve_unresolved_indices( identity_gate_hook, identity_gate_edges, clients=clients, + **policy_kwargs, ) @@ -1034,6 +1075,7 @@ async def resolve_extracted_nodes( node_pre_resolution_edges: list[EntityEdge] | None = None, identity_properties: dict[str, list[str]] | None = None, trace: 'ResolutionTrace | None' = None, + prompt_attributes: PromptAttributes = 'all', ) -> tuple[list[EntityNode], dict[str, str], list[tuple[EntityNode, EntityNode]]]: """Resolve nodes with semantic retrieval first, then deterministic and LLM dedup. @@ -1105,6 +1147,7 @@ async def resolve_extracted_nodes( ordinary_nodes, existing_nodes_override=existing_nodes_override, identity_properties=identity_properties, + **_kwargs_if(trace is not None, trace=trace), ) if ordinary_nodes else [] @@ -1135,6 +1178,7 @@ async def resolve_extracted_nodes( identity_gate_hook=identity_gate_hook, identity_gate_edges=identity_gate_edges, pre_resolved=pre_resolved, + prompt_attributes=prompt_attributes, ) @@ -1151,6 +1195,7 @@ async def resolve_nodes_with_candidates( identity_gate_hook: IdentityGateHook | None = None, identity_gate_edges: list[EntityEdge] | None = None, pre_resolved: dict[int, EntityNode] | None = None, + prompt_attributes: PromptAttributes = 'all', ) -> tuple[list[EntityNode], dict[str, str], list[tuple[EntityNode, EntityNode]]]: """Resolve nodes against given candidates: identity rule, similarity rule, then LLM. @@ -1234,6 +1279,7 @@ async def resolve_nodes_with_candidates( identity_gate_hook, identity_gate_edges, clients=clients, + **_kwargs_if(prompt_attributes != 'all', prompt_attributes=prompt_attributes), ) if not state.unresolved_indices and not any(candidate_nodes_by_extracted): @@ -1292,6 +1338,7 @@ async def extract_attributes_only_from_nodes( previous_episodes: list[EpisodicNode] | None = None, entity_types: dict[str, type[BaseModel]] | None = None, validate_shape: bool = True, + prompt_attributes: PromptAttributes = 'all', ) -> list[EntityNode]: if not nodes: return nodes @@ -1320,6 +1367,7 @@ async def extract_attributes_only_from_nodes( entity_type, clients=clients, validate_shape=validate_shape, + **_kwargs_if(prompt_attributes != 'all', prompt_attributes=prompt_attributes), ) for node, entity_type in extraction_inputs ], @@ -1349,6 +1397,7 @@ async def extract_attributes_from_nodes( skip_fact_appending: bool = False, include_type_descriptions: bool = False, skip_attribute_extraction: bool = False, + prompt_attributes: PromptAttributes = 'all', ) -> list[EntityNode]: llm_client = clients.llm_client embedder = clients.embedder @@ -1363,6 +1412,7 @@ async def extract_attributes_from_nodes( episode, previous_episodes, entity_types, + **_kwargs_if(prompt_attributes != 'all', prompt_attributes=prompt_attributes), ) # Extract summaries in batch @@ -1377,6 +1427,11 @@ async def extract_attributes_from_nodes( entity_types=entity_types if include_type_descriptions else None, clients=clients, max_coroutines=getattr(clients, 'max_coroutines', None), + **( + {'prompt_attributes': prompt_attributes, 'declared_entity_types': entity_types} + if prompt_attributes != 'all' + else {} + ), ) await create_entity_node_embeddings(embedder, nodes) @@ -1393,6 +1448,7 @@ async def _extract_entity_attributes( *, clients: GraphitiClients | None = None, validate_shape: bool = True, + prompt_attributes: PromptAttributes = 'all', ) -> dict[str, Any]: if entity_type is None or len(entity_type.model_fields) == 0: # No typed schema: preserve any pre-existing attributes rather than @@ -1400,12 +1456,19 @@ async def _extract_entity_attributes( # this result back cannot alias the original mapping. return dict(node.attributes or {}) + shown_attributes = node.attributes + if prompt_attributes == 'declared': + shown_attributes = { + key: value + for key, value in (node.attributes or {}).items() + if key in entity_type.model_fields + } attributes_context = _build_episode_context( # should not include summary node_data={ 'name': node.name, 'entity_types': node.labels, - 'attributes': without_merge_lineage(node.attributes), + 'attributes': without_merge_lineage(shown_attributes), }, episode=episode, previous_episodes=previous_episodes, @@ -1455,6 +1518,8 @@ async def _extract_entity_summaries_batch( entity_types: dict[str, type[BaseModel]] | None = None, clients: GraphitiClients | None = None, max_coroutines: int | None = None, + prompt_attributes: PromptAttributes = 'all', + declared_entity_types: dict[str, type[BaseModel]] | None = None, ) -> None: """Extract summaries for multiple entities in batched LLM calls. @@ -1520,6 +1585,8 @@ async def _extract_entity_summaries_batch( use_episode_prompt=skip_fact_appending, entity_types=entity_types, clients=clients, + prompt_attributes=prompt_attributes, + declared_entity_types=declared_entity_types, ) for flight in node_flights ], @@ -1536,6 +1603,8 @@ async def _process_summary_flight( use_episode_prompt: bool = False, entity_types: dict[str, type[BaseModel]] | None = None, clients: GraphitiClients | None = None, + prompt_attributes: PromptAttributes = 'all', + declared_entity_types: dict[str, type[BaseModel]] | None = None, ) -> None: """Process a single flight of nodes for batch summarization.""" # Build entity type descriptions from docstrings, stripping GOOD/BAD @@ -1552,7 +1621,9 @@ async def _process_summary_flight( 'name': node.name, 'summary': node.summary, 'entity_types': node.labels, - 'attributes': node.attributes, + 'attributes': prompt_attributes_for_node( + node, declared_entity_types, prompt_attributes + ), } for node in nodes ] diff --git a/pyproject.toml b/pyproject.toml index e2e85efdc7..5e3007c0e7 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.post2" +version = "0.32.1.post3" 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 new file mode 100644 index 0000000000..aed6dd30da --- /dev/null +++ b/tests/test_replay_capture.py @@ -0,0 +1,576 @@ +"""Candidate-universe capture seams (menhir fork): the trace hooks, deterministic tie-breaks, +seeded uuids and the `prompt_attributes` policy. No database and no model call.""" + +import json +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock, MagicMock, Mock + +import pytest +from pydantic import BaseModel + +import graphiti_core.graphiti as graphiti_module +from graphiti_core.cross_encoder.client import CrossEncoderClient +from graphiti_core.driver.driver import GraphProvider +from graphiti_core.edges import EntityEdge +from graphiti_core.embedder import EmbedderClient +from graphiti_core.graphiti import Graphiti +from graphiti_core.graphiti_types import GraphitiClients +from graphiti_core.ingestion import ConcurrentIngestionConfig +from graphiti_core.ingestion.change_set import ResolutionTrace +from graphiti_core.llm_client import LLMClient +from graphiti_core.nodes import EntityNode, EpisodeType, EpisodicNode +from graphiti_core.search import search_utils +from graphiti_core.search.search_filters import SearchFilters +from graphiti_core.seeded_uuids import reseed_extraction, seeded_uuid +from graphiti_core.tracer import NoOpTracer +from graphiti_core.utils.maintenance import edge_operations as edge_ops +from graphiti_core.utils.maintenance import node_operations as node_ops +from graphiti_core.utils.maintenance.dedup_helpers import ( + DedupResolutionState, + _build_candidate_indexes, +) +from graphiti_core.utils.maintenance.graph_data_operations import retrieve_episodes + +GROUP = 'replay_group' +T0 = datetime(2026, 1, 1, tzinfo=timezone.utc) +T1 = T0 + timedelta(days=3) + + +class Person(BaseModel): + """A person.""" + + role: str | None = None + + +class StopLookup(Exception): + pass + + +def make_episode(uuid: str = 'ep1') -> EpisodicNode: + return EpisodicNode( + uuid=uuid, + name='episode', + group_id=GROUP, + source=EpisodeType.text, + source_description='test', + content='content', + valid_at=T1, + created_at=T1, + ) + + +# --------------------------------------------------------------------------- +# Trace hooks +# --------------------------------------------------------------------------- + + +def test_trace_records_context_episodes_endpoint_and_name_lookups_even_when_empty(): + trace = ResolutionTrace() + trace.record_context_episodes([]) + assert trace.context_episode_uuids == [] + trace.record_context_episodes([make_episode('a'), make_episode('b')]) + assert trace.context_episode_uuids == ['a', 'b'] + + trace.record_endpoint_lookup(['n2', 'n1'], []) + trace.record_endpoint_lookup(['n1'], [EntityNode(uuid='n1', name='n1', group_id=GROUP)]) + assert trace.endpoint_lookups == [(['n2', 'n1'], []), (['n1'], ['n1'])] + + trace.record_name_lookup(['Ana'], [GROUP], []) + assert trace.name_lookups == [(['Ana'], [GROUP], [])] + + +async def test_exact_name_lookup_is_reported_to_the_trace_with_empty_pools(monkeypatch): + found = EntityNode(uuid='stored', name='Ana', group_id=GROUP) + lookup = AsyncMock(side_effect=[[found], []]) + monkeypatch.setattr(EntityNode, 'get_by_names', lookup) + clients = SimpleNamespace(driver=MagicMock()) + nodes = [EntityNode(uuid='x1', name='Ana', group_id=GROUP)] + + trace = ResolutionTrace() + pools = await node_ops._collect_exact_name_candidate_nodes(clients, nodes, trace=trace) + assert [[n.uuid for n in pool] for pool in pools] == [['stored']] + pools = await node_ops._collect_exact_name_candidate_nodes(clients, nodes, trace=trace) + assert pools == [[]] + assert trace.name_lookups == [(['Ana'], [GROUP], ['stored']), (['Ana'], [GROUP], [])] + + # Without a trace the result is the same. + lookup.side_effect = [[found]] + plain = await node_ops._collect_exact_name_candidate_nodes(clients, nodes) + assert [[n.uuid for n in pool] for pool in plain] == [['stored']] + + +async def test_collect_candidate_nodes_forwards_trace_only_when_set(monkeypatch): + seen: list[dict] = [] + + async def fake_exact(clients, nodes, **kwargs): + seen.append(kwargs) + return [[] for _ in nodes] + + monkeypatch.setattr(node_ops, '_collect_exact_name_candidate_nodes', fake_exact) + monkeypatch.setattr(node_ops, '_semantic_candidate_search', AsyncMock(return_value=[[]])) + clients = SimpleNamespace(driver=MagicMock()) + nodes = [EntityNode(uuid='x1', name='Ana', group_id=GROUP)] + + await node_ops._collect_candidate_nodes(clients, nodes) + trace = ResolutionTrace() + await node_ops._collect_candidate_nodes(clients, nodes, trace=trace) + assert seen == [{}, {'trace': trace}] + + +async def test_edge_resolution_reports_endpoint_lookup_with_and_without_result(monkeypatch): + stored = EntityNode(uuid='b', name='b', group_id=GROUP) + get_by_uuids = AsyncMock(side_effect=[[stored], []]) + monkeypatch.setattr(EntityNode, 'get_by_uuids', get_by_uuids) + # Stop after the lookup: the rest of resolution is not under test. + monkeypatch.setattr(edge_ops, 'enforce_edge_type_signatures', Mock(side_effect=StopLookup)) + edge = EntityEdge( + uuid='e1', + group_id=GROUP, + source_node_uuid='a', + target_node_uuid='b', + name='RELATES', + fact='f', + created_at=T0, + ) + clients = SimpleNamespace( + driver=MagicMock(), llm_client=MagicMock(), embedder=MagicMock(), cross_encoder=MagicMock() + ) + nodes = [EntityNode(uuid='a', name='a', group_id=GROUP)] + trace = ResolutionTrace() + for _ in range(2): + with pytest.raises(StopLookup): + await edge_ops.resolve_extracted_edges( + clients, [edge], make_episode(), nodes, {}, {('Entity', 'Entity'): []}, trace=trace + ) + assert trace.endpoint_lookups == [(['b'], ['b']), (['b'], [])] + + +# --------------------------------------------------------------------------- +# add_episode: guard, trace forwarding, uuid_seed +# --------------------------------------------------------------------------- + + +def make_graphiti(concurrent: bool = False) -> tuple[Graphiti, Mock]: + driver = Mock() + driver._database = GROUP + graphiti = Graphiti.__new__(Graphiti) + graphiti.driver = driver + graphiti.tracer = NoOpTracer() + graphiti.clients = GraphitiClients.model_construct( + driver=driver, + llm_client=Mock(spec=LLMClient), + embedder=Mock(spec=EmbedderClient), + cross_encoder=Mock(spec=CrossEncoderClient), + tracer=graphiti.tracer, + ) + for name in ( + 'single_episode_extraction_hook', + 'identity_gate_hook', + 'candidate_filter_hook', + 'node_pre_resolution_hook', + 'edge_expiry_hook', + 'edge_invalidation_hook', + ): + setattr(graphiti, name, None) + graphiti.preserved_edge_attributes = frozenset() + graphiti.max_coroutines = None + graphiti.store_raw_episode_content = True + if concurrent: + graphiti.concurrent_ingestion = ConcurrentIngestionConfig(window=4) + ingestor = Mock() + ingestor.add_episode = AsyncMock(return_value=object()) + graphiti._concurrent_ingestor = ingestor + return graphiti, driver + + +async def call_add_episode(graphiti: Graphiti, **kwargs): + return await graphiti.add_episode( + name='episode', + episode_body='content', + source_description='test', + reference_time=T0, + group_id=GROUP, + **kwargs, + ) + + +@pytest.mark.parametrize( + 'kwargs', + [ + {'resolution_trace': ResolutionTrace()}, + {'uuid_seed': 'seed'}, + {'prompt_attributes': 'declared'}, + ], + ids=['resolution_trace', 'uuid_seed', 'prompt_attributes'], +) +async def test_concurrent_path_rejects_the_replay_seams(kwargs): + graphiti, _ = make_graphiti(concurrent=True) + with pytest.raises(ValueError, match='not supported with concurrent ingestion'): + await call_add_episode(graphiti, **kwargs) + graphiti._concurrent_ingestor.add_episode.assert_not_awaited() + + +async def test_concurrent_path_still_routes_with_default_replay_seams(): + graphiti, _ = make_graphiti(concurrent=True) + await call_add_episode(graphiti) + await call_add_episode(graphiti, prompt_attributes='all') + assert graphiti._concurrent_ingestor.add_episode.await_count == 2 + + +async def test_unknown_prompt_attributes_policy_is_rejected(): + graphiti, _ = make_graphiti() + with pytest.raises(ValueError, match='prompt_attributes'): + 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.""" + record: dict[str, Any] = {} + clients = graphiti.clients + + monkeypatch.setattr(graphiti, '_resolve_request_scope', lambda gid: (gid, driver, clients)) + monkeypatch.setattr(graphiti_module, '_validate_saga_scope', AsyncMock()) + monkeypatch.setattr(graphiti, 'retrieve_episodes', AsyncMock(return_value=previous)) + + def extraction(episode, *_args, **_kwargs): + nodes = [EntityNode(name=name, group_id=GROUP, labels=['Entity']) for name in 'ABC'] + edges = [ + EntityEdge( + group_id=GROUP, + source_node_uuid=nodes[i].uuid, + target_node_uuid=nodes[i + 1].uuid, + name='RELATES', + fact=f'fact {i}', + created_at=T0, + ) + for i in range(2) + ] + index_map = {node.uuid: [0] for node in nodes} + return nodes, edges, index_map, None + + monkeypatch.setattr(graphiti, '_extract_single_episode', AsyncMock(side_effect=extraction)) + + async def fake_resolve_nodes(clients, extracted, episode, previous_episodes, *a, **kwargs): + record['resolve_nodes_kwargs'] = kwargs + record['extracted_nodes'] = [(n.uuid, n.name) for n in extracted] + return list(extracted), {n.uuid: n.uuid for n in extracted}, [] + + monkeypatch.setattr(graphiti_module, 'resolve_extracted_nodes', fake_resolve_nodes) + + async def fake_edges(episode, extracted, *a, **kwargs): + record['edges_kwargs'] = kwargs + edges = kwargs['precomputed_edges'] + record['edges'] = [(e.uuid, e.source_node_uuid, e.target_node_uuid) for e in edges] + return edges, [], edges + + monkeypatch.setattr(graphiti, '_extract_and_resolve_edges', fake_edges) + + async def fake_attrs(clients, nodes, *a, **kwargs): + record['attrs_kwargs'] = kwargs + return nodes + + monkeypatch.setattr(graphiti_module, 'extract_attributes_from_nodes', fake_attrs) + + async def fake_process( + episode, nodes, entity_edges, now, group_id, saga, prev, index_map, **kw + ): + record['process_kwargs'] = kw + record['node_index_map'] = dict(index_map) + from graphiti_core.utils.maintenance.edge_operations import build_episodic_edges + + episodic_edges = build_episodic_edges(nodes, [episode.uuid], now, index_map) + if kw.get('uuid_seed') is not None: + for index, edge in enumerate(episodic_edges): + edge.uuid = seeded_uuid(kw['uuid_seed'], 'episodic_edge', index) + record['episodic_edges'] = [e.uuid for e in episodic_edges] + return episodic_edges, episode + + monkeypatch.setattr(graphiti, '_process_episode_data', fake_process) + return record + + +async def test_add_episode_forwards_trace_and_records_context_episodes(monkeypatch): + graphiti, driver = make_graphiti() + previous = [make_episode('p1'), make_episode('p2')] + record = stub_pipeline(monkeypatch, graphiti, driver, previous) + trace = ResolutionTrace() + + await call_add_episode(graphiti, resolution_trace=trace) + + assert trace.context_episode_uuids == ['p1', 'p2'] + assert record['resolve_nodes_kwargs']['trace'] is trace + assert record['edges_kwargs']['trace'] is trace + assert 'prompt_attributes' not in record['resolve_nodes_kwargs'] + assert 'prompt_attributes' not in record['attrs_kwargs'] + + +async def test_add_episode_default_call_has_no_replay_kwargs(monkeypatch): + graphiti, driver = make_graphiti() + record = stub_pipeline(monkeypatch, graphiti, driver, []) + + await call_add_episode(graphiti) + + assert 'trace' not in record['resolve_nodes_kwargs'] + assert 'trace' not in record['edges_kwargs'] + assert 'uuid_seed' not in record['edges_kwargs'] + assert 'uuid_seed' not in record['process_kwargs'] + assert 'prompt_attributes' not in record['attrs_kwargs'] + + +async def test_add_episode_forwards_the_declared_policy(monkeypatch): + graphiti, driver = make_graphiti() + record = stub_pipeline(monkeypatch, graphiti, driver, []) + + await call_add_episode(graphiti, prompt_attributes='declared') + + assert record['resolve_nodes_kwargs']['prompt_attributes'] == 'declared' + assert record['edges_kwargs']['prompt_attributes'] == 'declared' + assert record['attrs_kwargs']['prompt_attributes'] == 'declared' + + +async def test_uuid_seed_gives_the_same_uuids_twice_and_none_gives_random(monkeypatch): + runs = [] + for seed in ('seed-1', 'seed-1', 'seed-2', None, None): + graphiti, driver = make_graphiti() + record = stub_pipeline(monkeypatch, graphiti, driver, []) + await call_add_episode(graphiti, uuid_seed=seed) + runs.append(record) + + first, second, other, plain_a, plain_b = runs + assert first['extracted_nodes'] == second['extracted_nodes'] + assert first['edges'] == second['edges'] + assert first['episodic_edges'] == second['episodic_edges'] + assert first['extracted_nodes'] != other['extracted_nodes'] + + # Edge endpoints and the episode index map follow the new node uuids. + node_uuids = [uuid for uuid, _ in first['extracted_nodes']] + assert node_uuids == [seeded_uuid('seed-1', 'node', i) for i in range(3)] + assert [(s, t) for _, s, t in first['edges']] == [ + (node_uuids[0], node_uuids[1]), + (node_uuids[1], node_uuids[2]), + ] + assert sorted(first['node_index_map']) == sorted(node_uuids) + + # Without a seed the uuids are random uuid4 values. + from uuid import UUID + + for record in (plain_a, plain_b): + for uuid, _ in record['extracted_nodes']: + assert UUID(uuid).version == 4 + assert plain_a['extracted_nodes'] != plain_b['extracted_nodes'] + + +def test_seeded_uuids_follow_input_order_not_the_old_uuids(): + def build(old_uuids): + return [ + EntityNode(uuid=old, name=name, group_id=GROUP) + for old, name in zip(old_uuids, 'AB', strict=True) + ] + + first = build(['u1', 'u2']) + second = build(['z9', 'z8']) # a different completion order gives different old uuids + reseed_extraction('s', first) + reseed_extraction('s', second) + assert [n.uuid for n in first] == [n.uuid for n in second] + + swapped = list(reversed(build(['u1', 'u2']))) + reseed_extraction('s', swapped) + assert [n.name for n in swapped] == ['B', 'A'] + assert [n.uuid for n in swapped] == [n.uuid for n in first] # position, not content + + assert seeded_uuid('s', 'node', 0) != seeded_uuid('s', 'edge', 0) + assert seeded_uuid('s', 'node', 0) != seeded_uuid('t', 'node', 0) + assert seeded_uuid('s', 'node', 0) != seeded_uuid('s', 'node', 1) + + +# --------------------------------------------------------------------------- +# prompt_attributes +# --------------------------------------------------------------------------- + + +def candidate(**attributes: Any) -> EntityNode: + return EntityNode( + uuid='cand', + name='Ana Lopez', + group_id=GROUP, + labels=['Entity', 'Person'], + summary='A person', + attributes={'role': 'engineer', **attributes}, + ) + + +async def capture_dedupe_context(monkeypatch, node: EntityNode, policy: str | None) -> str: + captured: dict = {} + + async def fake_generate(llm_client, name, legacy_prompt, context, **kwargs): + captured['context'] = context + return {'entity_resolutions': [{'id': 0, 'name': 'Ana', 'duplicate_candidate_id': -1}]} + + monkeypatch.setattr(node_ops, 'generate_prompt_response', fake_generate) + indexes = _build_candidate_indexes([node]) + extracted = [EntityNode(uuid='x1', name='Ana', group_id=GROUP, labels=['Entity', 'Person'])] + state = DedupResolutionState(resolved_nodes=[None], uuid_map={}, unresolved_indices=[0]) + kwargs: dict = {} if policy is None else {'prompt_attributes': policy} + await node_ops._resolve_with_llm( + MagicMock(max_tokens=1000), + extracted, + indexes, + state, + make_episode(), + [], + {'Person': Person}, + **kwargs, + ) + return json.dumps(captured['context'], sort_keys=True, default=str) + + +async def test_declared_policy_makes_dedupe_prompt_ignore_undeclared_properties(monkeypatch): + old = await capture_dedupe_context( + monkeypatch, candidate(last_accessed='2026-01-01T00:00:00'), 'declared' + ) + new = await capture_dedupe_context( + monkeypatch, candidate(last_accessed='2026-02-02T09:09:09', access_count=7), 'declared' + ) + assert old == new + assert 'engineer' in old + assert 'last_accessed' not in old + + +async def test_all_policy_keeps_the_dedupe_prompt_of_upstream(monkeypatch): + old = await capture_dedupe_context( + monkeypatch, candidate(last_accessed='2026-01-01T00:00:00'), None + ) + explicit = await capture_dedupe_context( + monkeypatch, candidate(last_accessed='2026-01-01T00:00:00'), 'all' + ) + new = await capture_dedupe_context( + monkeypatch, candidate(last_accessed='2026-02-02T09:09:09'), None + ) + assert old == explicit + assert old != new + assert 'last_accessed' in old + + +async def test_declared_policy_gives_no_attributes_to_an_untyped_node(monkeypatch): + untyped = EntityNode( + uuid='cand', + name='Ana Lopez', + group_id=GROUP, + labels=['Entity'], + attributes={'role': 'engineer'}, + ) + declared = await capture_dedupe_context(monkeypatch, untyped, 'declared') + assert 'engineer' not in declared + assert 'engineer' in await capture_dedupe_context(monkeypatch, untyped, 'all') + + +async def capture_summary_context(monkeypatch, node: EntityNode, policy: str | None) -> str: + captured: dict = {} + + async def fake_generate(llm_client, name, legacy_prompt, context, **kwargs): + captured['context'] = context + return {'summaries': []} + + monkeypatch.setattr(node_ops, 'generate_prompt_response', fake_generate) + kwargs: dict = {} + if policy is not None: + kwargs = {'prompt_attributes': policy, 'declared_entity_types': {'Person': Person}} + await node_ops._process_summary_flight( + MagicMock(), [node], make_episode(), [], entity_types={'Person': Person}, **kwargs + ) + return json.dumps(captured['context'], sort_keys=True, default=str) + + +async def test_declared_policy_makes_summary_prompt_ignore_undeclared_properties(monkeypatch): + old = await capture_summary_context( + monkeypatch, candidate(last_accessed='2026-01-01T00:00:00'), 'declared' + ) + new = await capture_summary_context( + monkeypatch, candidate(last_accessed='2026-02-02T09:09:09'), 'declared' + ) + assert old == new + assert 'engineer' in old + assert 'last_accessed' not in old + + +async def test_all_policy_keeps_the_summary_prompt_of_upstream(monkeypatch): + old = await capture_summary_context( + monkeypatch, candidate(last_accessed='2026-01-01T00:00:00'), None + ) + explicit = await capture_summary_context( + monkeypatch, candidate(last_accessed='2026-01-01T00:00:00'), 'all' + ) + new = await capture_summary_context( + monkeypatch, candidate(last_accessed='2026-02-02T09:09:09'), None + ) + assert old == explicit + assert old != new + + +# --------------------------------------------------------------------------- +# Deterministic tie-breaks (query text only; no database) +# --------------------------------------------------------------------------- + + +def fake_driver(provider: GraphProvider) -> Mock: + driver = Mock() + driver.provider = provider + driver.search_interface = None + driver.graph_operations_interface = None + driver.execute_query = AsyncMock(return_value=([], None, None)) + driver.build_fulltext_query = Mock(return_value='query') + driver.fulltext_syntax = '' + return driver + + +def queries_of(driver: Mock) -> list[str]: + return [' '.join(call.args[0].split()) for call in driver.execute_query.await_args_list] + + +def assert_tied_scores_break_on_uuid(queries: list[str], alias: str) -> None: + assert queries + for query in queries: + order = query.split('ORDER BY', 1)[1] + assert order.lstrip().startswith(('score DESC, ', 'i.score DESC, ', 'edge.score DESC, ')), ( + order + ) + assert f'{alias}.uuid ASC' in order.split('LIMIT')[0] + + +@pytest.mark.parametrize('provider', [GraphProvider.NEO4J, GraphProvider.FALKORDB]) +async def test_node_searches_break_score_ties_on_uuid(provider): + driver = fake_driver(provider) + await search_utils.node_similarity_search(driver, [0.1, 0.2], SearchFilters(), [GROUP], 5) + await search_utils.node_fulltext_search(driver, 'ana', SearchFilters(), [GROUP], 5) + assert_tied_scores_break_on_uuid(queries_of(driver), 'n') + + +@pytest.mark.parametrize('provider', [GraphProvider.NEO4J, GraphProvider.FALKORDB]) +async def test_edge_searches_break_score_ties_on_uuid(provider): + driver = fake_driver(provider) + await search_utils.edge_similarity_search( + driver, [0.1, 0.2], None, None, SearchFilters(), [GROUP], 5 + ) + await search_utils.edge_fulltext_search(driver, 'ana', SearchFilters(), [GROUP], 5) + assert_tied_scores_break_on_uuid(queries_of(driver), 'e') + + +async def test_get_by_names_and_attribute_lookup_have_a_uuid_order(): + driver = fake_driver(GraphProvider.NEO4J) + await EntityNode.get_by_names(driver, ['Ana'], [GROUP]) + await EntityNode.get_by_attribute_values(driver, GROUP, {'email': 'a@b.c'}, ['Person'], 5) + queries = queries_of(driver) + assert len(queries) == 2 + for query in queries: + assert 'ORDER BY n.uuid ASC' in query + + +@pytest.mark.parametrize('provider', [GraphProvider.NEO4J, GraphProvider.NEPTUNE]) +@pytest.mark.parametrize('saga', [None, 'saga-1']) +async def test_retrieve_episodes_breaks_created_at_ties_on_uuid(provider, saga): + driver = fake_driver(provider) + await retrieve_episodes(driver, T1, 3, [GROUP], None, saga) + (query,) = queries_of(driver) + assert 'ORDER BY e.valid_at DESC, e.created_at DESC, e.uuid ASC' in query diff --git a/uv.lock b/uv.lock index 6523d0b0f6..a23bbe8e3e 100644 --- a/uv.lock +++ b/uv.lock @@ -284,7 +284,7 @@ wheels = [ [[package]] name = "archolith-graphiti-core" -version = "0.32.1.post2" +version = "0.32.1.post3" source = { editable = "." } dependencies = [ { name = "certifi" },