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/03 16:31:14 UTC
(cassandra-accord) branch trunk updated (183d5d0b -> cd7f4956)
This is an automated email from the ASF dual-hosted git repository.
benedict pushed a change to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra-accord.git
discard 183d5d0b Refactor RedundantStatus to encode vector of states that can be merged independently Also fix: - Truncate command on first access, without participants - Use Ballot.ZERO when invoking CFK.insertOutOfRange where appropriate - Don't supply a command's own route to ProgressLog.waiting to ensure new keys are incorporated - Ensure progress in CommandsForKey by setting vestigial commands to ERASED - Add any missing owned keys to StoreParticipants.route to ensure fetch can [...]
new cd7f4956 Refactor RedundantStatus to encode vector of states that can be merged independently Also fix: - Truncate command on first access, without participants - Use Ballot.ZERO when invoking CFK.insertOutOfRange where appropriate - Don't supply a command's own route to ProgressLog.waiting to ensure new keys are incorporated - Ensure progress in CommandsForKey by setting vestigial commands to ERASED - Add any missing owned keys to StoreParticipants.route to ensure fetch can [...]
This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version. This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:
* -- * -- B -- O -- O -- O (183d5d0b)
\
N -- N -- N refs/heads/trunk (cd7f4956)
You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.
Any revisions marked "omit" are not gone; other references still
refer to them. Any revisions marked "discard" are gone forever.
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
(cassandra-accord) 01/01: Refactor RedundantStatus to encode vector of states that can be merged independently Also fix: - Truncate command on first access, without participants - Use Ballot.ZERO when invoking CFK.insertOutOfRange where appropriate - Don't supply a command's own route to ProgressLog.waiting to ensure new keys are incorporated - Ensure progress in CommandsForKey by setting vestigial commands to ERASED - Add any missing owned keys to StoreParticipants.route to ensure fetch can make progress - R [...]
Posted by be...@apache.org.
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
commit cd7f49564a5ad053286453d10f8cd46b8d870c4f
Author: Benedict Elliott Smith <be...@apache.org>
AuthorDate: Wed Jan 29 22:22:06 2025 +0000
Refactor RedundantStatus to encode vector of states that can be merged independently
Also fix:
- Truncate command on first access, without participants
- Use Ballot.ZERO when invoking CFK.insertOutOfRange where appropriate
- Don't supply a command's own route to ProgressLog.waiting to ensure new keys are incorporated
- Ensure progress in CommandsForKey by setting vestigial commands to ERASED
- Add any missing owned keys to StoreParticipants.route to ensure fetch can make progress
- Recovery must wait for earlier not-accepted transactions if either has the privileged coordinator optimisation
- Inclusive SyncPoint used incorrect topologies for propose phase
- Barrier must not register local listener without up-to-date topology information
- Stop home shard truncating a TxnId to vestigial rather than Invalidated so other shards can make progress
Also improve:
- Validate commands are constructed with non-empty participants
- Remove some unnecessary synchronized keywords
- Clear ok messages on PreAccept and Accept to free up memory
- Introduce TxnId.Cardinality flag so we can optimise single key queries
- Update CommandsForKey serialization to better handle larger flag space
- Configurable which Txn.Kind can result in a CommandStore being marked stale
- Process DefaultProgressLog queue synchronously when relevant state is resident in memory
- Remove defunct CollectMaxApplied version of ListStore bootstrap
- Standardise linearizability violation reporting
- Improve CommandStore.execute method naming to reduce chance of misuse
- Relax Invariant on recovery that we cannot both Accept and Reject, as we could be a stale recovery
- Prune and address some comments
patch by Benedict; reviewed by Alex Petrov for CASSANDRA-20282
---
accord-core/src/main/java/accord/api/Agent.java | 5 +-
.../main/java/accord/api/ProtocolModifiers.java | 14 +-
.../coordinate/AbstractCoordinatePreAccept.java | 9 +-
.../src/main/java/accord/coordinate/Barrier.java | 13 +-
.../main/java/accord/coordinate/CheckShards.java | 2 +-
.../accord/coordinate/CoordinateEphemeralRead.java | 4 +-
.../coordinate/CoordinateGloballyDurable.java | 6 +-
.../accord/coordinate/CoordinatePreAccept.java | 5 +-
.../accord/coordinate/CoordinateSyncPoint.java | 7 +-
.../accord/coordinate/CoordinateTransaction.java | 7 +-
.../accord/coordinate/CoordinationAdapter.java | 11 +-
.../accord/coordinate/ExecuteEphemeralRead.java | 4 +-
.../java/accord/coordinate/ExecuteSyncPoint.java | 6 +-
.../java/accord/coordinate/FetchCoordinator.java | 3 -
.../src/main/java/accord/coordinate/FetchData.java | 4 +-
.../src/main/java/accord/coordinate/Infer.java | 1 -
.../main/java/accord/coordinate/Invalidate.java | 2 +-
.../main/java/accord/coordinate/MaybeRecover.java | 3 +-
.../src/main/java/accord/coordinate/Propose.java | 16 +-
.../src/main/java/accord/coordinate/Recover.java | 20 +-
.../java/accord/coordinate/RecoverWithRoute.java | 2 -
.../coordinate/tracking/FastPathTracker.java | 12 +-
.../coordinate/tracking/InvalidationTracker.java | 12 +-
.../java/accord/impl/AbstractFetchCoordinator.java | 6 +-
.../src/main/java/accord/impl/CommandChange.java | 5 +-
.../java/accord/impl/DefaultLocalListeners.java | 9 +-
.../java/accord/impl/DefaultRemoteListeners.java | 1 -
.../java/accord/impl/InMemoryCommandStore.java | 37 +-
.../main/java/accord/impl/RequestCallbacks.java | 1 -
.../accord/impl/progresslog/CallbackInvoker.java | 2 +-
.../impl/progresslog/DefaultProgressLog.java | 89 ++-
.../impl/progresslog/DefaultProgressLogs.java | 4 +-
.../src/main/java/accord/local/Bootstrap.java | 16 +-
.../src/main/java/accord/local/Cleanup.java | 229 ++++----
.../src/main/java/accord/local/Command.java | 76 +--
.../src/main/java/accord/local/CommandStore.java | 48 +-
.../src/main/java/accord/local/CommandStores.java | 12 +-
.../main/java/accord/local/CommandSummaries.java | 2 +-
.../src/main/java/accord/local/Commands.java | 281 +++++-----
accord-core/src/main/java/accord/local/Node.java | 45 +-
.../src/main/java/accord/local/PreLoadContext.java | 10 +-
.../main/java/accord/local/RedundantBefore.java | 405 ++++++--------
.../main/java/accord/local/RedundantStatus.java | 600 +++++++--------------
.../main/java/accord/local/SafeCommandStore.java | 63 +--
.../main/java/accord/local/StoreParticipants.java | 9 +-
.../main/java/accord/local/cfk/CommandsForKey.java | 52 +-
.../src/main/java/accord/local/cfk/NotifySink.java | 14 +-
.../main/java/accord/local/cfk/PostProcess.java | 2 +-
.../src/main/java/accord/local/cfk/Pruning.java | 1 +
.../src/main/java/accord/local/cfk/Serialize.java | 240 +++++----
.../src/main/java/accord/local/cfk/Updating.java | 18 +-
.../src/main/java/accord/messages/Accept.java | 1 -
.../src/main/java/accord/messages/Apply.java | 2 -
.../main/java/accord/messages/BeginRecovery.java | 33 +-
.../src/main/java/accord/messages/Callback.java | 2 -
.../src/main/java/accord/messages/CheckStatus.java | 5 +-
.../src/main/java/accord/messages/Commit.java | 1 -
.../main/java/accord/messages/InformDurable.java | 2 +-
.../src/main/java/accord/messages/MessageType.java | 111 ++--
.../src/main/java/accord/messages/PreAccept.java | 2 -
.../src/main/java/accord/messages/Propagate.java | 64 +--
.../src/main/java/accord/messages/ReadData.java | 12 +-
.../java/accord/messages/ReadEphemeralTxnData.java | 5 +-
.../java/accord/messages/SetGloballyDurable.java | 4 -
.../java/accord/primitives/AbstractRanges.java | 2 +-
.../src/main/java/accord/primitives/Deps.java | 2 +-
.../main/java/accord/primitives/EpochSupplier.java | 1 -
.../src/main/java/accord/primitives/KeyDeps.java | 2 -
.../main/java/accord/primitives/PartialDeps.java | 5 -
.../main/java/accord/primitives/PartialTxn.java | 2 -
.../src/main/java/accord/primitives/RangeDeps.java | 6 +-
.../main/java/accord/primitives/SaveStatus.java | 16 +-
.../src/main/java/accord/primitives/Timestamp.java | 4 +-
.../src/main/java/accord/primitives/Txn.java | 2 -
.../src/main/java/accord/primitives/TxnId.java | 205 +++++--
.../src/main/java/accord/topology/Shard.java | 11 +-
.../src/main/java/accord/topology/Topology.java | 5 +-
.../main/java/accord/topology/TopologyManager.java | 19 +-
.../src/main/java/accord/utils/BitUtils.java | 1 -
.../src/main/java/accord/utils/Invariants.java | 73 +++
.../src/main/java/accord/utils/RandomSource.java | 2 +-
.../java/accord/utils/ReducingIntervalMap.java | 2 +-
.../main/java/accord/utils/ReducingRangeMap.java | 14 +-
.../main/java/accord/utils/RelationMultiMap.java | 10 +-
.../src/main/java/accord/utils/SortedArrays.java | 2 +-
.../src/main/java/accord/utils/TinyEnumSet.java | 6 +-
.../src/main/java/accord/utils/UnhandledEnum.java | 17 +-
accord-core/src/main/java/accord/utils/Utils.java | 12 +
.../main/java/accord/utils/async/AsyncChain.java | 2 -
.../src/test/java/accord/burn/BurnTestBase.java | 29 +-
.../coordinate/CoordinateTransactionTest.java | 8 +-
.../tracking/RecoveryTrackerReconciler.java | 2 +-
.../coordinate/tracking/TrackerReconciler.java | 2 +-
.../test/java/accord/impl/PrefixedIntHashKey.java | 1 -
.../test/java/accord/impl/RemoteListenersTest.java | 4 +-
.../src/test/java/accord/impl/basic/Cluster.java | 11 +-
.../accord/impl/basic/DelayedCommandStores.java | 4 +-
.../src/test/java/accord/impl/list/ListAgent.java | 6 -
.../accord/impl/list/ListFetchCoordinator.java | 43 +-
.../src/test/java/accord/impl/list/ListStore.java | 11 +-
.../src/test/java/accord/local/CommandsTest.java | 3 +-
.../java/accord/local/ImmutableCommandTest.java | 4 +-
.../java/accord/local/cfk/CommandsForKeyTest.java | 43 +-
.../test/java/accord/local/cfk/SerializeTest.java | 122 +++++
.../test/java/accord/messages/PreAcceptTest.java | 6 +-
.../test/java/accord/messages/ReadDataTest.java | 14 +-
.../test/java/accord/primitives/KeyDepsTest.java | 2 +-
.../test/java/accord/primitives/RangeDepsTest.java | 2 +-
.../src/test/java/accord/utils/AccordGens.java | 38 +-
.../verify/StrictSerializabilityVerifier.java | 4 +-
110 files changed, 1737 insertions(+), 1734 deletions(-)
diff --git a/accord-core/src/main/java/accord/api/Agent.java b/accord-core/src/main/java/accord/api/Agent.java
index a76dd41f..9cdd757c 100644
--- a/accord-core/src/main/java/accord/api/Agent.java
+++ b/accord-core/src/main/java/accord/api/Agent.java
@@ -20,11 +20,14 @@ package accord.api;
import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+
import accord.api.ProgressLog.BlockedUntil;
import accord.local.Command;
import accord.local.Node;
import accord.local.SafeCommandStore;
import accord.messages.ReplyContext;
+import accord.primitives.Participants;
import accord.primitives.Ranges;
import accord.primitives.Routable;
import accord.primitives.Status.Phase;
@@ -153,5 +156,5 @@ public interface Agent extends UncaughtExceptionListener
long localExpiresAt(TxnId txnId, Phase phase, TimeUnit unit);
long expiresAt(ReplyContext replyContext, TimeUnit unit);
- default void onViolation(String message) { throw illegalState(message); }
+ default void onViolation(String message, Participants<?> participants, @Nullable TxnId notWitnessed, @Nullable Timestamp notWitnessedExecuteAt, @Nullable TxnId by, @Nullable Timestamp byEexecuteAt) { throw illegalState(message); }
}
diff --git a/accord-core/src/main/java/accord/api/ProtocolModifiers.java b/accord-core/src/main/java/accord/api/ProtocolModifiers.java
index 5a82c9d8..17a247b2 100644
--- a/accord-core/src/main/java/accord/api/ProtocolModifiers.java
+++ b/accord-core/src/main/java/accord/api/ProtocolModifiers.java
@@ -21,11 +21,13 @@ package accord.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.primitives.TxnId.FastPath;
import accord.primitives.TxnId.FastPaths;
import accord.primitives.TxnId.MediumPath;
import accord.utils.Invariants;
+import accord.utils.TinyEnumSet;
import static accord.api.ProtocolModifiers.QuorumEpochIntersections.ChaseFixedPoint.Chase;
import static accord.api.ProtocolModifiers.QuorumEpochIntersections.ChaseFixedPoint.DoNotChase;
@@ -162,7 +164,6 @@ public class ProtocolModifiers
static
{
- // TODO (expected): configurable
Spec spec = new Spec(false, false, false, false);
txnInstability = spec.txnInstability;
txnDiscardPreAcceptDeps = spec.txnDiscardPreAcceptDeps;
@@ -187,7 +188,7 @@ public class ProtocolModifiers
public static void setPermittedFastPaths(FastPaths newPermittedFastPaths) { permittedFastPaths = newPermittedFastPaths; }
public static FastPath ensurePermitted(FastPath path) { return path.toPermitted(permittedFastPaths); }
- private static MediumPath defaultMediumPath = MediumPath.TRACK_STABLE;
+ private static MediumPath defaultMediumPath = MediumPath.TrackStable;
public static MediumPath defaultMediumPath() { return defaultMediumPath; }
public static void setDefaultMediumPath(MediumPath newDefaultMediumPath) { defaultMediumPath = newDefaultMediumPath; }
@@ -203,6 +204,15 @@ public class ProtocolModifiers
public static boolean requiresUniqueHlcs() { return requiresUniqueHlcs; }
public static void setRequiresUniqueHlcs(boolean newRequiresUniqueHlcs) { requiresUniqueHlcs = newRequiresUniqueHlcs; }
+ private static int markStaleIfCannotExecute = TinyEnumSet.encode(Txn.Kind.Write);
+ public static boolean markStaleIfCannotExecute(Txn.Kind kind) { return TinyEnumSet.contains(markStaleIfCannotExecute, kind); }
+ public static void setMarkStaleIfCannotExecute(Txn.Kind ... kinds)
+ {
+ int newMarkStaleIfCannotExecute = TinyEnumSet.encode(kinds);
+ Invariants.require(TinyEnumSet.contains(newMarkStaleIfCannotExecute, Txn.Kind.Write));
+ markStaleIfCannotExecute = newMarkStaleIfCannotExecute;
+ }
+
public enum DependencyElision { OFF, ON, IF_DURABLE }
private static DependencyElision dependencyElision = IF_DURABLE;
public static DependencyElision dependencyElision() { return dependencyElision; }
diff --git a/accord-core/src/main/java/accord/coordinate/AbstractCoordinatePreAccept.java b/accord-core/src/main/java/accord/coordinate/AbstractCoordinatePreAccept.java
index 4a257ea5..c153d980 100644
--- a/accord-core/src/main/java/accord/coordinate/AbstractCoordinatePreAccept.java
+++ b/accord-core/src/main/java/accord/coordinate/AbstractCoordinatePreAccept.java
@@ -74,14 +74,14 @@ abstract class AbstractCoordinatePreAccept<T, R> extends SettableResult<T> imple
abstract long executeAtEpoch();
@Override
- public synchronized final void onFailure(Id from, Throwable failure)
+ public final void onFailure(Id from, Throwable failure)
{
if (!isDone)
onFailureInternal(from, failure);
}
@Override
- public final synchronized boolean onCallbackFailure(Id from, Throwable failure)
+ public final boolean onCallbackFailure(Id from, Throwable failure)
{
if (isDone) return false;
isDone = true;
@@ -89,15 +89,14 @@ abstract class AbstractCoordinatePreAccept<T, R> extends SettableResult<T> imple
}
@Override
- // TODO (expected): shouldn't need synchronized
- public final synchronized void onSuccess(Id from, R reply)
+ public final void onSuccess(Id from, R reply)
{
if (!isDone)
onSuccessInternal(from, reply);
}
@Override
- public final synchronized void onSlowResponse(Id from)
+ public final void onSlowResponse(Id from)
{
if (!isDone)
onSlowResponseInternal(from);
diff --git a/accord-core/src/main/java/accord/coordinate/Barrier.java b/accord-core/src/main/java/accord/coordinate/Barrier.java
index f94d916c..5589e87d 100644
--- a/accord-core/src/main/java/accord/coordinate/Barrier.java
+++ b/accord-core/src/main/java/accord/coordinate/Barrier.java
@@ -57,6 +57,7 @@ import static accord.local.CommandSummaries.SummaryStatus.INVALIDATED;
import static accord.local.CommandSummaries.ComputeIsDep.IGNORE;
import static accord.local.CommandSummaries.TestStartedAt.STARTED_AFTER;
import static accord.primitives.Txn.Kind.AnyGloballyVisible;
+import static accord.primitives.TxnId.Cardinality.cardinality;
import static accord.utils.Invariants.illegalState;
/**
@@ -149,7 +150,7 @@ public class Barrier extends AsyncResults.AbstractResult<TxnId>
private static BiFunction<Node, FullRoute<?>, AsyncSyncPoint> wrap(TriFunction<Node, TxnId, FullRoute<?>, AsyncResult<? extends SyncPoint<?>>> syncPointFactory)
{
return (node, route) -> {
- TxnId txnId = node.nextTxnId(Txn.Kind.SyncPoint, route.domain());
+ TxnId txnId = node.nextTxnId(Txn.Kind.SyncPoint, route.domain(), cardinality(route));
return new AsyncSyncPoint(txnId, syncPointFactory.apply(node, txnId, route));
};
}
@@ -186,11 +187,10 @@ public class Barrier extends AsyncResults.AbstractResult<TxnId>
coordinateSyncPoint = async.async;
if (barrierType.async)
{
- Invariants.require(barrierType.async);
TxnId txnId = async.txnId;
long epoch = txnId.epoch();
RoutingKey homeKey = route.homeKey();
- node.commandStores().ifLocal(txnId, homeKey, epoch, epoch, safeStore -> register(safeStore, txnId, homeKey))
+ node.withEpoch(epoch, () -> node.commandStores().ifLocal(txnId, homeKey, epoch, epoch, safeStore -> register(safeStore, txnId, homeKey)))
.begin(node.agent());
}
@@ -278,7 +278,7 @@ public class Barrier extends AsyncResults.AbstractResult<TxnId>
@Override
public BarrierTxn apply(SafeCommandStore safeStore)
{
- // TODO (required): consider these semantics carefully
+ // TODO (required): it isn't probably safe to use a Read here; but, we can and should implement Barriers via writes
// Barriers are trying to establish that committed transactions are applied before the barrier (or in this case just minEpoch)
// so all existing transaction types should ensure that at this point. An earlier txnid may have an executeAt that is after
// this barrier or the transaction we listen on and that is fine
@@ -289,8 +289,9 @@ public class Barrier extends AsyncResults.AbstractResult<TxnId>
//noinspection SillyAssignment,ConstantConditions
safeStore = safeStore; // prevent use in lambda
safeStore.commandStore()
- .execute(found.txnId, safeStoreWithTxn -> register(safeStoreWithTxn, found.txnId, found.key))
- .begin(node.agent());
+ .execute(found.txnId, safeStoreWithTxn -> {
+ register(safeStoreWithTxn, found.txnId, found.key);
+ }, node.agent());
}
return found;
}
diff --git a/accord-core/src/main/java/accord/coordinate/CheckShards.java b/accord-core/src/main/java/accord/coordinate/CheckShards.java
index 526f207e..787642b8 100644
--- a/accord-core/src/main/java/accord/coordinate/CheckShards.java
+++ b/accord-core/src/main/java/accord/coordinate/CheckShards.java
@@ -67,7 +67,7 @@ public abstract class CheckShards<U extends Participants<?>> extends ReadCoordin
private static Topologies topologyFor(Node node, TxnId txnId, Unseekables<?> contact, long epoch)
{
- // TODO (expected): only fetch data from source epoch
+ // TODO (desired): only fetch data from source epoch
return node.topology().preciseEpochs(contact, txnId.epoch(), epoch);
}
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateEphemeralRead.java b/accord-core/src/main/java/accord/coordinate/CoordinateEphemeralRead.java
index 555f8a4e..53526571 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateEphemeralRead.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateEphemeralRead.java
@@ -32,6 +32,7 @@ import accord.primitives.FullRoute;
import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Topologies;
+import accord.utils.Invariants;
import accord.utils.SortedListMap;
import accord.utils.async.AsyncResult;
import accord.utils.async.AsyncResults;
@@ -125,6 +126,7 @@ public class CoordinateEphemeralRead extends AbstractCoordinatePreAccept<Result,
{
Deps deps = Deps.merge(oks, oks.domainSize(), SortedListMap::getValue, ok -> ok.deps);
topologies = node.topology().reselect(topologies, QuorumEpochIntersections.preaccept.include, route, executeAtEpoch, executeAtEpoch, Owned);
- new ExecuteEphemeralRead(node, topologies, route, txnId.withEpoch(executeAtEpoch), txn, executeAtEpoch, deps, this).start();
+ 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/CoordinateGloballyDurable.java b/accord-core/src/main/java/accord/coordinate/CoordinateGloballyDurable.java
index e8f313ee..2baca3e7 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateGloballyDurable.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateGloballyDurable.java
@@ -31,12 +31,12 @@ import accord.utils.SortedArrays;
import accord.utils.async.AsyncResult;
import accord.utils.async.AsyncResults.SettableResult;
-// TODO (expected): this does not need to query every shard; can disseminate globally any sub-range of the ring
-// (indeed, we could slice both the query and dissemination only so that they always overlap)
+// TODO (expected): this does not need to query every shard OR more than one replica per shard;
+// can disseminate globally any sub-range of the ring.
+// Infact, we could simply autonomously disseminate our latest information to some subset of replicas
public class CoordinateGloballyDurable extends SettableResult<Void> implements Callback<DurableBeforeReply>
{
final Node node;
- // TODO (expected): this can be a ReadTracker, we only need one response from each shard
final QuorumTracker tracker;
private DurableBefore durableBefore = DurableBefore.EMPTY;
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java b/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
index 5e580ee3..371eef18 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
@@ -36,6 +36,7 @@ import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Topologies;
+import accord.utils.Invariants;
import accord.utils.SortedListMap;
import accord.utils.WrappableException;
@@ -49,12 +50,10 @@ import static accord.primitives.Timestamp.mergeMaxAndFlags;
* If we are preempted by a recovery coordinator, we abort and let them complete (and notify us about the execution result)
*
* TODO (desired, testing): dedicated burn test to validate outcomes
- * TODO (expected):
*/
abstract class CoordinatePreAccept<T> extends AbstractCoordinatePreAccept<T, PreAcceptReply>
{
final PreAcceptTracker<?> tracker;
- // TODO (expected): this can be cleared after preaccept
private final SortedListMap<Id, PreAcceptOk> oks;
final Txn txn;
boolean fastPathEnabled = true;
@@ -148,10 +147,10 @@ abstract class CoordinatePreAccept<T> extends AbstractCoordinatePreAccept<T, Pre
@Override
void onPreAccepted(Topologies topologies)
{
- // TODO (expected): we do not have to take max here if we have enough fast path votes (this may unnecessarily force us onto the slow path)
Timestamp executeAt = oks.foldlNonNullValues((ok, prev) -> mergeMaxAndFlags(ok.witnessedAt, prev), Timestamp.NONE);
node.withEpoch(executeAt.epoch(), this, t -> WrappableException.wrap(t), () -> {
onPreAccepted(topologies, executeAt, oks);
+ if (!Invariants.debug()) oks.clear();
});
}
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
index becaa76f..17acc99c 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
@@ -56,6 +56,7 @@ import static accord.messages.Apply.participates;
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;
/**
* Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
@@ -124,14 +125,14 @@ public class CoordinateSyncPoint<R> extends CoordinatePreAccept<R>
public static <U extends Unseekable> AsyncResult<SyncPoint<U>> coordinate(Node node, Kind kind, Unseekables<U> keysOrRanges, SyncPointAdapter<SyncPoint<U>> adapter)
{
Invariants.requireArgument(kind.isSyncPoint());
- TxnId txnId = node.nextTxnId(kind, keysOrRanges.domain());
+ TxnId txnId = node.nextTxnId(kind, keysOrRanges.domain(), cardinality(keysOrRanges));
return node.withEpoch(txnId.epoch(), () -> coordinate(node, txnId, keysOrRanges, adapter)).beginAsResult();
}
public static <U extends Unseekable> AsyncResult<SyncPoint<U>> coordinate(Node node, Kind kind, FullRoute<U> route, SyncPointAdapter<SyncPoint<U>> adapter)
{
Invariants.requireArgument(kind.isSyncPoint());
- TxnId txnId = node.nextTxnId(kind, route.domain());
+ TxnId txnId = node.nextTxnId(kind, route.domain(), cardinality(route));
return node.withEpoch(txnId.epoch(), () -> coordinate(node, txnId, route, adapter)).beginAsResult();
}
@@ -150,7 +151,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), node.agent().emptySystemTxn(txnId.kind(), txnId.domain()), route, adapter);
+ CoordinateSyncPoint<SyncPoint<U>> coordinate = new CoordinateSyncPoint<>(node, txnId, adapter.forDecision(node, route, txnId, txnId), node.agent().emptySystemTxn(txnId.kind(), txnId.domain()), route, adapter);
coordinate.start();
return coordinate;
}
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java b/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
index 556c7b4c..e77dd837 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
@@ -64,7 +64,7 @@ import static accord.coordinate.ExecutePath.FAST;
import static accord.coordinate.Propose.NotAccept.proposeAndCommitInvalidate;
import static accord.local.Commands.AcceptOutcome.Success;
import static accord.primitives.Timestamp.Flag.REJECTED;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
/**
@@ -148,7 +148,6 @@ public class CoordinateTransaction extends CoordinatePreAccept<Result>
return Adapters.standard();
}
- // TODO (expected): override in C* rather than default to configurability here
protected CoordinationAdapter<Result> executeAdapter()
{
return node.coordinationAdapter(txnId, Standard);
@@ -201,7 +200,7 @@ public class CoordinateTransaction extends CoordinatePreAccept<Result>
// TODO (desired): we can probably still process and record fast path votes from peers, just with different quorum requirements
boolean hasCoordinatorVote = txnId.equals(ok.witnessedAt);
if (!hasCoordinatorVote) fastPathEnabled = false;
- Deps deps = hasCoordinatorVote && txnId.is(PRIVILEGED_COORDINATOR_WITH_DEPS) ? ok.deps : null;
+ Deps deps = hasCoordinatorVote && txnId.is(PrivilegedCoordinatorWithDeps) ? ok.deps : null;
onSuccess(node.id(), ok);
for (Node.Id id : topologies.nodes())
{
@@ -225,7 +224,7 @@ public class CoordinateTransaction extends CoordinatePreAccept<Result>
SafeCommand safeCommand = safeStore.get(txnId, participants);
Deps deps;
- if (txnId.is(PRIVILEGED_COORDINATOR_WITH_DEPS))
+ if (txnId.is(PrivilegedCoordinatorWithDeps))
{
deps = PreAccept.calculateDeps(safeStore, txnId, participants, minEpoch, txnId, true);
if (deps == null)
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java b/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
index 6a77b504..b8b30346 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
@@ -225,14 +225,14 @@ public interface CoordinationAdapter<R>
this.preacceptTrackerFactory = preacceptTrackerFactory;
}
- abstract Topologies forDecision(Node node, FullRoute<?> route, TxnId txnId);
+ 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 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);
+ Topologies all = forDecision(node, route, txnId, executeAt);
new ProposeSyncPoint<>(this, node, all, route, kind, ballot, txnId, txn, executeAt, deps, callback).start();
}
@@ -269,7 +269,7 @@ public interface CoordinationAdapter<R>
}
@Override
- Topologies forDecision(Node node, FullRoute<?> route, TxnId txnId)
+ Topologies forDecision(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt)
{
return node.topology().withOpenEpochs(route, null, txnId);
}
@@ -316,14 +316,13 @@ public interface CoordinationAdapter<R>
{
protected AbstractInclusiveSyncPointAdapter()
{
- // TODO (required): this is only safe if SyncPoint is visible to other transactions
super(FastPathTracker::new);
}
@Override
- Topologies forDecision(Node node, FullRoute<?> route, TxnId txnId)
+ Topologies forDecision(Node node, FullRoute<?> route, TxnId txnId, Timestamp executeAt)
{
- return node.topology().withUnsyncedEpochs(route, txnId, txnId);
+ return node.topology().withUnsyncedEpochs(route, txnId, executeAt);
}
@Override
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java b/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
index b99e0002..67b89549 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
@@ -59,7 +59,7 @@ public class ExecuteEphemeralRead extends ReadCoordinator<ReadReply>
final BiConsumer<? super Result, Throwable> callback;
private Data data;
- ExecuteEphemeralRead(Node node, Topologies topologies, FullRoute<?> route, TxnId txnId, Txn txn, long executionEpoch, Deps deps, BiConsumer<? super Result, Throwable> callback)
+ ExecuteEphemeralRead(Node node, Topologies topologies, FullRoute<?> route, TxnId txnId, Txn txn, Deps deps, BiConsumer<? super Result, Throwable> callback)
{
// we need to send Stable to the origin epoch as well as the execution epoch
// TODO (desired): permit slicing Topologies by key (though unnecessary if we eliminate the concept of non-participating home keys)
@@ -100,7 +100,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, ok.futureEpoch, deps, callback).start();
+ new ExecuteEphemeralRead(node, node.topology().preciseEpochs(route, ok.futureEpoch, ok.futureEpoch), 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 68bc99a5..7dcaa1c0 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
@@ -179,7 +179,7 @@ public abstract class ExecuteSyncPoint<U extends Unseekable> extends SettableRes
}
@Override
- public synchronized void onSuccess(Node.Id from, ReadReply reply)
+ public void onSuccess(Node.Id from, ReadReply reply)
{
if (reply instanceof ReadData.ReadOkWithFutureEpoch)
retryInFutureEpoch = Math.max(retryInFutureEpoch, ((ReadData.ReadOkWithFutureEpoch) reply).futureEpoch);
@@ -240,7 +240,7 @@ public abstract class ExecuteSyncPoint<U extends Unseekable> extends SettableRes
protected abstract void start();
@Override
- public synchronized void onSuccess(Node.Id from, ReadReply reply)
+ public void onSuccess(Node.Id from, ReadReply reply)
{
if (isDone()) return;
if (debug != null)
@@ -281,7 +281,7 @@ public abstract class ExecuteSyncPoint<U extends Unseekable> extends SettableRes
}
@Override
- public synchronized void onFailure(Node.Id from, Throwable failure)
+ public void onFailure(Node.Id from, Throwable failure)
{
if (isDone()) return;
if (debug != null)
diff --git a/accord-core/src/main/java/accord/coordinate/FetchCoordinator.java b/accord-core/src/main/java/accord/coordinate/FetchCoordinator.java
index 32447fb7..3f790d6c 100644
--- a/accord-core/src/main/java/accord/coordinate/FetchCoordinator.java
+++ b/accord-core/src/main/java/accord/coordinate/FetchCoordinator.java
@@ -142,7 +142,6 @@ public abstract class FetchCoordinator
private Ranges needed;
private int inflight;
- // TODO (required): use ExecuteExclusiveSyncPoint logic
protected FetchCoordinator(Node node, Ranges ranges, SyncPoint syncPoint, FetchRanges fetchRanges)
{
this.node = node;
@@ -151,8 +150,6 @@ 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)
- // TODO (required): the sourceEpoch may be wrong, as a transaction may execute in a future epoch
- // is this a problem on bootstrap? probably
Topology topology = node.topology().forEpoch(ranges, syncPoint.syncId.epoch()).get(0);
for (Node.Id id : topology.nodes())
{
diff --git a/accord-core/src/main/java/accord/coordinate/FetchData.java b/accord-core/src/main/java/accord/coordinate/FetchData.java
index 81c474d3..9fd41204 100644
--- a/accord-core/src/main/java/accord/coordinate/FetchData.java
+++ b/accord-core/src/main/java/accord/coordinate/FetchData.java
@@ -237,7 +237,7 @@ public class FetchData extends CheckShards<Route<?>>
case Erased:
case WasApply:
case Apply:
- // TODO (expected): we may be stale
+ // TODO (required): we may be stale
req.callback.accept(new FetchResult(found, req.fetchKeys.slice(0, 0), req.fetchKeys), null);
}
}
@@ -353,7 +353,7 @@ public class FetchData extends CheckShards<Route<?>>
if (success == ReadCoordinator.Success.Success)
Invariants.require(isSufficient(merged), "Status %s is not sufficient", merged);
- // TODO (expected): should we automatically trigger a new fetch if we find executeAt but did not request enough information? would be more rob ust
+ // TODO (expected): should we automatically trigger a new fetch if we find executeAt but did not request enough information? would be more robust
Propagate.propagate(node, txnId, previouslyKnownToBeInvalidIf, sourceEpoch, lowEpoch, highEpoch, success.withQuorum, query(), propagateTo, target, (CheckStatusOkFull) merged, callback);
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/Infer.java b/accord-core/src/main/java/accord/coordinate/Infer.java
index 41964860..cc50ffbb 100644
--- a/accord-core/src/main/java/accord/coordinate/Infer.java
+++ b/accord-core/src/main/java/accord/coordinate/Infer.java
@@ -171,7 +171,6 @@ public class Infer
{
// we're applying an invalidation, so the record will not be cleaned up until the whole range is truncated
Command command = safeCommand.current();
- // TODO (required, consider): consider the !command.hasBeen(PreCommitted) condition
Invariants.require(!command.hasBeen(PreCommitted) || command.hasBeen(Status.Truncated), "Unexpected status for %s", command);
Commands.commitInvalidate(safeStore, safeCommand, participants);
return null;
diff --git a/accord-core/src/main/java/accord/coordinate/Invalidate.java b/accord-core/src/main/java/accord/coordinate/Invalidate.java
index dc6a4700..87808210 100644
--- a/accord-core/src/main/java/accord/coordinate/Invalidate.java
+++ b/accord-core/src/main/java/accord/coordinate/Invalidate.java
@@ -106,7 +106,7 @@ public class Invalidate implements Callback<InvalidateReply>
}
@Override
- public synchronized void onSuccess(Id from, InvalidateReply reply)
+ public void onSuccess(Id from, InvalidateReply reply)
{
if (isDone || isPrepareDone)
return;
diff --git a/accord-core/src/main/java/accord/coordinate/MaybeRecover.java b/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
index d53b7273..19946120 100644
--- a/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
+++ b/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
@@ -68,7 +68,7 @@ public class MaybeRecover extends CheckShards<Route<?>>
public boolean hasMadeProgress(CheckStatusOk ok)
{
- // TODO (required, liveness): if Ballot.hlc is stale enough then preempt; also do not query isCoordinating, query directly the node that owns the ballot (or TxnId if Ballot is ZERO)
+ // TODO (required): if Ballot.hlc is stale enough then preempt; also do not query isCoordinating, query directly the node that owns the ballot (or TxnId if Ballot is ZERO)
return ok != null && (ok.isCoordinating
|| ok.toProgressToken().compareTo(prevProgress) > 0);
}
@@ -129,7 +129,6 @@ public class MaybeRecover extends CheckShards<Route<?>>
case WasApply:
case Erased:
// TODO (required): if we're home replica, don't want to cancel coordination without either invalidating or applying unless we're stale
- // TODO (required): on Erased, should we maybe mark stale, or leave to FetchData?
callback.accept(full.toProgressToken(), null);
break;
diff --git a/accord-core/src/main/java/accord/coordinate/Propose.java b/accord-core/src/main/java/accord/coordinate/Propose.java
index 3c7be52a..b190550a 100644
--- a/accord-core/src/main/java/accord/coordinate/Propose.java
+++ b/accord-core/src/main/java/accord/coordinate/Propose.java
@@ -52,7 +52,7 @@ 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.Status.AcceptedInvalidate;
-import static accord.primitives.TxnId.MediumPath.TRACK_STABLE;
+import static accord.primitives.TxnId.MediumPath.TrackStable;
import static accord.utils.Invariants.debug;
abstract class Propose<R> implements Callback<AcceptReply>
@@ -86,6 +86,7 @@ abstract class Propose<R> implements Callback<AcceptReply>
this.acceptTracker = new QuorumTracker(topologies);
Invariants.require(txnId.isSyncPoint() || deps.maxTxnId(txnId).compareTo(executeAt) <= 0,
"Attempted to propose %s with an earlier executeAt than a conflicting transaction it witnessed: %s vs executeAt: %s", txnId, deps, executeAt);
+ Invariants.require(topologies.currentEpoch() == executeAt.epoch());
}
void start()
@@ -145,7 +146,7 @@ abstract class Propose<R> implements Callback<AcceptReply>
if (isDone)
return;
- // TODO (expected): we aren't tracking the specific failure here to report
+ // TODO (required): we aren't tracking the specific failure here to report
if (acceptTracker.recordFailure(from) == Failed)
{
isDone = true;
@@ -166,15 +167,14 @@ abstract class Propose<R> implements Callback<AcceptReply>
void onAccepted()
{
- // TODO (desired): can we avoid merging on original preaccept? Would be nice to be able to reduce range txn dep calculation cost.
+ // TODO (desired): can we avoid merging on original accept? Would be nice to be able to reduce range txn dep calculation cost (by not including PreLoadContext).
// 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);
+ 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);
+ if (!Invariants.debug()) acceptOks.clear();
}
Deps mergeDeps()
@@ -183,7 +183,7 @@ abstract class Propose<R> implements Callback<AcceptReply>
if (Faults.discardPreAcceptDeps(txnId))
return deps;
- if (txnId.is(TRACK_STABLE))
+ if (txnId.is(TrackStable))
{
// we must not propose as stable any dep < txnId that we did not witness in our original preaccept
if (!filterDuplicateDependenciesFromAcceptReply())
diff --git a/accord-core/src/main/java/accord/coordinate/Recover.java b/accord-core/src/main/java/accord/coordinate/Recover.java
index 9b582b89..8dab98c4 100644
--- a/accord-core/src/main/java/accord/coordinate/Recover.java
+++ b/accord-core/src/main/java/accord/coordinate/Recover.java
@@ -84,7 +84,7 @@ 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.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
import static accord.utils.Invariants.illegalState;
import static accord.utils.SortedArrays.Search.CEIL;
import static accord.utils.SortedArrays.Search.FLOOR;
@@ -208,7 +208,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
}
@Override
- public synchronized void onSuccess(Id from, RecoverReply reply)
+ public void onSuccess(Id from, RecoverReply reply)
{
if (isDone || isBallotPromised)
return;
@@ -219,7 +219,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
default: throw new AssertionError("Unhandled RecoverReply.Kind: " + reply.kind());
case Reject:
case Truncated:
- // TODO (expected): handle partial truncation
+ // TODO (required): handle partial truncations (both within a shard e.g. pre-bootstrap, and for some shards)
accept(null, new Preempted(txnId, route.homeKey()));
return;
@@ -426,10 +426,14 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
private static InferredFastPath merge(InferredFastPath a, InferredFastPath b)
{
- boolean accept = a == InferredFastPath.Accept || b == InferredFastPath.Accept;
- boolean reject = a == Reject || b == Reject;
- Invariants.require(!accept || !reject);
- return accept ? InferredFastPath.Accept : reject ? Reject : Unknown;
+ if (a == Unknown || b == Unknown)
+ return a == Unknown ? b : a;
+
+ // we CAN encounter both Reject AND Accept in the event we are a stale recovery attempt, and a "later" recovery
+ // has already invalidated us, due to witnessing a different quorum
+ // (e.g. witnessing the privileged coordinator so knew we did not take fast path, even if we could have done).
+ // So, we just take the Reject unless both are A
+ return a == b ? a : Reject;
}
private static Participants<?> extraCoordinatorVotes(TxnId txnId, boolean coordinatorInQuorum, List<RecoverOk> oks)
@@ -595,7 +599,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
for (int i = 0 ; i < waitOn.txnIdCount() ; ++i)
{
TxnId awaitId = waitOn.txnId(i);
- Invariants.require(awaitId.is(PRIVILEGED_COORDINATOR_WITH_DEPS));
+ Invariants.require(awaitId.is(PrivilegedCoordinatorWithDeps));
Invariants.require(awaitId.compareTo(recoverId) > 0);
Participants<?> participants = waitOn.participants(awaitId)
.intersecting(reliesOnAwaitIdCoordVote, Minimal);
diff --git a/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java b/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
index 48daae7d..eddec2e2 100644
--- a/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
+++ b/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
@@ -165,7 +165,6 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
}
else if (!known.definition().isOrWasKnown())
{
- // TODO (required): this logic should be put in Infer, alongside any similar inferences in Recover
if (witnessedByInvalidation != null && witnessedByInvalidation.compareTo(Status.PreAccepted) > 0)
throw illegalState("We previously invalidated, finding a status that should be recoverable");
Invalidate.invalidate(node, txnId, route, witnessedByInvalidation != null, reportLowEpoch, reportHighEpoch, callback);
@@ -227,7 +226,6 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
}
else
{
- // TODO (expected): tighten up / centralise this implication, perhaps in Infer
propagate = full.merge(Majority);
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/tracking/FastPathTracker.java b/accord-core/src/main/java/accord/coordinate/tracking/FastPathTracker.java
index fe22dbfd..5680b531 100644
--- a/accord-core/src/main/java/accord/coordinate/tracking/FastPathTracker.java
+++ b/accord-core/src/main/java/accord/coordinate/tracking/FastPathTracker.java
@@ -34,9 +34,9 @@ import javax.annotation.Nonnull;
import java.util.function.BiFunction;
import static accord.coordinate.tracking.AbstractTracker.ShardOutcomes.*;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITHOUT_DEPS;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
-import static accord.primitives.TxnId.FastPath.UNOPTIMISED;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithoutDeps;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
+import static accord.primitives.TxnId.FastPath.Unoptimised;
// TODO (desired, efficiency): if any shard *cannot* take the fast path, and all shards have accepted, terminate
public class FastPathTracker extends PreAcceptTracker<FastPathTracker.FastPathShardTracker>
@@ -246,9 +246,9 @@ public class FastPathTracker extends PreAcceptTracker<FastPathTracker.FastPathSh
switch (txnId.fastPath())
{
default: throw new UnhandledEnum(txnId.fastPath());
- case UNOPTIMISED: return (i, s) -> create(UNOPTIMISED, i, s);
- case PRIVILEGED_COORDINATOR_WITHOUT_DEPS: return (i, s) -> create(PRIVILEGED_COORDINATOR_WITHOUT_DEPS, i, s);
- case PRIVILEGED_COORDINATOR_WITH_DEPS: return (i, s) -> create(PRIVILEGED_COORDINATOR_WITH_DEPS, i, s);
+ case Unoptimised: return (i, s) -> create(Unoptimised, i, s);
+ case PrivilegedCoordinatorWithoutDeps: return (i, s) -> create(PrivilegedCoordinatorWithoutDeps, i, s);
+ case PrivilegedCoordinatorWithDeps: return (i, s) -> create(PrivilegedCoordinatorWithDeps, i, s);
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/tracking/InvalidationTracker.java b/accord-core/src/main/java/accord/coordinate/tracking/InvalidationTracker.java
index 3b470594..cac5e195 100644
--- a/accord-core/src/main/java/accord/coordinate/tracking/InvalidationTracker.java
+++ b/accord-core/src/main/java/accord/coordinate/tracking/InvalidationTracker.java
@@ -30,9 +30,9 @@ import accord.topology.Topologies;
import accord.utils.UnhandledEnum;
import static accord.coordinate.tracking.AbstractTracker.ShardOutcomes.*;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITHOUT_DEPS;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
-import static accord.primitives.TxnId.FastPath.UNOPTIMISED;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithoutDeps;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
+import static accord.primitives.TxnId.FastPath.Unoptimised;
public class InvalidationTracker extends AbstractTracker<InvalidationTracker.InvalidationShardTracker>
{
@@ -197,9 +197,9 @@ public class InvalidationTracker extends AbstractTracker<InvalidationTracker.Inv
switch (txnId.fastPath())
{
default: throw new UnhandledEnum(txnId.fastPath());
- case UNOPTIMISED: return (i, s) -> new InvalidationShardTracker(UNOPTIMISED, s);
- case PRIVILEGED_COORDINATOR_WITHOUT_DEPS: return (i, s) -> new InvalidationShardTracker(PRIVILEGED_COORDINATOR_WITHOUT_DEPS, s);
- case PRIVILEGED_COORDINATOR_WITH_DEPS: return (i, s) -> new InvalidationShardTracker(PRIVILEGED_COORDINATOR_WITH_DEPS, s);
+ case Unoptimised: return (i, s) -> new InvalidationShardTracker(Unoptimised, s);
+ case PrivilegedCoordinatorWithoutDeps: return (i, s) -> new InvalidationShardTracker(PrivilegedCoordinatorWithoutDeps, s);
+ case PrivilegedCoordinatorWithDeps: return (i, s) -> new InvalidationShardTracker(PrivilegedCoordinatorWithDeps, s);
}
}
}
diff --git a/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java b/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
index 5aa30347..41d543bb 100644
--- a/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
+++ b/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
@@ -158,7 +158,7 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
if (reply != Redundant)
throw new UnhandledEnum((CommitOrReadNack)reply);
// too late, sync point has been erased
- // TODO (expected): stop fetch sync points from garbage collecting too quickly
+ // TODO (desired): stop fetch sync points from garbage collecting too quickly
}
return;
}
@@ -180,7 +180,7 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
received = ranges;
}
- // TODO (required): make sure it works if invoked in either order
+ // TODO (expected): make sure it works if invoked in either order
inflight.remove(key).started(ok.safeToReadAfter);
onReadOk(to, commandStore, ok.data, received);
// received must be invoked after submitting the persistence future, as it triggers onDone
@@ -197,7 +197,7 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
@Override
public boolean onCallbackFailure(Node.Id from, Throwable failure)
{
- // TODO (soon)
+ // TODO (required): improve this
logger.error("Fetch coordination failure from " + from, failure);
return true;
}
diff --git a/accord-core/src/main/java/accord/impl/CommandChange.java b/accord-core/src/main/java/accord/impl/CommandChange.java
index 0ec5d9c9..0b7115b0 100644
--- a/accord-core/src/main/java/accord/impl/CommandChange.java
+++ b/accord-core/src/main/java/accord/impl/CommandChange.java
@@ -72,7 +72,6 @@ import static accord.local.Command.NotDefined.uninitialised;
import static accord.local.Command.PreAccepted.preaccepted;
import static accord.local.Command.Truncated.erased;
import static accord.local.Command.Truncated.invalidated;
-import static accord.local.Command.Truncated.truncatedApply;
import static accord.local.Command.Truncated.vestigial;
import static accord.local.StoreParticipants.Filter.LOAD;
import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
@@ -425,9 +424,9 @@ public class CommandChange
{
default: throw new UnhandledEnum(status);
case TruncatedApplyWithOutcome:
- case TruncatedApplyWithDeps:
case TruncatedApply:
- return truncatedApply(txnId, status, durability, participants, executeAt, writes, result, executesAtLeast);
+ case TruncatedUnapplied:
+ return Command.Truncated.truncated(txnId, status, durability, participants, executeAt, writes, result, executesAtLeast);
case Vestigial:
return vestigial(txnId, participants);
case Erased:
diff --git a/accord-core/src/main/java/accord/impl/DefaultLocalListeners.java b/accord-core/src/main/java/accord/impl/DefaultLocalListeners.java
index 0bb86f72..541366fc 100644
--- a/accord-core/src/main/java/accord/impl/DefaultLocalListeners.java
+++ b/accord-core/src/main/java/accord/impl/DefaultLocalListeners.java
@@ -39,7 +39,7 @@ import accord.utils.Invariants;
import accord.utils.btree.BTree;
import accord.utils.btree.BTreeRemoval;
-// TODO (expected): evict to disk
+// TODO (desired): evict to disk
public class DefaultLocalListeners implements LocalListeners
{
public static class Factory implements LocalListeners.Factory
@@ -92,9 +92,7 @@ public class DefaultLocalListeners implements LocalListeners
safeStore = safeStore; // prevent use in lambda
TxnId updatedId = safeCommand.txnId();
PreLoadContext context = PreLoadContext.contextFor(listenerId, updatedId);
- safeStore.commandStore()
- .execute(context, safeStore0 -> notify(safeStore0, listenerId, updatedId))
- .begin(safeStore.agent());
+ safeStore.commandStore().execute(context, safeStore0 -> notify(safeStore0, listenerId, updatedId), safeStore.agent());
}
}
@@ -473,7 +471,6 @@ public class DefaultLocalListeners implements LocalListeners
private void notifyComplexListeners(SafeCommandStore safeStore, SafeCommand safeCommand)
{
- // TODO (expected): potential for lock inversion on notify calls; consider buffering notifies as we do elsewhere
complexListeners.compute(safeCommand.txnId(), (id, cur) -> {
if (cur == null)
return null;
@@ -495,7 +492,7 @@ public class DefaultLocalListeners implements LocalListeners
SaveStatus saveStatus = safeCommand.current().saveStatus();
Invariants.require(saveStatus.compareTo(entry.await) >= 0);
entry.notify(notifySink, safeStore, safeCommand);
- }).begin(commandStore.agent());
+ }, commandStore.agent());
txnListeners = BTreeRemoval.remove(txnListeners, TxnListeners::compareListeners, entry);
}
}
diff --git a/accord-core/src/main/java/accord/impl/DefaultRemoteListeners.java b/accord-core/src/main/java/accord/impl/DefaultRemoteListeners.java
index 617a5451..ddcf10ba 100644
--- a/accord-core/src/main/java/accord/impl/DefaultRemoteListeners.java
+++ b/accord-core/src/main/java/accord/impl/DefaultRemoteListeners.java
@@ -35,7 +35,6 @@ import accord.primitives.Route;
import accord.primitives.TxnId;
import accord.utils.Invariants;
-// TODO (expected): evict to disk
public class DefaultRemoteListeners implements RemoteListeners
{
public interface NotifySink
diff --git a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
index 2a6e8c25..6c4f642c 100644
--- a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
+++ b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
@@ -59,7 +59,6 @@ import accord.local.Commands;
import accord.local.KeyHistory;
import accord.local.NodeCommandStoreService;
import accord.local.PreLoadContext;
-import accord.local.RedundantBefore;
import accord.local.RejectBefore;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
@@ -90,6 +89,7 @@ import org.agrona.collections.ObjectHashSet;
import static accord.local.Cleanup.Input.FULL;
import static accord.local.KeyHistory.ASYNC;
+import static accord.local.RedundantStatus.Coverage.ALL;
import static accord.primitives.Known.KnownRoute.MaybeRoute;
import static accord.primitives.Routable.Domain.Range;
import static accord.primitives.Routables.Slice.Minimal;
@@ -284,7 +284,7 @@ public abstract class InMemoryCommandStore extends CommandStore
for (TxnId txnId : clearing)
{
GlobalCommand globalCommand = commands.get(txnId);
-; Invariants.require(globalCommand != null && !globalCommand.isEmpty());
+ Invariants.require(globalCommand != null && !globalCommand.isEmpty());
Command command = globalCommand.value();
Cleanup cleanup = Cleanup.shouldCleanup(FULL, agent, txnId, command.executeAt(), command.saveStatus(), command.durability(), command.participants(), unsafeGetRedundantBefore(), durableBefore());
Invariants.require(command.hasBeen(Applied)
@@ -433,22 +433,6 @@ public abstract class InMemoryCommandStore extends CommandStore
}
}
- private static Timestamp maxApplied(SafeCommandStore safeStore, Unseekables<?> keysOrRanges, Ranges slice)
- {
- Timestamp max = ((InMemoryCommandStore)safeStore.commandStore()).maxRedundant;
- for (GlobalCommand command : ((InMemoryCommandStore) safeStore.commandStore()).commands.values())
- {
- if (command.value().hasBeen(Applied))
- max = Timestamp.max(command.value().executeAt(), max);
- }
- return max;
- }
-
- public AsyncChain<Timestamp> maxAppliedFor(Unseekables<?> keysOrRanges, Ranges slice)
- {
- return submit(PreLoadContext.contextFor(keysOrRanges), safeStore -> maxApplied(safeStore, keysOrRanges, slice));
- }
-
@Override
public String toString()
{
@@ -681,7 +665,7 @@ public abstract class InMemoryCommandStore extends CommandStore
if (txnId.domain() != Domain.Range)
return;
- // TODO (expected): consider removing if erased
+ // TODO (testing): consider removing if erased
if (updated.saveStatus() == Erased || updated.saveStatus() == Vestigial)
return;
@@ -797,7 +781,6 @@ public abstract class InMemoryCommandStore extends CommandStore
commandsForRanges().visit(keysOrRanges, startedBefore, testKind, visitor, p1, p2);
}
- // TODO (expected): instead of accepting a slice, accept the min/max epoch and let implementation handle it
@Override
public boolean visit(Unseekables<?> keysOrRanges, TxnId testTxnId, Kinds testKind, TestStartedAt testStartedAt, Timestamp testStartedAtTimestamp, ComputeIsDep computeIsDep, AllCommandVisitor visit)
{
@@ -822,7 +805,7 @@ public abstract class InMemoryCommandStore extends CommandStore
Participants<?> intersecting = txnId.is(ExclusiveSyncPoint) ? command.participants().owns().intersecting(updated.participants().touches(), Minimal)
: command.participants().stillExecutes().intersecting(covering, Minimal);
if (intersecting.isEmpty()) continue;
- if (commandStore().unsafeGetRedundantBefore().preBootstrapOrStale(command.txnId(), intersecting) == RedundantBefore.PreBootstrapOrStale.FULLY) continue;
+ if (commandStore().unsafeGetRedundantBefore().preBootstrapOrStale(command.txnId(), intersecting) == ALL) continue;
illegalState();
}
}
@@ -876,13 +859,13 @@ public abstract class InMemoryCommandStore extends CommandStore
}
@Override
- public AsyncChain<Void> execute(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
+ public AsyncChain<Void> build(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
{
- return submit(context, i -> { consumer.accept(i); return null; });
+ return build(context, i -> { consumer.accept(i); return null; });
}
@Override
- public <T> AsyncChain<T> submit(PreLoadContext context, Function<? super SafeCommandStore, T> function)
+ public <T> AsyncChain<T> build(PreLoadContext context, Function<? super SafeCommandStore, T> function)
{
return new AsyncChains.Head<T>()
{
@@ -957,13 +940,13 @@ public abstract class InMemoryCommandStore extends CommandStore
}
@Override
- public AsyncChain<Void> execute(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
+ public AsyncChain<Void> build(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
{
- return submit(context, i -> { consumer.accept(i); return null; });
+ return build(context, i -> { consumer.accept(i); return null; });
}
@Override
- public <T> AsyncChain<T> submit(PreLoadContext context, Function<? super SafeCommandStore, T> function)
+ public <T> AsyncChain<T> build(PreLoadContext context, Function<? super SafeCommandStore, T> function)
{
return AsyncChains.ofCallable(executor, () -> executeInContext(this, context, function));
}
diff --git a/accord-core/src/main/java/accord/impl/RequestCallbacks.java b/accord-core/src/main/java/accord/impl/RequestCallbacks.java
index aa61d022..81fccf23 100644
--- a/accord-core/src/main/java/accord/impl/RequestCallbacks.java
+++ b/accord-core/src/main/java/accord/impl/RequestCallbacks.java
@@ -33,7 +33,6 @@ import org.agrona.collections.Long2ObjectHashMap;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
-// TODO (expected): tie shards to an AccordExecutor
public class RequestCallbacks extends AbstractTimeouts<RequestCallbacks.CallbackStripe>
{
private static final Logger logger = LoggerFactory.getLogger(RequestCallbacks.class);
diff --git a/accord-core/src/main/java/accord/impl/progresslog/CallbackInvoker.java b/accord-core/src/main/java/accord/impl/progresslog/CallbackInvoker.java
index 5018001d..c1c155e0 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/CallbackInvoker.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/CallbackInvoker.java
@@ -82,7 +82,7 @@ class CallbackInvoker<P, V> implements BiConsumer<V, Throwable>
callback.callback(safeStore, safeCommand, owner, txnId, param, success, fail);
owner.undebugActive(this);
- }).begin(owner.commandStore.agent());
+ }, owner.commandStore.agent());
}
@Override
diff --git a/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java b/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
index 9d7f1703..03a8e769 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
@@ -45,6 +45,7 @@ import accord.primitives.ProgressToken;
import accord.primitives.Ranges;
import accord.primitives.Route;
import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
import accord.utils.Invariants;
import accord.utils.LogGroupTimers;
import accord.utils.btree.BTree;
@@ -64,6 +65,8 @@ import static accord.impl.progresslog.Progress.Querying;
import static accord.impl.progresslog.Progress.Queued;
import static accord.impl.progresslog.TxnStateKind.Home;
import static accord.impl.progresslog.TxnStateKind.Waiting;
+import static accord.local.Command.NotDefined.uninitialised;
+import static accord.local.PreLoadContext.empty;
import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Status.PreApplied;
import static accord.primitives.Status.PreCommitted;
@@ -72,8 +75,8 @@ import static accord.utils.ArrayBuffers.cachedAny;
import static accord.utils.btree.UpdateFunction.noOpReplace;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
-// TODO (required): for transactions that span multiple progress logs (notably: sync points) we need to coordinate *fetching* to avoid redundant work
-public class DefaultProgressLog implements ProgressLog, Runnable
+// TODO (expected): for transactions that span multiple progress logs (notably: sync points) we need to coordinate *fetching* to avoid redundant work
+public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStore>
{
private static final Logger logger = LoggerFactory.getLogger(DefaultProgressLog.class);
@@ -322,7 +325,7 @@ public class DefaultProgressLog implements ProgressLog, Runnable
TxnId txnId = state.txnId;
safeStore.commandStore().execute(txnId, safeStore0 -> {
safeStore0.unsafeGet(txnId);
- }).begin(node.agent());
+ }, node.agent());
}
if (state.txnId.compareTo(clearAllBefore) < 0)
@@ -386,8 +389,8 @@ public class DefaultProgressLog implements ProgressLog, Runnable
if (!blockedBy.txnId().isVisible())
return;
- blockedBy.initialise();
Command command = blockedBy.current();
+ if (command == null) command = uninitialised(blockedBy.txnId());
SaveStatus saveStatus = command.saveStatus();
Invariants.require(saveStatus.compareTo(blockedUntil.unblockedFrom) < 0);
@@ -447,7 +450,7 @@ public class DefaultProgressLog implements ProgressLog, Runnable
}
@Override
- public void run()
+ public void accept(@Nullable SafeCommandStore safeStore)
{
long nowMicros = node.elapsed(TimeUnit.MICROSECONDS);
try
@@ -458,13 +461,17 @@ public class DefaultProgressLog implements ProgressLog, Runnable
return;
}
- processAwaitingEpoch();
- // drain to a buffer to avoid reentrancy in timers
- runBuffer = EMPTY_RUN_BUFFER;
- runBufferCount = 0;
- timers.advance(nowMicros, this, DefaultProgressLog::addToRunBuffer);
- processRunBuffer(nowMicros);
- cachedAny().forceDiscard(runBuffer, runBufferCount);
+ try (BufferList<RunInvoker> readyToRun = safeStore == null ? null : new BufferList<>())
+ {
+ processAwaitingEpoch(safeStore, readyToRun);
+ // drain to a buffer to avoid reentrancy in timers
+ runBuffer = EMPTY_RUN_BUFFER;
+ runBufferCount = 0;
+ timers.advance(nowMicros, this, DefaultProgressLog::addToRunBuffer);
+ processRunBuffer(safeStore, nowMicros, readyToRun);
+ cachedAny().forceDiscard(runBuffer, runBufferCount);
+ processReadyToRun(safeStore, readyToRun);
+ }
if (awaitingEpochBufferCount > 0)
rerunWithPendingEpoch();
}
@@ -491,16 +498,16 @@ public class DefaultProgressLog implements ProgressLog, Runnable
minEpoch = Math.min(awaitingEpochBuffer[i].run.txnId.epoch(), minEpoch);
Invariants.requireArgument(minEpoch != Long.MAX_VALUE);
isAwaitingEpoch = true;
- node.withEpoch(minEpoch, (success, fail) -> commandStore.execute(() -> {
+ node.withEpoch(minEpoch, (success, fail) -> commandStore.execute(empty(), ss -> {
isAwaitingEpoch = false;
- run();
- }));
+ accept(ss);
+ }, node.agent()));
}
- // TODO (expected): invoke immediately if the command is already loaded
- private void processRunBuffer(long nowMicros)
+ private void processRunBuffer(@Nullable SafeCommandStore safeStore, long nowMicros, List<RunInvoker> readyToRun)
{
long hasEpoch = node.topology().epoch();
+
for (int i = 0; i < runBufferCount; ++i)
{
TxnState run = (TxnState) runBuffer[i];
@@ -526,8 +533,8 @@ public class DefaultProgressLog implements ProgressLog, Runnable
long epoch = run.txnId.epoch();
if (epoch <= hasEpoch)
{
- invoke(invoker(run, runKind));
- if (invokeBoth) invoke(invoker(run, runKind.other()));
+ addIfReadyElseSubmit(safeStore, invoker(run, runKind), readyToRun);
+ if (invokeBoth) addIfReadyElseSubmit(safeStore, invoker(run, runKind.other()), readyToRun);
}
else
{
@@ -543,14 +550,17 @@ public class DefaultProgressLog implements ProgressLog, Runnable
runBufferCount = 0;
}
- private void processAwaitingEpoch()
+ private void processAwaitingEpoch(@Nullable SafeCommandStore safeStore, List<RunInvoker> readyToRun)
{
+ if (awaitingEpochBufferCount == 0)
+ return;
+
long hasEpoch = node.topology().epoch();
int retainCount = 0;
for (int i = 0 ; i < awaitingEpochBufferCount ; ++i)
{
RunInvoker awaiting = awaitingEpochBuffer[i];
- if (awaiting.run.txnId.epoch() <= hasEpoch) invoke(awaiting);
+ if (awaiting.run.txnId.epoch() <= hasEpoch) addIfReadyElseSubmit(safeStore, awaiting, readyToRun);
else awaitingEpochBuffer[retainCount++] = awaiting;
}
awaitingEpochBufferCount = retainCount;
@@ -558,16 +568,43 @@ public class DefaultProgressLog implements ProgressLog, Runnable
else if (retainCount < awaitingEpochBuffer.length / 2) awaitingEpochBuffer = Arrays.copyOf(awaitingEpochBuffer, retainCount);
}
+ private void processReadyToRun(SafeCommandStore safeStore, List<RunInvoker> readyToRun)
+ {
+ if (safeStore == null || readyToRun.isEmpty())
+ return;
+
+ int i = 0;
+ try
+ {
+ while (i < readyToRun.size())
+ readyToRun.get(i++).accept(safeStore);
+ }
+ finally
+ {
+ while (i < readyToRun.size())
+ {
+ commandStore.execute(empty(), readyToRun.get(i++), node.agent());
+ }
+ }
+ }
+
private void validatePreRunState(TxnState run, TxnStateKind kind)
{
Progress progress = kind == Waiting ? run.waiting().waitingProgress() : run.home().homeProgress();
Invariants.require(progress != NoneExpected && progress != Querying);
}
- void invoke(RunInvoker invoker)
+ void addIfReadyElseSubmit(@Nullable SafeCommandStore safeStore, RunInvoker invoker, List<RunInvoker> ifReady)
{
- commandStore.execute(invoker.run.txnId, invoker)
- .begin(commandStore.agent());
+ if (safeStore != null && safeStore.canExecuteWith(invoker.run.txnId))
+ {
+ ifReady.add(invoker);
+ }
+ else
+ {
+ // TODO (required): if we fail execution, do we need to reschedule the state?
+ commandStore.execute(invoker.run.txnId, invoker, commandStore.agent());
+ }
}
RunInvoker invoker(TxnState run, TxnStateKind runKind)
@@ -706,13 +743,13 @@ public class DefaultProgressLog implements ProgressLog, Runnable
{
if (commandStore.inStore())
{
- run();
+ accept(null);
}
else
{
long now = node.elapsed(MICROSECONDS);
if (timers.shouldWake(now))
- commandStore.execute(this);
+ commandStore.execute(empty(), this, node.agent());
}
}
diff --git a/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLogs.java b/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLogs.java
index 8ca59d6c..5453f19f 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLogs.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLogs.java
@@ -26,6 +26,8 @@ import accord.api.ProgressLog;
import accord.local.CommandStore;
import accord.local.Node;
+import static accord.local.PreLoadContext.empty;
+
// TODO (desired, consider): consider propagating invalidations in the same way as we do applied
// TODO (expected): report transactions not making progress
// TODO (expected): evict to disk
@@ -54,7 +56,7 @@ public class DefaultProgressLogs implements ProgressLog.Factory
return false;
if (!paused.containsKey(progressLog))
- paused.putIfAbsent(progressLog, () -> progressLog.commandStore.execute(progressLog));
+ paused.putIfAbsent(progressLog, () -> progressLog.commandStore.execute(empty(), progressLog, progressLog.commandStore.agent()));
return true;
}
diff --git a/accord-core/src/main/java/accord/local/Bootstrap.java b/accord-core/src/main/java/accord/local/Bootstrap.java
index 609217fe..9eea42aa 100644
--- a/accord-core/src/main/java/accord/local/Bootstrap.java
+++ b/accord-core/src/main/java/accord/local/Bootstrap.java
@@ -122,7 +122,7 @@ class Bootstrap
if (!node.topology().hasEpoch(globalSyncId.epoch()))
{
// Ignore timeouts fetching the epoch, always keep trying to bootstrap
- node.withEpoch(globalSyncId.epoch(), (ignored, failure) -> store.execute(empty(), Attempt.this::start).begin((ignored1, failure2) -> {
+ node.withEpoch(globalSyncId.epoch(), (ignored, failure) -> store.execute(empty(), Attempt.this::start, (ignored1, failure2) -> {
if (failure2 != null)
node.agent().acceptAndWrap(null, failure2);
}));
@@ -135,12 +135,12 @@ class Bootstrap
safeStore = safeStore;
// we submit a separate execution so that we know markBootstrapping is durable before we initiate the fetch
safeStore.commandStore()
- .submit(empty(), safeStore0 -> {
+ .build(empty(), safeStore0 -> {
store.markBootstrapping(safeStore0, globalSyncId, commitRanges);
return CoordinateSyncPoint.exclusiveSyncPoint(node, globalSyncId, commitRanges);
})
.flatMap(i -> i)
- .flatMap(syncPoint -> node.withEpoch(epoch, () -> store.submit(empty(), safeStore1 -> {
+ .flatMap(syncPoint -> node.withEpoch(epoch, () -> store.build(empty(), safeStore1 -> {
if (valid.isEmpty()) // we've lost ownership of the range
return AsyncResults.success(Ranges.EMPTY);
return fetch = safeStore1.dataStore().fetch(node, safeStore1, valid, syncPoint, this);
@@ -270,7 +270,7 @@ class Bootstrap
accept(null, failure);
store.agent().onFailedBootstrap("PartialFetch", newFailures, () -> {
- store.execute(empty(), safeStore -> restart(safeStore, newFailures.slice(allValid))).begin(store.agent());
+ store.execute(empty(), safeStore -> restart(safeStore, newFailures.slice(allValid)), store.agent());
}, failure);
Invariants.require(!newFailures.intersects(fetchedAndSafeToRead));
}
@@ -307,9 +307,9 @@ class Bootstrap
if (completed)
return;
- // TODO (now): we don't need this method, as we should have the user implementation invoke us as necessary
- // at most this should interpret failure to account for non-fetch related breakages
- // so as to schedule a retry
+ // TODO (desired): we shouldn't need this method, as we should have the user implementation invoke us as necessary
+ // at most this should interpret failure to account for non-fetch related breakages
+ // so as to schedule a retry
synchronized (this)
{
fetchCompleted = true;
@@ -344,7 +344,7 @@ class Bootstrap
if (!retry.isEmpty())
{
store.agent().onFailedBootstrap("Fetch", retry, () -> {
- store.execute(empty(), safeStore -> restart(safeStore, retry)).begin(node.agent());
+ store.execute(empty(), safeStore -> restart(safeStore, retry), node.agent());
}, fetchOutcome);
}
}
diff --git a/accord-core/src/main/java/accord/local/Cleanup.java b/accord-core/src/main/java/accord/local/Cleanup.java
index 1244eb31..f6a4f829 100644
--- a/accord-core/src/main/java/accord/local/Cleanup.java
+++ b/accord-core/src/main/java/accord/local/Cleanup.java
@@ -23,20 +23,29 @@ import javax.annotation.Nonnull;
import accord.api.Agent;
import accord.primitives.FullRoute;
import accord.primitives.Participants;
+import accord.primitives.Ranges;
import accord.primitives.Route;
import accord.primitives.SaveStatus;
import accord.primitives.Status.Durability;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
+import accord.utils.Invariants;
import accord.utils.UnhandledEnum;
import static accord.api.ProtocolModifiers.Toggles.requiresUniqueHlcs;
import static accord.local.Cleanup.Input.FULL;
import static accord.local.Cleanup.Input.PARTIAL;
-import static accord.local.RedundantBefore.PreBootstrapOrStale.FULLY;
-import static accord.local.RedundantStatus.NOT_OWNED;
-import static accord.local.RedundantStatus.TRUNCATE_BEFORE;
+import static accord.local.RedundantStatus.Coverage.ALL;
+import static accord.local.RedundantStatus.Property.GC_BEFORE;
+import static accord.local.RedundantStatus.Property.LOCALLY_APPLIED;
+import static accord.local.RedundantStatus.Property.LOCALLY_DEFUNCT;
+import static accord.local.RedundantStatus.Property.LOCALLY_REDUNDANT;
+import static accord.local.RedundantStatus.Property.NOT_OWNED;
+import static accord.local.RedundantStatus.Property.SHARD_APPLIED_AND_LOCALLY_REDUNDANT;
+import static accord.local.RedundantStatus.Property.SHARD_APPLIED_ONLY;
+import static accord.local.RedundantStatus.Property.TRUNCATE_BEFORE;
import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
+import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.SaveStatus.Erased;
import static accord.primitives.SaveStatus.Invalidated;
import static accord.primitives.SaveStatus.TruncatedApply;
@@ -46,11 +55,11 @@ import static accord.primitives.SaveStatus.Vestigial;
import static accord.primitives.Status.Applied;
import static accord.primitives.Status.Durability.UniversalOrInvalidated;
import static accord.primitives.Status.PreCommitted;
+import static accord.primitives.Status.Truncated;
import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Txn.Kind.EphemeralRead;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.primitives.Txn.Kind.Write;
-import static accord.utils.Invariants.illegalState;
+import static accord.primitives.TxnId.Cardinality.Any;
/**
* Logic related to whether metadata about transactions is safe to discard given currently available information.
@@ -61,7 +70,6 @@ public enum Cleanup
NO(Uninitialised),
// we don't know if the command has been applied or invalidated as we have incomplete information
// so erase what information we don't need in future to decide this
- // TODO (required): tighten up semantics here (and maybe infer more aggressively)
TRUNCATE_WITH_OUTCOME(TruncatedApplyWithOutcome),
TRUNCATE(TruncatedApply),
VESTIGIAL(Vestigial),
@@ -135,8 +143,6 @@ public enum Cleanup
* If we know a transaction is invalidated, but don't know its FullRoute,
* we pessimistically assume the whole cluster may need to see its outcome
* TODO (expected): we should be able to rely on replicas to infer Invalidated from an Erased record
- * </p>
- *
*/
private static Cleanup shouldCleanupInternal(Input input, Agent agent, TxnId txnId, Timestamp executeAt, SaveStatus saveStatus, Durability durability, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
@@ -149,139 +155,119 @@ public enum Cleanup
if (participants == null)
return NO;
- if (!participants.hasFullRoute())
- return cleanupIfUndecided(input, txnId, saveStatus, participants, redundantBefore);
+ if (participants.hasFullRoute())
+ return cleanupWithFullRoute(input, agent, participants, txnId, executeAt, saveStatus, durability, redundantBefore, durableBefore);
+ return cleanupWithoutFullRoute(input, txnId, saveStatus, participants, redundantBefore, durableBefore);
+ }
+
+ private static Cleanup cleanupWithFullRoute(Input input, Agent agent, StoreParticipants participants, TxnId txnId, Timestamp executeAt, SaveStatus saveStatus, Durability durability, RedundantBefore redundantBefore, DurableBefore durableBefore)
+ {
+ // We first check if the command is redundant locally, i.e. whether it has been applied to all non-faulty replicas of the local shard
+ // If not, we don't want to truncate its state else we may make catching up for these other replicas much harder
+ FullRoute<?> route = Route.castToFullRoute(participants.route());
+ if (!saveStatus.known.is(ApplyAtKnown)) executeAt = null;
+ RedundantStatus redundant = redundantBefore.status(txnId, executeAt, route);
+ Invariants.require(redundant.none(NOT_OWNED),"Command " + txnId + " that is being loaded is not owned by this shard on route " + route);
- return cleanupWithFullRoute(input, agent, participants, txnId, executeAt, saveStatus, durability, redundantBefore, durableBefore);
+ if (redundant.none(LOCALLY_REDUNDANT))
+ return NO;
+
+ Cleanup ifUndecided = cleanupIfUndecidedOrDefunctWithFullRoute(input, txnId, saveStatus, redundant, redundant.all(TRUNCATE_BEFORE) ? null : NO);
+ if (ifUndecided != null)
+ return ifUndecided;
+
+ if (input == FULL)
+ {
+ Participants<?> executes = participants.stillExecutes();
+ if (!saveStatus.hasBeen(Applied) && (executes == null || (!executes.isEmpty() && redundantBefore.preBootstrapOrStale(txnId, executes) != ALL)))
+ {
+ // if we should execute this transaction locally, and we have not done so by the time we reach a GC point, something has gone wrong
+ TxnId supersededBy = redundantBefore.max(participants.route(), e -> e.shardAppliedBefore);
+ Participants<?> on = executes.slice(redundantBefore.foldl(participants.route(), (e, r, s) -> s.equals(e.shardAppliedBefore) ? r.with(Ranges.of(e.range)) : r, Ranges.EMPTY, supersededBy), Minimal);
+ String message = "Loading " + redundant + " command " + txnId + " with status " + saveStatus + " (that should have been Applied). Expected to be witnessed and executed by " + supersededBy + ".";
+ agent.onViolation(message, on, txnId, executeAt, supersededBy, supersededBy);
+ return truncate(txnId);
+ }
+ }
+
+ Durability test = Durability.max(durability, durableBefore.min(txnId, participants.route()));
+ switch (test)
+ {
+ default: throw new UnhandledEnum(durability);
+ case Local:
+ case NotDurable:
+ case ShardUniversal:
+ return truncateWithOutcome();
+
+ case MajorityOrInvalidated:
+ case Majority:
+ return truncate(txnId);
+
+ case UniversalOrInvalidated:
+ case Universal:
+ if (redundant.get(GC_BEFORE) == ALL)
+ return erase();
+ return truncate(txnId);
+ }
}
- private static Cleanup cleanupIfUndecided(Input input, TxnId txnId, SaveStatus saveStatus, StoreParticipants participants, RedundantBefore redundantBefore)
+ private static Cleanup cleanupWithoutFullRoute(Input input, TxnId txnId, SaveStatus saveStatus, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
// TODO (expected): consider if we can truncate more aggressively partial records, although we cannot infer anything from the fact they're undecided
- if (input == PARTIAL || saveStatus.hasBeen(PreCommitted))
+ if (input == PARTIAL || saveStatus.hasBeen(Truncated))
return NO;
+ Invariants.require(!saveStatus.hasBeen(PreCommitted));
if (participants.owns().isEmpty())
- return txnId.compareTo(redundantBefore.minShardRedundantBefore()) < 0 ? vestigial() : NO;
-
- RedundantStatus redundant = redundantBefore.status(txnId, null, participants.owns());
- switch (redundant)
{
- default: throw new UnhandledEnum(redundant);
- case WAS_OWNED:
- case WAS_OWNED_CLOSED:
- case LIVE:
- case PARTIALLY_PRE_BOOTSTRAP_OR_STALE:
- case PRE_BOOTSTRAP_OR_STALE:
- case LOCALLY_REDUNDANT:
- case PARTIALLY_LOCALLY_REDUNDANT:
- case PARTIALLY_SHARD_REDUNDANT:
+ // we don't want to erase something that we only don't own because it hasn't been initialised
+ if (saveStatus == Uninitialised)
+ return NO;
+
+ if (txnId.compareTo(redundantBefore.minShardRedundantBefore()) >= 0)
return NO;
- case WAS_OWNED_PARTIALLY_RETIRED:
- case WAS_OWNED_RETIRED:
- case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- return vestigial();
-
- case SHARD_REDUNDANT:
- case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
- case TRUNCATE_BEFORE:
- case GC_BEFORE:
- // correctness here relies on the fact that we process expunges first via global properties
- // so, if we reach here we would expect any Erase/Truncate to still exist and this path would not be taken
- return invalidate();
+ return vestigial(txnId);
}
+
+ RedundantStatus redundant = redundantBefore.status(txnId, null, participants.owns());
+ return cleanupUndecided(txnId, redundant);
}
- private static Cleanup cleanupWithFullRoute(Input input, Agent agent, StoreParticipants participants, TxnId txnId, Timestamp executeAt, SaveStatus saveStatus, Durability durability, RedundantBefore redundantBefore, DurableBefore durableBefore)
+ private static Cleanup cleanupIfUndecidedOrDefunctWithFullRoute(Input input, TxnId txnId, SaveStatus saveStatus, RedundantStatus redundantStatus, Cleanup ifDecided)
{
- // We first check if the command is redundant locally, i.e. whether it has been applied to all non-faulty replicas of the local shard
- // If not, we don't want to truncate its state else we may make catching up for these other replicas much harder
- FullRoute<?> route = Route.castToFullRoute(participants.route());
- if (!saveStatus.known.is(ApplyAtKnown)) executeAt = null;
- RedundantStatus redundant = redundantBefore.status(txnId, executeAt, route);
- if (redundant == NOT_OWNED)
- illegalState("Command " + txnId + " that is being loaded is not owned by this shard on route " + route);
-
- switch (redundant)
+ if (saveStatus.hasBeen(PreCommitted))
{
- default: throw new UnhandledEnum(redundant);
- case WAS_OWNED:
- case WAS_OWNED_CLOSED:
- case LIVE:
- case PARTIALLY_PRE_BOOTSTRAP_OR_STALE:
- case PRE_BOOTSTRAP_OR_STALE:
- case LOCALLY_REDUNDANT:
- case PARTIALLY_LOCALLY_REDUNDANT:
- case PARTIALLY_SHARD_REDUNDANT:
- return NO;
+ // TODO (required): consider more the invariants we're guaranteeing here, particularly with respect to other shards
+ // also consider whether we interfere with stronger cleanup that would run after in cleanupWithFullRoute
+ if (input != PARTIAL && redundantStatus.all(SHARD_APPLIED_ONLY) && !redundantStatus.any(LOCALLY_APPLIED) && redundantStatus.all(LOCALLY_DEFUNCT))
+ return truncate(txnId);
+ return ifDecided;
+ }
- case WAS_OWNED_PARTIALLY_RETIRED:
- // all keys are no longer owned, and at least one key is locally redundant
- if (txnId.is(ExclusiveSyncPoint))
- return NO;
+ if (input == PARTIAL)
+ return NO;
- case WAS_OWNED_RETIRED:
- return vestigial();
+ return cleanupUndecided(txnId, redundantStatus);
+ }
- case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- return truncate(saveStatus);
+ private static Cleanup cleanupUndecided(TxnId txnId, RedundantStatus redundantStatus)
+ {
+ if (redundantStatus.any(LOCALLY_APPLIED))
+ return invalidate(txnId);
- case SHARD_REDUNDANT:
- case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
- if (!saveStatus.hasBeen(PreCommitted))
- return input == FULL ? invalidate() : NO;
- return NO;
+ if (redundantStatus.all(SHARD_APPLIED_AND_LOCALLY_REDUNDANT))
+ return vestigial(txnId);
- case GC_BEFORE:
- case TRUNCATE_BEFORE:
- if (!saveStatus.hasBeen(PreCommitted))
- return input == FULL ? invalidate() : NO;
-
- if (input == FULL)
- {
- Participants<?> executes = participants.stillExecutes();
- if (!saveStatus.hasBeen(Applied) && (executes == null || (!executes.isEmpty() && redundantBefore.preBootstrapOrStale(txnId, executes) != FULLY)))
- {
- // if we should execute this transaction locally, and we have not done so by the time we reach a GC point, something has gone wrong
- agent.onViolation(String.format("Loading %s command %s with status %s (that should have been Applied). Expected to be witnessed and executed by %s.", redundant, txnId, saveStatus, redundantBefore.max(participants.route(), e -> e.shardAppliedOrInvalidatedBefore)));
- return truncate(saveStatus);
- }
- }
-
- Durability test = Durability.max(durability, durableBefore.min(txnId, participants.route()));
- switch (test)
- {
- default: throw new UnhandledEnum(durability);
- case Local:
- case NotDurable:
- case ShardUniversal:
- return truncateWithOutcome();
-
- case MajorityOrInvalidated:
- case Majority:
- return truncate();
-
- case UniversalOrInvalidated:
- case Universal:
- if (redundant == TRUNCATE_BEFORE)
- return truncate();
- return erase();
- }
- }
+ return NO;
}
private static boolean expunge(TxnId txnId, Timestamp executeAt, SaveStatus saveStatus, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
- // since we cannot guarantee to witness participants for all records, we must use the global durableBefore bounds
- // TODO (expected): introduce a single-key flag, as this would facilitate faster cleanup of common transactions
- if (durableBefore.min(txnId) != UniversalOrInvalidated)
+ if (txnId.is(Any) && durableBefore.min(txnId) != UniversalOrInvalidated)
return false;
- // TODO (desired): we should perhaps weaken this to separately account whether remotely and locally redundant?
- // i.e., if we know that the shard is remotely durable and we know we don't need it locally (e.g. due to bootstrap)
- // then we can safely erase. Revisit as part of rationalising RedundantBefore registers.
-
+ // since we cannot guarantee to witness participants for all records, we must use the global durableBefore bounds
TxnId minGcBefore = redundantBefore.minGcBefore();
if (minGcBefore.compareTo(txnId) <= 0)
return false;
@@ -299,14 +285,19 @@ public enum Cleanup
}
// convenient for debugging
- private static Cleanup invalidate() { return INVALIDATE; }
- private static Cleanup truncate(SaveStatus saveStatus)
+ private static Cleanup invalidate(TxnId txnId)
{
- return saveStatus.known.is(ApplyAtKnown) ? truncate() : vestigial();
+ return INVALIDATE;
}
private static Cleanup truncateWithOutcome() { return TRUNCATE_WITH_OUTCOME; }
- private static Cleanup truncate() { return TRUNCATE; }
- private static Cleanup vestigial() { return VESTIGIAL; }
+ private static Cleanup truncate(TxnId txnId)
+ {
+ return TRUNCATE;
+ }
+ private static Cleanup vestigial(TxnId txnId)
+ {
+ return VESTIGIAL;
+ }
private static Cleanup erase() { return ERASE; }
private static Cleanup expunge() { return EXPUNGE; }
}
diff --git a/accord-core/src/main/java/accord/local/Command.java b/accord-core/src/main/java/accord/local/Command.java
index 78186fdd..70eda1b6 100644
--- a/accord-core/src/main/java/accord/local/Command.java
+++ b/accord-core/src/main/java/accord/local/Command.java
@@ -62,10 +62,13 @@ import static accord.local.Command.Committed.committed;
import static accord.local.Command.Executed.executed;
import static accord.local.Command.NotAcceptedWithoutDefinition.notAccepted;
import static accord.primitives.Known.KnownDeps.DepsUnknown;
+import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
import static accord.primitives.Routable.Domain.Key;
import static accord.primitives.Routable.Domain.Range;
import static accord.primitives.Routables.Slice;
import static accord.primitives.SaveStatus.AcceptedInvalidate;
+import static accord.primitives.SaveStatus.TruncatedApply;
+import static accord.primitives.SaveStatus.TruncatedUnapplied;
import static accord.primitives.SaveStatus.Vestigial;
import static accord.primitives.SaveStatus.ReadyToExecute;
import static accord.primitives.SaveStatus.Uninitialised;
@@ -195,17 +198,6 @@ public abstract class Command implements ICommand
return txnId;
}
- /**
- * We require that this is a FullRoute for all states where isDefinitionKnown().
- * In some cases, the home shard will contain an arbitrary slice of the Route where !isDefinitionKnown(),
- * i.e. when a non-home shard informs the home shards of a transaction to ensure forward progress.
- *
- * If hasBeen(Committed) this must contain the keys for both txnId.epoch and executeAt.epoch
- *
- * TODO (required): audit uses; do not assume non-null means it is a complete route for the shard;
- * preferably introduce two variations so callers can declare whether they need the full shard's route
- * or any route will do
- */
@Override
public final StoreParticipants participants()
{
@@ -407,9 +399,14 @@ public abstract class Command implements ICommand
public static class Truncated extends Command
{
public static Truncated erased(Command command)
+ {
+ return erased(command, command.participants());
+ }
+
+ public static Truncated erased(Command command, StoreParticipants participants)
{
Durability durability = Durability.mergeAtLeast(command.durability(), UniversalOrInvalidated);
- return erased(command.txnId(), durability, command.participants());
+ return erased(command.txnId(), durability, participants);
}
public static Truncated erased(TxnId txnId, Status.Durability durability, StoreParticipants participants)
@@ -422,59 +419,70 @@ public abstract class Command implements ICommand
return vestigial(command.txnId(), command.participants());
}
+ public static Truncated vestigial(Command command, StoreParticipants participants)
+ {
+ return vestigial(command.txnId(), participants);
+ }
+
public static Truncated vestigial(TxnId txnId, StoreParticipants participants)
{
return validate(new Truncated(txnId, SaveStatus.Vestigial, NotDurable, participants, null, null, null));
}
- public static Truncated truncatedApply(Command command)
+ public static Truncated truncated(Command command)
{
- return truncatedApply(command, command.participants());
+ return truncated(command, command.participants());
}
- public static Truncated truncatedApply(Command command, @Nonnull StoreParticipants participants)
+ public static Truncated truncated(Command command, @Nonnull StoreParticipants participants)
{
Invariants.requireArgument(command.known().isExecuteAtKnown());
+ SaveStatus newSaveStatus = command.known().is(ApplyAtKnown) ? TruncatedApply : TruncatedUnapplied;
Durability durability = Durability.mergeAtLeast(command.durability(), ShardUniversal);
if (command.txnId().awaitsOnlyDeps())
{
Timestamp executesAtLeast = command.hasBeen(Stable) ? command.executesAtLeast() : null;
- return validate(new TruncatedAwaitsOnlyDeps(command.txnId(), SaveStatus.TruncatedApply, durability, participants, command.executeAt(), null, null, executesAtLeast));
+ return validate(new TruncatedAwaitsOnlyDeps(command.txnId(), newSaveStatus, durability, participants, command.executeAt(), null, null, executesAtLeast));
}
- return validate(new Truncated(command.txnId(), SaveStatus.TruncatedApply, durability, participants, command.executeAt(), null, null));
+ return validate(new Truncated(command.txnId(), newSaveStatus, durability, participants, command.executeAt(), null, null));
}
public static Truncated truncatedApplyWithOutcome(Executed command)
+ {
+ return truncatedApplyWithOutcome(command, command.participants());
+ }
+
+ public static Truncated truncatedApplyWithOutcome(Executed command, StoreParticipants participants)
{
Durability durability = Durability.mergeAtLeast(command.durability(), ShardUniversal);
if (command.txnId().awaitsOnlyDeps())
return validate(new TruncatedAwaitsOnlyDeps(command.txnId(), SaveStatus.TruncatedApplyWithOutcome, durability, command.participants(), command.executeAt(), command.writes, command.result, command.executesAtLeast()));
- return validate(new Truncated(command.txnId(), SaveStatus.TruncatedApplyWithOutcome, durability, command.participants(), command.executeAt(), command.writes, command.result));
+ return validate(new Truncated(command.txnId(), SaveStatus.TruncatedApplyWithOutcome, durability, participants, command.executeAt(), command.writes, command.result));
}
- public static Truncated truncatedApply(ICommand common, SaveStatus saveStatus, Timestamp executeAt, Writes writes, Result result)
+ public static Truncated truncated(ICommand common, SaveStatus saveStatus, Timestamp executeAt, Writes writes, Result result)
{
- return truncatedApply(common.txnId(), saveStatus, common.durability(), common.participants(), executeAt, writes, result);
+ return truncated(common.txnId(), saveStatus, common.durability(), common.participants(), executeAt, writes, result);
}
- public static Truncated truncatedApply(TxnId txnId, SaveStatus saveStatus, Durability durability, StoreParticipants participants, Timestamp executeAt, Writes writes, Result result)
+ public static Truncated truncated(TxnId txnId, SaveStatus saveStatus, Durability durability, StoreParticipants participants, Timestamp executeAt, Writes writes, Result result)
{
Invariants.requireArgument(!txnId.awaitsOnlyDeps());
durability = checkTruncatedApplyInvariants(durability, saveStatus, executeAt);
return validate(new Truncated(txnId, saveStatus, durability, participants, executeAt, writes, result));
}
- public static Truncated truncatedApply(ICommand common, SaveStatus saveStatus, Timestamp executeAt, Writes writes, Result result, @Nullable Timestamp dependencyExecutesAt)
+ public static Truncated truncated(ICommand common, SaveStatus saveStatus, Timestamp executeAt, Writes writes, Result result, @Nullable Timestamp dependencyExecutesAt)
{
- return truncatedApply(common.txnId(), saveStatus, common.durability(), common.participants(), executeAt, writes, result, dependencyExecutesAt);
+ return truncated(common.txnId(), saveStatus, common.durability(), common.participants(), executeAt, writes, result, dependencyExecutesAt);
}
- public static Truncated truncatedApply(TxnId txnId, SaveStatus saveStatus, Durability durability, StoreParticipants participants, Timestamp executeAt, Writes writes, Result result, @Nullable Timestamp dependencyExecutesAt)
+ public static Truncated truncated(TxnId txnId, SaveStatus saveStatus, Durability durability, StoreParticipants participants, Timestamp executeAt, Writes writes, Result result, @Nullable Timestamp dependencyExecutesAt)
{
if (!txnId.awaitsOnlyDeps())
{
Invariants.require(dependencyExecutesAt == null);
- return truncatedApply(txnId, saveStatus, durability, participants, executeAt, writes, result);
+ return truncated(txnId, saveStatus, durability, participants, executeAt, writes, result);
}
durability = checkTruncatedApplyInvariants(durability, saveStatus, executeAt);
return validate(new TruncatedAwaitsOnlyDeps(txnId, saveStatus, durability, participants, executeAt, writes, result, dependencyExecutesAt));
@@ -483,20 +491,23 @@ public abstract class Command implements ICommand
private static Durability checkTruncatedApplyInvariants(Durability durability, SaveStatus saveStatus, Timestamp executeAt)
{
Invariants.requireArgument(executeAt != null);
- Invariants.requireArgument(saveStatus == SaveStatus.TruncatedApply || saveStatus == SaveStatus.TruncatedApplyWithDeps || saveStatus == SaveStatus.TruncatedApplyWithOutcome);
+ Invariants.requireArgument(saveStatus == SaveStatus.TruncatedApply || saveStatus == SaveStatus.TruncatedUnapplied || saveStatus == SaveStatus.TruncatedApplyWithOutcome);
return Durability.mergeAtLeast(durability, ShardUniversal);
}
public static Truncated invalidated(Command command)
+ {
+ return invalidated(command, command.participants());
+ }
+
+ public static Truncated invalidated(Command command, StoreParticipants participants)
{
Invariants.require(!command.hasBeen(Status.PreCommitted));
- return invalidated(command.txnId(), command.participants());
+ return invalidated(command.txnId(), participants);
}
public static Truncated invalidated(TxnId txnId, StoreParticipants participants)
{
- // TODO (expected): migrate to using null for executeAt when invalidated
- // TODO (expected): is UniversalOrInvalidated correct here? Should we have a lower implication pure Invalidated?
// NOTE: we *must* save participants here so that on replay we properly repopulate CommandsForKey
// (otherwise we may see this as a transitive transaction, but never mark it invalidated)
return validate(new Truncated(txnId, SaveStatus.Invalidated, UniversalOrInvalidated, participants, Timestamp.NONE, null, null));
@@ -507,13 +518,12 @@ public abstract class Command implements ICommand
public Truncated(ICommand copy, SaveStatus saveStatus)
{
- // TODO (expected): is Ballot.MAX helpful or harmful here?
- // We have to special-case partial truncation anyway as we can infinite loop if we think there's a superseding recovery.
super(copy, saveStatus);
this.writes = copy.writes();
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);
@@ -1213,7 +1223,6 @@ public abstract class Command implements ICommand
{
int index = keys.indexOf(key);
// we can be a member of a CFK we aren't waiting on, if we Accept in a later epoch using a key we don't own once Committed to an earlier eopch
- // TODO (expected): simply remove ourselves from any CFK we aren't waiting on
if (index < 0) return false;
index += txnIdCount();
@@ -1641,7 +1650,7 @@ public abstract class Command implements ICommand
case Applied:
return validateCommandClass(status, Executed.class, klass);
case TruncatedApply:
- case TruncatedApplyWithDeps:
+ case TruncatedUnapplied:
case TruncatedApplyWithOutcome:
if (txnId.awaitsOnlyDeps())
return validateCommandClass(status, TruncatedAwaitsOnlyDeps.class, klass);
@@ -1657,6 +1666,7 @@ public abstract class Command implements ICommand
public static <T extends Command> T validate(T validate)
{
Invariants.require(validate.txnId().hasOnlyIdentityFlags());
+ Invariants.require(!validate.participants().hasTouched().isEmpty() || validate.saveStatus() == Uninitialised);
Known known = validate.known();
switch (known.route())
{
diff --git a/accord-core/src/main/java/accord/local/CommandStore.java b/accord-core/src/main/java/accord/local/CommandStore.java
index beda7e2b..af237238 100644
--- a/accord-core/src/main/java/accord/local/CommandStore.java
+++ b/accord-core/src/main/java/accord/local/CommandStore.java
@@ -46,6 +46,7 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -155,9 +156,6 @@ public abstract class CommandStore implements AgentExecutor
* We also update safeToRead when we go stale, to remove ranges we may have bootstrapped but that are now known to
* be incomplete. In this case we permit transactions to execute in any order for the unsafe key ranges.
* But they may still be ordered for other key ranges they participate in.
- *
- * TODO (expected): merge with redundantBefore
- * TODO (required): if we ever actually erase data on disk (after losing ownership), make sure to mark the range unsafe to read
*/
private NavigableMap<Timestamp, Ranges> safeToRead = emptySafeToRead();
private final Set<Bootstrap> bootstraps = Collections.synchronizedSet(new DeterministicIdentitySet<>());
@@ -264,9 +262,29 @@ public abstract class CommandStore implements AgentExecutor
else execute(task);
}
- public abstract AsyncChain<Void> execute(PreLoadContext context, Consumer<? super SafeCommandStore> consumer);
+ public abstract AsyncChain<Void> build(PreLoadContext context, Consumer<? super SafeCommandStore> consumer);
+ public abstract <T> AsyncChain<T> build(PreLoadContext context, Function<? super SafeCommandStore, T> apply);
+
+ public void execute(PreLoadContext context, Consumer<? super SafeCommandStore> consumer, BiConsumer<? super Void, Throwable> callback)
+ {
+ build(context, consumer).begin(callback);
+ }
+
+ public AsyncResult<Void> execute(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
+ {
+ return build(context, consumer).beginAsResult();
+ }
+
+ public <T> void submit(PreLoadContext context, Function<? super SafeCommandStore, T> apply, BiConsumer<? super T, Throwable> callback)
+ {
+ build(context, apply).begin(callback);
+ }
+
+ public <T> AsyncResult<T> submit(PreLoadContext context, Function<? super SafeCommandStore, T> apply)
+ {
+ return build(context, apply).beginAsResult();
+ }
- public abstract <T> AsyncChain<T> submit(PreLoadContext context, Function<? super SafeCommandStore, T> apply);
public abstract void shutdown();
protected abstract void registerTransitive(SafeCommandStore safeStore, RangeDeps deps);
@@ -447,7 +465,6 @@ public abstract class CommandStore implements AgentExecutor
if (isExpired)
return node.uniqueNow(txnId).asRejected();
- // TODO (expected): we should (perhaps) separate conflicts for reads and writes
Timestamp min = TxnId.mergeMax(txnId, maxConflicts.get(keys));
if (permitFastPath && txnId == min && txnId.epoch() >= node.epoch())
return txnId;
@@ -547,7 +564,7 @@ public abstract class CommandStore implements AgentExecutor
bootstraps.add(bootstrap);
bootstrap.start(safeStore);
return new EpochReady(epoch, null, null, bootstrap.data, bootstrap.reads);
- }).beginAsResult();
+ });
AsyncResult<Void> readyToCoordinate = readyToCoordinate(newRanges, epoch);
return new EpochReady(epoch, metadata.<Void>map(ignore -> null).beginAsResult(),
@@ -584,7 +601,7 @@ public abstract class CommandStore implements AgentExecutor
Supplier<EpochReady> unbootstrap(long epoch, Ranges removedRanges)
{
return () -> {
- AsyncResult<Void> done = this.<Void>submit(empty(), safeStore -> {
+ AsyncResult<Void> done = submit(empty(), safeStore -> {
for (Bootstrap prev : bootstraps)
{
Ranges abort = prev.allValid.slice(removedRanges, Minimal);
@@ -592,7 +609,7 @@ public abstract class CommandStore implements AgentExecutor
prev.invalidate(abort);
}
return null;
- }).beginAsResult();
+ });
return new EpochReady(epoch, done, done, done, done);
};
@@ -616,7 +633,7 @@ public abstract class CommandStore implements AgentExecutor
public void markShardDurable(SafeCommandStore safeStore, TxnId globalSyncId, Ranges durableRanges)
{
final Ranges slicedRanges = durableRanges.slice(safeStore.ranges().allUntil(globalSyncId.epoch()), Minimal);
- TxnId locallyRedundantBefore = safeStore.redundantBefore().min(slicedRanges, e -> e.locallyAppliedOrInvalidatedBefore);
+ TxnId locallyRedundantBefore = safeStore.redundantBefore().min(slicedRanges, e -> e.locallyAppliedBefore);
RedundantBefore addShardRedundant = RedundantBefore.create(slicedRanges, Long.MIN_VALUE, Long.MAX_VALUE, globalSyncId, TxnId.NONE, globalSyncId, TxnId.NONE, TxnId.NONE);
safeStore.upsertRedundantBefore(addShardRedundant);
updatedRedundantBefore(safeStore, globalSyncId, slicedRanges);
@@ -646,7 +663,7 @@ public abstract class CommandStore implements AgentExecutor
execute(PreLoadContext.empty(), safeStore0 -> {
RedundantBefore addGc = RedundantBefore.create(slicedRanges, Long.MIN_VALUE, Long.MAX_VALUE, globalSyncId, globalSyncId, globalSyncId, globalSyncId, TxnId.NONE);
safeStore0.upsertRedundantBefore(addGc);
- }).begin(agent());
+ }, agent());
});
}
}
@@ -694,9 +711,6 @@ public abstract class CommandStore implements AgentExecutor
remove.forEach(waitingOnSync::remove);
}
- // TODO (expected): we can immediately truncate dependencies locally once an exclusiveSyncPoint applies, we don't need to wait for the whole shard
- // TODO (required): integrate validation of staleness with implementation (e.g. C* should know it has been marked stale)
- // also: we no longer expect epochs that are losing a range to be marked stale, make sure logic reflects this
public void markShardStale(SafeCommandStore safeStore, Timestamp staleSince, Ranges ranges, boolean isSincePrecise)
{
Timestamp staleUntilAtLeast = staleSince;
@@ -736,7 +750,7 @@ public abstract class CommandStore implements AgentExecutor
if (!newBootstrapRanges.isEmpty())
safeStore.setBootstrapBeganAt(bootstrap(TxnId.NONE, newBootstrapRanges, bootstrapBeganAt));
safeStore.setSafeToRead(purgeAndInsert(safeToRead, TxnId.NONE, ranges));
- }).beginAsResult();
+ });
return new EpochReady(epoch, done, done, done, done);
};
@@ -783,7 +797,7 @@ public abstract class CommandStore implements AgentExecutor
{
execute(empty(), safeStore -> {
safeStore.setSafeToRead(purgeHistory(safeToRead, ranges));
- }).beginAsResult();
+ }, agent);
}
}
@@ -794,7 +808,7 @@ public abstract class CommandStore implements AgentExecutor
Ranges validatedSafeToRead = redundantBefore.validateSafeToRead(forBootstrapAt, ranges);
safeStore.setSafeToRead(purgeAndInsert(safeToRead, at, validatedSafeToRead));
updateMaxConflicts(ranges, at);
- }).beginAsResult();
+ }, agent);
}
public static ImmutableSortedMap<TxnId, Ranges> bootstrap(TxnId at, Ranges ranges, NavigableMap<TxnId, Ranges> bootstrappedAt)
diff --git a/accord-core/src/main/java/accord/local/CommandStores.java b/accord-core/src/main/java/accord/local/CommandStores.java
index 7bcc212b..047072d3 100644
--- a/accord-core/src/main/java/accord/local/CommandStores.java
+++ b/accord-core/src/main/java/accord/local/CommandStores.java
@@ -616,9 +616,7 @@ public abstract class CommandStores
List<AsyncChain<Void>> list = new ArrayList<>();
Snapshot snapshot = current;
for (ShardHolder shard : snapshot.shards)
- {
- list.add(shard.store.execute(empty(), forEach));
- }
+ list.add(shard.store.build(empty(), forEach));
return AsyncChains.reduce(list, (a, b) -> null);
}
@@ -714,7 +712,7 @@ public abstract class CommandStores
if (!shardRanges.intersects(keys))
continue;
- AsyncChain<O> next = shard.store.submit(context, mapReduce);
+ AsyncChain<O> next = shard.store.build(context, mapReduce);
chain = chain != null ? AsyncChains.reduce(chain, next, reducer) : next;
}
return chain == null ? AsyncChains.success(null) : chain;
@@ -731,7 +729,7 @@ public abstract class CommandStores
List<AsyncChain<O>> results = new ArrayList<>(shards.length);
for (ShardHolder shard : shards)
- results.add(shard.store.submit(context, mapper));
+ results.add(shard.store.build(context, mapper));
return AsyncChains.all(results);
}
@@ -745,7 +743,7 @@ public abstract class CommandStores
for (int id : ids)
{
CommandStore commandStore = forId(id);
- AsyncChain<O> next = commandStore.submit(context, mapReduce);
+ AsyncChain<O> next = commandStore.build(context, mapReduce);
chain = chain != null ? AsyncChains.reduce(chain, next, reducer) : next;
}
return chain == null ? AsyncChains.success(null) : chain;
@@ -765,7 +763,7 @@ public abstract class CommandStores
for (ShardHolder shardHolder : current.shards)
{
CommandStore commandStore = shardHolder.store;
- AsyncChain<O> next = commandStore.submit(context, mapReduce);
+ AsyncChain<O> next = commandStore.build(context, mapReduce);
chain = chain != null ? AsyncChains.reduce(chain, next, reducer) : next;
}
return chain == null ? AsyncChains.success(null) : chain;
diff --git a/accord-core/src/main/java/accord/local/CommandSummaries.java b/accord-core/src/main/java/accord/local/CommandSummaries.java
index 78ce33e0..33fd918a 100644
--- a/accord-core/src/main/java/accord/local/CommandSummaries.java
+++ b/accord-core/src/main/java/accord/local/CommandSummaries.java
@@ -160,7 +160,7 @@ public interface CommandSummaries
return false;
case NOTACCEPTED:
case PREACCEPTED:
- if (!txnId.is(TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS))
+ if (!txnId.is(TxnId.FastPath.PrivilegedCoordinatorWithDeps))
return false;
case ACCEPTED:
return txnId.compareTo(findAsDep) > 0;
diff --git a/accord-core/src/main/java/accord/local/Commands.java b/accord-core/src/main/java/accord/local/Commands.java
index 75018925..4fa3e5b9 100644
--- a/accord-core/src/main/java/accord/local/Commands.java
+++ b/accord-core/src/main/java/accord/local/Commands.java
@@ -19,6 +19,7 @@
package accord.local;
import java.util.function.Consumer;
+import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -40,6 +41,7 @@ import accord.primitives.Ballot;
import accord.primitives.Deps;
import accord.primitives.FullRoute;
import accord.primitives.Known;
+import accord.primitives.Known.KnownExecuteAt;
import accord.primitives.PartialDeps;
import accord.primitives.PartialTxn;
import accord.primitives.Participants;
@@ -61,12 +63,13 @@ import static accord.api.ProgressLog.BlockedUntil.CanApply;
import static accord.api.ProgressLog.BlockedUntil.HasDecidedExecuteAt;
import static accord.api.ProtocolModifiers.Toggles.DependencyElision.IF_DURABLE;
import static accord.api.ProtocolModifiers.Toggles.dependencyElision;
+import static accord.api.ProtocolModifiers.Toggles.markStaleIfCannotExecute;
import static accord.local.Cleanup.Input.FULL;
import static accord.local.Cleanup.NO;
import static accord.local.Cleanup.shouldCleanup;
import static accord.local.Command.Truncated.erased;
import static accord.local.Command.Truncated.invalidated;
-import static accord.local.Command.Truncated.truncatedApply;
+import static accord.local.Command.Truncated.truncated;
import static accord.local.Command.Truncated.truncatedApplyWithOutcome;
import static accord.local.Command.Truncated.vestigial;
import static accord.local.Commands.Validated.INSUFFICIENT;
@@ -76,7 +79,16 @@ import static accord.local.Commands.Validated.UPDATE_TXN_AND_DEPS;
import static accord.local.KeyHistory.INCR;
import static accord.local.KeyHistory.SYNC;
import static accord.local.PreLoadContext.contextFor;
-import static accord.local.RedundantBefore.PreBootstrapOrStale.FULLY;
+import static accord.local.RedundantStatus.Coverage.ALL;
+import static accord.local.RedundantStatus.Coverage.NONE;
+import static accord.local.RedundantStatus.Property.LOCALLY_APPLIED;
+import static accord.local.RedundantStatus.Property.LOCALLY_DEFUNCT;
+import static accord.local.RedundantStatus.Property.LOCALLY_REDUNDANT;
+import static accord.local.RedundantStatus.Property.LOCALLY_SYNCED;
+import static accord.local.RedundantStatus.Property.PRE_BOOTSTRAP_OR_STALE;
+import static accord.local.RedundantStatus.Property.SHARD_AND_LOCALLY_APPLIED;
+import static accord.local.RedundantStatus.Property.SHARD_APPLIED_AND_LOCALLY_REDUNDANT;
+import static accord.local.RedundantStatus.Property.WAS_OWNED;
import static accord.local.StoreParticipants.Filter.LOAD;
import static accord.local.StoreParticipants.Filter.UPDATE;
import static accord.messages.Commit.Kind.StableMediumPath;
@@ -106,7 +118,7 @@ import static accord.primitives.Status.Truncated;
import static accord.primitives.Route.isFullRoute;
import static accord.primitives.Txn.Kind.EphemeralRead;
import static accord.primitives.Txn.Kind.Write;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
import static accord.utils.Invariants.illegalState;
public class Commands
@@ -121,7 +133,7 @@ public class Commands
public static AcceptOutcome preaccept(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, TxnId txnId, Txn partialTxn, @Nullable Deps partialDeps, boolean hasCoordinatorVote, FullRoute<?> route)
{
- Invariants.require(partialDeps == null || txnId.is(PRIVILEGED_COORDINATOR_WITH_DEPS));
+ Invariants.require(partialDeps == null || txnId.is(PrivilegedCoordinatorWithDeps));
Invariants.require(!hasCoordinatorVote || txnId.hasPrivilegedCoordinator());
SaveStatus newSaveStatus;
if (partialDeps != null) newSaveStatus = PreAcceptedWithDeps;
@@ -192,7 +204,7 @@ public class Commands
}
else
{
- // TODO (expected, ?): in the case that we are pre-committed but had not been preaccepted/accepted, should we inform progressLog?
+ // TODO (expected): in the case that we are pre-committed but had not been preaccepted/accepted, should we inform progressLog?
PartialTxn partialTxn = prepareTxn(newSaveStatus, participants, command, txn);
participants = prepareParticipants(validated, participants, command);
safeCommand.markDefined(safeStore, participants, ballot, partialTxn);
@@ -255,7 +267,6 @@ public class Commands
public static AcceptOutcome notAccept(SafeCommandStore safeStore, SafeCommand safeCommand, Status status, Ballot ballot)
{
- // TODO (expected): save some partial route we can use to determine if it can be GC'd
final Command command = safeCommand.current();
if (command.hasBeen(PreCommitted))
{
@@ -341,7 +352,6 @@ public class Commands
WaitingOn waitingOn = initialiseWaitingOn(safeStore, txnId, executeAt, participants, partialDeps);
committed = safeCommand.stable(safeStore, participants, ballot, executeAt, partialTxn, partialDeps, waitingOn);
safeStore.agent().metricsEventsListener().onStable(committed);
- // TODO (expected, safety): introduce intermediate status to avoid reentry when notifying listeners (which might notify us)
maybeExecute(safeStore, safeCommand, true, true);
}
else
@@ -386,7 +396,6 @@ public class Commands
public static void ephemeralRead(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, Route<?> route, TxnId txnId, PartialTxn txn, PartialDeps deps)
{
- // TODO (expected): introduce in-memory only commands
Command command = safeCommand.current();
if (command.hasBeen(Stable))
return;
@@ -421,7 +430,6 @@ public class Commands
safeCommand.set(erased(command));
}
- // TODO (expected, ?): commitInvalidate may need to update cfks _if_ possible
public static void commitInvalidate(SafeCommandStore safeStore, SafeCommand safeCommand, Unseekables<?> scope)
{
final Command command = safeCommand.current();
@@ -456,7 +464,20 @@ public class Commands
if (command.hasBeen(PreApplied))
{
logger.trace("{}: skipping apply - already preapplied ({})", txnId, command.status());
- if (command.executeAt() != null && !executeAt.equalsStrict(command.executeAt()) && command.saveStatus().compareTo(Erased) < 0)
+ boolean inconsistent = false;
+ Timestamp cur = command.executeAt();
+ KnownExecuteAt known = command.known().executeAt();
+ switch (known)
+ {
+ default: throw UnhandledEnum.unknown(known);
+ case ExecuteAtProposed: throw UnhandledEnum.invalid(known);
+ case ApplyAtKnown: inconsistent = !executeAt.equalsStrict(cur); break;
+ case ExecuteAtKnown: inconsistent = !executeAt.equals(cur); break;
+ case NoExecuteAt: inconsistent = true;
+ case ExecuteAtErased:
+ case ExecuteAtUnknown:
+ }
+ if (inconsistent)
safeStore.agent().onInconsistentTimestamp(command, command.executeAt(), executeAt);
return ApplyOutcome.Redundant;
}
@@ -470,7 +491,7 @@ public class Commands
participants = participants.filter(UPDATE, safeStore, txnId, executeAt);
Validated validated = validate(Ballot.ZERO, SaveStatus.PreApplied, command, participants, route, txn, deps);
if (validated == INSUFFICIENT)
- return ApplyOutcome.Insufficient; // TODO (expected, consider): this should probably be an assertion failure if !TrySet
+ return ApplyOutcome.Insufficient;
PartialTxn partialTxn = prepareTxn(SaveStatus.PreApplied, participants, command, txn);
PartialDeps partialDeps = prepareDeps(validated, participants, command, deps);
@@ -562,7 +583,7 @@ public class Commands
Participants<?> executes = command.participants().stillExecutes(); // including any keys we aren't writing
return command.writes().apply(safeStore, executes, command.partialTxn())
// TODO (expected): once we guarantee execution order KeyHistory can be ASYNC
- .flatMap(unused -> unsafeStore.submit(contextFor(txnId, executes, SYNC), ss -> {
+ .flatMap(unused -> unsafeStore.build(contextFor(txnId, executes, SYNC), ss -> {
Command cmd = ss.get(txnId).current();
if (!cmd.hasBeen(Applied))
ss.agent().metricsEventsListener().onApplied(cmd, t0);
@@ -579,7 +600,7 @@ public class Commands
Participants<?> executes = executed.participants().stillExecutes();
if (!executes.isEmpty())
return command.writes().apply(safeStore, executes, command.partialTxn())
- .flatMap(unused -> unsafeStore.submit(context, ss -> {
+ .flatMap(unused -> unsafeStore.build(context, ss -> {
postApply(ss, command);
return null;
}));
@@ -616,16 +637,11 @@ public class Commands
return false;
}
- // TODO (required): slice our execute ranges based on any pre-bootstrap state
- // FIXME: need to communicate to caller that we didn't execute if we take one of the above paths
TxnId txnId = command.txnId();
switch (command.status())
{
case Stable:
- // TODO (desirable, efficiency): maintain distinct ReadyToRead and ReadyToWrite states
- // TODO (required): we can have dangling transactions if we don't execute them,
- // but we don't want to erase the transaction until
- // We can also have dangling progress log entries for commands we simply don't execute
+ // TODO (required): maintain distinct ReadyToRead and ReadyToWrite states
// immediately, as no transaction should take a local dependency on this transaction.
// This handles both transactions whose ownership is lost, as well as those that become pre-bootstrap or stale
safeCommand.readyToExecute(safeStore);
@@ -700,12 +716,16 @@ public class Commands
switch (dependency.saveStatus())
{
default: throw new AssertionError("Unhandled saveStatus: " + dependency.saveStatus());
- case TruncatedApply:
case TruncatedApplyWithOutcome:
- case TruncatedApplyWithDeps:
+ case TruncatedApply:
+ case TruncatedUnapplied:
Invariants.require(dependency.executeAt().compareTo(waitingExecuteAt) < 0
|| waitingId.awaitsOnlyDeps()
- || waiting.participants().stillExecutes().isEmpty());
+ || waiting.participants().stillExecutes().isEmpty()
+ || !markStaleIfCannotExecute(dependencyId.kind())
+ || safeStore.redundantBefore().status(dependencyId, null,
+ waiting.partialDeps().participants(dependencyId)).all(LOCALLY_DEFUNCT)
+ );
case Vestigial:
case Erased:
logger.trace("{}: {} is truncated. Stop listening and removing from waiting on commit set.", waitingId, dependencyId);
@@ -736,14 +756,10 @@ public class Commands
Participants<?> participants = waiting.partialDeps().participants(dependency.txnId());
Participants<?> executes = participants.intersecting(waiting.participants().stillExecutes(), Minimal);
RedundantStatus status = safeStore.redundantBefore().status(dependencyId, waitingExecuteAt, executes);
- switch (status)
- {
- case WAS_OWNED_PARTIALLY_RETIRED:
- case WAS_OWNED_RETIRED:
- case PRE_BOOTSTRAP_OR_STALE:
- case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- return false;
- }
+
+ if (status.get(LOCALLY_DEFUNCT) == ALL)
+ return false;
+
throw illegalState("We have a dependency (" + dependency + ") to wait on, but have already finished waiting (" + waiting + ")");
}
}
@@ -770,7 +786,7 @@ public class Commands
{
TxnId nextWaitingOn = command.waitingOn().nextWaitingOn();
if (nextWaitingOn != null && nextWaitingOn.equals(pred.txnId()) && !pred.hasBeen(PreApplied))
- safeStore.progressLog().waiting(CanApply, safeStore, predecessor, pred.route(), null, null);
+ safeStore.progressLog().waiting(CanApply, safeStore, predecessor, null, null, null);
}
}
}
@@ -805,7 +821,6 @@ public class Commands
public static void setTruncatedApplyOrErasedVestigial(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, @Nullable Timestamp executeAt)
{
- // TODO (expected): tighten up and declare invariants and reasoning here
Command command = safeCommand.current();
SaveStatus saveStatus = command.saveStatus();
if (saveStatus.compareTo(TruncatedApply) >= 0) return;
@@ -822,13 +837,13 @@ public class Commands
command = command.updateParticipants(participants);
if (!safeCommand.txnId().awaitsOnlyDeps())
{
- safeCommand.update(safeStore, truncatedApply(command, TruncatedApply, executeAt, null, null));
+ safeCommand.update(safeStore, Command.Truncated.truncated(command, TruncatedApply, executeAt, null, null));
}
else if (safeCommand.current().saveStatus().hasBeen(Applied))
{
Timestamp executesAtLeast = safeCommand.current().executesAtLeast();
if (executesAtLeast == null) safeCommand.update(safeStore, erased(command));
- else safeCommand.update(safeStore, truncatedApply(command, TruncatedApply, executeAt, null, null, executesAtLeast));
+ else safeCommand.update(safeStore, Command.Truncated.truncated(command, TruncatedApply, executeAt, null, null, executesAtLeast));
}
safeStore.progressLog().clear(command.txnId());
}
@@ -892,14 +907,7 @@ public class Commands
// TODO (desired): consider if there are better invariants we can impose for undecided transactions, to verify they aren't later committed (should be detected already, but more is better)
// note that our invariant here is imperfectly applied to keep the code cleaner: we don't verify that the caller was safe to invoke if we don't already have a route in the command and we're only PreCommitted
- Invariants.require(command.hasBeen(Applied)
- || !command.hasBeen(PreCommitted)
- || participants.route() == null // TODO (expected): tighten this e.g. with && participants.owns.isEmpty()
- || validateSafeToCleanup(store.redundantBefore(), command, participants)
- || store.redundantBefore().preBootstrapOrStale(command.txnId(), participants.owns()) == FULLY
- || (force && participants.executes() != null && participants.stillExecutes().isEmpty())
- , "Command %s could not be purged", command);
-
+ Invariants.require(validateSafeToCleanup(store.redundantBefore(), command, participants, force), "Command %s could not be purged", command);
return purge(command, participants, cleanup);
}
@@ -911,7 +919,7 @@ public class Commands
default: throw new AssertionError("Unexpected cleanup: " + cleanup);
case INVALIDATE:
Invariants.requireArgument(!command.hasBeen(PreCommitted));
- result = invalidated(command);
+ result = invalidated(command, newParticipants);
break;
case TRUNCATE_WITH_OUTCOME:
@@ -922,52 +930,44 @@ public class Commands
break;
case TRUNCATE:
- Invariants.require(command.saveStatus().compareTo(TruncatedApply) < 0);
- Invariants.requireArgument(command.known().is(ApplyAtKnown));
- result = truncatedApply(command, newParticipants);
+ result = truncated(command, newParticipants);
break;
case VESTIGIAL:
- Invariants.require(command.saveStatus().compareTo(Erased) < 0);
- result = vestigial(command);
+ Invariants.require(command.saveStatus().compareTo(SaveStatus.PreApplied) < 0);
+ result = vestigial(command, newParticipants);
break;
case ERASE:
case EXPUNGE:
Invariants.require(command.saveStatus().compareTo(Erased) < 0);
- result = erased(command);
+ result = erased(command, newParticipants);
break;
}
return result;
}
- private static boolean validateSafeToCleanup(RedundantBefore redundantBefore, Command command, @Nonnull StoreParticipants participants)
+ private static boolean validateSafeToCleanup(RedundantBefore redundantBefore, Command command, @Nonnull StoreParticipants participants, boolean force)
{
+ if (command.hasBeen(Applied)) return true;
+ if (!command.hasBeen(PreCommitted)) return true;
+ if (participants.route() == null) return true; // TODO (expected): tighten this e.g. with && participants.owns.isEmpty()
+
TxnId txnId = command.txnId();
- RedundantStatus status = redundantBefore.status(txnId, null, participants.owns());
- switch (status)
+ RedundantStatus status = redundantBefore.status(txnId, null, participants.route());
+ if (status.any(SHARD_AND_LOCALLY_APPLIED))
{
- default: throw new UnhandledEnum(status);
- case LIVE:
- case WAS_OWNED:
- case WAS_OWNED_CLOSED:
- case PARTIALLY_LOCALLY_REDUNDANT:
- case PARTIALLY_PRE_BOOTSTRAP_OR_STALE:
- return false;
- case LOCALLY_REDUNDANT:
- case PARTIALLY_SHARD_REDUNDANT:
- case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
- case SHARD_REDUNDANT:
- case GC_BEFORE:
- case TRUNCATE_BEFORE:
- Invariants.paranoid(!command.hasBeen(PreCommitted) || command.participants().stillExecutes().isEmpty());
- case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- case PRE_BOOTSTRAP_OR_STALE:
- case NOT_OWNED:
- case WAS_OWNED_PARTIALLY_RETIRED:
- case WAS_OWNED_RETIRED:
- return true;
+ Invariants.paranoid(command.participants().stillExecutes().isEmpty());
+ return true;
}
+
+ if (status.all(SHARD_APPLIED_AND_LOCALLY_REDUNDANT) || status.all(PRE_BOOTSTRAP_OR_STALE))
+ return true;
+
+ if (force && participants.executes() != null && participants.stillExecutes().isEmpty())
+ return true;
+
+ return false;
}
public static boolean maybeCleanup(SafeCommandStore safeStore, SafeCommand safeCommand, Command command, @Nonnull StoreParticipants newParticipants)
@@ -976,7 +976,7 @@ public class Commands
Cleanup cleanup = shouldCleanup(FULL, safeStore, command, cleanupParticipants);
if (cleanup == NO)
{
- if (cleanupParticipants == newParticipants)
+ if (cleanupParticipants == command.participants())
return false;
safeCommand.updateParticipants(safeStore, cleanupParticipants);
@@ -988,7 +988,6 @@ public class Commands
return true;
}
- // TODO (expected): either ignore this message if we don't have a route, or else require FullRoute requiring route, or else require FullRoute
public static Command setDurability(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, Durability durability, @Nullable Timestamp executeAt)
{
final Command command = safeCommand.current();
@@ -1022,8 +1021,9 @@ public class Commands
Invariants.require(!context.keys().isEmpty());
safeStore = safeStore; // prevent accidental usage inside lambda
- safeStore.commandStore().execute(context, safeStore0 -> setDurable(safeStore0, safeStore0.context(), txnId))
- .begin(safeStore.commandStore().agent);
+ safeStore.commandStore().execute(context, safeStore0 -> {
+ setDurable(safeStore0, safeStore0.context(), txnId);
+ }, safeStore.commandStore().agent);
}
}
}
@@ -1065,44 +1065,9 @@ public class Commands
if (loadDepId != null)
{
- depSafe = safeStore.get(loadDepId);
- if (depSafe.current().saveStatus() == Uninitialised)
- {
- RedundantStatus redundantStatus = safeStore.redundantBefore().status(loadDepId, null, waiting.partialDeps().participants(loadDepId));
- switch (redundantStatus)
- {
- default: throw new AssertionError("Unexpected redundant status: " + redundantStatus);
- case NOT_OWNED:
- throw new AssertionError("Invalid state: waiting for execution of command that is not owned at the execution time");
-
- case WAS_OWNED_PARTIALLY_RETIRED:
- case WAS_OWNED_RETIRED:
- case PRE_BOOTSTRAP_OR_STALE:
- case PARTIALLY_LOCALLY_REDUNDANT:
- case LOCALLY_REDUNDANT:
- case PARTIALLY_SHARD_REDUNDANT:
- case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
- case SHARD_REDUNDANT:
- case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- case TRUNCATE_BEFORE:
- case GC_BEFORE:
- removeRedundantDependencies(safeStore, waitingSafe, loadDepId);
- depSafe = null;
- break;
-
- case WAS_OWNED:
- case WAS_OWNED_CLOSED:
- if (!waitingId.awaitsPreviouslyOwned())
- {
- removeNoLongerOwnedDependency(safeStore, waitingSafe, loadDepId);
- depSafe = null;
- break;
- }
-
- case LIVE:
- case PARTIALLY_PRE_BOOTSTRAP_OR_STALE:
- }
- }
+ depSafe = safeStore.ifInitialised(loadDepId);
+ if (depSafe == null)
+ depSafe = initialiseOrRemoveDependency(safeStore, waitingSafe, loadDepId, waiting.partialDeps().participants(loadDepId));
}
}
@@ -1141,7 +1106,7 @@ public class Commands
if (depSafe == null)
{
loadDepId = directlyBlockedOn;
- safeStore.commandStore().execute(this, this).begin(safeStore.agent());
+ safeStore.commandStore().execute(this, this, safeStore.agent());
return;
}
}
@@ -1158,45 +1123,11 @@ public class Commands
{
// TODO (desired): slightly costly to invert a large partialDeps collection
participants = waiting.partialDeps().participants(dep.txnId());
- Participants<?> executes = participants.intersecting(waiting.participants().stillExecutes(), Minimal);
+ Participants<?> stillExecutes = participants.intersecting(waiting.participants().stillExecutes(), Minimal);
- RedundantStatus redundantStatus = safeStore.redundantBefore().status(dep.txnId(), null, executes);
- switch (redundantStatus)
- {
- default: throw new AssertionError("Unknown redundant status: " + redundantStatus);
- case WAS_OWNED:
- case WAS_OWNED_CLOSED:
- if (waitingId.awaitsPreviouslyOwned())
- break;
-
- case WAS_OWNED_PARTIALLY_RETIRED:
- case WAS_OWNED_RETIRED:
- case NOT_OWNED:
- if (!waitingId.awaitsPreviouslyOwned() && !safeStore.redundantBefore().preBootstrapOrStale(waitingId, participants).isAny())
- throw illegalState("Invalid state: %s waiting for execution of %s that is not owned at the execution time %s", waitingId, dep.txnId(), waiting.executeAt());
-
- removeRedundantDependencies(safeStore, waitingSafe, dep.txnId());
- depSafe = null;
- continue;
-
- case PARTIALLY_LOCALLY_REDUNDANT:
- case LOCALLY_REDUNDANT:
- case PARTIALLY_SHARD_REDUNDANT:
- case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
- case SHARD_REDUNDANT:
- case TRUNCATE_BEFORE:
- case GC_BEFORE:
- Invariants.require(dep.hasBeen(Applied) || !dep.hasBeen(PreCommitted));
- case PRE_BOOTSTRAP_OR_STALE:
- case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- // we've been applied, invalidated, or are no longer relevant
- removeRedundantDependencies(safeStore, waitingSafe, dep.txnId());
- depSafe = null;
- continue;
-
- case LIVE:
- case PARTIALLY_PRE_BOOTSTRAP_OR_STALE:
- }
+ depSafe = maybeCleanupRedundantDependency(safeStore, waitingSafe, depSafe, stillExecutes);
+ if (depSafe == null)
+ continue;
}
switch (depExecution)
@@ -1205,13 +1136,13 @@ public class Commands
case NotReady:
if (logger.isTraceEnabled()) logger.trace("{} blocked on {} until ReadyToExclude", waitingId, dep.txnId());
safeStore.registerListener(depSafe, HasDecidedExecuteAt.unblockedFrom, waitingId);
- safeStore.progressLog().waiting(HasDecidedExecuteAt, safeStore, depSafe, dep.route(), participants, null);
+ safeStore.progressLog().waiting(HasDecidedExecuteAt, safeStore, depSafe, null, participants, null);
return;
case ReadyToExclude:
case WaitingToExecute:
case ReadyToExecute:
- safeStore.progressLog().waiting(CanApply, safeStore, depSafe, dep.route(), participants, null);
+ safeStore.progressLog().waiting(CanApply, safeStore, depSafe, null, participants, null);
case Applying:
safeStore.registerListener(depSafe, SaveStatus.Applied, waitingId);
@@ -1249,6 +1180,46 @@ public class Commands
}
}
+ static SafeCommand maybeCleanupRedundantDependency(SafeCommandStore safeStore, SafeCommand waitingSafe, SafeCommand depSafe, Participants<?> executes)
+ {
+ return maybeCleanupRedundantDependency(safeStore, waitingSafe, depSafe.txnId(), sc -> sc.current().saveStatus(), executes, depSafe);
+ }
+
+ static SafeCommand initialiseOrRemoveDependency(SafeCommandStore safeStore, SafeCommand waitingSafe, TxnId depId, Participants<?> executes)
+ {
+ depId = maybeCleanupRedundantDependency(safeStore, waitingSafe, depId, ignore -> Uninitialised, executes, depId);
+ return depId != null ? safeStore.get(depId) : null;
+ }
+
+ // executes is not expected to be stillExecutes, i.e. does not need to remove pre-bootstrap, stale or was-owned+redundant
+ // (although in the hot path this is the case)
+ static <R> R maybeCleanupRedundantDependency(SafeCommandStore safeStore, SafeCommand waitingSafe, TxnId depId, Function<R, SaveStatus> saveStatusGetter, Participants<?> executes, R ifNotRedundant)
+ {
+ RedundantStatus status = safeStore.redundantBefore().status(depId, null, executes);
+ if (status.get(LOCALLY_REDUNDANT) == NONE)
+ return ifNotRedundant;
+
+ if (status.get(LOCALLY_APPLIED) != NONE)
+ {
+ // we've been applied or invalidated
+ SaveStatus saveStatus = saveStatusGetter.apply(ifNotRedundant);
+ Invariants.require(saveStatus.hasBeen(Applied) || !saveStatus.hasBeen(PreCommitted));
+ removeRedundantDependencies(safeStore, waitingSafe, depId);
+ return null;
+ }
+
+ boolean remove = status.get(LOCALLY_REDUNDANT) == ALL;
+ if (remove && waitingSafe.txnId().awaitsPreviouslyOwned())
+ remove = status.get(LOCALLY_SYNCED) == ALL || status.get(PRE_BOOTSTRAP_OR_STALE) == ALL;
+
+ if (!remove)
+ return ifNotRedundant;
+
+ if (status.get(WAS_OWNED) == ALL) removeNoLongerOwnedDependency(safeStore, waitingSafe, depId);
+ else removeRedundantDependencies(safeStore, waitingSafe, depId);
+ return null;
+ }
+
@Override
public TxnId primaryTxnId()
{
diff --git a/accord-core/src/main/java/accord/local/Node.java b/accord-core/src/main/java/accord/local/Node.java
index e199c56c..fe4a709d 100644
--- a/accord-core/src/main/java/accord/local/Node.java
+++ b/accord-core/src/main/java/accord/local/Node.java
@@ -75,6 +75,7 @@ import accord.primitives.Seekables;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
+import accord.primitives.TxnId.Cardinality;
import accord.primitives.Unseekables;
import accord.topology.Shard;
import accord.topology.Topology;
@@ -98,7 +99,10 @@ import net.nicoulaj.compilecommand.annotations.Inline;
import static accord.api.ProtocolModifiers.Toggles.ensurePermitted;
import static accord.api.ProtocolModifiers.Toggles.defaultMediumPath;
import static accord.api.ProtocolModifiers.Toggles.usePrivilegedCoordinator;
-import static accord.primitives.TxnId.FastPath.UNOPTIMISED;
+import static accord.primitives.Routable.Domain.Key;
+import static accord.primitives.TxnId.Cardinality.Any;
+import static accord.primitives.TxnId.Cardinality.cardinality;
+import static accord.primitives.TxnId.FastPath.Unoptimised;
import static accord.utils.Invariants.illegalState;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
@@ -171,7 +175,6 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
private final RandomSource random;
private final LocalConfig localConfig;
- // TODO (expected, consider): this really needs to be thought through some more, as it needs to be per-instance in some cases, and per-node in others
private final Scheduler scheduler;
private final DurabilityScheduling durabilityScheduling;
@@ -682,16 +685,27 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
public TxnId nextTxnId(Txn.Kind rw, Domain domain)
{
- return nextTxnId(rw, domain, defaultMediumPath().bits);
+ return nextTxnId(rw, domain, Any, defaultMediumPath().bit());
+ }
+
+ public TxnId nextTxnId(Txn.Kind rw, Domain domain, Cardinality cardinality)
+ {
+ return nextTxnId(rw, domain, cardinality, defaultMediumPath().bit());
+ }
+
+ public TxnId nextTxnId(Txn.Kind rw, Domain domain, int flags)
+ {
+ return nextTxnId(rw, domain, Any, flags);
}
/**
* TODO (required): Make sure we cannot re-issue the same txnid on startup
+ * TODO (required): Don't use a new epoch for the TxnId at least until we know its definition
*/
- public TxnId nextTxnId(Txn.Kind rw, Domain domain, int flags)
+ public TxnId nextTxnId(Txn.Kind rw, Domain domain, Cardinality cardinality, int flags)
{
- Invariants.require(domain == Domain.Key || rw != Txn.Kind.Write, "Range writes not supported without forwarding uniqueHlc information to WaitingOn for direct dependencies");
- TxnId txnId = new TxnId(uniqueNow(), flags, rw, domain);
+ Invariants.require(domain == Key || rw != Txn.Kind.Write, "Range writes not supported without forwarding uniqueHlc information to WaitingOn for direct dependencies");
+ TxnId txnId = new TxnId(uniqueNow(), flags, rw, domain, cardinality);
Invariants.require((txnId.lsb & (0xffff & ~TxnId.IDENTITY_FLAGS)) == 0);
return txnId;
}
@@ -701,12 +715,13 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
Seekables<?, ?> keys = txn.keys();
Txn.Kind kind = txn.kind();
Domain domain = keys.domain();
+ Cardinality cardinality = cardinality(domain, keys);
if (!usePrivilegedCoordinator())
- return nextTxnId(kind, domain);
+ return nextTxnId(kind, domain, cardinality);
Timestamp now = uniqueNow();
int flags = computeBestDefaultTxnIdFlags(keys, now.epoch());
- TxnId txnId = new TxnId(now, flags, kind, domain);
+ TxnId txnId = new TxnId(now, flags, kind, domain, cardinality);
Invariants.require((txnId.lsb & (0xffff & ~TxnId.IDENTITY_FLAGS)) == 0);
return txnId;
}
@@ -714,10 +729,10 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
private int computeBestDefaultTxnIdFlags(Routables<?> keys, long epoch)
{
if (!topology.hasEpoch(epoch) || !usePrivilegedCoordinator())
- return defaultMediumPath().bits;
+ return defaultMediumPath().bit();
TxnId.FastPath fastPath = ensurePermitted(topology().selectFastPath(keys, epoch));
- return fastPath.bits | defaultMediumPath().bits;
+ return fastPath.bits | defaultMediumPath().bit();
}
public TxnId nextTxnId(Txn txn, TxnId.FastPath fastPath, TxnId.MediumPath mediumPath)
@@ -728,10 +743,11 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
Timestamp now = uniqueNow();
fastPath = ensurePermitted(fastPath);
- if (fastPath != UNOPTIMISED && (!topology.hasEpoch(now.epoch()) || !topology.supportsPrivilegedFastPath(keys, now.epoch())))
- fastPath = UNOPTIMISED;
+ if (fastPath != Unoptimised && (!topology.hasEpoch(now.epoch()) || !topology.supportsPrivilegedFastPath(keys, now.epoch())))
+ fastPath = Unoptimised;
- return nextTxnId(kind, domain, fastPath.bits | mediumPath.bits);
+ Cardinality cardinality = cardinality(domain, keys);
+ return nextTxnId(kind, domain, cardinality, fastPath.bits | mediumPath.bit());
}
public AsyncResult<Result> coordinate(Txn txn)
@@ -748,9 +764,6 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
// TODO (required): plumb deadlineNanos in (perhaps on integration side, but maybe introduce some context we can pass through for the MessageSink)
public AsyncResult<Result> coordinate(TxnId txnId, Txn txn, long minEpoch, long deadlineNanos)
{
- // TODO (desirable, consider): The combination of updating the epoch of the next timestamp with epochs we don't have topologies for,
- // and requiring preaccept to talk to its topology epoch means that learning of a new epoch via timestamp
- // (ie not via config service) will halt any new txns from a node until it receives this topology
AsyncResult<Result> result = withEpoch(Math.max(txnId.epoch(), minEpoch), () -> initiateCoordination(txnId, txn)).beginAsResult();
coordinating.putIfAbsent(txnId, result);
result.addCallback((success, fail) -> coordinating.remove(txnId, result));
diff --git a/accord-core/src/main/java/accord/local/PreLoadContext.java b/accord-core/src/main/java/accord/local/PreLoadContext.java
index f4a68e6a..e322470e 100644
--- a/accord-core/src/main/java/accord/local/PreLoadContext.java
+++ b/accord-core/src/main/java/accord/local/PreLoadContext.java
@@ -52,10 +52,7 @@ public interface PreLoadContext
* This should ONLY be non-null if primaryTxnId() is non-null
*
* TODO (expected): this is used for Apply, NotifyWaitingOn and listenerContexts; others only use a single txnId
- * firstly, it would be nice to simply have that txnId as a single value.
- * In the case of Apply, we can likely avoid loading all dependent transactions, if we can track which ranges
- * out of memory have un-applied transactions (and try not to evict those that are not applied).
- * Either way, the information we need in memory is super minimal for secondary transactions.
+ * The information we need in memory is super minimal for secondary transactions (mostly just SaveStatus?).
*/
default @Nullable TxnId additionalTxnId() { return null; }
@@ -93,12 +90,7 @@ public interface PreLoadContext
/**
* @return keys of the {@link CommandsForKey} objects that need to be loaded into memory before this operation is run
- *
- * TODO (expected, efficiency): this used for only two things: calculateDeps and CommandStore.register.
- * Both can be done without. For range transactions calculateDeps needs to be asynchronous anyway to support
- * potentially large scans, and for register we do not need to load into memory, we can perform a blind write.
*/
- // TODO (required): specify epochs for which we should load, so we can narrow to owned keys
default Unseekables<?> keys() { return RoutingKeys.EMPTY; }
default KeyHistory keyHistory() { return NONE; }
diff --git a/accord-core/src/main/java/accord/local/RedundantBefore.java b/accord-core/src/main/java/accord/local/RedundantBefore.java
index c9eea0e2..362227fe 100644
--- a/accord-core/src/main/java/accord/local/RedundantBefore.java
+++ b/accord-core/src/main/java/accord/local/RedundantBefore.java
@@ -22,14 +22,13 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
-import java.util.function.BiPredicate;
import java.util.function.Function;
-import java.util.function.Predicate;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import accord.api.RoutingKey;
import accord.api.VisibleForImplementation;
+import accord.local.RedundantStatus.Coverage;
import accord.primitives.AbstractRanges;
import accord.primitives.Deps;
import accord.primitives.EpochSupplier;
@@ -49,23 +48,21 @@ import accord.utils.ReducingRangeMap;
import org.agrona.collections.Int2ObjectHashMap;
import static accord.api.ProtocolModifiers.Toggles.requiresUniqueHlcs;
-import static accord.local.RedundantBefore.PreBootstrapOrStale.FULLY;
-import static accord.local.RedundantBefore.PreBootstrapOrStale.POST_BOOTSTRAP;
-import static accord.local.RedundantBefore.PreBootstrapOrStale.PARTIALLY;
-import static accord.local.RedundantStatus.GC_BEFORE;
-import static accord.local.RedundantStatus.LIVE;
-import static accord.local.RedundantStatus.LOCALLY_REDUNDANT;
-import static accord.local.RedundantStatus.NOT_OWNED;
-import static accord.local.RedundantStatus.PRE_BOOTSTRAP_OR_STALE;
-import static accord.local.RedundantStatus.SHARD_REDUNDANT;
-import static accord.local.RedundantStatus.SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE;
-import static accord.local.RedundantStatus.TRUNCATE_BEFORE;
-import static accord.local.RedundantStatus.WAS_OWNED;
-import static accord.local.RedundantStatus.WAS_OWNED_CLOSED;
-import static accord.local.RedundantStatus.WAS_OWNED_PARTIALLY_RETIRED;
-import static accord.local.RedundantStatus.WAS_OWNED_RETIRED;
+import static accord.local.RedundantStatus.GC_BEFORE_ONLY;
+import static accord.local.RedundantStatus.LOCALLY_REDUNDANT_ONLY;
+import static accord.local.RedundantStatus.LOCALLY_SYNCED_AND_PRE_BOOTSTRAP_OR_STALE;
+import static accord.local.RedundantStatus.NOT_OWNED_ONLY;
+import static accord.local.RedundantStatus.PRE_BOOTSTRAP_OR_STALE_ONLY;
+import static accord.local.RedundantStatus.Property.LOCALLY_REDUNDANT;
+import static accord.local.RedundantStatus.Property.PRE_BOOTSTRAP_OR_STALE;
+import static accord.local.RedundantStatus.SHARD_AND_LOCALLY_APPLIED_ONLY;
+import static accord.local.RedundantStatus.SHARD_APPLIED_AND_LOCALLY_SYNCED_AND_PRE_BOOTSTRAP_OR_STALE;
+import static accord.local.RedundantStatus.SHARD_ONLY_APPLIED_AND_PRE_BOOTSTRAP_OR_STALE;
+import static accord.local.RedundantStatus.TRUNCATE_BEFORE_ONLY;
+import static accord.local.RedundantStatus.WAS_OWNED_LOCALLY_RETIRED;
+import static accord.local.RedundantStatus.WAS_OWNED_ONLY;
+import static accord.local.RedundantStatus.WAS_OWNED_SHARD_RETIRED;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
-import static accord.primitives.Txn.Kind.Write;
import static accord.utils.Invariants.illegalState;
import static accord.utils.Invariants.requirePartiallyOrdered;
@@ -84,19 +81,6 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
}
}
- public enum PreBootstrapOrStale
- {
- NOT_OWNED,
- FULLY,
- PARTIALLY,
- POST_BOOTSTRAP;
-
- public boolean isAny()
- {
- return this == PARTIALLY || this == FULLY;
- }
- }
-
// TODO (required): rationalise the various bounds we maintain; make merge idempotent and apply any filtering by superseding bounds on access
public static class Entry
{
@@ -108,35 +92,35 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
/**
* Represents the maximum TxnId we know to have a record of transactions before, or else they will be invalidated.
*/
- public final @Nonnull TxnId locallyWitnessedOrInvalidatedBefore;
+ public final @Nonnull TxnId locallyWitnessedBefore;
/**
* Represents the maximum TxnId we know to have fully executed until locally for the range in question.
* Unless we are stale or pre-bootstrap, in which case no such guarantees can be made.
*
- * We maintain locallyAppliedOrInvalidatedBefore that were reached prior to a new bootstrap exceeding them,
+ * We maintain locallyAppliedBefore that were reached prior to a new bootstrap exceeding them,
* as these were reached correctly.
*/
- public final @Nonnull TxnId locallyAppliedOrInvalidatedBefore;
+ public final @Nonnull TxnId locallyAppliedBefore;
/**
* Represents the maximum TxnId we know to have fully executed until locally for the range in question,
* and for which we guarantee that any distributed decision that might need to be consulted is also recorded
* locally (i.e. it is known to be Stable locally, or else it did not execute)
*
- * We maintain locallyDecidedAndAppliedOrInvalidatedBefore that were reached prior to a new bootstrap exceeding them,
+ * We maintain locallyDecidedAndAppliedBefore that were reached prior to a new bootstrap exceeding them,
* as these were reached correctly and can be used for pruning CommandsForKey.
*
- * However, once a bootstrap has begun we cannot safely advance until shardAppliedOrInvalidatedBefore goes
+ * However, once a bootstrap has begun we cannot safely advance until shardAppliedBefore goes
* ahead of the bootstrappedAt, because we cannot guarantee to have any intervening decision recorded locally.
*/
- public final @Nonnull TxnId locallyDecidedAndAppliedOrInvalidatedBefore;
+ public final @Nonnull TxnId locallyDecidedAndAppliedBefore;
/**
* Represents the maximum TxnId we know to have fully executed until across all healthy non-bootstrapping replicas
* for the range in question.
*/
- public final @Nonnull TxnId shardOnlyAppliedOrInvalidatedBefore;
+ public final @Nonnull TxnId shardOnlyAppliedBefore;
/**
* Represents the maximum TxnId we know to have fully executed until across all healthy non-bootstrapping replicas
@@ -146,13 +130,13 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
* invalidations, but remember that if we are erasing data we may report to peers then we must provide an RX
* in place of that data to prevent a stale peer thinking they have enough information.
*/
- public final @Nonnull TxnId shardAppliedOrInvalidatedBefore;
+ public final @Nonnull TxnId shardAppliedBefore;
/**
* Represents the maximum TxnId we know to have fully executed until across all healthy replicas for the range in question.
* Unless we are stale or pre-bootstrap, in which case no such guarantees can be made.
*
- * TODO (expected): track separate gcHlcBefore (i.e. gcBefore where is(HLC_BOUND))
+ * TODO (desired): track separate gcHlcBefore
*/
public final @Nonnull TxnId gcBefore;
@@ -165,7 +149,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
* We can also re-bootstrap the same range because bootstrap failed, and leave dangling transactions to execute
* which then execute in an unordered fashion.
*
- * See also {@link CommandStore#safeToRead}.
+ * See also {@link SafeCommandStore#safeToReadAt()}.
*/
public final @Nonnull TxnId bootstrappedAt;
@@ -173,28 +157,28 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
* staleUntilAtLeast provides a minimum TxnId until which we know we will be unable to completely execute
* transactions locally for the impacted range.
*
- * See also {@link CommandStore#safeToRead}.
+ * See also {@link SafeCommandStore#safeToReadAt()}.
*/
public final @Nullable Timestamp staleUntilAtLeast;
- public Entry(Range range, long startOwnershipEpoch, long endOwnershipEpoch, @Nonnull TxnId locallyWitnessedOrInvalidatedBefore, @Nonnull TxnId locallyAppliedOrInvalidatedBefore, @Nonnull TxnId locallyDecidedAndAppliedOrInvalidatedBefore, @Nonnull TxnId shardOnlyAppliedOrInvalidatedBefore, @Nonnull TxnId shardAppliedOrInvalidatedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt, @Nullable Timestamp staleUntilAtLeast)
+ public Entry(Range range, long startOwnershipEpoch, long endOwnershipEpoch, @Nonnull TxnId locallyWitnessedBefore, @Nonnull TxnId locallyAppliedBefore, @Nonnull TxnId locallyDecidedAndAppliedBefore, @Nonnull TxnId shardOnlyAppliedBefore, @Nonnull TxnId shardAppliedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt, @Nullable Timestamp staleUntilAtLeast)
{
this.range = range;
this.startOwnershipEpoch = startOwnershipEpoch;
this.endOwnershipEpoch = endOwnershipEpoch;
- this.locallyWitnessedOrInvalidatedBefore = locallyWitnessedOrInvalidatedBefore;
- this.locallyAppliedOrInvalidatedBefore = locallyAppliedOrInvalidatedBefore;
- this.locallyDecidedAndAppliedOrInvalidatedBefore = locallyDecidedAndAppliedOrInvalidatedBefore;
- this.shardOnlyAppliedOrInvalidatedBefore = shardOnlyAppliedOrInvalidatedBefore;
- this.shardAppliedOrInvalidatedBefore = shardAppliedOrInvalidatedBefore;
+ this.locallyWitnessedBefore = locallyWitnessedBefore;
+ this.locallyAppliedBefore = locallyAppliedBefore;
+ this.locallyDecidedAndAppliedBefore = locallyDecidedAndAppliedBefore;
+ this.shardOnlyAppliedBefore = shardOnlyAppliedBefore;
+ this.shardAppliedBefore = shardAppliedBefore;
this.gcBefore = gcBefore;
this.bootstrappedAt = bootstrappedAt;
this.staleUntilAtLeast = staleUntilAtLeast;
- checkNoneOrRX(locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, locallyDecidedAndAppliedOrInvalidatedBefore,
- shardAppliedOrInvalidatedBefore, gcBefore);
- requirePartiallyOrdered(locallyDecidedAndAppliedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore);
- requirePartiallyOrdered(shardAppliedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore);
- requirePartiallyOrdered(gcBefore, shardAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore);
+ checkNoneOrRX(locallyWitnessedBefore, locallyAppliedBefore, locallyDecidedAndAppliedBefore,
+ shardAppliedBefore, gcBefore);
+ requirePartiallyOrdered(locallyDecidedAndAppliedBefore, locallyAppliedBefore);
+ requirePartiallyOrdered(shardAppliedBefore, locallyAppliedBefore);
+ requirePartiallyOrdered(gcBefore, shardAppliedBefore, shardOnlyAppliedBefore);
}
private static void checkNoneOrRX(TxnId ... txnIds)
@@ -223,10 +207,10 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
long startEpoch = Long.max(cur.startOwnershipEpoch, add.startOwnershipEpoch);
long endEpoch = Long.min(cur.endOwnershipEpoch, add.endOwnershipEpoch);
- int cw = cur.locallyWitnessedOrInvalidatedBefore.compareTo(add.locallyWitnessedOrInvalidatedBefore);
- int cl = cur.locallyAppliedOrInvalidatedBefore.compareTo(add.locallyAppliedOrInvalidatedBefore);
- int cd = cur.locallyDecidedAndAppliedOrInvalidatedBefore.compareTo(add.locallyDecidedAndAppliedOrInvalidatedBefore);
- int cs = cur.shardOnlyAppliedOrInvalidatedBefore.compareTo(add.shardOnlyAppliedOrInvalidatedBefore);
+ int cw = cur.locallyWitnessedBefore.compareTo(add.locallyWitnessedBefore);
+ int cl = cur.locallyAppliedBefore.compareTo(add.locallyAppliedBefore);
+ int cd = cur.locallyDecidedAndAppliedBefore.compareTo(add.locallyDecidedAndAppliedBefore);
+ int cs = cur.shardOnlyAppliedBefore.compareTo(add.shardOnlyAppliedBefore);
int cg = cur.gcBefore.compareTo(add.gcBefore);
int cb = cur.bootstrappedAt.compareTo(add.bootstrappedAt);
int csu = compareStaleUntilAtLeast(cur.staleUntilAtLeast, add.staleUntilAtLeast);
@@ -236,10 +220,10 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (range.equals(add.range) && startEpoch == add.startOwnershipEpoch && endEpoch == add.endOwnershipEpoch && cw <= 0 && cl <= 0 && cd >= 0 && cs <= 0 && cg <= 0 && cb <= 0 && csu <= 0)
return add;
- TxnId locallyWitnessedOrInvalidatedBefore = cw >= 0 ? cur.locallyWitnessedOrInvalidatedBefore : add.locallyWitnessedOrInvalidatedBefore;
- TxnId locallyAppliedOrInvalidatedBefore = cl >= 0 ? cur.locallyAppliedOrInvalidatedBefore : add.locallyAppliedOrInvalidatedBefore;
- TxnId locallyDecidedAndAppliedOrInvalidatedBefore = cd >= 0 ? cur.locallyDecidedAndAppliedOrInvalidatedBefore : add.locallyDecidedAndAppliedOrInvalidatedBefore;
- TxnId shardOnlyAppliedOrInvalidatedBefore = cs >= 0 ? cur.shardOnlyAppliedOrInvalidatedBefore : add.shardOnlyAppliedOrInvalidatedBefore;
+ TxnId locallyWitnessedBefore = cw >= 0 ? cur.locallyWitnessedBefore : add.locallyWitnessedBefore;
+ TxnId locallyAppliedBefore = cl >= 0 ? cur.locallyAppliedBefore : add.locallyAppliedBefore;
+ TxnId locallyDecidedAndAppliedBefore = cd >= 0 ? cur.locallyDecidedAndAppliedBefore : add.locallyDecidedAndAppliedBefore;
+ TxnId shardOnlyAppliedBefore = cs >= 0 ? cur.shardOnlyAppliedBefore : add.shardOnlyAppliedBefore;
TxnId gcBefore = cg >= 0 ? cur.gcBefore : add.gcBefore;
TxnId bootstrappedAt = cb >= 0 ? cur.bootstrappedAt : add.bootstrappedAt;
Timestamp staleUntilAtLeast = csu >= 0 ? cur.staleUntilAtLeast : add.staleUntilAtLeast;
@@ -248,19 +232,19 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
// treating transactions prior as locally redundant when they may simply have not applied yet, since we may
// permit the sync point that defines redundancy to apply locally without waiting for these earlier
// transactions, since we now consider them to be bootstrapping.
- // however, any locallyAppliedOrInvalidatedBefore that was set before bootstrap can be safely maintained,
+ // however, any locallyAppliedBefore that was set before bootstrap can be safely maintained,
// and should not ideally go backwards (as CommandsForKey utilises it for GC)
// TODO (desired): revisit later as semantics here evolve
- if (bootstrappedAt.compareTo(locallyAppliedOrInvalidatedBefore) >= 0)
- locallyAppliedOrInvalidatedBefore = cur.locallyAppliedOrInvalidatedBefore;
+ if (bootstrappedAt.compareTo(locallyAppliedBefore) >= 0)
+ locallyAppliedBefore = cur.locallyAppliedBefore;
- TxnId shardAppliedOrInvalidatedBefore = TxnId.min(shardOnlyAppliedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore);
- if (bootstrappedAt.compareTo(shardAppliedOrInvalidatedBefore) >= 0)
- locallyDecidedAndAppliedOrInvalidatedBefore = cur.locallyDecidedAndAppliedOrInvalidatedBefore;
+ TxnId shardAppliedBefore = TxnId.min(shardOnlyAppliedBefore, locallyAppliedBefore);
+ if (bootstrappedAt.compareTo(shardAppliedBefore) >= 0)
+ locallyDecidedAndAppliedBefore = cur.locallyDecidedAndAppliedBefore;
if (staleUntilAtLeast != null && bootstrappedAt.compareTo(staleUntilAtLeast) >= 0)
staleUntilAtLeast = null;
- return new Entry(range, startEpoch, endEpoch, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, locallyDecidedAndAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
+ return new Entry(range, startEpoch, endEpoch, locallyWitnessedBefore, locallyAppliedBefore, locallyDecidedAndAppliedBefore, shardOnlyAppliedBefore, shardAppliedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
}
public Entry withGcBeforeBeforeAtLeast(TxnId newGcBefore)
@@ -268,10 +252,10 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (newGcBefore.compareTo(gcBefore) <= 0)
return this;
- TxnId locallyAppliedOrInvalidatedBefore = TxnId.nonNullOrMax(this.locallyAppliedOrInvalidatedBefore, newGcBefore);
- TxnId shardAppliedOrInvalidatedBefore = TxnId.nonNullOrMax(this.shardAppliedOrInvalidatedBefore, newGcBefore);
- TxnId shardOnlyAppliedOrInvalidatedBefore = TxnId.nonNullOrMax(this.shardOnlyAppliedOrInvalidatedBefore, newGcBefore);
- return new Entry(range, startOwnershipEpoch, endOwnershipEpoch, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, locallyDecidedAndAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, newGcBefore, bootstrappedAt, staleUntilAtLeast);
+ TxnId locallyAppliedBefore = TxnId.nonNullOrMax(this.locallyAppliedBefore, newGcBefore);
+ TxnId shardAppliedBefore = TxnId.nonNullOrMax(this.shardAppliedBefore, newGcBefore);
+ TxnId shardOnlyAppliedBefore = TxnId.nonNullOrMax(this.shardOnlyAppliedBefore, newGcBefore);
+ return new Entry(range, startOwnershipEpoch, endOwnershipEpoch, locallyWitnessedBefore, locallyAppliedBefore, locallyDecidedAndAppliedBefore, shardOnlyAppliedBefore, shardAppliedBefore, newGcBefore, bootstrappedAt, staleUntilAtLeast);
}
public Entry withBootstrappedAtLeast(TxnId newBootstrappedAt)
@@ -279,100 +263,26 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (newBootstrappedAt.compareTo(gcBefore) <= 0)
return this;
- return new Entry(range, startOwnershipEpoch, endOwnershipEpoch, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, locallyDecidedAndAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, gcBefore, newBootstrappedAt, staleUntilAtLeast);
+ return new Entry(range, startOwnershipEpoch, endOwnershipEpoch, locallyWitnessedBefore, locallyAppliedBefore, locallyDecidedAndAppliedBefore, shardOnlyAppliedBefore, shardAppliedBefore, gcBefore, newBootstrappedAt, staleUntilAtLeast);
}
@VisibleForImplementation
public Entry withEpochs(long start, long end)
{
- return new Entry(range, start, end, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, locallyDecidedAndAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
+ return new Entry(range, start, end, locallyWitnessedBefore, locallyAppliedBefore, locallyDecidedAndAppliedBefore, shardOnlyAppliedBefore, shardAppliedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
}
static @Nonnull Boolean isShardOnlyRedundant(Entry entry, @Nonnull Boolean prev, TxnId txnId)
{
- return entry == null ? prev : entry.shardOnlyAppliedOrInvalidatedBefore.compareTo(txnId) >= 0;
- }
-
- static @Nonnull Boolean isAnyOnCoordinationEpochShardRedundant(Entry entry, @Nonnull Boolean prev, TxnId txnId)
- {
- return isAnyOnCoordinationEpochAtLeast(entry, prev, txnId, SHARD_REDUNDANT);
- }
-
- static @Nonnull RedundantStatus getAndMerge(Entry entry, @Nonnull RedundantStatus prev, TxnId txnId, @Nullable Timestamp executeAtIfKnown)
- {
- if (entry == null)
- return prev;
- return prev.merge(entry.get(txnId, executeAtIfKnown));
- }
-
- static @Nonnull Boolean isAnyOnCoordinationEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, RedundantStatus status)
- {
- return isAnyOnCoordinationEpoch(entry, prev, txnId, status, (a, b) -> a == b);
- }
-
- static @Nonnull Boolean isAnyOnCoordinationEpochAtLeast(Entry entry, @Nonnull Boolean prev, TxnId txnId, RedundantStatus status)
- {
- return isAnyOnCoordinationEpoch(entry, prev, txnId, status, (a, b) -> a.compareTo(b) >= 0);
- }
-
- static @Nonnull Boolean isAnyOnCoordinationEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, RedundantStatus test, BiPredicate<RedundantStatus, RedundantStatus> predicate)
- {
- if (entry == null || prev)
- return prev;
-
- long epoch = txnId.epoch();
- if (entry.startOwnershipEpoch > epoch || entry.endOwnershipEpoch <= epoch)
- return prev;
-
- return predicate.test(entry.getIgnoringOwnership(txnId, null), test);
- }
-
- static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, Timestamp executeAt, RedundantStatus test, BiPredicate<RedundantStatus, RedundantStatus> predicate)
- {
- if (entry == null || prev)
- return prev;
-
- return predicate.test(entry.get(txnId, executeAt), test);
- }
-
- static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, Timestamp executeAt, RedundantStatus status)
- {
- return isAnyOnAnyEpoch(entry, prev, txnId, executeAt, status, (a, b) -> a == b);
- }
-
- static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, Timestamp executeAt, Predicate<RedundantStatus> testStatus)
- {
- if (entry == null || prev)
- return prev;
-
- return testStatus.test(entry.get(txnId, executeAt));
+ return entry == null ? prev : entry.shardOnlyAppliedBefore.compareTo(txnId) >= 0;
}
- static @Nonnull Boolean isAnyOnAnyEpochAtLeast(Entry entry, @Nonnull Boolean prev, TxnId txnId, RedundantStatus status)
- {
- return isAnyOnAnyEpoch(entry, prev, txnId, null, status, (a, b) -> a.compareTo(b) >= 0);
- }
-
- static RedundantStatus get(Entry entry, TxnId txnId, Timestamp executeAt)
+ static @Nullable RedundantStatus getAndMerge(Entry entry, @Nullable RedundantStatus prev, TxnId txnId, @Nullable Timestamp executeAtIfKnown)
{
if (entry == null)
- return NOT_OWNED;
-
- return entry.get(txnId, executeAt);
- }
-
- static PreBootstrapOrStale getAndMerge(Entry entry, @Nonnull PreBootstrapOrStale prev, TxnId txnId, Object ignore)
- {
- if (prev == PARTIALLY || entry == null)
return prev;
-
- // TODO (required): consider all call-sites and confirm the answers when wasOwned and willBeOwned are reasonable
- if (entry.wasOwned(txnId) && entry.isLocallyRetired())
- return prev;
-
- boolean isPreBootstrapOrStale = entry.staleUntilAtLeast != null || entry.bootstrappedAt.compareTo(txnId) > 0;
- return isPreBootstrapOrStale ? prev == POST_BOOTSTRAP ? PARTIALLY : FULLY
- : prev == FULLY ? PARTIALLY : POST_BOOTSTRAP;
+ RedundantStatus next = entry.get(txnId, executeAtIfKnown);
+ return prev == null ? next : prev.merge(next);
}
static RangeDeps.BuilderByRange collectDep(Entry entry, @Nonnull RangeDeps.BuilderByRange prev, @Nonnull EpochSupplier minEpoch, @Nonnull EpochSupplier executeAt)
@@ -384,8 +294,8 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
// transitive dependency history. If we consistently only GC'd at gcBefore we could report this bound,
// but since it is likely safe to use this bound in cases that don't have lagged durability,
// we conservatively report this bound since it is expected to be applied already at all non-stale shards
- if (entry.shardAppliedOrInvalidatedBefore.compareTo(Timestamp.NONE) > 0)
- prev.add(entry.range, entry.shardAppliedOrInvalidatedBefore);
+ if (entry.shardAppliedBefore.compareTo(Timestamp.NONE) > 0)
+ prev.add(entry.range, entry.shardAppliedBefore);
return prev;
}
@@ -455,10 +365,11 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (entry == null)
return execute;
- Invariants.require(executeAt == null ? !entry.outOfBounds(txnId) : !entry.outOfBounds(txnId, executeAt));
- if (txnId.compareTo(entry.shardOnlyAppliedOrInvalidatedBefore) < 0
- && (txnId.compareTo(entry.bootstrappedAt) < 0
- || entry.staleUntilAtLeast != null))
+ boolean outOfBounds = executeAt == null ? entry.outOfBounds(txnId) : entry.outOfBounds(txnId, executeAt);
+ Invariants.expect(!outOfBounds, "Trying to apply withoutRedundantAnd_StaleOrPreBootstrap to %s for a range we don't own (%s), suggesting we computed ownership without an up-to-date epoch", txnId, entry);
+ if (outOfBounds || (txnId.compareTo(entry.shardOnlyAppliedBefore) < 0
+ && (txnId.compareTo(entry.bootstrappedAt) < 0
+ || entry.staleUntilAtLeast != null)))
return execute.without(Ranges.of(entry.range));
return execute;
@@ -469,7 +380,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (entry == null)
return execute;
- if (txnId.compareTo(entry.shardOnlyAppliedOrInvalidatedBefore) < 0
+ if (txnId.compareTo(entry.shardOnlyAppliedBefore) < 0
&& (entry.endOwnershipEpoch <= txnId.epoch()
|| txnId.compareTo(entry.bootstrappedAt) < 0
|| entry.staleUntilAtLeast != null))
@@ -494,7 +405,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (entry == null)
return notRetired;
- if (txnId.compareTo(entry.shardOnlyAppliedOrInvalidatedBefore) < 0 && entry.endOwnershipEpoch <= txnId.epoch())
+ if (txnId.compareTo(entry.shardOnlyAppliedBefore) < 0 && entry.endOwnershipEpoch <= txnId.epoch())
return notRetired.without(Ranges.of(entry.range));
return notRetired;
@@ -502,7 +413,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
static Ranges withoutAnyRetired(Entry entry, @Nonnull Ranges notRetired)
{
- if (entry == null || entry.endOwnershipEpoch > entry.shardAppliedOrInvalidatedBefore.epoch())
+ if (entry == null || entry.endOwnershipEpoch > entry.shardAppliedBefore.epoch())
return notRetired;
return notRetired.without(Ranges.of(entry.range));
@@ -522,9 +433,11 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
RedundantStatus get(TxnId txnId, @Nullable Timestamp executeAtIfKnown)
{
if (wasOwned(txnId))
- return isShardRetired() ? WAS_OWNED_RETIRED :
- isLocallyRetired() ? WAS_OWNED_PARTIALLY_RETIRED :
- isClosed() ? WAS_OWNED_CLOSED : WAS_OWNED;
+ {
+ if (isShardRetired()) return WAS_OWNED_SHARD_RETIRED;
+ if (isLocallyRetired()) return WAS_OWNED_LOCALLY_RETIRED;
+ return WAS_OWNED_ONLY;
+ }
return getIgnoringOwnership(txnId, executeAtIfKnown);
}
@@ -532,28 +445,36 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
{
// we have to first check bootstrappedAt, since we are not locally redundant for the covered range
// if the txnId is partially pre-bootstrap (since we may not have applied it for this range)
- if (staleUntilAtLeast != null || bootstrappedAt.compareTo(txnId) > 0)
- return shardOnlyAppliedOrInvalidatedBefore.compareTo(txnId) > 0
- ? SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE : PRE_BOOTSTRAP_OR_STALE;
+ if (staleUntilAtLeast != null || bootstrappedAt.compareTo(txnId) > 0 || txnId.epoch() < startOwnershipEpoch)
+ {
+ if (locallyAppliedBefore.compareTo(txnId) > 0)
+ {
+ return shardOnlyAppliedBefore.compareTo(txnId) > 0
+ ? SHARD_APPLIED_AND_LOCALLY_SYNCED_AND_PRE_BOOTSTRAP_OR_STALE
+ : LOCALLY_SYNCED_AND_PRE_BOOTSTRAP_OR_STALE;
+ }
+ else
+ {
+ return shardOnlyAppliedBefore.compareTo(txnId) > 0
+ ? SHARD_ONLY_APPLIED_AND_PRE_BOOTSTRAP_OR_STALE
+ : PRE_BOOTSTRAP_OR_STALE_ONLY;
+ }
+ }
- if (locallyAppliedOrInvalidatedBefore.compareTo(txnId) > 0)
+ if (locallyAppliedBefore.compareTo(txnId) > 0)
{
if (gcBefore.compareTo(txnId) > 0)
{
if (!requiresUniqueHlcs() || executeAtIfKnown == null || gcBefore.hlc() > executeAtIfKnown.uniqueHlc())
- return GC_BEFORE;
- return TRUNCATE_BEFORE;
+ return GC_BEFORE_ONLY;
+ return TRUNCATE_BEFORE_ONLY;
}
- if (shardOnlyAppliedOrInvalidatedBefore.compareTo(txnId) > 0)
- return SHARD_REDUNDANT;
- return LOCALLY_REDUNDANT;
+ if (shardOnlyAppliedBefore.compareTo(txnId) > 0)
+ return SHARD_AND_LOCALLY_APPLIED_ONLY;
+ return LOCALLY_REDUNDANT_ONLY;
}
- // TODO (expected): place this at top with related conditions?
- if (txnId.epoch() < startOwnershipEpoch)
- return PRE_BOOTSTRAP_OR_STALE;
-
- return LIVE;
+ return RedundantStatus.NONE;
}
private static int compareStaleUntilAtLeast(@Nullable Timestamp a, @Nullable Timestamp b)
@@ -570,22 +491,22 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
public final TxnId shardRedundantBefore()
{
- return shardAppliedOrInvalidatedBefore;
+ return shardAppliedBefore;
}
public final TxnId locallyWitnessedBefore()
{
- return locallyWitnessedOrInvalidatedBefore;
+ return locallyWitnessedBefore;
}
public final TxnId locallyRedundantBefore()
{
- return locallyAppliedOrInvalidatedBefore;
+ return locallyAppliedBefore;
}
public final TxnId locallyRedundantOrBootstrappedBefore()
{
- return TxnId.max(locallyAppliedOrInvalidatedBefore, bootstrappedAt);
+ return TxnId.max(locallyAppliedBefore, bootstrappedAt);
}
private boolean outOfBounds(EpochSupplier lb, EpochSupplier ub)
@@ -598,23 +519,19 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return lb.epoch() >= endOwnershipEpoch;
}
- // TODO (required): do we still need this, or can we stick to just the explicit endOwnershipEpoch
private boolean isShardRetired()
{
- // TODO (required): carefully consider whether we should ALSO expect some local property to be met here
- return endOwnershipEpoch <= shardAppliedOrInvalidatedBefore.epoch();
+ return endOwnershipEpoch <= shardAppliedBefore.epoch();
}
private boolean isLocallyRetired()
{
- // TODO (required): carefully consider whether we should ALSO expect some local property to be met here
- return endOwnershipEpoch <= locallyAppliedOrInvalidatedBefore.epoch();
+ return endOwnershipEpoch <= locallyAppliedBefore.epoch();
}
private boolean isClosed()
{
- // TODO (required): carefully consider whether we should ALSO expect some local property to be met here
- return endOwnershipEpoch <= locallyWitnessedOrInvalidatedBefore.epoch();
+ return endOwnershipEpoch <= locallyWitnessedBefore.epoch();
}
private boolean outOfBounds(Timestamp lb)
@@ -624,12 +541,12 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
Entry withEpochs(int startEpoch, int endEpoch)
{
- return new Entry(range, startEpoch, endEpoch, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, locallyDecidedAndAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
+ return new Entry(range, startEpoch, endEpoch, locallyWitnessedBefore, locallyAppliedBefore, locallyDecidedAndAppliedBefore, shardOnlyAppliedBefore, shardAppliedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
}
public Entry withRange(Range range)
{
- return new Entry(range, startOwnershipEpoch, endOwnershipEpoch, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, locallyDecidedAndAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
+ return new Entry(range, startOwnershipEpoch, endOwnershipEpoch, locallyWitnessedBefore, locallyAppliedBefore, locallyDecidedAndAppliedBefore, shardOnlyAppliedBefore, shardAppliedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
}
public boolean equals(Object that)
@@ -646,10 +563,10 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
{
return this.startOwnershipEpoch == that.startOwnershipEpoch
&& this.endOwnershipEpoch == that.endOwnershipEpoch
- && this.locallyAppliedOrInvalidatedBefore.equals(that.locallyAppliedOrInvalidatedBefore)
- && this.locallyDecidedAndAppliedOrInvalidatedBefore.equals(that.locallyDecidedAndAppliedOrInvalidatedBefore)
- && this.shardAppliedOrInvalidatedBefore.equals(that.shardAppliedOrInvalidatedBefore)
- && this.shardOnlyAppliedOrInvalidatedBefore.equals(that.shardOnlyAppliedOrInvalidatedBefore)
+ && this.locallyAppliedBefore.equals(that.locallyAppliedBefore)
+ && this.locallyDecidedAndAppliedBefore.equals(that.locallyDecidedAndAppliedBefore)
+ && this.shardAppliedBefore.equals(that.shardAppliedBefore)
+ && this.shardOnlyAppliedBefore.equals(that.shardOnlyAppliedBefore)
&& this.gcBefore.equals(that.gcBefore)
&& this.bootstrappedAt.equals(that.bootstrappedAt)
&& Objects.equals(this.staleUntilAtLeast, that.staleUntilAtLeast);
@@ -661,7 +578,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return "("
+ (startOwnershipEpoch == Long.MIN_VALUE ? "-\u221E" : Long.toString(startOwnershipEpoch)) + ","
+ (endOwnershipEpoch == Long.MAX_VALUE ? "\u221E" : Long.toString(endOwnershipEpoch)) + ","
- + (locallyAppliedOrInvalidatedBefore.compareTo(bootstrappedAt) >= 0 ? locallyAppliedOrInvalidatedBefore + ")" : bootstrappedAt + "*)");
+ + (locallyAppliedBefore.compareTo(bootstrappedAt) >= 0 ? locallyAppliedBefore + ")" : bootstrappedAt + "*)");
}
}
@@ -730,29 +647,29 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return Ranges.ofSortedAndDeoverlapped(staleRanges).mergeTouching();
}
- public static RedundantBefore create(AbstractRanges ranges, @Nonnull TxnId locallyWitnessedOrInvalidatedBefore, @Nonnull TxnId locallyAppliedOrInvalidatedBefore, @Nonnull TxnId shardAppliedOrInvalidatedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt)
+ public static RedundantBefore create(AbstractRanges ranges, @Nonnull TxnId locallyWitnessedBefore, @Nonnull TxnId locallyAppliedBefore, @Nonnull TxnId shardAppliedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt)
{
- return create(ranges, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, gcBefore, bootstrappedAt, null);
+ return create(ranges, locallyWitnessedBefore, locallyAppliedBefore, shardAppliedBefore, gcBefore, bootstrappedAt, null);
}
- public static RedundantBefore create(AbstractRanges ranges, @Nonnull TxnId locallyWitnessedOrInvalidatedBefore, @Nonnull TxnId locallyAppliedOrInvalidatedBefore, @Nonnull TxnId shardAppliedOrInvalidatedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt, @Nullable Timestamp staleUntilAtLeast)
+ public static RedundantBefore create(AbstractRanges ranges, @Nonnull TxnId locallyWitnessedBefore, @Nonnull TxnId locallyAppliedBefore, @Nonnull TxnId shardAppliedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt, @Nullable Timestamp staleUntilAtLeast)
{
- return create(ranges, Long.MIN_VALUE, Long.MAX_VALUE, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
+ return create(ranges, Long.MIN_VALUE, Long.MAX_VALUE, locallyWitnessedBefore, locallyAppliedBefore, shardAppliedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
}
- public static RedundantBefore create(AbstractRanges ranges, long startEpoch, long endEpoch, @Nonnull TxnId locallyWitnessedOrInvalidatedBefore, @Nonnull TxnId locallyAppliedOrInvalidatedBefore, @Nonnull TxnId shardOnlyAppliedOrInvalidatedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt)
+ public static RedundantBefore create(AbstractRanges ranges, long startEpoch, long endEpoch, @Nonnull TxnId locallyWitnessedBefore, @Nonnull TxnId locallyAppliedBefore, @Nonnull TxnId shardOnlyAppliedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt)
{
- return create(ranges, startEpoch, endEpoch, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore, gcBefore, bootstrappedAt, null);
+ return create(ranges, startEpoch, endEpoch, locallyWitnessedBefore, locallyAppliedBefore, shardOnlyAppliedBefore, gcBefore, bootstrappedAt, null);
}
- public static RedundantBefore create(AbstractRanges ranges, long startEpoch, long endEpoch, @Nonnull TxnId locallyWitnessedOrInvalidatedBefore, @Nonnull TxnId locallyAppliedOrInvalidatedBefore, @Nonnull TxnId shardOnlyAppliedOrInvalidatedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt, @Nullable Timestamp staleUntilAtLeast)
+ public static RedundantBefore create(AbstractRanges ranges, long startEpoch, long endEpoch, @Nonnull TxnId locallyWitnessedBefore, @Nonnull TxnId locallyAppliedBefore, @Nonnull TxnId shardOnlyAppliedBefore, @Nonnull TxnId gcBefore, @Nonnull TxnId bootstrappedAt, @Nullable Timestamp staleUntilAtLeast)
{
if (ranges.isEmpty())
return new RedundantBefore();
- TxnId locallyDecidedAndAppliedOrInvalidatedBefore = locallyAppliedOrInvalidatedBefore;
- TxnId shardAppliedOrInvalidatedBefore = TxnId.min(locallyAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore);
- Entry entry = new Entry(null, startEpoch, endEpoch, locallyWitnessedOrInvalidatedBefore, locallyAppliedOrInvalidatedBefore, locallyDecidedAndAppliedOrInvalidatedBefore, shardOnlyAppliedOrInvalidatedBefore, shardAppliedOrInvalidatedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
+ TxnId locallyDecidedAndAppliedBefore = locallyAppliedBefore;
+ TxnId shardAppliedBefore = TxnId.min(locallyAppliedBefore, shardOnlyAppliedBefore);
+ Entry entry = new Entry(null, startEpoch, endEpoch, locallyWitnessedBefore, locallyAppliedBefore, locallyDecidedAndAppliedBefore, shardOnlyAppliedBefore, shardAppliedBefore, gcBefore, bootstrappedAt, staleUntilAtLeast);
Builder builder = new Builder(ranges.get(0).endInclusive(), ranges.size() * 2);
for (int i = 0 ; i < ranges.size() ; ++i)
{
@@ -768,66 +685,49 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
}
public RedundantStatus status(TxnId txnId, @Nullable Timestamp applyAtIfKnown, Participants<?> participants)
- { // TODO (required): consider how the use of txnId for executeAt affects exclusive sync points for cleanup
- // may want to issue synthetic sync points for local evaluation in later epochs
- return foldl(participants, Entry::getAndMerge, NOT_OWNED, txnId, applyAtIfKnown, ignore -> false);
+ {
+ RedundantStatus result = foldl(participants, Entry::getAndMerge, null, txnId, applyAtIfKnown);
+ return result == null ? NOT_OWNED_ONLY : result;
}
public RedundantStatus status(TxnId txnId, @Nullable Timestamp applyAtIfKnown, RoutingKey key)
- { // TODO (required): consider how the use of txnId for executeAt affects exclusive sync points for cleanup
- // may want to issue synthetic sync points for local evaluation in later epochs
- Entry entry = get(key);
- return entry == null ? NOT_OWNED : entry.get(txnId, applyAtIfKnown);
- }
-
- public boolean isAnyOnCoordinationEpoch(TxnId txnId, Unseekables<?> participants, RedundantStatus status)
{
- return foldl(participants, Entry::isAnyOnCoordinationEpoch, false, txnId, status, isDone -> isDone);
+ Entry entry = get(key);
+ return entry == null ? NOT_OWNED_ONLY : entry.get(txnId, applyAtIfKnown);
}
public boolean isShardOnlyRedundant(TxnId txnId, Unseekables<?> participants)
{
- return foldl(participants, Entry::isShardOnlyRedundant, false, txnId, ignore -> false);
- }
-
- public boolean isAnyOnCoordinationEpochAtLeast(TxnId txnId, Unseekables<?> participants, RedundantStatus status)
- {
- return foldl(participants, Entry::isAnyOnCoordinationEpochAtLeast, false, txnId, status, isDone -> isDone);
- }
-
- public boolean isAnyOnAnyEpochAtLeast(TxnId txnId, Unseekables<?> participants, RedundantStatus status)
- {
- Invariants.requireArgument(status != GC_BEFORE || !txnId.is(Write), "Cannot compute GC_BEFORE for Write without applyAt");
- return foldl(participants, Entry::isAnyOnAnyEpochAtLeast, false, txnId, status, isDone -> isDone);
+ return foldl(participants, Entry::isShardOnlyRedundant, false, txnId);
}
/**
* RedundantStatus.REDUNDANT overrides PRE_BOOTSTRAP; to avoid complicating that state machine,
* for cases where we care independently about the overall pre-bootstrap state we have a separate mechanism
*/
- public PreBootstrapOrStale preBootstrapOrStale(TxnId txnId, Participants<?> participants)
+ public Coverage preBootstrapOrStale(TxnId txnId, Participants<?> participants)
{
- return foldl(participants, Entry::getAndMerge, PreBootstrapOrStale.NOT_OWNED, txnId, null, r -> r == PARTIALLY);
+ return status(txnId, null, participants).get(PRE_BOOTSTRAP_OR_STALE);
}
public <T extends Deps> RangeDeps.BuilderByRange collectDeps(Routables<?> participants, RangeDeps.BuilderByRange builder, EpochSupplier minEpoch, EpochSupplier executeAt)
{
- return foldl(participants, Entry::collectDep, builder, minEpoch, executeAt, ignore -> false);
+ return foldl(participants, Entry::collectDep, builder, minEpoch, executeAt);
}
public Ranges validateSafeToRead(Timestamp forBootstrapAt, Ranges ranges)
{
- return foldl(ranges, Entry::validateSafeToRead, ranges, forBootstrapAt, null, r -> false);
+ return foldl(ranges, Entry::validateSafeToRead, ranges, forBootstrapAt, null);
}
public TxnId min(Routables<?> participants, Function<Entry, TxnId> get)
{
- return TxnId.nonNullOrMax(TxnId.NONE, foldl(participants, Entry::min, null, get, ignore -> false));
+ return TxnId.nonNullOrMax(TxnId.NONE, foldl(participants, Entry::min, null, get));
}
public TxnId max(Routables<?> participants, Function<Entry, TxnId> get)
{
- return foldl(participants, Entry::max, TxnId.NONE, get, ignore -> false);
+ return foldl(participants, Entry::max, TxnId.NONE, get);
}
/**
@@ -838,7 +738,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
Invariants.requireArgument(executeAt != null, "executeAt must not be null");
if (txnId.compareTo(maxGcBefore) >= 0)
return ranges;
- return foldl(ranges, Entry::withoutGarbage, ranges, txnId, executeAt, r -> false);
+ return foldl(ranges, Entry::withoutGarbage, ranges, txnId, executeAt);
}
/**
@@ -871,7 +771,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
{
if (maxBootstrap.compareTo(txnId) <= 0)
return ranges;
- return foldl(ranges, Entry::withoutPreBootstrap, ranges, txnId, null, r -> false);
+ return foldl(ranges, Entry::withoutPreBootstrap, ranges, txnId, null);
}
/**
@@ -885,14 +785,14 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (!mayFilterStaleOrPreBootstrapOrRetired(txnId, participants))
return participants;
- return foldl(participants, Entry::withoutRedundantAnd_StaleOrPreBootstrapOrRetired, participants, txnId, i -> false);
+ return foldl(participants, Entry::withoutRedundantAnd_StaleOrPreBootstrapOrRetired, participants, txnId);
}
else
{
if (!mayFilterStaleOrPreBootstrap(txnId, participants))
return participants;
- return foldl(participants, Entry::withoutRedundantAnd_StaleOrPreBootstrap, participants, txnId, executeAt, r -> false);
+ return foldl(participants, Entry::withoutRedundantAnd_StaleOrPreBootstrap, participants, txnId, executeAt);
}
}
@@ -906,14 +806,14 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (!mayFilterStaleOrPreBootstrapOrRetired(txnId, participants))
return participants;
- return foldl(participants, Entry::withoutStaleOrPreBootstrapOrLocallyRetired, participants, txnId, i -> false);
+ return foldl(participants, Entry::withoutStaleOrPreBootstrapOrLocallyRetired, participants, txnId);
}
else
{
if (!mayFilterStaleOrPreBootstrap(txnId, participants))
return participants;
- return foldl(participants, Entry::participantsWithoutStaleOrPreBootstrap, participants, txnId, executeAt, r -> false);
+ return foldl(participants, Entry::participantsWithoutStaleOrPreBootstrap, participants, txnId, executeAt);
}
}
@@ -939,7 +839,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
{
if (!mayFilterStaleOrPreBootstrapOrRetired(txnId, participants))
return participants;
- return foldl(participants, Entry::withoutRetired, participants, txnId, i -> false);
+ return foldl(participants, Entry::withoutRetired, participants, txnId);
}
/**
@@ -949,7 +849,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
{
if (!mayFilterStaleOrPreBootstrapOrRetired(txnId, participants))
return participants;
- return foldl(participants, Entry::withoutRedundantAnd_StaleOrPreBootstrapOrRetired, participants, txnId, i -> false);
+ return foldl(participants, Entry::withoutRedundantAnd_StaleOrPreBootstrapOrRetired, participants, txnId);
}
/**
@@ -959,7 +859,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
{
if (!mayFilterStaleOrPreBootstrap(txnId, ranges))
return ranges;
- return foldl(ranges, Entry::rangesWithoutStaleOrPreBootstrap, ranges, txnId, null, r -> false);
+ return foldl(ranges, Entry::rangesWithoutStaleOrPreBootstrap, ranges, txnId, null);
}
public static class Builder extends AbstractIntervalBuilder<RoutingKey, Entry, RedundantBefore>
@@ -975,7 +875,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (v.range.start().equals(start) && v.range.end().equals(end))
return v;
- return new Entry(v.range.newRange(start, end), v.startOwnershipEpoch, v.endOwnershipEpoch, v.locallyWitnessedOrInvalidatedBefore, v.locallyAppliedOrInvalidatedBefore, v.locallyDecidedAndAppliedOrInvalidatedBefore, v.shardOnlyAppliedOrInvalidatedBefore, v.shardAppliedOrInvalidatedBefore, v.gcBefore, v.bootstrappedAt, v.staleUntilAtLeast);
+ return new Entry(v.range.newRange(start, end), v.startOwnershipEpoch, v.endOwnershipEpoch, v.locallyWitnessedBefore, v.locallyAppliedBefore, v.locallyDecidedAndAppliedBefore, v.shardOnlyAppliedBefore, v.shardAppliedBefore, v.gcBefore, v.bootstrappedAt, v.staleUntilAtLeast);
}
@Override
@@ -994,7 +894,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return new Entry(a.range.newRange(
a.range.start().compareTo(b.range.start()) <= 0 ? a.range.start() : b.range.start(),
a.range.end().compareTo(b.range.end()) >= 0 ? a.range.end() : b.range.end()
- ), a.startOwnershipEpoch, a.endOwnershipEpoch, a.locallyWitnessedOrInvalidatedBefore, a.locallyAppliedOrInvalidatedBefore, a.locallyDecidedAndAppliedOrInvalidatedBefore, a.shardOnlyAppliedOrInvalidatedBefore, a.shardAppliedOrInvalidatedBefore, a.gcBefore, a.bootstrappedAt, a.staleUntilAtLeast);
+ ), a.startOwnershipEpoch, a.endOwnershipEpoch, a.locallyWitnessedBefore, a.locallyAppliedBefore, a.locallyDecidedAndAppliedBefore, a.shardOnlyAppliedBefore, a.shardAppliedBefore, a.gcBefore, a.bootstrappedAt, a.staleUntilAtLeast);
}
@Override
@@ -1065,7 +965,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
// find the txnIdx below which we are known to be fully redundant locally due to having been applied or invalidated
int bootstrapIdx = d.txnIdsWithFlags().find(e.bootstrappedAt);
if (bootstrapIdx < 0) bootstrapIdx = -1 - bootstrapIdx;
- int appliedIdx = d.txnIdsWithFlags().find(e.locallyAppliedOrInvalidatedBefore);
+ int appliedIdx = d.txnIdsWithFlags().find(e.locallyAppliedBefore);
if (appliedIdx < 0) appliedIdx = -1 - appliedIdx;
// remove intersecting transactions with known redundant txnId
@@ -1086,7 +986,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
});
}
return s;
- }, new KeyState(), directKeyDeps, builder, ignore -> false);
+ }, new KeyState(), directKeyDeps, builder);
}
/**
@@ -1123,15 +1023,14 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
}
RangeDeps rangeDeps = builder.directRangeDeps;
- // TODO (required, consider): slice to only those ranges we own, maybe don't even construct rangeDeps.covering()
foldl(participants, (e, s, d, b) -> {
int bootstrapIdx = d.txnIdsWithFlags().find(e.bootstrappedAt);
if (bootstrapIdx < 0) bootstrapIdx = -1 - bootstrapIdx;
s.bootstrapIdx = bootstrapIdx;
- int appliedIdx = d.txnIdsWithFlags().find(e.locallyAppliedOrInvalidatedBefore);
+ int appliedIdx = d.txnIdsWithFlags().find(e.locallyAppliedBefore);
if (appliedIdx < 0) appliedIdx = -1 - appliedIdx;
- if (e.locallyAppliedOrInvalidatedBefore.epoch() >= e.endOwnershipEpoch)
+ if (e.locallyAppliedBefore.epoch() >= e.endOwnershipEpoch)
{
// for range transactions, we should not infer that a still-owned range is redundant because a not-owned range that overlaps is redundant
int altAppliedIdx = d.txnIdsWithFlags().find(TxnId.minForEpoch(e.endOwnershipEpoch));
@@ -1163,7 +1062,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
});
}
return s;
- }, new RangeState(), rangeDeps, builder, ignore -> false);
+ }, new RangeState(), rangeDeps, builder);
}
public final boolean hasLocallyRedundantDependencies(TxnId minimumDependencyId, Timestamp executeAt, Participants<?> participantsOfWaitingTxn)
@@ -1171,6 +1070,6 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
// TODO (required): consider race conditions when bootstrapping into an active command store, that may have seen a higher txnId than this?
// might benefit from maintaining a per-CommandStore largest TxnId register to ensure we allocate a higher TxnId for our ExclSync,
// or from using whatever summary records we have for the range, once we maintain them
- return status(minimumDependencyId, executeAt, participantsOfWaitingTxn).compareTo(RedundantStatus.PARTIALLY_PRE_BOOTSTRAP_OR_STALE) >= 0;
+ return status(minimumDependencyId, executeAt, participantsOfWaitingTxn).any(LOCALLY_REDUNDANT);
}
}
diff --git a/accord-core/src/main/java/accord/local/RedundantStatus.java b/accord-core/src/main/java/accord/local/RedundantStatus.java
index a225684d..45f8a11b 100644
--- a/accord-core/src/main/java/accord/local/RedundantStatus.java
+++ b/accord-core/src/main/java/accord/local/RedundantStatus.java
@@ -18,429 +18,235 @@
package accord.local;
-import java.util.EnumMap;
-
import accord.utils.Invariants;
-
-// TODO (desired): is there a better way to represent these states? can we (for instance) collapse WAS_OWNED to a bit flag
-// Consider: can we collapse all PARTIALLY_LOCALLY states into simply LOCALLY? Since we know the transaction must be redundant in this case.
-// TODO (required): much better documentation
-public enum RedundantStatus
+import accord.utils.TinyEnumSet;
+
+import static accord.local.RedundantStatus.Coverage.ALL;
+import static accord.local.RedundantStatus.Coverage.SOME;
+import static accord.local.RedundantStatus.Property.GC_BEFORE;
+import static accord.local.RedundantStatus.Property.LOCALLY_REDUNDANT;
+import static accord.local.RedundantStatus.Property.LOCALLY_SYNCED;
+import static accord.local.RedundantStatus.Property.NOT_OWNED;
+import static accord.local.RedundantStatus.Property.PRE_BOOTSTRAP_OR_STALE;
+import static accord.local.RedundantStatus.Property.REVERSE_PROPERTIES;
+import static accord.local.RedundantStatus.Property.SHARD_AND_LOCALLY_APPLIED;
+import static accord.local.RedundantStatus.Property.SHARD_APPLIED_AND_LOCALLY_REDUNDANT;
+import static accord.local.RedundantStatus.Property.SHARD_APPLIED_AND_LOCALLY_SYNCED;
+import static accord.local.RedundantStatus.Property.TRUNCATE_BEFORE;
+import static accord.local.RedundantStatus.Property.WAS_OWNED;
+
+public class RedundantStatus
{
- /**
- * None of the relevant ranges are owned by the command store
- */
- NOT_OWNED,
+ public enum Coverage
+ {
+ NONE,
+ SOME,
+ ALL;
+
+ public boolean atLeast(Coverage coverage)
+ {
+ return compareTo(coverage) >= 0;
+ }
+ }
- /**
- * None of the relevant ranges are owned by the command store anymore
- */
- WAS_OWNED,
+ public enum Property
+ {
+ NOT_OWNED (false),
+ // applied or pre-bootstrap or stale or was owned
+ LOCALLY_REDUNDANT ( true),
+
+ // was owned OR pre-bootstrap or stale
+ LOCALLY_DEFUNCT ( true, LOCALLY_REDUNDANT),
+ WAS_OWNED ( true, LOCALLY_DEFUNCT),
+ PRE_BOOTSTRAP_OR_STALE (false, LOCALLY_DEFUNCT),
+
+ // we've applied a sync point locally covering the transaction, but the transaction itself may not have applied
+ LOCALLY_SYNCED ( true, LOCALLY_REDUNDANT),
+ LOCALLY_APPLIED (false, LOCALLY_SYNCED),
+
+ SHARD_APPLIED_ONLY ( true),
+ SHARD_APPLIED_AND_LOCALLY_REDUNDANT( true, SHARD_APPLIED_ONLY, LOCALLY_REDUNDANT),
+ SHARD_APPLIED_AND_LOCALLY_SYNCED ( true, SHARD_APPLIED_AND_LOCALLY_REDUNDANT, LOCALLY_SYNCED),
+ SHARD_AND_LOCALLY_APPLIED (false, SHARD_APPLIED_AND_LOCALLY_SYNCED, LOCALLY_APPLIED),
+ TRUNCATE_BEFORE (false, SHARD_AND_LOCALLY_APPLIED),
+ GC_BEFORE (false, TRUNCATE_BEFORE),
+ ;
+
+ static final Property[] PROPERTIES = values();
+ static final Property[] REVERSE_PROPERTIES = values();
+ static
+ {
+ for (int i = 0 ; i < REVERSE_PROPERTIES.length / 2 ; ++i)
+ {
+ REVERSE_PROPERTIES[i] = REVERSE_PROPERTIES[REVERSE_PROPERTIES.length - (1 + i)];
+ REVERSE_PROPERTIES[REVERSE_PROPERTIES.length - (1 + i)] = PROPERTIES[i];
+ }
+ }
- /**
- * None of the relevant ranges are owned by the command store anymore, and all of those ranges are closed
- * (i.e. we should know all participating commands already)
- */
- WAS_OWNED_CLOSED,
+ final boolean mergeWithWasOwned;
+ final Property[] implies;
- /**
- * None of the relevant ranges are owned by the command store anymore, and at least some of those ranges are
- * retired locally.
- * (i.e. we should not expect any knowledge of such a transaction)
- * TODO (desired): do we need this state?
- */
- WAS_OWNED_PARTIALLY_RETIRED,
+ Property(boolean mergeWithWasOwned, Property ... implies)
+ {
+ this.mergeWithWasOwned = mergeWithWasOwned;
+ this.implies = implies;
+ }
- /**
- * None of the relevant ranges are owned by the command store anymore, and all of those ranges are retired
- * at all healthy participating replicas
- * (i.e. we should not participate in any decisions)
- */
- WAS_OWNED_RETIRED,
+ final int shift()
+ {
+ return ordinal() * 2;
+ }
+ }
- /**
- * Some of the relevant ranges are owned by the command store and valid for execution
- */
- LIVE,
+ public static final RedundantStatus NONE = new RedundantStatus(0);
+ public static final RedundantStatus NOT_OWNED_ONLY = one(NOT_OWNED);
- /**
- * The relevant owned ranges are part live and part pre-bootstrap or stale
- */
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE,
+ public static final RedundantStatus WAS_OWNED_ONLY = one(WAS_OWNED);
+ public static final RedundantStatus WAS_OWNED_LOCALLY_RETIRED = multi(WAS_OWNED, LOCALLY_SYNCED);
+ public static final RedundantStatus WAS_OWNED_SHARD_RETIRED = multi(WAS_OWNED, SHARD_APPLIED_AND_LOCALLY_SYNCED);
- /**
- * The relevant owned ranges are ALL pre-bootstrap or stale, meaning we are either
- * 1) fetching the transaction's entire result from another node's snapshot already; or
- * 2) the range is stale and _must be bootstrapped_
- */
- PRE_BOOTSTRAP_OR_STALE,
+ public static final RedundantStatus PRE_BOOTSTRAP_OR_STALE_ONLY = one(PRE_BOOTSTRAP_OR_STALE);
+ public static final RedundantStatus LOCALLY_SYNCED_AND_PRE_BOOTSTRAP_OR_STALE = multi(LOCALLY_SYNCED, PRE_BOOTSTRAP_OR_STALE);
+ public static final RedundantStatus SHARD_APPLIED_AND_LOCALLY_SYNCED_AND_PRE_BOOTSTRAP_OR_STALE = multi(SHARD_APPLIED_AND_LOCALLY_SYNCED, PRE_BOOTSTRAP_OR_STALE);
+ public static final RedundantStatus SHARD_ONLY_APPLIED_AND_PRE_BOOTSTRAP_OR_STALE = multi(SHARD_APPLIED_AND_LOCALLY_REDUNDANT, PRE_BOOTSTRAP_OR_STALE);
- /**
- * Some of the relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied
- * or invalidated via a sync point that has applied locally, but these ranges may be pre-bootstrap or stale,
- * so that we cannot treat the transaction as having been fully applied locally, and other ranges may still be LIVE
- * so that we cannot fully cleanup the transaction.
- *
- * Note that this status overrides PRE_BOOTSTRAP_OR_STALE, since it implies the transaction has applied.
- */
- PARTIALLY_LOCALLY_REDUNDANT,
+ public static final RedundantStatus LOCALLY_REDUNDANT_ONLY = one(LOCALLY_REDUNDANT);
+ public static final RedundantStatus SHARD_AND_LOCALLY_APPLIED_ONLY = one(SHARD_AND_LOCALLY_APPLIED);
+ public static final RedundantStatus TRUNCATE_BEFORE_ONLY = one(TRUNCATE_BEFORE);
+ public static final RedundantStatus GC_BEFORE_ONLY = one(GC_BEFORE);
- /**
- * The relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied or invalidated
- * via a sync point that has applied locally.
- *
- * Note that this status overrides PRE_BOOTSTRAP_OR_STALE, since it implies the transaction has applied.
- */
- LOCALLY_REDUNDANT,
+ final long encoded;
+ RedundantStatus(long encoded)
+ {
+ this.encoded = encoded;
+ }
- /**
- * The relevant owned ranges are all shard-redundant AND (pre-bootstrap or stale), meaning any intersecting transaction
- * is known to be either applied or invalidated via a sync point that has applied locally AND on all healthy shards.
- * But the transaction may not have been maintained locally.
- */
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE,
+ public RedundantStatus merge(RedundantStatus that)
+ {
+ long merged = merge(this.encoded, that.encoded);
+ if (merged == this.encoded)
+ return this;
+ if (merged == that.encoded)
+ return that;
+ return new RedundantStatus(merged);
+ }
- /**
- * Some of the relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied
- * or invalidated via a sync point that has applied locally AND remotely, but these ranges may be pre-bootstrap or stale,
- * so that we cannot treat the transaction as having been fully applied locally, and other ranges may still be LIVE
- * so that we cannot fully cleanup the transaction.
- *
- * Note that this status overrides PRE_BOOTSTRAP_OR_STALE, since it implies the transaction has applied.
- */
- PARTIALLY_SHARD_REDUNDANT,
+ public RedundantStatus add(RedundantStatus that)
+ {
+ return new RedundantStatus(this.encoded | that.encoded);
+ }
- /**
- * Some of the relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied
- * or invalidated via a sync point that has applied locally AND on all healthy shards.
- * TODO (desired): do we need this state?
- */
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT,
+ public Coverage get(Property property)
+ {
+ return decode(encoded, property);
+ }
- /**
- * The relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied or invalidated
- * via a sync point that has applied locally AND on all healthy shards. Note that this status CANNOT be taken if
- * we are not ALSO LOCALLY_REDUNDANT, so we can use this to cleanup transactions < PreCommitted (or Erased).
- *
- * Note that this status overrides PRE_BOOTSTRAP_OR_STALE, since it implies the transaction has applied.
- */
- SHARD_REDUNDANT,
+ public boolean all(Property property)
+ {
+ return get(property) == ALL;
+ }
- /**
- * Note: some shards may be SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, others TRUNCATE_BEFORE or GC_BEFORE.
- *
- * All of the relevant owned ranges are either shard redundant and pre-bootstrap OR truncatable OR gc-able,
- * meaning any intersecting transaction is known to be applied at a majority of the shard,
- * or invalidated via a sync point that we have applied locally.
- *
- * We do not need to know anymore about the command's outcome ourselves and may TRUNCATE it.
- * We cannot ERASE it, because we may yet need the executeAt TIMESTAMP (only) for computing unique HLC
- * (for implementations where this matters)
- */
- TRUNCATE_BEFORE,
+ public boolean none(Property property)
+ {
+ return get(property) == Coverage.NONE;
+ }
- /**
- * The relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied or invalidated
- * via a sync point that has applied locally AND on all healthy shards. Note that this status CANNOT be taken if
- * we are not ALSO LOCALLY_REDUNDANT, so we can use this to cleanup local state.
- *
- * Note that this status overrides PRE_BOOTSTRAP_OR_STALE, since it implies the transaction has applied.
- */
- GC_BEFORE,
- ;
+ public boolean any(Property property)
+ {
+ return get(property) != Coverage.NONE;
+ }
- private EnumMap<RedundantStatus, RedundantStatus> merge;
+ public static Coverage decode(long encoded, Property property)
+ {
+ int coverage = (int)((encoded >>> property.shift()) & 0x3);
+ switch (coverage)
+ {
+ default: throw new IllegalStateException("Invalid Coverage value encoded for " + property + ": " + coverage);
+ case 0: return Coverage.NONE;
+ case 1: return SOME;
+ case 3: return ALL;
+ }
+ }
+ private static final long ALL_BITS = 0xAAAAAAAAAAAAAAAAL;
+ private static final long ANY_BITS = 0x5555555555555555L;
+ private static final long WAS_OWNED_MERGE_MASK;
+ private static final long WAS_OWNED_MASK = 0x3L << WAS_OWNED.shift();
+ private static final long NOT_OWNED_MASK = 0x3L << NOT_OWNED.shift();
static
{
- NOT_OWNED.merge = new EnumMap<>(RedundantStatus.class);
- NOT_OWNED.merge.put(NOT_OWNED, NOT_OWNED);
- NOT_OWNED.merge.put(WAS_OWNED, WAS_OWNED);
- NOT_OWNED.merge.put(WAS_OWNED_CLOSED, WAS_OWNED_CLOSED);
- NOT_OWNED.merge.put(WAS_OWNED_PARTIALLY_RETIRED, WAS_OWNED_PARTIALLY_RETIRED);
- NOT_OWNED.merge.put(WAS_OWNED_RETIRED, WAS_OWNED_RETIRED);
- NOT_OWNED.merge.put(LIVE, LIVE);
- NOT_OWNED.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- NOT_OWNED.merge.put(PRE_BOOTSTRAP_OR_STALE, PRE_BOOTSTRAP_OR_STALE);
- NOT_OWNED.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- NOT_OWNED.merge.put(LOCALLY_REDUNDANT, LOCALLY_REDUNDANT);
- NOT_OWNED.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- NOT_OWNED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- NOT_OWNED.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
- NOT_OWNED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- NOT_OWNED.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
- NOT_OWNED.merge.put(GC_BEFORE, GC_BEFORE);
- WAS_OWNED.merge = new EnumMap<>(RedundantStatus.class);
- WAS_OWNED.merge.put(NOT_OWNED, WAS_OWNED);
- WAS_OWNED.merge.put(WAS_OWNED, WAS_OWNED);
- WAS_OWNED.merge.put(WAS_OWNED_CLOSED, WAS_OWNED);
- WAS_OWNED.merge.put(WAS_OWNED_PARTIALLY_RETIRED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED.merge.put(WAS_OWNED_RETIRED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED.merge.put(LIVE, LIVE);
- WAS_OWNED.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- WAS_OWNED.merge.put(LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- WAS_OWNED.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_CLOSED.merge = new EnumMap<>(RedundantStatus.class);
- WAS_OWNED_CLOSED.merge.put(NOT_OWNED, WAS_OWNED_CLOSED);
- WAS_OWNED_CLOSED.merge.put(WAS_OWNED, WAS_OWNED);
- WAS_OWNED_CLOSED.merge.put(WAS_OWNED_CLOSED, WAS_OWNED_CLOSED);
- WAS_OWNED_CLOSED.merge.put(WAS_OWNED_PARTIALLY_RETIRED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_CLOSED.merge.put(WAS_OWNED_RETIRED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_CLOSED.merge.put(LIVE, LIVE);
- WAS_OWNED_CLOSED.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED_CLOSED.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED_CLOSED.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- WAS_OWNED_CLOSED.merge.put(LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- WAS_OWNED_CLOSED.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_CLOSED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_CLOSED.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_CLOSED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_CLOSED.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_CLOSED.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge = new EnumMap<>(RedundantStatus.class);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(NOT_OWNED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(WAS_OWNED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(WAS_OWNED_CLOSED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(WAS_OWNED_PARTIALLY_RETIRED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(WAS_OWNED_RETIRED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(LIVE, LIVE);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(PRE_BOOTSTRAP_OR_STALE, PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_RETIRED.merge = new EnumMap<>(RedundantStatus.class);
- WAS_OWNED_RETIRED.merge.put(NOT_OWNED, WAS_OWNED_RETIRED);
- WAS_OWNED_RETIRED.merge.put(WAS_OWNED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_RETIRED.merge.put(WAS_OWNED_CLOSED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_RETIRED.merge.put(WAS_OWNED_PARTIALLY_RETIRED, WAS_OWNED_PARTIALLY_RETIRED);
- WAS_OWNED_RETIRED.merge.put(WAS_OWNED_RETIRED, WAS_OWNED_RETIRED);
- WAS_OWNED_RETIRED.merge.put(LIVE, LIVE);
- WAS_OWNED_RETIRED.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED_RETIRED.merge.put(PRE_BOOTSTRAP_OR_STALE, PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED_RETIRED.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- WAS_OWNED_RETIRED.merge.put(LOCALLY_REDUNDANT, LOCALLY_REDUNDANT);
- WAS_OWNED_RETIRED.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_RETIRED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- WAS_OWNED_RETIRED.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
- WAS_OWNED_RETIRED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED_RETIRED.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
- WAS_OWNED_RETIRED.merge.put(GC_BEFORE, GC_BEFORE);
- LIVE.merge = new EnumMap<>(RedundantStatus.class);
- LIVE.merge.put(NOT_OWNED, LIVE);
- LIVE.merge.put(WAS_OWNED, LIVE);
- LIVE.merge.put(WAS_OWNED_CLOSED, LIVE);
- LIVE.merge.put(WAS_OWNED_PARTIALLY_RETIRED, LIVE);
- LIVE.merge.put(WAS_OWNED_RETIRED, LIVE);
- LIVE.merge.put(LIVE, LIVE);
- LIVE.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- LIVE.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- LIVE.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- LIVE.merge.put(LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- LIVE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- LIVE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- LIVE.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- LIVE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- LIVE.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- LIVE.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge = new EnumMap<>(RedundantStatus.class);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(NOT_OWNED, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_CLOSED, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_RETIRED, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(LIVE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- PRE_BOOTSTRAP_OR_STALE.merge = new EnumMap<>(RedundantStatus.class);
- PRE_BOOTSTRAP_OR_STALE.merge.put(NOT_OWNED, PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_CLOSED, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_RETIRED, PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(LIVE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(PRE_BOOTSTRAP_OR_STALE, PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- PRE_BOOTSTRAP_OR_STALE.merge.put(LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(NOT_OWNED, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(WAS_OWNED, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(WAS_OWNED_CLOSED, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(WAS_OWNED_RETIRED, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(LIVE, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- LOCALLY_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
- LOCALLY_REDUNDANT.merge.put(NOT_OWNED, LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(WAS_OWNED, PARTIALLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(WAS_OWNED_CLOSED, PARTIALLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(WAS_OWNED_RETIRED, LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(LIVE, PARTIALLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(LOCALLY_REDUNDANT, LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(GC_BEFORE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge = new EnumMap<>(RedundantStatus.class);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(NOT_OWNED, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_CLOSED, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_RETIRED, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(LIVE, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PRE_BOOTSTRAP_OR_STALE, PRE_BOOTSTRAP_OR_STALE);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE, TRUNCATE_BEFORE);
- PARTIALLY_SHARD_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
- PARTIALLY_SHARD_REDUNDANT.merge.put(NOT_OWNED, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(WAS_OWNED_CLOSED, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(WAS_OWNED_RETIRED, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(LIVE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(NOT_OWNED, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(WAS_OWNED_CLOSED, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(WAS_OWNED_RETIRED, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(LIVE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(GC_BEFORE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- SHARD_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
- SHARD_REDUNDANT.merge.put(NOT_OWNED, SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(WAS_OWNED_CLOSED, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(WAS_OWNED_RETIRED, SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(LIVE, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- // TODO (required): we merge LOCALLY_REDUNDANT and PARTIALLY_LOCALLY_REDUNDANT inconsistently.
- // Consider: do we ever need to know LOCALLY_REDUNDANT *and* PARTIALLY_SHARD_REDUNDANT?
- SHARD_REDUNDANT.merge.put(LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- SHARD_REDUNDANT.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- SHARD_REDUNDANT.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(TRUNCATE_BEFORE, SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(GC_BEFORE, SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge = new EnumMap<>(RedundantStatus.class);
- TRUNCATE_BEFORE.merge.put(NOT_OWNED, TRUNCATE_BEFORE);
- TRUNCATE_BEFORE.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(WAS_OWNED_CLOSED, PARTIALLY_SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(WAS_OWNED_RETIRED, TRUNCATE_BEFORE);
- TRUNCATE_BEFORE.merge.put(LIVE, PARTIALLY_SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
- TRUNCATE_BEFORE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, TRUNCATE_BEFORE);
- TRUNCATE_BEFORE.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
- TRUNCATE_BEFORE.merge.put(GC_BEFORE, TRUNCATE_BEFORE);
- GC_BEFORE.merge = new EnumMap<>(RedundantStatus.class);
- GC_BEFORE.merge.put(NOT_OWNED, GC_BEFORE);
- GC_BEFORE.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE.merge.put(WAS_OWNED_CLOSED, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE.merge.put(WAS_OWNED_RETIRED, GC_BEFORE);
- GC_BEFORE.merge.put(LIVE, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE.merge.put(LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- GC_BEFORE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- GC_BEFORE.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
- GC_BEFORE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, TRUNCATE_BEFORE);
- GC_BEFORE.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
- GC_BEFORE.merge.put(GC_BEFORE, GC_BEFORE);
-
- for (RedundantStatus a : values())
+ long mask = 0;
+ for (Property property : Property.values())
{
- for (RedundantStatus b : values())
- {
- Invariants.require(a.merge(b) == b.merge(a), "non-symmetric merge of %s and %s", a, b);
- }
+ if (!property.mergeWithWasOwned)
+ mask |= (0x3L << property.shift());
}
+ WAS_OWNED_MERGE_MASK = mask;
}
- public RedundantStatus merge(RedundantStatus that)
+ public static long merge(long a, long b)
{
- RedundantStatus result = merge.get(that);
- Invariants.require(result != null, "Invalid RedundantStatus combination: " + this + " and " + that);
+ long either = a | b;
+ Invariants.require((either & NOT_OWNED_MASK) == 0);
+ long all = (a & b) & ALL_BITS;
+ long any = either & ANY_BITS;
+ long result = all | any;
+ if ((either & WAS_OWNED_MASK) == WAS_OWNED_MASK)
+ result |= either & WAS_OWNED_MERGE_MASK;
return result;
}
+
+ private static RedundantStatus one(Property property)
+ {
+ return new RedundantStatus(transitiveClosure(property));
+ }
+
+ private static RedundantStatus multi(Property ... properties)
+ {
+ long encoded = 0;
+ for (Property property : properties)
+ encoded |= transitiveClosure(property);
+ return new RedundantStatus(encoded);
+ }
+
+ private static long transitiveClosure(Property property)
+ {
+ long encoded = 0x3L << (property.shift());
+ for (Property implied : property.implies)
+ encoded |= transitiveClosure(implied);
+ return encoded;
+ }
+
+ private static final Coverage[] COVERAGE_TO_STRING = new Coverage[] { ALL, SOME };
+ @Override
+ public String toString()
+ {
+ StringBuilder builder = new StringBuilder("{");
+ boolean firstCoverage = true;
+ for (Coverage coverage : COVERAGE_TO_STRING)
+ {
+ if (!firstCoverage) builder.append(',');
+ firstCoverage = false;
+ builder.append(coverage);
+ builder.append(":[");
+ int implied = 0;
+ boolean firstProperty = true;
+ for (Property property : REVERSE_PROPERTIES)
+ {
+ if (TinyEnumSet.contains(implied, property))
+ {
+ implied |= TinyEnumSet.encode(property.implies);
+ }
+ else if (get(property) == coverage)
+ {
+ if (!firstProperty) builder.append(",");
+ firstProperty = false;
+ builder.append(property);
+ }
+ }
+ builder.append("]");
+ }
+ builder.append("}");
+ return builder.toString();
+ }
}
diff --git a/accord-core/src/main/java/accord/local/SafeCommandStore.java b/accord-core/src/main/java/accord/local/SafeCommandStore.java
index eaac9edc..f616290c 100644
--- a/accord-core/src/main/java/accord/local/SafeCommandStore.java
+++ b/accord-core/src/main/java/accord/local/SafeCommandStore.java
@@ -46,12 +46,12 @@ import accord.primitives.Unseekables;
import accord.utils.Invariants;
import accord.utils.SimpleBitSet;
import accord.utils.SortedList;
-import accord.utils.UnhandledEnum;
import accord.utils.async.AsyncChain;
import static accord.local.KeyHistory.INCR;
import static accord.local.KeyHistory.NONE;
-import static accord.local.RedundantBefore.PreBootstrapOrStale.FULLY;
+import static accord.local.RedundantStatus.Property.LOCALLY_REDUNDANT;
+import static accord.local.RedundantStatus.Property.SHARD_APPLIED_ONLY;
import static accord.local.cfk.UpdateUnmanagedMode.REGISTER;
import static accord.primitives.Routable.Domain.Range;
import static accord.primitives.SaveStatus.Applied;
@@ -76,11 +76,13 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
*/
public @Nullable SafeCommand ifInitialised(TxnId txnId)
{
- SafeCommand safeCommand = get(txnId);
+ SafeCommand safeCommand = getInternal(txnId);
+ if (safeCommand == null)
+ return null;
Command command = safeCommand.current();
if (command.saveStatus().isUninitialised())
return null;
- return safeCommand;
+ return maybeCleanup(safeCommand);
}
// decidedExecuteAt == null if not yet PreCommitted
@@ -327,12 +329,12 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
if (update.isEmpty())
return;
- // TODO (expected): we don't want to insert any dependencies for those we only touch; we just need to record them as decided/applied for execution
+ // TODO (required): we don't want to insert any dependencies for those we only touch; we just need to record them as decided/applied for execution
PreLoadContext context = PreLoadContext.contextFor(next.txnId(), update, INCR);
PreLoadContext execute = safeStore.canExecute(context);
if (execute != null)
{
- updateManagedCommandsForKey(safeStore, execute.keys(), participants, next);
+ updateManagedCommandsForKey(safeStore, execute.keys(), next.txnId());
}
if (execute != context)
{
@@ -345,16 +347,20 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
PreLoadContext ctx = safeStore0.context();
TxnId txnId = ctx.primaryTxnId();
Unseekables<?> keys = ctx.keys();
- updateManagedCommandsForKey(safeStore0, keys, participants, safeStore0.get(txnId).current());
- }).begin(safeStore.commandStore().agent);
+ updateManagedCommandsForKey(safeStore0, keys, txnId);
+ }, safeStore.commandStore().agent);
}
}
- private static void updateManagedCommandsForKey(SafeCommandStore safeStore, Unseekables<?> update, StoreParticipants participants, Command next)
+ private static void updateManagedCommandsForKey(SafeCommandStore safeStore, Unseekables<?> update, TxnId txnId)
{
+ // TODO (expected): avoid reentrancy / recursion
+ SafeCommand safeCommand = safeStore.get(txnId);
for (RoutingKey key : (AbstractUnseekableKeys)update)
{
- safeStore.get(key).callback(safeStore, next);
+ // we use callback and re-fetch current to guard against reentrancy causing
+ // us to interact with "future" or stale information (respectively)
+ safeStore.get(key).callback(safeStore, safeCommand.current());
}
}
@@ -382,30 +388,10 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
SortedList<TxnId> txnIdsForKey = deps.txnIdsForKeyIndex(i);
RoutingKey key = keys.get(i);
TxnId maxTxnId = txnIdsForKey.get(txnIdsForKey.size() - 1);
- // TODO (required): convert to O(n) merge
+ // TODO (desired): convert to O(n) merge
RedundantStatus status = redundantBefore.status(maxTxnId, null, key);
- switch (status)
- {
- default: throw new UnhandledEnum(status);
- case NOT_OWNED:
- case WAS_OWNED:
- case WAS_OWNED_CLOSED:
- case WAS_OWNED_PARTIALLY_RETIRED: // means fully locally redundant in this case
- case LIVE:
- case PARTIALLY_PRE_BOOTSTRAP_OR_STALE:
- case PRE_BOOTSTRAP_OR_STALE:
- case PARTIALLY_LOCALLY_REDUNDANT:
- case LOCALLY_REDUNDANT:
- // we need to record transitive dependencies for coordination decisions
- select.set(i);
- case WAS_OWNED_RETIRED:
- case PARTIALLY_SHARD_REDUNDANT:
- case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
- case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- case SHARD_REDUNDANT:
- case TRUNCATE_BEFORE:
- case GC_BEFORE:
- }
+ if (!status.all(SHARD_APPLIED_ONLY) || !status.all(LOCALLY_REDUNDANT))
+ select.set(i);
}
if (select.getSetBitCount() != keys.size())
{
@@ -440,9 +426,9 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
safeStore = safeStore;
CommandStore unsafeStore = safeStore.commandStore();
- AsyncChain<Void> submit = unsafeStore.execute(context, safeStore0 -> updateUnmanagedCommandsForKey(safeStore0, safeStore0.context().keys(), txnId, mode));
+ AsyncChain<Void> submit = unsafeStore.build(context, safeStore0 -> { updateUnmanagedCommandsForKey(safeStore0, safeStore0.context().keys() , txnId, mode); });
if (next.txnId().is(Range))
- submit = submit.flatMap(success -> unsafeStore.execute(PreLoadContext.empty(), safeStore0 -> registerTransitive(safeStore0, txnId, next)));
+ submit = submit.flatMap(success -> unsafeStore.build(PreLoadContext.empty(), safeStore0 -> { registerTransitive(safeStore0, txnId, next); }));
submit.begin(safeStore.commandStore().agent);
}
}
@@ -522,13 +508,6 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
return ranges().allAt(at).without(safeToReadAt(at));
}
- // if we have to re-bootstrap (due to failed bootstrap or catching up on a range) then we may
- // have dangling redundant commands; these can safely be executed locally because we are a timestamp store
- final boolean isFullyPreBootstrapOrStale(Command command, Participants<?> forKeys)
- {
- return redundantBefore().preBootstrapOrStale(command.txnId(), forKeys) == FULLY;
- }
-
public void registerListener(SafeCommand listeningTo, SaveStatus await, TxnId waiting)
{
Invariants.require(listeningTo.current().saveStatus().compareTo(await) < 0);
diff --git a/accord-core/src/main/java/accord/local/StoreParticipants.java b/accord-core/src/main/java/accord/local/StoreParticipants.java
index cabc9470..42e75e0c 100644
--- a/accord-core/src/main/java/accord/local/StoreParticipants.java
+++ b/accord-core/src/main/java/accord/local/StoreParticipants.java
@@ -43,8 +43,7 @@ import static accord.primitives.Route.tryCastToRoute;
import static accord.primitives.SaveStatus.Erased;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
-// TODO (desired): split into a single sub-class to save memory in typical case of owns==touches==hasTouched
-// TODO (required): add invariants confirming owns contains AT LEAST anything in hasTouched() that intersects txnId.epoch()
+// TODO (expected): add invariants confirming owns contains AT LEAST anything in hasTouched() that intersects txnId.epoch()
public class StoreParticipants
{
public enum Filter { QUERY, LOAD, UPDATE }
@@ -63,7 +62,8 @@ public class StoreParticipants
this.hasTouched = hasTouched;
Invariants.requireArgument(route != null || (!Route.isRoute(owns) && !Route.isRoute(executes) && !Route.isRoute(touches) && !Route.isRoute(hasTouched)));
Routable.Domain domain = owns.domain();
- Invariants.requireArgument(touches.containsAll(owns));
+ Invariants.paranoid(route == null || route.containsAll(owns));
+ Invariants.paranoid(touches.containsAll(owns));
Invariants.requireArgument(route == null || domain == route.domain());
Invariants.requireArgument(domain == touches.domain());
Invariants.requireArgument(domain == hasTouched.domain());
@@ -395,8 +395,9 @@ public class StoreParticipants
*/
public final StoreParticipants merge(@Nullable Route<?> route, @Nullable Participants<?> owns, @Nullable Participants<?> touches, @Nullable Participants<?> hasTouched)
{
- route = Route.merge(this.route, (Route)route);
owns = Participants.merge(this.owns, (Participants) owns);
+ route = Route.merge(this.route, (Route)route);
+ if (route != null) route = route.with((Participants)owns);
Participants<?> curTouches = touches(), curHasTouched = hasTouched();
touches = Participants.merge(curTouches, (Participants) touches);
hasTouched = Participants.merge(curHasTouched, (Participants) hasTouched);
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 b9b975cd..995e4515 100644
--- a/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
@@ -33,6 +33,7 @@ import org.slf4j.LoggerFactory;
import accord.api.RoutingKey;
import accord.api.VisibleForImplementation;
import accord.local.Command;
+import accord.local.CommandStore;
import accord.local.RedundantBefore;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
@@ -42,6 +43,7 @@ import accord.local.CommandSummaries.IsDep;
import accord.local.CommandSummaries.SummaryStatus;
import accord.local.CommandSummaries.ComputeIsDep;
import accord.local.CommandSummaries.TestStartedAt;
+import accord.primitives.RoutingKeys;
import accord.primitives.SaveStatus;
import accord.primitives.Status;
import accord.local.cfk.PostProcess.NotifyUnmanagedResult;
@@ -92,7 +94,7 @@ import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Timestamp.Flag.UNSTABLE;
import static accord.primitives.Txn.Kind.AnyGloballyVisible;
import static accord.primitives.Txn.Kind.Write;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
import static accord.primitives.TxnId.NO_TXNIDS;
import static accord.utils.Invariants.Paranoia.LINEAR;
import static accord.utils.Invariants.Paranoia.NONE;
@@ -208,11 +210,7 @@ import static accord.utils.SortedArrays.Search.FAST;
* decisions, so that recovery does not need to contact future epochs to find any superseding transactions
* 3) when an accept round visits a later epoch than the one in which it is agreed.
* TODO (desired): track whether a TxnId is a write on this key only for execution (rather than globally)
- * TODO (expected): merge with TimestampsForKey
* TODO (desired): save space by encoding InternalStatus in TxnId.flags(), so that when executeAt==txnId we can save 8 bytes per entry
- * TODO (expected): remove a command that is committed to not intersect with the key for this store (i.e. if accepted in a later epoch than committed on, so ownership changes)
- * TODO (expected): avoid updating transactions we don't manage the execution of - perhaps have a dedicated InternalStatus
- * TODO (expected): minimise repeated notification, either by logic or marking a command as notified once ready-to-execute
* TODO (required): better linearizability violation detection
* TODO (expected): cleanup unmanaged transitively known transactions
* TODO (desired): introduce a new status or other fast and simple mechanism for filtering treatment of range or unmanaged transactions
@@ -281,11 +279,11 @@ public class CommandsForKey extends CommandsForKeyUpdate
public static boolean executes(RedundantBefore.Entry boundsInfo, TxnId txnId, Timestamp executeAt)
{
- return executesIgnoreBootstrap(boundsInfo, txnId, executeAt)
+ return executesIgnoringBootstrap(boundsInfo, txnId, executeAt)
&& boundsInfo.bootstrappedAt.compareTo(txnId) < 0;
}
- public static boolean executesIgnoreBootstrap(RedundantBefore.Entry boundsInfo, TxnId txnId, Timestamp executeAt)
+ public static boolean executesIgnoringBootstrap(RedundantBefore.Entry boundsInfo, TxnId txnId, Timestamp executeAt)
{
return managesExecution(txnId)
&& boundsInfo.endOwnershipEpoch > executeAt.epoch()
@@ -389,7 +387,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
Invariants.require(executeAt == txnId || !executeAt.equals(txnId));
Invariants.require(status.hasExecuteAt || executeAt == txnId);
Invariants.require(status.hasDeps || missing == NO_TXNIDS);
- Invariants.require(status.hasBallot || ballot == Ballot.ZERO);
+ Invariants.expect(status.hasBallot || ballot == Ballot.ZERO);
int encodedStatus = encode(txnId, status, mayExecute, statusOverrideXor);
if (missing == NO_TXNIDS && (!status.hasBallot || ballot == Ballot.ZERO))
return new TxnInfo(txnId, encodedStatus, executeAt);
@@ -835,6 +833,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
APPLIED_DURABLE (APPLIED, true, true, false, true),
APPLIED_NOT_EXECUTED /*(reserved)*/ (APPLIED, true, true, false, true),
INVALIDATED (SummaryStatus.INVALIDATED, false,false,false, false),
+ ERASED (SummaryStatus.NONE, false,false,false, false),
PRUNED (SummaryStatus.NONE, false,false,false, false)
;
@@ -871,9 +870,9 @@ public class CommandsForKey extends CommandsForKeyUpdate
// esp. to support pruning where we expect the prunedBefore entr*ies* to be APPLIED
// Note importantly that we have multiple logical pruned befores - the last APPLIED
// write per epoch is retained to cleanly support
- // TODO (desired): can we improve our semantics here to at least PRUNE truncated commands if there's a
- // superseding APPLIED command?
- // TODO (expected): if we truncate (but don't invalidate) a command that had not been decided, we should probably erase it?
+ // TODO (desired): can we improve our semantics here to at least PRUNE truncated commands if there's a superseding APPLIED command?
+ // TODO (desired): move all truncated to ERASED, but we have to handle the case we erase our prunedBefore boundary
+ FROM_SAVE_STATUS.put(SaveStatus.Vestigial, ERASED);
FROM_SAVE_STATUS.put(SaveStatus.Invalidated, INVALIDATED);
for (SaveStatus saveStatus : SaveStatus.values())
Invariants.require(FROM_SAVE_STATUS.get(saveStatus) != null || saveStatus.is(Status.Truncated) || saveStatus.is(Status.NotDefined));
@@ -1140,7 +1139,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
*
* However, it can be safely used as a prune lower bound that we know we do not need to go to disk to load.
*/
- return boundsInfo.locallyDecidedAndAppliedOrInvalidatedBefore;
+ return boundsInfo.locallyDecidedAndAppliedBefore;
}
public TxnId redundantOrBootstrappedBefore()
@@ -1317,7 +1316,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
if (txn.compareTo(ACCEPTED) >= 0) dep = hasAsDep ? IS_STABLE_DEP : IS_NOT_STABLE_DEP;
- else if (txn.is(PRIVILEGED_COORDINATOR_WITH_DEPS)) dep = hasAsDep ? IS_COORD_DEP : IS_NOT_COORD_DEP;
+ else if (txn.is(PrivilegedCoordinatorWithDeps)) dep = hasAsDep ? IS_COORD_DEP : IS_NOT_COORD_DEP;
else dep = NOT_ELIGIBLE;
}
}
@@ -1371,6 +1370,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
{
case TRANSITIVE:
case INVALIDATED:
+ case ERASED:
case PRUNED:
continue;
@@ -1633,7 +1633,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
Invariants.requireArgument(!mayExecute);
int statusOverridesXor = newStatus.flags & 1;
TxnInfo newInfo;
- if (curInfo == null) newInfo = TxnInfo.create(plainTxnId, newStatus, false, statusOverridesXor, plainTxnId, updated.acceptedOrCommitted());
+ 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);
@@ -1888,7 +1888,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
{
TxnId txnId = txn.plainTxnId();
notifySink.notWaiting(safeStore, txnId, key, txnId.is(Write) ? maxUniqueHlc + 1 : 0);
- // TODO (required): avoid invoking this here; we may do redundant work if we have local dependencies we're already waiting on
+ // TODO (expected): avoid invoking this here; we may do redundant work if we have local dependencies we're already waiting on
notifySink.waitingOn(safeStore, txn, key, SaveStatus.PreApplied, CanApply, false);
txn.setNotifiedReadyInPlace();
}
@@ -1964,7 +1964,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
else if (newBoundsInfo.gcBefore.equals(boundsInfo.gcBefore)
&& newBoundsInfo.bootstrappedAt.equals(boundsInfo.bootstrappedAt)
- && newBoundsInfo.locallyDecidedAndAppliedOrInvalidatedBefore.equals(boundsInfo.locallyDecidedAndAppliedOrInvalidatedBefore)
+ && newBoundsInfo.locallyDecidedAndAppliedBefore.equals(boundsInfo.locallyDecidedAndAppliedBefore)
&& newBoundsInfo.endOwnershipEpoch == boundsInfo.endOwnershipEpoch)
{
return this;
@@ -2124,11 +2124,9 @@ public class CommandsForKey extends CommandsForKeyUpdate
for (int i = maxAppliedWriteByExecuteAt ; i >= 0 ; --i)
{
TxnInfo txn = committedByExecuteAt[i];
- if (newInfo == txn && CommandsForKey.reportLinearizabilityViolations())
+ if (newInfo == txn)
{
- // we haven't found anything pre-bootstrap that follows this command, so log a linearizability violation
- // TODO (expected): this should be a rate-limited logger; need to integrate with Cassandra
- logger.error("Linearizability violation on key {}: {} is committed to execute (at {}) before {} that should witness it but has already applied (at {})", key, newInfo.plainTxnId(), newInfo.plainExecuteAt(), maxAppliedWrite.plainTxnId(), maxAppliedWrite.plainExecuteAt());
+ reportLinearizabilityViolation(key, newInfo.plainTxnId(), newInfo.plainExecuteAt(), maxAppliedWrite.plainTxnId(), maxAppliedWrite.plainExecuteAt());
break;
}
@@ -2301,6 +2299,20 @@ public class CommandsForKey extends CommandsForKeyUpdate
return reportLinearizabilityViolations;
}
+ static void reportLinearizabilityViolation(RoutingKey key, TxnId notWitnessed, Timestamp notWitnessedExecuteAt, TxnId by, Timestamp byExecuteAt)
+ {
+ if (!reportLinearizabilityViolations)
+ return;
+
+ String message = "Linearizability violation on key " + key + ": "
+ + notWitnessed + " is committed to execute (at " + notWitnessedExecuteAt + ") before "
+ + by + " that should witness it but has already applied (at " + byExecuteAt + ")";
+
+ CommandStore commandStore = CommandStore.maybeCurrent();
+ if (commandStore == null) logger.error(message);
+ else commandStore.agent().onViolation(message, RoutingKeys.of(key), notWitnessed, notWitnessedExecuteAt, by, byExecuteAt);
+ }
+
public static void enableLinearizabilityViolationsReporting()
{
reportLinearizabilityViolations = true;
diff --git a/accord-core/src/main/java/accord/local/cfk/NotifySink.java b/accord-core/src/main/java/accord/local/cfk/NotifySink.java
index b9fe1435..3e929168 100644
--- a/accord-core/src/main/java/accord/local/cfk/NotifySink.java
+++ b/accord-core/src/main/java/accord/local/cfk/NotifySink.java
@@ -33,6 +33,7 @@ import accord.primitives.RoutingKeys;
import accord.primitives.TxnId;
import accord.utils.Invariants;
+import static accord.local.Command.NotDefined.uninitialised;
import static accord.local.KeyHistory.SYNC;
import static accord.primitives.Status.Truncated;
@@ -53,8 +54,9 @@ interface NotifySink
if (safeCommand != null) notWaiting(safeStore, safeCommand, key, uniqueHlc);
else
{
- safeStore.commandStore().execute(txnId, safeStore0 -> notWaiting(safeStore0, safeStore0.unsafeGet(txnId), key, uniqueHlc))
- .begin(safeStore.agent());
+ safeStore.commandStore().execute(txnId, safeStore0 -> {
+ notWaiting(safeStore0, safeStore0.unsafeGet(txnId), key, uniqueHlc);
+ }, safeStore.agent());
}
}
@@ -71,15 +73,15 @@ interface NotifySink
if (safeStore.canExecuteWith(txnId)) doNotifyWaitingOn(safeStore, txnId, key, waitingOnStatus, blockedUntil, notifyCfk);
else safeStore.commandStore().execute(txnId, safeStore0 -> {
doNotifyWaitingOn(safeStore0, txnId, key, waitingOnStatus, blockedUntil, notifyCfk);
- }).begin(safeStore.agent());
+ }, safeStore.agent());
}
// TODO (desired): we could complicate our state machine to replicate PreCommitted here, so we can simply wait for waitingOnStatus.execution
private void doNotifyWaitingOn(SafeCommandStore safeStore, TxnId txnId, RoutingKey key, SaveStatus waitingOnStatus, BlockedUntil blockedUntil, boolean notifyCfk)
{
- SafeCommand safeCommand = safeStore.unsafeGet(txnId);
- safeCommand.initialise();
+ SafeCommand safeCommand = safeStore.unsafeGetNoCleanup(txnId);
Command command = safeCommand.current();
+ if (command == null) command = uninitialised(txnId);
StoreParticipants participants = command.participants();
if (!participants.hasTouched(key))
{
@@ -122,7 +124,7 @@ interface NotifySink
safeStore = safeStore; // prevent use in lambda
safeStore.commandStore().execute(PreLoadContext.contextFor(txnId, keys, SYNC), safeStore0 -> {
doNotifyAlreadyReady(safeStore0, txnId, key);
- }).begin(safeStore.agent());
+ }, safeStore.agent());
}
}
}
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 9e4412c5..e37eda0e 100644
--- a/accord-core/src/main/java/accord/local/cfk/PostProcess.java
+++ b/accord-core/src/main/java/accord/local/cfk/PostProcess.java
@@ -101,7 +101,7 @@ abstract class PostProcess
else
safeStore.commandStore().execute(PreLoadContext.contextFor(txnId, RoutingKeys.of(key), SYNC), safeStore0 -> {
load(safeStore0, safeStore0.unsafeGet(txnId), safeStore0.get(key), notifySink);
- }).begin(safeStore.agent());
+ }, safeStore.agent());
}
}
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 18cce562..32184bde 100644
--- a/accord-core/src/main/java/accord/local/cfk/Pruning.java
+++ b/accord-core/src/main/java/accord/local/cfk/Pruning.java
@@ -389,6 +389,7 @@ public class Pruning
case INVALIDATED:
case PRUNED:
+ case ERASED:
break;
}
}
diff --git a/accord-core/src/main/java/accord/local/cfk/Serialize.java b/accord-core/src/main/java/accord/local/cfk/Serialize.java
index 2396ba57..0eddccfe 100644
--- a/accord-core/src/main/java/accord/local/cfk/Serialize.java
+++ b/accord-core/src/main/java/accord/local/cfk/Serialize.java
@@ -23,33 +23,35 @@ import java.util.Arrays;
import javax.annotation.Nonnull;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import accord.api.RoutingKey;
+import accord.local.Node.Id;
import accord.local.RedundantBefore;
import accord.local.cfk.CommandsForKey.TxnInfo;
import accord.local.cfk.CommandsForKey.InternalStatus;
import accord.local.cfk.CommandsForKey.TxnInfoExtra;
import accord.local.cfk.CommandsForKey.Unmanaged;
-import accord.local.Node;
import accord.primitives.Ballot;
-import accord.primitives.Routable.Domain;
import accord.primitives.Timestamp;
-import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.utils.BitUtils;
import accord.utils.Invariants;
-import accord.utils.UnhandledEnum;
import accord.utils.VIntCoding;
import static accord.local.cfk.CommandsForKey.NO_BOUNDS_INFO;
import static accord.local.cfk.CommandsForKey.NO_PENDING_UNMANAGED;
+import static accord.primitives.Routable.Domain.Key;
+import static accord.primitives.Routable.Domain.Range;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
-import static accord.primitives.TxnId.MediumPath.TRACK_STABLE;
-import static accord.primitives.TxnId.NO_TXNIDS;
import static accord.primitives.Txn.Kind.Read;
-import static accord.primitives.Txn.Kind.SyncPoint;
import static accord.primitives.Txn.Kind.Write;
+import static accord.primitives.TxnId.Cardinality.SingleKey;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithoutDeps;
+import static accord.primitives.TxnId.MediumPath.TrackStable;
+import static accord.primitives.TxnId.NO_TXNIDS;
+import static accord.utils.ArrayBuffers.cachedAny;
import static accord.utils.ArrayBuffers.cachedInts;
import static accord.utils.ArrayBuffers.cachedTxnIds;
import static accord.utils.BitUtils.flushBits;
@@ -64,7 +66,6 @@ import static accord.utils.VIntCoding.sizeOfVInt;
public class Serialize
{
- private static final int RAW_FLAG_BITS = 0;
private static final int TIMESTAMP_BASE_SIZE = 16;
private static final InternalStatus[] DECODE_STATUS = InternalStatus.values();
@@ -76,8 +77,6 @@ public class Serialize
private static final int HAS_BALLOT_HEADER_BIT_SHIFT = 2;
private static final int HAS_STATUS_OVERRIDES_HEADER_BIT = 0x8;
private static final int HAS_STATUS_OVERRIDES_HEADER_BIT_SHIFT = 3;
- private static final int HAS_NON_STANDARD_FLAGS_HEADER_BIT = 0x10;
- private static final int HAS_NON_STANDARD_FLAGS_HEADER_BIT_SHIFT = 4;
private static final int COMMAND_HEADER_BIT_FLAGS_MASK = 0x1f;
private static final int HAS_BOOTSTRAPPED_AT_HEADER_BIT = 0x20;
private static final int HAS_BOUNDS_FLAGS_HEADER_BIT = 0x40;
@@ -126,10 +125,10 @@ public class Serialize
* as we can encode a single bit stream with the optimal number of bits.
* TODO (desired): we could prefix this collection with the subset of TxnId that are actually missing from any other
* deps, so as to shrink this collection much further.
+ * TODO (desired): offer filtering option that does not need to reconstruct objects/info, reusing prior encoding decisions
+ * TODO (desired): accept new redundantBefore on load to avoid deserializing stale data
+ * TODO (desired): determine timestamp resolution as a factor of 10
*/
- // TODO (expected): offer filtering option that does not need to reconstruct objects/info, reusing prior encoding decisions
- // TODO (expected): accept new redundantBefore on load to avoid deserializing stale data
- // TODO (desired): determine timestamp resolution as a factor of 10
public static ByteBuffer toBytesWithoutKey(CommandsForKey cfk)
{
Invariants.requireArgument(!cfk.isLoadingPruned());
@@ -161,7 +160,6 @@ public class Serialize
// first compute the unique Node Ids and some basic characteristics of the data, such as
// whether we have any missing transactions to encode, any executeAt that are not equal to their TxnId
// and whether there are any non-standard flag bits to encode
- boolean hasExtendedFlags = false;
int nodeIdCount, missingIdCount = 0, executeAtCount = 0, ballotCount = 0, overrideCount = 0;
int bitsPerExecuteAtEpoch = 0, bitsPerExecuteAtFlags = 0, bitsPerExecuteAtHlc = 1; // to permit us to use full 64 bits and encode in 5 bits we force at least one hlc bit
{
@@ -184,7 +182,6 @@ public class Serialize
TxnInfo txn = cfk.get(i);
Invariants.require(!txn.is(InternalStatus.PRUNED));
overrideCount += txn.statusOverrides();
- hasExtendedFlags |= hasExtendedFlags(txn);
nodeIds[nodeIdCount++] = txn.node.id;
if (txn.executeAt != txn)
@@ -231,7 +228,7 @@ public class Serialize
// We can now use this information to calculate the fixed header size, compute the amount
// of additional space we'll need to store the TxnId and its basic info
int bitsPerNodeId = numberOfBitsToRepresent(nodeIdCount);
- int minHeaderBits = 9 + bitsPerNodeId + (hasExtendedFlags ? 1 : 0) + (overrideCount > 0 ? 1 : 0);
+ int minHeaderBits = 10 + bitsPerNodeId + (overrideCount > 0 ? 1 : 0);
int headerFlags = (executeAtCount > 0 ? 1 : 0)
| (missingIdCount > 0 ? 2 : 0)
| (ballotCount > 0 ? 4 : 0);
@@ -241,6 +238,7 @@ public class Serialize
int prunedBeforeIndex = cfk.prunedBefore().equals(TxnId.NONE) ? -1 : cfk.indexOf(cfk.prunedBefore());
+ long flagHistory = EMPTY_FLAG_HISTORY;
long prevEpoch = cfk.redundantBefore().epoch();
long prevHlc = cfk.redundantBefore().hlc();
int[] bytesHistogram = cachedInts().getInts(12);
@@ -277,8 +275,11 @@ public class Serialize
prevHlc = hlc;
}
- if (txnIdFlagsBits(txn, hasExtendedFlags) == RAW_FLAG_BITS)
- totalBytes += 2;
+ int flags = txn.flags();
+ int encodedFlagBits = encodedFlagBits(flags, flagHistory);
+ flagHistory = updateFlagHistory(flags, encodedFlagBits, flagHistory);
+ if (encodedFlagBits < 2)
+ totalBytes += 1 + encodedFlagBits;
if (txn.hasExecuteAt())
headerBits += headerFlags & 0x1;
@@ -304,7 +305,6 @@ public class Serialize
int globalFlags = (missingIdCount > 0 ? HAS_MISSING_DEPS_HEADER_BIT : 0)
| (executeAtCount > 0 ? HAS_EXECUTE_AT_HEADER_BIT : 0)
| (ballotCount > 0 ? HAS_BALLOT_HEADER_BIT : 0)
- | (hasExtendedFlags ? HAS_NON_STANDARD_FLAGS_HEADER_BIT : 0)
| (overrideCount > 0 ? HAS_STATUS_OVERRIDES_HEADER_BIT : 0)
| (cfk.bootstrappedAt() != null ? HAS_BOOTSTRAPPED_AT_HEADER_BIT : 0)
| (hasBoundsFlags(cfk) ? HAS_BOUNDS_FLAGS_HEADER_BIT : 0)
@@ -470,7 +470,8 @@ public class Serialize
}
VIntCoding.writeUnsignedVInt32(prunedBeforeIndex + 1, out);
- int flagsPlus = (globalFlags & COMMAND_HEADER_BIT_FLAGS_MASK) + (2 << HAS_NON_STANDARD_FLAGS_HEADER_BIT_SHIFT);
+ flagHistory = EMPTY_FLAG_HISTORY;
+ int flagsPlus = globalFlags & COMMAND_HEADER_BIT_FLAGS_MASK;
// TODO (desired): check this loop compiles correctly to only branch on epoch case, for binarySearch and flushing
for (int i = 0 ; i < commandCount ; ++i)
{
@@ -499,10 +500,14 @@ public class Serialize
bits |= hasBallot << bitIndex;
bitIndex += statusHasBallot & (flagsPlus >>> HAS_BALLOT_HEADER_BIT_SHIFT);
- long flagBits = txnIdFlagsBits(txn, hasExtendedFlags);
- boolean writeFullFlags = flagBits == RAW_FLAG_BITS;
- bits |= flagBits << bitIndex;
- bitIndex += flagsPlus >>> HAS_NON_STANDARD_FLAGS_HEADER_BIT_SHIFT;
+ int encodedFlagBits;
+ {
+ int flags = txn.flags();
+ encodedFlagBits = encodedFlagBits(flags, flagHistory);
+ flagHistory = updateFlagHistory(flags, encodedFlagBits, flagHistory);
+ bits |= (long)encodedFlagBits << bitIndex;
+ bitIndex += 3;
+ }
long hlcBits;
int extraEpochDeltaBytes = 0;
@@ -555,8 +560,12 @@ public class Serialize
writeLeastSignificantBytes(bits, headerBytes, out);
writeLeastSignificantBytes(hlcBits, getHlcBytes(hlcBytesLookup, hlcFlag), out);
- if (writeFullFlags)
- out.putShort((short)txn.flags());
+ if (encodedFlagBits < 2)
+ {
+ int flags = txn.flags();
+ if (encodedFlagBits == 0) out.put((byte)flags);
+ else out.putShort((short)flags);
+ }
if (extraEpochDeltaBytes > 0)
{
@@ -725,23 +734,22 @@ public class Serialize
int nodeIdCount = VIntCoding.readUnsignedVInt32(in);
int bitsPerNodeId = numberOfBitsToRepresent(nodeIdCount);
long nodeIdMask = (1L << bitsPerNodeId) - 1;
- Node.Id[] nodeIds = new Node.Id[nodeIdCount]; // TODO (expected): use a shared reusable scratch buffer
+ Object[] nodeIds = cachedAny().get(nodeIdCount);
{
int prev = VIntCoding.readUnsignedVInt32(in);
- nodeIds[0] = new Node.Id(prev);
+ nodeIds[0] = new Id(prev);
for (int i = 1 ; i < nodeIdCount ; ++i)
- nodeIds[i] = new Node.Id(prev += VIntCoding.readUnsignedVInt32(in));
+ nodeIds[i] = new Id(prev += VIntCoding.readUnsignedVInt32(in));
}
int globalFlags = (int) readLeastSignificantBytes(3, in);
- int txnIdFlagsMask;
int headerByteCount, hlcBytesLookup;
{
- txnIdFlagsMask = 0 != (globalFlags & HAS_NON_STANDARD_FLAGS_HEADER_BIT) ? 7 : 3;
headerByteCount = 1 + ((globalFlags >>> 14) & 0x3);
hlcBytesLookup = setHlcByteDeltas((globalFlags >>> 16) & 0x3, (globalFlags >>> 18) & 0x3, (globalFlags >>> 20) & 0x3, (globalFlags >>> 22) & 0x3);
}
+ long flagHistory = EMPTY_FLAG_HISTORY;
RedundantBefore.Entry boundsInfo;
long prevEpoch, prevHlc, maxUniqueHlc = 0;
{
@@ -759,7 +767,7 @@ public class Serialize
prevHlc = VIntCoding.readUnsignedVInt(in);
{
int flags = ((globalFlags & HAS_BOUNDS_FLAGS_HEADER_BIT) == 0) ? RX_FLAGS : VIntCoding.readUnsignedVInt32(in);
- Node.Id node = nodeIds[VIntCoding.readUnsignedVInt32(in)];
+ Id node = (Id)nodeIds[VIntCoding.readUnsignedVInt32(in)];
boundsInfo = boundsInfo.withGcBeforeBeforeAtLeast(TxnId.fromValues(prevEpoch, prevHlc, flags, node));
}
if (0 != (globalFlags & HAS_BOOTSTRAPPED_AT_HEADER_BIT))
@@ -767,7 +775,7 @@ public class Serialize
long epoch = prevEpoch + VIntCoding.readUnsignedVInt(in);
long hlc = prevHlc + VIntCoding.readVInt(in);
int flags = ((globalFlags & HAS_BOUNDS_FLAGS_HEADER_BIT) == 0) ? RX_FLAGS : VIntCoding.readUnsignedVInt32(in);
- Node.Id node = nodeIds[VIntCoding.readUnsignedVInt32(in)];
+ Id node = (Id)nodeIds[VIntCoding.readUnsignedVInt32(in)];
boundsInfo = boundsInfo.withBootstrappedAtLeast(TxnId.fromValues(epoch, hlc, flags, node));
}
if (0 != (globalFlags & HAS_MAX_HLC_HEADER_BIT))
@@ -803,12 +811,8 @@ public class Serialize
commandFlags[i] = commandDecodeFlags;
}
- Txn.Kind kind; Domain domain; {
- int flags = (int)header & txnIdFlagsMask;
- kind = kindLookup(flags);
- domain = domainLookup(flags);
- }
- header >>>= Integer.bitCount(txnIdFlagsMask);
+ int encodedFlags = (int)header & 7;
+ header >>>= 3;
boolean hlcIsNegative = false;
long epoch = prevEpoch;
@@ -834,7 +838,7 @@ public class Serialize
}
}
- Node.Id node = nodeIds[(int)(header & nodeIdMask)];
+ Id node = (Id)nodeIds[(int)(header & nodeIdMask)];
header >>>= bitsPerNodeId;
int readHlcBytes = getHlcBytes(hlcBytesLookup, (int)(header & 0x3));
@@ -851,13 +855,19 @@ public class Serialize
hlc = -1-hlc;
hlc += prevHlc;
- int flags = kind != null ? 0 : in.getShort();
+ int decodedFlags;
+ switch (encodedFlags)
+ {
+ case 0: decodedFlags = in.get() & 0xff; break;
+ case 1: decodedFlags = in.getShort() & 0xffff; break;
+ default: decodedFlags = selectFlagHistory(encodedFlags, flagHistory);
+ }
if (readEpochBytes > 0)
epoch += readEpochBytes == 1 ? (in.get() & 0xff) : in.getInt();
- // TODO (required): efficiently encode medium path / coordinator optimisation Flag
- txnIds[i] = kind != null ? new TxnId(epoch, hlc, 0, kind, domain, node)
- : TxnId.fromValues(epoch, hlc, flags, node);
+ TxnId txnId = TxnId.fromValues(epoch, hlc, decodedFlags, node);
+ txnIds[i] = txnId;
+ flagHistory = updateFlagHistory(decodedFlags, encodedFlags, flagHistory);
prevEpoch = epoch;
prevHlc = hlc;
@@ -925,7 +935,7 @@ public class Serialize
{
long epoch, hlc;
int flags;
- Node.Id id;
+ Id id;
if (bitsPerExecuteAt <= 64)
{
long executeAtBits = reader.read(bitsPerExecuteAt, in);
@@ -935,14 +945,14 @@ public class Serialize
executeAtBits >>>= bitsPerExecuteAtHlc;
flags = (int)(executeAtBits & executeAtFlagsMask);
executeAtBits >>>= bitsPerExecuteAtFlags;
- id = nodeIds[(int)(executeAtBits & nodeIdMask)];
+ id = (Id)nodeIds[(int)(executeAtBits & nodeIdMask)];
}
else
{
epoch = txnId.epoch() + reader.read(bitsPerExecuteAtEpoch, in);
hlc = txnId.hlc() + reader.read(bitsPerExecuteAtHlc, in);
flags = (int) reader.read(bitsPerExecuteAtFlags, in);
- id = nodeIds[(int)(reader.read(bitsPerNodeId, in))];
+ id = (Id)nodeIds[(int)(reader.read(bitsPerNodeId, in))];
}
executeAt = Timestamp.fromValues(epoch, hlc, flags, id);
}
@@ -976,14 +986,14 @@ public class Serialize
{
long msb = reader.read(64, in);
long lsb = reader.read(64, in);
- Node.Id id = nodeIds[(int)(reader.read(bitsPerNodeId, in))];
+ Id id = (Id)nodeIds[(int)(reader.read(bitsPerNodeId, in))];
ballot = Ballot.fromBits(msb, lsb, id);
}
else
{
long epoch, hlc;
int flags;
- Node.Id id;
+ Id id;
if (bitsPerBallot <= 64)
{
long ballotBits = reader.read(bitsPerBallot, in);
@@ -993,14 +1003,14 @@ public class Serialize
ballotBits >>>= bitsPerBallotHlc;
flags = (int)(ballotBits & ballotFlagsMask);
ballotBits >>>= bitsPerBallotFlags;
- id = nodeIds[(int)(ballotBits & nodeIdMask)];
+ id = (Id)nodeIds[(int)(ballotBits & nodeIdMask)];
}
else
{
epoch = prevBallot.epoch() + decodeZigZag64(reader.read(bitsPerBallotEpoch, in));
hlc = prevBallot.hlc() + decodeZigZag64(reader.read(bitsPerBallotHlc, in));
flags = (int) reader.read(bitsPerBallotFlags, in);
- id = nodeIds[(int)(reader.read(bitsPerNodeId, in))];
+ id = (Id)nodeIds[(int)(reader.read(bitsPerNodeId, in))];
}
ballot = Ballot.fromValues(epoch, hlc, flags, id);
}
@@ -1028,7 +1038,7 @@ public class Serialize
}
}
cachedTxnIds().forceDiscard(txnIds, commandCount);
-
+ cachedAny().forceDiscard(nodeIds, nodeIdCount);
return CommandsForKey.SerializerSupport.create(key, txns, maxUniqueHlc, unmanageds, prunedBeforeIndex == -1 ? TxnId.NONE : txns[prunedBeforeIndex], boundsInfo);
}
@@ -1069,7 +1079,7 @@ public class Serialize
return (bootstrappedAt != null && bootstrappedAt.flags() != RX_FLAGS) || (redundantBefore.flags() != RX_FLAGS);
}
- private static final int RX_FLAGS = new TxnId(0, 0, TRACK_STABLE.bits, ExclusiveSyncPoint, Domain.Range, Node.Id.NONE).flags();
+ private static final int RX_FLAGS = new TxnId(0, 0, TrackStable.bit(), ExclusiveSyncPoint, Range, Id.NONE).flags();
private static int hlcBytesLookupToHlcFlagLookup(int bytesLookup)
{
@@ -1098,83 +1108,111 @@ public class Serialize
return count;
}
- private static boolean hasExtendedFlags(TxnId txnId)
+ // a static initial flag history that may capture some of the more common flags
+ // TODO (desired): let the implementation define this, or encode a compressed set of flags in an initial bit mask
+ static final long EMPTY_FLAG_HISTORY;
+ static
{
- if (txnId.flags() > Timestamp.KIND_AND_DOMAIN_FLAGS)
- return false; // will be encoded raw, so not non-standard
+ long empty = 0L;
+ empty |= new TxnId(0, 0, TrackStable.bit() | PrivilegedCoordinatorWithoutDeps.bits, Read, Key, SingleKey, Id.NONE).flags();
+ empty |= (long) new TxnId(0, 0, TrackStable.bit(), Read, Key, Id.NONE).flags() << 9;
+ empty |= (long) new TxnId(0, 0, TrackStable.bit() | PrivilegedCoordinatorWithoutDeps.bits, Write, Key, SingleKey, Id.NONE).flags() << 18;
+ empty |= (long) new TxnId(0, 0, TrackStable.bit(), Write, Key, SingleKey, Id.NONE).flags() << 27;
+ empty |= (long) new TxnId(0, 0, TrackStable.bit(), Write, Key, Id.NONE).flags() << 36;
+ empty |= (long) new TxnId(0, 0, TrackStable.bit(), ExclusiveSyncPoint, Range, Id.NONE).flags() << 45;
+ EMPTY_FLAG_HISTORY = empty;
+ }
+
+ private static final long MATCH_MASK1 = replicateMatchBits(0x0ff);
+ private static final long MATCH_INCR = replicateMatchBits(0x001);
+ private static final long MATCH_MASK2 = replicateMatchBits(0x100);
+ private static final long MAP_FLAG_BITS = 2L | (3L << 9) | (4L << 18) | (5L << 27) | (6L << 36) | (7L << 45);
- int flagBits = txnIdFlagsBits(txnId, true);
- return flagBits > 3;
+ // copy the provided 8 bits into bit positions 9, 18, 27, 36 and 45
+ private static long replicateMatchBits(long flags)
+ {
+ flags = flags | (flags << 9) | (flags << 18); // duplicate the flag values so they occur at both position 0 and 9
+ return flags | (flags << 27); // duplicate the flag values so they occur at both position 0, 9, 18, 27, 36, 45
+ }
+
+ // OR all 8 bits at each bit position 0, 9, 18, 27, 36 and 45 into position 0
+ private static long collapseMatchBits(long flags)
+ {
+ flags = flags | (flags >>> 9) | (flags >>> 18);
+ return flags | (flags >>> 27);
}
/**
- * 0 => write full flags
- * 1 => KR (Key Read)
- * 2 => KW (Key Write)
- * 3 => KS (Key SyncPoint)
- * 4 => RR (Range Read)
- * 5 => RX (Range Exclusive SyncPoint)
- * 6, 7 => UNUSED
+ * The bits we write to the output to encode the input flags.
+ * If the flags are equal to any of the flagHistory entries, we encode the relevant index (plus 2);
+ * otherwise we encode how many bytes (1 or 2) we must read (as 0 or 1).
+ *
+ * 0 => write 1 byte flags
+ * 1 => write 2 byte flags
+ * 2 to 6 => index into the flagHistory for a recently encoded 1-byte flag
*/
- private static int txnIdFlagsBits(TxnId txnId, boolean extended)
+ @VisibleForTesting
+ static int encodedFlagBits(int flags, long flagHistory)
{
- // TODO (required): we expect to almost always have more flags than this, so optimise handling
- if (txnId.flags() > Timestamp.KIND_AND_DOMAIN_FLAGS)
- return 0;
+ if (flags > 0xff)
+ return 1;
+
+ long flagMask = replicateMatchBits(flags); // duplicate the flag values so they occur at both position 0, 9, 18, 27, 36, 45
+ long matches = ~flagHistory ^ flagMask; // set 0xff if either history position is equal to the current flags value
+ matches &= MATCH_MASK1; // clear any unrelated bits, so we can use integer overflow
+ matches += MATCH_INCR; // increment by 1 - if 0xff was set ONLY, this will overflow to the next higher bit
+ matches &= MATCH_MASK2; // clear all but these overflow bits (if any)
+ matches -= matches >>> 8; // subtract the overflow bit from itself shifted down by 8 - this will set 0xff in the correct position
+ matches &= MAP_FLAG_BITS; // apply all potential masks simultaneously to the relevant decodeBits positions - only one is set (assuming no duplicate flag history entry)
+ return (int) collapseMatchBits(matches) & 0xff; // collapse all 6 possible match positions into an answer (only one will be non-zero)
+ }
- Txn.Kind kind = txnId.kind();
- Domain domain = txnId.domain();
- switch (domain)
+ // update the flag history register, moving any decoded value into the most recent position and shifting all
+ // values that were previously more recent back by one
+ static long updateFlagHistory(int flags, int encoded, long flagHistory)
+ {
+ switch (encoded)
{
- case Key:
- switch (kind)
- {
- case Read: return 1;
- case Write: return 2;
- case SyncPoint: return 3;
- default: return 0;
- }
- case Range:
- if (!extended)
- return 0;
-
- switch (kind)
- {
- case Read: return 4;
- case ExclusiveSyncPoint: return 5;
- default: return 0;
- }
- default: throw new UnhandledEnum(domain);
+ case 0:
+ case 7: // we're evicting least recently used
+ flagHistory <<= 9;
+ flagHistory |= flags;
+ case 2: // have re-used most recent value
+ return flagHistory;
+ default:
+ long mask = -1L << flagHistoryShift(encoded + 1);
+ flagHistory = (flagHistory & mask) | ((flagHistory << 9) & ~mask);
+ flagHistory |= flags;
+ return flagHistory;
}
}
- private static Domain domainLookup(int flags)
+ static int selectFlagHistory(int encoded, long flagHistory)
{
- return flags < 4 ? Domain.Key : Domain.Range;
+ return (int) ((flagHistory >>> flagHistoryShift(encoded)) & 0xff);
}
- private static Txn.Kind kindLookup(int flags)
+ private static int flagHistoryShift(int encodedFlagBits)
{
- return TXN_ID_FLAG_BITS_KIND_LOOKUP[flags];
+ int pos = encodedFlagBits - 2;
+ return (pos * 8) + pos;
}
- private static final Txn.Kind[] TXN_ID_FLAG_BITS_KIND_LOOKUP = new Txn.Kind[] { null, Read, Write, SyncPoint, Read, ExclusiveSyncPoint, null, null };
-
- private static Timestamp readTimestamp(ByteBuffer in, Node.Id[] ids, int idBytes)
+ private static Timestamp readTimestamp(ByteBuffer in, Object[] ids, int idBytes)
{
// TODO (desired): smarter encoding, separating into epoch,hlc,flag parts to be encoded separately
// OR encode Unmanaged as a list using same logic as we do for managed transactions
long msb = in.getLong();
long lsb = in.getLong();
- Node.Id id = ids[(int) readLeastSignificantBytes(idBytes, in)];
+ Id id = (Id)ids[(int) readLeastSignificantBytes(idBytes, in)];
return Timestamp.fromBits(msb, lsb, id);
}
- private static TxnId readTxnId(ByteBuffer in, Node.Id[] ids, int idBytes)
+ private static TxnId readTxnId(ByteBuffer in, Object[] ids, int idBytes)
{
long msb = in.getLong();
long lsb = in.getLong();
- Node.Id id = ids[(int) readLeastSignificantBytes(idBytes, in)];
+ Id id = (Id)ids[(int) readLeastSignificantBytes(idBytes, in)];
return TxnId.fromBits(msb, lsb, id);
}
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 6e9d0ff6..1397319f 100644
--- a/accord-core/src/main/java/accord/local/cfk/Updating.java
+++ b/accord-core/src/main/java/accord/local/cfk/Updating.java
@@ -57,8 +57,8 @@ import static accord.local.cfk.CommandsForKey.InternalStatus.INVALIDATED;
import static accord.local.cfk.CommandsForKey.InternalStatus.TRANSITIVE_VISIBLE;
import static accord.local.cfk.CommandsForKey.Unmanaged.Pending.APPLY;
import static accord.local.cfk.CommandsForKey.Unmanaged.Pending.COMMIT;
-import static accord.local.cfk.CommandsForKey.executesIgnoreBootstrap;
-import static accord.local.cfk.CommandsForKey.reportLinearizabilityViolations;
+import static accord.local.cfk.CommandsForKey.executesIgnoringBootstrap;
+import static accord.local.cfk.CommandsForKey.reportLinearizabilityViolation;
import static accord.local.cfk.CommandsForKey.mayExecute;
import static accord.local.cfk.Pruning.loadingPrunedFor;
import static accord.local.cfk.UpdateUnmanagedMode.REGISTER;
@@ -652,8 +652,8 @@ class Updating
{
for (int i = pos; i <= maxAppliedWriteByExecuteAt; ++i)
{
- if (committedByExecuteAt[pos].witnesses(newInfo) && reportLinearizabilityViolations())
- logger.error("Linearizability violation on key {}: {} is committed to execute (at {}) before {} that should witness it but has already applied (at {})", cfk.key, newInfo.plainTxnId(), newInfo.plainExecuteAt(), committedByExecuteAt[i].plainTxnId(), committedByExecuteAt[i].plainExecuteAt());
+ if (committedByExecuteAt[pos].witnesses(newInfo))
+ reportLinearizabilityViolation(cfk.key, newInfo.plainTxnId(), newInfo.plainExecuteAt(), committedByExecuteAt[i].plainTxnId(), committedByExecuteAt[i].plainExecuteAt());
}
}
}
@@ -710,10 +710,8 @@ class Updating
TxnInfo[] committedByExecuteAt = cfk.committedByExecuteAt;
for (int i = cfk.maxAppliedWriteByExecuteAt + 1; i < appliedPos ; ++i)
{
- if (committedByExecuteAt[i].isNot(APPLIED)
- && appliedKind.witnesses(committedByExecuteAt[i])
- && reportLinearizabilityViolations())
- logger.error("Linearizability violation on key {}: {} is committed to execute (at {}) before {} that should witness it but has already applied (at {})", cfk.key, committedByExecuteAt[i].plainTxnId(), committedByExecuteAt[i].plainExecuteAt(), applied.plainTxnId(), applied.plainExecuteAt());
+ if (committedByExecuteAt[i].isNot(APPLIED) && appliedKind.witnesses(committedByExecuteAt[i]))
+ reportLinearizabilityViolation(cfk.key, committedByExecuteAt[i].plainTxnId(), committedByExecuteAt[i].plainExecuteAt(), applied.plainTxnId(), applied.plainExecuteAt());
}
}
@@ -737,7 +735,7 @@ class Updating
private static long updateMaxUniqueHlc(CommandsForKey cfk, TxnInfo newInfo, Command update)
{
long maxUniqueHlc = cfk.maxUniqueHlc;
- if (newInfo.is(APPLIED) && newInfo.is(Write) && (newInfo.mayExecute() || executesIgnoreBootstrap(cfk.boundsInfo, newInfo, newInfo.executeAt)))
+ if (newInfo.is(APPLIED) && newInfo.is(Write) && (newInfo.mayExecute() || executesIgnoringBootstrap(cfk.boundsInfo, newInfo, newInfo.executeAt)))
{
long newUniqueHlc = update.executeAt().uniqueHlc();
if (maxUniqueHlc < newUniqueHlc)
@@ -762,7 +760,7 @@ class Updating
if (postProcess != null)
postProcess.postProcess(safeStore, key, notifySink);
}
- }).begin(commandStore.agent());
+ }, commandStore.agent());
}
static CommandsForKeyUpdate updateUnmanaged(CommandsForKey cfk, SafeCommand safeCommand)
diff --git a/accord-core/src/main/java/accord/messages/Accept.java b/accord-core/src/main/java/accord/messages/Accept.java
index 1c887269..163a065e 100644
--- a/accord-core/src/main/java/accord/messages/Accept.java
+++ b/accord-core/src/main/java/accord/messages/Accept.java
@@ -173,7 +173,6 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
public final AcceptOutcome outcome;
public final Ballot supersededBy;
- // TODO (expected): only send back deps that weren't in those we received
public final @Nullable Deps deps;
public final @Nullable Timestamp committedExecuteAt;
diff --git a/accord-core/src/main/java/accord/messages/Apply.java b/accord-core/src/main/java/accord/messages/Apply.java
index c8ad38ac..88516ddc 100644
--- a/accord-core/src/main/java/accord/messages/Apply.java
+++ b/accord-core/src/main/java/accord/messages/Apply.java
@@ -74,8 +74,6 @@ public class Apply extends TxnRequest<ApplyReply>
{
super(to, participates, sendTo, txnId);
Invariants.require(txnId.kind() != Txn.Kind.Write || writes != null);
- // TODO (desired): it's wasteful to encode the full set of ranges owned by the recipient node;
- // often it will be cheaper to include the FullRoute for Deps scope (or come up with some other safety-preserving encoding scheme)
this.kind = kind;
this.deps = deps.intersecting(scope);
this.txn = kind == Kind.Maximal ? txn.intersecting(scope, true) : null;
diff --git a/accord-core/src/main/java/accord/messages/BeginRecovery.java b/accord-core/src/main/java/accord/messages/BeginRecovery.java
index c9d5b91b..444d5e58 100644
--- a/accord-core/src/main/java/accord/messages/BeginRecovery.java
+++ b/accord-core/src/main/java/accord/messages/BeginRecovery.java
@@ -64,8 +64,7 @@ import static accord.primitives.Status.PreAccepted;
import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.primitives.Txn.Kind.Write;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
-import static accord.utils.Invariants.illegalState;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.RecoverReply>
{
@@ -86,7 +85,6 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
public BeginRecovery(Id to, Topologies topologies, TxnId txnId, @Nullable Timestamp executeAt, Txn txn, FullRoute<?> route, Ballot ballot)
{
super(to, topologies, txnId, route);
- // TODO (expected): only scope.contains(route.homeKey); this affects state eviction and is low priority given size in C*
this.partialTxn = txn.intersecting(scope, true);
this.ballot = ballot;
this.route = route;
@@ -117,18 +115,11 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
Commands.AcceptOutcome outcome = Commands.recover(safeStore, safeCommand, participants, txnId, partialTxn, route, ballot);
switch (outcome)
{
- default: throw illegalState("Unhandled Outcome: " + outcome);
- case Redundant: throw illegalState("Invaid Outcome: " + outcome);
-
- case Truncated:
- return new RecoverNack(Truncated, null);
-
- case Retired:
- return new RecoverNack(Retired, null);
-
- case RejectedBallot:
- return new RecoverNack(Reject, safeCommand.current().promised());
-
+ default: throw UnhandledEnum.unknown(outcome);
+ case Redundant: throw UnhandledEnum.invalid(outcome);
+ case Truncated: return new RecoverNack(Truncated, null);
+ case Retired: return new RecoverNack(Retired, null);
+ case RejectedBallot: return new RecoverNack(Reject, safeCommand.current().promised());
case Success:
}
@@ -164,7 +155,6 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
}
else
{
- // TODO (expected): modify the mapReduce API to perform this check in a single pass
try (Visitor visitor = new Visitor())
{
safeStore.visit(participants.owns(), txnId, txnId.witnessedBy(), ANY, txnId, EITHER, visitor);
@@ -341,9 +331,10 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
case PREACCEPTED:
case NOTACCEPTED:
// no need to wait for potential medium path transactions started before us, only after
- // however, both privileged coordinator optimisations require waiting for an earlier potential fast path to decide itself
- // TODO (desired): compute against shard whether this is necessary - for most quorum configurations it doesn't
- if (testTxnId.hasPrivilegedCoordinator())
+ // however, both privileged coordinator optimisations require waiting for the earlier potential fast path to decide itself
+ // (that is, if either transaction use the optimisation, we must wait for the earlier transaction)
+ // TODO (desired): compute against shard whether this is a necessary wait condition - for many quorum configurations it isn't
+ if (testTxnId.hasPrivilegedCoordinator() || txnId.hasPrivilegedCoordinator())
ensureEarlierWait().add(keyOrRange, testTxnId);
}
}
@@ -373,7 +364,7 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
break;
case IS_NOT_COORD_DEP:
- Invariants.requireArgument(testTxnId.is(PRIVILEGED_COORDINATOR_WITH_DEPS));
+ Invariants.requireArgument(testTxnId.is(PrivilegedCoordinatorWithDeps));
ensureLaterCoordRejects().add(keyOrRange, testTxnId);
}
}
@@ -425,7 +416,7 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
public static abstract class RecoverReply implements Reply
{
- // TODO (expected): recover should gracefully handle partial truncation (currently expected to be handled by MaybeRecover)
+ // TODO (required): recover should gracefully handle partial truncation (currently expected to be handled by MaybeRecover)
public enum Kind { Ok, Retired, Truncated, Reject }
@Override
diff --git a/accord-core/src/main/java/accord/messages/Callback.java b/accord-core/src/main/java/accord/messages/Callback.java
index 549c92e2..7f0d48e9 100644
--- a/accord-core/src/main/java/accord/messages/Callback.java
+++ b/accord-core/src/main/java/accord/messages/Callback.java
@@ -22,8 +22,6 @@ import accord.local.Node.Id;
/**
* Represents some execution for handling responses from messages a node has sent.
- * TODO (expected, efficiency): associate a Callback with a CommandShard or other context for execution
- * (for coordination, usually its home shard)
*/
public interface Callback<T>
{
diff --git a/accord-core/src/main/java/accord/messages/CheckStatus.java b/accord-core/src/main/java/accord/messages/CheckStatus.java
index 90beaa3d..e64af6c5 100644
--- a/accord-core/src/main/java/accord/messages/CheckStatus.java
+++ b/accord-core/src/main/java/accord/messages/CheckStatus.java
@@ -240,9 +240,6 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
public static class CheckStatusOk implements CheckStatusReply
{
public final KnownMap map;
- // TODO (required): tighten up constraints here to ensure we only report truncated when the range is Durable
- // TODO (expected, cleanup): stop using saveStatus and maxSaveStatus - move to only Known
- // care needed when merging Accepted and AcceptedInvalidate; might be easier to retain saveStatus only for merging these cases
public final SaveStatus maxKnowledgeSaveStatus, maxSaveStatus;
public final Ballot maxPromised;
public final Ballot acceptedOrCommitted;
@@ -254,7 +251,7 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
* with other commit records that in fact supersede the data we have.
*/
public final Ballot maxAcceptedOrCommitted;
- // TODO (expected, cleanup): try convert to committedExecuteAt, so null if not 'known'
+ // TODO (expected): convert to committedExecuteAt if safe to do so; then null if not 'known'
public final @Nullable Timestamp executeAt; // not set if invalidating or invalidated
public final boolean isCoordinating;
public final Durability durability;
diff --git a/accord-core/src/main/java/accord/messages/Commit.java b/accord-core/src/main/java/accord/messages/Commit.java
index acbdc0b5..4f76e621 100644
--- a/accord-core/src/main/java/accord/messages/Commit.java
+++ b/accord-core/src/main/java/accord/messages/Commit.java
@@ -275,7 +275,6 @@ public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
return node.mapReduceConsumeLocal(this, minEpoch, executeAt.epoch(), this);
}
- // TODO (expected, efficiency, clarity): do not guard with synchronized; let mapReduceLocal decide how to enforce mutual exclusivity
@Override
public synchronized CommitOrReadNack apply(SafeCommandStore safeStore)
{
diff --git a/accord-core/src/main/java/accord/messages/InformDurable.java b/accord-core/src/main/java/accord/messages/InformDurable.java
index b88a13d6..9d5f07df 100644
--- a/accord-core/src/main/java/accord/messages/InformDurable.java
+++ b/accord-core/src/main/java/accord/messages/InformDurable.java
@@ -108,7 +108,7 @@ public class InformDurable extends TxnRequest<Reply> implements PreLoadContext
@Override
public Cancellable submit()
{
- // TODO (expected, efficiency): do not load from disk to perform this update
+ // TODO (expected): do not load from disk to perform this update, just write a delta to any journal
return node.mapReduceConsumeLocal(txnId, scope, minEpoch, maxEpoch, this);
}
diff --git a/accord-core/src/main/java/accord/messages/MessageType.java b/accord-core/src/main/java/accord/messages/MessageType.java
index 799e7741..0dce2fc3 100644
--- a/accord-core/src/main/java/accord/messages/MessageType.java
+++ b/accord-core/src/main/java/accord/messages/MessageType.java
@@ -29,54 +29,54 @@ import static accord.messages.MessageType.Kind.LOCAL;
/**
* Meant to assist implementations with mapping accord messages to their own messaging systems.
*
- * TODO (expected): no longer need hasSideEffects parameter. Also, why are we not using enums?
+ * TODO (expected): Migrate to enum.
*/
public class MessageType
{
- public static final MessageType SIMPLE_RSP = remote("SIMPLE_RSP", false);
- public static final MessageType FAILURE_RSP = remote("FAILURE_RSP", false);
- public static final MessageType PRE_ACCEPT_REQ = remote("PRE_ACCEPT_REQ", true );
- public static final MessageType PRE_ACCEPT_RSP = remote("PRE_ACCEPT_RSP", false);
- public static final MessageType ACCEPT_REQ = remote("ACCEPT_REQ", true );
- public static final MessageType ACCEPT_RSP = remote("ACCEPT_RSP", false);
- public static final MessageType NOT_ACCEPT_REQ = remote("NOT_ACCEPT_REQ", true );
- public static final MessageType GET_LATEST_DEPS_REQ = remote("GET_LATEST_DEPS_REQ", false);
- public static final MessageType GET_LATEST_DEPS_RSP = remote("GET_LATEST_DEPS_RSP", false);
- public static final MessageType GET_EPHEMERAL_READ_DEPS_REQ = remote("GET_EPHEMERAL_READ_DEPS_REQ", false);
- public static final MessageType GET_EPHEMERAL_READ_DEPS_RSP = remote("GET_EPHEMERAL_READ_DEPS_RSP", false);
- public static final MessageType COMMIT_SLOW_PATH_REQ = remote("COMMIT_SLOW_PATH_REQ", true);
- public static final MessageType COMMIT_MAXIMAL_REQ = remote("COMMIT_MAXIMAL_REQ", true );
- public static final MessageType STABLE_FAST_PATH_REQ = remote("STABLE_FAST_PATH_REQ", true);
- public static final MessageType STABLE_SLOW_PATH_REQ = remote("STABLE_SLOW_PATH_REQ", true);
- public static final MessageType STABLE_MAXIMAL_REQ = remote("STABLE_MAXIMAL_REQ", true );
- public static final MessageType COMMIT_INVALIDATE_REQ = remote("COMMIT_INVALIDATE_REQ", true );
- public static final MessageType APPLY_MINIMAL_REQ = remote("APPLY_MINIMAL_REQ", true );
- public static final MessageType APPLY_MAXIMAL_REQ = remote("APPLY_MAXIMAL_REQ", true );
- public static final MessageType APPLY_RSP = remote("APPLY_RSP", false);
- public static final MessageType READ_REQ = remote("READ_REQ", false);
- public static final MessageType READ_EPHEMERAL_REQ = remote("READ_EPHEMERAL_REQ", false);
- public static final MessageType READ_RSP = remote("READ_RSP", false);
- public static final MessageType BEGIN_RECOVER_REQ = remote("BEGIN_RECOVER_REQ", true );
- public static final MessageType BEGIN_RECOVER_RSP = remote("BEGIN_RECOVER_RSP", false);
- public static final MessageType BEGIN_INVALIDATE_REQ = remote("BEGIN_INVALIDATE_REQ", true );
- public static final MessageType BEGIN_INVALIDATE_RSP = remote("BEGIN_INVALIDATE_RSP", false);
- public static final MessageType AWAIT_REQ = remote("AWAIT_REQ", false);
- public static final MessageType AWAIT_RSP = remote("AWAIT_RSP", false);
- public static final MessageType RECOVER_AWAIT_REQ = remote("RECOVER_AWAIT_REQ", false);
- public static final MessageType RECOVER_AWAIT_RSP = remote("RECOVER_AWAIT_RSP", false);
- public static final MessageType ASYNC_AWAIT_COMPLETE_REQ = remote("ASYNC_AWAIT_COMPLETE_RSP", false);
- public static final MessageType WAIT_UNTIL_APPLIED_REQ = remote("WAIT_UNTIL_APPLIED_REQ", false);
- public static final MessageType APPLY_THEN_WAIT_UNTIL_APPLIED_REQ = remote("APPLY_THEN_WAIT_UNTIL_APPLIED_REQ", true );
- public static final MessageType STABLE_THEN_READ_REQ = remote("STABLE_THEN_READ", true );
- public static final MessageType INFORM_DURABLE_REQ = remote("INFORM_DURABLE_REQ", true );
- public static final MessageType CHECK_STATUS_REQ = remote("CHECK_STATUS_REQ", false);
- public static final MessageType CHECK_STATUS_RSP = remote("CHECK_STATUS_RSP", false);
- public static final MessageType FETCH_DATA_REQ = remote("FETCH_DATA_REQ", false);
- public static final MessageType FETCH_DATA_RSP = remote("FETCH_DATA_RSP", false);
- public static final MessageType SET_SHARD_DURABLE_REQ = remote("SET_SHARD_DURABLE_REQ", true );
- public static final MessageType SET_GLOBALLY_DURABLE_REQ = remote("SET_GLOBALLY_DURABLE_REQ", true );
- public static final MessageType QUERY_DURABLE_BEFORE_REQ = remote("QUERY_DURABLE_BEFORE_REQ", false);
- public static final MessageType QUERY_DURABLE_BEFORE_RSP = remote("QUERY_DURABLE_BEFORE_RSP", false);
+ public static final MessageType SIMPLE_RSP = remote("SIMPLE_RSP");
+ public static final MessageType FAILURE_RSP = remote("FAILURE_RSP");
+ public static final MessageType PRE_ACCEPT_REQ = remote("PRE_ACCEPT_REQ");
+ public static final MessageType PRE_ACCEPT_RSP = remote("PRE_ACCEPT_RSP");
+ public static final MessageType ACCEPT_REQ = remote("ACCEPT_REQ");
+ public static final MessageType ACCEPT_RSP = remote("ACCEPT_RSP");
+ public static final MessageType NOT_ACCEPT_REQ = remote("NOT_ACCEPT_REQ");
+ public static final MessageType GET_LATEST_DEPS_REQ = remote("GET_LATEST_DEPS_REQ");
+ public static final MessageType GET_LATEST_DEPS_RSP = remote("GET_LATEST_DEPS_RSP");
+ public static final MessageType GET_EPHEMERAL_READ_DEPS_REQ = remote("GET_EPHEMERAL_READ_DEPS_REQ");
+ public static final MessageType GET_EPHEMERAL_READ_DEPS_RSP = remote("GET_EPHEMERAL_READ_DEPS_RSP");
+ public static final MessageType COMMIT_SLOW_PATH_REQ = remote("COMMIT_SLOW_PATH_REQ");
+ public static final MessageType COMMIT_MAXIMAL_REQ = remote("COMMIT_MAXIMAL_REQ");
+ public static final MessageType STABLE_FAST_PATH_REQ = remote("STABLE_FAST_PATH_REQ");
+ public static final MessageType STABLE_SLOW_PATH_REQ = remote("STABLE_SLOW_PATH_REQ");
+ public static final MessageType STABLE_MAXIMAL_REQ = remote("STABLE_MAXIMAL_REQ");
+ public static final MessageType COMMIT_INVALIDATE_REQ = remote("COMMIT_INVALIDATE_REQ");
+ public static final MessageType APPLY_MINIMAL_REQ = remote("APPLY_MINIMAL_REQ");
+ public static final MessageType APPLY_MAXIMAL_REQ = remote("APPLY_MAXIMAL_REQ");
+ public static final MessageType APPLY_RSP = remote("APPLY_RSP");
+ public static final MessageType READ_REQ = remote("READ_REQ");
+ public static final MessageType READ_EPHEMERAL_REQ = remote("READ_EPHEMERAL_REQ");
+ public static final MessageType READ_RSP = remote("READ_RSP");
+ public static final MessageType BEGIN_RECOVER_REQ = remote("BEGIN_RECOVER_REQ");
+ public static final MessageType BEGIN_RECOVER_RSP = remote("BEGIN_RECOVER_RSP");
+ public static final MessageType BEGIN_INVALIDATE_REQ = remote("BEGIN_INVALIDATE_REQ");
+ public static final MessageType BEGIN_INVALIDATE_RSP = remote("BEGIN_INVALIDATE_RSP");
+ public static final MessageType AWAIT_REQ = remote("AWAIT_REQ");
+ public static final MessageType AWAIT_RSP = remote("AWAIT_RSP");
+ public static final MessageType RECOVER_AWAIT_REQ = remote("RECOVER_AWAIT_REQ");
+ public static final MessageType RECOVER_AWAIT_RSP = remote("RECOVER_AWAIT_RSP");
+ public static final MessageType ASYNC_AWAIT_COMPLETE_REQ = remote("ASYNC_AWAIT_COMPLETE_RSP");
+ public static final MessageType WAIT_UNTIL_APPLIED_REQ = remote("WAIT_UNTIL_APPLIED_REQ");
+ public static final MessageType APPLY_THEN_WAIT_UNTIL_APPLIED_REQ = remote("APPLY_THEN_WAIT_UNTIL_APPLIED_REQ");
+ public static final MessageType STABLE_THEN_READ_REQ = remote("STABLE_THEN_READ");
+ public static final MessageType INFORM_DURABLE_REQ = remote("INFORM_DURABLE_REQ");
+ public static final MessageType CHECK_STATUS_REQ = remote("CHECK_STATUS_REQ");
+ public static final MessageType CHECK_STATUS_RSP = remote("CHECK_STATUS_RSP");
+ public static final MessageType FETCH_DATA_REQ = remote("FETCH_DATA_REQ");
+ public static final MessageType FETCH_DATA_RSP = remote("FETCH_DATA_RSP");
+ public static final MessageType SET_SHARD_DURABLE_REQ = remote("SET_SHARD_DURABLE_REQ");
+ public static final MessageType SET_GLOBALLY_DURABLE_REQ = remote("SET_GLOBALLY_DURABLE_REQ");
+ public static final MessageType QUERY_DURABLE_BEFORE_REQ = remote("QUERY_DURABLE_BEFORE_REQ");
+ public static final MessageType QUERY_DURABLE_BEFORE_RSP = remote("QUERY_DURABLE_BEFORE_RSP");
/**
* LOCAL messages are not sent to remote nodes.
@@ -105,29 +105,23 @@ public class MessageType
values = builder.build();
}
- protected static MessageType local(String name, boolean hasSideEffects)
+ protected static MessageType local(String name)
{
- return new MessageType(name, LOCAL, hasSideEffects);
+ return new MessageType(name, LOCAL);
}
- protected static MessageType remote(String name, boolean hasSideEffects)
+ protected static MessageType remote(String name)
{
- return new MessageType(name, REMOTE, hasSideEffects);
+ return new MessageType(name, REMOTE);
}
private final String name;
private final Kind kind;
- /**
- * If true, indicates that processing of the message has important side effects.
- */
- private final boolean hasSideEffects;
-
- protected MessageType(String name, Kind kind, boolean hasSideEffects)
+ protected MessageType(String name, Kind kind)
{
this.name = name;
this.kind = kind;
- this.hasSideEffects = hasSideEffects;
}
public String name()
@@ -150,9 +144,4 @@ public class MessageType
{
return kind == REMOTE;
}
-
- public boolean hasSideEffects()
- {
- return hasSideEffects;
- }
}
diff --git a/accord-core/src/main/java/accord/messages/PreAccept.java b/accord-core/src/main/java/accord/messages/PreAccept.java
index d11607be..6a9000f4 100644
--- a/accord-core/src/main/java/accord/messages/PreAccept.java
+++ b/accord-core/src/main/java/accord/messages/PreAccept.java
@@ -266,7 +266,6 @@ public class PreAccept extends WithUnsynced<PreAccept.PreAcceptReply>
public static Deps calculateDeps(SafeCommandStore safeStore, TxnId txnId, StoreParticipants participants, EpochSupplier minEpoch, Timestamp executeAt, boolean nullIfRedundant)
{
- // TODO (expected): do not build covering ranges; no longer especially valuable given use of FullRoute
// 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())
@@ -288,7 +287,6 @@ public class PreAccept extends WithUnsynced<PreAccept.PreAcceptReply>
in.add(keyOrRange, testTxnId);
}, executeAt.equals(txnId) ? null : txnId, builder);
- // TODO (required): make sure any sync point is in the past
Deps result = builder.build();
result = new Deps(result.keyDeps, result.rangeDeps.with(redundant), result.directKeyDeps);
Invariants.require(!result.contains(txnId));
diff --git a/accord-core/src/main/java/accord/messages/Propagate.java b/accord-core/src/main/java/accord/messages/Propagate.java
index 522a63c6..bac453ce 100644
--- a/accord-core/src/main/java/accord/messages/Propagate.java
+++ b/accord-core/src/main/java/accord/messages/Propagate.java
@@ -17,10 +17,12 @@
*/
package accord.messages;
+import accord.api.ProtocolModifiers;
import accord.api.Result;
import accord.api.RoutingKey;
import accord.coordinate.FetchData.FetchResult;
import accord.coordinate.Infer.InvalidIf;
+import accord.local.Cleanup;
import accord.local.Command;
import accord.local.Commands;
import accord.local.Node;
@@ -46,7 +48,6 @@ import accord.primitives.Unseekables;
import accord.primitives.Writes;
import accord.utils.Invariants;
import accord.utils.MapReduceConsume;
-import accord.utils.UnhandledEnum;
import javax.annotation.Nullable;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
@@ -57,6 +58,8 @@ import static accord.coordinate.Infer.InvalidIf.NotKnownToBeInvalid;
import static accord.local.Cleanup.ERASE;
import static accord.local.Cleanup.VESTIGIAL;
import static accord.local.Commands.purge;
+import static accord.local.RedundantStatus.Property.LOCALLY_DEFUNCT;
+import static accord.local.RedundantStatus.Property.SHARD_APPLIED_AND_LOCALLY_SYNCED;
import static accord.local.StoreParticipants.Filter.UPDATE;
import static accord.primitives.Known.KnownDeps.DepsKnown;
import static accord.primitives.Known.KnownDeps.DepsUnknown;
@@ -88,7 +91,6 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
final WithQuorum withQuorum;
@Nullable final PartialTxn partialTxn;
@Nullable final PartialDeps stableDeps;
- // TODO (expected): toEpoch may only apply to certain local command stores that have "witnessed the future" - confirm it is fine to use globally or else narrow its scope
final long lowEpoch, highEpoch;
@Nullable final Timestamp committedExecuteAt;
@Nullable final Writes writes;
@@ -176,10 +178,12 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
public Void apply(SafeCommandStore safeStore)
{
long executeAtEpoch = committedExecuteAt == null ? txnId.epoch() : committedExecuteAt.epoch();
- // TODO (required): rework low and high epoch handling; we should replicate coordination quorum intersections here,
- // and then we can safely compute our participants based on this. right now we're ignoring low/high epoch except for
- // deciding which commandStores to notify
StoreParticipants participants = StoreParticipants.update(safeStore, route, lowEpoch, txnId, executeAtEpoch, highEpoch, committedExecuteAt != null);
+ // TODO (expected): can we come up with a better more universal pattern for avoiding updating a command we don't intersect with?
+ // ideally integrated with safeStore.get()
+ if (participants.owns().isEmpty() && safeStore.ifInitialised(txnId) == null)
+ return null;
+
SafeCommand safeCommand = safeStore.get(txnId, participants);
Command command = safeCommand.current();
@@ -214,8 +218,6 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
boolean isShardTruncated = withQuorum == HasQuorum && known.hasAnyFullyTruncated(participants.stillTouches());
if (isShardTruncated)
{
- // TODO (required): do not markShardStale for reads; in general optimise handling of case where we cannot recover a known no-op transaction
- // TODO (required): permit staleness to be gated by some configuration state
found = tryUpgradeTruncated(safeStore, safeCommand, participants, command, executeAtIfKnown);
if (found == null)
{
@@ -382,15 +384,18 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
return null;
Participants<?> stale = staleTouches.with((Participants) staleOwnsOrMayExecutes);
- // TODO (required): fetch redundant before information, it should be available
+ // TODO (expected): trigger a refresh of redundantBefore; should be available on a peer
// wait until we know the shard is ahead and we are behind
if (!safeStore.redundantBefore().isShardOnlyRedundant(txnId, stale))
return null;
- // TODO (required): if the above last ditch doesn't work, see if only the stale ranges can't apply and so some shenanigans to apply partially and move on
- safeStore.commandStore().markShardStale(safeStore, executeAtIfKnown == null ? txnId : executeAtIfKnown, stale.toRanges(), true);
- if (!stale.containsAll(stillTouches) || !stale.containsAll(stillOwnsOrMayExecute))
- return required;
+ // TODO (expected): if the above last ditch doesn't work, see if only the stale ranges can't apply and so some shenanigans to apply partially and move on
+ if (ProtocolModifiers.Toggles.markStaleIfCannotExecute(txnId.kind()))
+ {
+ safeStore.commandStore().markShardStale(safeStore, executeAtIfKnown == null ? txnId : executeAtIfKnown, stale.toRanges(), true);
+ if (!stale.containsAll(stillTouches) || !stale.containsAll(stillOwnsOrMayExecute))
+ return required;
+ }
// TODO (expected): we might prefer to adopt Redundant status, and permit ourselves to later accept the result of the execution and/or definition
Commands.setTruncatedApplyOrErasedVestigial(safeStore, safeCommand, participants, executeAtIfKnown);
@@ -399,34 +404,12 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
private boolean tryPurge(SafeCommandStore safeStore, SafeCommand safeCommand, RedundantStatus status)
{
- switch (status)
- {
- default: throw new UnhandledEnum(status);
- case NOT_OWNED:
- case LOCALLY_REDUNDANT:
- case PARTIALLY_LOCALLY_REDUNDANT:
- case SHARD_REDUNDANT:
- case PARTIALLY_SHARD_REDUNDANT:
- case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
- case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- case TRUNCATE_BEFORE:
- case GC_BEFORE:
- // TODO (required): consider HLC clashes
- case PRE_BOOTSTRAP_OR_STALE:
- purge(safeStore, safeCommand, ERASE, true, true);
- return true;
-
- case WAS_OWNED_PARTIALLY_RETIRED:
- case WAS_OWNED_RETIRED:
- purge(safeStore, safeCommand, VESTIGIAL, true, true);
- return true;
-
- case PARTIALLY_PRE_BOOTSTRAP_OR_STALE:
- case LIVE:
- case WAS_OWNED:
- case WAS_OWNED_CLOSED:
- return false;
- }
+ if (!status.all(SHARD_APPLIED_AND_LOCALLY_SYNCED))
+ return false;
+
+ Cleanup cleanup = status.all(LOCALLY_DEFUNCT) ? VESTIGIAL : ERASE;
+ purge(safeStore, safeCommand, cleanup, true, true);
+ return true;
}
/*
@@ -434,7 +417,6 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
*/
private Void updateDurability(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants)
{
- // TODO (expected): Infer durability status from cleanup/truncation
if (!durability.isDurable() || homeKey == null)
return null;
diff --git a/accord-core/src/main/java/accord/messages/ReadData.java b/accord-core/src/main/java/accord/messages/ReadData.java
index 46ab1158..676e72c6 100644
--- a/accord-core/src/main/java/accord/messages/ReadData.java
+++ b/accord-core/src/main/java/accord/messages/ReadData.java
@@ -62,8 +62,9 @@ import static accord.primitives.Txn.Kind.Write;
import static accord.utils.Invariants.illegalState;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
-// TODO (expected): if one shard timesout waiting to reply, but another shard produces a reply, return a partial response (or response with suitably populated unavailable)
-// this means timing out a little earlier so the reply has time to arrive (but this should anyway be the case)
+// TODO (required): (v1.1) if one shard times out waiting to reply, but another shard produces a reply, return a partial response (or response with suitably populated unavailable)
+// this means timing out a little earlier so the reply has time to arrive (but this should anyway be the case).
+// This ensures a multi-key transaction interacting with replicas that have different stale shards on a replica can make progress
public abstract class ReadData implements PreLoadContext, Request, MapReduceConsume<SafeCommandStore, ReadData.CommitOrReadNack>, LocalListeners.ComplexListener, Timeouts.Timeout
{
private static final Logger logger = LoggerFactory.getLogger(ReadData.class);
@@ -351,7 +352,10 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
Timestamp executeAt = command.executesAtLeast();
if (executeAt == null) executeAt = command.executeAtOrTxnId();
// TODO (required): for awaitsOnlyDeps commands, if we cannot infer an actual executeAtLeast we should confirm no situation where txnId is not an adequately conservative value for unavailable/unsafeToRead
- return safeStore.unsafeToReadAt(executeAt);
+ Ranges ranges = safeStore.unsafeToReadAt(executeAt);
+ if (ranges.size() > command.route().size())
+ ranges = ranges.intersecting(command.route(), Minimal);
+ return ranges;
}
protected void read(SafeCommandStore safeStore, Command command)
@@ -610,8 +614,6 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
/**
* if the replica we contacted was unable to fully answer the query, due to bootstrapping some portion,
* this is set to the ranges that were unavailable
- *
- * TODO (required): narrow to only the *intersecting* ranges that are unavailable, or do so on the recipient
*/
public final @Nullable Ranges unavailable;
public final @Nullable Data data;
diff --git a/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java b/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
index 1894a361..6bce3cc7 100644
--- a/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
+++ b/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
@@ -177,8 +177,9 @@ public class ReadEphemeralTxnData extends ReadData
while (iter.hasNext())
{
node.commandStores().forId(iter.nextValue())
- .execute(PreLoadContext.empty(), safeStore -> eraseEphemeralRead(safeStore, txnId))
- .begin(node.agent());
+ .execute(PreLoadContext.empty(), safeStore -> {
+ eraseEphemeralRead(safeStore, txnId);
+ }, node.agent());
}
}
super.timeout();
diff --git a/accord-core/src/main/java/accord/messages/SetGloballyDurable.java b/accord-core/src/main/java/accord/messages/SetGloballyDurable.java
index 4a892c1c..f16e430e 100644
--- a/accord-core/src/main/java/accord/messages/SetGloballyDurable.java
+++ b/accord-core/src/main/java/accord/messages/SetGloballyDurable.java
@@ -27,10 +27,6 @@ import accord.primitives.TxnId;
import static accord.messages.SimpleReply.Ok;
-// TODO (required): if we have epochs 1 and 2, and a syncpoint that executes on epoch 2, where the transactions have not
-// finished executing on epoch 1, it may not be safe to mark durable on replicas on epoch 1. This is a very unlikely
-// race condition, but must consider our behaviour - it may be simpler to wait for a sync point to execute on all epochs
-// that haven't been closed off.
public class SetGloballyDurable implements Request, PreLoadContext
{
public final DurableBefore durableBefore;
diff --git a/accord-core/src/main/java/accord/primitives/AbstractRanges.java b/accord-core/src/main/java/accord/primitives/AbstractRanges.java
index ffee6d0d..45bc4609 100644
--- a/accord-core/src/main/java/accord/primitives/AbstractRanges.java
+++ b/accord-core/src/main/java/accord/primitives/AbstractRanges.java
@@ -537,7 +537,7 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
if (bi == bs.length)
return constructor.construct(param1, param2, (as == left.ranges ? left : right).ranges);
- // TODO (expected, efficiency): ArrayBuffers caching
+ // TODO (expected): use ArrayBuffers caching
Range[] result = new Range[as.length + (bs.length - bi)];
int resultCount;
switch (mode)
diff --git a/accord-core/src/main/java/accord/primitives/Deps.java b/accord-core/src/main/java/accord/primitives/Deps.java
index b59afe09..a1ff4158 100644
--- a/accord-core/src/main/java/accord/primitives/Deps.java
+++ b/accord-core/src/main/java/accord/primitives/Deps.java
@@ -85,7 +85,7 @@ public class Deps
return new Builder(buildRangeByTxnId);
}
- // TODO (expected, efficiency): cache this object per thread
+ // TODO (desired): cache this object per thread
public static abstract class AbstractBuilder<T extends Deps> implements AutoCloseable
{
final KeyDeps.Builder keyBuilder;
diff --git a/accord-core/src/main/java/accord/primitives/EpochSupplier.java b/accord-core/src/main/java/accord/primitives/EpochSupplier.java
index e82a89cc..d6ad196e 100644
--- a/accord-core/src/main/java/accord/primitives/EpochSupplier.java
+++ b/accord-core/src/main/java/accord/primitives/EpochSupplier.java
@@ -18,7 +18,6 @@
package accord.primitives;
-// TODO (expected): this is probably redundant
public interface EpochSupplier
{
long epoch();
diff --git a/accord-core/src/main/java/accord/primitives/KeyDeps.java b/accord-core/src/main/java/accord/primitives/KeyDeps.java
index 05609096..c3295503 100644
--- a/accord-core/src/main/java/accord/primitives/KeyDeps.java
+++ b/accord-core/src/main/java/accord/primitives/KeyDeps.java
@@ -49,7 +49,6 @@ import static accord.utils.Invariants.illegalArgument;
import static accord.utils.RelationMultiMap.*;
import static accord.utils.SortedArrays.Search.FAST;
-// TODO (desired, consider): switch to RoutingKey? Would mean adopting execution dependencies less precisely, but saving ser/deser of large keys
// TODO (expected): consider which projection we should default to on de/serialise
/**
* A collection of dependencies for a transaction, organised by the key the dependency is adopted via.
@@ -176,7 +175,6 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
* }
* }
*/
- // TODO (expected): support deserializing to one or the other
int[] keysToTxnIds; // Key -> [TxnId]
int[] txnIdsToKeys; // TxnId -> [Key]
diff --git a/accord-core/src/main/java/accord/primitives/PartialDeps.java b/accord-core/src/main/java/accord/primitives/PartialDeps.java
index 7bcc6d4b..33288fab 100644
--- a/accord-core/src/main/java/accord/primitives/PartialDeps.java
+++ b/accord-core/src/main/java/accord/primitives/PartialDeps.java
@@ -54,11 +54,6 @@ public class PartialDeps extends Deps
}
}
- // TODO (expected): we no longer need this if everyone has a FullRoute
- // could also retain a simple bitset over the original FullRoute
- // TODO (required) remove this and related concepts, as can cause problems with topology changes for a single store
- // where the store has some ranges that we participate in, and some we do not; we will not correctly construct covering in some cases
-
public final Participants<?> covering; // set only if this is a range transaction, containing the minimal ranges of the original transaction that we cover
public PartialDeps(Participants<?> covering, KeyDeps keyDeps, RangeDeps rangeDeps, KeyDeps directKeyDeps)
{
diff --git a/accord-core/src/main/java/accord/primitives/PartialTxn.java b/accord-core/src/main/java/accord/primitives/PartialTxn.java
index 9bb207b5..171c2365 100644
--- a/accord-core/src/main/java/accord/primitives/PartialTxn.java
+++ b/accord-core/src/main/java/accord/primitives/PartialTxn.java
@@ -28,8 +28,6 @@ import static accord.utils.Invariants.illegalState;
public interface PartialTxn extends Txn
{
- // TODO (expected): we no longer need this if everyone has a FullRoute
- // TODO (low priority, efficiency): efficient merge when more than one input
PartialTxn with(PartialTxn add);
Txn reconstitute(FullRoute<?> route);
PartialTxn reconstitutePartial(Participants<?> covering);
diff --git a/accord-core/src/main/java/accord/primitives/RangeDeps.java b/accord-core/src/main/java/accord/primitives/RangeDeps.java
index 9f3ad1bb..e6b6be66 100644
--- a/accord-core/src/main/java/accord/primitives/RangeDeps.java
+++ b/accord-core/src/main/java/accord/primitives/RangeDeps.java
@@ -82,10 +82,10 @@ import static accord.utils.SortedArrays.Search.FAST;
* <p>The relationship between Range and TxnId is maintained via {@code int[]} utilising {@link RelationMultiMap}
* functionality.
*
- * TODO (expected): de-overlap ranges per txnId if possible cheaply, or else reduce use of partial ranges where possible
* TODO (expected): keep only the latest exclusive sync point for a given range
- * TODO (expected): permit building out-of-order
- * TODO (expected): currently permitting duplicates
+ * TODO (expected): permit building out-of-order to facilitate incremental PreLoadContext
+ * TODO (desired): currently permitting duplicates
+ * TODO (testing): confirm we are de-overlapping ranges per txnId
* TODO (testing): randomised testing of all iteration methods
*/
public class RangeDeps implements Iterable<Map.Entry<Range, TxnId>>
diff --git a/accord-core/src/main/java/accord/primitives/SaveStatus.java b/accord-core/src/main/java/accord/primitives/SaveStatus.java
index 76b446d2..e77a7f38 100644
--- a/accord-core/src/main/java/accord/primitives/SaveStatus.java
+++ b/accord-core/src/main/java/accord/primitives/SaveStatus.java
@@ -105,12 +105,9 @@ public enum SaveStatus
// similar to Truncated, but doesn't imply we have any global knowledge about application
Applied (Status.Applied, LocalExecution.Applied),
// TruncatedApplyWithDeps is a state never adopted within a single replica; it is however a useful state we may enter by combining state from multiple replicas
- // TODO (expected): TruncatedApplyWithDeps should be redundant now we have migrated away from SaveStatus in CheckStatusOk to Known; remove in isolated commit once stable
- // however: we may want to retain it for the case where we want to truncate its payload but need to be able to answer recovery decisions
- TruncatedApplyWithDeps (Status.Truncated, FullRoute, DefinitionErased, ApplyAtKnown, DepsKnown, Apply, CleaningUp),
TruncatedApplyWithOutcome (Status.Truncated, FullRoute, DefinitionErased, ApplyAtKnown, DepsErased, Apply, CleaningUp),
-// TruncatedApplyWithRoute (Status.Truncated, FullRoute, DefinitionErased, ApplyAtKnown, DepsErased, WasApply,CleaningUp),
TruncatedApply (Status.Truncated, MaybeRoute, DefinitionErased, ApplyAtKnown, DepsErased, WasApply,CleaningUp),
+ TruncatedUnapplied (Status.Truncated, MaybeRoute, DefinitionErased, ExecuteAtKnown, DepsErased, WasApply,CleaningUp),
// Vestigial means the command cannot be completed and is either pre-bootstrap, did not commit, or did not participate in this shard's epoch
Vestigial (Status.Truncated, MaybeRoute, DefinitionUnknown, ExecuteAtUnknown, DepsUnknown, Unknown, CleaningUp),
// NOTE: Erased should ONLY be adopted on a replica that knows EVERY shard has successfully applied the transaction at all healthy replicas (or else that it is durably invalidated)
@@ -260,8 +257,7 @@ public enum SaveStatus
}
}
- // TODO (expected): merge Known only, and ensure 1:1 mapping so can reconstruct composite
- // TODO (expected, testing): exhaustive testing, particularly around PreCommitted
+ // TODO (testing): exhaustive testing, particularly around PreCommitted
public static SaveStatus get(Status status, Known known)
{
if (known.isInvalidated())
@@ -379,6 +375,10 @@ public enum SaveStatus
if (!known.outcome().isOrWasApply() || !known.is(ExecuteAtKnown))
return Erased;
+ case TruncatedUnapplied:
+ if (!known.is(ApplyAtKnown))
+ return TruncatedUnapplied;
+
case TruncatedApply:
if (known.outcome() != Apply)
return TruncatedApply;
@@ -387,10 +387,6 @@ public enum SaveStatus
if (known.deps() != DepsKnown)
return TruncatedApplyWithOutcome;
- case TruncatedApplyWithDeps:
- if (!known.isDefinitionKnown())
- return TruncatedApplyWithDeps;
-
return Applied;
}
}
diff --git a/accord-core/src/main/java/accord/primitives/Timestamp.java b/accord-core/src/main/java/accord/primitives/Timestamp.java
index 8f497bc8..9789b042 100644
--- a/accord-core/src/main/java/accord/primitives/Timestamp.java
+++ b/accord-core/src/main/java/accord/primitives/Timestamp.java
@@ -63,7 +63,7 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
* This means it did not witness any conflicts in a future epoch, and so all transactions that
* might take a lower HLC must have been witnessed.
*/
- HLC_BOUND(0x0400)
+ HLC_BOUND(0x0400),
;
public final int bit;
@@ -181,7 +181,7 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
}
// if caller masks no need to mask before returning
- final int flagsUnmasked()
+ public final int flagsUnmasked()
{
return (int)lsb;
}
diff --git a/accord-core/src/main/java/accord/primitives/Txn.java b/accord-core/src/main/java/accord/primitives/Txn.java
index 5cbd377b..168cc2a8 100644
--- a/accord-core/src/main/java/accord/primitives/Txn.java
+++ b/accord-core/src/main/java/accord/primitives/Txn.java
@@ -97,8 +97,6 @@ public interface Txn
*
* Invisible to other transactions.
*/
- // TODO (expected): introduce a special kind of visible ExclusiveSyncPoint that creates a precise moment,
- // and is therefore visible to all transactions.
ExclusiveSyncPoint('X', true, true, true, true),
;
diff --git a/accord-core/src/main/java/accord/primitives/TxnId.java b/accord-core/src/main/java/accord/primitives/TxnId.java
index d46d9d42..2a28d642 100644
--- a/accord-core/src/main/java/accord/primitives/TxnId.java
+++ b/accord-core/src/main/java/accord/primitives/TxnId.java
@@ -33,17 +33,18 @@ import accord.utils.TinyEnumSet;
import static accord.primitives.Txn.Kind.Read;
import static accord.primitives.Txn.Kind.Write;
+import static accord.primitives.TxnId.Cardinality.Any;
+import static accord.primitives.TxnId.MediumPath.NoMediumPath;
import static accord.utils.Invariants.illegalArgument;
public class TxnId extends Timestamp implements PreLoadContext
{
public enum FastPath
{
- UNOPTIMISED,
- PRIVILEGED_COORDINATOR_WITHOUT_DEPS,
- PRIVILEGED_COORDINATOR_WITH_DEPS;
+ Unoptimised,
+ PrivilegedCoordinatorWithoutDeps,
+ PrivilegedCoordinatorWithDeps;
- private static final FastPaths IS_PRIVILEGED = new FastPaths(PRIVILEGED_COORDINATOR_WITH_DEPS, PRIVILEGED_COORDINATOR_WITHOUT_DEPS);
private static final FastPath[] VALUES = values();
public final int bits;
@@ -53,26 +54,46 @@ public class TxnId extends Timestamp implements PreLoadContext
this.bits = ordinal() << 4;
}
+ final boolean is(int flagsUnmasked)
+ {
+ return is(flagsUnmasked, this);
+ }
+
+ private static boolean is(int flagsUnmasked, FastPath test)
+ {
+ return ((flagsUnmasked >>> 4) & 3) == test.ordinal();
+ }
+
+ private static FastPath forFlags(int flagsUnmasked)
+ {
+ return forOrdinal(ordinalFromFlags(flagsUnmasked));
+ }
+
+ private static int ordinalFromFlags(int flagsUnmasked)
+ {
+ return (flagsUnmasked >>> 4) & 3;
+ }
+
public static FastPath forOrdinal(int ordinal)
{
return VALUES[ordinal];
}
- static boolean hasPrivilegedCoordinator(int ordinal)
+ static boolean hasPrivilegedCoordinator(int flagsUnmasked)
{
- return IS_PRIVILEGED.contains(ordinal);
+ return 0 != ordinalFromFlags(flagsUnmasked);
}
public FastPath toPermitted(FastPaths permitted)
{
if (permitted.contains(this))
return this;
- if (this == UNOPTIMISED)
+ if (this == Unoptimised)
return this;
- FastPath alt = this == PRIVILEGED_COORDINATOR_WITH_DEPS ? PRIVILEGED_COORDINATOR_WITHOUT_DEPS : PRIVILEGED_COORDINATOR_WITH_DEPS;
+ FastPath alt = this == PrivilegedCoordinatorWithDeps ? PrivilegedCoordinatorWithoutDeps : PrivilegedCoordinatorWithDeps;
if (permitted.contains(alt))
return alt;
- return UNOPTIMISED;
+ return Unoptimised;
}
}
@@ -85,26 +106,71 @@ public class TxnId extends Timestamp implements PreLoadContext
public enum MediumPath
{
- NONE(0),
- TRACK_STABLE(1);
+ NoMediumPath, TrackStable;
- private static final MediumPath[] VALUES = values();
+ private static final int SHIFT = 6;
+ public final int bit() { return ordinal() << SHIFT; }
- public final int bits;
+ final boolean is(int flagsUnmasked)
+ {
+ return is(flagsUnmasked, this);
+ }
- MediumPath(int bits)
+ private static boolean is(int flagsUnmasked, MediumPath test)
{
- this.bits = bits << 6;
+ return ((flagsUnmasked >>> SHIFT) & 1) == test.ordinal();
}
- public static boolean any(int bits)
+ public static MediumPath forFlags(int flagsUnmasked)
{
- return bits != 0;
+ return (flagsUnmasked & (1 << SHIFT)) == 0 ? NoMediumPath : TrackStable;
}
public static MediumPath forOrdinal(int ordinal)
{
- return VALUES[ordinal];
+ return ordinal == 0 ? NoMediumPath : TrackStable;
+ }
+ }
+
+ public enum Cardinality
+ {
+ SingleKey,
+ Any;
+
+ private static final int SHIFT = 7;
+ public final int bit()
+ {
+ return ordinal() << SHIFT;
+ }
+
+ final boolean is(int flagsUnmasked)
+ {
+ return is(flagsUnmasked, this);
+ }
+
+ public static Cardinality cardinality(Routables<?> routables)
+ {
+ return routables.size() == 1 && routables.domain() == Domain.Key ? SingleKey : Any;
+ }
+
+ public static Cardinality cardinality(Domain domain, Routables<?> routables)
+ {
+ return domain == Domain.Key && routables.size() == 1 ? SingleKey : Any;
+ }
+
+ private static boolean is(int flagsUnmasked, Cardinality test)
+ {
+ return ((flagsUnmasked >>> SHIFT) & 1) == test.ordinal();
+ }
+
+ private static Cardinality forFlags(int flagsUnmasked)
+ {
+ return (flagsUnmasked & (1 << SHIFT)) == 0 ? SingleKey : Any;
+ }
+
+ public static Cardinality forOrdinal(int ordinal)
+ {
+ return ordinal == 0 ? SingleKey : Any;
}
}
@@ -136,12 +202,17 @@ public class TxnId extends Timestamp implements PreLoadContext
public TxnId(Timestamp timestamp, Kind rw, Domain domain)
{
- this(timestamp, 0, rw, domain);
+ this(timestamp, rw, domain, Any);
+ }
+
+ public TxnId(Timestamp timestamp, Kind rw, Domain domain, Cardinality cardinality)
+ {
+ this(timestamp, 0, rw, domain, cardinality);
}
- public TxnId(Timestamp timestamp, int flags, Kind rw, Domain domain)
+ public TxnId(Timestamp timestamp, int flags, Kind rw, Domain domain, Cardinality cardinality)
{
- super(timestamp, flags(flags, rw, domain));
+ super(timestamp, flags(flags, rw, domain, cardinality));
}
public TxnId(TxnId copy)
@@ -151,12 +222,22 @@ public class TxnId extends Timestamp implements PreLoadContext
public TxnId(long epoch, long hlc, Kind rw, Domain domain, Id node)
{
- this(epoch, hlc, 0, rw, domain, node);
+ this(epoch, hlc, rw, domain, Any, node);
+ }
+
+ public TxnId(long epoch, long hlc, Kind rw, Domain domain, Cardinality cardinality, Id node)
+ {
+ this(epoch, hlc, 0, rw, domain, cardinality, node);
}
public TxnId(long epoch, long hlc, int flags, Kind rw, Domain domain, Id node)
{
- this(epoch, hlc, flags(flags, rw, domain), node);
+ this(epoch, hlc, flags, rw, domain, Any, node);
+ }
+
+ public TxnId(long epoch, long hlc, int flags, Kind rw, Domain domain, Cardinality cardinality, Id node)
+ {
+ this(epoch, hlc, flags(flags, rw, domain, cardinality), node);
}
private TxnId(long epoch, long hlc, int flags, Id node)
@@ -169,107 +250,112 @@ public class TxnId extends Timestamp implements PreLoadContext
super(msb, lsb, node);
}
- public boolean isWrite()
+ public final boolean isWrite()
{
return is(Write);
}
- public boolean isRead()
+ public final boolean isRead()
{
return is(Read);
}
- public Kind kind()
+ public final Kind kind()
{
return kind(flagsUnmasked());
}
- public boolean is(Kinds kinds)
+ public final boolean is(Kinds kinds)
{
return kinds.testOrdinal(kindOrdinal(flagsUnmasked()));
}
- public boolean is(Kind kind)
+ public final boolean is(Kind kind)
{
return kindOrdinal(flagsUnmasked()) == kind.ordinal();
}
- public boolean is(FastPath fastPath)
+ public final boolean is(FastPath fastPath)
+ {
+ return fastPath.is(flagsUnmasked());
+ }
+
+ public final boolean is(MediumPath mediumPath)
{
- return 0 != (flagsUnmasked() & fastPath.bits);
+ return mediumPath.is(flagsUnmasked());
}
- public boolean is(MediumPath mediumPath)
+ public final boolean is(Cardinality cardinality)
{
- return 0 != (flagsUnmasked() & mediumPath.bits);
+ return cardinality.is(flagsUnmasked());
}
- public TxnId withoutNonIdentityFlags()
+ public final TxnId withoutNonIdentityFlags()
{
return (flags() & ~IDENTITY_FLAGS) == 0 ? this : new TxnId(msb, lsb & IDENTITY_LSB, node);
}
- public boolean hasPrivilegedCoordinator()
+ public final boolean hasPrivilegedCoordinator()
{
- return FastPath.hasPrivilegedCoordinator(fastPathOrdinal(flagsUnmasked()));
+ return FastPath.hasPrivilegedCoordinator(flagsUnmasked());
}
- public boolean hasMediumPath()
+ public final boolean hasMediumPath()
{
- return MediumPath.any(mediumPathOrdinal(flagsUnmasked()));
+ return !MediumPath.is(flagsUnmasked(), NoMediumPath);
}
- public boolean isVisible()
+ public final boolean isVisible()
{
return Kind.isVisible(kindOrdinal(flagsUnmasked()));
}
- public boolean isSyncPoint()
+ public final boolean isSyncPoint()
{
return Kind.isSyncPoint(kindOrdinal(flagsUnmasked()));
}
- public boolean isSystemTxn()
+ public final boolean isSystemTxn()
{
return Kind.isSystemTxn(kindOrdinal(flagsUnmasked()));
}
- public boolean awaitsOnlyDeps()
+ public final boolean awaitsOnlyDeps()
{
return Kind.awaitsOnlyDeps(kindOrdinal(flagsUnmasked()));
}
- public boolean awaitsPreviouslyOwned()
+ public final boolean awaitsPreviouslyOwned()
{
return Kind.awaitsPreviouslyOwned(kindOrdinal(flagsUnmasked()));
}
- public boolean is(Domain domain)
+ public final boolean is(Domain domain)
{
return domainOrdinal(flagsUnmasked()) == domain.ordinal();
}
- public Kinds witnesses()
+ public final Kinds witnesses()
{
return kind().witnesses();
}
- public boolean witnesses(TxnId txnId)
+ public final boolean witnesses(TxnId txnId)
{
return Kind.witnesses(kindOrdinal(flagsUnmasked()), kindOrdinal(txnId.flagsUnmasked()));
}
- public boolean witnessedBy(TxnId txnId)
+ public final boolean witnessedBy(TxnId txnId)
{
return txnId.witnesses(this);
}
- public Kinds witnessedBy()
+ public final Kinds witnessedBy()
{
return kind().witnessedBy();
}
- public Domain domain()
+ public final Domain domain()
{
return domain(flagsUnmasked());
}
@@ -286,7 +372,7 @@ public class TxnId extends Timestamp implements PreLoadContext
public TxnId as(Kind kind, Domain domain)
{
- return new TxnId(epoch(), hlc(), flagsWithoutDomainAndKind(), kind, domain, node);
+ return new TxnId(epoch(), hlc(), flagsWithoutDomainAndKind(), kind, domain, cardinality(), node);
}
private int flagsWithoutDomainAndKind()
@@ -334,11 +420,12 @@ public class TxnId extends Timestamp implements PreLoadContext
return "[" + epoch() + ',' + hlc() + ',' + flags() + '(' + domain().shortName() + kind().shortName() + ')' + ',' + node + ']';
}
- private static int flags(int flags, Kind rw, Domain domain)
+ private static int flags(int flags, Kind rw, Domain domain, Cardinality cardinality)
{
- int domainAndKindFlags = flags(rw) | flags(domain);
- Invariants.require((flags & domainAndKindFlags) == 0);
- return domainAndKindFlags | flags;
+ Invariants.require(cardinality == Any || domain == Domain.Key);
+ int paramFlags = flags(rw) | flags(domain) | cardinality.bit();
+ Invariants.require((flags & paramFlags) == 0);
+ return paramFlags | flags;
}
private static int flags(Kind rw)
@@ -368,17 +455,17 @@ public class TxnId extends Timestamp implements PreLoadContext
public FastPath fastPath()
{
- return FastPath.forOrdinal(fastPathOrdinal(flagsUnmasked()));
+ return FastPath.forFlags(flagsUnmasked());
}
- public static int fastPathOrdinal(int flags)
+ public MediumPath mediumPath()
{
- return (flags >>> 4) & 3;
+ return MediumPath.forFlags(flagsUnmasked());
}
- public static int mediumPathOrdinal(int flags)
+ public Cardinality cardinality()
{
- return (flags >>> 6) & 1;
+ return Cardinality.forFlags(flagsUnmasked());
}
public boolean hasOnlyIdentityFlags()
@@ -386,7 +473,7 @@ public class TxnId extends Timestamp implements PreLoadContext
return (flags() & ~IDENTITY_FLAGS) == 0;
}
- private static int domainOrdinal(int flags)
+ public static int domainOrdinal(int flags)
{
return flags & 1;
}
diff --git a/accord-core/src/main/java/accord/topology/Shard.java b/accord-core/src/main/java/accord/topology/Shard.java
index ded9ccad..f31a2d6a 100644
--- a/accord-core/src/main/java/accord/topology/Shard.java
+++ b/accord-core/src/main/java/accord/topology/Shard.java
@@ -34,7 +34,6 @@ import accord.utils.UnhandledEnum;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Shorts;
-// TODO (expected, efficiency): concept of region/locality
// TODO (expected): introduce recovery quorum size configuration
public class Shard
{
@@ -134,9 +133,9 @@ public class Shard
switch (fastPath)
{
default: throw new UnhandledEnum(fastPath);
- case UNOPTIMISED: return simpleFastQuorumSize;
- case PRIVILEGED_COORDINATOR_WITHOUT_DEPS: return privilegedWithoutDepsFastQuorumSize;
- case PRIVILEGED_COORDINATOR_WITH_DEPS: return privilegedWithDepsFastQuorumSize;
+ case Unoptimised: return simpleFastQuorumSize;
+ case PrivilegedCoordinatorWithoutDeps: return privilegedWithoutDepsFastQuorumSize;
+ case PrivilegedCoordinatorWithDeps: return privilegedWithDepsFastQuorumSize;
}
}
@@ -266,7 +265,7 @@ public class Shard
public FastPath bestFastPath()
{
return privilegedWithDepsFastQuorumSize == privilegedWithoutDepsFastQuorumSize
- ? FastPath.PRIVILEGED_COORDINATOR_WITHOUT_DEPS
- : FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
+ ? FastPath.PrivilegedCoordinatorWithoutDeps
+ : FastPath.PrivilegedCoordinatorWithDeps;
}
}
diff --git a/accord-core/src/main/java/accord/topology/Topology.java b/accord-core/src/main/java/accord/topology/Topology.java
index d6c40412..6ebe6b60 100644
--- a/accord-core/src/main/java/accord/topology/Topology.java
+++ b/accord-core/src/main/java/accord/topology/Topology.java
@@ -302,9 +302,12 @@ public class Topology
for (int shardIndex : newSubset)
{
Shard shard = shards[shardIndex];
+ int i = 0;
for (Id id : shard.nodes)
{
- nodes.set(nodeIds.find(id));
+ 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));
}
diff --git a/accord-core/src/main/java/accord/topology/TopologyManager.java b/accord-core/src/main/java/accord/topology/TopologyManager.java
index a3abfa45..76347357 100644
--- a/accord-core/src/main/java/accord/topology/TopologyManager.java
+++ b/accord-core/src/main/java/accord/topology/TopologyManager.java
@@ -62,9 +62,9 @@ import static accord.api.ProtocolModifiers.QuorumEpochIntersections.Include.Owne
import static accord.api.ProtocolModifiers.QuorumEpochIntersections.Include.Unsynced;
import static accord.coordinate.tracking.RequestStatus.Success;
import static accord.primitives.AbstractRanges.UnionMode.MERGE_ADJACENT;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITHOUT_DEPS;
-import static accord.primitives.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
-import static accord.primitives.TxnId.FastPath.UNOPTIMISED;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithoutDeps;
+import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
+import static accord.primitives.TxnId.FastPath.Unoptimised;
import static accord.utils.Invariants.illegalState;
import static accord.utils.Invariants.nonNull;
@@ -562,7 +562,7 @@ public class TopologyManager
epochs.syncComplete(node, epoch);
}
- // TODO (now, correctness): it seems to be wrong to count removed nodes towards sync quorums.
+ // TODO (nrequired): this is incorrect, we should not mark removed node as complete in the quorum as they may not be unresponsive
public synchronized void onRemoveNode(long removedIn, Id removed)
{
for (long epoch = removedIn, min = minEpoch(); epoch >= min; epoch--)
@@ -684,10 +684,9 @@ public class TopologyManager
}
else
{
- // TODO (expected): when we revisit epoch handling, see if we can avoid recalculating when minEpoch advances
if (prevIncluded == Unsynced && prev != null && prev.currentEpoch() == maxEpoch && prev.oldestEpoch() == minEpoch)
return prev;
- else
+ else // TODO (desired): can we avoid recalculating when only minEpoch advances?
return withUnsyncedEpochs(select, minEpoch, maxEpoch);
}
@@ -1048,7 +1047,7 @@ public class TopologyManager
public FastPath one(EpochState epoch, Routables<?> routables, boolean permitMissing)
{
if (!epoch.local.ranges.containsAll(routables) || !epoch.local.foldl(routables, this, true))
- return UNOPTIMISED;
+ return Unoptimised;
return epoch.local.foldl(routables, (s, v, i) -> merge(v, s.bestFastPath()), null);
}
@@ -1068,9 +1067,9 @@ public class TopologyManager
private static FastPath merge(FastPath a, FastPath b)
{
if (a == null) return b;
- if (a == UNOPTIMISED || b == UNOPTIMISED) return UNOPTIMISED;
- if (a == PRIVILEGED_COORDINATOR_WITH_DEPS || b == PRIVILEGED_COORDINATOR_WITH_DEPS) return PRIVILEGED_COORDINATOR_WITH_DEPS;
- return PRIVILEGED_COORDINATOR_WITHOUT_DEPS;
+ if (a == Unoptimised || b == Unoptimised) return Unoptimised;
+ if (a == PrivilegedCoordinatorWithDeps || b == PrivilegedCoordinatorWithDeps) return PrivilegedCoordinatorWithDeps;
+ return PrivilegedCoordinatorWithoutDeps;
}
@Override
diff --git a/accord-core/src/main/java/accord/utils/BitUtils.java b/accord-core/src/main/java/accord/utils/BitUtils.java
index a161279e..0b38456b 100644
--- a/accord-core/src/main/java/accord/utils/BitUtils.java
+++ b/accord-core/src/main/java/accord/utils/BitUtils.java
@@ -101,7 +101,6 @@ public class BitUtils
writeMostSignificantBytes(register << ((8 - bytes)*8), bytes, out);
}
- // TODO (expected): this is probably endian-sensitive
public static void writeMostSignificantBytes(long register, int bytes, ByteBuffer out)
{
int position = out.position();
diff --git a/accord-core/src/main/java/accord/utils/Invariants.java b/accord-core/src/main/java/accord/utils/Invariants.java
index 8f546f7f..7f70fe35 100644
--- a/accord-core/src/main/java/accord/utils/Invariants.java
+++ b/accord-core/src/main/java/accord/utils/Invariants.java
@@ -138,6 +138,79 @@ public class Invariants
return condition;
}
+ public static void expect(boolean condition, String msg)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(msg));
+ }
+
+ public static void expect(boolean condition, String fmt, int p1)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1)));
+ }
+
+ public static void expect(boolean condition, String fmt, int p1, int p2)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1, p2)));
+ }
+
+ public static void expect(boolean condition, String fmt, long p1)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1)));
+ }
+
+ public static void expect(boolean condition, String fmt, long p1, long p2)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1, p2)));
+ }
+
+ public static void expect(boolean condition, String fmt, @Nullable Object p1)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1)));
+ }
+
+ public static <P> void expect(boolean condition, String fmt, @Nullable P p1, Function<? super P, ?> transformP)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, transformP.apply(p1))));
+ }
+
+ public static void expect(boolean condition, String fmt, @Nullable Object p1, @Nullable Object p2)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1, p2)));
+ }
+
+ public static <P> void expect(boolean condition, String fmt, @Nullable Object p1, @Nullable P p2, Function<? super P, ?> transformP2)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1, transformP2.apply(p2))));
+ }
+
+
+ public static void expect(boolean condition, String fmt, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1, p2, p3)));
+ }
+
+ public static <P> void expect(boolean condition, String fmt, @Nullable Object p1, @Nullable Object p2, @Nullable P p3, Function<? super P, Object> transformP3)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, p1, p2, transformP3.apply(p3))));
+ }
+
+ public static void expect(boolean condition, String fmt, Object... args)
+ {
+ if (!condition)
+ onUnexpected.accept(illegalState(format(fmt, args)));
+ }
+
public static void require(boolean condition)
{
if (!condition)
diff --git a/accord-core/src/main/java/accord/utils/RandomSource.java b/accord-core/src/main/java/accord/utils/RandomSource.java
index f5d3e863..80b3cd2f 100644
--- a/accord-core/src/main/java/accord/utils/RandomSource.java
+++ b/accord-core/src/main/java/accord/utils/RandomSource.java
@@ -35,7 +35,7 @@ import com.google.common.collect.Iterables;
import accord.utils.random.Picker;
-// TODO (expected): merge with C* RandomSource
+// TODO (desired): merge with C* RandomSource
public interface RandomSource
{
static RandomSource wrap(Random random)
diff --git a/accord-core/src/main/java/accord/utils/ReducingIntervalMap.java b/accord-core/src/main/java/accord/utils/ReducingIntervalMap.java
index 13ee879e..37aaacf5 100644
--- a/accord-core/src/main/java/accord/utils/ReducingIntervalMap.java
+++ b/accord-core/src/main/java/accord/utils/ReducingIntervalMap.java
@@ -308,7 +308,7 @@ public class ReducingIntervalMap<K extends Comparable<? super K>, V>
}
// loop over any range covered by both
- // TODO (expected): optimise merging of very different sized maps (i.e. for inserts)
+ // TODO (desired): optimise merging of very different sized maps (i.e. for inserts)
while (left.hasCurrent() && right.hasCurrent())
{
int cmp = left.end().compareTo(right.end());
diff --git a/accord-core/src/main/java/accord/utils/ReducingRangeMap.java b/accord-core/src/main/java/accord/utils/ReducingRangeMap.java
index 20eedbea..38814c8f 100644
--- a/accord-core/src/main/java/accord/utils/ReducingRangeMap.java
+++ b/accord-core/src/main/java/accord/utils/ReducingRangeMap.java
@@ -52,9 +52,9 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
super(inclusiveEnds, starts, values);
}
- public V foldl(Routables<?> routables, BiFunction<V, V, V> fold, V accumulator)
+ public <V2> V2 foldl(Routables<?> routables, BiFunction<V, V2, V2> fold, V2 accumulator)
{
- return foldl(routables, (a, b, f, ignore) -> f.apply(a, b), accumulator, fold, null, ignore -> false);
+ return foldl(routables, fold, accumulator, ignore -> false);
}
public <V2> V2 foldl(Routables<?> routables, BiFunction<V, V2, V2> fold, V2 accumulator, Predicate<V2> terminate)
@@ -80,6 +80,11 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
return foldl(routables, (a, b, f, self, i, j, k) -> f.apply(a, b, self.starts[k], self.starts[k+1], i, j), accumulator, fold, this, terminate);
}
+ public <V2, P1> V2 foldl(Routables<?> routables, TriFunction<V, V2, P1, V2> fold, V2 accumulator, P1 p1)
+ {
+ return foldl(routables, fold, accumulator, p1, ignore -> false);
+ }
+
public <V2, P1> V2 foldl(Routables<?> routables, TriFunction<V, V2, P1, V2> fold, V2 accumulator, P1 p1, Predicate<V2> terminate)
{
return foldl(routables, (a, b, f, p) -> f.apply(a, b, p), accumulator, fold, p1, terminate);
@@ -90,6 +95,11 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
return foldl(routables, (v, v2, f, p, i, j, k) -> f.apply(v, v2, p, i), accumulator, fold, p1, terminate);
}
+ public <V2, P1, P2> V2 foldl(Routables<?> routables, QuadFunction<V, V2, P1, P2, V2> fold, V2 accumulator, P1 p1, P2 p2)
+ {
+ return foldl(routables, fold, accumulator, p1, p2, ignore -> false);
+ }
+
public <V2, P1, P2> V2 foldl(Routables<?> routables, QuadFunction<V, V2, P1, P2, V2> fold, V2 accumulator, P1 p1, P2 p2, Predicate<V2> terminate)
{
return foldl(routables, (v, v2, param1, param2, i, j, k) -> fold.apply(v, v2, param1, param2), accumulator, p1, p2, terminate);
diff --git a/accord-core/src/main/java/accord/utils/RelationMultiMap.java b/accord-core/src/main/java/accord/utils/RelationMultiMap.java
index f6afe54a..a7b24315 100644
--- a/accord-core/src/main/java/accord/utils/RelationMultiMap.java
+++ b/accord-core/src/main/java/accord/utils/RelationMultiMap.java
@@ -57,9 +57,9 @@ import static java.lang.String.format;
* }
* }
*
- * // TODO (expected, performance): it would be trivial to special-case transactions that intersect on all keys (e.g. by setting the top integer bit, and otherwise propagating the prior limit).
- * This would also neatly optimise cases where we only have a single key.
- * // TODO (desired, performance): it would also be simple to bitmask our integers, compressing to e.g. byte or short boundaries as permitted. We could do this for all values, including our offsets header.
+ * // TODO (desired): it would be trivial to special-case transactions that intersect on all keys (e.g. by setting the top integer bit, and otherwise propagating the prior limit).
+ * This would also neatly optimise cases where we only have a single key.
+ * // TODO (desired): it would also be simple to bitmask our integers, compressing to e.g. byte or short boundaries as permitted. We could do this for all values, including our offsets header.
*/
public class RelationMultiMap
{
@@ -95,7 +95,7 @@ public class RelationMultiMap
default BiFunction<V, V, V> valueMerger() { return null; }
}
- // TODO (expected, efficiency): cache this object per thread
+ // TODO (desired): cache this object per thread
public static abstract class AbstractBuilder<K, V, T> implements AutoCloseable
{
final Adapter<K, V> adapter;
@@ -990,7 +990,7 @@ public class RelationMultiMap
param, removeAndSplitValues, true);
}
- // TODO (required): add dedicated tests for partial overlap removals
+ // TODO (testing): add dedicated tests for partial overlap removals
private static <P, K, V> boolean removeInternal(K[] oldKeys, V[] oldValues, int[] oldKeysToValues,
K[] removeKeys, V[] removeValues, int[] removeKeysToValues,
Comparator<K> keyComparator, Comparator<V> valueComparator,
diff --git a/accord-core/src/main/java/accord/utils/SortedArrays.java b/accord-core/src/main/java/accord/utils/SortedArrays.java
index c292d6f6..244ca669 100644
--- a/accord-core/src/main/java/accord/utils/SortedArrays.java
+++ b/accord-core/src/main/java/accord/utils/SortedArrays.java
@@ -155,7 +155,7 @@ public class SortedArrays
public SortedArrayList<T> without(SortedArrayList<T> without)
{
// TODO (expected): wrap cachedAny with a complete() method that copies to an array of the source type.
- T[] array = (T[])SortedArrays.linearSubtract(Comparable::compareTo, this.array, without.array, ArrayBuffers.uncached(this.array));
+ T[] array = SortedArrays.linearSubtract(Comparable::compareTo, this.array, without.array, ArrayBuffers.uncached(this.array));
return array == this.array ? this : new SortedArrayList<>(array);
}
diff --git a/accord-core/src/main/java/accord/utils/TinyEnumSet.java b/accord-core/src/main/java/accord/utils/TinyEnumSet.java
index 234cc3ec..0008cef5 100644
--- a/accord-core/src/main/java/accord/utils/TinyEnumSet.java
+++ b/accord-core/src/main/java/accord/utils/TinyEnumSet.java
@@ -45,6 +45,11 @@ public class TinyEnumSet<E extends Enum<E>>
return bitset;
}
+ public static <E extends Enum<E>> int encode(Enum<E> value)
+ {
+ return 1 << value.ordinal();
+ }
+
public static <E extends Enum<E>> boolean contains(int bitset, E value)
{
return contains(bitset, value.ordinal());
@@ -65,7 +70,6 @@ public class TinyEnumSet<E extends Enum<E>>
return contains(bitset, ordinal);
}
-
public TinyEnumSet<E> or(TinyEnumSet<E> or)
{
return or(this, or, TinyEnumSet::new);
diff --git a/accord-core/src/main/java/accord/utils/UnhandledEnum.java b/accord-core/src/main/java/accord/utils/UnhandledEnum.java
index 09956548..05b4a42e 100644
--- a/accord-core/src/main/java/accord/utils/UnhandledEnum.java
+++ b/accord-core/src/main/java/accord/utils/UnhandledEnum.java
@@ -24,6 +24,21 @@ public class UnhandledEnum extends AssertionError
{
public UnhandledEnum(@Nonnull Enum<?> value)
{
- super("Unhandled " + value.getClass().getSimpleName() + ": " + value);
+ this("Unhandled ", value);
+ }
+
+ private UnhandledEnum(String prefix, @Nonnull Enum<?> value)
+ {
+ super(prefix + value.getClass().getSimpleName() + ": " + value);
+ }
+
+ public static UnhandledEnum invalid(@Nonnull Enum<?> value)
+ {
+ return new UnhandledEnum("Invalid ", value);
+ }
+
+ public static UnhandledEnum unknown(@Nonnull Enum<?> value)
+ {
+ return new UnhandledEnum("Unknown ", value);
}
}
diff --git a/accord-core/src/main/java/accord/utils/Utils.java b/accord-core/src/main/java/accord/utils/Utils.java
index 075c5260..b65ffbbb 100644
--- a/accord-core/src/main/java/accord/utils/Utils.java
+++ b/accord-core/src/main/java/accord/utils/Utils.java
@@ -152,6 +152,18 @@ public class Utils
}
}
+ public static void shuffle(Object[] array, RandomSource rs)
+ {
+ for (int i = array.length; i > 1; i--)
+ {
+ int j = i - 1;
+ int k = rs.nextInt(j);
+ Object tmp = array[j];
+ array[j] = array[k];
+ array[k] = tmp;
+ }
+ }
+
public static <A, B> B reduce(B zero,
Iterable<A> input,
Predicate<A> filter,
diff --git a/accord-core/src/main/java/accord/utils/async/AsyncChain.java b/accord-core/src/main/java/accord/utils/async/AsyncChain.java
index e53c61f4..0899b268 100644
--- a/accord-core/src/main/java/accord/utils/async/AsyncChain.java
+++ b/accord-core/src/main/java/accord/utils/async/AsyncChain.java
@@ -127,8 +127,6 @@ public interface AsyncChain<V>
/**
* Causes the chain to begin, starting all work required. This method must be called exactly once, not calling will
* not cause any work to start, and calling multiple times will be rejected.
- *
- * TODO (expected): Executor with cheap cancel() that cleansup task queue
*/
@Nullable Cancellable begin(BiConsumer<? super V, Throwable> callback);
diff --git a/accord-core/src/test/java/accord/burn/BurnTestBase.java b/accord-core/src/test/java/accord/burn/BurnTestBase.java
index 6886945b..1e3a48e8 100644
--- a/accord-core/src/test/java/accord/burn/BurnTestBase.java
+++ b/accord-core/src/test/java/accord/burn/BurnTestBase.java
@@ -55,6 +55,7 @@ import org.slf4j.LoggerFactory;
import accord.api.Agent;
import accord.api.Journal;
import accord.api.Key;
+import accord.api.ProtocolModifiers.Toggles;
import accord.burn.random.FrequentLargeRange;
import accord.impl.MessageListener;
import accord.impl.PrefixedIntHashKey;
@@ -87,6 +88,7 @@ import accord.primitives.Range;
import accord.primitives.Ranges;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
+import accord.primitives.Txn.Kind;
import accord.primitives.TxnId;
import accord.primitives.TxnId.FastPath;
import accord.primitives.TxnId.MediumPath;
@@ -115,6 +117,7 @@ import static accord.impl.list.ListResult.Status.Lost;
import static accord.impl.list.ListResult.Status.RecoveryApplied;
import static accord.impl.list.ListResult.Status.Truncated;
import static accord.primitives.Txn.Kind.EphemeralRead;
+import static accord.primitives.Txn.Kind.Write;
import static accord.utils.Utils.toArray;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
@@ -141,13 +144,29 @@ public class BurnTestBase
double readInCommandStore = random.nextDouble();
Function<int[], Range> nextRange = randomRanges(random);
+ {
+ Kind[] kinds = Kind.values();
+ kinds[Write.ordinal()] = kinds[0];
+ kinds[0] = Write;
+ int count = 1 + random.nextInt(kinds.length - 1);
+ for (int i = 1 ; i < count ; ++i)
+ {
+ int j = random.nextInt(i, kinds.length);
+ Kind tmp = kinds[i];
+ kinds[i] = kinds[j];
+ kinds[j] = tmp;
+ }
+ kinds = Arrays.copyOf(kinds, count);
+ Toggles.setMarkStaleIfCannotExecute(kinds);
+ }
+
FastPath[] fastPaths;
switch (random.nextInt(0, 2))
{
default: throw new IllegalStateException();
- case 0: fastPaths = new FastPath[] { FastPath.UNOPTIMISED }; break;
- case 1: fastPaths = new FastPath[] { FastPath.UNOPTIMISED, random.nextBoolean() ? FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS : FastPath.PRIVILEGED_COORDINATOR_WITHOUT_DEPS }; break;
- case 2: fastPaths = new FastPath[] { FastPath.UNOPTIMISED, FastPath.PRIVILEGED_COORDINATOR_WITHOUT_DEPS, FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS };
+ case 0: fastPaths = new FastPath[] { FastPath.Unoptimised }; break;
+ case 1: fastPaths = new FastPath[] { FastPath.Unoptimised, random.nextBoolean() ? FastPath.PrivilegedCoordinatorWithDeps : FastPath.PrivilegedCoordinatorWithoutDeps }; break;
+ case 2: fastPaths = new FastPath[] { FastPath.Unoptimised, FastPath.PrivilegedCoordinatorWithoutDeps, FastPath.PrivilegedCoordinatorWithDeps };
}
MediumPath[] mediumPaths;
@@ -209,7 +228,7 @@ public class BurnTestBase
boolean isWrite = random.nextBoolean();
int readCount = 1 + random.nextInt(2);
int writeCount = isWrite ? 1 + random.nextInt(2) : 0;
- Txn.Kind kind = isWrite ? Txn.Kind.Write : readCount == 1 ? EphemeralRead : Txn.Kind.Read;
+ Kind kind = isWrite ? Kind.Write : readCount == 1 ? EphemeralRead : Kind.Read;
TreeSet<Key> requestKeys = new TreeSet<>();
IntHashSet readValues = new IntHashSet();
@@ -374,7 +393,7 @@ public class BurnTestBase
Supplier<LongSupplier> nowSupplier = () -> {
RandomSource forked = random.fork();
- // TODO (expected): meta-randomise scale of clock drift
+ // TODO (testing): meta-randomise scale of clock drift
return FrequentLargeRange.builder(forked)
.ratio(1, 5)
.small(50, 5000, TimeUnit.MICROSECONDS)
diff --git a/accord-core/src/test/java/accord/coordinate/CoordinateTransactionTest.java b/accord-core/src/test/java/accord/coordinate/CoordinateTransactionTest.java
index f2d586c8..6146e131 100644
--- a/accord-core/src/test/java/accord/coordinate/CoordinateTransactionTest.java
+++ b/accord-core/src/test/java/accord/coordinate/CoordinateTransactionTest.java
@@ -234,7 +234,7 @@ public class CoordinateTransactionTest
Txn blockingTxn = new Txn.InMemory(keys, MockStore.read(keys), MockStore.QUERY, null);
PreLoadContext blockingTxnContext = PreLoadContext.contextFor(blockingTxnId, route);
for (Node n : cluster)
- assertEquals(AcceptOutcome.Success, getUninterruptibly(n.unsafeForKey(key).submit(blockingTxnContext, safeStore -> {
+ assertEquals(AcceptOutcome.Success, getUninterruptibly(n.unsafeForKey(key).build(blockingTxnContext, safeStore -> {
StoreParticipants participants = StoreParticipants.update(safeStore, route, blockingTxnId.epoch(), blockingTxnId, blockingTxnId.epoch());
return Commands.preaccept(safeStore, safeStore.get(blockingTxnId, participants), participants, blockingTxnId, blockingTxn.slice(safeStore.ranges().allAt(blockingTxnId), true), null, false, route);
})));
@@ -243,7 +243,7 @@ public class CoordinateTransactionTest
Txn txn = new Txn.InMemory(keys, MockStore.read(keys), MockStore.QUERY, null);
PreLoadContext context = PreLoadContext.contextFor(txnId, route);
for (Node n : cluster)
- assertEquals(AcceptOutcome.Success, getUninterruptibly(n.unsafeForKey(key).submit(context, safeStore -> {
+ assertEquals(AcceptOutcome.Success, getUninterruptibly(n.unsafeForKey(key).build(context, safeStore -> {
StoreParticipants participants = StoreParticipants.update(safeStore, route, txnId.epoch(), txnId, txnId.epoch());
return Commands.preaccept(safeStore, safeStore.get(txnId, participants), participants, txnId, txn.slice(safeStore.ranges().allAt(txnId.epoch()), true), null, false, route);
})));
@@ -270,7 +270,7 @@ public class CoordinateTransactionTest
// Move to preapplied in order to test that Barrier will find the transaction and add a listener
for (Node n : cluster)
- getUninterruptibly(n.unsafeForKey(key).execute(context, safeStore -> {
+ getUninterruptibly(n.unsafeForKey(key).build(context, safeStore -> {
StoreParticipants participants = StoreParticipants.execute(safeStore, route, txnId.epoch(), txnId, txnId.epoch());
SafeCommand safeCommand = safeStore.get(txnId, participants);
Command command = safeCommand.current();
@@ -291,7 +291,7 @@ public class CoordinateTransactionTest
// Apply the blockingTxn to unblock the rest
for (Node n : cluster)
- assertEquals(ApplyOutcome.Success, getUninterruptibly(n.unsafeForKey(key).submit(blockingTxnContext, safeStore -> {
+ assertEquals(ApplyOutcome.Success, getUninterruptibly(n.unsafeForKey(key).build(blockingTxnContext, safeStore -> {
StoreParticipants participants = StoreParticipants.execute(safeStore, route, blockingTxnId.epoch(), blockingTxnId, blockingTxnId.epoch());
return Commands.apply(safeStore, safeStore.get(blockingTxnId, participants), participants, blockingTxnId, route, blockingTxnId, PartialDeps.builder(route, true).build(), blockingTxn.slice(safeStore.ranges().allAt(blockingTxnId.epoch()), true), null, blockingTxn.query().compute(blockingTxnId, blockingTxnId, keys, null, null, null));
})));
diff --git a/accord-core/src/test/java/accord/coordinate/tracking/RecoveryTrackerReconciler.java b/accord-core/src/test/java/accord/coordinate/tracking/RecoveryTrackerReconciler.java
index 1a3fa933..8881fb33 100644
--- a/accord-core/src/test/java/accord/coordinate/tracking/RecoveryTrackerReconciler.java
+++ b/accord-core/src/test/java/accord/coordinate/tracking/RecoveryTrackerReconciler.java
@@ -26,7 +26,7 @@ import org.junit.jupiter.api.Assertions;
import java.util.ArrayList;
-// TODO (expected, testing): check fast path accounting
+// TODO (testing): check fast path accounting
public class RecoveryTrackerReconciler extends TrackerReconciler<RecoveryShardTracker, RecoveryTracker, RecoveryTrackerReconciler.Rsp>
{
enum Rsp { FAST, SLOW, FAIL }
diff --git a/accord-core/src/test/java/accord/coordinate/tracking/TrackerReconciler.java b/accord-core/src/test/java/accord/coordinate/tracking/TrackerReconciler.java
index e7fbf92f..486d5f7c 100644
--- a/accord-core/src/test/java/accord/coordinate/tracking/TrackerReconciler.java
+++ b/accord-core/src/test/java/accord/coordinate/tracking/TrackerReconciler.java
@@ -106,7 +106,7 @@ public abstract class TrackerReconciler<ST extends ShardTracker, T extends Abstr
.collect(Collectors.toList());
}
- // TODO (expected): (testing) generalise and parameterise topology generation a bit more
+ // TODO (testing): generalise and parameterise topology generation a bit more
// also, select a subset of the generated topologies to correctly simulate topology consumption logic
private static Stream<Topologies> topologies(RandomSource random, AgentExecutor executor)
{
diff --git a/accord-core/src/test/java/accord/impl/PrefixedIntHashKey.java b/accord-core/src/test/java/accord/impl/PrefixedIntHashKey.java
index 82b3adc8..3b5b0459 100644
--- a/accord-core/src/test/java/accord/impl/PrefixedIntHashKey.java
+++ b/accord-core/src/test/java/accord/impl/PrefixedIntHashKey.java
@@ -33,7 +33,6 @@ import accord.utils.Invariants;
import static accord.utils.Utils.toArray;
-// TODO (now): burn test is producing prefix keys over full integer range rather than 16bits
public 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 c316239b..806e104c 100644
--- a/accord-core/src/test/java/accord/impl/RemoteListenersTest.java
+++ b/accord-core/src/test/java/accord/impl/RemoteListenersTest.java
@@ -410,8 +410,8 @@ public class RemoteListenersTest
}
@Override public boolean inStore() { return false; }
- @Override public AsyncChain<Void> execute(PreLoadContext context, Consumer<? super SafeCommandStore> consumer) { return null; }
- @Override public <T> AsyncChain<T> submit(PreLoadContext context, Function<? super SafeCommandStore, T> apply) { return null; }
+ @Override public AsyncChain<Void> build(PreLoadContext context, Consumer<? super SafeCommandStore> consumer) { return null; }
+ @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; }
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 2faffc20..61ccb1dc 100644
--- a/accord-core/src/test/java/accord/impl/basic/Cluster.java
+++ b/accord-core/src/test/java/accord/impl/basic/Cluster.java
@@ -130,6 +130,7 @@ import static accord.impl.basic.Cluster.OverrideLinksKind.NONE;
import static accord.impl.basic.Cluster.OverrideLinksKind.RANDOM_BIDIRECTIONAL;
import static accord.impl.basic.NodeSink.Action.DELIVER;
import static accord.impl.basic.NodeSink.Action.DROP;
+import static accord.local.Command.NotDefined.uninitialised;
import static accord.local.StoreParticipants.Filter.LOAD;
import static accord.utils.AccordGens.keysInsideRanges;
import static accord.utils.AccordGens.rangeInsideRange;
@@ -390,7 +391,7 @@ public class Cluster
onDone.add(run);
}
- // TODO (expected): merge with BurnTest.burn
+ // TODO (testing): merge with BurnTest.burn
public static Map<MessageType, Cluster.Stats> run(Supplier<RandomSource> randomSupplier,
int[] prefixes,
List<Node.Id> nodes,
@@ -645,7 +646,7 @@ public class Cluster
NodeSink.TimeoutSupplier timeouts = new NodeSink.TimeoutSupplier()
{
final RandomSource random = randomSupplier.get();
- // TODO (expected): slow/expires should be broadly in sync with our link latency config
+ // TODO (testing): slow/expires should be broadly in sync with our link latency config
final LongSupplier slowAt, expiresAt, failsAt;
{
int medianSlowAt = random.nextInt(100, 200);
@@ -1453,7 +1454,11 @@ public class Cluster
}
Command blockedOn = null;
if (blockedOnId != null)
- blockedOn = store.unsafeCommands().get(blockedOnId).value();
+ {
+ GlobalCommand cmd = store.unsafeCommands().get(blockedOnId);
+ if (cmd == null) blockedOn = uninitialised(blockedOnId);
+ else blockedOn = cmd.value();
+ }
return new BlockingTransaction(command.txnId(), command, store, blockedOn, blockedVia);
}
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 8b73f4be..701d3a28 100644
--- a/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java
+++ b/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java
@@ -267,13 +267,13 @@ public class DelayedCommandStores extends InMemoryCommandStores.SingleThread
}
@Override
- public AsyncChain<Void> execute(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
+ public AsyncChain<Void> build(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
{
return submit(newTask(context, i -> { consumer.accept(i); return null; }));
}
@Override
- public <T> AsyncChain<T> submit(PreLoadContext context, Function<? super SafeCommandStore, T> function)
+ public <T> AsyncChain<T> build(PreLoadContext context, Function<? super SafeCommandStore, T> function)
{
return submit(newTask(context, function));
}
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 6ec82c9e..e54fe798 100644
--- a/accord-core/src/test/java/accord/impl/list/ListAgent.java
+++ b/accord-core/src/test/java/accord/impl/list/ListAgent.java
@@ -201,10 +201,4 @@ public class ListAgent implements Agent
{
return timeoutSupplier.expiresAt();
}
-
- public boolean collectMaxApplied()
- {
- // TODO (expected): randomise this to exercise both code paths
- return false;
- }
}
diff --git a/accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java b/accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java
index d32f2a38..b6a9d4fb 100644
--- a/accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java
+++ b/accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java
@@ -25,7 +25,6 @@ import java.util.function.Function;
import accord.api.Data;
import accord.api.DataStore;
import accord.impl.AbstractFetchCoordinator;
-import accord.impl.InMemoryCommandStore;
import accord.local.CommandStore;
import accord.local.Node;
import accord.local.PreLoadContext;
@@ -64,7 +63,7 @@ public class ListFetchCoordinator extends AbstractFetchCoordinator
return;
ListData listData = (ListData) data;
- persisting.add(commandStore.execute(PreLoadContext.empty(), safeStore -> {
+ persisting.add(commandStore.build(PreLoadContext.empty(), safeStore -> {
listData.forEach((key, value) -> listStore.writeUnsafe(key, value));
}).flatMap(ignore -> listStore.snapshot(true, received, syncPoint.syncId)).addCallback((success, fail) -> {
if (fail == null) success(from, received);
@@ -75,9 +74,6 @@ public class ListFetchCoordinator extends AbstractFetchCoordinator
@Override
protected ListFetchRequest newFetchRequest(long sourceEpoch, TxnId syncId, Ranges ranges, PartialDeps partialDeps, PartialTxn partialTxn)
{
- if (((ListAgent)node.agent()).collectMaxApplied())
- return new CollectMaxAppliedFetchRequest(sourceEpoch, syncId, ranges, partialDeps, partialTxn);
-
return new ListFetchRequest(sourceEpoch, syncId, ranges, partialDeps, partialTxn);
}
@@ -95,41 +91,4 @@ public class ListFetchCoordinator extends AbstractFetchCoordinator
return super.beginRead(safeStore, executeAt, txn, unavailable);
}
}
-
- static class CollectMaxAppliedFetchRequest extends ListFetchRequest
- {
- private transient Timestamp maxApplied;
-
- public CollectMaxAppliedFetchRequest(long sourceEpoch, TxnId syncId, Ranges ranges, PartialDeps partialDeps, PartialTxn partialTxn)
- {
- super(sourceEpoch, syncId, ranges, partialDeps, partialTxn);
- }
-
- @Override
- protected void readStarted(SafeCommandStore safeStore, Ranges unavailable)
- {
- CommandStore commandStore = safeStore.commandStore();
- Ranges slice = safeStore.ranges().allAt(txnId).without(unavailable);
- ((InMemoryCommandStore)commandStore).maxAppliedFor(scope, slice).begin((newMaxApplied, failure) -> {
- if (failure != null)
- {
- commandStore.agent().onUncaughtException(failure);
- }
- else
- {
- synchronized (this)
- {
- if (maxApplied == null) maxApplied = newMaxApplied;
- else maxApplied = Timestamp.max(maxApplied, newMaxApplied);
- }
- }
- });
- }
-
- @Override
- protected Timestamp safeToReadAfter()
- {
- return maxApplied;
- }
- }
}
diff --git a/accord-core/src/test/java/accord/impl/list/ListStore.java b/accord-core/src/test/java/accord/impl/list/ListStore.java
index bbe97a95..1e8f9705 100644
--- a/accord-core/src/test/java/accord/impl/list/ListStore.java
+++ b/accord-core/src/test/java/accord/impl/list/ListStore.java
@@ -337,7 +337,7 @@ public class ListStore implements DataStore
{
if (!allowedReads.contains(key))
{
- // TODO (expected): improve this validation logic
+ // TODO (testing): improve this validation logic
// but in the meantime, whitelist valid things, e.g. ephemeral reads can access data that has been retired
if (executeAt instanceof TxnId && ((TxnId) executeAt).awaitsOnlyDeps()
&& removedAts.stream().anyMatch(r -> r.ranges.contains(key) && r.epoch > executeAt.epoch()))
@@ -370,7 +370,7 @@ public class ListStore implements DataStore
Ranges singleRanges = Ranges.of(range);
if (!allowedReads.containsAll(singleRanges))
{
- // TODO (required): it is actually safe for a node on an old epoch to still be executing a transaction that has been executed in a later epoch,
+ // TODO (testing): it is actually safe for a node on an old epoch to still be executing a transaction that has been executed in a later epoch,
// making this check over-enthusiastic.
illegalState(String.format("Attempted to access range %s on node %s, which is not in the range %s;\nexecuteAt = %s\n%s",
range, node, allowedReads, executeAt, history(singleRanges)));
@@ -585,7 +585,7 @@ public class ListStore implements DataStore
if (!previousTopology.ranges().intersects(range))
{
// A range was added that globally didn't exist before; there is nothing to bootstrap here!
- // TODO (now): document this history change
+ // TODO (testing): document this history change
allowedReads = allowedReads.with(Ranges.of(range));
}
}
@@ -623,9 +623,8 @@ public class ListStore implements DataStore
private void removeLocalWhenReady(Node node, long epoch, Ranges removed)
{
- // TODO (now): can this migrate to a listener as bootstrap will do a SyncPoint which will propgate this knowlege?
-
- // TODO (duplication): there is overlap with durability scheduling, but that logic has a few issues which make it hard to use here:
+ // TODO (testing): can this migrate to a listener as bootstrap will do a SyncPoint which will propgate this knowlege?
+ // TODO (testing): there is overlap with durability scheduling, but that logic has a few issues which make it hard to use here:
// * always works off latest topology, so the removed ranges won't actually get marked durable!
// * api is range -> TxnId, so we still need a TxnId to be referenced off... so we need to create a TxnId to know when we are in-sync!
// * if we have a sync point, we really only care if the sync point is applied globally...
diff --git a/accord-core/src/test/java/accord/local/CommandsTest.java b/accord-core/src/test/java/accord/local/CommandsTest.java
index 635c517b..46279c7d 100644
--- a/accord-core/src/test/java/accord/local/CommandsTest.java
+++ b/accord-core/src/test/java/accord/local/CommandsTest.java
@@ -56,6 +56,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static accord.Utils.listWriteTxn;
+import static accord.primitives.Txn.Kind.Write;
import static accord.utils.Property.qt;
import static accord.utils.Utils.addAll;
@@ -95,7 +96,7 @@ class CommandsTest
Keys keys = Keys.of(Gens.lists(keyGen).unique().ofSizeBetween(1, 10).next(rs));
Txn txn = listWriteTxn(from, keys);
- TxnId txnId = node.nextTxnId(Txn.Kind.Write, Routable.Domain.Key);
+ TxnId txnId = node.nextTxnId(Write, Routable.Domain.Key);
for (Node n : nodeMap.values())
((TestableConfigurationService) n.configService()).reportTopology(updatedTopology);
diff --git a/accord-core/src/test/java/accord/local/ImmutableCommandTest.java b/accord-core/src/test/java/accord/local/ImmutableCommandTest.java
index ade234e6..80e3ee52 100644
--- a/accord-core/src/test/java/accord/local/ImmutableCommandTest.java
+++ b/accord-core/src/test/java/accord/local/ImmutableCommandTest.java
@@ -172,11 +172,11 @@ public class ImmutableCommandTest
setTopologyEpoch(support.local, 2);
((TestableConfigurationService)node.configService()).reportTopology(TopologyUtils.withEpoch(support.local.get(), 2));
Timestamp expectedTimestamp = Timestamp.fromValues(2, 110, ID1);
- getUninterruptibly(commands.execute(context, (Consumer<? super SafeCommandStore>) safeStore -> {
+ getUninterruptibly(commands.build(context, (Consumer<? super SafeCommandStore>) safeStore -> {
StoreParticipants participants = StoreParticipants.update(safeStore, ROUTE, txnId.epoch(), txnId, 2);
Commands.preaccept(safeStore, safeStore.get(txnId, participants), participants, txnId, txn.slice(FULL_RANGES, true), null, false, ROUTE);
}));
- commands.execute(PreLoadContext.contextFor(txnId, txn.keys().toParticipants()), safeStore -> {
+ commands.build(PreLoadContext.contextFor(txnId, txn.keys().toParticipants()), safeStore -> {
Command command = safeStore.get(txnId).current();
Assertions.assertEquals(Status.PreAccepted, command.status());
Assertions.assertEquals(expectedTimestamp, command.executeAt());
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 d738bb11..d2b349bd 100644
--- a/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
+++ b/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
@@ -98,14 +98,16 @@ import static accord.primitives.SaveStatus.ReadyToExecute;
import static accord.primitives.SaveStatus.Stable;
import static accord.primitives.Status.Durability.NotDurable;
import static accord.primitives.Txn.Kind.Write;
-
-// TODO (expected): test setting redundant before
-// TODO (expected): test ballot updates
-// TODO (expected): test transition to Erased
-// TODO (expected): ensure execution is not too early
-// TODO (expected): validate mapReduce
-// TODO (expected): insert linearizability violations and detect them
-// TODO (required): make sure we test execution is triggered promptly (precisely when it should be), esp. for unmanaged txns
+import static accord.primitives.TxnId.Cardinality.Any;
+import static accord.primitives.TxnId.Cardinality.SingleKey;
+
+// TODO (testing): test setting redundant before
+// TODO (testing): test ballot updates
+// TODO (testing): test transition to Erased
+// TODO (testing): ensure execution is not too early
+// TODO (testing): validate mapReduce
+// TODO (testing): insert linearizability violations and detect them
+// TODO (testing): make sure we test execution is triggered promptly (precisely when it should be), esp. for unmanaged txns
public class CommandsForKeyTest
{
private static final Logger logger = LoggerFactory.getLogger(CommandsForKeyTest.class);
@@ -129,12 +131,12 @@ public class CommandsForKeyTest
}
}
- // TODO (expected): randomise ballots
+ // TODO (testing): randomise ballots
static class Canon implements NotifySink
{
- private static final TxnId MIN = new TxnId(1, 1, 0, Txn.Kind.Read, Key, new Node.Id(1));
+ private static final TxnId MIN = new TxnId(1, 1, 0, Txn.Kind.Read, Key, SingleKey, new Node.Id(1));
- // TODO (expected): randomise ratios
+ // TODO (testing): randomise ratios
static final Txn.Kind[] KINDS = new Txn.Kind[] { Txn.Kind.Read, Write, Txn.Kind.EphemeralRead, Txn.Kind.SyncPoint, Txn.Kind.ExclusiveSyncPoint };
final RandomSource rnd;
final Node.Id[] nodeIds;
@@ -319,9 +321,9 @@ public class CommandsForKeyTest
{
default:
case NotDefined:
- case TruncatedApply:
- case TruncatedApplyWithDeps:
case TruncatedApplyWithOutcome:
+ case TruncatedApply:
+ case TruncatedUnapplied:
case PreApplied:
case PreCommitted:
throw new AssertionError();
@@ -412,7 +414,7 @@ public class CommandsForKeyTest
{
TxnId min = MIN;
TxnId max;
- if (byId.isEmpty()) max = new TxnId(1, 100, 0, Txn.Kind.Read, Key, nodeIds[0]);
+ if (byId.isEmpty()) max = new TxnId(1, 100, 0, Txn.Kind.Read, Key, SingleKey, nodeIds[0]);
else
{
max = byId.lastEntry().getValue().txnId();
@@ -422,7 +424,7 @@ public class CommandsForKeyTest
case 2:
min = max;
case 1:
- max = new TxnId(Math.min(100, max.epoch() * 2), max.hlc() + 100, 0, max.kind(), max.domain(), max.node);
+ max = new TxnId(Math.min(100, max.epoch() * 2), max.hlc() + 100, 0, max.kind(), max.domain(), max.cardinality(), max.node);
case 0:
}
@@ -458,7 +460,9 @@ public class CommandsForKeyTest
else if (hlc == max.hlc() && max.domain() == Key) domain = Key;
else domain = rnd.nextBoolean() ? Key : Domain.Range;
- return new TxnId(epoch, hlc, 0, kind, domain, node);
+ TxnId.Cardinality cardinality = domain == Domain.Range || rnd.nextBoolean() ? Any : SingleKey;
+
+ return new TxnId(epoch, hlc, 0, kind, domain, cardinality, node);
}
Timestamp generateTimestamp(Timestamp min, Timestamp max, boolean unique)
@@ -593,6 +597,7 @@ public class CommandsForKeyTest
{
TxnId bound = generateId(from.first(), from.last());
TxnId txnId = from.floor(bound);
+ if (txnId == null) txnId = from.first();
return byId.get(txnId);
}
@@ -605,7 +610,7 @@ public class CommandsForKeyTest
@Test
public void testOne()
{
- test(583600505900884L, 1000);
+ test(165440852372708L, 1000);
// test(System.nanoTime(), 500);
}
@@ -982,7 +987,7 @@ public class CommandsForKeyTest
}
@Override
- public AsyncChain<Void> execute(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
+ public AsyncChain<Void> build(PreLoadContext context, Consumer<? super SafeCommandStore> consumer)
{
Task task = new Task(consumer);
queue.add(task);
@@ -990,7 +995,7 @@ public class CommandsForKeyTest
}
@Override
- public <T> AsyncChain<T> submit(PreLoadContext context, Function<? super SafeCommandStore, T> apply)
+ public <T> AsyncChain<T> build(PreLoadContext context, Function<? super SafeCommandStore, T> apply)
{
throw new UnsupportedOperationException();
}
diff --git a/accord-core/src/test/java/accord/local/cfk/SerializeTest.java b/accord-core/src/test/java/accord/local/cfk/SerializeTest.java
new file mode 100644
index 00000000..cd163f55
--- /dev/null
+++ b/accord-core/src/test/java/accord/local/cfk/SerializeTest.java
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.local.cfk;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import accord.local.Node;
+import accord.primitives.Routable.Domain;
+import accord.primitives.Txn.Kind;
+import accord.primitives.TxnId;
+import accord.primitives.TxnId.Cardinality;
+import accord.primitives.TxnId.FastPath;
+import accord.primitives.TxnId.MediumPath;
+import accord.utils.RandomSource;
+import accord.utils.RandomTestRunner;
+
+import static accord.local.cfk.Serialize.EMPTY_FLAG_HISTORY;
+import static accord.local.cfk.Serialize.encodedFlagBits;
+import static accord.local.cfk.Serialize.selectFlagHistory;
+import static accord.local.cfk.Serialize.updateFlagHistory;
+import static accord.primitives.Routable.Domain.Range;
+import static accord.primitives.TxnId.Cardinality.Any;
+import static accord.utils.Utils.shuffle;
+
+// this class is mostly tested in C* integration due to having concrete serializers to work with
+public class SerializeTest
+{
+ @Test
+ public void testFlagHistory()
+ {
+ for (int c = 0 ; c < 1000 ; ++c)
+ testOneFlagHistory();
+ }
+
+ private void testOneFlagHistory()
+ {
+ RandomTestRunner.test().check(rnd -> {
+ int[] inputs = new int[rnd.nextInt(100, 1000)];
+
+ Supplier<Kind> kinds = rnd.randomWeightedPicker(randomSubset(Kind.values(), rnd));
+ Supplier<Domain> domains = rnd.randomWeightedPicker(randomSubset(Domain.values(), rnd));
+ Supplier<FastPath> fastPaths = rnd.randomWeightedPicker(randomSubset(FastPath.values(), rnd));
+ Supplier<MediumPath> mediumPaths = rnd.randomWeightedPicker(randomSubset(MediumPath.values(), rnd));
+ Supplier<Cardinality> cardinalities = rnd.randomWeightedPicker(randomSubset(Cardinality.values(), rnd));
+ float randomBitsChance = rnd.nextFloat() * 0.2f;
+
+ for (int i = 0 ; i < inputs.length ; ++i)
+ {
+ if (rnd.decide(randomBitsChance))
+ {
+ inputs[i] = rnd.nextInt(rnd.nextBoolean() ? 0x100 : 0x10000);
+ }
+ else
+ {
+ Domain domain = domains.get();
+ Cardinality cardinality = domain == Range ? Any : cardinalities.get();
+ TxnId txnId = new TxnId(0, 0, fastPaths.get().bits | mediumPaths.get().bit(), kinds.get(), domain, cardinality, Node.Id.NONE);
+ inputs[i] = txnId.flags();
+ }
+ }
+
+ int[] sortedHistoryFlags = new int[6];
+ long flagHistory = Serialize.EMPTY_FLAG_HISTORY;
+ int[] encoded = new int[inputs.length];
+ int[] raw = new int[inputs.length];
+ long[] histories = new long[inputs.length];
+ for (int i = 0 ; i < inputs.length ; ++i)
+ {
+ int flags = inputs[i];
+ encoded[i] = encodedFlagBits(flags, flagHistory);
+ Assertions.assertTrue(encoded[i] < 8);
+ raw[i] = encoded[i] == 0 ? (flags & 0xff) : encoded[i] == 1 ? (flags & 0xffff) : -1;
+ if (encoded[i] == 0)
+ {
+ flagHistory = updateFlagHistory(flags, encoded[i], flagHistory);
+ for (int j = 0 ; j < 6 ; ++j)
+ sortedHistoryFlags[j] = (int) ((flagHistory >>> (9 * j)) & 0xff);
+ Arrays.sort(sortedHistoryFlags);
+ for (int j = 1 ; j < 6 ; ++j)
+ Assertions.assertNotEquals(sortedHistoryFlags[j - 1], sortedHistoryFlags[j]);
+ }
+ histories[i] = flagHistory;
+ }
+
+ flagHistory = EMPTY_FLAG_HISTORY;
+ for (int i = 0 ; i < inputs.length ; ++i)
+ {
+ int decodedFlags = encoded[i] < 2 ? raw[i] : selectFlagHistory(encoded[i], flagHistory);
+ Assertions.assertEquals(inputs[i], decodedFlags);
+ if (encoded[i] == 0)
+ flagHistory = updateFlagHistory(decodedFlags, encoded[i], flagHistory);
+ Assertions.assertEquals(histories[i], flagHistory);
+ }
+ });
+ }
+
+ private static <T> T[] randomSubset(T[] input, RandomSource rnd)
+ {
+ shuffle(input, rnd);
+ return Arrays.copyOf(input, 1 + rnd.nextInt(input.length - 1));
+ }
+}
diff --git a/accord-core/src/test/java/accord/messages/PreAcceptTest.java b/accord-core/src/test/java/accord/messages/PreAcceptTest.java
index 7592c73d..ba8ea769 100644
--- a/accord-core/src/test/java/accord/messages/PreAcceptTest.java
+++ b/accord-core/src/test/java/accord/messages/PreAcceptTest.java
@@ -103,7 +103,7 @@ public class PreAcceptTest
clock.increment(10);
preAccept.process(node, ID2, REPLY_CONTEXT);
- commandStore.execute(PreLoadContext.contextFor(txnId, txn.keys().toParticipants(), SYNC), safeStore -> {
+ commandStore.build(PreLoadContext.contextFor(txnId, txn.keys().toParticipants(), SYNC), safeStore -> {
CommandsForKey cfk = safeStore.get(key.toUnseekable()).current();
TxnId commandId = cfk.get(0).plainTxnId();
Command command = safeStore.ifInitialised(commandId).current();
@@ -165,7 +165,7 @@ public class PreAcceptTest
invalidate.process(node, ID2, REPLY_CONTEXT);
messageSink.assertHistorySizes(0, 1);
- assertThat(messageSink.responses.get(0).payload).isEqualTo(new BeginInvalidation.InvalidateReply(null, Ballot.ZERO, SaveStatus.Uninitialised, false, null, null, null));
+ assertThat(messageSink.responses.get(0).payload).isEqualTo(new BeginInvalidation.InvalidateReply(null, Ballot.ZERO, SaveStatus.NotDefined, false, null, null, null));
messageSink.clearHistory();
PreAccept preAccept = preAccept(txnId, txn, key.toUnseekable());
@@ -272,7 +272,7 @@ public class PreAcceptTest
clock.increment(10);
preAccept.process(node, ID2, REPLY_CONTEXT);
- commandStore.execute(PreLoadContext.contextFor(txnId, txn.keys().toParticipants(), SYNC), safeStore -> {
+ commandStore.build(PreLoadContext.contextFor(txnId, txn.keys().toParticipants(), SYNC), safeStore -> {
CommandsForKey cfk = safeStore.get(key.toUnseekable()).current();
TxnId commandId = cfk.get(0).plainTxnId();
Command command = safeStore.ifInitialised(commandId).current();
diff --git a/accord-core/src/test/java/accord/messages/ReadDataTest.java b/accord-core/src/test/java/accord/messages/ReadDataTest.java
index f3618b41..a0645e0a 100644
--- a/accord-core/src/test/java/accord/messages/ReadDataTest.java
+++ b/accord-core/src/test/java/accord/messages/ReadDataTest.java
@@ -57,7 +57,6 @@ import accord.primitives.PartialDeps;
import accord.primitives.PartialTxn;
import accord.primitives.Range;
import accord.primitives.Ranges;
-import accord.primitives.Routable;
import accord.primitives.Route;
import accord.primitives.Seekables;
import accord.primitives.Timestamp;
@@ -75,6 +74,7 @@ import org.mockito.stubbing.Answer;
import static accord.Utils.createNode;
import static accord.Utils.id;
+import static accord.primitives.Routable.Domain.Key;
import static accord.utils.Invariants.illegalState;
import static accord.utils.Utils.listOf;
import static accord.utils.async.AsyncChains.getUninterruptibly;
@@ -96,7 +96,7 @@ class ReadDataTest
MessageSink sink = Mockito.mock(MessageSink.class);
Node node = createNode(ID1, TOPOLOGY, sink, new MockCluster.Clock(100));
- TxnId txnId = node.nextTxnId(Txn.Kind.Write, Routable.Domain.Key);
+ TxnId txnId = node.nextTxnId(Txn.Kind.Write, Key);
Keys keys = Keys.of(IntKey.key(1), IntKey.key(43));
AsyncResults.SettableResult<Data> readResult = new AsyncResults.SettableResult<>();
@@ -146,7 +146,7 @@ class ReadDataTest
{
// status=Commit, will listen waiting for ReadyToExecute; obsolete marked by status listener
test(state -> {
- state.forEach(store -> check(store.execute(PreLoadContext.contextFor(state.txnId, state.route), safe -> {
+ state.forEach(store -> check(store.build(PreLoadContext.contextFor(state.txnId, state.route), safe -> {
CheckedCommands.preaccept(safe, state.txnId, state.partialTxn, state.route);
CheckedCommands.accept(safe, state.txnId, Ballot.ZERO, state.partialRoute, state.executeAt, state.deps);
@@ -183,7 +183,7 @@ class ReadDataTest
state.readyToExecute(store);
store = stores.get(1);
- check(store.execute(PreLoadContext.contextFor(state.txnId, state.route), safeStore -> {
+ check(store.build(PreLoadContext.contextFor(state.txnId, state.route), safeStore -> {
StoreParticipants participants = StoreParticipants.notAccept(safeStore, state.route, state.txnId);
SafeCommand safeCommand = safeStore.get(state.txnId, participants);
Command prev = safeCommand.current();
@@ -201,7 +201,7 @@ class ReadDataTest
{
test(state -> {
List<CommandStore> stores = stores(state);
- stores.forEach(store -> check(store.execute(PreLoadContext.contextFor(state.txnId, state.route), safeStore -> {
+ stores.forEach(store -> check(store.build(PreLoadContext.contextFor(state.txnId, state.route), safeStore -> {
StoreParticipants participants = StoreParticipants.notAccept(safeStore, state.route, state.txnId);
SafeCommand command = safeStore.get(state.txnId, participants);
command.commitInvalidated(safeStore);
@@ -270,7 +270,7 @@ class ReadDataTest
void readyToExecute(CommandStore store)
{
- check(store.execute(PreLoadContext.contextFor(txnId, route), safe -> {
+ check(store.build(PreLoadContext.contextFor(txnId, route), safe -> {
CheckedCommands.preaccept(safe, txnId, partialTxn, route);
CheckedCommands.accept(safe, txnId, Ballot.ZERO, partialRoute, executeAt, deps);
CheckedCommands.commit(safe, SaveStatus.Stable, Ballot.ZERO, txnId, route, partialTxn, executeAt, deps);
@@ -294,7 +294,7 @@ class ReadDataTest
Mockito.when(write.apply(any(), any(), any(), any(), any(), any())).thenReturn(writeResult);
Writes writes = new Writes(txnId, executeAt, keys, write);
- forEach(store -> check(store.execute(PreLoadContext.contextFor(txnId, route), safe -> {
+ forEach(store -> check(store.build(PreLoadContext.contextFor(txnId, route), safe -> {
CheckedCommands.apply(safe, txnId, route, executeAt, deps, partialTxn, writes, Mockito.mock(Result.class));
})));
return writeResult;
diff --git a/accord-core/src/test/java/accord/primitives/KeyDepsTest.java b/accord-core/src/test/java/accord/primitives/KeyDepsTest.java
index 10c11505..d0417561 100644
--- a/accord-core/src/test/java/accord/primitives/KeyDepsTest.java
+++ b/accord-core/src/test/java/accord/primitives/KeyDepsTest.java
@@ -61,7 +61,7 @@ import static accord.utils.Property.qt;
import static accord.utils.Utils.toArray;
import static org.assertj.core.api.Assertions.assertThat;
-// TODO (expected, testing): test Keys with no contents, "without", "with" where TxnId and Keys are the same, but Key -> [TxnId] does not match;
+// TODO (testing): test Keys with no contents, "without", "with" where TxnId and Keys are the same, but Key -> [TxnId] does not match;
// ensure high code coverage
public class KeyDepsTest
{
diff --git a/accord-core/src/test/java/accord/primitives/RangeDepsTest.java b/accord-core/src/test/java/accord/primitives/RangeDepsTest.java
index 5c2e8e81..b5dd4caa 100644
--- a/accord-core/src/test/java/accord/primitives/RangeDepsTest.java
+++ b/accord-core/src/test/java/accord/primitives/RangeDepsTest.java
@@ -195,7 +195,7 @@ public class RangeDepsTest
private static final boolean EXHAUSTIVE = false;
- // TODO (expected, testing): generate ranges of different sizes at different ratios
+ // TODO (testing): generate ranges of different sizes at different ratios
private static Validate generate(Random random, GenerateRanges generate, int txnIdCount, int rangeCount)
{
Map<TxnId, Ranges> map = new TreeMap<>();
diff --git a/accord-core/src/test/java/accord/utils/AccordGens.java b/accord-core/src/test/java/accord/utils/AccordGens.java
index 2844a394..eb8ec6d8 100644
--- a/accord-core/src/test/java/accord/utils/AccordGens.java
+++ b/accord-core/src/test/java/accord/utils/AccordGens.java
@@ -47,16 +47,18 @@ import accord.primitives.Keys;
import accord.primitives.Range;
import accord.primitives.RangeDeps;
import accord.primitives.Ranges;
-import accord.primitives.Routable;
+import accord.primitives.Routable.Domain;
import accord.primitives.RoutableKey;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
+import accord.primitives.TxnId.Cardinality;
import accord.topology.Shard;
import accord.topology.Topology;
import accord.utils.SortedArrays.SortedArrayList;
import org.agrona.collections.IntHashSet;
+import static accord.primitives.TxnId.Cardinality.Any;
import static accord.utils.Utils.toArray;
public class AccordGens
@@ -121,9 +123,14 @@ public class AccordGens
return txnIds(epochs(), hlcs(), nodeIdValues(), kinds);
}
- public static Gen<TxnId> txnIds(Gen<Txn.Kind> kinds, Gen<Routable.Domain> domains)
+ public static Gen<TxnId> txnIds(Gen<Txn.Kind> kinds, Gen<Domain> domains)
{
- return txnIds(epochs(), hlcs(), nodeIdValues(), kinds, domains);
+ return txnIds(epochs(), hlcs(), nodeIdValues(), kinds, domains, ignore -> Any);
+ }
+
+ public static Gen<TxnId> txnIds(Gen<Txn.Kind> kinds, Gen<Domain> domains, Gen<Cardinality> cardinalities)
+ {
+ return txnIds(epochs(), hlcs(), nodeIdValues(), kinds, domains, cardinalities);
}
public static Gen<TxnId> txnIds(Gen.LongGen epochs, Gen.LongGen hlcs, Gen.IntGen nodes)
@@ -133,12 +140,21 @@ public class AccordGens
public static Gen<TxnId> txnIds(Gen.LongGen epochs, Gen.LongGen hlcs, Gen.IntGen nodes, Gen<Txn.Kind> kinds)
{
- return txnIds(epochs, hlcs, nodes, kinds, Gens.enums().all(Routable.Domain.class));
+ return txnIds(epochs, hlcs, nodes, kinds, Gens.enums().all(Domain.class), ignore -> Any);
+ }
+
+ public static Gen<TxnId> txnIds(Gen.LongGen epochs, Gen.LongGen hlcs, Gen.IntGen nodes, Gen<Txn.Kind> kinds, Gen<Domain> domains)
+ {
+ return txnIds(epochs, hlcs, nodes, kinds, domains, ignore -> Any);
}
- public static Gen<TxnId> txnIds(Gen.LongGen epochs, Gen.LongGen hlcs, Gen.IntGen nodes, Gen<Txn.Kind> kinds, Gen<Routable.Domain> domains)
+ public static Gen<TxnId> txnIds(Gen.LongGen epochs, Gen.LongGen hlcs, Gen.IntGen nodes, Gen<Txn.Kind> kinds, Gen<Domain> domains, Gen<Cardinality> cardinalities)
{
- return rs -> new TxnId(epochs.nextLong(rs), hlcs.nextLong(rs), 0, kinds.next(rs), domains.next(rs), new Node.Id(nodes.nextInt(rs)));
+ return rs -> {
+ Domain domain = domains.next(rs);
+ Cardinality cardinality = domain == Domain.Range ? Any : cardinalities.next(rs);
+ return new TxnId(epochs.nextLong(rs), hlcs.nextLong(rs), 0, kinds.next(rs), domain, cardinality, new Node.Id(nodes.nextInt(rs)));
+ };
}
public static Gen<Ballot> ballot()
@@ -277,13 +293,13 @@ public class AccordGens
public static Gen<KeyDeps> keyDeps(Gen<? extends RoutingKey> keyGen)
{
Gen<Txn.Kind> kinds = Gens.pick(Txn.Kind.Write, Txn.Kind.Read);
- return keyDeps(keyGen, txnIds(kinds, ignore -> Routable.Domain.Key));
+ return keyDeps(keyGen, txnIds(kinds, ignore -> Domain.Key));
}
public static Gen<KeyDeps> directKeyDeps(Gen<? extends RoutingKey> keyGen)
{
Gen<Txn.Kind> kinds = Gens.pick(Txn.Kind.SyncPoint, Txn.Kind.ExclusiveSyncPoint);
- return keyDeps(keyGen, txnIds(kinds, ignore -> Routable.Domain.Key));
+ return keyDeps(keyGen, txnIds(kinds, ignore -> Domain.Key));
}
public static Gen<KeyDeps> keyDeps(Gen<? extends RoutingKey> keyGen, Gen<TxnId> idGen)
@@ -527,7 +543,7 @@ public class AccordGens
public static Gen<RangeDeps> rangeDeps(Gen<? extends Range> rangeGen)
{
Gen<Txn.Kind> kinds = Gens.pick(Txn.Kind.Write, Txn.Kind.Read, Txn.Kind.SyncPoint, Txn.Kind.ExclusiveSyncPoint);
- return rangeDeps(rangeGen, txnIds(kinds, ignore -> Routable.Domain.Range));
+ return rangeDeps(rangeGen, txnIds(kinds, ignore -> Domain.Range));
}
public static Gen<RangeDeps> rangeDeps(Gen<? extends Range> rangeGen, Gen<TxnId> idGen)
@@ -578,7 +594,7 @@ public class AccordGens
Gens.longs().between(0, txnId.hlc()),
nodeIdValues(),
Gens.pick(Txn.Kind.Write, Txn.Kind.Read),
- ignore -> Routable.Domain.Key));
+ ignore -> Domain.Key));
rangeDepsGen = i -> RangeDeps.NONE;
directKeyDepsGen = i -> KeyDeps.NONE;
}
@@ -602,7 +618,7 @@ public class AccordGens
{
return rs -> {
Deps deps = depsGen.next(rs);
- if (deps.isEmpty()) return Command.WaitingOn.empty(Routable.Domain.Key);
+ if (deps.isEmpty()) return Command.WaitingOn.empty(Domain.Key);
int size = deps.rangeDeps.txnIdCount() + deps.directKeyDeps.txnIdCount() + deps.keyDeps.keys().size();
SimpleBitSet set = new SimpleBitSet(size);
int directKeyOffset = deps.rangeDeps.txnIdCount();
diff --git a/accord-core/src/test/java/accord/verify/StrictSerializabilityVerifier.java b/accord-core/src/test/java/accord/verify/StrictSerializabilityVerifier.java
index ebdeb4b4..d023f5a1 100644
--- a/accord-core/src/test/java/accord/verify/StrictSerializabilityVerifier.java
+++ b/accord-core/src/test/java/accord/verify/StrictSerializabilityVerifier.java
@@ -477,7 +477,7 @@ public class StrictSerializabilityVerifier implements Verifier
}
}
- // TODO (expected, testing): rethink this concept - should it be a Step? Does it provide any value? If not, it's more confusing.
+ // TODO (testing): rethink this concept - should it be a Step? Does it provide any value? If not, it's more confusing.
class FutureWrites extends Step
{
/**
@@ -540,7 +540,7 @@ public class StrictSerializabilityVerifier implements Verifier
@Override
boolean updatePredecessorsOfWrite(int[][] reads, int[] writes, StrictSerializabilityVerifier verifier)
{
- // TODO (required): this evidently wasn't carefully considered at the time, and removing it improves things
+ // TODO (testing): this evidently wasn't carefully considered at the time, and removing it improves things
// but what if anything this trying to achieve?
// probably we DO want to update the predecessors of any NEW step. perhaps we also want
// and we probably want some additional unit tests around blind writes
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org