Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from hugegraph_llm.config import huge_settings, prompt
from hugegraph_llm.nodes.base_node import BaseNode
from hugegraph_llm.operators.operator_list import OperatorList
from hugegraph_llm.utils.hugegraph_utils import gremlin_literal
from hugegraph_llm.utils.log import log

# TODO: remove 'as('subj)' step
Expand Down Expand Up @@ -193,7 +194,7 @@ def _process_vertex(

# TODO: we may remove label id or replace with label name
if matched_str in v_cache:
node_str = matched_str
node_str = str(matched_str) # numeric vertex ids are ints
else:
v_cache.add(matched_str)
node_str = f"{item['id']}{{{props_str}}}"
Expand Down Expand Up @@ -355,7 +356,7 @@ def _subgraph_query(self, context: Dict[str, Any]) -> Dict[str, Any]:
if not matched_vids:
return context

gremlin_query = VERTEX_QUERY_TPL.format(keywords=matched_vids)
gremlin_query = VERTEX_QUERY_TPL.format(keywords=",".join(gremlin_literal(vid) for vid in matched_vids))
vertexes = self._client.gremlin().exec(gremlin=gremlin_query)["data"]
log.debug("Vids gremlin query: %s", gremlin_query)

Expand All @@ -364,7 +365,7 @@ def _subgraph_query(self, context: Dict[str, Any]) -> Dict[str, Any]:
# TODO: use generator or asyncio to speed up the query logic
for matched_vid in matched_vids:
gremlin_query = VID_QUERY_NEIGHBOR_TPL.format(
keywords=f"'{matched_vid}'",
keywords=gremlin_literal(matched_vid),
Comment thread
atharrva01 marked this conversation as resolved.
Resolved
max_deep=self._max_deep,
edge_labels=edge_labels_str,
edge_limit=edge_limit_amount,
Expand All @@ -390,7 +391,7 @@ def _subgraph_query(self, context: Dict[str, Any]) -> Dict[str, Any]:
# WARN: When will the query enter here?
keywords = context.get("keywords")
assert keywords, "No related property(keywords) for graph query."
keywords_str = ",".join("'" + kw + "'" for kw in keywords)
keywords_str = ",".join(gremlin_literal(kw) for kw in keywords)
gremlin_query = PROPERTY_QUERY_NEIGHBOR_TPL.format(
prop=self._prop_to_match,
keywords=keywords_str,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from hugegraph_llm.config import huge_settings, resource_path
from hugegraph_llm.indices.vector_index.base import VectorStoreBase
from hugegraph_llm.models.embeddings.base import BaseEmbedding
from hugegraph_llm.utils.hugegraph_utils import gremlin_literal
from hugegraph_llm.utils.log import log


Expand Down Expand Up @@ -64,7 +65,7 @@ def _exact_match_vids(self, keywords: List[str]) -> Tuple[List[str], List[str]]:
for i in range(vertex_label_num):
possible_vids.update([f"{i + 1}:{keyword}" for keyword in keywords])

vids_str = ",".join([f"'{vid}'" for vid in possible_vids])
vids_str = ",".join(gremlin_literal(vid) for vid in possible_vids)
resp = self._client.gremlin().exec(SemanticIdQuery.ID_QUERY_TEMPL.format(vids_str=vids_str))
searched_vids = [v["id"] for v in resp["data"]]

Expand Down
4 changes: 2 additions & 2 deletions hugegraph-llm/src/hugegraph_llm/utils/graph_index_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
)

from ..config import huge_settings
from .hugegraph_utils import clean_hg_data
from .hugegraph_utils import clean_hg_data, gremlin_literal
from .log import log
from .vector_index_utils import read_documents

Expand Down Expand Up @@ -69,7 +69,7 @@ def get_vertex_details(vertex_ids: List[str], context: Dict[str, Any]) -> List[D
if not vertex_ids:
return []

formatted_ids = ", ".join(f"'{vid}'" for vid in vertex_ids)
formatted_ids = ", ".join(gremlin_literal(vid) for vid in vertex_ids)
gremlin_query = f"g.V({formatted_ids}).limit(20)"
result = client.gremlin().exec(gremlin=gremlin_query)["data"]
return result
Expand Down
18 changes: 18 additions & 0 deletions hugegraph-llm/src/hugegraph_llm/utils/hugegraph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,24 @@
BACKUP_DIR = str(os.path.join(resource_path, "backup-graph-data-4020", huge_settings.graph_name))


_GROOVY_ESCAPES = {"\\": "\\\\", "'": "\\'", "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r"}


def gremlin_literal(value) -> str:
"""Render a vertex id or keyword as a Gremlin literal.

Integers stay numeric (HugeGraph treats 123 and '123' as different ids). Everything else becomes a
Groovy single-quoted string (no `$` interpolation) with quotes, backslashes and control chars escaped.
"""
if isinstance(value, int) and not isinstance(value, bool):
return str(value)
escaped = "".join(
_GROOVY_ESCAPES.get(ch) or (f"\\u{ord(ch):04x}" if ord(ch) < 0x20 or ord(ch) == 0x7F else ch)
for ch in str(value)
)
return f"'{escaped}'"


def run_gremlin_query(query, fmt=True, connection=None):
res = get_hg_client(connection=connection).gremlin().exec(query)
return json.dumps(res, indent=4, ensure_ascii=False) if fmt else res
Expand Down
69 changes: 69 additions & 0 deletions hugegraph-llm/src/tests/nodes/test_graph_query_node.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 types import SimpleNamespace

from hugegraph_llm.nodes.hugegraph_node.graph_query_node import GraphQueryNode
from tests.utils.mock import FakeGremlinEndpoint


def _graph_query_node(endpoint):
node = GraphQueryNode()
node._client = SimpleNamespace(gremlin=lambda: endpoint)
node._schema = "Vertex properties: [name: person, properties: []]\nEdge properties: [name: knows, properties: []]\n"
node._prop_to_match = None
node._max_deep = 2
node._max_items = 30
return node


def test_subgraph_query_escapes_vertex_ids_with_apostrophes():
# Fuzzy matching returns raw vertex ids from the vid index, so ids like 1:O'Brien reach the node unchanged.
endpoint = FakeGremlinEndpoint({"1:O'Brien": {"name": "O'Brien"}})
node = _graph_query_node(endpoint)

result = node._subgraph_query({"match_vids": ["1:O'Brien"]})

assert result["graph_result"] == ["1:O'Brien{name: O'Brien}"]
assert len(endpoint.scripts) == 2
assert all("'1:O\\'Brien'" in script for script in endpoint.scripts)


def _knows_path(start_id, start_name, end_id, end_name):
return {
"objects": [
{"label": "person", "id": start_id, "props": {"name": start_name}},
{"label": "knows", "inV": end_id, "outV": start_id, "props": {}},
{"label": "person", "id": end_id, "props": {"name": end_name}},
]
}


def test_subgraph_query_keeps_numeric_vertex_ids_numeric():
# Graphs with numeric ids store ints in the vid index; HugeGraph treats 123 and '123' as different ids.
# Two paths share the start vertex, so the second one hits the v_cache branch with an int id.
endpoint = FakeGremlinEndpoint(
{123: {"name": "n123"}},
paths=[_knows_path(123, "n123", 1, "Alice"), _knows_path(123, "n123", 2, "Bob")],
)
node = _graph_query_node(endpoint)

result = node._subgraph_query({"match_vids": [123]})

assert [script.split(")", 1)[0] for script in endpoint.scripts] == ["g.V(123", "g.V(123"]
assert sorted(result["graph_result"]) == [
"123--[knows]-->2{name: Bob}",
"123{name: n123}--[knows]-->1{name: Alice}",
]
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from unittest.mock import MagicMock, patch

from hugegraph_llm.operators.index_op.semantic_id_query import SemanticIdQuery
from tests.utils.mock import MockEmbedding
from tests.utils.mock import FakeGremlinEndpoint, MockEmbedding


class MockVectorStore:
Expand Down Expand Up @@ -156,3 +156,22 @@ def test_run_with_empty_keywords(self, mock_settings, mock_resource_path):

# Verify search was not called for empty keywords
query.vector_index.search.assert_not_called()

@patch("hugegraph_llm.operators.index_op.semantic_id_query.resource_path")
@patch("hugegraph_llm.operators.index_op.semantic_id_query.huge_settings")
@patch("hugegraph_llm.operators.index_op.semantic_id_query.PyHugeClient", new=MockPyHugeClient)
def test_exact_match_escapes_apostrophes_in_vids(self, mock_settings, mock_resource_path):
mock_settings.graph_name = "test_graph"
mock_settings.topk_per_keyword = 2
mock_settings.vector_dis_threshold = 1.5

with patch("os.path.join", return_value=self.test_dir):
query = SemanticIdQuery(self.embedding, self.mock_vector_store_class, by="keywords")
endpoint = FakeGremlinEndpoint({"1:O'Brien": {"name": "O'Brien"}, "1:Tom Hanks": {"name": "Tom Hanks"}})
query._client._gremlin = endpoint
query.vector_index.search.return_value = []

result_context = query.run({"keywords": ["O'Brien", "Tom Hanks"]})

self.assertEqual(sorted(result_context["match_vids"]), ["1:O'Brien", "1:Tom Hanks"])
self.assertIn("'1:O\\'Brien'", endpoint.scripts[-1])
61 changes: 61 additions & 0 deletions hugegraph-llm/src/tests/utils/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@

# pylint: disable=unused-argument

import ast

from pyhugegraph.utils.exceptions import ServerError

from hugegraph_llm.models.embeddings.base import BaseEmbedding


Expand Down Expand Up @@ -74,3 +78,60 @@ def __len__(self):
def search(self, query_vector, top_k=5):
# Simply return the first top_k documents.
return self.documents[: min(top_k, len(self.documents))]


class FakeGremlinEndpoint:
"""Stand-in for HugeGraph's /gremlin endpoint that rejects scripts whose g.V(...) ids don't parse.

Groovy and Python share the same rules for single-quoted literals with \\' and \\\\ escapes,
so ast.literal_eval acts as the parser. Vertex lookups return matching entries from `vertices`;
traversals (anything with `.repeat(`) return the `paths` that start at one of the requested ids.
"""

def __init__(self, vertices, paths=None):
self.vertices = vertices
self.paths = paths or []
self.scripts = []

@staticmethod
def _v_args(gremlin):
"""Return the text inside g.V(...), skipping quoted content and escapes; None if it never closes."""
if not gremlin.startswith("g.V("):
return None
quote, depth, i = None, 0, len("g.V(")
while i < len(gremlin):
ch = gremlin[i]
if quote:
if ch == "\\":
i += 1
elif ch == quote:
quote = None
elif ch in "'\"":
quote = ch
elif ch in "([":
depth += 1
elif ch in ")]":
if depth == 0:
return gremlin[len("g.V(") : i]
depth -= 1
i += 1
return None

def exec(self, gremlin):
self.scripts.append(gremlin)
args = self._v_args(gremlin)
try:
if args is None:
raise SyntaxError("unterminated g.V(...) call")
ids = ast.literal_eval(f"[{args}]")
except SyntaxError as e:
raise ServerError(f"Server Exception: startup failed: {e}") from e
if len(ids) == 1 and isinstance(ids[0], list): # g.V([...]) is equivalent to g.V(...)
ids = ids[0]
if ".repeat(" in gremlin:
return {"data": [path for path in self.paths if path["objects"][0]["id"] in ids]}
return {
"data": [
{"id": vid, "label": "person", "properties": self.vertices[vid]} for vid in ids if vid in self.vertices
]
}
44 changes: 44 additions & 0 deletions hugegraph-llm/src/tests/utils/test_graph_index_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 unittest.mock import Mock

import pytest
from pyhugegraph.client import PyHugeClient

from hugegraph_llm.utils.graph_index_utils import get_vertex_details
from tests.utils.mock import FakeGremlinEndpoint


def test_get_vertex_details_escapes_apostrophes_in_vertex_ids():
endpoint = FakeGremlinEndpoint({"1:O'Brien": {"name": "O'Brien"}})
client = Mock(spec=PyHugeClient)
client.gremlin.return_value = endpoint

result = get_vertex_details(["1:O'Brien"], {"graph_client": client})

assert [v["id"] for v in result] == ["1:O'Brien"]
assert endpoint.scripts == ["g.V('1:O\\'Brien').limit(20)"]


@pytest.mark.parametrize("vertex_id", ["1:x).y", "1:a', 'b').limit(1", "1:[x](y)", '1:say "hi").z'])
def test_get_vertex_details_handles_ids_with_gremlin_syntax(vertex_id):
endpoint = FakeGremlinEndpoint({vertex_id: {"name": "n"}})
client = Mock(spec=PyHugeClient)
client.gremlin.return_value = endpoint

result = get_vertex_details([vertex_id], {"graph_client": client})

assert [v["id"] for v in result] == [vertex_id]
28 changes: 27 additions & 1 deletion hugegraph-llm/src/tests/utils/test_hugegraph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.

import ast
import json
import os
import stat
Expand All @@ -29,7 +30,7 @@

from hugegraph_llm.config import huge_settings
from hugegraph_llm.utils import hugegraph_utils
from hugegraph_llm.utils.hugegraph_utils import get_hg_client
from hugegraph_llm.utils.hugegraph_utils import get_hg_client, gremlin_literal


def test_request_connection_passes_canonical_validated_url(monkeypatch):
Expand Down Expand Up @@ -245,3 +246,28 @@ def test_backup_flow_writes_native_schema_and_cleans_only_reused_directory(tmp_p
assert json.loads((current / "edges.json").read_text(encoding="utf-8"))[0]["outV"] == "alice"
assert not (current / "schema.groovy").exists()
assert (historical / "schema.groovy").read_text(encoding="utf-8") == "historic"


@pytest.mark.parametrize(
("value", "expected"),
[
("1:Tom Hanks", "'1:Tom Hanks'"),
("1:O'Brien", "'1:O\\'Brien'"),
("C:\\path", "'C:\\\\path'"),
("1:$100 bill", "'1:$100 bill'"),
("1:line\nbreak\r\tend", "'1:line\\nbreak\\r\\tend'"),
("1:bell\x07", "'1:bell\\u0007'"),
(123, "123"),
(2**40, "1099511627776"),
("123", "'123'"),
(True, "'True'"),
],
)
def test_gremlin_literal_escapes_strings_and_keeps_ints_numeric(value, expected):
assert gremlin_literal(value) == expected


@pytest.mark.parametrize("value", ["1:O'Brien", "C:\\x\\'y", "a\nb\rc\td\be\ff\x00g\x1f\x7f", "$x ${y}"])
def test_gremlin_literal_round_trips_through_a_single_quoted_literal(value):
# Python and Groovy decode these escapes (\\ \' \n \r \t \b \f \uXXXX) the same way in '...' strings.
assert ast.literal_eval(gremlin_literal(value)) == value
Loading