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 @@ -92,7 +92,8 @@ public CypherModel submitQuery(String cypherQuery, @Nullable Map<String, String>
} catch (Exception e) {
LOG.error(String.format("Failed to submit cypher-query: [ %s ], caused by:",
cypherQuery), e);
res = CypherModel.failOf(request.getRequestId().toString(), e.getMessage());
res = CypherModel.failOf(request.getRequestId().toString(),
e.getMessage(), CypherErrorMapper.map(e));
} finally {
try {
if (client != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* 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.
*/

package org.apache.hugegraph.api.cypher;

/**
* Classify cypher execution failures into stable error codes and attach
* actionable hints for the most common, cryptic translator messages.
*/
public final class CypherErrorMapper {

public static final String SYNTAX_ERROR = "HugeGraph.Cypher.SyntaxError";
public static final String UNSUPPORTED_FEATURE =
"HugeGraph.Cypher.UnsupportedFeature";
public static final String EXECUTION_ERROR = "HugeGraph.Cypher.ExecutionError";

private CypherErrorMapper() {
}

public static CypherModel.CypherError map(Throwable e) {
String raw = e.getMessage() != null ? e.getMessage() : e.toString();
// translator/parser exception types indicate a real parse failure even
// when the message is generic; check class name and FULL message
// before the class-prefix strip below removes the evidence
String className = e.getClass().getName();
String lowerFull = raw.toLowerCase();
if (className.contains("SyntaxException")
|| className.contains("ParseException")
|| lowerFull.contains("syntaxexception")
|| lowerFull.contains("parseexception")
|| lowerFull.contains("no viable alternative")
// openCypher front-end: "Invalid input 'R': expected ..."
|| lowerFull.contains("invalid input '")
|| lowerFull.contains("mismatched input")
|| lowerFull.contains("extraneous input")
|| lowerFull.contains("token recognition error")) {
return new CypherModel.CypherError(SYNTAX_ERROR,
raw.replaceFirst(
"^([a-zA-Z0-9_]+\\.)+[A-Za-z0-9_]+(Exception|Error):\\s*", ""),
"Check the Cypher statement near the position reported " +
"in the message");
}
String message = raw.replaceFirst(
"^([a-zA-Z0-9_]+\\.)+[A-Za-z0-9_]+(Exception|Error):\\s*", "");
String lower = message.toLowerCase();
if (lower.contains("undefined vertex label")
|| lower.contains("undefined edge label")
|| lower.contains("undefined property key")) {
return new CypherModel.CypherError(EXECUTION_ERROR, message,
"Create the schema element via the schema API before " +
"running the query");
}
if (lower.contains("not defined") || lower.contains("undefined")) {

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: SyntaxError is assigned only when the message contains "not defined" or "undefined", so real parse errors fall through to ExecutionError with an empty hint on line 65. The PR's goal is to let clients branch on the failure mode, and these codes are described as stable, so a client that checks for HugeGraph.Cypher.SyntaxError will miss most syntax errors.

Evidence: I ran CypherAst.parse(q, {}) from translation 1.0.4 with gremlin+cfog_server_extensions+inline_parameters:

  • MATCH (n:person RETURN n gives SyntaxException: Invalid input 'R': expected ..., mapped to ExecutionError.
  • MATCH (n:person) RETRUN n gives Invalid input 'R': expected 'u/U', mapped to ExecutionError.
  • MATCH (n) RETURN n; MATCH (m) RETURN m gives Expected exactly one statement per query but got: 2, mapped to ExecutionError.
  • RETURN date() gives SyntaxException: Unknown function 'date', mapped to ExecutionError.
  • MATCH (n:person) RETURN not_defined_var gives "Variable not_defined_var not defined", the only one mapped to SyntaxError.

The PR description's own live check shows the same result: a syntax error returned HugeGraph.Cypher.ExecutionError with "hint":"". The branch also catches any other HugeGraph message with "undefined", such as Undefined index label: 'x', and tells the user to declare a variable.

Requested change: match the parser messages explicitly (invalid input, expected exactly one statement, unknown function, variable ... not defined) for SyntaxError, narrow the variable hint to the Variable ... not defined message, and add a test that sends a real parse error such as MATCH (n:person RETURN n and asserts "code":"HugeGraph.Cypher.SyntaxError".

return new CypherModel.CypherError(SYNTAX_ERROR, message,
"Declare the variable in a MATCH, UNWIND or WITH clause " +
"before referencing it");
}
if (lower.contains("not supported") || lower.contains("unsupported")) {

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: This branch matches not supported or unsupported anywhere in the message, so HugeGraph's own query limits come back as UnsupportedFeature with a hint that blames the translator.

Evidence: at this head, TraversalUtil.newUnsupportedPredicate() throws BackendException("Unsupported predicate: '%s'"), and LocalContainsStep raises CONTAINS query with relation '%s' is not supported. Both run in the HugeGraph traversal optimizer while a translated Cypher traversal executes, after the translator has accepted the query, so pointing the user at the Cypher compatibility guide sends them to the wrong place.

Requested change: limit UNSUPPORTED_FEATURE to failures raised by the translator (check the exception class or the specific translator messages), and let HugeGraph backend and optimizer messages fall through to EXECUTION_ERROR. A test that sends a query using an unsupported predicate would cover it.

return new CypherModel.CypherError(UNSUPPORTED_FEATURE, message,
"This construct is not covered by the built-in translator, " +
"see the Cypher compatibility guide for supported syntax");
}
return new CypherModel.CypherError(EXECUTION_ERROR, message, "");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude;

import io.swagger.v3.oas.annotations.media.Schema;

/**
Expand All @@ -37,6 +39,11 @@ public class CypherModel {
@Schema(description = "The query result")
public Result result = new Result();

@Schema(description = "Structured errors, present only on failure so that "
+ "older clients keep parsing successful responses")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public List<CypherError> errors = Collections.emptyList();

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: This field breaks every existing Java client call to /cypher, successful queries included. errors defaults to Collections.emptyList() and Jersey's JacksonFeature serializes it, so every response now ends with "errors":[]. hugegraph-toolchain's CypherAPI.post parses the body with RestResult.readObject(org.apache.hugegraph.structure.gremlin.Response.class). That class declares only requestId, status and result and has no ignoreUnknown, and RestResult uses a plain ObjectMapper, where FAIL_ON_UNKNOWN_PROPERTIES is on by default.

Evidence: with hugegraph-client-1.8.0.jar and hugegraph-common-1.7.0.jar, new RestResult(200, body, null).readObject(Response.class) parses the current response shape. With ,"errors":[] appended it throws SerializeException caused by UnrecognizedPropertyException: Unrecognized field "errors" (class org.apache.hugegraph.structure.gremlin.Response), not marked as ignorable. CypherManager.execute() and Hubble's QueryService.executeCypher() both go through that path. CI does not catch this because CypherApiTest checks the body as a string.

Requested change: keep the top-level shape unchanged. The existing status.attributes map (Map<String, Object>, already accepted by the client as Map<String, ?>) can carry the code and hint on failures, for example attributes = {"code": ..., "hint": ...}. If a top-level errors field is still wanted, land @JsonIgnoreProperties(ignoreUnknown = true) on the client's Response in hugegraph-toolchain and release it first, and do not emit the field on success in the meantime.


public static CypherModel dataOf(String requestId, List<Object> data) {
CypherModel res = new CypherModel();
res.requestId = requestId;
Expand All @@ -45,11 +52,15 @@ public static CypherModel dataOf(String requestId, List<Object> data) {
return res;
}

public static CypherModel failOf(String requestId, String message) {
public static CypherModel failOf(String requestId, String message,
CypherError error) {
CypherModel res = new CypherModel();
res.requestId = requestId;
res.status.code = 400;
res.status.message = message;
if (error != null) {
res.errors = Collections.singletonList(error);

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: Failed queries still break the Java client and Hubble, because failOf always adds a top-level errors array. The NON_EMPTY change fixed only the success path.

hugegraph-client's CypherAPI.post parses every /cypher body with RestResult.readObject(Response.class). Response declares only requestId, status and result, has no @JsonIgnoreProperties, and RestResult uses a default ObjectMapper, so the unknown field throws before any caller sees status. On toolchain master, CypherManager.execute() never reaches its status.code() != 200 branch, which is what turns the server's status.message into a ServerException. Hubble's QueryService.executeCypher() then gets a SerializeException (Failed to deserialize: ...) through its ClientException branch, where it used to get the Cypher error through the ServerException branch.

Evidence: with hugegraph-client-1.8.0.jar, hugegraph-common-1.7.0.jar and Jackson 2.15.2, a default ObjectMapper reads today's failure body ({"requestId":"r1","status":{"message":"Variable x not defined","code":400,"attributes":{}},"result":{"data":[],"meta":{}}}) into Response with status.code=400. The same body with this PR's errors entry appended throws UnrecognizedPropertyException: Unrecognized field "errors" (class org.apache.hugegraph.structure.gremlin.Response), not marked as ignorable. testSuccessResponseKeepsLegacyShape covers only the success body, and the three failure tests read the body as a string, so nothing in the build catches this.

Requested change: to answer your open question, please move the code and hint into status.attributes (for example {"code": ..., "hint": ...}) and drop the top-level errors field. CypherModel.Status.attributes already exists and the client maps it as Map<String, ?>, so no client release is needed. Then add a failure-path test that parses a failed response with FAIL_ON_UNKNOWN_PROPERTIES enabled, the way the success test does.

}
return res;
}

Expand Down Expand Up @@ -77,4 +88,22 @@ private static class Result {
public Map<String, Object> meta = Collections.EMPTY_MAP;
}

public static class CypherError {

@Schema(description = "Stable error classification code")
public String code;

@Schema(description = "The error message")
public String message;

@Schema(description = "Actionable hint, empty when unavailable")
public String hint = "";

public CypherError(String code, String message, String hint) {
this.code = code;
this.message = message;
this.hint = hint;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
import org.junit.Before;
import org.junit.Test;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

Expand Down Expand Up @@ -135,6 +137,49 @@ public void testRelationQuery() {
assertColumn(query(cypher), "friend", "peter");
}

@Test
public void testSyntaxErrorHasStructuredErrorWithHint() {
Response r = client().post(PATH,
"MATCH (n:person) RETURN not_defined_var");
String content = assertResponseStatus(200, r);
assertContains("\"errors\"", content);
assertContains("SyntaxError", content);
assertContains("Declare the variable", content);
Comment on lines +145 to +147
}

@Test
public void testParseErrorIsClassifiedAsSyntaxError() {
Response r = client().post(PATH, "MATCH (n:person RETURN n");
String content = assertResponseStatus(200, r);
assertContains("\"code\":\"HugeGraph.Cypher.SyntaxError\"", content);
assertContains("Check the Cypher statement", content);
}

@Test
public void testUndefinedLabelHasSchemaHint() {
Response r = client().post(PATH, "MATCH (n:robot) RETURN n");
String content = assertResponseStatus(200, r);
assertContains("ExecutionError", content);
assertContains("Create the schema element", content);
}

@Test
public void testSuccessResponseKeepsLegacyShape() throws Exception {
Response r = client().post(PATH, QUERY);
String content = assertResponseStatus(200, r);
// hugegraph-client RestResult.readObject fails on unknown fields
// (FAIL_ON_UNKNOWN_PROPERTIES defaults to true), so a successful
// response must not carry the new "errors" key
org.junit.Assert.assertFalse("success response must not contain errors",
content.contains("\"errors\""));
ObjectMapper strict = new ObjectMapper()
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
@SuppressWarnings("unchecked")
Map<String, Object> legacy = strict.readValue(content, Map.class);
org.junit.Assert.assertTrue(legacy.containsKey("requestId"));
org.junit.Assert.assertTrue(legacy.containsKey("result"));
}

@Test
public void testReturnNodeIdAsPrimitiveValue() {
String cypher = "MATCH (n:cypher_person) WHERE n.name = 'marko' " +
Expand Down