You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by "bdeggleston (via GitHub)" <gi...@apache.org> on 2024/07/22 17:35:05 UTC
Re: [PR] CASSANDRA-19744 Accord migration and interop correctness [cassandra]
bdeggleston commented on code in PR #3395:
URL: https://github.com/apache/cassandra/pull/3395#discussion_r1680152067
##########
src/java/org/apache/cassandra/db/CassandraKeyspaceWriteHandler.java:
##########
@@ -89,7 +89,7 @@ private CommitLogPosition addToCommitLog(Mutation mutation)
if (update.metadata().params.memtable.factory().writesShouldSkipCommitLog())
ids.add(update.metadata().id);
}
- mutation = mutation.without(ids);
+ mutation = mutation.filter(ids::contains);
Review Comment:
This doesn't seem right. If I'm reading this right then when we encounter mixed `writesShouldSkipCommitLog` mutations we'll _only_ write commit log entries for tables which aren't supposed to be written to the commit log?
##########
src/java/org/apache/cassandra/service/accord/api/AccordAgent.java:
##########
@@ -122,7 +122,7 @@ public long preAcceptTimeout()
@Override
public Txn emptyTxn(Kind kind, Seekables<?, ?> seekables)
{
- return new Txn.InMemory(kind, seekables, TxnRead.EMPTY, TxnQuery.EMPTY, null);
+ return new Txn.InMemory(kind, seekables, TxnRead.EMPTY, TxnQuery.UNSAFE_EMPTY, null);
Review Comment:
could we rename this method to `emptySystemTxn` or `emptyUnsafeTxn` or something so people know that it doesn't offer all the normal guardrails
##########
src/java/org/apache/cassandra/batchlog/BatchlogManager.java:
##########
@@ -340,66 +391,116 @@ private static class ReplayingBatch
{
private final TimeUUID id;
private final long writtenAt;
- private final List<Mutation> mutations;
+ private final int unsplitGcGs;
+ private final List<Mutation> normalMutations;
+ private final List<Mutation> accordMutations;
private final int replayedBytes;
- private List<ReplayWriteResponseHandler<Mutation>> replayHandlers;
+ private List<ReplayWriteResponseHandler<Mutation>> replayHandlers = ImmutableList.of();
+ private Pair<TxnId, Future<TxnResult>> accordResult;
+ private long accordTxnStartNanos;
ReplayingBatch(TimeUUID id, int version, List<ByteBuffer> serializedMutations) throws IOException
{
this.id = id;
this.writtenAt = id.unix(MILLISECONDS);
- this.mutations = new ArrayList<>(serializedMutations.size());
- this.replayedBytes = addMutations(version, serializedMutations);
+ List<Mutation> unsplitMutations = new ArrayList<>(serializedMutations.size());
+ this.replayedBytes = addMutations(unsplitMutations, version, serializedMutations);
+ unsplitGcGs = gcgs(unsplitMutations);
+ Pair<List<Mutation>, List<Mutation>> accordAndNormal = ConsensusMigrationMutationHelper.splitMutationsIntoAccordAndNormal(unsplitMutations);
+ logger.trace("Replaying batch with Accord {} and normal {}", accordAndNormal.left, accordAndNormal.right);
+ normalMutations = accordAndNormal.right;
+ accordMutations = accordAndNormal.left;
}
- public int replay(RateLimiter rateLimiter, Set<UUID> hintedNodes) throws IOException
+ public boolean replay(RateLimiter rateLimiter, Set<UUID> hintedNodes) throws IOException
{
logger.trace("Replaying batch {}", id);
- if (mutations.isEmpty())
- return 0;
+ if ((normalMutations == null || normalMutations.isEmpty()) && (accordMutations == null || accordMutations.isEmpty()))
+ return false;
- int gcgs = gcgs(mutations);
- if (MILLISECONDS.toSeconds(writtenAt) + gcgs <= FBUtilities.nowInSeconds())
- return 0;
+ if (MILLISECONDS.toSeconds(writtenAt) + unsplitGcGs <= FBUtilities.nowInSeconds())
+ return false;
+
+ // TODO (expected): this can refuse to initiate if Accord loses the ranges that it had when splitting making the batch fail to apply
+ if (accordMutations != null)
+ {
+ accordTxnStartNanos = Clock.Global.nanoTime();
+ accordResult = accordMutations != null ? mutateWithAccordAsync(accordMutations, null, accordTxnStartNanos) : null;
+ }
- replayHandlers = sendReplays(mutations, writtenAt, hintedNodes);
+ if (normalMutations != null)
+ replayHandlers = sendReplays(normalMutations, writtenAt, hintedNodes);
rateLimiter.acquire(replayedBytes); // acquire afterwards, to not mess up ttl calculation.
- return replayHandlers.size();
+ return replayHandlers.size() > 0 || accordMutations != null;
}
public void finish(Set<UUID> hintedNodes)
{
- for (int i = 0; i < replayHandlers.size(); i++)
+ Throwable failure = null;
+ // Check if the Accord mutations succeeded asynchronously
+ try
{
- ReplayWriteResponseHandler<Mutation> handler = replayHandlers.get(i);
- try
+ if (accordResult != null)
{
- handler.get();
+ IAccordService accord = AccordService.instance();
+ TxnResult.Kind kind = accord.getTxnResult(accordResult, true, ConsistencyLevel.QUORUM, accordTxnStartNanos).kind();
+ if (kind == retry_new_protocol)
+ throw new RetryOnDifferentSystemException();
}
- catch (WriteTimeoutException|WriteFailureException e)
+ }
+ catch (WriteTimeoutException|WriteFailureException|RetryOnDifferentSystemException e)
+ {
+ logger.trace("Failed replaying a batched mutation on Accord, will write a hint");
+ logger.trace("Failure was : {}", e.getMessage());
+ writeHintsForUndeliveredAccordTxns(hintedNodes);
+ }
+ catch (Exception e)
+ {
+ failure = Throwables.merge(failure, e);
+ }
+
+ try
+ {
+ for (int i = 0; i < replayHandlers.size(); i++)
{
- logger.trace("Failed replaying a batched mutation to a node, will write a hint");
- logger.trace("Failure was : {}", e.getMessage());
- // writing hints for the rest to hints, starting from i
- writeHintsForUndeliveredEndpoints(i, hintedNodes);
- return;
+ ReplayWriteResponseHandler<Mutation> handler = replayHandlers.get(i);
+ try
+ {
+ handler.get();
+ }
+ catch (WriteTimeoutException|WriteFailureException|RetryOnDifferentSystemException e)
+ {
+ logger.trace("Failed replaying a batched mutation to a node, will write a hint");
+ logger.trace("Failure was : {}", e.getMessage());
+ // writing hints for the rest to hints, starting from i
+ writeHintsForUndeliveredEndpoints(i, hintedNodes);
+ break;
+ }
}
}
+ catch (Exception e)
+ {
+ logger.debug("Unexpected batchlog replay exception", e);
+ failure = Throwables.merge(failure, e);
+ }
+
+ if (failure != null)
+ throw Throwables.unchecked(failure);
}
- private int addMutations(int version, List<ByteBuffer> serializedMutations) throws IOException
+ private int addMutations(List<Mutation> unsplitMutations, int version, List<ByteBuffer> serializedMutations) throws IOException
Review Comment:
this (and `addMutation`) can be made static if you pass `writtenAt` in
##########
test/unit/org/apache/cassandra/cql3/PagingTest.java:
##########
@@ -140,7 +140,7 @@ public boolean isWorthMergingForRangeQuery(ReplicaCollection merged, ReplicaColl
}
Thread.sleep(1500);
- Statement stmt = new SimpleStatement(String.format("SELECT DISTINCT token(id, id2), id, id2 FROM %s", table));
+ Statement stmt = new SimpleStatement(String.format("SELECT DISTINCT token(id, id2), id, id2 FROM %s WHERE token(id, id2) >= -9223372036854775808", table));
Review Comment:
what's up with the token bit you added here?
##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusMigrationMutationHelper.java:
##########
@@ -0,0 +1,399 @@
+/*
+ * 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.consensus.migration;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import com.google.common.collect.ImmutableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.primitives.Keys;
+import accord.primitives.Txn;
+import accord.primitives.TxnId;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.ConsistencyLevel;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.IMutation;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.CoordinatorBehindException;
+import org.apache.cassandra.exceptions.RetryOnDifferentSystemException;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.StorageProxy.WriteResponseHandlerWrapper;
+import org.apache.cassandra.service.accord.AccordService;
+import org.apache.cassandra.service.accord.IAccordService;
+import org.apache.cassandra.service.accord.api.PartitionKey;
+import org.apache.cassandra.service.accord.txn.TxnCondition;
+import org.apache.cassandra.service.accord.txn.TxnQuery;
+import org.apache.cassandra.service.accord.txn.TxnRead;
+import org.apache.cassandra.service.accord.txn.TxnReferenceOperations;
+import org.apache.cassandra.service.accord.txn.TxnResult;
+import org.apache.cassandra.service.accord.txn.TxnUpdate;
+import org.apache.cassandra.service.accord.txn.TxnWrite;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tracing.Tracing;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.function.Predicate.not;
+import static org.apache.cassandra.dht.Range.isInNormalizedRanges;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetrics;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetricsForLevel;
+import static org.apache.cassandra.service.StorageProxy.mutate;
+import static org.apache.cassandra.service.accord.txn.TxnResult.Kind.retry_new_protocol;
+import static org.apache.cassandra.service.consensus.migration.ConsensusRequestRouter.getTableMetadata;
+import static org.apache.cassandra.utils.Throwables.unchecked;
+
+/**
+ * Applying mutations can fail with RetryOnDifferentSystemException if a
+ * mutation conflicts with a table and range that needs to be managed
+ * transactionally. This impacts mutations, logged/unlogged batches, hints,and blocking read repair.
+ *
+ * This class contains the logic needed for managing these retry loops and splitting the mutations up
+ */
+public class ConsensusMigrationMutationHelper
+{
+ private static final Logger logger = LoggerFactory.getLogger(ConsensusMigrationMutationHelper.class);
+
+ private static ConsistencyLevel consistencyLevelForCommit(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel)
+ {
+ // Null means no specific consistency behavior is required from Accord, it's functionally similar to ANY
+ // if you aren't reading the result back via Accord
+ if (consistencyLevel == null)
+ return null;
+
+ for (IMutation mutation : mutations)
+ {
+ for (TableId tableId : mutation.getTableIds())
+ {
+ TransactionalMode mode = Schema.instance.getTableMetadata(tableId).params.transactionalMode;
+ // commitCLForStrategy should return either null or the supplied consistency level
+ // in which case we will commit everything at that CL since Accord doesn't support per table
+ // commit consistency
+ ConsistencyLevel commitCL = mode.commitCLForStrategy(consistencyLevel);
+ if (commitCL != null)
+ return commitCL;
+ }
+ }
+ return null;
+ }
+
+ public static <T extends IMutation> Pair<List<T>, List<T>> splitMutationsIntoAccordAndNormal(List<T> mutations)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<T> accordMutations = null;
+ List<T> normalMutations = null;
+ for (int i=0,mi=mutations.size(); i<mi; i++)
+ {
+ T mutation = mutations.get(i);
+ Pair<T, T> accordAndNormalMutation = splitMutationIntoAccordAndNormal(mutation, cm);
+ T accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(mutations.size(), 10));
Review Comment:
why are you allocating a minimum of 10 entries here? Was this meant to be max?
##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusMigrationMutationHelper.java:
##########
@@ -0,0 +1,399 @@
+/*
+ * 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.consensus.migration;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import com.google.common.collect.ImmutableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.primitives.Keys;
+import accord.primitives.Txn;
+import accord.primitives.TxnId;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.ConsistencyLevel;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.IMutation;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.CoordinatorBehindException;
+import org.apache.cassandra.exceptions.RetryOnDifferentSystemException;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.StorageProxy.WriteResponseHandlerWrapper;
+import org.apache.cassandra.service.accord.AccordService;
+import org.apache.cassandra.service.accord.IAccordService;
+import org.apache.cassandra.service.accord.api.PartitionKey;
+import org.apache.cassandra.service.accord.txn.TxnCondition;
+import org.apache.cassandra.service.accord.txn.TxnQuery;
+import org.apache.cassandra.service.accord.txn.TxnRead;
+import org.apache.cassandra.service.accord.txn.TxnReferenceOperations;
+import org.apache.cassandra.service.accord.txn.TxnResult;
+import org.apache.cassandra.service.accord.txn.TxnUpdate;
+import org.apache.cassandra.service.accord.txn.TxnWrite;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tracing.Tracing;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.function.Predicate.not;
+import static org.apache.cassandra.dht.Range.isInNormalizedRanges;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetrics;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetricsForLevel;
+import static org.apache.cassandra.service.StorageProxy.mutate;
+import static org.apache.cassandra.service.accord.txn.TxnResult.Kind.retry_new_protocol;
+import static org.apache.cassandra.service.consensus.migration.ConsensusRequestRouter.getTableMetadata;
+import static org.apache.cassandra.utils.Throwables.unchecked;
+
+/**
+ * Applying mutations can fail with RetryOnDifferentSystemException if a
+ * mutation conflicts with a table and range that needs to be managed
+ * transactionally. This impacts mutations, logged/unlogged batches, hints,and blocking read repair.
+ *
+ * This class contains the logic needed for managing these retry loops and splitting the mutations up
+ */
+public class ConsensusMigrationMutationHelper
+{
+ private static final Logger logger = LoggerFactory.getLogger(ConsensusMigrationMutationHelper.class);
+
+ private static ConsistencyLevel consistencyLevelForCommit(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel)
+ {
+ // Null means no specific consistency behavior is required from Accord, it's functionally similar to ANY
+ // if you aren't reading the result back via Accord
+ if (consistencyLevel == null)
+ return null;
+
+ for (IMutation mutation : mutations)
+ {
+ for (TableId tableId : mutation.getTableIds())
+ {
+ TransactionalMode mode = Schema.instance.getTableMetadata(tableId).params.transactionalMode;
+ // commitCLForStrategy should return either null or the supplied consistency level
+ // in which case we will commit everything at that CL since Accord doesn't support per table
+ // commit consistency
+ ConsistencyLevel commitCL = mode.commitCLForStrategy(consistencyLevel);
+ if (commitCL != null)
+ return commitCL;
+ }
+ }
+ return null;
+ }
+
+ public static <T extends IMutation> Pair<List<T>, List<T>> splitMutationsIntoAccordAndNormal(List<T> mutations)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<T> accordMutations = null;
+ List<T> normalMutations = null;
+ for (int i=0,mi=mutations.size(); i<mi; i++)
+ {
+ T mutation = mutations.get(i);
+ Pair<T, T> accordAndNormalMutation = splitMutationIntoAccordAndNormal(mutation, cm);
+ T accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(mutations.size(), 10));
+ accordMutations.add(accordMutation);
+ }
+ T normalMutation = accordAndNormalMutation.right;
+ if (normalMutation != null)
+ {
+ if (normalMutations == null)
+ normalMutations = new ArrayList<>(Math.min(mutations.size(), 10));
+ normalMutations.add(normalMutation);
+ }
+ }
+ return Pair.create(accordMutations, normalMutations);
+ }
+
+ public static <T extends IMutation> Pair<T, T> splitMutationIntoAccordAndNormal(T mutation, ClusterMetadata cm)
+ {
+ if (mutation.allowPotentialTransactionConflicts())
+ return Pair.create(null, mutation);
+
+ Token token = mutation.key().getToken();
+ Predicate<TableId> isAccordUpdate = tableId -> {
+ TableMetadata tm = getTableMetadata(cm, tableId);
+ if (tm == null)
+ return false;
+ return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+ };
+
+ T accordMutation = (T)mutation.filter(isAccordUpdate);
+ T normalMutation = (T)mutation.filter(not(isAccordUpdate));
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ checkState((accordMutation == null ? false : accordMutation.hasUpdateForTable(pu.metadata().id))
+ || (normalMutation == null ? false : normalMutation.hasUpdateForTable(pu.metadata().id)),
+ "All partition updates should still be present after splitting");
+ return Pair.create(accordMutation, normalMutation);
+ }
+
+ public static Pair<List<? extends IMutation>, List<WriteResponseHandlerWrapper>> splitWrappersIntoAccordAndNormal(List<WriteResponseHandlerWrapper> wrappers)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<IMutation> accordMutations = null;
+ List<WriteResponseHandlerWrapper> normalWrappers = null;
+ for (int i=0,mi=wrappers.size(); i<mi; i++)
+ {
+ WriteResponseHandlerWrapper wrapper = wrappers.get(i);
+ Pair<IMutation, WriteResponseHandlerWrapper> accordAndNormalMutation = splitWrapperIntoAccordAndNormal(wrapper, cm);
+ IMutation accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(wrappers.size(), 10));
+ accordMutations.add(accordMutation);
+ }
+ WriteResponseHandlerWrapper normalWrapper = accordAndNormalMutation.right;
+ if (normalWrapper != null)
+ {
+ if (normalWrappers == null)
+ normalWrappers = new ArrayList<>(Math.min(wrappers.size(), 10));
+ normalWrappers.add(normalWrapper);
+ }
+ }
+ return Pair.create(accordMutations, normalWrappers);
+ }
+
+ private static Pair<IMutation, WriteResponseHandlerWrapper> splitWrapperIntoAccordAndNormal(WriteResponseHandlerWrapper wrapper, ClusterMetadata cm)
+ {
+ Mutation mutation = wrapper.mutation;
+ if (mutation.allowPotentialTransactionConflicts())
+ return Pair.create(null, wrapper);
+
+ Token token = mutation.key().getToken();
+ Predicate<TableId> isAccordUpdate = tableId -> {
+ TableMetadata tm = getTableMetadata(cm, tableId);
+ if (tm == null)
+ return false;
+ return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+ };
+
+ IMutation accordMutation = mutation.filter(isAccordUpdate);
+ Mutation normalMutation = mutation.filter(not(isAccordUpdate));
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ checkState((accordMutation == null ? false : accordMutation.hasUpdateForTable(pu.metadata().id))
+ || (normalMutation == null ? false : normalMutation.hasUpdateForTable(pu.metadata().id)),
+ "All partition updates should still be present after splitting");
+ if (accordMutation == null)
+ return Pair.create(null, wrapper);
+ if (normalMutation == null)
+ return Pair.create( accordMutation, null);
+ // Since this now depends on an Accord txn need to wait for that to complete first
+ wrapper.handler.deferCleanup();
+ return Pair.create(accordMutation, new WriteResponseHandlerWrapper(wrapper.handler, normalMutation));
+ }
+
+ public static Pair<TxnId, Future<TxnResult>> mutateWithAccordAsync(Mutation mutation, @Nullable ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ return mutateWithAccordAsync(ImmutableList.of(mutation), consistencyLevel, queryStartNanoTime);
+ }
+
+
+ public static Pair<TxnId, Future<TxnResult>> mutateWithAccordAsync(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ int fragmentIndex = 0;
+ List<TxnWrite.Fragment> fragments = new ArrayList<>(mutations.size());
+ List<PartitionKey> partitionKeys = new ArrayList<>(mutations.size());
+ for (IMutation mutation : mutations)
+ {
+ for (PartitionUpdate update : mutation.getPartitionUpdates())
+ {
+ PartitionKey pk = PartitionKey.of(update);
+ partitionKeys.add(pk);
+ fragments.add(new TxnWrite.Fragment(PartitionKey.of(update), fragmentIndex++, update, TxnReferenceOperations.empty()));
+ }
+ }
+ // Potentially ignore commit consistency level if the strategy specifies accord and not migration
+ ConsistencyLevel clForCommit = consistencyLevelForCommit(mutations, consistencyLevel);
+ TxnUpdate update = new TxnUpdate(fragments, TxnCondition.none(), clForCommit, true);
+ Txn.InMemory txn = new Txn.InMemory(Keys.of(partitionKeys), TxnRead.EMPTY, TxnQuery.NONE, update);
+ IAccordService accordService = AccordService.instance();
+ return accordService.coordinateAsync(txn, consistencyLevel, queryStartNanoTime);
+ }
+
+ public static void dispatchMutationsWithRetryOnDifferentSystem(List<? extends IMutation> mutations, ConsistencyLevel consistencyLevel, long queryStartNanoTime)
Review Comment:
can we move this to StorageProxy?
##########
src/java/org/apache/cassandra/hints/HintsDispatcher.java:
##########
@@ -138,8 +196,11 @@ private Action sendHintsAndAwait(HintsReader.Page page)
*
* If that is not the case, we'll need to perform conversion to a newer (or an older) format, and decoding the hint
* is an unavoidable intermediate step.
+ *
+ * If Accord is enabled or these hints are from the batchlog and were originally attempted on Accord then
+ * we also need to decode so we can route the Hint contents appropriately.
*/
- Action action = reader.descriptor().messagingVersion() == messagingVersion
+ Action action = reader.descriptor().messagingVersion() == messagingVersion && !DatabaseDescriptor.getAccordTransactionsEnabled() && !hostId.equals(RETRY_ON_DIFFERENT_SYSTEM_UUID)
Review Comment:
Always skipping the buffer sending path if accord is enabled seems excessive for what (I think) is a situation we'd only encounter while migrating. I think we could wait for the hint recipient to complain or make it possible to efficiently determine if a serialized hint belongs to a table that needs accord support
##########
src/java/org/apache/cassandra/service/consensus/TransactionalMode.java:
##########
@@ -112,6 +112,10 @@ public ConsistencyLevel commitCLForStrategy(ConsistencyLevel consistencyLevel)
return consistencyLevel;
}
+ // TODO (required): This won't work for migration directly from none to full because there is no safe system to read from
Review Comment:
What a migration from `none` to `full` effectively ran accord in `mixed_reads` mode during migration?
##########
src/java/org/apache/cassandra/service/AbstractWriteResponseHandler.java:
##########
@@ -294,8 +329,20 @@ public void onFailure(InetAddressAndPort from, RequestFailure failure)
if (blockFor() + n > candidateReplicaCount())
signal();
- if (hintOnFailure != null && StorageProxy.shouldHint(replicaPlan.lookup(from)))
- StorageProxy.submitHint(hintOnFailure.get(), replicaPlan.lookup(from), null);
+ // If the failure was RETRY_ON_DIFFERENT_TRANSACTION_SYSTEM then we only want to hint once
Review Comment:
wouldn't we want to retry with accord instead of writing a hint?
##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusMigrationMutationHelper.java:
##########
@@ -0,0 +1,399 @@
+/*
+ * 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.consensus.migration;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import com.google.common.collect.ImmutableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.primitives.Keys;
+import accord.primitives.Txn;
+import accord.primitives.TxnId;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.ConsistencyLevel;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.IMutation;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.CoordinatorBehindException;
+import org.apache.cassandra.exceptions.RetryOnDifferentSystemException;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.StorageProxy.WriteResponseHandlerWrapper;
+import org.apache.cassandra.service.accord.AccordService;
+import org.apache.cassandra.service.accord.IAccordService;
+import org.apache.cassandra.service.accord.api.PartitionKey;
+import org.apache.cassandra.service.accord.txn.TxnCondition;
+import org.apache.cassandra.service.accord.txn.TxnQuery;
+import org.apache.cassandra.service.accord.txn.TxnRead;
+import org.apache.cassandra.service.accord.txn.TxnReferenceOperations;
+import org.apache.cassandra.service.accord.txn.TxnResult;
+import org.apache.cassandra.service.accord.txn.TxnUpdate;
+import org.apache.cassandra.service.accord.txn.TxnWrite;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tracing.Tracing;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.function.Predicate.not;
+import static org.apache.cassandra.dht.Range.isInNormalizedRanges;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetrics;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetricsForLevel;
+import static org.apache.cassandra.service.StorageProxy.mutate;
+import static org.apache.cassandra.service.accord.txn.TxnResult.Kind.retry_new_protocol;
+import static org.apache.cassandra.service.consensus.migration.ConsensusRequestRouter.getTableMetadata;
+import static org.apache.cassandra.utils.Throwables.unchecked;
+
+/**
+ * Applying mutations can fail with RetryOnDifferentSystemException if a
+ * mutation conflicts with a table and range that needs to be managed
+ * transactionally. This impacts mutations, logged/unlogged batches, hints,and blocking read repair.
+ *
+ * This class contains the logic needed for managing these retry loops and splitting the mutations up
+ */
+public class ConsensusMigrationMutationHelper
+{
+ private static final Logger logger = LoggerFactory.getLogger(ConsensusMigrationMutationHelper.class);
+
+ private static ConsistencyLevel consistencyLevelForCommit(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel)
+ {
+ // Null means no specific consistency behavior is required from Accord, it's functionally similar to ANY
+ // if you aren't reading the result back via Accord
+ if (consistencyLevel == null)
+ return null;
+
+ for (IMutation mutation : mutations)
+ {
+ for (TableId tableId : mutation.getTableIds())
+ {
+ TransactionalMode mode = Schema.instance.getTableMetadata(tableId).params.transactionalMode;
+ // commitCLForStrategy should return either null or the supplied consistency level
+ // in which case we will commit everything at that CL since Accord doesn't support per table
+ // commit consistency
+ ConsistencyLevel commitCL = mode.commitCLForStrategy(consistencyLevel);
+ if (commitCL != null)
+ return commitCL;
+ }
+ }
+ return null;
+ }
+
+ public static <T extends IMutation> Pair<List<T>, List<T>> splitMutationsIntoAccordAndNormal(List<T> mutations)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<T> accordMutations = null;
+ List<T> normalMutations = null;
+ for (int i=0,mi=mutations.size(); i<mi; i++)
+ {
+ T mutation = mutations.get(i);
+ Pair<T, T> accordAndNormalMutation = splitMutationIntoAccordAndNormal(mutation, cm);
+ T accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(mutations.size(), 10));
+ accordMutations.add(accordMutation);
+ }
+ T normalMutation = accordAndNormalMutation.right;
+ if (normalMutation != null)
+ {
+ if (normalMutations == null)
+ normalMutations = new ArrayList<>(Math.min(mutations.size(), 10));
+ normalMutations.add(normalMutation);
+ }
+ }
+ return Pair.create(accordMutations, normalMutations);
+ }
+
+ public static <T extends IMutation> Pair<T, T> splitMutationIntoAccordAndNormal(T mutation, ClusterMetadata cm)
+ {
+ if (mutation.allowPotentialTransactionConflicts())
+ return Pair.create(null, mutation);
+
+ Token token = mutation.key().getToken();
+ Predicate<TableId> isAccordUpdate = tableId -> {
+ TableMetadata tm = getTableMetadata(cm, tableId);
+ if (tm == null)
+ return false;
+ return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+ };
+
+ T accordMutation = (T)mutation.filter(isAccordUpdate);
+ T normalMutation = (T)mutation.filter(not(isAccordUpdate));
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ checkState((accordMutation == null ? false : accordMutation.hasUpdateForTable(pu.metadata().id))
+ || (normalMutation == null ? false : normalMutation.hasUpdateForTable(pu.metadata().id)),
+ "All partition updates should still be present after splitting");
+ return Pair.create(accordMutation, normalMutation);
+ }
+
+ public static Pair<List<? extends IMutation>, List<WriteResponseHandlerWrapper>> splitWrappersIntoAccordAndNormal(List<WriteResponseHandlerWrapper> wrappers)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<IMutation> accordMutations = null;
+ List<WriteResponseHandlerWrapper> normalWrappers = null;
+ for (int i=0,mi=wrappers.size(); i<mi; i++)
+ {
+ WriteResponseHandlerWrapper wrapper = wrappers.get(i);
+ Pair<IMutation, WriteResponseHandlerWrapper> accordAndNormalMutation = splitWrapperIntoAccordAndNormal(wrapper, cm);
+ IMutation accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(wrappers.size(), 10));
+ accordMutations.add(accordMutation);
+ }
+ WriteResponseHandlerWrapper normalWrapper = accordAndNormalMutation.right;
+ if (normalWrapper != null)
+ {
+ if (normalWrappers == null)
+ normalWrappers = new ArrayList<>(Math.min(wrappers.size(), 10));
+ normalWrappers.add(normalWrapper);
+ }
+ }
+ return Pair.create(accordMutations, normalWrappers);
+ }
+
+ private static Pair<IMutation, WriteResponseHandlerWrapper> splitWrapperIntoAccordAndNormal(WriteResponseHandlerWrapper wrapper, ClusterMetadata cm)
+ {
+ Mutation mutation = wrapper.mutation;
+ if (mutation.allowPotentialTransactionConflicts())
+ return Pair.create(null, wrapper);
+
+ Token token = mutation.key().getToken();
+ Predicate<TableId> isAccordUpdate = tableId -> {
+ TableMetadata tm = getTableMetadata(cm, tableId);
+ if (tm == null)
+ return false;
+ return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+ };
+
+ IMutation accordMutation = mutation.filter(isAccordUpdate);
+ Mutation normalMutation = mutation.filter(not(isAccordUpdate));
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ checkState((accordMutation == null ? false : accordMutation.hasUpdateForTable(pu.metadata().id))
+ || (normalMutation == null ? false : normalMutation.hasUpdateForTable(pu.metadata().id)),
+ "All partition updates should still be present after splitting");
+ if (accordMutation == null)
+ return Pair.create(null, wrapper);
+ if (normalMutation == null)
+ return Pair.create( accordMutation, null);
+ // Since this now depends on an Accord txn need to wait for that to complete first
+ wrapper.handler.deferCleanup();
+ return Pair.create(accordMutation, new WriteResponseHandlerWrapper(wrapper.handler, normalMutation));
+ }
+
+ public static Pair<TxnId, Future<TxnResult>> mutateWithAccordAsync(Mutation mutation, @Nullable ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ return mutateWithAccordAsync(ImmutableList.of(mutation), consistencyLevel, queryStartNanoTime);
+ }
+
+
+ public static Pair<TxnId, Future<TxnResult>> mutateWithAccordAsync(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ int fragmentIndex = 0;
+ List<TxnWrite.Fragment> fragments = new ArrayList<>(mutations.size());
+ List<PartitionKey> partitionKeys = new ArrayList<>(mutations.size());
+ for (IMutation mutation : mutations)
+ {
+ for (PartitionUpdate update : mutation.getPartitionUpdates())
+ {
+ PartitionKey pk = PartitionKey.of(update);
+ partitionKeys.add(pk);
+ fragments.add(new TxnWrite.Fragment(PartitionKey.of(update), fragmentIndex++, update, TxnReferenceOperations.empty()));
+ }
+ }
+ // Potentially ignore commit consistency level if the strategy specifies accord and not migration
+ ConsistencyLevel clForCommit = consistencyLevelForCommit(mutations, consistencyLevel);
+ TxnUpdate update = new TxnUpdate(fragments, TxnCondition.none(), clForCommit, true);
+ Txn.InMemory txn = new Txn.InMemory(Keys.of(partitionKeys), TxnRead.EMPTY, TxnQuery.NONE, update);
+ IAccordService accordService = AccordService.instance();
+ return accordService.coordinateAsync(txn, consistencyLevel, queryStartNanoTime);
+ }
+
+ public static void dispatchMutationsWithRetryOnDifferentSystem(List<? extends IMutation> mutations, ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ while (true)
+ {
+ try
+ {
+ // Keep attempting to route the mutations until they all succeed on the correct system
+ // TODO (review): Metrics are going to double count when we split between the two systems
+ // but they will be split across different accord/non-accord metrics
+ Pair<List<IMutation>, List<IMutation>> accordAndNormal = splitMutationsIntoAccordAndNormal((List<IMutation>)mutations);
+ List<? extends IMutation> accordMutations = accordAndNormal.left;
+ // TODO this can race with migration to/from Accord and Accord doesn't know what range we are referring to or it just hasn't updated to the epoch we are aware of
+ // client side retry can still succeed but the error could be exposed
+ Pair<TxnId, Future<TxnResult>> accordResult = accordMutations != null ? mutateWithAccordAsync(accordMutations, consistencyLevel, queryStartNanoTime) : null;
+ List<? extends IMutation> normalMutations = accordAndNormal.right;
+
+ Throwable failure = null;
+ try
+ {
+ if (normalMutations != null)
+ mutate(normalMutations, consistencyLevel, queryStartNanoTime);
+ }
+ catch (RetryOnDifferentSystemException | CoordinatorBehindException e)
+ {
+ throw e;
+ }
+ catch (Exception e)
+ {
+ failure = Throwables.merge(failure, e);
+ }
+
+ // Check if the Accord mutations succeeded asynchronously
+ try
+ {
+ if (accordResult != null)
+ {
+ IAccordService accord = AccordService.instance();
+ TxnResult.Kind kind = accord.getTxnResult(accordResult, true, consistencyLevel, queryStartNanoTime).kind();
+ if (kind == retry_new_protocol)
+ throw new RetryOnDifferentSystemException();
+ }
+ }
+ catch (RetryOnDifferentSystemException | CoordinatorBehindException e)
+ {
+ throw e;
+ }
+ catch (Exception e)
+ {
+ failure = Throwables.merge(failure, e);
+ }
+
+ if (failure != null)
+ throw unchecked(failure);
+ }
+ catch (RetryOnDifferentSystemException e)
+ {
+ writeMetrics.mutationRetriedOnDifferentSystem.mark();
+ writeMetricsForLevel(consistencyLevel).mutationRetriedOnDifferentSystem.mark();
+ logger.debug("Retrying mutations on different system because some mutations were misrouted");
+ continue;
+ }
+ catch (CoordinatorBehindException e)
+ {
+ logger.debug("Retrying mutations now that coordinator has caught up to cluster metadata");
+ continue;
+ }
+ break;
+ }
+ }
+
+ public static void validateSafeToExecuteNonTransactionally(IMutation mutation) throws RetryOnDifferentSystemException
+ {
+ if (mutation.allowPotentialTransactionConflicts())
+ return;
+
+ // System keyspaces are never managed by Accord
+ if (SchemaConstants.isSystemKeyspace(mutation.getKeyspaceName()))
+ return;
+
+ ClusterMetadata cm = ClusterMetadata.current();
+
+ DecoratedKey dk = mutation.key();
+ // Check all the partition updates and if any can't be done return an error response
+ // and the coordinator can retry with things correctly routed
+ boolean throwRetryOnDifferentSystem = false;
+ // Track CFS so we only mark each one once
+ Set<TableId> markedColumnFamilies = null;
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ {
+ ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(pu.metadata().id);
+ TableMetadata tm = cfs.metadata();
+ if (tokenShouldBeWrittenThroughAccord(cm, tm, dk.getToken()))
+ {
+ throwRetryOnDifferentSystem = true;
+ if (markedColumnFamilies == null)
+ markedColumnFamilies = new HashSet<>();
+ if (markedColumnFamilies.add(cfs.getTableId()))
+ cfs.metric.mutationsRejectedOnWrongSystem.mark();
+ logger.debug("Rejecting mutation on wrong system to table {}.{}", cfs.keyspace.getName(), cfs.name);
+ Tracing.trace("Rejecting mutation on wrong system to table {}.{} token {}", cfs.keyspace.getName(), cfs.name, dk.getToken());
+ }
+ }
+ if (throwRetryOnDifferentSystem)
+ throw new RetryOnDifferentSystemException();
+ }
+
+ public static boolean tokenShouldBeWrittenThroughAccord(@Nonnull ClusterMetadata cm, @Nonnull TableMetadata tm, @Nonnull Token token)
Review Comment:
We should be passing in the `TableId` and using it to retrieve the table metadata from the provided `ClusterMetadata`. Passing in table metadata directly like this makes it possible to read table params from a different epoch than the cm passed in, which I think is possible in invocation in `BlockingReadRepair`
##########
src/java/org/apache/cassandra/db/IMutation.java:
##########
@@ -75,4 +78,22 @@ default boolean allowsOutOfRangeMutations()
{
return false;
}
+
+ /**
+ * True if this mutation is being applied by a transaction system or doesn't need to be
+ * and conflicts between this mutation and transactions systems that are managing all or part of this table
+ * should be assumed to be handled already (by either Paxos or Accord) and the mutation should be applied.
+ *
+ * This causes mutations against tables to fail if they are from a non-transaction sub-system such as mutations,
+ * logged and unlogged batches, hints, and read repair against tables that are being managed by a transaction system
+ * like Accord that can't safely read data that is written non-transactionally.
+ *
+ */
+ default boolean allowPotentialTransactionConflicts()
Review Comment:
I had a hard time parsing this comment
TODO: propose something easier to understand
##########
src/java/org/apache/cassandra/service/StorageProxy.java:
##########
@@ -1344,66 +1266,151 @@ public static void mutateAtomically(Collection<Mutation> mutations,
// require ALL, or EACH_QUORUM. This is so that *at least* QUORUM nodes see the update.
ConsistencyLevel batchConsistencyLevel = requireQuorumForRemove
? ConsistencyLevel.QUORUM
- : consistency_level;
+ : consistencyLevel;
- switch (consistency_level)
+ switch (consistencyLevel)
{
case ALL:
case EACH_QUORUM:
- batchConsistencyLevel = consistency_level;
+ batchConsistencyLevel = consistencyLevel;
}
ReplicaPlan.ForWrite replicaPlan = ReplicaPlans.forBatchlogWrite(batchConsistencyLevel == ConsistencyLevel.ANY);
final TimeUUID batchUUID = nextTimeUUID();
- BatchlogCleanup cleanup = new BatchlogCleanup(mutations.size(),
- () -> asyncRemoveFromBatchlog(replicaPlan, batchUUID));
-
- // add a handler for each mutation - includes checking availability, but doesn't initiate any writes, yet
- for (Mutation mutation : mutations)
+ boolean wroteToBatchLog = false;
+ while (true)
{
- WriteResponseHandlerWrapper wrapper = wrapBatchResponseHandler(mutation,
- consistency_level,
- batchConsistencyLevel,
- WriteType.BATCH,
- cleanup,
- queryStartNanoTime);
- // exit early if we can't fulfill the CL at this time.
- wrappers.add(wrapper);
- }
+ try
+ {
+ BatchlogCleanup cleanup = new BatchlogCleanup(mutations.size(),
+ () -> asyncRemoveFromBatchlog(replicaPlan, batchUUID));
+ List<WriteResponseHandlerWrapper> wrappers = new ArrayList<>(mutations.size());
- // write to the batchlog
- syncWriteToBatchlog(mutations, replicaPlan, batchUUID, queryStartNanoTime);
+ // add a handler for each mutation - includes checking availability, but doesn't initiate any writes, yet
+ for (Mutation mutation : mutations)
+ {
+ WriteResponseHandlerWrapper wrapper = wrapBatchResponseHandler(mutation,
+ consistencyLevel,
+ batchConsistencyLevel,
+ WriteType.BATCH,
+ cleanup,
+ queryStartNanoTime);
+ // exit early if we can't fulfill the CL at this time.
+ wrappers.add(wrapper);
+ }
+
+ // TODO (review): A lot of the code duplication in splitting is from WriteResponseHandlerWrapper, but we could split before making the wrappers
Review Comment:
see my comment on [BatchlogResponseHandler.java](https://github.com/apache/cassandra/pull/3395/files/96a7efd671fbd3592676af7e5cbf5db9b7512cf0#diff-f7c3660cfeb41cef884d6c0a9d8d857ff39580193b650a9ae1ca338011bc56ef). I agree splitting up the mutations before wrapping them would make this a little neater
##########
src/java/org/apache/cassandra/service/BatchlogResponseHandler.java:
##########
@@ -31,6 +31,8 @@ public class BatchlogResponseHandler<T> extends AbstractWriteResponseHandler<T>
AbstractWriteResponseHandler<T> wrapped;
BatchlogCleanup cleanup;
protected volatile int requiredBeforeFinish;
+ // Defer cleanup until `maybeAckMutationForCleanup` is called
+ private boolean deferCleanup = false;
Review Comment:
this could be made immutable if we split mutations in `StorageProxy#mutateAtomically` before calling `wrapBatchResponseHandler` and determine if we need to defer batchlog cleanup based on the existence of accord mutations.
##########
src/java/org/apache/cassandra/service/accord/AccordService.java:
##########
@@ -364,8 +392,16 @@ public IVerbHandler<? extends Request> verbHandler()
return requestHandler;
}
- private <S extends Seekables<?, ?>> long barrier(@Nonnull S keysOrRanges, long epoch, long queryStartNanos, long timeoutNanos, BarrierType barrierType, boolean isForWrite, BiFunction<Node, S, AsyncResult<SyncPoint<S>>> syncPoint)
+ private <S extends Seekables<?, ?>> Seekables barrier(@Nonnull S keysOrRanges, long epoch, long queryStartNanos, long timeoutNanos, BarrierType barrierType, boolean isForWrite, BiFunction<Node, S, AsyncResult<SyncPoint<S>>> syncPoint)
{
+ // TODO (review): So do we get what we really want picking a random cluster metadata and only doing a barrier on a subset of what was asked?
+ // We will definitely return a result indicating exactly what we ended up doing the barrier on so it's not misleading and won't falsely
+ // make progress when it shouldn't and now we don't have to be as precise as an operator specifying what to do the barrier on
+ keysOrRanges = (S)intersectionWithAccordManagedRanges(keysOrRanges);
Review Comment:
Well it's not random, it's the most recent metadata we're aware of :)
To turn the question around, why would we want to run barriers on ranges that we can't run barriers on? As long as we're not breaking the use case of intentionally migrating only a handful of keys/ranges, and we provide the user with clear feedback about what we are/are not doing, I think it's a good middle ground.
##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusMigrationMutationHelper.java:
##########
@@ -0,0 +1,399 @@
+/*
+ * 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.consensus.migration;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import com.google.common.collect.ImmutableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.primitives.Keys;
+import accord.primitives.Txn;
+import accord.primitives.TxnId;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.ConsistencyLevel;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.IMutation;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.CoordinatorBehindException;
+import org.apache.cassandra.exceptions.RetryOnDifferentSystemException;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.StorageProxy.WriteResponseHandlerWrapper;
+import org.apache.cassandra.service.accord.AccordService;
+import org.apache.cassandra.service.accord.IAccordService;
+import org.apache.cassandra.service.accord.api.PartitionKey;
+import org.apache.cassandra.service.accord.txn.TxnCondition;
+import org.apache.cassandra.service.accord.txn.TxnQuery;
+import org.apache.cassandra.service.accord.txn.TxnRead;
+import org.apache.cassandra.service.accord.txn.TxnReferenceOperations;
+import org.apache.cassandra.service.accord.txn.TxnResult;
+import org.apache.cassandra.service.accord.txn.TxnUpdate;
+import org.apache.cassandra.service.accord.txn.TxnWrite;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tracing.Tracing;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.function.Predicate.not;
+import static org.apache.cassandra.dht.Range.isInNormalizedRanges;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetrics;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetricsForLevel;
+import static org.apache.cassandra.service.StorageProxy.mutate;
+import static org.apache.cassandra.service.accord.txn.TxnResult.Kind.retry_new_protocol;
+import static org.apache.cassandra.service.consensus.migration.ConsensusRequestRouter.getTableMetadata;
+import static org.apache.cassandra.utils.Throwables.unchecked;
+
+/**
+ * Applying mutations can fail with RetryOnDifferentSystemException if a
+ * mutation conflicts with a table and range that needs to be managed
+ * transactionally. This impacts mutations, logged/unlogged batches, hints,and blocking read repair.
+ *
+ * This class contains the logic needed for managing these retry loops and splitting the mutations up
+ */
+public class ConsensusMigrationMutationHelper
+{
+ private static final Logger logger = LoggerFactory.getLogger(ConsensusMigrationMutationHelper.class);
+
+ private static ConsistencyLevel consistencyLevelForCommit(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel)
+ {
+ // Null means no specific consistency behavior is required from Accord, it's functionally similar to ANY
+ // if you aren't reading the result back via Accord
+ if (consistencyLevel == null)
+ return null;
+
+ for (IMutation mutation : mutations)
+ {
+ for (TableId tableId : mutation.getTableIds())
+ {
+ TransactionalMode mode = Schema.instance.getTableMetadata(tableId).params.transactionalMode;
+ // commitCLForStrategy should return either null or the supplied consistency level
+ // in which case we will commit everything at that CL since Accord doesn't support per table
+ // commit consistency
+ ConsistencyLevel commitCL = mode.commitCLForStrategy(consistencyLevel);
+ if (commitCL != null)
+ return commitCL;
+ }
+ }
+ return null;
+ }
+
+ public static <T extends IMutation> Pair<List<T>, List<T>> splitMutationsIntoAccordAndNormal(List<T> mutations)
Review Comment:
Instead of using Pair, can we just define a simple container class that contains accord and normal mutations? Pair's generic left and right labels make reading the code more difficult / error prone. Plus you can roll some of the repetitive list instantiation stuff into the container class.
##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusMigrationMutationHelper.java:
##########
@@ -0,0 +1,399 @@
+/*
+ * 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.consensus.migration;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import com.google.common.collect.ImmutableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.primitives.Keys;
+import accord.primitives.Txn;
+import accord.primitives.TxnId;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.ConsistencyLevel;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.IMutation;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.CoordinatorBehindException;
+import org.apache.cassandra.exceptions.RetryOnDifferentSystemException;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.StorageProxy.WriteResponseHandlerWrapper;
+import org.apache.cassandra.service.accord.AccordService;
+import org.apache.cassandra.service.accord.IAccordService;
+import org.apache.cassandra.service.accord.api.PartitionKey;
+import org.apache.cassandra.service.accord.txn.TxnCondition;
+import org.apache.cassandra.service.accord.txn.TxnQuery;
+import org.apache.cassandra.service.accord.txn.TxnRead;
+import org.apache.cassandra.service.accord.txn.TxnReferenceOperations;
+import org.apache.cassandra.service.accord.txn.TxnResult;
+import org.apache.cassandra.service.accord.txn.TxnUpdate;
+import org.apache.cassandra.service.accord.txn.TxnWrite;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tracing.Tracing;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.function.Predicate.not;
+import static org.apache.cassandra.dht.Range.isInNormalizedRanges;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetrics;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetricsForLevel;
+import static org.apache.cassandra.service.StorageProxy.mutate;
+import static org.apache.cassandra.service.accord.txn.TxnResult.Kind.retry_new_protocol;
+import static org.apache.cassandra.service.consensus.migration.ConsensusRequestRouter.getTableMetadata;
+import static org.apache.cassandra.utils.Throwables.unchecked;
+
+/**
+ * Applying mutations can fail with RetryOnDifferentSystemException if a
+ * mutation conflicts with a table and range that needs to be managed
+ * transactionally. This impacts mutations, logged/unlogged batches, hints,and blocking read repair.
+ *
+ * This class contains the logic needed for managing these retry loops and splitting the mutations up
+ */
+public class ConsensusMigrationMutationHelper
+{
+ private static final Logger logger = LoggerFactory.getLogger(ConsensusMigrationMutationHelper.class);
+
+ private static ConsistencyLevel consistencyLevelForCommit(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel)
+ {
+ // Null means no specific consistency behavior is required from Accord, it's functionally similar to ANY
+ // if you aren't reading the result back via Accord
+ if (consistencyLevel == null)
+ return null;
+
+ for (IMutation mutation : mutations)
+ {
+ for (TableId tableId : mutation.getTableIds())
+ {
+ TransactionalMode mode = Schema.instance.getTableMetadata(tableId).params.transactionalMode;
+ // commitCLForStrategy should return either null or the supplied consistency level
+ // in which case we will commit everything at that CL since Accord doesn't support per table
+ // commit consistency
+ ConsistencyLevel commitCL = mode.commitCLForStrategy(consistencyLevel);
+ if (commitCL != null)
+ return commitCL;
+ }
+ }
+ return null;
+ }
+
+ public static <T extends IMutation> Pair<List<T>, List<T>> splitMutationsIntoAccordAndNormal(List<T> mutations)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<T> accordMutations = null;
+ List<T> normalMutations = null;
+ for (int i=0,mi=mutations.size(); i<mi; i++)
+ {
+ T mutation = mutations.get(i);
+ Pair<T, T> accordAndNormalMutation = splitMutationIntoAccordAndNormal(mutation, cm);
+ T accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(mutations.size(), 10));
+ accordMutations.add(accordMutation);
+ }
+ T normalMutation = accordAndNormalMutation.right;
+ if (normalMutation != null)
+ {
+ if (normalMutations == null)
+ normalMutations = new ArrayList<>(Math.min(mutations.size(), 10));
+ normalMutations.add(normalMutation);
+ }
+ }
+ return Pair.create(accordMutations, normalMutations);
+ }
+
+ public static <T extends IMutation> Pair<T, T> splitMutationIntoAccordAndNormal(T mutation, ClusterMetadata cm)
+ {
+ if (mutation.allowPotentialTransactionConflicts())
+ return Pair.create(null, mutation);
+
+ Token token = mutation.key().getToken();
+ Predicate<TableId> isAccordUpdate = tableId -> {
+ TableMetadata tm = getTableMetadata(cm, tableId);
+ if (tm == null)
+ return false;
+ return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+ };
+
+ T accordMutation = (T)mutation.filter(isAccordUpdate);
+ T normalMutation = (T)mutation.filter(not(isAccordUpdate));
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ checkState((accordMutation == null ? false : accordMutation.hasUpdateForTable(pu.metadata().id))
+ || (normalMutation == null ? false : normalMutation.hasUpdateForTable(pu.metadata().id)),
+ "All partition updates should still be present after splitting");
+ return Pair.create(accordMutation, normalMutation);
+ }
+
+ public static Pair<List<? extends IMutation>, List<WriteResponseHandlerWrapper>> splitWrappersIntoAccordAndNormal(List<WriteResponseHandlerWrapper> wrappers)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<IMutation> accordMutations = null;
+ List<WriteResponseHandlerWrapper> normalWrappers = null;
+ for (int i=0,mi=wrappers.size(); i<mi; i++)
+ {
+ WriteResponseHandlerWrapper wrapper = wrappers.get(i);
+ Pair<IMutation, WriteResponseHandlerWrapper> accordAndNormalMutation = splitWrapperIntoAccordAndNormal(wrapper, cm);
+ IMutation accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(wrappers.size(), 10));
+ accordMutations.add(accordMutation);
+ }
+ WriteResponseHandlerWrapper normalWrapper = accordAndNormalMutation.right;
+ if (normalWrapper != null)
+ {
+ if (normalWrappers == null)
+ normalWrappers = new ArrayList<>(Math.min(wrappers.size(), 10));
+ normalWrappers.add(normalWrapper);
+ }
+ }
+ return Pair.create(accordMutations, normalWrappers);
+ }
+
+ private static Pair<IMutation, WriteResponseHandlerWrapper> splitWrapperIntoAccordAndNormal(WriteResponseHandlerWrapper wrapper, ClusterMetadata cm)
+ {
+ Mutation mutation = wrapper.mutation;
+ if (mutation.allowPotentialTransactionConflicts())
+ return Pair.create(null, wrapper);
+
+ Token token = mutation.key().getToken();
+ Predicate<TableId> isAccordUpdate = tableId -> {
+ TableMetadata tm = getTableMetadata(cm, tableId);
+ if (tm == null)
+ return false;
+ return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+ };
+
+ IMutation accordMutation = mutation.filter(isAccordUpdate);
+ Mutation normalMutation = mutation.filter(not(isAccordUpdate));
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ checkState((accordMutation == null ? false : accordMutation.hasUpdateForTable(pu.metadata().id))
+ || (normalMutation == null ? false : normalMutation.hasUpdateForTable(pu.metadata().id)),
+ "All partition updates should still be present after splitting");
+ if (accordMutation == null)
+ return Pair.create(null, wrapper);
+ if (normalMutation == null)
+ return Pair.create( accordMutation, null);
+ // Since this now depends on an Accord txn need to wait for that to complete first
+ wrapper.handler.deferCleanup();
+ return Pair.create(accordMutation, new WriteResponseHandlerWrapper(wrapper.handler, normalMutation));
+ }
+
+ public static Pair<TxnId, Future<TxnResult>> mutateWithAccordAsync(Mutation mutation, @Nullable ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ return mutateWithAccordAsync(ImmutableList.of(mutation), consistencyLevel, queryStartNanoTime);
+ }
+
+
+ public static Pair<TxnId, Future<TxnResult>> mutateWithAccordAsync(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ int fragmentIndex = 0;
+ List<TxnWrite.Fragment> fragments = new ArrayList<>(mutations.size());
+ List<PartitionKey> partitionKeys = new ArrayList<>(mutations.size());
+ for (IMutation mutation : mutations)
+ {
+ for (PartitionUpdate update : mutation.getPartitionUpdates())
+ {
+ PartitionKey pk = PartitionKey.of(update);
+ partitionKeys.add(pk);
+ fragments.add(new TxnWrite.Fragment(PartitionKey.of(update), fragmentIndex++, update, TxnReferenceOperations.empty()));
+ }
+ }
+ // Potentially ignore commit consistency level if the strategy specifies accord and not migration
+ ConsistencyLevel clForCommit = consistencyLevelForCommit(mutations, consistencyLevel);
+ TxnUpdate update = new TxnUpdate(fragments, TxnCondition.none(), clForCommit, true);
+ Txn.InMemory txn = new Txn.InMemory(Keys.of(partitionKeys), TxnRead.EMPTY, TxnQuery.NONE, update);
+ IAccordService accordService = AccordService.instance();
+ return accordService.coordinateAsync(txn, consistencyLevel, queryStartNanoTime);
+ }
+
+ public static void dispatchMutationsWithRetryOnDifferentSystem(List<? extends IMutation> mutations, ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ while (true)
+ {
+ try
+ {
+ // Keep attempting to route the mutations until they all succeed on the correct system
+ // TODO (review): Metrics are going to double count when we split between the two systems
Review Comment:
that seems reasonable... a write is following both write paths
##########
src/java/org/apache/cassandra/service/accord/AccordService.java:
##########
@@ -592,12 +715,9 @@ public TopologyManager topology()
}
catch (TimeoutException e)
{
+ // TODO (review): This is j.u.c timeout so maybe this should mark?
Review Comment:
j.u.c?
##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusRequestRouter.java:
##########
@@ -85,11 +87,17 @@ ConsensusRoutingDecision decisionFor(TransactionalMode transactionalMode)
private static TableMetadata metadata(ClusterMetadata cm, String keyspace, String table)
{
- KeyspaceMetadata ksm = cm.schema.getKeyspaceMetadata(keyspace);
- TableMetadata tbm = ksm != null ? ksm.getTableOrViewNullable(table) : null;
-
+ Optional<KeyspaceMetadata> ksm = cm.schema.maybeGetKeyspaceMetadata(keyspace);
+ if (ksm.isEmpty())
+ {
+ KeyspaceMetadata ksm2 = Schema.instance.getKeyspaceMetadata(keyspace);
+ if (ksm2 == null)
Review Comment:
what's happening here? Is this meant to allow for system and virtual tables?
The call to `ClusterMetadata#current` in `Schema#getKeyspaceMetadata` creates a race that may cause us to erroneously pick paxos for accord tables.
If the cluster metadata object doesn't contain the keyspace we're looking for, we'll check w/ Schema. If the schema changes and the keyspace we're looking for appears between calls we'll return null and we'll pick paxos when we should have either thrown an exception or picked accord
##########
src/java/org/apache/cassandra/hints/HintsDispatcher.java:
##########
@@ -165,10 +226,62 @@ private Action sendHintsAndAwait(HintsReader.Page page)
else
{
HintDiagnostics.pageSuccessResult(this, success, failures, timeouts);
+ rehintHintsNeedingRehinting();
return Action.CONTINUE;
}
}
+ private void rehintHintsNeedingRehinting()
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ Hint hint;
+ while ((hint = hintsNeedingRehinting.poll()) != null)
+ {
+ HintsService.instance.writeForAllReplicas(hint);
+ Mutation mutation = hint.mutation;
+ // Also may need to apply locally because it's possible this is from the batchlog
+ // and we never applied it locally
+ // TODO (review): Additional error handling necessary? Hints are lossy
Review Comment:
agreed, they're best effort
##########
src/java/org/apache/cassandra/service/StorageProxy.java:
##########
@@ -1263,53 +1218,22 @@ public static void mutateWithTriggers(List<? extends IMutation> mutations,
}
}
- Collection<Mutation> augmented = TriggerExecutor.instance.execute(mutations);
+ List<Mutation> augmented = TriggerExecutor.instance.execute(mutations);
String keyspaceName = mutations.iterator().next().getKeyspaceName();
- boolean updatesView = Keyspace.open(mutations.iterator().next().getKeyspaceName())
+ boolean updatesView = Keyspace.open(keyspaceName)
.viewManager
.updatesAffectView(mutations, true);
-
+ // TODO (review): This is not the same as augmented? Doesn't seem right
Review Comment:
yeah seems like a metrics bug
##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusMigrationMutationHelper.java:
##########
@@ -0,0 +1,399 @@
+/*
+ * 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.consensus.migration;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import com.google.common.collect.ImmutableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.primitives.Keys;
+import accord.primitives.Txn;
+import accord.primitives.TxnId;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.ConsistencyLevel;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.IMutation;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.CoordinatorBehindException;
+import org.apache.cassandra.exceptions.RetryOnDifferentSystemException;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.StorageProxy.WriteResponseHandlerWrapper;
+import org.apache.cassandra.service.accord.AccordService;
+import org.apache.cassandra.service.accord.IAccordService;
+import org.apache.cassandra.service.accord.api.PartitionKey;
+import org.apache.cassandra.service.accord.txn.TxnCondition;
+import org.apache.cassandra.service.accord.txn.TxnQuery;
+import org.apache.cassandra.service.accord.txn.TxnRead;
+import org.apache.cassandra.service.accord.txn.TxnReferenceOperations;
+import org.apache.cassandra.service.accord.txn.TxnResult;
+import org.apache.cassandra.service.accord.txn.TxnUpdate;
+import org.apache.cassandra.service.accord.txn.TxnWrite;
+import org.apache.cassandra.service.consensus.TransactionalMode;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.tracing.Tracing;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.function.Predicate.not;
+import static org.apache.cassandra.dht.Range.isInNormalizedRanges;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetrics;
+import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.writeMetricsForLevel;
+import static org.apache.cassandra.service.StorageProxy.mutate;
+import static org.apache.cassandra.service.accord.txn.TxnResult.Kind.retry_new_protocol;
+import static org.apache.cassandra.service.consensus.migration.ConsensusRequestRouter.getTableMetadata;
+import static org.apache.cassandra.utils.Throwables.unchecked;
+
+/**
+ * Applying mutations can fail with RetryOnDifferentSystemException if a
+ * mutation conflicts with a table and range that needs to be managed
+ * transactionally. This impacts mutations, logged/unlogged batches, hints,and blocking read repair.
+ *
+ * This class contains the logic needed for managing these retry loops and splitting the mutations up
+ */
+public class ConsensusMigrationMutationHelper
+{
+ private static final Logger logger = LoggerFactory.getLogger(ConsensusMigrationMutationHelper.class);
+
+ private static ConsistencyLevel consistencyLevelForCommit(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel)
+ {
+ // Null means no specific consistency behavior is required from Accord, it's functionally similar to ANY
+ // if you aren't reading the result back via Accord
+ if (consistencyLevel == null)
+ return null;
+
+ for (IMutation mutation : mutations)
+ {
+ for (TableId tableId : mutation.getTableIds())
+ {
+ TransactionalMode mode = Schema.instance.getTableMetadata(tableId).params.transactionalMode;
+ // commitCLForStrategy should return either null or the supplied consistency level
+ // in which case we will commit everything at that CL since Accord doesn't support per table
+ // commit consistency
+ ConsistencyLevel commitCL = mode.commitCLForStrategy(consistencyLevel);
+ if (commitCL != null)
+ return commitCL;
+ }
+ }
+ return null;
+ }
+
+ public static <T extends IMutation> Pair<List<T>, List<T>> splitMutationsIntoAccordAndNormal(List<T> mutations)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<T> accordMutations = null;
+ List<T> normalMutations = null;
+ for (int i=0,mi=mutations.size(); i<mi; i++)
+ {
+ T mutation = mutations.get(i);
+ Pair<T, T> accordAndNormalMutation = splitMutationIntoAccordAndNormal(mutation, cm);
+ T accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(mutations.size(), 10));
+ accordMutations.add(accordMutation);
+ }
+ T normalMutation = accordAndNormalMutation.right;
+ if (normalMutation != null)
+ {
+ if (normalMutations == null)
+ normalMutations = new ArrayList<>(Math.min(mutations.size(), 10));
+ normalMutations.add(normalMutation);
+ }
+ }
+ return Pair.create(accordMutations, normalMutations);
+ }
+
+ public static <T extends IMutation> Pair<T, T> splitMutationIntoAccordAndNormal(T mutation, ClusterMetadata cm)
+ {
+ if (mutation.allowPotentialTransactionConflicts())
+ return Pair.create(null, mutation);
+
+ Token token = mutation.key().getToken();
+ Predicate<TableId> isAccordUpdate = tableId -> {
+ TableMetadata tm = getTableMetadata(cm, tableId);
+ if (tm == null)
+ return false;
+ return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+ };
+
+ T accordMutation = (T)mutation.filter(isAccordUpdate);
+ T normalMutation = (T)mutation.filter(not(isAccordUpdate));
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ checkState((accordMutation == null ? false : accordMutation.hasUpdateForTable(pu.metadata().id))
+ || (normalMutation == null ? false : normalMutation.hasUpdateForTable(pu.metadata().id)),
+ "All partition updates should still be present after splitting");
+ return Pair.create(accordMutation, normalMutation);
+ }
+
+ public static Pair<List<? extends IMutation>, List<WriteResponseHandlerWrapper>> splitWrappersIntoAccordAndNormal(List<WriteResponseHandlerWrapper> wrappers)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ List<IMutation> accordMutations = null;
+ List<WriteResponseHandlerWrapper> normalWrappers = null;
+ for (int i=0,mi=wrappers.size(); i<mi; i++)
+ {
+ WriteResponseHandlerWrapper wrapper = wrappers.get(i);
+ Pair<IMutation, WriteResponseHandlerWrapper> accordAndNormalMutation = splitWrapperIntoAccordAndNormal(wrapper, cm);
+ IMutation accordMutation = accordAndNormalMutation.left;
+ if (accordMutation != null)
+ {
+ if (accordMutations == null)
+ accordMutations = new ArrayList<>(Math.min(wrappers.size(), 10));
+ accordMutations.add(accordMutation);
+ }
+ WriteResponseHandlerWrapper normalWrapper = accordAndNormalMutation.right;
+ if (normalWrapper != null)
+ {
+ if (normalWrappers == null)
+ normalWrappers = new ArrayList<>(Math.min(wrappers.size(), 10));
+ normalWrappers.add(normalWrapper);
+ }
+ }
+ return Pair.create(accordMutations, normalWrappers);
+ }
+
+ private static Pair<IMutation, WriteResponseHandlerWrapper> splitWrapperIntoAccordAndNormal(WriteResponseHandlerWrapper wrapper, ClusterMetadata cm)
+ {
+ Mutation mutation = wrapper.mutation;
+ if (mutation.allowPotentialTransactionConflicts())
+ return Pair.create(null, wrapper);
+
+ Token token = mutation.key().getToken();
+ Predicate<TableId> isAccordUpdate = tableId -> {
+ TableMetadata tm = getTableMetadata(cm, tableId);
+ if (tm == null)
+ return false;
+ return tokenShouldBeWrittenThroughAccord(cm, tm, token);
+ };
+
+ IMutation accordMutation = mutation.filter(isAccordUpdate);
+ Mutation normalMutation = mutation.filter(not(isAccordUpdate));
+ for (PartitionUpdate pu : mutation.getPartitionUpdates())
+ checkState((accordMutation == null ? false : accordMutation.hasUpdateForTable(pu.metadata().id))
+ || (normalMutation == null ? false : normalMutation.hasUpdateForTable(pu.metadata().id)),
+ "All partition updates should still be present after splitting");
+ if (accordMutation == null)
+ return Pair.create(null, wrapper);
+ if (normalMutation == null)
+ return Pair.create( accordMutation, null);
+ // Since this now depends on an Accord txn need to wait for that to complete first
+ wrapper.handler.deferCleanup();
+ return Pair.create(accordMutation, new WriteResponseHandlerWrapper(wrapper.handler, normalMutation));
+ }
+
+ public static Pair<TxnId, Future<TxnResult>> mutateWithAccordAsync(Mutation mutation, @Nullable ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ return mutateWithAccordAsync(ImmutableList.of(mutation), consistencyLevel, queryStartNanoTime);
+ }
+
+
+ public static Pair<TxnId, Future<TxnResult>> mutateWithAccordAsync(Collection<? extends IMutation> mutations, @Nullable ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ int fragmentIndex = 0;
+ List<TxnWrite.Fragment> fragments = new ArrayList<>(mutations.size());
+ List<PartitionKey> partitionKeys = new ArrayList<>(mutations.size());
+ for (IMutation mutation : mutations)
+ {
+ for (PartitionUpdate update : mutation.getPartitionUpdates())
+ {
+ PartitionKey pk = PartitionKey.of(update);
+ partitionKeys.add(pk);
+ fragments.add(new TxnWrite.Fragment(PartitionKey.of(update), fragmentIndex++, update, TxnReferenceOperations.empty()));
+ }
+ }
+ // Potentially ignore commit consistency level if the strategy specifies accord and not migration
+ ConsistencyLevel clForCommit = consistencyLevelForCommit(mutations, consistencyLevel);
+ TxnUpdate update = new TxnUpdate(fragments, TxnCondition.none(), clForCommit, true);
+ Txn.InMemory txn = new Txn.InMemory(Keys.of(partitionKeys), TxnRead.EMPTY, TxnQuery.NONE, update);
+ IAccordService accordService = AccordService.instance();
+ return accordService.coordinateAsync(txn, consistencyLevel, queryStartNanoTime);
+ }
+
+ public static void dispatchMutationsWithRetryOnDifferentSystem(List<? extends IMutation> mutations, ConsistencyLevel consistencyLevel, long queryStartNanoTime)
+ {
+ while (true)
+ {
+ try
+ {
+ // Keep attempting to route the mutations until they all succeed on the correct system
+ // TODO (review): Metrics are going to double count when we split between the two systems
+ // but they will be split across different accord/non-accord metrics
+ Pair<List<IMutation>, List<IMutation>> accordAndNormal = splitMutationsIntoAccordAndNormal((List<IMutation>)mutations);
+ List<? extends IMutation> accordMutations = accordAndNormal.left;
+ // TODO this can race with migration to/from Accord and Accord doesn't know what range we are referring to or it just hasn't updated to the epoch we are aware of
+ // client side retry can still succeed but the error could be exposed
+ Pair<TxnId, Future<TxnResult>> accordResult = accordMutations != null ? mutateWithAccordAsync(accordMutations, consistencyLevel, queryStartNanoTime) : null;
+ List<? extends IMutation> normalMutations = accordAndNormal.right;
+
+ Throwable failure = null;
+ try
+ {
+ if (normalMutations != null)
Review Comment:
I think this whole try block should be contained in this if block?
##########
src/java/org/apache/cassandra/hints/HintsDispatcher.java:
##########
@@ -194,38 +307,106 @@ private <T> Action sendHints(Iterator<T> hints, Collection<Callback> callbacks,
return Action.CONTINUE;
}
+ // TODO (review): Could add the loop, but how often will it be needed?
Review Comment:
agreed looping here would be excessive
##########
src/java/org/apache/cassandra/service/consensus/migration/ConsensusRequestRouter.java:
##########
@@ -98,18 +106,37 @@ public ConsensusRoutingDecision routeAndMaybeMigrate(@Nonnull DecoratedKey key,
{
ClusterMetadata cm = ClusterMetadata.current();
TableMetadata metadata = metadata(cm, keyspace, table);
+ // Non-distributed tables always take the Paxos path
+ if (metadata == null)
+ return pickPaxos();
return routeAndMaybeMigrate(cm, metadata, key, consistencyLevel, queryStartNanoTime, timeoutNanos, isForWrite);
}
public ConsensusRoutingDecision routeAndMaybeMigrate(@Nonnull DecoratedKey key, @Nonnull TableId tableId, ConsistencyLevel consistencyLevel, long queryStartNanotime, long timeoutNanos, boolean isForWrite)
{
ClusterMetadata cm = ClusterMetadata.current();
- TableMetadata metadata = cm.schema.getTableMetadata(tableId);
+ TableMetadata metadata = getTableMetadata(cm, tableId);
+ // Non-distributed tables always take the Paxos path
if (metadata == null)
- throw new IllegalStateException("Can't route consensus request for nonexistent table %s".format(tableId.toString()));
+ pickPaxos();
return routeAndMaybeMigrate(cm, metadata, key, consistencyLevel, queryStartNanotime, timeoutNanos, isForWrite);
}
+ public static TableMetadata getTableMetadata(ClusterMetadata cm, TableId tableId)
+ {
+ TableMetadata tm = cm.schema.getTableMetadata(tableId);
+ if (tm == null)
+ {
+ // It's a non-distributed table which is fine, but we want to error if it doesn't exist
+ // We should never actually reach here unless there is a race with dropping the table
+ TableMetadata tm2 = Schema.instance.getTableMetadata(tableId);
Review Comment:
same issue as `getKeyspaceMetadata`
##########
src/java/org/apache/cassandra/hints/HintsDispatcher.java:
##########
@@ -138,8 +196,11 @@ private Action sendHintsAndAwait(HintsReader.Page page)
*
* If that is not the case, we'll need to perform conversion to a newer (or an older) format, and decoding the hint
* is an unavoidable intermediate step.
+ *
+ * If Accord is enabled or these hints are from the batchlog and were originally attempted on Accord then
+ * we also need to decode so we can route the Hint contents appropriately.
*/
- Action action = reader.descriptor().messagingVersion() == messagingVersion
+ Action action = reader.descriptor().messagingVersion() == messagingVersion && !DatabaseDescriptor.getAccordTransactionsEnabled() && !hostId.equals(RETRY_ON_DIFFERENT_SYSTEM_UUID)
Review Comment:
Alternatively, what if the hint recipient took over accord coordination instead of sending it back to the hint dispatcher? It does something similar when it receives a hint for a key it no longer replicates
##########
src/java/org/apache/cassandra/hints/HintsDispatcher.java:
##########
@@ -194,38 +307,106 @@ private <T> Action sendHints(Iterator<T> hints, Collection<Callback> callbacks,
return Action.CONTINUE;
}
+ // TODO (review): Could add the loop, but how often will it be needed?
+ // While this could loop if splitting the mutation misroutes there isn't a strong need because Hints will retry anyways
+ // It will cause hint delivery for this endpoint to pause until it is rescheduled again
+ // Given the structure of page at a time delivery it's also a little tricky because we would really need to iterate over the entire page
+ // again only applying the hints that ended up needing to be re-routed
private Callback sendHint(Hint hint)
{
- Callback callback = new Callback(hint.creationTime);
- Message<?> message = Message.out(HINT_REQ, new HintMessage(hostId, hint));
- MessagingService.instance().sendWithCallback(message, address, callback);
+ Pair<Mutation, Hint> accordAndNormal = splitHintIntoAccordAndNormal(hint);
+ Mutation accordHintMutation = accordAndNormal.left;
+ long txnStartNanoTime = 0;
+ Pair<TxnId, Future<TxnResult>> accordTxnResult = null;
+ if (accordHintMutation != null)
+ {
+ txnStartNanoTime = Clock.Global.nanoTime();
+ accordTxnResult = accordHintMutation != null ? mutateWithAccordAsync(accordHintMutation, null, txnStartNanoTime) : null;
+ }
+
+ Hint normalHint = accordAndNormal.right;
+ Callback callback = new Callback(address, hint.creationTime, txnStartNanoTime, accordTxnResult);
+ if (normalHint != null)
+ {
+ // We had a hint that was supposed to be done on Accord for the batch log (otherwise address would be non-null),
+ // but Accord no longer manages that table/range and now we don't know which nodes (if any) are missing the Mutation.
+ // Convert them to per replica hints *after* all the hints in this page have been applied so we can be reasonably sure
+ // this page isn't going to be played again thus avoiding any futher amplification from the same hint being
+ // replayed and repeatedly converted to per replica hints
+ if (address == null)
+ {
+ checkState(hostId.equals(RETRY_ON_DIFFERENT_SYSTEM_UUID), "If there is no address to send the hint to then the host ID should be BATCHLOG_ACCORD_HINT_UUID");
+ callback.onResponse(null);
+ hintsNeedingRehinting.add(normalHint);
+ }
+ else
+ {
+ Message<?> message = Message.out(HINT_REQ, new HintMessage(hostId, normalHint));
+ MessagingService.instance().sendWithCallback(message, address, callback);
+ }
+ }
+ else
+ {
+ // Don't wait for a normal response that will never come since no hints were sent
+ callback.onResponse(null);
+ }
+
return callback;
}
+ private Pair<Mutation, Hint> splitHintIntoAccordAndNormal(Hint hint)
+ {
+ ClusterMetadata cm = ClusterMetadata.current();
+ Pair<Mutation, Mutation> accordAndNormal = splitMutationIntoAccordAndNormal(hint.mutation, cm);
+ if (accordAndNormal.left == null)
+ return Pair.create(null, hint);
+ if (accordAndNormal.right == null)
+ return Pair.create(accordAndNormal.left, null);
+ Hint normalHint = Hint.create(accordAndNormal.right, hint.creationTime, accordAndNormal.right.smallestGCGS());
+ return Pair.create(accordAndNormal.left, normalHint);
+ }
+
/*
* Sending hints in raw mode.
*/
private Callback sendEncodedHint(ByteBuffer hint)
{
HintMessage.Encoded message = new HintMessage.Encoded(hostId, hint, messagingVersion);
- Callback callback = new Callback(message.getHintCreationTime());
+ Callback callback = new Callback(address, message.getHintCreationTime());
MessagingService.instance().sendWithCallback(Message.out(HINT_REQ, message), address, callback);
return callback;
}
- static final class Callback implements RequestCallback
+ static final class Callback implements RequestCallback, Runnable
{
enum Outcome { SUCCESS, TIMEOUT, FAILURE, INTERRUPTED }
private final long start = approxTime.now();
private final Condition condition = newOneTimeCondition();
- private volatile Outcome outcome;
+ private Outcome normalOutcome;
+ private Outcome accordOutcome;
+ @Nullable
+ private final InetAddressAndPort to;
private final long hintCreationNanoTime;
+ private final long accordTxnStartNanos;
+ private final Pair<TxnId, Future<TxnResult>> accordTxnResult;
+
+ private Callback(@Nonnull InetAddressAndPort to, long hintCreationTimeMillisSinceEpoch)
+ {
+ this(to, hintCreationTimeMillisSinceEpoch, -1, null);
+ }
- private Callback(long hintCreationTimeMillisSinceEpoch)
+ private Callback(@Nullable InetAddressAndPort to, long hintCreationTimeMillisSinceEpoch, long accordTxnStartNanos, @Nullable Pair<TxnId, Future<TxnResult>> accordTxnResult)
{
+ this.to = to != null ? to : ACCORD_HINT_ENDPOINT;
this.hintCreationNanoTime = approxTime.translate().fromMillisSinceEpoch(hintCreationTimeMillisSinceEpoch);
+ this.accordTxnStartNanos = accordTxnStartNanos;
+ this.accordTxnResult = accordTxnResult;
+ if (accordTxnResult != null)
+ accordTxnResult.right.addListener(this, ImmediateExecutor.INSTANCE);
Review Comment:
shouldn't we register as a result/throwable consumer so we are notified if the txn fails unexpectedly?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org