Skip to content
Merged
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 @@ -48,7 +48,7 @@
* new leader and accept writes. This eliminates the possibility of divergent data.
*/
@Testcontainers
class SplitBrainIT extends ContainersTestTemplate {
class SplitBrainIT extends ContainersTestTemplate {

private static final String SERVER_LIST = "arcadedb-0:2434:2480,arcadedb-1:2434:2480,arcadedb-2:2434:2480";

Expand Down Expand Up @@ -119,13 +119,17 @@ void splitBrainPrevention() throws Exception {
logger.info("Waiting for Raft leader step-down in minority and new election in majority");
final List<ServerWrapper> majorityServers = List.of(servers.get(survivor1), servers.get(survivor2));
waitForRaftLeader(majorityServers, 60);
// Wait until both majority nodes know the leader address so follower-to-leader proxying
// works immediately; without this, addUserAndPhotos can silently fail when the follower
// hasn't yet propagated the new leader's address.
waitForAllNodesKnowLeader(majorityServers, 30);

logger.info("Writing to majority partition (nodes {} and {}) - should succeed with new leader", survivor1, survivor2);
dbs[survivor1].addUserAndPhotos(10, 10);

logger.info("Verifying writes on majority partition");
Awaitility.await()
.atMost(30, TimeUnit.SECONDS)
.atMost(2, TimeUnit.MINUTES)
.pollInterval(2, TimeUnit.SECONDS)
.until(() -> {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import com.arcadedb.GlobalConfiguration;
import com.arcadedb.gremlin.io.ArcadeIoRegistry;
import com.arcadedb.server.ArcadeDBServer;
import com.arcadedb.test.BaseGraphServerTest;
import com.arcadedb.utility.FileUtils;
import org.apache.tinkerpop.gremlin.driver.Cluster;
Expand Down Expand Up @@ -47,24 +48,26 @@ class GremlinDefaultGraphCreationIT extends BaseGraphServerTest {
@Override
public void setTestConfiguration() {
super.setTestConfiguration();
GlobalConfiguration.SERVER_PLUGINS.setValue("GremlinServer:com.arcadedb.server.gremlin.GremlinServerPlugin");
GlobalConfiguration.TYPE_DEFAULT_BUCKETS.setValue(Runtime.getRuntime().availableProcessors());
}

/**
* Write Gremlin config files here, AFTER deleteDatabaseFolders() has run (which clears ./target/config/)
* but BEFORE server.start() — so the plugin finds the yaml and properties on disk.
*/
@Override
protected void onBeforeStarting(final ArcadeDBServer server) {
new File("./target/config").mkdirs();

try {
FileUtils.writeFile(new File("./target/config/gremlin-server.yaml"),
FileUtils.readStreamAsString(getClass().getClassLoader().getResourceAsStream("gremlin-server.yaml"), "utf8"));

FileUtils.writeFile(new File("./target/config/gremlin-server.properties"),
FileUtils.readStreamAsString(getClass().getClassLoader().getResourceAsStream("gremlin-server.properties"), "utf8"));

FileUtils.writeFile(new File("./target/config/gremlin-server.groovy"),
FileUtils.readStreamAsString(getClass().getClassLoader().getResourceAsStream("gremlin-server.groovy"), "utf8"));

GlobalConfiguration.SERVER_PLUGINS.setValue("GremlinServer:com.arcadedb.server.gremlin.GremlinServerPlugin");
GlobalConfiguration.TYPE_DEFAULT_BUCKETS.setValue(Runtime.getRuntime().availableProcessors());

} catch (final IOException e) {
fail("Failed to configure test settings", e);
fail("Failed to write Gremlin config files", e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1337,8 +1337,16 @@ private ResultSet forwardCommandToLeaderViaRaft(final String language, final Str
body.put("command", query);
if (mapArgs != null && !mapArgs.isEmpty())
body.put("params", new JSONObject(mapArgs));
else if (positionalArgs != null && positionalArgs.length > 0)
body.put("params", new com.arcadedb.serializer.json.JSONArray(Arrays.asList(positionalArgs)));
else if (positionalArgs != null && positionalArgs.length > 0) {
// Use ordinal-map format {"0": v0, "1": v1, ...} so the leader's PostCommandHandler
// can safely parse params as a Map regardless of the toMap(true) numeric-array optimization.
// Sending a plain JSON array like [110] causes toMap(true) to return float[]{110.0},
// which then cannot be cast to Map at the params-extraction site.
final JSONObject ordinalParams = new JSONObject();
for (int i = 0; i < positionalArgs.length; i++)
ordinalParams.put("" + i, positionalArgs[i]);
body.put("params", ordinalParams);
}

final HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create("http://" + leaderHttpAddress + "/api/v1/command/" + getName()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,63 @@ void dmlViaFollowerIsProxiedToLeader() throws Exception {
}
}

/**
* Regression test for the bug where positional params serialized as a JSON array [110]
* were converted to float[]{110.0} by toMap(true) on the leader, causing
* ClassCastException: [F cannot be cast to Map when PostCommandHandler tried to cast it.
*/
@Test
void positionalParamsViaFollowerIsProxiedToLeader() throws Exception {
final int leaderIndex = findLeaderIndex();
assertThat(leaderIndex).as("A Raft leader must be elected before the test").isGreaterThanOrEqualTo(0);

final int followerIndex = firstFollowerIndex(leaderIndex);
final int followerPort = 2480 + followerIndex;
final String dbName = getDatabaseName();

final JSONObject body = new JSONObject()
.put("language", "sql")
.put("command", "INSERT INTO V1 SET id = ?, name = ?")
.put("params", new com.arcadedb.serializer.json.JSONArray().put(42).put("positional-test"));

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.

medium

The current regression test uses a mixed-type array [42, "positional-test"]. While this correctly tests the List handling in PostCommandHandler, it does not trigger the float[] optimization in json.toMap(true) which was the specific cause of the ClassCastException mentioned in the PR description (where an all-numeric array like [110] is converted to a primitive array).

Consider adding a second test case or updating this one to use an all-numeric array to ensure the float[] code path in PostCommandHandler is also covered by the regression suite.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added in df6b830. The test now sends a second request with params: [42] (all-numeric) via the follower, which exercises the float[] branch in PostCommandHandler. The assertion verifies the response is 200 rather than a 500 ClassCastException.


final HttpResponse<String> response = postCommandWithBody(followerPort, dbName, body.toString());
assertThat(response.statusCode())
.as("INSERT with positional params proxied via follower should return 200, body: " + response.body())
.isEqualTo(200);

for (int i = 0; i < getServerCount(); i++)
waitForReplicationIsCompleted(i);

for (int i = 0; i < getServerCount(); i++) {
final Database db = getServerDatabase(i, dbName);
final long[] found = { 0 };
db.transaction(() -> {
try (final com.arcadedb.query.sql.executor.ResultSet rs = db.query("sql",
"SELECT FROM V1 WHERE name = 'positional-test'")) {
while (rs.hasNext()) {
rs.next();
found[0]++;
}
}
});
assertThat(found[0])
.as("Server %d should have the positional-param-inserted record after replication", i)
.isEqualTo(1L);
}

// Also test the float[] code path: an all-numeric JSON array [42] is converted to float[]
// by toMap(true) on the leader. This previously caused ClassCastException before the fix.
final JSONObject numericBody = new JSONObject()
.put("language", "sql")
.put("command", "SELECT FROM V1 WHERE id = ?")
.put("params", new com.arcadedb.serializer.json.JSONArray().put(42));

final HttpResponse<String> numericResponse = postCommandWithBody(followerPort, dbName, numericBody.toString());
assertThat(numericResponse.statusCode())
.as("SELECT with all-numeric positional params (float[] path) should not throw ClassCastException, body: " + numericResponse.body())
.isEqualTo(200);
}

// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
Expand All @@ -153,19 +210,20 @@ private int firstFollowerIndex(final int leaderIndex) {
* at {@code port}, using Basic authentication.
*/
private HttpResponse<String> postCommand(final int port, final String dbName, final String sql) throws Exception {
return postCommandWithBody(port, dbName, new JSONObject().put("language", "sql").put("command", sql).toString());
}

private HttpResponse<String> postCommandWithBody(final int port, final String dbName, final String jsonBody)
throws Exception {
final String authHeader = "Basic " + Base64.getEncoder()
.encodeToString(("root:" + BaseGraphServerTest.DEFAULT_PASSWORD_FOR_TESTS).getBytes(StandardCharsets.UTF_8));
final String body = new JSONObject()
.put("language", "sql")
.put("command", sql)
.toString();

final HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://127.0.0.1:" + port + "/api/v1/command/" + dbName))
.timeout(Duration.ofSeconds(30))
.header("Authorization", authHeader)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
.POST(HttpRequest.BodyPublishers.ofString(jsonBody, StandardCharsets.UTF_8))
.build();

return HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,61 @@ protected int waitForRaftLeader(final List<ServerWrapper> servers, final int tim
return -1;
}

/**
* Waits until every node in the list reports a non-null {@code leaderHttpAddress} via
* {@code GET /api/v1/cluster}. Call this after {@link #waitForRaftLeader} when you need
* all followers to know the leader before issuing write commands, so that follower-to-leader
* proxying works immediately without silent failures caused by a null leader address.
*
* @param servers the server wrappers to check
* @param timeoutSeconds maximum time to wait
*/
protected void waitForAllNodesKnowLeader(final List<ServerWrapper> servers, final int timeoutSeconds) {
final long deadline = System.currentTimeMillis() + (timeoutSeconds * 1000L);
while (System.currentTimeMillis() < deadline) {
boolean allKnow = true;
for (final ServerWrapper server : servers) {
try {
final HttpURLConnection conn = (HttpURLConnection) URI.create(
"http://" + server.host() + ":" + server.httpPort() + "/api/v1/cluster").toURL().openConnection();
conn.setRequestProperty("Authorization",
"Basic " + Base64.getEncoder().encodeToString(("root:" + PASSWORD).getBytes()));
conn.setConnectTimeout(2000);
conn.setReadTimeout(2000);
try {
if (conn.getResponseCode() == 200) {
final String body = new String(conn.getInputStream().readAllBytes());
final JSONObject json = new JSONObject(body);
if (json.isNull("leaderHttpAddress")) {
allKnow = false;
break;
}
} else {
allKnow = false;
break;
}
} finally {
conn.disconnect();
}
} catch (final Exception e) {
allKnow = false;
break;
}
}
if (allKnow) {
logger.info("All {} nodes know the Raft leader", servers.size());
return;
}
try {
Thread.sleep(500);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
logger.warn("Not all nodes know the Raft leader after {}s — proceeding anyway", timeoutSeconds);
}

/**
* Creates a standalone ArcadeDB container without HA.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package com.arcadedb.test.support;

import com.arcadedb.network.binary.ServerIsNotTheLeaderException;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.remote.RemoteHttpComponent;
Expand Down Expand Up @@ -105,19 +106,45 @@ public void close() {
}

public void createDatabase() {
RemoteServer httpServer = new RemoteServer(
final RemoteServer httpServer = new RemoteServer(
server.host(),
server.httpPort(),
"root",
PASSWORD);
// FIXED strategy prevents the client from following cluster-reported internal Docker
// addresses (arcadedb-N:2480) after a failure; those are unreachable from the test host.
httpServer.setConnectionStrategy(RemoteHttpComponent.CONNECTION_STRATEGY.FIXED);

if (httpServer.exists(DATABASE)) {
logger.info("Dropping existing database {}", DATABASE);
httpServer.drop(DATABASE);
}
logger.info("Creating database {}", DATABASE);
httpServer.create(DATABASE);

// Retry when:
// (a) leader address not yet propagated after election (ServerIsNotTheLeaderException, null leader)
// (b) server temporarily unavailable during rolling restart (RemoteException / ConnectException)
final int maxAttempts = 30;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
httpServer.create(DATABASE);
return;
} catch (final ServerIsNotTheLeaderException e) {
if (e.getLeaderAddress() != null || attempt == maxAttempts)
throw e;
logger.info("Leader address not yet known (attempt {}/{}), retrying in 2s...", attempt, maxAttempts);
} catch (final Exception e) {
if (attempt == maxAttempts)
throw e;
logger.info("Database creation attempt {}/{} failed ({}), retrying in 2s...", attempt, maxAttempts, e.getMessage());
}
try {
Thread.sleep(2_000);
} catch (final InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,26 @@ public ExecutionResponse execute(final HttpServerExchange exchange, final Server

command = command.trim();

Map<String, Object> paramMap = (Map<String, Object>) requestMap.get("params");
if (paramMap == null)
final Object rawParams = requestMap.get("params");
Map<String, Object> paramMap;
if (rawParams instanceof Map<?, ?> m) {
@SuppressWarnings("unchecked")
final Map<String, Object> typed = (Map<String, Object>) m;
paramMap = typed;
} else if (rawParams instanceof List<?> list) {
// Positional params forwarded as a JSON array [v0, v1, ...] — convert to ordinal map
paramMap = new HashMap<>((int) (list.size() / 0.75f) + 1);
for (int i = 0; i < list.size(); i++)
paramMap.put("" + i, list.get(i));
} else if (rawParams != null && rawParams.getClass().isArray()) {
// Positional params converted to a primitive array by toMap(true) — convert to ordinal map
final int len = java.lang.reflect.Array.getLength(rawParams);
paramMap = new HashMap<>((int) (len / 0.75f) + 1);
for (int i = 0; i < len; i++)
paramMap.put("" + i, java.lang.reflect.Array.get(rawParams, i));
} else {
paramMap = new HashMap<>();
}

if (limit != -1) {
if (language.equalsIgnoreCase("sql") || language.equalsIgnoreCase("sqlScript")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ void createDropDatabaseCaseSensitivity() throws Exception {
*/
@Test
void userCommandsCaseSensitivity() throws Exception {
// Drop users first to ensure idempotency (stale state from prior test runs)
executeServerCommand("DROP USER testuser");
executeServerCommand("DROP USER testuser2");
executeServerCommand("DROP USER testuser3");

// CREATE USER expects JSON payload format
HttpResponse<String> response = executeServerCommand("""
CREATE USER {"name":"testuser","password":"testpass"}
Expand Down
Loading