diff --git a/e2e-ha/src/test/java/com/arcadedb/containers/ha/SplitBrainIT.java b/e2e-ha/src/test/java/com/arcadedb/containers/ha/SplitBrainIT.java index 918b98a8071..bd02ed91dc3 100644 --- a/e2e-ha/src/test/java/com/arcadedb/containers/ha/SplitBrainIT.java +++ b/e2e-ha/src/test/java/com/arcadedb/containers/ha/SplitBrainIT.java @@ -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"; @@ -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 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 { diff --git a/gremlin/src/test/java/com/arcadedb/server/gremlin/GremlinDefaultGraphCreationIT.java b/gremlin/src/test/java/com/arcadedb/server/gremlin/GremlinDefaultGraphCreationIT.java index a91fb164ded..0d11e433e56 100644 --- a/gremlin/src/test/java/com/arcadedb/server/gremlin/GremlinDefaultGraphCreationIT.java +++ b/gremlin/src/test/java/com/arcadedb/server/gremlin/GremlinDefaultGraphCreationIT.java @@ -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; @@ -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); } } diff --git a/ha-raft/src/main/java/com/arcadedb/server/ha/raft/RaftReplicatedDatabase.java b/ha-raft/src/main/java/com/arcadedb/server/ha/raft/RaftReplicatedDatabase.java index f73cc7cdeca..33006d5d8b3 100644 --- a/ha-raft/src/main/java/com/arcadedb/server/ha/raft/RaftReplicatedDatabase.java +++ b/ha-raft/src/main/java/com/arcadedb/server/ha/raft/RaftReplicatedDatabase.java @@ -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())) diff --git a/ha-raft/src/test/java/com/arcadedb/server/ha/raft/RaftLeaderProxyIT.java b/ha-raft/src/test/java/com/arcadedb/server/ha/raft/RaftLeaderProxyIT.java index b1a61451b8d..aebdfb6990d 100644 --- a/ha-raft/src/test/java/com/arcadedb/server/ha/raft/RaftLeaderProxyIT.java +++ b/ha-raft/src/test/java/com/arcadedb/server/ha/raft/RaftLeaderProxyIT.java @@ -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")); + + final HttpResponse 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 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 // ------------------------------------------------------------------------- @@ -153,19 +210,20 @@ private int firstFollowerIndex(final int leaderIndex) { * at {@code port}, using Basic authentication. */ private HttpResponse 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 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)); diff --git a/load-tests/src/test/java/com/arcadedb/test/support/ContainersTestTemplate.java b/load-tests/src/test/java/com/arcadedb/test/support/ContainersTestTemplate.java index 705723e78d1..a967e74e234 100644 --- a/load-tests/src/test/java/com/arcadedb/test/support/ContainersTestTemplate.java +++ b/load-tests/src/test/java/com/arcadedb/test/support/ContainersTestTemplate.java @@ -285,6 +285,61 @@ protected int waitForRaftLeader(final List 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 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. */ diff --git a/load-tests/src/test/java/com/arcadedb/test/support/DatabaseWrapper.java b/load-tests/src/test/java/com/arcadedb/test/support/DatabaseWrapper.java index e17ecdd69a5..c2baef2a7b7 100644 --- a/load-tests/src/test/java/com/arcadedb/test/support/DatabaseWrapper.java +++ b/load-tests/src/test/java/com/arcadedb/test/support/DatabaseWrapper.java @@ -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; @@ -105,11 +106,13 @@ 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)) { @@ -117,7 +120,31 @@ public void createDatabase() { 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; + } + } } /** diff --git a/server/src/main/java/com/arcadedb/server/http/handler/PostCommandHandler.java b/server/src/main/java/com/arcadedb/server/http/handler/PostCommandHandler.java index 4a2b071cbc2..54cdfd1bdff 100644 --- a/server/src/main/java/com/arcadedb/server/http/handler/PostCommandHandler.java +++ b/server/src/main/java/com/arcadedb/server/http/handler/PostCommandHandler.java @@ -88,9 +88,26 @@ public ExecutionResponse execute(final HttpServerExchange exchange, final Server command = command.trim(); - Map paramMap = (Map) requestMap.get("params"); - if (paramMap == null) + final Object rawParams = requestMap.get("params"); + Map paramMap; + if (rawParams instanceof Map m) { + @SuppressWarnings("unchecked") + final Map typed = (Map) 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")) { diff --git a/server/src/test/java/com/arcadedb/server/http/handler/PostServerCommandHandlerIT.java b/server/src/test/java/com/arcadedb/server/http/handler/PostServerCommandHandlerIT.java index da47118a13b..ec062923dd1 100644 --- a/server/src/test/java/com/arcadedb/server/http/handler/PostServerCommandHandlerIT.java +++ b/server/src/test/java/com/arcadedb/server/http/handler/PostServerCommandHandlerIT.java @@ -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 response = executeServerCommand(""" CREATE USER {"name":"testuser","password":"testpass"}