Skip to content

feat(llm): enforce read-only Gremlin before execution - #456

Open
yuangu-chengzi wants to merge 5 commits into
apache:mainfrom
yuangu-chengzi:feat/llm-gremlin-readonly-guard
Open

yuangu-chengzi wants to merge 5 commits into
apache:mainfrom
yuangu-chengzi:feat/llm-gremlin-readonly-guard

Conversation

@yuangu-chengzi

@yuangu-chengzi yuangu-chengzi commented Dec 4, 2026 •

Copy link
Copy Markdown

Summary

Implements the server-side read-only boundary requested in #455 for GraphRAG execution.

Adds GRAPH_GREMLIN_READ_ONLY (default true). Before GraphQueryNode or run_gremlin_query executes Gremlin produced by the model or supplied by a caller, a conservative classifier rejects unsafe and uncertain queries.

Motivation

#455 exposes /rag/graph as an MCP tool, but HugeGraph-AI executes model-generated Gremlin with its own graph credentials. The MCP layer cannot verify those credentials, so the boundary belongs at the execution point in HugeGraph-AI. This also protects the Text2Gremlin execution paths, which use run_gremlin_query.

Relates to #455 and #225.

Changes

  • Add hugegraph_llm/utils/gremlin_policy.py, a conservative read-only classifier mirroring the MCP policy, and gremlin_guard.py.
  • GraphQueryNode: when generated Gremlin is not read-only, log the rejection, clear graph_result, and fall back to the safe subgraph query.
  • run_gremlin_query: raise a clear ValueError before executing non-read-only Gremlin; GremlinExecuteNode already reports execution errors.
  • Add GRAPH_GREMLIN_READ_ONLY (default true) to HugeGraphConfig and document it in config.md.
  • Add tests for the classifier, the guard helper, and the config default/override.
  • Keep the existing test_gremlin_execute_surfaces_invalid_query focused on server-side error surfacing by disabling the read-only guard in that test; the guard itself has dedicated unit tests.
  • Allow the read-only shaping steps, predicates, and anonymous traversals used by the bundled text2gremlin.csv examples (project, fold, match, constant, hasNext, identity, comparison/string predicates, and __ roots), so the default-on guard does not reject Text2Gremlin's own examples.
  • Reject any $ inside double-quoted or triple-double-quoted GStrings, not only ${...}, because Groovy also interpolates bare $name and $a.b.
  • Reject any Groovy unicode escape (\uXXXX) before lexing; Groovy expands it before tokenization and can use it to close a string/comment and hide a mutation.
  • Escape vertex IDs and property keywords before interpolating them into fallback Gremlin literals; unsafe value types fail closed instead of being stringified.
  • Add tests for every bundled text2gremlin.csv query, $ interpolation, run_gremlin_query rejection before client creation, and fallback escaping after a rejected generated query.
  • Fix a missing . before where(...) in one bundled CSV example so the shipped example is valid Gremlin.

Tests

  • pytest src/tests/utils/test_gremlin_policy.py src/tests/utils/test_gremlin_guard.py -q — 30 passed.
  • Added src/tests/nodes/test_graph_query_node_guard.py for generated-Gremlin rejection and escaped fallback IDs; it runs in CI because pycgraph is Linux-only.
  • Config document/default tests are part of the normal HugeGraph-AI suite; CI will run the full suite.
  • ruff format --check and ruff check pass on src/.
  • git diff --check — passed.

Notes

  • The classifier is conservative: uncertain queries are rejected. Operators can set GRAPH_GREMLIN_READ_ONLY=false only for controlled write workflows; the default protects generated-Gremlin execution.
  • The policy currently mirrors hugegraph-mcp/gremlin_policy.py. A follow-up can move it into a shared package once Python-client release coordination allows it; this PR keeps the change inside hugegraph-llm to avoid a cross-package version dependency.

🤖 Generated with Claude Code

Add GRAPH_GREMLIN_READ_ONLY (default true) and reject non-read-only Gremlin produced by the model or caller before GraphQueryNode or run_gremlin_query executes it.

The conservative classifier mirrors the MCP read-only policy; GraphQueryNode falls back to the safe subgraph query, while run_gremlin_query raises a clear ValueError.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi
yuangu-chengzi force-pushed the feat/llm-gremlin-readonly-guard branch 2 times, most recently from 45a1fdf to df928bf Compare December 4, 2026 15:40
@yuangu-chengzi

Copy link
Copy Markdown
Author

Pushed CI fixes: ruff formatting in gremlin_policy.py, and the existing boundary test now disables the guard because it asserts server-side error surfacing (the guard has dedicated unit tests). The new workflow run is action_required; could a maintainer approve it when convenient?

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: The default-on read-only guard rejects 45 of the 80 bundled text2gremlin.csv read queries, and it classifies Groovy $name interpolation in double-quoted strings as safe, so it blocks valid reads while still letting the server evaluate caller expressions.

"call",
"program",
}
_READ_METHODS = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: with GRAPH_GREMLIN_READ_ONLY=true as the default, 45 of the 80 bundled text2gremlin.csv few-shot queries classify uncertain because project(), fold(), match(), hasNext(), predicates such as lt() and containing(), and __ traversals are not allowed, so Text2Gremlin execution of these read queries fails and GraphRAG drops to the subgraph fallback. Allow the read steps, predicates and anonymous traversals those examples use, and add a test that every query in text2gremlin.csv classifies safe.


# ========== Classifier constants ==========

_DYNAMIC_MARKERS = ("${", "#{", "->")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: Groovy interpolates $name and $a.b in double-quoted strings without braces, but only ${ is checked, so g.V().hasLabel("$System.env.HOME") classifies safe and the server evaluates that property chain. Treat any $ inside a double-quoted or triple-double-quoted string as uncertain, and add a test for that form.



def run_gremlin_query(query, fmt=True, connection=None):
if huge_settings.graph_gremlin_read_only:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: no test exercises the guard calls in run_gremlin_query or GraphQueryNode._gremlin_generate_query; the new tests cover only the helper and the config flag. Add tests that a rejected query raises before the client runs and that GraphQueryNode skips execution and falls back to the subgraph query.

@imbajin imbajin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Score: 5.0/10 · Confidence: medium

Blocking: yes

Summary

The fallback may execute unescaped vertex IDs outside the guard. Existing findings also identify rejected read queries and allowed Groovy interpolation.

Evidence

The rejection clears graph_result, so operator_schedule calls _subgraph_query, which interpolates matched_vid into Gremlin and executes it. Local classifier probes confirm the existing findings.

Validation notes

No live HugeGraph server, vertex ID acceptance, or deployed sandbox was tested.

rejection_reason = gremlin_readonly_rejection_reason(gremlin)
if rejection_reason is not None:
log.error("Refusing to execute non-read-only generated Gremlin: %s", rejection_reason)
context["graph_result"] = []

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Secure the fallback before executing it

Clearing graph_result makes operator_schedule call _subgraph_query, which puts each matched_vid inside a single-quoted Gremlin string and executes it without the guard. If a matched stored ID contains a quote and Groovy statements, it can escape that literal and potentially execute a mutation with the configured credentials even when read-only mode is enabled. Please bind or safely encode fallback inputs and test a rejected query followed by a quoted ID. This depends on accepted vertex IDs and server sandbox behavior, which I could not verify against a live server.

@yuangu-chengzi
yuangu-chengzi force-pushed the feat/llm-gremlin-readonly-guard branch from b96e554 to df928bf Compare December 5, 2026 05:06
@yuangu-chengzi

Copy link
Copy Markdown
Author

Thanks — pushed a follow-up addressing the new findings:

  • Bundled read queries: extended the classifier with the read-only steps these examples use (project, fold, match, constant, hasNext, identity), comparison/string predicates (lt, lte, gt, gte, eq, neq, containing, within, without, between, inside, outside, startingWith/endingWith, text predicates, regex), asc/desc order tokens, and anonymous __ traversal roots. Added a test that loads every query in hugegraph-llm/src/hugegraph_llm/resources/demo/text2gremlin.csv and asserts all 80 classify safe. I also fixed a missing . before where(...) in one bundled example, which was invalid Gremlin.
  • Groovy interpolation: any $ in a double-quoted or triple-double-quoted string is now uncertain, covering bare $name and $a.b as well as ${...}. Added positive/negative tests, including g.V().hasLabel("$System.env.HOME").
  • Fallback injection: vertex IDs and property keywords are encoded with a new _gremlin_literal helper (escapes backslash, single quote, CR/LF; rejects non-scalar types) before they enter VERTEX_QUERY_TPL, VID_QUERY_NEIGHBOR_TPL, or PROPERTY_QUERY_NEIGHBOR_TPL. Added a test that a rejected generated query falls back with a quoted ID and asserts the executed query contains the escaped literal.
  • Guard call coverage: added run_gremlin_query rejection-before-client-creation coverage and GraphQueryNode tests for skipping execution after a rejected generated query.

Local: pytest src/tests/utils/test_gremlin_policy.py src/tests/utils/test_gremlin_guard.py -q — 30 passed; ruff format --check/ruff check pass on src/. The new GraphQueryNode tests run in CI because pycgraph is Linux-only.

On the previous red llm job: opentelemetry-api==1.46.0 was published at 17:20:17Z and uv sync picked it up six seconds later. That release made opentelemetry._logs.get_logger() keyword-only, while FastAPI 0.165.1 calls it positionally. 1.46.1 was published later the same day with the positional signature restored, so the new run picks up a compatible version. The llm failures in that run were all this dependency break, not this PR's tests.

@yuangu-chengzi

Copy link
Copy Markdown
Author

Pushed the follow-up for the latest review (head 965991b). The new HugeGraph AI CI run is again action_required; could a maintainer approve it when convenient? Thanks!

@yuangu-chengzi
yuangu-chengzi force-pushed the feat/llm-gremlin-readonly-guard branch from 965991b to df928bf Compare December 5, 2026 05:08
…back

- Allow read-only project/fold/match/constant/hasNext/identity and the
  predicates used by bundled examples; permit anonymous traversal roots.
- Reject bare $ interpolation in double-quoted GStrings, not only ${...}.
- Escape vertex IDs and keywords before building fallback Gremlin queries.
- Add tests for every bundled text2gremlin.csv query, interpolation,
  run_gremlin_query rejection, and fallback escaping; fix a missing dot in
  one bundled example.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Re-pushed with one more hardening change (property names are now encoded through the same Gremlin literal helper as vertex IDs), head fdf2861. The new HugeGraph AI CI run needs workflow approval again — thanks!

…back

- Allow read-only project/fold/match/constant/hasNext/identity and the
  predicates used by bundled examples; permit anonymous traversal roots.
- Reject bare $ interpolation in double-quoted GStrings, not only ${...}.
- Escape vertex IDs and keywords before building fallback Gremlin queries.
- Add tests for every bundled text2gremlin.csv query, interpolation,
  run_gremlin_query rejection, and fallback escaping; fix a missing dot in
  one bundled example.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Fixed the two llm failures from the last run: they were in the new test_graph_query_node_guard.py harness, not in the guard itself. The SimpleNamespace node did not bind _format_graph_from_vertex / _format_graph_query_result, so the fallback path raised before the assertions. Both helpers are now bound to the real GraphQueryNode methods; head b05c93b.

Local checks still pass (pytest src/tests/utils/test_gremlin_policy.py src/tests/utils/test_gremlin_guard.py -q — 30 passed; ruff format --check / ruff check on src/). The GraphQueryNode tests run in CI (Linux pycgraph).

Could a maintainer approve the new HugeGraph AI CI run when convenient? Thanks!

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: The earlier findings are fixed at this head, but a \uXXXX escape in a string or comment hides drop() from the classifier while Groovy still runs it, so model-generated writes pass the read-only guard.


while index < length:
char = query[index]
if char == "\\":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical: Groovy translates \uXXXX escapes before lexing, so g.V().has('name','x\u0027).drop()//') and g.V() /* \u002a/.drop()// */ classify safe while Groovy 4.0.25 runs drop(). Classify any \u escape as uncertain and add tests for both forms.

…back

- Allow the read-only steps, predicates, and anonymous traversals used by all
  80 bundled text2gremlin.csv examples; add a test that every example is safe.
- Reject bare $ interpolation in double-quoted GStrings and any Groovy
  unicode escape (\uXXXX), which is expanded before lexing and can hide a
  mutation in a string or comment.
- Escape vertex IDs, keywords, and property names before building fallback
  Gremlin queries.
- Add tests for the unicode-escape bypasses, run_gremlin_query rejection,
  GraphQueryNode fallback, and the full examples file; fix a missing dot in
  one bundled example.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Fixed the \uXXXX bypass in head 1e9d54e:

  • The classifier now rejects any Groovy unicode escape (\u+[0-9a-fA-F]{4}) before lexing, because Groovy expands these before tokenization and they can close a string/comment to expose a mutation.
  • Added tests for both reported forms ('x\u0027).drop()//') and /* \u002a/.drop()// */) plus a plain read containing \u0041; all classify uncertain.
  • pytest src/tests/utils/test_gremlin_policy.py src/tests/utils/test_gremlin_guard.py -q — 33 passed; ruff passes.

The new HugeGraph AI CI run is action_required; could a maintainer approve it? Thanks!

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: The earlier findings are fixed at this head, but the default-on guard still classifies common read-only steps such as sum(), max(), is() and union() as uncertain, so Text2Gremlin refuses ordinary aggregation queries.

"toset",
"explain",
"profile",
# Read-only projection, aggregation, and pattern-match steps. The bundled

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: read-only steps outside the bundled examples, such as sum(), max(), min(), mean(), is(), union(), local() and next(), still classify uncertain, so with the default GRAPH_GREMLIN_READ_ONLY=true Text2Gremlin refuses a query like g.V().hasLabel('person').values('age').max(). Add these read steps to _READ_METHODS and test that each classifies safe.

@imbajin imbajin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Score: 6.0/10 · Confidence: high

Blocking: yes

Summary

The fallback still interpolates schema edge labels without escaping; common valid read steps are also rejected by default.

Evidence

Traced guard rejection to fallback execution, schema label interpolation and the policy allowlist.

Validation notes

Source review only; mutation requires a crafted schema and permissive server sandbox; no live HugeGraph test.

for matched_vid in matched_vids:
gremlin_query = VID_QUERY_NEIGHBOR_TPL.format(
keywords=f"'{matched_vid}'",
keywords=_gremlin_literal(matched_vid),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Encode edge labels in the fallback too

This fallback escapes the vertex ID, but edge_labels_str still wraps schema-derived labels in quotes without escaping and is inserted into the unguarded Gremlin below. A label containing a quote can break the query; a crafted label may inject a mutation when the guard rejects a generated traversal. Please encode each label with _gremlin_literal as well and test a quoted label. This depends on schema creation permissions and the server sandbox; I did not run a live mutation.

…back

- Allow the read-only steps, predicates, anonymous traversals, aggregations
  (sum/max/min/mean), is/union/local/next, and all 80 bundled text2gremlin.csv
  examples.
- Reject bare $ interpolation in double-quoted GStrings and any Groovy
  unicode escape (\uXXXX), which is expanded before lexing.
- Escape vertex IDs, keywords, property names, and schema edge labels before
  building fallback Gremlin queries.
- Add tests for unicode-escape bypasses, aggregation steps, run_gremlin_query
  rejection, GraphQueryNode fallback, and edge-label escaping.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Addressed the latest review in head f567d14:

  • Added read-only sum, max, min, mean, is, union, local, and next to _READ_METHODS; added a parametrized test that each classifies safe (including values('age').max()).
  • Fallback edge labels from the schema now go through _gremlin_literal, so a label containing a quote is escaped. Added a k'nows label test.

Local policy/guard tests: 41 passed; ruff passes. The new HugeGraph AI CI run is action_required; could a maintainer approve it?

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: The guard also covers the Graph Tools Gremlin console, so operators lose write access there unless they turn off read-only protection for GraphRAG and Text2Gremlin too. The earlier interpolation, \uXXXX, read-step, guard-test and fallback-escaping comments are addressed at this head.

if huge_settings.graph_gremlin_read_only:
rejection_reason = gremlin_readonly_rejection_reason(query)
if rejection_reason is not None:
raise ValueError(f"Refusing to execute non-read-only Gremlin: {rejection_reason}")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: run_gremlin_query also backs the Graph Tools console in create_other_block, so with the default GRAPH_GREMLIN_READ_ONLY=true operator-written queries such as g.addV('person') now raise, and allowing them again turns the guard off for GraphRAG and Text2Gremlin as well. Let the console call skip the check, for example through a read_only argument that create_other_block sets to False.

The classifier is conservative: ``safe`` means a known read-only traversal,
``unsafe`` means a write/mutation step was detected, and ``uncertain`` means the
query cannot be confirmed as read-only. Callers should execute only ``safe``
queries. This mirrors the MCP classifier so both execution surfaces apply the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: the docstring says both execution surfaces apply the same rules, but hugegraph-mcp/hugegraph_mcp/gremlin_policy.py lacks the \uXXXX and bare $ checks and still classifies g.V().has('name','x\u0027).drop()//') as safe. Drop the parity claim.

return classify_gremlin_read_safety(gremlin_query) == "safe"


def _extract_method_names(query_without_strings: str) -> list[str]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: _extract_method_names, _has_unsafe_write_steps, _has_dynamic_construction_markers, _has_bare_identifier_arguments, _strip_string_literals, is_safe_gremlin_read and the GremlinSafety alias have no callers in hugegraph-llm. Remove them so check_gremlin_read stays the one entry point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants