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 2023/04/10 20:45:54 UTC
[GitHub] [cassandra-accord] bdeggleston commented on a diff in pull request #36: CASSANDRA-18129 Accord <-> Paxos live migration
bdeggleston commented on code in PR #36:
URL: https://github.com/apache/cassandra-accord/pull/36#discussion_r1161965051
##########
accord-core/src/main/java/accord/coordinate/Barrier.java:
##########
@@ -0,0 +1,301 @@
+/*
+ * 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 accord.coordinate;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.BarrierType;
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandListener;
+import accord.local.Node;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommand;
+import accord.local.SafeCommandStore;
+import accord.local.SafeCommandStore.TestDep;
+import accord.local.SafeCommandStore.TestKind;
+import accord.local.SafeCommandStore.TestTimestamp;
+import accord.local.Status;
+import accord.primitives.Keys;
+import accord.primitives.Ranges;
+import accord.primitives.Routable.Domain;
+import accord.primitives.Seekable;
+import accord.primitives.Seekables;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.MapReduceConsume;
+import accord.utils.async.AsyncResults;
+import javax.annotation.Nonnull;
+
+import static accord.local.PreLoadContext.EMPTY_PRELOADCONTEXT;
+import static accord.local.PreLoadContext.contextFor;
+import static accord.utils.Invariants.checkArgument;
+
+/**
+ * Local or global barriers that return a result once all transactions have their side effects visible.
+ *
+ * For local barriers the epoch is the only guarantee, but for global barriers a new transaction is created so it will
+ * be as of the timestamp of the created transaction.
+ *
+ * Note that reads might still order after, but side effect bearing transactions should not.
+ */
+public class Barrier extends AsyncResults.SettableResult<Timestamp>
+{
+ private static final Logger logger = LoggerFactory.getLogger(Barrier.class);
Review Comment:
unused
##########
accord-core/src/main/java/accord/coordinate/Barrier.java:
##########
@@ -0,0 +1,301 @@
+/*
+ * 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 accord.coordinate;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.BarrierType;
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandListener;
+import accord.local.Node;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommand;
+import accord.local.SafeCommandStore;
+import accord.local.SafeCommandStore.TestDep;
+import accord.local.SafeCommandStore.TestKind;
+import accord.local.SafeCommandStore.TestTimestamp;
+import accord.local.Status;
+import accord.primitives.Keys;
+import accord.primitives.Ranges;
+import accord.primitives.Routable.Domain;
+import accord.primitives.Seekable;
+import accord.primitives.Seekables;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.MapReduceConsume;
+import accord.utils.async.AsyncResults;
+import javax.annotation.Nonnull;
+
+import static accord.local.PreLoadContext.EMPTY_PRELOADCONTEXT;
+import static accord.local.PreLoadContext.contextFor;
+import static accord.utils.Invariants.checkArgument;
+
+/**
+ * Local or global barriers that return a result once all transactions have their side effects visible.
+ *
+ * For local barriers the epoch is the only guarantee, but for global barriers a new transaction is created so it will
+ * be as of the timestamp of the created transaction.
+ *
+ * Note that reads might still order after, but side effect bearing transactions should not.
+ */
+public class Barrier extends AsyncResults.SettableResult<Timestamp>
+{
+ private static final Logger logger = LoggerFactory.getLogger(Barrier.class);
+
+ private final Node node;
+ private final Seekable keyOrRange;
+
+ private final Seekables<?, ?> seekables;
+
+ private final long minEpoch;
+ private final BarrierType barrierType;
+
+ @VisibleForTesting
+ CoordinateSyncPoint coordinateSyncPoint;
+ @VisibleForTesting
+ ExistingTransactionCheck existingTransactionCheck;
+
+ Barrier(Node node, Seekable keyOrRange, long minEpoch, BarrierType barrierType)
+ {
+ checkArgument(keyOrRange.domain() == Domain.Key || barrierType.global, "Ranges are only supported with global barriers");
+ this.node = node;
+ this.minEpoch = minEpoch;
+ this.keyOrRange = keyOrRange;
+ this.seekables = keyOrRange.domain() == Domain.Key ? Keys.of(keyOrRange.asKey()) : Ranges.of(keyOrRange.asRange());
+ this.barrierType = barrierType;
+ }
+
+ public static Barrier barrier(Node node, Seekable keyOrRange, long minEpoch, BarrierType barrierType)
+ {
+ Barrier barrier = new Barrier(node, keyOrRange, minEpoch, barrierType);
+ barrier.start();
+ return barrier;
+ }
+
+ private void start()
+ {
+ // It may be possible to use local state to determine that the barrier is already satisfied or
+ // there is an existing transaction we can wait on
+ if (keyOrRange.domain().isKey() && !barrierType.global)
+ {
+ existingTransactionCheck = checkForExistingTransaction();
+ existingTransactionCheck.addCallback((barrierTxn, existingTransactionCheckFailure) -> {
+ if (existingTransactionCheckFailure != null)
+ {
+ Barrier.this.tryFailure(existingTransactionCheckFailure);
+ return;
+ }
+
+ if (barrierTxn != null)
+ {
+ if (barrierTxn.status.equals(Status.Applied))
+ {
+ doBarrierSuccess(barrierTxn.executeAt);
+ }
+ // A listener was added to the transaction already
+ }
+ else
+ {
+ createSyncPoint();
+ }
+ });
+ }
+ else
+ {
+ createSyncPoint();
+ }
+ }
+
+ private void doBarrierSuccess(Timestamp executeAt)
+ {
+ // The transaction we wait on might have more keys, but it's not
+ // guaranteed they were wanted and we don't want to force the agent to filter them
+ // so provide the seekables we were given.
+ // We also don't notify the agent for range barriers since that makes sense as a local concept
+ // since ranges can easily span multiple nodes
+ if (seekables != null)
+ node.agent().onLocalBarrier(seekables, executeAt);
+ Barrier.this.trySuccess(executeAt);
+ }
+
+ private void createSyncPoint()
+ {
+ coordinateSyncPoint = CoordinateSyncPoint.inclusive(node, Seekables.of(keyOrRange), barrierType.async);
+ coordinateSyncPoint.addCallback((syncPoint, syncPointFailure) -> {
+ if (syncPointFailure != null)
+ {
+ Barrier.this.tryFailure(syncPointFailure);
+ return;
+ }
+
+ // Need to wait for the local transaction to finish since coordinate sync point won't wait on anything
+ // if async was requested or there were no deps found
+ if (syncPoint.finishedAsync)
+ {
+ TxnId txnId = syncPoint.txnId;
+ long epoch = txnId.epoch();
+ RoutingKey homeKey = syncPoint.homeKey;
+ node.commandStores().ifLocal(PreLoadContext.contextFor(syncPoint.txnId), homeKey, epoch, epoch, safeStore -> {
+ CommandListener listener = new BarrierCommandListener();
+ SafeCommand safeCommand = safeStore.command(txnId);
+ listener.onChange(safeStore, safeCommand);
+ if (!isDone())
+ safeCommand.addListener(listener);
+ }).begin(node.agent());
+ }
+ else
+ {
+ doBarrierSuccess(syncPoint.txnId);
+ }
+ });
+ }
+
+ private class BarrierCommandListener implements CommandListener
+ {
+ @Override
+ public void onChange(SafeCommandStore safeStore, SafeCommand safeCommand)
+ {
+ Command command = safeCommand.current();
+ if (command.is(Status.Applied))
+ {
+ Timestamp executeAt = command.executeAt();
+ // In all the cases where we add a listener (listening to existing command, async completion of CoordinateSyncPoint)
+ // we want to notify the agent
+ doBarrierSuccess(executeAt);
+ }
+ else if (command.is(Status.Invalidated))
+ // TODO is this the right way to error out?
+ Barrier.this.tryFailure(new Timeout(command.txnId(), command.homeKey()));
+
+ }
+
+ @Override
+ public PreLoadContext listenerPreLoadContext(TxnId caller)
+ {
+ // TODO Surely the command passed to `onChange` is loaded?
+ return EMPTY_PRELOADCONTEXT;
+ }
+
+ @Override
+ public boolean isTransient()
+ {
+ return true;
+ }
+ }
+
+ private ExistingTransactionCheck checkForExistingTransaction()
+ {
+ // TODO this could execute at several different command stores and register multiple command listeners
+ // Won't harm correctness, but maybe wasteful?
+ ExistingTransactionCheck check = new ExistingTransactionCheck();
+ node.commandStores().mapReduceConsume(
+ contextFor(keyOrRange.asKey()),
+ keyOrRange.asKey().toUnseekable(),
+ minEpoch,
+ Long.MAX_VALUE,
+ check);
+ return check;
+ }
+
+ // Hold result of looking for a transaction to act as a barrier for an Epoch
+ static class BarrierTxn
+ {
+ @Nonnull
+ public final TxnId txnId;
+ @Nonnull
+ public final Timestamp executeAt;
+ @Nonnull
+ public final Status status;
+ public BarrierTxn(@Nonnull TxnId txnId, @Nonnull Timestamp executeAt, @Nonnull Status status)
+ {
+ this.txnId = txnId;
+ this.executeAt = executeAt;
+ this.status = status;
+ }
+
+ public BarrierTxn max(BarrierTxn other)
+ {
+ if (other == null)
+ return this;
+ return status.compareTo(other.status) >= 0 ? this : other;
+ }
+ }
+
+ /*
+ * Check for an existing transaction that is either already Applied (dependencies were applied)
+ * or PreApplied (outcome fixed, dependencies not yet applied).
+ *
+ * For Applied we can return success immediately with the executeAt epoch. For PreApplied we can add
+ * a listener for when it transitions to Applied and then return success.
+ */
+ class ExistingTransactionCheck extends AsyncResults.SettableResult<BarrierTxn> implements MapReduceConsume<SafeCommandStore, BarrierTxn>
+ {
+ @Override
+ public BarrierTxn apply(SafeCommandStore safeStore)
+ {
+ // TODO Is this going to find the correct command store to listen for transaction progress?
+ BarrierTxn found = safeStore.mapReduceWithTerminate(
+ seekables,
+ safeStore.ranges().since(minEpoch),
+ // Can I use any transaction, optimally I could wait on a sync point just created as part of transaction initiation
+ // so we can overlap the accord sync point with sending the prepare/reads for Paxos
+ TestKind.Any,
+ TestTimestamp.EXECUTES_AFTER,
+ TxnId.minForEpoch(minEpoch),
+ TestDep.ANY_DEPS,
+ null,
+ // TODO is PreApplied right? It's the first OutcomeKnown state, but why not Committed?
+ Status.PreApplied,
+ Status.Applied,
+ (keyOrRange, txnId, executeAt, status, barrierTxn) -> new BarrierTxn(txnId, executeAt, status),
+ null,
+ // Take the first one we find, and call it good enough to wait on
+ barrierTxn -> true);
+ // It's not applied so add a listener to find out when it is applied
+ if (found != null && !found.status.equals(Status.Applied))
+ {
+ // TODO Should this lean harder into AsyncChain and not call begin?
+ safeStore.commandStore().execute(PreLoadContext.contextFor(found.txnId), safeStoreWithTxn -> safeStoreWithTxn.command(found.txnId).addListener(new BarrierCommandListener())).begin(node.agent());
+ }
+ return found;
+ }
+
+ @Override
+ public BarrierTxn reduce(BarrierTxn o1, BarrierTxn o2)
+ {
+ return o1 != null && o1.status.compareTo(o2.status) >= 0 ? o1 : o2;
Review Comment:
I it would be an error if multiple command stores owned the same key for the same epoch, especially if one was null. It would break it's barrier contract wouldn't it?
##########
accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 accord.coordinate;
+
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.local.Node;
+import accord.messages.Apply;
+import accord.messages.PreAccept.PreAcceptOk;
+import accord.primitives.Ballot;
+import accord.primitives.Deps;
+import accord.primitives.FullRoute;
+import accord.primitives.Seekables;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.Txn;
+import accord.primitives.Txn.Kind;
+import accord.primitives.TxnId;
+
+import static accord.coordinate.Propose.Invalidate.proposeAndCommitInvalidate;
+import static accord.primitives.Timestamp.mergeMax;
+import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
+import static accord.utils.Functions.foldl;
+import static accord.utils.Invariants.checkArgument;
+
+/**
+ * Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
+ * If we are preempted by a recovery coordinator, we abort and let them complete (and notify us about the execution result)
+ *
+ * TODO (desired, testing): dedicated burn test to validate outcomes
+ */
+public class CoordinateSyncPoint extends CoordinatePreAccept<SyncPoint>
+{
+ private static final Logger logger = LoggerFactory.getLogger(CoordinateSyncPoint.class);
+
+ // Whether to wait on the dependencies applying globally before returning a result
+ private final boolean async;
+
+ private CoordinateSyncPoint(Node node, TxnId txnId, Txn txn, FullRoute<?> route, boolean async)
+ {
+ super(node, txnId, txn, route);
+ checkArgument(txnId.rw() == Kind.SyncPoint || async, "Exclusive sync points only support async application");
+ this.async = async;
+ }
+
+ public static CoordinateSyncPoint exclusive(Node node, Seekables<?, ?> keysOrRanges)
+ {
+ return coordinate(ExclusiveSyncPoint, node, keysOrRanges, true);
+ }
+
+ public static CoordinateSyncPoint inclusive(Node node, Seekables<?, ?> keysOrRanges, boolean async)
+ {
+ return coordinate(Kind.SyncPoint, node, keysOrRanges, async);
+ }
+
+ private static CoordinateSyncPoint coordinate(Kind kind, Node node, Seekables<?, ?> keysOrRanges, boolean async)
+ {
+ TxnId txnId = node.nextTxnId(kind, keysOrRanges.domain());
+ FullRoute<?> route = node.computeRoute(txnId, keysOrRanges);
+ CoordinateSyncPoint coordinate = new CoordinateSyncPoint(node, txnId, node.agent().emptyTxn(kind, keysOrRanges), route, async);
+ coordinate.start();
+ return coordinate;
+ }
+
+ void onPreAccepted(List<PreAcceptOk> successes)
+ {
+ Deps deps = Deps.merge(successes, ok -> ok.deps);
+ Timestamp executeAt = foldl(successes, (ok, prev) -> mergeMax(ok.witnessedAt, prev), Timestamp.NONE);
+ if (executeAt.isRejected())
+ {
+ proposeAndCommitInvalidate(node, Ballot.ZERO, txnId, route.homeKey(), route, executeAt, this);
+ }
+ else
+ {
+ // SyncPoint transactions always propose their own txnId as their executeAt, as they are not really executed.
+ // They only create happens-after relationships wrt their dependencies, which represent all transactions
+ // that *may* execute before their txnId, so once these dependencies apply we can say that any action that
+ // awaits these dependencies applies after them. In the case of ExclusiveSyncPoint, we additionally guarantee
+ // that no lower TxnId can later apply.
+ new Propose<SyncPoint>(node, tracker.topologies(), Ballot.ZERO, txnId, txn, route, deps, txnId, this)
Review Comment:
can we add a static `Propose.propose` method instead of calling the Propose ctor directly?
##########
accord-core/src/main/java/accord/local/SafeCommandStore.java:
##########
@@ -76,13 +87,65 @@ default void addAndInvokeListener(TxnId txnId, TxnId listenerId)
EXECUTES_AFTER
}
enum TestDep { WITH, WITHOUT, ANY_DEPS }
- enum TestKind { Ws, RorWs }
+ enum TestKind implements Predicate<Kind>
+ {
+ Ws, RorWs, WsOrSyncPoint, SyncPoints, Any;
+
+ public boolean test(Kind kind)
+ {
+ switch (this)
+ {
+ default: throw new AssertionError();
+ case Any: return true;
+ case WsOrSyncPoint: return kind == Write || kind == Kind.SyncPoint || kind == ExclusiveSyncPoint;
+ case SyncPoints: return kind == Kind.SyncPoint || kind == ExclusiveSyncPoint;
+ case Ws: return kind == Write;
+ case RorWs: return kind == Read || kind == Write;
+ }
+ }
+
+ public static TestKind conflicts(Kind kind)
Review Comment:
correct usage of `conflicts` and `shouldHaveWitnessed` was confusing. Let's either improve method names or add comment (or both) indicating that `conflicts` determine which txns should be takes as deps for the given kind, and that `shouldHaveWitnessed` determines which types of txns should have taken the given kind as a dependency.
##########
accord-core/src/main/java/accord/messages/BeginRecovery.java:
##########
@@ -128,10 +136,13 @@ public RecoverReply apply(SafeCommandStore safeStore)
earlierAcceptedNoWitness = acceptedStartedBeforeWithoutWitnessing(safeStore, txnId, ranges, partialTxn.keys());
}
+ Status status = command.status();
+ Ballot accepted = command.accepted();
+ Timestamp executeAt = command.executeAt();
+ PartialDeps acceptedDeps = status.phase.compareTo(Phase.Accept) >= 0 ? deps : PartialDeps.NONE;
Review Comment:
could we only include acceptedDeps for operations that propose deps?
##########
accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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 accord.coordinate;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.BiConsumer;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.coordinate.tracking.FastPathTracker;
+import accord.coordinate.tracking.RequestStatus;
+import accord.local.Node;
+import accord.local.Node.Id;
+import accord.messages.Callback;
+import accord.messages.PreAccept;
+import accord.messages.PreAccept.PreAcceptOk;
+import accord.messages.PreAccept.PreAcceptReply;
+import accord.primitives.FullRoute;
+import accord.primitives.Txn;
+import accord.primitives.TxnId;
+import accord.topology.Topologies;
+import accord.utils.async.AsyncResults;
+
+import static accord.utils.Invariants.checkState;
+
+/**
+ * Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
+ * If we are preempted by a recovery coordinator, we abort and let them complete (and notify us about the execution result)
+ *
+ * TODO (desired, testing): dedicated burn test to validate outcomes
+ */
+abstract class CoordinatePreAccept<T> extends AsyncResults.SettableResult<T> implements Callback<PreAcceptReply>, BiConsumer<T, Throwable>
+{
+ private static final Logger logger = LoggerFactory.getLogger(CoordinatePreAccept.class);
Review Comment:
unused
##########
accord-core/src/main/java/accord/coordinate/Barrier.java:
##########
@@ -0,0 +1,301 @@
+/*
+ * 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 accord.coordinate;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.BarrierType;
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandListener;
+import accord.local.Node;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommand;
+import accord.local.SafeCommandStore;
+import accord.local.SafeCommandStore.TestDep;
+import accord.local.SafeCommandStore.TestKind;
+import accord.local.SafeCommandStore.TestTimestamp;
+import accord.local.Status;
+import accord.primitives.Keys;
+import accord.primitives.Ranges;
+import accord.primitives.Routable.Domain;
+import accord.primitives.Seekable;
+import accord.primitives.Seekables;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.MapReduceConsume;
+import accord.utils.async.AsyncResults;
+import javax.annotation.Nonnull;
+
+import static accord.local.PreLoadContext.EMPTY_PRELOADCONTEXT;
+import static accord.local.PreLoadContext.contextFor;
+import static accord.utils.Invariants.checkArgument;
+
+/**
+ * Local or global barriers that return a result once all transactions have their side effects visible.
+ *
+ * For local barriers the epoch is the only guarantee, but for global barriers a new transaction is created so it will
+ * be as of the timestamp of the created transaction.
+ *
+ * Note that reads might still order after, but side effect bearing transactions should not.
+ */
+public class Barrier extends AsyncResults.SettableResult<Timestamp>
+{
+ private static final Logger logger = LoggerFactory.getLogger(Barrier.class);
+
+ private final Node node;
+ private final Seekable keyOrRange;
+
+ private final Seekables<?, ?> seekables;
+
+ private final long minEpoch;
+ private final BarrierType barrierType;
+
+ @VisibleForTesting
+ CoordinateSyncPoint coordinateSyncPoint;
+ @VisibleForTesting
+ ExistingTransactionCheck existingTransactionCheck;
+
+ Barrier(Node node, Seekable keyOrRange, long minEpoch, BarrierType barrierType)
+ {
+ checkArgument(keyOrRange.domain() == Domain.Key || barrierType.global, "Ranges are only supported with global barriers");
+ this.node = node;
+ this.minEpoch = minEpoch;
+ this.keyOrRange = keyOrRange;
+ this.seekables = keyOrRange.domain() == Domain.Key ? Keys.of(keyOrRange.asKey()) : Ranges.of(keyOrRange.asRange());
+ this.barrierType = barrierType;
+ }
+
+ public static Barrier barrier(Node node, Seekable keyOrRange, long minEpoch, BarrierType barrierType)
+ {
+ Barrier barrier = new Barrier(node, keyOrRange, minEpoch, barrierType);
+ barrier.start();
+ return barrier;
+ }
+
+ private void start()
+ {
+ // It may be possible to use local state to determine that the barrier is already satisfied or
+ // there is an existing transaction we can wait on
+ if (keyOrRange.domain().isKey() && !barrierType.global)
+ {
+ existingTransactionCheck = checkForExistingTransaction();
+ existingTransactionCheck.addCallback((barrierTxn, existingTransactionCheckFailure) -> {
+ if (existingTransactionCheckFailure != null)
+ {
+ Barrier.this.tryFailure(existingTransactionCheckFailure);
+ return;
+ }
+
+ if (barrierTxn != null)
+ {
+ if (barrierTxn.status.equals(Status.Applied))
+ {
+ doBarrierSuccess(barrierTxn.executeAt);
+ }
+ // A listener was added to the transaction already
+ }
+ else
+ {
+ createSyncPoint();
+ }
+ });
+ }
+ else
+ {
+ createSyncPoint();
+ }
+ }
+
+ private void doBarrierSuccess(Timestamp executeAt)
+ {
+ // The transaction we wait on might have more keys, but it's not
+ // guaranteed they were wanted and we don't want to force the agent to filter them
+ // so provide the seekables we were given.
+ // We also don't notify the agent for range barriers since that makes sense as a local concept
+ // since ranges can easily span multiple nodes
+ if (seekables != null)
+ node.agent().onLocalBarrier(seekables, executeAt);
+ Barrier.this.trySuccess(executeAt);
+ }
+
+ private void createSyncPoint()
+ {
+ coordinateSyncPoint = CoordinateSyncPoint.inclusive(node, Seekables.of(keyOrRange), barrierType.async);
+ coordinateSyncPoint.addCallback((syncPoint, syncPointFailure) -> {
+ if (syncPointFailure != null)
+ {
+ Barrier.this.tryFailure(syncPointFailure);
+ return;
+ }
+
+ // Need to wait for the local transaction to finish since coordinate sync point won't wait on anything
+ // if async was requested or there were no deps found
+ if (syncPoint.finishedAsync)
+ {
+ TxnId txnId = syncPoint.txnId;
+ long epoch = txnId.epoch();
+ RoutingKey homeKey = syncPoint.homeKey;
+ node.commandStores().ifLocal(PreLoadContext.contextFor(syncPoint.txnId), homeKey, epoch, epoch, safeStore -> {
+ CommandListener listener = new BarrierCommandListener();
+ SafeCommand safeCommand = safeStore.command(txnId);
+ listener.onChange(safeStore, safeCommand);
+ if (!isDone())
+ safeCommand.addListener(listener);
+ }).begin(node.agent());
+ }
+ else
+ {
+ doBarrierSuccess(syncPoint.txnId);
+ }
+ });
+ }
+
+ private class BarrierCommandListener implements CommandListener
+ {
+ @Override
+ public void onChange(SafeCommandStore safeStore, SafeCommand safeCommand)
+ {
+ Command command = safeCommand.current();
+ if (command.is(Status.Applied))
+ {
+ Timestamp executeAt = command.executeAt();
+ // In all the cases where we add a listener (listening to existing command, async completion of CoordinateSyncPoint)
+ // we want to notify the agent
+ doBarrierSuccess(executeAt);
+ }
+ else if (command.is(Status.Invalidated))
+ // TODO is this the right way to error out?
+ Barrier.this.tryFailure(new Timeout(command.txnId(), command.homeKey()));
Review Comment:
> TODO is this the right way to error out?
yes / good enough
##########
accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 accord.coordinate;
+
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.local.Node;
+import accord.messages.Apply;
+import accord.messages.PreAccept.PreAcceptOk;
+import accord.primitives.Ballot;
+import accord.primitives.Deps;
+import accord.primitives.FullRoute;
+import accord.primitives.Seekables;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.Txn;
+import accord.primitives.Txn.Kind;
+import accord.primitives.TxnId;
+
+import static accord.coordinate.Propose.Invalidate.proposeAndCommitInvalidate;
+import static accord.primitives.Timestamp.mergeMax;
+import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
+import static accord.utils.Functions.foldl;
+import static accord.utils.Invariants.checkArgument;
+
+/**
+ * Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
+ * If we are preempted by a recovery coordinator, we abort and let them complete (and notify us about the execution result)
+ *
+ * TODO (desired, testing): dedicated burn test to validate outcomes
+ */
+public class CoordinateSyncPoint extends CoordinatePreAccept<SyncPoint>
+{
+ private static final Logger logger = LoggerFactory.getLogger(CoordinateSyncPoint.class);
Review Comment:
unused
##########
accord-core/src/main/java/accord/utils/Functions.java:
##########
@@ -57,4 +57,12 @@ public static <I, O> O mapReduceNonNull(Function<I, O> map, BiFunction<O, O, O>
return result;
}
+ public static <I, O> O foldl(List<I> list, BiFunction<I, O, O> foldl, O zero)
Review Comment:
could you rename `zero` to `identity` or `initial` or something, since this isn't strictly numerical?
##########
accord-core/src/main/java/accord/coordinate/Barrier.java:
##########
@@ -0,0 +1,301 @@
+/*
+ * 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 accord.coordinate;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.BarrierType;
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandListener;
+import accord.local.Node;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommand;
+import accord.local.SafeCommandStore;
+import accord.local.SafeCommandStore.TestDep;
+import accord.local.SafeCommandStore.TestKind;
+import accord.local.SafeCommandStore.TestTimestamp;
+import accord.local.Status;
+import accord.primitives.Keys;
+import accord.primitives.Ranges;
+import accord.primitives.Routable.Domain;
+import accord.primitives.Seekable;
+import accord.primitives.Seekables;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.MapReduceConsume;
+import accord.utils.async.AsyncResults;
+import javax.annotation.Nonnull;
+
+import static accord.local.PreLoadContext.EMPTY_PRELOADCONTEXT;
+import static accord.local.PreLoadContext.contextFor;
+import static accord.utils.Invariants.checkArgument;
+
+/**
+ * Local or global barriers that return a result once all transactions have their side effects visible.
+ *
+ * For local barriers the epoch is the only guarantee, but for global barriers a new transaction is created so it will
+ * be as of the timestamp of the created transaction.
+ *
+ * Note that reads might still order after, but side effect bearing transactions should not.
+ */
+public class Barrier extends AsyncResults.SettableResult<Timestamp>
Review Comment:
Could we make `AsyncResults.AbstractResult#trySetResult` protected and extend that class, so setResult/setFailure aren't visible to anyone interacting w/ Barrier?
##########
accord-core/src/main/java/accord/coordinate/Barrier.java:
##########
@@ -0,0 +1,301 @@
+/*
+ * 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 accord.coordinate;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.BarrierType;
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandListener;
+import accord.local.Node;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommand;
+import accord.local.SafeCommandStore;
+import accord.local.SafeCommandStore.TestDep;
+import accord.local.SafeCommandStore.TestKind;
+import accord.local.SafeCommandStore.TestTimestamp;
+import accord.local.Status;
+import accord.primitives.Keys;
+import accord.primitives.Ranges;
+import accord.primitives.Routable.Domain;
+import accord.primitives.Seekable;
+import accord.primitives.Seekables;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.MapReduceConsume;
+import accord.utils.async.AsyncResults;
+import javax.annotation.Nonnull;
+
+import static accord.local.PreLoadContext.EMPTY_PRELOADCONTEXT;
+import static accord.local.PreLoadContext.contextFor;
+import static accord.utils.Invariants.checkArgument;
+
+/**
+ * Local or global barriers that return a result once all transactions have their side effects visible.
+ *
+ * For local barriers the epoch is the only guarantee, but for global barriers a new transaction is created so it will
+ * be as of the timestamp of the created transaction.
+ *
+ * Note that reads might still order after, but side effect bearing transactions should not.
+ */
+public class Barrier extends AsyncResults.SettableResult<Timestamp>
+{
+ private static final Logger logger = LoggerFactory.getLogger(Barrier.class);
+
+ private final Node node;
+ private final Seekable keyOrRange;
+
+ private final Seekables<?, ?> seekables;
+
+ private final long minEpoch;
+ private final BarrierType barrierType;
+
+ @VisibleForTesting
+ CoordinateSyncPoint coordinateSyncPoint;
+ @VisibleForTesting
+ ExistingTransactionCheck existingTransactionCheck;
+
+ Barrier(Node node, Seekable keyOrRange, long minEpoch, BarrierType barrierType)
+ {
+ checkArgument(keyOrRange.domain() == Domain.Key || barrierType.global, "Ranges are only supported with global barriers");
+ this.node = node;
+ this.minEpoch = minEpoch;
+ this.keyOrRange = keyOrRange;
+ this.seekables = keyOrRange.domain() == Domain.Key ? Keys.of(keyOrRange.asKey()) : Ranges.of(keyOrRange.asRange());
+ this.barrierType = barrierType;
+ }
+
+ public static Barrier barrier(Node node, Seekable keyOrRange, long minEpoch, BarrierType barrierType)
+ {
+ Barrier barrier = new Barrier(node, keyOrRange, minEpoch, barrierType);
+ barrier.start();
+ return barrier;
+ }
+
+ private void start()
+ {
+ // It may be possible to use local state to determine that the barrier is already satisfied or
+ // there is an existing transaction we can wait on
+ if (keyOrRange.domain().isKey() && !barrierType.global)
+ {
+ existingTransactionCheck = checkForExistingTransaction();
+ existingTransactionCheck.addCallback((barrierTxn, existingTransactionCheckFailure) -> {
+ if (existingTransactionCheckFailure != null)
+ {
+ Barrier.this.tryFailure(existingTransactionCheckFailure);
+ return;
+ }
+
+ if (barrierTxn != null)
+ {
+ if (barrierTxn.status.equals(Status.Applied))
+ {
+ doBarrierSuccess(barrierTxn.executeAt);
+ }
+ // A listener was added to the transaction already
+ }
+ else
+ {
+ createSyncPoint();
+ }
+ });
+ }
+ else
+ {
+ createSyncPoint();
+ }
+ }
+
+ private void doBarrierSuccess(Timestamp executeAt)
+ {
+ // The transaction we wait on might have more keys, but it's not
+ // guaranteed they were wanted and we don't want to force the agent to filter them
+ // so provide the seekables we were given.
+ // We also don't notify the agent for range barriers since that makes sense as a local concept
+ // since ranges can easily span multiple nodes
+ if (seekables != null)
+ node.agent().onLocalBarrier(seekables, executeAt);
+ Barrier.this.trySuccess(executeAt);
+ }
+
+ private void createSyncPoint()
+ {
+ coordinateSyncPoint = CoordinateSyncPoint.inclusive(node, Seekables.of(keyOrRange), barrierType.async);
+ coordinateSyncPoint.addCallback((syncPoint, syncPointFailure) -> {
+ if (syncPointFailure != null)
+ {
+ Barrier.this.tryFailure(syncPointFailure);
+ return;
+ }
+
+ // Need to wait for the local transaction to finish since coordinate sync point won't wait on anything
+ // if async was requested or there were no deps found
+ if (syncPoint.finishedAsync)
+ {
+ TxnId txnId = syncPoint.txnId;
+ long epoch = txnId.epoch();
+ RoutingKey homeKey = syncPoint.homeKey;
+ node.commandStores().ifLocal(PreLoadContext.contextFor(syncPoint.txnId), homeKey, epoch, epoch, safeStore -> {
+ CommandListener listener = new BarrierCommandListener();
+ SafeCommand safeCommand = safeStore.command(txnId);
+ listener.onChange(safeStore, safeCommand);
+ if (!isDone())
+ safeCommand.addListener(listener);
+ }).begin(node.agent());
+ }
+ else
+ {
+ doBarrierSuccess(syncPoint.txnId);
+ }
+ });
+ }
+
+ private class BarrierCommandListener implements CommandListener
+ {
+ @Override
+ public void onChange(SafeCommandStore safeStore, SafeCommand safeCommand)
+ {
+ Command command = safeCommand.current();
+ if (command.is(Status.Applied))
+ {
+ Timestamp executeAt = command.executeAt();
+ // In all the cases where we add a listener (listening to existing command, async completion of CoordinateSyncPoint)
+ // we want to notify the agent
+ doBarrierSuccess(executeAt);
+ }
+ else if (command.is(Status.Invalidated))
+ // TODO is this the right way to error out?
+ Barrier.this.tryFailure(new Timeout(command.txnId(), command.homeKey()));
+
+ }
+
+ @Override
+ public PreLoadContext listenerPreLoadContext(TxnId caller)
+ {
+ // TODO Surely the command passed to `onChange` is loaded?
+ return EMPTY_PRELOADCONTEXT;
+ }
+
+ @Override
+ public boolean isTransient()
+ {
+ return true;
+ }
+ }
+
+ private ExistingTransactionCheck checkForExistingTransaction()
+ {
+ // TODO this could execute at several different command stores and register multiple command listeners
+ // Won't harm correctness, but maybe wasteful?
+ ExistingTransactionCheck check = new ExistingTransactionCheck();
+ node.commandStores().mapReduceConsume(
+ contextFor(keyOrRange.asKey()),
+ keyOrRange.asKey().toUnseekable(),
+ minEpoch,
+ Long.MAX_VALUE,
+ check);
+ return check;
+ }
+
+ // Hold result of looking for a transaction to act as a barrier for an Epoch
+ static class BarrierTxn
+ {
+ @Nonnull
+ public final TxnId txnId;
+ @Nonnull
+ public final Timestamp executeAt;
+ @Nonnull
+ public final Status status;
+ public BarrierTxn(@Nonnull TxnId txnId, @Nonnull Timestamp executeAt, @Nonnull Status status)
+ {
+ this.txnId = txnId;
+ this.executeAt = executeAt;
+ this.status = status;
+ }
+
+ public BarrierTxn max(BarrierTxn other)
+ {
+ if (other == null)
+ return this;
+ return status.compareTo(other.status) >= 0 ? this : other;
+ }
+ }
+
+ /*
+ * Check for an existing transaction that is either already Applied (dependencies were applied)
+ * or PreApplied (outcome fixed, dependencies not yet applied).
+ *
+ * For Applied we can return success immediately with the executeAt epoch. For PreApplied we can add
+ * a listener for when it transitions to Applied and then return success.
+ */
+ class ExistingTransactionCheck extends AsyncResults.SettableResult<BarrierTxn> implements MapReduceConsume<SafeCommandStore, BarrierTxn>
+ {
+ @Override
+ public BarrierTxn apply(SafeCommandStore safeStore)
+ {
+ // TODO Is this going to find the correct command store to listen for transaction progress?
+ BarrierTxn found = safeStore.mapReduceWithTerminate(
Review Comment:
there are a lot of TODOs still here indicating you're not confident in its correctness?
##########
accord-core/src/main/java/accord/coordinate/Barrier.java:
##########
@@ -0,0 +1,301 @@
+/*
+ * 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 accord.coordinate;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.BarrierType;
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandListener;
+import accord.local.Node;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommand;
+import accord.local.SafeCommandStore;
+import accord.local.SafeCommandStore.TestDep;
+import accord.local.SafeCommandStore.TestKind;
+import accord.local.SafeCommandStore.TestTimestamp;
+import accord.local.Status;
+import accord.primitives.Keys;
+import accord.primitives.Ranges;
+import accord.primitives.Routable.Domain;
+import accord.primitives.Seekable;
+import accord.primitives.Seekables;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.MapReduceConsume;
+import accord.utils.async.AsyncResults;
+import javax.annotation.Nonnull;
+
+import static accord.local.PreLoadContext.EMPTY_PRELOADCONTEXT;
+import static accord.local.PreLoadContext.contextFor;
+import static accord.utils.Invariants.checkArgument;
+
+/**
+ * Local or global barriers that return a result once all transactions have their side effects visible.
+ *
+ * For local barriers the epoch is the only guarantee, but for global barriers a new transaction is created so it will
+ * be as of the timestamp of the created transaction.
+ *
+ * Note that reads might still order after, but side effect bearing transactions should not.
+ */
+public class Barrier extends AsyncResults.SettableResult<Timestamp>
+{
+ private static final Logger logger = LoggerFactory.getLogger(Barrier.class);
+
+ private final Node node;
+ private final Seekable keyOrRange;
+
+ private final Seekables<?, ?> seekables;
+
+ private final long minEpoch;
+ private final BarrierType barrierType;
+
+ @VisibleForTesting
+ CoordinateSyncPoint coordinateSyncPoint;
+ @VisibleForTesting
+ ExistingTransactionCheck existingTransactionCheck;
+
+ Barrier(Node node, Seekable keyOrRange, long minEpoch, BarrierType barrierType)
+ {
+ checkArgument(keyOrRange.domain() == Domain.Key || barrierType.global, "Ranges are only supported with global barriers");
+ this.node = node;
+ this.minEpoch = minEpoch;
+ this.keyOrRange = keyOrRange;
+ this.seekables = keyOrRange.domain() == Domain.Key ? Keys.of(keyOrRange.asKey()) : Ranges.of(keyOrRange.asRange());
+ this.barrierType = barrierType;
+ }
+
+ public static Barrier barrier(Node node, Seekable keyOrRange, long minEpoch, BarrierType barrierType)
+ {
+ Barrier barrier = new Barrier(node, keyOrRange, minEpoch, barrierType);
+ barrier.start();
+ return barrier;
+ }
+
+ private void start()
+ {
+ // It may be possible to use local state to determine that the barrier is already satisfied or
+ // there is an existing transaction we can wait on
+ if (keyOrRange.domain().isKey() && !barrierType.global)
+ {
+ existingTransactionCheck = checkForExistingTransaction();
+ existingTransactionCheck.addCallback((barrierTxn, existingTransactionCheckFailure) -> {
+ if (existingTransactionCheckFailure != null)
+ {
+ Barrier.this.tryFailure(existingTransactionCheckFailure);
+ return;
+ }
+
+ if (barrierTxn != null)
+ {
+ if (barrierTxn.status.equals(Status.Applied))
+ {
+ doBarrierSuccess(barrierTxn.executeAt);
+ }
+ // A listener was added to the transaction already
+ }
+ else
+ {
+ createSyncPoint();
+ }
+ });
+ }
+ else
+ {
+ createSyncPoint();
+ }
+ }
+
+ private void doBarrierSuccess(Timestamp executeAt)
+ {
+ // The transaction we wait on might have more keys, but it's not
+ // guaranteed they were wanted and we don't want to force the agent to filter them
+ // so provide the seekables we were given.
+ // We also don't notify the agent for range barriers since that makes sense as a local concept
+ // since ranges can easily span multiple nodes
+ if (seekables != null)
+ node.agent().onLocalBarrier(seekables, executeAt);
+ Barrier.this.trySuccess(executeAt);
+ }
+
+ private void createSyncPoint()
+ {
+ coordinateSyncPoint = CoordinateSyncPoint.inclusive(node, Seekables.of(keyOrRange), barrierType.async);
+ coordinateSyncPoint.addCallback((syncPoint, syncPointFailure) -> {
+ if (syncPointFailure != null)
+ {
+ Barrier.this.tryFailure(syncPointFailure);
+ return;
+ }
+
+ // Need to wait for the local transaction to finish since coordinate sync point won't wait on anything
+ // if async was requested or there were no deps found
+ if (syncPoint.finishedAsync)
+ {
+ TxnId txnId = syncPoint.txnId;
+ long epoch = txnId.epoch();
+ RoutingKey homeKey = syncPoint.homeKey;
+ node.commandStores().ifLocal(PreLoadContext.contextFor(syncPoint.txnId), homeKey, epoch, epoch, safeStore -> {
+ CommandListener listener = new BarrierCommandListener();
+ SafeCommand safeCommand = safeStore.command(txnId);
+ listener.onChange(safeStore, safeCommand);
+ if (!isDone())
+ safeCommand.addListener(listener);
+ }).begin(node.agent());
+ }
+ else
+ {
+ doBarrierSuccess(syncPoint.txnId);
+ }
+ });
+ }
+
+ private class BarrierCommandListener implements CommandListener
+ {
+ @Override
+ public void onChange(SafeCommandStore safeStore, SafeCommand safeCommand)
+ {
+ Command command = safeCommand.current();
+ if (command.is(Status.Applied))
+ {
+ Timestamp executeAt = command.executeAt();
+ // In all the cases where we add a listener (listening to existing command, async completion of CoordinateSyncPoint)
+ // we want to notify the agent
+ doBarrierSuccess(executeAt);
+ }
+ else if (command.is(Status.Invalidated))
+ // TODO is this the right way to error out?
+ Barrier.this.tryFailure(new Timeout(command.txnId(), command.homeKey()));
+
+ }
+
+ @Override
+ public PreLoadContext listenerPreLoadContext(TxnId caller)
+ {
+ // TODO Surely the command passed to `onChange` is loaded?
+ return EMPTY_PRELOADCONTEXT;
Review Comment:
that's not guaranteed, it's possible that it was evicted in the time between the listener update being scheduled and being executed. Anyway, it needs to be in context or safeStore will complain
##########
accord-core/src/main/java/accord/impl/InMemoryCommandStore.java:
##########
@@ -359,6 +399,37 @@ public void completeOperation(SafeCommandStore store)
}
}
+ public void setRejectBefore(ReducingRangeMap<Timestamp> newRejectBefore)
+ {
+ this.rejectBefore = newRejectBefore;
+ }
+
+ @Override
+ public Timestamp preaccept(TxnId txnId, Seekables<?, ?> keys, SafeCommandStore safeStore)
Review Comment:
can some of this logic be moved into `CommandStore`? A lot of it seems easily generalizable and important for correctness.
##########
accord-core/src/main/java/accord/topology/Topologies.java:
##########
@@ -18,20 +18,28 @@
package accord.topology;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import com.google.common.collect.Sets;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import accord.api.TopologySorter;
import accord.local.Node;
import accord.local.Node.Id;
import accord.primitives.Ranges;
import accord.utils.IndexedConsumer;
-import com.google.common.collect.Sets;
import accord.utils.Invariants;
-import java.util.*;
-
// TODO (desired, efficiency/clarity): since Topologies are rarely needed, should optimise API for single topology case
// (e.g. at least implementing Topologies by Topology)
public interface Topologies extends TopologySorter
{
+ Logger logger = LoggerFactory.getLogger(Topologies.class);
Review Comment:
unused
##########
accord-core/src/main/java/accord/coordinate/Recover.java:
##########
@@ -210,56 +211,70 @@ private void recover()
{
default: throw new IllegalStateException();
case Invalidated:
+ {
commitInvalidate();
return;
+ }
case Applied:
case PreApplied:
- // TODO (desired, efficiency): in some cases we can use the deps we already have (e.g. if we have a quorum of Committed responses)
- node.withEpoch(executeAt.epoch(), () -> {
- CollectDeps.withDeps(node, txnId, route, txn, acceptOrCommit.executeAt, (deps, fail) -> {
- if (fail != null)
- {
- accept(null, fail);
- }
- else
- {
- // TODO (required, consider): when writes/result are partially replicated, need to confirm we have quorum of these
- Persist.persistAndCommit(node, txnId, route, txn, executeAt, deps, acceptOrCommit.writes, acceptOrCommit.result);
- accept(acceptOrCommit.result, null);
- }
- });
- });
+ {
+ // must have gone through Accepted, so we must have witnessed >= Accepted for each shard
+ Deps acceptedDeps = tryMergeAcceptedDeps();
+ Invariants.checkState(acceptedDeps != null);
+ // TODO (required, consider): when writes/result are partially replicated, need to confirm we have quorum of these
+ Persist.persistAndCommit(node, txnId, route, txn, executeAt, acceptedDeps, acceptOrCommit.writes, acceptOrCommit.result);
+ accept(acceptOrCommit.result, null);
return;
+ }
case ReadyToExecute:
case PreCommitted:
case Committed:
+ {
+ Deps acceptedDeps = tryMergeAcceptedDeps(); // must have gone through Accepted, so we must have witnessed >= Accepted for each shard
+ Invariants.checkState(acceptedDeps != null);
Review Comment:
should add `mergeAcceptedDeps` for the places where we expect/require a full set to be assembled (Committed, Applied) and enforce the invariant there
##########
accord-core/src/main/java/accord/local/CommandStores.java:
##########
@@ -49,6 +55,8 @@
*/
public abstract class CommandStores<S extends CommandStore>
{
+ private static final Logger logger = LoggerFactory.getLogger(CommandStores.class);
Review Comment:
unused
##########
accord-core/src/main/java/accord/coordinate/Recover.java:
##########
@@ -210,56 +211,70 @@ private void recover()
{
default: throw new IllegalStateException();
case Invalidated:
+ {
commitInvalidate();
return;
+ }
case Applied:
case PreApplied:
- // TODO (desired, efficiency): in some cases we can use the deps we already have (e.g. if we have a quorum of Committed responses)
- node.withEpoch(executeAt.epoch(), () -> {
- CollectDeps.withDeps(node, txnId, route, txn, acceptOrCommit.executeAt, (deps, fail) -> {
- if (fail != null)
- {
- accept(null, fail);
- }
- else
- {
- // TODO (required, consider): when writes/result are partially replicated, need to confirm we have quorum of these
- Persist.persistAndCommit(node, txnId, route, txn, executeAt, deps, acceptOrCommit.writes, acceptOrCommit.result);
- accept(acceptOrCommit.result, null);
- }
- });
- });
+ {
+ // must have gone through Accepted, so we must have witnessed >= Accepted for each shard
Review Comment:
I don't think this assumption holds. In the case of a fast path commit, it's possible to jump straight to commit/execute/apply, and if some shards have missed that message and others haven't, you'll have a high status that is accepted, but have missing keys in your accepted deps because some shards are still only preaccepted. Since sync points always run an accept phase, I think this would be safe for them, but you'd still need to run CollectDeps for normal txns
##########
accord-core/src/main/java/accord/local/SafeCommandStore.java:
##########
@@ -76,13 +87,65 @@ default void addAndInvokeListener(TxnId txnId, TxnId listenerId)
EXECUTES_AFTER
}
enum TestDep { WITH, WITHOUT, ANY_DEPS }
- enum TestKind { Ws, RorWs }
+ enum TestKind implements Predicate<Kind>
+ {
+ Ws, RorWs, WsOrSyncPoint, SyncPoints, Any;
Review Comment:
With usage mostly contained in its own methods, let's expand Rs & Ws into Reads and Writes since it's slightly easier to read.
##########
accord-core/src/main/java/accord/local/Status.java:
##########
@@ -422,4 +422,9 @@ public static Status max(Status a, Ballot acceptedA, Status b, Ballot acceptedB)
{
return max(a, a, acceptedA, b, b, acceptedB);
}
+
+ public boolean isTerminal()
Review Comment:
unused
##########
accord-core/src/main/java/accord/messages/PreAccept.java:
##########
@@ -35,12 +38,16 @@
import accord.primitives.TxnId;
import static accord.local.SafeCommandStore.TestDep.ANY_DEPS;
+import static accord.local.SafeCommandStore.TestKind.Any;
import static accord.local.SafeCommandStore.TestKind.RorWs;
import static accord.local.SafeCommandStore.TestKind.Ws;
import static accord.local.SafeCommandStore.TestTimestamp.STARTED_BEFORE;
+import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
public class PreAccept extends WithUnsynced<PreAccept.PreAcceptReply>
{
+ private static final Logger logger = LoggerFactory.getLogger(PreAccept.class);
Review Comment:
unused
##########
accord-core/src/main/java/accord/messages/Commit.java:
##########
@@ -130,6 +143,24 @@ public static void commitMinimalAndRead(Node node, Topologies executeTopologies,
}
}
+ public static void commitMinimalAndBlockOnDeps(Node node, Topologies topologies, TxnId txnId, Txn txn, FullRoute<?> route, Deps deps, Callback<ExecuteReply> callback)
+ {
+ checkArgument(topologies.size() == 1);
+ Topology topology = topologies.get(0);
+ for (Node.Id to : topology.nodes())
+ {
+ // To simplify making sure the agent is notified once and is notified before the barrier coordination
+ // returns a result; we never notify the agent on the coordinator as part of WaitForDependenciesThenApply execution
+ boolean notifyAgent = to != node.id();
Review Comment:
should be `boolean notifyAgent = !to.equals(node.id());`
##########
accord-core/src/main/java/accord/primitives/Timestamp.java:
##########
@@ -19,12 +19,22 @@
package accord.primitives;
import accord.local.Node.Id;
-import accord.utils.Invariants;
+
+import static accord.utils.Invariants.checkArgument;
import javax.annotation.Nonnull;
public class Timestamp implements Comparable<Timestamp>
{
+ private static final int REJECTED_FLAG = 0x8000;
+
+ /**
+ * The set of flags we want to retain as we merge timestamps (e.g. when taking mergeMax).
+ * Today this is only the REJECTED_FLAG, but we may include additional flags in future (such as Committed, Applied..)
+ * which we may also want to retain when merging in other contexts (such as in Deps).
+ */
+ private static final int MERGE_FLAGS = 0x8000;
Review Comment:
can you assign the value from `REJECTED_FLAG`? So in the future (with additional hypothetical flags) it would look like: `MERGED_FLAG = REJECTED_FLAG | ANOTHER_FLAG;`?
##########
accord-core/src/main/java/accord/messages/WaitForDependenciesThenApply.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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 accord.messages;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.Result;
+import accord.local.Command;
+import accord.local.CommandStore;
+import accord.local.Commands;
+import accord.local.Commands.ApplyOutcome;
+import accord.local.SafeCommandStore;
+import accord.primitives.PartialDeps;
+import accord.primitives.PartialRoute;
+import accord.primitives.Seekables;
+import accord.primitives.TxnId;
+import accord.primitives.Writes;
+
+/*
+ * Used by local and global inclusive sync points to effect the sync point at each node
+ * Combines commit, execute (with nothing really to execute), and apply into one request/response
+ */
+public class WaitForDependenciesThenApply extends WhenReadyToExecute
+{
+ private static final Logger logger = LoggerFactory.getLogger(WhenReadyToExecute.class);
+
+ @SuppressWarnings("unused")
+ public static class SerializerSupport
+ {
+ public static WaitForDependenciesThenApply create(TxnId txnId, PartialRoute<?> route, PartialDeps deps, Seekables<?, ?> partialTxnKeys, Writes writes, Result result, boolean notifyAgent)
+ {
+ return new WaitForDependenciesThenApply(txnId, route, deps, partialTxnKeys, writes, result, notifyAgent);
+ }
+ }
+
+ public final PartialRoute<?> route;
+ public final PartialDeps deps;
+ public final Writes writes;
+ public final Result result;
+ public final boolean notifyAgent;
+
+ WaitForDependenciesThenApply(TxnId txnId, PartialRoute<?> route, PartialDeps deps, Seekables<?, ?> partialTxnKeys, Writes writes, Result result, boolean notifyAgent)
+ {
+ super(txnId, partialTxnKeys, txnId.epoch(), txnId.epoch());
+ this.route = route;
+ this.deps = deps;
+ this.writes = writes;
+ this.result = result;
+ this.notifyAgent = notifyAgent;
+ }
+
+ @Override
+ protected void readyToExecute(SafeCommandStore safeStore, Command.Committed command)
+ {
+ logger.trace("{}: executing WaitForDependenciesThenApply", command.txnId());
+ CommandStore unsafeStore = safeStore.commandStore();
+ if (notifyAgent)
Review Comment:
should this also check that `txnId.proposesDeps()`?
##########
accord-core/src/main/java/accord/coordinate/Recover.java:
##########
@@ -210,56 +211,70 @@ private void recover()
{
default: throw new IllegalStateException();
case Invalidated:
+ {
commitInvalidate();
return;
+ }
case Applied:
case PreApplied:
- // TODO (desired, efficiency): in some cases we can use the deps we already have (e.g. if we have a quorum of Committed responses)
- node.withEpoch(executeAt.epoch(), () -> {
- CollectDeps.withDeps(node, txnId, route, txn, acceptOrCommit.executeAt, (deps, fail) -> {
- if (fail != null)
- {
- accept(null, fail);
- }
- else
- {
- // TODO (required, consider): when writes/result are partially replicated, need to confirm we have quorum of these
- Persist.persistAndCommit(node, txnId, route, txn, executeAt, deps, acceptOrCommit.writes, acceptOrCommit.result);
- accept(acceptOrCommit.result, null);
- }
- });
- });
+ {
+ // must have gone through Accepted, so we must have witnessed >= Accepted for each shard
+ Deps acceptedDeps = tryMergeAcceptedDeps();
+ Invariants.checkState(acceptedDeps != null);
+ // TODO (required, consider): when writes/result are partially replicated, need to confirm we have quorum of these
+ Persist.persistAndCommit(node, txnId, route, txn, executeAt, acceptedDeps, acceptOrCommit.writes, acceptOrCommit.result);
+ accept(acceptOrCommit.result, null);
return;
+ }
case ReadyToExecute:
case PreCommitted:
case Committed:
+ {
Review Comment:
`node.withEpoch(executeAt.epoch(), () ->` has been removed from the various branches of the switch statement. I think this could lead to an exception when fetching topology for the executeAt epoch if we haven't received that epoch yet.
##########
accord-core/src/main/java/accord/primitives/Timestamp.java:
##########
@@ -108,11 +118,38 @@ public int flags()
return flags(lsb);
}
+ public boolean isRejected()
+ {
+ return (lsb & REJECTED_FLAG) != 0;
+ }
+
+ public Timestamp asRejected()
+ {
+ return withExtraFlags(REJECTED_FLAG);
+ }
+
public Timestamp withEpochAtLeast(long minEpoch)
{
return minEpoch <= epoch() ? this : new Timestamp(minEpoch, hlc(), flags(), node);
}
+ public Timestamp withExtraFlags(int flags)
+ {
+ checkArgument(flags <= MAX_FLAGS);
+ long newLsb = lsb | flags;
+ if (lsb == newLsb)
+ return this;
+ return new Timestamp(msb, newLsb, node);
+ }
+
+ public Timestamp mergeFlags(Timestamp mergeFlags)
Review Comment:
can be private
##########
accord-core/src/main/java/accord/primitives/TxnId.java:
##########
@@ -120,7 +120,7 @@ private static Domain domain(int flags)
private static int rwOrdinal(int flags)
{
- return (flags >> 1) & 1;
+ return (flags >> 1) & 3;
Review Comment:
can you replace `3` with a mask constant?
##########
accord-core/src/main/java/accord/primitives/Timestamp.java:
##########
@@ -108,11 +118,38 @@ public int flags()
return flags(lsb);
}
+ public boolean isRejected()
+ {
+ return (lsb & REJECTED_FLAG) != 0;
+ }
+
+ public Timestamp asRejected()
Review Comment:
can you add a comment noting this should only be used in `preaccept`
##########
accord-core/src/main/java/accord/primitives/Timestamp.java:
##########
@@ -108,11 +118,38 @@ public int flags()
return flags(lsb);
}
+ public boolean isRejected()
+ {
+ return (lsb & REJECTED_FLAG) != 0;
+ }
+
+ public Timestamp asRejected()
+ {
+ return withExtraFlags(REJECTED_FLAG);
+ }
+
public Timestamp withEpochAtLeast(long minEpoch)
{
return minEpoch <= epoch() ? this : new Timestamp(minEpoch, hlc(), flags(), node);
}
+ public Timestamp withExtraFlags(int flags)
Review Comment:
can be private
##########
accord-core/src/main/java/accord/primitives/TxnId.java:
##########
@@ -120,7 +120,7 @@ private static Domain domain(int flags)
private static int rwOrdinal(int flags)
Review Comment:
can you rename this (and `rw`) to `kindOrdinal` and `kind`, respectively?
##########
accord-core/src/main/java/accord/topology/TopologyManager.java:
##########
@@ -52,6 +60,8 @@
*/
public class TopologyManager implements ConfigurationService.Listener
{
+ private static final Logger logger = LoggerFactory.getLogger(TopologyManager.class);
Review Comment:
unused
--
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