You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by be...@apache.org on 2025/02/17 09:37:04 UTC
(cassandra-accord) branch trunk updated: Fix recovery when one shard is committed/stable and another is preaccepted Also fix: - Topology slicing must declare whether we share/slice node ownership (to assist above) - CFK.visit removes transitive dependencies too eagerly across epoch change - apply cleanup to builder consistently, and construct the same value we would produce by purge (so that replay is idempotent) - Invoke ExecuteTxn.LocalExecute callbacks on originating CommandStore - CFK load pruned can race with regular ca [...]
This is an automated email from the ASF dual-hosted git repository.
benedict pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra-accord.git
The following commit(s) were added to refs/heads/trunk by this push:
new 1542da5d Fix recovery when one shard is committed/stable and another is preaccepted Also fix: - Topology slicing must declare whether we share/slice node ownership (to assist above) - CFK.visit removes transitive dependencies too eagerly across epoch change - apply cleanup to builder consistently, and construct the same value we would produce by purge (so that replay is idempotent) - Invoke ExecuteTxn.LocalExecute callbacks on originating CommandStore - CFK load pruned can r [...]
1542da5d is described below
commit 1542da5d8acf08b8226227c91d4f81c64ed9762c
Author: Benedict Elliott Smith <be...@apache.org>
AuthorDate: Thu Feb 6 12:28:49 2025 +0000
Fix recovery when one shard is committed/stable and another is preaccepted
Also fix:
- Topology slicing must declare whether we share/slice node ownership (to assist above)
- CFK.visit removes transitive dependencies too eagerly across epoch change
- apply cleanup to builder consistently, and construct the same value we would produce by purge (so that replay is idempotent)
- Invoke ExecuteTxn.LocalExecute callbacks on originating CommandStore
- CFK load pruned can race with regular callback; both should invoke callback to test if potentially pruned (whether or not isLoadingPruned)
- misc other minor issues
patch by Benedict; reviewed by Alex Petrov for CASSANDRA-20325
---
accord-core/src/main/java/accord/api/Agent.java | 1 +
accord-core/src/main/java/accord/api/Key.java | 3 +
.../main/java/accord/api/ProtocolModifiers.java | 26 +++-
.../src/main/java/accord/api/RoutingKey.java | 3 +
.../coordinate/AbstractCoordinatePreAccept.java | 3 +-
.../main/java/accord/coordinate/CheckShards.java | 3 +-
.../java/accord/coordinate/CollectLatestDeps.java | 39 +++--
.../accord/coordinate/CoordinateEphemeralRead.java | 3 +-
.../accord/coordinate/CoordinatePreAccept.java | 3 +-
.../accord/coordinate/CoordinateSyncPoint.java | 5 +-
.../accord/coordinate/CoordinateTransaction.java | 2 +-
.../accord/coordinate/CoordinationAdapter.java | 160 +++++++++++--------
.../accord/coordinate/ExecuteEphemeralRead.java | 3 +-
.../java/accord/coordinate/ExecuteSyncPoint.java | 5 +-
.../main/java/accord/coordinate/ExecuteTxn.java | 79 +++++++---
.../java/accord/coordinate/FetchCoordinator.java | 3 +-
.../main/java/accord/coordinate/Invalidate.java | 3 +-
.../main/java/accord/coordinate/MaybeRecover.java | 4 +-
.../src/main/java/accord/coordinate/Persist.java | 8 +-
.../java/accord/coordinate/PersistSyncPoint.java | 4 +-
.../main/java/accord/coordinate/PersistTxn.java | 5 +-
.../src/main/java/accord/coordinate/Propose.java | 86 +++++++----
.../{ProposeSyncPoint.java => ProposeOnly.java} | 22 ++-
.../java/accord/coordinate/ProposeSyncPoint.java | 2 +-
.../main/java/accord/coordinate/ProposeTxn.java | 2 +-
.../java/accord/coordinate/ReadCoordinator.java | 13 +-
.../src/main/java/accord/coordinate/Recover.java | 37 +++--
.../java/accord/coordinate/RecoverWithRoute.java | 50 +++---
.../src/main/java/accord/coordinate/Stabilise.java | 7 +-
.../{StabiliseTxn.java => StabiliseOnly.java} | 20 ++-
.../java/accord/coordinate/StabiliseSyncPoint.java | 2 +-
.../main/java/accord/coordinate/StabiliseTxn.java | 2 +-
.../accord/coordinate/tracking/ReadTracker.java | 5 +-
.../src/main/java/accord/impl/CommandChange.java | 146 +++++++++---------
.../java/accord/impl/DurabilityScheduling.java | 2 +-
.../java/accord/impl/InMemoryCommandStore.java | 8 +-
.../accord/impl/progresslog/PackedKeyTracker.java | 3 +-
.../java/accord/impl/progresslog/WaitingState.java | 12 +-
.../src/main/java/accord/local/AgentExecutor.java | 7 +-
.../src/main/java/accord/local/Command.java | 14 +-
.../main/java/accord/local/CommandSummaries.java | 23 +--
.../src/main/java/accord/local/Commands.java | 92 ++++++-----
accord-core/src/main/java/accord/local/Node.java | 2 +-
.../src/main/java/accord/local/SafeCommand.java | 8 +-
.../main/java/accord/local/SafeCommandStore.java | 5 -
.../main/java/accord/local/cfk/CommandsForKey.java | 92 ++++++-----
.../main/java/accord/local/cfk/PostProcess.java | 2 +-
.../src/main/java/accord/local/cfk/Pruning.java | 11 +-
.../java/accord/local/cfk/SafeCommandsForKey.java | 16 +-
.../src/main/java/accord/local/cfk/Updating.java | 8 +-
.../src/main/java/accord/messages/Accept.java | 142 ++++++++++++-----
.../src/main/java/accord/messages/Apply.java | 41 +----
.../java/accord/messages/BeginInvalidation.java | 6 -
.../main/java/accord/messages/BeginRecovery.java | 13 --
.../src/main/java/accord/messages/CheckStatus.java | 6 -
.../src/main/java/accord/messages/Commit.java | 23 +--
.../java/accord/messages/GetEphemeralReadDeps.java | 13 --
.../main/java/accord/messages/GetLatestDeps.java | 65 +++++---
.../main/java/accord/messages/InformDurable.java | 6 -
.../src/main/java/accord/messages/PreAccept.java | 23 +--
.../src/main/java/accord/messages/Propagate.java | 16 +-
.../src/main/java/accord/messages/ReadData.java | 1 +
.../java/accord/messages/ReadEphemeralTxnData.java | 8 +
.../main/java/accord/messages/SafeCallback.java | 2 +-
.../main/java/accord/messages/StableThenRead.java | 2 +
.../src/main/java/accord/messages/TxnRequest.java | 6 +
.../main/java/accord/primitives/AbstractKeys.java | 56 ++-----
.../java/accord/primitives/AbstractRanges.java | 79 +++++-----
.../accord/primitives/AbstractUnseekableKeys.java | 55 ++++++-
.../src/main/java/accord/primitives/KeyDeps.java | 4 +-
.../src/main/java/accord/primitives/KeyRoute.java | 26 ++--
.../src/main/java/accord/primitives/Keys.java | 64 +++++++-
.../main/java/accord/primitives/LatestDeps.java | 169 +++++++++++++++++----
.../main/java/accord/primitives/PartialDeps.java | 5 +
.../main/java/accord/primitives/PartialTxn.java | 28 +++-
.../src/main/java/accord/primitives/Range.java | 19 ++-
.../main/java/accord/primitives/RangeRoute.java | 6 +-
.../src/main/java/accord/primitives/Routable.java | 34 +++++
.../src/main/java/accord/primitives/Routables.java | 154 +++++++++----------
.../main/java/accord/primitives/Unseekables.java | 31 ++++
.../src/main/java/accord/topology/Topologies.java | 34 +++--
.../src/main/java/accord/topology/Topology.java | 49 ++----
.../main/java/accord/topology/TopologyManager.java | 58 ++++---
.../src/main/java/accord/utils/SortedArrays.java | 8 +-
.../java/accord/utils/async/AsyncExecutor.java | 12 +-
.../accord/coordinate/CoordinateSyncPointTest.java | 4 +-
accord-core/src/test/java/accord/impl/IntKey.java | 2 +-
.../test/java/accord/impl/PrefixedIntHashKey.java | 2 +-
.../test/java/accord/impl/RemoteListenersTest.java | 2 +-
.../src/test/java/accord/impl/TestAgent.java | 6 +
.../src/test/java/accord/impl/basic/Cluster.java | 2 +-
.../accord/impl/basic/DelayedCommandStores.java | 2 +-
.../java/accord/impl/basic/InMemoryJournal.java | 18 +--
.../accord/impl/basic/TaskExecutorService.java | 6 +-
.../src/test/java/accord/impl/list/ListAgent.java | 11 +-
.../src/test/java/accord/impl/list/ListRead.java | 8 +-
.../src/test/java/accord/impl/list/ListWrite.java | 2 +-
.../src/test/java/accord/local/CommandsTest.java | 2 +-
.../java/accord/local/cfk/CommandsForKeyTest.java | 8 +-
.../test/java/accord/messages/PreAcceptTest.java | 3 +-
.../test/java/accord/messages/ReadDataTest.java | 29 ++--
.../java/accord/messages/TxnRequestScopeTest.java | 7 +-
.../java/accord/topology/TopologyManagerTest.java | 13 +-
.../test/java/accord/topology/TopologyTest.java | 103 ++++++-------
.../main/java/accord/maelstrom/MaelstromAgent.java | 6 +
.../main/java/accord/maelstrom/MaelstromKey.java | 2 +-
.../java/accord/maelstrom/MaelstromUpdate.java | 10 +-
107 files changed, 1559 insertions(+), 1017 deletions(-)
diff --git a/accord-core/src/main/java/accord/api/Agent.java b/accord-core/src/main/java/accord/api/Agent.java
index 9cdd757c..1b748700 100644
--- a/accord-core/src/main/java/accord/api/Agent.java
+++ b/accord-core/src/main/java/accord/api/Agent.java
@@ -153,6 +153,7 @@ public interface Agent extends UncaughtExceptionListener
*/
long retryAwaitTimeout(Node node, SafeCommandStore safeStore, TxnId txnId, int retryCount, BlockedUntil retrying, TimeUnit units);
+ long localSlowAt(TxnId txnId, Phase phase, TimeUnit unit);
long localExpiresAt(TxnId txnId, Phase phase, TimeUnit unit);
long expiresAt(ReplyContext replyContext, TimeUnit unit);
diff --git a/accord-core/src/main/java/accord/api/Key.java b/accord-core/src/main/java/accord/api/Key.java
index 1504b406..9174fd7e 100644
--- a/accord-core/src/main/java/accord/api/Key.java
+++ b/accord-core/src/main/java/accord/api/Key.java
@@ -35,4 +35,7 @@ public interface Key extends Seekable, RoutableKey
@Override
default Range asRange() { throw new UnsupportedOperationException(); }
+
+ @Override
+ default Kind kind() { return Kind.SeekableKey; }
}
diff --git a/accord-core/src/main/java/accord/api/ProtocolModifiers.java b/accord-core/src/main/java/accord/api/ProtocolModifiers.java
index 75ded99c..a7affba1 100644
--- a/accord-core/src/main/java/accord/api/ProtocolModifiers.java
+++ b/accord-core/src/main/java/accord/api/ProtocolModifiers.java
@@ -47,9 +47,18 @@ public class ProtocolModifiers
{
Chase, DoNotChase;
}
+
public enum Include
{
- Unsynced, Owned;
+ // include all nodes and epochs with unsynced ranges
+ Unsynced,
+ // include only replicas that own the ranges, and only the ownership epochs
+ Owned;
+
+ private static Include max(Include a, Include b)
+ {
+ return a.compareTo(b) >= 0 ? a : b;
+ }
}
public static class ChaseAndInclude
@@ -80,8 +89,8 @@ public class ProtocolModifiers
this.commit = commit;
this.stable = stable;
this.recover = recover;
- this.preacceptOrRecover = preaccept.include == Owned || recover == Owned ? Owned : Unsynced;
- this.preacceptOrCommit = preaccept.include == Owned || commit == Owned ? Owned : Unsynced;
+ this.preacceptOrRecover = Include.max(preaccept.include, recover);
+ this.preacceptOrCommit = Include.max(preaccept.include, commit);
}
static Spec parse(String description)
@@ -129,7 +138,7 @@ public class ProtocolModifiers
static
{
- Spec spec = Spec.parse(System.getProperty("accord.quorums.epochs", "preaccept=-,accept=-,commit=-,stable=,recover=-"));
+ Spec spec = Spec.parse(System.getProperty("accord.quorums.epochs", "preaccept=-,accept=-,commit=-,stable=-,recover=-"));
preaccept = spec.preaccept;
accept = spec.accept;
commit = spec.commit;
@@ -196,6 +205,10 @@ public class ProtocolModifiers
public static boolean filterDuplicateDependenciesFromAcceptReply() { return filterDuplicateDependenciesFromAcceptReply; }
public static void setFilterDuplicateDependenciesFromAcceptReply(boolean newFilterDuplicateDependenciesFromAcceptReply) { filterDuplicateDependenciesFromAcceptReply = newFilterDuplicateDependenciesFromAcceptReply; }
+ private static boolean sendMinimalStableMessages = true;
+ public static void setSendMinimalStableMessages(boolean newSendMinimalStableMessages) { sendMinimalStableMessages = newSendMinimalStableMessages; }
+ public static boolean sendMinimalStableMessages() { return sendMinimalStableMessages; }
+
private static boolean permitLocalExecution = true;
public static boolean permitLocalExecution() { return permitLocalExecution; }
public static void setPermitLocalExecution(boolean newPermitLocalExecution) { permitLocalExecution = newPermitLocalExecution; }
@@ -204,6 +217,11 @@ public class ProtocolModifiers
public static boolean requiresUniqueHlcs() { return requiresUniqueHlcs; }
public static void setRequiresUniqueHlcs(boolean newRequiresUniqueHlcs) { requiresUniqueHlcs = newRequiresUniqueHlcs; }
+ // TODO (required): this is a temporary measure to not break migration
+ private static boolean temporaryPermitUnsafeBlindWrites = true;
+ public static boolean temporaryPermitUnsafeBlindWrites() { return temporaryPermitUnsafeBlindWrites; }
+ public static void setTemporaryPermitUnsafeBlindWrites(boolean newTemporaryPermitUnsafeBlindWrites) { temporaryPermitUnsafeBlindWrites = newTemporaryPermitUnsafeBlindWrites; }
+
private static int markStaleIfCannotExecute = TinyEnumSet.encode(Txn.Kind.Write);
public static boolean markStaleIfCannotExecute(TxnId txnId) { return TinyEnumSet.contains(markStaleIfCannotExecute, txnId.kindOrdinal()); }
public static boolean markStaleIfCannotExecute(Txn.Kind kind) { return TinyEnumSet.contains(markStaleIfCannotExecute, kind); }
diff --git a/accord-core/src/main/java/accord/api/RoutingKey.java b/accord-core/src/main/java/accord/api/RoutingKey.java
index b2190361..7bceb52c 100644
--- a/accord-core/src/main/java/accord/api/RoutingKey.java
+++ b/accord-core/src/main/java/accord/api/RoutingKey.java
@@ -26,6 +26,9 @@ import accord.primitives.Unseekable;
public interface RoutingKey extends Unseekable, RoutableKey
{
@Override default RoutingKey toUnseekable() { return this; }
+
+ @Override default Kind kind() { return Kind.UnseekableKey; }
+
Range asRange();
RangeFactory rangeFactory();
}
diff --git a/accord-core/src/main/java/accord/coordinate/AbstractCoordinatePreAccept.java b/accord-core/src/main/java/accord/coordinate/AbstractCoordinatePreAccept.java
index c153d980..5e47a5d4 100644
--- a/accord-core/src/main/java/accord/coordinate/AbstractCoordinatePreAccept.java
+++ b/accord-core/src/main/java/accord/coordinate/AbstractCoordinatePreAccept.java
@@ -33,6 +33,7 @@ import accord.utils.WrappableException;
import accord.utils.async.AsyncResults.SettableResult;
import static accord.api.ProtocolModifiers.QuorumEpochIntersections;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
/**
* Abstract parent class for implementing preaccept-like operations where we may need to fetch additional replies
@@ -49,7 +50,7 @@ abstract class AbstractCoordinatePreAccept<T, R> extends SettableResult<T> imple
AbstractCoordinatePreAccept(Node node, FullRoute<?> route, @Nonnull TxnId txnId)
{
- this(node, route, txnId, node.topology().select(route, txnId, txnId, QuorumEpochIntersections.preaccept.include));
+ this(node, route, txnId, node.topology().select(route, txnId, txnId, SHARE, QuorumEpochIntersections.preaccept.include));
}
AbstractCoordinatePreAccept(Node node, FullRoute<?> route, @Nonnull TxnId txnId, Topologies topologies)
diff --git a/accord-core/src/main/java/accord/coordinate/CheckShards.java b/accord-core/src/main/java/accord/coordinate/CheckShards.java
index 787642b8..53e1d56c 100644
--- a/accord-core/src/main/java/accord/coordinate/CheckShards.java
+++ b/accord-core/src/main/java/accord/coordinate/CheckShards.java
@@ -28,6 +28,7 @@ import accord.primitives.*;
import accord.topology.Topologies;
import accord.utils.Invariants;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Invariants.illegalState;
/**
@@ -68,7 +69,7 @@ public abstract class CheckShards<U extends Participants<?>> extends ReadCoordin
private static Topologies topologyFor(Node node, TxnId txnId, Unseekables<?> contact, long epoch)
{
// TODO (desired): only fetch data from source epoch
- return node.topology().preciseEpochs(contact, txnId.epoch(), epoch);
+ return node.topology().preciseEpochs(contact, txnId.epoch(), epoch, SHARE);
}
@Override
diff --git a/accord-core/src/main/java/accord/coordinate/CollectLatestDeps.java b/accord-core/src/main/java/accord/coordinate/CollectLatestDeps.java
index cb6d3c08..ecb23105 100644
--- a/accord-core/src/main/java/accord/coordinate/CollectLatestDeps.java
+++ b/accord-core/src/main/java/accord/coordinate/CollectLatestDeps.java
@@ -22,6 +22,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
+import javax.annotation.Nullable;
+
import accord.coordinate.tracking.QuorumTracker;
import accord.local.CommandStore;
import accord.local.Node;
@@ -29,6 +31,8 @@ import accord.local.Node.Id;
import accord.messages.Callback;
import accord.messages.GetLatestDeps;
import accord.messages.GetLatestDeps.GetLatestDepsOk;
+import accord.messages.GetLatestDeps.GetLatestDepsReply;
+import accord.primitives.Ballot;
import accord.primitives.FullRoute;
import accord.primitives.LatestDeps;
import accord.primitives.Route;
@@ -43,50 +47,60 @@ import static accord.coordinate.tracking.RequestStatus.Failed;
import static accord.coordinate.tracking.RequestStatus.Success;
import static accord.primitives.Routables.Slice.Minimal;
-public class CollectLatestDeps implements Callback<GetLatestDepsOk>
+public class CollectLatestDeps implements Callback<GetLatestDepsReply>
{
final Node node;
final TxnId txnId;
final Route<?> route;
final Timestamp executeAt;
+ final @Nullable Ballot ballot;
private final SortedListMap<Id, GetLatestDepsOk> oks;
private final QuorumTracker tracker;
private final BiConsumer<List<LatestDeps>, Throwable> callback;
private boolean isDone;
+ private Throwable failure;
- CollectLatestDeps(Node node, Topologies topologies, TxnId txnId, Route<?> route, Timestamp executeAt, BiConsumer<List<LatestDeps>, Throwable> callback)
+ CollectLatestDeps(Node node, Topologies topologies, TxnId txnId, Route<?> route, @Nullable Ballot ballot, Timestamp executeAt, BiConsumer<List<LatestDeps>, Throwable> callback)
{
this.node = node;
this.txnId = txnId;
this.route = route;
this.executeAt = executeAt;
+ this.ballot = ballot;
this.callback = callback;
this.oks = new SortedListMap<>(topologies.nodes(), GetLatestDepsOk[]::new);
this.tracker = new QuorumTracker(topologies);
}
- public static void withLatestDeps(Node node, TxnId txnId, FullRoute<?> fullRoute, Unseekables<?> collectFrom, Timestamp executeAt, BiConsumer<List<LatestDeps>, Throwable> callback)
+ public static void withLatestDeps(Node node, TxnId txnId, FullRoute<?> fullRoute, Unseekables<?> collectFrom, @Nullable Ballot ballot, Timestamp executeAt, BiConsumer<List<LatestDeps>, Throwable> callback)
{
Route<?> route = fullRoute.intersecting(collectFrom, Minimal);
Topologies topologies = node.topology().withUnsyncedEpochs(route, txnId, executeAt);
- CollectLatestDeps collect = new CollectLatestDeps(node, topologies, txnId, route, executeAt, callback);
+ CollectLatestDeps collect = new CollectLatestDeps(node, topologies, txnId, route, ballot, executeAt, callback);
CommandStore store = CommandStore.currentOrElseSelect(node, fullRoute);
SortedArrayList<Id> contact = collect.tracker.filterAndRecordFaulty();
if (contact == null) callback.accept(null, new Exhausted(txnId, route.homeKey(), null));
- else node.send(contact, to -> new GetLatestDeps(to, topologies, route, txnId, executeAt), store, collect);
+ else node.send(contact, to -> new GetLatestDeps(to, topologies, route, txnId, ballot, executeAt), store, collect);
}
@Override
- public void onSuccess(Id from, GetLatestDepsOk ok)
+ public void onSuccess(Id from, GetLatestDepsReply ok)
{
if (isDone)
return;
- oks.put(from, ok);
- if (tracker.recordSuccess(from) == Success)
- onQuorum();
+ if (ok.isOk())
+ {
+ oks.put(from, (GetLatestDepsOk) ok);
+ if (tracker.recordSuccess(from) == Success)
+ onQuorum();
+ }
+ else
+ {
+ onFailure(from, null);
+ }
}
@Override
@@ -95,10 +109,15 @@ public class CollectLatestDeps implements Callback<GetLatestDepsOk>
if (isDone)
return;
+ if (failure != null)
+ this.failure = FailureAccumulator.append(this.failure, failure);
+
if (tracker.recordFailure(from) == Failed)
{
isDone = true;
- callback.accept(null, new Timeout(txnId, route.homeKey()));
+ if (this.failure == null)
+ this.failure = new Exhausted(txnId, route.homeKey(), null);
+ callback.accept(null, this.failure);
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateEphemeralRead.java b/accord-core/src/main/java/accord/coordinate/CoordinateEphemeralRead.java
index 53526571..b95c2eb9 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateEphemeralRead.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateEphemeralRead.java
@@ -41,6 +41,7 @@ import static accord.api.ProtocolModifiers.QuorumEpochIntersections;
import static accord.api.ProtocolModifiers.QuorumEpochIntersections.Include.Owned;
import static accord.coordinate.tracking.RequestStatus.Failed;
import static accord.coordinate.tracking.RequestStatus.Success;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
/**
* An Ephemeral Read is a single-key linearizable read, that is invisible to other transactions so can be non-durable.
@@ -125,7 +126,7 @@ public class CoordinateEphemeralRead extends AbstractCoordinatePreAccept<Result,
void onPreAccepted(Topologies topologies)
{
Deps deps = Deps.merge(oks, oks.domainSize(), SortedListMap::getValue, ok -> ok.deps);
- topologies = node.topology().reselect(topologies, QuorumEpochIntersections.preaccept.include, route, executeAtEpoch, executeAtEpoch, Owned);
+ topologies = node.topology().reselect(topologies, QuorumEpochIntersections.preaccept.include, route, executeAtEpoch, executeAtEpoch, SHARE, Owned);
new ExecuteEphemeralRead(node, topologies, route, txnId.withEpoch(executeAtEpoch), txn, deps, this).start();
if (!Invariants.debug()) oks.clear();
}
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java b/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
index 371eef18..7df3c304 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
@@ -44,6 +44,7 @@ import static accord.api.ProtocolModifiers.QuorumEpochIntersections;
import static accord.coordinate.Propose.NotAccept.proposeInvalidate;
import static accord.coordinate.tracking.RequestStatus.Success;
import static accord.primitives.Timestamp.mergeMaxAndFlags;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
/**
* Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
@@ -60,7 +61,7 @@ abstract class CoordinatePreAccept<T> extends AbstractCoordinatePreAccept<T, Pre
CoordinatePreAccept(Node node, TxnId txnId, Txn txn, FullRoute<?> route)
{
- this(node, txnId, txn, route, node.topology().select(route, txnId, txnId, QuorumEpochIntersections.preaccept.include));
+ this(node, txnId, txn, route, node.topology().select(route, txnId, txnId, SHARE, QuorumEpochIntersections.preaccept.include));
}
CoordinatePreAccept(Node node, TxnId txnId, Txn txn, FullRoute<?> route, Topologies topologies)
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
index 17acc99c..1dad27d4 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
@@ -57,6 +57,7 @@ import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Timestamp.Flag.REJECTED;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.primitives.TxnId.Cardinality.cardinality;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
/**
* Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
@@ -151,7 +152,7 @@ public class CoordinateSyncPoint<R> extends CoordinatePreAccept<R>
: TopologyMismatch.checkForMismatchOrPendingRemoval(node.topology().globalForEpoch(txnId.epoch()), txnId, route.homeKey(), route);
if (mismatch != null)
return AsyncResults.failure(mismatch);
- CoordinateSyncPoint<SyncPoint<U>> coordinate = new CoordinateSyncPoint<>(node, txnId, adapter.forDecision(node, route, txnId, txnId), node.agent().emptySystemTxn(txnId.kind(), txnId.domain()), route, adapter);
+ CoordinateSyncPoint<SyncPoint<U>> coordinate = new CoordinateSyncPoint<>(node, txnId, adapter.forDecision(node, route, SHARE, txnId, txnId), node.agent().emptySystemTxn(txnId.kind(), txnId.domain()), route, adapter);
coordinate.start();
return coordinate;
}
@@ -176,7 +177,7 @@ public class CoordinateSyncPoint<R> extends CoordinatePreAccept<R>
withFlags = txnId.addFlag(HLC_BOUND);
Deps deps = Deps.merge(oks.valuesAsNullableList(), oks.domainSize(), List::get, ok -> ok.deps);
if (tracker.hasFastPathAccepted())
- adapter.execute(node, topologies, route, FAST, txnId, txn, withFlags, deps, this);
+ adapter.execute(node, topologies, route, FAST, txnId, txn, withFlags, deps, deps, this);
else if (tracker.hasMediumPathAccepted())
adapter.propose(node, topologies, route, Accept.Kind.MEDIUM, Ballot.ZERO, txnId, txn, withFlags, deps, this);
else
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java b/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
index e77dd837..50c74469 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
@@ -106,7 +106,7 @@ public class CoordinateTransaction extends CoordinatePreAccept<Result>
// note: we merge all Deps regardless of witnessedAt. While we only need fast path votes,
// we must include Deps from fast path votes from earlier epochs that may have witnessed later transactions
// TODO (desired): we might mask some bugs by merging more responses than we strictly need, so optimise this to optionally merge minimal deps
- executeAdapter().execute(node, topologies, route, FAST, txnId, txn, txnId, deps, settingCallback());
+ executeAdapter().execute(node, topologies, route, FAST, txnId, txn, txnId, deps, deps, settingCallback());
node.agent().metricsEventsListener().onFastPathTaken(txnId, deps);
}
else if (tracker.hasMediumPathAccepted() && txnId.hasMediumPath())
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java b/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
index b8b30346..f5562e32 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
@@ -34,7 +34,6 @@ import accord.messages.Apply;
import accord.primitives.Ballot;
import accord.primitives.Deps;
import accord.primitives.FullRoute;
-import accord.primitives.Participants;
import accord.primitives.Route;
import accord.primitives.SyncPoint;
import accord.primitives.Timestamp;
@@ -43,15 +42,19 @@ import accord.primitives.TxnId;
import accord.primitives.Unseekable;
import accord.primitives.Writes;
import accord.topology.Topologies;
+import accord.topology.Topologies.SelectNodeOwnership;
import accord.utils.Invariants;
import accord.utils.UnhandledEnum;
import static accord.api.ProtocolModifiers.QuorumEpochIntersections;
+import static accord.api.ProtocolModifiers.Toggles.requiresUniqueHlcs;
+import static accord.api.ProtocolModifiers.Toggles.temporaryPermitUnsafeBlindWrites;
import static accord.coordinate.CoordinationAdapter.Factory.Kind.Recovery;
import static accord.coordinate.ExecutePath.FAST;
import static accord.coordinate.ExecutePath.SLOW;
import static accord.messages.Apply.Kind.Maximal;
import static accord.messages.Apply.Kind.Minimal;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
public interface CoordinationAdapter<R>
{
@@ -62,12 +65,14 @@ public interface CoordinationAdapter<R>
}
void propose(Node node, @Nullable Topologies preaccept, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback);
+ void proposeOnly(Node node, Route<?> require, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Deps, Throwable> callback);
void stabilise(Node node, @Nullable Topologies any, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback);
- void execute(Node node, @Nullable Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback);
- void persist(Node node, @Nullable Topologies any, FullRoute<?> route, Route<?> sendTo, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super R, Throwable> callback);
+ void stabiliseOnly(Node node, Route<?> require, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Deps, Throwable> callback);
+ void execute(Node node, @Nullable Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps stableDeps, Deps sendDeps, BiConsumer<? super R, Throwable> callback);
+ void persist(Node node, @Nullable Topologies any, Route<?> require, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super R, Throwable> callback);
default void persist(Node node, @Nullable Topologies any, FullRoute<?> route, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super R, Throwable> callback)
{
- persist(node, any, route, route, txnId, txn, executeAt, deps, writes, result, callback);
+ persist(node, any, route, route, SHARE, route, txnId, txn, executeAt, deps, writes, result, callback);
}
class DefaultFactory implements Factory
@@ -98,14 +103,14 @@ public interface CoordinationAdapter<R>
{
public static CoordinationAdapter<Result> standard()
{
- return StandardTxnAdapter.INSTANCE;
+ return TxnAdapter.STANDARD;
}
// note that by default the recovery adapter is only used for the initial recovery decision - if e.g. propose is initiated
// then we revert back to standard adapter behaviour for later steps
public static CoordinationAdapter<Result> recover()
{
- return RecoverTxnAdapter.INSTANCE;
+ return TxnAdapter.RECOVERY;
}
public static <U extends Unseekable> SyncPointAdapter<SyncPoint<U>> inclusiveSyncPoint()
@@ -133,16 +138,33 @@ public interface CoordinationAdapter<R>
return RecoverExclusiveSyncPointAdapter.INSTANCE;
}
- public static abstract class AbstractTxnAdapter implements CoordinationAdapter<Result>
+ public static class TxnAdapter implements CoordinationAdapter<Result>
{
+ static final TxnAdapter STANDARD = new TxnAdapter(Minimal);
+ static final TxnAdapter RECOVERY = new TxnAdapter(Maximal);
+
+ final Apply.Kind applyKind;
+ public TxnAdapter(Apply.Kind applyKind)
+ {
+ this.applyKind = applyKind;
+ }
+
@Override
public void propose(Node node, @Nullable Topologies preacceptOrRecovery, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Result, Throwable> callback)
{
Topologies accept = node.topology().reselect(preacceptOrRecovery, QuorumEpochIntersections.preacceptOrRecover,
- route, txnId, executeAt, QuorumEpochIntersections.accept);
+ route, txnId, executeAt, SHARE, QuorumEpochIntersections.accept);
new ProposeTxn(node, accept, route, kind, ballot, txnId, txn, executeAt, deps, callback).start();
}
+ @Override
+ public void proposeOnly(Node node, Route<?> require, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Deps, Throwable> callback)
+ {
+ Topologies accept = node.topology().reselect(null, QuorumEpochIntersections.preacceptOrRecover,
+ sendTo, txnId, executeAt, selectNodeOwnership, QuorumEpochIntersections.accept);
+ new ProposeOnly(node, accept, sendTo, route, kind, ballot, txnId, txn, executeAt, deps, callback).start();
+ }
+
@Override
public void stabilise(Node node, Topologies accept, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Result, Throwable> callback)
{
@@ -156,63 +178,64 @@ public interface CoordinationAdapter<R>
}
Topologies all = node.topology().reselect(accept, QuorumEpochIntersections.accept,
- route, txnId, executeAt, QuorumEpochIntersections.commit);
+ route, txnId, executeAt, SHARE, QuorumEpochIntersections.commit);
Topologies coordinates = all.size() == 1 ? all : accept.forEpoch(txnId.epoch());
- if (ProtocolModifiers.Faults.txnInstability) execute(node, all, route, SLOW, txnId, txn, executeAt, deps, callback);
+ if (ProtocolModifiers.Faults.txnInstability) execute(node, all, route, SLOW, txnId, txn, executeAt, deps, deps, callback);
else new StabiliseTxn(node, coordinates, all, route, ballot, txnId, txn, executeAt, deps, callback).start();
}
@Override
- public void execute(Node node, Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Result, Throwable> callback)
+ public void stabiliseOnly(Node node, Route<?> require, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Deps, Throwable> callback)
+ {
+ if (!node.topology().hasEpoch(executeAt.epoch()))
+ {
+ node.withEpoch(executeAt.epoch(), (success, fail) -> {
+ if (fail != null) callback.accept(null, fail);
+ else stabiliseOnly(node, require, sendTo, selectNodeOwnership, route, ballot, txnId, txn, executeAt, deps, callback);
+ });
+ return;
+ }
+
+ Topologies all = node.topology().reselect(null, QuorumEpochIntersections.accept,
+ sendTo, txnId, executeAt, selectNodeOwnership, QuorumEpochIntersections.commit);
+ Topologies coordinates = all.size() == 1 ? all : all.forEpoch(txnId.epoch());
+
+ new StabiliseOnly(node, coordinates, all, require, route, ballot, txnId, txn, executeAt, deps, callback).start();
+ }
+
+ @Override
+ public void execute(Node node, Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps stableDeps, Deps sendDeps, BiConsumer<? super Result, Throwable> callback)
{
- Topologies all = execution(node, any, route, txnId, executeAt);
+ Topologies all = execution(node, any, route, SHARE, route, txnId, executeAt);
- if (txn.read().keys().isEmpty())
+ if ((temporaryPermitUnsafeBlindWrites() || !requiresUniqueHlcs()) && txn.read().keys().isEmpty())
{
Writes writes = txnId.is(Txn.Kind.Write) ? txn.execute(txnId, executeAt, null) : null;
Result result = txn.result(txnId, executeAt, null);
- persist(node, all, route, txnId, txn, executeAt, deps, writes, result, callback);
+ persist(node, all, route, txnId, txn, executeAt, stableDeps, writes, result, callback);
}
else
{
- new ExecuteTxn(node, all, route, path, txnId, txn, executeAt, deps, callback).start();
+ new ExecuteTxn(node, all, route, path, txnId, txn, executeAt, stableDeps, sendDeps, callback).start();
}
}
- Topologies execution(Node node, Topologies preacceptOrCommit, Participants<?> participants, TxnId txnId, Timestamp executeAt)
- {
- return node.topology().reselect(preacceptOrCommit, QuorumEpochIntersections.preacceptOrCommit,
- participants, txnId, executeAt, QuorumEpochIntersections.stable);
- }
- }
-
- public static class StandardTxnAdapter extends AbstractTxnAdapter
- {
- public static final StandardTxnAdapter INSTANCE = new StandardTxnAdapter();
-
@Override
- public void persist(Node node, Topologies any, FullRoute<?> route, Route<?> sendTo, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super Result, Throwable> callback)
+ public void persist(Node node, Topologies any, Route<?> require, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super Result, Throwable> callback)
{
- Topologies all = execution(node, any, sendTo, txnId, executeAt);
+ Topologies all = execution(node, any, sendTo, selectNodeOwnership, route, txnId, executeAt);
if (callback != null) callback.accept(result, null);
- new PersistTxn(node, all, txnId, sendTo, txn, executeAt, deps, writes, result, route)
- .start(Apply.FACTORY, Minimal, all, writes, result);
+ new PersistTxn(node, all, txnId, require, txn, executeAt, deps, writes, result, route, Apply.FACTORY)
+ .start(applyKind, all, writes, result);
}
- }
- public static class RecoverTxnAdapter extends AbstractTxnAdapter
- {
- public static final RecoverTxnAdapter INSTANCE = new RecoverTxnAdapter();
- @Override
- public void persist(Node node, Topologies any, FullRoute<?> route, Route<?> sendTo, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super Result, Throwable> callback)
+ protected Topologies execution(Node node, @Nullable Topologies preacceptOrCommit, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, TxnId txnId, Timestamp executeAt)
{
- Topologies all = execution(node, any, sendTo, txnId, executeAt);
-
- if (callback != null) callback.accept(result, null);
- new PersistTxn(node, all, txnId, sendTo, txn, executeAt, deps, writes, result, route)
- .start(Apply.FACTORY, Maximal, all, writes, result);
+ if (route != sendTo) preacceptOrCommit = null;
+ return node.topology().reselect(preacceptOrCommit, QuorumEpochIntersections.preacceptOrCommit,
+ sendTo, txnId, executeAt, selectNodeOwnership, QuorumEpochIntersections.stable);
}
}
@@ -225,39 +248,54 @@ public interface CoordinationAdapter<R>
this.preacceptTrackerFactory = preacceptTrackerFactory;
}
- abstract Topologies forDecision(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt);
- abstract Topologies forExecution(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt, Deps deps);
+ abstract Topologies forDecision(Node node, Route<?> route, SelectNodeOwnership selectNodeOwnership, TxnId txnId, Timestamp executeAt);
+ abstract Topologies forExecution(Node node, Route<?> route, SelectNodeOwnership selectNodeOwnership, TxnId txnId, Timestamp executeAt, Deps deps);
abstract void invokeSuccess(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt, Txn txn, Deps deps, BiConsumer<? super R, Throwable> callback);
@Override
public void propose(Node node, Topologies any, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback)
{
- Topologies all = forDecision(node, route, txnId, executeAt);
+ Topologies all = forDecision(node, route, SHARE, txnId, executeAt);
new ProposeSyncPoint<>(this, node, all, route, kind, ballot, txnId, txn, executeAt, deps, callback).start();
}
+ @Override
+ public void proposeOnly(Node node, Route<?> require, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Deps, Throwable> callback)
+ {
+ Topologies all = forDecision(node, sendTo, selectNodeOwnership, txnId, executeAt);
+ new ProposeOnly(node, all, sendTo, route, kind, ballot, txnId, txn, executeAt, deps, callback).start();
+ }
+
@Override
public void stabilise(Node node, Topologies any, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback)
{
- Topologies all = forExecution(node, route, txnId, executeAt, deps);
+ Topologies all = forExecution(node, route, SHARE, txnId, executeAt, deps);
Topologies coordinates = all.forEpoch(txnId.epoch());
new StabiliseSyncPoint<>(this, node, coordinates, all, route, ballot, txnId, txn, executeAt, deps, callback).start();
}
@Override
- public void execute(Node node, Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback)
+ public void stabiliseOnly(Node node, Route<?> require, Route<?> sendTo, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Deps, Throwable> callback)
+ {
+ Topologies all = forExecution(node, route, selectNodeOwnership, txnId, executeAt, deps);
+ Topologies coordinates = all.forEpoch(txnId.epoch());
+ new StabiliseOnly(node, coordinates, all, sendTo, route, ballot, txnId, txn, executeAt, deps, callback).start();
+ }
+
+ @Override
+ public void execute(Node node, Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps stableDeps, Deps sendDeps, BiConsumer<? super R, Throwable> callback)
{
- persist(node, null, route, txnId, txn, executeAt, deps, null, txn.result(txnId, executeAt, null), callback);
+ persist(node, null, route, txnId, txn, executeAt, stableDeps, null, txn.result(txnId, executeAt, null), callback);
}
@Override
- public void persist(Node node, Topologies ignore, FullRoute<?> route, Route<?> participants, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super R, Throwable> callback)
+ public void persist(Node node, Topologies ignore, Route<?> require, Route<?> participants, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super R, Throwable> callback)
{
- Topologies all = forExecution(node, route, txnId, executeAt, deps);
+ Topologies all = forExecution(node, participants, SHARE, txnId, executeAt, deps);
invokeSuccess(node, route, txnId, executeAt, txn, deps, callback);
new PersistSyncPoint(node, all, txnId, route, txn, executeAt, deps, writes, result)
- .start(Apply.FACTORY, Maximal, all, writes, result);
+ .start(Maximal, all, writes, result);
}
}
@@ -269,24 +307,24 @@ public interface CoordinationAdapter<R>
}
@Override
- Topologies forDecision(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt)
+ Topologies forDecision(Node node, Route<?> route, SelectNodeOwnership selectNodeOwnership, TxnId txnId, Timestamp executeAt)
{
return node.topology().withOpenEpochs(route, null, txnId);
}
@Override
- Topologies forExecution(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt, Deps deps)
+ Topologies forExecution(Node node, Route<?> route, SelectNodeOwnership selectNodeOwnership, TxnId txnId, Timestamp executeAt, Deps deps)
{
return node.topology().withUncompletedEpochs(route, txnId, txnId);
}
@Override
- public void execute(Node node, Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback)
+ public void execute(Node node, Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps stableDeps, Deps sendDeps, BiConsumer<? super R, Throwable> callback)
{
// We cannot use the fast path for sync points as their visibility is asymmetric wrt other transactions,
// so we could recover to include different transactions than those we fast path committed with.
Invariants.require(path != FAST);
- super.execute(node, any, route, path, txnId, txn, executeAt, deps, callback);
+ super.execute(node, any, route, path, txnId, txn, executeAt, stableDeps, sendDeps, callback);
}
}
@@ -320,15 +358,15 @@ public interface CoordinationAdapter<R>
}
@Override
- Topologies forDecision(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt)
+ Topologies forDecision(Node node, Route<?> route, SelectNodeOwnership selectNodeOwnership, TxnId txnId, Timestamp executeAt)
{
return node.topology().withUnsyncedEpochs(route, txnId, executeAt);
}
@Override
- Topologies forExecution(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt, Deps deps)
+ Topologies forExecution(Node node, Route<?> route, SelectNodeOwnership selectNodeOwnership, TxnId txnId, Timestamp executeAt, Deps deps)
{
- return node.topology().preciseEpochs(route, txnId.epoch(), executeAt.epoch());
+ return node.topology().preciseEpochs(route, txnId.epoch(), executeAt.epoch(), SHARE);
}
}
@@ -367,17 +405,17 @@ public interface CoordinationAdapter<R>
}
@Override
- public void execute(Node node, Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super SyncPoint<U>, Throwable> callback)
+ public void execute(Node node, Topologies any, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps stableDeps, Deps sendDeps, BiConsumer<? super SyncPoint<U>, Throwable> callback)
{
- Topologies all = forExecution(node, route, txnId, executeAt, deps);
+ Topologies all = forExecution(node, route, SHARE, txnId, executeAt, stableDeps);
- ExecuteInclusive<U> execute = ExecuteInclusive.atQuorum(node, all, new SyncPoint<>(txnId, executeAt, deps, (FullRoute<U>) route), executeAt);
+ ExecuteInclusive<U> execute = ExecuteInclusive.atQuorum(node, all, new SyncPoint<>(txnId, executeAt, stableDeps, (FullRoute<U>) route), executeAt);
execute.addCallback(callback);
execute.start();
}
@Override
- public void persist(Node node, Topologies any, FullRoute<?> route, Route<?> participants, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super SyncPoint<U>, Throwable> callback)
+ public void persist(Node node, Topologies any, Route<?> require, Route<?> participants, SelectNodeOwnership selectNodeOwnership, FullRoute<?> route, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, BiConsumer<? super SyncPoint<U>, Throwable> callback)
{
throw new UnsupportedOperationException();
}
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java b/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
index 67b89549..8ab79ee4 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
@@ -45,6 +45,7 @@ import static accord.coordinate.ReadCoordinator.Action.Aborted;
import static accord.coordinate.ReadCoordinator.Action.Approve;
import static accord.coordinate.ReadCoordinator.Action.ApprovePartial;
import static accord.primitives.Txn.Kind.EphemeralRead;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Invariants.illegalState;
public class ExecuteEphemeralRead extends ReadCoordinator<ReadReply>
@@ -100,7 +101,7 @@ public class ExecuteEphemeralRead extends ReadCoordinator<ReadReply>
{
// TODO (expected): only submit new requests for the keys that execute in a later epoch
node.withEpoch(ok.futureEpoch, callback, t -> WrappableException.wrap(t), () -> {
- new ExecuteEphemeralRead(node, node.topology().preciseEpochs(route, ok.futureEpoch, ok.futureEpoch), route, txnId.withEpoch(ok.futureEpoch), txn, deps, callback).start();
+ new ExecuteEphemeralRead(node, node.topology().preciseEpochs(route, ok.futureEpoch, ok.futureEpoch, SHARE), route, txnId.withEpoch(ok.futureEpoch), txn, deps, callback).start();
});
return Aborted;
}
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java b/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
index 7dcaa1c0..7b4670a1 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
@@ -53,6 +53,7 @@ import accord.utils.async.AsyncResults.SettableResult;
import static accord.messages.Apply.ApplyReply.Insufficient;
import static accord.primitives.Status.Durability.Majority;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
public abstract class ExecuteSyncPoint<U extends Unseekable> extends SettableResult<SyncPoint<U>> implements Callback<ReadReply>
{
@@ -151,7 +152,7 @@ public abstract class ExecuteSyncPoint<U extends Unseekable> extends SettableRes
private long retryInFutureEpoch;
public ExecuteExclusive(Node node, SyncPoint<Range> syncPoint, Function<Topologies, SimpleTracker<?>> trackerSupplier)
{
- super(node, syncPoint, Adapters.exclusiveSyncPoint().forExecution(node, syncPoint.route(), syncPoint.syncId, syncPoint.syncId, syncPoint.waitFor), trackerSupplier);
+ super(node, syncPoint, Adapters.exclusiveSyncPoint().forExecution(node, syncPoint.route(), SHARE, syncPoint.syncId, syncPoint.syncId, syncPoint.waitFor), trackerSupplier);
Invariants.requireArgument(syncPoint.syncId.kind() == ExclusiveSyncPoint);
}
@@ -193,7 +194,7 @@ public abstract class ExecuteSyncPoint<U extends Unseekable> extends SettableRes
if (retryInFutureEpoch > tracker.topologies().currentEpoch())
{
node.withEpoch(retryInFutureEpoch, (ignore, failure) -> tryFailure(WrappableException.wrap(failure)), () -> {
- ExecuteExclusive continuation = new ExecuteExclusive(node, syncPoint, trackerSupplier, trackerSupplier.apply(node.topology().preciseEpochs(syncPoint.route(), tracker.topologies().currentEpoch(), retryInFutureEpoch)));
+ ExecuteExclusive continuation = new ExecuteExclusive(node, syncPoint, trackerSupplier, trackerSupplier.apply(node.topology().preciseEpochs(syncPoint.route(), tracker.topologies().currentEpoch(), retryInFutureEpoch, SHARE)));
continuation.addCallback((success, failure) -> {
if (failure == null) trySuccess(success);
else tryFailure(failure);
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java b/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
index b336b836..dea1c7c4 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
@@ -20,11 +20,9 @@ package accord.coordinate;
import java.util.function.BiConsumer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import accord.api.Data;
import accord.api.Result;
+import accord.api.Timeouts;
import accord.local.CommandStore;
import accord.local.Commands;
import accord.local.Node;
@@ -41,6 +39,7 @@ import accord.messages.ReadData.ReadOk;
import accord.messages.ReadData.ReadReply;
import accord.messages.ReadTxnData;
import accord.messages.Request;
+import accord.messages.SafeCallback;
import accord.messages.StableThenRead;
import accord.primitives.Ballot;
import accord.primitives.Deps;
@@ -58,6 +57,7 @@ import accord.utils.UnhandledEnum;
import org.agrona.collections.IntHashSet;
import static accord.api.ProtocolModifiers.Toggles.permitLocalExecution;
+import static accord.api.ProtocolModifiers.Toggles.sendMinimalStableMessages;
import static accord.coordinate.CoordinationAdapter.Factory.Kind.Standard;
import static accord.coordinate.ExecutePath.FAST;
import static accord.coordinate.ExecutePath.RECOVER;
@@ -67,6 +67,7 @@ import static accord.messages.Commit.Kind.StableFastPath;
import static accord.messages.Commit.Kind.StableMediumPath;
import static accord.messages.Commit.Kind.StableSlowPath;
import static accord.messages.Commit.Kind.StableWithTxnAndDeps;
+import static accord.messages.ReadData.CommitOrReadNack.Waiting;
import static accord.primitives.SaveStatus.Stable;
import static accord.primitives.Status.Phase.Execute;
import static accord.primitives.Status.PreAccepted;
@@ -74,26 +75,23 @@ import static java.util.concurrent.TimeUnit.MICROSECONDS;
// TODO (expected): return Waiting from ReadData if not ready to execute, and do not submit more than one speculative retry in this case
// TODO (expected): by default, if we can execute locally, never contact a remote replica regardless of local outcome
-public class ExecuteTxn extends ReadCoordinator<ReadReply>
+public class ExecuteTxn extends ReadCoordinator<ReadReply> implements Timeouts.Timeout
{
- @SuppressWarnings("unused")
- private static final Logger logger = LoggerFactory.getLogger(ExecuteTxn.class);
- private static boolean SEND_MINIMUM_STABLE_MESSAGES = true;
- public static void setSendMinimumStableMessages(boolean sendMin) {SEND_MINIMUM_STABLE_MESSAGES = sendMin; }
-
final ExecutePath path;
final Txn txn;
final FullRoute<?> route;
final Timestamp executeAt;
final Deps stableDeps;
+ final Deps sendDeps;
final Topologies allTopologies;
final BiConsumer<? super Result, Throwable> callback;
+ private Timeouts.RegisteredTimeout localTimeout;
private Participants<?> readScope;
private Data data;
private long uniqueHlc;
- ExecuteTxn(Node node, Topologies topologies, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps stableDeps, BiConsumer<? super Result, Throwable> callback)
+ ExecuteTxn(Node node, Topologies topologies, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps stableDeps, Deps sendDeps, BiConsumer<? super Result, Throwable> callback)
{
super(node, topologies.forEpoch(executeAt.epoch()), txnId);
this.path = path;
@@ -102,6 +100,7 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
this.allTopologies = topologies;
this.executeAt = executeAt;
this.stableDeps = stableDeps;
+ this.sendDeps = sendDeps;
this.callback = callback;
Invariants.require(!txnId.awaitsOnlyDeps());
Invariants.require(!txnId.awaitsPreviouslyOwned());
@@ -132,7 +131,7 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
{
IntHashSet readSet = new IntHashSet();
to.forEach(i -> readSet.add(i.id));
- Commit.stableAndRead(node, allTopologies, commitKind(), txnId, txn, route, executeAt, stableDeps, readSet, this, SEND_MINIMUM_STABLE_MESSAGES && path != RECOVER);
+ Commit.stableAndRead(node, allTopologies, commitKind(), txnId, txn, route, executeAt, sendDeps, readSet, this, sendMinimalStableMessages() && path != RECOVER);
}
private Commit.Kind commitKind()
@@ -151,9 +150,9 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
public void contact(Id to)
{
CommandStore commandStore = CommandStore.currentOrElseSelect(node, route);
- if (SEND_MINIMUM_STABLE_MESSAGES && path != RECOVER)
+ if (sendMinimalStableMessages() && path != RECOVER)
{
- Request request = Commit.requestTo(to, true, allTopologies, commitKind(), Ballot.ZERO, txnId, txn, route, executeAt, stableDeps, false);
+ Request request = Commit.requestTo(to, true, allTopologies, commitKind(), Ballot.ZERO, txnId, txn, route, executeAt, sendDeps, false);
// we are always sending to a replica in the latest epoch and requesting a read, so onlyContactOldAndReadSet is a redundant parameter
node.send(to, request, commandStore, this);
}
@@ -192,11 +191,26 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
CommitOrReadNack nack = (CommitOrReadNack) reply;
switch (nack)
{
- default: throw new IllegalStateException();
+ default: throw new UnhandledEnum(nack);
+ case Waiting:
+ if (from.id == node.id().id)
+ {
+ long slowAt = node.agent().localSlowAt(txnId, Execute, MICROSECONDS);
+ // TODO (expected): better abstractions for this
+ CommandStore invokeOn = CommandStore.current();
+ localTimeout = node.timeouts().registerAt(new Timeouts.Timeout()
+ {
+ @Override public void timeout() { invokeOn.maybeExecuteImmediately(() -> onSlowResponse(node.id())); }
+ @Override public int stripe() { return txnId.hashCode(); }
+ }, slowAt, MICROSECONDS);
+ }
+ return Action.None;
+
case Redundant:
case Rejected:
callback.accept(null, new Preempted(txnId, route.homeKey()));
return Action.Aborted;
+
case Insufficient:
// the replica may be missing the original commit, or the additional commit, so send everything
Commit.stableMaximal(node, from, txn, txnId, executeAt, route, stableDeps);
@@ -208,6 +222,11 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
@Override
protected void onDone(Success success, Throwable failure)
{
+ if (localTimeout != null)
+ {
+ localTimeout.cancel();
+ localTimeout = null;
+ }
if (failure == null)
{
Timestamp executeAt = this.executeAt;
@@ -241,12 +260,28 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
'}';
}
+ @Override
+ public void timeout()
+ {
+ onSlowResponse(node.id());
+ localTimeout = null;
+ }
+
+ @Override
+ public int stripe()
+ {
+ return txnId.hashCode();
+ }
+
class LocalExecute extends ReadData
{
private boolean committed;
+ private final SafeCallback<ReadReply> callback;
+
public LocalExecute(TxnId txnId)
{
super(txnId, route, executeAt.epoch());
+ this.callback = new SafeCallback<>(CommandStore.current(), ExecuteTxn.this);
}
@Override
@@ -269,7 +304,11 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
@Override
public void accept(CommitOrReadNack reply, Throwable failure)
{
- if (failure == null && reply == null) committed = true;
+ if (failure == null && reply == null)
+ {
+ committed = true;
+ reply = Waiting;
+ }
super.accept(reply, failure);
}
@@ -286,18 +325,16 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
return false;
// TODO (desired): if we fail to commit locally we can submit a slow/medium path request
- if (txnId.hasPrivilegedCoordinator())
- finishOnFailure(new Timeout(txnId, route.homeKey(), "Could not promptly commit on privileged coordinator"), true);
- else
- onFailure(node.id(), new Timeout(txnId, route.homeKey(), "Could not promptly " + (committed ? "commit to" : "read from") + " local coordinator"));
+ callback.failure(node.id(), new Timeout(txnId, route.homeKey(), "Could not promptly " + (committed ? "commit to" : "read from") + " local coordinator"));
return true;
}
@Override
protected void reply(ReadReply reply, Throwable fail)
{
- if (fail == null) onSuccess(node.id(), reply);
- else onFailure(node.id(), fail);
+ // TODO (required): execute immediately if already on CommandStore
+ if (fail == null) callback.success(node.id(), reply);
+ else callback.failure(node.id(), fail);
}
@Override
diff --git a/accord-core/src/main/java/accord/coordinate/FetchCoordinator.java b/accord-core/src/main/java/accord/coordinate/FetchCoordinator.java
index 3f790d6c..f60d461e 100644
--- a/accord-core/src/main/java/accord/coordinate/FetchCoordinator.java
+++ b/accord-core/src/main/java/accord/coordinate/FetchCoordinator.java
@@ -32,6 +32,7 @@ import accord.topology.Topology;
import accord.utils.Invariants;
import static accord.primitives.Routables.Slice.Minimal;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Invariants.illegalState;
/**
@@ -150,7 +151,7 @@ public abstract class FetchCoordinator
this.fetchRanges = fetchRanges;
// TODO (expected): prioritise nodes that were members in the "prior" epoch also
// (by prior, we mean the prior epoch affecting ownership of this shard, not the prior numerical epoch)
- Topology topology = node.topology().forEpoch(ranges, syncPoint.syncId.epoch()).get(0);
+ Topology topology = node.topology().forEpoch(ranges, syncPoint.syncId.epoch(), SHARE).get(0);
for (Node.Id id : topology.nodes())
{
if (!id.equals(node.id()))
diff --git a/accord-core/src/main/java/accord/coordinate/Invalidate.java b/accord-core/src/main/java/accord/coordinate/Invalidate.java
index 87808210..0f9cc13a 100644
--- a/accord-core/src/main/java/accord/coordinate/Invalidate.java
+++ b/accord-core/src/main/java/accord/coordinate/Invalidate.java
@@ -46,6 +46,7 @@ import static accord.primitives.Status.AcceptedMedium;
import static accord.primitives.Status.PreAccepted;
import static accord.primitives.ProgressToken.INVALIDATED;
import static accord.primitives.ProgressToken.TRUNCATED_DURABLE_OR_INVALIDATED;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Invariants.illegalState;
public class Invalidate implements Callback<InvalidateReply>
@@ -74,7 +75,7 @@ public class Invalidate implements Callback<InvalidateReply>
this.transitivelyInvokedByPriorInvalidation = transitivelyInvokedByPriorInvalidation;
this.reportLowEpoch = reportLowEpoch;
this.reportHighEpoch = reportHighEpoch;
- Topologies topologies = node.topology().forEpoch(invalidateWith, txnId.epoch());
+ Topologies topologies = node.topology().forEpoch(invalidateWith, txnId.epoch(), SHARE);
Invariants.require(topologies.size() == 1);
this.tracker = new InvalidationTracker(topologies, txnId);
this.replies = new SortedListMap<>(topologies.nodes(), InvalidateReply[]::new);
diff --git a/accord-core/src/main/java/accord/coordinate/MaybeRecover.java b/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
index 19946120..81232d89 100644
--- a/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
+++ b/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
@@ -20,7 +20,6 @@ package accord.coordinate;
import java.util.function.BiConsumer;
-import accord.messages.Commit;
import accord.messages.InformDurable;
import accord.primitives.*;
import accord.utils.Invariants;
@@ -31,6 +30,7 @@ import accord.messages.CheckStatus.IncludeInfo;
import accord.utils.UnhandledEnum;
import static accord.coordinate.Infer.InvalidateAndCallback.locallyInvalidateAndCallback;
+import static accord.messages.Commit.Invalidate.commitInvalidate;
/**
* A result of null indicates the transaction is globally persistent
@@ -133,7 +133,7 @@ public class MaybeRecover extends CheckShards<Route<?>>
break;
case Abort:
- Commit.Invalidate.commitInvalidate(node, txnId, Route.merge(full.route, (Route)route), txnId.epoch());
+ commitInvalidate(node, txnId, Route.merge(full.route, (Route)route), txnId.epoch());
locallyInvalidateAndCallback(node, txnId, txnId.epoch(), txnId.epoch(), someRoute, full.toProgressToken(), callback);
break;
}
diff --git a/accord-core/src/main/java/accord/coordinate/Persist.java b/accord-core/src/main/java/accord/coordinate/Persist.java
index a37646e0..a602dff7 100644
--- a/accord-core/src/main/java/accord/coordinate/Persist.java
+++ b/accord-core/src/main/java/accord/coordinate/Persist.java
@@ -55,9 +55,10 @@ public abstract class Persist implements Callback<ApplyReply>
protected final Topologies topologies;
// TODO (expected): track separate ALL and Quorum, so we can report Universal durability to permit faster GC
protected final QuorumTracker tracker;
+ protected final Apply.Factory factory;
boolean isDone;
- protected Persist(Node node, Topologies all, TxnId txnId, Route<?> sendTo, Txn txn, Timestamp executeAt, Deps stableDeps, Writes writes, Result result, FullRoute<?> route)
+ protected Persist(Node node, Topologies all, TxnId txnId, Route<?> sendTo, Txn txn, Timestamp executeAt, Deps stableDeps, Writes writes, Result result, FullRoute<?> route, Apply.Factory factory)
{
this.node = node;
this.txnId = txnId;
@@ -70,6 +71,7 @@ public abstract class Persist implements Callback<ApplyReply>
this.route = route;
this.topologies = all;
this.tracker = new QuorumTracker(all);
+ this.factory = factory;
Invariants.require((writes != null) == txnId.is(Txn.Kind.Write), "%s: writes %s", txnId, writes);
}
@@ -91,7 +93,7 @@ public abstract class Persist implements Callback<ApplyReply>
}
break;
case Insufficient:
- Apply.sendMaximal(node, from, txnId, route, txn, executeAt, stableDeps, writes, result, route);
+ node.send(from, factory.create(Apply.Kind.Maximal, from, topologies, txnId, sendTo, txn, executeAt, stableDeps, writes, result, route));
}
}
@@ -109,7 +111,7 @@ public abstract class Persist implements Callback<ApplyReply>
return false;
}
- public void start(Apply.Factory factory, Apply.Kind kind, Topologies all, Writes writes, Result result)
+ public void start(Apply.Kind kind, Topologies all, Writes writes, Result result)
{
// applyMinimal is used for transaction execution by the original coordinator so it's important to use
// Node's Apply factory in case the factory has to do synchronous Apply.
diff --git a/accord-core/src/main/java/accord/coordinate/PersistSyncPoint.java b/accord-core/src/main/java/accord/coordinate/PersistSyncPoint.java
index 1e1b7f52..9380f936 100644
--- a/accord-core/src/main/java/accord/coordinate/PersistSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/PersistSyncPoint.java
@@ -34,11 +34,11 @@ public class PersistSyncPoint extends Persist
{
public PersistSyncPoint(Node node, Topologies topologies, TxnId txnId, FullRoute<?> route, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result)
{
- super(node, topologies, txnId, route, txn, executeAt, deps, writes, result, route);
+ super(node, topologies, txnId, route, txn, executeAt, deps, writes, result, route, Apply.FACTORY);
}
@Override
- public void start(Apply.Factory factory, Apply.Kind kind, Topologies all, Writes writes, Result result)
+ public void start(Apply.Kind kind, Topologies all, Writes writes, Result result)
{
SortedArrays.SortedArrayList<Node.Id> contact = tracker.filterAndRecordFaulty();
if (contact == null)
diff --git a/accord-core/src/main/java/accord/coordinate/PersistTxn.java b/accord-core/src/main/java/accord/coordinate/PersistTxn.java
index 797e8363..8ddad8f5 100644
--- a/accord-core/src/main/java/accord/coordinate/PersistTxn.java
+++ b/accord-core/src/main/java/accord/coordinate/PersistTxn.java
@@ -20,6 +20,7 @@ package accord.coordinate;
import accord.api.Result;
import accord.local.Node;
+import accord.messages.Apply;
import accord.primitives.Deps;
import accord.primitives.FullRoute;
import accord.primitives.Route;
@@ -31,8 +32,8 @@ import accord.topology.Topologies;
public class PersistTxn extends Persist
{
- public PersistTxn(Node node, Topologies topologies, TxnId txnId, Route<?> sendTo, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, FullRoute<?> route)
+ public PersistTxn(Node node, Topologies topologies, TxnId txnId, Route<?> sendTo, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, FullRoute<?> route, Apply.Factory factory)
{
- super(node, topologies, txnId, sendTo, txn, executeAt, deps, writes, result, route);
+ super(node, topologies, txnId, sendTo, txn, executeAt, deps, writes, result, route, factory);
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/Propose.java b/accord-core/src/main/java/accord/coordinate/Propose.java
index b190550a..f474ae9a 100644
--- a/accord-core/src/main/java/accord/coordinate/Propose.java
+++ b/accord-core/src/main/java/accord/coordinate/Propose.java
@@ -25,6 +25,7 @@ import accord.api.ProtocolModifiers.Faults;
import accord.api.RoutingKey;
import accord.coordinate.tracking.QuorumTracker;
import accord.coordinate.tracking.SimpleTracker;
+import accord.local.Commands.AcceptOutcome;
import accord.local.Node;
import accord.local.Node.Id;
import accord.messages.Accept;
@@ -51,8 +52,10 @@ import static accord.coordinate.ExecutePath.MEDIUM;
import static accord.coordinate.tracking.RequestStatus.Failed;
import static accord.coordinate.tracking.RequestStatus.Success;
import static accord.messages.Commit.Invalidate.commitInvalidate;
+import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Status.AcceptedInvalidate;
import static accord.primitives.TxnId.MediumPath.TrackStable;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Invariants.debug;
abstract class Propose<R> implements Callback<AcceptReply>
@@ -63,21 +66,25 @@ abstract class Propose<R> implements Callback<AcceptReply>
final TxnId txnId;
final Txn txn;
final FullRoute<?> route;
+ final Route<?> require;
final Deps deps;
final SortedListMap<Id, AcceptReply> acceptOks;
final Timestamp executeAt;
final QuorumTracker acceptTracker;
final BiConsumer<? super R, Throwable> callback;
+
+ private Throwable failure;
private boolean isDone;
- Propose(Node node, Topologies topologies, Kind kind, Ballot ballot, TxnId txnId, Txn txn, FullRoute<?> route, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback)
+ Propose(Node node, Topologies topologies, Kind kind, Ballot ballot, TxnId txnId, Txn txn, Route<?> require, FullRoute<?> route, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback)
{
this.node = node;
this.kind = kind;
this.ballot = ballot;
this.txnId = txnId;
this.txn = txn;
+ this.require = require;
this.route = route;
this.deps = deps;
this.executeAt = executeAt;
@@ -93,7 +100,7 @@ abstract class Propose<R> implements Callback<AcceptReply>
{
SortedArrays.SortedArrayList<Node.Id> contact = acceptTracker.filterAndRecordFaulty();
if (contact == null) callback.accept(null, new Timeout(null, null));
- else node.send(contact, to -> new Accept(to, acceptTracker.topologies(), kind, ballot, txnId, route, executeAt, deps), this);
+ else node.send(contact, to -> new Accept(to, acceptTracker.topologies(), kind, ballot, txnId, route, executeAt, deps, require != route), this);
}
@Override
@@ -102,32 +109,35 @@ abstract class Propose<R> implements Callback<AcceptReply>
if (isDone)
return;
- switch (reply.outcome())
+ switch (reply.outcome)
{
default: throw new AssertionError("Unhandled AcceptOutcome: " + reply.outcome());
- case Truncated:
- isDone = true;
- callback.accept(null, new Truncated(txnId, route.homeKey()));
- break;
-
case RejectedBallot:
isDone = true;
callback.accept(null, new Preempted(txnId, route.homeKey()));
break;
+ case Truncated:
case Redundant:
- if (reply.supersededBy != null || ballot.equals(Ballot.ZERO))
+ if (require == route || !isSufficientPartialReply(reply, from))
{
- isDone = true;
- callback.accept(null, new Preempted(txnId, route.homeKey()));
+ Throwable failNow = null;
+ if (reply.outcome == AcceptOutcome.Truncated)
+ failNow = new Truncated(txnId, route.homeKey());
+ else if (reply.supersededBy != null || ballot.equals(Ballot.ZERO))
+ failNow = new Preempted(txnId, route.homeKey());
+
+ if (failNow != null)
+ {
+ isDone = true;
+ callback.accept(null, failNow);
+ }
+ else
+ {
+ onFailure(from, reply.committedExecuteAt == null ? null : new Redundant(txnId, route.homeKey(), reply.committedExecuteAt));
+ }
+ break;
}
- else if (reply.committedExecuteAt != null)
- {
- isDone = true;
- callback.accept(null, new Redundant(txnId, route.homeKey(), reply.committedExecuteAt));
- }
-
- break;
case Retired:
case Success:
@@ -140,17 +150,28 @@ abstract class Propose<R> implements Callback<AcceptReply>
}
}
+ private boolean isSufficientPartialReply(AcceptReply reply, Id from)
+ {
+ return reply.successful != null && reply.successful.containsAll(require.slice(acceptTracker.topologies().computeRangesForNode(from), Minimal));
+ }
+
@Override
public void onFailure(Id from, Throwable failure)
{
+ // TODO (required): verify we are consistent in our error handling;
+ // TODO (desired): find a way to more fully share this common pattern
if (isDone)
return;
- // TODO (required): we aren't tracking the specific failure here to report
+ if (failure != null)
+ this.failure = FailureAccumulator.append(this.failure, failure);
+
if (acceptTracker.recordFailure(from) == Failed)
{
isDone = true;
- callback.accept(null, new Timeout(txnId, route.homeKey()));
+ if (this.failure == null)
+ this.failure = new Exhausted(txnId, route.homeKey(), null);
+ callback.accept(null, this.failure);
}
}
@@ -171,13 +192,24 @@ abstract class Propose<R> implements Callback<AcceptReply>
// I think probably not possible, as we could have a recovery coordinator for some id' < id contact us before our original coordinator does.
// In this case either id' needs to wait (which requires potentially more states like the alternative medium path)
// Or we must pick it up as an Unstable dependency here.
- Deps deps = mergeDeps();
- if (kind == Kind.MEDIUM) adapter().execute(node, acceptTracker.topologies(), route, MEDIUM, txnId, txn, executeAt, deps, callback);
- else adapter().stabilise(node, acceptTracker.topologies(), route, ballot, txnId, txn, executeAt, deps, callback);
+ Deps newDeps = mergeNewDeps();
+ Deps stableDeps = mergeDeps(newDeps);
+ if (kind == Kind.MEDIUM) adapter().execute(node, acceptTracker.topologies(), route, MEDIUM, txnId, txn, executeAt, stableDeps, newDeps, callback);
+ else adapter().stabilise(node, acceptTracker.topologies(), route, ballot, txnId, txn, executeAt, stableDeps, callback);
if (!Invariants.debug()) acceptOks.clear();
}
Deps mergeDeps()
+ {
+ return mergeNewDeps().with(deps);
+ }
+
+ Deps mergeDeps(Deps newDeps)
+ {
+ return Faults.discardPreAcceptDeps(txnId) ? newDeps : newDeps.with(deps);
+ }
+
+ Deps mergeNewDeps()
{
Deps deps = Deps.merge(acceptOks, acceptOks.domainSize(), SortedListMap::getValue, ok -> ok.deps);
if (Faults.discardPreAcceptDeps(txnId))
@@ -185,14 +217,14 @@ abstract class Propose<R> implements Callback<AcceptReply>
if (txnId.is(TrackStable))
{
- // we must not propose as stable any dep < txnId that we did not witness in our original preaccept
- if (!filterDuplicateDependenciesFromAcceptReply())
+ // we must not propose as stable any dep < txnId that we did not propose as part of this phase
+ if (filterDuplicateDependenciesFromAcceptReply())
deps = deps.without(this.deps);
deps = deps.markUnstableBefore(txnId);
}
- return deps.with(this.deps);
+ return deps;
}
abstract CoordinationAdapter<R> adapter();
@@ -231,7 +263,7 @@ abstract class Propose<R> implements Callback<AcceptReply>
public static NotAccept proposeNotAccept(Node node, Status status, Ballot ballot, TxnId txnId, RoutingKey participatingKey, BiConsumer<Void, Throwable> callback)
{
Participants<?> participants = Participants.singleton(txnId.domain(), participatingKey);
- Topologies topologies = node.topology().forEpoch(participants, txnId.epoch());
+ Topologies topologies = node.topology().forEpoch(participants, txnId.epoch(), SHARE);
NotAccept notAccept = new NotAccept(node, status, topologies, ballot, txnId, participants, callback);
node.send(topologies.nodes(), to -> new Accept.NotAccept(status, ballot, txnId, participants), notAccept);
return notAccept;
diff --git a/accord-core/src/main/java/accord/coordinate/ProposeSyncPoint.java b/accord-core/src/main/java/accord/coordinate/ProposeOnly.java
similarity index 68%
copy from accord-core/src/main/java/accord/coordinate/ProposeSyncPoint.java
copy to accord-core/src/main/java/accord/coordinate/ProposeOnly.java
index 54c99265..9bdf5724 100644
--- a/accord-core/src/main/java/accord/coordinate/ProposeSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/ProposeOnly.java
@@ -28,26 +28,32 @@ import accord.messages.Accept;
import accord.primitives.Ballot;
import accord.primitives.Deps;
import accord.primitives.FullRoute;
+import accord.primitives.Route;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Topologies;
-public class ProposeSyncPoint<R> extends Propose<R>
+public class ProposeOnly extends Propose<Deps>
{
@SuppressWarnings("unused")
- private static final Logger logger = LoggerFactory.getLogger(ProposeSyncPoint.class);
- private final CoordinationAdapter<R> adapter;
+ private static final Logger logger = LoggerFactory.getLogger(ProposeOnly.class);
- ProposeSyncPoint(CoordinationAdapter<R> adapter, Node node, Topologies topologies, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback)
+ ProposeOnly(Node node, Topologies topologies, Route<?> sendTo, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Deps, Throwable> callback)
{
- super(node, topologies, kind, ballot, txnId, txn, route, executeAt, deps, callback);
- this.adapter = adapter;
+ super(node, topologies, kind, ballot, txnId, txn, sendTo, route, executeAt, deps, callback);
}
@Override
- CoordinationAdapter<R> adapter()
+ void onAccepted()
{
- return adapter;
+ Deps deps = mergeDeps();
+ callback.accept(deps, null);
+ }
+
+ @Override
+ CoordinationAdapter<Deps> adapter()
+ {
+ throw new UnsupportedOperationException();
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/ProposeSyncPoint.java b/accord-core/src/main/java/accord/coordinate/ProposeSyncPoint.java
index 54c99265..d27735ce 100644
--- a/accord-core/src/main/java/accord/coordinate/ProposeSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/ProposeSyncPoint.java
@@ -41,7 +41,7 @@ public class ProposeSyncPoint<R> extends Propose<R>
ProposeSyncPoint(CoordinationAdapter<R> adapter, Node node, Topologies topologies, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super R, Throwable> callback)
{
- super(node, topologies, kind, ballot, txnId, txn, route, executeAt, deps, callback);
+ super(node, topologies, kind, ballot, txnId, txn, route, route, executeAt, deps, callback);
this.adapter = adapter;
}
diff --git a/accord-core/src/main/java/accord/coordinate/ProposeTxn.java b/accord-core/src/main/java/accord/coordinate/ProposeTxn.java
index 999ba413..66751cf5 100644
--- a/accord-core/src/main/java/accord/coordinate/ProposeTxn.java
+++ b/accord-core/src/main/java/accord/coordinate/ProposeTxn.java
@@ -37,7 +37,7 @@ class ProposeTxn extends Propose<Result>
{
ProposeTxn(Node node, Topologies topologies, FullRoute<?> route, Accept.Kind kind, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps deps, BiConsumer<? super Result, Throwable> callback)
{
- super(node, topologies, kind, ballot, txnId, txn, route, executeAt, deps, callback);
+ super(node, topologies, kind, ballot, txnId, txn, route, route, executeAt, deps, callback);
}
protected CoordinationAdapter<Result> adapter()
diff --git a/accord-core/src/main/java/accord/coordinate/ReadCoordinator.java b/accord-core/src/main/java/accord/coordinate/ReadCoordinator.java
index 2f5ba700..19c3ac99 100644
--- a/accord-core/src/main/java/accord/coordinate/ReadCoordinator.java
+++ b/accord-core/src/main/java/accord/coordinate/ReadCoordinator.java
@@ -35,6 +35,7 @@ import accord.primitives.TxnId;
import accord.topology.Topologies;
import accord.utils.Invariants;
import accord.utils.SortedListMap;
+import accord.utils.UnhandledEnum;
import static accord.primitives.WithQuorum.HasQuorum;
import static accord.primitives.WithQuorum.NoQuorum;
@@ -62,6 +63,8 @@ public abstract class ReadCoordinator<Reply extends accord.messages.Reply> exten
*/
TryAlternative,
+ None,
+
/**
* This response is unsuitable by itself, but if a quorum of such responses is received for the shard
* we will Success.Quorum
@@ -125,11 +128,14 @@ public abstract class ReadCoordinator<Reply extends accord.messages.Reply> exten
if (isDone)
return;
- switch (process(from, reply))
+ Action action = process(from, reply);
+ switch (action)
{
- default: throw new IllegalStateException();
+ default: throw new UnhandledEnum(action);
case Aborted:
isDone = true;
+
+ case None:
break;
case TryAlternative:
@@ -173,7 +179,8 @@ public abstract class ReadCoordinator<Reply extends accord.messages.Reply> exten
if (this.failure == null) this.failure = failure;
else this.failure.addSuppressed(failure);
- handle(recordFailure(from));
+ if (txnId.hasPrivilegedCoordinator() && from.id == node.id().id) finishOnFailure();
+ else handle(recordFailure(from));
}
@Override
diff --git a/accord-core/src/main/java/accord/coordinate/Recover.java b/accord-core/src/main/java/accord/coordinate/Recover.java
index d379b74e..eaee4f66 100644
--- a/accord-core/src/main/java/accord/coordinate/Recover.java
+++ b/accord-core/src/main/java/accord/coordinate/Recover.java
@@ -34,7 +34,6 @@ import accord.coordinate.tracking.RecoveryTracker;
import accord.local.Node;
import accord.local.Node.Id;
import accord.messages.Accept;
-import accord.primitives.Known.KnownDeps;
import accord.primitives.Range;
import accord.primitives.Ranges;
import accord.primitives.RoutingKeys;
@@ -79,12 +78,12 @@ import static accord.coordinate.tracking.RequestStatus.Success;
import static accord.messages.Accept.Kind.SLOW;
import static accord.messages.BeginRecovery.RecoverOk.maxAccepted;
import static accord.messages.BeginRecovery.RecoverOk.maxAcceptedNotTruncated;
-import static accord.primitives.Known.KnownDeps.DepsCommitted;
-import static accord.primitives.Known.KnownDeps.DepsKnown;
import static accord.primitives.ProgressToken.TRUNCATED_DURABLE_OR_INVALIDATED;
import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Status.AcceptedMedium;
+import static accord.primitives.Status.AcceptedSlow;
import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Invariants.illegalState;
import static accord.utils.SortedArrays.Search.CEIL;
import static accord.utils.SortedArrays.Search.FLOOR;
@@ -191,7 +190,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
public static Recover recover(Node node, Ballot ballot, TxnId txnId, Txn txn, FullRoute<?> route, @Nullable Timestamp executeAt, long reportLowEpoch, long reportHighEpoch, BiConsumer<Outcome, Throwable> callback)
{
- Topologies topologies = node.topology().select(route, txnId, executeAt == null ? txnId : executeAt, QuorumEpochIntersections.recover);
+ Topologies topologies = node.topology().select(route, txnId, executeAt == null ? txnId : executeAt, SHARE, QuorumEpochIntersections.recover);
return recover(node, topologies, ballot, txnId, txn, route, executeAt, reportLowEpoch, reportHighEpoch, callback);
}
@@ -233,6 +232,8 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
acceptsFastPath = true;
}
+ // TODO (expected): don't trigger recovery unless we have Q+1 responses, or 1 or more responses have
+ // no entries in WP where it is itself the coordinator. This means we can always recover immediately.
if (tracker.recordSuccess(from, acceptsFastPath) == Success)
recover();
}
@@ -257,7 +258,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
{
Invariants.require(acceptOrCommitNotTruncated.status.compareTo(Status.PreCommitted) < 0 || executeAt.equals(committedExecuteAt));
// if we know from a prior Accept attempt that this is committed we can go straight to the commit phase
- if (status == AcceptedMedium)
+ if (status == AcceptedMedium || status == AcceptedSlow)
status = Status.Committed;
}
switch (status)
@@ -283,7 +284,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
case Stable:
{
withStableDeps(recoverOkList, executeAt, this, stableDeps -> {
- adapter.execute(node, tracker.topologies(), route, RECOVER, txnId, txn, executeAt, stableDeps, this);
+ adapter.execute(node, tracker.topologies(), route, RECOVER, txnId, txn, executeAt, stableDeps, stableDeps, this);
});
return;
}
@@ -465,18 +466,14 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
private void withCommittedDeps(List<RecoverOk> nullableRecoverOkList, Timestamp executeAt, BiConsumer<?, Throwable> failureCallback, Consumer<Deps> withDeps)
{
- withCommittedOrStableDeps(DepsCommitted, nullableRecoverOkList, executeAt, failureCallback, withDeps);
+ LatestDeps.Merge merge = LatestDeps.merge(nullableRecoverOkList, ok -> ok == null ? null : ok.deps);
+ LatestDeps.withCommitted(adapter, node, merge, route, ballot, txnId, executeAt, txn, failureCallback, withDeps);
}
private void withStableDeps(List<RecoverOk> nullableRecoverOkList, Timestamp executeAt, BiConsumer<?, Throwable> failureCallback, Consumer<Deps> withDeps)
{
- withCommittedOrStableDeps(DepsKnown, nullableRecoverOkList, executeAt, failureCallback, withDeps);
- }
-
- private void withCommittedOrStableDeps(KnownDeps atLeast, List<RecoverOk> nullableRecoverOkList, Timestamp executeAt, BiConsumer<?, Throwable> failureCallback, Consumer<Deps> withDeps)
- {
- LatestDeps.MergedCommitResult merged = LatestDeps.mergeCommit(atLeast, executeAt, nullableRecoverOkList, txnId, ok -> ok == null ? null : ok.deps);
- LatestDeps.withCommitted(node, txnId, executeAt, merged.deps, route, route.without(merged.sufficientFor), failureCallback, withDeps);
+ LatestDeps.Merge merge = LatestDeps.merge(nullableRecoverOkList, ok -> ok == null ? null : ok.deps);
+ LatestDeps.withStable(adapter, node, merge, Deps.NONE, route, null, null, route, ballot, txnId, executeAt, txn, failureCallback, withDeps);
}
private void invalidate(SortedListMap<Id, RecoverOk> recoverOks)
@@ -524,8 +521,8 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
{
Topologies topologies = tracker.topologies();
if (executeAt != null && executeAt.epoch() != (this.committedExecuteAt == null ? txnId : this.committedExecuteAt).epoch())
- topologies = node.topology().select(route, txnId, executeAt, QuorumEpochIntersections.recover);
- Recover.recover(node, topologies, ballot, txnId, txn, route, executeAt, reportLowEpoch, reportHighEpoch, callback);
+ topologies = node.topology().select(route, txnId, executeAt, SHARE, QuorumEpochIntersections.recover);
+ Recover.recover(node, topologies, new Ballot(node.uniqueNow()), txnId, txn, route, executeAt, reportLowEpoch, reportHighEpoch, callback);
}
AsyncResult<InferredFastPath> awaitEarlier(Node node, Deps waitOn, BlockedUntil blockedUntil)
@@ -541,8 +538,8 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
Participants<?> participants = waitOn.participants(awaitId);
Topologies topologies;
- if (tracker.topologies().containsEpoch(awaitId.epoch())) topologies = tracker.topologies().selectEpoch(participants, awaitId.epoch());
- else topologies = node.topology().forEpoch(participants, awaitId.epoch());
+ if (tracker.topologies().containsEpoch(awaitId.epoch())) topologies = tracker.topologies().selectEpoch(participants, awaitId.epoch(), SHARE);
+ else topologies = node.topology().forEpoch(participants, awaitId.epoch(), SHARE);
requests.add(SynchronousRecoverAwait.awaitAny(node, topologies, awaitId, blockedUntil, true, participants, recoverId));
}
if (requests.isEmpty())
@@ -609,8 +606,8 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
continue;
Topologies topologies;
- if (tracker.topologies().containsEpoch(awaitId.epoch())) topologies = tracker.topologies().selectEpoch(participants, awaitId.epoch());
- else topologies = node.topology().forEpoch(participants, awaitId.epoch());
+ if (tracker.topologies().containsEpoch(awaitId.epoch())) topologies = tracker.topologies().selectEpoch(participants, awaitId.epoch(), SHARE);
+ else topologies = node.topology().forEpoch(participants, awaitId.epoch(), SHARE);
requests.add(SynchronousRecoverAwait.awaitAny(node, topologies, awaitId, blockedUntil, true, participants, recoverId));
}
if (requests.isEmpty())
diff --git a/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java b/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
index eddec2e2..36becff2 100644
--- a/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
+++ b/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
@@ -35,6 +35,7 @@ import accord.primitives.FullRoute;
import accord.primitives.Known;
import accord.primitives.LatestDeps;
import accord.primitives.Participants;
+import accord.primitives.ProgressToken;
import accord.primitives.Ranges;
import accord.primitives.Route;
import accord.primitives.Status;
@@ -46,15 +47,15 @@ import accord.utils.WrappableException;
import static accord.coordinate.CoordinationAdapter.Factory.Kind.Recovery;
import static accord.primitives.Known.KnownDeps.DepsKnown;
-import static accord.primitives.Known.KnownDeps.DepsUnknown;
import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
import static accord.primitives.Known.Outcome.Apply;
import static accord.primitives.ProgressToken.APPLIED;
import static accord.primitives.ProgressToken.INVALIDATED;
import static accord.primitives.ProgressToken.TRUNCATED_DURABLE_OR_INVALIDATED;
-import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Route.castToFullRoute;
import static accord.primitives.Status.Durability.Majority;
+import static accord.topology.Topologies.SelectNodeOwnership.SLICE;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Invariants.illegalState;
public class RecoverWithRoute extends CheckShards<FullRoute<?>>
@@ -82,7 +83,7 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
public static RecoverWithRoute recover(Node node, TxnId txnId, Infer.InvalidIf invalidIf, FullRoute<?> route, @Nullable Status witnessedByInvalidation, long reportLowEpoch, long reportHighEpoch, BiConsumer<Outcome, Throwable> callback)
{
- return recover(node, node.topology().forEpoch(route, txnId.epoch()), txnId, invalidIf, route, witnessedByInvalidation, reportLowEpoch, reportHighEpoch, callback);
+ return recover(node, node.topology().forEpoch(route, txnId.epoch(), SHARE), txnId, invalidIf, route, witnessedByInvalidation, reportLowEpoch, reportHighEpoch, callback);
}
private static RecoverWithRoute recover(Node node, Topologies topologies, TxnId txnId, Infer.InvalidIf invalidIf, FullRoute<?> route, @Nullable Status witnessedByInvalidation, long reportLowEpoch, long reportHighEpoch, BiConsumer<Outcome, Throwable> callback)
@@ -92,7 +93,7 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
public static RecoverWithRoute recover(Node node, @Nullable Ballot promisedBallot, TxnId txnId, Infer.InvalidIf invalidIf, FullRoute<?> route, @Nullable Status witnessedByInvalidation, long reportLowEpoch, long reportHighEpoch, BiConsumer<Outcome, Throwable> callback)
{
- return recover(node, node.topology().forEpoch(route, txnId.epoch()), promisedBallot, txnId, invalidIf, route, witnessedByInvalidation, reportLowEpoch, reportHighEpoch, callback);
+ return recover(node, node.topology().forEpoch(route, txnId.epoch(), SHARE), promisedBallot, txnId, invalidIf, route, witnessedByInvalidation, reportLowEpoch, reportHighEpoch, callback);
}
private static RecoverWithRoute recover(Node node, Topologies topologies, Ballot ballot, TxnId txnId, Infer.InvalidIf invalidIf, FullRoute<?> route, @Nullable Status witnessedByInvalidation, long reportLowEpoch, long reportHighEpoch, BiConsumer<Outcome, Throwable> callback)
@@ -154,6 +155,7 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
Known known = full.knownFor(txnId, route, route);
// TODO (required): audit this logic, and centralise with e.g. FetchData inferences
+ // TODO (expected): skip straight to ExecuteTxn if we have a Stable reply from each shard
switch (known.outcome())
{
default: throw new AssertionError();
@@ -179,9 +181,16 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
case Apply:
if (!known.isDefinitionKnown())
{
+ if (!known.isTruncated() && !known.isInvalidated())
+ {
+ // we must have raced with a successful apply, so should simply abort
+ callback.accept(ProgressToken.NONE, null);
+ return;
+ }
+
// TODO (expected): if we determine new durability, propagate it
CheckStatusOkFull propagate;
- if (full.map.hasFullyTruncated(route))
+ if (!full.map.hasFullyTruncated(route))
{
// we might have only part of the full transaction, and a shard may have truncated;
// in this case we want to skip straight to apply, but only for the shards that haven't truncated
@@ -195,31 +204,25 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
else
{
known = full.knownFor(txnId, trySendTo, trySendTo);
- Invariants.require(known.isExecuteAtKnown() && known.outcome() == Apply);
+ Invariants.require(known.isDefinitionKnown() && known.isExecuteAtKnown() && known.outcome() == Apply);
if (!known.is(DepsKnown))
{
Invariants.require(txnId.isSystemTxn() || full.partialTxn.covers(trySendTo));
- Participants<?> collect = full.map.knownFor(Known.Nothing.with(DepsKnown), route);
- // we don't simply calculate deps as we may have raced with
- CollectLatestDeps.withLatestDeps(node, txnId, route, collect, full.executeAt, (deps, fail) -> {
- if (fail != null)
- {
- node.agent().acceptAndWrap(null, fail);
- return;
- }
+ Participants<?> haveStable = full.map.knownFor(Known.DepsOnly, route);
+ Route<?> haveUnstable = route.without(haveStable);
+ Deps stable = full.stableDeps.reconstitutePartial(haveStable).asFullUnsafe();
- LatestDeps.MergedCommitResult mergedCommit = LatestDeps.mergeCommit(DepsUnknown, full.executeAt, deps, full.executeAt, i -> i);
- Route<?> canSendTo = trySendTo.without(collect).with((Participants) collect.slice(mergedCommit.sufficientFor, Minimal));
- Deps stableDeps = full.stableDeps.with(mergedCommit.deps).intersecting(canSendTo);
- node.coordinationAdapter(txnId, Recovery).persist(node, null, route, canSendTo, txnId, full.partialTxn, full.executeAt, stableDeps, full.writes, full.result, null);
+ LatestDeps.withStable(node.coordinationAdapter(txnId, Recovery), node, txnId, full.executeAt, full.partialTxn, stable, haveUnstable, trySendTo, SLICE, route, callback, deps -> {
+ Deps stableDeps = deps.intersecting(trySendTo);
+ node.coordinationAdapter(txnId, Recovery).persist(node, null, trySendTo, trySendTo, SLICE, route, txnId, full.partialTxn, full.executeAt, stableDeps, full.writes, full.result, null);
});
}
else
{
Invariants.require(full.stableDeps.covers(trySendTo));
Invariants.require(txnId.isSystemTxn() || full.partialTxn.covers(trySendTo));
- node.coordinationAdapter(txnId, Recovery).persist(node, null, route, trySendTo, txnId, full.partialTxn, full.executeAt, full.stableDeps, full.writes, full.result, null);
+ node.coordinationAdapter(txnId, Recovery).persist(node, null, trySendTo, trySendTo, SLICE, route, txnId, full.partialTxn, full.executeAt, full.stableDeps, full.writes, full.result, null);
}
}
propagate = full;
@@ -242,7 +245,7 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
if (known.is(ApplyAtKnown) && known.outcome() == Apply)
{
Deps deps;
- Participants<?> missingDeps;
+ Route<?> missingDeps;
if (known.is(DepsKnown))
{
deps = full.stableDeps.reconstitute(route);
@@ -256,11 +259,12 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
// PartialDeps if e.g. an empty range of deps is found
deps = new Deps(full.stableDeps.reconstitutePartial(hasDeps));
}
- LatestDeps.withCommitted(node, txnId, full.executeAt, deps, route, missingDeps, callback, mergedDeps -> {
+ LatestDeps.withStable(node.coordinationAdapter(txnId, Recovery), node, txnId, full.executeAt, full.partialTxn, deps, missingDeps, route, SHARE, route, callback, mergedDeps -> {
node.withEpoch(full.executeAt.epoch(), node.agent(), t -> WrappableException.wrap(t), () -> {
- node.coordinationAdapter(txnId, Recovery).persist(node, topologies, route, txnId, txn, full.executeAt, mergedDeps, full.writes, full.result, node.agent());
+ node.coordinationAdapter(txnId, Recovery).persist(node, topologies, route, txnId, txn, full.executeAt, mergedDeps, full.writes, full.result, (s, f) -> {
+ callback.accept(f == null ? APPLIED : null, f);
+ });
});
- callback.accept(APPLIED, null);
});
}
else
diff --git a/accord-core/src/main/java/accord/coordinate/Stabilise.java b/accord-core/src/main/java/accord/coordinate/Stabilise.java
index 25958400..a7cb15e3 100644
--- a/accord-core/src/main/java/accord/coordinate/Stabilise.java
+++ b/accord-core/src/main/java/accord/coordinate/Stabilise.java
@@ -31,6 +31,7 @@ import accord.messages.ReadData.ReadReply;
import accord.primitives.Ballot;
import accord.primitives.Deps;
import accord.primitives.FullRoute;
+import accord.primitives.Route;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
@@ -50,6 +51,7 @@ public abstract class Stabilise<R> implements Callback<ReadReply>
final Node node;
final Txn txn;
final FullRoute<?> route;
+ final Route<?> sendTo;
final TxnId txnId;
final Ballot ballot;
final Timestamp executeAt;
@@ -61,10 +63,11 @@ public abstract class Stabilise<R> implements Callback<ReadReply>
final BiConsumer<? super R, Throwable> callback;
private boolean isDone;
- public Stabilise(Node node, Topologies coordinates, Topologies allTopologies, FullRoute<?> route, TxnId txnId, Ballot ballot, Txn txn, Timestamp executeAt, Deps stabiliseDeps, BiConsumer<? super R, Throwable> callback)
+ public Stabilise(Node node, Topologies coordinates, Topologies allTopologies, Route<?> sendTo, FullRoute<?> route, TxnId txnId, Ballot ballot, Txn txn, Timestamp executeAt, Deps stabiliseDeps, BiConsumer<? super R, Throwable> callback)
{
this.node = node;
this.txn = txn;
+ this.sendTo = sendTo;
this.route = route;
this.txnId = txnId;
this.ballot = ballot;
@@ -154,7 +157,7 @@ public abstract class Stabilise<R> implements Callback<ReadReply>
protected void onStabilised()
{
- adapter().execute(node, allTopologies, route, ballot == Ballot.ZERO ? SLOW : RECOVER, txnId, txn, executeAt, stabiliseDeps, callback);
+ adapter().execute(node, allTopologies, route, ballot == Ballot.ZERO ? SLOW : RECOVER, txnId, txn, executeAt, stabiliseDeps, stabiliseDeps, callback);
}
protected abstract CoordinationAdapter<R> adapter();
diff --git a/accord-core/src/main/java/accord/coordinate/StabiliseTxn.java b/accord-core/src/main/java/accord/coordinate/StabiliseOnly.java
similarity index 65%
copy from accord-core/src/main/java/accord/coordinate/StabiliseTxn.java
copy to accord-core/src/main/java/accord/coordinate/StabiliseOnly.java
index 0750dd18..b82b8655 100644
--- a/accord-core/src/main/java/accord/coordinate/StabiliseTxn.java
+++ b/accord-core/src/main/java/accord/coordinate/StabiliseOnly.java
@@ -20,28 +20,32 @@ package accord.coordinate;
import java.util.function.BiConsumer;
-import accord.api.Result;
import accord.local.Node;
import accord.primitives.Ballot;
import accord.primitives.Deps;
import accord.primitives.FullRoute;
+import accord.primitives.Route;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Topologies;
-import static accord.coordinate.CoordinationAdapter.Factory.Kind.Standard;
-
-public class StabiliseTxn extends Stabilise<Result>
+public class StabiliseOnly extends Stabilise<Deps>
{
- StabiliseTxn(Node node, Topologies coordinates, Topologies all, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps unstableDeps, BiConsumer<? super Result, Throwable> callback)
+ StabiliseOnly(Node node, Topologies coordinates, Topologies all, Route<?> sendTo, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps unstableDeps, BiConsumer<? super Deps, Throwable> callback)
+ {
+ super(node, coordinates, all, sendTo, route, txnId, ballot, txn, executeAt, unstableDeps, callback);
+ }
+
+ @Override
+ protected void onStabilised()
{
- super(node, coordinates, all, route, txnId, ballot, txn, executeAt, unstableDeps, callback);
+ callback.accept(stabiliseDeps, null);
}
@Override
- protected CoordinationAdapter<Result> adapter()
+ protected CoordinationAdapter<Deps> adapter()
{
- return node.coordinationAdapter(txnId, Standard);
+ throw new UnsupportedOperationException();
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/StabiliseSyncPoint.java b/accord-core/src/main/java/accord/coordinate/StabiliseSyncPoint.java
index 9857d341..be70c778 100644
--- a/accord-core/src/main/java/accord/coordinate/StabiliseSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/StabiliseSyncPoint.java
@@ -34,7 +34,7 @@ public class StabiliseSyncPoint<R> extends Stabilise<R>
final CoordinationAdapter<R> adapter;
StabiliseSyncPoint(CoordinationAdapter<R> adapter, Node node, Topologies coordinates, Topologies all, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps unstableDeps, BiConsumer<? super R, Throwable> callback)
{
- super(node, coordinates, all, route, txnId, ballot, txn, executeAt, unstableDeps, callback);
+ super(node, coordinates, all, route, route, txnId, ballot, txn, executeAt, unstableDeps, callback);
this.adapter = adapter;
}
diff --git a/accord-core/src/main/java/accord/coordinate/StabiliseTxn.java b/accord-core/src/main/java/accord/coordinate/StabiliseTxn.java
index 0750dd18..6428d489 100644
--- a/accord-core/src/main/java/accord/coordinate/StabiliseTxn.java
+++ b/accord-core/src/main/java/accord/coordinate/StabiliseTxn.java
@@ -36,7 +36,7 @@ public class StabiliseTxn extends Stabilise<Result>
{
StabiliseTxn(Node node, Topologies coordinates, Topologies all, FullRoute<?> route, Ballot ballot, TxnId txnId, Txn txn, Timestamp executeAt, Deps unstableDeps, BiConsumer<? super Result, Throwable> callback)
{
- super(node, coordinates, all, route, txnId, ballot, txn, executeAt, unstableDeps, callback);
+ super(node, coordinates, all, route, route, txnId, ballot, txn, executeAt, unstableDeps, callback);
}
@Override
diff --git a/accord-core/src/main/java/accord/coordinate/tracking/ReadTracker.java b/accord-core/src/main/java/accord/coordinate/tracking/ReadTracker.java
index 6e6d2834..ddec94a2 100644
--- a/accord-core/src/main/java/accord/coordinate/tracking/ReadTracker.java
+++ b/accord-core/src/main/java/accord/coordinate/tracking/ReadTracker.java
@@ -236,8 +236,7 @@ public class ReadTracker extends AbstractTracker<ReadTracker.ReadShardTracker>
@VisibleForTesting
protected void recordInFlightRead(Id node)
{
- if (!inflight.add(node.id))
- throw illegalState(node + " already in flight");
+ Invariants.require(inflight.add(node.id), "%s already in flight", node);
recordResponse(this, node, ReadShardTracker::recordInFlightRead, false);
}
@@ -256,7 +255,7 @@ public class ReadTracker extends AbstractTracker<ReadTracker.ReadShardTracker>
protected RequestStatus recordSlowResponse(Id from)
{
if (!inflight.contains(from.id))
- throw new IllegalStateException();
+ return RequestStatus.NoChange;
if (slow == null)
slow = new IntHashSet(topologies.nodes().size());
diff --git a/accord-core/src/main/java/accord/impl/CommandChange.java b/accord-core/src/main/java/accord/impl/CommandChange.java
index 28fb3b23..10306182 100644
--- a/accord-core/src/main/java/accord/impl/CommandChange.java
+++ b/accord-core/src/main/java/accord/impl/CommandChange.java
@@ -48,7 +48,6 @@ import accord.utils.UnhandledEnum;
import static accord.api.Journal.Load;
import static accord.api.Journal.Load.ALL;
import static accord.impl.CommandChange.Field.ACCEPTED;
-import static accord.impl.CommandChange.Field.CLEANUP;
import static accord.impl.CommandChange.Field.DURABILITY;
import static accord.impl.CommandChange.Field.EXECUTES_AT_LEAST;
import static accord.impl.CommandChange.Field.EXECUTE_AT;
@@ -63,7 +62,6 @@ import static accord.impl.CommandChange.Field.SAVE_STATUS;
import static accord.impl.CommandChange.Field.WAITING_ON;
import static accord.impl.CommandChange.Field.WRITES;
import static accord.local.Cleanup.NO;
-import static accord.local.Cleanup.TRUNCATE_WITH_OUTCOME;
import static accord.local.Command.Accepted.accepted;
import static accord.local.Command.Committed.committed;
import static accord.local.Command.Executed.executed;
@@ -111,7 +109,7 @@ public class CommandChange
* which we can use in order to mark the corresponding fields as changed
* and setting them to null when they are erased.
*/
- public static int[] saveStatusMasks;
+ protected static final int[] saveStatusMasks;
static
{
@@ -121,13 +119,22 @@ public class CommandChange
SaveStatus saveStatus = SaveStatus.forOrdinal(i);
int mask = 0;
if (forceFieldChangedToNullFlag(saveStatus, saveStatus.known::is, DepsErased))
- mask |= setFieldIsNullAndChanged(PARTIAL_DEPS, mask);
+ mask |= setFieldIsNullAndChanged(PARTIAL_DEPS, mask)
+ | setFieldIsNullAndChanged(WAITING_ON, mask)
+ | setFieldIsNullAndChanged(MIN_UNIQUE_HLC, mask);
if (forceFieldChangedToNullFlag(saveStatus, saveStatus.known::is, ExecuteAtErased))
- mask |= setFieldIsNullAndChanged(EXECUTE_AT, mask);
+ mask |= setFieldIsNullAndChanged(EXECUTE_AT, mask)
+ | setFieldIsNullAndChanged(EXECUTES_AT_LEAST, mask);
if (forceFieldChangedToNullFlag(saveStatus, saveStatus.known::is, DefinitionErased))
mask |= setFieldIsNullAndChanged(PARTIAL_TXN, mask);
if (forceFieldChangedToNullFlag(saveStatus, saveStatus.known::is, WasApply))
- mask |= setFieldIsNullAndChanged(RESULT, mask);
+ mask |= setFieldIsNullAndChanged(RESULT, mask)
+ | setFieldIsNullAndChanged(WRITES, mask);
+ if (saveStatus.hasBeen(Status.Truncated))
+ mask |= setFieldIsNullAndChanged(PROMISED, mask)
+ | setFieldIsNullAndChanged(ACCEPTED, mask);
+ if (saveStatus == SaveStatus.Invalidated || saveStatus == SaveStatus.Vestigial)
+ mask |= setFieldIsNullAndChanged(DURABILITY, mask);
saveStatusMasks[i] = mask;
}
}
@@ -137,7 +144,7 @@ public class CommandChange
return saveStatus == SaveStatus.Vestigial || predicate.test(erased);
}
- public static class Builder
+ public static abstract class Builder
{
protected final int mask;
protected int flags;
@@ -187,6 +194,11 @@ public class CommandChange
this(ALL);
}
+ public TxnId txnId()
+ {
+ return txnId;
+ }
+
public SaveStatus saveStatus()
{
return saveStatus;
@@ -264,84 +276,58 @@ public class CommandChange
return cleanup;
}
- public Builder maybeCleanup(Cleanup cleanup)
+ public boolean maybeCleanup(Input input, Agent agent, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
- if (saveStatus == null)
- return this;
-
- switch (cleanup)
- {
- case EXPUNGE:
- case ERASE:
- return null;
-
- case VESTIGIAL:
- case INVALIDATE:
- return saveStatusOnly();
-
- case TRUNCATE_WITH_OUTCOME:
- case TRUNCATE:
- return expungePartial(cleanup, cleanup.appliesIfNot, cleanup == TRUNCATE_WITH_OUTCOME);
-
- case NO:
- return this;
- default:
- throw new UnhandledEnum(cleanup);
- }
+ Cleanup cleanup = shouldCleanup(input, agent, redundantBefore, durableBefore);
+ return maybeCleanup(input, cleanup);
}
- public Builder expungePartial(Cleanup cleanup, SaveStatus saveStatus, boolean includeOutcome)
+ public boolean maybeCleanup(Input input, Cleanup cleanup)
{
- Invariants.require(txnId != null);
- Builder builder = new Builder(txnId, ALL);
+ if (saveStatus == null)
+ return false;
- builder.count++;
- builder.nextCalled = true;
+ cleanup = cleanup.filter(saveStatus);
+ if (cleanup == NO)
+ return false;
- Invariants.require(saveStatus != null);
- builder.flags = setChanged(SAVE_STATUS, builder.flags);
- builder.saveStatus = saveStatus;
- builder.flags = setChanged(CLEANUP, builder.flags);
- builder.cleanup = cleanup;
- if (executeAt != null)
- {
- builder.flags = setChanged(EXECUTE_AT, builder.flags);
- builder.executeAt = executeAt;
- }
- if (durability != null)
+ SaveStatus newSaveStatus = cleanup.appliesIfNot;
+ truncate(saveStatusMasks[newSaveStatus.ordinal()]);
+ if (input == Input.FULL)
{
- builder.flags = setChanged(DURABILITY, builder.flags);
- builder.durability = durability;
+ if (newSaveStatus == SaveStatus.TruncatedApply && !saveStatus.known.is(ApplyAtKnown))
+ newSaveStatus = SaveStatus.TruncatedUnapplied;
+ saveStatus = newSaveStatus;
}
- if (participants != null)
- {
- builder.flags = setChanged(PARTICIPANTS, builder.flags);
- builder.participants = participants;
- }
- if (includeOutcome && builder.writes != null)
- {
- builder.flags = setChanged(WRITES, builder.flags);
- builder.writes = writes;
- }
-
- return builder;
+ return true;
}
- public Builder saveStatusOnly()
+ protected void truncate(int mask)
{
- Invariants.require(txnId != null);
- Builder builder = new Builder(txnId, ALL);
-
- builder.count++;
- builder.nextCalled = true;
-
- if (saveStatus != null)
+ // low flag bits represent fields already nulled out, so no need to visit them again
+ int iterable = toIterableSetFields(mask) & ~flags;
+ for (Field next = nextSetField(iterable); next != null; iterable = unsetIterable(next, iterable), next = nextSetField(iterable))
{
- builder.flags = setChanged(SAVE_STATUS, builder.flags);
- builder.saveStatus = saveStatus;
+ switch (next)
+ {
+ default: throw new UnhandledEnum(next);
+ case PARTICIPANTS: participants = null; break;
+ case SAVE_STATUS: saveStatus = null; break;
+ case PARTIAL_DEPS: partialDeps = null; break;
+ case EXECUTE_AT: executeAt = null; break;
+ case EXECUTES_AT_LEAST: executeAtLeast = null; break;
+ case MIN_UNIQUE_HLC: minUniqueHlc = 0; break;
+ case DURABILITY: durability = null; break;
+ case ACCEPTED: acceptedOrCommitted = null; break;
+ case PROMISED: promised = null; break;
+ case WAITING_ON: waitingOnBytes = null; waitingOn = null; break;
+ case PARTIAL_TXN: partialTxn = null; break;
+ case WRITES: writes = null; break;
+ case CLEANUP: cleanup = null; break;
+ case RESULT: result = null; break;
+ }
}
-
- return builder;
+ flags |= mask;
}
public Command.Minimal asMinimal()
@@ -587,6 +573,22 @@ public class CommandChange
return iterable & ~(1 << field.ordinal());
}
+ public static String describeFlags(int flags)
+ {
+ int iterable = toIterableSetFields(flags);
+ StringBuilder builder = new StringBuilder("[");
+ for (Field next = nextSetField(iterable) ; next != null; iterable = unsetIterable(next, iterable), next = nextSetField(iterable))
+ {
+ if (builder.length() > 1)
+ builder.append(',');
+ builder.append(next);
+ if (isNull(next, flags))
+ builder.append(":null");
+ }
+ builder.append(']');
+ return builder.toString();
+ }
+
@VisibleForTesting
public static boolean isNull(Field field, int oldFlags)
{
diff --git a/accord-core/src/main/java/accord/impl/DurabilityScheduling.java b/accord-core/src/main/java/accord/impl/DurabilityScheduling.java
index 6a166614..76c244f8 100644
--- a/accord-core/src/main/java/accord/impl/DurabilityScheduling.java
+++ b/accord-core/src/main/java/accord/impl/DurabilityScheduling.java
@@ -481,7 +481,7 @@ public class DurabilityScheduling implements ConfigurationService.Listener
try
{
long epoch = node.epoch();
- AsyncChain<AsyncResult<Void>> resultChain = node.withEpoch(epoch, () -> node.commandStores().any().submit(() -> CoordinateGloballyDurable.coordinate(node, epoch)));
+ AsyncChain<AsyncResult<Void>> resultChain = node.withEpoch(epoch, () -> node.commandStores().any().build(() -> CoordinateGloballyDurable.coordinate(node, epoch)));
resultChain.begin((success, fail) -> {
if (fail != null) logger.trace("Exception initiating coordination of global durability", fail);
else logger.trace("Successful coordination of global durability");
diff --git a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
index 9531099e..dbd1753a 100644
--- a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
+++ b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
@@ -669,10 +669,8 @@ public abstract class InMemoryCommandStore extends CommandStore
if (updated.saveStatus() == Erased || updated.saveStatus() == Vestigial)
return;
- Ranges slice = ranges(txnId, updated.executeAtOrTxnId());
- slice = commandStore().unsafeGetRedundantBefore().removeGcBefore(txnId, updated.executeAtOrTxnId(), slice);
commandStore().rangeCommands.computeIfAbsent(txnId, ignore -> new RangeCommand(commandStore().commands.get(txnId)))
- .update(((AbstractRanges)updated.participants().touches()).toRanges().slice(slice, Minimal));
+ .update(((AbstractRanges)updated.participants().stillTouches()).toRanges());
}
@Override
@@ -878,7 +876,7 @@ public abstract class InMemoryCommandStore extends CommandStore
}
@Override
- public <T> AsyncChain<T> submit(Callable<T> task)
+ public <T> AsyncChain<T> build(Callable<T> task)
{
return new AsyncChains.Head<T>()
{
@@ -952,7 +950,7 @@ public abstract class InMemoryCommandStore extends CommandStore
}
@Override
- public <T> AsyncChain<T> submit(Callable<T> task)
+ public <T> AsyncChain<T> build(Callable<T> task)
{
return AsyncChains.ofCallable(executor, task);
}
diff --git a/accord-core/src/main/java/accord/impl/progresslog/PackedKeyTracker.java b/accord-core/src/main/java/accord/impl/progresslog/PackedKeyTracker.java
index 3b24bedf..2f0c6f30 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/PackedKeyTracker.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/PackedKeyTracker.java
@@ -20,7 +20,6 @@ package accord.impl.progresslog;
import accord.local.Node;
import accord.primitives.Ranges;
-import accord.primitives.Routables;
import accord.primitives.Route;
import accord.primitives.TxnId;
import accord.primitives.Unseekables;
@@ -115,7 +114,7 @@ public class PackedKeyTracker
int bitSet = 0, start = roundSize * roundIndex, ai = start, bi = 0;
for (int i = 0; i < intersecting.size(); ++i)
{
- long abi = route.findNextIntersection(ai, (Routables) intersecting, bi);
+ long abi = route.findNextSameKindIntersection(ai, (Unseekables) intersecting, bi);
if (abi < 0)
break;
diff --git a/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java b/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java
index 9d018b79..9dea6210 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java
@@ -34,7 +34,6 @@ import accord.primitives.SaveStatus;
import accord.primitives.Status;
import accord.local.StoreParticipants;
import accord.primitives.Participants;
-import accord.primitives.Routables;
import accord.primitives.Route;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
@@ -66,6 +65,7 @@ import static accord.impl.progresslog.WaitingState.CallbackKind.AwaitSlice;
import static accord.impl.progresslog.WaitingState.CallbackKind.Fetch;
import static accord.impl.progresslog.WaitingState.CallbackKind.FetchRoute;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
/**
* This represents a simple state machine encoded in a small number of bits for efficiently gathering
@@ -227,7 +227,7 @@ abstract class WaitingState extends BaseTxnState
Topologies contact(DefaultProgressLog owner, Unseekables<?> forKeys, long epoch)
{
Node node = owner.node();
- Topologies topologies = node.topology().forEpoch(forKeys, epoch);
+ Topologies topologies = node.topology().forEpoch(forKeys, epoch, SHARE);
return node.agent().selectPreferred(node.id(), topologies);
}
@@ -459,7 +459,7 @@ abstract class WaitingState extends BaseTxnState
int prevRoundStart = prevRoundIndex * prevRoundSize;
int newRoundIndex = -1;
if (prevRoundStart < prevAwaitRoute.size())
- newRoundIndex = (int)awaitRoute.findNextIntersection(0, (Routables)prevAwaitRoute, prevRoundStart + prevRoundIndex);
+ newRoundIndex = (int)awaitRoute.findNextSameKindIntersection(0, (Unseekables)prevAwaitRoute, prevRoundStart + prevRoundIndex);
if (newRoundIndex < 0)
newRoundIndex = awaitRoute.size();
updateAwaitRound(newRoundIndex, roundSize);
@@ -550,14 +550,14 @@ abstract class WaitingState extends BaseTxnState
{
if (notReady == null)
{
- Invariants.expect((int) awaitRoute.findNextIntersection(roundStart, (Routables) ready, 0) / roundSize == roundIndex);
+ Invariants.expect((int) awaitRoute.findNextSameKindIntersection(roundStart, (Unseekables) ready, 0) / roundSize == roundIndex);
// TODO (desired): in this case perhaps upgrade to fetch for next round?
state.updateAwaitRound(roundIndex + 1, roundSize);
state.runInternal(safeStore, safeCommand, owner);
}
else
{
- Invariants.expect((int) awaitRoute.findNextIntersection(roundStart, (Routables) notReady, 0) / roundSize == roundIndex);
+ Invariants.expect((int) awaitRoute.findNextSameKindIntersection(roundStart, (Unseekables) notReady, 0) / roundSize == roundIndex);
// TODO (desired): would be nice to validate this is 0 in cases where we are starting a fresh round
// but have to be careful as cannot zero when we restart as we may have an async callback arrive while we're waiting that then advances state machine
state.initialiseAwaitBitSet(awaitRoute, notReady, roundIndex, roundSize);
@@ -581,7 +581,7 @@ abstract class WaitingState extends BaseTxnState
Invariants.require(notReady.intersects(slicedRoute), "Fetch was successful for all keys, but the WaitingState has not been cleared");
int nextIndex;
if (roundStart >= awaitRoute.size()) nextIndex = -1;
- else if (slicedRoute == awaitRoute) nextIndex = (int) awaitRoute.findNextIntersection(roundStart, (Routables) notReady, 0);
+ else if (slicedRoute == awaitRoute) nextIndex = (int) awaitRoute.findNextSameKindIntersection(roundStart, (Unseekables) notReady, 0);
else
{
Invariants.require(roundIndex == 0);
diff --git a/accord-core/src/main/java/accord/local/AgentExecutor.java b/accord-core/src/main/java/accord/local/AgentExecutor.java
index e304cc21..50c46f08 100644
--- a/accord-core/src/main/java/accord/local/AgentExecutor.java
+++ b/accord-core/src/main/java/accord/local/AgentExecutor.java
@@ -28,6 +28,11 @@ public interface AgentExecutor extends AsyncExecutor
@Override
default void execute(Runnable command)
{
- submit(command).begin(agent());
+ build(command).begin(agent());
+ }
+
+ default void maybeExecuteImmediately(Runnable command)
+ {
+ execute(command);
}
}
diff --git a/accord-core/src/main/java/accord/local/Command.java b/accord-core/src/main/java/accord/local/Command.java
index b66666bc..807bd933 100644
--- a/accord-core/src/main/java/accord/local/Command.java
+++ b/accord-core/src/main/java/accord/local/Command.java
@@ -144,6 +144,8 @@ public abstract class Command implements ICommand
this.partialDeps = partialDeps;
this.executeAt = executeAt;
this.acceptedOrCommitted = Invariants.nonNull(acceptedOrCommitted);
+ Invariants.require(partialTxn == null || txnId.isSystemTxn() || participants.owns().containsAll(partialTxn.keys()));
+ Invariants.require(partialTxn == null || txnId.isSystemTxn() || participants.owns().containsAll(partialTxn.read().keys()));
}
protected Command(TxnId txnId, SaveStatus saveStatus, Durability durability, @Nonnull StoreParticipants participants, Ballot promised, Timestamp executeAt, @Nullable PartialTxn partialTxn, @Nullable PartialDeps partialDeps, Ballot acceptedOrCommitted, boolean unsafeInitialisation)
@@ -438,6 +440,7 @@ public abstract class Command implements ICommand
public static Truncated truncated(Command command, @Nonnull StoreParticipants participants)
{
Invariants.requireArgument(command.known().isExecuteAtKnown());
+ // TODO (expected): centralise this translation so applied consistently
SaveStatus newSaveStatus = command.known().is(ApplyAtKnown) ? TruncatedApply : TruncatedUnapplied;
Durability durability = Durability.mergeAtLeast(command.durability(), ShardUniversal);
if (command.txnId().awaitsOnlyDeps())
@@ -524,7 +527,6 @@ public abstract class Command implements ICommand
this.result = copy.result();
}
- // TODO (required): is Ballot.MAX helpful or harmful here? We must consider how to best protect against infinite reject loops.
public Truncated(TxnId txnId, SaveStatus saveStatus, Durability durability, @Nonnull StoreParticipants participants, @Nullable Timestamp executeAt, @Nullable Writes writes, @Nullable Result result)
{
super(txnId, saveStatus, durability, participants, Ballot.MAX, executeAt, null, null, Ballot.MAX);
@@ -1542,10 +1544,10 @@ public abstract class Command implements ICommand
command.acceptedOrCommitted());
}
- static Command.Accepted accept(Command current, SaveStatus saveStatus, @Nonnull StoreParticipants participants, Ballot promised, Timestamp executeAt, PartialDeps partialDeps, Ballot acceptedOrCommitted)
+ static Command.Accepted accept(Command current, SaveStatus saveStatus, @Nonnull StoreParticipants participants, Ballot promised, Timestamp executeAt, PartialTxn partialTxn, PartialDeps partialDeps, Ballot acceptedOrCommitted)
{
- Invariants.require(saveStatus.status == Status.AcceptedSlow || saveStatus.status == Status.AcceptedMedium);
- return validate(new Command.Accepted(current.txnId(), saveStatus, current.durability(), participants, promised, executeAt, current.partialTxn(), partialDeps, acceptedOrCommitted));
+ Invariants.require(saveStatus.status == Status.AcceptedSlow || saveStatus.status == Status.AcceptedMedium || saveStatus.status == Status.PreCommitted);
+ return validate(new Command.Accepted(current.txnId(), saveStatus, current.durability(), participants, promised, executeAt, partialTxn, partialDeps, acceptedOrCommitted));
}
static Command notAccept(Status newStatus, Command copy, Ballot ballot)
@@ -1576,13 +1578,13 @@ public abstract class Command implements ICommand
Ballot.max(ballot, command.acceptedOrCommitted()), waitingOn));
}
- static Command precommit(Command command, Timestamp executeAt)
+ static Command precommit(Command command, Timestamp executeAt, Ballot promisedAtLeast)
{
SaveStatus saveStatus = SaveStatus.get(Status.PreCommitted, command.known());
PartialDeps partialDeps = command.partialDeps();
if (!saveStatus.known.deps().hasProposedOrDecidedDeps() && command.partialDeps() != null)
partialDeps = null;
- return validate(new Command.Accepted(command.txnId, saveStatus, command.durability, command.participants, command.promised, executeAt, command.partialTxn, partialDeps, command.acceptedOrCommitted));
+ return validate(new Command.Accepted(command.txnId, saveStatus, command.durability, command.participants, Ballot.max(command.promised, promisedAtLeast), executeAt, command.partialTxn, partialDeps, command.acceptedOrCommitted));
}
static Command.Committed readyToExecute(Command.Committed command)
diff --git a/accord-core/src/main/java/accord/local/CommandSummaries.java b/accord-core/src/main/java/accord/local/CommandSummaries.java
index 33fd918a..b04b1804 100644
--- a/accord-core/src/main/java/accord/local/CommandSummaries.java
+++ b/accord-core/src/main/java/accord/local/CommandSummaries.java
@@ -188,24 +188,24 @@ public interface CommandSummaries
if (!txnId.is(testKind))
return null;
- // TODO (desired): generalise this better for key loading
- Ranges ranges = touches.toRanges().intersecting(searchKeysOrRanges, Minimal);
- if (ranges.isEmpty())
+ // start in search key domain, since this is what we consult to decide if can be recovered
+ Unseekables<?> intersecting = searchKeysOrRanges.intersecting(touches, Minimal);
+ if (intersecting.isEmpty())
return null;
if (redundantBefore != null)
{
// TODO (expected): consider whether this is necessary (and document it).
- Ranges newRanges = redundantBefore.foldlWithBounds(ranges, (e, accum, start, end) -> {
+ Unseekables<?> newIntersecting = redundantBefore.foldlWithBounds(intersecting, (e, accum, start, end) -> {
if (e.gcBefore.compareTo(txnId) <= 0)
return accum;
return accum.without(Ranges.of(start.rangeFactory().newRange(start, end)));
- }, ranges, ignore -> false);
+ }, intersecting, ignore -> false);
- if (newRanges.isEmpty())
+ if (newIntersecting.isEmpty())
return null;
- ranges = newRanges;
+ intersecting = newIntersecting;
}
Invariants.require(partialDeps != null || findAsDep == null || !saveStatus.known.deps().hasProposedOrDecidedDeps());
@@ -219,14 +219,17 @@ public interface CommandSummaries
else
{
boolean isStable = summaryStatus.compareTo(ACCEPTED) >= 0;
- Unseekables<?> participants = partialDeps.participants(findAsDep);
- isDep = participants != null && participants.containsAll(ranges)
+ // this should be in same domain as intersecting, as will be taken from relevant Deps entry
+ Participants<?> participants = partialDeps.participants(findAsDep);
+ isDep = participants != null && participants.containsAll(intersecting)
? (isStable ? IsDep.IS_STABLE_DEP : IsDep.IS_COORD_DEP)
: (isStable ? IsDep.IS_NOT_STABLE_DEP : IsDep.IS_NOT_COORD_DEP);
}
}
- return new Summary(txnId, executeAt, summaryStatus, ranges, isDep, findAsDep);
+ // convert to the domain of the command we're loading
+ intersecting = touches.intersecting(intersecting, Minimal);
+ return new Summary(txnId, executeAt, summaryStatus, intersecting, isDep, findAsDep);
}
}
}
diff --git a/accord-core/src/main/java/accord/local/Commands.java b/accord-core/src/main/java/accord/local/Commands.java
index 753ae82c..af8bc16f 100644
--- a/accord-core/src/main/java/accord/local/Commands.java
+++ b/accord-core/src/main/java/accord/local/Commands.java
@@ -76,6 +76,7 @@ import static accord.local.Commands.Validated.INSUFFICIENT;
import static accord.local.Commands.Validated.UPDATE_TXN_IGNORE_DEPS;
import static accord.local.Commands.Validated.UPDATE_TXN_KEEP_DEPS;
import static accord.local.Commands.Validated.UPDATE_TXN_AND_DEPS;
+import static accord.local.Commands.Validated.UPDATE_TXN_MERGE_DEPS;
import static accord.local.KeyHistory.INCR;
import static accord.local.KeyHistory.SYNC;
import static accord.local.PreLoadContext.contextFor;
@@ -129,7 +130,7 @@ public class Commands
{
}
- public enum AcceptOutcome { Success, Redundant, RejectedBallot, Retired, Truncated }
+ public enum AcceptOutcome { Success, Redundant, RejectedBallot, Insufficient, Retired, Truncated }
public static AcceptOutcome preaccept(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, TxnId txnId, Txn partialTxn, @Nullable Deps partialDeps, boolean hasCoordinatorVote, FullRoute<?> route)
{
@@ -235,31 +236,54 @@ public class Commands
return true;
}
- public static AcceptOutcome accept(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, TxnId txnId, Accept.Kind kind, Ballot ballot, Route<?> route, Timestamp executeAt, PartialDeps deps)
+ private static AcceptOutcome maybeRejectAccept(Ballot ballot, Timestamp executeAt, Command command)
{
- final Command command = safeCommand.current();
- if (command.hasBeen(PreCommitted))
+ Status status = command.status();
+ int compareStatus = status.compareTo(PreCommitted);
+ if (compareStatus > 0)
{
- logger.trace("{}: skipping accept - already committed ({})", txnId, command.status());
+ logger.trace("{}: skipping accept/notaccept - already committed/invalidated ({})", command.txnId(), status);
return AcceptOutcome.Redundant;
}
- if (command.promised().compareTo(ballot) > 0)
+ Ballot promised = command.promised();
+ int comparePromised = command.promised().compareTo(ballot);
+ if (comparePromised > 0 || (comparePromised == 0 && compareStatus == 0 && command.acceptedOrCommitted().compareTo(ballot) == 0))
+ {
+ if (logger.isTraceEnabled())
+ logger.trace("{}: rejecting accept/notaccept - witnessed higher ballot (({},{}) > {})", command.txnId(), promised, status, ballot);
+ return AcceptOutcome.RejectedBallot;
+ }
+
+ if (compareStatus == 0 && executeAt != null && !executeAt.equals(command.executeAt()))
{
+ // we have to special-case this because we advance to Stable/Applied without Ballot, so we can propagate PreCommitted without the ballot used to agree it
if (logger.isTraceEnabled())
- logger.trace("{}: skipping accept - witnessed higher ballot ({} > {})", txnId, command.promised(), ballot);
+ logger.trace("{}: rejecting accept/notaccept - witnessed conflicting committed timestamp: {} != {}", command.txnId(), executeAt, command.executeAt());
return AcceptOutcome.RejectedBallot;
}
+ return null;
+ }
+
+ public static AcceptOutcome accept(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, TxnId txnId, Accept.Kind kind, Ballot ballot, Route<?> route, Timestamp executeAt, PartialDeps deps)
+ {
+ final Command command = safeCommand.current();
+ {
+ AcceptOutcome reject = maybeRejectAccept(ballot, executeAt, command);
+ if (reject != null)
+ return reject;
+ }
SaveStatus newSaveStatus = SaveStatus.get(kind == Accept.Kind.MEDIUM ? Status.AcceptedMedium : Status.AcceptedSlow, command.known());
participants = participants.filter(UPDATE, safeStore, txnId, null);
Validated validated = validate(ballot, newSaveStatus, command, participants, route, null, deps);
Invariants.require(validated != INSUFFICIENT);
+ PartialTxn partialTxn = prepareTxn(newSaveStatus, participants, command, null);
PartialDeps partialDeps = prepareDeps(validated, participants, command, deps);
participants = prepareParticipants(validated, participants, command);
- safeCommand.accept(safeStore, newSaveStatus, participants, ballot, executeAt, partialDeps, ballot);
+ safeCommand.accept(safeStore, newSaveStatus, participants, ballot, executeAt, partialTxn, partialDeps, ballot);
safeStore.notifyListeners(safeCommand, command);
return AcceptOutcome.Success;
@@ -268,28 +292,13 @@ public class Commands
public static AcceptOutcome notAccept(SafeCommandStore safeStore, SafeCommand safeCommand, Status status, Ballot ballot)
{
final Command command = safeCommand.current();
- if (command.hasBeen(PreCommitted))
- {
- logger.trace("{}: skipping not accept - already committed or invalidated ({})", command.txnId(), command.status());
- return AcceptOutcome.Redundant;
- }
-
- if (command.promised().compareTo(ballot) > 0)
- {
- if (logger.isTraceEnabled())
- logger.trace("{}: skipping {} - witnessed higher ballot ({} > {})", command.txnId(), status, command.promised(), ballot);
- return AcceptOutcome.RejectedBallot;
- }
-
- if (status.compareTo(command.status()) < 0 && command.acceptedOrCommitted().equals(ballot))
{
- if (logger.isTraceEnabled())
- logger.trace("{}: skipping {} - already acceptedOrCommitted ballot {} with status {}", command.txnId(), status, ballot, command.status());
- return AcceptOutcome.Redundant;
+ AcceptOutcome reject = maybeRejectAccept(ballot, null, command);
+ if (reject != null)
+ return reject;
}
logger.trace("{}: not accepted ({})", command.txnId(), status);
-
safeCommand.notAccept(safeStore, status, ballot);
safeStore.notifyListeners(safeCommand, command);
return AcceptOutcome.Success;
@@ -334,9 +343,7 @@ public class Commands
participants = participants.filter(UPDATE, safeStore, txnId, executeAt);
Known known = curStatus.known;
- if (kind == StableMediumPath && known.is(DepsProposedFixed))
- known = known.with(DepsKnown);
- Validated validated = validate(ballot, known, newSaveStatus, command, participants, route, txn, deps);
+ Validated validated = validate(ballot, known, newSaveStatus, command, participants, route, txn, deps, kind);
if (validated == INSUFFICIENT)
return CommitOutcome.Insufficient;
@@ -366,7 +373,7 @@ public class Commands
}
// relies on mutual exclusion for each key
- public static CommitOutcome precommit(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, TxnId txnId, Timestamp executeAt)
+ public static CommitOutcome precommit(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, TxnId txnId, Timestamp executeAt, Ballot promisedAtLeast)
{
Invariants.require(Route.isFullRoute(participants.route()));
final Command command = safeCommand.current();
@@ -388,7 +395,7 @@ public class Commands
}
supplementParticipants(safeStore, safeCommand, participants);
- safeCommand.precommit(safeStore, executeAt);
+ safeCommand.precommit(safeStore, executeAt, promisedAtLeast);
safeStore.notifyListeners(safeCommand, command);
logger.trace("{}: precommitted with executeAt: {}", txnId, executeAt);
return CommitOutcome.Success;
@@ -1292,7 +1299,13 @@ public class Commands
private static PartialTxn prepareTxn(SaveStatus newSaveStatus, StoreParticipants newParticipants, Command upd, @Nullable Txn txn)
{
PartialTxn cur = upd.partialTxn();
- if (txn == null || !newSaveStatus.known.definition().isKnown())
+ if (!newSaveStatus.known.definition().isKnown())
+ return cur;
+
+ if (cur != null)
+ cur = cur.intersecting(newParticipants.owns(), true);
+
+ if (txn == null)
return cur;
if (cur != null && cur.covers(newParticipants.stillOwns()))
@@ -1328,6 +1341,8 @@ public class Commands
default: throw new UnhandledEnum(validated);
case UPDATE_TXN_KEEP_DEPS:
return upd.partialDeps();
+ case UPDATE_TXN_MERGE_DEPS:
+ return upd.partialDeps().with(newDeps.intersecting(participants.stillTouches()));
case UPDATE_TXN_AND_DEPS:
return newDeps.intersecting(participants.stillTouches());
case UPDATE_TXN_IGNORE_DEPS:
@@ -1335,16 +1350,16 @@ public class Commands
}
}
- enum Validated { INSUFFICIENT, UPDATE_TXN_IGNORE_DEPS, UPDATE_TXN_KEEP_DEPS, UPDATE_TXN_AND_DEPS }
+ enum Validated { INSUFFICIENT, UPDATE_TXN_IGNORE_DEPS, UPDATE_TXN_KEEP_DEPS, UPDATE_TXN_MERGE_DEPS, UPDATE_TXN_AND_DEPS }
private static Validated validate(@Nullable Ballot ballot, SaveStatus newStatus, Command cur, StoreParticipants participants,
Route<?> addRoute, @Nullable Txn addPartialTxn, @Nullable Deps partialDeps)
{
- return validate(ballot, cur.known(), newStatus, cur, participants, addRoute, addPartialTxn, partialDeps);
+ return validate(ballot, cur.known(), newStatus, cur, participants, addRoute, addPartialTxn, partialDeps, null);
}
private static Validated validate(@Nullable Ballot ballot, Known haveKnown, SaveStatus newStatus, Command cur, StoreParticipants participants,
- Route<?> addRoute, @Nullable Txn addPartialTxn, @Nullable Deps partialDeps)
+ Route<?> addRoute, @Nullable Txn addPartialTxn, @Nullable Deps partialDeps, @Nullable Commit.Kind commitKind)
{
Known expectKnown = newStatus.known;
@@ -1379,6 +1394,13 @@ public class Commands
if (!expectKnown.hasAnyDeps())
return UPDATE_TXN_IGNORE_DEPS;
+ if (commitKind == StableMediumPath)
+ {
+ if (haveKnown.is(DepsProposedFixed) && expectKnown.is(DepsKnown) && ballot != null && ballot.equals(Ballot.ZERO) && participants.stillTouches().equals(cur.participants().touches()))
+ return UPDATE_TXN_MERGE_DEPS;
+ return INSUFFICIENT;
+ }
+
if (haveKnown.is(DepsKnown) || (haveKnown.equalDeps(expectKnown) && (ballot == null || ballot.equals(cur.acceptedOrCommitted()))))
return UPDATE_TXN_KEEP_DEPS;
diff --git a/accord-core/src/main/java/accord/local/Node.java b/accord-core/src/main/java/accord/local/Node.java
index 9f5326f7..21b57487 100644
--- a/accord-core/src/main/java/accord/local/Node.java
+++ b/accord-core/src/main/java/accord/local/Node.java
@@ -407,7 +407,7 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
}
}
- public void withEpoch(long epoch, BiConsumer<?, Throwable> ifFailure, Runnable ifSuccess)
+ public void withEpoch(long epoch, BiConsumer<?, ? super Throwable> ifFailure, Runnable ifSuccess)
{
if (topology.hasEpoch(epoch))
{
diff --git a/accord-core/src/main/java/accord/local/SafeCommand.java b/accord-core/src/main/java/accord/local/SafeCommand.java
index 4f6b8465..7f10b37d 100644
--- a/accord-core/src/main/java/accord/local/SafeCommand.java
+++ b/accord-core/src/main/java/accord/local/SafeCommand.java
@@ -109,9 +109,9 @@ public abstract class SafeCommand
return incidentalUpdate(current().updatePromised(promised));
}
- public Command.Accepted accept(SafeCommandStore safeStore, SaveStatus status, @Nonnull StoreParticipants participants, Ballot promised, Timestamp executeAt, PartialDeps partialDeps, Ballot acceptedOrCommitted)
+ public Command.Accepted accept(SafeCommandStore safeStore, SaveStatus status, @Nonnull StoreParticipants participants, Ballot promised, Timestamp executeAt, PartialTxn partialTxn, PartialDeps partialDeps, Ballot acceptedOrCommitted)
{
- return update(safeStore, Command.accept(current(), status, participants, promised, executeAt, partialDeps, acceptedOrCommitted));
+ return update(safeStore, Command.accept(current(), status, participants, promised, executeAt, partialTxn, partialDeps, acceptedOrCommitted));
}
public Command notAccept(SafeCommandStore safeStore, Status status, Ballot ballot)
@@ -138,9 +138,9 @@ public abstract class SafeCommand
return update(safeStore, Truncated.invalidated(current));
}
- public Command precommit(SafeCommandStore safeStore, Timestamp executeAt)
+ public Command precommit(SafeCommandStore safeStore, Timestamp executeAt, Ballot promisedAtLeast)
{
- return update(safeStore, Command.precommit(current(), executeAt));
+ return update(safeStore, Command.precommit(current(), executeAt, promisedAtLeast));
}
public Command.Committed readyToExecute(SafeCommandStore safeStore)
diff --git a/accord-core/src/main/java/accord/local/SafeCommandStore.java b/accord-core/src/main/java/accord/local/SafeCommandStore.java
index f616290c..9be69f49 100644
--- a/accord-core/src/main/java/accord/local/SafeCommandStore.java
+++ b/accord-core/src/main/java/accord/local/SafeCommandStore.java
@@ -488,11 +488,6 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
return ranges().allAt(txnId.epoch());
}
- public Ranges ranges(TxnId txnId, Timestamp executeAt)
- {
- return ranges(txnId, executeAt.epoch());
- }
-
public Ranges ranges(TxnId txnId, long untilLocalEpoch)
{
return ranges().allBetween(txnId.epoch(), untilLocalEpoch);
diff --git a/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java b/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
index 100bc4d3..4a844575 100644
--- a/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
@@ -84,6 +84,7 @@ import static accord.local.cfk.CommandsForKey.InternalStatus.TRANSITIVE_VISIBLE;
import static accord.local.cfk.CommandsForKey.InternalStatus.from;
import static accord.local.cfk.CommandsForKey.InternalStatus.prunedFrom;
import static accord.local.cfk.PostProcess.notifyManagedPreBootstrap;
+import static accord.local.cfk.Pruning.find;
import static accord.local.cfk.Pruning.isAnyPredecessorWaitingOnPruned;
import static accord.local.cfk.Pruning.isWaitingOnPruned;
import static accord.local.cfk.Pruning.loadingPrunedFor;
@@ -1353,7 +1354,8 @@ public class CommandsForKey extends CommandsForKeyUpdate
// the range is marked as durable. If now the replica then witnesses one of these transactions it will
// consider that they must be invalidated, as it had not witnessed them, they were not pre-bootstrap and
// they were pre-RX.
- TxnInfo maxCommittedWriteBefore;
+ TxnInfo maxCommittedWriteBefore = NO_INFO;
+ TxnInfo maxCommittedWriteForEpoch = NO_INFO;
{
int from = 0, to = committedByExecuteAt.length;
if (maxAppliedWriteByExecuteAt >= 0)
@@ -1365,7 +1367,12 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (i < 0) i = -2 - i;
else --i;
while (i >= 0 && !committedByExecuteAt[i].is(Write)) --i;
- maxCommittedWriteBefore = i < 0 ? null : committedByExecuteAt[i];
+ if (i >= 0)
+ {
+ maxCommittedWriteBefore = committedByExecuteAt[i];
+ if (maxCommittedWriteBefore.executeAt == maxCommittedWriteBefore)
+ maxCommittedWriteForEpoch = maxCommittedWriteBefore;
+ }
}
// TODO (expected): consider whether this is strictly needed - if we've applied a transaction after the pruned
@@ -1380,7 +1387,6 @@ public class CommandsForKey extends CommandsForKeyUpdate
nextPruned = loadingPruned.next();
}
- TxnInfo maxCommittedWriteForEpoch = null;
for (int i = 0; i < end ; ++i)
{
TxnInfo txn = byId[i];
@@ -1409,8 +1415,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
case APPLIED_NOT_DURABLE:
case APPLIED_DURABLE:
case APPLIED_NOT_EXECUTED:
- if (maxCommittedWriteBefore == null
- || txn.compareTo(maxCommittedWriteBefore) >= 0
+ if (txn.compareTo(maxCommittedWriteBefore) >= 0
|| txn.executeAt.compareTo(maxCommittedWriteBefore.executeAt) >= 0
|| !Write.witnesses(txn))
break;
@@ -1434,14 +1439,9 @@ public class CommandsForKey extends CommandsForKeyUpdate
// from all epochs we know
long epoch = txn.epoch();
- if (epoch == maxCommittedWriteBefore.epoch())
- continue;
-
- if (maxCommittedWriteForEpoch != null && epoch != maxCommittedWriteForEpoch.epoch())
- maxCommittedWriteForEpoch = null;
-
- if (maxCommittedWriteForEpoch == null)
+ if (epoch != maxCommittedWriteForEpoch.epoch())
{
+ maxCommittedWriteForEpoch = NO_INFO;
for (int j = i ; j < end ; ++j)
{
TxnInfo t = byId[j];
@@ -1451,10 +1451,10 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (!t.isWrite() || t.executeAt != t || !t.isCommittedToExecute())
continue;
- if (maxCommittedWriteForEpoch == null || t.compareExecuteAt(maxCommittedWriteForEpoch) > 0)
+ if (t.compareExecuteAt(maxCommittedWriteForEpoch) > 0)
maxCommittedWriteForEpoch = t;
}
- if (maxCommittedWriteForEpoch == null)
+ if (maxCommittedWriteForEpoch == NO_INFO)
maxCommittedWriteForEpoch = txn;
}
@@ -1494,24 +1494,34 @@ public class CommandsForKey extends CommandsForKeyUpdate
public CommandsForKeyUpdate callback(SafeCommandStore safeStore, Command update)
{
+ LoadingPruned loading = find(loadingPruned, update.txnId());
if (maybePruned(update))
- return maybePrunedCallback(safeStore, update);
- return update(safeStore, update);
+ return maybePrunedCallback(safeStore, update, loading);
+ return update(safeStore, update, loading);
}
public CommandsForKeyUpdate update(SafeCommandStore safeStore, Command update)
+ {
+ return update(safeStore, update, find(loadingPruned, update.txnId()));
+ }
+
+ private CommandsForKeyUpdate update(SafeCommandStore safeStore, Command update, @Nullable LoadingPruned loading)
{
Invariants.require(manages(update.txnId()));
InternalStatus newStatus = from(safeStore, update);
if (newStatus == null)
{
- // handle replay of TruncatedApply with uniqueHlc
- if (update.known().is(ApplyAtKnown))
- return updateUniqueHlc(update.executeAt().uniqueHlc());
- return this;
+ if (loading == null)
+ {
+ // handle replay of TruncatedApply with uniqueHlc
+ if (update.known().is(ApplyAtKnown))
+ return updateUniqueHlc(update.executeAt().uniqueHlc());
+ return this;
+ }
+ newStatus = loading.isVisible ? TRANSITIVE_VISIBLE : TRANSITIVE;
}
- return update(newStatus, update);
+ return update(newStatus, update, loading);
}
public CommandsForKey updateUniqueHlc(long minUniqueHlc)
@@ -1536,22 +1546,21 @@ public class CommandsForKey extends CommandsForKeyUpdate
return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, unmanageds);
}
- CommandsForKeyUpdate maybePrunedCallback(SafeCommandStore safeStore, Command update)
+ CommandsForKeyUpdate maybePrunedCallback(SafeCommandStore safeStore, Command update, @Nullable LoadingPruned loading)
{
TxnId txnId = update.txnId();
InternalStatus ifPrunedStatus = prunedFrom(update.saveStatus());
- boolean isLoadingPruned = loadingPrunedFor(loadingPruned, txnId, null) != null;
- if (!isLoadingPruned)
+ if (loading == null)
{
TxnInfo cur = get(txnId);
if (cur != null && !cur.is(PRUNED))
- return update(safeStore, update); // if we're not pruned, this should be treated as a regular callback
+ return update(safeStore, update, loading); // if we're not pruned, this should be treated as a regular callback
if (!manages(txnId))
ifPrunedStatus = PRUNED;
}
- return update(ifPrunedStatus, update);
+ return update(ifPrunedStatus, update, loading);
}
private boolean maybePruned(Command command)
@@ -1565,7 +1574,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
return command.hasBeen(Status.Truncated) || (command.hasBeen(Status.Applied) && prunedBefore.executeAt.compareTo(command.executeAt()) > 0);
}
- private CommandsForKeyUpdate update(InternalStatus newStatus, Command updated)
+ private CommandsForKeyUpdate update(InternalStatus newStatus, Command updated, @Nullable LoadingPruned loading)
{
TxnId txnId = updated.txnId();
Invariants.requireArgument(updated.participants().hasTouched(key) || !manages(txnId));
@@ -1577,10 +1586,9 @@ public class CommandsForKey extends CommandsForKeyUpdate
boolean isOutOfRange = !mayExecute && newStatus.compareTo(APPLIED) <= 0 && manages(txnId)
&& !updated.participants().stillTouches(key);
- TxnId[] loadingAsPrunedFor = loadingPrunedFor(loadingPruned, txnId, null); // we default to null to distinguish between no match, and a match with NO_TXNIDS
- boolean wasPruned = loadingAsPrunedFor != null;
+ TxnId[] loadingAsPrunedFor = loading != null ? loading.witnessedBy : null;
- if (!wasPruned && isOutOfRange && newStatus.compareTo(COMMITTED) < 0)
+ if (loading == null && isOutOfRange && newStatus.compareTo(COMMITTED) < 0)
return this;
int pos = Arrays.binarySearch(byId, txnId);
@@ -1591,9 +1599,9 @@ public class CommandsForKey extends CommandsForKeyUpdate
return this; // if outOfRange we only need to maintain any existing records; if none, don't update
pos = -1 - pos;
- if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, null, newStatus, mayExecute, updated, wasPruned, loadingAsPrunedFor);
- else if (newStatus.hasDeps() && !wasPruned) result = insert(pos, txnId, newStatus, mayExecute, updated);
- else result = insert(pos, txnId, TxnInfo.create(txnId, newStatus, mayExecute, updated), wasPruned, loadingAsPrunedFor, updated);
+ if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, null, newStatus, mayExecute, updated, loadingAsPrunedFor);
+ else if (newStatus.hasDeps() && loading == null) result = insert(pos, txnId, newStatus, mayExecute, updated);
+ else result = insert(pos, txnId, TxnInfo.create(txnId, newStatus, mayExecute, updated), loadingAsPrunedFor, updated);
}
else
{
@@ -1627,9 +1635,9 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
}
- if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, cur, newStatus, mayExecute, updated, wasPruned, loadingAsPrunedFor);
- else if (newStatus.hasDeps() && !wasPruned) result = update(pos, txnId, cur, newStatus, mayExecute, updated);
- else result = update(pos, txnId, cur, TxnInfo.create(txnId, newStatus, mayExecute, updated), wasPruned, loadingAsPrunedFor, updated);
+ if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, cur, newStatus, mayExecute, updated, loadingAsPrunedFor);
+ else if (newStatus.hasDeps() && loading == null) result = update(pos, txnId, cur, newStatus, mayExecute, updated);
+ else result = update(pos, txnId, cur, TxnInfo.create(txnId, newStatus, mayExecute, updated), loadingAsPrunedFor, updated);
}
return result;
@@ -1645,20 +1653,20 @@ public class CommandsForKey extends CommandsForKeyUpdate
return insertOrUpdate(this, updatePos, updatePos, plainTxnId, curInfo, newStatus, mayExecute, command);
}
- CommandsForKeyUpdate update(int pos, TxnId plainTxnId, TxnInfo curInfo, TxnInfo newInfo, boolean wasPruned, TxnId[] loadingAsPrunedFor, Command command)
+ CommandsForKeyUpdate update(int pos, TxnId plainTxnId, TxnInfo curInfo, TxnInfo newInfo, TxnId[] loadingAsPrunedFor, Command command)
{
- return insertOrUpdate(this, pos, plainTxnId, curInfo, newInfo, wasPruned, loadingAsPrunedFor, command);
+ return insertOrUpdate(this, pos, plainTxnId, curInfo, newInfo, loadingAsPrunedFor, command);
}
/**
* Insert a new txnId and info
*/
- CommandsForKeyUpdate insert(int pos, TxnId plainTxnId, TxnInfo newInfo, boolean wasPruned, TxnId[] loadingAsPrunedFor, Command updated)
+ CommandsForKeyUpdate insert(int pos, TxnId plainTxnId, TxnInfo newInfo, TxnId[] loadingAsPrunedFor, Command updated)
{
- return insertOrUpdate(this, pos, plainTxnId, null, newInfo, wasPruned, loadingAsPrunedFor, updated);
+ return insertOrUpdate(this, pos, plainTxnId, null, newInfo, loadingAsPrunedFor, updated);
}
- private CommandsForKeyUpdate insertOrUpdateOutOfRange(int updatePos, TxnId plainTxnId, @Nullable TxnInfo curInfo, InternalStatus newStatus, boolean mayExecute, Command updated, boolean wasPruned, TxnId[] loadingAsPrunedFor)
+ private CommandsForKeyUpdate insertOrUpdateOutOfRange(int updatePos, TxnId plainTxnId, @Nullable TxnInfo curInfo, InternalStatus newStatus, boolean mayExecute, Command updated, TxnId[] loadingAsPrunedFor)
{
Invariants.requireArgument(!mayExecute);
int statusOverridesXor = newStatus.flags & 1;
@@ -1666,7 +1674,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (curInfo == null) newInfo = TxnInfo.create(plainTxnId, newStatus, false, statusOverridesXor, plainTxnId, newStatus.hasBallot ? updated.acceptedOrCommitted() : Ballot.ZERO);
else newInfo = curInfo.withEncodedStatus(TxnInfo.encode(plainTxnId, newStatus, false, statusOverridesXor));
// out of range means we have no deps, we're just marking committed, so we set HAS_DEPS to 0
- return insertOrUpdate(this, updatePos, plainTxnId, curInfo, newInfo, wasPruned, loadingAsPrunedFor, updated);
+ return insertOrUpdate(this, updatePos, plainTxnId, curInfo, newInfo, loadingAsPrunedFor, updated);
}
// TODO (required): additional linearizability violation detection, based on expectation of presence in missing set
diff --git a/accord-core/src/main/java/accord/local/cfk/PostProcess.java b/accord-core/src/main/java/accord/local/cfk/PostProcess.java
index e37eda0e..b938746b 100644
--- a/accord-core/src/main/java/accord/local/cfk/PostProcess.java
+++ b/accord-core/src/main/java/accord/local/cfk/PostProcess.java
@@ -111,7 +111,7 @@ abstract class PostProcess
StoreParticipants participants = command.participants();
if (participants.owns().domain() == Routable.Domain.Key && !participants.hasTouched(safeCfk.key()))
command = safeCommand.updateParticipants(safeStore, participants.supplementHasTouched(RoutingKeys.of(safeCfk.key())));
- safeCfk.updatePruned(safeStore, command, notifySink);
+ safeCfk.callback(safeStore, command, notifySink);
}
static CommandsForKeyUpdate load(TxnId[] txnIds, CommandsForKeyUpdate result)
diff --git a/accord-core/src/main/java/accord/local/cfk/Pruning.java b/accord-core/src/main/java/accord/local/cfk/Pruning.java
index 978f854f..3f70bb56 100644
--- a/accord-core/src/main/java/accord/local/cfk/Pruning.java
+++ b/accord-core/src/main/java/accord/local/cfk/Pruning.java
@@ -28,6 +28,7 @@ import accord.primitives.TxnId;
import accord.utils.ArrayBuffers.RecursiveObjectBuffers;
import accord.utils.Invariants;
import accord.utils.SortedArrays;
+import accord.utils.UnhandledEnum;
import accord.utils.btree.BTree;
import accord.utils.btree.BTreeRemoval;
import accord.utils.btree.BulkIterator;
@@ -161,6 +162,14 @@ public class Pruning
return obj.witnessedBy;
}
+ /**
+ * Find the list of TxnId that are waiting for {@code find} to load
+ */
+ static LoadingPruned find(Object[] loadingPruned, TxnId find)
+ {
+ return (LoadingPruned) BTree.find(loadingPruned, TxnId::compareTo, find);
+ }
+
/**
* Updating {@code loadingPruned} to remove {@code find}, as it has been loaded
*/
@@ -325,7 +334,7 @@ public class Pruning
TxnInfo txn = byId[i];
switch (txn.status())
{
- default: throw new AssertionError("Unhandled status: " + txn.status());
+ default: throw new UnhandledEnum(txn.status());
case COMMITTED:
case STABLE:
if (txn.mayExecute())
diff --git a/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java b/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
index 65e61e59..5b3ecc11 100644
--- a/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
@@ -27,6 +27,7 @@ import accord.local.Command;
import accord.local.RedundantBefore;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
+import accord.local.cfk.NotifySink.DefaultNotifySink;
import accord.primitives.Status;
import accord.primitives.TxnId;
@@ -46,12 +47,6 @@ public abstract class SafeCommandsForKey implements SafeState<CommandsForKey>
return key;
}
- void updatePruned(SafeCommandStore safeStore, Command nextCommand, NotifySink notifySink)
- {
- CommandsForKey prevCfk = current();
- update(safeStore, nextCommand, prevCfk, prevCfk.maybePrunedCallback(safeStore, nextCommand), notifySink);
- }
-
public void update(SafeCommandStore safeStore, Command nextCommand)
{
CommandsForKey prevCfk = current();
@@ -66,14 +61,19 @@ public abstract class SafeCommandsForKey implements SafeState<CommandsForKey>
// equivalent to update, but for async callbacks with additional validation around pruning
public void callback(SafeCommandStore safeStore, Command nextCommand)
+ {
+ callback(safeStore, nextCommand, DefaultNotifySink.INSTANCE);
+ }
+
+ public void callback(SafeCommandStore safeStore, Command nextCommand, NotifySink notifySink)
{
CommandsForKey prevCfk = current();
- update(safeStore, nextCommand, prevCfk, prevCfk.callback(safeStore, nextCommand));
+ update(safeStore, nextCommand, prevCfk, prevCfk.callback(safeStore, nextCommand), notifySink);
}
private void update(SafeCommandStore safeStore, @Nullable Command command, CommandsForKey prevCfk, CommandsForKeyUpdate updateCfk)
{
- update(safeStore, command, prevCfk, updateCfk, NotifySink.DefaultNotifySink.INSTANCE);
+ update(safeStore, command, prevCfk, updateCfk, DefaultNotifySink.INSTANCE);
}
private void update(SafeCommandStore safeStore, @Nullable Command command, CommandsForKey prevCfk, CommandsForKeyUpdate updateCfk, NotifySink notifySink)
diff --git a/accord-core/src/main/java/accord/local/cfk/Updating.java b/accord-core/src/main/java/accord/local/cfk/Updating.java
index fee896d0..635dde05 100644
--- a/accord-core/src/main/java/accord/local/cfk/Updating.java
+++ b/accord-core/src/main/java/accord/local/cfk/Updating.java
@@ -117,7 +117,7 @@ class Updating
// TODO (expected): do not calculate any deps or additions if we're transitioning from Stable to Applied; wasted effort and might trigger LoadPruned
Object newInfoObj = computeInfoAndAdditions(cfk, insertPos, updatePos, plainTxnId, newStatus, mayExecute, command);
if (newInfoObj.getClass() != InfoWithAdditions.class)
- return insertOrUpdate(cfk, insertPos, plainTxnId, curInfo, (TxnInfo)newInfoObj, false, null, command);
+ return insertOrUpdate(cfk, insertPos, plainTxnId, curInfo, (TxnInfo)newInfoObj, null, command);
InfoWithAdditions newInfoWithAdditions = (InfoWithAdditions) newInfoObj;
TxnId[] additions = newInfoWithAdditions.additions;
@@ -328,7 +328,7 @@ class Updating
return new InfoWithAdditions(info, additions, additionCount);
}
- static CommandsForKeyUpdate insertOrUpdate(CommandsForKey cfk, int pos, TxnId plainTxnId, TxnInfo curInfo, TxnInfo newInfo, boolean wasPruned, @Nullable TxnId[] loadingAsPrunedFor, Command command)
+ static CommandsForKeyUpdate insertOrUpdate(CommandsForKey cfk, int pos, TxnId plainTxnId, TxnInfo curInfo, TxnInfo newInfo, @Nullable TxnId[] loadingAsPrunedFor, Command command)
{
if (curInfo == newInfo)
return cfk;
@@ -337,8 +337,8 @@ class Updating
if (loadingAsPrunedFor != null) newLoadingPruned = Pruning.removeLoadingPruned(newLoadingPruned, plainTxnId);
int committedByExecuteAtUpdatePos = committedByExecuteAtUpdatePos(cfk.committedByExecuteAt, curInfo, newInfo);
- TxnInfo[] newCommittedByExecuteAt = updateCommittedByExecuteAt(cfk, committedByExecuteAtUpdatePos, newInfo, wasPruned);
- int newMaxAppliedWriteByExecuteAt = updateMaxAppliedWriteByExecuteAt(cfk, committedByExecuteAtUpdatePos, newInfo, newCommittedByExecuteAt, wasPruned);
+ TxnInfo[] newCommittedByExecuteAt = updateCommittedByExecuteAt(cfk, committedByExecuteAtUpdatePos, newInfo, loadingAsPrunedFor != null);
+ int newMaxAppliedWriteByExecuteAt = updateMaxAppliedWriteByExecuteAt(cfk, committedByExecuteAtUpdatePos, newInfo, newCommittedByExecuteAt, loadingAsPrunedFor != null);
int newMinUndecidedById = cfk.minUndecidedById;
TxnInfo[] byId = cfk.byId;
diff --git a/accord-core/src/main/java/accord/messages/Accept.java b/accord-core/src/main/java/accord/messages/Accept.java
index 163a065e..35968ec7 100644
--- a/accord-core/src/main/java/accord/messages/Accept.java
+++ b/accord-core/src/main/java/accord/messages/Accept.java
@@ -36,12 +36,13 @@ import accord.primitives.FullRoute;
import accord.primitives.PartialDeps;
import accord.primitives.Participants;
import accord.primitives.Route;
+import accord.primitives.SaveStatus;
import accord.primitives.Status;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
-import accord.primitives.Unseekables;
import accord.topology.Topologies;
import accord.utils.Invariants;
+import accord.utils.UnhandledEnum;
import accord.utils.async.Cancellable;
import static accord.api.ProtocolModifiers.Toggles.filterDuplicateDependenciesFromAcceptReply;
@@ -49,6 +50,7 @@ import static accord.local.Commands.AcceptOutcome.Redundant;
import static accord.local.Commands.AcceptOutcome.RejectedBallot;
import static accord.local.Commands.AcceptOutcome.Success;
import static accord.local.KeyHistory.SYNC;
+import static accord.primitives.Known.KnownDeps.DepsKnown;
// TODO (low priority, efficiency): use different objects for send and receive, so can be more efficient
// (e.g. serialize without slicing, and without unnecessary fields)
@@ -56,9 +58,9 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
{
public static class SerializerSupport
{
- public static Accept create(TxnId txnId, Route<?> scope, long waitForEpoch, long minEpoch, Kind kind, Ballot ballot, Timestamp executeAt, PartialDeps partialDeps)
+ public static Accept create(TxnId txnId, Route<?> scope, long waitForEpoch, long minEpoch, Kind kind, Ballot ballot, Timestamp executeAt, PartialDeps partialDeps, boolean isPartialAccept)
{
- return new Accept(txnId, scope, waitForEpoch, minEpoch, kind, ballot, executeAt, partialDeps);
+ return new Accept(txnId, scope, waitForEpoch, minEpoch, kind, ballot, executeAt, partialDeps, isPartialAccept);
}
}
@@ -68,23 +70,26 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
public final Ballot ballot;
public final Timestamp executeAt;
public final PartialDeps partialDeps;
+ public final boolean isPartialAccept;
- public Accept(Id to, Topologies topologies, Kind kind, Ballot ballot, TxnId txnId, FullRoute<?> route, Timestamp executeAt, Deps deps)
+ public Accept(Id to, Topologies topologies, Kind kind, Ballot ballot, TxnId txnId, FullRoute<?> route, Timestamp executeAt, Deps deps, boolean isPartialAccept)
{
super(to, topologies, txnId, route);
this.kind = kind;
this.ballot = ballot;
this.executeAt = executeAt;
this.partialDeps = deps.intersecting(scope);
+ this.isPartialAccept = isPartialAccept;
}
- private Accept(TxnId txnId, Route<?> scope, long waitForEpoch, long minEpoch, Kind kind, Ballot ballot, Timestamp executeAt, PartialDeps partialDeps)
+ private Accept(TxnId txnId, Route<?> scope, long waitForEpoch, long minEpoch, Kind kind, Ballot ballot, Timestamp executeAt, PartialDeps partialDeps, boolean isPartialAccept)
{
super(txnId, scope, waitForEpoch, minEpoch);
this.kind = kind;
this.ballot = ballot;
this.executeAt = executeAt;
this.partialDeps = partialDeps;
+ this.isPartialAccept = isPartialAccept;
}
@Override
@@ -95,24 +100,74 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
AcceptOutcome outcome = Commands.accept(safeStore, safeCommand, participants, txnId, kind, ballot, scope, executeAt, partialDeps);
switch (outcome)
{
- default: throw new IllegalStateException();
+ default: throw new UnhandledEnum(outcome);
case Redundant:
case Truncated:
- return AcceptReply.redundant(ballot, participants, safeCommand.current());
+ {
+ Command command = safeCommand.current();
+
+ boolean notOwner = participants.owns().isEmpty();
+ Participants<?> hasDeps = null;
+ Deps deps = null;
+
+ if (command.known().is(DepsKnown) && (isPartialAccept || notOwner))
+ {
+ deps = command.partialDeps().asFullUnsafe();
+ hasDeps = command.participants().stillTouches();
+ }
+
+ Ballot superseding = command.promised();
+ if (superseding.compareTo(ballot) <= 0)
+ superseding = null;
+
+ boolean calculateDeps = isPartialAccept;
+ if (command.saveStatus() == SaveStatus.Vestigial)
+ {
+ superseding = null;
+ outcome = Success;
+ calculateDeps = true;
+ }
+
+ if (calculateDeps)
+ {
+ Participants<?> calculate = participants.touches();
+ if (hasDeps != null)
+ calculate = calculate.without(hasDeps);
+
+ if (!calculate.isEmpty())
+ {
+ Deps calculatedDeps = calculateDeps(safeStore, calculate);
+ if (calculatedDeps == null)
+ return AcceptReply.inThePast(ballot, participants, command);
+
+ deps = deps == null ? calculatedDeps : calculatedDeps.with(deps);
+ }
+ hasDeps = participants.touches();
+ }
+
+ Participants<?> successful = isPartialAccept ? hasDeps : null;
+ if (notOwner && (outcome == Redundant || (hasDeps != null && hasDeps.containsAll(participants.touches()))))
+ outcome = Success;
+ return new AcceptReply(outcome, superseding, successful, deps, command.executeAtIfKnown());
+ }
+
case RejectedBallot:
return new AcceptReply(safeCommand.current().promised());
+
case Retired:
// if we're Retired, participants.owns() is empty, so we're just fetching deps
// TODO (desired): optimise deps calculation; for some keys we only need to return the last RX
case Success:
Deps deps = calculateDeps(safeStore, participants);
if (deps == null)
- return AcceptReply.redundant(ballot, participants, safeCommand.current());
+ return AcceptReply.inThePast(ballot, participants, safeCommand.current());
Invariants.require(deps.maxTxnId(txnId).epoch() <= executeAt.epoch());
if (filterDuplicateDependenciesFromAcceptReply())
deps = deps.without(this.partialDeps);
- return new AcceptReply(deps);
+
+ Participants<?> successful = isPartialAccept ? participants.touches() : null;
+ return new AcceptReply(successful, deps);
}
}
@@ -121,6 +176,11 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
return PreAccept.calculateDeps(safeStore, txnId, participants, EpochSupplier.constant(minEpoch), executeAt, true);
}
+ private Deps calculateDeps(SafeCommandStore safeStore, Participants<?> participants)
+ {
+ return PreAccept.calculateDeps(safeStore, txnId, participants, EpochSupplier.constant(minEpoch), executeAt, true);
+ }
+
@Override
public AcceptReply reduce(AcceptReply r1, AcceptReply r2)
{
@@ -133,18 +193,6 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
return node.mapReduceConsumeLocal(this, minEpoch, executeAt.epoch(), this);
}
- @Override
- public TxnId primaryTxnId()
- {
- return txnId;
- }
-
- @Override
- public Unseekables<?> keys()
- {
- return scope;
- }
-
@Override
public KeyHistory keyHistory()
{
@@ -173,6 +221,7 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
public final AcceptOutcome outcome;
public final Ballot supersededBy;
+ public final @Nullable Participants<?> successful;
public final @Nullable Deps deps;
public final @Nullable Timestamp committedExecuteAt;
@@ -180,6 +229,7 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
{
this.outcome = outcome;
this.supersededBy = null;
+ this.successful = null;
this.deps = null;
this.committedExecuteAt = null;
}
@@ -188,46 +238,68 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
{
this.outcome = RejectedBallot;
this.supersededBy = supersededBy;
+ this.successful = null;
this.deps = null;
this.committedExecuteAt = null;
}
- public AcceptReply(@Nonnull Deps deps)
+ public AcceptReply(@Nullable Participants<?> successful, @Nonnull Deps deps)
{
this.outcome = Success;
this.supersededBy = null;
+ this.successful = successful;
this.deps = deps;
this.committedExecuteAt = null;
}
- public AcceptReply(Ballot supersededBy, @Nullable Timestamp committedExecuteAt)
+ public AcceptReply(AcceptOutcome outcome, Ballot supersededBy, @Nullable Timestamp committedExecuteAt)
{
- this.outcome = Redundant;
+ this.outcome = outcome;
this.supersededBy = supersededBy;
+ this.successful = null;
this.deps = null;
this.committedExecuteAt = committedExecuteAt;
}
- static AcceptReply redundant(Ballot ballot, StoreParticipants participants, Command command)
+ public AcceptReply(AcceptOutcome outcome, Ballot supersededBy, @Nullable Participants<?> successful, @Nullable Deps deps, @Nullable Timestamp committedExecuteAt)
{
- if (participants.owns().isEmpty() && (command.is(Status.Truncated) || command.promised().compareTo(ballot) <= 0))
- return new AcceptReply(Deps.NONE);
+ this.outcome = outcome;
+ this.supersededBy = supersededBy;
+ this.successful = successful;
+ this.deps = deps;
+ this.committedExecuteAt = committedExecuteAt;
+ }
+ static AcceptReply redundant(AcceptOutcome outcome, Ballot ballot, Command command)
+ {
Ballot superseding = command.promised();
if (superseding.compareTo(ballot) <= 0)
superseding = null;
- return new AcceptReply(superseding, command.executeAtIfKnown());
+
+ return new AcceptReply(outcome, superseding, command.executeAtIfKnown());
}
- public static AcceptReply reduce(AcceptReply r1, AcceptReply r2)
+ static AcceptReply inThePast(Ballot ballot, StoreParticipants participants, Command command)
{
- if (!r1.isOk() || !r2.isOk())
- return r1.outcome().compareTo(r2.outcome()) >= 0 ? r1 : r2;
+ if (participants.owns().isEmpty() && (command.is(Status.Truncated) || command.promised().compareTo(ballot) <= 0))
+ return new AcceptReply(participants.owns(), Deps.NONE);
+ return redundant(Redundant, ballot, command);
+ }
+
+ public static AcceptReply reduce(AcceptReply r1, AcceptReply r2)
+ {
+ AcceptOutcome o1 = r1.outcome(), o2 = r2.outcome();
+ AcceptOutcome o = o1.compareTo(o2) >= 0 ? o1 : o2;
Deps deps = r1.deps == null ? r2.deps : r2.deps == null ? r1.deps : r1.deps.with(r2.deps);
- if (deps == r1.deps) return r1;
- if (deps == r2.deps) return r2;
- return new AcceptReply(deps);
+ Participants<?> successful = Participants.merge(r1.successful, (Participants)r2.successful);
+ Ballot supersededBy = Ballot.nonNullOrMax(r1.supersededBy, r2.supersededBy);
+ Timestamp committedExecuteAt = r1.committedExecuteAt != null ? r1.committedExecuteAt : r2.committedExecuteAt;
+ if (o == r1.outcome && successful == r1.successful && deps == r1.deps && supersededBy == r1.supersededBy && committedExecuteAt == r1.committedExecuteAt)
+ return r1;
+ if (o == r2.outcome && successful == r2.successful && deps == r2.deps && supersededBy == r2.supersededBy && committedExecuteAt == r2.committedExecuteAt)
+ return r2;
+ return new AcceptReply(o, supersededBy, successful, deps, committedExecuteAt);
}
@Override
@@ -293,7 +365,7 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
default: throw new IllegalArgumentException("Unknown status: " + outcome);
case Redundant:
case Truncated:
- return AcceptReply.redundant(ballot, participants, safeCommand.current());
+ return AcceptReply.redundant(outcome, ballot, safeCommand.current());
case Retired:
case Success:
return AcceptReply.SUCCESS;
diff --git a/accord-core/src/main/java/accord/messages/Apply.java b/accord-core/src/main/java/accord/messages/Apply.java
index 88516ddc..66bc3887 100644
--- a/accord-core/src/main/java/accord/messages/Apply.java
+++ b/accord-core/src/main/java/accord/messages/Apply.java
@@ -43,6 +43,8 @@ import accord.topology.Topologies;
import accord.utils.Invariants;
import accord.utils.async.Cancellable;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
+
public class Apply extends TxnRequest<ApplyReply>
{
public static final Factory FACTORY = Apply::new;
@@ -84,26 +86,6 @@ public class Apply extends TxnRequest<ApplyReply>
this.minEpoch = participates.oldestEpoch();
}
- public static void sendMaximal(Node node, Id to, TxnId txnId, Route<?> sendTo, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, FullRoute<?> fullRoute)
- {
- Topologies executes = executes(node, sendTo, executeAt);
- sendMaximal(node, to, executes, txnId, sendTo, txn, executeAt, deps, writes, result, fullRoute, null);
- }
-
- public static void sendMaximal(Node node, Id to, Topologies executes, TxnId txnId, Route<?> route, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, FullRoute<?> fullRoute, @Nullable Callback<ApplyReply> callback)
- {
- Topologies participates = participates(node, route, txnId, executeAt, executes);
- // TODO (required): should this FACTORY be overridden by the implementation???
- Apply apply = applyMaximal(FACTORY, to, participates, txnId, route, txn, executeAt, deps, writes, result, fullRoute);
- if (callback == null) node.send(to, apply);
- else node.send(to, apply, callback);
- }
-
- public static Topologies executes(Node node, Unseekables<?> route, Timestamp executeAt)
- {
- return node.topology().forEpoch(route, executeAt.epoch());
- }
-
public static Topologies participates(Node node, Unseekables<?> route, TxnId txnId, Timestamp executeAt, Topologies executes)
{
return txnId.epoch() == executeAt.epoch() ? executes : participates(node, route, txnId, executeAt);
@@ -111,12 +93,7 @@ public class Apply extends TxnRequest<ApplyReply>
public static Topologies participates(Node node, Unseekables<?> route, TxnId txnId, Timestamp executeAt)
{
- return node.topology().preciseEpochs(route, txnId.epoch(), executeAt.epoch());
- }
-
- public static Apply applyMaximal(Factory factory, Id to, Topologies participates, TxnId txnId, Route<?> sendTo, Txn txn, Timestamp executeAt, Deps stableDeps, Writes writes, Result result, FullRoute<?> fullRoute)
- {
- return factory.create(Kind.Maximal, to, participates, txnId, sendTo, txn, executeAt, stableDeps, writes, result, fullRoute);
+ return node.topology().preciseEpochs(route, txnId.epoch(), executeAt.epoch(), SHARE);
}
protected Apply(Kind kind, TxnId txnId, Route<?> route, long minEpoch, long waitForEpoch, Timestamp executeAt, PartialDeps deps, @Nullable PartialTxn txn, @Nullable FullRoute<?> fullRoute, Writes writes, Result result)
@@ -177,18 +154,6 @@ public class Apply extends TxnRequest<ApplyReply>
return a.compareTo(b) >= 0 ? a : b;
}
- @Override
- public TxnId primaryTxnId()
- {
- return txnId;
- }
-
- @Override
- public Unseekables<?> keys()
- {
- return scope;
- }
-
@Override
public KeyHistory keyHistory()
{
diff --git a/accord-core/src/main/java/accord/messages/BeginInvalidation.java b/accord-core/src/main/java/accord/messages/BeginInvalidation.java
index 65b84a1c..4537a59f 100644
--- a/accord-core/src/main/java/accord/messages/BeginInvalidation.java
+++ b/accord-core/src/main/java/accord/messages/BeginInvalidation.java
@@ -101,12 +101,6 @@ public class BeginInvalidation extends AbstractRequest<BeginInvalidation.Invalid
return new InvalidateReply(supersededBy, maxStatus.accepted, maxStatus.maxStatus, maxKnowledgeStatus.maxKnowledgeStatus, acceptedFastPath, truncated, route, homeKey);
}
- @Override
- public TxnId primaryTxnId()
- {
- return txnId;
- }
-
@Override
public long waitForEpoch()
{
diff --git a/accord-core/src/main/java/accord/messages/BeginRecovery.java b/accord-core/src/main/java/accord/messages/BeginRecovery.java
index 9478d63c..d4cd79f2 100644
--- a/accord-core/src/main/java/accord/messages/BeginRecovery.java
+++ b/accord-core/src/main/java/accord/messages/BeginRecovery.java
@@ -40,7 +40,6 @@ import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.primitives.Unseekable;
-import accord.primitives.Unseekables;
import accord.primitives.Writes;
import accord.topology.Topologies;
import accord.utils.Invariants;
@@ -222,18 +221,6 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
);
}
- @Override
- public TxnId primaryTxnId()
- {
- return txnId;
- }
-
- @Override
- public Unseekables<?> keys()
- {
- return scope;
- }
-
@Override
public KeyHistory keyHistory()
{
diff --git a/accord-core/src/main/java/accord/messages/CheckStatus.java b/accord-core/src/main/java/accord/messages/CheckStatus.java
index e64af6c5..ac85ec64 100644
--- a/accord-core/src/main/java/accord/messages/CheckStatus.java
+++ b/accord-core/src/main/java/accord/messages/CheckStatus.java
@@ -121,12 +121,6 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
this.includeInfo = includeInfo;
}
- @Override
- public TxnId primaryTxnId()
- {
- return txnId;
- }
-
public CheckStatus(Id to, Topologies topologies, TxnId txnId, Participants<?> query, long sourceEpoch, IncludeInfo includeInfo)
{
super(txnId);
diff --git a/accord-core/src/main/java/accord/messages/Commit.java b/accord-core/src/main/java/accord/messages/Commit.java
index 4f76e621..30f87366 100644
--- a/accord-core/src/main/java/accord/messages/Commit.java
+++ b/accord-core/src/main/java/accord/messages/Commit.java
@@ -42,7 +42,6 @@ import accord.primitives.Route;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
-import accord.primitives.Unseekables;
import accord.topology.Topologies;
import accord.utils.Invariants;
import accord.utils.SortedArrays.SortedArrayList;
@@ -59,6 +58,7 @@ import static accord.messages.Commit.WithDeps.NoDeps;
import static accord.messages.Commit.WithTxn.HasNewlyOwnedTxnRanges;
import static accord.messages.Commit.WithTxn.HasTxn;
import static accord.messages.Commit.WithTxn.NoTxn;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
{
@@ -127,7 +127,7 @@ public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
CommitWithTxn ( HasTxn, HasDeps, Committed),
// We retain HasNewlyOwnedTxnRanges for the later eventuality where we permit fast path decisions if the fast quorum is valid for all topologies and everyone agrees on the execution timestamp.
StableFastPath( HasNewlyOwnedTxnRanges, HasDeps, SaveStatus.Stable),
- StableMediumPath( NoTxn, NoDeps, SaveStatus.Stable),
+ StableMediumPath( NoTxn, HasDeps, SaveStatus.Stable),
StableSlowPath( NoTxn, NoDeps, SaveStatus.Stable),
StableWithTxnAndDeps(HasTxn, HasDeps, SaveStatus.Stable);
@@ -188,7 +188,6 @@ public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
// TODO (desired, efficiency): do not commit if we're already ready to execute (requires extra info in Accept responses)
public static void stableAndRead(Node node, Topologies all, Kind kind, TxnId txnId, Txn txn, FullRoute<?> route, Timestamp executeAt, Deps stableDeps, IntHashSet readSet, Callback<ReadReply> callback, boolean onlyContactOldAndReadSet)
{
- Invariants.require(all.oldestEpoch() == txnId.epoch());
Invariants.require(all.currentEpoch() == executeAt.epoch());
SortedArrayList<Id> contact = all.nodes().without(all::isFaulty);
@@ -196,14 +195,6 @@ public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
txnId, txn, route, executeAt, stableDeps, callback, onlyContactOldAndReadSet);
}
- public static void stableAndRead(Id to, Node node, Topologies all, Kind kind, TxnId txnId, Txn txn, FullRoute<?> route, Timestamp executeAt, Deps stableDeps, Callback<ReadReply> callback, boolean onlyContactOldAndReadSet)
- {
- Invariants.require(all.oldestEpoch() == txnId.epoch());
- Invariants.require(all.currentEpoch() == executeAt.epoch());
-
- sendTo(to, true, true, node, all, kind, Ballot.ZERO, txnId, txn, route, executeAt, stableDeps, callback, onlyContactOldAndReadSet);
- }
-
private static <P> void sendTo(SortedArrayList<Id> contact, P param, BiPredicate<P, Id> reads, BiPredicate<P, Id> registerCallback,
Node node, Topologies all, Kind kind, Ballot ballot,
TxnId txnId, @Nullable Txn txn, FullRoute<?> route, Timestamp executeAt, @Nullable Deps deps,
@@ -252,16 +243,10 @@ public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
public static void stableMaximal(Node node, Node.Id to, Txn txn, TxnId txnId, Timestamp executeAt, FullRoute<?> route, Deps deps)
{
// the replica may be missing the original commit, or the additional commit, so send everything
- Topologies topologies = node.topology().preciseEpochs(route, txnId.epoch(), executeAt.epoch());
+ Topologies topologies = node.topology().preciseEpochs(route, txnId.epoch(), executeAt.epoch(), SHARE);
node.send(to, new Commit(StableWithTxnAndDeps, to, topologies, txnId, txn, route, Ballot.ZERO, executeAt, deps));
}
- @Override
- public Unseekables<?> keys()
- {
- return scope;
- }
-
@Override
public KeyHistory keyHistory()
{
@@ -355,7 +340,7 @@ public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
// TODO (expected, safety): this kind of check needs to be inserted in all equivalent methods
Invariants.require(untilEpoch >= txnId.epoch());
Invariants.require(node.topology().hasEpoch(untilEpoch));
- Topologies commitTo = node.topology().preciseEpochsIfExists(inform, txnId.epoch(), untilEpoch);
+ Topologies commitTo = node.topology().preciseEpochsIfExists(inform, txnId.epoch(), untilEpoch, SHARE);
commitInvalidate(node, commitTo, txnId, inform);
}
diff --git a/accord-core/src/main/java/accord/messages/GetEphemeralReadDeps.java b/accord-core/src/main/java/accord/messages/GetEphemeralReadDeps.java
index 1e375d20..755708ff 100644
--- a/accord-core/src/main/java/accord/messages/GetEphemeralReadDeps.java
+++ b/accord-core/src/main/java/accord/messages/GetEphemeralReadDeps.java
@@ -29,7 +29,6 @@ import accord.primitives.FullRoute;
import accord.primitives.Route;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
-import accord.primitives.Unseekables;
import accord.topology.Topologies;
import accord.utils.Invariants;
import accord.utils.async.Cancellable;
@@ -97,18 +96,6 @@ public class GetEphemeralReadDeps extends TxnRequest.WithUnsynced<GetEphemeralRe
'}';
}
- @Override
- public TxnId primaryTxnId()
- {
- return txnId;
- }
-
- @Override
- public Unseekables<?> keys()
- {
- return scope;
- }
-
@Override
public KeyHistory keyHistory()
{
diff --git a/accord-core/src/main/java/accord/messages/GetLatestDeps.java b/accord-core/src/main/java/accord/messages/GetLatestDeps.java
index 115ed589..b8d7b2d4 100644
--- a/accord-core/src/main/java/accord/messages/GetLatestDeps.java
+++ b/accord-core/src/main/java/accord/messages/GetLatestDeps.java
@@ -19,6 +19,7 @@
package accord.messages;
import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import accord.local.Command;
import accord.local.KeyHistory;
@@ -26,6 +27,7 @@ import accord.local.Node.Id;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.local.StoreParticipants;
+import accord.primitives.Ballot;
import accord.primitives.Deps;
import accord.primitives.LatestDeps;
import accord.primitives.PartialDeps;
@@ -33,7 +35,6 @@ import accord.primitives.Route;
import accord.primitives.Status;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
-import accord.primitives.Unseekables;
import accord.topology.Topologies;
import accord.utils.Invariants;
import accord.utils.async.Cancellable;
@@ -41,27 +42,30 @@ import accord.utils.async.Cancellable;
import static accord.messages.PreAccept.calculateDeps;
import static accord.primitives.EpochSupplier.constant;
-public class GetLatestDeps extends TxnRequest.WithUnsynced<GetLatestDeps.GetLatestDepsOk>
+public class GetLatestDeps extends TxnRequest.WithUnsynced<GetLatestDeps.GetLatestDepsReply>
{
public static final class SerializationSupport
{
- public static GetLatestDeps create(TxnId txnId, Route<?> scope, long waitForEpoch, long minEpoch, Timestamp executeAt)
+ public static GetLatestDeps create(TxnId txnId, Route<?> scope, long waitForEpoch, long minEpoch, @Nullable Ballot ballot, Timestamp executeAt)
{
- return new GetLatestDeps(txnId, scope, waitForEpoch, minEpoch, executeAt);
+ return new GetLatestDeps(txnId, scope, waitForEpoch, minEpoch, ballot, executeAt);
}
}
+ public final Ballot ballot;
public final Timestamp executeAt;
- public GetLatestDeps(Id to, Topologies topologies, Route<?> route, TxnId txnId, Timestamp executeAt)
+ public GetLatestDeps(Id to, Topologies topologies, Route<?> route, TxnId txnId, Ballot ballot, Timestamp executeAt)
{
super(to, topologies, txnId, route);
+ this.ballot = ballot;
this.executeAt = executeAt;
}
- protected GetLatestDeps(TxnId txnId, Route<?> scope, long waitForEpoch, long minEpoch, Timestamp executeAt)
+ protected GetLatestDeps(TxnId txnId, Route<?> scope, long waitForEpoch, long minEpoch, Ballot ballot, Timestamp executeAt)
{
super(txnId, scope, waitForEpoch, minEpoch);
+ this.ballot = ballot;
this.executeAt = executeAt;
}
@@ -72,11 +76,17 @@ public class GetLatestDeps extends TxnRequest.WithUnsynced<GetLatestDeps.GetLate
}
@Override
- public GetLatestDepsOk apply(SafeCommandStore safeStore)
+ public GetLatestDepsReply apply(SafeCommandStore safeStore)
{
StoreParticipants participants = StoreParticipants.read(safeStore, scope, txnId, minEpoch, executeAt.epoch());
SafeCommand safeCommand = safeStore.get(txnId, participants);
Command command = safeCommand.current();
+ if (ballot != null)
+ {
+ if (command.promised().compareTo(ballot) > 0)
+ return GetLatestDepsNack.INSTANCE;
+ command = safeCommand.updatePromised(ballot);
+ }
PartialDeps coordinatedDeps = command.partialDeps();
Deps localDeps = null;
if (!command.known().deps().hasCommittedOrDecidedDeps() && !command.hasBeen(Status.Truncated))
@@ -89,9 +99,11 @@ public class GetLatestDeps extends TxnRequest.WithUnsynced<GetLatestDeps.GetLate
}
@Override
- public GetLatestDepsOk reduce(GetLatestDepsOk ok1, GetLatestDepsOk ok2)
+ public GetLatestDepsReply reduce(GetLatestDepsReply r1, GetLatestDepsReply r2)
{
- return new GetLatestDepsOk(LatestDeps.merge(ok1.deps, ok2.deps));
+ if (!r1.isOk()) return r1;
+ if (!r2.isOk()) return r2;
+ return new GetLatestDepsOk(LatestDeps.merge(((GetLatestDepsOk)r1).deps, ((GetLatestDepsOk)r2).deps));
}
@Override
@@ -111,24 +123,35 @@ public class GetLatestDeps extends TxnRequest.WithUnsynced<GetLatestDeps.GetLate
}
@Override
- public TxnId primaryTxnId()
+ public KeyHistory keyHistory()
{
- return txnId;
+ return KeyHistory.SYNC;
}
- @Override
- public Unseekables<?> keys()
+ public interface GetLatestDepsReply extends Reply
{
- return scope;
+ boolean isOk();
}
- @Override
- public KeyHistory keyHistory()
+ public static final class GetLatestDepsNack implements GetLatestDepsReply
{
- return KeyHistory.SYNC;
+ public static final GetLatestDepsNack INSTANCE = new GetLatestDepsNack();
+ private GetLatestDepsNack(){}
+
+ @Override
+ public boolean isOk()
+ {
+ return false;
+ }
+
+ @Override
+ public MessageType type()
+ {
+ return MessageType.GET_LATEST_DEPS_RSP;
+ }
}
- public static class GetLatestDepsOk implements Reply
+ public static class GetLatestDepsOk implements GetLatestDepsReply
{
public final LatestDeps deps;
@@ -148,6 +171,12 @@ public class GetLatestDeps extends TxnRequest.WithUnsynced<GetLatestDeps.GetLate
{
return MessageType.GET_LATEST_DEPS_RSP;
}
+
+ @Override
+ public boolean isOk()
+ {
+ return true;
+ }
}
}
diff --git a/accord-core/src/main/java/accord/messages/InformDurable.java b/accord-core/src/main/java/accord/messages/InformDurable.java
index 9d5f07df..d89db311 100644
--- a/accord-core/src/main/java/accord/messages/InformDurable.java
+++ b/accord-core/src/main/java/accord/messages/InformDurable.java
@@ -149,10 +149,4 @@ public class InformDurable extends TxnRequest<Reply> implements PreLoadContext
{
return MessageType.INFORM_DURABLE_REQ;
}
-
- @Override
- public TxnId primaryTxnId()
- {
- return txnId;
- }
}
diff --git a/accord-core/src/main/java/accord/messages/PreAccept.java b/accord-core/src/main/java/accord/messages/PreAccept.java
index 6a9000f4..cc948373 100644
--- a/accord-core/src/main/java/accord/messages/PreAccept.java
+++ b/accord-core/src/main/java/accord/messages/PreAccept.java
@@ -32,6 +32,7 @@ import accord.local.Node.Id;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.primitives.PartialDeps;
+import accord.primitives.Participants;
import accord.primitives.RangeDeps;
import accord.local.StoreParticipants;
import accord.messages.TxnRequest.WithUnsynced;
@@ -44,7 +45,6 @@ import accord.primitives.Status;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
-import accord.primitives.Unseekables;
import accord.topology.Shard;
import accord.topology.Topologies;
import accord.utils.Invariants;
@@ -97,18 +97,6 @@ public class PreAccept extends WithUnsynced<PreAccept.PreAcceptReply>
this.hasCoordinatorVote = hasCoordinatorVote;
}
- @Override
- public TxnId primaryTxnId()
- {
- return txnId;
- }
-
- @Override
- public Unseekables<?> keys()
- {
- return scope;
- }
-
@Override
public KeyHistory keyHistory()
{
@@ -265,12 +253,17 @@ public class PreAccept extends WithUnsynced<PreAccept.PreAcceptReply>
}
public static Deps calculateDeps(SafeCommandStore safeStore, TxnId txnId, StoreParticipants participants, EpochSupplier minEpoch, Timestamp executeAt, boolean nullIfRedundant)
+ {
+ return calculateDeps(safeStore, txnId, participants.touches(), minEpoch, executeAt, nullIfRedundant);
+ }
+
+ public static Deps calculateDeps(SafeCommandStore safeStore, TxnId txnId, Participants<?> touches, EpochSupplier minEpoch, Timestamp executeAt, boolean nullIfRedundant)
{
// NOTE: ExclusiveSyncPoint *relies* on STARTED_BEFORE to ensure it reports a dependency on *every* earlier TxnId that may execute (before or after it).
try (Deps.AbstractBuilder<Deps> builder = new Deps.Builder(true);
RangeDeps.BuilderByRange redundantBuilder = RangeDeps.builderByRange())
{
- RangeDeps redundant = safeStore.redundantBefore().collectDeps(participants.touches(), redundantBuilder, minEpoch, executeAt).build();
+ RangeDeps redundant = safeStore.redundantBefore().collectDeps(touches, redundantBuilder, minEpoch, executeAt).build();
if (nullIfRedundant && !txnId.is(EphemeralRead))
{
TxnId maxRedundantBefore = redundant.maxTxnId(null);
@@ -281,7 +274,7 @@ public class PreAccept extends WithUnsynced<PreAccept.PreAcceptReply>
}
}
- safeStore.visit(participants.touches(), executeAt, txnId.witnesses(),
+ safeStore.visit(touches, executeAt, txnId.witnesses(),
(p1, in, keyOrRange, testTxnId) -> {
if (p1 == null || !testTxnId.equals(p1))
in.add(keyOrRange, testTxnId);
diff --git a/accord-core/src/main/java/accord/messages/Propagate.java b/accord-core/src/main/java/accord/messages/Propagate.java
index d5fb8390..a8c2c27e 100644
--- a/accord-core/src/main/java/accord/messages/Propagate.java
+++ b/accord-core/src/main/java/accord/messages/Propagate.java
@@ -83,7 +83,8 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
// TODO (desired): remove dependency on these two SaveStatus
final SaveStatus maxKnowledgeSaveStatus;
final SaveStatus maxSaveStatus;
- final Ballot ballot;
+ final Ballot promised;
+ final Ballot acceptedOrCommitted;
final Status.Durability durability;
@Nullable final RoutingKey homeKey;
// this is a WHOLE NODE measure, so if commit epoch has more ranges we do not count as committed if we can only commit in coordination epoch
@@ -105,8 +106,8 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
Route<?> route,
Unseekables<?> propagateTo, Known target, InvalidIf invalidIf,
SaveStatus maxKnowledgeSaveStatus,
- SaveStatus maxSaveStatus,
- Ballot ballot,
+ SaveStatus maxSaveStatus, Ballot promised,
+ Ballot acceptedOrCommitted,
Status.Durability durability,
@Nullable RoutingKey homeKey,
KnownMap known, WithQuorum withQuorum,
@@ -127,7 +128,8 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
this.invalidIf = invalidIf;
this.maxKnowledgeSaveStatus = maxKnowledgeSaveStatus;
this.maxSaveStatus = maxSaveStatus;
- this.ballot = ballot;
+ this.promised = promised;
+ this.acceptedOrCommitted = acceptedOrCommitted;
this.durability = durability;
this.homeKey = homeKey;
this.known = known;
@@ -158,7 +160,7 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
Route<?> route = Invariants.nonNull(full.route);
Propagate propagate =
- new Propagate(node, txnId, route, propagateTo, target, full.invalidIf, full.maxKnowledgeSaveStatus, full.maxSaveStatus, full.acceptedOrCommitted, full.durability, full.homeKey, full.map, withQuorum, full.partialTxn, full.stableDeps, lowEpoch, highEpoch, full.executeAtIfKnown(), full.writes, full.result, callback);
+ new Propagate(node, txnId, route, propagateTo, target, full.invalidIf, full.maxKnowledgeSaveStatus, full.maxSaveStatus, full.maxPromised, full.acceptedOrCommitted, full.durability, full.homeKey, full.map, withQuorum, full.partialTxn, full.stableDeps, lowEpoch, highEpoch, full.executeAtIfKnown(), full.writes, full.result, callback);
if (full.executeAt != null && full.executeAt.epoch() > highEpoch)
highEpoch = full.executeAt.epoch();
@@ -282,13 +284,13 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
break;
case Stable:
- confirm(Commands.commit(safeStore, safeCommand, participants, Stable, ballot, txnId, route, partialTxn, executeAtIfKnown, stableDeps, null));
+ confirm(Commands.commit(safeStore, safeCommand, participants, Stable, acceptedOrCommitted, txnId, route, partialTxn, executeAtIfKnown, stableDeps, null));
break;
case Committed:
// TODO (expected): we can propagate Committed as Stable if we have any other Stable result AND a quorum of committedDeps
case PreCommitted:
- confirm(Commands.precommit(safeStore, safeCommand, participants, txnId, executeAtIfKnown));
+ confirm(Commands.precommit(safeStore, safeCommand, participants, txnId, executeAtIfKnown, promised));
// TODO (desired): would it be clearer to yield a SaveStatus so we can have PreCommittedWithDefinition
if (!found.definition().isKnown())
break;
diff --git a/accord-core/src/main/java/accord/messages/ReadData.java b/accord-core/src/main/java/accord/messages/ReadData.java
index 676e72c6..8cba1a25 100644
--- a/accord-core/src/main/java/accord/messages/ReadData.java
+++ b/accord-core/src/main/java/accord/messages/ReadData.java
@@ -181,6 +181,7 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
process(on, expiresAt);
}
+ // TODO (expected): register slowAt
public final void process(Node on, long expiresAt)
{
this.node = on;
diff --git a/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java b/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
index 6bce3cc7..eb8a1c70 100644
--- a/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
+++ b/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
@@ -91,6 +91,14 @@ public class ReadEphemeralTxnData extends ReadData
this.route = route;
}
+ @Override
+ public CommitOrReadNack apply(SafeCommandStore safeStore)
+ {
+ StoreParticipants participants = StoreParticipants.execute(safeStore, route, txnId, minEpoch(), executeAtEpoch);
+ SafeCommand safeCommand = safeStore.get(txnId, participants);
+ return apply(safeStore, safeCommand, participants);
+ }
+
@Override
protected synchronized CommitOrReadNack apply(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants)
{
diff --git a/accord-core/src/main/java/accord/messages/SafeCallback.java b/accord-core/src/main/java/accord/messages/SafeCallback.java
index 02aeefc6..1be03788 100644
--- a/accord-core/src/main/java/accord/messages/SafeCallback.java
+++ b/accord-core/src/main/java/accord/messages/SafeCallback.java
@@ -68,7 +68,7 @@ public class SafeCallback<T extends Reply>
private <P> void safeCall(Node.Id src, P param, SafeCall<T, P> call)
{
// TODO (low priority, correctness): if the executor is shutdown this propgates the exception to the network stack
- executor.execute(() -> {
+ executor.maybeExecuteImmediately(() -> {
try
{
call.accept(callback, src, param);
diff --git a/accord-core/src/main/java/accord/messages/StableThenRead.java b/accord-core/src/main/java/accord/messages/StableThenRead.java
index 3c37f59c..793482d5 100644
--- a/accord-core/src/main/java/accord/messages/StableThenRead.java
+++ b/accord-core/src/main/java/accord/messages/StableThenRead.java
@@ -91,6 +91,8 @@ public class StableThenRead extends ReadData
StoreParticipants participants = StoreParticipants.execute(safeStore, route, txnId, minEpoch(), executeAtEpoch);
SafeCommand safeCommand = safeStore.get(txnId, participants);
Commands.commit(safeStore, safeCommand, participants, kind.saveStatus, Ballot.ZERO, txnId, route, partialTxn, executeAt, partialDeps, kind);
+ if (participants.executes().isEmpty())
+ return null;
return super.apply(safeStore, safeCommand, participants);
}
diff --git a/accord-core/src/main/java/accord/messages/TxnRequest.java b/accord-core/src/main/java/accord/messages/TxnRequest.java
index 89f7db1a..1cf58445 100644
--- a/accord-core/src/main/java/accord/messages/TxnRequest.java
+++ b/accord-core/src/main/java/accord/messages/TxnRequest.java
@@ -104,6 +104,12 @@ public abstract class TxnRequest<R extends Reply> extends AbstractRequest<R> imp
return scope;
}
+ @Override
+ public Unseekables<?> keys()
+ {
+ return scope;
+ }
+
/**
* The minimum epoch the recipient needs to know in order to process the request. This is computed by the sender
* to permit a recipient to process a request before knowing of a topology change if the sender determines it is
diff --git a/accord-core/src/main/java/accord/primitives/AbstractKeys.java b/accord-core/src/main/java/accord/primitives/AbstractKeys.java
index f00e6658..637072ec 100644
--- a/accord-core/src/main/java/accord/primitives/AbstractKeys.java
+++ b/accord-core/src/main/java/accord/primitives/AbstractKeys.java
@@ -94,19 +94,6 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
return keys.length;
}
- @Override
- public final boolean contains(RoutableKey key)
- {
- return Arrays.binarySearch(keys, key) >= 0;
- }
-
- @Override
- public final boolean containsAll(Routables<?> keysOrRanges)
- {
- // TODO (required): this is incorrect for ranges, it's effectively intersectsAll
- return keysOrRanges.size() == Routables.foldl(keysOrRanges, this, (k, p, v, i) -> v + 1, 0, 0, 0);
- }
-
@Override
public final boolean intersects(AbstractUnseekableKeys keys)
{
@@ -119,18 +106,6 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
return findNextIntersection(0, ranges, 0) >= 0;
}
- @Override
- public final int find(RoutableKey key, SortedArrays.Search search)
- {
- return SortedArrays.binarySearch(keys, 0, keys.length, key, RoutableKey::compareTo, search);
- }
-
- @Override
- public final int findNext(int thisIndex, RoutableKey key, SortedArrays.Search search)
- {
- return SortedArrays.exponentialSearch(keys, thisIndex, keys.length, key, RoutableKey::compareTo, search);
- }
-
@Override
public final int find(Range find, SortedArrays.Search search)
{
@@ -150,21 +125,20 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
}
@Override
- public final long findNextIntersection(int thisIdx, AbstractKeys<?> that, int thatIdx)
+ public final long findNextIntersection(int thisIdx, AbstractUnseekableKeys that, int thatIdx)
{
- return SortedArrays.findNextIntersection(this.keys, thisIdx, that.keys, thatIdx, RoutableKey::compareTo);
+ return SortedArrays.findNextIntersection(this.keys, thisIdx, that.keys, thatIdx, RoutableKey::compareAsRoutingKey);
}
@Override
- public final long findNextIntersection(int thisIdx, AbstractUnseekableKeys that, int thatIdx)
+ public final long findNextSameKindIntersection(int thisIdx, Routables<K> that, int thatIdx)
{
- return SortedArrays.findNextIntersection(this.keys, thisIdx, that.keys, thatIdx, RoutableKey::compareAsRoutingKey);
+ return SortedArrays.findNextIntersection(this.keys, thisIdx, ((AbstractKeys<?>)that).keys, thatIdx, RoutableKey::compareTo);
}
- @Override
- public final long findNextIntersection(int thisIndex, Routables<K> with, int withIndex)
+ final boolean containsAllSameKind(AbstractKeys<?> that)
{
- return findNextIntersection(thisIndex, (AbstractKeys<?>) with, withIndex);
+ return that.size() == SortedArrays.foldlIntersection(keys, 0, keys.length, that.keys, 0, that.keys.length, (k, p, v, l, r) -> v + 1, 0, 0, 0);
}
@Override
@@ -261,18 +235,6 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
return Routables.foldl(this, rs, fold, accumulator);
}
- @Inline
- public final long foldl(AbstractKeys<K> intersect, IndexedFoldToLong<K> fold, long param, long accumulator, long terminalValue)
- {
- return Routables.foldl(this, intersect, fold, param, accumulator, terminalValue);
- }
-
- @Inline
- public final <P1, P2, V> V foldl(AbstractKeys<K> intersect, IndexedTriFold<P1, P2, K, V> fold, P1 p1, P2 p2, V accumulator)
- {
- return Routables.foldl(this, intersect, fold, p1, p2, accumulator, i -> false);
- }
-
@Inline
public final <P1, P2, V> V foldl(AbstractRanges intersect, IndexedTriFold<P1, P2, K, V> fold, P1 p1, P2 p2, V accumulator)
{
@@ -300,6 +262,12 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
return Routables.foldl(this, rs, fold, param, initialValue, terminalValue);
}
+ @Inline
+ public final long foldl(AbstractKeys<K> that, IndexedFoldToLong<? super K> fold, long param, long initialValue, long terminalValue)
+ {
+ return Routables.foldl(this, that, fold, param, initialValue, terminalValue);
+ }
+
@Inline
public final long foldl(IndexedFoldToLong<? super K> fold, long param, long initialValue, long terminalValue)
{
diff --git a/accord-core/src/main/java/accord/primitives/AbstractRanges.java b/accord-core/src/main/java/accord/primitives/AbstractRanges.java
index 45bc4609..4ed129c1 100644
--- a/accord-core/src/main/java/accord/primitives/AbstractRanges.java
+++ b/accord-core/src/main/java/accord/primitives/AbstractRanges.java
@@ -25,6 +25,7 @@ import javax.annotation.Nonnull;
import com.google.common.collect.Iterators;
+import accord.api.Key;
import accord.api.RoutingKey;
import accord.utils.ArrayBuffers.ObjectBuffers;
import accord.utils.IndexedFoldToLong;
@@ -54,6 +55,12 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
this.ranges = Invariants.nonNull(ranges);
}
+ @Override
+ public final Routable.Kind domainKind()
+ {
+ return Routable.Kind.Range;
+ }
+
public int indexOf(RoutableKey key)
{
return SortedArrays.binarySearch(ranges, 0, ranges.length, key, (k, r) -> -r.compareTo(k), FAST);
@@ -69,67 +76,55 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
return indexOf(find, CEIL);
}
- @Override
- public boolean contains(RoutableKey key)
+ public final boolean contains(RoutingKey key)
{
return indexOf(key) >= 0;
}
- @Override
- public boolean containsAll(Routables<?> that)
+ public final boolean contains(Key key)
{
- switch (that.domain())
- {
- default: throw new AssertionError();
- case Key: return containsAll((AbstractKeys<?>) that);
- case Range: return containsAll((AbstractRanges) that);
- }
+ return indexOf(key) >= 0;
}
- /**
- * @return true iff {@code that} is fully contained within {@code this}
- */
- public boolean containsAll(AbstractKeys<?> that)
+ public final boolean contains(RoutableKey key)
{
- if (this.isEmpty()) return that.isEmpty();
- if (that.isEmpty()) return true;
- return Routables.rangeFoldl(that, this, (p, v, from, to) -> v + (to - from), 0, 0, 0) == that.size();
+ return indexOf(key) >= 0;
}
/**
- * @return true iff {@code that} is a subset of {@code this}
+ * @return true iff {@code that} is fully contained within {@code this}
*/
- public boolean containsAll(AbstractRanges that)
+ public final boolean containsAll(Keys that)
{
- if (this.isEmpty()) return that.isEmpty();
- if (that.isEmpty()) return true;
- return ((int) supersetLinearMerge(this.ranges, that.ranges)) == that.size();
+ return containsAll((AbstractKeys<?>) that);
}
- @Override
- public boolean intersectsAll(Unseekables<?> keysOrRanges)
+ /**
+ * @return true iff {@code that} is fully contained within {@code this}
+ */
+ public final boolean containsAll(AbstractUnseekableKeys that)
{
- return intersectsAll((Routables<?>) keysOrRanges);
+ return containsAll((AbstractKeys<?>) that);
}
- public boolean intersectsAll(Routables<?> that)
+ /**
+ * @return true iff {@code that} is fully contained within {@code this}
+ */
+ public final boolean containsAll(AbstractKeys<?> that)
{
- switch (that.domain())
- {
- default: throw new AssertionError();
- case Key: return containsAll((AbstractKeys<?>) that);
- case Range: return intersectsAll((AbstractRanges) that);
- }
+ if (this.isEmpty()) return that.isEmpty();
+ if (that.isEmpty()) return true;
+ return Routables.rangeFoldl(that, this, (p, v, from, to) -> v + (to - from), 0, 0, 0) == that.size();
}
/**
* @return true iff {@code that} is a subset of {@code this}
*/
- public boolean intersectsAll(AbstractRanges that)
+ public final boolean containsAll(AbstractRanges that)
{
if (this.isEmpty()) return that.isEmpty();
if (that.isEmpty()) return true;
- return Routables.rangeFoldl(that, this, (p, v, from, to) -> v + (to - from), 0, 0, 0) == that.size();
+ return ((int) supersetLinearMerge(this.ranges, that.ranges)) == that.size();
}
@Override
@@ -186,7 +181,7 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
// returns ri in low 32 bits, ki in top, or -1 if no match found
@Override
- public final long findNextIntersection(int ri, AbstractKeys<?> keys, int ki)
+ public final long findNextIntersection(int ri, Keys keys, int ki)
{
return swapHighLow32b(SortedArrays.findNextIntersectionWithMultipleMatches(keys.keys, ki, ranges, ri));
}
@@ -204,6 +199,12 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
return SortedArrays.findNextIntersectionWithMultipleMatches(ranges, thisi, that.ranges, thati, Range::compareIntersecting, Range::compareIntersecting);
}
+ // returns ki in bottom 32 bits, ri in top, or -1 if no match found
+ public final long findNextSameKindIntersection(int thisi, Routables<Range> that, int thati)
+ {
+ return findNextIntersection(thisi, (AbstractRanges) that, thati);
+ }
+
@Override
public final long findNextIntersection(int thisIndex, Routables<Range> with, int withIndex)
{
@@ -222,14 +223,12 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
return SortedArrays.exponentialSearch(ranges, thisIndex, size(), find, Range::compareIntersecting, search);
}
- @Override
- public final int find(RoutableKey find, SortedArrays.Search search)
+ public final int find(RoutingKey find, SortedArrays.Search search)
{
return SortedArrays.binarySearch(ranges, 0, size(), find, (k, r) -> -r.compareTo(k), search);
}
- @Override
- public final int findNext(int thisIndex, RoutableKey find, SortedArrays.Search search)
+ public final int findNext(int thisIndex, RoutingKey find, SortedArrays.Search search)
{
return SortedArrays.exponentialSearch(ranges, thisIndex, size(), find, (k, r) -> -r.compareTo(k), search);
}
@@ -665,7 +664,7 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
try
{
int count = copyAndMergeTouching(ranges, 0, buffer, 0, ranges.length);
- if (count == buffer.length)
+ if (count == ranges.length)
return input;
Range[] result = cachedRanges.complete(buffer, count);
cachedRanges.discard(buffer, count);
diff --git a/accord-core/src/main/java/accord/primitives/AbstractUnseekableKeys.java b/accord-core/src/main/java/accord/primitives/AbstractUnseekableKeys.java
index ba89a185..7a163dfb 100644
--- a/accord-core/src/main/java/accord/primitives/AbstractUnseekableKeys.java
+++ b/accord-core/src/main/java/accord/primitives/AbstractUnseekableKeys.java
@@ -18,11 +18,13 @@
package accord.primitives;
+import accord.api.Key;
import accord.api.RoutingKey;
import accord.utils.SortedArrays;
import java.util.Arrays;
+import static accord.primitives.Routable.Kind.UnseekableKey;
import static accord.utils.ArrayBuffers.cachedRoutingKeys;
// TODO: do we need this class?
@@ -34,6 +36,12 @@ implements Iterable<RoutingKey>, Unseekables<RoutingKey>, Participants<RoutingKe
super(keys);
}
+ @Override
+ public final Routable.Kind domainKind()
+ {
+ return UnseekableKey;
+ }
+
@Override
public final int indexOf(RoutingKey key)
{
@@ -41,9 +49,52 @@ implements Iterable<RoutingKey>, Unseekables<RoutingKey>, Participants<RoutingKe
}
@Override
- public final boolean intersectsAll(Unseekables<?> keysOrRanges)
+ public final boolean contains(RoutingKey key)
+ {
+ return Arrays.binarySearch(keys, key) >= 0;
+ }
+
+ @Override
+ public final boolean contains(Key key)
+ {
+ return Arrays.binarySearch(keys, key, RoutableKey::compareAsRoutingKey) >= 0;
+ }
+
+ @Override
+ public final int find(RoutingKey key, SortedArrays.Search search)
+ {
+ return SortedArrays.binarySearch(keys, 0, keys.length, key, RoutingKey::compareTo, search);
+ }
+
+ @Override
+ public final int findNext(int thisIndex, RoutingKey key, SortedArrays.Search search)
+ {
+ return SortedArrays.exponentialSearch(keys, thisIndex, keys.length, key, RoutingKey::compareTo, search);
+ }
+
+ @Override
+ public long findNextIntersection(int thisIndex, Keys with, int withIndex)
+ {
+ return SortedArrays.findNextIntersection(this.keys, thisIndex, with.keys, withIndex, RoutableKey::compareAsRoutingKey);
+ }
+
+ @Override
+ public final boolean containsAll(AbstractUnseekableKeys that)
+ {
+ return containsAllSameKind(that);
+ }
+
+ @Override
+ public final boolean containsAll(Keys that)
+ {
+ return that.size() == SortedArrays.foldlIntersection(0, RoutableKey::compareAsRoutingKey, keys, 0, keys.length, that.keys, 0, that.keys.length, (k, p, v, l, r) -> v + 1, 0, 0, 0);
+ }
+
+ @Override
+ public boolean containsAll(AbstractRanges ranges)
{
- return containsAll(keysOrRanges);
+ // TODO (desired): something more efficient
+ return toRanges().containsAll(ranges);
}
@Override
diff --git a/accord-core/src/main/java/accord/primitives/KeyDeps.java b/accord-core/src/main/java/accord/primitives/KeyDeps.java
index c3295503..b02b9030 100644
--- a/accord-core/src/main/java/accord/primitives/KeyDeps.java
+++ b/accord-core/src/main/java/accord/primitives/KeyDeps.java
@@ -424,7 +424,7 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
public void forEach(Ranges ranges, BiConsumer<RoutingKey, TxnId> forEach)
{
int[] keysToTxnIds = keysToTxnIds();
- Routables.foldl(keys, ranges, (key, value, index) -> {
+ Routables.foldl(keys, (AbstractRanges) ranges, (key, value, index) -> {
for (int t = startOffset(index), end = endOffset(index); t < end ; ++t)
{
TxnId txnId = txnIds[keysToTxnIds[t]];
@@ -472,7 +472,7 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
}
else
{
- BitSet bitset = Routables.foldl(keys, ranges, (key, value, keyIndex) -> {
+ BitSet bitset = Routables.foldl(keys, (AbstractRanges) ranges, (key, value, keyIndex) -> {
int index = startOffset(keyIndex);
int end = endOffset(keyIndex);
while (index < end)
diff --git a/accord-core/src/main/java/accord/primitives/KeyRoute.java b/accord-core/src/main/java/accord/primitives/KeyRoute.java
index 168faac0..e4b50b75 100644
--- a/accord-core/src/main/java/accord/primitives/KeyRoute.java
+++ b/accord-core/src/main/java/accord/primitives/KeyRoute.java
@@ -66,8 +66,7 @@ public abstract class KeyRoute extends AbstractUnseekableKeys implements Route<R
case Key:
{
AbstractUnseekableKeys that = (AbstractUnseekableKeys) keysOrRanges;
- RoutingKey[] newKeys = SortedArrays.linearSubtract(this.keys, that.keys, cachedRoutingKeys());
- return newKeys == keys ? this : new PartialKeyRoute(homeKey, newKeys);
+ return select(SortedArrays.linearSubtract(this.keys, that.keys, cachedRoutingKeys()));
}
case Range:
{
@@ -84,8 +83,7 @@ public abstract class KeyRoute extends AbstractUnseekableKeys implements Route<R
private KeyRoute without(AbstractRanges ranges)
{
- RoutingKey[] newKeys = subtract(ranges, keys, RoutingKey[]::new);
- return newKeys == keys ? this : new PartialKeyRoute(homeKey, newKeys);
+ return select(subtract(ranges, keys, RoutingKey[]::new));
}
@SuppressWarnings("unchecked")
@@ -129,38 +127,36 @@ public abstract class KeyRoute extends AbstractUnseekableKeys implements Route<R
}
@Override
- public PartialKeyRoute slice(Ranges select)
+ public KeyRoute slice(Ranges select)
{
- return new PartialKeyRoute(homeKey, slice(select, RoutingKey[]::new));
+ return select(slice(select, RoutingKey[]::new));
}
@Override
- public PartialKeyRoute slice(Ranges ranges, Slice slice)
+ public KeyRoute slice(Ranges ranges, Slice slice)
{
return slice(ranges);
}
@Override
- public PartialKeyRoute intersecting(Unseekables<?> intersecting)
+ public KeyRoute intersecting(Unseekables<?> intersecting)
{
switch (intersecting.domain())
{
default: throw new AssertionError("Unhandled domain: " + intersecting.domain());
- case Key: return new PartialKeyRoute(homeKey, intersecting((AbstractUnseekableKeys)intersecting, cachedRoutingKeys()));
- case Range: return new PartialKeyRoute(homeKey, slice((AbstractRanges)intersecting, RoutingKey[]::new));
+ case Key: return select(intersecting((AbstractUnseekableKeys)intersecting, cachedRoutingKeys()));
+ case Range: return select(slice((AbstractRanges)intersecting, RoutingKey[]::new));
}
}
@Override
- public PartialKeyRoute intersecting(Unseekables<?> intersecting, Slice slice)
+ public KeyRoute intersecting(Unseekables<?> intersecting, Slice slice)
{
return intersecting(intersecting);
}
- private AbstractUnseekableKeys wrap(RoutingKey[] wrap, AbstractKeys<RoutingKey> that)
+ private KeyRoute select(RoutingKey[] newKeys)
{
- return wrap == keys ? this : wrap == that.keys && that instanceof AbstractUnseekableKeys
- ? (AbstractUnseekableKeys) that
- : new RoutingKeys(wrap);
+ return newKeys == keys ? this : new PartialKeyRoute(homeKey, newKeys);
}
}
diff --git a/accord-core/src/main/java/accord/primitives/Keys.java b/accord-core/src/main/java/accord/primitives/Keys.java
index 7a8687d8..5304b737 100644
--- a/accord-core/src/main/java/accord/primitives/Keys.java
+++ b/accord-core/src/main/java/accord/primitives/Keys.java
@@ -26,11 +26,11 @@ import java.util.SortedSet;
import java.util.function.Function;
import accord.api.Key;
-import accord.primitives.Routable.Domain;
+import accord.api.RoutingKey;
import accord.utils.ArrayBuffers.ObjectBuffers;
-import accord.utils.Invariants;
import accord.utils.SortedArrays;
+import static accord.primitives.Routable.Kind.SeekableKey;
import static accord.utils.ArrayBuffers.cachedKeys;
import static accord.utils.SortedArrays.isSortedUnique;
@@ -64,6 +64,12 @@ public class Keys extends AbstractKeys<Key> implements Seekables<Key, Keys>
super(keys);
}
+ @Override
+ public final Routable.Kind domainKind()
+ {
+ return SeekableKey;
+ }
+
@Override
public boolean equals(Object o)
{
@@ -86,11 +92,21 @@ public class Keys extends AbstractKeys<Key> implements Seekables<Key, Keys>
}
@Override
- public final boolean intersectsAll(Unseekables<?> keysOrRanges)
+ public final boolean containsAll(AbstractUnseekableKeys that)
+ {
+ return that.size() == SortedArrays.foldlIntersection(0, RoutableKey::compareAsRoutingKey, that.keys, 0, that.keys.length, keys, 0, keys.length, (k, p, v, l, r) -> v + 1, 0, 0, 0);
+ }
+
+ @Override
+ public final boolean containsAll(Keys that)
+ {
+ return containsAllSameKind(that);
+ }
+
+ @Override
+ public final boolean containsAll(AbstractRanges ranges)
{
- Invariants.requireArgument(keysOrRanges.domain() == Domain.Key);
- AbstractUnseekableKeys that = (AbstractUnseekableKeys) keysOrRanges;
- return SortedArrays.isSubset((rk, k) -> -k.compareAsRoutingKey(rk), that.keys, 0, that.keys.length, this.keys, 0, this.keys.length);
+ throw new UnsupportedOperationException();
}
@Override
@@ -145,6 +161,12 @@ public class Keys extends AbstractKeys<Key> implements Seekables<Key, Keys>
return wrap(SortedArrays.intersectWithMultipleMatches(this.keys, this.keys.length, that.keys, that.keys.length, Key::compareAsRoutingKey, cachedKeys()), this);
}
+ @Override
+ public final long findNextIntersection(int thisIndex, Keys with, int withIndex)
+ {
+ return SortedArrays.findNextIntersection(this.keys, thisIndex, with.keys, withIndex, Key::compareTo);
+ }
+
public Keys with(Key key)
{
int insertPos = Arrays.binarySearch(keys, key);
@@ -171,6 +193,36 @@ public class Keys extends AbstractKeys<Key> implements Seekables<Key, Keys>
return wrap(subtract(ranges, keys, Key[]::new));
}
+ @Override
+ public boolean contains(RoutingKey key)
+ {
+ return Arrays.binarySearch(keys, key, RoutableKey::compareAsRoutingKey) >= 0;
+ }
+
+ @Override
+ public final boolean contains(Key key)
+ {
+ return Arrays.binarySearch(keys, key, RoutableKey::compareTo) >= 0;
+ }
+
+ @Override
+ public int find(RoutingKey find, SortedArrays.Search search)
+ {
+ return SortedArrays.binarySearch(keys, 0, keys.length, find, RoutingKey::compareAsRoutingKey, search);
+ }
+
+ @Override
+ public int findNext(int thisIndex, RoutingKey find, SortedArrays.Search search)
+ {
+ return SortedArrays.exponentialSearch(keys, thisIndex, keys.length, find, RoutingKey::compareAsRoutingKey, search);
+ }
+
+ @Override
+ public int findNext(int thisIndex, Key find, SortedArrays.Search search)
+ {
+ return SortedArrays.exponentialSearch(keys, thisIndex, keys.length, find, Key::compareTo, search);
+ }
+
@Override
public Keys without(Keys subtract)
{
diff --git a/accord-core/src/main/java/accord/primitives/LatestDeps.java b/accord-core/src/main/java/accord/primitives/LatestDeps.java
index 6d892f45..e5e688e4 100644
--- a/accord-core/src/main/java/accord/primitives/LatestDeps.java
+++ b/accord-core/src/main/java/accord/primitives/LatestDeps.java
@@ -33,20 +33,23 @@ import com.google.common.collect.ImmutableList;
import accord.api.RoutingKey;
import accord.coordinate.CollectLatestDeps;
+import accord.coordinate.CoordinationAdapter;
import accord.local.Node;
import accord.primitives.Known.KnownDeps;
+import accord.topology.Topologies.SelectNodeOwnership;
import accord.utils.Invariants;
import accord.utils.ReducingIntervalMap;
import accord.utils.ReducingRangeMap;
import accord.utils.TriFunction;
import accord.utils.UnhandledEnum;
+import static accord.messages.Accept.Kind.SLOW;
import static accord.primitives.Known.KnownDeps.DepsCommitted;
import static accord.primitives.Known.KnownDeps.DepsErased;
import static accord.primitives.Known.KnownDeps.DepsKnown;
import static accord.primitives.Known.KnownDeps.DepsProposed;
import static accord.primitives.Known.KnownDeps.DepsProposedFixed;
-import static accord.primitives.Known.KnownDeps.DepsUnknown;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
{
@@ -60,29 +63,110 @@ public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
}
}
- public static void withCommitted(Node node, TxnId txnId, Timestamp executeAt, Deps mergeDeps, FullRoute<?> route, Unseekables<?> missing, BiConsumer<?, Throwable> failureCallback, Consumer<Deps> withDeps)
+ public static void withCommitted(CoordinationAdapter<?> adapter, Node node, Merge merge, FullRoute<?> route, Ballot ballot, TxnId txnId, Timestamp executeAt, Txn txn, BiConsumer<?, Throwable> failureCallback, Consumer<Deps> withDeps)
{
- node.withEpoch(executeAt.epoch(), failureCallback, () -> {
- if (missing.isEmpty())
+ if (!node.topology().hasEpoch(executeAt.epoch()))
+ {
+ node.withEpoch(executeAt.epoch(), failureCallback, () -> withCommitted(adapter, node, merge, route, ballot, txnId, executeAt, txn, failureCallback, withDeps));
+ return;
+ }
+
+ LatestDeps.MergedCommitResult merged = merge.mergeCommitOrStable(null, DepsCommitted);
+ Route<?> missing = route.without(merged.sufficientFor);
+ Deps committed = merged.deps;
+ if (missing.isEmpty()) withDeps.accept(merged.deps);
+ else
+ {
+ // we include the committed deps in our proposal so that if we contact a replica that participates in one of the committed shards we include any deps it should see
+ Deps propose = merge.mergeProposal(missing).with(committed);
+ adapter.proposeOnly(node, missing, missing, SHARE, route, SLOW, ballot, txnId, txn, executeAt, propose, (success, fail) -> {
+ if (fail != null) failureCallback.accept(null, fail);
+ else
+ {
+ success = success.intersecting(missing).asFullUnsafe();
+ withDeps.accept(success.with(committed));
+ }
+ });
+ }
+ }
+
+ public static void withStable(CoordinationAdapter<?> adapter, Node node, Merge merge, Deps alreadyStableDeps, Route<?> require, @Nullable Route<?> sendTo, @Nullable SelectNodeOwnership selectSendTo, FullRoute<?> route, Ballot ballot, TxnId txnId, Timestamp executeAt, Txn txn, BiConsumer<?, ? super Throwable> failureCallback, Consumer<Deps> withDeps)
+ {
+ Invariants.require(sendTo == null || selectSendTo != null);
+ if (!node.topology().hasEpoch(executeAt.epoch()))
+ {
+ node.withEpoch(executeAt.epoch(), failureCallback, () -> withStable(adapter, node, merge, alreadyStableDeps, require, sendTo, selectSendTo, route, ballot, txnId, executeAt, txn, failureCallback, withDeps));
+ return;
+ }
+
+ LatestDeps.MergedCommitResult mergedStable = merge.mergeCommitOrStable(null, DepsKnown);
+ Deps stable = mergedStable.deps.with(alreadyStableDeps);
+ Route<?> stabilise = require.without(mergedStable.sufficientFor);
+ if (stabilise.isEmpty()) withDeps.accept(stable);
+ else
+ {
+ LatestDeps.MergedCommitResult mergedCommitted = merge.mergeCommitOrStable(stabilise, DepsCommitted);
+ Route<?> propose = stabilise.without(mergedCommitted.sufficientFor);
+ // we merge with stable to make sure we can send a full Commit to any replica that overlaps the stable and unstable ranges
+ Deps committed = stable.with(mergedCommitted.deps);
+ if (propose.isEmpty())
{
- withDeps.accept(mergeDeps);
+ stabilise(adapter, node, committed, stabilise, sendTo, selectSendTo, route, ballot, txnId, executeAt, txn, failureCallback, withDeps);
}
else
{
- CollectLatestDeps.withLatestDeps(node, txnId, route, missing, executeAt, (extraDeps, fail) -> {
- if (fail != null)
- {
- failureCallback.accept(null, fail);
- }
+ // we merge with committed to make sure we can send a full Commit to any replica that overlaps the stable and unstable ranges
+ Deps notaccepted = committed.with(merge.mergeProposal(propose));
+ adapter.proposeOnly(node, propose, sendTo == null ? propose : sendTo, sendTo == null ? SHARE : selectSendTo, route, SLOW, ballot, txnId, txn, executeAt, notaccepted, (success, fail) -> {
+ if (fail != null) failureCallback.accept(null, fail);
else
{
- withDeps.accept(LatestDeps.mergeCommit(DepsUnknown, executeAt, extraDeps, executeAt, i -> i).deps.with(mergeDeps));
+ // TODO (desired): do we need to slice to those we were proposing, or can we just stabilise whatever we get back?
+ success = success.intersecting(propose).asFullUnsafe();
+ stabilise(adapter, node, success.with(committed), stabilise, sendTo, selectSendTo, route, ballot, txnId, executeAt, txn, failureCallback, withDeps);
}
});
}
+ }
+ }
+
+ public static void stabilise(CoordinationAdapter<?> adapter, Node node, Deps deps, Route<?> stabilise, @Nullable Route<?> sendTo, SelectNodeOwnership selectSendTo, FullRoute<?> route, Ballot ballot, TxnId txnId, Timestamp executeAt, Txn txn, BiConsumer<?, ? super Throwable> failureCallback, Consumer<Deps> withDeps)
+ {
+ Invariants.require(sendTo == null || selectSendTo != null);
+ adapter.stabiliseOnly(node, stabilise, sendTo == null ? stabilise : sendTo, sendTo == null ? SHARE : selectSendTo, route, ballot, txnId, txn, executeAt, deps, (success, fail) -> {
+ if (fail != null) failureCallback.accept(null, fail);
+ else withDeps.accept(deps);
});
}
+ public static void withStable(CoordinationAdapter<?> adapter, Node node, TxnId txnId, Timestamp executeAt, Txn txn, Deps alreadyStableDeps, Route<?> require, @Nullable Route<?> sendTo, SelectNodeOwnership selectSendTo, FullRoute<?> route, BiConsumer<?, ? super Throwable> failureCallback, Consumer<Deps> withDeps)
+ {
+ Invariants.require(sendTo == null || selectSendTo != null);
+ if (!node.topology().hasEpoch(executeAt.epoch()))
+ {
+ node.withEpoch(executeAt.epoch(), failureCallback, () -> withStable(adapter, node, txnId, executeAt, txn, alreadyStableDeps, require, sendTo, selectSendTo, route, failureCallback, withDeps));
+ }
+ else if (require.isEmpty())
+ {
+ withDeps.accept(alreadyStableDeps);
+ }
+ else
+ {
+ Ballot ballot = new Ballot(node.uniqueNow());
+ CollectLatestDeps.withLatestDeps(node, txnId, route, require, ballot, executeAt, (extraDeps, fail) -> {
+ if (fail != null)
+ {
+ failureCallback.accept(null, fail);
+ }
+ else
+ {
+ Merge merge = merge(extraDeps, i -> i);
+ LatestDeps.withStable(adapter, node, merge, alreadyStableDeps, require, sendTo, selectSendTo, route, ballot, txnId, executeAt, txn, failureCallback, withDeps);
+ }
+ });
+ }
+ }
+
public static class MergedCommitResult
{
public final Deps deps;
@@ -101,7 +185,7 @@ public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
public final Ballot ballot;
public final @Nullable Deps coordinatedDeps;
- private AbstractEntry(KnownDeps known, Ballot ballot, Deps coordinatedDeps)
+ private AbstractEntry(KnownDeps known, Ballot ballot, @Nullable Deps coordinatedDeps)
{
this.known = known;
this.ballot = ballot;
@@ -263,16 +347,7 @@ public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
return merge.mergeProposal();
}
- public static <T> MergedCommitResult mergeCommit(KnownDeps atLeast, Timestamp executeAt, List<T> list, Timestamp localDepsComputedUntil, Function<T, LatestDeps> getter)
- {
- Invariants.require(atLeast.compareTo(DepsCommitted) >= 0 || executeAt.compareTo(localDepsComputedUntil) <= 0);
- // merge merge merge
- Merge merge = merge(list, getter);
- return merge.mergeForCommitOrStable(atLeast == DepsProposedFixed ? test -> test.compareTo(DepsKnown) >= 0 || test == DepsProposedFixed
- : test -> test.compareTo(atLeast) >= 0);
- }
-
- private static <T> Merge merge(List<T> list, Function<T, LatestDeps> getter)
+ public static <T> Merge merge(List<T> list, Function<T, LatestDeps> getter)
{
Merge merge = Merge.EMPTY;
for (int i = 0, size = list.size() ; i < size ; ++i)
@@ -286,7 +361,7 @@ public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
}
// build a merge-intention without actually merging any deps, to save time merging ones we discover we don't need to
- private static class Merge extends ReducingRangeMap<Merge.MergeEntry>
+ public static class Merge extends ReducingRangeMap<Merge.MergeEntry>
{
private static final Merge EMPTY = new Merge();
@@ -347,34 +422,62 @@ public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
}
Deps mergeProposal()
+ {
+ return mergeProposal(null);
+ }
+
+ Deps mergeProposal(Participants<?> intersecting)
{
if (size() == 0)
return Deps.NONE;
- KeyDeps keyDeps = KeyDeps.merge(stream(Merge::forProposal, (d, r) -> d.keyDeps.slice(r)));
- KeyDeps directKeyDeps = KeyDeps.merge(stream(Merge::forProposal, (d, r) -> d.directKeyDeps.slice(r)));
- RangeDeps rangeDeps = RangeDeps.merge(stream(Merge::forProposal, (d, r) -> d.rangeDeps.slice(r)));
+ KeyDeps keyDeps = KeyDeps.merge(stream(intersecting, Merge::forProposal, (d, r) -> slice(d.keyDeps, r, intersecting)));
+ KeyDeps directKeyDeps = KeyDeps.merge(stream(intersecting, Merge::forProposal, (d, r) -> slice(d.directKeyDeps, r, intersecting)));
+ RangeDeps rangeDeps = RangeDeps.merge(stream(intersecting, Merge::forProposal, (d, r) -> slice(d.rangeDeps, r, intersecting)));
return new Deps(keyDeps, rangeDeps, directKeyDeps);
}
- MergedCommitResult mergeForCommitOrStable(Predicate<KnownDeps> atLeast)
+ MergedCommitResult mergeCommitOrStable(@Nullable Participants<?> intersecting, KnownDeps atLeast)
+ {
+ return mergeCommitOrStable(intersecting, atLeast == DepsProposedFixed ? test -> test.compareTo(DepsKnown) >= 0 || test == DepsProposedFixed
+ : test -> test.compareTo(atLeast) >= 0);
+ }
+
+ MergedCommitResult mergeCommitOrStable(@Nullable Participants<?> intersecting, Predicate<KnownDeps> atLeast)
{
if (size() == 0)
return new MergedCommitResult(Deps.NONE, Ranges.EMPTY);
SuccessCollector sufficientFor = new SuccessCollector(true);
- KeyDeps keyDeps = KeyDeps.merge(stream(forCommitOrStable(atLeast, sufficientFor), (d, r) -> d.keyDeps.slice(r)));
- KeyDeps directKeyDeps = KeyDeps.merge(stream(forCommitOrStable(atLeast, sufficientFor), (d, r) -> d.directKeyDeps.slice(r)));
- RangeDeps rangeDeps = RangeDeps.merge(stream(forCommitOrStable(atLeast, sufficientFor), (d, r) -> d.rangeDeps.slice(r)));
+ KeyDeps keyDeps = KeyDeps.merge(stream(intersecting, forCommitOrStable(atLeast, sufficientFor), (d, r) -> slice(d.keyDeps, r, intersecting)));
+ KeyDeps directKeyDeps = KeyDeps.merge(stream(intersecting, forCommitOrStable(atLeast, sufficientFor), (d, r) -> slice(d.directKeyDeps, r, intersecting)));
+ RangeDeps rangeDeps = RangeDeps.merge(stream(intersecting, forCommitOrStable(atLeast, sufficientFor), (d, r) -> slice(d.rangeDeps, r, intersecting)));
return new MergedCommitResult(new Deps(keyDeps, rangeDeps, directKeyDeps), Ranges.of(sufficientFor.toArray(new Range[0])));
}
- private <V> Stream<V> stream(TriFunction<Ranges, MergeEntry, BiFunction<Deps, Ranges, V>, Stream<V>> selector, BiFunction<Deps, Ranges, V> getter)
+ private static KeyDeps slice(KeyDeps keyDeps, Ranges ranges, @Nullable Participants<?> intersecting)
+ {
+ keyDeps = keyDeps.slice(ranges);
+ return intersecting == null ? keyDeps : keyDeps.intersecting(intersecting);
+ }
+
+ private static RangeDeps slice(RangeDeps rangeDeps, Ranges ranges, @Nullable Participants<?> intersecting)
+ {
+ rangeDeps = rangeDeps.slice(ranges);
+ return intersecting == null ? rangeDeps : rangeDeps.intersecting(intersecting);
+ }
+
+ private <V> Stream<V> stream(@Nullable Participants<?> intersecting, TriFunction<Ranges, MergeEntry, BiFunction<Deps, Ranges, V>, Stream<V>> selector, BiFunction<Deps, Ranges, V> getter)
{
RangeFactory rangeFactory = starts[0].rangeFactory();
return IntStream.range(0, size())
.filter(i -> values[i] != null)
- .mapToObj(i -> selector.apply(Ranges.of(rangeFactory.newRange(starts[i], starts[i+1])), values[i], getter))
+ .mapToObj(i -> {
+ Range range = rangeFactory.newRange(starts[i], starts[i+1]);
+ if (intersecting != null && !intersecting.intersects(range))
+ return Stream.<V>of();
+ return selector.apply(Ranges.of(range), values[i], getter);
+ })
.flatMap(v -> v);
}
@@ -386,7 +489,7 @@ public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
case DepsProposedFixed: case DepsProposed: return Stream.of(getter.apply(e.coordinatedDeps, slice));
case DepsUnknown: case DepsFromCoordinator: return e.merge.stream().map(d -> getter.apply(d, slice));
case DepsKnown: case DepsErased: case NoDeps: case DepsCommitted:
- throw new AssertionError("Invalid KnownDeps for proposal: " + e.known);
+ throw UnhandledEnum.invalid(e.known);
}
}
diff --git a/accord-core/src/main/java/accord/primitives/PartialDeps.java b/accord-core/src/main/java/accord/primitives/PartialDeps.java
index 33288fab..801f33b1 100644
--- a/accord-core/src/main/java/accord/primitives/PartialDeps.java
+++ b/accord-core/src/main/java/accord/primitives/PartialDeps.java
@@ -111,6 +111,11 @@ public class PartialDeps extends Deps
return new PartialDeps(this.covering.intersecting(participants, Minimal), keyDeps.intersecting(participants), rangeDeps.intersecting(participants), directKeyDeps.intersecting(participants));
}
+ public Deps asFullUnsafe()
+ {
+ return new Deps(keyDeps, rangeDeps, directKeyDeps);
+ }
+
public Deps reconstitute(FullRoute<?> route)
{
if (!covers(route.participants()))
diff --git a/accord-core/src/main/java/accord/primitives/PartialTxn.java b/accord-core/src/main/java/accord/primitives/PartialTxn.java
index 171c2365..f23cbbd6 100644
--- a/accord-core/src/main/java/accord/primitives/PartialTxn.java
+++ b/accord-core/src/main/java/accord/primitives/PartialTxn.java
@@ -22,8 +22,10 @@ import accord.api.Query;
import accord.api.Read;
import accord.api.Update;
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import static accord.primitives.Routables.Slice.Minimal;
import static accord.utils.Invariants.illegalState;
public interface PartialTxn extends Txn
@@ -40,7 +42,7 @@ public interface PartialTxn extends Txn
if (query() == null && route.contains(route.homeKey()))
return false;
- return keys().intersectsAll(route);
+ return keys().containsAll(route);
}
default boolean covers(Unseekables<?> participants)
@@ -48,7 +50,7 @@ public interface PartialTxn extends Txn
if (kind().isSystemTxn())
return true;
- return keys().intersectsAll(participants);
+ return keys().containsAll(participants);
}
static PartialTxn merge(@Nullable PartialTxn a, @Nullable PartialTxn b)
@@ -107,5 +109,27 @@ public interface PartialTxn extends Txn
return new PartialTxn.InMemory(kind(), keys(), read(), query(), update());
}
+
+ @Nonnull
+ @Override
+ public PartialTxn intersecting(Participants<?> participants, boolean includeQuery)
+ {
+ Seekables<?, ?> keys = keys();
+ Seekables<?, ?> intersecting = keys().intersecting(participants, Minimal);
+ if (intersecting == keys)
+ return this;
+
+ return new PartialTxn.InMemory(
+ kind(), intersecting,
+ read().intersecting(participants), includeQuery ? query() : null,
+ update() == null ? null : update().intersecting(participants)
+ );
+ }
+
+ @Override
+ public PartialTxn slice(Ranges ranges, boolean includeQuery)
+ {
+ return super.slice(ranges, includeQuery);
+ }
}
}
diff --git a/accord-core/src/main/java/accord/primitives/Range.java b/accord-core/src/main/java/accord/primitives/Range.java
index c16c0b14..e6a86879 100644
--- a/accord-core/src/main/java/accord/primitives/Range.java
+++ b/accord-core/src/main/java/accord/primitives/Range.java
@@ -229,6 +229,9 @@ public abstract class Range implements Comparable<RoutableKey>, Unseekable, Seek
@Override
public final Domain domain() { return Domain.Range; }
+ @Override
+ public final Kind kind() { return Kind.Range; }
+
public abstract boolean startInclusive();
public abstract boolean endInclusive();
@@ -310,6 +313,21 @@ public abstract class Range implements Comparable<RoutableKey>, Unseekable, Seek
return 0;
}
+ /**
+ * Returns a negative integer, zero, or a positive integer if both points of the provided range are less than,
+ * the range touches or intersects this range, or both points are greater than this range
+ */
+ public int compareTouching(Range that)
+ {
+ if (that.getClass() != this.getClass())
+ throw new IllegalArgumentException("Cannot mix Range of different types");
+ if (this.start.compareTo(that.end) > 0)
+ return 1;
+ if (this.end.compareTo(that.start) < 0)
+ return -1;
+ return 0;
+ }
+
/**
* Sorts by start then end
*/
@@ -434,7 +452,6 @@ public abstract class Range implements Comparable<RoutableKey>, Unseekable, Seek
return this;
}
-
@Override
public String toString()
{
diff --git a/accord-core/src/main/java/accord/primitives/RangeRoute.java b/accord-core/src/main/java/accord/primitives/RangeRoute.java
index 110ae0b3..abc8b8a7 100644
--- a/accord-core/src/main/java/accord/primitives/RangeRoute.java
+++ b/accord-core/src/main/java/accord/primitives/RangeRoute.java
@@ -91,15 +91,15 @@ public abstract class RangeRoute extends AbstractRanges implements Route<Range>,
}
@Override
- public PartialRangeRoute slice(Ranges ranges)
+ public RangeRoute slice(Ranges ranges)
{
return slice(ranges, Overlapping);
}
@Override
- public PartialRangeRoute slice(Ranges ranges, Slice slice)
+ public RangeRoute slice(Ranges ranges, Slice slice)
{
- return slice(ranges, slice, this, homeKey, (ignore, hk, rs) -> new PartialRangeRoute(hk, rs));
+ return slice(ranges, slice, this, homeKey, (self, hk, rs) -> self.ranges == rs ? this : new PartialRangeRoute(hk, rs));
}
@Override
diff --git a/accord-core/src/main/java/accord/primitives/Routable.java b/accord-core/src/main/java/accord/primitives/Routable.java
index 1072df68..34534f92 100644
--- a/accord-core/src/main/java/accord/primitives/Routable.java
+++ b/accord-core/src/main/java/accord/primitives/Routable.java
@@ -53,6 +53,40 @@ public interface Routable
}
}
+ enum Kind
+ {
+ SeekableKey('K'), UnseekableKey('U'), Range('R');
+
+ final char shortName;
+ private static final Domain[] VALUES = Domain.values();
+
+ Kind(char shortName)
+ {
+ this.shortName = shortName;
+ }
+
+ public boolean isKey()
+ {
+ return this != Range;
+ }
+
+ public boolean isRange()
+ {
+ return this == Range;
+ }
+
+ public static Routable.Domain ofOrdinal(int ordinal)
+ {
+ return VALUES[ordinal];
+ }
+
+ public char shortName()
+ {
+ return shortName;
+ }
+ }
+
+ Kind kind();
Domain domain();
Unseekable toUnseekable();
diff --git a/accord-core/src/main/java/accord/primitives/Routables.java b/accord-core/src/main/java/accord/primitives/Routables.java
index a9a0aaf1..33589fdf 100644
--- a/accord-core/src/main/java/accord/primitives/Routables.java
+++ b/accord-core/src/main/java/accord/primitives/Routables.java
@@ -18,6 +18,7 @@
package accord.primitives;
+import accord.api.Key;
import accord.api.RoutingKey;
import accord.primitives.Routable.Domain;
import accord.utils.*;
@@ -71,9 +72,32 @@ public interface Routables<K extends Routable> extends Iterable<K>
}
}
- boolean contains(RoutableKey key);
- boolean containsAll(Routables<?> keysOrRanges);
- boolean intersectsAll(Unseekables<?> keysOrRanges);
+ // note if one collection is Seekable and the other Unseekable, we compare contents as Unseekable
+ default boolean containsAll(Routables<?> keysOrRanges)
+ {
+ switch (keysOrRanges.domainKind())
+ {
+ default: throw new UnhandledEnum(keysOrRanges.domainKind());
+ case UnseekableKey: return containsAll((AbstractUnseekableKeys) keysOrRanges);
+ case SeekableKey: return containsAll((Keys) keysOrRanges);
+ case Range: return containsAll((AbstractRanges) keysOrRanges);
+ }
+ }
+
+ default boolean containsAll(Unseekables<?> keysOrRanges)
+ {
+ switch (keysOrRanges.domain())
+ {
+ default: throw new UnhandledEnum(keysOrRanges.domainKind());
+ case Key: return containsAll((AbstractUnseekableKeys) keysOrRanges);
+ case Range: return containsAll((AbstractRanges) keysOrRanges);
+ }
+ }
+
+ boolean containsAll(AbstractUnseekableKeys keys);
+ boolean containsAll(Keys keys);
+ boolean containsAll(AbstractRanges ranges);
+ default boolean containsAll(Ranges ranges) { return containsAll((AbstractRanges) ranges); }
Routables<K> slice(int from, int to);
Routables<K> slice(Ranges ranges);
@@ -98,7 +122,7 @@ public interface Routables<K extends Routable> extends Iterable<K>
* that intersect with each other. Return their position packed in a long, with low bits representing
* the resultant {@code thisIndex} and high bits {@code withIndex}.
*/
- long findNextIntersection(int thisIndex, AbstractKeys<?> with, int withIndex);
+ long findNextIntersection(int thisIndex, Keys with, int withIndex);
/**
* Search forwards from {code thisIndex} and {@code withIndex} to find the first entries in each collection
@@ -112,42 +136,57 @@ public interface Routables<K extends Routable> extends Iterable<K>
* that intersect with each other. Return their position packed in a long, with low bits representing
* the resultant {@code thisIndex} and high bits {@code withIndex}.
*/
- long findNextIntersection(int thisIndex, Routables<K> with, int withIndex);
+ default long findNextIntersection(int thisIndex, Routables<K> with, int withIndex)
+ {
+ switch (with.domainKind())
+ {
+ default: throw new UnhandledEnum(with.domainKind());
+ case UnseekableKey: return findNextIntersection(thisIndex, (AbstractUnseekableKeys) with, withIndex);
+ case SeekableKey: return findNextIntersection(thisIndex, (Keys) with, withIndex);
+ case Range: return findNextIntersection(thisIndex, (AbstractRanges) with, withIndex);
+ }
+ }
+
+ /**
+ * Search forwards from {code thisIndex} and {@code withIndex} to find the first entries in each collection
+ * that intersect with each other. Return their position packed in a long, with low bits representing
+ * the resultant {@code thisIndex} and high bits {@code withIndex}.
+ */
+ long findNextSameKindIntersection(int thisIndex, Routables<K> with, int withIndex);
+
+ // if this collection contains Seekables, this indicates if there exists a where .toUnseekable() == key
+ boolean contains(RoutingKey key);
+
+ // if this collection contains Unseekables, this indicates if there exists a Key where .toUnseekable() == key
+ boolean contains(Key key);
/**
* Perform {@link SortedArrays#binarySearch} looking for {@code find} with behaviour of {@code search}
*/
- int find(Range find, SortedArrays.Search search);
+ int find(RoutingKey find, SortedArrays.Search search);
/**
* Perform {@link SortedArrays#exponentialSearch} from {@code thisIndex} looking for {@code find} with behaviour of {@code search}
*/
- int findNext(int thisIndex, Range find, SortedArrays.Search search);
+ int findNext(int thisIndex, RoutingKey find, SortedArrays.Search search);
/**
- * Perform {@link SortedArrays#binarySearch} looking for {@code find} with behaviour of {@code search}
+ * Perform {@link SortedArrays#exponentialSearch} from {@code thisIndex} looking for {@code find} with behaviour of {@code search}
*/
- int find(RoutableKey find, SortedArrays.Search search);
+ int findNext(int thisIndex, K find, SortedArrays.Search search);
/**
- * Perform {@link SortedArrays#exponentialSearch} from {@code thisIndex} looking for {@code find} with behaviour of {@code search}
+ * Perform {@link SortedArrays#binarySearch} looking for {@code find} with behaviour of {@code search}
*/
- int findNext(int thisIndex, RoutableKey find, SortedArrays.Search search);
+ int find(Range find, SortedArrays.Search search);
/**
* Perform {@link SortedArrays#exponentialSearch} from {@code thisIndex} looking for {@code find} with behaviour of {@code search}
*/
- default int findNext(int thisIndex, Routable find, SortedArrays.Search search)
- {
- switch (find.domain())
- {
- default: throw new AssertionError("Unhandled domain: " + find.domain());
- case Key: return findNext(thisIndex, (RoutableKey) find, search);
- case Range: return findNext(thisIndex, (Range) find, search);
- }
- }
+ int findNext(int thisIndex, Range find, SortedArrays.Search search);
Domain domain();
+ Routable.Kind domainKind();
/**
* Fold-left over the {@code inputs} that intersect with {@code matching} in ascending order.
@@ -186,44 +225,24 @@ public interface Routables<K extends Routable> extends Iterable<K>
* Terminate once we hit {@code terminalValue}.
*/
@Inline
- static <T> T foldl(AbstractRanges inputs, Routables<?> matching, IndexedFold<? super Range, T> fold, T initialValue)
- {
- switch (matching.domain())
- {
- default: throw new AssertionError();
- case Key: return Helper.foldl(AbstractRanges::findNextIntersection, Helper::findLimit, inputs, (AbstractKeys<?>)matching, fold, initialValue);
- case Range: return Helper.foldl(AbstractRanges::findNextIntersection, Helper::findLimit, inputs, (AbstractRanges)matching, fold, initialValue);
- }
- }
-
- /**
- * Fold-left over the {@code inputs} that intersect with {@code matching} in ascending order.
- * Terminate once we hit {@code terminalValue}.
- */
- @Inline
- static <Input extends RoutableKey, T> T foldl(AbstractKeys<Input> inputs, Routables<?> matching, IndexedFold<? super Input, T> fold, T initialValue)
+ static <T> T foldl(AbstractUnseekableKeys inputs, Unseekables<?> matching, IndexedFold<? super RoutingKey, T> fold, T initialValue)
{
switch (matching.domain())
{
default: throw new AssertionError();
- case Key: return Helper.foldl(AbstractKeys::findNextIntersection, Helper::findLimit, inputs, (AbstractKeys<?>)matching, fold, initialValue);
- case Range: return Helper.foldl(AbstractKeys::findNextIntersection, Helper::findLimit, inputs, (AbstractRanges)matching, fold, initialValue);
+ case Key: return Helper.foldl(AbstractUnseekableKeys::findNextSameKindIntersection, Helper::findLimit, inputs, (AbstractUnseekableKeys)matching, fold, initialValue);
+ case Range: return Helper.foldl(AbstractUnseekableKeys::findNextIntersection, Helper::findLimit, inputs, (AbstractRanges)matching, fold, initialValue);
}
}
@Inline
- static <P1, P2, Input extends RoutableKey, T> T foldl(AbstractKeys<Input> inputs, Routables<?> matching, IndexedTriFold<P1, P2, ? super Input, T> fold, P1 p1, P2 p2, T initialValue, Predicate<T> terminate)
+ static <P1, P2, Input extends RoutableKey, T> T foldl(AbstractKeys<Input> inputs, AbstractRanges matching, IndexedTriFold<P1, P2, ? super Input, T> fold, P1 p1, P2 p2, T initialValue, Predicate<T> terminate)
{
- switch (matching.domain())
- {
- default: throw new AssertionError();
- case Key: return Helper.foldl(AbstractKeys::findNextIntersection, Helper::findLimit, inputs, (AbstractKeys<?>)matching, fold, p1, p2, initialValue, terminate);
- case Range: return Helper.foldl(AbstractKeys::findNextIntersection, Helper::findLimit, inputs, (AbstractRanges)matching, fold, p1, p2, initialValue, terminate);
- }
+ return Helper.foldl(Routables::findNextIntersection, Helper::findLimit, inputs, matching, fold, p1, p2, initialValue, terminate);
}
@Inline
- static <P1, P2, Input extends RoutableKey, T> T foldl(AbstractKeys<Input> inputs, AbstractRanges matching, IndexedTriFold<P1, P2, ? super Input, T> fold, P1 p1, P2 p2, T initialValue, Predicate<T> terminate)
+ static <P1, P2, Input extends RoutableKey, T> T foldl(AbstractKeys<Input> inputs, AbstractKeys<Input> matching, IndexedTriFold<P1, P2, ? super Input, T> fold, P1 p1, P2 p2, T initialValue, Predicate<T> terminate)
{
return Helper.foldl(Routables::findNextIntersection, Helper::findLimit, inputs, matching, fold, p1, p2, initialValue, terminate);
}
@@ -240,25 +259,10 @@ public interface Routables<K extends Routable> extends Iterable<K>
return Helper.foldl(AbstractKeys::findNextIntersection, Helper::findLimit, inputs, matching, fold, param, initialValue, terminalValue);
}
- /**
- * Fold-left over the {@code inputs} that intersect with {@code matching} in ascending order.
- * Terminate once we hit {@code terminalValue}.
- */
@Inline
- static <Input extends Routable> long foldl(Routables<Input> inputs, AbstractRanges matching, IndexedFoldToLong<? super Input> fold, long param, long initialValue, long terminalValue)
+ static <Input extends RoutableKey> long foldl(AbstractKeys<Input> inputs, AbstractKeys<Input> matching, IndexedFoldToLong<? super Input> fold, long param, long initialValue, long terminalValue)
{
- return Helper.foldl(Routables::findNextIntersection, Helper::findLimit, inputs, matching, fold, param, initialValue, terminalValue);
- }
-
- /**
- * Fold-left over the {@code inputs} that intersect with {@code matching} in ascending order.
- * Terminate once we hit {@code terminalValue}.
- */
- @Inline
- static <Input extends Routable> long foldl(Routables<Input> inputs, AbstractKeys<?> matching, IndexedFoldToLong<? super Input> fold, long param, long initialValue, long terminalValue)
- {
- return Helper.foldl(Routables::findNextIntersection, (ls, li, rs, ri) -> li + 1,
- inputs, matching, fold, param, initialValue, terminalValue);
+ return Helper.foldl(AbstractKeys::findNextIntersection, Helper::findLimit, inputs, matching, fold, param, initialValue, terminalValue);
}
/**
@@ -266,10 +270,9 @@ public interface Routables<K extends Routable> extends Iterable<K>
* Terminate once we hit {@code terminalValue}.
*/
@Inline
- static <Input extends RoutingKey, Matching extends Routable> long foldl(AbstractKeys<Input> inputs, Routables<Matching> matching, IndexedFoldToLong<? super Input> fold, long param, long initialValue, long terminalValue)
+ static <Input extends Routable> long foldl(Routables<Input> inputs, AbstractRanges matching, IndexedFoldToLong<? super Input> fold, long param, long initialValue, long terminalValue)
{
- return Helper.foldl((ls, li, rs, ri) -> SortedArrays.swapHighLow32b(rs.findNextIntersection(ri, ls, li)), (ls, li, rs, ri) -> li + 1,
- inputs, matching, fold, param, initialValue, terminalValue);
+ return Helper.foldl(Routables::findNextIntersection, Helper::findLimit, inputs, matching, fold, param, initialValue, terminalValue);
}
/**
@@ -283,17 +286,6 @@ public interface Routables<K extends Routable> extends Iterable<K>
inputs, matching, fold, param, initialValue, terminalValue);
}
- /**
- * Fold-left over the {@code inputs} that intersect with {@code matching} in ascending order, passing the contiguous ranges that intersect to the IndexedRangeFold function.
- * Terminate once we hit {@code terminalValue}.
- */
- @Inline
- static <Input extends Routable> long rangeFoldl(Routables<Input> inputs, AbstractKeys<?> matching, IndexedRangeFoldToLong fold, long param, long initialValue, long terminalValue)
- {
- return Helper.rangeFoldl(Routables::findNextIntersection, (ls, li, rs, ri) -> li + 1,
- inputs, matching, fold, param, initialValue, terminalValue);
- }
-
class Helper
{
interface SetIntersections<L extends Routables<?>, R extends Routables<?>>
@@ -450,9 +442,9 @@ public interface Routables<K extends Routable> extends Iterable<K>
return nextl;
}
- static int findLimit(AbstractRanges ls, int li, AbstractKeys<?> rs, int ri)
+ static int findLimit(AbstractUnseekableKeys ls, int li, AbstractUnseekableKeys rs, int ri)
{
- RoutableKey r = rs.get(ri);
+ RoutingKey r = rs.get(ri);
int nextl = ls.findNext(li + 1, r, FLOOR);
if (nextl < 0) nextl = -1 - nextl;
@@ -460,9 +452,9 @@ public interface Routables<K extends Routable> extends Iterable<K>
return nextl;
}
- static int findLimit(AbstractKeys<?> ls, int li, AbstractKeys<?> rs, int ri)
+ static <K extends RoutableKey> int findLimit(AbstractKeys<K> ls, int li, AbstractKeys<K> rs, int ri)
{
- RoutableKey r = rs.get(ri);
+ K r = rs.get(ri);
int nextl = ls.findNext(li + 1, r, FLOOR);
if (nextl < 0) nextl = -1 - nextl;
diff --git a/accord-core/src/main/java/accord/primitives/Unseekables.java b/accord-core/src/main/java/accord/primitives/Unseekables.java
index fcd65bd0..61827f74 100644
--- a/accord-core/src/main/java/accord/primitives/Unseekables.java
+++ b/accord-core/src/main/java/accord/primitives/Unseekables.java
@@ -19,6 +19,8 @@
package accord.primitives;
import accord.api.RoutingKey;
+import accord.utils.SortedArrays;
+import accord.utils.UnhandledEnum;
/**
* Either a Route or a simple collection of keys or ranges
@@ -40,6 +42,20 @@ public interface Unseekables<K extends Unseekable> extends Iterable<K>, Routable
}
}
+ /**
+ * Perform {@link SortedArrays#exponentialSearch} from {@code thisIndex} looking for {@code find} with behaviour of {@code search}
+ */
+ default int findNext(int thisIndex, Unseekable find, SortedArrays.Search search)
+ {
+ switch (find.domain())
+ {
+ default: throw new AssertionError("Unhandled domain: " + find.domain());
+ case Key: return findNext(thisIndex, (RoutingKey) find, search);
+ case Range: return findNext(thisIndex, (Range) find, search);
+ }
+ }
+
+
@Override
Unseekables<K> slice(int from, int to);
@Override
@@ -66,6 +82,21 @@ public interface Unseekables<K extends Unseekable> extends Iterable<K>, Routable
Unseekables<K> with(RoutingKey withKey);
UnseekablesKind kind();
+ /**
+ * Search forwards from {code thisIndex} and {@code withIndex} to find the first entries in each collection
+ * that intersect with each other. Return their position packed in a long, with low bits representing
+ * the resultant {@code thisIndex} and high bits {@code withIndex}.
+ */
+ default long findNextIntersection(int thisIndex, Unseekables<K> with, int withIndex)
+ {
+ switch (with.domain())
+ {
+ default: throw new UnhandledEnum(with.domainKind());
+ case Key: return findNextIntersection(thisIndex, (AbstractUnseekableKeys) with, withIndex);
+ case Range: return findNextIntersection(thisIndex, (AbstractRanges) with, withIndex);
+ }
+ }
+
/**
* If both left and right are a Route, invoke {@link Route#with} on them. Otherwise invoke {@link #with}.
*/
diff --git a/accord-core/src/main/java/accord/topology/Topologies.java b/accord-core/src/main/java/accord/topology/Topologies.java
index aa29ca62..b5bc7ef5 100644
--- a/accord-core/src/main/java/accord/topology/Topologies.java
+++ b/accord-core/src/main/java/accord/topology/Topologies.java
@@ -39,6 +39,20 @@ import static accord.utils.SortedArrays.isSortedUnique;
// (e.g. at least implementing Topologies by Topology)
public interface Topologies extends TopologySorter
{
+ enum SelectNodeOwnership
+ {
+ /**
+ * Slice node ownership information to cover only those ranges we have queried.
+ */
+ SLICE,
+
+ /**
+ * Use the node information from the topology we are selecting from. This means nodes may report
+ * ranges that do not intersect the ranges we are selecting.
+ */
+ SHARE
+ }
+
Topology current();
default boolean containsEpoch(long epoch) { return epoch >= oldestEpoch() && epoch <= currentEpoch(); }
@@ -83,9 +97,9 @@ public interface Topologies extends TopologySorter
int maxShardsPerEpoch();
- Topologies selectSince(Participants<?> participants, long sinceEpoch);
+ Topologies selectSince(Participants<?> participants, long sinceEpoch, SelectNodeOwnership selectNodeOwnership);
- Topologies selectEpoch(Participants<?> participants, long epoch);
+ Topologies selectEpoch(Participants<?> participants, long epoch, SelectNodeOwnership selectNodeOwnership);
default void forEach(IndexedConsumer<Topology> consumer)
{
@@ -206,18 +220,18 @@ public interface Topologies extends TopologySorter
}
@Override
- public Topologies selectSince(Participants<?> participants, long sinceEpoch)
+ public Topologies selectSince(Participants<?> participants, long sinceEpoch, SelectNodeOwnership selectNodeOwnership)
{
Invariants.require(sinceEpoch <= currentEpoch());
- Topology subset = topology.select(participants);
+ Topology subset = topology.select(participants, selectNodeOwnership);
return subset == topology ? this : new Single(sorter, subset);
}
@Override
- public Topologies selectEpoch(Participants<?> participants, long epoch)
+ public Topologies selectEpoch(Participants<?> participants, long epoch, SelectNodeOwnership selectNodeOwnership)
{
Invariants.require(epoch == currentEpoch());
- Topology subset = topology.select(participants);
+ Topology subset = topology.select(participants, selectNodeOwnership);
return subset == topology ? this : new Single(sorter, subset);
}
@@ -479,7 +493,7 @@ public interface Topologies extends TopologySorter
}
@Override
- public Topologies selectSince(Participants<?> participants, long sinceEpoch)
+ public Topologies selectSince(Participants<?> participants, long sinceEpoch, SelectNodeOwnership selectNodeOwnership)
{
Topology[] subsets = null;
int limit = topologies.length;
@@ -488,7 +502,7 @@ public interface Topologies extends TopologySorter
for (int i = 0 ; i < limit ; ++i)
{
Topology superset = topologies[i];
- Topology subset = superset.select(participants);
+ Topology subset = superset.select(participants, selectNodeOwnership);
if (subset != superset && subsets == null)
{
subsets = new Topology[limit];
@@ -510,13 +524,13 @@ public interface Topologies extends TopologySorter
}
@Override
- public Topologies selectEpoch(Participants<?> participants, long epoch)
+ public Topologies selectEpoch(Participants<?> participants, long epoch, SelectNodeOwnership selectNodeOwnership)
{
if (!containsEpoch(epoch))
throw new IndexOutOfBoundsException();
Topology superset = getEpoch(epoch);
- Topology subset = superset.select(participants);
+ Topology subset = superset.select(participants, selectNodeOwnership);
return new Single(sorter, subset);
}
}
diff --git a/accord-core/src/main/java/accord/topology/Topology.java b/accord-core/src/main/java/accord/topology/Topology.java
index 6ebe6b60..839656c2 100644
--- a/accord-core/src/main/java/accord/topology/Topology.java
+++ b/accord-core/src/main/java/accord/topology/Topology.java
@@ -21,7 +21,6 @@ package accord.topology;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -41,6 +40,7 @@ import accord.primitives.Ranges;
import accord.primitives.RoutableKey;
import accord.primitives.Routables;
import accord.primitives.Unseekables;
+import accord.topology.Topologies.SelectNodeOwnership;
import accord.utils.ArrayBuffers;
import accord.utils.ArrayBuffers.IntBuffers;
import accord.utils.IndexedBiFunction;
@@ -54,6 +54,7 @@ import accord.utils.Utils;
import org.agrona.collections.Int2ObjectHashMap;
import org.agrona.collections.IntArrayList;
+import static accord.topology.Topologies.SelectNodeOwnership.SLICE;
import static accord.utils.Invariants.illegalArgument;
import static accord.utils.SortedArrays.Search.FLOOR;
import static accord.utils.SortedArrays.exponentialSearch;
@@ -269,36 +270,31 @@ public class Topology
return subsetOfRanges.indexOf(range, search);
}
- @VisibleForTesting
- public Topology withEmptySubset()
- {
- return forSubset(EMPTY_SUBSET);
- }
-
- public Topology select(Routables<?> select)
+ public Topology select(Routables<?> select, SelectNodeOwnership selectNodeOwnership)
{
- return select(select, false);
+ return select(select, false, selectNodeOwnership);
}
- public Topology selectIfExists(Routables<?> select)
+ public Topology selectIfExists(Routables<?> select, SelectNodeOwnership selectNodeOwnership)
{
- return select(select, true);
+ return select(select, true, selectNodeOwnership);
}
- public Topology select(Routables<?> select, boolean permitMissing)
+ public Topology select(Routables<?> select, boolean permitMissing, SelectNodeOwnership selectNodeOwnership)
{
- return forSubset(subsetFor(select, permitMissing));
+ return forSubset(subsetFor(select, permitMissing), selectNodeOwnership);
}
@VisibleForTesting
- Topology forSubset(int[] newSubset)
+ Topology forSubset(int[] newSubset, SelectNodeOwnership selectNodeOwnership)
{
Ranges rangeSubset = ranges.select(newSubset);
if (rangeSubset == ranges)
return this;
+ boolean reselectNodeOwnership = selectNodeOwnership == SLICE;
SimpleBitSet nodes = new SimpleBitSet(nodeIds.size());
- Int2ObjectHashMap<NodeInfo> nodeLookup = new Int2ObjectHashMap<>(nodes.size(), 0.8f);
+ Int2ObjectHashMap<NodeInfo> nodeLookup = reselectNodeOwnership ? new Int2ObjectHashMap<>(nodes.size(), 0.8f) : this.nodeLookup;
for (int shardIndex : newSubset)
{
Shard shard = shards[shardIndex];
@@ -308,33 +304,16 @@ public class Topology
i = nodeIds.findNext(i, id);
if (i >= 0) nodes.set(i++);
else i = -1 - i;
- // TODO (expected): do we need to shrink to the subset? I don't think we do anymore, and if not we can avoid copying the nodeLookup entirely
- nodeLookup.putIfAbsent(id.id, this.nodeLookup.get(id.id).forSubset(newSubset));
+ if (reselectNodeOwnership)
+ nodeLookup.putIfAbsent(id.id, this.nodeLookup.get(id.id).forSubset(newSubset));
}
}
+
Id[] nodeIds = new Id[nodes.getSetBitCount()];
int count = 0;
for (int i = nodes.firstSetBit() ; i >= 0 ; i = nodes.nextSetBit(i + 1, -1))
nodeIds[count++] = this.nodeIds.get(i);
- return new Topology(global(), epoch, shards, ranges, staleNodes, new SortedArrayList<>(nodeIds), nodeLookup, rangeSubset, newSubset);
- }
- @VisibleForTesting
- Topology forSubset(int[] newSubset, Collection<Id> nodes)
- {
- Ranges rangeSubset = ranges.select(newSubset);
- Id[] nodeIds = new Id[nodes.size()];
- Int2ObjectHashMap<NodeInfo> nodeLookup = new Int2ObjectHashMap<>(nodes.size(), 0.8f);
- for (Id id : nodes)
- {
- NodeInfo info = this.nodeLookup.get(id.id).forSubset(newSubset);
- if (info.ranges.isEmpty()) continue;
- nodeIds[nodeLookup.size()] = id;
- nodeLookup.put(id.id, info);
- }
- if (nodeLookup.size() != nodeIds.length)
- nodeIds = Arrays.copyOf(nodeIds, nodeLookup.size());
- Arrays.sort(nodeIds);
return new Topology(global(), epoch, shards, ranges, staleNodes, new SortedArrayList<>(nodeIds), nodeLookup, rangeSubset, newSubset);
}
diff --git a/accord-core/src/main/java/accord/topology/TopologyManager.java b/accord-core/src/main/java/accord/topology/TopologyManager.java
index d7b3a1be..999b6ee4 100644
--- a/accord-core/src/main/java/accord/topology/TopologyManager.java
+++ b/accord-core/src/main/java/accord/topology/TopologyManager.java
@@ -54,6 +54,7 @@ import accord.primitives.Routables;
import accord.primitives.Timestamp;
import accord.primitives.TxnId.FastPath;
import accord.primitives.Unseekables;
+import accord.topology.Topologies.SelectNodeOwnership;
import accord.topology.Topologies.Single;
import accord.utils.IndexedBiFunction;
import accord.utils.Invariants;
@@ -528,7 +529,8 @@ public class TopologyManager
}
private final TopologySorter.Supplier sorter;
- private final TopologiesCollectors topologiesCollectors;
+ private final TopologiesCollectors collector;
+ private final TopologiesCollectors selectNodeOwnershipCollector;
private final BestFastPath bestFastPath;
private final SupportsPrivilegedFastPath supportsPrivilegedFastPath;
private final Agent agent;
@@ -543,7 +545,8 @@ public class TopologyManager
public TopologyManager(TopologySorter.Supplier sorter, Agent agent, Id self, Scheduler scheduler, TimeService time, LocalConfig localConfig)
{
this.sorter = sorter;
- this.topologiesCollectors = new TopologiesCollectors(sorter);
+ this.collector = new TopologiesCollectors(sorter, SelectNodeOwnership.SHARE);
+ this.selectNodeOwnershipCollector = new TopologiesCollectors(sorter, SelectNodeOwnership.SLICE);
this.bestFastPath = new BestFastPath(self);
this.supportsPrivilegedFastPath = new SupportsPrivilegedFastPath(self);
this.agent = agent;
@@ -768,35 +771,35 @@ public class TopologyManager
return withUnsyncedEpochs(select, min.epoch(), max.epoch());
}
- public Topologies select(Unseekables<?> select, Timestamp min, Timestamp max, Include include)
+ public Topologies select(Unseekables<?> select, Timestamp min, Timestamp max, SelectNodeOwnership selectNodeOwnership, Include include)
{
- return select(select, min.epoch(), max.epoch(), include);
+ return select(select, min.epoch(), max.epoch(), selectNodeOwnership, include);
}
- public Topologies select(Unseekables<?> select, long minEpoch, long maxEpoch, Include include)
+ public Topologies select(Unseekables<?> select, long minEpoch, long maxEpoch, SelectNodeOwnership selectNodeOwnership, Include include)
{
switch (include)
{
default: throw new AssertionError("Unhandled Include: " +include);
case Unsynced: return withUnsyncedEpochs(select, minEpoch, maxEpoch);
- case Owned: return preciseEpochs(select, minEpoch, maxEpoch);
+ case Owned: return preciseEpochs(select, minEpoch, maxEpoch, selectNodeOwnership);
}
}
- public Topologies reselect(@Nullable Topologies prev, @Nullable Include prevIncluded, Unseekables<?> select, Timestamp min, Timestamp max, Include include)
+ public Topologies reselect(@Nullable Topologies prev, @Nullable Include prevIncluded, Unseekables<?> select, Timestamp min, Timestamp max, SelectNodeOwnership selectNodeOwnership, Include include)
{
- return reselect(prev, prevIncluded, select, min.epoch(), max.epoch(), include);
+ return reselect(prev, prevIncluded, select, min.epoch(), max.epoch(), selectNodeOwnership, include);
}
// prevIncluded may be null even when prev is not null, in cases where we do not know what prev was produced with
- public Topologies reselect(@Nullable Topologies prev, @Nullable Include prevIncluded, Unseekables<?> select, long minEpoch, long maxEpoch, Include include)
+ public Topologies reselect(@Nullable Topologies prev, @Nullable Include prevIncluded, Unseekables<?> select, long minEpoch, long maxEpoch, SelectNodeOwnership selectNodeOwnership, Include include)
{
if (include == Owned)
{
if (prev != null && prev.currentEpoch() >= maxEpoch && prev.oldestEpoch() <= minEpoch)
return prev.forEpochs(minEpoch, maxEpoch);
else
- return preciseEpochs(select, minEpoch, maxEpoch);
+ return preciseEpochs(select, minEpoch, maxEpoch, selectNodeOwnership);
}
else
{
@@ -847,7 +850,7 @@ public class TopologyManager
private Topologies withSufficientEpochsAtLeast(Unseekables<?> select, long minEpoch, long maxEpoch, Function<EpochState, Ranges> isSufficientFor)
{
- return atLeast(select, minEpoch, maxEpoch, isSufficientFor, topologiesCollectors);
+ return atLeast(select, minEpoch, maxEpoch, isSufficientFor, collector);
}
@@ -919,7 +922,7 @@ public class TopologyManager
private Topologies withSufficientEpochsAtMost(Routables<?> select, long minEpoch, long maxEpoch, BiFunction<EpochState, EpochState, Ranges> isSufficientFor)
{
- return atMost(select, minEpoch, maxEpoch, isSufficientFor, topologiesCollectors);
+ return atMost(select, minEpoch, maxEpoch, isSufficientFor, collector);
}
private <C, K extends Routables<?>, T> T atMost(K select, long minEpoch, long maxEpoch, BiFunction<EpochState, EpochState, Ranges> isSufficientFor,
@@ -1007,31 +1010,36 @@ public class TopologyManager
return maxEpoch;
}
- public Topologies preciseEpochs(Unseekables<?> select, long minEpoch, long maxEpoch)
+ public Topologies preciseEpochs(Unseekables<?> select, long minEpoch, long maxEpoch, SelectNodeOwnership selectNodeOwnership)
{
- return preciseEpochs(select, minEpoch, maxEpoch, Topology::select);
+ return preciseEpochs(select, minEpoch, maxEpoch, selectNodeOwnership, Topology::select);
}
- public Topologies preciseEpochsIfExists(Unseekables<?> select, long minEpoch, long maxEpoch)
+ public Topologies preciseEpochsIfExists(Unseekables<?> select, long minEpoch, long maxEpoch, SelectNodeOwnership selectNodeOwnership)
{
- return preciseEpochs(select, minEpoch, maxEpoch, Topology::selectIfExists);
+ return preciseEpochs(select, minEpoch, maxEpoch, selectNodeOwnership, Topology::selectIfExists);
}
- public Topologies preciseEpochs(Unseekables<?> select, long minEpoch, long maxEpoch, BiFunction<Topology, Unseekables<?>, Topology> selectFunction)
+ public interface SelectFunction
+ {
+ Topology apply(Topology topology, Unseekables<?> select, SelectNodeOwnership selectNodeOwnership);
+ }
+
+ public Topologies preciseEpochs(Unseekables<?> select, long minEpoch, long maxEpoch, SelectNodeOwnership selectNodeOwnership, SelectFunction selectFunction)
{
Epochs snapshot = epochs;
EpochState maxState = snapshot.get(maxEpoch);
Invariants.require(maxState != null, "Unable to find epoch %d; known epochs are %d -> %d", maxEpoch, snapshot.minEpoch(), snapshot.currentEpoch);
if (minEpoch == maxEpoch)
- return new Single(sorter, selectFunction.apply(snapshot.get(minEpoch).global, select));
+ return new Single(sorter, selectFunction.apply(snapshot.get(minEpoch).global, select, selectNodeOwnership));
int count = (int)(1 + maxEpoch - minEpoch);
Topologies.Builder topologies = new Topologies.Builder(count);
for (int i = count - 1 ; i >= 0 ; --i)
{
EpochState epochState = snapshot.get(minEpoch + i);
- topologies.add(selectFunction.apply(epochState.global, select));
+ topologies.add(selectFunction.apply(epochState.global, select, selectNodeOwnership));
select = select.without(epochState.addedRanges);
}
Invariants.require(!topologies.isEmpty(), "Unable to find an epoch that contained %s", select);
@@ -1039,10 +1047,10 @@ public class TopologyManager
return topologies.build(sorter);
}
- public Topologies forEpoch(Unseekables<?> select, long epoch)
+ public Topologies forEpoch(Unseekables<?> select, long epoch, SelectNodeOwnership selectNodeOwnership)
{
EpochState state = epochs.get(epoch);
- return new Single(sorter, state.global.select(select));
+ return new Single(sorter, state.global.select(select, selectNodeOwnership));
}
public Shard forEpochIfKnown(RoutableKey key, long epoch)
@@ -1112,23 +1120,25 @@ public class TopologyManager
static class TopologiesCollectors implements Collectors<Topologies.Builder, Routables<?>, Topologies>
{
final TopologySorter.Supplier sorter;
+ final SelectNodeOwnership selectNodeOwnership;
- TopologiesCollectors(TopologySorter.Supplier sorter)
+ TopologiesCollectors(TopologySorter.Supplier sorter, SelectNodeOwnership selectNodeOwnership)
{
this.sorter = sorter;
+ this.selectNodeOwnership = selectNodeOwnership;
}
@Override
public Topologies.Builder update(Topologies.Builder collector, EpochState epoch, Routables<?> select, boolean permitMissing)
{
- collector.add(epoch.global.select(select, permitMissing));
+ collector.add(epoch.global.select(select, permitMissing, selectNodeOwnership));
return collector;
}
@Override
public Topologies one(EpochState epoch, Routables<?> unseekables, boolean permitMissing)
{
- return new Topologies.Single(sorter, epoch.global.select(unseekables, permitMissing));
+ return new Topologies.Single(sorter, epoch.global.select(unseekables, permitMissing, selectNodeOwnership));
}
@Override
diff --git a/accord-core/src/main/java/accord/utils/SortedArrays.java b/accord-core/src/main/java/accord/utils/SortedArrays.java
index 244ca669..098ffc05 100644
--- a/accord-core/src/main/java/accord/utils/SortedArrays.java
+++ b/accord-core/src/main/java/accord/utils/SortedArrays.java
@@ -1426,6 +1426,12 @@ public class SortedArrays
@Inline
public static <T> long foldlIntersection(AsymmetricComparator<? super T, ? super T> comparator, T[] as, int ai, int alim, T[] bs, int bi, int blim, IndexedFoldIntersectToLong<? super T> fold, long param, long initialValue, long terminalValue)
+ {
+ return foldlIntersection(1, comparator, as, ai, alim, bs, bi, blim, fold, param, initialValue, terminalValue);
+ }
+
+ @Inline
+ public static <T> long foldlIntersection(int aiMatchIncrement, AsymmetricComparator<? super T, ? super T> comparator, T[] as, int ai, int alim, T[] bs, int bi, int blim, IndexedFoldIntersectToLong<? super T> fold, long param, long initialValue, long terminalValue)
{
while (true)
{
@@ -1440,7 +1446,7 @@ public class SortedArrays
if (initialValue == terminalValue)
break;
- ++ai;
+ ai += aiMatchIncrement;
++bi;
}
diff --git a/accord-core/src/main/java/accord/utils/async/AsyncExecutor.java b/accord-core/src/main/java/accord/utils/async/AsyncExecutor.java
index 50d2116e..a1f95237 100644
--- a/accord-core/src/main/java/accord/utils/async/AsyncExecutor.java
+++ b/accord-core/src/main/java/accord/utils/async/AsyncExecutor.java
@@ -24,15 +24,13 @@ import java.util.concurrent.Executors;
public interface AsyncExecutor extends Executor
{
- default AsyncChain<?> submit(Runnable task)
+ default AsyncChain<?> build(Runnable task)
{
- return submit(Executors.callable(task));
+ return build(Executors.callable(task));
}
-
- default <T> AsyncChain<T> submit(Runnable task, T result)
+ default <T> AsyncChain<T> build(Runnable task, T result)
{
- return submit(Executors.callable(task, result));
+ return build(Executors.callable(task, result));
}
-
- <T> AsyncChain<T> submit(Callable<T> task);
+ <T> AsyncChain<T> build(Callable<T> task);
}
diff --git a/accord-core/src/test/java/accord/coordinate/CoordinateSyncPointTest.java b/accord-core/src/test/java/accord/coordinate/CoordinateSyncPointTest.java
index 294c2e4a..fe8d62d9 100644
--- a/accord-core/src/test/java/accord/coordinate/CoordinateSyncPointTest.java
+++ b/accord-core/src/test/java/accord/coordinate/CoordinateSyncPointTest.java
@@ -101,7 +101,7 @@ class CoordinateSyncPointTest
var await = CoordinateSyncPoint.exclusiveSyncPoint(node, new TxnId(1, node.now(), 0, Txn.Kind.ExclusiveSyncPoint, Routable.Domain.Range, node.id()), Ranges.single(removed))
.flatMap(syncPoint ->
// the test uses an executor that runs everything right away, so this gets called outside the CommandStore
- node.commandStores().forId(0).submit(() -> {
+ node.commandStores().forId(0).build(() -> {
ExecuteSyncPoint.ExecuteExclusive execute = new ExecuteSyncPoint.ExecuteExclusive(node, syncPoint, AllTracker::new);
execute.start();
return execute;
@@ -124,7 +124,7 @@ class CoordinateSyncPointTest
}
else if (request instanceof Accept)
{
- onSuccess(args, new Accept.AcceptReply(PartialDeps.NONE));
+ onSuccess(args, new Accept.AcceptReply(((Accept) request).scope, PartialDeps.NONE));
}
else if (request instanceof Commit)
{
diff --git a/accord-core/src/test/java/accord/impl/IntKey.java b/accord-core/src/test/java/accord/impl/IntKey.java
index 308d5e2f..b8f63757 100644
--- a/accord-core/src/test/java/accord/impl/IntKey.java
+++ b/accord-core/src/test/java/accord/impl/IntKey.java
@@ -34,7 +34,7 @@ import javax.annotation.Nonnull;
import static accord.utils.Utils.toArray;
-public class IntKey implements RoutableKey
+public abstract class IntKey implements RoutableKey
{
public static class Splitter implements ShardDistributor.EvenSplit.Splitter<Long>
{
diff --git a/accord-core/src/test/java/accord/impl/PrefixedIntHashKey.java b/accord-core/src/test/java/accord/impl/PrefixedIntHashKey.java
index 3b5b0459..57e7877b 100644
--- a/accord-core/src/test/java/accord/impl/PrefixedIntHashKey.java
+++ b/accord-core/src/test/java/accord/impl/PrefixedIntHashKey.java
@@ -33,7 +33,7 @@ import accord.utils.Invariants;
import static accord.utils.Utils.toArray;
-public class PrefixedIntHashKey implements RoutableKey
+public abstract class PrefixedIntHashKey implements RoutableKey
{
public static final int MIN_KEY = Integer.MIN_VALUE + 1;
diff --git a/accord-core/src/test/java/accord/impl/RemoteListenersTest.java b/accord-core/src/test/java/accord/impl/RemoteListenersTest.java
index 806e104c..3ba32f24 100644
--- a/accord-core/src/test/java/accord/impl/RemoteListenersTest.java
+++ b/accord-core/src/test/java/accord/impl/RemoteListenersTest.java
@@ -414,7 +414,7 @@ public class RemoteListenersTest
@Override public <T> AsyncChain<T> build(PreLoadContext context, Function<? super SafeCommandStore, T> apply) { return null; }
@Override public void shutdown() {}
@Override protected void registerTransitive(SafeCommandStore safeStore, RangeDeps deps) { }
- @Override public <T> AsyncChain<T> submit(Callable<T> task) { return null; }
+ @Override public <T> AsyncChain<T> build(Callable<T> task) { return null; }
}
static class TestSafeCommandStore extends SafeCommandStore
diff --git a/accord-core/src/test/java/accord/impl/TestAgent.java b/accord-core/src/test/java/accord/impl/TestAgent.java
index 089bf5cd..a03f042a 100644
--- a/accord-core/src/test/java/accord/impl/TestAgent.java
+++ b/accord-core/src/test/java/accord/impl/TestAgent.java
@@ -167,6 +167,12 @@ public class TestAgent implements Agent
return units.convert(1L, SECONDS);
}
+ @Override
+ public long localSlowAt(TxnId txnId, Status.Phase phase, TimeUnit unit)
+ {
+ return unit.convert(100L, MICROSECONDS);
+ }
+
@Override
public long localExpiresAt(TxnId txnId, Status.Phase phase, TimeUnit unit)
{
diff --git a/accord-core/src/test/java/accord/impl/basic/Cluster.java b/accord-core/src/test/java/accord/impl/basic/Cluster.java
index 61b80810..1f83d89d 100644
--- a/accord-core/src/test/java/accord/impl/basic/Cluster.java
+++ b/accord-core/src/test/java/accord/impl/basic/Cluster.java
@@ -590,7 +590,7 @@ public class Cluster
command = command.updateParticipants(command.participants().filter(LOAD, commandStore.unsafeGetRedundantBefore(), command.txnId(), command.executeAtIfKnown()));
// Journal will not have result persisted. This part is here for test purposes and ensuring that we have strict object equality.
Command reconstructed = journal.loadCommand(commandStore.id(), command.txnId(), commandStore.unsafeGetRedundantBefore(), commandStore.durableBefore());
- if (isWrite && reconstructed.saveStatus().is(Status.Truncated))
+ if (isWrite && reconstructed.saveStatus().hasBeen(Status.Truncated))
return;
List<ReflectionUtils.Difference<?>> diff = ReflectionUtils.recursiveEquals(command, reconstructed);
diff --git a/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java b/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java
index 67368e8f..fdf6b92b 100644
--- a/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java
+++ b/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java
@@ -304,7 +304,7 @@ public class DelayedCommandStores extends InMemoryCommandStores.SingleThread
}
@Override
- public <T> AsyncChain<T> submit(Callable<T> fn)
+ public <T> AsyncChain<T> build(Callable<T> fn)
{
return submit(new DelayedTask<>(fn));
}
diff --git a/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java b/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
index 9807c877..7ac22f89 100644
--- a/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
+++ b/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
@@ -34,7 +34,6 @@ import accord.api.Journal;
import accord.api.Result;
import accord.impl.CommandChange;
import accord.impl.InMemoryCommandStore;
-import accord.impl.RetiredSafeCommand;
import accord.local.Cleanup;
import accord.local.Command;
import accord.local.Command.WaitingOnWithExecuteAt;
@@ -89,7 +88,6 @@ import static accord.impl.CommandChange.unsetIterable;
import static accord.impl.CommandChange.validateFlags;
import static accord.local.Cleanup.Input.FULL;
import static accord.primitives.SaveStatus.Erased;
-import static accord.primitives.SaveStatus.Vestigial;
import static accord.primitives.Status.Invalidated;
import static accord.primitives.Status.Truncated;
import static accord.utils.Invariants.illegalState;
@@ -122,17 +120,7 @@ public class InMemoryJournal implements Journal
return null;
Builder builder = reconstruct(saved, ALL);
- Cleanup cleanup = builder.shouldCleanup(FULL, agent, redundantBefore, durableBefore);
- switch (cleanup)
- {
- case VESTIGIAL:
- return RetiredSafeCommand.erased(txnId, Vestigial);
-
- case EXPUNGE:
- case ERASE:
- return RetiredSafeCommand.erased(txnId, Erased);
- }
-
+ builder.maybeCleanup(FULL, agent, redundantBefore, durableBefore);
return builder.construct(redundantBefore);
}
@@ -183,7 +171,7 @@ public class InMemoryJournal implements Journal
}
@Override
- public void saveCommand(int store, CommandUpdate update, Runnable onFlush)
+ public void saveCommand(int commandStoreId, CommandUpdate update, Runnable onFlush)
{
Diff diff;
if ((diff = toDiff(update)) == null)
@@ -193,7 +181,7 @@ public class InMemoryJournal implements Journal
return;
}
- diffsPerCommandStore.computeIfAbsent(store, (k) -> new TreeMap<>())
+ diffsPerCommandStore.computeIfAbsent(commandStoreId, (k) -> new TreeMap<>())
.computeIfAbsent(update.txnId, (k_) -> new ArrayList<>())
.add(diff);
diff --git a/accord-core/src/test/java/accord/impl/basic/TaskExecutorService.java b/accord-core/src/test/java/accord/impl/basic/TaskExecutorService.java
index d7057c73..b7ca8fc4 100644
--- a/accord-core/src/test/java/accord/impl/basic/TaskExecutorService.java
+++ b/accord-core/src/test/java/accord/impl/basic/TaskExecutorService.java
@@ -103,19 +103,19 @@ public abstract class TaskExecutorService extends AbstractExecutorService implem
}
@Override
- public Task<?> submit(Runnable task)
+ public Task<?> build(Runnable task)
{
return (Task<?>) super.submit(task);
}
@Override
- public <T> Task<T> submit(Runnable task, T result)
+ public <T> Task<T> build(Runnable task, T result)
{
return (Task<T>) super.submit(task, result);
}
@Override
- public <T> Task<T> submit(Callable<T> task)
+ public <T> Task<T> build(Callable<T> task)
{
return (Task<T>) super.submit(task);
}
diff --git a/accord-core/src/test/java/accord/impl/list/ListAgent.java b/accord-core/src/test/java/accord/impl/list/ListAgent.java
index e54fe798..233fcc28 100644
--- a/accord-core/src/test/java/accord/impl/list/ListAgent.java
+++ b/accord-core/src/test/java/accord/impl/list/ListAgent.java
@@ -51,6 +51,7 @@ import accord.utils.RandomSource;
import static accord.local.Node.Id.NONE;
import static com.google.common.base.Functions.identity;
+import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
@@ -169,7 +170,7 @@ public class ListAgent implements Agent
@Override
public long attemptCoordinationDelay(Node node, SafeCommandStore safeStore, TxnId txnId, TimeUnit units, int retryCount)
{
- // TODO (testing): meta randomise
+ // TODO (required): meta randomise
return units.convert(rnd.nextInt(100, 1000), MILLISECONDS);
}
@@ -196,9 +197,15 @@ public class ListAgent implements Agent
return unit.convert(expiresAt, MILLISECONDS);
}
+ @Override
+ public long localSlowAt(TxnId txnId, Status.Phase phase, TimeUnit unit)
+ {
+ return unit.convert(timeoutSupplier.slowAt(), MICROSECONDS);
+ }
+
@Override
public long localExpiresAt(TxnId txnId, Status.Phase phase, TimeUnit unit)
{
- return timeoutSupplier.expiresAt();
+ return unit.convert(timeoutSupplier.expiresAt(), MICROSECONDS);
}
}
diff --git a/accord-core/src/test/java/accord/impl/list/ListRead.java b/accord-core/src/test/java/accord/impl/list/ListRead.java
index b1ea3c7c..7326dc0f 100644
--- a/accord-core/src/test/java/accord/impl/list/ListRead.java
+++ b/accord-core/src/test/java/accord/impl/list/ListRead.java
@@ -41,6 +41,8 @@ import accord.primitives.Seekable;
import accord.primitives.Seekables;
import accord.utils.async.AsyncExecutor;
+import static accord.primitives.Routables.Slice.Minimal;
+
public class ListRead implements Read
{
private static final Logger logger = LoggerFactory.getLogger(ListRead.class);
@@ -69,7 +71,7 @@ public class ListRead implements Read
{
ListStore s = (ListStore)store;
logger.trace("submitting READ on {} at {} key:{}", s.node, executeAt, key);
- return executor.apply(safeStore.commandStore()).submit(() -> {
+ return executor.apply(safeStore.commandStore()).build(() -> {
Ranges unavailable = safeStore.unsafeToReadAt(executeAt);
ListData result = new ListData();
switch (key.domain())
@@ -96,13 +98,13 @@ public class ListRead implements Read
@Override
public Read slice(Ranges ranges)
{
- return new ListRead(executor, isEphemeralRead, userReadKeys.slice(ranges), keys.slice(ranges));
+ return new ListRead(executor, isEphemeralRead, userReadKeys.slice(ranges, Minimal), keys.slice(ranges, Minimal));
}
@Override
public Read intersecting(Participants<?> participants)
{
- return new ListRead(executor, isEphemeralRead, userReadKeys.intersecting(participants), keys.intersecting(participants));
+ return new ListRead(executor, isEphemeralRead, userReadKeys.intersecting(participants, Minimal), keys.intersecting(participants, Minimal));
}
@Override
diff --git a/accord-core/src/test/java/accord/impl/list/ListWrite.java b/accord-core/src/test/java/accord/impl/list/ListWrite.java
index ea326b44..c0f63d88 100644
--- a/accord-core/src/test/java/accord/impl/list/ListWrite.java
+++ b/accord-core/src/test/java/accord/impl/list/ListWrite.java
@@ -56,7 +56,7 @@ public class ListWrite extends TreeMap<Key, int[]> implements Write
return Writes.SUCCESS;
logger.trace("submitting WRITE on {} at {} key:{}", s.node, executeAt, key);
- return executor.apply(safeStore.commandStore()).submit(() -> {
+ return executor.apply(safeStore.commandStore()).build(() -> {
int[] data = get(key);
s.write((Key)key, executeAt, data);
logger.trace("WRITE on {} at {} key:{} -> {}", s.node, executeAt, key, data);
diff --git a/accord-core/src/test/java/accord/local/CommandsTest.java b/accord-core/src/test/java/accord/local/CommandsTest.java
index 46279c7d..f10b9e7f 100644
--- a/accord-core/src/test/java/accord/local/CommandsTest.java
+++ b/accord-core/src/test/java/accord/local/CommandsTest.java
@@ -69,7 +69,7 @@ class CommandsTest
{
// could use AccordGens.nodes() but to make debugging easier limit the node ids to small values
Gen<List<Node.Id>> nodeGen = Gens.ints().between(1, 10).map(size -> IntStream.range(1, size + 1).mapToObj(Node.Id::new).collect(Collectors.toList()));
- qt().withExamples(50).check(rs -> {
+ qt().withSeed(4036384075497011411L).withExamples(50).check(rs -> {
List<Node.Id> nodes = nodeGen.next(rs);
int rf = nodes.size() <= 3 ? nodes.size() : rs.nextInt(3, nodes.size());
logger.info("Running with {} nodes and rf={}", nodes.size(), rf);
diff --git a/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java b/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
index d2b349bd..7e306f36 100644
--- a/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
+++ b/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
@@ -1010,7 +1010,7 @@ public class CommandsForKeyTest
protected void registerTransitive(SafeCommandStore safeStore, RangeDeps deps){ }
@Override
- public <T> AsyncChain<T> submit(Callable<T> task)
+ public <T> AsyncChain<T> build(Callable<T> task)
{
throw new UnsupportedOperationException();
}
@@ -1105,6 +1105,12 @@ public class CommandsForKeyTest
return 0;
}
+ @Override
+ public long localSlowAt(TxnId txnId, Status.Phase phase, TimeUnit unit)
+ {
+ return 0;
+ }
+
@Override
public long localExpiresAt(TxnId txnId, Status.Phase phase, TimeUnit unit)
{
diff --git a/accord-core/src/test/java/accord/messages/PreAcceptTest.java b/accord-core/src/test/java/accord/messages/PreAcceptTest.java
index ba8ea769..326aef37 100644
--- a/accord-core/src/test/java/accord/messages/PreAcceptTest.java
+++ b/accord-core/src/test/java/accord/messages/PreAcceptTest.java
@@ -63,6 +63,7 @@ import static accord.impl.mock.MockCluster.configService;
import static accord.local.KeyHistory.SYNC;
import static accord.primitives.Routable.Domain.Key;
import static accord.primitives.Txn.Kind.Write;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Utils.listOf;
import static org.assertj.core.api.Assertions.assertThat;
@@ -161,7 +162,7 @@ public class PreAcceptTest
Txn txn = writeTxn(Keys.of(key));
Participants<?> invalidateWith = txn.keys().toParticipants();
- BeginInvalidation invalidate = new BeginInvalidation(ID1, node.topology().forEpoch(invalidateWith, txnId.epoch()), txnId, invalidateWith, Ballot.fromValues(txnId.epoch(), txnId.hlc(), txnId.node));
+ BeginInvalidation invalidate = new BeginInvalidation(ID1, node.topology().forEpoch(invalidateWith, txnId.epoch(), SHARE), txnId, invalidateWith, Ballot.fromValues(txnId.epoch(), txnId.hlc(), txnId.node));
invalidate.process(node, ID2, REPLY_CONTEXT);
messageSink.assertHistorySizes(0, 1);
diff --git a/accord-core/src/test/java/accord/messages/ReadDataTest.java b/accord-core/src/test/java/accord/messages/ReadDataTest.java
index a0645e0a..b0953a1f 100644
--- a/accord-core/src/test/java/accord/messages/ReadDataTest.java
+++ b/accord-core/src/test/java/accord/messages/ReadDataTest.java
@@ -62,6 +62,7 @@ import accord.primitives.Seekables;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
+import accord.primitives.Unseekables;
import accord.primitives.Writes;
import accord.topology.Topologies;
import accord.topology.Topology;
@@ -101,8 +102,21 @@ class ReadDataTest
AsyncResults.SettableResult<Data> readResult = new AsyncResults.SettableResult<>();
+ Read read = mockRead(keys, readResult);
+ Query query = Mockito.mock(Query.class);
+ Update update = Mockito.mock(Update.class);
+ Mockito.when(update.intersecting(any())).thenReturn(update);
+
+ Txn txn = new Txn.InMemory(keys, read, query, update);
+ PartialTxn partialTxn = txn.intersecting(RANGES, true);
+
+ fn.accept(new State(node, sink, txnId, partialTxn, readResult));
+ }
+
+ private Read mockRead(Keys keys, AsyncResults.SettableResult<Data> readResult)
+ {
Read read = Mockito.mock(Read.class);
- Mockito.when(read.intersecting(any())).thenReturn(read);
+ Mockito.when(read.intersecting(any())).thenAnswer(i -> mockRead(keys.intersecting((Unseekables) i.getArgument(0)), readResult));
Mockito.when(read.merge(any())).thenReturn(read);
Mockito.when(read.keys()).thenReturn((Seekables)keys);
Mockito.when(read.read(any(), any(), any(), any())).thenAnswer(new Answer<AsyncChain<Data>>()
@@ -115,14 +129,7 @@ class ReadDataTest
return readResult;
}
});
- Query query = Mockito.mock(Query.class);
- Update update = Mockito.mock(Update.class);
- Mockito.when(update.intersecting(any())).thenReturn(update);
-
- Txn txn = new Txn.InMemory(keys, read, query, update);
- PartialTxn partialTxn = txn.intersecting(RANGES, true);
-
- fn.accept(new State(node, sink, txnId, partialTxn, readResult));
+ return read;
}
@Test
@@ -151,7 +158,9 @@ class ReadDataTest
CheckedCommands.accept(safe, state.txnId, Ballot.ZERO, state.partialRoute, state.executeAt, state.deps);
SafeCommand safeCommand = safe.ifInitialised(state.txnId);
- safeCommand.stable(safe, StoreParticipants.execute(safe, state.route, state.txnId, state.txnId.epoch()), Ballot.ZERO, state.executeAt, state.partialTxn, state.deps, Command.WaitingOn.empty(state.txnId.domain()));
+ StoreParticipants participants = StoreParticipants.execute(safe, state.route, state.txnId, state.txnId.epoch());
+ PartialTxn txn = state.partialTxn.intersecting(participants.owns(), true);
+ safeCommand.stable(safe, participants, Ballot.ZERO, state.executeAt, txn, state.deps, Command.WaitingOn.empty(state.txnId.domain()));
})));
ReplyContext replyContext = state.process();
diff --git a/accord-core/src/test/java/accord/messages/TxnRequestScopeTest.java b/accord-core/src/test/java/accord/messages/TxnRequestScopeTest.java
index 95021c13..1ab71499 100644
--- a/accord-core/src/test/java/accord/messages/TxnRequestScopeTest.java
+++ b/accord-core/src/test/java/accord/messages/TxnRequestScopeTest.java
@@ -19,6 +19,7 @@
package accord.messages;
import accord.api.TopologySorter;
+import accord.primitives.KeyRoute;
import accord.primitives.Range;
import accord.primitives.FullKeyRoute;
import accord.primitives.PartialKeyRoute;
@@ -47,13 +48,13 @@ public class TxnRequestScopeTest
Topologies.Multi topologies = new Topologies.Multi((TopologySorter.StaticSorter)(a, b, s)->0, topology2, topology1);
// 3 remains a member across both topologies, so can process requests without waiting for latest topology data
- Assertions.assertEquals(scope(150), ((PartialKeyRoute)TxnRequest.computeScope(id(3), topologies, route)).toParticipants());
+ Assertions.assertEquals(scope(150), ((KeyRoute)TxnRequest.computeScope(id(3), topologies, route)).toParticipants());
Assertions.assertEquals(1, TxnRequest.computeWaitForEpoch(id(3), topologies, route));
// 1 leaves the shard, and 4 joins, so both need the latest information
- Assertions.assertEquals(scope(150), ((PartialKeyRoute)TxnRequest.computeScope(id(1), topologies, route)).toParticipants());
+ Assertions.assertEquals(scope(150), ((KeyRoute)TxnRequest.computeScope(id(1), topologies, route)).toParticipants());
Assertions.assertEquals(2, TxnRequest.computeWaitForEpoch(id(1), topologies, route));
- Assertions.assertEquals(scope(150), ((PartialKeyRoute)TxnRequest.computeScope(id(4), topologies, route)).toParticipants());
+ Assertions.assertEquals(scope(150), ((KeyRoute)TxnRequest.computeScope(id(4), topologies, route)).toParticipants());
Assertions.assertEquals(2, TxnRequest.computeWaitForEpoch(id(4), topologies, route));
}
diff --git a/accord-core/src/test/java/accord/topology/TopologyManagerTest.java b/accord-core/src/test/java/accord/topology/TopologyManagerTest.java
index 6aabe6f3..cb1e0e9d 100644
--- a/accord-core/src/test/java/accord/topology/TopologyManagerTest.java
+++ b/accord-core/src/test/java/accord/topology/TopologyManagerTest.java
@@ -64,6 +64,7 @@ import static accord.impl.IntKey.keys;
import static accord.impl.IntKey.range;
import static accord.impl.SizeOfIntersectionSorter.SUPPLIER;
import static accord.messages.TxnRequest.computeWaitForEpoch;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.ExtendedAssertions.assertThat;
import static accord.utils.Property.qt;
@@ -89,7 +90,7 @@ public class TopologyManagerTest
for (Unseekables<?> select : Arrays.asList(Ranges.ofSortedAndDeoverlapped(range(10, 20)), Ranges.ofSortedAndDeoverlapped(range(110, 120))))
{
- Topologies t = service.preciseEpochs(select, 1, 2);
+ Topologies t = service.preciseEpochs(select, 1, 2, SHARE);
for (int i : unmoved)
org.assertj.core.api.Assertions.assertThat(computeWaitForEpoch(new Node.Id(i), t, select)).isEqualTo(1);
for (int i : moved)
@@ -218,14 +219,14 @@ public class TopologyManagerTest
Assertions.assertFalse(service.getEpochStateUnsafe(2).syncComplete());
RoutingKeys keys = keys(150).toParticipants();
- Assertions.assertEquals(topologies(topology3.select(keys), topology2.select(keys), topology1.select(keys)),
+ Assertions.assertEquals(topologies(topology3.select(keys, SHARE), topology2.select(keys, SHARE), topology1.select(keys, SHARE)),
service.withUnsyncedEpochs(keys, 3, 3));
service.onEpochSyncComplete(id(2), 2);
service.onEpochSyncComplete(id(3), 2);
service.onEpochSyncComplete(id(2), 3);
service.onEpochSyncComplete(id(3), 3);
- Assertions.assertEquals(topologies(topology3.select(keys)),
+ Assertions.assertEquals(topologies(topology3.select(keys, SHARE)),
service.withUnsyncedEpochs(keys, 3, 3));
}
@@ -330,7 +331,7 @@ public class TopologyManagerTest
Unseekables<?> unseekables = TopologyUtils.select(ranges, rs);
long maxEpoch = topology.epoch();
long minEpoch = tm.minEpoch() == maxEpoch ? maxEpoch : rs.nextLong(tm.minEpoch(), maxEpoch + 1);
- assertThat(tm.preciseEpochs(unseekables, minEpoch, maxEpoch))
+ assertThat(tm.preciseEpochs(unseekables, minEpoch, maxEpoch, SHARE))
.isNotEmpty()
.epochsBetween(minEpoch, maxEpoch)
.containsAll(unseekables)
@@ -371,7 +372,7 @@ public class TopologyManagerTest
// prefix=0 was added in epoch=1, removed in epoch=2, and added back to epoch=3; the ABA problem
RoutingKeys unseekables = RoutingKeys.of(PrefixedIntHashKey.forHash(0, 42));
- for (Supplier<Topologies> fn : Arrays.<Supplier<Topologies>>asList(() -> service.preciseEpochs(unseekables, 1, 3),
+ for (Supplier<Topologies> fn : Arrays.<Supplier<Topologies>>asList(() -> service.preciseEpochs(unseekables, 1, 3, SHARE),
() -> service.withUnsyncedEpochs(unseekables, 1, 3)))
{
assertThat(fn.get())
@@ -431,7 +432,7 @@ public class TopologyManagerTest
EpochRange range = EpochRange.from(service, rand);
Unseekables<?> select = select(service, range, rand);
- assertThat(service.preciseEpochs(select, range.min, range.max))
+ assertThat(service.preciseEpochs(select, range.min, range.max, SHARE))
.isNotEmpty()
.epochsBetween(range.min, range.max)
.containsAll(select);
diff --git a/accord-core/src/test/java/accord/topology/TopologyTest.java b/accord-core/src/test/java/accord/topology/TopologyTest.java
index b87fc123..110c0f2b 100644
--- a/accord-core/src/test/java/accord/topology/TopologyTest.java
+++ b/accord-core/src/test/java/accord/topology/TopologyTest.java
@@ -36,12 +36,13 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
import java.util.function.Consumer;
+import static accord.topology.Topologies.SelectNodeOwnership.SLICE;
+import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.topology.TopologyUtils.routingKey;
import static accord.topology.TopologyUtils.routingKeyOutsideRange;
import static accord.topology.TopologyUtils.withEpoch;
@@ -62,7 +63,7 @@ public class TopologyTest
Assertions.assertTrue(shard.range.contains(expectedKey));
Assertions.assertEquals(expectedRange, shard.range);
- Topology subTopology = topology.select(Keys.of(expectedKey).toParticipants());
+ Topology subTopology = topology.select(Keys.of(expectedKey).toParticipants(), SHARE);
shard = Iterables.getOnlyElement(subTopology.shards());
Assertions.assertTrue(shard.range.contains(expectedKey));
Assertions.assertEquals(expectedRange, shard.range);
@@ -127,61 +128,57 @@ public class TopologyTest
for (int i = 0; i < topology.size(); i++)
{
Shard shard = topology.get(i);
- for (boolean withNodes : Arrays.asList(true, false))
+
+ Topology subset = topology.forSubset(new int[] {i}, SLICE);
+ Topology trimmed = subset.trim();
+
+ assertThat(subset)
+ .isSubset()
+ .isEqualTo(trimmed)
+ .hasSameHashCodeAs(trimmed)
+ // this is slightly redundant as trimmed model should catch this... it is here in case trim breaks
+ .hasSize(1)
+ .isShardsEqualTo(shard)
+ .isHostsEqualTo(shard.nodes)
+ .isRangesEqualTo(shard.range);
+
+ checkTopology(subset, rs);
{
- Topology subset = withNodes ?
- topology.forSubset(new int[] {i}, topology.nodes()) : // TODO (correctness): should this drop non-overlapping nodes, or reject?
- topology.forSubset(new int[] {i});
- Topology trimmed = subset.trim();
-
- assertThat(subset)
- .isSubset()
- .isEqualTo(trimmed)
- .hasSameHashCodeAs(trimmed)
- // this is slightly redundant as trimmed model should catch this... it is here in case trim breaks
- .hasSize(1)
- .isShardsEqualTo(shard)
- .isHostsEqualTo(shard.nodes)
- .isRangesEqualTo(shard.range);
-
- checkTopology(subset, rs);
- {
- List<Shard> forEachShard = new ArrayList<>(1);
- subset.forEach(s -> forEachShard.add(s)); // cant do forEachShard::add due ambiguous signature (multiple matches in topology)
- assertThat(forEachShard).isEqualTo(Collections.singletonList(shard));
- }
+ List<Shard> forEachShard = new ArrayList<>(1);
+ subset.forEach(s -> forEachShard.add(s)); // cant do forEachShard::add due ambiguous signature (multiple matches in topology)
+ assertThat(forEachShard).isEqualTo(Collections.singletonList(shard));
+ }
- Consumer<Unseekables<?>> foldl = unseekables -> assertThat(subset.foldl(unseekables, (s, accum, indexed) -> accum + System.identityHashCode(s), 0))
- .isEqualTo(trimmed.foldl(unseekables, (s, accum, indexed) -> accum + System.identityHashCode(s), 0))
- .isEqualTo(System.identityHashCode(shard));
- Consumer<Unseekables<?>> visitNodeForKeysOnceOrMore = unseekables -> {
- List<Node.Id> actual = new ArrayList<>(shard.nodes.size());
- subset.visitNodeForKeysOnceOrMore(unseekables, actual::add);
- assertThat(actual).isEqualTo(shard.nodes);
- };
- for (Range range : subset.ranges())
+ Consumer<Unseekables<?>> foldl = unseekables -> assertThat(subset.foldl(unseekables, (s, accum, indexed) -> accum + System.identityHashCode(s), 0))
+ .isEqualTo(trimmed.foldl(unseekables, (s, accum, indexed) -> accum + System.identityHashCode(s), 0))
+ .isEqualTo(System.identityHashCode(shard));
+ Consumer<Unseekables<?>> visitNodeForKeysOnceOrMore = unseekables -> {
+ List<Node.Id> actual = new ArrayList<>(shard.nodes.size());
+ subset.visitNodeForKeysOnceOrMore(unseekables, actual::add);
+ assertThat(actual).isEqualTo(shard.nodes);
+ };
+ for (Range range : subset.ranges())
+ {
+ for (int j = 0; j < 10; j++)
{
- for (int j = 0; j < 10; j++)
- {
- RoutingKey key = routingKey(range, rs);
- assertThat(subset.forKey(key)).isEqualTo(shard);
-
- RoutingKeys unseekables = RoutingKeys.of(key);
- foldl.accept(unseekables);
- visitNodeForKeysOnceOrMore.accept(unseekables);
- }
- Ranges unseekables = Ranges.single(range);
+ RoutingKey key = routingKey(range, rs);
+ assertThat(subset.forKey(key)).isEqualTo(shard);
+
+ RoutingKeys unseekables = RoutingKeys.of(key);
foldl.accept(unseekables);
visitNodeForKeysOnceOrMore.accept(unseekables);
}
+ Ranges unseekables = Ranges.single(range);
+ foldl.accept(unseekables);
+ visitNodeForKeysOnceOrMore.accept(unseekables);
+ }
- for (Node.Id node : new TreeSet<>(subset.nodes()))
- {
- assertThat(subset.forNode(node))
- .isEqualTo(trimmed.forNode(node))
- .isRangesEqualTo(subset.rangesForNode(node))
- .isRangesEqualTo(trimmed.rangesForNode(node));
- }
+ for (Node.Id node : new TreeSet<>(subset.nodes()))
+ {
+ assertThat(subset.forNode(node))
+ .isEqualTo(trimmed.forNode(node))
+ .isRangesEqualTo(subset.rangesForNode(node))
+ .isRangesEqualTo(trimmed.rangesForNode(node));
}
}
});
@@ -202,12 +199,12 @@ public class TopologyTest
}
for (Range range : topology.ranges())
{
- Topology subset = topology.select(Ranges.single(range));
+ Topology subset = topology.select(Ranges.single(range), SHARE);
for (int i = 0; i < 10; i++)
{
RoutingKey key = routingKey(range, rs);
- assertThat(topology.select(RoutingKeys.of(key))).isEqualTo(subset);
+ assertThat(topology.select(RoutingKeys.of(key), SHARE)).isEqualTo(subset);
assertThat(topology.forKey(key))
.describedAs("forKey(key) != get(indexForKey(key)) for key %s", key)
@@ -225,6 +222,6 @@ public class TopologyTest
.hasMessage("Range not found for %s", outsideRange);
}
}
- assertThat(topology.select(topology.ranges())).isEqualTo(topology);
+ assertThat(topology.select(topology.ranges(), SHARE)).isEqualTo(topology);
}
}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
index bd602d21..9a64217f 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
@@ -145,6 +145,12 @@ public class MaelstromAgent implements Agent
return units.convert(1L, SECONDS);
}
+ @Override
+ public long localSlowAt(TxnId txnId, Status.Phase phase, TimeUnit unit)
+ {
+ return unit.convert(100L, MICROSECONDS);
+ }
+
@Override
public long localExpiresAt(TxnId txnId, Status.Phase phase, TimeUnit unit)
{
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromKey.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromKey.java
index 076e26ca..0ca6793c 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromKey.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromKey.java
@@ -33,7 +33,7 @@ import com.google.gson.stream.JsonWriter;
import javax.annotation.Nonnull;
-public class MaelstromKey implements RoutableKey
+public abstract class MaelstromKey implements RoutableKey
{
public static class Splitter implements ShardDistributor.EvenSplit.Splitter<Long>
{
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromUpdate.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromUpdate.java
index cf0ba59d..c7b16b92 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromUpdate.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromUpdate.java
@@ -27,7 +27,6 @@ import accord.api.Update;
import accord.primitives.Participants;
import accord.primitives.Ranges;
import accord.primitives.Keys;
-import accord.primitives.Routables;
import accord.primitives.Timestamp;
public class MaelstromUpdate extends TreeMap<Key, Value> implements Update
@@ -51,21 +50,16 @@ public class MaelstromUpdate extends TreeMap<Key, Value> implements Update
@Override
public Update slice(Ranges ranges)
{
- return intersecting((Routables<?>) ranges);
+ return intersecting(ranges);
}
@Override
public Update intersecting(Participants<?> participants)
- {
- return intersecting((Routables<?>) participants);
- }
-
- public Update intersecting(Routables<?> routables)
{
MaelstromUpdate result = new MaelstromUpdate();
for (Map.Entry<Key, Value> e : entrySet())
{
- if (routables.contains(e.getKey()))
+ if (participants.contains(e.getKey().toUnseekable()))
result.put(e.getKey(), e.getValue());
}
return result;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org