From e2ab2b5584ef2b1c8a310a4847033af2750d8143 Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 00:35:48 -0400 Subject: [PATCH 01/10] Fix split()/collection-method receivers, append() leading null, shutdown-hook bound with open databases, async update validation, async delete double listener dispatch, setParallelLevel back pressure and scan truncation Closes #7027, #7028, #7025, #7004, #7003, #7002. - split() now answers a List, like the split() function and Cypher split(), and every collection method (join, sort, transform, asList, asSet, asString) normalises List/Set/array/iterable receivers through one AbstractSQLMethod helper; first()/last() are available as methods bridging to the existing MultiValue helpers. Also: the AST builder dropped every modifier after a :param, so :list.join('-') silently answered the bare parameter. - append() skips a leading null like any other null instead of dropping every argument after it. - The shutdown hook bound follows the open databases, not the status: STARTING with databases open waits arcadedb.server.shutdownTimeout; a lock holder parked in System.exit() is not waited for at all. - The async update validates the document (MANDATORY/NOTNULL) and reports the violation to the error callback, as the synchronous paths do. - The async delete no longer dispatches the delete listeners itself; deleteRecordNoLock owns the dispatch and returns the veto outcome. - backPressurePercentage is read once in the executor, not per worker, so setParallelLevel() no longer reverts setBackPressure(); scans and browse iterators bail on a kill/interrupt, not on the drain-and-exit flag a retired worker carries. --- .../com/arcadedb/GlobalConfiguration.java | 14 +- .../arcadedb/database/DatabaseInternal.java | 9 +- .../com/arcadedb/database/LocalDatabase.java | 14 +- .../async/DatabaseAsyncBrowseIterator.java | 3 +- .../async/DatabaseAsyncDeleteRecord.java | 29 +-- .../async/DatabaseAsyncExecutorImpl.java | 20 +- .../async/DatabaseAsyncScanBucket.java | 5 +- .../async/DatabaseAsyncUpdateRecord.java | 14 ++ .../query/sql/antlr/SQLASTBuilder.java | 24 ++ .../query/sql/method/AbstractSQLMethod.java | 42 ++++ .../sql/method/DefaultSQLMethodFactory.java | 4 + .../sql/method/collection/SQLMethodFirst.java | 50 ++++ .../sql/method/collection/SQLMethodJoin.java | 8 +- .../sql/method/collection/SQLMethodLast.java | 50 ++++ .../sql/method/collection/SQLMethodSort.java | 7 +- .../method/collection/SQLMethodTransform.java | 24 +- .../method/conversion/SQLMethodAsList.java | 4 + .../sql/method/conversion/SQLMethodAsSet.java | 3 + .../method/conversion/SQLMethodAsString.java | 6 + .../sql/method/string/SQLMethodAppend.java | 13 +- .../sql/method/string/SQLMethodSplit.java | 6 +- .../Issue7002AsyncUpdateValidationTest.java | 106 ++++++++ ...7003AsyncDeleteListenerDoubleFireTest.java | 111 +++++++++ .../Issue7004AsyncParallelLevelTest.java | 135 ++++++++++ .../function/sql/sql/SQLFunctionsTest.java | 12 +- ...7CollectionMethodsOnArrayReceiverTest.java | 114 +++++++++ .../method/collection/SQLMethodFirstTest.java | 64 +++++ .../method/collection/SQLMethodJoinTest.java | 21 ++ .../method/collection/SQLMethodLastTest.java | 64 +++++ .../method/collection/SQLMethodSortTest.java | 20 ++ .../collection/SQLMethodTransformTest.java | 4 +- .../conversion/SQLMethodAsListTest.java | 8 + .../method/conversion/SQLMethodAsSetTest.java | 9 + .../conversion/SQLMethodAsStringTest.java | 7 + .../method/string/SQLMethodAppendTest.java | 66 +++++ .../sql/method/string/SQLMethodSplitTest.java | 12 +- .../ha/raft/RaftReplicatedDatabase.java | 4 +- .../com/arcadedb/server/ArcadeDBServer.java | 155 ++++++++++-- .../com/arcadedb/server/ServerDatabase.java | 4 +- .../server/Issue6981ShutdownHookHintTest.java | 9 +- ...025ShutdownHookOpenDatabasesBoundTest.java | 232 ++++++++++++++++++ .../services/com.arcadedb.server.ServerPlugin | 1 + 42 files changed, 1403 insertions(+), 104 deletions(-) create mode 100644 engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodFirst.java create mode 100644 engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodLast.java create mode 100644 engine/src/test/java/com/arcadedb/database/async/Issue7002AsyncUpdateValidationTest.java create mode 100644 engine/src/test/java/com/arcadedb/database/async/Issue7003AsyncDeleteListenerDoubleFireTest.java create mode 100644 engine/src/test/java/com/arcadedb/database/async/Issue7004AsyncParallelLevelTest.java create mode 100644 engine/src/test/java/com/arcadedb/query/sql/method/Issue7027CollectionMethodsOnArrayReceiverTest.java create mode 100644 engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodFirstTest.java create mode 100644 engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodLastTest.java create mode 100644 engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodAppendTest.java create mode 100644 server/src/test/java/com/arcadedb/server/Issue7025ShutdownHookOpenDatabasesBoundTest.java diff --git a/engine/src/main/java/com/arcadedb/GlobalConfiguration.java b/engine/src/main/java/com/arcadedb/GlobalConfiguration.java index 963f7fed1e6..b162e1dc76c 100644 --- a/engine/src/main/java/com/arcadedb/GlobalConfiguration.java +++ b/engine/src/main/java/com/arcadedb/GlobalConfiguration.java @@ -1328,12 +1328,14 @@ proved who it is, and the handshake timeout (arcadedb.network.socketTimeout) onl """ Milliseconds the JVM shutdown hook waits for the server lifecycle lock before giving up and letting \ the JVM exit WITHOUT a graceful stop. It only matters when another thread holds the lifecycle lock \ - when the shutdown signal arrives - a stop() in progress, or the tail of start() after the status has \ - already turned ONLINE: normally the hook takes the lock immediately and this value is never \ - reached, and while the server is still STARTING the hook uses a fixed 2000ms bound instead, which \ - this setting does not govern. Giving up leaves databases as a kill would - the next open replays the \ - WAL - which is the lesser evil, because a hook that waits forever can make the process unkillable \ - (issue #5418). Raise it if a legitimate shutdown of very large databases needs longer than the default.""", + when the shutdown signal arrives - a stop() in progress, a start() that has already opened its \ + databases (they open long before the HTTP service, the plugins and HA come up), or the tail of \ + start() after the status has already turned ONLINE: normally the hook takes the lock immediately \ + and this value is never reached, and while the server is still STARTING with no database open yet \ + the hook uses a fixed 2000ms bound instead, which this setting does not govern. Giving up leaves \ + databases as a kill would - the next open replays the WAL - which is the lesser evil, because a hook \ + that waits forever can make the process unkillable (issue #5418). Raise it if a legitimate shutdown \ + of very large databases needs longer than the default.""", Long.class, 60_000L), // Metrics diff --git a/engine/src/main/java/com/arcadedb/database/DatabaseInternal.java b/engine/src/main/java/com/arcadedb/database/DatabaseInternal.java index d4b731d1e18..1ea60ae2b71 100644 --- a/engine/src/main/java/com/arcadedb/database/DatabaseInternal.java +++ b/engine/src/main/java/com/arcadedb/database/DatabaseInternal.java @@ -225,7 +225,14 @@ static Database unwrap(final Database database) { void updateRecordNoLock(Record record, boolean discardRecordAfter); - void deleteRecordNoLock(Record record); + /** + * Deletes the record without taking the database read lock, dispatching the before/after-delete listeners itself. + * + * @return {@code true} when the record was deleted, {@code false} when a before-delete listener vetoed it. The + * asynchronous delete task relies on this to skip its success callback on a veto without dispatching the listeners + * a second time (issue #7003). + */ + boolean deleteRecordNoLock(Record record); /** * Deletes an edge record the way {@code edge.delete()} does - index cleanup, external values, delete events and diff --git a/engine/src/main/java/com/arcadedb/database/LocalDatabase.java b/engine/src/main/java/com/arcadedb/database/LocalDatabase.java index 93e7a73b7f9..05d6e8479a3 100644 --- a/engine/src/main/java/com/arcadedb/database/LocalDatabase.java +++ b/engine/src/main/java/com/arcadedb/database/LocalDatabase.java @@ -1500,8 +1500,8 @@ public void deleteEdgeSkippingEndpoint(final Edge edge, final RID skipEndpoint) } @Override - public void deleteRecordNoLock(final Record record) { - deleteRecordNoLock(record, null); + public boolean deleteRecordNoLock(final Record record) { + return deleteRecordNoLock(record, null); } /** @@ -1510,19 +1510,20 @@ public void deleteRecordNoLock(final Record record) { * {@link #deleteEdgeSkippingEndpoint(Edge, RID)}). Ignored for any other record type, * and always {@code null} on the ordinary delete path. */ - private void deleteRecordNoLock(final Record record, final RID skipEdgeEndpoint) { + private boolean deleteRecordNoLock(final Record record, final RID skipEdgeEndpoint) { if (record.getIdentity() == null) throw new IllegalArgumentException("Cannot delete a non persistent record"); if (mode == ComponentFile.MODE.READ_ONLY) throw new DatabaseIsReadOnlyException("Cannot delete record " + record.getIdentity()); - // INVOKE EVENT CALLBACKS + // INVOKE EVENT CALLBACKS. This is the ONE place the delete listeners are dispatched from: every caller, the + // asynchronous delete task included, reaches the listeners through here (issue #7003). if (!events.onBeforeDelete(record)) - return; + return false; if (record instanceof Document document) if (!((RecordEventsRegistry) document.getType().getEvents()).onBeforeDelete(record)) - return; + return false; boolean success = false; final boolean implicitTransaction = checkTransactionIsActive(autoTransaction); @@ -1634,6 +1635,7 @@ private void deleteRecordNoLock(final Record record, final RID skipEdgeEndpoint) wrappedDatabaseInstance.rollback(); } } + return true; } /** The INDEX/EXTERNAL cleanup could not read the record, so the delete proceeds without it. */ diff --git a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncBrowseIterator.java b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncBrowseIterator.java index 04b02c93130..597b082a094 100644 --- a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncBrowseIterator.java +++ b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncBrowseIterator.java @@ -43,7 +43,8 @@ public void execute(final DatabaseAsyncExecutorImpl.AsyncThread async, final Dat if (!callback.onRecord(iterator.next().asDocument())) break; - if (async.isShutdown()) + // isAborting(), not isShutdown(): same silent truncation on a retired worker as DatabaseAsyncScanBucket (#7004) + if (async.isAborting()) break; } } diff --git a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncDeleteRecord.java b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncDeleteRecord.java index 6eac64f7a2b..ad590104a9a 100644 --- a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncDeleteRecord.java +++ b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncDeleteRecord.java @@ -19,13 +19,20 @@ package com.arcadedb.database.async; import com.arcadedb.database.DatabaseInternal; -import com.arcadedb.database.Document; import com.arcadedb.database.Record; -import com.arcadedb.database.RecordEventsRegistry; import com.arcadedb.log.LogManager; import java.util.logging.Level; +/** + * Asynchronous delete of one record. + *

+ * The before/after-delete listeners are NOT dispatched here: {@code deleteRecordNoLock} owns that dispatch, exactly + * as it does for the synchronous {@code deleteRecord()}. This task used to dispatch them as well, so every listener + * fired twice per asynchronous delete - a counter double-counted, an audit log got two entries, a cascade ran twice + * (issue #7003). A veto is learnt from the delegate's return value instead, so a vetoed delete still skips the + * success callback as it always did. + */ public class DatabaseAsyncDeleteRecord implements DatabaseAsyncTask { public final Record record; public final DeletedRecordCallback onOkCallback; @@ -40,21 +47,9 @@ public DatabaseAsyncDeleteRecord(final Record record, final DeletedRecordCallbac @Override public void execute(final DatabaseAsyncExecutorImpl.AsyncThread async, final DatabaseInternal database) { try { - if (record instanceof Document document) { - // INVOKE EVENT CALLBACKS - if (!((RecordEventsRegistry) database.getEvents()).onBeforeDelete(document)) - return; - if (!((RecordEventsRegistry) document.getType().getEvents()).onBeforeDelete(document)) - return; - } - - database.deleteRecordNoLock(record); - - if (record instanceof Document document) { - // INVOKE EVENT CALLBACKS - ((RecordEventsRegistry) database.getEvents()).onAfterDelete(document); - ((RecordEventsRegistry) document.getType().getEvents()).onAfterDelete(document); - } + if (!database.deleteRecordNoLock(record)) + // VETOED BY A BEFORE-DELETE LISTENER + return; if (onOkCallback != null) onOkCallback.call(record); diff --git a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutorImpl.java b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutorImpl.java index 57b56f1a8b8..093b432fff1 100644 --- a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutorImpl.java +++ b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutorImpl.java @@ -282,14 +282,27 @@ else if ("standard".equalsIgnoreCase(cfgQueueImpl)) cfgQueueImpl); this.queue = new ArrayBlockingQueue<>(queueSize); } - - backPressurePercentage = database.getConfiguration().getValueAsInteger(GlobalConfiguration.ASYNC_BACK_PRESSURE); } public boolean isShutdown() { return shutdown; } + /** + * Whether a task in flight on this worker must abandon what it is doing: {@link #forceShutdown} is set by + * {@code kill()} and by the close path when a worker is asked to exit at once, and the interrupt is the close + * path's escalation on a worker that outlived its drain budget. + *

+ * Distinct from {@link #isShutdown()} on purpose (issue #7004). {@link #shutdown} also means "this worker is + * being replaced": a shrinking {@code setParallelLevel()} retires a worker by setting it and lets the worker + * drain its queue, so a scan task already queued on it that bailed on that flag stopped after its first record + * while {@code scanType()} still reported success. A drain is exactly the moment such a task must run to + * completion. + */ + public boolean isAborting() { + return forceShutdown || isInterrupted(); + } + @Override public void run() { try { @@ -575,6 +588,9 @@ public DatabaseAsyncExecutorImpl(final DatabaseInternal database, final ContextC this.configuration = configuration; // #4961: a non-positive batch size would make every task fail on count % commitEvery. this.commitEvery = Math.max(1, database.getConfiguration().getValueAsInteger(GlobalConfiguration.ASYNC_TX_BATCH_SIZE)); + // Read once here, NOT in AsyncThread's constructor (issue #7004): the field is executor-wide, and reading it + // per worker meant every setParallelLevel() silently reverted whatever setBackPressure() had been asked for. + this.backPressurePercentage = database.getConfiguration().getValueAsInteger(GlobalConfiguration.ASYNC_BACK_PRESSURE); createThreads(database.getConfiguration().getValueAsInteger(GlobalConfiguration.ASYNC_WORKER_THREADS)); } diff --git a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncScanBucket.java b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncScanBucket.java index de235002598..ed8e29c7f01 100644 --- a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncScanBucket.java +++ b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncScanBucket.java @@ -55,7 +55,10 @@ public DatabaseAsyncScanBucket(final CountDownLatch semaphore, final DocumentCal public void execute(final DatabaseAsyncExecutorImpl.AsyncThread async, final DatabaseInternal database) { try { bucket.scan((rid, view) -> { - if (async.isShutdown()) + // isAborting(), not isShutdown() (issue #7004): a worker retired by a shrinking setParallelLevel() carries the + // shutdown flag while it drains its queue, and this scan is part of that drain. Bailing on it truncated the + // scan after its first record while scanType() still reported success to the caller. + if (async.isAborting()) return false; final Record record = database.getRecordFactory() diff --git a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncUpdateRecord.java b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncUpdateRecord.java index 41716d2ca90..55798f97578 100644 --- a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncUpdateRecord.java +++ b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncUpdateRecord.java @@ -20,12 +20,20 @@ import com.arcadedb.database.DatabaseInternal; import com.arcadedb.database.Document; +import com.arcadedb.database.MutableDocument; import com.arcadedb.database.Record; import com.arcadedb.database.RecordEventsRegistry; import com.arcadedb.log.LogManager; import java.util.logging.Level; +/** + * Asynchronous update of one record. Mirrors the preconditions of the synchronous {@code updateRecord()}: the record + * must be persistent and, when it is a document, it must satisfy its schema. The validation used to be missing here, + * so an asynchronous update persisted a record violating a MANDATORY/NOTNULL constraint with no error anywhere - not + * to the caller, not to the error callback (issue #7002). A violation now takes the same route as any other failure of + * this task: the worker's transaction is rolled back and the error callback is invoked. + */ public class DatabaseAsyncUpdateRecord implements DatabaseAsyncTask { public final Record record; public final UpdatedRecordCallback onOkCallback; @@ -40,6 +48,12 @@ public DatabaseAsyncUpdateRecord(final Record record, final UpdatedRecordCallbac @Override public void execute(final DatabaseAsyncExecutorImpl.AsyncThread async, final DatabaseInternal database) { try { + if (record.getIdentity() == null) + throw new IllegalArgumentException("Cannot update the record because it is not persistent"); + + if (record instanceof MutableDocument document) + document.validate(); + // INVOKE EVENT CALLBACKS if (!((RecordEventsRegistry) database.getEvents()).onBeforeUpdate(record)) return; diff --git a/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java b/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java index 1b3f47d5ecf..8d3a5b39312 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java +++ b/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java @@ -3299,9 +3299,33 @@ public BaseExpression visitThisLiteral(final SQLParser.ThisLiteralContext ctx) { public BaseExpression visitInputParam(final SQLParser.InputParamContext ctx) { final BaseExpression baseExpr = new BaseExpression(); baseExpr.inputParam = (InputParameter) visit(ctx.inputParameter()); + // The grammar accepts `:param.method()` / `:param[0]` and this visitor used to drop the modifiers on the floor, + // so `:list.join('-')` silently answered the bare parameter value (found while fixing issue #7027). + baseExpr.modifier = buildModifierChain(ctx.modifier()); return baseExpr; } + /** + * Links the modifiers of a base expression (method calls, suffixes, array selectors) into the singly linked chain + * {@link BaseExpression#modifier} expects, in source order. + * + * @return the head of the chain, or {@code null} when there is no modifier + */ + private Modifier buildModifierChain(final List modifierContexts) { + Modifier firstModifier = null; + Modifier currentModifier = null; + if (modifierContexts != null) + for (final SQLParser.ModifierContext modCtx : modifierContexts) { + final Modifier modifier = (Modifier) visit(modCtx); + if (firstModifier == null) + firstModifier = modifier; + else + currentModifier.next = modifier; + currentModifier = modifier; + } + return firstModifier; + } + /** * Function call visitor (e.g., EXPAND(arr), SUM(price)). */ diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java b/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java index 64b4f69aa67..94cb7df7ceb 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java @@ -19,9 +19,15 @@ package com.arcadedb.query.sql.method; import com.arcadedb.database.Identifiable; +import com.arcadedb.query.sql.executor.MultiValue; import com.arcadedb.query.sql.executor.SQLMethod; import com.arcadedb.utility.NumberUtils; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + /** * @author Johann Sorel (Geomatys) */ @@ -149,6 +155,42 @@ protected String numericTextOrNull(final Object value) { return text.isEmpty() ? null : text; } + /** + * Reads the receiver of a collection method ({@code join()}, {@code sort()}, {@code transform()}, ...) as a + * {@link List}, answering {@code null} when the value is not a collection at all: {@code null}, a scalar, or a map. + *

+ * Every collection method used to type-test its receiver for {@code List} (or {@code Collection}) on its own and + * fall through to {@code toString()} or to an identity return on anything else. A {@code String[]} - what + * {@code split()} produced, and what a JSON array parameter still arrives as - therefore met a different failure in + * every method: {@code join()} and {@code asString()} leaked the array's identity {@code toString()} + * ({@code "[Ljava.lang.String;@7a8fa663"}) into the result set, {@code sort()} returned it unsorted with no error, + * {@code asList()} wrapped the whole array as a single element (issue #7027). One helper is what keeps the next + * hardening from reaching only one of them, the same move {@link #numericTextOrNull} made for the conversion + * methods in #6825. + *

+ * A {@code List} is answered as is, so the read-only methods pay nothing for it; an {@code Object[]} is answered as + * a fixed-size view of the array; every other collection, primitive array, iterable or iterator is materialised + * into a new list. Callers that mutate the result must copy it first. + * + * @param value the value the method was invoked on + * + * @return the receiver as a list, or {@code null} when it is not a collection + */ + protected static List listReceiverOrNull(final Object value) { + if (value == null || value instanceof Map || !MultiValue.isMultiValue(value)) + return null; + + final List list = MultiValue.getMultiValueAsList(value); + if (list != null) + return list; + + // AN ITERABLE, AN ITERATOR OR A RESULT SET: MATERIALISE IT ONCE + final List materialised = new ArrayList<>(); + for (final Iterator iterator = MultiValue.getMultiValueIterator(value); iterator.hasNext(); ) + materialised.add(iterator.next()); + return materialised; + } + protected Object getParameterValue(final Identifiable iRecord, final String iValue) { if (iValue == null) { return null; diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java b/engine/src/main/java/com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java index 99c168eabb8..8367cf8d083 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java @@ -21,7 +21,9 @@ import com.arcadedb.exception.CommandExecutionException; import com.arcadedb.query.sql.executor.SQLMethod; import com.arcadedb.query.sql.method.collection.SQLMethodField; +import com.arcadedb.query.sql.method.collection.SQLMethodFirst; import com.arcadedb.query.sql.method.collection.SQLMethodJoin; +import com.arcadedb.query.sql.method.collection.SQLMethodLast; import com.arcadedb.query.sql.method.collection.SQLMethodKeys; import com.arcadedb.query.sql.method.collection.SQLMethodRemove; import com.arcadedb.query.sql.method.collection.SQLMethodRemoveAll; @@ -105,7 +107,9 @@ public static DefaultSQLMethodFactory getInstance() { private DefaultSQLMethodFactory() { // Collections register(SQLMethodField.NAME, new SQLMethodField()); + register(SQLMethodFirst.NAME, new SQLMethodFirst()); register(SQLMethodJoin.NAME, new SQLMethodJoin()); + register(SQLMethodLast.NAME, new SQLMethodLast()); register(SQLMethodKeys.NAME, new SQLMethodKeys()); register(SQLMethodRemove.NAME, new SQLMethodRemove()); register(SQLMethodRemoveAll.NAME, new SQLMethodRemoveAll()); diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodFirst.java b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodFirst.java new file mode 100644 index 00000000000..c19cb37ea05 --- /dev/null +++ b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodFirst.java @@ -0,0 +1,50 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.query.sql.method.collection; + +import com.arcadedb.database.Identifiable; +import com.arcadedb.query.sql.executor.CommandContext; +import com.arcadedb.query.sql.executor.MultiValue; +import com.arcadedb.query.sql.method.AbstractSQLMethod; + +/** + * Returns the first item of a collection (list, set, array, map values), or the value itself when it is not a + * collection: the method form of the `first()` SQL function, so it can be chained after any method that produces a + * collection - `'a,b'.split(',').first()` used to fail with "Unknown method name: first" (issue #7027). + * + * @author Luca Garulli (l.garulli@arcadedata.com) + * @see com.arcadedb.function.sql.coll.SQLFunctionFirst + */ +public class SQLMethodFirst extends AbstractSQLMethod { + + public static final String NAME = "first"; + + public SQLMethodFirst() { + super(NAME); + } + + @Override + public Object execute(final Object value, final Identifiable currentRecord, final CommandContext context, + final Object[] params) { + if (MultiValue.isMultiValue(value)) + return MultiValue.getFirstValue(value); + + return value; + } +} diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodJoin.java b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodJoin.java index 88dee4d2216..8bbdf0f19bd 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodJoin.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodJoin.java @@ -28,6 +28,11 @@ /** * Joins a list of objects using a delimiter. + *

+ * The receiver is any collection: a list, a set, an array (what a JSON array parameter arrives as), an iterable. It + * used to accept a {@code List} only, so {@code 'a,b'.split(',').join('-')} answered the array's identity + * {@code toString()} and {@code ['b','a'].asSet().join('-')} answered the set's own {@code toString()} with the + * separator ignored (issue #7027). */ public class SQLMethodJoin extends AbstractSQLMethod { @@ -47,7 +52,8 @@ public Object execute(final Object value, return null; } - if (value instanceof List list) { + final List list = listReceiverOrNull(value); + if (list != null) { final String separator = Optional.ofNullable(params) .filter(p -> p.length > 0) diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodLast.java b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodLast.java new file mode 100644 index 00000000000..49f68dd8240 --- /dev/null +++ b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodLast.java @@ -0,0 +1,50 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.query.sql.method.collection; + +import com.arcadedb.database.Identifiable; +import com.arcadedb.query.sql.executor.CommandContext; +import com.arcadedb.query.sql.executor.MultiValue; +import com.arcadedb.query.sql.method.AbstractSQLMethod; + +/** + * Returns the last item of a collection (list, set, array, map values), or the value itself when it is not a + * collection: the method form of the `last()` SQL function, so it can be chained after any method that produces a + * collection - `'a,b'.split(',').last()` used to fail with "Unknown method name: last" (issue #7027). + * + * @author Luca Garulli (l.garulli@arcadedata.com) + * @see com.arcadedb.function.sql.coll.SQLFunctionLast + */ +public class SQLMethodLast extends AbstractSQLMethod { + + public static final String NAME = "last"; + + public SQLMethodLast() { + super(NAME); + } + + @Override + public Object execute(final Object value, final Identifiable currentRecord, final CommandContext context, + final Object[] params) { + if (MultiValue.isMultiValue(value)) + return MultiValue.getLastValue(value); + + return value; + } +} diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodSort.java b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodSort.java index 530c38fa8f6..ff0021b1a49 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodSort.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodSort.java @@ -42,8 +42,11 @@ public SQLMethodSort() { public Object execute(final Object value, final Identifiable currentRecord, final CommandContext context, final Object[] params) { - if (value instanceof List list) { - List result = new ArrayList(list); + // ANY COLLECTION, NOT ONLY A List: A SET OR AN ARRAY RECEIVER USED TO COME BACK UNSORTED WITH NO ERROR, WHICH IS + // WORSE THAN A FAILURE BECAUSE IT LOOKS LIKE IT WORKED (ISSUE #7027). SCALARS STAY AN IDENTITY. + final List list = listReceiverOrNull(value); + if (list != null) { + final List result = new ArrayList<>(list); if (params != null && params.length > 0 && params[0] instanceof Boolean bool && !bool) result.sort((left, right) -> BinaryComparator.compareTo(right, left)); else diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodTransform.java b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodTransform.java index 17cba7a7299..7a89b55be19 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodTransform.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodTransform.java @@ -65,28 +65,32 @@ public Object execute(final Object value, final Identifiable currentRecord, fina transformers.add(methodFactory.createMethod(o.toString())); } - if (value instanceof List list) { - final List newList = new ArrayList<>(list.size()); - for (Object o : list) { + if (value instanceof Set set) { + final Set newSet = new HashSet<>(set.size()); + for (Object o : set) { Object transformed = o; for (SQLMethod m : transformers) transformed = m.execute(transformed, null, context, EMPTY_ARGS); - newList.add(transformed); + newSet.add(transformed); } - return newList; - } else if (value instanceof Set set) { - final Set newSet = new HashSet<>(set.size()); - for (Object o : set) { + return newSet; + } + + // A LIST, AN ARRAY OR ANY OTHER COLLECTION (ISSUE #7027): SCALARS STAY AN IDENTITY + final List list = listReceiverOrNull(value); + if (list != null) { + final List newList = new ArrayList<>(list.size()); + for (Object o : list) { Object transformed = o; for (SQLMethod m : transformers) transformed = m.execute(transformed, null, context, EMPTY_ARGS); - newSet.add(transformed); + newList.add(transformed); } - return newSet; + return newList; } return value; diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsList.java b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsList.java index 10b9fcab25e..2d67ce93404 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsList.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsList.java @@ -50,6 +50,10 @@ public Object execute(Object value, final Identifiable currentRecord, final Comm if (value instanceof Collection) { return new ArrayList<>((Collection) value); + } else if (value.getClass().isArray()) { + // AN ARRAY (split(), A JSON ARRAY PARAMETER) USED TO FALL THROUGH TO THE SINGLE-ITEM BRANCH BELOW AND COME + // BACK AS A ONE-ELEMENT LIST HOLDING THE WHOLE ARRAY (ISSUE #7027) + return new ArrayList<>(listReceiverOrNull(value)); } else if (value instanceof Iterable iterable) { value = iterable.iterator(); } diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSet.java b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSet.java index 580111d8e13..afc2ccc0fe3 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSet.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSet.java @@ -50,6 +50,9 @@ public Object execute(Object value, final Identifiable currentRecord, final Comm if (value instanceof Collection) { return new HashSet<>((Collection) value); + } else if (value.getClass().isArray()) { + // SAME AS asList(): AN ARRAY IS A COLLECTION OF ITS ELEMENTS, NOT A SINGLE ITEM (ISSUE #7027) + return new HashSet<>(listReceiverOrNull(value)); } else if (value instanceof Iterable iterable) { value = iterable.iterator(); } diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsString.java b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsString.java index a58e3f00f7e..b02c79c8014 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsString.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsString.java @@ -64,6 +64,12 @@ public Object execute(final Object value, final Identifiable currentRecord, fina } } + if (value.getClass().isArray()) + // A NON-NUMERIC ARRAY HAS NO NATURAL STRING FORM OF ITS OWN: Object.toString() IS THE JVM IDENTITY + // ("[Ljava.lang.String;@7a8fa663"), WHICH USED TO REACH THE CLIENT AS DATA (ISSUE #7027). RENDER IT AS THE + // LIST OF ITS ELEMENTS, EXACTLY AS THE SAME VALUES IN A List WOULD BE. + return listReceiverOrNull(value).toString(); + return value.toString(); } diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java index 6ad4b6c4a5a..70534c16bc4 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java @@ -45,15 +45,16 @@ public String getSyntax() { @Override public Object execute( final Object value, final Identifiable currentRecord, final CommandContext context, final Object[] params) { - if (value == null || params[0] == null) - return value; + if (value == null) + return null; + // A null argument is skipped, wherever it appears. A leading null used to return the receiver untouched, dropping + // every argument after it - so 'x'.append(null, 'A', 'B') answered "x" while 'x'.append('A', null, 'B') answered + // "xAB" (issue #7028). final StringBuilder buffer = new StringBuilder(value.toString()); - for (int i = 0; i < params.length; ++i) { - if (params[i] != null) { + for (int i = 0; i < params.length; ++i) + if (params[i] != null) buffer.append(FileUtils.getStringContent(params[i])); - } - } return buffer.toString(); } diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodSplit.java b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodSplit.java index 249c076224c..2f4e18aff93 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodSplit.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodSplit.java @@ -22,6 +22,7 @@ import com.arcadedb.query.sql.executor.CommandContext; import com.arcadedb.query.sql.method.AbstractSQLMethod; +import java.util.List; import java.util.regex.Pattern; /** @@ -46,6 +47,9 @@ public Object execute(final Object value, final Identifiable iRecord, final Comm // which all wrap the delimiter in Pattern.quote() for the same reason - this method was the only one of the // four that passed the caller-supplied delimiter straight to String.split(regex) unescaped, exposing it to // the same catastrophic-backtracking risk as every other regex entry point in that issue). - return value.toString().split(Pattern.quote(params[0].toString())); + // A List, not the String[] String.split() hands back (issue #7027): the SQL split() function, the Cypher split() + // function and the documentation of this very method all answer a list, and this was the only one of the four + // that leaked the raw Java array - the one receiver shape most of the collection methods then mishandled. + return List.of(value.toString().split(Pattern.quote(params[0].toString()))); } } diff --git a/engine/src/test/java/com/arcadedb/database/async/Issue7002AsyncUpdateValidationTest.java b/engine/src/test/java/com/arcadedb/database/async/Issue7002AsyncUpdateValidationTest.java new file mode 100644 index 00000000000..b408948ec54 --- /dev/null +++ b/engine/src/test/java/com/arcadedb/database/async/Issue7002AsyncUpdateValidationTest.java @@ -0,0 +1,106 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.database.async; + +import com.arcadedb.TestHelper; +import com.arcadedb.database.Document; +import com.arcadedb.database.MutableDocument; +import com.arcadedb.database.RID; +import com.arcadedb.exception.ValidationException; +import com.arcadedb.schema.DocumentType; +import com.arcadedb.schema.Type; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Regression test for issue #7002: {@code async().updateRecord()} never validated the document, so an asynchronous + * update persisted a record violating a MANDATORY/NOTNULL constraint with no error reaching the caller or the error + * callback. The synchronous update is the control. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +class Issue7002AsyncUpdateValidationTest extends TestHelper { + + private static final String TYPE = "Issue7002P"; + + @Override + protected void beginTest() { + final DocumentType type = database.getSchema().createDocumentType(TYPE); + type.createProperty("name", Type.STRING).setMandatory(true).setNotNull(true); + type.createProperty("v", Type.INTEGER); + } + + @Test + void asyncUpdateRejectsARecordViolatingItsSchemaAndReportsItToTheErrorCallback() { + final RID rid = createRecord(); + + // CONTROL: THE SYNCHRONOUS UPDATE REFUSES THE SAME EDIT + assertThatThrownBy(() -> database.transaction(() -> { + final MutableDocument doc = rid.asDocument().modify(); + doc.set("v", 2); + doc.remove("name"); + doc.save(); + })).isInstanceOf(ValidationException.class); + + final AtomicInteger okCalls = new AtomicInteger(); + final AtomicReference reported = new AtomicReference<>(); + final AtomicReference executorWide = new AtomicReference<>(); + database.async().onError(executorWide::set); + + final MutableDocument doc = rid.asDocument().modify(); + doc.set("v", 3); + doc.remove("name"); + database.async().updateRecord(doc, record -> okCalls.incrementAndGet(), reported::set); + database.async().waitCompletion(); + + assertThat(reported.get()).as("the violation must reach the task's error callback").isInstanceOf(ValidationException.class); + assertThat(executorWide.get()).as("and the executor-wide onError").isInstanceOf(ValidationException.class); + assertThat(okCalls.get()).as("a rejected update has no success to report").isZero(); + + // THE DATABASE STILL HOLDS THE RECORD THE SCHEMA ALLOWS: NAME PRESENT, THE EDIT NEVER LANDED + final Document stored = database.lookupByRID(rid, true).asDocument(); + assertThat(stored.getString("name")).isEqualTo("original"); + assertThat(stored.getInteger("v")).isEqualTo(1); + } + + @Test + void asyncUpdateStillAppliesAValidEdit() { + final RID rid = createRecord(); + + final AtomicReference reported = new AtomicReference<>(); + final MutableDocument doc = rid.asDocument().modify(); + doc.set("v", 5); + database.async().updateRecord(doc, null, reported::set); + database.async().waitCompletion(); + + assertThat(reported.get()).isNull(); + assertThat(database.lookupByRID(rid, true).asDocument().getInteger("v")).isEqualTo(5); + } + + private RID createRecord() { + final AtomicReference rid = new AtomicReference<>(); + database.transaction(() -> rid.set(database.newDocument(TYPE).set("name", "original").set("v", 1).save().getIdentity())); + return rid.get(); + } +} diff --git a/engine/src/test/java/com/arcadedb/database/async/Issue7003AsyncDeleteListenerDoubleFireTest.java b/engine/src/test/java/com/arcadedb/database/async/Issue7003AsyncDeleteListenerDoubleFireTest.java new file mode 100644 index 00000000000..066a0e64d2c --- /dev/null +++ b/engine/src/test/java/com/arcadedb/database/async/Issue7003AsyncDeleteListenerDoubleFireTest.java @@ -0,0 +1,111 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.database.async; + +import com.arcadedb.TestHelper; +import com.arcadedb.database.RID; +import com.arcadedb.event.AfterRecordDeleteListener; +import com.arcadedb.event.BeforeRecordDeleteListener; +import com.arcadedb.schema.DocumentType; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Regression test for issue #7003: {@code async().deleteRecord()} fired every before/after-delete listener twice, + * once from the async task and once more from the {@code deleteRecordNoLock} path it delegates to. Both the + * database-level and the type-level registries are counted, and the veto path is pinned as well: a vetoed delete must + * neither delete the record nor report success. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +class Issue7003AsyncDeleteListenerDoubleFireTest extends TestHelper { + + private static final String TYPE = "Issue7003Doc"; + + @Override + protected void beginTest() { + database.getSchema().createDocumentType(TYPE); + } + + @Test + void everyDeleteListenerFiresExactlyOncePerAsyncDelete() { + final AtomicInteger dbBefore = new AtomicInteger(); + final AtomicInteger dbAfter = new AtomicInteger(); + final AtomicInteger typeBefore = new AtomicInteger(); + final AtomicInteger typeAfter = new AtomicInteger(); + + final DocumentType type = database.getSchema().getType(TYPE); + database.getEvents().registerListener((BeforeRecordDeleteListener) record -> { + dbBefore.incrementAndGet(); + return true; + }).registerListener((AfterRecordDeleteListener) record -> dbAfter.incrementAndGet()); + type.getEvents().registerListener((BeforeRecordDeleteListener) record -> { + typeBefore.incrementAndGet(); + return true; + }).registerListener((AfterRecordDeleteListener) record -> typeAfter.incrementAndGet()); + + final RID rid = createRecord(); + + final AtomicInteger okCalls = new AtomicInteger(); + final AtomicReference error = new AtomicReference<>(); + database.async().deleteRecord(rid.getRecord(), record -> okCalls.incrementAndGet(), error::set); + database.async().waitCompletion(); + + assertThat(error.get()).isNull(); + assertThat(okCalls.get()).isEqualTo(1); + assertThat(dbBefore.get()).as("database-level beforeDelete").isEqualTo(1); + assertThat(dbAfter.get()).as("database-level afterDelete").isEqualTo(1); + assertThat(typeBefore.get()).as("type-level beforeDelete").isEqualTo(1); + assertThat(typeAfter.get()).as("type-level afterDelete").isEqualTo(1); + assertThat(database.existsRecord(rid)).isFalse(); + } + + @Test + void aVetoedAsyncDeleteKeepsTheRecordAndSkipsTheSuccessCallback() { + final AtomicInteger before = new AtomicInteger(); + final AtomicInteger after = new AtomicInteger(); + database.getEvents().registerListener((BeforeRecordDeleteListener) record -> { + before.incrementAndGet(); + return false; + }).registerListener((AfterRecordDeleteListener) record -> after.incrementAndGet()); + + final RID rid = createRecord(); + + final AtomicInteger okCalls = new AtomicInteger(); + final AtomicReference error = new AtomicReference<>(); + database.async().deleteRecord(rid.getRecord(), record -> okCalls.incrementAndGet(), error::set); + database.async().waitCompletion(); + + assertThat(error.get()).isNull(); + assertThat(before.get()).as("the vetoing listener is asked once").isEqualTo(1); + assertThat(after.get()).as("nothing was deleted, so no afterDelete").isZero(); + assertThat(okCalls.get()).as("a vetoed delete is not a success").isZero(); + assertThat(database.existsRecord(rid)).isTrue(); + } + + private RID createRecord() { + final AtomicReference rid = new AtomicReference<>(); + database.transaction(() -> rid.set(database.newDocument(TYPE).set("id", 1).save().getIdentity())); + return rid.get(); + } +} diff --git a/engine/src/test/java/com/arcadedb/database/async/Issue7004AsyncParallelLevelTest.java b/engine/src/test/java/com/arcadedb/database/async/Issue7004AsyncParallelLevelTest.java new file mode 100644 index 00000000000..d8bc01e0b34 --- /dev/null +++ b/engine/src/test/java/com/arcadedb/database/async/Issue7004AsyncParallelLevelTest.java @@ -0,0 +1,135 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.database.async; + +import com.arcadedb.GlobalConfiguration; +import com.arcadedb.TestHelper; +import com.arcadedb.database.DatabaseInternal; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Regression tests for issue #7004, two defects around {@code setParallelLevel()}: + *
    + *
  1. {@code backPressurePercentage} is executor-wide but was (re)read from the configuration inside every + * {@code AsyncThread} constructor, so each resize silently reverted whatever {@code setBackPressure()} asked for.
  2. + *
  3. {@code DatabaseAsyncScanBucket} bailed on the worker's {@code shutdown} flag, which a shrinking + * {@code setParallelLevel()} sets on the workers it retires while they drain their queues - so a scan task queued on + * a retired worker stopped after its first record while {@code scanType()} still reported success.
  4. + *
+ * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +class Issue7004AsyncParallelLevelTest extends TestHelper { + + private static final String TYPE = "Issue7004Doc"; + private static final int RECORDS = 500; + + @Test + void setParallelLevelKeepsTheBackPressureAskedFor() { + final DatabaseAsyncExecutorImpl async = (DatabaseAsyncExecutorImpl) ((DatabaseInternal) database).async(); + final int configured = database.getConfiguration().getValueAsInteger(GlobalConfiguration.ASYNC_BACK_PRESSURE); + final int requested = configured == 80 ? 70 : 80; + + async.setBackPressure(requested); + assertThat(async.getBackPressure()).isEqualTo(requested); + + async.setParallelLevel(async.getThreadCount() + 2); + assertThat(async.getBackPressure()).as("a grow must not revert setBackPressure()").isEqualTo(requested); + + async.setParallelLevel(1); + assertThat(async.getBackPressure()).as("a shrink must not revert setBackPressure()").isEqualTo(requested); + } + + @Test + @Timeout(60) + void aScanQueuedOnARetiredWorkerRunsToCompletion() throws Exception { + final DatabaseAsyncExecutorImpl async = (DatabaseAsyncExecutorImpl) ((DatabaseInternal) database).async(); + async.setParallelLevel(2); + + database.getSchema().createDocumentType(TYPE, 2); + database.transaction(() -> { + for (int i = 0; i < RECORDS; i++) + database.newDocument(TYPE).set("id", i).save(); + }); + + // PARK BOTH WORKERS ON A GATE, SO THE SCAN TASKS SCHEDULED NEXT ARE PROVABLY STILL QUEUED - NOT RUN - WHEN THE + // SHRINK RETIRES ONE OF THE TWO. WHICH BUCKET LANDS ON WHICH SLOT DOES NOT MATTER: BOTH SLOTS ARE GATED. + final CountDownLatch gatesEntered = new CountDownLatch(2); + final CountDownLatch release = new CountDownLatch(1); + for (int slot = 0; slot < 2; slot++) + assertThat(async.scheduleTask(slot, AsyncTestTasks.awaitTask(gatesEntered, release), true, 0)).isTrue(); + assertThat(gatesEntered.await(30, TimeUnit.SECONDS)).as("both workers must be parked on their gate").isTrue(); + + // THE SCAN, FROM ITS OWN THREAD: scanType() BLOCKS UNTIL EVERY BUCKET TASK HAS COMPLETED + final AtomicInteger scanned = new AtomicInteger(); + final AtomicReference scanFailure = new AtomicReference<>(); + final Thread scanner = new Thread(() -> { + try { + database.async().scanType(TYPE, true, record -> { + scanned.incrementAndGet(); + return true; + }); + } catch (final Throwable t) { + scanFailure.set(t); + } + }, "issue7004-scanner"); + scanner.start(); + + // WAIT UNTIL BOTH BUCKET TASKS SIT IN THE QUEUES BEHIND THE GATES + final long deadline = System.currentTimeMillis() + 30_000; + while (async.getStats().queueSize < 2 && System.currentTimeMillis() < deadline) + Thread.sleep(10); + assertThat(async.getStats().queueSize).as("the two bucket scans must be queued behind the gates").isEqualTo(2); + + // SHRINK TO ONE WORKER, FROM ITS OWN THREAD BECAUSE THE RESIZE WAITS FOR THE RETIRED WORKER TO DRAIN - WHICH IT + // CANNOT DO UNTIL THE GATE IS RELEASED. THE RETIRED WORKER NOW CARRIES THE shutdown FLAG WITH THE SCAN OF ONE + // BUCKET STILL IN ITS QUEUE: THE SHAPE THE BUG NEEDS. + final AtomicReference resizeFailure = new AtomicReference<>(); + final Thread resizer = new Thread(() -> { + try { + async.setParallelLevel(1); + } catch (final Throwable t) { + resizeFailure.set(t); + } + }, "issue7004-resizer"); + resizer.start(); + while (async.getThreadCount() != 1 && System.currentTimeMillis() < deadline) + Thread.sleep(10); + assertThat(async.getThreadCount()).as("the survivors must be published before the gates open").isEqualTo(1); + + release.countDown(); + resizer.join(30_000); + scanner.join(30_000); + + assertThat(resizeFailure.get()).isNull(); + assertThat(scanFailure.get()).isNull(); + assertThat(scanner.isAlive()).as("scanType() must have returned").isFalse(); + assertThat(scanned.get()) + .as("the bucket scan drained by the retired worker must deliver every record, not stop after the first one") + .isEqualTo(RECORDS); + } +} diff --git a/engine/src/test/java/com/arcadedb/function/sql/sql/SQLFunctionsTest.java b/engine/src/test/java/com/arcadedb/function/sql/sql/SQLFunctionsTest.java index a6ba18a1b7c..cabcd9dbd79 100755 --- a/engine/src/test/java/com/arcadedb/function/sql/sql/SQLFunctionsTest.java +++ b/engine/src/test/java/com/arcadedb/function/sql/sql/SQLFunctionsTest.java @@ -592,15 +592,9 @@ void querySplit() { assertThat(result.hasNext()).isTrue(); for (final ResultSet it = result; it.hasNext(); ) { final Result d = it.next(); - assertThat(d.getProperty("value")).isNotNull(); - assertThat(d.getProperty("value").getClass().isArray()).isTrue(); - - final Object[] array = d.getProperty("value"); - - assertThat(array.length).isEqualTo(3); - assertThat(array[0]).isEqualTo("1"); - assertThat(array[1]).isEqualTo("2"); - assertThat(array[2]).isEqualTo("3"); + // A List, not a String[] (issue #7027): the same shape the split() function and the Cypher split() answer + assertThat(d.getProperty("value")).isInstanceOf(List.class); + assertThat(d.>getProperty("value")).containsExactly("1", "2", "3"); } } diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/Issue7027CollectionMethodsOnArrayReceiverTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/Issue7027CollectionMethodsOnArrayReceiverTest.java new file mode 100644 index 00000000000..833958c871c --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/sql/method/Issue7027CollectionMethodsOnArrayReceiverTest.java @@ -0,0 +1,114 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.query.sql.method; + +import com.arcadedb.TestHelper; +import com.arcadedb.query.sql.executor.Result; +import com.arcadedb.query.sql.executor.ResultSet; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Regression test for issue #7027: {@code split()} answered a {@code String[]}, and the collection methods each + * mishandled that receiver in their own way - {@code join()} and {@code asString()} leaked the array's identity + * {@code toString()} into the result set, {@code sort()} returned it unsorted with no error, {@code asList()} wrapped + * the whole array as one element, {@code first()}/{@code last()} did not exist as methods at all. Every cell below is + * the receiver matrix from the report, with the {@code List} literal as the control in the same run. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +@SuppressWarnings("unchecked") +class Issue7027CollectionMethodsOnArrayReceiverTest extends TestHelper { + + @Test + void splitAnswersAListLikeTheSplitFunctionAndTheCypherSplit() { + assertThat(scalar("SELECT 'a,b'.split(',') AS r")).isInstanceOf(List.class).isEqualTo(List.of("a", "b")); + } + + @Test + void joinHonoursEveryCollectionReceiver() { + assertThat(scalar("SELECT ['a','b'].join('-') AS r")).isEqualTo("a-b"); + assertThat(scalar("SELECT 'a,b'.split(',').join('-') AS r")).isEqualTo("a-b"); + assertThat(scalar("SELECT 'a,b'.split(',').asList().join('-') AS r")).isEqualTo("a-b"); + // A SET HAS NO ORDER, BUT THE SEPARATOR MUST BE HONOURED RATHER THAN THE SET'S OWN toString() RETURNED + assertThat(scalar("SELECT ['b','a'].asSet().join('-') AS r")).isIn("a-b", "b-a"); + } + + @Test + void sortSortsAnArrayInsteadOfReturningItUntouched() { + assertThat(scalar("SELECT 'b,a'.split(',').sort() AS r")).isEqualTo(List.of("a", "b")); + assertThat(scalar("SELECT 'a,b'.split(',').sort(false) AS r")).isEqualTo(List.of("b", "a")); + assertThat(scalar("SELECT ['b','a'].asSet().sort() AS r")).isEqualTo(List.of("a", "b")); + } + + @Test + void sizeFirstAndLastWorkOnTheSplitResult() { + assertThat(scalar("SELECT 'a,b'.split(',').size() AS r")).isEqualTo(2); + assertThat(scalar("SELECT 'a,b'.split(',').first() AS r")).isEqualTo("a"); + assertThat(scalar("SELECT 'a,b'.split(',').last() AS r")).isEqualTo("b"); + // THE METHOD FORM IS THE SAME OPERATION AS THE FUNCTION FORM + assertThat(scalar("SELECT first('a,b'.split(',')) AS r")).isEqualTo("a"); + assertThat(scalar("SELECT last(['a','b']) AS r")).isEqualTo("b"); + // A SCALAR IS AN IDENTITY, EXACTLY AS THE FUNCTIONS TREAT IT + assertThat(scalar("SELECT 'abc'.first() AS r")).isEqualTo("abc"); + assertThat(scalar("SELECT 'abc'.last() AS r")).isEqualTo("abc"); + } + + @Test + void asStringNeverLeaksTheJavaArrayIdentity() { + final Object rendered = scalar("SELECT 'a,b'.split(',').asString() AS r"); + assertThat(rendered).isEqualTo("[a, b]"); + assertThat(scalar("SELECT ['a','b'].asString() AS r")).as("the list control renders the same").isEqualTo(rendered); + } + + @Test + void asListAsSetAndTransformSeeTheArrayElements() { + assertThat(scalar("SELECT 'a,b'.split(',').asList() AS r")).isEqualTo(List.of("a", "b")); + assertThat((Set) scalar("SELECT 'a,b,a'.split(',').asSet() AS r")).containsExactlyInAnyOrder("a", "b"); + assertThat(scalar("SELECT 'a,b'.split(',').transform('toUpperCase') AS r")).isEqualTo(List.of("A", "B")); + } + + @Test + void aJsonArrayParameterIsACollectionReceiverToo() { + // A NUMERIC JSON ARRAY PARAMETER ARRIVES AS A PRIMITIVE ARRAY; A STRING ONE AS A String[]. ALSO PINS THAT THE + // METHOD CHAIN AFTER A PARAMETER IS APPLIED AT ALL: THE AST BUILDER USED TO DROP IT AND ANSWER THE BARE PARAMETER + assertThat(scalar("SELECT :p.size() AS r", Map.of("p", new int[] { 3, 1, 2 }))).isEqualTo(3); + assertThat(scalar("SELECT :p.join('-') AS r", Map.of("p", new int[] { 3, 1, 2 }))).isEqualTo("3-1-2"); + assertThat(scalar("SELECT :p.sort() AS r", Map.of("p", new int[] { 3, 1, 2 }))).isEqualTo(List.of(1, 2, 3)); + assertThat(scalar("SELECT :p.join('-') AS r", Map.of("p", new String[] { "x", "y" }))).isEqualTo("x-y"); + } + + private Object scalar(final String query) { + return scalar(query, Map.of()); + } + + private Object scalar(final String query, final Map params) { + try (final ResultSet rs = database.query("sql", query, params)) { + assertThat(rs.hasNext()).isTrue(); + final Result result = rs.next(); + assertThat(rs.hasNext()).isFalse(); + return result.getProperty("r"); + } + } +} diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodFirstTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodFirstTest.java new file mode 100644 index 00000000000..53e62801d31 --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodFirstTest.java @@ -0,0 +1,64 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.query.sql.method.collection; + +import com.arcadedb.query.sql.executor.SQLMethod; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashSet; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The method form of the {@code first()} function (issue #7027). + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +class SQLMethodFirstTest { + + private SQLMethod method; + + @BeforeEach + void setUp() { + method = new SQLMethodFirst(); + } + + @Test + void collectionsOfEveryShape() { + assertThat(method.execute(List.of(1, 2, 3), null, null, null)).isEqualTo(1); + assertThat(method.execute(new Integer[] { 1, 2, 3 }, null, null, null)).isEqualTo(1); + assertThat(method.execute(new int[] { 1, 2, 3 }, null, null, null)).isEqualTo(1); + assertThat(method.execute(new LinkedHashSet<>(List.of(1, 2, 3)), null, null, null)).isEqualTo(1); + } + + @Test + void emptyCollectionAnswersNull() { + assertThat(method.execute(List.of(), null, null, null)).isNull(); + assertThat(method.execute(new String[0], null, null, null)).isNull(); + } + + @Test + void scalarsAndNullAreAnIdentity() { + assertThat(method.execute("abc", null, null, null)).isEqualTo("abc"); + assertThat(method.execute(7, null, null, null)).isEqualTo(7); + assertThat(method.execute(null, null, null, null)).isNull(); + } +} diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodJoinTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodJoinTest.java index 71903728d0b..74173f72301 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodJoinTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodJoinTest.java @@ -23,6 +23,7 @@ import org.junit.jupiter.api.Test; import java.util.Collections; +import java.util.LinkedHashSet; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -76,4 +77,24 @@ void joinByProvidedSeparator() { assertThat(result).isInstanceOf(String.class); assertThat(result).isEqualTo("first;second"); } + + @Test + void joinAnArrayReceiver() { + // Issue #7027: what split() used to answer, and what a JSON array parameter still arrives as + assertThat(method.execute(new String[] { "first", "second" }, null, null, new Object[] { "-" })).isEqualTo("first-second"); + assertThat(method.execute(new int[] { 3, 1, 2 }, null, null, new Object[] { "-" })).isEqualTo("3-1-2"); + } + + @Test + void joinASetHonoursTheSeparator() { + // Issue #7027: a Set receiver used to come back as the set's own toString(), separator ignored + final Object result = method.execute(new LinkedHashSet<>(List.of("first", "second")), null, null, new Object[] { "-" }); + assertThat(result).isEqualTo("first-second"); + } + + @Test + void joinAnIterableReceiver() { + final Iterable iterable = () -> List.of("a", "b").iterator(); + assertThat(method.execute(iterable, null, null, new Object[] { "|" })).isEqualTo("a|b"); + } } diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodLastTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodLastTest.java new file mode 100644 index 00000000000..16c21120b19 --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodLastTest.java @@ -0,0 +1,64 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.query.sql.method.collection; + +import com.arcadedb.query.sql.executor.SQLMethod; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashSet; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The method form of the {@code last()} function (issue #7027). + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +class SQLMethodLastTest { + + private SQLMethod method; + + @BeforeEach + void setUp() { + method = new SQLMethodLast(); + } + + @Test + void collectionsOfEveryShape() { + assertThat(method.execute(List.of(1, 2, 3), null, null, null)).isEqualTo(3); + assertThat(method.execute(new Integer[] { 1, 2, 3 }, null, null, null)).isEqualTo(3); + assertThat(method.execute(new int[] { 1, 2, 3 }, null, null, null)).isEqualTo(3); + assertThat(method.execute(new LinkedHashSet<>(List.of(1, 2, 3)), null, null, null)).isEqualTo(3); + } + + @Test + void emptyCollectionAnswersNull() { + assertThat(method.execute(List.of(), null, null, null)).isNull(); + assertThat(method.execute(new String[0], null, null, null)).isNull(); + } + + @Test + void scalarsAndNullAreAnIdentity() { + assertThat(method.execute("abc", null, null, null)).isEqualTo("abc"); + assertThat(method.execute(7, null, null, null)).isEqualTo(7); + assertThat(method.execute(null, null, null, null)).isNull(); + } +} diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodSortTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodSortTest.java index cc7650ea642..828a094d449 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodSortTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodSortTest.java @@ -22,6 +22,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.LinkedHashSet; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -94,4 +95,23 @@ void scalar() { assertThat(result).isInstanceOf(Number.class); assertThat(result).isEqualTo(listout); } + + @Test + void arrayReceiverIsSortedNotReturnedUntouched() { + // Issue #7027: an array came back unsorted with no error, which looked like it had worked + assertThat(method.execute(new String[] { "b", "a" }, null, null, null)).isEqualTo(List.of("a", "b")); + assertThat(method.execute(new int[] { 3, 1, 2 }, null, null, null)).isEqualTo(List.of(1, 2, 3)); + assertThat(method.execute(new int[] { 3, 1, 2 }, null, null, new Boolean[] { false })).isEqualTo(List.of(3, 2, 1)); + } + + @Test + void setReceiverIsSorted() { + assertThat(method.execute(new LinkedHashSet<>(List.of(3, 1, 2)), null, null, null)).isEqualTo(List.of(1, 2, 3)); + } + + @Test + void scalarAndNullAreAnIdentity() { + assertThat(method.execute("abc", null, null, null)).isEqualTo("abc"); + assertThat(method.execute(null, null, null, null)).isNull(); + } } diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodTransformTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodTransformTest.java index fd4a9220a62..4d5cab074ac 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodTransformTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodTransformTest.java @@ -310,8 +310,8 @@ public void updateRecordNoLock(Record record, boolean discardRecordAfter) { } @Override - public void deleteRecordNoLock(Record record) { - + public boolean deleteRecordNoLock(Record record) { + return true; } @Override diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsListTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsListTest.java index 93c9fe9ee5a..6d5baa09a42 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsListTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsListTest.java @@ -26,6 +26,7 @@ import java.util.ArrayList; import java.util.LinkedHashSet; +import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; @@ -140,4 +141,11 @@ void otherSingleValue() { assertThat(result).isEqualTo(expected); } + + @Test + void arrayIsConvertedToAListOfItsElements() { + // Issue #7027: an array used to come back as a one-element list holding the whole array + assertThat(function.execute(new String[] { "a", "b" }, null, null, null)).isEqualTo(List.of("a", "b")); + assertThat(function.execute(new int[] { 1, 2 }, null, null, null)).isEqualTo(List.of(1, 2)); + } } diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSetTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSetTest.java index 2680be29df3..10640b61d54 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSetTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSetTest.java @@ -27,6 +27,8 @@ import java.util.ArrayList; import java.util.HashSet; +import java.util.Set; + import static org.assertj.core.api.Assertions.assertThat; /** @@ -141,4 +143,11 @@ void otherSingleValue() { expected.add(Integer.valueOf(4)); assertThat(expected).isEqualTo(result); } + + @Test + @SuppressWarnings("unchecked") + void arrayIsConvertedToASetOfItsElements() { + // Issue #7027: an array used to come back as a one-element set holding the whole array + assertThat((Set) function.execute(new String[] { "a", "b", "a" }, null, null, null)).containsExactlyInAnyOrder("a", "b"); + } } diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsStringTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsStringTest.java index a5439e943da..58d9f78c606 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsStringTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsStringTest.java @@ -53,4 +53,11 @@ void numberIsReturnedAsString() { result = method.execute(100.0, null, null, null); assertThat(result).isEqualTo("100.0"); } + + @Test + void nonNumericArrayIsRenderedAsItsElementsNotAsTheJvmIdentity() { + // Issue #7027: "[Ljava.lang.String;@7a8fa663" used to reach the client as data + assertThat(method.execute(new String[] { "a", "b" }, null, null, null)).isEqualTo("[a, b]"); + assertThat(method.execute(new Object[] { "a", 1, null }, null, null, null)).isEqualTo("[a, 1, null]"); + } } diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodAppendTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodAppendTest.java new file mode 100644 index 00000000000..1fad8795d2f --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodAppendTest.java @@ -0,0 +1,66 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.query.sql.method.string; + +import com.arcadedb.query.sql.executor.SQLMethod; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Regression test for issue #7028: {@code append()} skipped a null argument anywhere except first, where it returned + * the receiver untouched and dropped every argument after it - {@code 'x'.append(null, 'A', 'B')} answered + * {@code "x"} while {@code 'x'.append('A', null, 'B')} answered {@code "xAB"}. Both directions are pinned together. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +class SQLMethodAppendTest { + + private SQLMethod method; + + @BeforeEach + void setUp() { + method = new SQLMethodAppend(); + } + + @Test + void aLeadingNullIsSkippedLikeAnyOtherNull() { + assertThat(method.execute("x", null, null, new Object[] { null, "A", "B" })).isEqualTo("xAB"); + assertThat(method.execute("x", null, null, new Object[] { "A", null, "B" })).isEqualTo("xAB"); + assertThat(method.execute("x", null, null, new Object[] { "A", "B", null })).isEqualTo("xAB"); + } + + @Test + void allNullArgumentsLeaveTheReceiverUnchanged() { + assertThat(method.execute("x", null, null, new Object[] { null })).isEqualTo("x"); + assertThat(method.execute("x", null, null, new Object[] { null, null })).isEqualTo("x"); + } + + @Test + void aNullReceiverStaysNull() { + assertThat(method.execute(null, null, null, new Object[] { "A" })).isNull(); + assertThat(method.execute(null, null, null, new Object[] { null, "A" })).isNull(); + } + + @Test + void appendsEveryArgumentInOrder() { + assertThat(method.execute("x", null, null, new Object[] { "A", 1, true })).isEqualTo("xA1true"); + } +} diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodSplitTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodSplitTest.java index 62b40d1dee8..b317c29557d 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodSplitTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodSplitTest.java @@ -28,6 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat; +@SuppressWarnings("unchecked") class SQLMethodSplitTest { private SQLMethod method; @@ -52,9 +53,9 @@ void testNull() { void splitByComma() { //null separator final Object result = method.execute("first,second", null, null, new Object[]{","}); - assertThat(result).isInstanceOf(String[].class); - final String[] splitted = (String[]) result; - assertThat(splitted).hasSize(2).contains("first", "second"); + // A List, not a String[] (issue #7027): the same answer as the split() function and the Cypher split() + assertThat(result).isInstanceOf(List.class); + assertThat((List) result).containsExactly("first", "second"); } @Test @@ -65,9 +66,8 @@ void delimiterIsTreatedLiterallyNotAsRegex() { // regex-metacharacter behavior (a "." delimiter split on every character instead of the literal dot) and // to catastrophic backtracking for a maliciously-crafted delimiter. final Object result = method.execute("a.b.c", null, null, new Object[] { "." }); - assertThat(result).isInstanceOf(String[].class); - final String[] splitted = (String[]) result; - assertThat(splitted).containsExactly("a", "b", "c"); + assertThat(result).isInstanceOf(List.class); + assertThat((List) result).containsExactly("a", "b", "c"); } @Disabled 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 7b6a6bf7022..5b02cbe83a7 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 @@ -1184,8 +1184,8 @@ public void updateRecordNoLock(final Record record, final boolean discardRecordA } @Override - public void deleteRecordNoLock(final Record record) { - proxied.deleteRecordNoLock(record); + public boolean deleteRecordNoLock(final Record record) { + return proxied.deleteRecordNoLock(record); } @Override diff --git a/server/src/main/java/com/arcadedb/server/ArcadeDBServer.java b/server/src/main/java/com/arcadedb/server/ArcadeDBServer.java index 86520d065bf..0dd3082ff68 100644 --- a/server/src/main/java/com/arcadedb/server/ArcadeDBServer.java +++ b/server/src/main/java/com/arcadedb/server/ArcadeDBServer.java @@ -107,13 +107,33 @@ public enum STATUS {OFFLINE, STARTING, ONLINE, SHUTTING_DOWN} public static final String RESERVED_DATABASE_PREFIX = "."; /** - * How long the shutdown hook waits for the lifecycle lock when the server is still {@code STARTING} - * (issue #5418). Short on purpose: a server that never came up has nothing worth flushing, and the - * most likely holder of the lock is the starting thread that triggered this shutdown by calling - * {@code System.exit()} - which will never release it. Long enough only to lose a benign race with a - * start that is about to complete. + * How long the shutdown hook waits for the lifecycle lock when the server is still {@code STARTING} and has not + * opened any database yet (issues #5418, #7025). Short on purpose: with no database open there is nothing worth + * flushing, so the wait only has to be long enough to lose a benign race with a start that is about to complete. + * Once {@code loadDatabases()} has run - which happens well before the status turns {@code ONLINE}, ahead of the + * HTTP service and every plugin phase - the bound is {@code arcadedb.server.shutdownTimeout} instead, because + * cutting the wait short then leaves every open database to a WAL replay on the next start. */ - private static final long SHUTDOWN_HOOK_STARTING_TIMEOUT_MS = 2_000; + // @VisibleForTesting + static final long SHUTDOWN_HOOK_STARTING_TIMEOUT_MS = 2_000; + + /** + * Which bound the shutdown hook applies while waiting for the lifecycle lock (issue #7025). Chosen by + * {@link #chooseShutdownHookBound}, and reported by name in the WARNING the hook emits when the wait expires, so + * the operator is told which setting - if any - governs the wait they just saw. + */ + enum ShutdownHookBound { + /** + * The thread holding the lock is itself parked inside {@code System.exit()}, waiting for this very hook to + * finish (issue #5418: Apache Ratis exits from inside {@code start()} on a port conflict). It can never release + * the lock, so waiting any time at all only delays the exit. + */ + HOLDER_EXITING, + /** {@code STARTING} with no database open yet: nothing to flush, wait only {@link #SHUTDOWN_HOOK_STARTING_TIMEOUT_MS}. */ + STARTING_NO_DATABASES, + /** Databases are open, or the status left {@code STARTING}: wait up to {@code arcadedb.server.shutdownTimeout}. */ + CONFIGURED + } private final ContextConfiguration configuration; private final String serverName; private String hostAddress; @@ -149,6 +169,12 @@ public enum STATUS {OFFLINE, STARTING, ONLINE, SHUTTING_DOWN} // startup failure that calls System.exit() from inside start() would otherwise deadlock the JVM // permanently (issue #5418). Reentrant because start() calls stop() on its failure path. private final ReentrantLock lifecycleLock = new ReentrantLock(); + /** + * The thread currently holding {@link #lifecycleLock} through {@link #start()} or {@link #stop()}, or null. Read + * by the shutdown hook (issue #7025): when that thread is parked inside {@code System.exit()} it is waiting for the + * hook itself and will never release the lock, so the hook does not wait for it at all. + */ + private volatile Thread lifecycleOwner; private final List testEventListeners = new ArrayList<>(); private volatile STATUS status = STATUS.OFFLINE; private final AtomicBoolean snapshotInstallInProgress = new AtomicBoolean(false); @@ -228,6 +254,7 @@ public void start() { // Reentrant because start() calls stop() on its own failure path. lifecycleLock.lock(); try { + recordLifecycleOwner(); startInternal(); } catch (final RuntimeException | Error e) { // A start that fails after the metrics install (a plugin, the HTTP service, the databases) does not @@ -239,10 +266,23 @@ public void start() { CodeUtils.executeIgnoringExceptions(this::stopMetrics, "Error on stopping the metrics collection", false); throw e; } finally { + clearLifecycleOwner(); lifecycleLock.unlock(); } } + /** Publishes the current thread as {@link #lifecycleOwner} on the outermost acquisition of the lifecycle lock. */ + private void recordLifecycleOwner() { + if (lifecycleLock.getHoldCount() == 1) + lifecycleOwner = Thread.currentThread(); + } + + /** Counterpart of {@link #recordLifecycleOwner()}, called before the outermost release. */ + private void clearLifecycleOwner() { + if (lifecycleLock.getHoldCount() == 1) + lifecycleOwner = null; + } + private void startInternal() { LogManager.instance().setContext(getServerName()); @@ -512,8 +552,10 @@ private Set getAllPluginNames() { public void stop() { lifecycleLock.lock(); try { + recordLifecycleOwner(); stopInternal(); } finally { + clearLifecycleOwner(); lifecycleLock.unlock(); } } @@ -529,30 +571,38 @@ public void stop() { * that can never be released - a deadlock in which the JVM cannot exit and only SIGKILL ends it. Any * startup port conflict was enough to trigger it. *

- * So the wait is bounded, and the bound depends on what the mutex holder is likely doing: + * So the wait is bounded, and the bound depends on what the mutex holder is likely doing - see + * {@link ShutdownHookBound} and {@link #chooseShutdownHookBound} (issue #7025): *

    - *
  • {@code STARTING}: the server never came up, so there is nothing worth flushing and the holder - * is very likely the thread that triggered this shutdown. Wait only briefly, for the benign race - * where a concurrent start is about to finish.
  • - *
  • anything else: a legitimate concurrent {@code stop()} may be flushing databases - and so may the - * tail of a {@code start()} that already flipped the status to {@code ONLINE} but has not released - * the mutex yet - and cutting that short would cost a WAL recovery on the next open. Wait up to - * {@code arcadedb.server.shutdownTimeout}.
  • + *
  • the holder is parked inside {@code System.exit()}: it is waiting for this hook and can never + * release the mutex, so there is nothing to wait for at all;
  • + *
  • {@code STARTING} with no database open yet: nothing worth flushing, so wait only briefly, for + * the benign race where a concurrent start is about to finish;
  • + *
  • anything else - databases are open, even though the status may still read {@code STARTING} + * because {@code loadDatabases()} runs long before the HTTP service, the plugins and the HA + * bring-up - a legitimate concurrent {@code stop()} may be flushing them, and so may the tail of a + * {@code start()} that has not released the mutex yet. Cutting that short would cost a WAL + * recovery on every open database at the next start (the #7025 report: a liveness probe killing + * a pod mid-start left three databases to replay their WAL on every restart, each one slower than + * the last). Wait up to {@code arcadedb.server.shutdownTimeout}.
  • *
* If the mutex never arrives, the databases are left as they are: the next open replays the WAL, * exactly as after a kill. That is strictly better than a process that cannot be stopped. */ - private void stopFromShutdownHook() { + // @VisibleForTesting + void stopFromShutdownHook() { // Snapshot the status once: start() can flip it STARTING -> ONLINE while still holding the // lifecycle lock, so re-reading it after the bounded wait could describe a bound that was not // the one actually applied. The warning must be built from the same snapshot that chose the bound. final STATUS observedStatus = status; - final long timeout = observedStatus == STATUS.STARTING - ? SHUTDOWN_HOOK_STARTING_TIMEOUT_MS - : configuration.getValueAsLong(GlobalConfiguration.SERVER_SHUTDOWN_TIMEOUT); + final Thread owner = lifecycleOwner; + final boolean holderExiting = + owner != null && owner != Thread.currentThread() && isRunningShutdownHooks(owner.getStackTrace()); + final ShutdownHookBound bound = chooseShutdownHookBound(observedStatus, !databases.isEmpty(), holderExiting); + final long timeout = shutdownHookTimeoutMs(bound); if (!awaitLifecycleLock(lifecycleLock, timeout)) { - LogManager.instance().log(this, Level.WARNING, shutdownHookLockTimeoutWarning(timeout, observedStatus)); + LogManager.instance().log(this, Level.WARNING, shutdownHookLockTimeoutWarning(timeout, observedStatus, bound)); return; } @@ -563,19 +613,72 @@ private void stopFromShutdownHook() { } } + /** + * Picks the bound the shutdown hook waits under (issue #7025). The question that decides it is not "is the + * status {@code STARTING}?" but "is there an open database to flush?": databases open at the start of + * {@code startInternal()}, long before the status turns {@code ONLINE}, so a status-only rule applied the short + * fixed bound to a server that had everything worth flushing already open. Static and side-effect free so every + * cell of the decision can be pinned without driving a real JVM shutdown. + * + * @param status the server status observed when the hook started + * @param databasesOpen whether at least one database is registered + * @param holderExiting whether the lifecycle lock holder is parked in {@code System.exit()} - see + * {@link #isRunningShutdownHooks} + */ + // @VisibleForTesting + static ShutdownHookBound chooseShutdownHookBound(final STATUS status, final boolean databasesOpen, + final boolean holderExiting) { + if (holderExiting) + return ShutdownHookBound.HOLDER_EXITING; + if (status == STATUS.STARTING && !databasesOpen) + return ShutdownHookBound.STARTING_NO_DATABASES; + return ShutdownHookBound.CONFIGURED; + } + + private long shutdownHookTimeoutMs(final ShutdownHookBound bound) { + return switch (bound) { + case HOLDER_EXITING -> 0; + case STARTING_NO_DATABASES -> SHUTDOWN_HOOK_STARTING_TIMEOUT_MS; + case CONFIGURED -> configuration.getValueAsLong(GlobalConfiguration.SERVER_SHUTDOWN_TIMEOUT); + }; + } + + /** + * Whether the given stack belongs to a thread that is running the JVM shutdown hooks, i.e. one parked inside + * {@code System.exit()} / {@code Runtime.exit()} / {@code Shutdown.exit()} waiting for the hooks - this one + * included - to finish. Such a thread holding the lifecycle lock is the #5418 deadlock shape, and it will never + * release the lock however long the hook waits. + */ + // @VisibleForTesting + static boolean isRunningShutdownHooks(final StackTraceElement[] stack) { + for (final StackTraceElement frame : stack) { + final String className = frame.getClassName(); + if ("java.lang.Shutdown".equals(className)) + return true; + if ("exit".equals(frame.getMethodName()) && ("java.lang.Runtime".equals(className) || "java.lang.System".equals( + className))) + return true; + } + return false; + } + /** * Builds the WARNING for a shutdown hook that could not acquire the lifecycle lock. The advice depends - * on which bound was in effect: while {@code STARTING} the wait is the fixed + * on which bound was in effect: under {@link ShutdownHookBound#STARTING_NO_DATABASES} the wait is the fixed * {@link #SHUTDOWN_HOOK_STARTING_TIMEOUT_MS}, so pointing the operator at * {@code arcadedb.server.shutdownTimeout} would name the one setting that provably had no effect on - * that branch (issue #6981). Extracted so the message can be tested without driving a real JVM shutdown. + * that branch (issue #6981); under {@link ShutdownHookBound#HOLDER_EXITING} no wait could have helped at all. + * Extracted so the message can be tested without driving a real JVM shutdown. */ // @VisibleForTesting - static String shutdownHookLockTimeoutWarning(final long timeout, final STATUS status) { - final String hint = status == STATUS.STARTING ? - "This wait during STARTING is a fixed " + SHUTDOWN_HOOK_STARTING_TIMEOUT_MS - + "ms bound not governed by arcadedb.server.shutdownTimeout." : - "Raise arcadedb.server.shutdownTimeout if a legitimate shutdown needs longer."; + static String shutdownHookLockTimeoutWarning(final long timeout, final STATUS status, final ShutdownHookBound bound) { + final String hint = switch (bound) { + case HOLDER_EXITING -> "The thread holding the lock is itself inside System.exit() waiting for this hook, so no " + + "wait could have acquired it: the hook did not wait."; + case STARTING_NO_DATABASES -> "This wait during STARTING with no database open yet is a fixed " + + SHUTDOWN_HOOK_STARTING_TIMEOUT_MS + "ms bound not governed by arcadedb.server.shutdownTimeout."; + case CONFIGURED -> "Raise arcadedb.server.shutdownTimeout if a legitimate shutdown needs longer."; + }; return """ Could not acquire the server lifecycle lock within %dms while status is %s, so the shutdown hook is \ returning WITHOUT a graceful stop and the JVM will exit. Another thread is inside start()/stop() and \ diff --git a/server/src/main/java/com/arcadedb/server/ServerDatabase.java b/server/src/main/java/com/arcadedb/server/ServerDatabase.java index 256c7b9aaa7..c83c8c5d995 100644 --- a/server/src/main/java/com/arcadedb/server/ServerDatabase.java +++ b/server/src/main/java/com/arcadedb/server/ServerDatabase.java @@ -353,8 +353,8 @@ public void updateRecordNoLock(final Record record, final boolean discardRecordA } @Override - public void deleteRecordNoLock(final Record record) { - wrapped.deleteRecordNoLock(record); + public boolean deleteRecordNoLock(final Record record) { + return wrapped.deleteRecordNoLock(record); } @Override diff --git a/server/src/test/java/com/arcadedb/server/Issue6981ShutdownHookHintTest.java b/server/src/test/java/com/arcadedb/server/Issue6981ShutdownHookHintTest.java index 5ab9a8d38f6..be10825aa8f 100644 --- a/server/src/test/java/com/arcadedb/server/Issue6981ShutdownHookHintTest.java +++ b/server/src/test/java/com/arcadedb/server/Issue6981ShutdownHookHintTest.java @@ -38,7 +38,8 @@ class Issue6981ShutdownHookHintTest { @Test void startingWarningMustNotAdviseRaisingTheSettingItIgnores() { - final String message = ArcadeDBServer.shutdownHookLockTimeoutWarning(2_000, ArcadeDBServer.STATUS.STARTING); + final String message = ArcadeDBServer.shutdownHookLockTimeoutWarning(2_000, ArcadeDBServer.STATUS.STARTING, + ArcadeDBServer.ShutdownHookBound.STARTING_NO_DATABASES); assertThat(message).contains("2000ms").contains("STARTING"); assertThat(message) @@ -53,7 +54,8 @@ void startingWarningMustNotAdviseRaisingTheSettingItIgnores() { void warningOutsideStartingKeepsTheRaiseHint() { for (final ArcadeDBServer.STATUS status : new ArcadeDBServer.STATUS[] { ArcadeDBServer.STATUS.OFFLINE, ArcadeDBServer.STATUS.ONLINE, ArcadeDBServer.STATUS.SHUTTING_DOWN }) { - final String message = ArcadeDBServer.shutdownHookLockTimeoutWarning(60_000, status); + final String message = ArcadeDBServer.shutdownHookLockTimeoutWarning(60_000, status, + ArcadeDBServer.ShutdownHookBound.CONFIGURED); assertThat(message).contains("60000ms").contains(status.toString()); assertThat(message) @@ -82,7 +84,8 @@ void settingDescriptionMustQuoteTheSameStartingBoundTheHookApplies() { // keeps the two in step, and a description quoting a bound the hook no longer applies is exactly the // defect #6981 reports - one module edit away from coming back. final Matcher bound = Pattern.compile("fixed (\\d+)ms bound") - .matcher(ArcadeDBServer.shutdownHookLockTimeoutWarning(2_000, ArcadeDBServer.STATUS.STARTING)); + .matcher(ArcadeDBServer.shutdownHookLockTimeoutWarning(2_000, ArcadeDBServer.STATUS.STARTING, + ArcadeDBServer.ShutdownHookBound.STARTING_NO_DATABASES)); assertThat(bound.find()).as("the STARTING warning must state the fixed bound it applied").isTrue(); diff --git a/server/src/test/java/com/arcadedb/server/Issue7025ShutdownHookOpenDatabasesBoundTest.java b/server/src/test/java/com/arcadedb/server/Issue7025ShutdownHookOpenDatabasesBoundTest.java new file mode 100644 index 00000000000..e57d09695e2 --- /dev/null +++ b/server/src/test/java/com/arcadedb/server/Issue7025ShutdownHookOpenDatabasesBoundTest.java @@ -0,0 +1,232 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed 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. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.server; + +import com.arcadedb.ContextConfiguration; +import com.arcadedb.GlobalConfiguration; +import com.arcadedb.database.Database; +import com.arcadedb.database.DatabaseFactory; +import com.arcadedb.server.ArcadeDBServer.STATUS; +import com.arcadedb.server.ArcadeDBServer.ShutdownHookBound; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.io.File; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Regression test for issue #7025: the shutdown hook applied its fixed 2000ms STARTING bound to a server whose + * databases were already open - they open at the top of {@code startInternal()}, long before the status turns ONLINE - + * so a shutdown signal arriving during the HTTP/plugin/HA bring-up gave up on the lifecycle lock after two seconds and + * left every open database to a WAL replay on the next start. + *

+ * The bound now follows the thing it protects: no database open, short fixed wait; databases open, the configured + * {@code arcadedb.server.shutdownTimeout}; lock holder parked in {@code System.exit()} (the #5418 deadlock shape), no + * wait at all. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +class Issue7025ShutdownHookOpenDatabasesBoundTest extends StaticBaseServerTest { + private static final String DATABASE_DIRECTORY = "./target/databases"; + private static final String DATABASE = "issue7025"; + + /** + * How long the plugin below holds {@code start()} once the hook is waiting for the lock: longer than the fixed + * 2000ms bound the hook used to apply, so the old behaviour - giving up and leaving the databases open - has time + * to happen if it ever comes back. Not a latency assertion: nothing measures elapsed time here. + */ + private static final long START_HOLD_MS = ArcadeDBServer.SHUTDOWN_HOOK_STARTING_TIMEOUT_MS + 1_000; + + @Test + void theBoundFollowsTheOpenDatabasesNotTheStatus() { + assertThat(ArcadeDBServer.chooseShutdownHookBound(STATUS.STARTING, false, false)) + .as("STARTING with nothing open: nothing to flush, short fixed wait").isEqualTo(ShutdownHookBound.STARTING_NO_DATABASES); + assertThat(ArcadeDBServer.chooseShutdownHookBound(STATUS.STARTING, true, false)) + .as("STARTING with databases open: the configured timeout, exactly as when ONLINE").isEqualTo(ShutdownHookBound.CONFIGURED); + for (final STATUS status : new STATUS[] { STATUS.OFFLINE, STATUS.ONLINE, STATUS.SHUTTING_DOWN }) + for (final boolean open : new boolean[] { false, true }) + assertThat(ArcadeDBServer.chooseShutdownHookBound(status, open, false)).as(status + " open=" + open) + .isEqualTo(ShutdownHookBound.CONFIGURED); + // THE #5418 SHAPE WINS OVER EVERYTHING: THE HOLDER CAN NEVER RELEASE THE LOCK, SO NO WAIT CAN HELP + assertThat(ArcadeDBServer.chooseShutdownHookBound(STATUS.STARTING, true, true)).isEqualTo(ShutdownHookBound.HOLDER_EXITING); + assertThat(ArcadeDBServer.chooseShutdownHookBound(STATUS.ONLINE, true, true)).isEqualTo(ShutdownHookBound.HOLDER_EXITING); + } + + @Test + void aThreadParkedInSystemExitIsRecognisedFromItsStack() { + assertThat(ArcadeDBServer.isRunningShutdownHooks(new StackTraceElement[] { + new StackTraceElement("java.lang.Object", "wait", "Object.java", 1), + new StackTraceElement("java.lang.Thread", "join", "Thread.java", 1), + new StackTraceElement("java.lang.ApplicationShutdownHooks", "runHooks", "ApplicationShutdownHooks.java", 1), + new StackTraceElement("java.lang.Shutdown", "runHooks", "Shutdown.java", 1), + new StackTraceElement("java.lang.Shutdown", "exit", "Shutdown.java", 1), + new StackTraceElement("java.lang.Runtime", "exit", "Runtime.java", 1), + new StackTraceElement("java.lang.System", "exit", "System.java", 1), + new StackTraceElement("org.apache.ratis.util.ExitUtils", "terminate", "ExitUtils.java", 1), + new StackTraceElement(ArcadeDBServer.class.getName(), "startInternal", "ArcadeDBServer.java", 1) })).isTrue(); + + assertThat(ArcadeDBServer.isRunningShutdownHooks(new StackTraceElement[] { + new StackTraceElement("java.net.ServerSocket", "bind", "ServerSocket.java", 1), + new StackTraceElement(ArcadeDBServer.class.getName(), "startInternal", "ArcadeDBServer.java", 1), + new StackTraceElement(ArcadeDBServer.class.getName(), "start", "ArcadeDBServer.java", 1) })) + .as("a start() that is merely progressing must be waited for").isFalse(); + assertThat(ArcadeDBServer.isRunningShutdownHooks(new StackTraceElement[0])).isFalse(); + } + + @Test + void theWarningNamesTheBoundThatWasApplied() { + final String starting = ArcadeDBServer.shutdownHookLockTimeoutWarning(2_000, STATUS.STARTING, + ShutdownHookBound.STARTING_NO_DATABASES); + assertThat(starting).contains("no database open yet").contains("fixed 2000ms bound") + .doesNotContain("Raise arcadedb.server.shutdownTimeout"); + + final String configured = ArcadeDBServer.shutdownHookLockTimeoutWarning(60_000, STATUS.STARTING, ShutdownHookBound.CONFIGURED); + assertThat(configured).as("with databases open the setting IS the bound, even while STARTING") + .contains("Raise arcadedb.server.shutdownTimeout").doesNotContain("fixed"); + + final String exiting = ArcadeDBServer.shutdownHookLockTimeoutWarning(0, STATUS.STARTING, ShutdownHookBound.HOLDER_EXITING); + assertThat(exiting).contains("inside System.exit()").contains("did not wait") + .doesNotContain("Raise arcadedb.server.shutdownTimeout"); + } + + /** + * The end-to-end shape of the report: a shutdown signal arriving while the server is still STARTING but has its + * databases open. The plugin holds {@code start()} for longer than the old fixed bound with the hook already waiting + * on the lock; the hook must outlast that hold, acquire the lock once {@code start()} releases it and perform the + * full graceful stop - which is what closes the database cleanly. + */ + @Test + @Tag("slow") + @Timeout(120) + void aHookArrivingWhileStartingWithOpenDatabasesWaitsForTheLockAndStopsCleanly() throws Exception { + GlobalConfiguration.SERVER_DATABASE_DIRECTORY.setValue(DATABASE_DIRECTORY); + final File databaseDir = new File(DATABASE_DIRECTORY, DATABASE); + try (final Database db = new DatabaseFactory(databaseDir.getPath()).create()) { + db.getSchema().createDocumentType("Doc"); + } + assertThat(new File(databaseDir, "database.lck")).as("a cleanly closed database leaves no lock marker").doesNotExist(); + + final ContextConfiguration config = new ContextConfiguration(); + config.setValue(GlobalConfiguration.SERVER_NAME, "ArcadeDB_0"); + config.setValue(GlobalConfiguration.SERVER_DATABASE_DIRECTORY, DATABASE_DIRECTORY); + config.setValue(GlobalConfiguration.SERVER_ROOT_PATH, "./target"); + config.setValue(GlobalConfiguration.SERVER_ROOT_PASSWORD, DEFAULT_PASSWORD_FOR_TESTS); + config.setValue(GlobalConfiguration.SERVER_HTTP_INCOMING_HOST, "localhost"); + config.setValue(GlobalConfiguration.SERVER_SHUTDOWN_TIMEOUT, 60_000L); + config.setValue(GlobalConfiguration.SERVER_PLUGINS, "hook-during-start:" + HookDuringStartPlugin.class.getName()); + + HookDuringStartPlugin.reset(); + final ArcadeDBServer server = new ArcadeDBServer(config); + try { + server.start(); + + final Thread hook = HookDuringStartPlugin.hook.get(); + assertThat(hook).as("the plugin must have fired the hook while start() was in progress").isNotNull(); + hook.join(60_000); + assertThat(hook.isAlive()).as("the hook must return once start() releases the lock").isFalse(); + assertThat(HookDuringStartPlugin.hookFailure.get()).isNull(); + + assertThat(HookDuringStartPlugin.statusSeenByTheHook.get()) + .as("the shape under test: the hook ran while the server was still STARTING").isEqualTo(STATUS.STARTING); + assertThat(HookDuringStartPlugin.databasesSeenByTheHook.get()) + .as("...with the databases already open").contains(DATABASE); + + // THE OLD 2000ms BOUND EXPIRED DURING THE HOLD AND THE HOOK RETURNED WITHOUT STOPPING: THE SERVER WOULD STILL + // BE ONLINE HERE AND THE DATABASE STILL OPEN. THE FIX WAITS THE CONFIGURED BOUND, SO THE HOOK STOPPED IT. + assertThat(server.getStatus()).as("the hook performed the graceful stop").isEqualTo(STATUS.OFFLINE); + assertThat(server.getDatabaseNames()).isEmpty(); + assertThat(new File(databaseDir, "database.lck")).as("the database was closed cleanly, so no WAL replay next time") + .doesNotExist(); + } finally { + if (server.getStatus() != STATUS.OFFLINE) + server.stop(); + } + } + + /** + * Fires {@code stopFromShutdownHook()} from another thread while {@code start()} is inside the plugin phase - i.e. + * after {@code loadDatabases()}, with the status still STARTING - then holds {@code start()} for + * {@link #START_HOLD_MS} once the hook is provably waiting. Discovered through the {@code ServiceLoader} registration + * in {@code META-INF/services/com.arcadedb.server.ServerPlugin} of the test resources and installed only when + * {@code SERVER_PLUGINS} names it, so it needs the public no-argument constructor. + */ + public static class HookDuringStartPlugin implements ServerPlugin { + static final AtomicReference hook = new AtomicReference<>(); + static final AtomicReference hookFailure = new AtomicReference<>(); + static final AtomicReference statusSeenByTheHook = new AtomicReference<>(); + static final AtomicReference> databasesSeenByTheHook = new AtomicReference<>(); + + private ArcadeDBServer server; + + static void reset() { + hook.set(null); + hookFailure.set(null); + statusSeenByTheHook.set(null); + databasesSeenByTheHook.set(null); + } + + @Override + public void configure(final ArcadeDBServer arcadeDBServer, final ContextConfiguration configuration) { + this.server = arcadeDBServer; + } + + @Override + public void startService() { + final CountDownLatch hookStarted = new CountDownLatch(1); + final Thread thread = new Thread(() -> { + try { + statusSeenByTheHook.set(server.getStatus()); + // A COPY: getDatabaseNames() IS A LIVE VIEW THAT THE STOP BELOW EMPTIES + databasesSeenByTheHook.set(new HashSet<>(server.getDatabaseNames())); + hookStarted.countDown(); + server.stopFromShutdownHook(); + } catch (final Throwable t) { + hookFailure.set(t); + } + }, "issue7025-shutdown-hook"); + thread.setDaemon(true); + hook.set(thread); + thread.start(); + + try { + hookStarted.await(30, TimeUnit.SECONDS); + // THE HOOK IS NOW WAITING FOR THE LIFECYCLE LOCK THIS start() HOLDS: OUTLAST THE OLD FIXED BOUND + Thread.sleep(START_HOLD_MS); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @Override + public void stopService() { + } + + @Override + public PluginInstallationPriority getInstallationPriority() { + return PluginInstallationPriority.BEFORE_HTTP_ON; + } + } +} diff --git a/server/src/test/resources/META-INF/services/com.arcadedb.server.ServerPlugin b/server/src/test/resources/META-INF/services/com.arcadedb.server.ServerPlugin index 55d4ad5f074..045e6134c22 100644 --- a/server/src/test/resources/META-INF/services/com.arcadedb.server.ServerPlugin +++ b/server/src/test/resources/META-INF/services/com.arcadedb.server.ServerPlugin @@ -1,2 +1,3 @@ com.arcadedb.server.http.ArrayPayloadTestPlugin com.arcadedb.server.plugin.DatabaseLifecycleTestPlugin +com.arcadedb.server.Issue7025ShutdownHookOpenDatabasesBoundTest$HookDuringStartPlugin From 7acba3e80aff41f3dfa469074e945e0f18793afa Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 00:41:57 -0400 Subject: [PATCH 02/10] Address code review: admit a bare Iterator receiver in listReceiverOrNull as its comment already claimed, and compare the lifecycle owner with equals() (Codacy) --- .../com/arcadedb/query/sql/method/AbstractSQLMethod.java | 4 +++- .../query/sql/method/collection/SQLMethodJoinTest.java | 5 +++++ server/src/main/java/com/arcadedb/server/ArcadeDBServer.java | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java b/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java index 94cb7df7ceb..3267fcd83d0 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java @@ -177,7 +177,9 @@ protected String numericTextOrNull(final Object value) { * @return the receiver as a list, or {@code null} when it is not a collection */ protected static List listReceiverOrNull(final Object value) { - if (value == null || value instanceof Map || !MultiValue.isMultiValue(value)) + // A BARE Iterator IS NOT A MultiValue.isMultiValue() (THAT TEST COVERS Iterable, NOT Iterator), SO IT IS ADMITTED + // EXPLICITLY OR THE MATERIALISATION BELOW WOULD NEVER SEE ONE + if (value == null || value instanceof Map || !(MultiValue.isMultiValue(value) || value instanceof Iterator)) return null; final List list = MultiValue.getMultiValueAsList(value); diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodJoinTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodJoinTest.java index 74173f72301..053a3091079 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodJoinTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodJoinTest.java @@ -97,4 +97,9 @@ void joinAnIterableReceiver() { final Iterable iterable = () -> List.of("a", "b").iterator(); assertThat(method.execute(iterable, null, null, new Object[] { "|" })).isEqualTo("a|b"); } + + @Test + void joinAnIteratorReceiver() { + assertThat(method.execute(List.of("a", "b").iterator(), null, null, new Object[] { "|" })).isEqualTo("a|b"); + } } diff --git a/server/src/main/java/com/arcadedb/server/ArcadeDBServer.java b/server/src/main/java/com/arcadedb/server/ArcadeDBServer.java index 0dd3082ff68..4805341272e 100644 --- a/server/src/main/java/com/arcadedb/server/ArcadeDBServer.java +++ b/server/src/main/java/com/arcadedb/server/ArcadeDBServer.java @@ -597,7 +597,7 @@ void stopFromShutdownHook() { final STATUS observedStatus = status; final Thread owner = lifecycleOwner; final boolean holderExiting = - owner != null && owner != Thread.currentThread() && isRunningShutdownHooks(owner.getStackTrace()); + owner != null && !owner.equals(Thread.currentThread()) && isRunningShutdownHooks(owner.getStackTrace()); final ShutdownHookBound bound = chooseShutdownHookBound(observedStatus, !databases.isEmpty(), holderExiting); final long timeout = shutdownHookTimeoutMs(bound); From 37595252ce315c6109f7b04db2072070901c71b8 Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 00:47:15 -0400 Subject: [PATCH 03/10] Address code review: retired-worker regression test for DatabaseAsyncBrowseIterator, stall-discounted waits in the #7004 test, final on loop variables and the stub parameter --- .../method/collection/SQLMethodTransform.java | 8 +- .../Issue7004AsyncParallelLevelTest.java | 152 ++++++++++++++---- .../collection/SQLMethodTransformTest.java | 2 +- 3 files changed, 125 insertions(+), 37 deletions(-) diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodTransform.java b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodTransform.java index 7a89b55be19..c294c825fe8 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodTransform.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodTransform.java @@ -67,10 +67,10 @@ public Object execute(final Object value, final Identifiable currentRecord, fina if (value instanceof Set set) { final Set newSet = new HashSet<>(set.size()); - for (Object o : set) { + for (final Object o : set) { Object transformed = o; - for (SQLMethod m : transformers) + for (final SQLMethod m : transformers) transformed = m.execute(transformed, null, context, EMPTY_ARGS); newSet.add(transformed); @@ -82,10 +82,10 @@ public Object execute(final Object value, final Identifiable currentRecord, fina final List list = listReceiverOrNull(value); if (list != null) { final List newList = new ArrayList<>(list.size()); - for (Object o : list) { + for (final Object o : list) { Object transformed = o; - for (SQLMethod m : transformers) + for (final SQLMethod m : transformers) transformed = m.execute(transformed, null, context, EMPTY_ARGS); newList.add(transformed); diff --git a/engine/src/test/java/com/arcadedb/database/async/Issue7004AsyncParallelLevelTest.java b/engine/src/test/java/com/arcadedb/database/async/Issue7004AsyncParallelLevelTest.java index d8bc01e0b34..952682f2606 100644 --- a/engine/src/test/java/com/arcadedb/database/async/Issue7004AsyncParallelLevelTest.java +++ b/engine/src/test/java/com/arcadedb/database/async/Issue7004AsyncParallelLevelTest.java @@ -21,13 +21,19 @@ import com.arcadedb.GlobalConfiguration; import com.arcadedb.TestHelper; import com.arcadedb.database.DatabaseInternal; +import com.arcadedb.database.Identifiable; +import com.arcadedb.database.RID; +import com.arcadedb.utility.StallAwareStopwatch; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; import static org.assertj.core.api.Assertions.assertThat; @@ -36,17 +42,23 @@ *
    *
  1. {@code backPressurePercentage} is executor-wide but was (re)read from the configuration inside every * {@code AsyncThread} constructor, so each resize silently reverted whatever {@code setBackPressure()} asked for.
  2. - *
  3. {@code DatabaseAsyncScanBucket} bailed on the worker's {@code shutdown} flag, which a shrinking - * {@code setParallelLevel()} sets on the workers it retires while they drain their queues - so a scan task queued on - * a retired worker stopped after its first record while {@code scanType()} still reported success.
  4. + *
  5. {@code DatabaseAsyncScanBucket} (and {@code DatabaseAsyncBrowseIterator}, the same shape) bailed on the + * worker's {@code shutdown} flag, which a shrinking {@code setParallelLevel()} sets on the workers it retires while + * they drain their queues - so a scan task queued on a retired worker stopped after its first record while + * {@code scanType()} still reported success.
  6. *
+ * The success-path waits are stall-discounted slices ({@link StallAwareStopwatch#effectiveMs()}), so a JVM-wide pause + * late in a long run cannot expire them (#6260); {@code @Timeout} stays as the plain hang detector. * * @author Luca Garulli (l.garulli@arcadedata.com) */ class Issue7004AsyncParallelLevelTest extends TestHelper { - private static final String TYPE = "Issue7004Doc"; - private static final int RECORDS = 500; + private static final String TYPE = "Issue7004Doc"; + private static final int RECORDS = 500; + /** Stall-discounted budget of every success-path wait: generous, since a wider bound cannot turn a passing run red. */ + private static final long BUDGET_MS = 30_000; + private static final long POLL_MS = 10; @Test void setParallelLevelKeepsTheBackPressureAskedFor() { @@ -69,12 +81,7 @@ void setParallelLevelKeepsTheBackPressureAskedFor() { void aScanQueuedOnARetiredWorkerRunsToCompletion() throws Exception { final DatabaseAsyncExecutorImpl async = (DatabaseAsyncExecutorImpl) ((DatabaseInternal) database).async(); async.setParallelLevel(2); - - database.getSchema().createDocumentType(TYPE, 2); - database.transaction(() -> { - for (int i = 0; i < RECORDS; i++) - database.newDocument(TYPE).set("id", i).save(); - }); + createRecords(); // PARK BOTH WORKERS ON A GATE, SO THE SCAN TASKS SCHEDULED NEXT ARE PROVABLY STILL QUEUED - NOT RUN - WHEN THE // SHRINK RETIRES ONE OF THE TWO. WHICH BUCKET LANDS ON WHICH SLOT DOES NOT MATTER: BOTH SLOTS ARE GATED. @@ -82,7 +89,7 @@ void aScanQueuedOnARetiredWorkerRunsToCompletion() throws Exception { final CountDownLatch release = new CountDownLatch(1); for (int slot = 0; slot < 2; slot++) assertThat(async.scheduleTask(slot, AsyncTestTasks.awaitTask(gatesEntered, release), true, 0)).isTrue(); - assertThat(gatesEntered.await(30, TimeUnit.SECONDS)).as("both workers must be parked on their gate").isTrue(); + assertThat(awaited(gatesEntered)).as("both workers must be parked on their gate").isTrue(); // THE SCAN, FROM ITS OWN THREAD: scanType() BLOCKS UNTIL EVERY BUCKET TASK HAS COMPLETED final AtomicInteger scanned = new AtomicInteger(); @@ -100,14 +107,63 @@ void aScanQueuedOnARetiredWorkerRunsToCompletion() throws Exception { scanner.start(); // WAIT UNTIL BOTH BUCKET TASKS SIT IN THE QUEUES BEHIND THE GATES - final long deadline = System.currentTimeMillis() + 30_000; - while (async.getStats().queueSize < 2 && System.currentTimeMillis() < deadline) - Thread.sleep(10); - assertThat(async.getStats().queueSize).as("the two bucket scans must be queued behind the gates").isEqualTo(2); - - // SHRINK TO ONE WORKER, FROM ITS OWN THREAD BECAUSE THE RESIZE WAITS FOR THE RETIRED WORKER TO DRAIN - WHICH IT - // CANNOT DO UNTIL THE GATE IS RELEASED. THE RETIRED WORKER NOW CARRIES THE shutdown FLAG WITH THE SCAN OF ONE - // BUCKET STILL IN ITS QUEUE: THE SHAPE THE BUG NEEDS. + assertThat(awaited(() -> async.getStats().queueSize >= 2)).as("the two bucket scans must be queued behind the gates") + .isTrue(); + + final Thread resizer = shrinkToOneWorkerWhileGated(async); + + release.countDown(); + assertThat(awaited(resizer)).as("the resize must complete once the gates open").isTrue(); + assertThat(awaited(scanner)).as("scanType() must have returned").isTrue(); + + assertThat(scanFailure.get()).isNull(); + assertThat(scanned.get()) + .as("the bucket scan drained by the retired worker must deliver every record, not stop after the first one") + .isEqualTo(RECORDS); + } + + /** + * Same shape for {@link DatabaseAsyncBrowseIterator}, which gated on the same flag: the iterator task is queued + * behind a gate on the worker the shrink retires, and every record it holds must reach the callback. + */ + @Test + @Timeout(60) + void aBrowseIteratorQueuedOnARetiredWorkerDeliversEveryRecord() throws Exception { + final DatabaseAsyncExecutorImpl async = (DatabaseAsyncExecutorImpl) ((DatabaseInternal) database).async(); + async.setParallelLevel(2); + final List rids = createRecords(); + + // WORKER 1 IS THE ONE THE SHRINK RETIRES. PARK IT ON A GATE AND QUEUE THE ITERATOR TASK BEHIND THE GATE. + final CountDownLatch gateEntered = new CountDownLatch(1); + final CountDownLatch release = new CountDownLatch(1); + assertThat(async.scheduleTask(1, AsyncTestTasks.awaitTask(gateEntered, release), true, 0)).isTrue(); + assertThat(awaited(gateEntered)).as("worker 1 must be parked on its gate").isTrue(); + + final AtomicInteger browsed = new AtomicInteger(); + final CountDownLatch completed = new CountDownLatch(1); + final List toBrowse = new ArrayList<>(rids); + assertThat(async.scheduleTask(1, new DatabaseAsyncBrowseIterator(completed, record -> { + browsed.incrementAndGet(); + return true; + }, toBrowse.iterator()), true, 0)).isTrue(); + + final Thread resizer = shrinkToOneWorkerWhileGated(async); + + release.countDown(); + assertThat(awaited(resizer)).as("the resize must complete once the gate opens").isTrue(); + assertThat(awaited(completed)).as("the iterator task must complete").isTrue(); + + assertThat(browsed.get()) + .as("the iterator drained by the retired worker must deliver every record, not stop after the first one") + .isEqualTo(RECORDS); + } + + /** + * Shrinks the pool to one worker from its own thread, because the resize WAITS for the retired worker to drain - + * which it cannot do until the caller releases the gate. Returns once the survivors are published, i.e. once the + * retired worker carries the {@code shutdown} flag with the gated task still in its queue: the shape the bug needs. + */ + private Thread shrinkToOneWorkerWhileGated(final DatabaseAsyncExecutorImpl async) throws InterruptedException { final AtomicReference resizeFailure = new AtomicReference<>(); final Thread resizer = new Thread(() -> { try { @@ -117,19 +173,51 @@ void aScanQueuedOnARetiredWorkerRunsToCompletion() throws Exception { } }, "issue7004-resizer"); resizer.start(); - while (async.getThreadCount() != 1 && System.currentTimeMillis() < deadline) - Thread.sleep(10); - assertThat(async.getThreadCount()).as("the survivors must be published before the gates open").isEqualTo(1); + assertThat(awaited(() -> async.getThreadCount() == 1)).as("the survivors must be published before the gates open") + .isTrue(); + assertThat(resizeFailure.get()).isNull(); + return resizer; + } - release.countDown(); - resizer.join(30_000); - scanner.join(30_000); + private List createRecords() { + database.getSchema().createDocumentType(TYPE, 2); + final List rids = new ArrayList<>(RECORDS); + database.transaction(() -> { + for (int i = 0; i < RECORDS; i++) + rids.add(database.newDocument(TYPE).set("id", i).save().getIdentity()); + }); + return rids; + } - assertThat(resizeFailure.get()).isNull(); - assertThat(scanFailure.get()).isNull(); - assertThat(scanner.isAlive()).as("scanType() must have returned").isFalse(); - assertThat(scanned.get()) - .as("the bucket scan drained by the retired worker must deliver every record, not stop after the first one") - .isEqualTo(RECORDS); + /** A latch await in stall-discounted slices: a JVM-wide pause inside the wait does not count against the budget. */ + private static boolean awaited(final CountDownLatch latch) throws InterruptedException { + final StallAwareStopwatch watch = StallAwareStopwatch.start(); + do { + if (latch.await(POLL_MS, TimeUnit.MILLISECONDS)) + return true; + } while (watch.effectiveMs() < BUDGET_MS); + return false; + } + + /** {@link #awaited(CountDownLatch)} for a thread join. */ + private static boolean awaited(final Thread thread) throws InterruptedException { + final StallAwareStopwatch watch = StallAwareStopwatch.start(); + do { + thread.join(POLL_MS); + if (!thread.isAlive()) + return true; + } while (watch.effectiveMs() < BUDGET_MS); + return false; + } + + /** {@link #awaited(CountDownLatch)} for a polled condition. */ + private static boolean awaited(final BooleanSupplier condition) throws InterruptedException { + final StallAwareStopwatch watch = StallAwareStopwatch.start(); + do { + if (condition.getAsBoolean()) + return true; + Thread.sleep(POLL_MS); + } while (watch.effectiveMs() < BUDGET_MS); + return false; } } diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodTransformTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodTransformTest.java index 4d5cab074ac..89d110171f5 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodTransformTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/collection/SQLMethodTransformTest.java @@ -310,7 +310,7 @@ public void updateRecordNoLock(Record record, boolean discardRecordAfter) { } @Override - public boolean deleteRecordNoLock(Record record) { + public boolean deleteRecordNoLock(final Record record) { return true; } From d1a5d8752a436dbd9513d21735c380eccb6d32d3 Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 00:52:12 -0400 Subject: [PATCH 04/10] Address code review: the async update also refuses a read-only database like the synchronous path, and the seven identical modifier-chain blocks in SQLASTBuilder reuse buildModifierChain() --- .../async/DatabaseAsyncUpdateRecord.java | 5 + .../query/sql/antlr/SQLASTBuilder.java | 120 +----------------- 2 files changed, 12 insertions(+), 113 deletions(-) diff --git a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncUpdateRecord.java b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncUpdateRecord.java index 55798f97578..aaf3fc01433 100644 --- a/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncUpdateRecord.java +++ b/engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncUpdateRecord.java @@ -23,6 +23,8 @@ import com.arcadedb.database.MutableDocument; import com.arcadedb.database.Record; import com.arcadedb.database.RecordEventsRegistry; +import com.arcadedb.engine.ComponentFile; +import com.arcadedb.exception.DatabaseIsReadOnlyException; import com.arcadedb.log.LogManager; import java.util.logging.Level; @@ -51,6 +53,9 @@ public void execute(final DatabaseAsyncExecutorImpl.AsyncThread async, final Dat if (record.getIdentity() == null) throw new IllegalArgumentException("Cannot update the record because it is not persistent"); + if (database.getMode() == ComponentFile.MODE.READ_ONLY) + throw new DatabaseIsReadOnlyException("Cannot update a record"); + if (record instanceof MutableDocument document) document.validate(); diff --git a/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java b/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java index 8d3a5b39312..3893523830e 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java +++ b/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java @@ -1748,24 +1748,7 @@ public FromItem visitFromIdentifier(final SQLParser.FromIdentifierContext ctx) { } // Handle modifiers if present - chain them using modifier.next - if (CollectionUtils.isNotEmpty(ctx.modifier())) { - Modifier firstModifier = null; - Modifier currentModifier = null; - - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - currentModifier.next = modifier; - currentModifier = modifier; - } - } - - fromItem.modifier = firstModifier; - } + fromItem.modifier = buildModifierChain(ctx.modifier()); return fromItem; } @@ -1929,24 +1912,7 @@ public FromItem visitFromSubquery(final SQLParser.FromSubqueryContext ctx) { fromItem.statement = (Statement) visit(ctx.statement()); // Handle modifiers if present - chain them using modifier.next - if (CollectionUtils.isNotEmpty(ctx.modifier())) { - Modifier firstModifier = null; - Modifier currentModifier = null; - - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - currentModifier.next = modifier; - currentModifier = modifier; - } - } - - fromItem.modifier = firstModifier; - } + fromItem.modifier = buildModifierChain(ctx.modifier()); // Handle alias if present if (ctx.identifier() != null) { @@ -2833,21 +2799,7 @@ public BaseExpression visitMapLit(final SQLParser.MapLitContext ctx) { } // Process modifiers (e.g., {"a": 1}.a) - if (ctx.modifier() != null && !ctx.modifier().isEmpty()) { - Modifier firstModifier = null; - Modifier currentModifier = null; - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - currentModifier.next = modifier; - currentModifier = modifier; - } - } - baseExpr.modifier = firstModifier; - } + baseExpr.modifier = buildModifierChain(ctx.modifier()); return baseExpr; } @@ -3248,23 +3200,7 @@ public BaseExpression visitStringLiteral(final SQLParser.StringLiteralContext ct baseExpr.string = text; // Process modifiers (method calls like .prefix(), .toUpperCase(), etc.) - if (CollectionUtils.isNotEmpty(ctx.modifier())) { - Modifier firstModifier = null; - Modifier currentModifier = null; - - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - currentModifier.next = modifier; - currentModifier = modifier; - } - } - - baseExpr.modifier = firstModifier; - } + baseExpr.modifier = buildModifierChain(ctx.modifier()); return baseExpr; } @@ -3457,21 +3393,7 @@ public BaseExpression visitArrayLit(final SQLParser.ArrayLitContext ctx) { baseExpr.expression = expression; // Process modifiers (method calls like .keys(), .values(), etc.) - if (ctx.modifier() != null && !ctx.modifier().isEmpty()) { - Modifier firstModifier = null; - Modifier currentModifier = null; - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - currentModifier.next = modifier; - currentModifier = modifier; - } - } - baseExpr.modifier = firstModifier; - } + baseExpr.modifier = buildModifierChain(ctx.modifier()); return baseExpr; } @@ -4032,21 +3954,7 @@ public BaseExpression visitCaseExpr(final SQLParser.CaseExprContext ctx) { result.expression = wrapperExpression; // Process modifiers if any - if (ctx.modifier() != null && !ctx.modifier().isEmpty()) { - Modifier firstModifier = null; - Modifier currentModifier = null; - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - currentModifier.next = modifier; - currentModifier = modifier; - } - } - result.modifier = firstModifier; - } + result.modifier = buildModifierChain(ctx.modifier()); return result; } @@ -4090,21 +3998,7 @@ public BaseExpression visitExtendedCaseExpr(final SQLParser.ExtendedCaseExprCont result.expression = wrapperExpression; // Process modifiers if any - if (ctx.modifier() != null && !ctx.modifier().isEmpty()) { - Modifier firstModifier = null; - Modifier currentModifier = null; - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - currentModifier.next = modifier; - currentModifier = modifier; - } - } - result.modifier = firstModifier; - } + result.modifier = buildModifierChain(ctx.modifier()); return result; } From 136c92a447c5b66ab750d24a45f02ce67845d330 Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 00:57:47 -0400 Subject: [PATCH 05/10] Address code review: append() tolerates a null argument array from a direct caller --- .../arcadedb/query/sql/method/string/SQLMethodAppend.java | 2 ++ .../query/sql/method/string/SQLMethodAppendTest.java | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java index 70534c16bc4..dcca302c1ae 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java @@ -47,6 +47,8 @@ public Object execute( final Object value, final Identifiable currentRecord, fin final Object[] params) { if (value == null) return null; + if (params == null) + return value.toString(); // A null argument is skipped, wherever it appears. A leading null used to return the receiver untouched, dropping // every argument after it - so 'x'.append(null, 'A', 'B') answered "x" while 'x'.append('A', null, 'B') answered diff --git a/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodAppendTest.java b/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodAppendTest.java index 1fad8795d2f..bc26f9d4f37 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodAppendTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/method/string/SQLMethodAppendTest.java @@ -53,6 +53,13 @@ void allNullArgumentsLeaveTheReceiverUnchanged() { assertThat(method.execute("x", null, null, new Object[] { null, null })).isEqualTo("x"); } + @Test + void noArgumentsAtAllLeaveTheReceiverUnchanged() { + // THE FRAMEWORK ENFORCES THE ARITY (AT LEAST ONE ARGUMENT); A DIRECT CALLER MUST NOT GET AN NPE + assertThat(method.execute("x", null, null, null)).isEqualTo("x"); + assertThat(method.execute("x", null, null, new Object[0])).isEqualTo("x"); + } + @Test void aNullReceiverStaysNull() { assertThat(method.execute(null, null, null, new Object[] { "A" })).isNull(); From 25df303a7ebb2e1cd890d413bf02a81aff5cd6ed Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 01:01:34 -0400 Subject: [PATCH 06/10] Address code review: state the non-null invariant at the three array call sites of listReceiverOrNull() --- .../arcadedb/query/sql/method/conversion/SQLMethodAsList.java | 3 ++- .../arcadedb/query/sql/method/conversion/SQLMethodAsSet.java | 3 ++- .../query/sql/method/conversion/SQLMethodAsString.java | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsList.java b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsList.java index 2d67ce93404..07d5a8859c5 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsList.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsList.java @@ -52,7 +52,8 @@ public Object execute(Object value, final Identifiable currentRecord, final Comm return new ArrayList<>((Collection) value); } else if (value.getClass().isArray()) { // AN ARRAY (split(), A JSON ARRAY PARAMETER) USED TO FALL THROUGH TO THE SINGLE-ITEM BRANCH BELOW AND COME - // BACK AS A ONE-ELEMENT LIST HOLDING THE WHOLE ARRAY (ISSUE #7027) + // BACK AS A ONE-ELEMENT LIST HOLDING THE WHOLE ARRAY (ISSUE #7027). NEVER NULL FOR AN ARRAY: EVERY ARRAY IS A + // MultiValue, SO THE HELPER ALWAYS ANSWERS A LIST HERE return new ArrayList<>(listReceiverOrNull(value)); } else if (value instanceof Iterable iterable) { value = iterable.iterator(); diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSet.java b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSet.java index afc2ccc0fe3..435384e39cd 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSet.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsSet.java @@ -51,7 +51,8 @@ public Object execute(Object value, final Identifiable currentRecord, final Comm if (value instanceof Collection) { return new HashSet<>((Collection) value); } else if (value.getClass().isArray()) { - // SAME AS asList(): AN ARRAY IS A COLLECTION OF ITS ELEMENTS, NOT A SINGLE ITEM (ISSUE #7027) + // SAME AS asList(): AN ARRAY IS A COLLECTION OF ITS ELEMENTS, NOT A SINGLE ITEM (ISSUE #7027). NEVER NULL FOR + // AN ARRAY: EVERY ARRAY IS A MultiValue, SO THE HELPER ALWAYS ANSWERS A LIST HERE return new HashSet<>(listReceiverOrNull(value)); } else if (value instanceof Iterable iterable) { value = iterable.iterator(); diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsString.java b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsString.java index b02c79c8014..962551e8268 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsString.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/conversion/SQLMethodAsString.java @@ -67,7 +67,8 @@ public Object execute(final Object value, final Identifiable currentRecord, fina if (value.getClass().isArray()) // A NON-NUMERIC ARRAY HAS NO NATURAL STRING FORM OF ITS OWN: Object.toString() IS THE JVM IDENTITY // ("[Ljava.lang.String;@7a8fa663"), WHICH USED TO REACH THE CLIENT AS DATA (ISSUE #7027). RENDER IT AS THE - // LIST OF ITS ELEMENTS, EXACTLY AS THE SAME VALUES IN A List WOULD BE. + // LIST OF ITS ELEMENTS, EXACTLY AS THE SAME VALUES IN A List WOULD BE. NEVER NULL FOR AN ARRAY: EVERY ARRAY IS + // A MultiValue, SO THE HELPER ALWAYS ANSWERS A LIST HERE. return listReceiverOrNull(value).toString(); return value.toString(); From f15e43569de6bcb5e1bbb5572ebb19ed7419de0d Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 01:09:54 -0400 Subject: [PATCH 07/10] Address code review: import order, and append() with no argument array returns the receiver itself --- .../com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java | 2 +- .../com/arcadedb/query/sql/method/string/SQLMethodAppend.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java b/engine/src/main/java/com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java index 8367cf8d083..e989748c8eb 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/DefaultSQLMethodFactory.java @@ -23,8 +23,8 @@ import com.arcadedb.query.sql.method.collection.SQLMethodField; import com.arcadedb.query.sql.method.collection.SQLMethodFirst; import com.arcadedb.query.sql.method.collection.SQLMethodJoin; -import com.arcadedb.query.sql.method.collection.SQLMethodLast; import com.arcadedb.query.sql.method.collection.SQLMethodKeys; +import com.arcadedb.query.sql.method.collection.SQLMethodLast; import com.arcadedb.query.sql.method.collection.SQLMethodRemove; import com.arcadedb.query.sql.method.collection.SQLMethodRemoveAll; import com.arcadedb.query.sql.method.collection.SQLMethodSize; diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java index dcca302c1ae..df2a6c86cdd 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodAppend.java @@ -48,7 +48,7 @@ public Object execute( final Object value, final Identifiable currentRecord, fin if (value == null) return null; if (params == null) - return value.toString(); + return value; // A null argument is skipped, wherever it appears. A leading null used to return the receiver untouched, dropping // every argument after it - so 'x'.append(null, 'A', 'B') answered "x" while 'x'.append('A', null, 'B') answered From 528f930a06db01fc09f73ce7e1a1af84d7473229 Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 01:13:48 -0400 Subject: [PATCH 08/10] Address code review: buildModifierChain() appends after the tail of a visited chain so the two parenthesised-statement sites use it too, and listReceiverOrNull() answers a List before the reflective multi-value test --- .../query/sql/antlr/SQLASTBuilder.java | 48 ++++--------------- .../query/sql/method/AbstractSQLMethod.java | 6 +++ 2 files changed, 14 insertions(+), 40 deletions(-) diff --git a/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java b/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java index 3893523830e..1da74d05112 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java +++ b/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java @@ -3257,7 +3257,11 @@ private Modifier buildModifierChain(final List modifi firstModifier = modifier; else currentModifier.next = modifier; + // A VISITED MODIFIER MAY ALREADY BE A CHAIN (A PARENTHESISED STATEMENT'S MODIFIERS ARE): APPEND AFTER ITS TAIL, + // NOT AFTER ITS HEAD, OR THE NEXT ONE WOULD OVERWRITE THE REST OF IT currentModifier = modifier; + while (currentModifier.next != null) + currentModifier = currentModifier.next; } return firstModifier; } @@ -3857,26 +3861,8 @@ public BaseExpression visitParenthesizedStmt(final SQLParser.ParenthesizedStmtCo } // Process modifiers if present (e.g., (SELECT ...).name or (SELECT ...)[0]) - if (CollectionUtils.isNotEmpty(ctx.modifier())) { - Modifier firstModifier = null; - Modifier currentModifier = null; - - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - // Find the end of the current modifier chain - while (currentModifier.next != null) - currentModifier = currentModifier.next; - currentModifier.next = modifier; - currentModifier = modifier; - } - } - result.setModifier(firstModifier); - } + if (CollectionUtils.isNotEmpty(ctx.modifier())) + result.setModifier(buildModifierChain(ctx.modifier())); return result; } @@ -3896,26 +3882,8 @@ public BaseExpression visitParenthesizedExpr(final SQLParser.ParenthesizedExprCo baseExpr.parenthesized = true; // Process modifiers if present - if (CollectionUtils.isNotEmpty(ctx.modifier())) { - Modifier firstModifier = null; - Modifier currentModifier = null; - - for (final SQLParser.ModifierContext modCtx : ctx.modifier()) { - final Modifier modifier = (Modifier) visit(modCtx); - - if (firstModifier == null) { - firstModifier = modifier; - currentModifier = modifier; - } else { - // Find the end of the current modifier chain - while (currentModifier.next != null) - currentModifier = currentModifier.next; - currentModifier.next = modifier; - currentModifier = modifier; - } - } - baseExpr.setModifier(firstModifier); - } + if (CollectionUtils.isNotEmpty(ctx.modifier())) + baseExpr.setModifier(buildModifierChain(ctx.modifier())); return baseExpr; } diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java b/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java index 3267fcd83d0..423261c96d2 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/AbstractSQLMethod.java @@ -176,7 +176,13 @@ protected String numericTextOrNull(final Object value) { * * @return the receiver as a list, or {@code null} when it is not a collection */ + @SuppressWarnings("unchecked") protected static List listReceiverOrNull(final Object value) { + // THE COMMON CASE FIRST, AHEAD OF THE REFLECTIVE isMultiValue() TEST: A List IS ANSWERED AS IS AT THE COST OF ONE + // instanceof + if (value instanceof List) + return (List) value; + // A BARE Iterator IS NOT A MultiValue.isMultiValue() (THAT TEST COVERS Iterable, NOT Iterator), SO IT IS ADMITTED // EXPLICITLY OR THE MATERIALISATION BELOW WOULD NEVER SEE ONE if (value == null || value instanceof Map || !(MultiValue.isMultiValue(value) || value instanceof Iterator)) From 75c98fa2b59af47006c4375a49a47327060eb008 Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 01:17:59 -0400 Subject: [PATCH 09/10] Address code review: the test plugin reports a hook thread that never reached the lock instead of ignoring the await result --- .../server/Issue7025ShutdownHookOpenDatabasesBoundTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/src/test/java/com/arcadedb/server/Issue7025ShutdownHookOpenDatabasesBoundTest.java b/server/src/test/java/com/arcadedb/server/Issue7025ShutdownHookOpenDatabasesBoundTest.java index e57d09695e2..e27e7e0dbd7 100644 --- a/server/src/test/java/com/arcadedb/server/Issue7025ShutdownHookOpenDatabasesBoundTest.java +++ b/server/src/test/java/com/arcadedb/server/Issue7025ShutdownHookOpenDatabasesBoundTest.java @@ -212,7 +212,8 @@ public void startService() { thread.start(); try { - hookStarted.await(30, TimeUnit.SECONDS); + if (!hookStarted.await(30, TimeUnit.SECONDS)) + hookFailure.compareAndSet(null, new IllegalStateException("the hook thread never reached the lifecycle lock")); // THE HOOK IS NOW WAITING FOR THE LIFECYCLE LOCK THIS start() HOLDS: OUTLAST THE OLD FIXED BOUND Thread.sleep(START_HOLD_MS); } catch (final InterruptedException e) { From 786a9c6db3a7b78e0241a67d6c5af4b1e8054493 Mon Sep 17 00:00:00 2001 From: Luca Garulli Date: Thu, 3 Sep 2026 01:21:33 -0400 Subject: [PATCH 10/10] Address code review: note why split() answers an immutable list, and drop the redundant guards around the two setModifier() call sites --- .../java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java | 6 ++---- .../arcadedb/query/sql/method/string/SQLMethodSplit.java | 3 +++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java b/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java index 1da74d05112..3d096195a50 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java +++ b/engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java @@ -3861,8 +3861,7 @@ public BaseExpression visitParenthesizedStmt(final SQLParser.ParenthesizedStmtCo } // Process modifiers if present (e.g., (SELECT ...).name or (SELECT ...)[0]) - if (CollectionUtils.isNotEmpty(ctx.modifier())) - result.setModifier(buildModifierChain(ctx.modifier())); + result.setModifier(buildModifierChain(ctx.modifier())); return result; } @@ -3882,8 +3881,7 @@ public BaseExpression visitParenthesizedExpr(final SQLParser.ParenthesizedExprCo baseExpr.parenthesized = true; // Process modifiers if present - if (CollectionUtils.isNotEmpty(ctx.modifier())) - baseExpr.setModifier(buildModifierChain(ctx.modifier())); + baseExpr.setModifier(buildModifierChain(ctx.modifier())); return baseExpr; } diff --git a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodSplit.java b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodSplit.java index 2f4e18aff93..6ad8f2d31c7 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodSplit.java +++ b/engine/src/main/java/com/arcadedb/query/sql/method/string/SQLMethodSplit.java @@ -50,6 +50,9 @@ public Object execute(final Object value, final Identifiable iRecord, final Comm // A List, not the String[] String.split() hands back (issue #7027): the SQL split() function, the Cypher split() // function and the documentation of this very method all answer a list, and this was the only one of the four // that leaked the raw Java array - the one receiver shape most of the collection methods then mishandled. + // Immutable on purpose (and safe: String.split() never yields a null element, which List.of() would reject). A + // consumer that needs to mutate the result copies it first, as every collection method does through + // AbstractSQLMethod.listReceiverOrNull(). return List.of(value.toString().split(Pattern.quote(params[0].toString()))); } }