You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by dc...@apache.org on 2024/09/27 23:25:13 UTC
(cassandra) branch cep-15-accord updated: CEP-15: (Accord) sequence EpochReady.coordinating to allow syncComplete to be learned from newer epochs
This is an automated email from the ASF dual-hosted git repository.
dcapwell pushed a commit to branch cep-15-accord
in repository https://gitbox.apache.org/repos/asf/cassandra.git
The following commit(s) were added to refs/heads/cep-15-accord by this push:
new a8f32d0a4c CEP-15: (Accord) sequence EpochReady.coordinating to allow syncComplete to be learned from newer epochs
a8f32d0a4c is described below
commit a8f32d0a4c586431b7aa955ff0493166b771bcff
Author: David Capwell <dc...@apache.org>
AuthorDate: Tue Jun 18 13:55:38 2024 -0700
CEP-15: (Accord) sequence EpochReady.coordinating to allow syncComplete to be learned from newer epochs
patch by David Capwell; reviewed by Alex Petrov, Blake Eggleston for CASSANDRA-19769
---
modules/accord | 2 +-
.../org/apache/cassandra/config/AccordSpec.java | 9 +
.../config/CassandraRelevantProperties.java | 4 +
.../cassandra/index/sai/utils/IndexTermType.java | 2 +-
src/java/org/apache/cassandra/net/Verb.java | 3 +
.../apache/cassandra/schema/KeyspaceMetadata.java | 7 +
.../apache/cassandra/schema/ReplicationParams.java | 5 +
.../service/accord/AccordConfigurationService.java | 64 ++-
.../cassandra/service/accord/AccordService.java | 204 ++++++-
.../cassandra/service/accord/FetchMinEpoch.java | 209 +++++++
.../cassandra/service/accord/IAccordService.java | 8 +
.../cassandra/service/accord/TokenRange.java | 35 +-
.../cassandra/service/accord/api/AccordAgent.java | 12 +
.../migration/TransactionalMigrationFromMode.java | 5 +
src/java/org/apache/cassandra/tcm/Processor.java | 20 +
src/java/org/apache/cassandra/tcm/Startup.java | 19 +-
.../cassandra/distributed/shared/ClusterUtils.java | 44 +-
.../cassandra/distributed/test/TestBaseImpl.java | 23 +
.../distributed/test/accord/AccordCQLTestBase.java | 1 +
.../test/accord/AccordHostReplacementTest.java | 90 +++
.../distributed/test/accord/AccordTestBase.java | 67 +--
.../distributed/test/accord/NewSchemaTest.java | 22 +-
.../fuzz/topology/AccordTopologyMixupTest.java | 300 ++++++++++
.../fuzz/topology/TopologyMixupTestBase.java | 8 +-
.../org/apache/cassandra/harry/HarryHelper.java | 15 +-
.../org/apache/cassandra/harry/ddl/ColumnSpec.java | 105 ++++
.../cassandra/harry/ddl/SchemaGenerators.java | 18 +-
.../org/apache/cassandra/harry/ddl/SchemaSpec.java | 85 ++-
.../apache/cassandra/harry/gen/Collections.java | 27 +-
.../cassandra/harry/gen/EntropyRandomSource.java | 89 +++
.../org/apache/cassandra/harry/gen/Generators.java | 11 +
.../harry/gen/RandomSourceEntropySource.java | 79 +++
.../cassandra/harry/model/QuiescentChecker.java | 7 +-
.../model/QuiescentLocalStateCheckerBase.java | 5 +-
.../apache/cassandra/harry/model/SelectHelper.java | 183 +++---
.../apache/cassandra/harry/operations/Query.java | 5 +
.../config/DatabaseDescriptorRefTest.java | 1 +
test/unit/org/apache/cassandra/cql3/CQLTester.java | 165 +++++-
.../apache/cassandra/cql3/RandomSchemaTest.java | 57 +-
.../apache/cassandra/cql3/RandomSchemaV2Test.java | 303 ++++++++++
.../ast/And.java} | 36 +-
.../cassandra/cql3/ast/AssignmentOperator.java | 112 ++++
.../ast/Bind.java} | 54 +-
.../apache/cassandra/cql3/ast/CasCondition.java | 66 +++
.../ast/Cast.java} | 47 +-
.../cassandra/cql3/ast/CollectionAccess.java | 58 ++
.../org/apache/cassandra/cql3/ast/Conditional.java | 107 ++++
.../apache/cassandra/cql3/ast/CreateIndexDDL.java | 251 +++++++++
.../ast/DDL.java} | 27 +-
.../ast/Element.java} | 46 +-
.../ast/Elements.java} | 30 +-
.../ast/Expression.java} | 28 +-
.../cassandra/cql3/ast/ExpressionEvaluator.java | 145 +++++
.../apache/cassandra/cql3/ast/FunctionCall.java | 82 +++
.../ast/Literal.java} | 47 +-
.../org/apache/cassandra/cql3/ast/Mutation.java | 358 ++++++++++++
.../org/apache/cassandra/cql3/ast/Operator.java | 95 ++++
.../org/apache/cassandra/cql3/ast/Reference.java | 182 ++++++
.../ast/ReferenceExpression.java} | 30 +-
.../unit/org/apache/cassandra/cql3/ast/Select.java | 370 ++++++++++++
.../org/apache/cassandra/cql3/ast/Statement.java | 108 ++++
.../unit/org/apache/cassandra/cql3/ast/Symbol.java | 146 +++++
.../apache/cassandra/cql3/ast/TableReference.java | 57 ++
test/unit/org/apache/cassandra/cql3/ast/Txn.java | 310 +++++++++++
.../org/apache/cassandra/cql3/ast/TypeHint.java | 74 +++
.../ast/Value.java} | 29 +-
test/unit/org/apache/cassandra/cql3/ast/Where.java | 71 +++
.../org/apache/cassandra/repair/FuzzTestBase.java | 3 +-
.../cassandra/service/accord/EpochSyncTest.java | 413 +++++++++-----
.../service/accord/FetchMinEpochTest.java | 283 ++++++++++
.../org/apache/cassandra/utils/ASTGenerators.java | 604 ++++++++++++++++++++
.../cassandra/utils/AbstractTypeGenerators.java | 50 +-
.../utils/AbstractTypeGeneratorsTest.java | 53 ++
.../cassandra/utils/CassandraGenerators.java | 563 ++++++++++++++++---
.../cassandra/utils/CassandraGeneratorsTest.java | 32 ++
.../org/apache/cassandra/utils/Generators.java | 2 +
.../cassandra/utils/SimulatedMiniCluster.java | 619 +++++++++++++++++++++
77 files changed, 7186 insertions(+), 720 deletions(-)
diff --git a/modules/accord b/modules/accord
index 486cd4bc15..107966eeaf 160000
--- a/modules/accord
+++ b/modules/accord
@@ -1 +1 @@
-Subproject commit 486cd4bc15d33500b7b896f9e4691a38d946b679
+Subproject commit 107966eeaf69a968dcd736519b6d6199ee28acb1
diff --git a/src/java/org/apache/cassandra/config/AccordSpec.java b/src/java/org/apache/cassandra/config/AccordSpec.java
index 39fefbf187..0350e587c6 100644
--- a/src/java/org/apache/cassandra/config/AccordSpec.java
+++ b/src/java/org/apache/cassandra/config/AccordSpec.java
@@ -90,6 +90,15 @@ public class AccordSpec
public boolean ephemeralReadEnabled = false;
public boolean state_cache_listener_jfr_enabled = true;
public final JournalSpec journal = new JournalSpec();
+ public final MinEpochRetrySpec minEpochSyncRetry = new MinEpochRetrySpec();
+
+ public static class MinEpochRetrySpec extends RetrySpec
+ {
+ public MinEpochRetrySpec()
+ {
+ maxAttempts = new MaxAttempt(3);
+ }
+ }
public static class JournalSpec implements Params
{
diff --git a/src/java/org/apache/cassandra/config/CassandraRelevantProperties.java b/src/java/org/apache/cassandra/config/CassandraRelevantProperties.java
index 072c9e93fc..215eef3ceb 100644
--- a/src/java/org/apache/cassandra/config/CassandraRelevantProperties.java
+++ b/src/java/org/apache/cassandra/config/CassandraRelevantProperties.java
@@ -25,6 +25,7 @@ import javax.annotation.Nullable;
import com.google.common.primitives.Ints;
+import accord.utils.Invariants;
import org.apache.cassandra.db.virtual.LogMessagesTable;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.utils.FBUtilities;
@@ -36,6 +37,9 @@ import org.apache.cassandra.utils.StorageCompatibilityMode;
public enum CassandraRelevantProperties
{
ACCORD_AGENT_CLASS("cassandra.test.accord.agent"),
+ ACCORD_KEY_PARANOIA_COSTFACTOR(Invariants.KEY_PARANOIA_COSTFACTOR),
+ ACCORD_KEY_PARANOIA_CPU(Invariants.KEY_PARANOIA_CPU),
+ ACCORD_KEY_PARANOIA_MEMORY(Invariants.KEY_PARANOIA_MEMORY),
ACCORD_REPAIR_RANGE_STEP_UPDATE_INTERVAL("cassandra.accord.repair.range_step_update_interval", "100"),
ACQUIRE_RETRY_SECONDS("cassandra.acquire_retry_seconds", "60"),
ACQUIRE_SLEEP_MS("cassandra.acquire_sleep_ms", "1000"),
diff --git a/src/java/org/apache/cassandra/index/sai/utils/IndexTermType.java b/src/java/org/apache/cassandra/index/sai/utils/IndexTermType.java
index a558d5ee82..c07f10dd8e 100644
--- a/src/java/org/apache/cassandra/index/sai/utils/IndexTermType.java
+++ b/src/java/org/apache/cassandra/index/sai/utils/IndexTermType.java
@@ -745,7 +745,7 @@ public class IndexTermType
return CompositeType.getInstance(collection.nameComparator(), collection.valueComparator());
}
default:
- throw new IllegalArgumentException("Unsupported collection type: " + collection.kind);
+ throw new IllegalArgumentException("Unsupported collection type: " + collection.kind + "; index type: " + indexType.name());
}
}
diff --git a/src/java/org/apache/cassandra/net/Verb.java b/src/java/org/apache/cassandra/net/Verb.java
index 5a404fd21f..c656ccc527 100644
--- a/src/java/org/apache/cassandra/net/Verb.java
+++ b/src/java/org/apache/cassandra/net/Verb.java
@@ -81,6 +81,7 @@ import org.apache.cassandra.service.SnapshotVerbHandler;
import org.apache.cassandra.service.accord.AccordService;
import org.apache.cassandra.service.accord.AccordSyncPropagator;
import org.apache.cassandra.service.accord.AccordSyncPropagator.Notification;
+import org.apache.cassandra.service.accord.FetchMinEpoch;
import org.apache.cassandra.service.accord.interop.AccordInteropApply;
import org.apache.cassandra.service.accord.interop.AccordInteropCommit;
import org.apache.cassandra.service.accord.interop.AccordInteropRead;
@@ -354,6 +355,8 @@ public enum Verb
ACCORD_INTEROP_READ_REPAIR_RSP (157, P2, writeTimeout, IMMEDIATE, () -> AccordInteropReadRepair.replySerializer, RESPONSE_HANDLER),
ACCORD_INTEROP_READ_REPAIR_REQ (158, P2, writeTimeout, IMMEDIATE, () -> AccordInteropReadRepair.requestSerializer, AccordService::verbHandlerOrNoop, ACCORD_INTEROP_READ_REPAIR_RSP),
ACCORD_INTEROP_APPLY_REQ (160, P2, writeTimeout, IMMEDIATE, () -> AccordInteropApply.serializer, AccordService::verbHandlerOrNoop, ACCORD_APPLY_RSP),
+ ACCORD_FETCH_MIN_EPOCH_RSP (166, P2, writeTimeout, IMMEDIATE, () -> FetchMinEpoch.Response.serializer, RESPONSE_HANDLER),
+ ACCORD_FETCH_MIN_EPOCH_REQ (165, P2, writeTimeout, IMMEDIATE, () -> FetchMinEpoch.serializer, () -> FetchMinEpoch.handler, ACCORD_FETCH_MIN_EPOCH_RSP),
// generic failure response
FAILURE_RSP (99, P0, noTimeout, REQUEST_RESPONSE, () -> RequestFailure.serializer, RESPONSE_HANDLER ),
diff --git a/src/java/org/apache/cassandra/schema/KeyspaceMetadata.java b/src/java/org/apache/cassandra/schema/KeyspaceMetadata.java
index 4f920c70f4..798b009977 100644
--- a/src/java/org/apache/cassandra/schema/KeyspaceMetadata.java
+++ b/src/java/org/apache/cassandra/schema/KeyspaceMetadata.java
@@ -25,6 +25,7 @@ import java.util.stream.Stream;
import javax.annotation.Nullable;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
@@ -84,6 +85,12 @@ public final class KeyspaceMetadata implements SchemaElement
this.replicationStrategy = AbstractReplicationStrategy.createReplicationStrategy(keyspaceName, params.replication);
}
+ @VisibleForTesting
+ public static KeyspaceMetadata createUnsafe(String keyspaceName, Kind kind, KeyspaceParams params, Tables tables, Views views, Types types, UserFunctions functions)
+ {
+ return new KeyspaceMetadata(keyspaceName, kind, params, tables, views, types, functions);
+ }
+
public static KeyspaceMetadata create(String name, KeyspaceParams params)
{
return new KeyspaceMetadata(name, Kind.REGULAR, params, Tables.none(), Views.none(), Types.none(), UserFunctions.none());
diff --git a/src/java/org/apache/cassandra/schema/ReplicationParams.java b/src/java/org/apache/cassandra/schema/ReplicationParams.java
index cf445a4b78..ad15103dda 100644
--- a/src/java/org/apache/cassandra/schema/ReplicationParams.java
+++ b/src/java/org/apache/cassandra/schema/ReplicationParams.java
@@ -63,6 +63,11 @@ public final class ReplicationParams
this.options = ImmutableMap.copyOf(options);
}
+ public static ReplicationParams copy(AbstractReplicationStrategy strategy)
+ {
+ return new ReplicationParams(strategy.getClass(), strategy.configOptions);
+ }
+
public static ReplicationParams local()
{
return new ReplicationParams(LocalStrategy.class, ImmutableMap.of());
diff --git a/src/java/org/apache/cassandra/service/accord/AccordConfigurationService.java b/src/java/org/apache/cassandra/service/accord/AccordConfigurationService.java
index 1e6cb1d769..e0d1d84020 100644
--- a/src/java/org/apache/cassandra/service/accord/AccordConfigurationService.java
+++ b/src/java/org/apache/cassandra/service/accord/AccordConfigurationService.java
@@ -19,8 +19,10 @@
package org.apache.cassandra.service.accord;
import java.util.Objects;
+import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
@@ -30,6 +32,7 @@ import com.google.common.collect.Sets;
import accord.impl.AbstractConfigurationService;
import accord.local.Node;
import accord.primitives.Ranges;
+import accord.topology.Shard;
import accord.topology.Topology;
import accord.utils.Invariants;
import accord.utils.async.AsyncResult;
@@ -207,12 +210,18 @@ public class AccordConfigurationService extends AbstractConfigurationService<Acc
return new EpochHistory();
}
+ @VisibleForTesting
public synchronized void start()
+ {
+ start(ignore -> {});
+ }
+
+ public synchronized void start(Consumer<OptionalLong> callback)
{
Invariants.checkState(state == State.INITIALIZED, "Expected state to be INITIALIZED but was %s", state);
state = State.LOADING;
- updateMapping(ClusterMetadata.current());
EndpointMapping snapshot = mapping;
+ //TODO (restart): if there are topologies loaded then there is likely failures if reporting is needed, as mapping is not setup yet
diskState = diskStateManager.loadTopologies(((epoch, topology, syncStatus, pendingSyncNotify, remoteSyncComplete, closed, redundant) -> {
if (topology != null)
reportTopology(topology, syncStatus == SyncStatus.NOT_STARTED);
@@ -230,6 +239,7 @@ public class AccordConfigurationService extends AbstractConfigurationService<Acc
receiveRedundant(redundant, epoch);
}));
state = State.STARTED;
+ callback.accept(diskState.isEmpty() ? OptionalLong.empty() : OptionalLong.of(diskState.maxEpoch));
ClusterMetadataService.instance().log().addListener(this);
}
@@ -293,27 +303,54 @@ public class AccordConfigurationService extends AbstractConfigurationService<Acc
private void reportMetadata(ClusterMetadata metadata)
{
- Stage.MISC.submit(() -> {
- synchronized (AccordConfigurationService.this)
+ Stage.MISC.submit(() -> reportMetadataInternal(metadata));
+ }
+
+ synchronized void reportMetadataInternal(ClusterMetadata metadata)
+ {
+ updateMapping(metadata);
+ Topology topology = AccordTopology.createAccordTopology(metadata);
+ if (Invariants.isParanoid())
+ {
+ for (Node.Id node : topology.nodes())
{
- updateMapping(metadata);
- Topology topology = AccordTopology.createAccordTopology(metadata);
- Topology current = isEmpty() ? Topology.EMPTY : currentTopology();
- reportTopology(topology);
- Sets.SetView<Node.Id> removedNodes = Sets.difference(current.nodes(), topology.nodes());
- if (!removedNodes.isEmpty())
- onNodesRemoved(topology.epoch(), removedNodes);
+ if (mapping.mappedEndpointOrNull(node) == null)
+ throw new IllegalStateException("Epoch " + topology.epoch() + " has node " + node + " but mapping does not!");
}
- });
+ }
+ Topology current = isEmpty() ? Topology.EMPTY : currentTopology();
+ reportTopology(topology);
+ // for all nodes removed, or pending removal, mark them as removed so we don't wait on their replies
+ Sets.SetView<Node.Id> removedNodes = Sets.difference(current.nodes(), topology.nodes());
+ if (!removedNodes.isEmpty())
+ {
+ onNodesRemoved(topology.epoch(), removedNodes);
+ for (Node.Id node : removedNodes)
+ {
+ if (shareShard(current, node, localId))
+ AccordService.instance().tryMarkRemoved(current, node);
+ }
+ }
+ }
+
+ private static boolean shareShard(Topology current, Node.Id target, Node.Id self)
+ {
+ for (Shard shard : current.shards())
+ {
+ if (!shard.contains(target)) continue;
+ if (shard.contains(self)) return true;
+ }
+ return false;
}
- private synchronized void onNodesRemoved(long epoch, Set<Node.Id> removed)
+ public synchronized void onNodesRemoved(long epoch, Set<Node.Id> removed)
{
+ if (removed.isEmpty()) return;
syncPropagator.onNodesRemoved(removed);
for (long oldEpoch : nonCompletedEpochsBefore(epoch))
{
for (Node.Id node : removed)
- receiveRemoteSyncComplete(node, oldEpoch);
+ receiveRemoteSyncCompletePreListenerNotify(node, oldEpoch);
}
listeners.forEach(l -> l.onRemoveNodes(epoch, removed));
}
@@ -350,7 +387,6 @@ public class AccordConfigurationService extends AbstractConfigurationService<Acc
@Override
public void notifyPostCommit(ClusterMetadata prev, ClusterMetadata next, boolean fromSnapshot)
{
- maybeReportMetadata(prev);
maybeReportMetadata(next);
}
diff --git a/src/java/org/apache/cassandra/service/accord/AccordService.java b/src/java/org/apache/cassandra/service/accord/AccordService.java
index f480287f29..cab494dd96 100644
--- a/src/java/org/apache/cassandra/service/accord/AccordService.java
+++ b/src/java/org/apache/cassandra/service/accord/AccordService.java
@@ -21,7 +21,11 @@ package org.apache.cassandra.service.accord;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@@ -38,28 +42,49 @@ import javax.annotation.concurrent.GuardedBy;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
+import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
+
+import accord.coordinate.Barrier;
+import accord.coordinate.CoordinateSyncPoint;
+import accord.coordinate.Exhausted;
+import accord.coordinate.FailureAccumulator;
+import accord.coordinate.Invalidated;
+import accord.coordinate.TopologyMismatch;
+import accord.impl.CoordinateDurabilityScheduling;
+import accord.local.Command;
+import accord.local.PreLoadContext;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.topology.Topology;
+import org.apache.cassandra.config.CassandraRelevantProperties;
+import org.apache.cassandra.cql3.statements.RequestValidations;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.repair.SharedContext;
+import org.apache.cassandra.schema.KeyspaceMetadata;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.service.accord.exceptions.ReadExhaustedException;
+import org.apache.cassandra.service.accord.interop.AccordInteropAdapter.AccordInteropFactory;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.service.accord.repair.RepairSyncPointAdapter;
+import org.apache.cassandra.tcm.ClusterMetadataService;
+import org.apache.cassandra.tcm.ownership.DataPlacement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import accord.api.BarrierType;
import accord.api.LocalConfig;
import accord.api.Result;
-import accord.coordinate.Barrier;
-import accord.coordinate.CoordinateSyncPoint;
import accord.coordinate.CoordinationFailed;
-import accord.coordinate.Exhausted;
-import accord.coordinate.FailureAccumulator;
import accord.coordinate.Preempted;
import accord.coordinate.Timeout;
-import accord.coordinate.TopologyMismatch;
import accord.impl.AbstractConfigurationService;
-import accord.impl.CoordinateDurabilityScheduling;
import accord.impl.DefaultLocalListeners;
import accord.impl.DefaultRemoteListeners;
import accord.impl.DefaultRequestTimeouts;
import accord.impl.SizeOfIntersectionSorter;
-import accord.local.Command;
import accord.local.CommandStore;
import accord.impl.progresslog.DefaultProgressLogs;
import accord.local.CommandStores;
@@ -68,7 +93,6 @@ import accord.local.KeyHistory;
import accord.local.Node;
import accord.local.Node.Id;
import accord.local.NodeTimeService;
-import accord.local.PreLoadContext;
import accord.local.RedundantBefore;
import accord.local.SaveStatus;
import accord.local.ShardDistributor.EvenSplit;
@@ -76,10 +100,8 @@ import accord.local.Status;
import accord.local.cfk.CommandsForKey;
import accord.messages.Request;
import accord.primitives.Keys;
-import accord.primitives.Ranges;
import accord.primitives.Seekable;
import accord.primitives.Seekables;
-import accord.primitives.SyncPoint;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.Txn.Kind;
@@ -92,25 +114,19 @@ import accord.utils.async.AsyncChains;
import accord.utils.async.AsyncResult;
import org.agrona.collections.Int2ObjectHashMap;
import org.apache.cassandra.concurrent.Shutdownable;
-import org.apache.cassandra.config.CassandraRelevantProperties;
import org.apache.cassandra.config.DatabaseDescriptor;
-import org.apache.cassandra.cql3.statements.RequestValidations;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.WriteType;
import org.apache.cassandra.exceptions.ReadTimeoutException;
-import org.apache.cassandra.exceptions.RequestExecutionException;
import org.apache.cassandra.exceptions.RequestTimeoutException;
import org.apache.cassandra.exceptions.WriteTimeoutException;
-import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.metrics.AccordClientRequestMetrics;
import org.apache.cassandra.net.IVerbHandler;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessageDelivery;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.schema.TableId;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.service.accord.AccordSyncPropagator.Notification;
import org.apache.cassandra.service.accord.api.AccordAgent;
import org.apache.cassandra.service.accord.api.AccordRoutingKey.KeyspaceSplitter;
@@ -118,16 +134,11 @@ import org.apache.cassandra.service.accord.api.AccordScheduler;
import org.apache.cassandra.service.accord.api.AccordTopologySorter;
import org.apache.cassandra.service.accord.api.CompositeTopologySorter;
import org.apache.cassandra.service.accord.api.PartitionKey;
-import org.apache.cassandra.service.accord.exceptions.ReadExhaustedException;
import org.apache.cassandra.service.accord.exceptions.ReadPreemptedException;
import org.apache.cassandra.service.accord.exceptions.WritePreemptedException;
-import org.apache.cassandra.service.accord.interop.AccordInteropAdapter.AccordInteropFactory;
-import org.apache.cassandra.service.accord.repair.RepairSyncPointAdapter;
import org.apache.cassandra.service.accord.txn.TxnResult;
import org.apache.cassandra.service.consensus.TransactionalMode;
import org.apache.cassandra.service.consensus.migration.TableMigrationState;
-import org.apache.cassandra.tcm.ClusterMetadata;
-import org.apache.cassandra.tcm.ClusterMetadataService;
import org.apache.cassandra.tcm.Epoch;
import org.apache.cassandra.tcm.membership.NodeId;
import org.apache.cassandra.transport.Dispatcher;
@@ -276,6 +287,19 @@ public class AccordService implements IAccordService, Shutdownable
{
return Collections.emptyList();
}
+
+ @Nullable
+ @Override
+ public Long minEpoch(Collection<TokenRange> ranges)
+ {
+ return null;
+ }
+
+ @Override
+ public void tryMarkRemoved(Topology topology, Id node)
+ {
+
+ }
};
private static volatile IAccordService instance = null;
@@ -350,6 +374,7 @@ public class AccordService implements IAccordService, Shutdownable
Invariants.checkState(localId != null, "static localId must be set before instantiating AccordService");
logger.info("Starting accord with nodeId {}", localId);
AccordAgent agent = FBUtilities.construct(CassandraRelevantProperties.ACCORD_AGENT_CLASS.getString(AccordAgent.class.getName()), "AccordAgent");
+ agent.setNodeId(localId);
this.configService = new AccordConfigurationService(localId);
this.fastPathCoordinator = AccordFastPathCoordinator.create(localId, configService);
this.messageSink = new AccordMessageSink(agent, configService);
@@ -387,10 +412,48 @@ public class AccordService implements IAccordService, Shutdownable
if (state != State.INIT)
return;
journal.start(node);
- configService.start();
+ ClusterMetadataService cms = ClusterMetadataService.instance();
+ class Ref { List<ClusterMetadata> historic = Collections.emptyList();}
+ Ref ref = new Ref();
+ configService.start((optMaxEpoch -> {
+ // when max epoch isn't know, this means the node started for the first time; check cluster's min epoch
+ // when max epoch is known, then there is no reason to discover min epoch (we already did it)
+ if (optMaxEpoch.isPresent()) return;
+ List<ClusterMetadata> historic = ref.historic = discoverHistoric(node, cms);
+ for (ClusterMetadata m : historic)
+ configService.reportMetadataInternal(m);
+ }));
+ ClusterMetadata current = cms.metadata();
+ if (!ref.historic.isEmpty())
+ {
+ List<ClusterMetadata> historic = ref.historic;
+ long lastHistoric = ref.historic.get(historic.size() - 1).epoch.getEpoch();
+ // new epochs added while loading... load the deltas
+ for (ClusterMetadata metadata : tcmLoadRange(lastHistoric + 1, current.epoch.getEpoch()))
+ {
+ historic.add(metadata);
+ configService.reportMetadataInternal(metadata);
+ }
+
+ // sync doesn't happen when this node isn't in the epoch
+ //TODO (now, correctness): sync points use "closed" and not "syncComplete", so need to call TM.epochRedundant or TM.onEpochClosed
+ // epochRedundant implies all txn that have been proposed for this epoch have been executed "globally" - we don't have this knowlege
+ // epochClosed implies no "new" txn can be proposed
+ for (ClusterMetadata m : historic)
+ {
+ Topology t = AccordTopology.createAccordTopology(m);
+ long epoch = t.epoch();
+ for (Id id : t.nodes())
+ node.onRemoteSyncComplete(id, epoch);
+ //TODO (correctness): is this true?
+ node.onEpochClosed(t.ranges(), t.epoch());
+ node.onEpochRedundant(t.ranges(), t.epoch());
+ }
+ }
+ configService.reportMetadataInternal(current);
fastPathCoordinator.start();
- ClusterMetadataService.instance().log().addListener(fastPathCoordinator);
+ cms.log().addListener(fastPathCoordinator);
durabilityScheduling.setGlobalCycleTime(Ints.checkedCast(DatabaseDescriptor.getAccordGlobalDurabilityCycle(SECONDS)), SECONDS);
durabilityScheduling.setShardCycleTime(Ints.checkedCast(DatabaseDescriptor.getAccordShardDurabilityCycle(SECONDS)), SECONDS);
durabilityScheduling.setTxnIdLag(Ints.checkedCast(DatabaseDescriptor.getAccordScheduleDurabilityTxnIdLag(SECONDS)), TimeUnit.SECONDS);
@@ -399,6 +462,74 @@ public class AccordService implements IAccordService, Shutdownable
state = State.STARTED;
}
+ private List<ClusterMetadata> discoverHistoric(Node node, ClusterMetadataService cms)
+ {
+ ClusterMetadata current = cms.metadata();
+ Topology topology = AccordTopology.createAccordTopology(current);
+ Ranges localRanges = topology.rangesForNode(node.id());
+ if (!localRanges.isEmpty()) // already joined, nothing to see here
+ return Collections.emptyList();
+
+ Map<InetAddressAndPort, Set<TokenRange>> peers = new HashMap<>();
+ for (KeyspaceMetadata keyspace : current.schema.getKeyspaces())
+ {
+ List<TableMetadata> tables = keyspace.tables.stream().filter(TableMetadata::requiresAccordSupport).collect(Collectors.toList());
+ if (tables.isEmpty())
+ continue;
+ DataPlacement placement = current.placements.get(keyspace.params.replication);
+ DataPlacement whenSettled = current.writePlacementAllSettled(keyspace);
+ Sets.SetView<InetAddressAndPort> alive = Sets.intersection(whenSettled.writes.byEndpoint().keySet(), placement.writes.byEndpoint().keySet());
+ InetAddressAndPort self = FBUtilities.getBroadcastAddressAndPort();
+ whenSettled.writes.forEach((range, group) -> {
+ if (group.endpoints().contains(self))
+ {
+ for (InetAddressAndPort peer : group.endpoints())
+ {
+ if (!alive.contains(peer)) continue;
+ for (TableMetadata table : tables)
+ peers.computeIfAbsent(peer, i -> new HashSet<>()).add(AccordTopology.fullRange(table.id));
+ }
+ }
+ });
+ }
+ if (peers.isEmpty())
+ return Collections.emptyList();
+
+ Long minEpoch = findMinEpoch(SharedContext.Global.instance, peers);
+ if (minEpoch == null)
+ return Collections.emptyList();
+ return tcmLoadRange(minEpoch, current.epoch.getEpoch());
+ }
+
+ private static List<ClusterMetadata> tcmLoadRange(long min, long max)
+ {
+ List<ClusterMetadata> afterLoad = ClusterMetadataService.instance().processor().reconstructFull(Epoch.create(min - 1), Epoch.create(max));
+ while (!afterLoad.isEmpty() && afterLoad.get(0).epoch.getEpoch() < min)
+ afterLoad.remove(0);
+ assert !afterLoad.isEmpty() : "TCM was unable to return the needed epochs";
+ assert afterLoad.get(0).epoch.getEpoch() == min : String.format("Unexpected epoch: expected %d but given %d", min, afterLoad.get(0).epoch.getEpoch());
+ assert afterLoad.get(afterLoad.size() - 1).epoch.getEpoch() == max : String.format("Unexpected epoch: expected %d but given %d", max, afterLoad.get(afterLoad.size() - 1).epoch.getEpoch());
+ return afterLoad;
+ }
+
+ @VisibleForTesting
+ static Long findMinEpoch(SharedContext context, Map<InetAddressAndPort, Set<TokenRange>> peers)
+ {
+ try
+ {
+ return FetchMinEpoch.fetch(context, peers).get();
+ }
+ catch (InterruptedException e)
+ {
+ Thread.currentThread().interrupt();
+ throw new UncheckedInterruptedException(e);
+ }
+ catch (ExecutionException e)
+ {
+ throw new RuntimeException(e.getCause());
+ }
+ }
+
@Override
public IVerbHandler<? extends Request> verbHandler()
{
@@ -437,12 +568,14 @@ public class AccordService implements IAccordService, Shutdownable
if (cause instanceof Timeout)
{
TxnId txnId = ((Timeout) cause).txnId();
+ ((AccordAgent) node.agent()).onFailedBarrier(txnId, keysOrRanges, cause);
metrics.timeouts.mark();
throw newBarrierTimeout(txnId, barrierType, isForWrite, keysOrRanges);
}
if (cause instanceof Preempted)
{
TxnId txnId = ((Preempted) cause).txnId();
+ ((AccordAgent) node.agent()).onFailedBarrier(txnId, keysOrRanges, cause);
//TODO need to improve
// Coordinator "could" query the accord state to see whats going on but that doesn't exist yet.
// Protocol also doesn't have a way to denote "unknown" outcome, so using a timeout as the closest match
@@ -451,6 +584,7 @@ public class AccordService implements IAccordService, Shutdownable
if (cause instanceof Exhausted)
{
TxnId txnId = ((Exhausted) cause).txnId();
+ ((AccordAgent) node.agent()).onFailedBarrier(txnId, keysOrRanges, cause);
// this case happens when a non-timeout exception is seen, and we are unable to move forward
metrics.failures.mark();
throw newBarrierExhausted(txnId, barrierType, isForWrite, keysOrRanges);
@@ -973,6 +1107,30 @@ public class AccordService implements IAccordService, Shutdownable
return cmdTxnState.build();
}
+ @Nullable
+ @Override
+ public Long minEpoch(Collection<TokenRange> ranges)
+ {
+ return node.topology().minEpoch();
+ }
+
+ @Override
+ public void tryMarkRemoved(Topology topology, Id target)
+ {
+ if (node.commandStores().count() == 0) return; // when starting up stores can be empty, so ignore
+ Ranges ranges = topology.rangesForNode(target);
+ if (ranges.isEmpty()) return;
+ tryMarkRemoved(ranges, 0).begin(node().agent());
+ }
+
+ private AsyncChain<SyncPoint<Ranges>> tryMarkRemoved(Ranges ranges, int attempt)
+ {
+ return CoordinateSyncPoint.exclusive(node, ranges)
+ .recover(t ->
+ //TODO (operability): make this configurable / monitorable?
+ attempt <= 3 && t instanceof Invalidated || t instanceof Preempted || t instanceof Timeout ? tryMarkRemoved(ranges, attempt + 1) : null);
+ }
+
public Node node()
{
return node;
diff --git a/src/java/org/apache/cassandra/service/accord/FetchMinEpoch.java b/src/java/org/apache/cassandra/service/accord/FetchMinEpoch.java
new file mode 100644
index 0000000000..0e40afc6c1
--- /dev/null
+++ b/src/java/org/apache/cassandra/service/accord/FetchMinEpoch.java
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Iterators;
+
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.db.TypeSizes;
+import org.apache.cassandra.io.IVersionedSerializer;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.io.util.DataOutputPlus;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.IVerbHandler;
+import org.apache.cassandra.net.Message;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.net.Verb;
+import org.apache.cassandra.repair.SharedContext;
+import org.apache.cassandra.utils.Backoff;
+import org.apache.cassandra.utils.concurrent.Future;
+import org.apache.cassandra.utils.concurrent.FutureCombiner;
+
+public class FetchMinEpoch
+{
+ public static final IVersionedSerializer<FetchMinEpoch> serializer = new IVersionedSerializer<>()
+ {
+
+ @Override
+ public void serialize(FetchMinEpoch t, DataOutputPlus out, int version) throws IOException
+ {
+ out.writeUnsignedVInt32(t.ranges.size());
+ for (TokenRange range : t.ranges)
+ TokenRange.serializer.serialize(range, out, version);
+ }
+
+ @Override
+ public FetchMinEpoch deserialize(DataInputPlus in, int version) throws IOException
+ {
+ int size = in.readUnsignedVInt32();
+ List<TokenRange> ranges = new ArrayList<>(size);
+ for (int i = 0; i < size; i++)
+ ranges.add(TokenRange.serializer.deserialize(in, version));
+ return new FetchMinEpoch(ranges);
+ }
+
+ @Override
+ public long serializedSize(FetchMinEpoch t, int version)
+ {
+ long size = TypeSizes.sizeofUnsignedVInt(t.ranges.size());
+ for (TokenRange range : t.ranges)
+ size += TokenRange.serializer.serializedSize(range, version);
+ return size;
+ }
+ };
+ public static final IVerbHandler<FetchMinEpoch> handler = new IVerbHandler<FetchMinEpoch>()
+ {
+ @Override
+ public void doVerb(Message<FetchMinEpoch> message) throws IOException
+ {
+ Long epoch = AccordService.instance().minEpoch(message.payload.ranges);
+ MessagingService.instance().respond(new Response(epoch), message);
+ }
+ };
+ public final Collection<TokenRange> ranges;
+
+ public FetchMinEpoch(Collection<TokenRange> ranges)
+ {
+ this.ranges = ranges;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ FetchMinEpoch that = (FetchMinEpoch) o;
+ return Objects.equals(ranges, that.ranges);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(ranges);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "FetchMinEpoch{" +
+ "ranges=" + ranges +
+ '}';
+ }
+
+ public static Future<Long> fetch(SharedContext context, Map<InetAddressAndPort, Set<TokenRange>> peers)
+ {
+ List<Future<Long>> accum = new ArrayList<>(peers.size());
+ for (Map.Entry<InetAddressAndPort, Set<TokenRange>> e : peers.entrySet())
+ accum.add(fetch(context, e.getKey(), e.getValue()));
+ return FutureCombiner.successfulOf(accum).map(ls -> {
+ Long min = null;
+ for (Long l : ls)
+ {
+ if (l == null) continue;
+ if (min == null) min = l;
+ else min = Math.min(min, l);
+ }
+ return min;
+ });
+ }
+
+ @VisibleForTesting
+ static Future<Long> fetch(SharedContext context, InetAddressAndPort to, Set<TokenRange> value)
+ {
+ FetchMinEpoch req = new FetchMinEpoch(value);
+ Backoff backoff = Backoff.fromConfig(context, DatabaseDescriptor.getAccord().minEpochSyncRetry);
+ return context.messaging().<FetchMinEpoch, FetchMinEpoch.Response>sendWithRetries(backoff, context.optionalTasks()::schedule,
+ Verb.ACCORD_FETCH_MIN_EPOCH_REQ, req,
+ Iterators.cycle(to),
+ (i1, i2, i3) -> true,
+ (i1, i2, i3, i4) -> null)
+ .map(m -> m.payload.minEpoch);
+ }
+
+ public static class Response
+ {
+ public static final IVersionedSerializer<Response> serializer = new IVersionedSerializer<Response>()
+ {
+ @Override
+ public void serialize(Response t, DataOutputPlus out, int version) throws IOException
+ {
+ out.writeBoolean(t.minEpoch != null);
+ if (t.minEpoch != null)
+ out.writeUnsignedVInt(t.minEpoch);
+ }
+
+ @Override
+ public Response deserialize(DataInputPlus in, int version) throws IOException
+ {
+ boolean notNull = in.readBoolean();
+ return new Response(notNull ? in.readUnsignedVInt() : null);
+ }
+
+ @Override
+ public long serializedSize(Response t, int version)
+ {
+ int size = TypeSizes.BOOL_SIZE;
+ if (t.minEpoch != null)
+ size += TypeSizes.sizeofUnsignedVInt(t.minEpoch);
+ return size;
+ }
+ };
+ @Nullable
+ public final Long minEpoch;
+
+ public Response(@Nullable Long minEpoch)
+ {
+ this.minEpoch = minEpoch;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Response response = (Response) o;
+ return Objects.equals(minEpoch, response.minEpoch);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(minEpoch);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "Response{" +
+ "minEpoch=" + minEpoch +
+ '}';
+ }
+ }
+}
diff --git a/src/java/org/apache/cassandra/service/accord/IAccordService.java b/src/java/org/apache/cassandra/service/accord/IAccordService.java
index 2daa31e272..be87f1b4a4 100644
--- a/src/java/org/apache/cassandra/service/accord/IAccordService.java
+++ b/src/java/org/apache/cassandra/service/accord/IAccordService.java
@@ -31,6 +31,7 @@ import com.google.common.collect.ImmutableSet;
import accord.api.BarrierType;
import accord.local.CommandStores;
import accord.local.DurableBefore;
+import accord.local.Node;
import accord.local.Node.Id;
import accord.local.RedundantBefore;
import accord.messages.Request;
@@ -38,6 +39,7 @@ import accord.primitives.Ranges;
import accord.primitives.Seekables;
import accord.primitives.Txn;
import accord.primitives.TxnId;
+import accord.topology.Topology;
import accord.topology.TopologyManager;
import org.agrona.collections.Int2ObjectHashMap;
import org.apache.cassandra.db.ColumnFamilyStore;
@@ -54,6 +56,8 @@ import org.apache.cassandra.transport.Dispatcher;
import org.apache.cassandra.utils.concurrent.AsyncPromise;
import org.apache.cassandra.utils.concurrent.Future;
+import java.util.Collection;
+
import static com.google.common.base.Preconditions.checkNotNull;
@@ -150,4 +154,8 @@ public interface IAccordService
default Id nodeId() { throw new UnsupportedOperationException(); }
List<CommandStoreTxnBlockedGraph> debugTxnBlockedGraph(TxnId txnId);
+ @Nullable
+ Long minEpoch(Collection<TokenRange> ranges);
+
+ void tryMarkRemoved(Topology topology, Node.Id node);
}
diff --git a/src/java/org/apache/cassandra/service/accord/TokenRange.java b/src/java/org/apache/cassandra/service/accord/TokenRange.java
index be3eaa80ca..aed0270979 100644
--- a/src/java/org/apache/cassandra/service/accord/TokenRange.java
+++ b/src/java/org/apache/cassandra/service/accord/TokenRange.java
@@ -48,13 +48,30 @@ public class TokenRange extends Range.EndInclusive
public TableId table()
{
- return ((AccordRoutingKey) start()).table();
+ return start().table();
+ }
+
+ @Override
+ public AccordRoutingKey start()
+ {
+ return (AccordRoutingKey) super.start();
+ }
+
+ @Override
+ public AccordRoutingKey end()
+ {
+ return (AccordRoutingKey) super.end();
+ }
+
+ public boolean isFullRange()
+ {
+ return start().kindOfRoutingKey() == AccordRoutingKey.RoutingKeyKind.SENTINEL && end().kindOfRoutingKey() == AccordRoutingKey.RoutingKeyKind.SENTINEL;
}
@VisibleForTesting
public Range withTable(TableId table)
{
- return new TokenRange(((AccordRoutingKey) start()).withTable(table), ((AccordRoutingKey) end()).withTable(table));
+ return new TokenRange(start().withTable(table), end().withTable(table));
}
public static TokenRange fullRange(TableId table)
@@ -80,20 +97,20 @@ public class TokenRange extends Range.EndInclusive
public org.apache.cassandra.dht.Range<Token> toKeyspaceRange ()
{
IPartitioner partitioner = DatabaseDescriptor.getPartitioner();
- AccordRoutingKey start = (AccordRoutingKey) start();
- AccordRoutingKey end = (AccordRoutingKey) end();
+ AccordRoutingKey start = start();
+ AccordRoutingKey end = end();
Token left = start instanceof SentinelKey ? partitioner.getMinimumToken() : start.token();
Token right = end instanceof SentinelKey ? partitioner.getMinimumToken() : end.token();
return new org.apache.cassandra.dht.Range<>(left, right);
}
- public static final IVersionedSerializer<TokenRange> serializer = new IVersionedSerializer<TokenRange>()
+ public static final IVersionedSerializer<TokenRange> serializer = new IVersionedSerializer<>()
{
@Override
public void serialize(TokenRange range, DataOutputPlus out, int version) throws IOException
{
- AccordRoutingKey.serializer.serialize((AccordRoutingKey) range.start(), out, version);
- AccordRoutingKey.serializer.serialize((AccordRoutingKey) range.end(), out, version);
+ AccordRoutingKey.serializer.serialize(range.start(), out, version);
+ AccordRoutingKey.serializer.serialize(range.end(), out, version);
}
@Override
@@ -106,8 +123,8 @@ public class TokenRange extends Range.EndInclusive
@Override
public long serializedSize(TokenRange range, int version)
{
- return AccordRoutingKey.serializer.serializedSize((AccordRoutingKey) range.start(), version)
- + AccordRoutingKey.serializer.serializedSize((AccordRoutingKey) range.end(), version);
+ return AccordRoutingKey.serializer.serializedSize(range.start(), version)
+ + AccordRoutingKey.serializer.serializedSize(range.end(), version);
}
};
}
diff --git a/src/java/org/apache/cassandra/service/accord/api/AccordAgent.java b/src/java/org/apache/cassandra/service/accord/api/AccordAgent.java
index bf351c323f..23a3520853 100644
--- a/src/java/org/apache/cassandra/service/accord/api/AccordAgent.java
+++ b/src/java/org/apache/cassandra/service/accord/api/AccordAgent.java
@@ -69,10 +69,17 @@ public class AccordAgent implements Agent
{
private static final Logger logger = LoggerFactory.getLogger(AccordAgent.class);
+ protected Node.Id self;
+
// TODO (required): this should be configurable and have exponential back-off, escaping to operator input past a certain number of retries
private long retryBootstrapDelayMicros = SECONDS.toMicros(1L);
private final RandomSource random = new DefaultRandom();
+ public void setNodeId(Node.Id id)
+ {
+ self = id;
+ }
+
public void setRetryBootstrapDelay(long delay, TimeUnit units)
{
retryBootstrapDelayMicros = units.toMicros(delay);
@@ -93,6 +100,11 @@ public class AccordAgent implements Agent
throw error;
}
+ public void onFailedBarrier(TxnId id, Seekables<?, ?> keysOrRanges, Throwable cause)
+ {
+
+ }
+
@Override
public void onFailedBootstrap(String phase, Ranges ranges, Runnable retry, Throwable failure)
{
diff --git a/src/java/org/apache/cassandra/service/consensus/migration/TransactionalMigrationFromMode.java b/src/java/org/apache/cassandra/service/consensus/migration/TransactionalMigrationFromMode.java
index bf84c6c062..f916a96b8e 100644
--- a/src/java/org/apache/cassandra/service/consensus/migration/TransactionalMigrationFromMode.java
+++ b/src/java/org/apache/cassandra/service/consensus/migration/TransactionalMigrationFromMode.java
@@ -80,4 +80,9 @@ public enum TransactionalMigrationFromMode
{
return this != none;
}
+
+ public String asCqlParam()
+ {
+ return String.format("transactional_migration_from = '%s'", this.name().toLowerCase());
+ }
}
diff --git a/src/java/org/apache/cassandra/tcm/Processor.java b/src/java/org/apache/cassandra/tcm/Processor.java
index 5f9e015200..96cc42c066 100644
--- a/src/java/org/apache/cassandra/tcm/Processor.java
+++ b/src/java/org/apache/cassandra/tcm/Processor.java
@@ -18,6 +18,8 @@
package org.apache.cassandra.tcm;
+import java.util.ArrayList;
+import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.cassandra.config.DatabaseDescriptor;
@@ -25,6 +27,8 @@ import org.apache.cassandra.metrics.TCMMetrics;
import org.apache.cassandra.tcm.log.Entry;
import org.apache.cassandra.tcm.log.LogState;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+
public interface Processor
{
/**
@@ -74,4 +78,20 @@ public interface Processor
ClusterMetadata fetchLogAndWait(Epoch waitFor, Retry.Deadline retryPolicy);
LogState reconstruct(Epoch lowEpoch, Epoch highEpoch, Retry.Deadline retryPolicy);
+
+ default List<ClusterMetadata> reconstructFull(Epoch lowEpoch, Epoch highEpoch)
+ {
+ LogState logState = reconstruct(lowEpoch, highEpoch, Retry.Deadline.retryIndefinitely(DatabaseDescriptor.getCmsAwaitTimeout().to(NANOSECONDS),
+ TCMMetrics.instance.commitRetries));
+ List<ClusterMetadata> cms = new ArrayList<>(logState.entries.size());
+ ClusterMetadata accum = logState.baseState;
+ for (Entry entry : logState.entries)
+ {
+ Transformation.Result res = entry.transform.execute(accum);
+ assert res.isSuccess() : res.toString();
+ accum = res.success().metadata;
+ cms.add(accum);
+ }
+ return cms;
+ }
}
diff --git a/src/java/org/apache/cassandra/tcm/Startup.java b/src/java/org/apache/cassandra/tcm/Startup.java
index 7ac664b199..4af2194163 100644
--- a/src/java/org/apache/cassandra/tcm/Startup.java
+++ b/src/java/org/apache/cassandra/tcm/Startup.java
@@ -72,6 +72,8 @@ import static org.apache.cassandra.tcm.ClusterMetadataService.State.LOCAL;
import static org.apache.cassandra.tcm.compatibility.GossipHelper.emptyWithSchemaFromSystemTables;
import static org.apache.cassandra.tcm.compatibility.GossipHelper.fromEndpointStates;
import static org.apache.cassandra.tcm.membership.NodeState.JOINED;
+import static org.apache.cassandra.tcm.membership.NodeState.LEFT;
+import static org.apache.cassandra.tcm.membership.NodeState.REGISTERED;
import static org.apache.cassandra.utils.FBUtilities.getBroadcastAddressAndPort;
/**
@@ -365,13 +367,21 @@ import static org.apache.cassandra.utils.FBUtilities.getBroadcastAddressAndPort;
{
ClusterMetadata metadata = ClusterMetadata.current();
NodeId self = metadata.myNodeId();
- AccordService.startup(self);
// finish in-progress sequences first
InProgressSequences.finishInProgressSequences(self);
metadata = ClusterMetadata.current();
- switch (metadata.directory.peerState(self))
+ NodeState startingstate = metadata.directory.peerState(self);
+ switch (startingstate)
+ {
+ case REGISTERED:
+ case LEFT:
+ break;
+ default:
+ AccordService.startup(self);
+ }
+ switch (startingstate)
{
case REGISTERED:
case LEFT:
@@ -379,7 +389,10 @@ import static org.apache.cassandra.utils.FBUtilities.getBroadcastAddressAndPort;
ReconfigureCMS.maybeReconfigureCMS(metadata, DatabaseDescriptor.getReplaceAddress());
ClusterMetadataService.instance().commit(initialTransformation.get());
-
+ // When Accord starts up it needs to check for any historic epochs that it needs to know about (in order
+ // to handle pending transactions), in order to know what nodes to check with it needs to know what the
+ // settled placement is (so it knows what peers to reach out to).
+ AccordService.startup(self);
InProgressSequences.finishInProgressSequences(self);
metadata = ClusterMetadata.current();
diff --git a/test/distributed/org/apache/cassandra/distributed/shared/ClusterUtils.java b/test/distributed/org/apache/cassandra/distributed/shared/ClusterUtils.java
index a3a9f1fabd..41d552bcf3 100644
--- a/test/distributed/org/apache/cassandra/distributed/shared/ClusterUtils.java
+++ b/test/distributed/org/apache/cassandra/distributed/shared/ClusterUtils.java
@@ -25,6 +25,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -49,6 +50,7 @@ import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import accord.primitives.TxnId;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.Feature;
@@ -58,6 +60,7 @@ import org.apache.cassandra.distributed.api.IInstanceConfig;
import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.IMessageFilters;
import org.apache.cassandra.distributed.api.NodeToolResult;
+import org.apache.cassandra.distributed.api.SimpleQueryResult;
import org.apache.cassandra.distributed.impl.AbstractCluster;
import org.apache.cassandra.distributed.impl.InstanceConfig;
import org.apache.cassandra.distributed.impl.TestChangeListener;
@@ -77,7 +80,6 @@ import org.apache.cassandra.tcm.ClusterMetadataService;
import org.apache.cassandra.tcm.Commit;
import org.apache.cassandra.tcm.Epoch;
import org.apache.cassandra.tcm.Transformation;
-import org.apache.cassandra.tcm.log.Entry;
import org.apache.cassandra.tcm.membership.NodeId;
import org.apache.cassandra.tcm.ownership.ReplicaGroups;
import org.apache.cassandra.utils.Isolated;
@@ -90,6 +92,7 @@ import static org.apache.cassandra.config.CassandraRelevantProperties.BROADCAST_
import static org.apache.cassandra.config.CassandraRelevantProperties.REPLACE_ADDRESS_FIRST_BOOT;
import static org.apache.cassandra.config.CassandraRelevantProperties.RING_DELAY;
import static org.apache.cassandra.distributed.impl.DistributedTestSnitch.toCassandraInetAddressAndPort;
+import static org.apache.cassandra.schema.SchemaConstants.VIRTUAL_VIEWS;
import static org.assertj.core.api.Assertions.assertThat;
/**
@@ -1458,5 +1461,44 @@ public class ClusterUtils
{
System.setSecurityManager(new PreventSystemExit());
}
+
+ public static <T extends IInstance> LinkedHashMap<String, SimpleQueryResult> queryTxnState(AbstractCluster<T> cluster, TxnId txnId, int... nodes)
+ {
+ String cql = String.format("SELECT * FROM %s.txn_blocked_by WHERE txn_id=?", VIRTUAL_VIEWS);
+ LinkedHashMap<String, SimpleQueryResult> map = new LinkedHashMap<>();
+ Iterable<T> it = nodes.length == 0 ? cluster::iterator : cluster.get(nodes);
+ for (T i : it)
+ {
+ if (i.isShutdown())
+ continue;
+ SimpleQueryResult result = i.executeInternalWithResult(cql, txnId.toString());
+ map.put(i.toString(), result);
+ }
+ return map;
+ }
+
+ public static <T extends IInstance> String queryTxnStateAsString(AbstractCluster<T> cluster, TxnId txnId, int... nodes)
+ {
+ StringBuilder sb = new StringBuilder();
+ queryTxnStateAsString(sb, cluster, txnId, nodes);
+ return sb.toString();
+ }
+
+ public static <T extends IInstance> void queryTxnStateAsString(StringBuilder sb, AbstractCluster<T> cluster, TxnId txnId, int... nodes)
+ {
+ LinkedHashMap<String, SimpleQueryResult> map = queryTxnState(cluster, txnId, nodes);
+ for (var e : map.entrySet())
+ {
+ sb.append(e.getKey()).append(":\n");
+ SimpleQueryResult result = e.getValue();
+ if (!result.names().isEmpty())
+ sb.append(result.names()).append('\n');
+ while (result.hasNext())
+ {
+ var row = result.next();
+ sb.append(Arrays.asList(row.toObjectArray())).append('\n');
+ }
+ }
+ }
}
diff --git a/test/distributed/org/apache/cassandra/distributed/test/TestBaseImpl.java b/test/distributed/org/apache/cassandra/distributed/test/TestBaseImpl.java
index c529834204..1589f5dc4f 100644
--- a/test/distributed/org/apache/cassandra/distributed/test/TestBaseImpl.java
+++ b/test/distributed/org/apache/cassandra/distributed/test/TestBaseImpl.java
@@ -287,4 +287,27 @@ public class TestBaseImpl extends DistributedTestBase
asyncThread.start();
return task;
}
+
+ /**
+ * @see org.apache.cassandra.cql3.CQLTester#wrapInTxn(String...)
+ */
+ protected static String wrapInTxn(String... stmts)
+ {
+ return wrapInTxn(Arrays.asList(stmts));
+ }
+
+ protected static String wrapInTxn(List<String> stmts)
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.append("BEGIN TRANSACTION\n");
+ for (String stmt : stmts)
+ {
+ sb.append('\t').append(stmt);
+ if (!stmt.endsWith(";"))
+ sb.append(';');
+ sb.append('\n');
+ }
+ sb.append("COMMIT TRANSACTION");
+ return sb.toString();
+ }
}
diff --git a/test/distributed/org/apache/cassandra/distributed/test/accord/AccordCQLTestBase.java b/test/distributed/org/apache/cassandra/distributed/test/accord/AccordCQLTestBase.java
index c0956391b2..824498b229 100644
--- a/test/distributed/org/apache/cassandra/distributed/test/accord/AccordCQLTestBase.java
+++ b/test/distributed/org/apache/cassandra/distributed/test/accord/AccordCQLTestBase.java
@@ -389,6 +389,7 @@ public abstract class AccordCQLTestBase extends AccordTestBase
private void assertResultsFromAccordMatches(Cluster cluster, String accordRead, String simpleRead, int key)
{
+ accordRead = wrapInTxn(accordRead);
Object[][] simpleReadResult;
if (transactionalMode.ignoresSuppliedConsistencyLevel)
// With accord non-SERIAL write strategy the commit CL is effectively ANY so we need to read at SERIAL
diff --git a/test/distributed/org/apache/cassandra/distributed/test/accord/AccordHostReplacementTest.java b/test/distributed/org/apache/cassandra/distributed/test/accord/AccordHostReplacementTest.java
new file mode 100644
index 0000000000..80ca00cdaa
--- /dev/null
+++ b/test/distributed/org/apache/cassandra/distributed/test/accord/AccordHostReplacementTest.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.test.accord;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+
+import accord.utils.Gens;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.TokenSupplier;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.harry.HarryHelper;
+import org.apache.cassandra.harry.ddl.SchemaSpec;
+import org.apache.cassandra.harry.dsl.ReplayingHistoryBuilder;
+import org.apache.cassandra.harry.gen.Generators;
+import org.apache.cassandra.harry.sut.SystemUnderTest;
+import org.apache.cassandra.harry.sut.TokenPlacementModel;
+import org.apache.cassandra.harry.sut.injvm.InJvmSut;
+import org.apache.cassandra.harry.tracker.DefaultDataTracker;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+
+import static accord.utils.Property.qt;
+import static java.lang.String.format;
+import static org.apache.cassandra.distributed.shared.ClusterUtils.stopUnchecked;
+import static org.apache.cassandra.distributed.shared.ClusterUtils.waitForCMSToQuiesce;
+
+public class AccordHostReplacementTest extends TestBaseImpl
+{
+ private static final List<TransactionalMode> TRANSACTIONAL_MODES = Stream.of(TransactionalMode.values()).filter(t -> t.accordIsEnabled).collect(Collectors.toList());
+
+ @Test
+ public void hostReplace() throws IOException
+ {
+ // start 3 node cluster, then do a host replacement of one of the nodes
+ Cluster.Builder clusterBuilder = Cluster.build(3)
+ .withConfig(c -> c.with(Feature.values())
+ .set("accord.shard_count", "1"));
+ TokenSupplier tokenRing = TokenSupplier.evenlyDistributedTokens(3, clusterBuilder.getTokenCount());
+ int nodeToReplace = 2;
+ clusterBuilder = clusterBuilder.withTokenSupplier((TokenSupplier) node -> tokenRing.tokens(node == 4 ? nodeToReplace : node));
+ try (Cluster cluster = clusterBuilder.start())
+ {
+ fixDistributedSchemas(cluster);
+ init(cluster);
+
+ qt().withExamples(1).check(rs -> {
+ SchemaSpec schema = HarryHelper.schemaSpecBuilder(HarryHelper.KEYSPACE, "tbl")
+ .transactionalMode(Generators.toHarry(Gens.pick(TRANSACTIONAL_MODES).map(Optional::of)))
+ .surjection()
+ .inflate(rs.nextLong());
+ ReplayingHistoryBuilder harry = new ReplayingHistoryBuilder(rs.nextLong(), 100, 1, new DefaultDataTracker(), new InJvmSut(cluster), schema, new TokenPlacementModel.SimpleReplicationFactor(3), SystemUnderTest.ConsistencyLevel.ALL);
+ cluster.schemaChange(format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};", HarryHelper.KEYSPACE));
+ cluster.schemaChange(schema.compile().cql());
+ waitForCMSToQuiesce(cluster, cluster.get(1));
+
+ for (int i = 0; i < 1000; i++)
+ harry.insert();
+ harry.validateAll(harry.quiescentLocalChecker());
+
+ stopUnchecked(cluster.get(nodeToReplace));
+ ClusterUtils.replaceHostAndStart(cluster, cluster.get(nodeToReplace));
+
+ harry.validateAll(harry.quiescentLocalChecker());
+ });
+ }
+ }
+}
diff --git a/test/distributed/org/apache/cassandra/distributed/test/accord/AccordTestBase.java b/test/distributed/org/apache/cassandra/distributed/test/accord/AccordTestBase.java
index 6180a5fc54..318b922d29 100644
--- a/test/distributed/org/apache/cassandra/distributed/test/accord/AccordTestBase.java
+++ b/test/distributed/org/apache/cassandra/distributed/test/accord/AccordTestBase.java
@@ -35,6 +35,12 @@ import java.util.stream.StreamSupport;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
+
+import org.apache.cassandra.cql3.CQLStatement;
+import org.apache.cassandra.cql3.QueryProcessor;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.TableMetadata;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
@@ -84,11 +90,9 @@ import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.Verb;
-import org.apache.cassandra.schema.Schema;
-import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.service.accord.AccordService;
-import org.apache.cassandra.service.accord.AccordTestUtils;
import org.apache.cassandra.service.accord.api.AccordRoutingKey;
+import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.accord.exceptions.ReadPreemptedException;
import org.apache.cassandra.service.accord.exceptions.WritePreemptedException;
import org.apache.cassandra.service.consensus.TransactionalMode;
@@ -104,7 +108,6 @@ import static org.apache.cassandra.db.SystemKeyspace.CONSENSUS_MIGRATION_STATE;
import static org.apache.cassandra.db.SystemKeyspace.PAXOS;
import static org.apache.cassandra.distributed.api.ConsistencyLevel.ALL;
import static org.apache.cassandra.schema.SchemaConstants.SYSTEM_KEYSPACE_NAME;
-import static org.apache.cassandra.schema.SchemaConstants.VIRTUAL_VIEWS;
import static org.junit.Assert.assertArrayEquals;
public abstract class AccordTestBase extends TestBaseImpl
@@ -406,43 +409,27 @@ public abstract class AccordTestBase extends TestBaseImpl
}
- private static SimpleQueryResult executeWithRetry0(int count, Cluster cluster, String check, Object... boundValues)
+ private static SimpleQueryResult executeWithRetry0(int count, Cluster cluster, IInvokableInstance inst, String check, Object... boundValues)
{
try
{
- return execute(cluster, check, boundValues);
+ logger.info("Executing statement:\n{}", check);
+ return inst.coordinator().executeWithResult(check, ConsistencyLevel.ANY, boundValues);
}
catch (RuntimeException ex)
{
if (count <= MAX_RETRIES && (hasRootCause(ex, ReadPreemptedException.class) || hasRootCause(ex, WritePreemptedException.class) || hasRootCause(ex, Invalidated.class)))
{
logger.warn("[Retry attempt={}] Preempted failure for\n{}", count, check);
- return executeWithRetry0(count + 1, cluster, check, boundValues);
+ return executeWithRetry0(count + 1, cluster, inst, check, boundValues);
}
TxnId txnId = maybeExtractId(ex);
if (txnId != null)
{
// query the cluster to find its status...
- String cql = String.format("SELECT * FROM %s.txn_blocked_by WHERE txn_id=?", VIRTUAL_VIEWS);
StringBuilder sb = new StringBuilder();
sb.append("Txn ").append(txnId).append(" timed out...\n");
- for (IInvokableInstance inst : cluster)
- {
- if (inst.isShutdown())
- {
- sb.append(inst).append(": is down\n");
- continue;
- }
- sb.append(inst).append(":\n");
- SimpleQueryResult result = inst.executeInternalWithResult(cql, txnId.toString());
- if (!result.names().isEmpty())
- sb.append(result.names()).append('\n');
- while (result.hasNext())
- {
- var row = result.next();
- sb.append(Arrays.asList(row.toObjectArray())).append('\n');
- }
- }
+ ClusterUtils.queryTxnStateAsString(sb, cluster, txnId);
throw new AssertionError(sb.toString(), ex.getCause());
}
throw ex;
@@ -470,21 +457,37 @@ public abstract class AccordTestBase extends TestBaseImpl
public static SimpleQueryResult executeWithRetry(Cluster cluster, String check, Object... boundValues)
{
- check = wrapInTxn(check);
+ return executeWithRetry(cluster, cluster.get(1), check, boundValues);
+ }
+ public static SimpleQueryResult executeWithRetry(Cluster cluster, IInvokableInstance inst, String check, Object... boundValues)
+ {
// is this method safe?
- if (!isIdempotent(cluster, check))
+ if (!isIdempotent(inst, check))
throw new AssertionError("Unable to retry txn that is not idempotent: cql=\n" + check);
- return executeWithRetry0(0, cluster, check, boundValues);
+ return executeWithRetry0(0, cluster, inst, check, boundValues);
}
- private static boolean isIdempotent(Cluster cluster, String cql)
+ public static Boolean isIdempotent(IInvokableInstance inst, String cql)
{
- return cluster.get(1).callOnInstance(() -> {
- TransactionStatement stmt = AccordTestUtils.parse(cql);
- return isIdempotent(stmt);
+ return inst.callOnInstance(() -> {
+ CQLStatement.Raw parsed = QueryProcessor.parseStatement(cql);
+ if (parsed instanceof TransactionStatement.Parsed)
+ {
+ TransactionStatement stmt = (TransactionStatement) parsed.prepare(ClientState.forInternalCalls());
+ return isIdempotent(stmt);
+ }
+ else if (parsed instanceof ModificationStatement.Parsed)
+ {
+ ModificationStatement stmt = (ModificationStatement) parsed.prepare(ClientState.forInternalCalls());
+ return isIdempotent(stmt);
+ }
+ else
+ {
+ throw new IllegalArgumentException("Unexpected type: " + parsed.getClass());
+ }
});
}
diff --git a/test/distributed/org/apache/cassandra/distributed/test/accord/NewSchemaTest.java b/test/distributed/org/apache/cassandra/distributed/test/accord/NewSchemaTest.java
index 82c9e2f806..585e75d8e4 100644
--- a/test/distributed/org/apache/cassandra/distributed/test/accord/NewSchemaTest.java
+++ b/test/distributed/org/apache/cassandra/distributed/test/accord/NewSchemaTest.java
@@ -20,6 +20,7 @@ package org.apache.cassandra.distributed.test.accord;
import java.io.IOException;
import java.nio.ByteBuffer;
+import java.util.Arrays;
import java.util.List;
import org.junit.BeforeClass;
@@ -27,8 +28,11 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.apache.cassandra.cql3.ast.Select;
+import org.apache.cassandra.cql3.ast.Txn;
import org.apache.cassandra.distributed.api.SimpleQueryResult;
import org.apache.cassandra.service.accord.AccordService;
+import org.assertj.core.api.Assertions;
import static java.util.function.UnaryOperator.identity;
@@ -54,25 +58,29 @@ public class NewSchemaTest extends AccordTestBase
for (int i = 0; i < 20; i++)
{
String ks = "ks" + i;
- String table = ks + ".tbl" + i;
+ String tableName = "tbl" + i;
+ String table = ks + "." + tableName;
SHARED_CLUSTER.schemaChange("CREATE KEYSPACE " + ks + " WITH REPLICATION={'class':'SimpleStrategy', 'replication_factor': 1}");
SHARED_CLUSTER.schemaChange(String.format("CREATE TABLE %s (pk blob primary key) WITH transactional_mode='full'", table));
SHARED_CLUSTER.forEach(node -> node.runOnInstance(() -> AccordService.instance().setCacheSize(0)));
List<ByteBuffer> keys = tokensToKeys(tokens());
- read(table, keys).exec();
+ read(ks, tableName, keys).exec();
}
}
- private static Query read(String table, List<ByteBuffer> keys)
+ private static Query read(String ks, String table, List<ByteBuffer> keys)
{
assert !keys.isEmpty();
- StringBuilder sb = new StringBuilder();
+ Txn.Builder builder = new Txn.Builder();
for (int i = 0; i < keys.size(); i++)
- sb.append("let row").append(i).append(" = (select * from ").append(table).append(" where pk = ?);\n");
- sb.append("SELECT row0.pk;");
- return new Query(sb.toString(), keys.toArray());
+ builder.addLet("row" + i, new Select.Builder().withWildcard().withTable(ks, table).withColumnEquals("pk", keys.get(i)));
+ builder.addReturnReferences("row0.pk");
+ Txn txn = builder.build();
+ ByteBuffer[] binds = txn.bindsEncoded();
+ Assertions.assertThat(Arrays.asList(binds)).isEqualTo(keys);
+ return new Query(txn.toCQL(), binds);
}
private static class Query
diff --git a/test/distributed/org/apache/cassandra/fuzz/topology/AccordTopologyMixupTest.java b/test/distributed/org/apache/cassandra/fuzz/topology/AccordTopologyMixupTest.java
new file mode 100644
index 0000000000..9a222c7c05
--- /dev/null
+++ b/test/distributed/org/apache/cassandra/fuzz/topology/AccordTopologyMixupTest.java
@@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.fuzz.topology;
+
+import java.nio.ByteBuffer;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.coordinate.Exhausted;
+import accord.coordinate.Preempted;
+import accord.coordinate.Timeout;
+import accord.local.Node;
+import accord.primitives.Ranges;
+import accord.primitives.Seekables;
+import accord.primitives.TxnId;
+import accord.utils.Gen;
+import accord.utils.Gens;
+import accord.utils.Invariants;
+import accord.utils.Property;
+import accord.utils.Property.Command;
+import accord.utils.RandomSource;
+import org.apache.cassandra.config.CassandraRelevantProperties;
+import org.apache.cassandra.config.Config;
+import org.apache.cassandra.cql3.ast.Mutation;
+import org.apache.cassandra.cql3.ast.Statement;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.ConsistencyLevel;
+import org.apache.cassandra.distributed.api.IInstanceConfig;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.api.SimpleQueryResult;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.accord.AccordTestBase;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.accord.api.AccordAgent;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.utils.ASTGenerators;
+import org.apache.cassandra.utils.CassandraGenerators;
+import org.apache.cassandra.utils.Isolated;
+import org.apache.cassandra.utils.Shared;
+
+import static org.apache.cassandra.utils.AccordGenerators.fromQT;
+
+public class AccordTopologyMixupTest extends TopologyMixupTestBase<AccordTopologyMixupTest.Spec>
+{
+ private static final Logger logger = LoggerFactory.getLogger(AccordTopologyMixupTest.class);
+
+ static
+ {
+ CassandraRelevantProperties.ACCORD_AGENT_CLASS.setString(InterceptAgent.class.getName());
+ // enable most expensive debugging checks
+ CassandraRelevantProperties.ACCORD_KEY_PARANOIA_CPU.setString(Invariants.Paranoia.QUADRATIC.name());
+ CassandraRelevantProperties.ACCORD_KEY_PARANOIA_MEMORY.setString(Invariants.Paranoia.QUADRATIC.name());
+ CassandraRelevantProperties.ACCORD_KEY_PARANOIA_COSTFACTOR.setString(Invariants.ParanoiaCostFactor.HIGH.name());
+ }
+
+ private static final List<TransactionalMode> TRANSACTIONAL_MODES = Stream.of(TransactionalMode.values()).filter(t -> t.accordIsEnabled).collect(Collectors.toList());
+
+ @Override
+ protected Gen<State<Spec>> stateGen()
+ {
+ return AccordState::new;
+ }
+
+ @Override
+ protected void preCheck(Property.StatefulBuilder builder)
+ {
+ // if a failing seed is detected, populate here
+ // Example: builder.withSeed(42L);
+ }
+
+ private static Spec createSchemaSpec(RandomSource rs, Cluster cluster)
+ {
+ TransactionalMode mode = rs.pick(TRANSACTIONAL_MODES);
+ boolean enableMigration = allowsMigration(mode) && rs.nextBoolean();
+ TableMetadata metadata = fromQT(new CassandraGenerators.TableMetadataBuilder()
+ .withKeyspaceName(KEYSPACE)
+ .withTableKinds(TableMetadata.Kind.REGULAR)
+ .withKnownMemtables()
+ //TODO (coverage): include "fast_path = 'keyspace'" override
+ .withTransactionalMode(enableMigration ? TransactionalMode.off : mode)
+ .withoutEmpty()
+ .build())
+ .next(rs);
+ maybeCreateUDTs(cluster, metadata);
+ String schemaCQL = metadata.toCqlString(false, false, false);
+ logger.info("Creating test table:\n{}", schemaCQL);
+ cluster.schemaChange(schemaCQL);
+ if (enableMigration)
+ {
+ cluster.schemaChange("ALTER TABLE " + metadata + " WITH " + mode.asCqlParam());
+ cluster.get(1).nodetoolResult("consensus_admin", "begin-migration", "--target-protocol", "accord", metadata.keyspace, metadata.name).asserts().success();
+ }
+ return new Spec(mode, enableMigration, metadata);
+ }
+
+ private static BiFunction<RandomSource, State<Spec>, Command<State<Spec>, Void, ?>> cqlOperations(Spec spec)
+ {
+ Gen<Statement> select = (Gen<Statement>) (Gen<?>) fromQT(new ASTGenerators.SelectGenBuilder(spec.metadata).withLimit1().build());
+ Gen<Statement> mutation = (Gen<Statement>) (Gen<?>) fromQT(new ASTGenerators.MutationGenBuilder(spec.metadata).withoutTimestamp().build());
+ Gen<Statement> txn = (Gen<Statement>) (Gen<?>) fromQT(new ASTGenerators.TxnGenBuilder(spec.metadata).build());
+ Map<Gen<Statement>, Integer> operations = new LinkedHashMap<>();
+ operations.put(select, 1);
+ operations.put(mutation, 1);
+ operations.put(txn, 1);
+ Gen<Statement> statementGen = Gens.oneOf(operations);
+ return (rs, state) -> cqlOperation(rs, state, statementGen);
+ }
+
+ private static Command<State<Spec>, Void, ?> cqlOperation(RandomSource rs, State<Spec> state, Gen<Statement> statementGen)
+ {
+ Statement stmt = statementGen.next(rs);
+ String cql;
+ //TODO (usability): are there any transaction_modes that actually need simple mutations/select to be wrapped in a BEGIN TRANSACTION? If not then this logica can be simplified
+ if (stmt.kind() == Statement.Kind.TXN || stmt.kind() == Statement.Kind.MUTATION && ((Mutation) stmt).isCas())
+ cql = stmt.toCQL();
+ else cql = wrapInTxn(stmt.toCQL());
+ IInvokableInstance node = state.cluster.get(rs.pickInt(state.topologyHistory.up()));
+ return new Property.SimpleCommand<>(node + ": " + stmt.kind() + "; epoch=" + state.currentEpoch.get(), s2 -> executeTxn(s2.cluster, node, cql, stmt.bindsEncoded()));
+ }
+
+ private static boolean allowsMigration(TransactionalMode mode)
+ {
+ switch (mode)
+ {
+ case unsafe_writes:
+ case mixed_reads:
+ case full:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static SimpleQueryResult executeTxn(Cluster cluster, IInvokableInstance node, String stmt, ByteBuffer[] binds)
+ {
+ if (!AccordTestBase.isIdempotent(node, stmt))
+ {
+ // won't be able to retry...
+ return node.coordinator().executeWithResult(stmt, ConsistencyLevel.ANY, (Object[]) binds);
+ }
+ return AccordTestBase.executeWithRetry(cluster, node, stmt, (Object[]) binds);
+ }
+
+ private static void maybeCreateUDTs(Cluster cluster, TableMetadata metadata)
+ {
+ CassandraGenerators.visitUDTs(metadata, next -> {
+ String cql = next.toCqlString(false, false, false);
+ logger.warn("Creating UDT {}", cql);
+ cluster.schemaChange(cql);
+ });
+ }
+
+ public static class Spec implements TopologyMixupTestBase.SchemaSpec
+ {
+ private final TransactionalMode mode;
+ private final boolean enableMigration;
+ private final TableMetadata metadata;
+
+ public Spec(TransactionalMode mode, boolean enableMigration, TableMetadata metadata)
+ {
+ this.mode = mode;
+ this.enableMigration = enableMigration;
+ this.metadata = metadata;
+ }
+
+ @Override
+ public String name()
+ {
+ return metadata.name;
+ }
+
+ @Override
+ public String keyspaceName()
+ {
+ return metadata.keyspace;
+ }
+ }
+
+ private static class AccordState extends State<Spec> implements SharedState.Listener
+ {
+ private final List<Runnable> onError = new CopyOnWriteArrayList<>();
+
+ public AccordState(RandomSource rs)
+ {
+ super(rs, AccordTopologyMixupTest::createSchemaSpec, AccordTopologyMixupTest::cqlOperations);
+
+ SharedState.listeners.add(this);
+ }
+
+ @Override
+ protected void onConfigure(IInstanceConfig c)
+ {
+ c.set("accord.shard_count", 1)
+ .set("paxos_variant", Config.PaxosVariant.v2.name());
+ }
+
+ @Override
+ public void debugTxn(@Nullable Node.Id exclude, String type, TxnId txnId)
+ {
+ onError.add(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ // this runs in the main thread, so is actually thread safe
+ int[] up = topologyHistory.up();
+ logger.error("{} failed with txn id {}; global debug summary:\n{}", type, txnId, ClusterUtils.queryTxnStateAsString(cluster, txnId, up));
+ onError.remove(this);
+ }
+ });
+ }
+
+ @Override
+ public void close() throws Exception
+ {
+ for (Runnable r : onError)
+ {
+ try
+ {
+ r.run();
+ }
+ catch (Throwable t)
+ {
+ // TODO (correctness): how to handle?
+ logger.error("Unhandled error in onError listeners", t);
+ }
+ }
+ onError.clear();
+ SharedState.listeners.remove(this);
+ super.close();
+ }
+ }
+
+ @Shared
+ public static class SharedState
+ {
+ public interface Listener
+ {
+ void debugTxn(Node.Id node, String type, TxnId txnId);
+ }
+
+ public static final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
+
+ public static void debugTxn(@Nullable Integer node, String type, String id)
+ {
+ Node.Id nodeId = node == null ? null : new Node.Id(node);
+ TxnId txnId = TxnId.parse(id);
+ listeners.forEach(l -> l.debugTxn(nodeId, type, txnId));
+ }
+ }
+
+ @Isolated
+ public static class InterceptAgent extends AccordAgent
+ {
+ @Override
+ public void onFailedBarrier(TxnId id, Seekables<?, ?> keysOrRanges, Throwable cause)
+ {
+ if (cause instanceof Timeout || cause instanceof Preempted)
+ {
+ SharedState.debugTxn(null, "Repair Barrier", id.toString());
+ }
+ }
+
+ @Override
+ public void onFailedBootstrap(String phase, Ranges ranges, Runnable retry, Throwable failure)
+ {
+ if (failure instanceof Exhausted)
+ {
+ Exhausted e = (Exhausted) failure;
+ SharedState.debugTxn(self.id, "Bootstrap#" + phase, e.txnId().toString());
+ }
+ super.onFailedBootstrap(phase, ranges, retry, failure);
+ }
+ }
+}
diff --git a/test/distributed/org/apache/cassandra/fuzz/topology/TopologyMixupTestBase.java b/test/distributed/org/apache/cassandra/fuzz/topology/TopologyMixupTestBase.java
index 8e8c57b132..f3ef929eec 100644
--- a/test/distributed/org/apache/cassandra/fuzz/topology/TopologyMixupTestBase.java
+++ b/test/distributed/org/apache/cassandra/fuzz/topology/TopologyMixupTestBase.java
@@ -131,9 +131,9 @@ public abstract class TopologyMixupTestBase<S extends TopologyMixupTestBase.Sche
state -> ClusterUtils.waitForCMSToQuiesce(state.cluster, state.cmsGroup));
}
- private Command<State<S>, Void, ?> stopInstance(int toRemove)
+ private Command<State<S>, Void, ?> stopInstance(int toRemove, String why)
{
- return new SimpleCommand<>(state -> "Stop Node" + toRemove + " for Assassinate" + state.commandNamePostfix(),
+ return new SimpleCommand<>(state -> "Stop Node" + toRemove + " for " + why + state.commandNamePostfix(),
state -> {
IInvokableInstance inst = state.cluster.get(toRemove);
TopologyHistory.Node node = state.topologyHistory.node(toRemove);
@@ -180,7 +180,7 @@ public abstract class TopologyMixupTestBase<S extends TopologyMixupTestBase.Sche
while (picked == toRemove);
toCoordinate = picked;
}
- return multistep(stopInstance(toRemove),
+ return multistep(stopInstance(toRemove, "nodetool removenode"),
new SimpleCommand<>("nodetool removenode node" + toRemove + " from node" + toCoordinate + state.commandNamePostfix(), s2 -> {
TopologyHistory.Node node = s2.topologyHistory.node(toRemove);
node.status = TopologyHistory.Node.Status.BeingRemoved;
@@ -213,7 +213,7 @@ public abstract class TopologyMixupTestBase<S extends TopologyMixupTestBase.Sche
while (picked == toRemove);
toCoordinate = picked;
}
- return multistep(stopInstance(toRemove),
+ return multistep(stopInstance(toRemove, "nodetool assassinate"),
new SimpleCommand<>("nodetool assassinate node" + toRemove + " from node" + toCoordinate + state.commandNamePostfix(), s2 -> {
TopologyHistory.Node node = s2.topologyHistory.node(toRemove);
node.status = TopologyHistory.Node.Status.BeingAssassinated;
diff --git a/test/harry/main/org/apache/cassandra/harry/HarryHelper.java b/test/harry/main/org/apache/cassandra/harry/HarryHelper.java
index 9dc0fcfaf4..8db0d9b5a0 100644
--- a/test/harry/main/org/apache/cassandra/harry/HarryHelper.java
+++ b/test/harry/main/org/apache/cassandra/harry/HarryHelper.java
@@ -68,11 +68,9 @@ public class HarryHelper
return configuration;
}
- private static AtomicInteger counter = new AtomicInteger();
-
- public static Surjections.Surjection<SchemaSpec> schemaSpecGen(String keyspace, String prefix)
+ public static SchemaGenerators.Builder schemaSpecBuilder(String keyspace, String name)
{
- return new SchemaGenerators.Builder(keyspace, () -> prefix + counter.getAndIncrement())
+ return new SchemaGenerators.Builder(keyspace, () -> name)
.partitionKeySpec(1, 2,
ColumnSpec.int8Type,
ColumnSpec.int16Type,
@@ -108,7 +106,14 @@ public class HarryHelper
ColumnSpec.int64Type,
ColumnSpec.floatType,
ColumnSpec.doubleType,
- ColumnSpec.asciiType(4, 128))
+ ColumnSpec.asciiType(4, 128));
+ }
+
+ private static AtomicInteger counter = new AtomicInteger();
+
+ public static Surjections.Surjection<SchemaSpec> schemaSpecGen(String keyspace, String prefix)
+ {
+ return schemaSpecBuilder(keyspace, prefix + counter.getAndIncrement())
.surjection();
}
diff --git a/test/harry/main/org/apache/cassandra/harry/ddl/ColumnSpec.java b/test/harry/main/org/apache/cassandra/harry/ddl/ColumnSpec.java
index 88bd95d6a9..2dcaa4ace5 100644
--- a/test/harry/main/org/apache/cassandra/harry/ddl/ColumnSpec.java
+++ b/test/harry/main/org/apache/cassandra/harry/ddl/ColumnSpec.java
@@ -27,6 +27,19 @@ import java.util.Map;
import java.util.Objects;
import java.util.UUID;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.AsciiType;
+import org.apache.cassandra.db.marshal.BooleanType;
+import org.apache.cassandra.db.marshal.ByteType;
+import org.apache.cassandra.db.marshal.DoubleType;
+import org.apache.cassandra.db.marshal.FloatType;
+import org.apache.cassandra.db.marshal.Int32Type;
+import org.apache.cassandra.db.marshal.LongType;
+import org.apache.cassandra.db.marshal.ShortType;
+import org.apache.cassandra.db.marshal.TimeUUIDType;
+import org.apache.cassandra.db.marshal.TimestampType;
+import org.apache.cassandra.db.marshal.UTF8Type;
+import org.apache.cassandra.db.marshal.UUIDType;
import org.apache.cassandra.harry.gen.Bijections;
import org.apache.cassandra.harry.gen.StringBijection;
@@ -68,6 +81,12 @@ public class ColumnSpec<T>
{
return override;
}
+
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return type.asServerType();
+ }
},
kind);
}
@@ -201,6 +220,8 @@ public class ColumnSpec<T>
public abstract Bijections.Bijection<T> generator();
+ public abstract AbstractType<?> asServerType();
+
public int maxSize()
{
return generator().byteSize();
@@ -236,6 +257,12 @@ public class ColumnSpec<T>
{
return Bijections.INT8_GENERATOR;
}
+
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return ByteType.instance;
+ }
};
public static final DataType<Short> int16Type = new DataType<Short>("smallint")
@@ -244,6 +271,12 @@ public class ColumnSpec<T>
{
return Bijections.INT16_GENERATOR;
}
+
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return ShortType.instance;
+ }
};
public static final DataType<Integer> int32Type = new DataType<Integer>("int")
@@ -252,6 +285,12 @@ public class ColumnSpec<T>
{
return Bijections.INT32_GENERATOR;
}
+
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return Int32Type.instance;
+ }
};
public static final DataType<Long> int64Type = new DataType<Long>("bigint")
@@ -260,6 +299,12 @@ public class ColumnSpec<T>
{
return Bijections.INT64_GENERATOR;
}
+
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return LongType.instance;
+ }
};
public static final DataType<Boolean> booleanType = new DataType<Boolean>("boolean")
@@ -269,6 +314,12 @@ public class ColumnSpec<T>
return Bijections.BOOLEAN_GENERATOR;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return BooleanType.instance;
+ }
+
public int compareLexicographically(long l, long r)
{
throw new RuntimeException("Boolean does not support custom comparators");
@@ -281,6 +332,12 @@ public class ColumnSpec<T>
{
return Bijections.FLOAT_GENERATOR;
}
+
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return FloatType.instance;
+ }
};
public static final DataType<Double> doubleType = new DataType<Double>("double")
@@ -289,6 +346,12 @@ public class ColumnSpec<T>
{
return Bijections.DOUBLE_GENERATOR;
}
+
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return DoubleType.instance;
+ }
};
public static final DataType<String> asciiType = new DataType<String>("ascii")
@@ -300,6 +363,12 @@ public class ColumnSpec<T>
return gen;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return AsciiType.instance;
+ }
+
public int compareLexicographically(long l, long r)
{
return Long.compare(l, r);
@@ -315,6 +384,12 @@ public class ColumnSpec<T>
return gen;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return UTF8Type.instance;
+ }
+
public int compareLexicographically(long l, long r)
{
return Long.compare(l, r);
@@ -332,6 +407,12 @@ public class ColumnSpec<T>
return gen;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return AsciiType.instance;
+ }
+
public int compareLexicographically(long l, long r)
{
return Long.compare(l, r);
@@ -354,6 +435,12 @@ public class ColumnSpec<T>
return Bijections.UUID_GENERATOR;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return UUIDType.instance;
+ }
+
public int compareLexicographically(long l, long r)
{
throw new RuntimeException("UUID does not support custom comparators");
@@ -367,6 +454,12 @@ public class ColumnSpec<T>
return Bijections.TIME_UUID_GENERATOR;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return TimeUUIDType.instance;
+ }
+
public int compareLexicographically(long l, long r)
{
throw new RuntimeException("UUID does not support custom comparators");
@@ -380,6 +473,12 @@ public class ColumnSpec<T>
return Bijections.TIMESTAMP_GENERATOR;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return TimestampType.instance;
+ }
+
public int compareLexicographically(long l, long r)
{
throw new RuntimeException("Date does not support custom comparators");
@@ -443,6 +542,12 @@ public class ColumnSpec<T>
return generator;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ return org.apache.cassandra.db.marshal.ReversedType.getInstance(baseType.asServerType());
+ }
+
public int maxSize()
{
return baseType.maxSize();
diff --git a/test/harry/main/org/apache/cassandra/harry/ddl/SchemaGenerators.java b/test/harry/main/org/apache/cassandra/harry/ddl/SchemaGenerators.java
index 7f1a8790bd..145c59c2e0 100644
--- a/test/harry/main/org/apache/cassandra/harry/ddl/SchemaGenerators.java
+++ b/test/harry/main/org/apache/cassandra/harry/ddl/SchemaGenerators.java
@@ -25,6 +25,8 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -32,6 +34,7 @@ import java.util.function.Supplier;
import org.apache.cassandra.config.CassandraRelevantProperties;
import org.apache.cassandra.harry.gen.Generator;
import org.apache.cassandra.harry.gen.Surjections;
+import org.apache.cassandra.service.consensus.TransactionalMode;
public class SchemaGenerators
{
@@ -177,6 +180,7 @@ public class SchemaGenerators
private Generator<ColumnSpec<?>> ckGenerator = clusteringColumnSpecGenerator("ck");
private Generator<ColumnSpec<?>> regularGenerator = columnSpecGenerator("regular", ColumnSpec.Kind.REGULAR);
private Generator<ColumnSpec<?>> staticGenerator = columnSpecGenerator("static", ColumnSpec.Kind.STATIC);
+ private Generator<Optional<TransactionalMode>> transactionalModeGenerator = ignore -> Optional.empty();
private int minPks = 1;
private int maxPks = 1;
@@ -298,6 +302,17 @@ public class SchemaGenerators
return this;
}
+ public Builder transactionalMode(Generator<Optional<TransactionalMode>> transactionalModeGenerator)
+ {
+ this.transactionalModeGenerator = Objects.requireNonNull(transactionalModeGenerator);
+ return this;
+ }
+
+ public Builder transactionalMode(TransactionalMode mode)
+ {
+ return transactionalMode(ignore -> Optional.of(mode));
+ }
+
private static class ColumnCounts
{
private final int pks;
@@ -339,7 +354,8 @@ public class SchemaGenerators
pk,
ck,
regularGenerator.generate(rand, counts.regulars),
- staticGenerator.generate(rand, counts.statics));
+ staticGenerator.generate(rand, counts.statics),
+ transactionalModeGenerator.generate(rand));
};
});
}
diff --git a/test/harry/main/org/apache/cassandra/harry/ddl/SchemaSpec.java b/test/harry/main/org/apache/cassandra/harry/ddl/SchemaSpec.java
index 407059dfce..de41908237 100644
--- a/test/harry/main/org/apache/cassandra/harry/ddl/SchemaSpec.java
+++ b/test/harry/main/org/apache/cassandra/harry/ddl/SchemaSpec.java
@@ -21,11 +21,17 @@ package org.apache.cassandra.harry.ddl;
import java.util.*;
import java.util.function.Consumer;
+import javax.annotation.Nullable;
+
import org.apache.cassandra.harry.gen.DataGenerators;
import org.apache.cassandra.harry.sut.SystemUnderTest;
import org.apache.cassandra.harry.operations.CompiledStatement;
import org.apache.cassandra.harry.operations.Relation;
import org.apache.cassandra.harry.util.BitSet;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+
+import static org.apache.cassandra.harry.ddl.ColumnSpec.int64Type;
+import static org.apache.cassandra.harry.gen.Collections.listColumn;
public class SchemaSpec
{
@@ -52,6 +58,7 @@ public class SchemaSpec
public final List<ColumnSpec<?>> staticColumns;
public final List<ColumnSpec<?>> allColumns;
public final Set<ColumnSpec<?>> allColumnsSet;
+ public final Optional<TransactionalMode> transactionalMode;
public final BitSet ALL_COLUMNS_BITSET;
public final int regularColumnsOffset;
@@ -67,51 +74,73 @@ public class SchemaSpec
List<ColumnSpec<?>> regularColumns,
List<ColumnSpec<?>> staticColumns)
{
- this(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, DataGenerators.createKeyGenerator(clusteringKeys), false, false, null, false);
+ this(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, Optional.empty());
+ }
+
+ public SchemaSpec(String keyspace,
+ String table,
+ List<ColumnSpec<?>> partitionKeys,
+ List<ColumnSpec<?>> clusteringKeys,
+ List<ColumnSpec<?>> regularColumns,
+ List<ColumnSpec<?>> staticColumns,
+ Optional<TransactionalMode> transactionalMode)
+ {
+ this(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, DataGenerators.createKeyGenerator(clusteringKeys), false, false, null, false, transactionalMode);
}
public SchemaSpec cloneWithName(String ks,
String table)
{
- return new SchemaSpec(ks, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, isCompactStorage, disableReadRepair, compactionStrategy, trackLts);
+ return new SchemaSpec(ks, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, isCompactStorage, disableReadRepair, compactionStrategy, trackLts, transactionalMode);
}
public SchemaSpec trackLts()
{
- return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, isCompactStorage, disableReadRepair, compactionStrategy, true);
+ return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, isCompactStorage, disableReadRepair, compactionStrategy, true, transactionalMode);
}
public SchemaSpec withCompactStorage()
{
- return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, true, disableReadRepair, compactionStrategy, trackLts);
+ return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, true, disableReadRepair, compactionStrategy, trackLts, transactionalMode);
}
public SchemaSpec withCompactionStrategy(String compactionStrategy)
{
- return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, false, disableReadRepair, compactionStrategy, trackLts);
+ return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, false, disableReadRepair, compactionStrategy, trackLts, transactionalMode);
}
public SchemaSpec withCkGenerator(DataGenerators.KeyGenerator ckGeneratorOverride, List<ColumnSpec<?>> clusteringKeys)
{
- return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGeneratorOverride, isCompactStorage, disableReadRepair, compactionStrategy, trackLts);
+ return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGeneratorOverride, isCompactStorage, disableReadRepair, compactionStrategy, trackLts, transactionalMode);
}
public SchemaSpec withColumns(List<ColumnSpec<?>> regularColumns, List<ColumnSpec<?>> staticColumns)
{
- return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, isCompactStorage, disableReadRepair, compactionStrategy, trackLts);
+ return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, isCompactStorage, disableReadRepair, compactionStrategy, trackLts, transactionalMode);
}
- public SchemaSpec(String keyspace,
- String table,
- List<ColumnSpec<?>> partitionKeys,
- List<ColumnSpec<?>> clusteringKeys,
- List<ColumnSpec<?>> regularColumns,
- List<ColumnSpec<?>> staticColumns,
- DataGenerators.KeyGenerator ckGenerator,
- boolean isCompactStorage,
- boolean disableReadRepair,
- String compactionStrategy,
- boolean trackLts)
+ public SchemaSpec withTransactionMode(TransactionalMode transactionalMode)
+ {
+ return withTransactionMode(Optional.ofNullable(transactionalMode));
+ }
+
+ public SchemaSpec withTransactionMode(Optional<TransactionalMode> transactionalMode)
+ {
+ return new SchemaSpec(keyspace, table, partitionKeys, clusteringKeys, regularColumns, staticColumns, ckGenerator, isCompactStorage, disableReadRepair, compactionStrategy, trackLts, transactionalMode);
+ }
+
+ private SchemaSpec(String keyspace,
+ String table,
+ List<ColumnSpec<?>> partitionKeys,
+ List<ColumnSpec<?>> clusteringKeys,
+ List<ColumnSpec<?>> regularColumns,
+ List<ColumnSpec<?>> staticColumns,
+ DataGenerators.KeyGenerator ckGenerator,
+ boolean isCompactStorage,
+ boolean disableReadRepair,
+ String compactionStrategy,
+ boolean trackLts,
+ Optional<TransactionalMode> transactionalMode)
{
assert !isCompactStorage || clusteringKeys.isEmpty() || regularColumns.size() <= 1 :
String.format("Compact storage %s. Clustering keys: %d. Regular columns: %d", isCompactStorage, clusteringKeys.size(), regularColumns.size());
@@ -121,6 +150,7 @@ public class SchemaSpec
this.isCompactStorage = isCompactStorage;
this.disableReadRepair = disableReadRepair;
this.compactionStrategy = compactionStrategy;
+ this.transactionalMode = transactionalMode;
this.partitionKeys = Collections.unmodifiableList(new ArrayList<>(partitionKeys));
for (int i = 0; i < partitionKeys.size(); i++)
@@ -162,7 +192,12 @@ public class SchemaSpec
this.trackLts = trackLts;
}
-
+ @Nullable
+ public ColumnSpec<List<Long>> ltsColumn()
+ {
+ if (!trackLts) return null;
+ return new ColumnSpec<>("visited_lts", listColumn(int64Type, Integer.MAX_VALUE), ColumnSpec.Kind.STATIC);
+ }
public static BitSet allColumnsMask(SchemaSpec schema)
{
@@ -286,6 +321,12 @@ public class SchemaSpec
return DataGenerators.deflateData(regularColumns, regulars);
}
+ public boolean isWriteTimeFromAccord()
+ {
+
+ return transactionalMode.isPresent() && transactionalMode.get().writesThroughAccord;
+ }
+
public CompiledStatement compile()
{
StringBuilder sb = new StringBuilder();
@@ -343,6 +384,12 @@ public class SchemaSpec
sb.append(" compaction = {'class': '").append(compactionStrategy).append("'} AND");
}
+ if (transactionalMode.isPresent())
+ {
+ appendWith.run();
+ sb.append(' ').append(transactionalMode.get().asCqlParam()).append(" AND");
+ }
+
if (clusteringKeys.size() > 0)
{
appendWith.run();
diff --git a/test/harry/main/org/apache/cassandra/harry/gen/Collections.java b/test/harry/main/org/apache/cassandra/harry/gen/Collections.java
index 22ff5b6565..0556de1805 100644
--- a/test/harry/main/org/apache/cassandra/harry/gen/Collections.java
+++ b/test/harry/main/org/apache/cassandra/harry/gen/Collections.java
@@ -25,6 +25,10 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.ListType;
+import org.apache.cassandra.db.marshal.MapType;
+import org.apache.cassandra.db.marshal.SetType;
import org.apache.cassandra.harry.ddl.ColumnSpec;
import org.apache.cassandra.harry.gen.rng.RngUtils;
@@ -44,6 +48,13 @@ public class Collections
return gen;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ //TODO (correctness): no way to know if this is frozen or not... so can't actually define isMultiCell correctly...
+ return MapType.getInstance(k.asServerType(), v.asServerType(), false);
+ }
+
public int maxSize()
{
return Long.BYTES;
@@ -54,7 +65,7 @@ public class Collections
public static <V> ColumnSpec.DataType<List<V>> listColumn(ColumnSpec.DataType<V> v,
int maxSize)
{
- return new ColumnSpec.DataType<List<V>>(String.format("set<%s>", v.toString()))
+ return new ColumnSpec.DataType<List<V>>(String.format("list<%s>", v.toString()))
{
private final Bijections.Bijection<List<V>> gen = listGen(v.generator(), maxSize);
@@ -63,6 +74,13 @@ public class Collections
return gen;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ //TODO (correctness): no way to know if this is frozen or not... so can't actually define isMultiCell correctly...
+ return ListType.getInstance(v.asServerType(), false);
+ }
+
public int maxSize()
{
return Long.BYTES;
@@ -83,6 +101,13 @@ public class Collections
return gen;
}
+ @Override
+ public AbstractType<?> asServerType()
+ {
+ //TODO (correctness): no way to know if this is frozen or not... so can't actually define isMultiCell correctly...
+ return SetType.getInstance(v.asServerType(), false);
+ }
+
public int maxSize()
{
return Long.BYTES;
diff --git a/test/harry/main/org/apache/cassandra/harry/gen/EntropyRandomSource.java b/test/harry/main/org/apache/cassandra/harry/gen/EntropyRandomSource.java
new file mode 100644
index 0000000000..63f62ab7e2
--- /dev/null
+++ b/test/harry/main/org/apache/cassandra/harry/gen/EntropyRandomSource.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.harry.gen;
+
+import accord.utils.RandomSource;
+
+public class EntropyRandomSource implements RandomSource
+{
+ private final EntropySource delegate;
+
+ public EntropyRandomSource(EntropySource delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void nextBytes(byte[] bytes)
+ {
+ for (int i = 0, len = bytes.length; i < len; )
+ for (int rnd = nextInt(),
+ n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
+ n-- > 0; rnd >>= Byte.SIZE)
+ bytes[i++] = (byte)rnd;
+ }
+
+ @Override
+ public boolean nextBoolean()
+ {
+ return delegate.nextBoolean();
+ }
+
+ @Override
+ public int nextInt()
+ {
+ return delegate.nextInt();
+ }
+
+ @Override
+ public long nextLong()
+ {
+ return ((long) nextInt() << 32) + nextInt();
+ }
+
+ @Override
+ public float nextFloat()
+ {
+ return delegate.nextFloat();
+ }
+
+ @Override
+ public double nextDouble()
+ {
+ throw new UnsupportedOperationException("TODO: Implement");
+ }
+
+ @Override
+ public double nextGaussian()
+ {
+ throw new UnsupportedOperationException("TODO: Implement");
+ }
+
+ @Override
+ public void setSeed(long seed)
+ {
+ delegate.seed(seed);
+ }
+
+ @Override
+ public RandomSource fork()
+ {
+ return new EntropyRandomSource(delegate.derive());
+ }
+}
diff --git a/test/harry/main/org/apache/cassandra/harry/gen/Generators.java b/test/harry/main/org/apache/cassandra/harry/gen/Generators.java
index ed966a96ed..a00c8b54bb 100644
--- a/test/harry/main/org/apache/cassandra/harry/gen/Generators.java
+++ b/test/harry/main/org/apache/cassandra/harry/gen/Generators.java
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
+import accord.utils.Gen;
import org.apache.cassandra.locator.InetAddressAndPort;
public class Generators
@@ -119,4 +120,14 @@ public class Generators
{
return (random) -> constant.get();
}
+
+ public static <T> Gen<T> toAccord(Generator<T> gen)
+ {
+ return rng -> gen.generate(new RandomSourceEntropySource(rng));
+ }
+
+ public static <T> Generator<T> toHarry(Gen<T> gen)
+ {
+ return rng -> gen.next(new EntropyRandomSource(rng));
+ }
}
\ No newline at end of file
diff --git a/test/harry/main/org/apache/cassandra/harry/gen/RandomSourceEntropySource.java b/test/harry/main/org/apache/cassandra/harry/gen/RandomSourceEntropySource.java
new file mode 100644
index 0000000000..2c2084359d
--- /dev/null
+++ b/test/harry/main/org/apache/cassandra/harry/gen/RandomSourceEntropySource.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.harry.gen;
+
+import accord.utils.RandomSource;
+
+public class RandomSourceEntropySource implements EntropySource
+{
+ private final RandomSource delegate;
+
+ public RandomSourceEntropySource(RandomSource delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public long next()
+ {
+ return delegate.nextLong();
+ }
+
+ @Override
+ public void seed(long seed)
+ {
+ delegate.setSeed(seed);
+ }
+
+ @Override
+ public EntropySource derive()
+ {
+ return new RandomSourceEntropySource(delegate.fork());
+ }
+
+ @Override
+ public int nextInt()
+ {
+ return delegate.nextInt();
+ }
+
+ @Override
+ public int nextInt(int max)
+ {
+ return delegate.nextInt(max);
+ }
+
+ @Override
+ public int nextInt(int min, int max)
+ {
+ return delegate.nextInt(min, max);
+ }
+
+ @Override
+ public float nextFloat()
+ {
+ return delegate.nextFloat();
+ }
+
+ @Override
+ public boolean nextBoolean()
+ {
+ return delegate.nextBoolean();
+ }
+}
diff --git a/test/harry/main/org/apache/cassandra/harry/model/QuiescentChecker.java b/test/harry/main/org/apache/cassandra/harry/model/QuiescentChecker.java
index 64af6520d5..5f3085fd62 100644
--- a/test/harry/main/org/apache/cassandra/harry/model/QuiescentChecker.java
+++ b/test/harry/main/org/apache/cassandra/harry/model/QuiescentChecker.java
@@ -21,6 +21,8 @@ package org.apache.cassandra.harry.model;
import java.util.*;
import java.util.function.Supplier;
+import javax.annotation.Nullable;
+
import org.apache.cassandra.harry.core.Run;
import org.apache.cassandra.harry.data.ResultSetRow;
import org.apache.cassandra.harry.ddl.ColumnSpec;
@@ -82,8 +84,7 @@ public class QuiescentChecker implements Model
public static void validate(SchemaSpec schema, DataTracker tracker, PartitionState partitionState, List<ResultSetRow> actualRows, Query query)
{
- Set<ColumnSpec<?>> columns = new HashSet<>();
- columns.addAll(schema.allColumns);
+ Set<ColumnSpec<?>> columns = schema.isWriteTimeFromAccord() ? null : new HashSet<>(schema.allColumns);
validate(schema, tracker, columns, partitionState, actualRows, query);
}
@@ -106,7 +107,7 @@ public class QuiescentChecker implements Model
return newRowState;
}
- public static void validate(SchemaSpec schema, DataTracker tracker, Set<ColumnSpec<?>> selection, PartitionState partitionState, List<ResultSetRow> actualRows, Query query)
+ public static void validate(SchemaSpec schema, DataTracker tracker, @Nullable Set<ColumnSpec<?>> selection, PartitionState partitionState, List<ResultSetRow> actualRows, Query query)
{
boolean isWildcardQuery = selection == null;
String trackerBefore = tracker.toString();
diff --git a/test/harry/main/org/apache/cassandra/harry/model/QuiescentLocalStateCheckerBase.java b/test/harry/main/org/apache/cassandra/harry/model/QuiescentLocalStateCheckerBase.java
index 54ea8638b9..d9f7af8781 100644
--- a/test/harry/main/org/apache/cassandra/harry/model/QuiescentLocalStateCheckerBase.java
+++ b/test/harry/main/org/apache/cassandra/harry/model/QuiescentLocalStateCheckerBase.java
@@ -91,7 +91,8 @@ public abstract class QuiescentLocalStateCheckerBase extends QuiescentChecker
protected void validate(Query query, TokenPlacementModel.ReplicatedRanges ring)
{
- CompiledStatement compiled = query.toSelectStatement();
+ boolean isAccord = query.schemaSpec.isWriteTimeFromAccord();
+ CompiledStatement compiled = isAccord ? query.toWildcardSelectStatement() : query.toSelectStatement();
List<Replica> replicas = ring.replicasFor(token(query.pd));
logger.trace("Predicted {} as replicas for {}. Ring: {}", replicas, query.pd, ring);
@@ -104,7 +105,7 @@ public abstract class QuiescentLocalStateCheckerBase extends QuiescentChecker
List<ResultSetRow> result = new ArrayList<>();
for (Object[] obj : objects)
- result.add(resultSetToRow(query.schemaSpec, clock, obj));
+ result.add(resultSetToRow(query.schemaSpec, clock, isAccord ? SelectHelper.broadenResult(query.schemaSpec, null, obj) : obj));
return result;
}, query);
diff --git a/test/harry/main/org/apache/cassandra/harry/model/SelectHelper.java b/test/harry/main/org/apache/cassandra/harry/model/SelectHelper.java
index b2888afa19..e053ce7683 100644
--- a/test/harry/main/org/apache/cassandra/harry/model/SelectHelper.java
+++ b/test/harry/main/org/apache/cassandra/harry/model/SelectHelper.java
@@ -20,6 +20,12 @@ package org.apache.cassandra.harry.model;
import java.util.*;
+import org.apache.cassandra.cql3.ast.Bind;
+import org.apache.cassandra.cql3.ast.FunctionCall;
+import org.apache.cassandra.cql3.ast.Reference;
+import org.apache.cassandra.cql3.ast.Select;
+import org.apache.cassandra.cql3.ast.Symbol;
+import org.apache.cassandra.cql3.ast.Where;
import org.apache.cassandra.harry.data.ResultSetRow;
import org.apache.cassandra.harry.ddl.ColumnSpec;
import org.apache.cassandra.harry.ddl.SchemaSpec;
@@ -61,20 +67,13 @@ public class SelectHelper
public static CompiledStatement select(SchemaSpec schema, Long pd, Set<ColumnSpec<?>> columns, List<Relation> relations, boolean reverse, boolean includeWriteTime)
{
- boolean isWildcardQuery = columns == null;
- if (isWildcardQuery)
+ Select.Builder builder = new Select.Builder();
+ if (columns == null)
{
+ // these are not touched in this case, but still better to be safe than sorry
columns = schema.allColumnsSet;
includeWriteTime = false;
- }
-
- StringBuilder b = new StringBuilder();
- b.append("SELECT ");
-
- boolean isFirst = true;
- if (isWildcardQuery)
- {
- b.append("*");
+ builder.withWildcard();
}
else
{
@@ -84,61 +83,36 @@ public class SelectHelper
if (columns != null && !columns.contains(spec))
continue;
- if (isFirst)
- isFirst = false;
- else
- b.append(", ");
- b.append(spec.name);
+ builder.withColumnSelection(spec.name, spec.type.asServerType());
}
- }
- if (includeWriteTime)
- {
- for (ColumnSpec<?> spec : schema.staticColumns)
+ if (includeWriteTime)
{
- if (columns != null && !columns.contains(spec))
- continue;
- b.append(", ")
- .append("writetime(")
- .append(spec.name)
- .append(")");
+ for (ColumnSpec<?> spec : schema.staticColumns)
+ {
+ if (columns != null && !columns.contains(spec))
+ continue;
+ builder.withSelection(FunctionCall.writetime(spec.name, spec.type.asServerType()));
+ }
+
+ for (ColumnSpec<?> spec : schema.regularColumns)
+ {
+ if (columns != null && !columns.contains(spec))
+ continue;
+ builder.withSelection(FunctionCall.writetime(spec.name, spec.type.asServerType()));
+ }
}
- for (ColumnSpec<?> spec : schema.regularColumns)
+ if (schema.trackLts)
{
- if (columns != null && !columns.contains(spec))
- continue;
- b.append(", ")
- .append("writetime(")
- .append(spec.name)
- .append(")");
+ ColumnSpec<?> spec = schema.ltsColumn();
+ builder.withColumnSelection(spec.name, spec.type.asServerType());
}
}
- if (schema.trackLts)
- b.append(", visited_lts");
+ builder.withTable(schema.keyspace, schema.table);
- b.append(" FROM ")
- .append(schema.keyspace)
- .append(".")
- .append(schema.table)
- .append(" WHERE ");
-
- List<Object> bindings = new ArrayList<>();
-
- SchemaSpec.AddRelationCallback consumer = new SchemaSpec.AddRelationCallback()
- {
- boolean isFirst = true;
- public void accept(ColumnSpec<?> spec, Relation.RelationKind kind, Object value)
- {
- if (isFirst)
- isFirst = false;
- else
- b.append(" AND ");
- b.append(kind.getClause(spec));
- bindings.add(value);
- }
- };
+ SchemaSpec.AddRelationCallback consumer = appendToBuilderCallback(builder);
if (pd != null)
{
Object[] pk = schema.inflatePartitionKey(pd);
@@ -148,68 +122,71 @@ public class SelectHelper
}
schema.inflateRelations(relations, consumer);
- addOrderBy(schema, b, reverse);
- b.append(";");
- Object[] bindingsArr = bindings.toArray(new Object[bindings.size()]);
- return new CompiledStatement(b.toString(), bindingsArr);
+ addOrderBy(schema, builder, reverse);
+
+ return toCompiled(builder.build());
}
public static CompiledStatement count(SchemaSpec schema, long pd)
{
- StringBuilder b = new StringBuilder();
- b.append("SELECT count(*) ");
-
- b.append(" FROM ")
- .append(schema.keyspace)
- .append(".")
- .append(schema.table)
- .append(" WHERE ");
-
- List<Object> bindings = new ArrayList<>(schema.partitionKeys.size());
-
- schema.inflateRelations(pd,
- Collections.emptyList(),
- new SchemaSpec.AddRelationCallback()
- {
- boolean isFirst = true;
- public void accept(ColumnSpec<?> spec, Relation.RelationKind kind, Object value)
- {
- if (isFirst)
- isFirst = false;
- else
- b.append(" AND ");
- b.append(kind.getClause(spec));
- bindings.add(value);
- }
- });
-
- Object[] bindingsArr = bindings.toArray(new Object[bindings.size()]);
- return new CompiledStatement(b.toString(), bindingsArr);
+ Select.Builder builder = new Select.Builder();
+ builder.withSelection(FunctionCall.countStar());
+ builder.withTable(schema.keyspace, schema.table);
+ schema.inflateRelations(pd, Collections.emptyList(), appendToBuilderCallback(builder));
+
+ return toCompiled(builder.build());
}
- private static void addOrderBy(SchemaSpec schema, StringBuilder b, boolean reverse)
+ private static SchemaSpec.AddRelationCallback appendToBuilderCallback(Select.Builder builder)
{
- if (reverse && schema.clusteringKeys.size() > 0)
+ return (spec, kind, value) ->
+ builder.withWhere(toInequalities(kind), Reference.of(new Symbol(spec.name, spec.type.asServerType())), new Bind(value, spec.type.asServerType()));
+ }
+
+ private static Where.Inequalities toInequalities(Relation.RelationKind kind)
+ {
+ Where.Inequalities inequalities;
+ switch (kind)
{
- b.append(" ORDER BY ");
- for (int i = 0; i < schema.clusteringKeys.size(); i++)
- {
- ColumnSpec<?> c = schema.clusteringKeys.get(i);
- if (i > 0)
- b.append(", ");
- b.append(c.isReversed() ? asc(c.name) : desc(c.name));
- }
+ case LT:
+ inequalities = Where.Inequalities.LESS_THAN;
+ break;
+ case LTE:
+ inequalities = Where.Inequalities.LESS_THAN_EQ;
+ break;
+ case GT:
+ inequalities = Where.Inequalities.GREATER_THAN;
+ break;
+ case GTE:
+ inequalities = Where.Inequalities.GREATER_THAN_EQ;
+ break;
+ case EQ:
+ inequalities = Where.Inequalities.EQUAL;
+ break;
+ default:
+ throw new UnsupportedOperationException("Unknown kind: " + kind);
}
+ return inequalities;
}
- public static String asc(String name)
+ private static CompiledStatement toCompiled(Select select)
{
- return name + " ASC";
+ // Select does not add ';' by default, but CompiledStatement expects this
+ String cql = select.toCQL() + ";";
+ Object[] bindingsArr = select.binds();
+ return new CompiledStatement(cql, bindingsArr);
}
- public static String desc(String name)
+ private static void addOrderBy(SchemaSpec schema, Select.Builder builder, boolean reverse)
{
- return name + " DESC";
+ if (reverse && schema.clusteringKeys.size() > 0)
+ {
+ for (int i = 0; i < schema.clusteringKeys.size(); i++)
+ {
+ ColumnSpec<?> c = schema.clusteringKeys.get(i);
+ builder.withOrderByColumn(c.name, c.type.asServerType(), c.isReversed() ? Select.OrderBy.Ordering.ASC : Select.OrderBy.Ordering.DESC);
+ }
+ }
}
diff --git a/test/harry/main/org/apache/cassandra/harry/operations/Query.java b/test/harry/main/org/apache/cassandra/harry/operations/Query.java
index 2ca8a429ee..0b73b9a135 100644
--- a/test/harry/main/org/apache/cassandra/harry/operations/Query.java
+++ b/test/harry/main/org/apache/cassandra/harry/operations/Query.java
@@ -251,6 +251,11 @@ public abstract class Query
}
}
+ public CompiledStatement toWildcardSelectStatement()
+ {
+ return SelectHelper.select(schemaSpec, pd, relations, reverse, false);
+ }
+
public CompiledStatement toSelectStatement()
{
return SelectHelper.select(schemaSpec, pd, selection.columns(), relations, reverse, selection.includeTimestamp());
diff --git a/test/unit/org/apache/cassandra/config/DatabaseDescriptorRefTest.java b/test/unit/org/apache/cassandra/config/DatabaseDescriptorRefTest.java
index 8bd5ba7356..db7476e799 100644
--- a/test/unit/org/apache/cassandra/config/DatabaseDescriptorRefTest.java
+++ b/test/unit/org/apache/cassandra/config/DatabaseDescriptorRefTest.java
@@ -79,6 +79,7 @@ public class DatabaseDescriptorRefTest
"org.apache.cassandra.auth.IRoleManager",
"org.apache.cassandra.config.AccordSpec",
"org.apache.cassandra.config.AccordSpec$JournalSpec",
+ "org.apache.cassandra.config.AccordSpec$MinEpochRetrySpec",
"org.apache.cassandra.config.AccordSpec$TransactionalRangeMigration",
"org.apache.cassandra.config.CassandraRelevantProperties",
"org.apache.cassandra.config.CassandraRelevantProperties$PropertyConverter",
diff --git a/test/unit/org/apache/cassandra/cql3/CQLTester.java b/test/unit/org/apache/cassandra/cql3/CQLTester.java
index 30b568d3a4..4b1ef7df60 100644
--- a/test/unit/org/apache/cassandra/cql3/CQLTester.java
+++ b/test/unit/org/apache/cassandra/cql3/CQLTester.java
@@ -68,8 +68,19 @@ import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
+import accord.utils.RandomSource;
+import org.apache.cassandra.cql3.ast.Conditional;
+import org.apache.cassandra.cql3.ast.Expression;
+import org.apache.cassandra.cql3.ast.Mutation;
+import org.apache.cassandra.cql3.ast.Select;
+import org.apache.cassandra.cql3.ast.Symbol;
+import org.apache.cassandra.cql3.ast.TableReference;
+import org.apache.cassandra.cql3.ast.Where;
import org.apache.cassandra.db.marshal.ByteBufferAccessor;
import org.apache.cassandra.db.virtual.SystemViewsKeyspace;
+import org.apache.cassandra.utils.ASTGenerators;
+import org.apache.cassandra.utils.CassandraGenerators;
+import org.apache.cassandra.utils.Generators;
import org.assertj.core.api.Assertions;
import org.awaitility.Awaitility;
import org.apache.commons.lang3.ArrayUtils;
@@ -89,7 +100,6 @@ import org.slf4j.LoggerFactory;
import accord.utils.DefaultRandom;
import accord.utils.Gen;
import accord.utils.Property;
-import accord.utils.RandomSource;
import com.codahale.metrics.Gauge;
import com.datastax.driver.core.CloseFuture;
import com.datastax.driver.core.Cluster;
@@ -195,6 +205,8 @@ import org.apache.cassandra.utils.LazyToString;
import org.apache.cassandra.utils.Pair;
import org.apache.cassandra.utils.TimeUUID;
+import static org.apache.cassandra.utils.CassandraGenerators.regularKeyspace;
+import static org.apache.cassandra.utils.CassandraGenerators.regularTable;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -299,6 +311,7 @@ public abstract class CQLTester
private List<String> keyspaces = new ArrayList<>();
private List<String> tables = new ArrayList<>();
+ private List<String> indexes = new ArrayList<>();
private List<String> views = new ArrayList<>();
private List<String> types = new ArrayList<>();
private List<String> functions = new ArrayList<>();
@@ -382,6 +395,7 @@ public abstract class CQLTester
public static void prepareServer()
{
ServerTestUtils.prepareServer();
+ AccordStateCache.validateLoadOnEvict(true);
}
public static void cleanup()
@@ -439,7 +453,6 @@ public abstract class CQLTester
// Once per-JVM is enough
prepareServer();
- AccordStateCache.validateLoadOnEvict(true);
}
protected static void prePrepareServer()
@@ -504,6 +517,7 @@ public abstract class CQLTester
keyspaces = null;
tables = null;
+ indexes = null;
views = null;
types = null;
functions = null;
@@ -521,6 +535,27 @@ public abstract class CQLTester
VirtualKeyspaceRegistry.instance.register(SystemViewsKeyspace.instance);
}
+ protected void clearSchema()
+ {
+ ServerTestUtils.resetCMS();
+ keyspaces.clear();
+ tables.clear();
+ indexes.clear();;
+ views.clear();
+ types.clear();
+ functions.clear();
+ aggregates.clear();
+ }
+
+ protected void clearState()
+ {
+ clearSchema();
+ usePrepared = USE_PREPARED_VALUES;
+ reusePrepared = REUSE_PREPARED;
+
+ seqNumber.set(0);
+ }
+
protected void resetSchema() throws Throwable
{
for (TableMetadata table : SchemaKeyspace.metadata().tables)
@@ -2121,7 +2156,10 @@ public abstract class CQLTester
if (!((cellValidator == null && actualValue == null) || (cellValidator != null && cellValidator.equals(actualValue))))
{
Object actualValueDecoded = actualValue == null ? null : column.type.getSerializer().deserialize(actualValue);
- if (!Objects.equal(expected != null ? expected[j] : null, actualValueDecoded))
+ Object expectedValueDecoded = expected != null ? expected[j] : null;
+ if (expectedValueDecoded instanceof ByteBuffer && !(actualValueDecoded instanceof ByteBuffer))
+ expectedValueDecoded = column.type.getSerializer().deserialize(((ByteBuffer) expectedValueDecoded).duplicate());
+ if (!Objects.equal(expectedValueDecoded, actualValueDecoded))
{
if (isEmptyContainerNull(column.type, cellValidator != null ? cellValidator.expected() : null, actualValue))
continue;
@@ -2551,6 +2589,116 @@ public abstract class CQLTester
values);
}
+ protected CassandraGenerators.KeyspaceMetadataBuilder createKeyspaceMetadataBuilder()
+ {
+ return regularKeyspace()
+ .withName(createKeyspaceName())
+ .withReplication(new CassandraGenerators.AbstractReplicationStrategyBuilder()
+ .withUserAllowed()
+ .withDatacenters("datacenter1")
+ .withRf(1));
+ }
+
+ protected KeyspaceMetadata createKeyspace(RandomSource rs)
+ {
+ KeyspaceMetadata metadata = Generators.toGen(createKeyspaceMetadataBuilder().build()).next(rs);
+ String fullQuery = metadata.toCqlString(false, false, false);
+ logger.info(fullQuery);
+ schemaChange(fullQuery);
+ return metadata;
+ }
+
+ protected CassandraGenerators.TableMetadataBuilder createTableMetadataBuilder()
+ {
+ String ks = currentKeyspace();
+ if (ks == null)
+ ks = KEYSPACE;
+ return createTableMetadataBuilder(ks);
+ }
+
+ protected CassandraGenerators.TableMetadataBuilder createTableMetadataBuilder(String ks)
+ {
+ return regularTable()
+ .withKeyspaceName(ks)
+ .withSimpleColumnNames();
+ }
+
+ protected TableMetadata createTable(RandomSource rs)
+ {
+ TableMetadata metadata = Generators.toGen(createTableMetadataBuilder().build()).next(rs);
+ maybeCreateUDTs(metadata);
+ String fullQuery = metadata.toCqlString(false, false, false);
+ logger.info(fullQuery);
+ schemaChange(fullQuery);
+ return metadata;
+ }
+
+ protected TableMetadata createTable(RandomSource rs, String keyspace)
+ {
+ TableMetadata metadata = Generators.toGen(createTableMetadataBuilder(keyspace).build()).next(rs);
+ maybeCreateUDTs(metadata);
+ String fullQuery = metadata.toCqlString(false, false, false);
+ logger.info(fullQuery);
+ schemaChange(fullQuery);
+ return Schema.instance.getTableMetadata(keyspace, metadata.name);
+ }
+
+ protected void maybeCreateUDTs(TableMetadata metadata)
+ {
+ CassandraGenerators.visitUDTs(metadata, next -> {
+ String cql = next.toCqlString(false, false, true);
+ logger.warn("Creating UDT {}", cql);
+ schemaChange(cql);
+ });
+ }
+
+ protected String createIndexName()
+ {
+ String name = createSchemaElementName(SchemaElement.SchemaElementType.INDEX, null);
+ indexes.add(name);
+ return name;
+ }
+
+ protected UntypedResultSet execute(org.apache.cassandra.cql3.ast.Statement stmt)
+ {
+ return executeFormattedQuery(stmt.toCQL(), stmt.bindsEncoded());
+ }
+
+ protected ResultSet executeNet(ProtocolVersion protocolVersion, org.apache.cassandra.cql3.ast.Statement stmt)
+ {
+ return sessionNet(protocolVersion).execute(stmt.toCQL(), stmt.bindsEncoded());
+ }
+
+ protected Mutation nonTransactionMutation(RandomSource rs, TableMetadata metadata)
+ {
+ return Generators.toGen(new ASTGenerators.MutationGenBuilder(metadata).withoutTransaction().build()).next(rs);
+ }
+
+ protected Select select(Mutation mutation)
+ {
+ // select * from table where <primaryKeys>
+ return new Select(Collections.emptyList(),
+ Optional.of(new TableReference(Optional.of(mutation.table.keyspace), mutation.table.name)),
+ where(mutation.primaryKeys()),
+ Optional.empty(),
+ Optional.empty());
+ }
+
+ private Optional<Conditional> where(Map<Symbol, Expression> keys)
+ {
+ if (keys.isEmpty())
+ throw new IllegalArgumentException("Unable to create a where clause from empty keys");
+ Conditional.Builder builder = new Conditional.Builder();
+ for (Map.Entry<Symbol, Expression> e : keys.entrySet())
+ builder.where(Where.Inequalities.EQUAL, e.getKey(), e.getValue());
+ return Optional.of(builder.build());
+ }
+
+ protected Object[][] rows(Mutation mutation)
+ {
+ return mutation.kind == Mutation.Kind.DELETE ? new Object[0][] : new Object[][]{row(mutation.toRowEncoded())};
+ }
+
@FunctionalInterface
public interface CheckedFunction
{
@@ -2830,8 +2978,15 @@ public abstract class CQLTester
// CollectionType override getString() to use hexToBytes. We can't change that
// without breaking SSTable2json, but the serializer for collection have the
// right getString so using it directly instead.
- TypeSerializer ser = type.getSerializer();
- return ser.toString(ser.deserialize(bb));
+ try
+ {
+ TypeSerializer ser = type.getSerializer();
+ return ser.toString(ser.deserialize(bb));
+ }
+ catch (Throwable t)
+ {
+ return "TypeSerializer.toString failed for type " + type.asCQL3Type() + ": " + t.getMessage();
+ }
}
try
diff --git a/test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java b/test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java
index 1eff610c84..075fbf8e91 100644
--- a/test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java
+++ b/test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java
@@ -20,27 +20,18 @@ package org.apache.cassandra.cql3;
import java.io.IOException;
import java.nio.ByteBuffer;
-import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Deque;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
-import java.util.NavigableMap;
-import java.util.Set;
-import java.util.TreeMap;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableList;
import org.junit.Assert;
import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.CassandraRelevantProperties;
import org.apache.cassandra.config.DatabaseDescriptor;
-import org.apache.cassandra.db.marshal.UserType;
import org.apache.cassandra.io.sstable.format.SSTableFormat;
import org.apache.cassandra.io.util.DataInputBuffer;
import org.apache.cassandra.io.util.DataOutputBuffer;
@@ -65,8 +56,6 @@ import static org.junit.Assert.assertTrue;
public class RandomSchemaTest extends CQLTester.InMemory
{
- private static final Logger logger = LoggerFactory.getLogger(RandomSchemaTest.class);
-
static
{
// make sure blob is always the same
@@ -80,20 +69,17 @@ public class RandomSchemaTest extends CQLTester.InMemory
{
// in accord branch there is a much cleaner api for this pattern...
Gen<AbstractTypeGenerators.ValueDomain> domainGen = SourceDSL.integers().between(1, 100).map(i -> i < 2 ? AbstractTypeGenerators.ValueDomain.NULL : i < 4 ? AbstractTypeGenerators.ValueDomain.EMPTY_BYTES : AbstractTypeGenerators.ValueDomain.NORMAL);
- // make sure ordering is determanstic, else repeatability breaks
- NavigableMap<String, SSTableFormat<?, ?>> formats = new TreeMap<>(DatabaseDescriptor.getSSTableFormats());
- Gen<SSTableFormat<?, ?>> ssTableFormatGen = SourceDSL.arbitrary().pick(new ArrayList<>(formats.values()));
+
+ Gen<SSTableFormat<?, ?>> sstableFormatGen = CassandraGenerators.sstableFormat();
qt().checkAssert(random -> {
resetSchema();
// TODO : when table level override of sstable format is allowed, migrate to that
- SSTableFormat<?, ?> sstableFormat = ssTableFormatGen.generate(random);
- DatabaseDescriptor.setSelectedSSTableFormat(sstableFormat);
+ DatabaseDescriptor.setSelectedSSTableFormat(sstableFormatGen.generate(random));
Gen<String> udtName = Generators.unique(IDENTIFIER_GEN);
TypeGenBuilder withoutUnsafeEquality = AbstractTypeGenerators.withoutUnsafeEquality()
- .withUserTypeKeyspace(KEYSPACE)
.withUDTNames(udtName);
TableMetadata metadata = new TableMetadataBuilder()
.withKeyspaceName(KEYSPACE)
@@ -101,17 +87,14 @@ public class RandomSchemaTest extends CQLTester.InMemory
.withKnownMemtables()
.withDefaultTypeGen(AbstractTypeGenerators.builder()
.withoutEmpty()
- .withUserTypeKeyspace(KEYSPACE)
.withMaxDepth(2)
.withDefaultSetKey(withoutUnsafeEquality)
.withoutTypeKinds(AbstractTypeGenerators.TypeKind.COUNTER)
- .withUDTNames(udtName)
- .build())
+ .withUDTNames(udtName))
.withPartitionColumnsCount(1)
.withPrimaryColumnTypeGen(new TypeGenBuilder(withoutUnsafeEquality)
// map of vector of map crossed the size cut-off for one of the tests, so changed max depth from 2 to 1, so we can't have the second map
- .withMaxDepth(1)
- .build())
+ .withMaxDepth(1))
.withClusteringColumnsBetween(1, 2)
.withRegularColumnsBetween(1, 5)
.withStaticColumnsBetween(0, 2)
@@ -189,36 +172,6 @@ public class RandomSchemaTest extends CQLTester.InMemory
}
}
- private void maybeCreateUDTs(TableMetadata metadata)
- {
- Set<UserType> udts = CassandraGenerators.extractUDTs(metadata);
- if (!udts.isEmpty())
- {
- Deque<UserType> pending = new ArrayDeque<>(udts);
- Set<ByteBuffer> created = new HashSet<>();
- while (!pending.isEmpty())
- {
- UserType next = pending.poll();
- Set<UserType> subTypes = AbstractTypeGenerators.extractUDTs(next);
- subTypes.remove(next); // it includes self
- if (subTypes.isEmpty() || subTypes.stream().allMatch(t -> created.contains(t.name)))
- {
- String cql = next.toCqlString(true, false, false);
- logger.warn("Creating UDT {}", cql);
- schemaChange(cql);
- created.add(next.name);
- }
- else
- {
- logger.warn("Unable to create UDT {}; following sub-types still not created: {}",
- next.getCqlTypeName(),
- subTypes.stream().filter(t -> !created.contains(t.name)).collect(Collectors.toSet()));
- pending.add(next);
- }
- }
- }
- }
-
private static int primaryColumnCount(TableMetadata metadata)
{
return metadata.partitionKeyColumns().size() + metadata.clusteringColumns().size();
diff --git a/test/unit/org/apache/cassandra/cql3/RandomSchemaV2Test.java b/test/unit/org/apache/cassandra/cql3/RandomSchemaV2Test.java
new file mode 100644
index 0000000000..ae50446069
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/RandomSchemaV2Test.java
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import accord.utils.Gen;
+import accord.utils.Gens;
+import accord.utils.RandomSource;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.ast.CreateIndexDDL;
+import org.apache.cassandra.cql3.ast.CreateIndexDDL.Indexer;
+import org.apache.cassandra.cql3.ast.Mutation;
+import org.apache.cassandra.cql3.ast.ReferenceExpression;
+import org.apache.cassandra.cql3.ast.Select;
+import org.apache.cassandra.cql3.ast.Symbol;
+import org.apache.cassandra.cql3.ast.TableReference;
+import org.apache.cassandra.cql3.ast.Txn;
+import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.CompositeType;
+import org.apache.cassandra.db.marshal.MapType;
+import org.apache.cassandra.db.marshal.UTF8Type;
+import org.apache.cassandra.index.Index;
+import org.apache.cassandra.index.SecondaryIndexManager;
+import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.schema.KeyspaceMetadata;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.transport.ProtocolVersion;
+import org.apache.cassandra.utils.AbstractTypeGenerators;
+import org.apache.cassandra.utils.CassandraGenerators;
+import org.awaitility.Awaitility;
+
+import static accord.utils.Property.qt;
+import static java.lang.String.format;
+
+public class RandomSchemaV2Test extends CQLTester
+{
+ @BeforeClass
+ public static void setUpClass()
+ {
+ prePrepareServer();
+
+ // When values are large SAI will drop them... soooo... disable that... this test does not care about perf but correctness
+ DatabaseDescriptor.getRawConfig().sai_frozen_term_size_warn_threshold = null;
+ DatabaseDescriptor.getRawConfig().sai_frozen_term_size_fail_threshold = null;
+
+ // Once per-JVM is enough
+ prepareServer();
+ }
+
+ enum Mode { AccordEnabled, Default}
+
+ @Test
+ public void test()
+ {
+ requireNetwork();
+ Gen<ProtocolVersion> clientVersionGen = rs -> {
+ if (rs.decide(.8)) return null;
+ return rs.pickOrderedSet(ProtocolVersion.SUPPORTED);
+ };
+ Gen<Mode> modeGen = Gens.enums().all(Mode.class);
+ qt().withExamples(100).forAll(Gens.random(), modeGen, clientVersionGen).check((rs, mode, protocolVersion) -> {
+ clearState();
+
+ KeyspaceMetadata ks = createKeyspace(rs);
+ TableMetadata metadata = createTable(rs, ks.name);
+ if (mode == Mode.AccordEnabled)
+ {
+ // enable accord
+ schemaChange(String.format("ALTER TABLE %s WITH " + TransactionalMode.full.asCqlParam(), metadata));
+ metadata = Objects.requireNonNull(Schema.instance.getTableMetadata(ks.name, metadata.name));
+ }
+ Map<ColumnMetadata, CreateIndexDDL> indexedColumns = createIndex(rs, metadata);
+ Mutation mutation = nonTransactionMutation(rs, metadata);
+ if (mode == Mode.AccordEnabled)
+ mutation = mutation.withoutTimestamp().withoutTTL(); // Accord doesn't allow custom timestamps or TTL
+ Select select = select(mutation);
+ Object[][] expectedRows = rows(mutation);
+ try
+ {
+ if (protocolVersion != null)
+ {
+ //TODO (usability): as of this moment reads don't go through Accord when transaction_mode='full', so need to wrap the select in a txn
+ executeNet(protocolVersion, mode == Mode.AccordEnabled ? Txn.wrap(mutation) : mutation);
+ assertRowsNet(executeNet(protocolVersion, mode == Mode.AccordEnabled ? Txn.wrap(select) : select), expectedRows);
+ }
+ else
+ {
+ execute(mode == Mode.AccordEnabled ? Txn.wrap(mutation) : mutation);
+ assertRows(execute(mode == Mode.AccordEnabled ? Txn.wrap(select) : select), expectedRows);
+ }
+ }
+ catch (Throwable t)
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Error writing/reading:");
+ sb.append("\nKeyspace:\n ").append(Keyspace.open(metadata.keyspace).getMetadata().toCqlString(false, false, false));
+ CassandraGenerators.visitUDTs(metadata, udt -> sb.append("\nUDT:\n").append(udt.toCqlString(false, false, false)));
+ sb.append("\nTable:\n").append(metadata.toCqlString(false, false, false));
+ sb.append("\nMutation:\n").append(mutation);
+ sb.append("\nSelect:\n").append(select);
+ throw new AssertionError(sb.toString(), t);
+ }
+
+ checkIndexes(metadata, indexedColumns, mutation, mode, protocolVersion);
+ });
+ }
+
+ private void checkIndexes(TableMetadata metadata, Map<ColumnMetadata, CreateIndexDDL> indexedColumns, Mutation mutation, Mode mode, ProtocolVersion protocolVersion)
+ {
+ if (indexedColumns.isEmpty()) return;
+
+ // 2i time!
+ // check each column 1 by 1
+ for (ColumnMetadata col : indexedColumns.keySet())
+ {
+ Select select = select(mutation, col, mode);
+ try
+ {
+ if (protocolVersion != null)
+ {
+ assertRowsNet(executeNet(protocolVersion, mode == Mode.AccordEnabled ? Txn.wrap(select) : select),
+ rows(mutation));
+ }
+ else
+ {
+ assertRows(execute(mode == Mode.AccordEnabled ? Txn.wrap(select) : select),
+ rows(mutation));
+ }
+ }
+ catch (Throwable t)
+ {
+ throw new AssertionError(format("Error reading %s index for col %s: %s:\nKeyspace:\n %s\nTable:\n%s",
+ indexedColumns.get(col).indexer.name().toCQL(),
+ col, col.type.unwrap().asCQL3Type(),
+ Keyspace.open(metadata.keyspace).getMetadata().toCqlString(false, false, false),
+ metadata.toCqlString(false, false, false)),
+ t);
+ }
+ }
+ filterKnownIssues(indexedColumns);
+
+ // check what happens when we query all columns within a single indexer
+ var groupByIndexer = indexedColumns.entrySet().stream().collect(Collectors.groupingBy(e -> e.getValue().indexer.name(), Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
+ for (var e : groupByIndexer.entrySet())
+ {
+ if (e.getValue().size() == 1) continue; // tested already doing single column queries
+ checkMultipleIndexes(metadata, e.getValue(), mutation, mode, protocolVersion);
+ }
+
+ // check what happens when we query with all columns
+ checkMultipleIndexes(metadata, indexedColumns, mutation, mode, protocolVersion);
+ }
+
+ private void filterKnownIssues(Map<ColumnMetadata, CreateIndexDDL> indexedColumns)
+ {
+ // Remove once CASSANDRA-19891 is fixed
+ List<ColumnMetadata> toRemove = new ArrayList<>();
+ for (Map.Entry<ColumnMetadata, CreateIndexDDL> e : indexedColumns.entrySet())
+ {
+ AbstractType<?> type = e.getKey().type.unwrap();
+ if (type instanceof CompositeType && AbstractTypeGenerators.contains(type, t -> t instanceof MapType))
+ toRemove.add(e.getKey());
+ }
+ toRemove.forEach(indexedColumns::remove);
+ }
+
+ private void checkMultipleIndexes(TableMetadata metadata, Map<ColumnMetadata, CreateIndexDDL> indexedColumns, Mutation mutation, Mode mode, ProtocolVersion protocolVersion)
+ {
+ Select select = select(mutation, indexedColumns.keySet(), mode);
+ if (requiresAllowFiltering(indexedColumns))
+ select = select.withAllowFiltering();
+ try
+ {
+ if (protocolVersion != null)
+ {
+ assertRowsNet(executeNet(protocolVersion, mode == Mode.AccordEnabled ? Txn.wrap(select) : select),
+ rows(mutation));
+ }
+ else
+ {
+ assertRows(execute(mode == Mode.AccordEnabled ? Txn.wrap(select) : select),
+ rows(mutation));
+ }
+ }
+ catch (Throwable t)
+ {
+ throw new AssertionError(format("Error reading all indexes:\nKeyspace:\n %s\nTable:\n%s\nIndexes: [%s]",
+ Keyspace.open(metadata.keyspace).getMetadata().toCqlString(false, false, false),
+ metadata.toCqlString(false, false, false),
+ indexedColumns.values().stream().map(ddl -> ddl.toCQL().replace("org.apache.cassandra.db.marshal.", "")).collect(Collectors.joining(";\n\t"))),
+ t);
+ }
+ }
+
+ private boolean requiresAllowFiltering(Map<ColumnMetadata, CreateIndexDDL> indexedColumns)
+ {
+ return indexedColumns.values().stream().anyMatch(c -> c.indexer.kind() != Indexer.Kind.sai);
+ }
+
+ private static Select select(Mutation mutation, Set<ColumnMetadata> columns, Mode mode)
+ {
+ Select.Builder builder = new Select.Builder().withTable(mutation.table);
+ for (ColumnMetadata col : columns)
+ {
+ Symbol symbol = Symbol.from(col);
+ builder.withColumnEquals(symbol, mutation.values.get(symbol));
+ }
+ if (mode == Mode.AccordEnabled )
+ {
+ for (ColumnMetadata col : mutation.table.partitionKeyColumns())
+ {
+ if (columns.contains(col)) continue; // already included
+ Symbol symbol = Symbol.from(col);
+ builder.withColumnEquals(symbol, mutation.values.get(symbol));
+ }
+ builder.withLimit(1);
+ }
+ return builder.build();
+ }
+
+ private static Select select(Mutation mutation, ColumnMetadata col, Mode mode)
+ {
+ return select(mutation, Collections.singleton(col), mode);
+ }
+
+ private Map<ColumnMetadata, CreateIndexDDL> createIndex(RandomSource rs, TableMetadata metadata)
+ {
+ Map<ColumnMetadata, CreateIndexDDL> indexed = new LinkedHashMap<>();
+ for (ColumnMetadata col : metadata.columns())
+ {
+ if (col.type.isReversed()) continue; //TODO (correctness): see https://issues.apache.org/jira/browse/CASSANDRA-19889
+ if (col.name.toString().length() >= 48) continue; // TODO (correctness): https://issues.apache.org/jira/browse/CASSANDRA-19897
+
+ AbstractType<?> type = col.type.unwrap();
+ if (type.isCollection() && !type.isFrozenCollection()) continue; //TODO (coverage): include non-frozen collections; the index part works fine, its the select that fails... basic equality isn't allowed for map type... so how do you query?
+ List<Indexer> allowed = allowed(metadata, col);
+ if (allowed.isEmpty()) continue;
+ Indexer indexer = rs.pick(allowed);
+ ReferenceExpression colExpression = Symbol.from(col);
+ if (type.isFrozenCollection())
+ colExpression = new CreateIndexDDL.CollectionReference(CreateIndexDDL.CollectionReference.Kind.FULL, colExpression);
+
+ String name = createIndexName();
+ CreateIndexDDL ddl = new CreateIndexDDL(rs.pick(CreateIndexDDL.Version.values()),
+ indexer,
+ Optional.of(new Symbol(name, UTF8Type.instance)),
+ TableReference.from(metadata),
+ Collections.singletonList(colExpression),
+ Collections.emptyMap());
+ String stmt = ddl.toCQL();
+ logger.info(stmt);
+ schemaChange(stmt);
+
+ SecondaryIndexManager indexManager = Keyspace.open(metadata.keyspace).getColumnFamilyStore(metadata.name).indexManager;
+ Index index = indexManager.getIndexByName(name);
+ Awaitility.await(stmt)
+ .atMost(1, TimeUnit.MINUTES)
+ .until(() -> indexManager.isIndexQueryable(index));
+
+ indexed.put(col, ddl);
+ }
+ return indexed;
+ }
+
+ private List<Indexer> allowed(TableMetadata metadata, ColumnMetadata col)
+ {
+ return CreateIndexDDL.supportedIndexers().stream()
+ .filter(i -> i.supported(metadata, col))
+ .collect(Collectors.toList());
+ }
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/And.java
similarity index 52%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/And.java
index b4e037ef3a..229b4866be 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/And.java
@@ -16,29 +16,31 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
+import java.util.stream.Stream;
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
+public class And implements Conditional
+{
+ private final Conditional left, right;
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
+ public And(Conditional left, Conditional right)
+ {
+ this.left = left;
+ this.right = right;
+ }
-public class CassandraGeneratorsTest
-{
- @Test
- public void partitionerToToken()
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
+ left.toCQL(sb, indent);
+ sb.append(" AND ");
+ right.toCQL(sb, indent);
}
- @Test
- public void partitionerKeys()
+ @Override
+ public Stream<? extends Element> stream()
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
+ return Stream.of(left, right);
}
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/AssignmentOperator.java b/test/unit/org/apache/cassandra/cql3/ast/AssignmentOperator.java
new file mode 100644
index 0000000000..43c7d2f310
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/AssignmentOperator.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.EnumSet;
+import java.util.stream.Stream;
+
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.CollectionType;
+import org.apache.cassandra.db.marshal.ListType;
+import org.apache.cassandra.db.marshal.MapType;
+import org.apache.cassandra.db.marshal.SetType;
+
+//TODO this is hacky as Mutation takes Expression then figures out where to put it...
+// this can only be applied to UPDATE ... SET
+public class AssignmentOperator implements Expression
+{
+ public enum Kind
+ {
+ ADD('+'),
+ SUBTRACT('-');
+
+ private final char value;
+
+ Kind(char value)
+ {
+ this.value = value;
+ }
+ }
+
+ public final Kind kind;
+ public final Expression right;
+
+ public AssignmentOperator(Kind kind, Expression right)
+ {
+ this.kind = kind;
+ this.right = right;
+ }
+
+ public static EnumSet<Kind> supportsOperators(AbstractType<?> type)
+ {
+ type = type.unwrap();
+ EnumSet<Kind> result = EnumSet.noneOf(Kind.class);
+ for (Operator.Kind supported : Operator.supportsOperators(type))
+ {
+ Kind kind = toKind(supported);
+ if (kind != null)
+ result.add(kind);
+ }
+ if (result.isEmpty())
+ {
+ if (type instanceof CollectionType && type.isMultiCell())
+ {
+ if (type instanceof SetType || type instanceof ListType)
+ return EnumSet.of(Kind.ADD, Kind.SUBTRACT);
+ if (type instanceof MapType)
+ {
+ // map supports subtract, but not map - map; only map - set!
+ // since this is annoying to support, for now dropping -
+ return EnumSet.of(Kind.ADD);
+ }
+ throw new AssertionError("Unexpected collection type: " + type);
+ }
+ }
+ return result;
+ }
+
+ private static Kind toKind(Operator.Kind kind)
+ {
+ switch (kind)
+ {
+ case ADD: return Kind.ADD;
+ case SUBTRACT: return Kind.SUBTRACT;
+ default: return null;
+ }
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append(' ').append(kind.value).append("= ");
+ right.toCQL(sb, indent);
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(right);
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return right.type();
+ }
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/Bind.java
similarity index 51%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/Bind.java
index b4e037ef3a..c36239c59c 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/Bind.java
@@ -16,29 +16,49 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
+import java.nio.ByteBuffer;
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
+import org.apache.cassandra.db.marshal.AbstractType;
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
-
-public class CassandraGeneratorsTest
+public class Bind implements Value
{
- @Test
- public void partitionerToToken()
+ private final Object value;
+ private final AbstractType<?> type;
+
+ public Bind(Object value, AbstractType<?> type)
+ {
+ this.value = value;
+ this.type = type;
+ }
+
+ @Override
+ public Object value()
+ {
+ return value;
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return type;
+ }
+
+ public ByteBuffer encode()
+ {
+ return ((AbstractType) type).decompose(value);
+ }
+
+ @Override
+ public Bind with(Object value, AbstractType<?> type)
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
+ return new Bind(value, type);
}
- @Test
- public void partitionerKeys()
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
+ sb.append('?');
}
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/CasCondition.java b/test/unit/org/apache/cassandra/cql3/ast/CasCondition.java
new file mode 100644
index 0000000000..5dc304101a
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/CasCondition.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.stream.Stream;
+
+public interface CasCondition extends Element
+{
+ enum Simple implements CasCondition
+ {
+ NotExists("IF NOT EXISTS"),
+ Exists("IF EXISTS");
+
+ private final String cql;
+
+ Simple(String s)
+ {
+ this.cql = s;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append(cql);
+ }
+ }
+
+ class IfCondition implements CasCondition
+ {
+ private final Conditional conditional;
+
+ public IfCondition(Conditional conditional)
+ {
+ this.conditional = conditional;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append("IF ");
+ conditional.toCQL(sb, indent);
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(conditional);
+ }
+ }
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/Cast.java
similarity index 52%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/Cast.java
index b4e037ef3a..a99bfa900c 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/Cast.java
@@ -16,29 +16,42 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
+import java.util.stream.Stream;
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
+import org.apache.cassandra.db.marshal.AbstractType;
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
-
-public class CassandraGeneratorsTest
+public class Cast implements Expression
{
- @Test
- public void partitionerToToken()
+ private final Expression e;
+ private final AbstractType<?> type;
+
+ public Cast(Expression e, AbstractType<?> type)
+ {
+ this.e = e;
+ this.type = type;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append("CAST (");
+ e.toCQL(sb, indent);
+ sb.append(" AS ");
+ sb.append(type.asCQL3Type());
+ sb.append(")");
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
+ return Stream.of(e);
}
- @Test
- public void partitionerKeys()
+ @Override
+ public AbstractType<?> type()
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
+ return type;
}
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/CollectionAccess.java b/test/unit/org/apache/cassandra/cql3/ast/CollectionAccess.java
new file mode 100644
index 0000000000..6a4c4dcea7
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/CollectionAccess.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.stream.Stream;
+
+import org.apache.cassandra.db.marshal.AbstractType;
+
+public class CollectionAccess implements ReferenceExpression
+{
+ private final ReferenceExpression column;
+ private final ReferenceExpression element;
+ private final AbstractType<?> type;
+
+ public CollectionAccess(ReferenceExpression column, ReferenceExpression element, AbstractType<?> type)
+ {
+ this.column = column;
+ this.element = element;
+ this.type = type;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ column.toCQL(sb, indent);
+ sb.append('[');
+ element.toCQL(sb, indent);
+ sb.append(']');
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return type;
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(column, element);
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Conditional.java b/test/unit/org/apache/cassandra/cql3/ast/Conditional.java
new file mode 100644
index 0000000000..ffce162450
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Conditional.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import accord.utils.Invariants;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.BooleanType;
+
+public interface Conditional extends Expression
+{
+ @Override
+ default AbstractType<?> type()
+ {
+ return BooleanType.instance;
+ }
+
+ class In implements Conditional
+ {
+ public final ReferenceExpression symbol;
+ public final List<Expression> expressions;
+
+ public In(ReferenceExpression symbol, List<Expression> expressions)
+ {
+ Invariants.checkArgument(!expressions.isEmpty());
+ this.symbol = symbol;
+ this.expressions = expressions;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ symbol.toCQL(sb, indent);
+ sb.append(" IN ");
+ sb.append('(');
+ for (Expression e : expressions)
+ {
+ e.toCQL(sb, indent);
+ sb.append(", ");
+ }
+ sb.setLength(sb.length() - 2); // ", "
+ sb.append(')');
+ }
+ }
+
+ class Builder
+ {
+ private final List<Conditional> sub = new ArrayList<>();
+
+ public boolean isEmpty()
+ {
+ return sub.isEmpty();
+ }
+
+ private Builder add(Conditional conditional)
+ {
+ sub.add(conditional);
+ return this;
+ }
+
+ public Builder where(Where.Inequalities kind, ReferenceExpression ref, Expression expression)
+ {
+ return add(Where.create(kind, ref, expression));
+ }
+
+ public Builder in(ReferenceExpression symbol, Expression... expressions)
+ {
+ return add(new In(symbol, Arrays.asList(expressions)));
+ }
+
+ public Builder in(ReferenceExpression symbol, List<Expression> expressions)
+ {
+ return add(new In(symbol, expressions));
+ }
+
+ public Conditional build()
+ {
+ if (sub.isEmpty())
+ throw new IllegalStateException("Unable to build an empty Conditional");
+ if (sub.size() == 1)
+ return sub.get(0);
+ Conditional accum = sub.get(0);
+ for (int i = 1; i < sub.size(); i++)
+ accum = new And(accum, sub.get(i));
+ return accum;
+ }
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/CreateIndexDDL.java b/test/unit/org/apache/cassandra/cql3/ast/CreateIndexDDL.java
new file mode 100644
index 0000000000..d2f5a0e9a4
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/CreateIndexDDL.java
@@ -0,0 +1,251 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+import org.apache.cassandra.cql3.ast.Symbol.UnquotedSymbol;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.CompositeType;
+import org.apache.cassandra.db.marshal.DurationType;
+import org.apache.cassandra.db.marshal.UTF8Type;
+import org.apache.cassandra.index.sai.StorageAttachedIndex;
+import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.utils.AbstractTypeGenerators;
+
+import static org.apache.cassandra.cql3.ast.Elements.newLine;
+
+//TODO (now): replace with IndexMetadata? Rather than create a custom DDL type can just leverage the existing metadata like Table/Keyspace
+public class CreateIndexDDL implements Element
+{
+ public enum Version { V1, V2 }
+
+ public interface Indexer
+ {
+ enum Kind { legacy, sai }
+ Kind kind();
+ default boolean isCustom()
+ {
+ return kind() != Kind.legacy;
+ }
+ UnquotedSymbol name();
+ default UnquotedSymbol longName()
+ {
+ return name();
+ }
+ boolean supported(TableMetadata table, ColumnMetadata column);
+ }
+
+ public static List<Indexer> supportedIndexers()
+ {
+ return Arrays.asList(LEGACY, SAI);
+ }
+
+ private static boolean standardSupported(TableMetadata metadata, ColumnMetadata col)
+ {
+ if (metadata.partitionKeyColumns().size() == 1 && col.isPartitionKey()) return false;
+ AbstractType<?> type = col.type.unwrap();
+ if (type.isUDT() && type.isMultiCell()) return false; // non-frozen UDTs are not supported
+ if (type.referencesDuration()) return false; // Duration is not allowed! See org.apache.cassandra.cql3.statements.schema.CreateIndexStatement.validateIndexTarget
+ if (AbstractTypeGenerators.contains(type, DurationType.instance)) return false; //TODO (correctness): remove once fixed in CASSANDRA-19890; type.referencesDuration is not correct in all cases
+ return true;
+ }
+
+ private static boolean isFrozen(AbstractType<?> type)
+ {
+ return !type.subTypes().isEmpty() && !type.isMultiCell();
+ }
+
+ public static final Indexer LEGACY = new Indexer()
+ {
+
+ @Override
+ public Kind kind()
+ {
+ return Kind.legacy;
+ }
+
+ @Override
+ public UnquotedSymbol name()
+ {
+ return new UnquotedSymbol("legacy_local_table", UTF8Type.instance);
+ }
+
+ @Override
+ public boolean supported(TableMetadata table, ColumnMetadata column)
+ {
+ return standardSupported(table, column);
+ }
+ };
+
+ public static final Indexer SAI = new Indexer()
+ {
+ @Override
+ public Kind kind()
+ {
+ return Kind.sai;
+ }
+
+ @Override
+ public UnquotedSymbol name()
+ {
+ return new UnquotedSymbol("SAI", UTF8Type.instance);
+ }
+
+ @Override
+ public UnquotedSymbol longName()
+ {
+ return new UnquotedSymbol("StorageAttachedIndex", UTF8Type.instance);
+ }
+
+ @Override
+ public boolean supported(TableMetadata table, ColumnMetadata col)
+ {
+ if (!standardSupported(table, col)) return false;
+ AbstractType<?> type = col.type.unwrap();
+ if (type instanceof CompositeType)
+ {
+ // each element must be SUPPORTED_TYPES only...
+ if (type.subTypes().stream().allMatch(StorageAttachedIndex.SUPPORTED_TYPES::contains))
+ return true;
+ }
+ else if (((isFrozen(type) && !type.isVector()) || StorageAttachedIndex.SUPPORTED_TYPES.contains(type.asCQL3Type())))
+ return true;
+ return false;
+ }
+ };
+
+ public final Version version;
+ public final Indexer indexer;
+ public final Optional<Symbol> name;
+ public final TableReference on;
+ public final List<ReferenceExpression> references;
+ public final Map<String, String> options;
+
+ public CreateIndexDDL(Version version, Indexer indexer, Optional<Symbol> name, TableReference on, List<ReferenceExpression> references, Map<String, String> options)
+ {
+ this.version = version;
+ this.indexer = indexer;
+ this.name = name;
+ this.on = on;
+ this.references = references;
+ this.options = options;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ switch (version)
+ {
+ case V1:
+ if (indexer.isCustom()) sb.append("CREATE CUSTOM INDEX");
+ else sb.append("CREATE INDEX");
+ break;
+ case V2:
+ sb.append("CREATE INDEX");
+ break;
+ default:
+ throw new UnsupportedOperationException(version.name());
+ }
+ if (name.isPresent())
+ {
+ sb.append(' ');
+ name.get().toCQL(sb, indent);
+ }
+ newLine(sb, indent);
+ sb.append("ON ");
+ on.toCQL(sb, indent);
+ sb.append('(');
+ for (ReferenceExpression ref : references)
+ {
+ ref.toCQL(sb, indent);
+ sb.append(", ");
+ }
+ sb.setLength(sb.length() - 2); // remove last ", "
+ sb.append(')');
+ UnquotedSymbol indexerName = null;
+ switch (version)
+ {
+ case V1:
+ if (indexer.isCustom())
+ indexerName = indexer.longName();
+ break;
+ case V2:
+ indexerName = indexer.name();
+ break;
+ default:
+ throw new UnsupportedOperationException(version.name());
+ }
+ if (indexerName != null)
+ {
+ newLine(sb, indent);
+ sb.append("USING '");
+ indexerName.toCQL(sb, indent);
+ sb.append("'");
+ }
+ if (!options.isEmpty())
+ {
+ newLine(sb, indent);
+ sb.append("WITH OPTIONS = {");
+ for (Map.Entry<String, String> e : options.entrySet())
+ sb.append("'").append(e.getKey()).append("': '").append(e.getValue()).append("', ");
+ sb.setLength(sb.length() - 2); // remove ", "
+ sb.append('}');
+ }
+ }
+
+ public static class CollectionReference implements ReferenceExpression
+ {
+ public enum Kind { FULL, KEYS, ENTRIES }
+
+ public final Kind kind;
+ public final ReferenceExpression column;
+
+ public CollectionReference(Kind kind, ReferenceExpression column)
+ {
+ this.kind = kind;
+ this.column = column;
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return column.type();
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append(kind.name()).append('(');
+ column.toCQL(sb, indent);
+ sb.append(')');
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(column);
+ }
+ }
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/DDL.java
similarity index 51%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/DDL.java
index b4e037ef3a..7575bec7a4 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/DDL.java
@@ -16,29 +16,8 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
-
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
-
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
-
-public class CassandraGeneratorsTest
+public interface DDL extends Statement
{
- @Test
- public void partitionerToToken()
- {
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
- }
-
- @Test
- public void partitionerKeys()
- {
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
- }
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/Element.java
similarity index 50%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/Element.java
index b4e037ef3a..b448d860df 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/Element.java
@@ -16,29 +16,41 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
+import java.util.stream.Stream;
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
+public interface Element
+{
+ void toCQL(StringBuilder sb, int indent);
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
+ default void toCQL(StringBuilder sb)
+ {
+ toCQL(sb, 0);
+ }
-public class CassandraGeneratorsTest
-{
- @Test
- public void partitionerToToken()
+ default String toCQL()
+ {
+ StringBuilder sb = new StringBuilder();
+ toCQL(sb, 0);
+ return sb.toString();
+ }
+
+ default Stream<? extends Element> stream()
+ {
+ return Stream.empty();
+ }
+
+ default Stream<? extends Element> streamRecursive()
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
+ return streamRecursive(false);
}
- @Test
- public void partitionerKeys()
+ default Stream<? extends Element> streamRecursive(boolean includeSelf)
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
+ Stream<Element> stream = stream().flatMap(e -> Stream.concat(Stream.of(e), e.streamRecursive()));
+ if (includeSelf)
+ stream = Stream.concat(Stream.of(this), stream);
+ return stream;
}
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/Elements.java
similarity index 51%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/Elements.java
index b4e037ef3a..f750c4efc1 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/Elements.java
@@ -16,29 +16,17 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
-
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
-
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
-
-public class CassandraGeneratorsTest
+public final class Elements
{
- @Test
- public void partitionerToToken()
- {
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
- }
+ private Elements()
+ {}
- @Test
- public void partitionerKeys()
+ public static void newLine(StringBuilder sb, int indent)
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
+ sb.append('\n');
+ for (int i = 0; i < indent; i++)
+ sb.append(' ');
}
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/Expression.java
similarity index 51%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/Expression.java
index b4e037ef3a..909f13b953 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/Expression.java
@@ -16,29 +16,15 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
+import org.apache.cassandra.db.marshal.AbstractType;
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
-
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
-
-public class CassandraGeneratorsTest
+public interface Expression extends Element
{
- @Test
- public void partitionerToToken()
- {
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
- }
-
- @Test
- public void partitionerKeys()
+ AbstractType<?> type();
+ default String name()
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
+ return toCQL();
}
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/ExpressionEvaluator.java b/test/unit/org/apache/cassandra/cql3/ast/ExpressionEvaluator.java
new file mode 100644
index 0000000000..1c4abff151
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/ExpressionEvaluator.java
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.Optional;
+
+import org.apache.cassandra.db.marshal.AbstractType;
+
+import static java.util.Optional.of;
+
+public class ExpressionEvaluator
+{
+ public static Optional<Object> tryEval(Expression e)
+ {
+ if (e instanceof Value)
+ return of(((Value) e).value());
+ if (e instanceof TypeHint)
+ return tryEval(((TypeHint) e).e);
+ if (e instanceof Operator)
+ return tryEval((Operator) e);
+ return Optional.empty();
+ }
+
+ public static Optional<Object> tryEval(Operator e)
+ {
+ switch (e.kind)
+ {
+ case ADD:
+ {
+ var lhsOpt = tryEval(e.left);
+ var rhsOpt = tryEval(e.right);
+ if (lhsOpt.isEmpty() || rhsOpt.isEmpty())
+ return Optional.empty();
+ Object lhs = lhsOpt.get();
+ Object rhs = rhsOpt.get();
+ if (lhs instanceof Byte)
+ return of((byte) (((Byte) lhs) + ((Byte) rhs)));
+ if (lhs instanceof Short)
+ return of((short) (((Short) lhs) + ((Short) rhs)));
+ if (lhs instanceof Integer)
+ return of((int) (((Integer) lhs) + ((Integer) rhs)));
+ if (lhs instanceof Long)
+ return of((long) (((Long) lhs) + ((Long) rhs)));
+ if (lhs instanceof Float)
+ return of((float) (((Float) lhs) + ((Float) rhs)));
+ if (lhs instanceof Double)
+ return of((double) (((Double) lhs) + ((Double) rhs)));
+ if (lhs instanceof BigInteger)
+ return of(((BigInteger) lhs).add((BigInteger) rhs));
+ if (lhs instanceof BigDecimal)
+ return of(((BigDecimal) lhs).add((BigDecimal) rhs));
+ if (lhs instanceof String)
+ return of(lhs.toString() + rhs.toString());
+ throw new UnsupportedOperationException("Unexpected type: " + lhs.getClass());
+ }
+ case SUBTRACT:
+ {
+ var lhsOpt = tryEval(e.left);
+ var rhsOpt = tryEval(e.right);
+ if (lhsOpt.isEmpty() || rhsOpt.isEmpty())
+ return Optional.empty();
+ Object lhs = lhsOpt.get();
+ Object rhs = rhsOpt.get();
+ if (lhs instanceof Byte)
+ return of((byte) (((Byte) lhs) - ((Byte) rhs)));
+ if (lhs instanceof Short)
+ return of((short) (((Short) lhs) - ((Short) rhs)));
+ if (lhs instanceof Integer)
+ return of((int) (((Integer) lhs) - ((Integer) rhs)));
+ if (lhs instanceof Long)
+ return of((long) (((Long) lhs) - ((Long) rhs)));
+ if (lhs instanceof Float)
+ return of((float) (((Float) lhs) - ((Float) rhs)));
+ if (lhs instanceof Double)
+ return of((double) (((Double) lhs) - ((Double) rhs)));
+ if (lhs instanceof BigInteger)
+ return of(((BigInteger) lhs).subtract((BigInteger) rhs));
+ if (lhs instanceof BigDecimal)
+ return of(((BigDecimal) lhs).subtract((BigDecimal) rhs));
+ throw new UnsupportedOperationException("Unexpected type: " + lhs.getClass());
+ }
+ case MULTIPLY:
+ {
+ var lhsOpt = tryEval(e.left);
+ var rhsOpt = tryEval(e.right);
+ if (lhsOpt.isEmpty() || rhsOpt.isEmpty())
+ return Optional.empty();
+ Object lhs = lhsOpt.get();
+ Object rhs = rhsOpt.get();
+ if (lhs instanceof Byte)
+ return of((byte) (((Byte) lhs) * ((Byte) rhs)));
+ if (lhs instanceof Short)
+ return of((short) (((Short) lhs) * ((Short) rhs)));
+ if (lhs instanceof Integer)
+ return of((int) (((Integer) lhs) * ((Integer) rhs)));
+ if (lhs instanceof Long)
+ return of((long) (((Long) lhs) * ((Long) rhs)));
+ if (lhs instanceof Float)
+ return of((float) (((Float) lhs) * ((Float) rhs)));
+ if (lhs instanceof Double)
+ return of((double) ((Double) lhs) * ((Double) rhs));
+ if (lhs instanceof BigInteger)
+ return of(((BigInteger) lhs).multiply((BigInteger) rhs));
+ if (lhs instanceof BigDecimal)
+ return of(((BigDecimal) lhs).multiply((BigDecimal) rhs));
+ throw new UnsupportedOperationException("Unexpected type: " + lhs.getClass());
+ }
+ default:
+ throw new UnsupportedOperationException(e.kind.name());
+ }
+ }
+
+ public static Optional<ByteBuffer> tryEvalEncoded(Expression e)
+ {
+ return tryEval(e).map(v -> {
+ try
+ {
+ return ((AbstractType) e.type()).decompose(v);
+ }
+ catch (Throwable t)
+ {
+ throw t;
+ }
+ });
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/FunctionCall.java b/test/unit/org/apache/cassandra/cql3/ast/FunctionCall.java
new file mode 100644
index 0000000000..0d325b5123
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/FunctionCall.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Stream;
+
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.LongType;
+
+public class FunctionCall implements Expression
+{
+ private final String name;
+ private final List<Expression> arguments;
+ private final AbstractType<?> returnType;
+
+ public FunctionCall(String name, List<Expression> arguments, AbstractType<?> returnType)
+ {
+ this.name = name;
+ this.arguments = arguments;
+ this.returnType = returnType;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append(name).append('(');
+ for (Expression e : arguments)
+ {
+ e.toCQL(sb, indent);
+ sb.append(", ");
+ }
+ if (!arguments.isEmpty())
+ sb.setLength(sb.length() - 2);
+ sb.append(')');
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return arguments.stream();
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return returnType;
+ }
+
+ @Override
+ public String name()
+ {
+ return name;
+ }
+
+ public static FunctionCall writetime(String column, AbstractType<?> type)
+ {
+ return new FunctionCall("writetime", Collections.singletonList(Reference.of(new Symbol(column, type))), LongType.instance);
+ }
+
+ public static FunctionCall countStar()
+ {
+ return new FunctionCall("count(*)", Collections.emptyList(), LongType.instance);
+ }
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/Literal.java
similarity index 52%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/Literal.java
index b4e037ef3a..6051286bd1 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/Literal.java
@@ -16,29 +16,42 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
+import org.apache.cassandra.db.marshal.AbstractType;
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
+public class Literal implements Value
+{
+ private final Object value;
+ private final AbstractType<?> type;
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
+ public Literal(Object value, AbstractType<?> type)
+ {
+ this.value = value;
+ this.type = type;
+ }
-public class CassandraGeneratorsTest
-{
- @Test
- public void partitionerToToken()
+ @Override
+ public AbstractType<?> type()
+ {
+ return type;
+ }
+
+ @Override
+ public Object value()
+ {
+ return value;
+ }
+
+ @Override
+ public Literal with(Object value, AbstractType<?> type)
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
+ return new Literal(value, type);
}
- @Test
- public void partitionerKeys()
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
+ sb.append(type.asCQL3Type().toCQLLiteral(((AbstractType<Object>) type.unwrap()).decompose(value)));
}
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Mutation.java b/test/unit/org/apache/cassandra/cql3/ast/Mutation.java
new file mode 100644
index 0000000000..e9134ddee7
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Mutation.java
@@ -0,0 +1,358 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.schema.TableMetadata;
+
+import static org.apache.cassandra.cql3.ast.Elements.newLine;
+
+public class Mutation implements Statement
+{
+ public enum Kind
+ {INSERT, UPDATE, DELETE}
+
+ public final Kind kind;
+ public final TableMetadata table;
+ public final Map<Symbol, Expression> values;
+ private final Set<Symbol> partitionColumns, clusteringColumns, primaryColumns, nonPrimaryColumns;
+ public final OptionalInt ttl;
+ public final OptionalLong timestamp;
+ public final Optional<? extends CasCondition> casCondition;
+ private final List<Element> orderedElements = new ArrayList<>();
+
+ public Mutation(Kind kind, TableMetadata table, Map<Symbol, Expression> values, OptionalInt ttl, OptionalLong timestamp, Optional<? extends CasCondition> casCondition)
+ {
+ this.kind = kind;
+ this.table = table;
+ this.values = values;
+ this.ttl = ttl;
+ this.timestamp = timestamp;
+ this.casCondition = casCondition;
+
+ // partition key is always required, so validate
+ this.partitionColumns = toSet(table.partitionKeyColumns());
+ this.clusteringColumns = toSet(table.clusteringColumns());
+ this.primaryColumns = Sets.union(partitionColumns, clusteringColumns);
+ Set<Symbol> allColumns = toSet(table.columns());
+ nonPrimaryColumns = Sets.difference(allColumns, primaryColumns);
+
+ Set<Symbol> requiredColumns;
+ switch (kind)
+ {
+ case INSERT:
+ case UPDATE:
+ requiredColumns = primaryColumns;
+ break;
+ case DELETE:
+ requiredColumns = partitionColumns;
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown kind: " + kind);
+ }
+ if (!values.keySet().containsAll(requiredColumns))
+ throw new IllegalArgumentException("Not all required columns present; expected (" + requiredColumns + ") but was (" + values.keySet() + ")");
+ }
+
+ private Mutation(Kind kind, TableMetadata table, Map<Symbol, Expression> values,
+ Set<Symbol> partitionColumns, Set<Symbol> clusteringColumns, Set<Symbol> primaryColumns, Set<Symbol> nonPrimaryColumns,
+ OptionalInt ttl, OptionalLong timestamp, Optional<? extends CasCondition> casCondition)
+ {
+ this.kind = kind;
+ this.table = table;
+ this.values = values;
+ this.partitionColumns = partitionColumns;
+ this.clusteringColumns = clusteringColumns;
+ this.primaryColumns = primaryColumns;
+ this.nonPrimaryColumns = nonPrimaryColumns;
+ this.ttl = ttl;
+ this.timestamp = timestamp;
+ this.casCondition = casCondition;
+ }
+
+ @Override
+ public Statement.Kind kind()
+ {
+ return Statement.Kind.MUTATION;
+ }
+
+ public Mutation withoutTimestamp()
+ {
+ return new Mutation(kind, table, values, partitionColumns, clusteringColumns, primaryColumns, nonPrimaryColumns, ttl, OptionalLong.empty(), casCondition);
+ }
+
+ public Mutation withoutTTL()
+ {
+ return new Mutation(kind, table, values, partitionColumns, clusteringColumns, primaryColumns, nonPrimaryColumns, OptionalInt.empty(), timestamp, casCondition);
+ }
+
+ public Mutation withTable(TableMetadata table)
+ {
+ return new Mutation(kind, table, values, partitionColumns, clusteringColumns, primaryColumns, nonPrimaryColumns, ttl, timestamp, casCondition);
+ }
+
+ public Map<Symbol, Expression> partitionKeys()
+ {
+ return Maps.filterKeys(values, partitionColumns::contains);
+ }
+
+ public Map<Symbol, Expression> clusteringKeys()
+ {
+ return Maps.filterKeys(values, clusteringColumns::contains);
+ }
+
+ public Map<Symbol, Expression> primaryKeys()
+ {
+ return Maps.filterKeys(values, primaryColumns::contains);
+ }
+
+ public Object[] toRow()
+ {
+ //TODO (coverage): mutations don't really allow functions in the value def side... so this hack kinda works...
+ Object[] array = new Object[table.columns().size()];
+ Iterator<ColumnMetadata> it = table.allColumnsInSelectOrder();
+ for (int i = 0; it.hasNext(); i++)
+ {
+ Symbol symbol = new Symbol(it.next());
+ Expression expression = values.get(symbol);
+ Optional<Object> opt = ExpressionEvaluator.tryEval(expression);
+ array[i] = opt.orElseThrow(() -> new IllegalStateException("Unable to eval expression " + expression + "; " + expression.toCQL()));
+ }
+ return array;
+ }
+
+ public ByteBuffer[] toRowEncoded()
+ {
+ //TODO (coverage): mutations don't really allow functions in the value def side... so this hack kinda works...
+ ByteBuffer[] array = new ByteBuffer[table.columns().size()];
+ Iterator<ColumnMetadata> it = table.allColumnsInSelectOrder();
+ for (int i = 0; it.hasNext(); i++)
+ {
+ Symbol symbol = new Symbol(it.next());
+ Expression expression = values.get(symbol);
+ Optional<ByteBuffer> opt = ExpressionEvaluator.tryEvalEncoded(expression);
+ array[i] = opt.orElseThrow(() -> new IllegalStateException("Unable to eval expression " + expression + "; " + expression.toCQL()));
+ }
+ return array;
+ }
+
+ public boolean isCas()
+ {
+ return casCondition.isPresent();
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ if (!orderedElements.isEmpty())
+ orderedElements.clear();
+ switch (kind)
+ {
+ case INSERT:
+ toCQLInsert(sb, indent);
+ break;
+ case UPDATE:
+ toCQLUpdate(sb, indent);
+ break;
+ case DELETE:
+ toCQLDelete(sb, indent);
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported kind: " + kind);
+ }
+ }
+
+ private void toCQLInsert(StringBuilder sb, int indent)
+ {
+ /*
+INSERT INTO [keyspace_name.] table_name (column_list)
+VALUES (column_values)
+[IF NOT EXISTS]
+[USING TTL seconds | TIMESTAMP epoch_in_microseconds]
+ */
+ sb.append("INSERT INTO ").append(table.toString()).append(" (");
+ List<Symbol> columnOrder = new ArrayList<>(values.keySet());
+ for (Symbol name : columnOrder)
+ {
+ name.toCQL(sb, indent);
+ orderedElements.add(name);
+ sb.append(", ");
+ }
+ sb.setLength(sb.length() - 2);
+ sb.append(")");
+ newLine(sb, indent);
+ sb.append("VALUES (");
+ for (Symbol name : columnOrder)
+ {
+ Element value = values.get(name);
+ orderedElements.add(value);
+ value.toCQL(sb, indent);
+ sb.append(", ");
+ }
+ sb.setLength(sb.length() - 2);
+ sb.append(")");
+ maybeAddCasCondition(sb, indent);
+ maybeAddTTL(sb, indent);
+ }
+
+ private void maybeAddCasCondition(StringBuilder sb, int indent)
+ {
+ if (casCondition.isPresent())
+ {
+ newLine(sb, indent);
+ CasCondition condition = casCondition.get();
+ orderedElements.add(condition);
+ condition.toCQL(sb, indent);
+ }
+ }
+
+ private void maybeAddTTL(StringBuilder sb, int indent)
+ {
+ if (ttl.isPresent() || timestamp.isPresent())
+ {
+ newLine(sb, indent);
+ sb.append("USING ");
+ if (ttl.isPresent())
+ sb.append("TTL ").append(ttl.getAsInt()).append(" ");
+ if (timestamp.isPresent())
+ sb.append(ttl.isPresent() ? "AND " : "").append("TIMESTAMP ").append(timestamp.getAsLong());
+ }
+ }
+
+ private void toCQLUpdate(StringBuilder sb, int indent)
+ {
+ /*
+UPDATE [keyspace_name.] table_name
+[USING TTL time_value | USING TIMESTAMP timestamp_value]
+SET assignment [, assignment] . . .
+WHERE row_specification
+[IF EXISTS | IF condition [AND condition] . . .] ;
+ */
+ sb.append("UPDATE ").append(table.toString());
+ maybeAddTTL(sb, indent);
+ newLine(sb, indent);
+ sb.append("SET ");
+ int subindent = indent + 4;
+ for (Symbol name : nonPrimaryColumns)
+ {
+ newLine(sb, subindent);
+ Element value = values.get(name);
+ name.toCQL(sb, subindent);
+ orderedElements.add(name);
+ // when a AssignmentOperator the `=` is added there so don't add
+ //TODO this is super hacky...
+ if (!(value instanceof AssignmentOperator))
+ sb.append('=');
+ value.toCQL(sb, subindent);
+ orderedElements.add(value);
+ sb.append(", ");
+ }
+ if (!nonPrimaryColumns.isEmpty())
+ sb.setLength(sb.length() - 2);
+ newLine(sb, indent);
+ sb.append("WHERE ");
+ valuesAnd(sb, indent + 2, primaryColumns);
+ maybeAddCasCondition(sb, indent);
+ }
+
+ private void toCQLDelete(StringBuilder sb, int indent)
+ {
+ /*
+DELETE [column_name (term)][, ...]
+FROM [keyspace_name.] table_name
+[USING TIMESTAMP timestamp_value]
+WHERE PK_column_conditions
+[IF EXISTS | IF static_column_conditions]
+ */
+ sb.append("DELETE ");
+ Set<Symbol> toDelete = Sets.intersection(nonPrimaryColumns, values.keySet());
+ for (Symbol column : toDelete)
+ {
+ column.toCQL(sb, indent);
+ orderedElements.add(column);
+ sb.append(", ");
+ }
+ if (!toDelete.isEmpty())
+ sb.setLength(sb.length() - 2);
+ newLine(sb, indent);
+ sb.append("FROM ").append(table.toString());
+ newLine(sb, indent);
+ if (timestamp.isPresent())
+ {
+ sb.append("USING TIMESTAMP ").append(timestamp.getAsLong());
+ newLine(sb, indent);
+ }
+ sb.append("WHERE ");
+ // in the case of partition delete, need to exclude clustering
+ valuesAnd(sb, indent + 2, Sets.intersection(primaryColumns, values.keySet()));
+ maybeAddCasCondition(sb, indent);
+ }
+
+ private void valuesAnd(StringBuilder sb, int indent, Collection<Symbol> names)
+ {
+ for (Symbol name : names)
+ {
+ newLine(sb, indent);
+ Element value = values.get(name);
+ name.toCQL(sb, indent);
+ orderedElements.add(name);
+ sb.append('=');
+ value.toCQL(sb, indent);
+ orderedElements.add(value);
+ sb.append(" AND ");
+ }
+ sb.setLength(sb.length() - 5);
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ if (orderedElements.isEmpty())
+ toCQL();
+ return orderedElements.stream();
+ }
+
+ @Override
+ public String toString()
+ {
+ return detailedToString();
+ }
+
+ public static Set<Symbol> toSet(Iterable<ColumnMetadata> columns)
+ {
+ return StreamSupport.stream(columns.spliterator(), false).map(m -> new Symbol(m)).collect(Collectors.toSet());
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Operator.java b/test/unit/org/apache/cassandra/cql3/ast/Operator.java
new file mode 100644
index 0000000000..7d45ea3736
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Operator.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.EnumSet;
+import java.util.stream.Stream;
+
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.NumberType;
+import org.apache.cassandra.db.marshal.StringType;
+import org.apache.cassandra.db.marshal.TemporalType;
+
+public class Operator implements Expression
+{
+ public enum Kind
+ {
+ ADD('+'),
+ SUBTRACT('-'),
+ MULTIPLY('*');
+ //TODO support avoiding 42 / 0 and 42 % 0 as these will fail
+// DIVIDE('/'),
+// MOD('%');
+
+ private final char value;
+
+ Kind(char value)
+ {
+ this.value = value;
+ }
+ }
+
+ public final Kind kind;
+ public final Expression left;
+ public final Expression right;
+
+ public Operator(Kind kind, Expression left, Expression right)
+ {
+ this.kind = kind;
+ this.left = left;
+ this.right = right;
+ if (!left.type().equals(right.type()))
+ throw new IllegalArgumentException("Types do not match: left=" + left.type() + ", right=" + right.type());
+ }
+
+ public static EnumSet<Kind> supportsOperators(AbstractType<?> type)
+ {
+ //TODO (coverage): some operators exist but only for different inputs than (type, type)
+ // date and time both support +- duration; aka date + duration = date, time - duration = time (looks like all temporal types are this way)
+ type = type.unwrap();
+ // see org.apache.cassandra.cql3.functions.OperationFcts.OPERATION
+ if (type instanceof NumberType)
+ return EnumSet.allOf(Kind.class);
+ if (type instanceof TemporalType)
+ return EnumSet.noneOf(Kind.class); //TODO (coverage): not true, but requires the RHS to be duration type only
+ if (type instanceof StringType)
+ return EnumSet.of(Kind.ADD);
+ return EnumSet.noneOf(Kind.class);
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return left.type();
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ left.toCQL(sb, indent);
+ sb.append(' ').append(kind.value).append(' ');
+ right.toCQL(sb, indent);
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(left, right);
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Reference.java b/test/unit/org/apache/cassandra/cql3/ast/Reference.java
new file mode 100644
index 0000000000..9adafa0f36
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Reference.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import com.google.common.collect.ImmutableList;
+
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.BytesType;
+
+public class Reference implements ReferenceExpression
+{
+ public final List<ReferenceExpression> path;
+
+ private Reference(List<ReferenceExpression> path)
+ {
+ if (path.isEmpty())
+ throw new IllegalArgumentException("Reference may not be empty");
+ this.path = path;
+ if (path.stream().anyMatch(e -> e.toCQL().contains("\"\"")))
+ new Throwable().printStackTrace();
+ }
+
+ public static Reference of(ReferenceExpression top)
+ {
+ return new Reference(Collections.singletonList(Objects.requireNonNull(top)));
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return path.get(path.size() - 1).type();
+ }
+
+ public Builder unbuild()
+ {
+ return new Builder(path);
+ }
+
+ public Reference add(String symbol, AbstractType<?> subType)
+ {
+ return unbuild().add(symbol, subType).build();
+ }
+
+ public Reference add(Expression expression)
+ {
+ if (expression instanceof Reference)
+ {
+ Reference other = (Reference) expression;
+ List<ReferenceExpression> path = new ArrayList<>(this.path.size() + other.path.size());
+ path.addAll(this.path);
+ path.addAll(other.path);
+ return new Reference(path);
+ }
+ else if (expression instanceof Symbol)
+ {
+ return unbuild().add((Symbol) expression).build();
+ }
+ else
+ {
+ return unbuild().add(expression.name(), expression.type()).build();
+ }
+ }
+
+ public Reference lastAsCollection(Function<ReferenceExpression, CollectionAccess> fn)
+ {
+ List<ReferenceExpression> path = new ArrayList<>(this.path.size());
+ for (int i = 0; i < this.path.size() - 1; i++)
+ path.add(this.path.get(i));
+ ReferenceExpression last = this.path.get(this.path.size() - 1);
+ path.add(Objects.requireNonNull(fn.apply(last)));
+ return new Reference(path);
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ path.forEach(p -> {
+ p.toCQL(sb, indent);
+ sb.append('.');
+ });
+ sb.setLength(sb.length() - 1); // last .
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return path.stream();
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Reference elements = (Reference) o;
+ return Objects.equals(path, elements.path);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(path);
+ }
+
+ @Override
+ public String toString()
+ {
+ return toCQL();
+ }
+
+ public static class Builder
+ {
+ private final List<ReferenceExpression> path;
+
+ public Builder()
+ {
+ path = new ArrayList<>();
+ }
+
+ private Builder(List<ReferenceExpression> path)
+ {
+ this.path = new ArrayList<>(path.size() + 1);
+ this.path.addAll(path);
+ }
+
+ public Builder add(String name)
+ {
+ return add(new Symbol(name, BytesType.instance));
+ }
+
+ public Builder add(String symbol, AbstractType<?> subType)
+ {
+ return add(new Symbol(symbol, subType));
+ }
+
+ public Builder add(Symbol symbol)
+ {
+ path.add(Objects.requireNonNull(symbol));
+ return this;
+ }
+
+ public Builder add(String[] paths)
+ {
+ for (String name : paths)
+ path.add(new Symbol(name, BytesType.instance));
+ return this;
+ }
+
+ public Reference build()
+ {
+ switch (path.size())
+ {
+ case 0: throw new IllegalStateException("Unable to make a Reference from an empty path");
+ case 1: return Reference.of(path.get(0));
+ default: return new Reference(ImmutableList.copyOf(path));
+ }
+ }
+ }
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/ReferenceExpression.java
similarity index 51%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/ReferenceExpression.java
index b4e037ef3a..a322c5ddfe 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/ReferenceExpression.java
@@ -16,29 +16,11 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
-
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
-
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
-
-public class CassandraGeneratorsTest
+/**
+ * Marker interface of what is allowed in a reference
+ */
+public interface ReferenceExpression extends Expression
{
- @Test
- public void partitionerToToken()
- {
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
- }
-
- @Test
- public void partitionerKeys()
- {
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
- }
-}
\ No newline at end of file
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Select.java b/test/unit/org/apache/cassandra/cql3/ast/Select.java
new file mode 100644
index 0000000000..bfe39c425d
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Select.java
@@ -0,0 +1,370 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+import javax.annotation.Nullable;
+
+import com.google.common.collect.ImmutableList;
+
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.BytesType;
+import org.apache.cassandra.db.marshal.LongType;
+import org.apache.cassandra.schema.TableMetadata;
+
+import static org.apache.cassandra.cql3.ast.Elements.newLine;
+
+public class Select implements Statement
+{
+ /*
+SELECT * | select_expression | DISTINCT partition //TODO DISTINCT
+FROM [keyspace_name.] table_name
+[WHERE partition_value
+ [AND clustering_filters
+ [AND static_filters]]]
+[ORDER BY PK_column_name ASC|DESC]
+[LIMIT N]
+[ALLOW FILTERING] //TODO
+ */
+ // select
+ public final List<Expression> selections;
+ // from
+ public final Optional<TableReference> source;
+ // where
+ public final Optional<Conditional> where;
+ public final Optional<OrderBy> orderBy;
+ public final Optional<Value> limit;
+ public final boolean allowFiltering;
+
+ public Select(List<Expression> selections)
+ {
+ this(selections, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
+ }
+
+ public Select(List<Expression> selections, Optional<TableReference> source, Optional<Conditional> where, Optional<OrderBy> orderBy, Optional<Value> limit)
+ {
+ this(selections, source, where, orderBy, limit, false);
+ }
+
+ public Select(List<Expression> selections, Optional<TableReference> source, Optional<Conditional> where, Optional<OrderBy> orderBy, Optional<Value> limit, boolean allowFiltering)
+ {
+ this.selections = selections;
+ this.source = source;
+ this.where = where;
+ this.orderBy = orderBy;
+ this.limit = limit;
+ this.allowFiltering = allowFiltering;
+ if (!source.isPresent())
+ {
+ if (where.isPresent())
+ throw new IllegalArgumentException("Can not have a WHERE clause when there isn't a FROM");
+ if (orderBy.isPresent())
+ throw new IllegalArgumentException("Can not have a ORDER BY clause when there isn't a FROM");
+ if (limit.isPresent())
+ throw new IllegalArgumentException("Can not have a LIMIT clause when there isn't a FROM");
+ if (allowFiltering)
+ throw new IllegalArgumentException("Can not have a ALLOW FILTERING clause when there isn't a FROM");
+ }
+ }
+
+ public Select withAllowFiltering()
+ {
+ return new Select(selections, source, where, orderBy, limit, true);
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append("SELECT ");
+ if (selections.isEmpty())
+ {
+ sb.append('*');
+ }
+ else
+ {
+ int finalIndent = indent;
+ selections.forEach(s -> {
+ s.toCQL(sb, finalIndent);
+ sb.append(", ");
+ });
+ sb.setLength(sb.length() - 2); // last ', '
+ }
+ if (source.isPresent())
+ {
+ newLine(sb, indent);
+ sb.append("FROM ");
+ source.get().toCQL(sb, indent);
+ if (where.isPresent())
+ {
+ newLine(sb, indent);
+ sb.append("WHERE ");
+ where.get().toCQL(sb, indent);
+ }
+ if (orderBy.isPresent())
+ {
+ newLine(sb, indent);
+ sb.append("ORDER BY ");
+ orderBy.get().toCQL(sb, indent);
+ }
+ if (limit.isPresent())
+ {
+ newLine(sb, indent);
+ sb.append("LIMIT ");
+ limit.get().toCQL(sb, indent);
+ }
+
+ if (allowFiltering)
+ {
+ newLine(sb, indent);
+ sb.append("ALLOW FILTERING");
+ }
+ }
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ List<Element> es = new ArrayList<>(selections.size()
+ + (source.isPresent() ? 1 : 0)
+ + (where.isPresent() ? 1 : 0)
+ + (orderBy.isPresent() ? 1 : 0)
+ + (limit.isPresent() ? 1 : 0));
+ es.addAll(selections);
+ if (source.isPresent())
+ es.add(source.get());
+ if (where.isPresent())
+ es.add(where.get());
+ if (orderBy.isPresent())
+ es.add(orderBy.get());
+ if (limit.isPresent())
+ es.add(limit.get());
+ return es.stream();
+ }
+
+ @Override
+ public String toString()
+ {
+ return detailedToString();
+ }
+
+ @Override
+ public Kind kind()
+ {
+ return Kind.SELECT;
+ }
+
+ public static class OrderBy implements Element
+ {
+ public enum Ordering
+ {ASC, DESC}
+
+ public final List<Ordered> ordered;
+
+ public OrderBy(List<Ordered> ordered)
+ {
+ if (ordered.isEmpty())
+ throw new IllegalArgumentException("Can not ORDER BY an empty list");
+ this.ordered = ordered;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ if (ordered.size() == 1)
+ {
+ ordered.get(0).toCQL(sb, indent);
+ return;
+ }
+
+ String postfix = ", ";
+ for (Ordered o : ordered)
+ {
+ o.toCQL(sb, indent);
+ sb.append(postfix);
+ }
+ sb.setLength(sb.length() - postfix.length());
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return ordered.stream();
+ }
+
+ public static class Ordered implements Element
+ {
+ public final ReferenceExpression expression;
+ public final Ordering ordering;
+
+ public Ordered(ReferenceExpression expression, Ordering ordering)
+ {
+ this.expression = expression;
+ this.ordering = ordering;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ expression.toCQL(sb, indent);
+ sb.append(' ');
+ sb.append(ordering.name());
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(expression);
+ }
+ }
+
+ public static class Builder
+ {
+ private final List<OrderBy.Ordered> ordered = new ArrayList<>();
+
+ public boolean isEmpty()
+ {
+ return ordered.isEmpty();
+ }
+
+ public Builder add(ReferenceExpression expression, Ordering ordering)
+ {
+ ordered.add(new Ordered(expression, ordering));
+ return this;
+ }
+
+ public OrderBy build()
+ {
+ return new OrderBy(ImmutableList.copyOf(ordered));
+ }
+ }
+ }
+
+ public static class Builder
+ {
+ @Nullable // null means wildcard
+ private List<Expression> selections = new ArrayList<>();
+ private Optional<TableReference> source = Optional.empty();
+ private Conditional.Builder where = new Conditional.Builder();
+ private OrderBy.Builder orderBy = new OrderBy.Builder();
+ private Optional<Value> limit = Optional.empty();
+
+ public Builder withWildcard()
+ {
+ if (selections != null && !selections.isEmpty())
+ throw new IllegalStateException("Attempted to use * for selection but existing selections exist: " + selections);
+ selections = null;
+ return this;
+ }
+
+ public Builder withColumnSelection(String name, AbstractType<?> type)
+ {
+ return withSelection(Reference.of(new Symbol(name, type)));
+ }
+
+ public Builder withSelection(Expression e)
+ {
+ if (selections == null)
+ throw new IllegalStateException("Unable to add '" + e.name() + "' as a selection as * was already requested");
+ selections.add(e);
+ return this;
+ }
+
+ public Builder withTable(String ks, String name)
+ {
+ source = Optional.of(new TableReference(Optional.of(ks), name));
+ return this;
+ }
+
+ public Builder withTable(String name)
+ {
+ source = Optional.of(new TableReference(name));
+ return this;
+ }
+
+ public Builder withTable(TableMetadata table)
+ {
+ source = Optional.of(TableReference.from(table));
+ return this;
+ }
+
+ public Builder withWhere(Where.Inequalities kind, ReferenceExpression ref, Expression expression)
+ {
+ where.where(kind, ref, expression);
+ return this;
+ }
+
+ public Builder withIn(ReferenceExpression symbol, Expression... expressions)
+ {
+ where.in(symbol, expressions);
+ return this;
+ }
+
+ public Builder withIn(ReferenceExpression symbol, List<Expression> expressions)
+ {
+ where.in(symbol, expressions);
+ return this;
+ }
+
+ /**
+ * When the column type/value type isn't known, this will fall back to byte type
+ */
+ public Builder withColumnEquals(String column, ByteBuffer value)
+ {
+ BytesType type = BytesType.instance;
+ return withWhere(Where.Inequalities.EQUAL, Reference.of(new Symbol(column, type)), new Bind(value, type));
+ }
+
+ public Builder withColumnEquals(Symbol column, Expression value)
+ {
+ return withWhere(Where.Inequalities.EQUAL, Reference.of(column), value);
+ }
+
+ public Builder withOrderByColumn(String name, AbstractType<?> type, OrderBy.Ordering ordering)
+ {
+ orderBy.add(Reference.of(new Symbol(name, type)), ordering);
+ return this;
+ }
+
+ public Builder withLimit(Value limit)
+ {
+ this.limit = Optional.of(limit);
+ return this;
+ }
+
+ public Builder withLimit(long limit)
+ {
+ return withLimit(new Literal(limit, LongType.instance));
+ }
+
+ public Select build()
+ {
+ return new Select((selections == null || selections.isEmpty()) ? Collections.emptyList() : ImmutableList.copyOf(selections),
+ source,
+ where.isEmpty() ? Optional.empty() : Optional.of(where.build()),
+ orderBy.isEmpty() ? Optional.empty() : Optional.of(orderBy.build()),
+ limit);
+ }
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Statement.java b/test/unit/org/apache/cassandra/cql3/ast/Statement.java
new file mode 100644
index 0000000000..cded2a2588
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Statement.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.nio.ByteBuffer;
+import java.util.Collection;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.apache.cassandra.utils.ByteBufferUtil;
+
+public interface Statement extends Element
+{
+ enum Kind { SELECT, MUTATION, TXN }
+ Kind kind();
+
+ default Object[] binds()
+ {
+ return streamRecursive()
+ .filter(e -> e instanceof Bind)
+ .map(e -> ((Bind) e).value())
+ .toArray(Object[]::new);
+ }
+
+ default ByteBuffer[] bindsEncoded()
+ {
+ return streamRecursive()
+ .filter(e -> e instanceof Bind)
+ .map(e -> ((Bind) e).encode())
+ .toArray(ByteBuffer[]::new);
+ }
+
+ default String detailedToString()
+ {
+ Object[] binds = binds();
+ return "CQL:\n" + toCQL() + "\nBinds:\n" + IntStream.range(0, binds.length)
+ .mapToObj(i -> i + " -> " + binds[i].getClass().getCanonicalName() + "(" + normalize(binds[i]) + ")")
+ .collect(Collectors.joining("\n"));
+ }
+
+ static boolean hasByteBuffer(Object value)
+ {
+ if (value == null)
+ return false;
+ if (value instanceof ByteBuffer)
+ return true;
+ else if (value instanceof Collection)
+ {
+ Collection<Object> collection = (Collection<Object>) value;
+ return collection.stream().anyMatch(Statement::hasByteBuffer);
+ }
+ else if (value instanceof Map)
+ {
+ Map<Object, Object> map = (Map<Object, Object>) value;
+ return map.entrySet().stream().anyMatch(e -> hasByteBuffer(e.getKey()) || hasByteBuffer(e.getValue()));
+ }
+ return false;
+ }
+
+ static String normalize(Object value)
+ {
+ if (value == null)
+ return null;
+ if (value instanceof ByteBuffer)
+ {
+ ByteBuffer bb = (ByteBuffer) value;
+ if (bb.remaining() > 100)
+ {
+ bb = bb.duplicate();
+ bb.limit(bb.position() + 100);
+ return ByteBufferUtil.bytesToHex(bb) + "...";
+ }
+ return ByteBufferUtil.bytesToHex(bb);
+ }
+ else if (value instanceof Collection)
+ {
+ Collection<Object> collection = (Collection<Object>) value;
+ if (hasByteBuffer(collection))
+ return collection.stream().map(Statement::normalize).collect(Collectors.toList()).toString();
+ }
+ else if (value instanceof Map)
+ {
+ Map<Object, Object> map = (Map<Object, Object>) value;
+ if (hasByteBuffer(map))
+ return map.entrySet().stream()
+ .map(e -> normalize(e.getKey()) + " -> " + normalize(e.getValue()))
+ .collect(Collectors.joining(", ", "{", "}"));
+ }
+ return value.toString();
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Symbol.java b/test/unit/org/apache/cassandra/cql3/ast/Symbol.java
new file mode 100644
index 0000000000..dc4c0aab3c
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Symbol.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.Objects;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.cassandra.cql3.ColumnIdentifier;
+import org.apache.cassandra.cql3.ReservedKeywords;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.schema.ColumnMetadata;
+
+public class Symbol implements ReferenceExpression, Comparable<Symbol>
+{
+ public final String symbol;
+ private final AbstractType<?> type;
+
+ public Symbol(ColumnMetadata column)
+ {
+ this(column.name.toString(), column.type);
+ }
+
+ public Symbol(String symbol, AbstractType<?> type)
+ {
+ this.symbol = Objects.requireNonNull(symbol);
+ this.type = Objects.requireNonNull(type);
+ }
+
+ public static Symbol from(ColumnMetadata metadata)
+ {
+ return new Symbol(metadata.name.toString(), metadata.type.unwrap());
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ maybeQuote(sb, symbol);
+ }
+
+ public static void maybeQuote(StringBuilder sb, String symbol)
+ {
+ if (ReservedKeywords.isReserved(symbol))
+ {
+ // does not matter the casing, if its reserved it MUST be quoted
+ sb.append(quote(symbol));
+ }
+ else
+ {
+ sb.append(ColumnIdentifier.maybeQuote(symbol));
+ }
+ }
+
+ private static final Pattern PATTERN_DOUBLE_QUOTE = Pattern.compile("\"", Pattern.LITERAL);
+ private static final String ESCAPED_DOUBLE_QUOTE = Matcher.quoteReplacement("\"\"");
+
+ //TODO refactor ColumnIdentifier to expose this
+ private static String quote(String text)
+ {
+ return '"' + PATTERN_DOUBLE_QUOTE.matcher(text).replaceAll(ESCAPED_DOUBLE_QUOTE) + '"';
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return type;
+ }
+
+ @Override
+ public String name()
+ {
+ return symbol;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Symbol symbol1 = (Symbol) o;
+ return Objects.equals(symbol, symbol1.symbol);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(symbol);
+ }
+
+ @Override
+ public String toString()
+ {
+ return toCQL();
+ }
+
+ @Override
+ public int compareTo(Symbol o)
+ {
+ return toCQL().compareTo(o.toCQL());
+ }
+
+ public static class UnquotedSymbol extends Symbol
+ {
+ public UnquotedSymbol(String symbol, AbstractType<?> type)
+ {
+ super(symbol, type);
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append(symbol);
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ UnquotedSymbol symbol1 = (UnquotedSymbol) o;
+ return Objects.equals(symbol, symbol1.symbol);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(symbol);
+ }
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/TableReference.java b/test/unit/org/apache/cassandra/cql3/ast/TableReference.java
new file mode 100644
index 0000000000..5fb129464f
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/TableReference.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.Objects;
+import java.util.Optional;
+
+import org.apache.cassandra.schema.TableMetadata;
+
+public class TableReference implements Element
+{
+ public final Optional<String> keyspace;
+ public final String name;
+
+ public TableReference(String name)
+ {
+ this(Optional.empty(), name);
+ }
+
+ public TableReference(Optional<String> keyspace, String name)
+ {
+ this.keyspace = Objects.requireNonNull(keyspace);
+ this.name = Objects.requireNonNull(name);
+ }
+
+ public static TableReference from(TableMetadata metadata)
+ {
+ return new TableReference(Optional.of(metadata.keyspace), metadata.name);
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ if (keyspace.isPresent())
+ {
+ Symbol.maybeQuote(sb, keyspace.get());
+ sb.append('.');
+ }
+ Symbol.maybeQuote(sb, name);
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Txn.java b/test/unit/org/apache/cassandra/cql3/ast/Txn.java
new file mode 100644
index 0000000000..03c0588860
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Txn.java
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.apache.cassandra.cql3.FieldIdentifier;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.BytesType;
+import org.apache.cassandra.db.marshal.UserType;
+
+import static org.apache.cassandra.cql3.ast.Elements.newLine;
+
+public class Txn implements Statement
+{
+ // lets
+ public final List<Let> lets;
+ // return
+ public final Optional<Select> output;
+ public final Optional<If> ifBlock;
+ public final List<Mutation> mutations;
+
+ public Txn(List<Let> lets, Optional<Select> output, Optional<If> ifBlock, List<Mutation> mutations)
+ {
+ this.lets = lets;
+ this.output = output;
+ this.ifBlock = ifBlock;
+ if (ifBlock.isPresent() && !mutations.isEmpty())
+ throw new IllegalArgumentException("Unable to define both IF and non-conditional mutations");
+ this.mutations = mutations;
+ }
+
+ public static Txn wrap(Select select)
+ {
+ return new Txn(Collections.emptyList(), Optional.of(select), Optional.empty(), Collections.emptyList());
+ }
+
+ public static Txn wrap(Mutation mutation)
+ {
+ return new Txn(Collections.emptyList(), Optional.empty(), Optional.empty(), Collections.singletonList(mutation));
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append("BEGIN TRANSACTION");
+ int subIndent = indent + 2;
+
+ stream().forEach(e -> {
+ newLine(sb, subIndent);
+ e.toCQL(sb, subIndent);
+ if (!(e instanceof If))
+ sb.append(';');
+ });
+ newLine(sb, indent);
+ sb.append("COMMIT TRANSACTION");
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ Stream<? extends Element> ret = lets.stream();
+ if (output.isPresent())
+ ret = Stream.concat(ret, Stream.of(output.get()));
+ if (ifBlock.isPresent())
+ ret = Stream.concat(ret, Stream.of(ifBlock.get()));
+ ret = Stream.concat(ret, mutations.stream());
+ return ret;
+ }
+
+ @Override
+ public String toString()
+ {
+ return toCQL();
+ }
+
+ @Override
+ public Kind kind()
+ {
+ return Kind.TXN;
+ }
+
+ private static void recursiveReferences(Collection<Reference> accum, Reference ref)
+ {
+ //NOTE: this doesn't actually collect the references due to lack of support in CQL within a Txn, need to fix those cases
+ //Coverage: Map/Set/List are a bit annoying as they use real values and not something known in the schema, so may need to handle that different in validation
+ AbstractType<?> type = ref.type().unwrap();
+ if (type.isCollection())
+ {
+ //TODO Caleb to add support for [] like normal read/write supports
+// if (type instanceof SetType)
+// {
+// // [value] syntax
+// SetType set = (SetType) type;
+// AbstractType subType = set.getElementsType();
+
+// }
+// else if (type instanceof MapType)
+// {
+// // [key] syntax
+// MapType map = (MapType) type;
+// AbstractType keyType = map.getKeysType();
+// AbstractType valueType = map.getValuesType();
+// }
+ // see Selectable.specForElementOrSlice; ListType is not supported
+ }
+ else if (type.isUDT())
+ {
+ //TODO Caleb to support multiple nesting
+// UserType udt = (UserType) type;
+// for (int i = 0; i < udt.size(); i++)
+// {
+// Reference subRef = ref.add(udt.fieldName(i).toString(), udt.type(i));
+// accum.add(subRef);
+// recursiveReferences(accum, subRef);
+// }
+ }
+ }
+
+ public static class Builder
+ {
+ private final Map<String, Select> lets = new LinkedHashMap<>();
+ // no type system so don't need easy lookup to Expression; just existence check
+ private final Set<Reference> allowedReferences = new HashSet<>();
+ private Optional<Select> output = Optional.empty();
+ private Optional<If> ifBlock = Optional.empty();
+ private final List<Mutation> mutations = new ArrayList<>();
+
+ public Set<Reference> allowedReferences()
+ {
+ return Collections.unmodifiableSet(allowedReferences);
+ }
+
+ public Map<String, Select> lets()
+ {
+ return Collections.unmodifiableMap(lets);
+ }
+
+ public boolean isEmpty()
+ {
+ // don't include output as 'BEGIN TRANSACTION SELECT "000000000000000010000"; COMMIT TRANSACTION' isn't valid
+// return lets.isEmpty();
+ // TransactionStatement defines empty as no SELECT or updates
+ return !output.isPresent() && !ifBlock.isPresent() && mutations.isEmpty();
+ }
+
+ public void addLet(String name, Select.Builder select)
+ {
+ addLet(name, select.build());
+ }
+
+ public void addLet(String name, Select select)
+ {
+ if (lets.containsKey(name))
+ throw new IllegalArgumentException("Let name " + name + " already exists");
+ lets.put(name, select);
+
+ Reference ref = Reference.of(new Symbol.UnquotedSymbol(name, toNamedTuple(select)));
+ for (Expression e : select.selections)
+ addAllowedReference(ref.add(e));
+ }
+
+ private AbstractType<?> toNamedTuple(Select select)
+ {
+ //TODO don't rely on UserType...
+ List<FieldIdentifier> fieldNames = new ArrayList<>(select.selections.size());
+ List<AbstractType<?>> fieldTypes = new ArrayList<>(select.selections.size());
+ for (Expression e : select.selections)
+ {
+ fieldNames.add(FieldIdentifier.forQuoted(e.name()));
+ fieldTypes.add(e.type());
+ }
+ return new UserType(null, null, fieldNames, fieldTypes, false);
+ }
+
+ private void addAllowedReference(Reference ref)
+ {
+ allowedReferences.add(ref);
+ recursiveReferences(allowedReferences, ref);
+ }
+
+ public void addReturn(Select select)
+ {
+ output = Optional.of(select);
+ }
+
+ public void addReturnReferences(String... names)
+ {
+ Select.Builder builder = new Select.Builder();
+ for (String name : names)
+ builder.withSelection(ref(name));
+ addReturn(builder.build());
+ }
+
+ private Reference ref(String name)
+ {
+ if (!name.contains("."))
+ return Reference.of(new Symbol(name, BytesType.instance));
+ String[] splits = name.split("\\.");
+ Reference.Builder builder = new Reference.Builder();
+ builder.add(splits);
+ return builder.build();
+ }
+
+ public void addIf(If block)
+ {
+ ifBlock = Optional.of(block);
+ }
+
+ public void addUpdate(Mutation mutation)
+ {
+ this.mutations.add(Objects.requireNonNull(mutation));
+ }
+
+ public Txn build()
+ {
+ List<Let> lets = this.lets.entrySet().stream().map(e -> new Let(e.getKey(), e.getValue())).collect(Collectors.toList());
+ return new Txn(lets, output, ifBlock, new ArrayList<>(mutations));
+ }
+ }
+
+ public static class If implements Element
+ {
+ private final Conditional conditional;
+ private final List<Mutation> mutations;
+
+ public If(Conditional conditional, List<Mutation> mutations)
+ {
+ this.conditional = conditional;
+ this.mutations = mutations;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append("IF ");
+ conditional.toCQL(sb, indent);
+ sb.append(" THEN");
+ int subIndent = indent + 2;
+ for (Mutation mutation : mutations)
+ {
+ newLine(sb, subIndent);
+ mutation.toCQL(sb, subIndent);
+ sb.append(';');
+ }
+ newLine(sb, indent);
+ sb.append("END IF");
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.concat(Stream.of(conditional), mutations.stream());
+ }
+ }
+
+ public static class Let implements Element
+ {
+ public final String symbol;
+ public final Select select;
+
+ public Let(String symbol, Select select)
+ {
+ this.symbol = symbol;
+ this.select = select;
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ int offset = sb.length();
+ sb.append("LET ").append(symbol).append(" = (");
+ select.toCQL(sb, sb.length() - offset + 2);
+ sb.append(")");
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(select);
+ }
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/TypeHint.java b/test/unit/org/apache/cassandra/cql3/ast/TypeHint.java
new file mode 100644
index 0000000000..53a455dfde
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/TypeHint.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.stream.Stream;
+
+import org.apache.cassandra.db.marshal.AbstractType;
+
+public class TypeHint implements Expression
+{
+ public final Expression e;
+ private final AbstractType<?> type;
+
+ public TypeHint(Expression e, AbstractType<?> type)
+ {
+ this.e = e;
+ this.type = type;
+ }
+
+ public TypeHint(Expression e)
+ {
+ this.e = e;
+ this.type = e.type();
+ }
+
+ /**
+ * {@code ? + ?} is not clear to parsing, so rather than assume the type (like we do for literals) we fail and ask
+ * the user to CAST... so need to {@link TypeHint} when a {@link Bind} is found.
+ *
+ * Wait, {@link TypeHint} and not {@link Cast}? See CASSANDRA-17915...
+ */
+ public static Expression maybeApplyTypeHint(Expression e)
+ {
+ if (!(e instanceof Bind))
+ return e;
+ // see https://the-asf.slack.com/archives/CK23JSY2K/p1663788235000449
+ return new TypeHint(e);
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ sb.append('(').append(type.asCQL3Type()).append(") ");
+ e.toCQL(sb, indent);
+ }
+
+ @Override
+ public AbstractType<?> type()
+ {
+ return type;
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(e);
+ }
+}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/cql3/ast/Value.java
similarity index 52%
copy from test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
copy to test/unit/org/apache/cassandra/cql3/ast/Value.java
index b4e037ef3a..2e1860a8f7 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/ast/Value.java
@@ -16,29 +16,18 @@
* limitations under the License.
*/
-package org.apache.cassandra.utils;
+package org.apache.cassandra.cql3.ast;
-import org.junit.Test;
+import java.nio.ByteBuffer;
-import accord.utils.Gens;
-import org.assertj.core.api.Assertions;
+import org.apache.cassandra.db.marshal.AbstractType;
-import static accord.utils.Property.qt;
-import static org.apache.cassandra.utils.Generators.toGen;
-
-public class CassandraGeneratorsTest
+public interface Value extends Expression
{
- @Test
- public void partitionerToToken()
- {
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.token(p)).next(rs)).isNotNull());
- }
-
- @Test
- public void partitionerKeys()
+ Object value();
+ default ByteBuffer valueEncoded()
{
- qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
- .check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
+ return ((AbstractType) type()).decompose(value());
}
-}
\ No newline at end of file
+ Value with(Object value, AbstractType<?> type);
+}
diff --git a/test/unit/org/apache/cassandra/cql3/ast/Where.java b/test/unit/org/apache/cassandra/cql3/ast/Where.java
new file mode 100644
index 0000000000..bea8c9a44b
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/ast/Where.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.cql3.ast;
+
+import java.util.stream.Stream;
+
+public class Where implements Conditional
+{
+ public enum Inequalities
+ {
+ EQUAL("="),
+ NOT_EQUAL("!="),
+ GREATER_THAN(">"),
+ GREATER_THAN_EQ(">="),
+ LESS_THAN("<"),
+ LESS_THAN_EQ("<=");
+
+ private final String value;
+
+ Inequalities(String value)
+ {
+ this.value = value;
+ }
+ }
+
+ public final Inequalities kind;
+ public final ReferenceExpression symbol;
+ public final Expression expression;
+
+ private Where(Inequalities kind, ReferenceExpression symbol, Expression expression)
+ {
+ this.kind = kind;
+ this.symbol = symbol;
+ this.expression = expression;
+ }
+
+ public static Where create(Inequalities kind, ReferenceExpression ref, Expression expression)
+ {
+ return new Where(kind, ref instanceof Symbol ? Reference.of(ref) : ref, expression);
+ }
+
+ @Override
+ public void toCQL(StringBuilder sb, int indent)
+ {
+ symbol.toCQL(sb, indent);
+ sb.append(' ').append(kind.value).append(' ');
+ expression.toCQL(sb, indent);
+ }
+
+ @Override
+ public Stream<? extends Element> stream()
+ {
+ return Stream.of(symbol, expression);
+ }
+}
diff --git a/test/unit/org/apache/cassandra/repair/FuzzTestBase.java b/test/unit/org/apache/cassandra/repair/FuzzTestBase.java
index de1e8ba9ce..7668ad7296 100644
--- a/test/unit/org/apache/cassandra/repair/FuzzTestBase.java
+++ b/test/unit/org/apache/cassandra/repair/FuzzTestBase.java
@@ -328,7 +328,8 @@ public abstract class FuzzTestBase extends CQLTester.InMemory
TableId id = ids.get(i);
TableMetadata tableMetadata = new CassandraGenerators.TableMetadataBuilder().withKeyspaceName(ks).withTableName(name).withTableId(id).withTableKinds(TableMetadata.Kind.REGULAR)
// shouldn't matter, just wanted to avoid UDT as that needs more setup
- .withDefaultTypeGen(AbstractTypeGenerators.builder().withTypeKinds(AbstractTypeGenerators.TypeKind.PRIMITIVE).withoutPrimitive(EmptyType.instance).build()).build().generate(qt);
+ .withDefaultTypeGen(AbstractTypeGenerators.builder().withTypeKinds(AbstractTypeGenerators.TypeKind.PRIMITIVE).withoutPrimitive(EmptyType.instance))
+ .build(qt);
tableBuilder.add(tableMetadata);
}
KeyspaceParams params = KeyspaceParams.simple(3);
diff --git a/test/unit/org/apache/cassandra/service/accord/EpochSyncTest.java b/test/unit/org/apache/cassandra/service/accord/EpochSyncTest.java
index fc215508ee..fc2a36d8ab 100644
--- a/test/unit/org/apache/cassandra/service/accord/EpochSyncTest.java
+++ b/test/unit/org/apache/cassandra/service/accord/EpochSyncTest.java
@@ -20,7 +20,6 @@ package org.apache.cassandra.service.accord;
import java.net.UnknownHostException;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
@@ -28,6 +27,7 @@ import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
@@ -38,7 +38,7 @@ import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
-import java.util.function.Consumer;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
@@ -60,7 +60,7 @@ import accord.topology.Topology;
import accord.topology.TopologyManager;
import accord.utils.Gen;
import accord.utils.Invariants;
-import accord.utils.Property.UnitCommand;
+import accord.utils.Property.SimpleCommand;
import accord.utils.RandomSource;
import accord.utils.async.AsyncChain;
import accord.utils.async.AsyncChains;
@@ -74,7 +74,6 @@ import org.apache.cassandra.dht.Murmur3Partitioner.LongToken;
import org.apache.cassandra.gms.IFailureDetectionEventListener;
import org.apache.cassandra.gms.IFailureDetector;
import org.apache.cassandra.locator.InetAddressAndPort;
-import org.apache.cassandra.locator.Replica;
import org.apache.cassandra.net.IVerbHandler;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.SimulatedMessageDelivery;
@@ -94,13 +93,18 @@ import org.apache.cassandra.service.consensus.TransactionalMode;
import org.apache.cassandra.tcm.ClusterMetadata;
import org.apache.cassandra.tcm.ClusterMetadataService;
import org.apache.cassandra.tcm.Epoch;
+import org.apache.cassandra.tcm.MultiStepOperation;
import org.apache.cassandra.tcm.StubClusterMetadataService;
+import org.apache.cassandra.tcm.Transformation;
import org.apache.cassandra.tcm.membership.Directory;
import org.apache.cassandra.tcm.membership.Location;
import org.apache.cassandra.tcm.membership.NodeAddresses;
import org.apache.cassandra.tcm.membership.NodeId;
-import org.apache.cassandra.tcm.ownership.DataPlacement;
-import org.apache.cassandra.tcm.ownership.DataPlacements;
+import org.apache.cassandra.tcm.membership.NodeState;
+import org.apache.cassandra.tcm.ownership.UniformRangePlacement;
+import org.apache.cassandra.tcm.sequences.LeaveStreams;
+import org.apache.cassandra.tcm.transformations.PrepareJoin;
+import org.apache.cassandra.tcm.transformations.PrepareLeave;
import org.apache.cassandra.utils.ByteArrayUtil;
import org.apache.cassandra.utils.Pair;
import org.assertj.core.api.Assertions;
@@ -123,20 +127,43 @@ public class EpochSyncTest
@Test
public void test()
{
- stateful().withExamples(50).check(commands(() -> Cluster::new)
- .destroyState(cluster -> {
- cluster.processAll();
- cluster.validate(true);
- })
- .addIf(cluster -> cluster.alive().size() <= cluster.maxNodes, EpochSyncTest::addNode)
- .addIf(cluster -> cluster.alive().size() > cluster.minNodes, EpochSyncTest::removeNode)
- .addIf(cluster -> cluster.hasWork(), EpochSyncTest::processSome)
- .add(rs -> new SimpleCommand("Validate", c -> c.validate(false)))
- .add((rs, cluster) -> new SimpleCommand("Bump Epoch " + (cluster.current.epoch.getEpoch() + 1), Cluster::bumpEpoch))
- .build());
+ stateful().withExamples(50).withSteps(500).check(commands(() -> Cluster::new)
+ .destroyState(cluster -> {
+ finishPendingWork(cluster);
+ cluster.processAll();
+ cluster.validate(true);
+ })
+ .addAllIf(Cluster::hasPendingWork, b ->
+ b.addIf(c -> !c.status(s -> s == Cluster.Status.Registered).isEmpty(), (rs, state) -> {
+ long epoch = state.current.epoch.getEpoch() + 1;
+ Node.Id pick = rs.pick(state.status(s -> s == Cluster.Status.Registered));
+ return new SimpleCommand<>(pick + " Start Joining; epoch=" + epoch,
+ c -> c.increment(pick));
+ })
+ .addIf(c -> !c.current.inProgressSequences.isEmpty(),
+ (rs, state) -> new SimpleCommand<>("Next Epoch Step; epoch=" + (state.current.epoch.getEpoch() + 1),
+ Cluster::incrementInProgressSequences))
+ )
+ .addAllIf(Cluster::hasNoPendingWork, b ->
+ b.addIf(cluster -> cluster.joined().size() <= cluster.maxNodes, EpochSyncTest::addNode)
+ .addIf(cluster -> cluster.joined().size() > cluster.minNodes, EpochSyncTest::removeNode)
+ )
+ .addIf(Cluster::hasWork, EpochSyncTest::processSome)
+ .add(rs -> new SimpleCommand<>("Validate", c -> c.validate(false)))
+ .add((rs, cluster) -> new SimpleCommand<>("Bump Epoch " + (cluster.current.epoch.getEpoch() + 1), Cluster::bumpEpoch))
+ .build());
}
- private static SimpleCommand addNode(RandomSource rs, Cluster cluster)
+ private static void finishPendingWork(Cluster cluster)
+ {
+ List<Node.Id> registered = cluster.status(s -> s == Cluster.Status.Registered);
+ if (!registered.isEmpty())
+ registered.forEach(cluster::increment);
+ while (!cluster.current.inProgressSequences.isEmpty())
+ cluster.incrementInProgressSequences();
+ }
+
+ private static SimpleCommand<Cluster> addNode(RandomSource rs, Cluster cluster)
{
Node.Id id = new Node.Id(++cluster.nodeCounter);
long token = cluster.tokenGen.nextLong(rs);
@@ -144,64 +171,31 @@ public class EpochSyncTest
token = cluster.tokenGen.nextLong(rs);
long epoch = cluster.current.epoch.getEpoch() + 1;
long finalToken = token;
- return new SimpleCommand("Add Node " + id + "; token=" + token + ", epoch=" + epoch,
- c -> c.addNode(id, finalToken));
+ return new SimpleCommand<>("Start Node " + id + "; token=" + token + ", epoch=" + epoch,
+ c -> c.registerNode(id, finalToken));
}
- private static SimpleCommand removeNode(RandomSource rs, Cluster cluster)
+ private static SimpleCommand<Cluster> removeNode(RandomSource rs, Cluster cluster)
{
- List<Node.Id> alive = cluster.alive();
+ List<Node.Id> alive = cluster.joined();
Node.Id pick = rs.pick(alive);
long token = cluster.instances.get(pick).token;
long epoch = cluster.current.epoch.getEpoch() + 1;
- return new SimpleCommand("Remove Node " + pick + "; token=" + token + "; epoch=" + epoch, c -> c.removeNode(pick));
- }
-
- private static SimpleCommand processSome(RandomSource rs)
- {
- return new SimpleCommand("Process Some",
- c -> {//noinspection StatementWithEmptyBody
- for (int i = 0, attempts = rs.nextInt(1, 100); i < attempts && c.processOne(); i++)
- {
- }
- });
+ return new SimpleCommand<>("Remove Node " + pick + "; token=" + token + "; epoch=" + epoch, c -> c.removeNode(pick));
}
- private static class SimpleCommand implements UnitCommand<Cluster, Void>
- {
- private final String name;
- private final Consumer<Cluster> fn;
-
- private SimpleCommand(String name, Consumer<Cluster> fn)
- {
- this.name = name;
- this.fn = fn;
- }
-
- @Override
- public String detailed(Cluster Cluster)
- {
- return name;
- }
-
- @Override
- public void applyUnit(Cluster Cluster)
- {
- fn.accept(Cluster);
- }
-
- @Override
- public void runUnit(Void Void)
- {
-
- }
+ private static SimpleCommand<Cluster> processSome(RandomSource rs) {
+ return new SimpleCommand<>("Process Some",
+ c -> {//noinspection StatementWithEmptyBody
+ for (int i = 0, attempts = rs.nextInt(1, 100); i < attempts && c.processOne(); i++) {
+ }
+ });
}
private static class Cluster
{
private static final int rf = 2;
private static final ReplicationParams replication_params = ReplicationParams.simple(rf);
- private static final ReplicationParams meta = ReplicationParams.simpleMeta(1, Collections.singleton("dc1"));
private final RandomSource rs;
private final int minNodes, maxNodes;
@@ -222,7 +216,7 @@ public class EpochSyncTest
@Override
public boolean isAlive(InetAddressAndPort ep)
{
- return !removed.contains(nodeId(ep));
+ return instances.get(nodeId(ep)).status != Status.Removed;
}
@Override
@@ -262,39 +256,6 @@ public class EpochSyncTest
}
};
- private static InetAddressAndPort address(Node.Id id)
- {
- try
- {
- return InetAddressAndPort.getByAddress(ByteArrayUtil.bytes(id.id));
- }
- catch (UnknownHostException e)
- {
- throw new AssertionError("Unable to create address for id " + id, e);
- }
- }
-
- public enum EpochTracker { topologyManager, accordSyncPropagator, configurationService}
-
- Set<EpochTracker> globalSynced(long epoch)
- {
- return alive().stream()
- .filter(n -> instances.get(n).epoch.getEpoch() <= epoch)
- .map(n -> instances.get(n).synced(epoch))
- .reduce(EnumSet.allOf(EpochTracker.class), Sets::intersection);
- }
-
- boolean allSynced(long epoch)
- {
- Set<EpochTracker> done = globalSynced(epoch);
- return done.contains(EpochTracker.topologyManager);
- }
-
- private static Node.Id nodeId(InetAddressAndPort address)
- {
- return new Node.Id(ByteArrayUtil.getInt(address.addressBytes));
- }
-
public Cluster(RandomSource rs)
{
this.rs = rs;
@@ -321,7 +282,7 @@ public class EpochSyncTest
else
{
// add partition
- List<Node.Id> alive = alive();
+ List<Node.Id> alive = notRemoved();
InetAddressAndPort a = address(rs.pick(alive));
InetAddressAndPort b = address(rs.pick(alive));
while (a.equals(b))
@@ -331,9 +292,89 @@ public class EpochSyncTest
}, 1, 1, TimeUnit.MINUTES);
}
+ private static InetAddressAndPort address(Node.Id id)
+ {
+ try
+ {
+ return InetAddressAndPort.getByAddress(ByteArrayUtil.bytes(id.id));
+ }
+ catch (UnknownHostException e)
+ {
+ throw new AssertionError("Unable to create address for id " + id, e);
+ }
+ }
+
+ private boolean hasPendingWork()
+ {
+ return !status(s -> s == Cluster.Status.Registered).isEmpty()
+ || !current.inProgressSequences.isEmpty();
+ }
+
+ private boolean hasNoPendingWork()
+ {
+ return !hasPendingWork();
+ }
+
+ private Transformation.Success process(Transformation transformation)
+ {
+ Transformation.Result result = transformation.execute(current);
+ if (result.isRejected())
+ throw new IllegalStateException("Unable to make TCM transition: " + result.rejected());
+ return result.success();
+ }
+
+ private Transformation.Success process(MultiStepOperation<?> transformation)
+ {
+ Transformation.Result result = transformation.applyTo(current);
+ if (result.isRejected())
+ throw new IllegalStateException("Unable to make TCM transition");
+ return result.success();
+ }
+
+ public void incrementInProgressSequences()
+ {
+ if (current.inProgressSequences.isEmpty())
+ throw new IllegalStateException("Attempted to bump epoch when nothing was pending");
+ Iterator<MultiStepOperation<?>> it = current.inProgressSequences.iterator();
+ Invariants.checkState(it.hasNext());
+ notify(current = process(it.next()).metadata);
+ }
+
+ private static boolean left(ClusterMetadata metadata, Node.Id id)
+ {
+ return metadata.directory.peerState(new NodeId(id.id)) == NodeState.LEFT;
+ }
+
+ private static boolean joined(ClusterMetadata metadata, Node.Id id)
+ {
+ NodeAddresses address = metadata.directory.getNodeAddresses(new NodeId(id.id));
+ return metadata.placements.get(replication_params).reads.byEndpoint().keySet().contains(address.broadcastAddress);
+ }
+
+ public enum EpochTracker { topologyManager, accordSyncPropagator, configurationService}
+
+ Set<EpochTracker> globalSynced(long epoch)
+ {
+ return notRemoved().stream()
+ .filter(n -> instances.get(n).epoch.getEpoch() <= epoch)
+ .map(n -> instances.get(n).synced(epoch))
+ .reduce(EnumSet.allOf(EpochTracker.class), Sets::intersection);
+ }
+
+ boolean allSynced(long epoch)
+ {
+ Set<EpochTracker> done = globalSynced(epoch);
+ return done.contains(EpochTracker.topologyManager);
+ }
+
+ private static Node.Id nodeId(InetAddressAndPort address)
+ {
+ return new Node.Id(ByteArrayUtil.getInt(address.addressBytes));
+ }
+
void validate(boolean isDone)
{
- for (Node.Id id : alive())
+ for (Node.Id id : notRemoved())
{
Instance inst = instances.get(id);
if (removed.contains(id)) continue; // ignore removed nodes
@@ -352,7 +393,9 @@ public class EpochSyncTest
Assertions.assertThat(tm.hasEpoch(epoch)).describedAs("node%s does not have epoch %d", id, epoch).isTrue();
Ranges ranges = tm.globalForEpoch(epoch).ranges().mergeTouching();
Ranges actual = tm.syncComplete(epoch).mergeTouching();
- Assertions.assertThat(actual).describedAs("node%s does not have all expected sync ranges for epoch %d; missing %s", id, epoch, ranges.without(actual)).isEqualTo(ranges);
+ Assertions.assertThat(actual)
+ .describedAs("node%s does not have all expected sync ranges for epoch %d; missing %s", id, epoch, ranges.without(actual))
+ .isEqualTo(ranges);
}
else
{
@@ -379,13 +422,32 @@ public class EpochSyncTest
String displayTopology()
{
- List<Node.Id> alive = alive();
- List<Pair<Node.Id, Long>> withToken = new ArrayList<>(alive.size());
- for (Node.Id n : alive)
- withToken.add(Pair.create(n, instances.get(n).token));
- withToken.sort(Comparator.comparing(a -> a.right));
+ class Hold {
+ final Cluster.Status status;
+ final long token;
+
+ Hold(Status status, long token)
+ {
+ this.status = status;
+ this.token = token;
+ }
+
+ @Override
+ public String toString()
+ {
+ return status + "\t" + (status == Status.Registered ? "?" : Long.toString(token));
+ }
+ }
+ List<Node.Id> notRemoved = notRemoved();
+ List<Pair<Node.Id, Hold>> list = new ArrayList<>(notRemoved.size());
+ for (Node.Id n : notRemoved)
+ {
+ Instance instance = instances.get(n);
+ list.add(Pair.create(n, new Hold(instance.status, instance.token)));
+ }
+ list.sort(Comparator.comparing(a -> a.right.token));
StringBuilder sb = new StringBuilder();
- for (var p : withToken)
+ for (var p : list)
sb.append(p.left).append('\t').append(p.right).append('\n');
return sb.toString();
}
@@ -427,7 +489,24 @@ public class EpochSyncTest
throw error;
}
- List<Node.Id> alive()
+ List<Node.Id> joined()
+ {
+ return status(s -> s == Status.Joined);
+ }
+
+ List<Node.Id> status(Predicate<Status> fn)
+ {
+ List<Node.Id> ids = new ArrayList<>(instances.size());
+ for (Instance i : instances.values())
+ {
+ if (fn.test(i.status))
+ ids.add(i.id);
+ }
+ ids.sort(Comparator.naturalOrder());
+ return ids;
+ }
+
+ List<Node.Id> notRemoved()
{
ArrayList<Node.Id> ids = new ArrayList<>(Sets.difference(instances.keySet(), removed));
ids.sort(Comparator.naturalOrder());
@@ -461,14 +540,16 @@ public class EpochSyncTest
},
SimulatedMessageDelivery.randomDelay(rs.fork()),
(to, msg) -> instances.get(nodeId(to)).reciver.recieve(msg),
- (action, to, msg) -> logger.warn("{} message {}", action, msg),
+ (action, to, msg) -> logger.trace("{} message {}", action, msg),
scheduler::schedule,
failures::add);
}
- void addNode(Node.Id id, long token)
+ void registerNode(Node.Id id, long token)
{
Invariants.checkState(!tokens.contains(token), "Attempted to add token %d for node %s but token is already taken", token, id);
+ Invariants.checkState(!instances.containsKey(id), "Attempted to add node %s; but already exists", id);
+
Epoch epoch = Epoch.create(current.epoch.getEpoch() + 1);
Instance instance = new Instance(id, token, epoch, createMessaging(id), fd);
@@ -476,38 +557,38 @@ public class EpochSyncTest
tokens.add(token);
current = current.forceEpoch(epoch)
- .withPlacements(DataPlacements.builder(2)
- .with(meta, DataPlacement.empty())
- .with(replication_params, rebuildPlacements(epoch))
- .build())
.withDirectory(current.directory.with(new NodeAddresses(address(id)), new Location("dc1", "r1")));
notify(current);
}
- void removeNode(Node.Id pick)
+ void increment(Node.Id pick)
{
Instance inst = Objects.requireNonNull(instances.get(pick), "Unknown id " + pick);
- Invariants.checkState(!removed.contains(pick), "Can not remove node twice; node " + pick);
- tokens.remove(inst.token);
- removed.add(pick);
- inst.stop();
- current = current.forceEpoch(Epoch.create(current.epoch.getEpoch() + 1))
- .withDirectory(current.directory.without(new NodeId(pick.id)));
-
- current = current.withPlacements(DataPlacements.builder(2)
- .with(meta, DataPlacement.empty())
- .with(replication_params, rebuildPlacements(current.epoch))
- .build());
- notify(current);
+
+ switch (inst.status)
+ {
+ case Init:
+ case Joined:
+ case Removed:
+ throw new IllegalStateException("Unexpected status: " + inst.status);
+ case Registered:
+ inst.status = Status.Joining;
+ PrepareJoin task = new PrepareJoin(new NodeId(pick.id), Collections.singleton(new LongToken(inst.token)), new UniformRangePlacement(), true, false);
+ notify(current = process(task).metadata);
+ break;
+ default:
+ throw new UnsupportedOperationException("Unknown status: " + inst.status);
+ }
}
- private DataPlacement rebuildPlacements(Epoch epoch)
+ void removeNode(Node.Id pick)
{
- DataPlacement.Builder builder = DataPlacement.builder();
- for (Node.Id inst : alive())
- for (Replica replica : instances.get(inst).replica())
- builder.withReadReplica(epoch, replica).withWriteReplica(epoch, replica);
- return builder.build();
+ Instance inst = Objects.requireNonNull(instances.get(pick), "Unknown id " + pick);
+ Invariants.checkState(!removed.contains(pick), "Can not remove node twice; node " + pick);
+ removed.add(pick);
+ inst.status = Status.Leaving;
+ PrepareLeave prepareLeave = new PrepareLeave(new NodeId(pick.id), false, new UniformRangePlacement(), LeaveStreams.Kind.REMOVENODE);
+ notify(current = process(prepareLeave).metadata);
}
void bumpEpoch()
@@ -518,14 +599,15 @@ public class EpochSyncTest
private void notify(ClusterMetadata current)
{
- Ranges ranges = AccordTopology.createAccordTopology(current).ranges().mergeTouching();
- if (!current.directory.isEmpty())
+ Topology t = AccordTopology.createAccordTopology(current);
+ Ranges ranges = t.ranges().mergeTouching();
+ if (!current.placements.get(replication_params).reads.isEmpty())
Assertions.assertThat(ranges).hasSize(1);
((StubClusterMetadataService) ClusterMetadataService.instance()).setMetadata(current);
- for (Node.Id id : alive())
+ for (Node.Id id : status(s -> s != Status.Removed))
{
Instance inst = instances.get(id);
- inst.maybeStart();
+ inst.maybeTransition(current, t);
inst.config.maybeReportMetadata(current);
}
}
@@ -555,7 +637,7 @@ public class EpochSyncTest
};
}
- private enum Status { Init, Started}
+ private enum Status { Init, Registered, Joining, Joined, Leaving, Removed}
private class Instance
{
private final Node.Id id;
@@ -634,12 +716,47 @@ public class EpochSyncTest
this.reciver = messagingService.receiver(new SimulatedMessageDelivery.SimpleVerbHandler(handlers));
}
- void maybeStart()
+ @Override
+ public String toString()
+ {
+ return "Instance{" +
+ "id=" + id +
+ ", token=" + token +
+ ", epoch=" + epoch +
+ ", status=" + status +
+ '}';
+ }
+
+ void maybeTransition(ClusterMetadata current, Topology t)
{
- if (status == Status.Init)
+ switch (status)
{
- start();
- status = Status.Started;
+ case Init:
+ Invariants.checkState(!t.nodes().contains(id), "Node was in Init state but present in the Topology!");
+ Invariants.checkState(current.directory.peerId(address(id)) != null, "Node exists but not in TCM");
+ start();
+ status = Status.Registered;
+ break;
+ case Registered:
+ Invariants.checkState(!t.nodes().contains(id), "Node was in Init state but present in the Topology!");
+ Invariants.checkState(current.directory.peerId(address(id)) != null, "Node exists but not in TCM");
+ if (current.placements.get(replication_params).writes.byEndpoint().keySet().contains(address(id)))
+ status = Status.Joining;
+ break;
+ case Joining:
+ Invariants.checkState(current.directory.peerId(address(id)) != null, "Node exists but not in TCM");
+ if (joined(current, id))
+ status = Status.Joined;
+ case Removed:
+ case Joined:
+ // nothing to do
+ break;
+ case Leaving:
+ if (left(current, id))
+ stop();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unknown status: " + status);
}
}
@@ -653,20 +770,6 @@ public class EpochSyncTest
return topology;
}
- Collection<Replica> replica()
- {
- InetAddressAndPort address = Cluster.address(id);
- SortedSet<Long> lessThan = tokens.headSet(token);
- if (lessThan.isEmpty())
- {
- // wrap around
- return Arrays.asList(new Replica(address, new LongToken(Long.MIN_VALUE), new LongToken(token), true),
- new Replica(address, new LongToken(tokens.last()), new LongToken(Long.MIN_VALUE), true));
- }
-
- return Collections.singletonList(new Replica(address, new LongToken(lessThan.last()), new LongToken(token), true));
- }
-
Set<EpochTracker> synced(long epoch)
{
if (epoch < this.epoch.getEpoch()) throw new IllegalArgumentException("Asked for epoch before this instance existed");
@@ -683,6 +786,8 @@ public class EpochSyncTest
void stop()
{
+ status = Status.Removed;
+ tokens.remove(token);
messaging.stop();
}
}
diff --git a/test/unit/org/apache/cassandra/service/accord/FetchMinEpochTest.java b/test/unit/org/apache/cassandra/service/accord/FetchMinEpochTest.java
new file mode 100644
index 0000000000..936bc13b0b
--- /dev/null
+++ b/test/unit/org/apache/cassandra/service/accord/FetchMinEpochTest.java
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.Assert;
+import org.junit.Test;
+
+import accord.utils.Gen;
+import accord.utils.Gens;
+import accord.utils.RandomSource;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.config.RetrySpec;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Murmur3Partitioner;
+import org.apache.cassandra.io.IVersionedSerializers;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.MessageDelivery;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.net.SimulatedMessageDelivery.Action;
+import org.apache.cassandra.service.accord.api.AccordRoutingKey;
+import org.apache.cassandra.utils.AccordGenerators;
+import org.apache.cassandra.utils.CassandraGenerators;
+import org.apache.cassandra.utils.SimulatedMiniCluster;
+import org.apache.cassandra.utils.SimulatedMiniCluster.Node;
+import org.apache.cassandra.utils.concurrent.Future;
+import org.assertj.core.api.Assertions;
+
+import static accord.utils.Property.qt;
+import static org.apache.cassandra.net.MessagingService.Version.VERSION_51;
+import static org.apache.cassandra.utils.AccordGenerators.fromQT;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class FetchMinEpochTest
+{
+ static
+ {
+ DatabaseDescriptor.clientInitialization();
+ DatabaseDescriptor.setPartitionerUnsafe(Murmur3Partitioner.instance);
+ }
+
+ private static final Gen<Gen<Action>> ACTION_DISTRIBUTION = Gens.enums().allMixedDistribution(Action.class);
+ private static final List<MessagingService.Version> SUPPORTED = Stream.of(MessagingService.Version.values()).filter(v -> v.compareTo(VERSION_51) >= 0).collect(Collectors.toList());
+
+ private static void boundedRetries(int retries)
+ {
+ DatabaseDescriptor.getAccord().minEpochSyncRetry.maxAttempts = new RetrySpec.MaxAttempt(retries);
+ }
+
+ @Test
+ public void requestSerde()
+ {
+ DataOutputBuffer output = new DataOutputBuffer();
+ Gen<FetchMinEpoch> gen = fromQT(CassandraGenerators.partitioners())
+ .flatMap(partitioner ->
+ Gens.lists(AccordGenerators.range(partitioner)
+ .map(r -> (TokenRange) r))
+ .ofSizeBetween(0, 10)
+ .map(FetchMinEpoch::new));
+ qt().forAll(gen).check(req -> {
+ maybeSetPartitioner(req);
+ for (MessagingService.Version version : SUPPORTED)
+ IVersionedSerializers.testSerde(output, FetchMinEpoch.serializer, req, version.value);
+ });
+ }
+
+ @Test
+ public void responseSerde()
+ {
+ Gen<Long> all = Gens.longs().all();
+ Gen<Long> nulls = ignore -> null;
+ Gen<Long> domain = rs -> rs.nextBoolean() ? nulls.next(rs) : all.next(rs);
+ DataOutputBuffer output = new DataOutputBuffer();
+ qt().forAll(domain.map(FetchMinEpoch.Response::new)).check(rsp -> {
+ for (MessagingService.Version version : SUPPORTED)
+ IVersionedSerializers.testSerde(output, FetchMinEpoch.Response.serializer, rsp, version.value);
+ });
+ }
+
+ @Test
+ public void fetchOneNodeAlwaysFails()
+ {
+ int expectedMaxAttempts = 3;
+ boundedRetries(expectedMaxAttempts);
+ qt().check(rs -> {
+ SimulatedMiniCluster cluster = new SimulatedMiniCluster.Builder(rs, node -> msg -> {throw new IllegalStateException();}).build();
+ Node from = cluster.createNodeAndJoin();
+ Node to = cluster.createNodeAndJoin();
+
+ Future<Long> f = FetchMinEpoch.fetch(from, to.broadcastAddressAndPort(), Collections.emptySet());
+ assertThat(f).isNotDone();
+ cluster.processAll();
+ assertThat(f).isDone();
+ MessageDelivery.MaxRetriesException maxRetries = getMaxRetriesException(f);
+ Assertions.assertThat(maxRetries.attempts).isEqualTo(expectedMaxAttempts);
+ });
+ }
+
+ @Test
+ public void fetchOneNode()
+ {
+ int maxRetries = 42;
+ boundedRetries(maxRetries);
+ qt().check(rs -> {
+ long epoch = rs.nextLong(0, Long.MAX_VALUE);
+ SimulatedMiniCluster cluster = new SimulatedMiniCluster.Builder(rs, node -> msg -> node.messaging().respond(new FetchMinEpoch.Response(epoch), msg)).build();
+ Node from = cluster.createNodeAndJoin();
+ {
+ Supplier<Action> safeActionGen = actionGen(rs, maxRetries);
+ from.messagingActions((self, msg, to) -> safeActionGen.get());
+ }
+ Node to = cluster.createNodeAndJoin();
+
+ Future<Long> f = FetchMinEpoch.fetch(from, to.broadcastAddressAndPort(), Collections.emptySet());
+ assertThat(f).isNotDone();
+ cluster.processAll();
+ assertThat(f).isDone();
+ assertThat(f.get()).isEqualTo(epoch);
+ });
+ }
+
+ @Test
+ public void fetchManyNodesAllNodesFail()
+ {
+ int expectedMaxAttempts = 3;
+ boundedRetries(expectedMaxAttempts);
+ qt().check(rs -> {
+ SimulatedMiniCluster cluster = new SimulatedMiniCluster.Builder(rs, node -> msg -> {throw new IllegalStateException();}).build();
+
+ Node from = cluster.createNodeAndJoin();
+ Node to1 = cluster.createNodeAndJoin();
+ Node to2 = cluster.createNodeAndJoin();
+ Node to3 = cluster.createNodeAndJoin();
+ Node to4 = cluster.createNodeAndJoin();
+
+ Future<Long> f = FetchMinEpoch.fetch(from, ImmutableMap.of(to1.broadcastAddressAndPort(), Collections.emptySet(),
+ to2.broadcastAddressAndPort(), Collections.emptySet(),
+ to3.broadcastAddressAndPort(), Collections.emptySet(),
+ to4.broadcastAddressAndPort(), Collections.emptySet()));
+ assertThat(f).isNotDone();
+ cluster.processAll();
+ assertThat(f).isDone();
+ assertThat(f.get()).isNull();
+ });
+ }
+
+ @Test
+ public void fetchManyNodes()
+ {
+ boundedRetries(Integer.MAX_VALUE); // networking should be unbounded, but the actions should be bounded
+ int maxRetries = 3;
+ qt().check(rs -> {
+ Map<Integer, Long> nodeToEpoch = new HashMap<>();
+ Long min = null;
+ for (int i = 2; i < 6; i++)
+ {
+ Long epoch = rs.nextBoolean() ? null : rs.nextLong();
+ nodeToEpoch.put(i, epoch);
+ if (min == null) min = epoch;
+ else if (epoch != null) min = Math.min(min, epoch);
+ }
+
+ SimulatedMiniCluster cluster = new SimulatedMiniCluster.Builder(rs, node -> msg -> node.messaging().respond(new FetchMinEpoch.Response(nodeToEpoch.get(node.id().id())), msg)).build();
+
+ Node from = cluster.createNodeAndJoin();
+ Node to1 = cluster.createNodeAndJoin();
+ Node to2 = cluster.createNodeAndJoin();
+ Node to3 = cluster.createNodeAndJoin();
+ Node to4 = cluster.createNodeAndJoin();
+ Map<InetAddressAndPort, Supplier<Action>> nodeToActions = ImmutableMap.of(to1.broadcastAddressAndPort(), actionGen(rs, maxRetries),
+ to2.broadcastAddressAndPort(), actionGen(rs, maxRetries),
+ to3.broadcastAddressAndPort(), actionGen(rs, maxRetries),
+ to4.broadcastAddressAndPort(), actionGen(rs, maxRetries));
+ from.messagingActions((self, msg, to) -> nodeToActions.get(to).get());
+
+ Future<Long> f = FetchMinEpoch.fetch(from, ImmutableMap.of(to1.broadcastAddressAndPort(), Collections.emptySet(),
+ to2.broadcastAddressAndPort(), Collections.emptySet(),
+ to3.broadcastAddressAndPort(), Collections.emptySet(),
+ to4.broadcastAddressAndPort(), Collections.emptySet()));
+ assertThat(f).isNotDone();
+ cluster.processAll();
+ assertThat(f).isDone();
+ assertThat(f.get()).isEqualTo(min);
+ });
+ }
+
+ private static Supplier<Action> actionGen(RandomSource rs, int maxRetries)
+ {
+ RandomSource actionSource = rs.fork();
+ Gen<Action> actionGen = ACTION_DISTRIBUTION.next(actionSource);
+ // it is very possible that DELIVER is very rare, which will cause the test to run for a long time and could fail in CI,
+ // when a long history of non-DELIVER is seen, start to force DELIVER to bound the amount of processing in the test
+ Gen<Action> safeActionGen = new Gen<>()
+ {
+ private int notDelivers = 0;
+ @Override
+ public Action next(RandomSource rng)
+ {
+ if (notDelivers > maxRetries - 1)
+ return Action.DELIVER;
+ Action action = actionGen.next(rng);
+ if (action == Action.DELIVER) notDelivers = 0;
+ else notDelivers++;
+ return action;
+ }
+ };
+ return safeActionGen.asSupplier(actionSource);
+ }
+
+ private static void maybeSetPartitioner(FetchMinEpoch req)
+ {
+ IPartitioner partitioner = null;
+ for (TokenRange r : req.ranges)
+ {
+ IPartitioner rangePartitioner = null;
+ if (r.start().kindOfRoutingKey() == AccordRoutingKey.RoutingKeyKind.TOKEN)
+ rangePartitioner = r.start().token().getPartitioner();
+ if (rangePartitioner == null && r.end().kindOfRoutingKey() == AccordRoutingKey.RoutingKeyKind.TOKEN)
+ rangePartitioner = r.end().token().getPartitioner();
+ if (rangePartitioner == null)
+ continue;
+ if (partitioner == null)
+ {
+ partitioner = rangePartitioner;
+ }
+ else
+ {
+ Assertions.assertThat(rangePartitioner).isEqualTo(partitioner);
+ }
+ }
+ if (partitioner != null)
+ DatabaseDescriptor.setPartitionerUnsafe(partitioner);
+ }
+
+ private static MessageDelivery.MaxRetriesException getMaxRetriesException(Future<Long> f) throws InterruptedException, ExecutionException
+ {
+ MessageDelivery.MaxRetriesException maxRetries;
+ try
+ {
+ f.get();
+ Assert.fail("Future should have failed");
+ throw new AssertionError("Unreachable");
+ }
+ catch (ExecutionException e)
+ {
+ if (e.getCause() instanceof MessageDelivery.MaxRetriesException)
+ {
+ maxRetries = (MessageDelivery.MaxRetriesException) e.getCause();
+ }
+ else
+ {
+ throw e;
+ }
+ }
+ return maxRetries;
+ }
+}
\ No newline at end of file
diff --git a/test/unit/org/apache/cassandra/utils/ASTGenerators.java b/test/unit/org/apache/cassandra/utils/ASTGenerators.java
new file mode 100644
index 0000000000..20a84f49ca
--- /dev/null
+++ b/test/unit/org/apache/cassandra/utils/ASTGenerators.java
@@ -0,0 +1,604 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.StreamSupport;
+
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Sets;
+
+import org.apache.cassandra.cql3.ast.And;
+import org.apache.cassandra.cql3.ast.AssignmentOperator;
+import org.apache.cassandra.cql3.ast.Bind;
+import org.apache.cassandra.cql3.ast.CasCondition;
+import org.apache.cassandra.cql3.ast.Conditional;
+import org.apache.cassandra.cql3.ast.Expression;
+import org.apache.cassandra.cql3.ast.Literal;
+import org.apache.cassandra.cql3.ast.Mutation;
+import org.apache.cassandra.cql3.ast.Operator;
+import org.apache.cassandra.cql3.ast.Reference;
+import org.apache.cassandra.cql3.ast.Select;
+import org.apache.cassandra.cql3.ast.Symbol;
+import org.apache.cassandra.cql3.ast.TableReference;
+import org.apache.cassandra.cql3.ast.Txn;
+import org.apache.cassandra.cql3.ast.TypeHint;
+import org.apache.cassandra.cql3.ast.Value;
+import org.apache.cassandra.cql3.ast.Where;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.Int32Type;
+import org.apache.cassandra.db.marshal.IntegerType;
+import org.apache.cassandra.db.marshal.MapType;
+import org.apache.cassandra.db.marshal.SetType;
+import org.apache.cassandra.db.marshal.ShortType;
+import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.schema.TableMetadata;
+import org.quicktheories.core.Gen;
+import org.quicktheories.core.RandomnessSource;
+import org.quicktheories.generators.SourceDSL;
+import org.quicktheories.impl.Constraint;
+
+import static org.apache.cassandra.utils.Generators.SYMBOL_NOT_RESERVED_KEYWORD_GEN;
+
+public class ASTGenerators
+{
+ static Gen<Value> valueGen(Object value, AbstractType<?> type)
+ {
+ Gen<Boolean> bool = SourceDSL.booleans().all();
+ return rnd -> bool.generate(rnd) ? new Bind(value, type) : new Literal(value, type);
+ }
+
+ static Gen<Value> valueGen(AbstractType<?> type)
+ {
+ Gen<?> v = AbstractTypeGenerators.getTypeSupport(type).valueGen;
+ return rnd -> valueGen(v.generate(rnd), type).generate(rnd);
+ }
+
+ public static Gen<AssignmentOperator> assignmentOperatorGen(EnumSet<AssignmentOperator.Kind> allowed, Expression right)
+ {
+ if (allowed.isEmpty())
+ throw new IllegalArgumentException("Unable to create a operator gen for empty set of allowed operators");
+ if (allowed.size() == 1)
+ return SourceDSL.arbitrary().constant(new AssignmentOperator(Iterables.getFirst(allowed, null), right));
+
+ Gen<AssignmentOperator.Kind> kind = SourceDSL.arbitrary().pick(new ArrayList<>(allowed));
+ return kind.map(k -> new AssignmentOperator(k, right));
+ }
+
+ public static Gen<Operator> operatorGen(Set<Operator.Kind> allowed, Expression e, Gen<Value> paramValueGen)
+ {
+ if (allowed.isEmpty())
+ throw new IllegalArgumentException("Unable to create a operator gen for empty set of allowed operators");
+ Gen<Operator.Kind> kindGen = allowed.size() == 1 ?
+ SourceDSL.arbitrary().constant(Iterables.getFirst(allowed, null))
+ : SourceDSL.arbitrary().pick(new ArrayList<>(allowed));
+ Gen<Boolean> bool = SourceDSL.booleans().all();
+ return rnd -> {
+ Gen<Value> valueGen = paramValueGen;
+ Operator.Kind kind = kindGen.generate(rnd);
+ if (kind == Operator.Kind.SUBTRACT && e.type() instanceof MapType)
+ {
+ // `map - set` not `map - map`
+ valueGen = valueGen.map(v -> {
+ // since we know E is of type map we know the value is a map
+ Map<?, ?> map = (Map<?, ?>) v.value();
+ Set<?> newValue = map.keySet();
+ SetType<Object> newType = SetType.getInstance(((MapType) e.type()).nameComparator(), false);
+ return v.with(newValue, newType);
+ });
+ }
+ Expression other = valueGen.generate(rnd);
+ Expression left, right;
+ if (bool.generate(rnd))
+ {
+ left = e;
+ right = other;
+ }
+ else
+ {
+ left = other;
+ right = e;
+ }
+ //TODO (correctness): "(smallint) ? - 16250" failed, but is this general or is it a small int thing?
+ //NOTE: (smallint) of -11843 and 3749 failed as well...
+ //NOTE: (long) was found and didn't fail...
+ //NOTE: see https://the-asf.slack.com/archives/CK23JSY2K/p1724819303058669 - varint didn't fail but serialized using int32 which causes equality mismatches for pk/ck lookups
+ if (e.type().unwrap() == ShortType.instance
+ || e.type().unwrap() == IntegerType.instance) // seed=7525457176675272023L
+ {
+ left = new TypeHint(left);
+ right = new TypeHint(right);
+ }
+ return new Operator(kind, TypeHint.maybeApplyTypeHint(left), TypeHint.maybeApplyTypeHint(right));
+ };
+ }
+
+ public static class SelectGenBuilder
+ {
+ private final TableMetadata metadata;
+ private Gen<List<Expression>> selectGen;
+ private Gen<Map<Symbol, Expression>> partitionKeyGen;
+ private Gen<Optional<Value>> limit;
+
+ public SelectGenBuilder(TableMetadata metadata)
+ {
+ this.metadata = Objects.requireNonNull(metadata);
+ this.selectGen = selectColumns(metadata);
+ this.partitionKeyGen = partitionKeyGen(metadata);
+
+ withDefaultLimit();
+ }
+
+ public SelectGenBuilder withSelectStar()
+ {
+ selectGen = ignore -> Collections.emptyList();
+ return this;
+ }
+
+ public SelectGenBuilder withDefaultLimit()
+ {
+ Gen<Optional<Value>> non = ignore -> Optional.empty();
+ Constraint limitLength = Constraint.between(1, 10_000);
+ Gen<Optional<Value>> positive = rnd -> Optional.of(valueGen(Math.toIntExact(rnd.next(limitLength)), Int32Type.instance).generate(rnd));
+ limit = non.mix(positive);
+ return this;
+ }
+
+ public SelectGenBuilder withLimit1()
+ {
+ this.limit = rnd -> Optional.of(valueGen(1, Int32Type.instance).generate(rnd));
+ return this;
+ }
+
+ public SelectGenBuilder withoutLimit()
+ {
+ this.limit = ignore -> Optional.empty();
+ return this;
+ }
+
+ public SelectGenBuilder withPrimaryKeys(Map<Symbol, Expression> primaryKeys)
+ {
+ partitionKeyGen = ignore -> primaryKeys;
+ return this;
+ }
+
+ public Gen<Select> build()
+ {
+ return rnd -> {
+ List<Expression> select = selectGen.generate(rnd);
+ Map<Symbol, Expression> partitionKey = partitionKeyGen.generate(rnd);
+ Conditional partitionKeyClause = and(partitionKey);
+ return new Select(select, Optional.of(TableReference.from(metadata)), Optional.of(partitionKeyClause), Optional.empty(), limit.generate(rnd));
+ };
+ }
+
+ private static Conditional and(Map<Symbol, Expression> data)
+ {
+ Conditional.Builder builder = new Conditional.Builder();
+ for (Map.Entry<Symbol, Expression> e : data.entrySet())
+ builder.where(Where.Inequalities.EQUAL, e.getKey(), e.getValue());
+ return builder.build();
+ }
+
+ private static Gen<List<Expression>> selectColumns(TableMetadata metadata)
+ {
+ List<ColumnMetadata> columns = new ArrayList<>(metadata.columns());
+ Constraint between = Constraint.between(0, columns.size() - 1);
+ Gen<int[]> indexGen = rnd -> {
+ int size = Math.toIntExact(rnd.next(between)) + 1;
+ Set<Integer> dedup = new HashSet<>();
+ while (dedup.size() < size)
+ dedup.add(Math.toIntExact(rnd.next(between)));
+ return dedup.stream().mapToInt(Integer::intValue).toArray();
+ };
+ return rnd -> {
+ int[] indexes = indexGen.generate(rnd);
+ List<Expression> es = new ArrayList<>(indexes.length);
+ IntStream.of(indexes).mapToObj(columns::get).forEach(c -> {
+ Reference ref = Reference.of(new Symbol(c));
+ es.add(ref);
+ });
+ return es;
+ };
+ }
+
+ private static Gen<Map<Symbol, Expression>> partitionKeyGen(TableMetadata metadata)
+ {
+ Map<ColumnMetadata, Gen<?>> gens = new LinkedHashMap<>();
+ for (ColumnMetadata col : metadata.columns())
+ gens.put(col, AbstractTypeGenerators.getTypeSupport(col.type).valueGen);
+ return rnd -> {
+ Map<Symbol, Expression> output = new LinkedHashMap<>();
+ for (ColumnMetadata col : metadata.partitionKeyColumns())
+ output.put(new Symbol(col), gens.get(col)
+ .map(o -> valueGen(o, col.type).generate(rnd))
+ .generate(rnd));
+ return output;
+ };
+ }
+ }
+
+ public static class MutationGenBuilder
+ {
+ private final TableMetadata metadata;
+ private final Set<Symbol> allColumns;
+ private final Set<Symbol> primaryColumns;
+ private final Set<Symbol> nonPrimaryColumns;
+ private Gen<Mutation.Kind> kindGen = SourceDSL.arbitrary().enumValues(Mutation.Kind.class);
+ private Gen<OptionalInt> ttlGen = SourceDSL.integers().between(1, Math.toIntExact(TimeUnit.DAYS.toSeconds(10))).map(i -> i % 2 == 0 ? OptionalInt.empty() : OptionalInt.of(i));
+ private Gen<OptionalLong> timestampGen = SourceDSL.longs().between(1, Long.MAX_VALUE).map(i -> i % 2 == 0 ? OptionalLong.empty() : OptionalLong.of(i));
+ private Gen<Map<Symbol, Expression>> valuesGen;
+ private boolean allowOperators = true;
+ private Collection<Reference> references = Collections.emptyList();
+ private Gen<Boolean> withCasGen = SourceDSL.booleans().all();
+ private Gen<Boolean> useCasIf = SourceDSL.booleans().all();
+ private BiFunction<RandomnessSource, List<Symbol>, List<Symbol>> ifConditionFilter = (rnd, symbols) -> symbols;
+ private final Map<Symbol, Gen<?>> columnDataGens;
+
+ public MutationGenBuilder(TableMetadata metadata)
+ {
+ this.metadata = Objects.requireNonNull(metadata);
+ this.allColumns = Mutation.toSet(metadata.columns());
+ this.primaryColumns = Mutation.toSet(metadata.primaryKeyColumns());
+ this.nonPrimaryColumns = Sets.difference(allColumns, primaryColumns);
+
+ columnDataGens = new LinkedHashMap<>();
+ for (ColumnMetadata col : metadata.columns())
+ columnDataGens.put(new Symbol(col), AbstractTypeGenerators.getTypeSupport(col.type).valueGen);
+ this.valuesGen = rnd -> {
+ Map<Symbol, Expression> map = new HashMap<>();
+ for (Symbol name : allColumns)
+ {
+ Gen<?> gen = columnDataGens.get(name);
+ map.put(name, valueGen(gen.generate(rnd), name.type()).generate(rnd));
+ }
+ return map;
+ };
+ }
+
+ public MutationGenBuilder withoutTransaction()
+ {
+ withoutCas();
+ return this;
+ }
+
+ public MutationGenBuilder withCas()
+ {
+ withCasGen = SourceDSL.arbitrary().constant(true);
+ return this;
+ }
+
+ public MutationGenBuilder withoutCas()
+ {
+ withCasGen = SourceDSL.arbitrary().constant(false);
+ return this;
+ }
+
+ public MutationGenBuilder withCasGen(Gen<Boolean> withCasGen)
+ {
+ withCasGen = Objects.requireNonNull(withCasGen);
+ return this;
+ }
+
+ public MutationGenBuilder withCasIf()
+ {
+ useCasIf = SourceDSL.arbitrary().constant(true);
+ return this;
+ }
+
+ public MutationGenBuilder withoutCasIf()
+ {
+ useCasIf = SourceDSL.arbitrary().constant(false);
+ return this;
+ }
+
+ public MutationGenBuilder withCasIfGen(Gen<Boolean> gen)
+ {
+ useCasIf = Objects.requireNonNull(gen);
+ return this;
+ }
+
+ public MutationGenBuilder withIfColumnFilter(BiFunction<RandomnessSource, List<Symbol>, List<Symbol>> ifConditionFilter)
+ {
+ this.ifConditionFilter = Objects.requireNonNull(ifConditionFilter);
+ return this;
+ }
+
+ public MutationGenBuilder withoutTimestamp()
+ {
+ timestampGen = ignore -> OptionalLong.empty();
+ return this;
+ }
+
+ public MutationGenBuilder withOperators()
+ {
+ allowOperators = true;
+ return this;
+ }
+
+ public MutationGenBuilder withoutOperators()
+ {
+ allowOperators = false;
+ return this;
+ }
+
+ public MutationGenBuilder withReferences(Collection<Reference> references)
+ {
+ this.references = references;
+ return this;
+ }
+
+ public Gen<Mutation> build()
+ {
+ Map<Symbol, ColumnMetadata> allColumnsMap = metadata.columns().stream().collect(Collectors.toMap(m -> new Symbol(m), Function.identity()));
+ List<Symbol> allColumns = new ArrayList<>(allColumnsMap.keySet());
+ Collections.sort(allColumns);
+ Gen<Boolean> bool = SourceDSL.booleans().all();
+ return rnd -> {
+ Mutation.Kind kind = kindGen.generate(rnd);
+ boolean isCas = withCasGen.generate(rnd);
+ boolean isTransaction = isCas; //TODO (coverage): add accord support
+ // when there are not non-primary-columns then can't support UPDATE
+ if (nonPrimaryColumns.isEmpty())
+ {
+ int i;
+ int maxRetries = 42;
+ for (i = 0; i < maxRetries && kind == Mutation.Kind.UPDATE; i++)
+ kind = kindGen.generate(rnd);
+ if (i == maxRetries)
+ throw new IllegalArgumentException("Kind gen kept returning UPDATE, but not supported when there are no non-primary columns");
+ }
+
+ Map<Symbol, Expression> values = valuesGen.generate(rnd);
+ Map<? extends AbstractType<?>, List<Reference>> typeToReference = references.stream().collect(Collectors.groupingBy(Reference::type));
+ if (!typeToReference.isEmpty())
+ {
+ // Due to being able to discover the partition key *before running*, we don't
+ // allow WHERE clause to have references, so the type of mutation dicates what columns
+ // are allowed to be mutated
+ List<Symbol> allowed = nonPrimaryColumns.stream().filter(values::containsKey).collect(Collectors.toList());
+ for (Symbol s : allowed)
+ {
+ List<Reference> matches = typeToReference.get(s.type());
+ if (matches == null)
+ continue;
+ if (bool.generate(rnd))
+ values.put(s, SourceDSL.arbitrary().pick(matches).generate(rnd));
+ }
+ }
+ if (allowOperators)
+ {
+ for (Symbol c : allColumns)
+ {
+ Set<Operator.Kind> operatorAllowed = Operator.supportsOperators(allColumnsMap.get(c).type);
+ EnumSet<AssignmentOperator.Kind> additionOperatorAllowed = isTransaction
+ ? AssignmentOperator.supportsOperators(allColumnsMap.get(c).type)
+ : EnumSet.noneOf(AssignmentOperator.Kind.class);
+ if (values.containsKey(c))
+ {
+ if (!operatorAllowed.isEmpty() && bool.generate(rnd))
+ {
+ Expression e = values.get(c);
+ //TODO remove hack; currently INSERT references with operators fails
+ if (!(e instanceof Reference))
+ {
+ Gen<Operator> operatorGen = operatorGen(operatorAllowed, e, valueGen(e.type()));
+ values.put(c, operatorGen.generate(rnd));
+ }
+ }
+ if (!additionOperatorAllowed.isEmpty() && kind == Mutation.Kind.UPDATE && nonPrimaryColumns.contains(c) && bool.generate(rnd))
+ {
+ values.put(c, assignmentOperatorGen(additionOperatorAllowed, values.get(c)).generate(rnd));
+ }
+ }
+ }
+ }
+ Optional<? extends CasCondition> casCondition = Optional.empty();
+ if (isCas)
+ {
+ switch (kind)
+ {
+ case INSERT:
+ casCondition = Optional.of(CasCondition.Simple.NotExists);
+ break;
+ case UPDATE:
+ {
+ if (useCasIf.generate(rnd))
+ {
+ casCondition = ifGen(metadata.regularAndStaticColumns()).generate(rnd);
+ }
+ else
+ {
+ casCondition = Optional.of(CasCondition.Simple.Exists);
+ }
+ }
+ break;
+ case DELETE:
+ {
+ if (metadata.staticColumns().isEmpty() || !useCasIf.generate(rnd))
+ {
+ casCondition = Optional.of(CasCondition.Simple.Exists);
+ }
+ else
+ {
+ casCondition = ifGen(metadata.staticColumns()).generate(rnd);
+ }
+ }
+ break;
+ default:
+ throw new AssertionError();
+ }
+ }
+ return new Mutation(kind, metadata, values, ttlGen.generate(rnd), timestampGen.generate(rnd), casCondition);
+ };
+ }
+
+ private Gen<Optional<CasCondition.IfCondition>> ifGen(Iterable<ColumnMetadata> iterable)
+ {
+ List<Symbol> possibleColumns = StreamSupport.stream(iterable.spliterator(), false).map(Symbol::new).collect(Collectors.toList());
+ return rnd -> {
+ List<Symbol> symbols = ifConditionFilter.apply(rnd, possibleColumns);
+ if (symbols == null || symbols.isEmpty())
+ return Optional.empty();
+ Conditional.Builder builder = new Conditional.Builder();
+ for (Symbol symbol : symbols)
+ builder.where(Where.Inequalities.EQUAL, symbol, valueGen(columnDataGens.get(symbol).generate(rnd), symbol.type()).generate(rnd));
+ return Optional.of(new CasCondition.IfCondition(builder.build()));
+ };
+ }
+ }
+
+ public static class TxnGenBuilder
+ {
+ public enum TxReturn { NONE, TABLE, REF}
+ private final TableMetadata metadata;
+ private Constraint letRange = Constraint.between(0, 3);
+ private Constraint ifUpdateRange = Constraint.between(1, 3);
+ private Constraint updateRange = Constraint.between(0, 3);
+ private Gen<Select> selectGen;
+ private Gen<TxReturn> txReturnGen = SourceDSL.arbitrary().enumValues(TxReturn.class);
+ private boolean allowReferences = true;
+
+ public TxnGenBuilder(TableMetadata metadata)
+ {
+ this.metadata = metadata;
+ this.selectGen = new SelectGenBuilder(metadata)
+ .withLimit1()
+ .build();
+ }
+
+ public TxnGenBuilder withoutReferences()
+ {
+ this.allowReferences = false;
+ return this;
+ }
+
+ public Gen<Txn> build()
+ {
+ Gen<Boolean> bool = SourceDSL.booleans().all();
+ return rnd -> {
+ Txn.Builder builder = new Txn.Builder();
+ do
+ {
+ int numLets = Math.toIntExact(rnd.next(letRange));
+ for (int i = 0; i < numLets; i++)
+ {
+ // LET doesn't use normal symbol logic and acts closer to a common lanaguage; name does not lower
+ // case... it is possible that a reserved word gets used, so make sure to use a generator that
+ // filters those out.
+ String name;
+ while (builder.lets().containsKey(name = SYMBOL_NOT_RESERVED_KEYWORD_GEN.generate(rnd))) {}
+ builder.addLet(name, selectGen.generate(rnd));
+ }
+ Gen<Reference> refGen = SourceDSL.arbitrary().pick(new ArrayList<>(builder.allowedReferences()));
+ if (allowReferences)
+ {
+ switch (txReturnGen.generate(rnd))
+ {
+ case REF:
+ {
+ if (!builder.allowedReferences().isEmpty())
+ {
+ Gen<List<Reference>> refsGen = SourceDSL.lists().of(refGen).ofSizeBetween(1, Math.max(10, builder.allowedReferences().size()));
+ builder.addReturn(new Select((List<Expression>) (List<?>) refsGen.generate(rnd)));
+ }
+ }
+ break;
+ case TABLE:
+ builder.addReturn(selectGen.generate(rnd));
+ break;
+ }
+ }
+ else
+ {
+ builder.addReturn(selectGen.generate(rnd));
+ }
+ MutationGenBuilder mutationBuilder = new MutationGenBuilder(metadata)
+ .withoutCas()
+ .withoutTimestamp()
+ .withReferences(new ArrayList<>(builder.allowedReferences()));
+ if (!allowReferences)
+ mutationBuilder.withReferences(Collections.emptyList());
+ Gen<Mutation> updateGen = mutationBuilder.build();
+ if (allowReferences && !builder.lets().isEmpty() && bool.generate(rnd))
+ {
+ Gen<Conditional> conditionalGen = conditionalGen(refGen);
+ int numUpdates = Math.toIntExact(rnd.next(ifUpdateRange));
+ List<Mutation> mutations = new ArrayList<>(numUpdates);
+ for (int i = 0; i < numUpdates; i++)
+ mutations.add(updateGen.generate(rnd));
+ builder.addIf(new Txn.If(conditionalGen.generate(rnd), mutations));
+ }
+ else
+ {
+ // Current limitation is that mutations are tied to the condition if present; can't have
+ // a condition and mutations that don't belong to it in v1... once multiple conditions are
+ // supported then can always attempt to add updates
+ int numUpdates = Math.toIntExact(rnd.next(updateRange));
+ for (int i = 0; i < numUpdates; i++)
+ builder.addUpdate(updateGen.generate(rnd));
+ }
+ } while (builder.isEmpty());
+ return builder.build();
+ };
+ }
+
+ private static Gen<Conditional> conditionalGen(Gen<Reference> refGen)
+ {
+ Constraint numConditionsConstraint = Constraint.between(1, 10);
+ return rnd -> {
+ //TODO support OR
+ Gen<Where> whereGen = whereGen(refGen.generate(rnd));
+ int size = Math.toIntExact(rnd.next(numConditionsConstraint));
+ Conditional accum = whereGen.generate(rnd);
+ for (int i = 1; i < size; i++)
+ accum = new And(accum, whereGen.generate(rnd));
+ return accum;
+ };
+ }
+
+ private static Gen<Where> whereGen(Reference ref)
+ {
+ Gen<Where.Inequalities> kindGen = SourceDSL.arbitrary().enumValues(Where.Inequalities.class);
+ Gen<?> dataGen = AbstractTypeGenerators.getTypeSupport(ref.type()).valueGen;
+ return rnd -> {
+ Where.Inequalities kind = kindGen.generate(rnd);
+ return Where.create(kind, ref, valueGen(dataGen.generate(rnd), ref.type()).generate(rnd));
+ };
+ }
+ }
+}
diff --git a/test/unit/org/apache/cassandra/utils/AbstractTypeGenerators.java b/test/unit/org/apache/cassandra/utils/AbstractTypeGenerators.java
index 0fe8315add..23e6579ce8 100644
--- a/test/unit/org/apache/cassandra/utils/AbstractTypeGenerators.java
+++ b/test/unit/org/apache/cassandra/utils/AbstractTypeGenerators.java
@@ -244,17 +244,22 @@ public final class AbstractTypeGenerators
return () -> PRIMITIVE_TYPE_DATA_GENS.put(type, original);
}
- public static TypeGenBuilder withoutUnsafeEquality()
+ public static TypeGenBuilder withoutUnsafeEquality(TypeGenBuilder builder)
{
// make sure to keep UNSAFE_EQUALITY in-sync
- return AbstractTypeGenerators.builder()
- .withoutEmpty()
- .withoutPrimitive(DurationType.instance)
- // decimal "normalizes" the data to compare, so primary columns "may" mutate the data, causing missmatches
- // see CASSANDRA-18530
- .withoutPrimitive(DecimalType.instance)
- // counters are only for top level
- .withoutTypeKinds(TypeKind.COUNTER);
+ return builder
+ .withoutEmpty()
+ .withoutPrimitive(DurationType.instance)
+ // decimal "normalizes" the data to compare, so primary columns "may" mutate the data, causing missmatches
+ // see CASSANDRA-18530
+ .withoutPrimitive(DecimalType.instance)
+ // counters are only for top level
+ .withoutTypeKinds(TypeKind.COUNTER);
+ }
+
+ public static TypeGenBuilder withoutUnsafeEquality()
+ {
+ return withoutUnsafeEquality(AbstractTypeGenerators.builder());
}
public interface Releaser extends AutoCloseable
@@ -745,6 +750,18 @@ public final class AbstractTypeGenerators
return userTypeGen(elementGen, sizeGen, ksGen, nameGen, BOOLEAN_GEN);
}
+ private static ThreadLocal<String> OVERRIDE_KEYSPACE = new ThreadLocal<>();
+
+ public static void overrideUDTKeyspace(String ks)
+ {
+ OVERRIDE_KEYSPACE.set(ks);
+ }
+
+ public static void clearUDTKeyspace()
+ {
+ OVERRIDE_KEYSPACE.remove();
+ }
+
public static Gen<UserType> userTypeGen(Gen<AbstractType<?>> elementGen, Gen<Integer> sizeGen, Gen<String> ksGen, Gen<String> nameGen, Gen<Boolean> multiCellGen)
{
Gen<FieldIdentifier> fieldNameGen = IDENTIFIER_GEN.map(FieldIdentifier::forQuoted);
@@ -753,7 +770,9 @@ public final class AbstractTypeGenerators
int numElements = sizeGen.generate(rnd);
List<AbstractType<?>> fieldTypes = new ArrayList<>(numElements);
LinkedHashSet<FieldIdentifier> fieldNames = new LinkedHashSet<>(numElements);
- String ks = ksGen.generate(rnd);
+ String ks = OVERRIDE_KEYSPACE.get();
+ if (ks == null)
+ ks = ksGen.generate(rnd);
String name = nameGen.generate(rnd);
ByteBuffer nameBB = AsciiType.instance.decompose(name);
@@ -1154,12 +1173,11 @@ public final class AbstractTypeGenerators
public static void extractUDTs(AbstractType<?> type, Set<UserType> matches)
{
- if (type instanceof ReversedType)
- type = ((ReversedType) type).baseType;
- if (type instanceof UserType)
- matches.add((UserType) type);
- for (AbstractType<?> t : type.subTypes())
- extractUDTs(t, matches);
+ visit(type, t -> {
+ if (t instanceof UserType)
+ matches.add((UserType) t);
+ return VisitAction.CONTINUE;
+ });
}
public static String typeTree(AbstractType<?> type)
diff --git a/test/unit/org/apache/cassandra/utils/AbstractTypeGeneratorsTest.java b/test/unit/org/apache/cassandra/utils/AbstractTypeGeneratorsTest.java
new file mode 100644
index 0000000000..2cd5470a6b
--- /dev/null
+++ b/test/unit/org/apache/cassandra/utils/AbstractTypeGeneratorsTest.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils;
+
+import java.util.ArrayList;
+
+import org.junit.Test;
+
+import accord.utils.LazyToString;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.assertj.core.api.Assertions;
+import org.quicktheories.core.Gen;
+import org.quicktheories.generators.SourceDSL;
+
+import static org.quicktheories.QuickTheory.qt;
+
+public class AbstractTypeGeneratorsTest
+{
+ @Test
+ public void withoutPrimitive()
+ {
+ Gen<AbstractType<?>> primitiveGen = SourceDSL.arbitrary().pick(new ArrayList<>(AbstractTypeGenerators.primitiveTypes()));
+ qt().forAll(r -> r).checkAssert(rs -> {
+ AbstractType<?> primitiveType = primitiveGen.generate(rs);
+ Gen<AbstractType<?>> gen = AbstractTypeGenerators.builder().withoutPrimitive(primitiveType).build();
+ for (int i = 0; i < 1000; i++)
+ {
+ AbstractType<?> type = gen.generate(rs);
+ Assertions.assertThat(AbstractTypeGenerators.contains(type, primitiveType))
+ .describedAs("Expected type %s not to be found in %s", primitiveType.asCQL3Type(), new LazyToString(() -> AbstractTypeGenerators.typeTree(type)))
+ .isFalse();
+ if (type.subTypes().isEmpty())
+ break; // not worth checking this type again...
+ }
+ });
+ }
+}
\ No newline at end of file
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGenerators.java b/test/unit/org/apache/cassandra/utils/CassandraGenerators.java
index f45d05b7ce..3abae215e5 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGenerators.java
+++ b/test/unit/org/apache/cassandra/utils/CassandraGenerators.java
@@ -21,14 +21,23 @@ import java.lang.reflect.Modifier;
import java.math.BigInteger;
import java.net.InetAddress;
import java.nio.ByteBuffer;
+import java.util.ArrayDeque;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.NavigableMap;
+import java.util.Objects;
import java.util.Set;
+import java.util.TreeMap;
import java.util.UUID;
+import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -38,6 +47,7 @@ import javax.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
import org.apache.commons.lang3.builder.MultilineRecursiveToStringStyle;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
@@ -53,6 +63,7 @@ import org.apache.cassandra.db.Slices;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.ByteBufferAccessor;
import org.apache.cassandra.db.marshal.CompositeType;
+import org.apache.cassandra.db.marshal.CounterColumnType;
import org.apache.cassandra.db.marshal.EmptyType;
import org.apache.cassandra.db.rows.Cell;
import org.apache.cassandra.db.marshal.UserType;
@@ -66,21 +77,39 @@ import org.apache.cassandra.dht.RandomPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.ReversedLongLocalPartitioner;
import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.gms.ApplicationState;
import org.apache.cassandra.gms.EndpointState;
import org.apache.cassandra.gms.HeartBeatState;
import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.io.sstable.format.SSTableFormat;
+import org.apache.cassandra.locator.AbstractReplicationStrategy;
import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.locator.LocalStrategy;
+import org.apache.cassandra.locator.MetaStrategy;
+import org.apache.cassandra.locator.NetworkTopologyStrategy;
+import org.apache.cassandra.locator.SimpleStrategy;
import org.apache.cassandra.net.ConnectionType;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.NoPayload;
import org.apache.cassandra.net.PingRequest;
import org.apache.cassandra.net.Verb;
import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.schema.KeyspaceMetadata;
+import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.schema.MemtableParams;
+import org.apache.cassandra.schema.ReplicationParams;
import org.apache.cassandra.schema.TableId;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.schema.TableParams;
+import org.apache.cassandra.schema.Tables;
+import org.apache.cassandra.schema.Types;
+import org.apache.cassandra.schema.UserFunctions;
+import org.apache.cassandra.schema.Views;
+import org.apache.cassandra.service.accord.fastpath.FastPathStrategy;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.utils.AbstractTypeGenerators.TypeGenBuilder;
import org.apache.cassandra.utils.AbstractTypeGenerators.ValueDomain;
import org.quicktheories.core.Gen;
import org.quicktheories.core.RandomnessSource;
@@ -90,6 +119,7 @@ import org.quicktheories.impl.Constraint;
import static org.apache.cassandra.utils.AbstractTypeGenerators.allowReversed;
import static org.apache.cassandra.utils.AbstractTypeGenerators.getTypeSupport;
+import static org.apache.cassandra.utils.AbstractTypeGenerators.withoutUnsafeEquality;
import static org.apache.cassandra.utils.Generators.IDENTIFIER_GEN;
import static org.apache.cassandra.utils.Generators.SMALL_TIME_SPAN_NANOS;
import static org.apache.cassandra.utils.Generators.TIMESTAMP_NANOS;
@@ -185,15 +215,219 @@ public final class CassandraGenerators
return SourceDSL.arbitrary().pick("big", "bti");
}
+ public static Gen<SSTableFormat<?, ?>> sstableFormat()
+ {
+ // make sure ordering is determanstic, else repeatability breaks
+ NavigableMap<String, SSTableFormat<?, ?>> formats = new TreeMap<>(DatabaseDescriptor.getSSTableFormats());
+ return SourceDSL.arbitrary().pick(new ArrayList<>(formats.values()));
+ }
+
+ public static class AbstractReplicationStrategyBuilder
+ {
+ public enum Strategy
+ {
+ Simple(true),
+ NetworkTopology(true),
+ Local(false),
+ Meta(false);
+
+ public final boolean userAllowed;
+
+ Strategy(boolean userAllowed)
+ {
+ this.userAllowed = userAllowed;
+ }
+ }
+
+ private Gen<Strategy> strategyGen = SourceDSL.arbitrary().enumValues(Strategy.class);
+ private Gen<String> keyspaceNameGen = KEYSPACE_NAME_GEN;
+ private Gen<Integer> rfGen = SourceDSL.integers().between(1, 3);
+ private Gen<List<String>> networkTopologyDCGen = rs -> {
+ Gen<Integer> numDcsGen = SourceDSL.integers().between(1, 3);
+ Gen<String> nameGen = IDENTIFIER_GEN;
+ Set<String> dcs = new HashSet<>();
+ int targetSize = numDcsGen.generate(rs);
+ while (dcs.size() != targetSize)
+ dcs.add(nameGen.generate(rs));
+ List<String> ordered = new ArrayList<>(dcs);
+ ordered.sort(Comparator.naturalOrder());
+ return ordered;
+ };
+
+ public AbstractReplicationStrategyBuilder withKeyspace(Gen<String> keyspaceNameGen)
+ {
+ this.keyspaceNameGen = keyspaceNameGen;
+ return this;
+ }
+
+ public AbstractReplicationStrategyBuilder withKeyspace(String keyspace)
+ {
+ this.keyspaceNameGen = i -> keyspace;
+ return this;
+ }
+
+ public AbstractReplicationStrategyBuilder withUserAllowed()
+ {
+ List<Strategy> allowed = Stream.of(Strategy.values()).filter(s -> s.userAllowed).collect(Collectors.toList());
+ strategyGen = SourceDSL.arbitrary().pick(allowed);
+ return this;
+ }
+
+ public AbstractReplicationStrategyBuilder withRf(Gen<Integer> rfGen)
+ {
+ this.rfGen = rfGen;
+ return this;
+ }
+
+ public AbstractReplicationStrategyBuilder withRf(int rf)
+ {
+ this.rfGen = i -> rf;
+ return this;
+ }
+
+ public AbstractReplicationStrategyBuilder withDatacenters(Gen<List<String>> networkTopologyDCGen)
+ {
+ this.networkTopologyDCGen = networkTopologyDCGen;
+ return this;
+ }
+
+ public AbstractReplicationStrategyBuilder withDatacenters(String first, String... rest)
+ {
+ if (rest.length == 0)
+ {
+ this.networkTopologyDCGen = i -> Collections.singletonList(first);
+ }
+ else
+ {
+ List<String> all = new ArrayList<>(rest.length + 1);
+ all.add(first);
+ all.addAll(Arrays.asList(rest));
+ this.networkTopologyDCGen = i -> all;
+ }
+ return this;
+ }
+
+ public Gen<AbstractReplicationStrategy> build()
+ {
+ return rs -> {
+ Strategy strategy = strategyGen.generate(rs);
+ switch (strategy)
+ {
+ case Simple:
+ return new SimpleStrategy(keyspaceNameGen.generate(rs),
+ ImmutableMap.of(SimpleStrategy.REPLICATION_FACTOR, rfGen.generate(rs).toString()));
+ case NetworkTopology:
+ ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
+ List<String> names = networkTopologyDCGen.generate(rs);
+ for (String name : names)
+ builder.put(name, rfGen.generate(rs).toString());
+ ImmutableMap<String, String> map = builder.build();
+ return new TestableNetworkTopologyStrategy(keyspaceNameGen.generate(rs), map);
+ case Meta:
+ return new MetaStrategy(keyspaceNameGen.generate(rs), ImmutableMap.of());
+ case Local:
+ return new LocalStrategy(keyspaceNameGen.generate(rs), ImmutableMap.of());
+ default:
+ throw new UnsupportedOperationException(strategy.name());
+ }
+ };
+ }
+ }
+
+ public static class TestableNetworkTopologyStrategy extends NetworkTopologyStrategy
+ {
+ public TestableNetworkTopologyStrategy(String keyspaceName, Map<String, String> configOptions) throws ConfigurationException
+ {
+ super(keyspaceName, configOptions);
+ }
+
+ @Override
+ public Collection<String> recognizedOptions(ClusterMetadata metadata)
+ {
+ return configOptions.keySet();
+ }
+ }
+
+ public static KeyspaceMetadataBuilder regularKeyspace()
+ {
+ return new KeyspaceMetadataBuilder().withKind(KeyspaceMetadata.Kind.REGULAR);
+ }
+
+ public static class KeyspaceMetadataBuilder
+ {
+ private Gen<String> nameGen = KEYSPACE_NAME_GEN;
+ private Gen<KeyspaceMetadata.Kind> kindGen = SourceDSL.arbitrary().enumValues(KeyspaceMetadata.Kind.class);
+ private Gen<AbstractReplicationStrategyBuilder> replicationGen = i -> new AbstractReplicationStrategyBuilder();
+ private Gen<Boolean> durableWritesGen = SourceDSL.booleans().all();
+
+ public KeyspaceMetadataBuilder withReplication(Gen<AbstractReplicationStrategyBuilder> replicationGen)
+ {
+ this.replicationGen = replicationGen;
+ return this;
+ }
+
+ public KeyspaceMetadataBuilder withReplication(AbstractReplicationStrategyBuilder replication)
+ {
+ this.replicationGen = i -> replication;
+ return this;
+ }
+
+ public KeyspaceMetadataBuilder withName(Gen<String> nameGen)
+ {
+ this.nameGen = nameGen;
+ return this;
+ }
+
+ public KeyspaceMetadataBuilder withName(String name)
+ {
+ this.nameGen = i -> name;
+ return this;
+ }
+
+ public KeyspaceMetadataBuilder withKind(Gen<KeyspaceMetadata.Kind> kindGen)
+ {
+ this.kindGen = kindGen;
+ return this;
+ }
+
+ public KeyspaceMetadataBuilder withKind(KeyspaceMetadata.Kind kind)
+ {
+ this.kindGen = i -> kind;
+ return this;
+ }
+
+ public Gen<KeyspaceMetadata> build()
+ {
+ return rs -> {
+ String name = nameGen.generate(rs);
+ KeyspaceMetadata.Kind kind = kindGen.generate(rs);
+ AbstractReplicationStrategy replication = replicationGen.generate(rs).withKeyspace(nameGen).build().generate(rs);
+ ReplicationParams replicationParams = ReplicationParams.copy(replication);
+ boolean durableWrites = durableWritesGen.generate(rs);
+ KeyspaceParams params = new KeyspaceParams(durableWrites, replicationParams, FastPathStrategy.simple());
+ Tables tables = Tables.none();
+ Views views = Views.none();
+ Types types = Types.none();
+ UserFunctions userFunctions = UserFunctions.none();
+ return KeyspaceMetadata.createUnsafe(name, kind, params, tables, views, types, userFunctions);
+ };
+ }
+ }
+
+ public static TableMetadataBuilder regularTable()
+ {
+ return new TableMetadataBuilder()
+ .withTableKinds(TableMetadata.Kind.REGULAR)
+ .withKnownMemtables();
+ }
+
public static class TableMetadataBuilder
{
private Gen<String> ksNameGen = CassandraGenerators.KEYSPACE_NAME_GEN;
private Gen<String> tableNameGen = IDENTIFIER_GEN;
- private Gen<AbstractType<?>> defaultTypeGen = AbstractTypeGenerators.builder()
- .withDefaultSetKey(AbstractTypeGenerators.withoutUnsafeEquality())
- .withMaxDepth(1)
- .build();
- private Gen<AbstractType<?>> partitionColTypeGen, clusteringColTypeGen, staticColTypeGen, regularColTypeGen;
+ private TypeGenBuilder defaultTypeGen = defaultTypeGen();
+ private Gen<Boolean> useCounter = ignore -> false;
+ private TypeGenBuilder partitionColTypeGen, clusteringColTypeGen, staticColTypeGen, regularColTypeGen;
private Gen<TableId> tableIdGen = TABLE_ID_GEN;
private Gen<TableMetadata.Kind> tableKindGen = SourceDSL.arbitrary().constant(TableMetadata.Kind.REGULAR);
private Gen<Integer> numPartitionColumnsGen = SourceDSL.integers().between(1, 2);
@@ -201,6 +435,51 @@ public final class CassandraGenerators
private Gen<Integer> numRegularColumnsGen = SourceDSL.integers().between(1, 5);
private Gen<Integer> numStaticColumnsGen = SourceDSL.integers().between(0, 2);
private Gen<String> memtableKeyGen = null;
+ @Nullable
+ private Gen<TransactionalMode> transactionalMode = null;
+ @Nullable
+ private ColumnNameGen columnNameGen = null;
+
+ public static TypeGenBuilder defaultTypeGen()
+ {
+ return AbstractTypeGenerators.builder()
+ .withoutEmpty()
+ .withDefaultSetKey(withoutUnsafeEquality())
+ .withMaxDepth(1)
+ .withoutTypeKinds(AbstractTypeGenerators.TypeKind.COUNTER);
+ }
+
+ public TableMetadataBuilder withSimpleColumnNames()
+ {
+ columnNameGen = (i, kind, offset) -> {
+ switch (kind)
+ {
+ case PARTITION_KEY: return "pk" + offset;
+ case CLUSTERING: return "ck" + offset;
+ case STATIC: return "s" + offset;
+ case REGULAR: return "v" + offset;
+ default: throw new UnsupportedOperationException("Unknown kind: " + kind);
+ }
+ };
+ return this;
+ }
+
+ public TableMetadataBuilder withUseCounter(Gen<Boolean> useCounter)
+ {
+ this.useCounter = Objects.requireNonNull(useCounter);
+ return this;
+ }
+
+ public TableMetadataBuilder withTransactionalMode(Gen<TransactionalMode> transactionalMode)
+ {
+ this.transactionalMode = transactionalMode;
+ return this;
+ }
+
+ public TableMetadataBuilder withTransactionalMode(TransactionalMode transactionalMode)
+ {
+ return withTransactionalMode(SourceDSL.arbitrary().constant(transactionalMode));
+ }
public TableMetadataBuilder withKnownMemtables()
{
@@ -295,38 +574,44 @@ public final class CassandraGenerators
return this;
}
- public TableMetadataBuilder withDefaultTypeGen(Gen<AbstractType<?>> typeGen)
+ public TableMetadataBuilder withDefaultTypeGen(TypeGenBuilder typeGen)
{
this.defaultTypeGen = typeGen;
return this;
}
- public TableMetadataBuilder withPrimaryColumnTypeGen(Gen<AbstractType<?>> typeGen)
+ public TableMetadataBuilder withoutEmpty()
+ {
+ defaultTypeGen.withoutEmpty();
+ return this;
+ }
+
+ public TableMetadataBuilder withPrimaryColumnTypeGen(TypeGenBuilder typeGen)
{
withPartitionColumnTypeGen(typeGen);
withClusteringColumnTypeGen(typeGen);
return this;
}
- public TableMetadataBuilder withPartitionColumnTypeGen(Gen<AbstractType<?>> typeGen)
+ public TableMetadataBuilder withPartitionColumnTypeGen(TypeGenBuilder typeGen)
{
this.partitionColTypeGen = typeGen;
return this;
}
- public TableMetadataBuilder withClusteringColumnTypeGen(Gen<AbstractType<?>> typeGen)
+ public TableMetadataBuilder withClusteringColumnTypeGen(TypeGenBuilder typeGen)
{
this.clusteringColTypeGen = typeGen;
return this;
}
- public TableMetadataBuilder withStaticColumnTypeGen(Gen<AbstractType<?>> typeGen)
+ public TableMetadataBuilder withStaticColumnTypeGen(TypeGenBuilder typeGen)
{
this.staticColTypeGen = typeGen;
return this;
}
- public TableMetadataBuilder withRegularColumnTypeGen(Gen<AbstractType<?>> typeGen)
+ public TableMetadataBuilder withRegularColumnTypeGen(TypeGenBuilder typeGen)
{
this.regularColTypeGen = typeGen;
return this;
@@ -345,36 +630,72 @@ public final class CassandraGenerators
public TableMetadata build(RandomnessSource rnd)
{
- if (partitionColTypeGen == null && clusteringColTypeGen == null)
- withPrimaryColumnTypeGen(Generators.filter(defaultTypeGen, t -> !AbstractTypeGenerators.UNSAFE_EQUALITY.contains(t.getClass())));
+ Gen<AbstractType<?>> partitionColTypeGen = withoutUnsafeEquality(new TypeGenBuilder(this.partitionColTypeGen != null ? this.partitionColTypeGen : defaultTypeGen)).build();
+ Gen<AbstractType<?>> clusteringColTypeGen = withoutUnsafeEquality(new TypeGenBuilder(this.clusteringColTypeGen != null ? this.clusteringColTypeGen : defaultTypeGen)).build();
+ Gen<AbstractType<?>> staticColTypeGen = (this.staticColTypeGen != null ? this.staticColTypeGen : defaultTypeGen).build();
+ Gen<AbstractType<?>> regularColTypeGen = (this.regularColTypeGen != null ? this.regularColTypeGen : defaultTypeGen).build();
String ks = ksNameGen.generate(rnd);
- String tableName = tableNameGen.generate(rnd);
- TableParams.Builder params = TableParams.builder();
- if (memtableKeyGen != null)
- params.memtable(MemtableParams.get(memtableKeyGen.generate(rnd)));
- TableMetadata.Builder builder = TableMetadata.builder(ks, tableName, tableIdGen.generate(rnd))
- .partitioner(partitioners().generate(rnd))
- .kind(tableKindGen.generate(rnd))
- .isCounter(BOOLEAN_GEN.generate(rnd))
- .params(params.build());
-
- int numPartitionColumns = numPartitionColumnsGen.generate(rnd);
- int numClusteringColumns = numClusteringColumnsGen.generate(rnd);
- int numRegularColumns = numRegularColumnsGen.generate(rnd);
- int numStaticColumns = numStaticColumnsGen.generate(rnd);
-
- Set<String> createdColumnNames = new HashSet<>();
- for (int i = 0; i < numPartitionColumns; i++)
- builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.PARTITION_KEY, createdColumnNames, partitionColTypeGen == null ? defaultTypeGen : partitionColTypeGen, rnd));
- for (int i = 0; i < numClusteringColumns; i++)
- builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.CLUSTERING, createdColumnNames, clusteringColTypeGen == null ? defaultTypeGen : clusteringColTypeGen, rnd));
- for (int i = 0; i < numStaticColumns; i++)
- builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.STATIC, createdColumnNames, staticColTypeGen == null ? defaultTypeGen : staticColTypeGen, rnd));
- for (int i = 0; i < numRegularColumns; i++)
- builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.REGULAR, createdColumnNames, regularColTypeGen == null ? defaultTypeGen : regularColTypeGen, rnd));
+ AbstractTypeGenerators.overrideUDTKeyspace(ks);
+ try
+ {
+ String tableName = tableNameGen.generate(rnd);
+ TableParams.Builder params = TableParams.builder();
+ if (memtableKeyGen != null)
+ params.memtable(MemtableParams.get(memtableKeyGen.generate(rnd)));
+ if (transactionalMode != null)
+ params.transactionalMode(transactionalMode.generate(rnd));
+ boolean isCounter = useCounter.generate(rnd);
+ TableMetadata.Builder builder = TableMetadata.builder(ks, tableName, tableIdGen.generate(rnd))
+ .partitioner(partitioners().generate(rnd))
+ .kind(tableKindGen.generate(rnd))
+ .isCounter(isCounter)
+ .params(params.build());
+
+ int numPartitionColumns = numPartitionColumnsGen.generate(rnd);
+ int numClusteringColumns = numClusteringColumnsGen.generate(rnd);
+ int numRegularColumns = numRegularColumnsGen.generate(rnd);
+ int numStaticColumns = numStaticColumnsGen.generate(rnd);
+
+ ColumnNameGen nameGen;
+ if (columnNameGen != null)
+ {
+ nameGen = columnNameGen;
+ }
+ else
+ {
+ Set<String> createdColumnNames = new HashSet<>();
+ // filter for unique names
+ nameGen = (r, i1, i2) -> {
+ String str;
+ while (!createdColumnNames.add(str = IDENTIFIER_GEN.generate(r)))
+ {
+ }
+ return str;
+ };
+ }
+ for (int i = 0; i < numPartitionColumns; i++)
+ builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.PARTITION_KEY, i, nameGen, partitionColTypeGen, rnd));
+ for (int i = 0; i < numClusteringColumns; i++)
+ builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.CLUSTERING, i, nameGen, clusteringColTypeGen, rnd));
- return builder.build();
+ if (isCounter)
+ {
+ builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.REGULAR, 0, nameGen, ignore -> CounterColumnType.instance, rnd));
+ }
+ else
+ {
+ for (int i = 0; i < numStaticColumns; i++)
+ builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.STATIC, i, nameGen, staticColTypeGen, rnd));
+ for (int i = 0; i < numRegularColumns; i++)
+ builder.addColumn(createColumnDefinition(ks, tableName, ColumnMetadata.Kind.REGULAR, i, nameGen, regularColTypeGen, rnd));
+ }
+ return builder.build();
+ }
+ finally
+ {
+ AbstractTypeGenerators.clearUDTKeyspace();
+ }
}
}
@@ -386,13 +707,19 @@ public final class CassandraGenerators
String ks = ksNameGen.generate(rs);
String table = tableNameGen.generate(rs);
ColumnMetadata.Kind kind = kindGen.generate(rs);
- return createColumnDefinition(ks, table, kind, new HashSet<>(), typeGen, rs);
+ return createColumnDefinition(ks, table, kind, 0, (r, i1, i2) -> IDENTIFIER_GEN.generate(r), typeGen, rs);
};
}
+ public interface ColumnNameGen
+ {
+ String next(RandomnessSource rs, ColumnMetadata.Kind kind, int kindOffset);
+ }
+
private static ColumnMetadata createColumnDefinition(String ks, String table,
ColumnMetadata.Kind kind,
- Set<String> createdColumnNames, /* This is mutated to check for collisions, so has a side effect outside of normal random generation */
+ int kindOffset,
+ ColumnNameGen nameGen,
Gen<AbstractType<?>> typeGen,
RandomnessSource rnd)
{
@@ -410,14 +737,12 @@ public final class CassandraGenerators
// when working on a clustering column, add in reversed types periodically
typeGen = allowReversed(typeGen);
}
- // filter for unique names
- String str;
- while (!createdColumnNames.add(str = IDENTIFIER_GEN.generate(rnd)))
- {
- }
+ String str = nameGen.next(rnd, kind, kindOffset);
+
ColumnIdentifier name = new ColumnIdentifier(str, true);
- int position = !kind.isPrimaryKeyKind() ? -1 : (int) rnd.next(Constraint.between(0, 30));
- return new ColumnMetadata(ks, table, name, typeGen.generate(rnd), position, kind, null);
+ int position = !kind.isPrimaryKeyKind() ? -1 : kindOffset;
+ AbstractType<?> type = typeGen.generate(rnd);
+ return new ColumnMetadata(ks, table, name, type, position, kind, null);
}
public static Gen<ByteBuffer> partitionKeyDataGen(TableMetadata metadata)
@@ -439,27 +764,7 @@ public final class CassandraGenerators
public static Gen<ByteBuffer[]> data(TableMetadata metadata, @Nullable Gen<ValueDomain> valueDomainGen)
{
- AbstractTypeGenerators.TypeSupport<?>[] types = new AbstractTypeGenerators.TypeSupport[metadata.columns().size()];
- Iterator<ColumnMetadata> it = metadata.allColumnsInSelectOrder();
- int partitionColumns = metadata.partitionKeyColumns().size();
- int clusteringColumns = metadata.clusteringColumns().size();
- int primaryKeyColumns = partitionColumns + clusteringColumns;
- for (int i = 0; it.hasNext(); i++)
- {
- ColumnMetadata col = it.next();
- types[i] = AbstractTypeGenerators.getTypeSupportWithNulls(col.type, i < partitionColumns ? null : valueDomainGen);
- if (i < partitionColumns)
- types[i] = types[i].withoutEmptyData();
- if (i >= partitionColumns && i < primaryKeyColumns)
- // clustering doesn't allow null...
- types[i] = types[i].mapBytes(b -> b == null ? ByteBufferUtil.EMPTY_BYTE_BUFFER : b);
- }
- return rnd -> {
- ByteBuffer[] row = new ByteBuffer[types.length];
- for (int i = 0; i < row.length; i++)
- row[i] = types[i].bytesGen().generate(rnd);
- return row;
- };
+ return new DataGeneratorBuilder(metadata).withValueDomain(valueDomainGen).build();
}
/**
@@ -906,4 +1211,126 @@ public final class CassandraGenerators
return partitioner.decorateKey(valueGen.generate(rs));
};
}
+
+ public static void visitUDTs(TableMetadata metadata, Consumer<UserType> fn)
+ {
+ Set<UserType> udts = CassandraGenerators.extractUDTs(metadata);
+ if (!udts.isEmpty())
+ {
+ Deque<UserType> pending = new ArrayDeque<>(udts);
+ Set<ByteBuffer> visited = new HashSet<>();
+ while (!pending.isEmpty())
+ {
+ UserType next = pending.poll();
+ Set<UserType> subTypes = AbstractTypeGenerators.extractUDTs(next);
+ subTypes.remove(next); // it includes self
+ if (subTypes.isEmpty() || subTypes.stream().allMatch(t -> visited.contains(t.name)))
+ {
+ fn.accept(next);
+ visited.add(next.name);
+ }
+ else
+ {
+ pending.add(next);
+ }
+ }
+ }
+ }
+
+ public static class DataGeneratorBuilder
+ {
+ private final TableMetadata metadata;
+ @Nullable
+ private Gen<ValueDomain> valueDomainGen = null;
+
+ public DataGeneratorBuilder(TableMetadata metadata)
+ {
+ this.metadata = metadata;
+ }
+
+ public DataGeneratorBuilder withValueDomain(@Nullable Gen<ValueDomain> valueDomainGen)
+ {
+ this.valueDomainGen = valueDomainGen;
+ return this;
+ }
+
+ public Gen<Gen<ByteBuffer[]>> build(Gen<Integer> numUniqPartitionsGen)
+ {
+ AbstractTypeGenerators.TypeSupport<?>[] types = typeSupport();
+ return rnd -> {
+ int numPartitions = numUniqPartitionsGen.generate(rnd);
+ Set<List<ByteBuffer>> partitions = Sets.newHashSetWithExpectedSize(numPartitions);
+ int partitionColumns = metadata.partitionKeyColumns().size();
+ for (int i = 0; i < numPartitions; i++)
+ {
+ List<ByteBuffer> pk = new ArrayList<>(partitionColumns);
+ int attempts = 0;
+ do
+ {
+ attempts++;
+ pk.clear();
+ for (int c = 0; c < partitionColumns; c++)
+ pk.add(types[c].bytesGen().generate(rnd));
+ }
+ while (!partitions.add(pk) && attempts < 42);
+ }
+ List<List<ByteBuffer>> deterministicOrder = new ArrayList<>(partitions);
+ deterministicOrder.sort((a, b) -> {
+ int rc = 0;
+ for (int i = 0; i < a.size(); i++)
+ {
+ rc = a.get(i).compareTo(b.get(i));
+ if (rc != 0) return rc;
+ }
+ return rc;
+ });
+
+ Gen<List<ByteBuffer>> pkGen = SourceDSL.arbitrary().pick(deterministicOrder);
+
+ return next -> {
+ // select partition
+ List<ByteBuffer> pk = pkGen.generate(next);
+ // generate rest
+ ByteBuffer[] row = new ByteBuffer[types.length];
+ for (int i = 0; i < pk.size(); i++)
+ row[i] = pk.get(i);
+
+ for (int i = partitionColumns; i < row.length; i++)
+ row[i] = types[i].bytesGen().generate(rnd);
+ return row;
+ };
+ };
+ }
+
+ public Gen<ByteBuffer[]> build()
+ {
+ AbstractTypeGenerators.TypeSupport<?>[] types = typeSupport();
+ return rnd -> {
+ ByteBuffer[] row = new ByteBuffer[types.length];
+ for (int i = 0; i < row.length; i++)
+ row[i] = types[i].bytesGen().generate(rnd);
+ return row;
+ };
+ }
+
+ private AbstractTypeGenerators.TypeSupport<?>[] typeSupport()
+ {
+ AbstractTypeGenerators.TypeSupport<?>[] types = new AbstractTypeGenerators.TypeSupport[metadata.columns().size()];
+ Iterator<ColumnMetadata> it = metadata.allColumnsInSelectOrder();
+ int partitionColumns = metadata.partitionKeyColumns().size();
+ int clusteringColumns = metadata.clusteringColumns().size();
+ int primaryKeyColumns = partitionColumns + clusteringColumns;
+ for (int i = 0; it.hasNext(); i++)
+ {
+ ColumnMetadata col = it.next();
+ types[i] = AbstractTypeGenerators.getTypeSupportWithNulls(col.type, i < partitionColumns ? null : valueDomainGen);
+ if (i < partitionColumns)
+ types[i] = types[i].withoutEmptyData();
+ if (i >= partitionColumns && i < primaryKeyColumns)
+ // clustering doesn't allow null...
+ types[i] = types[i].mapBytes(b -> b == null ? ByteBufferUtil.EMPTY_BYTE_BUFFER : b);
+ }
+ return types;
+ }
+ }
}
diff --git a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java b/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
index b4e037ef3a..2a31c135cf 100644
--- a/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
+++ b/test/unit/org/apache/cassandra/utils/CassandraGeneratorsTest.java
@@ -18,9 +18,20 @@
package org.apache.cassandra.utils;
+import java.util.Arrays;
+import java.util.List;
+
import org.junit.Test;
import accord.utils.Gens;
+import accord.utils.LazyToString;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.CounterColumnType;
+import org.apache.cassandra.db.marshal.DecimalType;
+import org.apache.cassandra.db.marshal.DurationType;
+import org.apache.cassandra.db.marshal.EmptyType;
+import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.utils.CassandraGenerators.TableMetadataBuilder;
import org.assertj.core.api.Assertions;
import static accord.utils.Property.qt;
@@ -28,6 +39,11 @@ import static org.apache.cassandra.utils.Generators.toGen;
public class CassandraGeneratorsTest
{
+ private static final List<AbstractType<?>> NOT_ALLOWED_IN_PRIMARY_KEY = Arrays.asList(EmptyType.instance,
+ DurationType.instance,
+ DecimalType.instance,
+ CounterColumnType.instance);
+
@Test
public void partitionerToToken()
{
@@ -41,4 +57,20 @@ public class CassandraGeneratorsTest
qt().forAll(Gens.random(), toGen(CassandraGenerators.partitioners()))
.check((rs, p) -> Assertions.assertThat(toGen(CassandraGenerators.decoratedKeys(i -> p)).next(rs)).isNotNull());
}
+
+ @Test
+ public void primaryKeysNoUnsafeTypes()
+ {
+ qt().forAll(toGen(new TableMetadataBuilder().build())).check(table -> {
+ for (ColumnMetadata pk : table.primaryKeyColumns())
+ {
+ for (AbstractType<?> t : NOT_ALLOWED_IN_PRIMARY_KEY)
+ {
+ Assertions.assertThat(AbstractTypeGenerators.contains(pk.type, t))
+ .describedAs("Expected type %s not to be found in %s", t.asCQL3Type(), new LazyToString(() -> AbstractTypeGenerators.typeTree(pk.type)))
+ .isFalse();
+ }
+ }
+ });
+ }
}
\ No newline at end of file
diff --git a/test/unit/org/apache/cassandra/utils/Generators.java b/test/unit/org/apache/cassandra/utils/Generators.java
index 4135bab4d7..cac1248c86 100644
--- a/test/unit/org/apache/cassandra/utils/Generators.java
+++ b/test/unit/org/apache/cassandra/utils/Generators.java
@@ -39,6 +39,7 @@ import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.apache.cassandra.cql3.ReservedKeywords;
import org.quicktheories.core.Gen;
import org.quicktheories.core.RandomnessSource;
import org.quicktheories.generators.SourceDSL;
@@ -80,6 +81,7 @@ public final class Generators
// see CASSANDRA-17919
return !("P".equals(value) || "PT".equals(value));
}
+ public static final Gen<String> SYMBOL_NOT_RESERVED_KEYWORD_GEN = Generators.filter(SYMBOL_GEN, s -> !ReservedKeywords.isReserved(s));
public static Gen<String> symbolGen(Gen<Integer> size)
{
diff --git a/test/unit/org/apache/cassandra/utils/SimulatedMiniCluster.java b/test/unit/org/apache/cassandra/utils/SimulatedMiniCluster.java
new file mode 100644
index 0000000000..279059b476
--- /dev/null
+++ b/test/unit/org/apache/cassandra/utils/SimulatedMiniCluster.java
@@ -0,0 +1,619 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils;
+
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Random;
+import java.util.TreeSet;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+
+import com.google.common.collect.Iterables;
+
+import accord.utils.Gen;
+import accord.utils.Gens;
+import accord.utils.Invariants;
+import accord.utils.RandomSource;
+import org.apache.cassandra.concurrent.ExecutorFactory;
+import org.apache.cassandra.concurrent.ScheduledExecutorPlus;
+import org.apache.cassandra.concurrent.SequentialExecutorPlus;
+import org.apache.cassandra.concurrent.SimulatedExecutorFactory;
+import org.apache.cassandra.concurrent.Stage;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.compaction.ICompactionManager;
+import org.apache.cassandra.db.repair.CassandraTableRepairManager;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.gms.ApplicationState;
+import org.apache.cassandra.gms.EndpointState;
+import org.apache.cassandra.gms.HeartBeatState;
+import org.apache.cassandra.gms.IEndpointStateChangeSubscriber;
+import org.apache.cassandra.gms.IFailureDetector;
+import org.apache.cassandra.gms.IGossiper;
+import org.apache.cassandra.gms.VersionedValue;
+import org.apache.cassandra.locator.IEndpointSnitch;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.IVerbHandler;
+import org.apache.cassandra.net.MessageDelivery;
+import org.apache.cassandra.net.SimulatedMessageDelivery;
+import org.apache.cassandra.net.SimulatedMessageDelivery.ActionSupplier;
+import org.apache.cassandra.repair.IValidationManager;
+import org.apache.cassandra.repair.SharedContext;
+import org.apache.cassandra.repair.StreamExecutor;
+import org.apache.cassandra.repair.TableRepairManager;
+import org.apache.cassandra.repair.ValidationManager;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.service.paxos.cleanup.PaxosRepairState;
+import org.apache.cassandra.streaming.StreamEventHandler;
+import org.apache.cassandra.streaming.StreamState;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tcm.ClusterMetadataService;
+import org.apache.cassandra.tcm.MultiStepOperation;
+import org.apache.cassandra.tcm.StubClusterMetadataService;
+import org.apache.cassandra.tcm.Transformation;
+import org.apache.cassandra.tcm.membership.Directory;
+import org.apache.cassandra.tcm.membership.Location;
+import org.apache.cassandra.tcm.membership.NodeAddresses;
+import org.apache.cassandra.tcm.membership.NodeId;
+import org.apache.cassandra.tcm.ownership.UniformRangePlacement;
+import org.apache.cassandra.tcm.transformations.PrepareJoin;
+import org.mockito.Mockito;
+
+import static org.apache.cassandra.utils.AccordGenerators.fromQT;
+
+public class SimulatedMiniCluster
+{
+ private final RandomSource rs;
+ private final Function<Node, IVerbHandler<?>> verbHandlerFactory;
+ private final SimulatedExecutorFactory executorFactory;
+ private final SequentialExecutorPlus orderedExecutor;
+ private final ScheduledExecutorPlus unorderedScheduled;
+ private final IFailureDetector failureDetector = Mockito.mock(IFailureDetector.class);
+ private final IEndpointSnitch snitch = Mockito.mock(IEndpointSnitch.class);
+ private final MBeanWrapper mbean = Mockito.mock(MBeanWrapper.class);
+ private final SimulatedGossip gossiper = new SimulatedGossip();
+ private final List<Throwable> failures = new ArrayList<>();
+ private final IPartitioner partitioner;
+ private final Map<String, List<String>> dcsToRacks;
+ private final List<String> dcs;
+ private final int tokensPerInstance;
+ private final Gen<Token> tokenGen;
+ private ClusterMetadata current;
+ private final Map<NodeId, Node> nodes = new LinkedHashMap<>();
+ private final TreeSet<Token> knownTokens = new TreeSet<>(); // includes bootstraping nodes tokens (aka tokens not in the ring)
+
+ private SimulatedMiniCluster(Builder builder)
+ {
+ this.rs = builder.rs;
+ this.verbHandlerFactory = builder.verbHandlerFactory;
+ this.executorFactory = new SimulatedExecutorFactory(rs, failures::add);
+ this.orderedExecutor = executorFactory.configureSequential("ignore").build();
+ this.unorderedScheduled = executorFactory.scheduled("ignored");
+ this.partitioner = fromQT(CassandraGenerators.nonLocalPartitioners()).next(rs);
+ this.dcsToRacks = createDcRackDetails(rs);
+ this.dcs = new ArrayList<>(dcsToRacks.keySet());
+ dcs.sort(Comparator.naturalOrder());
+ this.tokensPerInstance = rs.nextBoolean() ? 1 : 4;
+ this.tokenGen = fromQT(CassandraGenerators.token(partitioner)).filter(t -> !knownTokens.contains(t));
+ // setup Directory with known dcs
+ this.current = new ClusterMetadata(partitioner);
+ ClusterMetadataService.unsetInstance();
+ ClusterMetadataService.setInstance(StubClusterMetadataService.forTesting(current));
+ }
+
+ public Node node(int id)
+ {
+ return node(new NodeId(id));
+ }
+
+ public Node node(NodeId id)
+ {
+ Node node = nodes.get(id);
+ if (node == null)
+ throw new AssertionError("Unable to find node for id " + id);
+ return node;
+ }
+
+ public Node node(InetAddressAndPort address)
+ {
+ //TODO (performance): don't walk, keep index?
+ for (Node node : nodes.values())
+ {
+ if (node.broadcastAddressAndPort.equals(address))
+ return node;
+ }
+ throw new AssertionError("Unable to find node for address " + address);
+ }
+
+ private Collection<Token> nextUnknownTokens()
+ {
+ if (tokensPerInstance == 1) return Collections.singleton(tokenGen.next(rs));
+ return Gens.lists(tokenGen).unique().ofSize(tokensPerInstance).next(rs);
+ }
+
+ public Node createNode()
+ {
+ if (nodes.isEmpty())
+ return createFirstNode();
+
+ NodeId id = new NodeId(nodes.size() + 1);
+ UUID hostId = id.toUUID();
+ Collection<Token> tokens = nextUnknownTokens();
+ String dc = rs.pick(dcs);
+ String rack = rs.pick(dcsToRacks.get(dc));
+ Node node = new Node(id, hostId, address(id), tokens, dc, rack);
+ register(node);
+ return node;
+ }
+
+ public Node createNodeAndJoin()
+ {
+ if (nodes.isEmpty())
+ return createFirstNode();
+
+ NodeId id = new NodeId(nodes.size() + 1);
+ UUID hostId = id.toUUID();
+ Collection<Token> tokens = nextUnknownTokens();
+ String dc = rs.pick(dcs);
+ String rack = rs.pick(dcsToRacks.get(dc));
+ Node node = new Node(id, hostId, address(id), tokens, dc, rack);
+ registerAndJoin(node);
+ return node;
+ }
+
+ private Node createFirstNode()
+ {
+ NodeId id = new NodeId(nodes.size() + 1);
+ UUID hostId = id.toUUID();
+ Collection<Token> tokens = nextUnknownTokens();
+ String dc = dcs.get(0);
+ String rack = dcsToRacks.get(dc).get(0);
+ Node node = new Node(id, hostId, address(id), tokens, dc, rack);
+ registerAndJoin(node);
+ return node;
+ }
+
+ private void registerAndJoin(Node node)
+ {
+ register(node);
+ prepareJoin(node.id);
+ while (!current.inProgressSequences.isEmpty())
+ bumpInProgress();
+ }
+
+ private void register(Node node)
+ {
+ nodes.put(node.id, node);
+ knownTokens.addAll(node.tokens);
+ registerWithSnitch(node);
+ registerWithGossip(node);
+ registerWithCMS(node);
+ }
+
+ private void registerWithCMS(Node node)
+ {
+ if (node.id.id() == 1)
+ {
+ // rebuild metadata from scratch
+ Directory directory = Directory.EMPTY.with(new NodeAddresses(node.hostId, node.broadcastAddressAndPort, node.broadcastAddressAndPort, node.broadcastAddressAndPort), new Location(node.dc, node.rack));
+ notifyMetadataChange(new ClusterMetadata(partitioner, directory));
+ }
+ else
+ {
+ notifyMetadataChange(current.forceEpoch(current.epoch.nextEpoch())
+ .withDirectory(current.directory.with(new NodeAddresses(node.hostId, node.broadcastAddressAndPort, node.broadcastAddressAndPort, node.broadcastAddressAndPort),
+ new Location(node.dc, node.rack))));
+ }
+ }
+
+ private void prepareJoin(NodeId id)
+ {
+ Node node = nodes.get(id);
+ if (node == null)
+ throw new IllegalArgumentException("Unknown " + id);
+ PrepareJoin task = new PrepareJoin(id, new HashSet<>(node.tokens), new UniformRangePlacement(), true, false);
+ notifyMetadataChange(process(task).metadata);
+ }
+
+ private void bumpInProgress()
+ {
+ if (current.inProgressSequences.isEmpty())
+ throw new IllegalStateException("Attempted to bump epoch when nothing was pending");
+ Iterator<MultiStepOperation<?>> it = current.inProgressSequences.iterator();
+ Invariants.checkState(it.hasNext());
+ notifyMetadataChange(process(it.next()).metadata);
+ }
+
+ protected void notifyMetadataChange(ClusterMetadata current)
+ {
+ this.current = current;
+ ((StubClusterMetadataService) ClusterMetadataService.instance()).setMetadata(current);
+ }
+
+ private Transformation.Success process(Transformation transformation)
+ {
+ Transformation.Result result = transformation.execute(current);
+ if (result.isRejected())
+ throw new IllegalStateException("Unable to make TCM transition");
+ return result.success();
+ }
+
+ private Transformation.Success process(MultiStepOperation<?> transformation)
+ {
+ Transformation.Result result = transformation.applyTo(current);
+ if (result.isRejected())
+ throw new IllegalStateException("Unable to make TCM transition");
+ return result.success();
+ }
+
+ private static InetAddressAndPort address(NodeId id)
+ {
+ try
+ {
+ return InetAddressAndPort.getByAddress(ByteArrayUtil.bytes(id.id()));
+ }
+ catch (UnknownHostException e)
+ {
+ throw new AssertionError("Unable to create address for id " + id, e);
+ }
+ }
+
+ private static Map<String, List<String>> createDcRackDetails(RandomSource rs)
+ {
+ int numDCs = rs.nextInt(1, 4);
+ Map<String, List<String>> map = new LinkedHashMap<>();
+ for (int i = 0; i < numDCs; i++)
+ {
+ String name = "DC" + (i + 1);
+ int numRacks = rs.nextInt(1, 10);
+ List<String> racks = Gens.lists(Gens.strings().ascii().ofLength(5).map(s -> "R" + s)).unique().ofSize(numRacks).next(rs);
+ racks.sort(Comparator.naturalOrder());
+ map.put(name, racks);
+ }
+ return map;
+ }
+
+ public boolean hasWork()
+ {
+ return executorFactory.hasWork();
+ }
+
+ public boolean processAny()
+ {
+ return executorFactory.processAny();
+ }
+
+ public boolean processOne()
+ {
+ return executorFactory.processOne();
+ }
+
+ public void processAll()
+ {
+ executorFactory.processAll();;
+ }
+
+ public void simulateStages(Stage... stages)
+ {
+ for (Stage stage : stages)
+ {
+ switch (stage)
+ {
+ case GOSSIP:
+ case ANTI_ENTROPY:
+ case MIGRATION:
+ case MISC:
+ case TRACING:
+ case FETCH_LOG:
+ stage.unsafeSetExecutor(orderedExecutor);
+ break;
+ default:
+ stage.unsafeSetExecutor(unorderedScheduled);
+ }
+ }
+ }
+
+ private void registerWithSnitch(Node node)
+ {
+ Mockito.when(snitch.getDatacenter(Mockito.eq(node.broadcastAddressAndPort))).thenReturn(node.dc);
+ Mockito.when(snitch.getRack(Mockito.eq(node.broadcastAddressAndPort))).thenReturn(node.rack);
+ }
+
+ private void registerWithGossip(Node node)
+ {
+ VersionedValue.VersionedValueFactory valueFactory = node.valueFactory;
+ EndpointState state = new EndpointState(new HeartBeatState(42, 42));
+ state.addApplicationState(ApplicationState.STATUS, valueFactory.normal(node.tokens));
+ state.addApplicationState(ApplicationState.STATUS_WITH_PORT, valueFactory.normal(node.tokens));
+ state.addApplicationState(ApplicationState.HOST_ID, valueFactory.hostId(node.hostId));
+ state.addApplicationState(ApplicationState.TOKENS, valueFactory.tokens(node.tokens));
+ state.addApplicationState(ApplicationState.DC, valueFactory.datacenter(node.dc));
+ state.addApplicationState(ApplicationState.RACK, valueFactory.rack(node.rack));
+ state.addApplicationState(ApplicationState.RELEASE_VERSION, valueFactory.releaseVersion());
+
+ gossiper.endpoints.put(node.broadcastAddressAndPort, state);
+ }
+
+ public static class Builder
+ {
+ private final RandomSource rs;
+ private final Function<Node, IVerbHandler<?>> verbHandlerFactory;
+
+ public Builder(RandomSource rs, Function<Node, IVerbHandler<?>> verbHandlerFactory)
+ {
+ this.rs = rs;
+ this.verbHandlerFactory = verbHandlerFactory;
+ }
+
+ public SimulatedMiniCluster build()
+ {
+ return new SimulatedMiniCluster(this);
+ }
+ }
+
+ private enum NodeStatus { Init, Registered, Joining, Joined, Leaving, Removed}
+
+ public class Node implements SharedContext
+ {
+ private final ICompactionManager compactionManager = Mockito.mock(ICompactionManager.class);
+ private final NodeId id;
+ private final UUID hostId;
+ private final InetAddressAndPort broadcastAddressAndPort;
+ private final Collection<Token> tokens;
+ private final String dc, rack;
+ private final VersionedValue.VersionedValueFactory valueFactory;
+ private final SimulatedMessageDelivery messaging;
+ private final SimulatedMessageDelivery.SimulatedMessageReceiver receiver;
+ private final ActiveRepairService activeRepairService;
+ private final PaxosRepairState paxosRepairState;
+ private final IValidationManager validationManager;
+ private final StreamExecutor streamExecutor;
+ private NodeStatus status = NodeStatus.Init;
+ private ActionSupplier messagingActions = (self, msg, to) -> SimulatedMessageDelivery.Action.DELIVER;
+
+ public Node(NodeId id, UUID hostId, InetAddressAndPort broadcastAddressAndPort, Collection<Token> tokens, String dc, String rack)
+ {
+ this.id = id;
+ this.hostId = hostId;
+ this.broadcastAddressAndPort = broadcastAddressAndPort;
+ this.tokens = tokens;
+ this.dc = dc;
+ this.rack = rack;
+
+ IPartitioner partitioner = Iterables.getFirst(tokens, null).getPartitioner();
+ this.valueFactory = new VersionedValue.VersionedValueFactory(partitioner);
+ this.messaging = new SimulatedMessageDelivery(broadcastAddressAndPort,
+ messagingActions::get,
+ SimulatedMessageDelivery.randomDelay(rs),
+ (to, msg) -> unorderedScheduled.submit(() -> node(to).receiver.recieve(msg)),
+ (action, to, msg) -> {},
+ unorderedScheduled::schedule,
+ failures::add);
+ this.activeRepairService = new ActiveRepairService(this);
+ this.paxosRepairState = new PaxosRepairState(this);
+ this.validationManager = (cfs, validator) -> unorderedScheduled.submit(() -> {
+ try
+ {
+ ValidationManager.doValidation(cfs, validator);
+ }
+ catch (Throwable e)
+ {
+ validator.fail(e);
+ }
+ });
+ this.streamExecutor = plan -> {
+ long delayNanos = rs.nextLong(TimeUnit.SECONDS.toNanos(5), TimeUnit.MINUTES.toNanos(10));
+ unorderedScheduled.schedule(() -> {
+ StreamState success = new StreamState(plan.planId(), plan.streamOperation(), Collections.emptySet());
+ for (StreamEventHandler handler : plan.handlers())
+ handler.onSuccess(success);
+ }, delayNanos, TimeUnit.NANOSECONDS);
+ return null;
+ };
+
+ // setup last as "this" is leaking, so make sure all final fields are defined first
+ this.receiver = messaging.receiver(verbHandlerFactory.apply(this));
+ }
+
+ public NodeId id()
+ {
+ return id;
+ }
+
+ public UUID hostId()
+ {
+ return hostId;
+ }
+
+ public void messagingActions(ActionSupplier messagingActions)
+ {
+ this.messagingActions = Objects.requireNonNull(messagingActions);
+ }
+
+ @Override
+ public InetAddressAndPort broadcastAddressAndPort()
+ {
+ return broadcastAddressAndPort;
+ }
+
+ @Override
+ public Supplier<Random> random()
+ {
+ return () -> rs.fork().asJdkRandom();
+ }
+
+ @Override
+ public Clock clock()
+ {
+ return executorFactory;
+ }
+
+ @Override
+ public ExecutorFactory executorFactory()
+ {
+ return executorFactory;
+ }
+
+ @Override
+ public MBeanWrapper mbean()
+ {
+ return mbean;
+ }
+
+ @Override
+ public ScheduledExecutorPlus optionalTasks()
+ {
+ return unorderedScheduled;
+ }
+
+ @Override
+ public ScheduledExecutorPlus nonPeriodicTasks()
+ {
+ return unorderedScheduled;
+ }
+
+ @Override
+ public ScheduledExecutorPlus scheduledTasks()
+ {
+ return unorderedScheduled;
+ }
+
+
+ @Override
+ public IFailureDetector failureDetector()
+ {
+ return failureDetector;
+ }
+
+ @Override
+ public IEndpointSnitch snitch()
+ {
+ return snitch;
+ }
+
+ @Override
+ public IGossiper gossiper()
+ {
+ return gossiper;
+ }
+
+ @Override
+ public MessageDelivery messaging()
+ {
+ return messaging;
+ }
+
+ @Override
+ public ActiveRepairService repair()
+ {
+ return activeRepairService;
+ }
+
+ @Override
+ public PaxosRepairState paxosRepairState()
+ {
+ return paxosRepairState;
+ }
+
+ @Override
+ public ICompactionManager compactionManager()
+ {
+ return compactionManager;
+ }
+
+ @Override
+ public IValidationManager validationManager()
+ {
+ return validationManager;
+ }
+
+ @Override
+ public TableRepairManager repairManager(ColumnFamilyStore store)
+ {
+ return new CassandraTableRepairManager(store, this)
+ {
+ @Override
+ public void snapshot(String name, Collection<Range<Token>> ranges, boolean force)
+ {
+ // no-op
+ }
+ };
+ }
+
+ @Override
+ public StreamExecutor streamExecutor()
+ {
+ return streamExecutor;
+ }
+ }
+
+ private class SimulatedGossip implements IGossiper
+ {
+ private final Map<InetAddressAndPort, EndpointState> endpoints = new HashMap<>();
+
+ @Override
+ public void register(IEndpointStateChangeSubscriber subscriber)
+ {
+
+ }
... 30 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org