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/08/13 09:11:26 UTC
(cassandra-accord) branch trunk updated: Enrich Durability with each phase, so we can both prune unapplied dependencies to mitigate replicas that are behind causing Deps growth, and more reliably avoid initialising recovery progress log state of transactions that cannot yet make progress Also fix: - Infer invalid in MaybeRecover and FetchData - MaybeRecover sometimes aborts before home shard knows outcome - Epoch sync with VisibilitySyncPoint - Retired implies synced Also improve: - Add Topology.removedNodes - If Durability [...]
This is an automated email from the ASF dual-hosted git repository.
benedict pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra-accord.git
The following commit(s) were added to refs/heads/trunk by this push:
new b86550c1 Enrich Durability with each phase, so we can both prune unapplied dependencies to mitigate replicas that are behind causing Deps growth, and more reliably avoid initialising recovery progress log state of transactions that cannot yet make progress Also fix: - Infer invalid in MaybeRecover and FetchData - MaybeRecover sometimes aborts before home shard knows outcome - Epoch sync with VisibilitySyncPoint - Retired implies synced Also improve: - Add Topology.removedNod [...]
b86550c1 is described below
commit b86550c154758e5dd223fa8101a2a83005b644a6
Author: Benedict Elliott Smith <be...@apache.org>
AuthorDate: Sun Aug 3 18:55:28 2025 +0100
Enrich Durability with each phase, so we can both prune unapplied dependencies to mitigate replicas that are behind causing Deps growth,
and more reliably avoid initialising recovery progress log state of transactions that cannot yet make progress
Also fix:
- Infer invalid in MaybeRecover and FetchData
- MaybeRecover sometimes aborts before home shard knows outcome
- Epoch sync with VisibilitySyncPoint
- Retired implies synced
Also improve:
- Add Topology.removedNodes
- If Durability implies we can fetch a status, update the waiting state to fetch it
patch by Benedict; reviewed by Alex Petrov for CASSANDRA-20832
---
.../src/main/java/accord/api/ProgressLog.java | 39 +-
.../main/java/accord/api/ProtocolModifiers.java | 11 +-
.../src/main/java/accord/api/RemoteListeners.java | 6 +-
.../accord/coordinate/CoordinateSyncPoint.java | 3 +-
.../accord/coordinate/CoordinationAdapter.java | 3 +-
.../java/accord/coordinate/ExecuteSyncPoint.java | 10 +-
.../main/java/accord/coordinate/ExecuteTxn.java | 14 +-
.../main/java/accord/coordinate/KeyBarriers.java | 2 +-
.../main/java/accord/coordinate/MaybeRecover.java | 32 +-
.../src/main/java/accord/coordinate/Persist.java | 4 +-
.../src/main/java/accord/coordinate/Recover.java | 2 +-
.../java/accord/coordinate/RecoverWithRoute.java | 4 +-
.../coordinate/tracking/DurabilityTracker.java | 2 +-
.../accord/impl/AbstractConfigurationService.java | 1 +
.../java/accord/impl/DefaultRemoteListeners.java | 21 +-
.../java/accord/impl/InMemoryCommandStore.java | 17 +-
.../impl/progresslog/DefaultProgressLog.java | 122 +++---
.../java/accord/impl/progresslog/HomeState.java | 24 +-
.../impl/progresslog/SavedProgressToken.java | 2 +-
.../java/accord/impl/progresslog/WaitingState.java | 14 +-
.../src/main/java/accord/local/Cleanup.java | 43 +--
.../src/main/java/accord/local/Command.java | 20 +-
.../src/main/java/accord/local/CommandStore.java | 25 +-
.../main/java/accord/local/CommandSummaries.java | 25 +-
.../src/main/java/accord/local/Commands.java | 60 +--
.../src/main/java/accord/local/DepsCalculator.java | 5 +-
.../src/main/java/accord/local/DurableBefore.java | 80 ++--
.../src/main/java/accord/local/MaxDecidedRX.java | 5 +-
accord-core/src/main/java/accord/local/Node.java | 9 +-
.../main/java/accord/local/RedundantBefore.java | 67 ++--
.../main/java/accord/local/RedundantStatus.java | 116 ++++--
.../main/java/accord/local/SafeCommandStore.java | 6 +-
.../main/java/accord/local/StoreParticipants.java | 15 +-
.../main/java/accord/local/cfk/CommandsForKey.java | 230 +++++++-----
.../src/main/java/accord/local/cfk/Pruning.java | 17 +-
.../java/accord/local/cfk/SafeCommandsForKey.java | 5 +-
.../src/main/java/accord/local/cfk/Serialize.java | 26 +-
.../src/main/java/accord/local/cfk/Updating.java | 16 +-
.../accord/local/durability/DurabilityRequest.java | 9 +-
.../accord/local/durability/DurabilityService.java | 27 +-
.../accord/local/durability/ShardDurability.java | 14 +-
.../src/main/java/accord/messages/Await.java | 2 +-
.../main/java/accord/messages/BeginRecovery.java | 20 +-
.../src/main/java/accord/messages/CheckStatus.java | 62 +--
.../main/java/accord/messages/InformDecided.java | 93 -----
.../main/java/accord/messages/InformDurable.java | 6 +-
.../src/main/java/accord/messages/MessageType.java | 1 -
.../src/main/java/accord/messages/Propagate.java | 21 +-
.../main/java/accord/messages/RecoverAwait.java | 3 +-
.../main/java/accord/messages/SetShardDurable.java | 14 +-
.../src/main/java/accord/primitives/Known.java | 1 +
.../main/java/accord/primitives/ProgressToken.java | 38 +-
.../src/main/java/accord/primitives/Status.java | 417 ++++++++++++++++++---
.../src/main/java/accord/primitives/Timestamp.java | 7 +-
.../src/main/java/accord/primitives/Txn.java | 73 ++--
.../src/main/java/accord/primitives/TxnId.java | 6 +-
.../src/main/java/accord/topology/Topologies.java | 11 +-
.../src/main/java/accord/topology/Topology.java | 43 ++-
.../main/java/accord/topology/TopologyManager.java | 7 +-
.../test/java/accord/impl/LocalListenersTest.java | 2 +-
.../test/java/accord/impl/RemoteListenersTest.java | 23 +-
.../src/test/java/accord/impl/basic/Cluster.java | 3 +-
.../java/accord/local/RedundantBeforeTest.java | 4 +-
.../test/java/accord/topology/TopologyUtils.java | 2 +-
.../src/test/java/accord/utils/AccordGens.java | 1 +
.../java/accord/maelstrom/TopologyFactory.java | 3 +-
66 files changed, 1201 insertions(+), 815 deletions(-)
diff --git a/accord-core/src/main/java/accord/api/ProgressLog.java b/accord-core/src/main/java/accord/api/ProgressLog.java
index 3b4d8764..e4ffeb99 100644
--- a/accord-core/src/main/java/accord/api/ProgressLog.java
+++ b/accord-core/src/main/java/accord/api/ProgressLog.java
@@ -29,17 +29,17 @@ import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.local.StoreParticipants;
import accord.primitives.SaveStatus;
-import accord.primitives.Status.Durability;
import accord.primitives.Participants;
import accord.primitives.Route;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
import accord.utils.SortedArrays;
import static accord.api.ProgressLog.BlockedUntil.Query.HOME;
import static accord.api.ProgressLog.BlockedUntil.Query.SHARD;
-import static accord.primitives.Status.Durability.Majority;
-import static accord.primitives.Status.Durability.NotDurable;
+import static accord.primitives.Status.Durability.HasOutcome.None;
+import static accord.primitives.Status.Durability.HasOutcome.Quorum;
import static accord.utils.SortedArrays.Search.FAST;
/**
@@ -76,14 +76,14 @@ public interface ProgressLog
enum BlockedUntil
{
- NotBlocked(HOME, HOME, SaveStatus.NotDefined, NotDurable),
+ NotBlocked(HOME, HOME, SaveStatus.NotDefined, None),
/**
* Wait for the transaction to decide its executeAt (or else decide to be invalidated).
*
* This also waits for a FullRoute to be known.
*/
- HasDecidedExecuteAt(HOME, HOME, SaveStatus.PreCommitted, NotDurable),
+ HasDecidedExecuteAt(HOME, HOME, SaveStatus.PreCommitted, None),
/**
* Wait for the transaction to be Committed, or guaranteed not to fast-path commit.
@@ -92,7 +92,7 @@ public interface ProgressLog
*
* This is used for transactions that may have used the coordinator optimisation.
*/
- CommittedOrNotFastPathCommit(SHARD, SHARD, SaveStatus.Committed, NotDurable, null),
+ CommittedOrNotFastPathCommit(SHARD, SHARD, SaveStatus.Committed, None, null),
/**
* Wait for the transaction to be Committed.
@@ -103,29 +103,29 @@ public interface ProgressLog
* This BlockedUntil is useful for remote listeners performing recovery that are waiting for transactions in
* the Accept phase that need to reach Committed to advance the recovery machine.
*/
- HasCommittedDeps(SHARD, SHARD, SaveStatus.Committed, NotDurable),
+ HasCommittedDeps(SHARD, SHARD, SaveStatus.Committed, None),
/**
* Wait for the transaction's dependencies to stabilise. This provides enough information
* to locally execute a transaction (if all the dependencies have applied).
*/
- HasStableDeps(SHARD, SHARD, SaveStatus.Stable, NotDurable),
+ HasStableDeps(SHARD, SHARD, SaveStatus.Stable, None),
/**
* Wait for all shards to be ReadyToExecute so that a recovery coordinator may make progress
*/
- CanCoordinateExecution(SHARD, SHARD, SaveStatus.ReadyToExecute, NotDurable),
+ CanCoordinateExecution(SHARD, SHARD, SaveStatus.ReadyToExecute, None),
/**
* Wait for the transaction to have enough information to apply.
* It does not need to be ready to apply yet.
*/
- CanApply(HOME, SHARD, SaveStatus.PreApplied, Majority),
+ CanApply(HOME, SHARD, SaveStatus.PreApplied, Quorum),
/**
* Wait for the transaction to be applied.
*/
- IsApplied(SHARD, SHARD, SaveStatus.Applied, NotDurable);
+ IsApplied(SHARD, SHARD, SaveStatus.Applied, None);
public enum Query { HOME, SHARD }
@@ -137,20 +137,20 @@ public interface ProgressLog
public final @Nullable Predicate<SaveStatus> additionallyUnblockedBy;
// have remote listeners wait for the Durability before responding
// this permits us to wait for only the home shard for CanApply
- public final Durability remoteDurability;
+ public final HasOutcome remoteOutcomeDurability;
- BlockedUntil(Query waitsOn, Query fetchFrom, SaveStatus unblockedFrom, Durability remoteDurability)
+ BlockedUntil(Query waitsOn, Query fetchFrom, SaveStatus unblockedFrom, HasOutcome remoteOutcomeDurability)
{
- this(waitsOn, fetchFrom, unblockedFrom, remoteDurability, null);
+ this(waitsOn, fetchFrom, unblockedFrom, remoteOutcomeDurability, null);
}
- BlockedUntil(Query waitsOn, Query fetchFrom, SaveStatus unblockedFrom, Durability remoteDurability, @Nullable Predicate<SaveStatus> additionallyUnblockedBy)
+ BlockedUntil(Query waitsOn, Query fetchFrom, SaveStatus unblockedFrom, HasOutcome remoteOutcomeDurability, @Nullable Predicate<SaveStatus> additionallyUnblockedBy)
{
this.waitsOn = waitsOn;
this.fetchFrom = fetchFrom;
this.unblockedFrom = unblockedFrom;
this.additionallyUnblockedBy = additionallyUnblockedBy;
- this.remoteDurability = remoteDurability;
+ this.remoteOutcomeDurability = remoteOutcomeDurability;
}
public long fetchEpoch(TxnId txnId, Timestamp executeAt)
@@ -181,11 +181,6 @@ public interface ProgressLog
*/
void update(SafeCommandStore safeStore, TxnId txnId, Command before, Command after, boolean force);
- /**
- * Record a remote notification that the command has been decided, so does not need to be recovered until ready to execute.
- */
- void decided(SafeCommandStore safeStore, TxnId txnId);
-
/**
* Process a remote asynchronous callback.
*/
@@ -242,7 +237,7 @@ public interface ProgressLog
class NoOpProgressLog implements ProgressLog
{
@Override public void update(SafeCommandStore safeStore, TxnId txnId, Command before, Command after, boolean force) {}
- @Override public void decided(SafeCommandStore safeStore, TxnId txnId) {}
+
@Override public void remoteCallback(SafeCommandStore safeStore, SafeCommand safeCommand, SaveStatus remoteStatus, int callbackId, Node.Id from) {}
@Override public void waiting(BlockedUntil blockedUntil, SafeCommandStore safeStore, SafeCommand blockedBy, Route<?> blockedOnRoute, Participants<?> blockedOnParticipants, StoreParticipants participants) {}
@Override public void invalidIfUncommitted(TxnId txnId) {}
diff --git a/accord-core/src/main/java/accord/api/ProtocolModifiers.java b/accord-core/src/main/java/accord/api/ProtocolModifiers.java
index 92f61c4e..bfe62eb8 100644
--- a/accord-core/src/main/java/accord/api/ProtocolModifiers.java
+++ b/accord-core/src/main/java/accord/api/ProtocolModifiers.java
@@ -33,11 +33,12 @@ import static accord.api.ProtocolModifiers.QuorumEpochIntersections.ChaseFixedPo
import static accord.api.ProtocolModifiers.QuorumEpochIntersections.ChaseFixedPoint.DoNotChase;
import static accord.api.ProtocolModifiers.QuorumEpochIntersections.Include.Owned;
import static accord.api.ProtocolModifiers.QuorumEpochIntersections.Include.Unsynced;
-import static accord.api.ProtocolModifiers.Toggles.DependencyElision.IF_DURABLE;
+import static accord.api.ProtocolModifiers.Toggles.DependencyElision.IF_DURABLY_COMMITTED;
import static accord.api.ProtocolModifiers.Toggles.InformOfDurability.ALL;
import static accord.api.ProtocolModifiers.Toggles.SendStableMessages.FOR_READS;
import static accord.api.ProtocolModifiers.Toggles.SendStableMessages.FOR_READS_OR_NONE_IF_FASTEXEC;
import static accord.primitives.Txn.Kind.EphemeralRead;
+import static accord.primitives.Txn.Kind.VisibilitySyncPoint;
/**
* Configure various protocol behaviours. Many of these switches are correctness impacting, and should not be touched.
@@ -232,18 +233,18 @@ public class ProtocolModifiers
markStaleIfCannotExecute = newMarkStaleIfCannotExecute;
}
- private static int transitiveDependenciesAreVisible = TinyEnumSet.encode(Txn.Kind.ExclusiveSyncPoint);
+ private static int transitiveDependenciesAreVisible = TinyEnumSet.encode(VisibilitySyncPoint);
public static boolean isTransitiveDependencyVisible(TxnId txnId) { return TinyEnumSet.contains(transitiveDependenciesAreVisible, txnId.kindOrdinal()); }
public static boolean isTransitiveDependencyVisible(Txn.Kind kind) { return TinyEnumSet.contains(transitiveDependenciesAreVisible, kind); }
public static void setTransitiveDependenciesAreVisible(Txn.Kind ... kinds)
{
int newTransitiveDependenciesAreVisible = TinyEnumSet.encode(kinds);
- Invariants.require(TinyEnumSet.contains(newTransitiveDependenciesAreVisible, Txn.Kind.ExclusiveSyncPoint));
+ Invariants.require(TinyEnumSet.contains(newTransitiveDependenciesAreVisible, Txn.Kind.VisibilitySyncPoint));
transitiveDependenciesAreVisible = newTransitiveDependenciesAreVisible;
}
- public enum DependencyElision { OFF, ON, IF_DURABLE }
- private static DependencyElision dependencyElision = IF_DURABLE;
+ public enum DependencyElision { OFF, ON, IF_DURABLY_COMMITTED, IF_DURABLY_PREAPPLIED }
+ private static DependencyElision dependencyElision = IF_DURABLY_COMMITTED;
public static DependencyElision dependencyElision() { return dependencyElision; }
public static void setDependencyElision(DependencyElision newDependencyElision) { dependencyElision = newDependencyElision; }
diff --git a/accord-core/src/main/java/accord/api/RemoteListeners.java b/accord-core/src/main/java/accord/api/RemoteListeners.java
index c6b4e867..28175e59 100644
--- a/accord-core/src/main/java/accord/api/RemoteListeners.java
+++ b/accord-core/src/main/java/accord/api/RemoteListeners.java
@@ -23,7 +23,7 @@ import accord.local.Node;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.primitives.SaveStatus;
-import accord.primitives.Status.Durability;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.TxnId;
/**
@@ -54,7 +54,7 @@ public interface RemoteListeners
/**
* CallbackId must be a non-negative integer
*/
- Registration register(TxnId txnId, SaveStatus awaitSaveStatus, Durability awaitDurability, Node.Id listener, int callbackId);
+ Registration register(TxnId txnId, SaveStatus awaitSaveStatus, HasOutcome awaitOutcomeDurability, Node.Id listener, int callbackId);
void notify(SafeCommandStore safeStore, SafeCommand safeCommand, Command prev);
class NoOpRemoteListeners implements RemoteListeners
@@ -65,7 +65,7 @@ public interface RemoteListeners
@Override public int done() { return 0; }
}
- @Override public Registration register(TxnId txnId, SaveStatus awaitSaveStatus, Durability awaitDurability, Node.Id listener, int callbackId) { return new NoOpRegistration();}
+ @Override public Registration register(TxnId txnId, SaveStatus awaitSaveStatus, HasOutcome awaitOutcomeDurability, Node.Id listener, int callbackId) { return new NoOpRegistration();}
@Override public void notify(SafeCommandStore safeStore, SafeCommand safeCommand, Command prev) {}
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
index c3321567..98e04767 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
@@ -164,7 +164,8 @@ public class CoordinateSyncPoint<R> extends CoordinatePreAccept<R>
else
{
TxnId withFlags = txnId;
- if (txnId.is(ExclusiveSyncPoint) && txnId.epoch() == executeAt.epoch())
+ Invariants.require(txnId.isSyncPoint());
+ if (txnId.epoch() == executeAt.epoch())
withFlags = txnId.addFlag(HLC_BOUND);
Deps deps = Deps.merge(oks.valuesAsNullableList(), oks.domainSize(), List::get, ok -> ok.deps);
node.agent().coordinatorEvents().onPreAccepted(txnId);
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java b/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
index adb9653a..4557db72 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinationAdapter.java
@@ -59,7 +59,6 @@ import static accord.local.durability.DurabilityService.SyncRemote.NoRemote;
import static accord.messages.Apply.Kind.Maximal;
import static accord.messages.Apply.Kind.Minimal;
import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
public interface CoordinationAdapter<R>
{
@@ -85,7 +84,7 @@ public interface CoordinationAdapter<R>
@Override
public <R> CoordinationAdapter<R> get(TxnId txnId, Kind kind)
{
- if (txnId.is(ExclusiveSyncPoint))
+ if (txnId.isSyncPoint())
{
// callback types are different, and we pass through the recovery adapter for sync points so should not invoke Continue
Invariants.require(kind == Recovery);
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java b/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
index 357987da..29a62937 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
@@ -52,8 +52,8 @@ import accord.utils.async.AsyncResult;
import accord.utils.async.AsyncResults.SettableResult;
import static accord.coordinate.CoordinationAdapter.Adapters.exclusiveSyncPoint;
-import static accord.primitives.Status.Durability.Majority;
-import static accord.primitives.Status.Durability.UniversalOrInvalidated;
+import static accord.primitives.Status.Durability.HasOutcome.Quorum;
+import static accord.primitives.Status.Durability.HasOutcome.Universal;
import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
public class ExecuteSyncPoint extends SettableResult<DurabilityResult> implements Callback<ReadReply>
@@ -116,7 +116,7 @@ public class ExecuteSyncPoint extends SettableResult<DurabilityResult> implement
node.agent().coordinatorEvents().onExecuting(syncPoint.syncId, null, syncPoint.waitFor, null);
SortedArrayList<Node.Id> contact = tracker.filterAndRecordFaulty();
// TODO (desired): special Apply message that doesn't resend deps if path=MEDIUM
- Txn txn = node.agent().emptySystemTxn(Txn.Kind.ExclusiveSyncPoint, syncPoint.syncId.domain());
+ Txn txn = node.agent().emptySystemTxn(syncPoint.syncId.kind(), syncPoint.syncId.domain());
Result result = txn.result(syncPoint.syncId, syncPoint.executeAt, null);
if (contact == null) tryFailure(new Exhausted(syncPoint.syncId, syncPoint.route.homeKey(), null));
else node.send(contact, to -> new ApplyThenWaitUntilApplied(to, tracker.topologies(), syncPoint.executeAt, tracker.topologies().currentEpoch(), syncPoint.route, syncPoint.syncId, txn, syncPoint.waitFor, syncPoint.route, null, result), executor, this);
@@ -234,11 +234,11 @@ public class ExecuteSyncPoint extends SettableResult<DurabilityResult> implement
if (result.achievedRemote == SyncRemote.All)
{
node.configService().reportEpochRetired(syncPoint.route.toRanges(), syncPoint.syncId.epoch() - 1);
- node.send(tracker.nodes(), new SetShardDurable(syncPoint, UniversalOrInvalidated));
+ node.send(tracker.nodes(), new SetShardDurable(syncPoint, Universal));
}
else if (result.achievedRemote == SyncRemote.Quorum)
{
- node.send(tracker.nodes(), new SetShardDurable(syncPoint, Majority));
+ node.send(tracker.nodes(), new SetShardDurable(syncPoint, Quorum));
}
else
{
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java b/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
index dec14bd0..9b0b9576 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
@@ -37,7 +37,7 @@ import accord.local.SequentialAsyncExecutor;
import accord.local.StoreParticipants;
import accord.messages.Accept;
import accord.messages.Commit;
-import accord.messages.InformDecided;
+import accord.messages.InformDurable;
import accord.messages.MessageType;
import accord.messages.ReadData;
import accord.messages.ReadData.CommitOrReadNack;
@@ -76,6 +76,7 @@ import static accord.messages.Commit.Kind.StableSlowPath;
import static accord.messages.Commit.Kind.StableWithTxnAndDeps;
import static accord.messages.ReadData.CommitOrReadNack.Waiting;
import static accord.primitives.SaveStatus.Stable;
+import static accord.primitives.Status.Durability.DurablyStable;
import static accord.primitives.Status.Phase.Execute;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
@@ -188,7 +189,7 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
if (!hasInformedDecidedOrSucceeded && (reply.isOk() || reply == Waiting))
{
if (RequestStatus.Success == stable.recordSuccess(from))
- informDecided();
+ informStable();
}
}
@@ -258,7 +259,7 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
else
{
if (!hasInformedDecidedOrSucceeded && stable.hasReachedQuorum())
- informDecided();
+ informStable();
callback.accept(null, failure);
}
}
@@ -268,7 +269,7 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
{
// send stable messages to everyone not yet contacted, and then inform decided, to avoid unnecessary recoveries
if (!hasInformedDecidedOrSucceeded && stable.hasReachedQuorum())
- informDecided();
+ informStable();
super.onSlowResponse(from);
}
@@ -280,14 +281,13 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
tryFinishOnFailure();
}
- private void informDecided()
+ private void informStable()
{
Invariants.require(stable.hasReachedQuorum());
hasInformedDecidedOrSucceeded = true;
- InformDecided.informHome(node, topologies, txnId, route);
+ InformDurable.informHome(node, topologies, txnId, route, executeAt, DurablyStable);
}
-
protected CoordinationAdapter<Result> adapter()
{
return node.coordinationAdapter(txnId, Standard);
diff --git a/accord-core/src/main/java/accord/coordinate/KeyBarriers.java b/accord-core/src/main/java/accord/coordinate/KeyBarriers.java
index 54ba8cda..c51021f2 100644
--- a/accord-core/src/main/java/accord/coordinate/KeyBarriers.java
+++ b/accord-core/src/main/java/accord/coordinate/KeyBarriers.java
@@ -132,7 +132,7 @@ public class KeyBarriers
return true;
SyncLocal knownLocal = status.compareTo(APPLIED) >= 0 ? Self : NoLocal;
- SyncRemote knownRemote = minDurability.compareTo(Status.Durability.MajorityOrInvalidated) >= 0 ? Quorum : NoRemote;
+ SyncRemote knownRemote = minDurability.isDurable() ? Quorum : NoRemote;
if (found != null && (found.knownRemote.compareTo(knownRemote) > 0 || found.knownRemote == knownRemote && found.knownLocal.compareTo(knownLocal) >= 0))
return true;
diff --git a/accord-core/src/main/java/accord/coordinate/MaybeRecover.java b/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
index 10aa851a..c0839c5f 100644
--- a/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
+++ b/accord-core/src/main/java/accord/coordinate/MaybeRecover.java
@@ -35,6 +35,7 @@ import accord.utils.UnhandledEnum;
import static accord.api.TraceEventType.RECOVER;
import static accord.coordinate.Infer.InvalidateAndCallback.locallyInvalidateAndCallback;
import static accord.messages.Commit.Invalidate.commitInvalidate;
+import static accord.primitives.Known.Outcome.Unknown;
import static accord.primitives.WithQuorum.HasQuorum;
/**
@@ -54,7 +55,6 @@ public class MaybeRecover extends CheckShards<Route<?>>
this.prevProgress = prevProgress;
this.callback = callback;
this.reportTo = reportTo;
- Invariants.expect(!prevProgress.durability.isDurableOrInvalidated());
}
public static Object maybeRecover(Node node, TxnId txnId, Infer.InvalidIf invalidIf, Route<?> someRoute, ProgressToken prevProgress, LatentStoreSelector reportTo, BiConsumer<Outcome, Throwable> callback)
@@ -67,15 +67,14 @@ public class MaybeRecover extends CheckShards<Route<?>>
@Override
protected boolean isSufficient(CheckStatusOk ok)
{
- // We don't accept a single truncated response - must have a quorum so we can make inferences about invalidation
- return !ok.map.hasTruncated() && (hasMadeProgress(ok) || ok.durability.isDurableOrInvalidated());
+ // We don't accept a single response if any are truncated - must have a quorum so we can make inferences about invalidation
+ return !merged.map.hasTruncated() && hasMadeProgress(ok);
}
public boolean hasMadeProgress(CheckStatusOk ok)
{
// 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);
+ return ok.durability.isDurable() || ok.isCoordinating || ok.toProgressToken().compareTo(prevProgress) > 0;
}
@Override
@@ -104,7 +103,6 @@ public class MaybeRecover extends CheckShards<Route<?>>
default: throw new UnhandledEnum(known.outcome());
case Unknown:
{
-
// ErasedOrInvalidated takes Unknown, and so permits invalidation to be initiated.
// This might prima facie seem unsafe, as ErasedOrInvalidated might mean the command
// has been executed and erased, in which case it is not safe to invalidate.
@@ -128,6 +126,17 @@ public class MaybeRecover extends CheckShards<Route<?>>
tracing.trace(null, "MaybeRecover found quorum of Unknown that did not permit invalidation; falling through.");
// fall through otherwise to recovery
}
+ case WasApply:
+ {
+ if (merged.durability.isDurable() && full.minMaxKnown(someRoute.homeKey()).outcome().isOrWasApply())
+ {
+ ProgressToken progressToken = full.toProgressToken();
+ if (tracing != null)
+ tracing.trace(null, "MaybeRecover found %s which need not be recovered; reporting %s", known.outcome(), progressToken);
+ callback.accept(progressToken, null);
+ break;
+ }
+ }
case Apply:
{
// we have included the home key, and one that witnessed the definition has responded, so it should also know the full route
@@ -149,10 +158,17 @@ public class MaybeRecover extends CheckShards<Route<?>>
}
break;
}
- 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
+ if (full.minMaxKnown(someRoute.homeKey()).outcome() == Unknown)
+ {
+ if (previouslyKnownToBeInvalidIf != full.invalidIf)
+ {
+ MaybeRecover.maybeRecover(node, txnId, full.invalidIf, someRoute, full.toProgressToken(), reportTo, callback);
+ break;
+ }
+ else Invariants.expect(false, "Expect home shard to know outcome before completing recovery");
+ }
ProgressToken progressToken = full.toProgressToken();
if (tracing != null)
tracing.trace(null, "MaybeRecover found %s which cannot be recovered; reporting %s", known.outcome(), progressToken);
diff --git a/accord-core/src/main/java/accord/coordinate/Persist.java b/accord-core/src/main/java/accord/coordinate/Persist.java
index cd0d4b01..155ea4a4 100644
--- a/accord-core/src/main/java/accord/coordinate/Persist.java
+++ b/accord-core/src/main/java/accord/coordinate/Persist.java
@@ -41,7 +41,7 @@ import accord.utils.Invariants;
import accord.utils.SortedArrays;
import static accord.coordinate.tracking.RequestStatus.Success;
-import static accord.primitives.Status.Durability.Majority;
+import static accord.primitives.Status.Durability.AllQuorums;
public abstract class Persist implements Callback<ApplyReply>
{
@@ -99,7 +99,7 @@ public abstract class Persist implements Callback<ApplyReply>
// since we should only invoke Persist with sendTo != route when the remainder of the route is already persisted and truncated
// but we make this explicit for the caller with informDurableOnDone
isDone = true;
- InformDurable.informDefault(node, topologies, txnId, route, ballot, executeAt, Majority);
+ InformDurable.informDefault(node, topologies, txnId, route, ballot, executeAt, AllQuorums);
}
case RaceWithRecovery:
// don't count this towards durability; otherwise it is possible (though very unlikely)
diff --git a/accord-core/src/main/java/accord/coordinate/Recover.java b/accord-core/src/main/java/accord/coordinate/Recover.java
index 4783f8fa..7d937271 100644
--- a/accord-core/src/main/java/accord/coordinate/Recover.java
+++ b/accord-core/src/main/java/accord/coordinate/Recover.java
@@ -399,7 +399,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
.intersecting(route, id -> !recoverOks.containsKey(id.node));
InferredFastPath fastPath;
if (txnId.hasPrivilegedCoordinator() && coordinatorInRecoveryQuorum) fastPath = Reject;
- else if (txnId.is(Txn.Kind.ExclusiveSyncPoint)) fastPath = Reject;
+ else if (txnId.isSyncPoint()) fastPath = Reject;
else fastPath = merge(
supersedingRejects(recoverOkList) ? Reject : Unknown,
tracker.inferFastPathDecision(txnId, extraCoordVotes, extraRejects)
diff --git a/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java b/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
index e802a9c4..a2254b98 100644
--- a/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
+++ b/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
@@ -57,7 +57,7 @@ import static accord.primitives.Known.Outcome.Apply;
import static accord.primitives.ProgressToken.APPLIED;
import static accord.primitives.ProgressToken.INVALIDATED;
import static accord.primitives.ProgressToken.TRUNCATED_DURABLE_OR_INVALIDATED;
-import static accord.primitives.Status.Durability.Majority;
+import static accord.primitives.Status.Durability.AllQuorums;
import static accord.topology.Topologies.SelectNodeOwnership.SLICE;
import static accord.topology.Topologies.SelectNodeOwnership.SHARE;
import static accord.utils.Invariants.illegalState;
@@ -246,7 +246,7 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
if (tracing != null)
tracing.trace(null, "RecoverWithRoute found Apply truncated at all shards; advancing Durability to at least Majority");
- propagate = full.merge(Majority);
+ propagate = full.merge(AllQuorums);
}
}
else
diff --git a/accord-core/src/main/java/accord/coordinate/tracking/DurabilityTracker.java b/accord-core/src/main/java/accord/coordinate/tracking/DurabilityTracker.java
index 79893abf..925b7e29 100644
--- a/accord-core/src/main/java/accord/coordinate/tracking/DurabilityTracker.java
+++ b/accord-core/src/main/java/accord/coordinate/tracking/DurabilityTracker.java
@@ -140,7 +140,7 @@ public class DurabilityTracker extends SimpleTracker<DurabilityTracker.Durabilit
public DurabilityTracker(Topologies topologies)
{
- super(topologies, DurabilityShardTracker[]::new, topologies.current().staleIds(), (p, i, s) -> new DurabilityShardTracker(p, s));
+ super(topologies, DurabilityShardTracker[]::new, topologies.staleOrRemovedIds(), (p, i, s) -> new DurabilityShardTracker(p, s));
failures = SortedListSet.noneOf(topologies.nodes());
waitingOnQuorum = waitingOnShards;
}
diff --git a/accord-core/src/main/java/accord/impl/AbstractConfigurationService.java b/accord-core/src/main/java/accord/impl/AbstractConfigurationService.java
index bf579e79..4781c337 100644
--- a/accord-core/src/main/java/accord/impl/AbstractConfigurationService.java
+++ b/accord-core/src/main/java/accord/impl/AbstractConfigurationService.java
@@ -392,6 +392,7 @@ public abstract class AbstractConfigurationService<EpochState extends AbstractCo
return;
}
+ logger.debug("Epoch {} received with isLoad={} and startSync={}", topology.epoch(), isLoad, startSync);
epochs.receive(topology);
for (Listener listener : listeners)
listener.onTopologyUpdate(topology, isLoad, startSync);
diff --git a/accord-core/src/main/java/accord/impl/DefaultRemoteListeners.java b/accord-core/src/main/java/accord/impl/DefaultRemoteListeners.java
index ddcf10ba..ffd64661 100644
--- a/accord-core/src/main/java/accord/impl/DefaultRemoteListeners.java
+++ b/accord-core/src/main/java/accord/impl/DefaultRemoteListeners.java
@@ -32,6 +32,7 @@ import accord.primitives.SaveStatus;
import accord.primitives.Status.Durability;
import accord.messages.Await.AsyncAwaitComplete;
import accord.primitives.Route;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.TxnId;
import accord.utils.Invariants;
@@ -83,9 +84,9 @@ public class DefaultRemoteListeners implements RemoteListeners
long[] listeners;
int listenerCount;
- StatusListeners(SaveStatus awaitSaveStatus, Durability awaitDurability, int[] waitingOn, int waitingOnCount, int listenerNodeId, int listenerCallbackId)
+ StatusListeners(SaveStatus awaitSaveStatus, HasOutcome awaitOutcomeDurability, int[] waitingOn, int waitingOnCount, int listenerNodeId, int listenerCallbackId)
{
- this.await = encodeAwait(awaitSaveStatus, awaitDurability);
+ this.await = encodeAwait(awaitSaveStatus, awaitOutcomeDurability);
this.waitingOn = waitingOn;
this.waitingOnCount = this.waitingOnSize = waitingOnCount;
this.listeners = new long[] { encodeListener(listenerNodeId, listenerCallbackId) };
@@ -343,14 +344,14 @@ public class DefaultRemoteListeners implements RemoteListeners
{
final TxnId txnId;
final SaveStatus awaitSaveStatus;
- final Durability awaitDurability;
+ final HasOutcome awaitDurability;
final Node.Id listeningNodeId;
final int callbackId;
int[] waitingOn = new int[4];
int count = 0;
- Register(TxnId txnId, SaveStatus awaitSaveStatus, Durability awaitDurability, Node.Id listeningNodeId, int callbackId)
+ Register(TxnId txnId, SaveStatus awaitSaveStatus, HasOutcome awaitDurability, Node.Id listeningNodeId, int callbackId)
{
this.txnId = txnId;
this.awaitSaveStatus = awaitSaveStatus;
@@ -418,7 +419,7 @@ public class DefaultRemoteListeners implements RemoteListeners
}
@Override
- public Registration register(TxnId txnId, SaveStatus awaitSaveStatus, Durability awaitDurability, Node.Id listener, int callbackId)
+ public Registration register(TxnId txnId, SaveStatus awaitSaveStatus, HasOutcome awaitDurability, Node.Id listener, int callbackId)
{
Invariants.requireArgument(callbackId >= 0);
return new Register(txnId, awaitSaveStatus, awaitDurability, listener, callbackId);
@@ -444,7 +445,7 @@ public class DefaultRemoteListeners implements RemoteListeners
if (awaitSaveStatus(listener.await).compareTo(newStatus) > 0)
return;
- if (awaitDurability(listener.await).compareTo(newDurability) > 0)
+ if (awaitDurability(listener.await).compareTo(newDurability.allShards()) > 0)
continue;
listener.removeWaitingOn(storeId);
@@ -485,7 +486,7 @@ public class DefaultRemoteListeners implements RemoteListeners
static
{
- Invariants.require(Durability.maxOrdinal() < 16);
+ Invariants.require(HasOutcome.maxEncoded() < 16);
}
private static SaveStatus awaitSaveStatus(int encodedAwait)
@@ -493,12 +494,12 @@ public class DefaultRemoteListeners implements RemoteListeners
return SaveStatus.forOrdinal(encodedAwait >>> 4);
}
- private static Durability awaitDurability(int encodedAwait)
+ private static HasOutcome awaitDurability(int encodedAwait)
{
- return Durability.forOrdinal(encodedAwait & 0xf);
+ return HasOutcome.forOrdinal(encodedAwait & 0xf);
}
- private static int encodeAwait(SaveStatus awaitSaveStatus, Durability awaitDurability)
+ private static int encodeAwait(SaveStatus awaitSaveStatus, HasOutcome awaitDurability)
{
return (awaitSaveStatus.ordinal() << 4) | awaitDurability.ordinal();
}
diff --git a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
index 30f1ab12..d7438d69 100644
--- a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
+++ b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
@@ -79,8 +79,8 @@ import accord.primitives.Routable.Domain;
import accord.primitives.RoutableKey;
import accord.primitives.Route;
import accord.primitives.Status;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.Timestamp;
-import accord.primitives.Txn;
import accord.primitives.Txn.Kind.Kinds;
import accord.primitives.TxnId;
import accord.primitives.Unseekables;
@@ -107,12 +107,11 @@ import static accord.primitives.SaveStatus.ReadyToExecute;
import static accord.primitives.SaveStatus.Vestigial;
import static accord.primitives.Status.Applied;
import static accord.primitives.Status.Committed;
+import static accord.primitives.Status.Durability.HasOutcome.Universal;
import static accord.primitives.Status.Durability.NotDurable;
-import static accord.primitives.Status.Durability.UniversalOrInvalidated;
import static accord.primitives.Status.Stable;
import static accord.primitives.Status.Truncated;
import static accord.primitives.Txn.Kind.EphemeralRead;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.utils.Invariants.illegalState;
import static java.lang.String.format;
@@ -378,7 +377,7 @@ public abstract class InMemoryCommandStore extends CommandStore
Cleanup cleanup = Cleanup.shouldCleanup(FULL, txnId, command.executeAtIfKnown(), command.saveStatus(), command.durability(), participants, unsafeGetRedundantBefore(), durableBefore());
Invariants.require(command.hasBeen(Applied)
|| cleanup.compareTo(Cleanup.TRUNCATE) >= 0
- || (durableBefore().min(txnId) != UniversalOrInvalidated &&
+ || (durableBefore().min(txnId) != Universal &&
((command.participants().stillExecutes() != null && command.participants().stillExecutes().isEmpty())
|| !Route.isFullRoute(command.route()))));
}
@@ -386,10 +385,10 @@ public abstract class InMemoryCommandStore extends CommandStore
}
@Override
- public void markShardDurable(SafeCommandStore safeStore, TxnId syncId, Ranges ranges, Status.Durability durability)
+ public void markShardDurable(SafeCommandStore safeStore, TxnId syncId, Ranges ranges, HasOutcome level)
{
- super.markShardDurable(safeStore, syncId, ranges, durability);
- if (durability.compareTo(UniversalOrInvalidated) >= 0)
+ super.markShardDurable(safeStore, syncId, ranges, level);
+ if (level == Universal)
markShardDurable(syncId, ranges);
}
@@ -890,7 +889,7 @@ public abstract class InMemoryCommandStore extends CommandStore
public void updateExclusiveSyncPoint(Command prev, Command updated, boolean force)
{
super.updateExclusiveSyncPoint(prev, updated, force);
- if (updated.txnId().kind() != Txn.Kind.ExclusiveSyncPoint || updated.txnId().domain() != Range || !updated.hasBeen(Applied) || (prev.hasBeen(Applied) && !force) || updated.hasBeen(Truncated)) return;
+ if (!updated.txnId().isSyncPoint() || updated.txnId().domain() != Range || !updated.hasBeen(Applied) || (prev.hasBeen(Applied) && !force) || updated.hasBeen(Truncated)) return;
Participants<?> covering = updated.participants().touches();
for (Map.Entry<TxnId, GlobalCommand> entry : commandStore().commands.headMap(updated.txnId(), false).entrySet())
@@ -900,7 +899,7 @@ public abstract class InMemoryCommandStore extends CommandStore
if (!command.hasBeen(Committed)) continue;
if (command.hasBeen(Applied)) continue;
if (txnId.is(EphemeralRead)) continue;
- Participants<?> intersecting = (txnId.is(ExclusiveSyncPoint) ? command.participants().owns(): command.participants().stillWaitsOn()).intersecting(covering, Minimal);
+ Participants<?> intersecting = (txnId.isSyncPoint() ? command.participants().owns(): command.participants().stillWaitsOn()).intersecting(covering, Minimal);
if (intersecting.isEmpty()) continue;
if (commandStore().unsafeGetRedundantBefore().locallyDefunct(command.txnId(), intersecting) == ALL) continue;
if (txnId.is(Key))
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 4a870064..e1b19e14 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
@@ -68,10 +68,11 @@ 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.RedundantStatus.Property.QUORUM_APPLIED;
import static accord.primitives.Routables.Slice.Minimal;
+import static accord.primitives.SaveStatus.Stable;
import static accord.primitives.Status.PreApplied;
import static accord.primitives.Status.PreCommitted;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.utils.ArrayBuffers.cachedAny;
import static accord.utils.btree.UpdateFunction.noOpReplace;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
@@ -124,7 +125,7 @@ public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStor
private final Object2ObjectHashMap<TxnId, PendingTask> pendingHome = new Object2ObjectHashMap<>();
private final Long2ObjectHashMap<Object> active = new Long2ObjectHashMap<>();
- private final Map<TxnId, StackTraceElement[]> debugDeleted = Invariants.debug() ? new Object2ObjectHashMap<>() : null;
+ private final Map<TxnId, Boolean> debugDeleted = Invariants.debug() ? new Object2ObjectHashMap<>() : null;
private static final Object[] EMPTY_RUN_BUFFER = new Object[0];
private static final RunInvoker[] EMPTY_AWAITING_EPOCH_BUFFER = new RunInvoker[0];
@@ -219,60 +220,36 @@ public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStor
if (!txnId.isVisible())
return;
- TxnState state = null;
Route<?> beforeRoute = before.route();
Route<?> afterRoute = after.route();
- if (force || (afterRoute != null && beforeRoute == null) || (after.durability().isDurableOrInvalidated() && !before.durability().isDurableOrInvalidated()))
- state = updateOrInitialiseHomeState(safeStore, after, get(txnId));
-
SaveStatus beforeSaveStatus = before.saveStatus();
SaveStatus afterSaveStatus = after.saveStatus();
- if (beforeSaveStatus == afterSaveStatus && !force)
- return;
-
- if (state == null)
- state = get(txnId);
-
- if (state == null)
- return;
-
- state.waiting().record(this, afterSaveStatus);
- if (state.isHomeInitialised())
- updateHomeState(safeStore, state, before, after);
- }
-
- @Override
- public void decided(SafeCommandStore safeStore, TxnId txnId)
- {
- TxnState state = get(txnId);
- if (state != null && state.isHomeInitialised())
- state.home().atLeast(safeStore, this, Decided, NoneExpected);
- }
- private void updateHomeState(SafeCommandStore safeStore, TxnState state, Command before, Command after)
- {
- switch (after.saveStatus())
+ boolean recordWaiting = force || beforeSaveStatus != afterSaveStatus;
+ boolean updatedDurability = force || !before.durability().isAtLeast(after.durability());
+ boolean updateWaiting = updatedDurability && afterSaveStatus.compareTo(after.durability().durablyUnblocked().unblockedFrom) < 0;
+ boolean update = recordWaiting || updatedDurability || (afterRoute != null && beforeRoute == null);
+ if (update)
{
- case Stable:
- if (!after.acceptedOrCommitted().equals(Ballot.ZERO) || (before != null && before.saveStatus() == SaveStatus.Committed))
- state.home().atLeast(safeStore, this, Decided, NoneExpected);
- default:
- // fall-through to default handler, which simply postpones any scheduled coordination attempt if we witness another coordination attempt in the meantime
- if (state.homeProgress() == Queued && (before == null ? after.promised().compareTo(Ballot.ZERO) > 0 : (after.promised().compareTo(before.promised()) > 0) || after.acceptedOrCommitted().compareTo(before.acceptedOrCommitted()) > 0))
- {
- clearPendingAndActive(Home, state.txnId);
- state.home().set(safeStore, this, state.phase(), Queued);
- }
- break;
- case ReadyToExecute:
- case PreApplied:
- state.home().atLeast(safeStore, this, ReadyToExecute, Queued);
- break;
+ TxnState state = get(txnId);
+ if (updateWaiting)
+ {
+ if (state == null)
+ state = insert(txnId);
+ state.waiting().setBlockedUntil(safeStore, this, after.durability().durablyUnblocked());
+ }
+ state = updateHomeState(safeStore, before, after, state);
+
+ if (recordWaiting && state != null)
+ state.waiting().record(this, afterSaveStatus);
}
}
- private TxnState updateOrInitialiseHomeState(SafeCommandStore safeStore, Command after, @Nullable TxnState state)
+ private TxnState updateHomeState(SafeCommandStore safeStore, @Nullable Command before, Command after, @Nullable TxnState state)
{
+ if (state != null && state.isHomeDone())
+ return state;
+
Route<?> route = after.route();
if (after.durability().isDurableOrInvalidated())
{
@@ -292,26 +269,43 @@ public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStor
if (route == null)
return state; // we don't know if we're the home shard
+ Invariants.require(!after.durability().isDurableOrInvalidated());
TxnId txnId = after.txnId();
- RoutingKey homeKey = route.homeKey();
- Ranges coordinateRanges = safeStore.coordinateRanges(txnId);
- boolean isHome = coordinateRanges.contains(homeKey);
- state = get(txnId);
- if (isHome)
+ if (state == null || !state.isHomeInitialised())
{
+ RoutingKey homeKey = route.homeKey();
+ Ranges coordinateRanges = safeStore.coordinateRanges(txnId);
+ if (!coordinateRanges.contains(homeKey))
+ {
+ if (state != null)
+ state.setHomeDone(this);
+ return state;
+ }
if (state == null)
+ {
+ if (txnId.compareTo(safeStore.redundantBefore().get(homeKey).maxBound(QUORUM_APPLIED)) < 0)
+ return null;
state = insert(txnId);
-
- Invariants.require(!after.durability().isDurableOrInvalidated());
- if (!state.isHomeInitialised())
- state.set(safeStore, this, Undecided, Queued); // initialise
+ }
+ state.set(safeStore, this, Undecided, Queued); // initialise
}
- else if (state != null)
+
+ CoordinatePhase phase = state.phase();
+ if (phase.compareTo(ReadyToExecute) < 0)
{
- // not home shard
- state.setHomeDone(this);
+ if (after.saveStatus().compareTo(SaveStatus.ReadyToExecute) >= 0)
+ {
+ state.home().atLeast(safeStore, this, ReadyToExecute, Queued);
+ }
+ else if (phase.compareTo(Decided) < 0)
+ {
+ // TODO (desired): the second condition expression should simply imply the first (by updating durability earlier in processing)
+ boolean isDecided = after.durability().isDurablyStable()
+ || (after.saveStatus().compareTo(Stable) >= 0 && (!after.acceptedOrCommitted().equals(Ballot.ZERO) || (before != null && before.saveStatus() == SaveStatus.Committed)));
+ if (isDecided)
+ state.home().atLeast(safeStore, this, Decided, NoneExpected);
+ }
}
-
return state;
}
@@ -439,7 +433,7 @@ public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStor
{
stateMap = BTreeRemoval.<TxnId, TxnState>remove(stateMap, (id, s) -> id.compareTo(s.txnId), txnId);
if (debugDeleted != null)
- debugDeleted.put(txnId, Thread.currentThread().getStackTrace());
+ debugDeleted.put(txnId, Boolean.TRUE);
}
@Override
@@ -456,9 +450,9 @@ public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStor
if (!blockedBy.txnId().isVisible())
return;
-
Command command = blockedBy.current();
if (command == null) command = uninitialised(blockedBy.txnId());
+
SaveStatus saveStatus = command.saveStatus();
Invariants.require(saveStatus.compareTo(blockedUntil.unblockedFrom) < 0);
@@ -494,8 +488,8 @@ public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStor
command = blockedBy.incidentalUpdate(update);
// TODO (required): tighten up ExclusiveSyncPoint range bounds
- Invariants.require((command.txnId().is(ExclusiveSyncPoint) ? safeStore.ranges().all()
- : safeStore.ranges().allSince(command.txnId().epoch())
+ Invariants.require((command.txnId().isSyncPoint() ? safeStore.ranges().all()
+ : safeStore.ranges().allSince(command.txnId().epoch())
).intersects(command.participants().hasTouched()));
// TODO (desired): consider triggering a preemption of existing coordinator (if any) in some circumstances;
@@ -509,7 +503,7 @@ public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStor
state.waiting().setBlockedUntil(safeStore, this, blockedUntil);
// in case progress log hasn't been updated (e.g. bug on replay), force an update to the command's state since we're about to wait on it
if (!state.isHomeInitialised() && command.route() != null)
- updateOrInitialiseHomeState(safeStore, command, state);
+ updateHomeState(safeStore, null, command, state);
}
@Override
diff --git a/accord-core/src/main/java/accord/impl/progresslog/HomeState.java b/accord-core/src/main/java/accord/impl/progresslog/HomeState.java
index 0bdaac7f..b6f4f7eb 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/HomeState.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/HomeState.java
@@ -31,7 +31,8 @@ import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.primitives.ProgressToken;
import accord.primitives.Route;
-import accord.primitives.Status;
+import accord.primitives.Status.Durability;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.TxnId;
import accord.utils.Invariants;
@@ -147,14 +148,15 @@ abstract class HomeState extends WaitingState
Invariants.require(command.durability() != null);
// TODO (expected): when invalidated, safer to maintain HomeState until known to be globally invalidated
// TODO (expected): validate that we clear HomeState when we receive a Durable reply, to replace the token check logic
- Invariants.require(!command.durability().isDurableOrInvalidated(), "Command is durable or invalidated, but we have not cleared the ProgressLog");
+ Invariants.expect(!command.durability().isDurableOrInvalidated(), "Command is durable or invalidated, but we have not cleared the ProgressLog");
if (Route.isFullRoute(command.route()))
{
- Status.Durability min = safeStore.durableBefore().min(txnId, command.route());
- if (min.isDurableOrInvalidated())
+ HasOutcome min = safeStore.durableBefore().min(txnId, command.route());
+ if (min.isDurable())
{
if (tracing != null)
tracing.trace(safeStore.commandStore(), "DurableBefore records %s; terminating home state", min);
+ safeCommand.incidentalUpdate(command.updateDurability(command.durability().mergeMax(Durability.UniversalOrInvalidated)));
setHomeDone(instance);
return;
}
@@ -207,11 +209,23 @@ abstract class HomeState extends WaitingState
if (prevProgressToken != null)
token = token.merge(prevProgressToken);
- if (token.durability.isDurableOrInvalidated())
+ if (token.outcome.isDurableOrInvalidated())
{
if (tracing != null)
tracing.trace(safeStore.commandStore(), "Callback: progress token %s reports durable; marking home state done.", token);
state.setHomeDoneAndMaybeRemove(instance);
+ if (token.outcome.compareTo(command.durability().allShardsOrInvalidated()) >= 0)
+ {
+ Durability newDurability = null;
+ switch (token.outcome)
+ {
+ case Quorum: newDurability = Durability.AllQuorums; break;
+ case Universal: newDurability = Durability.Universal; break;
+ case UniversalOrInvalidated: newDurability = Durability.UniversalOrInvalidated; break;
+ }
+ if (newDurability != null)
+ safeCommand.incidentalUpdate(command.updateDurability(command.durability().mergeMax(newDurability)));
+ }
}
else
{
diff --git a/accord-core/src/main/java/accord/impl/progresslog/SavedProgressToken.java b/accord-core/src/main/java/accord/impl/progresslog/SavedProgressToken.java
index 0b3fea45..802d73d9 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/SavedProgressToken.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/SavedProgressToken.java
@@ -27,7 +27,7 @@ class SavedProgressToken extends ProgressToken
public SavedProgressToken(TxnId txnId, ProgressToken copy)
{
- super(copy.durability, copy.status, copy.promised, copy.isAccepted);
+ super(copy.outcome, copy.status, copy.promised, copy.isAccepted);
this.txnId = txnId;
}
diff --git a/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java b/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java
index d31846a3..21910a92 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java
@@ -27,6 +27,7 @@ import accord.api.Tracing;
import accord.coordinate.AsynchronousAwait;
import accord.coordinate.FetchData;
import accord.coordinate.FetchRoute;
+import accord.coordinate.Infer;
import accord.local.Command;
import accord.local.CommandStores.IncludingSpecificStoreSelector;
import accord.local.CommandStores.RangesForEpoch;
@@ -413,6 +414,7 @@ abstract class WaitingState extends BaseTxnState
{
if (tracing != null)
tracing.trace(owner.commandStore, "Blocked until %s. Fetching route from %s", blockedUntil, maxContactable);
+ // TODO (required): pass in InvalidIf
fetchRoute(owner, blockedUntil, txnId, maxContactable);
return;
}
@@ -440,12 +442,14 @@ abstract class WaitingState extends BaseTxnState
// including the home shard to get us to at least PreCommitted where we can safely wait on individual shards
if (tracing != null)
tracing.trace(owner.commandStore, "Blocked until %s; not currently decided. Fetching from %s for epochs [%d..%d].", blockedUntil, slicedRoute, lowEpoch, highEpoch);
- fetch(owner, blockedUntil, txnId, executeAt, slicedRoute, slicedRoute.withHomeKey(), route);
+ fetch(owner, blockedUntil, txnId, invalidIf(), executeAt, slicedRoute, slicedRoute.withHomeKey(), route);
return;
}
// the awaitRoute may be only the home shard, if that is sufficient to indicate the fetchRoute will be able to answer our query;
// the fetchRoute may also be only the home shard, if that is sufficient to answer our query (e.g. for executeAt)
+ // TODO (expected): this handles range transactions very poorly, as a range may be split amongst multiple shards but we cannot wait for them async independently
+ // we probably want to deterministically split ranges into shards on the epochs we care about and treat them separately
Route<?> awaitRoute = awaitRoute(slicedRoute, blockedUntil);
Route<?> fetchRoute = fetchRoute(slicedRoute, awaitRoute, blockedUntil, safeStore, lowEpoch, txnId, highEpoch, route);
if (awaitRoute.isHomeKeyOnlyRoute())
@@ -453,7 +457,7 @@ abstract class WaitingState extends BaseTxnState
// at this point we can switch to polling as we know someone has the relevant state
if (tracing != null)
tracing.trace(owner.commandStore, "Blocked until %s. Fetching %s%s for epochs [%d..%d].", blockedUntil, slicedRoute, slicedRoute == fetchRoute ? "" : " from " + fetchRoute, lowEpoch, highEpoch);
- fetch(owner, blockedUntil, txnId, executeAt, slicedRoute, fetchRoute, route);
+ fetch(owner, blockedUntil, txnId, invalidIf(), executeAt, slicedRoute, fetchRoute, route);
return;
}
@@ -486,7 +490,7 @@ abstract class WaitingState extends BaseTxnState
// all of the shards we are awaiting have been processed and found at least one replica that has the state needed to answer our query
// at this point we can switch to polling as we know someone has the relevant state
- fetch(owner, blockedUntil, txnId, executeAt, slicedRoute, fetchRoute, route);
+ fetch(owner, blockedUntil, txnId, invalidIf(), executeAt, slicedRoute, fetchRoute, route);
return;
}
@@ -819,12 +823,12 @@ abstract class WaitingState extends BaseTxnState
owner.start(invoker, FetchRoute.fetchRoute(owner.node(), txnId, contactable, new IncludingSpecificStoreSelector(owner.commandStore.id()), invoker));
}
- static void fetch(DefaultProgressLog owner, BlockedUntil blockedUntil, TxnId txnId, Timestamp executeAt, Route<?> slicedRoute, Route<?> fetchRoute, Route<?> maxRoute)
+ static void fetch(DefaultProgressLog owner, BlockedUntil blockedUntil, TxnId txnId, Infer.InvalidIf invalidIf, Timestamp executeAt, Route<?> slicedRoute, Route<?> fetchRoute, Route<?> maxRoute)
{
Invariants.require(!slicedRoute.isEmpty());
// we MUSt allocate before calling withEpoch to register cancellation, as async
CallbackInvoker<BlockedUntil, FetchData.FetchResult> invoker = invokeWaitingCallback(owner, txnId, blockedUntil, WaitingState::fetchCallback);
- owner.start(invoker, FetchData.fetchSpecific(blockedUntil.unblockedFrom.known, owner.node(), txnId, executeAt, fetchRoute, maxRoute, new IncludingSpecificStoreSelector(owner.commandStore.id()), invoker));
+ owner.start(invoker, FetchData.fetchSpecific(blockedUntil.unblockedFrom.known, owner.node(), txnId, invalidIf, executeAt, fetchRoute, maxRoute, new IncludingSpecificStoreSelector(owner.commandStore.id()), invoker));
}
void awaitHomeKey(DefaultProgressLog owner, BlockedUntil blockedUntil, TxnId txnId, Timestamp executeAt, Route<?> route)
diff --git a/accord-core/src/main/java/accord/local/Cleanup.java b/accord-core/src/main/java/accord/local/Cleanup.java
index b8cfb582..9137abbc 100644
--- a/accord-core/src/main/java/accord/local/Cleanup.java
+++ b/accord-core/src/main/java/accord/local/Cleanup.java
@@ -26,10 +26,10 @@ import accord.primitives.Participants;
import accord.primitives.Route;
import accord.primitives.SaveStatus;
import accord.primitives.Status.Durability;
+import accord.primitives.Status.Durability.HasOutcome;
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;
@@ -50,9 +50,8 @@ import static accord.primitives.SaveStatus.TruncatedApply;
import static accord.primitives.SaveStatus.TruncatedApplyWithOutcome;
import static accord.primitives.SaveStatus.Uninitialised;
import static accord.primitives.SaveStatus.Vestigial;
-import static accord.primitives.Status.Durability.MajorityOrInvalidated;
-import static accord.primitives.Status.Durability.NotDurable;
-import static accord.primitives.Status.Durability.UniversalOrInvalidated;
+import static accord.primitives.Status.Durability.HasOutcome.None;
+import static accord.primitives.Status.Durability.HasOutcome.Universal;
import static accord.primitives.Status.PreCommitted;
import static accord.primitives.Status.Truncated;
import static accord.primitives.Timestamp.Flag.HLC_BOUND;
@@ -200,36 +199,24 @@ public enum Cleanup
if (!redundant.all(LOCALLY_DURABLE_TO_DATA_STORE))
return truncateWithOutcome(txnId, input, redundant, min);
+ HasOutcome test = durability.allShards();
if (saveStatus.compareTo(Vestigial) >= 0)
{
// we can't use durability from an Invalidated record to decide if we can erase/expunge,
// as we don't know that this has been persisted at all shards.
// Similarly, vestigial/erased records don't know their etymology, and may derive from Invalidate
- durability = NotDurable;
+ test = None;
}
- Durability test;
- if (durability.compareTo(UniversalOrInvalidated) >= 0) test = durability;
- else test = Durability.max(durability, durableBefore.min(txnId, participants.route()));
+ if (test != Universal)
+ test = Durability.HasOutcome.max(test, durableBefore.min(txnId, participants.route()));
- switch (test)
- {
- default: throw new UnhandledEnum(durability);
- case Local:
- case NotDurable:
- case ShardUniversal:
- // TODO (required): consider how we guarantee not to break recovery of other shards if a majority on this shard are PRE_BOOTSTRAP
- // (if the condition is false and we fall through to removing Outcome)
- case MajorityOrInvalidated:
- case Majority:
- return truncateWithOutcome(txnId, input, redundant, min);
-
- case UniversalOrInvalidated:
- case Universal:
- if (redundant.all(GC_BEFORE))
- return erase(txnId, min);
- return truncate(txnId, min);
- }
+ if (test != Universal)
+ return truncateWithOutcome(txnId, input, redundant, min);
+
+ if (redundant.all(GC_BEFORE))
+ return erase(txnId, min);
+ return truncate(txnId, min);
}
private static Cleanup cleanupWithoutFullRoute(Input input, TxnId txnId, SaveStatus saveStatus, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
@@ -265,7 +252,7 @@ public enum Cleanup
if (ownStatus.any(LOCALLY_APPLIED))
return invalidate(txnId);
- // TODO (desired): safe to use MAJORITY_APPLIED, LOCALLY_REDUNDANT?
+ // TODO (desired): safe to use QUORUM_APPLIED, LOCALLY_REDUNDANT?
// TODO (required): can we guarantee we will always eventually obtain a covering route if others are garbage collecting?
if (isCoveringRoute && ownStatus.all(SHARD_APPLIED, LOCALLY_REDUNDANT))
return vestigial(txnId);
@@ -276,7 +263,7 @@ public enum Cleanup
private static boolean expunge(TxnId txnId, @Nullable Timestamp executeAt, @Nullable SaveStatus saveStatus, @Nullable StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
// since we cannot guarantee to witness participants for all records, we must use the global durableBefore bounds
- if (txnId.is(Any) && durableBefore.min(txnId).compareTo(MajorityOrInvalidated) < 0)
+ if (txnId.is(Any) && !durableBefore.min(txnId).isDurable())
return false;
TxnId minGcBefore = redundantBefore.minGcBefore();
diff --git a/accord-core/src/main/java/accord/local/Command.java b/accord-core/src/main/java/accord/local/Command.java
index 50c55110..f8a418de 100644
--- a/accord-core/src/main/java/accord/local/Command.java
+++ b/accord-core/src/main/java/accord/local/Command.java
@@ -44,7 +44,6 @@ import accord.primitives.Status;
import accord.primitives.Status.Durability;
import accord.primitives.Status.Phase;
import accord.primitives.Timestamp;
-import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.primitives.Unseekables;
import accord.primitives.Writes;
@@ -70,10 +69,8 @@ import static accord.primitives.SaveStatus.AcceptedInvalidate;
import static accord.primitives.SaveStatus.Erased;
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;
-import static accord.primitives.Status.Durability.Local;
import static accord.primitives.Status.Durability.NotDurable;
import static accord.primitives.Status.Durability.ShardUniversal;
import static accord.primitives.Status.Durability.UniversalOrInvalidated;
@@ -216,7 +213,7 @@ public abstract class Command implements ICommand
@Override
public final Durability durability()
{
- return Command.durability(durability, saveStatus());
+ return durability;
}
public final SaveStatus saveStatus()
@@ -484,7 +481,7 @@ public abstract class Command implements ICommand
{
Invariants.requireArgument(executeAt != null);
Invariants.requireArgument(saveStatus.status == Status.Truncated);
- return Durability.mergeAtLeast(durability, ShardUniversal);
+ return durability.mergeMax(ShardUniversal);
}
public static Truncated invalidated(Command command)
@@ -1074,7 +1071,7 @@ public abstract class Command implements ICommand
public static Initialise initialise(SafeCommandStore safeStore, TxnId txnId, Timestamp executeAt, StoreParticipants participants, PartialDeps deps)
{
Initialise initialise = new Initialise(txnId, participants, executeAt, deps);
- if (txnId.is(Txn.Kind.ExclusiveSyncPoint))
+ if (txnId.isSyncPoint())
{
CommandStores.RangesForEpoch rangesForEpoch = safeStore.ranges();
long prevEpoch = Long.MAX_VALUE;
@@ -1090,7 +1087,7 @@ public abstract class Command implements ICommand
TxnId id = upd.txnId(idx);
// because we use RX as RedundantBefore bounds, we must not let an RX on a closing range
// get ahead of one that isn't closed but has overlapping transactions (else we may erroneously treat as redundant)
- if (id.epoch() >= epoch && (id.is(Txn.Kind.ExclusiveSyncPoint) || id.epoch() < maxEpoch))
+ if (id.epoch() >= epoch && (id.isSyncPoint() || id.epoch() < maxEpoch))
initialise.initialise(idx);
});
int lbound = deps.rangeDeps.txnIdCount();
@@ -1648,7 +1645,6 @@ public abstract class Command implements ICommand
// TODO (expected): enable this invariant; requires rethinking how we update StoreParticipants on PreCommitted
// which must be done carefully as we cannot mess with touches()/Deps as the relationship there must be maintained
// for state machine correctness
-// Invariants.require(participants.executes() != null);
case ExecuteAtProposed:
Invariants.require(executeAt != null);
int c = executeAt.compareTo(validate.txnId());
@@ -1692,7 +1688,6 @@ public abstract class Command implements ICommand
case Abort:
Invariants.require(validate.durability().isMaybeInvalidated(), "%s is not invalidated", validate.durability());
case Unknown:
- Invariants.require(validate.durability() != Local);
case Erased:
case WasApply:
Invariants.require(writes == null, "Writes exist for %s", validate);
@@ -1720,13 +1715,6 @@ public abstract class Command implements ICommand
return validate;
}
- public static Durability durability(Durability durability, SaveStatus status)
- {
- if (durability == NotDurable && status.compareTo(SaveStatus.PreApplied) >= 0 && status.compareTo(Vestigial) < 0)
- return Local; // not necessary anywhere, but helps for logical consistency
- return durability;
- }
-
private static boolean isSameClass(Command command, Class<? extends Command> klass)
{
return command.getClass() == klass;
diff --git a/accord-core/src/main/java/accord/local/CommandStore.java b/accord-core/src/main/java/accord/local/CommandStore.java
index 376ff236..c27de992 100644
--- a/accord-core/src/main/java/accord/local/CommandStore.java
+++ b/accord-core/src/main/java/accord/local/CommandStore.java
@@ -48,7 +48,7 @@ import accord.local.RedundantBefore.Bounds;
import accord.local.RedundantStatus.SomeStatus;
import accord.primitives.Ranges;
import accord.primitives.Routables;
-import accord.primitives.Status.Durability;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
import accord.primitives.Unseekables;
@@ -66,13 +66,13 @@ import static accord.local.RedundantStatus.SomeStatus.LOCALLY_APPLIED_ONLY;
import static accord.local.RedundantStatus.SomeStatus.LOCALLY_DURABLE_TO_COMMAND_STORE_ONLY;
import static accord.local.RedundantStatus.SomeStatus.LOCALLY_DURABLE_TO_DATA_STORE_ONLY;
import static accord.local.RedundantStatus.SomeStatus.LOCALLY_WITNESSED_ONLY;
-import static accord.local.RedundantStatus.SomeStatus.MAJORITY_APPLIED_ONLY;
+import static accord.local.RedundantStatus.SomeStatus.QUORUM_APPLIED_ONLY;
import static accord.local.RedundantStatus.SomeStatus.PRE_BOOTSTRAP_ONLY;
import static accord.local.RedundantStatus.SomeStatus.SHARD_APPLIED_ONLY;
import static accord.primitives.AbstractRanges.UnionMode.MERGE_ADJACENT;
import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Timestamp.Flag.HLC_BOUND;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
+import static accord.primitives.Txn.Kind.VisibilitySyncPoint;
import static accord.utils.Invariants.nonNull;
/**
@@ -464,7 +464,7 @@ public abstract class CommandStore implements SequentialAsyncExecutor
final void markExclusiveSyncPoint(SafeCommandStore safeStore, TxnId txnId, Ranges ranges)
{
// TODO (desired): narrow ranges to those that are owned
- Invariants.requireArgument(txnId.is(ExclusiveSyncPoint));
+ Invariants.requireArgument(txnId.isSyncPoint());
RejectBefore newRejectBefore = rejectBefore != null ? rejectBefore : new RejectBefore();
newRejectBefore = RejectBefore.add(newRejectBefore, ranges, txnId);
unsafeSetRejectBefore(newRejectBefore);
@@ -478,7 +478,7 @@ public abstract class CommandStore implements SequentialAsyncExecutor
final void markExclusiveSyncPointLocallyApplied(SafeCommandStore safeStore, TxnId txnId, Ranges ranges)
{
// TODO (desired): narrow ranges to those that are owned
- Invariants.requireArgument(txnId.is(ExclusiveSyncPoint));
+ Invariants.requireArgument(txnId.isSyncPoint());
RedundantBefore addNow = RedundantBefore.create(ranges, txnId, LOCALLY_APPLIED_ONLY);
safeStore.upsertRedundantBefore(addNow);
RedundantBefore addOnDataStoreDurable = RedundantBefore.create(ranges, txnId, LOCALLY_DURABLE_TO_DATA_STORE_ONLY);
@@ -579,7 +579,7 @@ public abstract class CommandStore implements SequentialAsyncExecutor
private void ensureReadyToCoordinate(long epoch, Ranges ranges)
{
TxnId minForEpoch = TxnId.minForEpoch(epoch);
- node.durability().close("[" + this + " Epoch " + epoch + ']', minForEpoch, ranges, 1, TimeUnit.HOURS)
+ node.durability().close("[" + this + " Epoch " + epoch + ']', VisibilitySyncPoint, minForEpoch, ranges, 1, TimeUnit.HOURS)
.begin((success, fail) -> {
if (fail != null)
{
@@ -625,12 +625,12 @@ public abstract class CommandStore implements SequentialAsyncExecutor
}
// TODO (expected): we can immediately truncate dependencies locally once an exclusiveSyncPoint applies, we don't need to wait for the whole shard
- public void markShardDurable(SafeCommandStore safeStore, TxnId globalSyncId, Ranges durableRanges, Durability durability)
+ public void markShardDurable(SafeCommandStore safeStore, TxnId globalSyncId, Ranges durableRanges, HasOutcome durability)
{
- if (durability.compareTo(Durability.MajorityOrInvalidated) < 0)
+ if (!durability.isDurable())
return;
- SomeStatus status = durability.compareTo(Durability.UniversalOrInvalidated) >= 0 ? SHARD_APPLIED_ONLY : MAJORITY_APPLIED_ONLY;
+ SomeStatus status = durability.isUniversal() ? SHARD_APPLIED_ONLY : QUORUM_APPLIED_ONLY;
final Ranges slicedRanges = durableRanges.slice(safeStore.ranges().allUntil(globalSyncId.epoch()), Minimal);
TxnId locallyRedundantBefore = safeStore.redundantBefore().min(slicedRanges, Bounds::maxLocallyAppliedBefore);
RedundantBefore addNow = RedundantBefore.create(slicedRanges, globalSyncId, status);
@@ -661,7 +661,7 @@ public abstract class CommandStore implements SequentialAsyncExecutor
protected void updatedRedundantBefore(SafeCommandStore safeStore, RedundantBefore added)
{
TxnId clearWaitingBefore = redundantBefore.minShardAndLocallyAppliedBefore();
- TxnId clearAllBefore = TxnId.min(clearWaitingBefore, durableBefore().min.majorityBefore);
+ TxnId clearAllBefore = TxnId.min(clearWaitingBefore, durableBefore().min.quorumBefore);
progressLog.clearBefore(safeStore, clearWaitingBefore, clearAllBefore);
listeners.clearBefore(this, clearWaitingBefore);
}
@@ -732,6 +732,7 @@ public abstract class CommandStore implements SequentialAsyncExecutor
protected final void markSynced(SafeCommandStore safeStore, TxnId syncId, Ranges ranges)
{
+ Invariants.require(syncId.is(VisibilitySyncPoint));
RedundantBefore addRedundantBefore = RedundantBefore.create(ranges, syncId, LOCALLY_WITNESSED_ONLY);
safeStore.upsertRedundantBefore(addRedundantBefore);
@@ -786,6 +787,10 @@ public abstract class CommandStore implements SequentialAsyncExecutor
// make sure no in-progress bootstrap attempts will override the stale since for commands whose staleness bounds are unknown
staleUntilAtLeast = Timestamp.max(bootstrapBeganAt.lastKey(), staleUntilAtLeast);
}
+
+ if (ranges.isEmpty())
+ return;
+
agent.onStale(staleSince, ranges);
RedundantBefore addRedundantBefore = RedundantBefore.createStale(ranges, staleUntilAtLeast);
diff --git a/accord-core/src/main/java/accord/local/CommandSummaries.java b/accord-core/src/main/java/accord/local/CommandSummaries.java
index 0fefbbdb..58b1ebd5 100644
--- a/accord-core/src/main/java/accord/local/CommandSummaries.java
+++ b/accord-core/src/main/java/accord/local/CommandSummaries.java
@@ -47,7 +47,6 @@ import static accord.local.LoadKeysFor.RECOVERY;
import static accord.local.MaxDecidedRX.minDecidedDependencyId;
import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Status.Durability.NotDurable;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.primitives.Txn.Kind.Nothing;
public interface CommandSummaries
@@ -70,7 +69,7 @@ public interface CommandSummaries
enum IsDep
{
- IS_COORD_DEP, IS_NOT_COORD_DEP, NOT_ELIGIBLE, IS_STABLE_DEP, IS_NOT_STABLE_DEP;
+ IS_COORD_DEP, IS_NOT_COORD_DEP, NOT_ELIGIBLE, IS_PROPOSED_OR_STABLE_DEP, IS_NOT_PROPOSED_OR_STABLE_DEP;
private static final IsDep[] IS_DEPS = values();
}
@@ -80,7 +79,7 @@ public interface CommandSummaries
private static final int IS_DEP_SHIFT = 3;
private static final int IS_DEP_MASK = 0x7;
private static final int DURABILITY_SHIFT = 6;
- private static final int DURABILITY_MASK = 0x7;
+ private static final int DURABILITY_MASK = (1 << Durability.TOTAL_ENCODING_BITS) - 1;
final @Nonnull Timestamp executeAt;
final int encoded;
@@ -97,7 +96,7 @@ public interface CommandSummaries
super(txnId);
this.participants = participants;
this.executeAt = executeAt.equals(txnId) ? this : executeAt;
- this.encoded = status.ordinal() | (dep == null ? Integer.MIN_VALUE : (dep.ordinal() << IS_DEP_SHIFT)) | (durability.ordinal() << DURABILITY_SHIFT);
+ this.encoded = status.ordinal() | (dep == null ? Integer.MIN_VALUE : (dep.ordinal() << IS_DEP_SHIFT)) | (durability.encoded() << DURABILITY_SHIFT);
}
private Summary(@Nonnull TxnId txnId, @Nonnull Timestamp executeAt, int encoded, Unseekables<?> participants)
@@ -122,7 +121,7 @@ public interface CommandSummaries
public Durability durability()
{
- return Durability.forOrdinal((encoded >>> DURABILITY_SHIFT) & DURABILITY_MASK);
+ return Durability.forEncoded((encoded >>> DURABILITY_SHIFT) & DURABILITY_MASK);
}
public boolean is(SummaryStatus summaryStatus)
@@ -197,10 +196,10 @@ public interface CommandSummaries
{
Invariants.require(primaryTxnId != null);
TxnId minTxnId = redundantBefore.min(keysOrRanges, Bounds::gcBefore);
- Timestamp maxTxnId = loadKeysFor == RECOVERY || !primaryTxnId.is(ExclusiveSyncPoint) ? Timestamp.MAX : primaryTxnId;
+ Timestamp maxTxnId = loadKeysFor == RECOVERY || !primaryTxnId.isSyncPoint() ? Timestamp.MAX : primaryTxnId;
TxnId findAsDep = loadKeysFor == RECOVERY ? primaryTxnId : null;
Kinds kinds = primaryTxnId.witnesses().or(loadKeysFor == RECOVERY ? primaryTxnId.witnessedBy() : Nothing);
- if (!primaryTxnId.is(Txn.Kind.ExclusiveSyncPoint))
+ if (!primaryTxnId.is(Txn.Kind.ExclusiveSyncPoint)) // the main distinction between RX and RV is that RV doesn't filter out decided transactions
maxDecidedRX = null;
return factory.create(redundantBefore, maxDecidedRX, primaryTxnId, keysOrRanges, kinds, minTxnId, maxTxnId, findAsDep);
}
@@ -248,7 +247,7 @@ public interface CommandSummaries
// the caller must manage mutual exclusion for this method, but not to any others
public void maybeRecordFutureRx(Summary summary)
{
- if (summary.is(ExclusiveSyncPoint) && summary.compareTo(primaryTxnId) > 0 && (summary.is(SummaryStatus.STABLE) || summary.is(APPLIED)))
+ if (summary.isSyncPoint() && summary.compareTo(primaryTxnId) > 0 && (summary.is(SummaryStatus.STABLE) || summary.is(APPLIED)))
{
minVisitedFutureRX = ReducingRangeMap.merge(minVisitedFutureRX, ReducingRangeMap.create(summary.participants.toRanges(), summary.plainTxnId()), TxnId::min);
maxRx = minVisitedFutureRX.foldlWithDefault(searchKeysOrRanges, TxnId::max, TxnId.MAX, TxnId.NONE);
@@ -274,7 +273,7 @@ public interface CommandSummaries
if (txnId.compareTo(minTxnId) < 0 || txnId.compareTo(maxTxnId) > 0)
return false;
- if (txnId.is(ExclusiveSyncPoint))
+ if (txnId.isSyncPoint())
{
if (txnId.compareTo(maxRx) >= 0)
return false;
@@ -283,7 +282,7 @@ public interface CommandSummaries
return false;
}
- boolean mayFilterAsDecided = maxDecidedRX != null && (txnId.is(ExclusiveSyncPoint) || (durability != null && durability.isDurableOrInvalidated()));
+ boolean mayFilterAsDecided = maxDecidedRX != null && (txnId.isSyncPoint() || (durability != null && durability.isDurablyCommitted()));
if (!mayFilterAsDecided)
return true;
@@ -317,7 +316,7 @@ public interface CommandSummaries
if (txnId.compareTo(minTxnId) < 0 || txnId.compareTo(maxTxnId) > 0)
return null;
- boolean mayFilterAsDecided = maxDecidedRX != null && (durability.isDurableOrInvalidated() || txnId.is(ExclusiveSyncPoint));
+ boolean mayFilterAsDecided = maxDecidedRX != null && (txnId.isSyncPoint() || durability.isDurablyCommitted());
if (mayFilterAsDecided && minDecidedId != null && txnId.compareTo(minDecidedId) < 0)
return null;
@@ -364,8 +363,8 @@ public interface CommandSummaries
boolean isAnyDep = index >= 0 && partialDeps.isStable(index)
&& partialDeps.participants(index).containsAll(intersecting);
- isDep = isAnyDep ? (isCoordDeps ? IsDep.IS_COORD_DEP : IsDep.IS_STABLE_DEP)
- : (isCoordDeps ? IsDep.IS_NOT_COORD_DEP : IsDep.IS_NOT_STABLE_DEP);
+ isDep = isAnyDep ? (isCoordDeps ? IsDep.IS_COORD_DEP : IsDep.IS_PROPOSED_OR_STABLE_DEP)
+ : (isCoordDeps ? IsDep.IS_NOT_COORD_DEP : IsDep.IS_NOT_PROPOSED_OR_STABLE_DEP);
}
}
diff --git a/accord-core/src/main/java/accord/local/Commands.java b/accord-core/src/main/java/accord/local/Commands.java
index 2de2fc4e..5d8dea54 100644
--- a/accord-core/src/main/java/accord/local/Commands.java
+++ b/accord-core/src/main/java/accord/local/Commands.java
@@ -26,6 +26,7 @@ import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import accord.api.ProtocolModifiers.Toggles.DependencyElision;
import accord.api.Result;
import accord.api.RoutingKey;
import accord.api.VisibleForImplementation;
@@ -61,7 +62,9 @@ import accord.utils.async.AsyncChains;
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.IF_DURABLY_COMMITTED;
+import static accord.api.ProtocolModifiers.Toggles.DependencyElision.IF_DURABLY_PREAPPLIED;
+import static accord.api.ProtocolModifiers.Toggles.DependencyElision.OFF;
import static accord.api.ProtocolModifiers.Toggles.dependencyElision;
import static accord.api.ProtocolModifiers.Toggles.markStaleIfCannotExecute;
import static accord.local.Cleanup.Input.FULL;
@@ -118,7 +121,6 @@ import static accord.primitives.Status.Stable;
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.ExclusiveSyncPoint;
import static accord.primitives.Txn.Kind.Write;
import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
import static accord.utils.Invariants.illegalState;
@@ -1091,13 +1093,15 @@ public class Commands
return true;
}
- public static Command setDurability(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, Durability durability, @Nullable Timestamp executeAt)
+ public static Command setDurability(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, Durability addDurability, @Nullable Timestamp executeAt)
{
final Command command = safeCommand.current();
if (command.is(Truncated))
return command;
- if (command.durability().compareTo(durability) >= 0)
+ Durability oldDurability = command.durability();
+ Durability newDurability = oldDurability.mergeMax(addDurability);
+ if (newDurability == oldDurability)
return command;
Command updated = supplementParticipants(safeStore, safeCommand, participants);
@@ -1105,30 +1109,30 @@ public class Commands
if (executeAt != null && command.status().hasBeen(Committed) && !command.executeAt().equals(executeAt))
safeStore.agent().onInconsistentTimestamp(command, command.asCommitted().executeAt(), executeAt);
- if (command.durability().compareTo(durability) < 0)
+ updated = safeCommand.update(safeStore, updated.updateDurability(newDurability));
+ TxnId txnId = command.txnId();
+ DependencyElision updates = OFF;
+ if (newDurability.isDurable() && !oldDurability.isDurable()) updates = IF_DURABLY_PREAPPLIED;
+ else if (newDurability.isDurablyCommitted() && !oldDurability.isDurablyCommitted()) updates = IF_DURABLY_COMMITTED;
+ if (updates.compareTo(dependencyElision()) >= 0 && CommandsForKey.manages(txnId))
{
- updated = safeCommand.update(safeStore, updated.updateDurability(durability));
- TxnId txnId = command.txnId();
- if (dependencyElision() == IF_DURABLE && CommandsForKey.manages(txnId))
+ AbstractUnseekableKeys keys = (AbstractUnseekableKeys)updated.participants().touches();
+ PreLoadContext context = PreLoadContext.contextFor(keys, INCR, WRITE, "Set Durable");
+ PreLoadContext execute = safeStore.canExecute(context);
+ if (execute != null)
+ {
+ setDurable(safeStore, execute, txnId, newDurability);
+ }
+ if (execute != context)
{
- AbstractUnseekableKeys keys = (AbstractUnseekableKeys)updated.participants().touches();
- PreLoadContext context = PreLoadContext.contextFor(keys, INCR, WRITE, "Set Durable");
- PreLoadContext execute = safeStore.canExecute(context);
if (execute != null)
- {
- setDurable(safeStore, execute, txnId);
- }
- if (execute != context)
- {
- if (execute != null)
- context = contextFor(keys.without(execute.keys()), INCR, WRITE, "Set Durable");
-
- Invariants.require(!context.keys().isEmpty());
- safeStore = safeStore; // prevent accidental usage inside lambda
- safeStore.commandStore().execute(context, safeStore0 -> {
- setDurable(safeStore0, safeStore0.context(), txnId);
- }, safeStore.commandStore().agent);
- }
+ context = contextFor(keys.without(execute.keys()), INCR, WRITE, "Set Durable");
+
+ Invariants.require(!context.keys().isEmpty());
+ safeStore = safeStore; // prevent accidental usage inside lambda
+ safeStore.commandStore().execute(context, safeStore0 -> {
+ setDurable(safeStore0, safeStore0.context(), txnId, newDurability);
+ }, safeStore.commandStore().agent);
}
}
@@ -1139,10 +1143,10 @@ public class Commands
return updated;
}
- private static void setDurable(SafeCommandStore safeStore, PreLoadContext context, TxnId txnId)
+ private static void setDurable(SafeCommandStore safeStore, PreLoadContext context, TxnId txnId, Durability durability)
{
for (RoutingKey key : (AbstractUnseekableKeys)context.keys())
- safeStore.get(key).setDurable(txnId);
+ safeStore.get(key).setDurable(txnId, durability);
}
static class NotifyWaitingOn implements PreLoadContext, Consumer<SafeCommandStore>
@@ -1313,7 +1317,7 @@ public class Commands
boolean remove = status.all(LOCALLY_REDUNDANT);
// TODO (required): consider this logic again, incl. whether it is even needed
- if (remove && waitingSafe.txnId().is(ExclusiveSyncPoint) && depId.is(ExclusiveSyncPoint))
+ if (remove && waitingSafe.txnId().isSyncPoint() && depId.isSyncPoint())
remove = status.all(LOCALLY_SYNCED) || status.all(PRE_BOOTSTRAP_OR_STALE);
if (!remove)
diff --git a/accord-core/src/main/java/accord/local/DepsCalculator.java b/accord-core/src/main/java/accord/local/DepsCalculator.java
index c7cb4db0..5c95c3c9 100644
--- a/accord-core/src/main/java/accord/local/DepsCalculator.java
+++ b/accord-core/src/main/java/accord/local/DepsCalculator.java
@@ -58,7 +58,7 @@ public class DepsCalculator extends Deps.Builder implements CommandSummaries.Act
boolean include(Durability durability, Unseekable keyOrRange, TxnId depId)
{
- if (durability.isDurable() || depId.is(ExclusiveSyncPoint))
+ if (durability.isDurablyCommitted() || depId.isSyncPoint())
{
if (absoluteMinDecidedId != null && depId.compareTo(absoluteMinDecidedId) < 0)
return false;
@@ -135,13 +135,14 @@ public class DepsCalculator extends Deps.Builder implements CommandSummaries.Act
TxnId maxRedundantBefore = redundant.maxTxnId(null);
if (maxRedundantBefore != null && maxRedundantBefore.compareTo(executeAt) >= 0)
{
- Invariants.require(maxRedundantBefore.is(ExclusiveSyncPoint));
+ Invariants.require(maxRedundantBefore.isSyncPoint());
return null;
}
}
// NOTE: ExclusiveSyncPoint *relies* on STARTED_BEFORE to ensure it reports a dependency on *every* earlier TxnId that may execute (before or after it).
MinDependencyCalculator minDepCalc = null;
+ // the main difference between RX and RV is whether we apply this filtering
if (txnId.is(ExclusiveSyncPoint)) minDepCalc = new MinDependencyCalculator(safeStore.maxDecidedRX(), touches, txnId);
safeStore.visit(touches, executeAt, txnId.witnesses(), this, executeAt.equals(txnId) ? null : txnId, minDepCalc);
Deps result = super.build();
diff --git a/accord-core/src/main/java/accord/local/DurableBefore.java b/accord-core/src/main/java/accord/local/DurableBefore.java
index 61382732..45b658e3 100644
--- a/accord-core/src/main/java/accord/local/DurableBefore.java
+++ b/accord-core/src/main/java/accord/local/DurableBefore.java
@@ -24,8 +24,7 @@ import javax.annotation.Nullable;
import accord.api.RoutingKey;
import accord.primitives.AbstractRanges;
-import accord.primitives.Participants;
-import accord.primitives.Status.Durability;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.TxnId;
import accord.primitives.Unseekables;
import accord.utils.Invariants;
@@ -35,9 +34,9 @@ import accord.utils.ReducingRangeMap;
import accord.utils.async.AsyncResult;
import accord.utils.async.AsyncResults;
-import static accord.primitives.Status.Durability.MajorityOrInvalidated;
-import static accord.primitives.Status.Durability.NotDurable;
-import static accord.primitives.Status.Durability.UniversalOrInvalidated;
+import static accord.primitives.Status.Durability.HasOutcome.None;
+import static accord.primitives.Status.Durability.HasOutcome.Quorum;
+import static accord.primitives.Status.Durability.HasOutcome.Universal;
public class DurableBefore extends ReducingRangeMap<DurableBefore.Entry>
{
@@ -59,13 +58,13 @@ public class DurableBefore extends ReducingRangeMap<DurableBefore.Entry>
public static final Entry MAX = new Entry(TxnId.MAX, TxnId.MAX);
public static final Entry NONE = new Entry(TxnId.NONE, TxnId.NONE);
- public final @Nonnull TxnId majorityBefore, universalBefore;
+ public final @Nonnull TxnId quorumBefore, universalBefore;
- public Entry(@Nonnull TxnId majority, @Nonnull TxnId universalBefore)
+ public Entry(@Nonnull TxnId quorum, @Nonnull TxnId universal)
{
- Invariants.requireArgument(majority.compareTo(universalBefore) >= 0, "majority %s < universal %s", majority, universalBefore);
- this.majorityBefore = majority;
- this.universalBefore = universalBefore;
+ Invariants.requireArgument(quorum.compareTo(universal) >= 0, "quorum %s < universal %s", quorum, universal);
+ this.quorumBefore = quorum;
+ this.universalBefore = universal;
}
public static Entry max(Entry a, Entry b)
@@ -80,33 +79,33 @@ public class DurableBefore extends ReducingRangeMap<DurableBefore.Entry>
private static Entry reduce(Entry a, Entry b, BiFunction<TxnId, TxnId, TxnId> reduce)
{
- TxnId majority = reduce.apply(a.majorityBefore, b.majorityBefore);
+ TxnId majority = reduce.apply(a.quorumBefore, b.quorumBefore);
TxnId universal = reduce.apply(a.universalBefore, b.universalBefore);
- if (majority == a.majorityBefore && universal == a.universalBefore)
+ if (majority == a.quorumBefore && universal == a.universalBefore)
return a;
- if (majority.equals(b.majorityBefore) && universal.equals(b.universalBefore))
+ if (majority.equals(b.quorumBefore) && universal.equals(b.universalBefore))
return b;
return new Entry(majority, universal);
}
- public Durability get(TxnId txnId)
+ public HasOutcome get(TxnId txnId)
{
- if (txnId.compareTo(majorityBefore) < 0)
- return txnId.compareTo(universalBefore) < 0 ? UniversalOrInvalidated : MajorityOrInvalidated;
- return NotDurable;
+ if (txnId.compareTo(quorumBefore) < 0)
+ return txnId.compareTo(universalBefore) < 0 ? Universal : Quorum;
+ return None;
}
- static Durability mergeMin(Entry entry, @Nullable Durability prev, TxnId txnId)
+ static HasOutcome mergeMin(Entry entry, @Nullable HasOutcome prev, TxnId txnId)
{
- Durability next = entry.get(txnId);
+ HasOutcome next = entry.get(txnId);
return prev != null && prev.compareTo(next) <= 0 ? prev : next;
}
- static Durability mergeMax(Entry entry, Durability prev, TxnId txnId)
+ static HasOutcome mergeMax(Entry entry, HasOutcome prev, TxnId txnId)
{
- Durability next = entry.get(txnId);
+ HasOutcome next = entry.get(txnId);
return prev != null && prev.compareTo(next) >= 0 ? prev : next;
}
@@ -117,14 +116,14 @@ public class DurableBefore extends ReducingRangeMap<DurableBefore.Entry>
public boolean equals(Entry that)
{
- return this.majorityBefore.equals(that.majorityBefore)
+ return this.quorumBefore.equals(that.quorumBefore)
&& this.universalBefore.equals(that.universalBefore);
}
@Override
public String toString()
{
- return "(majority=" + majorityBefore + ",universal=" + universalBefore + ")";
+ return "(majority=" + quorumBefore + ",universal=" + universalBefore + ")";
}
}
@@ -172,9 +171,9 @@ public class DurableBefore extends ReducingRangeMap<DurableBefore.Entry>
return ReducingIntervalMap.merge(a, b, DurableBefore.Entry::max, Builder::new);
}
- public Durability min(TxnId txnId, Unseekables<?> unseekables)
+ public HasOutcome min(TxnId txnId, Unseekables<?> unseekables)
{
- return notDurableIfNull(foldlWithDefault(unseekables, Entry::mergeMin, Entry.NONE, null, txnId, test -> test == NotDurable));
+ return notDurableIfNull(foldlWithDefault(unseekables, Entry::mergeMin, Entry.NONE, null, txnId, test -> test == None));
}
public Entry minEntry(Unseekables<?> unseekables)
@@ -182,44 +181,39 @@ public class DurableBefore extends ReducingRangeMap<DurableBefore.Entry>
return foldlWithDefault(unseekables, Entry::min, Entry.NONE, Entry.MAX);
}
- public Durability max(TxnId txnId, Unseekables<?> unseekables)
+ public HasOutcome max(TxnId txnId, Unseekables<?> unseekables)
{
- return notDurableIfNull(foldl(unseekables, Entry::mergeMax, null, txnId, test -> test == UniversalOrInvalidated));
+ return notDurableIfNull(foldl(unseekables, Entry::mergeMax, null, txnId, test -> test == Universal));
}
- public Durability get(TxnId txnId, RoutingKey participant)
+ public HasOutcome get(TxnId txnId, RoutingKey participant)
{
DurableBefore.Entry entry = get(participant);
- return entry == null ? NotDurable : entry.get(txnId);
+ return entry == null ? None : entry.get(txnId);
}
public boolean isUniversal(TxnId txnId, RoutingKey participant)
{
- return get(txnId, participant) == UniversalOrInvalidated;
+ return get(txnId, participant) == Universal;
}
- public boolean isSomeShardDurable(TxnId txnId, Participants<?> participants, Durability durability)
- {
- return max(txnId, participants).compareTo(durability) >= 0;
- }
-
- public Durability min(TxnId txnId)
+ public HasOutcome min(TxnId txnId)
{
if (min.universalBefore.compareTo(txnId) > 0)
- return UniversalOrInvalidated;
- if (min.majorityBefore.compareTo(txnId) > 0)
- return MajorityOrInvalidated;
- return NotDurable;
+ return Universal;
+ if (min.quorumBefore.compareTo(txnId) > 0)
+ return Quorum;
+ return None;
}
public long maxEpoch()
{
- return foldl((e, v) -> TxnId.max(v, TxnId.max(e.majorityBefore, e.universalBefore)), TxnId.NONE, i -> false).epoch();
+ return foldl((e, v) -> TxnId.max(v, TxnId.max(e.quorumBefore, e.universalBefore)), TxnId.NONE, i -> false).epoch();
}
- private static Durability notDurableIfNull(Durability status)
+ private static HasOutcome notDurableIfNull(HasOutcome status)
{
- return status == null ? NotDurable : status;
+ return status == null ? None : status;
}
static class Builder extends AbstractBoundariesBuilder<RoutingKey, Entry, DurableBefore>
diff --git a/accord-core/src/main/java/accord/local/MaxDecidedRX.java b/accord-core/src/main/java/accord/local/MaxDecidedRX.java
index 5b73c236..d17dd744 100644
--- a/accord-core/src/main/java/accord/local/MaxDecidedRX.java
+++ b/accord-core/src/main/java/accord/local/MaxDecidedRX.java
@@ -24,7 +24,6 @@ import accord.api.VisibleForImplementation;
import accord.primitives.Range;
import accord.primitives.Routable.Domain;
import accord.primitives.Routables;
-import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.primitives.Unseekable;
import accord.primitives.Unseekables;
@@ -72,7 +71,7 @@ public class MaxDecidedRX extends ReducingRangeMap<TxnId>
public @Nullable TxnId minDecidedDependencyId(Unseekables<?> keysOrRanges, TxnId txnId)
{
- Invariants.require(txnId.is(Txn.Kind.ExclusiveSyncPoint));
+ Invariants.require(txnId.isSyncPoint());
// first check max, as if this is later we don't know that we can safely filter
TxnId maxDecidedId = max(keysOrRanges);
if (maxDecidedId.compareTo(txnId) < 0)
@@ -83,7 +82,7 @@ public class MaxDecidedRX extends ReducingRangeMap<TxnId>
@VisibleForImplementation
public @Nullable TxnId minDecidedDependencyId(Unseekable keyOrRange, TxnId txnId)
{
- Invariants.require(txnId.is(Txn.Kind.ExclusiveSyncPoint));
+ Invariants.require(txnId.isSyncPoint());
if (keyOrRange.domain() == Domain.Key)
{
TxnId minMaxDecidedId = get((RoutingKey) keyOrRange);
diff --git a/accord-core/src/main/java/accord/local/Node.java b/accord-core/src/main/java/accord/local/Node.java
index 971d76aa..3a927373 100644
--- a/accord-core/src/main/java/accord/local/Node.java
+++ b/accord-core/src/main/java/accord/local/Node.java
@@ -261,7 +261,7 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
public AsyncResult<Void> unsafeStart()
{
EpochReady ready = onTopologyUpdateInternal(configService.currentTopology(), false);
- ready.coordinate.invokeIfSuccess(() -> this.topology.onEpochSyncComplete(id, topology.epoch()));
+ ready.coordinate.invokeIfSuccess(() -> this.topology.onEpochSyncComplete(id, ready.epoch));
configService.acknowledgeEpoch(ready, false);
return ready.metadata;
}
@@ -296,7 +296,7 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
DurableBefore newDurableBefore = DurableBefore.merge(durableBefore, addDurableBefore);
// TODO (required): it is possible for this invariant to be breached if topologies are received out of order.
// We should not update min past the max known epoch.
- Invariants.require(newDurableBefore.min.majorityBefore.compareTo(durableBefore.min.majorityBefore) >= 0,
+ Invariants.require(newDurableBefore.min.quorumBefore.compareTo(durableBefore.min.quorumBefore) >= 0,
"Previous durable before: %s, new: %s", durableBefore, newDurableBefore);
minDurableBefore = DurableBefore.merge(minDurableBefore, addDurableBefore);
@@ -382,7 +382,8 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
if (topology.epoch() <= this.topology.epoch())
return AsyncResults.success(null);
EpochReady ready = onTopologyUpdateInternal(topology, startSync);
- ready.coordinate.invokeIfSuccess(() -> this.topology.onEpochSyncComplete(id, topology.epoch()));
+ long epoch = topology.epoch();
+ ready.coordinate.invokeIfSuccess(() -> this.topology.onEpochSyncComplete(id, epoch)).begin(agent);
configService.acknowledgeEpoch(ready, startSync);
return ready.coordinate;
}
@@ -767,7 +768,7 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
private static TxnId newTxnId(long epoch, long now, Txn.Kind rw, Domain domain, Cardinality cardinality, int flags, Node.Id node)
{
Invariants.require(domain == Key || rw != Write, "Range writes not supported without forwarding uniqueHlc information to WaitingOn for direct dependencies");
- Invariants.require(domain == Range || rw != Txn.Kind.ExclusiveSyncPoint, "Key ExclusiveSyncPoint not supported without improvements to CommandsForKey for managing execution");
+ Invariants.require(domain == Range || !rw.isSyncPoint, "Key ExclusiveSyncPoint not supported without improvements to CommandsForKey for managing execution");
TxnId txnId = new TxnId(epoch, now, flags, rw, domain, cardinality, node);
Invariants.require((txnId.lsb & (0xffff & ~TxnId.IDENTITY_FLAGS)) == 0);
return txnId;
diff --git a/accord-core/src/main/java/accord/local/RedundantBefore.java b/accord-core/src/main/java/accord/local/RedundantBefore.java
index 07653fd7..c697c42f 100644
--- a/accord-core/src/main/java/accord/local/RedundantBefore.java
+++ b/accord-core/src/main/java/accord/local/RedundantBefore.java
@@ -80,7 +80,6 @@ import static accord.local.RedundantStatus.matchesMask;
import static accord.local.RedundantStatus.toAll;
import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Timestamp.Flag.SHARD_BOUND;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.utils.ArrayBuffers.cachedAny;
import static accord.utils.ArrayBuffers.cachedShorts;
import static accord.utils.Invariants.illegalState;
@@ -160,7 +159,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
// OR we may be able to safely overwrite them with some better invariants and adequate testing
public final TxnId[] bounds;
// two entries per bound, first for equality (LE) matches, second for inequality (LT) matches
- public final short[] statuses;
+ private final short[] statuses;
private transient final long maxBoundEpoch, maxBoundHlc;
public transient final TxnId depBound;
@@ -179,6 +178,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
{
super(startEpoch, endEpoch, maxBound(bounds, statuses, PRE_BOOTSTRAP), maxBound(bounds, statuses, GC_BEFORE),
maxBound(bounds, statuses, LOCALLY_APPLIED));
+ Invariants.require(statuses.length == bounds.length * 2);
this.range = range;
this.bounds = bounds;
this.statuses = statuses;
@@ -187,11 +187,16 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
this.maxBoundEpoch = bounds.length == 0 ? 0 : bounds[0].epoch();
this.maxBoundHlc = bounds.length == 0 ? 0 : bounds[0].hlc();
this.depBound = depBound(bounds, statuses);
- checkMinBoundOrRX(bounds);
+ checkMinBoundOrSyncPoint(bounds);
requireStrictlyOrdered(Comparator.reverseOrder(), bounds);
require(isShardBound(gcBefore) || isMinBound(gcBefore));
}
+ public final int status(int index)
+ {
+ return statuses[index] & 0xFFFF;
+ }
+
public static Bounds create(Range range, TxnId bound, SomeStatus status, @Nullable Timestamp staleUntilAtLeast)
{
return create(range, Long.MIN_VALUE, Long.MAX_VALUE, bound, status, staleUntilAtLeast);
@@ -199,7 +204,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
public static Bounds create(Range range, long startEpoch, long endEpoch, TxnId bound, SomeStatus status, @Nullable Timestamp staleUntilAtLeast)
{
- return new Bounds(range, startEpoch, endEpoch, new TxnId[] { bound }, new short[] { (short) (status.encoded & ONLY_LE_MASK), status.encoded }, staleUntilAtLeast);
+ return new Bounds(range, startEpoch, endEpoch, new TxnId[] { bound }, new short[] { (short) (status.encoded & ONLY_LE_MASK), (short)status.encoded }, staleUntilAtLeast);
}
private static TxnId depBound(TxnId[] bounds, short[] statuses)
@@ -210,15 +215,15 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
return depBound.addFlag(SHARD_BOUND);
}
- private static void checkMinBoundOrRX(TxnId ... txnIds)
+ private static void checkMinBoundOrSyncPoint(TxnId ... txnIds)
{
for (TxnId txnId : txnIds)
- checkMinBoundOrRX(txnId);
+ checkMinBoundOrSyncPoint(txnId);
}
- private static void checkMinBoundOrRX(TxnId txnId)
+ private static void checkMinBoundOrSyncPoint(TxnId txnId)
{
- Invariants.requireArgument(txnId.domain().isRange() && txnId.is(ExclusiveSyncPoint) || isMinBound(txnId));
+ Invariants.requireArgument(txnId.domain().isRange() && txnId.isSyncPoint() || isMinBound(txnId));
}
private static boolean isMinBound(TxnId txnId)
@@ -228,7 +233,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
private static boolean isShardBound(TxnId txnId)
{
- return txnId.domain().isRange() && txnId.is(ExclusiveSyncPoint) && txnId.is(SHARD_BOUND);
+ return txnId.domain().isRange() && txnId.isSyncPoint() && txnId.is(SHARD_BOUND);
}
public static Bounds reduce(Bounds a, Bounds b)
@@ -258,33 +263,33 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
Object[] boundBuf = null;
short[] statusBuf = null;
int mergedCount = 0;
- short prevLtStatus = staleUntilAtLeast == null ? 0 : PRE_BOOTSTRAP_OR_STALE_ONLY.encodedPart(SOME);
- short prevExistingLtStatus = prevLtStatus; // we don't apply PRE_BOOTSTRAP_MERGE_MASK as this already applied
+ int prevLtStatus = staleUntilAtLeast == null ? 0 : PRE_BOOTSTRAP_OR_STALE_ONLY.encodedPart(SOME);
+ int prevExistingLtStatus = prevLtStatus; // we don't apply PRE_BOOTSTRAP_MERGE_MASK as this already applied
int i = 0, j = 0;
while (i < cur.bounds.length || j < add.bounds.length)
{
int c = i == cur.bounds.length ? -1 : j == add.bounds.length ? 1 : cur.bounds[i].compareTo(add.bounds[j]);
TxnId nextBound;
- short leStatus, ltStatus;
+ int leStatus, ltStatus;
if (c > 0)
{
nextBound = cur.bounds[i];
- leStatus = addHistory(prevLtStatus, cur.statuses[i*2]);
- ltStatus = addHistory(prevLtStatus, prevExistingLtStatus = cur.statuses[i*2+1]);
+ leStatus = addHistory(prevLtStatus, cur.status(i*2));
+ ltStatus = addHistory(prevLtStatus, prevExistingLtStatus = cur.status(i*2+1));
++i;
}
else if (c < 0)
{
nextBound = add.bounds[j];
- leStatus = addHistory((short) (prevLtStatus | add.statuses[j * 2]), prevExistingLtStatus);
- ltStatus = addHistory((short) (prevLtStatus | add.statuses[j * 2 + 1]), prevExistingLtStatus);
+ leStatus = addHistory(prevLtStatus | add.status(j * 2), prevExistingLtStatus);
+ ltStatus = addHistory(prevLtStatus | add.status(j * 2 + 1), prevExistingLtStatus);
++j;
}
else
{
nextBound = cur.bounds[i].addFlags(add.bounds[j]);
- leStatus = addHistory((short) (prevLtStatus | add.statuses[j * 2]), cur.statuses[i * 2]);
- ltStatus = addHistory((short) (prevLtStatus | add.statuses[j * 2 + 1]), prevExistingLtStatus = cur.statuses[i * 2 + 1]);
+ leStatus = addHistory(prevLtStatus | add.status(j * 2), cur.status(i * 2));
+ ltStatus = addHistory(prevLtStatus | add.status(j * 2 + 1), prevExistingLtStatus = cur.status(i * 2 + 1));
++i;
++j;
}
@@ -298,9 +303,9 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
if (mergedCount >= 2)
{
short[] prev = statusBuf != null ? statusBuf : cur.statuses;
- short prev2LtStatus = prev[mergedCount*2 - 3];
- short prevLeStatus = prev[mergedCount*2 - 2];
- Invariants.require(prevLtStatus == prev[mergedCount*2 - 1]);
+ int prev2LtStatus = 0xFFFF & prev[mergedCount*2 - 3];
+ int prevLeStatus = 0xFFFF & prev[mergedCount*2 - 2];
+ Invariants.require(prevLtStatus == (0xFFFF & prev[mergedCount*2 - 1]));
if (prevLtStatus == prev2LtStatus && prevLeStatus == prev2LtStatus)
--mergedCount;
}
@@ -309,7 +314,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
if (boundBuf == null)
{
if (mergedCount < cur.bounds.length && cur.bounds[mergedCount].equalsStrict(nextBound)
- && cur.statuses[mergedCount*2] == leStatus && cur.statuses[mergedCount*2+1] == ltStatus)
+ && cur.status(mergedCount*2) == leStatus && cur.status(mergedCount*2+1) == ltStatus)
{
prevLtStatus = ltStatus;
++mergedCount;
@@ -322,8 +327,8 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
System.arraycopy(cur.statuses, 0, statusBuf, 0, mergedCount*2);
}
boundBuf[mergedCount] = nextBound;
- statusBuf[mergedCount*2] = leStatus;
- statusBuf[mergedCount*2 + 1] = ltStatus;
+ statusBuf[mergedCount*2] = (short) leStatus;
+ statusBuf[mergedCount*2 + 1] = (short) ltStatus;
++mergedCount;
prevLtStatus = ltStatus;
}
@@ -360,7 +365,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
public Bounds with(TxnId newBound, SomeStatus addStatus)
{
// TODO (desired): introduce special-cased faster merge for adding a single value
- return merge(range, this, new Bounds(range, Long.MIN_VALUE, Long.MAX_VALUE, new TxnId[] { newBound }, new short[] { addStatus.encoded }, null));
+ return merge(range, this, new Bounds(range, Long.MIN_VALUE, Long.MAX_VALUE, new TxnId[] { newBound }, new short[] { (short)addStatus.encoded }, null));
}
@VisibleForImplementation
@@ -669,7 +674,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
if (i < 0)
return noMatch;
- short status = statuses[i];
+ int status = statuses[i] & 0xFFFF;
if (any(status, GC_BEFORE))
{
if (requiresUniqueHlcs() && txnId.isWrite())
@@ -678,7 +683,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
{
// if this is partial input (e.g. compaction) we don't want to infer ERASE
// we anyway only EXPUNGE on summary information before this point
- status &= (short) ~(1 << GC_BEFORE.shift());
+ status &= ~(1 << GC_BEFORE.shift());
}
else if (bounds[i/2].hlc() <= applyAtIfKnown.uniqueHlc())
{
@@ -686,7 +691,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
i/= 2;
while (--i >= 0 && bounds[i].hlc() <= uniqueHlc) {}
if (i < 0 || !any(statuses[i*2+1], GC_BEFORE))
- status &= (short) ~(1 << GC_BEFORE.shift());
+ status &= ~(1 << GC_BEFORE.shift());
}
}
}
@@ -912,7 +917,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
if (ranges.isEmpty())
return EMPTY;
- Bounds bounds = new Bounds(null, startEpoch, endEpoch, new TxnId[] { bound }, new short[] { (short) (status.encoded & ONLY_LE_MASK), status.encoded }, staleUntilAtLeast);
+ Bounds bounds = new Bounds(null, startEpoch, endEpoch, new TxnId[] { bound }, new short[] { (short) (status.encoded & ONLY_LE_MASK), (short)status.encoded }, staleUntilAtLeast);
Builder builder = new Builder(ranges.get(0).endInclusive(), ranges.size() * 2);
for (int i = 0 ; i < ranges.size() ; ++i)
{
@@ -1032,7 +1037,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
*/
public Participants<?> expectToOwn(TxnId txnId, @Nullable Timestamp executeAt, Participants<?> participants)
{
- if (txnId.is(ExclusiveSyncPoint))
+ if (txnId.isSyncPoint())
{
if (!mayFilterStaleOrPreBootstrapOrRetiredOrNotOwned(txnId, executeAt, participants))
return participants;
@@ -1064,7 +1069,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
*/
public Participants<?> expectExclusiveSyncPointToWaitOn(TxnId txnId, @Nullable Timestamp executeAt, Participants<?> participants)
{
- Invariants.require(txnId.is(ExclusiveSyncPoint));
+ Invariants.require(txnId.isSyncPoint());
if (!mayFilterStaleOrPreBootstrapOrRetiredOrNotOwned(txnId, executeAt, participants))
return participants;
diff --git a/accord-core/src/main/java/accord/local/RedundantStatus.java b/accord-core/src/main/java/accord/local/RedundantStatus.java
index ae977baa..ea9ed35d 100644
--- a/accord-core/src/main/java/accord/local/RedundantStatus.java
+++ b/accord-core/src/main/java/accord/local/RedundantStatus.java
@@ -32,13 +32,14 @@ import static accord.local.RedundantStatus.Property.LOCALLY_DURABLE_TO_COMMAND_S
import static accord.local.RedundantStatus.Property.LOCALLY_DURABLE_TO_DATA_STORE;
import static accord.local.RedundantStatus.Property.LOCALLY_SYNCED;
import static accord.local.RedundantStatus.Property.LOCALLY_WITNESSED;
-import static accord.local.RedundantStatus.Property.MAJORITY_APPLIED;
+import static accord.local.RedundantStatus.Property.QUORUM_APPLIED;
import static accord.local.RedundantStatus.Property.NOT_OWNED;
import static accord.local.RedundantStatus.Property.PRE_BOOTSTRAP;
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_APPLIED;
import static accord.local.RedundantStatus.Property.WAS_OWNED;
+import static accord.utils.Invariants.illegalState;
// TODO (testing): validate that we never lose a status previously held,
// i.e. once any particular property holds for a TxnId, it should continue to hold in perpetuity
@@ -91,22 +92,40 @@ public class RedundantStatus
PRE_BOOTSTRAP_OR_STALE ( true, true, LT, LOCALLY_DEFUNCT),
PRE_BOOTSTRAP ( true, true, LT, PRE_BOOTSTRAP_OR_STALE),
+ /**
+ * Ranges can be marked as LOCALLY_LOST if the node has lost was forced by operator to give up knowledge
+ * of transactional history for a specific range.
+ */
+ LOCALLY_LOST (false, false, LT, PRE_BOOTSTRAP_OR_STALE),
+
LOCALLY_WITNESSED (false, true, LE),
// we've applied a sync point locally covering the transaction, but the transaction itself may not have applied
LOCALLY_SYNCED (false, true, LE, LOCALLY_REDUNDANT),
LOCALLY_APPLIED ( true, false, LE, LOCALLY_SYNCED),
+ /**
+ * We have applied the preceding transactions durably to the store, so that we can safely truncate the Write
+ * information as we will not need to replay it to the store
+ */
+ LOCALLY_DURABLE_TO_DATA_STORE (false, false, LE, LOCALLY_APPLIED),
+
+ /**
+ * We have applied the preceding transactions durably to all summary structures, so that on restart we do
+ * not need to replay the transaction to restore any internal state.
+ */
+ LOCALLY_DURABLE_TO_COMMAND_STORE (false, false, LE, LOCALLY_APPLIED),
+
/**
* We have fully executed until across all a majority of replicas for the range in question,
* but not necessarily ourselves.
*/
- MAJORITY_APPLIED (false, true, LE),
+ QUORUM_APPLIED(false, true, LE),
/**
* We have fully executed until across all healthy non-bootstrapping replicas for the range in question,
* but not necessarily ourselves.
*/
- SHARD_APPLIED (false, true, LE, MAJORITY_APPLIED),
+ SHARD_APPLIED (false, true, LE, QUORUM_APPLIED),
TRUNCATE_BEFORE (false, true, LT, SHARD_APPLIED, LOCALLY_SYNCED),
GC_BEFORE (false, true, LT, TRUNCATE_BEFORE),
@@ -114,20 +133,6 @@ public class RedundantStatus
// not persisted
WAS_OWNED (false, false, LT, LOCALLY_DEFUNCT),
NOT_OWNED (false, false, LT),
-
- // added later, so vaguely out of order (but no specific order to this enum)
-
- /**
- * We have applied the preceding transactions durably to the store, so that we can safely truncate the Write
- * information as we will not need to replay it to the store
- */
- LOCALLY_DURABLE_TO_DATA_STORE (false, false, LE, LOCALLY_APPLIED),
-
- /**
- * We have applied the preceding transactions durably to all summary structures, so that on restart we do
- * not need to replay the transaction to restore any internal state.
- */
- LOCALLY_DURABLE_TO_COMMAND_STORE (false, false, LE, LOCALLY_APPLIED),
;
@@ -167,20 +172,21 @@ public class RedundantStatus
public static class SomeStatus
{
- public static final SomeStatus NONE = new SomeStatus((short)0);
+ public static final SomeStatus NONE = new SomeStatus(0);
public static final SomeStatus PRE_BOOTSTRAP_ONLY = oneSlow(PRE_BOOTSTRAP);
public static final SomeStatus LOCALLY_WITNESSED_ONLY = oneSlow(LOCALLY_WITNESSED);
public static final SomeStatus LOCALLY_APPLIED_ONLY = oneSlow(LOCALLY_APPLIED);
- public static final SomeStatus MAJORITY_APPLIED_ONLY = oneSlow(MAJORITY_APPLIED);
+ public static final SomeStatus QUORUM_APPLIED_ONLY = oneSlow(QUORUM_APPLIED);
public static final SomeStatus SHARD_APPLIED_ONLY = oneSlow(SHARD_APPLIED);
public static final SomeStatus LOCALLY_DURABLE_TO_DATA_STORE_ONLY = oneSlow(LOCALLY_DURABLE_TO_DATA_STORE);
public static final SomeStatus LOCALLY_DURABLE_TO_COMMAND_STORE_ONLY = oneSlow(LOCALLY_DURABLE_TO_COMMAND_STORE);
public static final SomeStatus GC_BEFORE_AND_LOCALLY_DURABLE = multi(GC_BEFORE, LOCALLY_DURABLE_TO_DATA_STORE, LOCALLY_DURABLE_TO_COMMAND_STORE);
- final short encoded;
- public SomeStatus(short encoded)
+ final int encoded;
+ public SomeStatus(int encoded)
{
+ Invariants.require((encoded & ~0xFFFF) == 0);
this.encoded = encoded;
}
@@ -232,11 +238,11 @@ public class RedundantStatus
return selectOrCreate(encoded, history, add);
}
- static short addHistory(short add, short history)
+ static int addHistory(int add, int history)
{
if (decode(history, PRE_BOOTSTRAP_OR_STALE) != Coverage.NONE)
add &= PRE_BOOTSTRAP_MERGE_MASK;
- return (short) (add | history);
+ return add | history;
}
static RedundantStatus selectOrCreate(int encoded, RedundantStatus a, RedundantStatus b)
@@ -246,21 +252,22 @@ public class RedundantStatus
return new RedundantStatus(encoded);
}
- static SomeStatus selectOrCreate(short encoded, SomeStatus a, SomeStatus b)
+ static SomeStatus selectOrCreate(int encoded, SomeStatus a, SomeStatus b)
{
+ Invariants.require(0 == (encoded & ~0xFFFF));
if (encoded == a.encoded) return a;
if (encoded == b.encoded) return b;
return new SomeStatus(encoded);
}
- public short encodedPart(Coverage coverage)
+ public int encodedPart(Coverage coverage)
{
switch (coverage)
{
default: throw new UnhandledEnum(coverage);
- case NONE: return (short)0;
- case SOME: return (short)(encoded & 0xff);
- case ALL: return (short)((encoded >>> 16) & 0xff);
+ case NONE: return 0;
+ case SOME: return (encoded & 0xffff);
+ case ALL: return (encoded >>> 16) & 0xffff;
}
}
@@ -269,6 +276,11 @@ public class RedundantStatus
return get(encoded, property);
}
+ public static Coverage get(short encoded, Property property)
+ {
+ return get(encoded & 0xFF, property);
+ }
+
public static Coverage get(int encoded, Property property)
{
return decode(encoded, property);
@@ -284,11 +296,21 @@ public class RedundantStatus
return all(encoded, a, b);
}
+ public static boolean all(short encoded, Property property)
+ {
+ return all(encoded & 0xFF, property);
+ }
+
public static boolean all(int encoded, Property property)
{
return get(encoded, property) == ALL;
}
+ public static boolean all(short encoded, Property a, Property b)
+ {
+ return all(encoded & 0xFF, a, b);
+ }
+
public static boolean all(int encoded, Property a, Property b)
{
return all(encoded, a) && all(encoded, b);
@@ -299,6 +321,11 @@ public class RedundantStatus
return none(encoded, property);
}
+ public static boolean none(short encoded, Property property)
+ {
+ return none(encoded & 0xFF, property);
+ }
+
public static boolean none(int encoded, Property property)
{
return get(encoded, property) == Coverage.NONE;
@@ -309,11 +336,21 @@ public class RedundantStatus
return any(encoded, property);
}
+ public static boolean any(short encoded, Property property)
+ {
+ return any(encoded & 0xFFFF, property);
+ }
+
public static boolean any(int encoded, Property property)
{
return get(encoded, property) != Coverage.NONE;
}
+ public static boolean matchesMask(short encoded, int propertyMask)
+ {
+ return matchesMask(encoded & 0xFFFF, propertyMask);
+ }
+
public static boolean matchesMask(int encoded, int propertyMask)
{
return (encoded & propertyMask) == propertyMask;
@@ -330,7 +367,7 @@ public class RedundantStatus
int coverage = (int)((encoded >>> property.shift()) & ALL.mask);
switch (coverage)
{
- default: throw new IllegalStateException("Invalid Coverage value encoded for " + property + ": " + coverage);
+ default: throw illegalState("Invalid Coverage value encoded for " + property + ": " + coverage);
case 0: return Coverage.NONE;
case 1: return SOME;
case 0x10001: return ALL;
@@ -340,14 +377,14 @@ public class RedundantStatus
private static final int ALL_BITS = 0xFFFF0000;
private static final int ANY_BITS = 0x0000FFFF;
private static final int WAS_OWNED_OVERRIDE_MASK;
- static final short PRE_BOOTSTRAP_MERGE_MASK;
- static final short ONLY_LE_MASK;
+ static final int PRE_BOOTSTRAP_MERGE_MASK;
+ static final int ONLY_LE_MASK;
private static final int WAS_ALL_OWNED_MASK = ALL.mask << WAS_OWNED.shift();
private static final int NOT_OWNED_MASK = ALL.mask << NOT_OWNED.shift();
static
{
int wasOwnedMask = 0;
- short preBootstrapMask = 0, leMask = 0;
+ int preBootstrapMask = 0, leMask = 0;
for (Property property : Property.values())
{
if (!property.overrideWasOwned)
@@ -386,23 +423,23 @@ public class RedundantStatus
private static SomeStatus multi(Property ... properties)
{
- short encoded = 0;
+ int encoded = 0;
for (Property property : properties)
encoded |= transitiveClosure(property);
return new SomeStatus(encoded);
}
- private static short transitiveClosure(Property property)
+ private static int transitiveClosure(Property property)
{
- short encoded = encodeAny(property);
+ int encoded = encodeAny(property);
for (Property implied : property.implies)
encoded |= transitiveClosure(implied);
return encoded;
}
- static short encodeAny(Property property)
+ static int encodeAny(Property property)
{
- return (short) (1 << property.shift());
+ return 1 << property.shift();
}
static int encodeAll(Property property)
@@ -410,9 +447,10 @@ public class RedundantStatus
return ALL.mask << property.shift();
}
- static int toAll(short encodedKeyStatus)
+ static int toAll(int encodedKeyStatus)
{
- return encodedKeyStatus | (((int)encodedKeyStatus)<<16);
+ Invariants.require(0 == (encodedKeyStatus & ~0xFFFF));
+ return encodedKeyStatus | (encodedKeyStatus<<16);
}
static RedundantStatus toAll(SomeStatus key)
diff --git a/accord-core/src/main/java/accord/local/SafeCommandStore.java b/accord-core/src/main/java/accord/local/SafeCommandStore.java
index 41f917c7..62553699 100644
--- a/accord-core/src/main/java/accord/local/SafeCommandStore.java
+++ b/accord-core/src/main/java/accord/local/SafeCommandStore.java
@@ -269,7 +269,7 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
public void updateExclusiveSyncPoint(Command prev, Command updated, boolean force)
{
- if (updated.txnId().kind() != Kind.ExclusiveSyncPoint || updated.txnId().domain() != Range) return;
+ if (!updated.txnId().isSyncPoint() || updated.txnId().domain() != Range) return;
if (updated.route() == null) return;
SaveStatus oldSaveStatus = prev == null ? SaveStatus.Uninitialised : prev.saveStatus();
@@ -426,7 +426,7 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
TxnId txnId = next.txnId();
RoutingKeys keys;
- if (!txnId.is(Kind.ExclusiveSyncPoint)) keys = next.asCommitted().waitingOn().keys;
+ if (!txnId.isSyncPoint()) keys = next.asCommitted().waitingOn().keys;
else
{
Command.WaitingOn waitingOn = next.asCommitted().waitingOn;
@@ -510,7 +510,7 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
private static void registerTransitiveRangeDeps(SafeCommandStore safeStore, TxnId syncId, Command syncCommand)
{
- if (!syncId.is(Kind.ExclusiveSyncPoint))
+ if (!syncId.is(Kind.VisibilitySyncPoint))
return;
CommandStore commandStore = safeStore.commandStore();
diff --git a/accord-core/src/main/java/accord/local/StoreParticipants.java b/accord-core/src/main/java/accord/local/StoreParticipants.java
index ec5ad5a7..387c7236 100644
--- a/accord-core/src/main/java/accord/local/StoreParticipants.java
+++ b/accord-core/src/main/java/accord/local/StoreParticipants.java
@@ -40,7 +40,6 @@ import static accord.primitives.Routable.Domain.Key;
import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Route.tryCastToRoute;
import static accord.primitives.SaveStatus.Erased;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
// TODO (expected): add invariants confirming owns contains AT LEAST anything in hasTouched() that intersects txnId.epoch()
public class StoreParticipants
@@ -354,7 +353,7 @@ public class StoreParticipants
if (stillExecutes != null)
{
stillExecutes = redundantBefore.expectToExecute(txnId, executeAtIfKnown, stillExecutes);
- if (txnId.is(ExclusiveSyncPoint))
+ if (txnId.isSyncPoint())
{
curStillWaitsOn = stillWaitsOn();
stillWaitsOn = redundantBefore.expectExclusiveSyncPointToWaitOn(txnId, executeAtIfKnown, curStillWaitsOn);
@@ -390,7 +389,7 @@ public class StoreParticipants
Participants<?> extraTouches = touches.without(owns);
if (!extraTouches.isEmpty())
{
- Participants<?> filteredExtra = txnId.is(ExclusiveSyncPoint)
+ Participants<?> filteredExtra = txnId.isSyncPoint()
? redundantBefore.withoutShardAppliedLocallySynced(txnId, extraTouches)
: redundantBefore.withoutShardApplied(txnId, extraTouches);
if (extraTouches != filteredExtra)
@@ -505,7 +504,7 @@ public class StoreParticipants
// TODO (required): retire this method, merge with executes()
public Ranges executeRanges(SafeCommandStore safeStore, TxnId txnId, Timestamp executeAt)
{
- Ranges ranges = txnId.is(ExclusiveSyncPoint)
+ Ranges ranges = txnId.isSyncPoint()
? safeStore.ranges().all()
: safeStore.ranges().allAt(executeAt.epoch());
@@ -517,7 +516,7 @@ public class StoreParticipants
public static Route<?> touches(SafeCommandStore safeStore, long fromEpoch, TxnId txnId, long toEpoch, Route<?> route)
{
// TODO (required): remove pre-bootstrap?
- if (txnId.is(ExclusiveSyncPoint))
+ if (txnId.isSyncPoint())
return route.slice(safeStore.ranges().all(), Minimal);
return route.slice(safeStore.ranges().allBetween(fromEpoch, toEpoch), Minimal);
@@ -632,7 +631,7 @@ public class StoreParticipants
{
Ranges executeRanges = storeRanges.allAt(executeAtEpoch);
executes = executeRanges == ownedRanges ? owns : participants.slice(executeRanges, Minimal);
- waitsOn = txnId.is(ExclusiveSyncPoint) ? touches : executes;
+ waitsOn = txnId.isSyncPoint() ? touches : executes;
}
return create(tryCastToRoute(participants), owns, executes, waitsOn, touches, touches);
}
@@ -685,7 +684,7 @@ public class StoreParticipants
private static long computeFetchLowEpoch(SafeCommandStore safeStore, TxnId txnId, Participants<?> touches, Participants<?> owns)
{
long txnIdEpoch = txnId.epoch();
- if (txnId.is(ExclusiveSyncPoint))
+ if (txnId.isSyncPoint())
return computeCoveringEpoch(safeStore, txnIdEpoch, touches);
if (touches.equals(owns))
@@ -696,7 +695,7 @@ public class StoreParticipants
public static long computePropagateLowEpoch(SafeCommandStore safeStore, TxnId txnId, Route<?> newRoute)
{
- if (txnId.is(ExclusiveSyncPoint)) return computeCoveringEpoch(safeStore, txnId.epoch(), newRoute);
+ if (txnId.isSyncPoint()) return computeCoveringEpoch(safeStore, txnId.epoch(), newRoute);
else return computeUnsyncedEpoch(safeStore, txnId.epoch(), newRoute);
}
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 d6e26bbb..d3710f99 100644
--- a/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
@@ -51,6 +51,7 @@ import accord.primitives.Status;
import accord.local.cfk.PostProcess.NotifyUnmanagedResult;
import accord.local.cfk.Pruning.LoadingPruned;
import accord.primitives.Ballot;
+import accord.primitives.Status.Durability;
import accord.primitives.Timestamp;
import accord.primitives.Txn.Kind;
import accord.primitives.Txn.Kind.Kinds;
@@ -66,9 +67,9 @@ import static accord.api.ProtocolModifiers.Toggles.dependencyElision;
import static accord.api.ProtocolModifiers.Toggles.isTransitiveDependencyVisible;
import static accord.api.ProtocolModifiers.Toggles.shouldVisitMaybePruned;
import static accord.local.CommandSummaries.IsDep.IS_COORD_DEP;
-import static accord.local.CommandSummaries.IsDep.IS_STABLE_DEP;
+import static accord.local.CommandSummaries.IsDep.IS_PROPOSED_OR_STABLE_DEP;
import static accord.local.CommandSummaries.IsDep.IS_NOT_COORD_DEP;
-import static accord.local.CommandSummaries.IsDep.IS_NOT_STABLE_DEP;
+import static accord.local.CommandSummaries.IsDep.IS_NOT_PROPOSED_OR_STABLE_DEP;
import static accord.local.CommandSummaries.IsDep.NOT_ELIGIBLE;
import static accord.local.CommandSummaries.SummaryStatus.APPLIED;
import static accord.local.CommandSummaries.SummaryStatus.NOT_DIRECTLY_WITNESSED;
@@ -100,12 +101,13 @@ import static accord.local.CommandSummaries.ComputeIsDep.IGNORE;
import static accord.local.cfk.Updating.maybeUpdateMaxAppliedPreBootstrapWriteById;
import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
import static accord.primitives.Routable.Domain.Key;
-import static accord.primitives.Status.Durability.Majority;
+import static accord.primitives.Status.Durability.AllQuorums;
+import static accord.primitives.Status.Durability.DurablyCommitted;
import static accord.primitives.Status.Durability.NotDurable;
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.ExclusiveSyncPoint;
+import static accord.primitives.Txn.Kind.AnyVisible;
+import static accord.primitives.Txn.Kind.EphemeralRead;
import static accord.primitives.Txn.Kind.Read;
import static accord.primitives.Txn.Kind.Write;
import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
@@ -330,9 +332,9 @@ public class CommandsForKey extends CommandsForKeyUpdate
public static class SerializerSupport
{
- public static CommandsForKey create(RoutingKey key, TxnInfo[] byId, long maxUniqueHlc, Unmanaged[] unmanageds, TxnId prunedBefore, QuickBounds bounds)
+ public static CommandsForKey create(RoutingKey key, TxnInfo[] byId, long maxUniqueHlc, Unmanaged[] unmanageds, TxnId prunedBefore, QuickBounds bounds, boolean expectUpToDate)
{
- return reconstruct(key, bounds, true, byId, maxUniqueHlc, prunedBefore, unmanageds);
+ return reconstruct(key, bounds, true, byId, maxUniqueHlc, prunedBefore, unmanageds, expectUpToDate);
}
}
@@ -342,7 +344,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById,
TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt,
long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById,
- Unmanaged[] unmanageds);
+ Unmanaged[] unmanageds, boolean expectUpToDate);
}
/**
@@ -366,6 +368,8 @@ public class CommandsForKey extends CommandsForKeyUpdate
static final int SUMMARY_STATUS_ORDINAL_SHIFT = 12;
static final int NOTIFIED_READY = 0x10000;
static final int NOTIFIED_WAITING = 0x20000;
+ static final int DURABLY_COMMITTED = 0x40000;
+ static final int DURABLY_COMMITTED_SHIFT = Integer.numberOfTrailingZeros(DURABLY_COMMITTED);
int encodedStatus;
public final Timestamp executeAt;
@@ -402,21 +406,21 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
public static TxnInfo create(@Nonnull TxnId txnId, InternalStatus status, boolean mayExecute, int statusOverrideXor, @Nonnull Timestamp executeAt, @Nonnull Ballot ballot)
{
- return create(txnId, status, mayExecute, statusOverrideXor, executeAt, NO_TXNIDS, ballot);
+ return create(txnId, status, mayExecute, statusOverrideXor, false, executeAt, NO_TXNIDS, ballot);
}
public static TxnInfo create(@Nonnull TxnId txnId, InternalStatus status, boolean mayExecute, @Nonnull Timestamp executeAt, @Nonnull TxnId[] missing, @Nonnull Ballot ballot)
{
- return create(txnId, status, mayExecute, 0, executeAt, missing, ballot);
+ return create(txnId, status, mayExecute, 0, false, executeAt, missing, ballot);
}
- public static TxnInfo create(@Nonnull TxnId txnId, InternalStatus status, boolean mayExecute, int statusOverrideXor, @Nonnull Timestamp executeAt, @Nonnull TxnId[] missing, @Nonnull Ballot ballot)
+ public static TxnInfo create(@Nonnull TxnId txnId, InternalStatus status, boolean mayExecute, int statusOverrideXor, boolean durablyCommitted, @Nonnull Timestamp executeAt, @Nonnull TxnId[] missing, @Nonnull Ballot ballot)
{
Invariants.require(executeAt == txnId || !executeAt.equals(txnId));
Invariants.require(status.hasExecuteAt || executeAt == txnId);
Invariants.require(status.hasDeps || missing == NO_TXNIDS);
Invariants.expect(status.hasBallot || ballot == Ballot.ZERO);
- int encodedStatus = encode(txnId, status, mayExecute, statusOverrideXor);
+ int encodedStatus = encode(txnId, status, mayExecute, statusOverrideXor, durablyCommitted);
if (missing == NO_TXNIDS && (!status.hasBallot || ballot == Ballot.ZERO))
return new TxnInfo(txnId, encodedStatus, executeAt);
Invariants.require(missing.length > 0 || missing == NO_TXNIDS);
@@ -489,9 +493,25 @@ public class CommandsForKey extends CommandsForKeyUpdate
return (encodedStatus >>> INTERNAL_STATUS_FLAGS_SHIFT) & 0x7;
}
- public boolean isDurable()
+ public boolean isDurablyCommitted()
{
- return is(APPLIED_DURABLE);
+ return 0 != (encodedStatus & DURABLY_COMMITTED);
+ }
+
+ public int durablyCommittedBit()
+ {
+ return (encodedStatus >>> DURABLY_COMMITTED_SHIFT) & 1;
+ }
+
+ public Durability durability()
+ {
+ if (is(APPLIED_DURABLE))
+ return AllQuorums;
+
+ if (isDurablyCommitted())
+ return DurablyCommitted;
+
+ return NotDurable;
}
// This field may differ from status().hasDeps(), in the event that the key is out of range for the transaction when committed.
@@ -589,8 +609,10 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TxnInfo info = (TxnInfo) o;
- return status() == info.status()
+ return super.equals(info)
+ && status() == info.status()
&& (executeAt == this ? info.executeAt == info : Objects.equals(executeAt, info.executeAt))
+ && isDurablyCommitted() == info.isDurablyCommitted()
&& TxnId.equalsStrict(missing(), info.missing());
}
@@ -634,6 +656,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
"txnId=" + toPlainString() +
", status=" + status() +
", executeAt=" + plainExecuteAt() +
+ (isDurablyCommitted() && !is(APPLIED_DURABLE) ? "*" : "") +
'}';
}
@@ -657,7 +680,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
return Long.compare(this.executeAt.epoch(), that.executeAt.epoch());
}
- private static int preencode(InternalStatus v)
+ private static int preencode(InternalStatus v, boolean isDurablyCommitted)
{
int encoded = v.ordinal();
encoded |= (v.summaryStatus == null ? SummaryStatus.values().length : v.summaryStatus.ordinal()) << SUMMARY_STATUS_ORDINAL_SHIFT;
@@ -666,6 +689,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (v.isCommittedToExecute) encoded |= COMMITTED_TO_EXECUTE;
if (v.depsKnownUntilExecuteAt()) encoded |= DEPS_KNOWN_UNTIL_EXECUTE_AT;
if (v.hasBallot) encoded |= HAS_BALLOT;
+ if (isDurablyCommitted) encoded |= DURABLY_COMMITTED;
return encoded;
}
@@ -677,12 +701,13 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
// statusOverrides is the bitmask we xor, not the new values of the flag (so providing zero has no effect, and providing the base value sets to zero)
- private static int encode(TxnId txnId, InternalStatus internalStatus, boolean mayExecute, int statusOverrideXor)
+ private static int encode(TxnId txnId, InternalStatus internalStatus, boolean mayExecute, int statusOverrideXor, boolean durablyCommitted)
{
Invariants.requireArgument(statusOverrideXor <= 1);
int encoded = internalStatus.txnInfoEncoded | (mayExecute ? MAY_EXECUTE : 0);
if (txnId.is(Key)) encoded |= MANAGED;
encoded ^= statusOverrideXor << INTERNAL_STATUS_FLAGS_SHIFT;
+ encoded |= (durablyCommitted ? DURABLY_COMMITTED : 0);
return encoded;
}
@@ -696,12 +721,18 @@ public class CommandsForKey extends CommandsForKeyUpdate
return 0 != (encodedStatus & NOTIFIED_WAITING);
}
- void setDurableInPlace()
+ void setAppliedDurableInPlace()
{
Invariants.require(is(APPLIED_NOT_DURABLE));
encodedStatus &= ~((SUMMARY_STATUS_ORDINAL_MASK << SUMMARY_STATUS_ORDINAL_SHIFT) | (INTERNAL_STATUS_ORDINAL_MASK << INTERNAL_STATUS_ORDINAL_SHIFT));
encodedStatus |= APPLIED_DURABLE.ordinal() << INTERNAL_STATUS_ORDINAL_SHIFT;
encodedStatus |= APPLIED_DURABLE.summaryStatus.ordinal() << SUMMARY_STATUS_ORDINAL_SHIFT;
+ encodedStatus |= DURABLY_COMMITTED;
+ }
+
+ void setDurablyCommittedInPlace()
+ {
+ encodedStatus |= DURABLY_COMMITTED;
}
void setNotifiedReadyInPlace()
@@ -858,7 +889,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
// NOTE: this only applies for transactions we execute. We need a new state for transactions
// that have been APPLIED but we don't execute as we want to retain the missing collection there.
APPLIED_NOT_DURABLE (APPLIED, true, true, false, true),
- APPLIED_DURABLE (APPLIED, true, true, false, true),
+ APPLIED_DURABLE (APPLIED, true, true, false, true, true),
APPLIED_NOT_EXECUTED /*(reserved)*/ (APPLIED, true, true, false, true),
INVALIDATED (SummaryStatus.INVALIDATED, false,false,false, false),
ERASED (SummaryStatus.NONE, false,false,false, false),
@@ -937,6 +968,10 @@ public class CommandsForKey extends CommandsForKeyUpdate
final int txnInfoEncoded;
InternalStatus(SummaryStatus summaryStatus, boolean hasExecuteAt, boolean hasDeps, boolean hasBallot, boolean isCommittedToExecute)
+ {
+ this(summaryStatus, hasExecuteAt, hasDeps, hasBallot, isCommittedToExecute, false);
+ }
+ InternalStatus(SummaryStatus summaryStatus, boolean hasExecuteAt, boolean hasDeps, boolean hasBallot, boolean isCommittedToExecute, boolean isDurablyCommitted)
{
this.summaryStatus = summaryStatus;
this.hasBallot = hasBallot;
@@ -944,7 +979,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
this.hasDeps = hasDeps;
this.isCommittedToExecute = isCommittedToExecute;
this.flags = (hasExecuteAt ? HAS_EXECUTE_AT : 0) | (hasDeps ? HAS_DEPS : 0);
- this.txnInfoEncoded = TxnInfo.preencode(this);
+ this.txnInfoEncoded = TxnInfo.preencode(this, isDurablyCommitted);
}
public boolean hasExecuteAtOrDeps()
@@ -1048,12 +1083,12 @@ public class CommandsForKey extends CommandsForKeyUpdate
final Unmanaged[] unmanageds;
final long maxUniqueHlc;
- CommandsForKey(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById, TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int prunedBeforeById, Unmanaged[] unmanageds)
+ CommandsForKey(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById, TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int prunedBeforeById, Unmanaged[] unmanageds, boolean expectUpToDate)
{
- this(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, unmanageds);
+ this(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, unmanageds, expectUpToDate);
}
- CommandsForKey(RoutingKey key, QuickBounds bounds, TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById, TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int prunedBeforeById, Unmanaged[] unmanageds)
+ CommandsForKey(RoutingKey key, QuickBounds bounds, TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById, TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int prunedBeforeById, Unmanaged[] unmanageds, boolean expectUpToDate)
{
this.key = key;
this.bounds = bounds;
@@ -1066,7 +1101,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
this.loadingPruned = loadingPruned;
this.prunedBeforeById = prunedBeforeById;
this.unmanageds = unmanageds;
- checkIntegrity();
+ checkIntegrity(expectUpToDate);
}
CommandsForKey(CommandsForKey copy, Object[] loadingPruned, Unmanaged[] unmanageds)
@@ -1082,7 +1117,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
this.loadingPruned = loadingPruned;
this.prunedBeforeById = copy.prunedBeforeById;
this.unmanageds = unmanageds;
- checkIntegrity();
+ checkIntegrity(true);
}
public CommandsForKey(RoutingKey key)
@@ -1257,7 +1292,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
@VisibleForTesting
public TxnId nextWaitingToApply()
{
- return nextWaitingToApply(AnyGloballyVisible, Timestamp.MAX);
+ return nextWaitingToApply(AnyVisible, Timestamp.MAX);
}
public TxnId blockedOnTxnId(TxnId txnId, @Nullable Timestamp executeAt)
@@ -1358,13 +1393,13 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
}
- if (txn.compareTo(ACCEPTED) >= 0) dep = hasAsDep ? IS_STABLE_DEP : IS_NOT_STABLE_DEP;
+ if (txn.compareTo(ACCEPTED) >= 0) dep = hasAsDep ? IS_PROPOSED_OR_STABLE_DEP : IS_NOT_PROPOSED_OR_STABLE_DEP;
else if (txn.is(PrivilegedCoordinatorWithDeps)) dep = hasAsDep ? IS_COORD_DEP : IS_NOT_COORD_DEP;
else dep = NOT_ELIGIBLE;
}
}
- if (!visitor.visit(key, txn.plainTxnId(), executeAt, summaryStatus, dep, txn.isDurable() ? Majority : NotDurable))
+ if (!visitor.visit(key, txn.plainTxnId(), executeAt, summaryStatus, dep, txn.durability()))
return false;
}
@@ -1456,12 +1491,12 @@ public class CommandsForKey extends CommandsForKeyUpdate
switch (dependencyElision())
{
- case IF_DURABLE:
- if (!txn.isDurable())
+ case IF_DURABLY_COMMITTED:
+ if (!txn.isDurablyCommitted())
break;
case ON:
- if (testKind != AnyGloballyVisible)
+ if (testKind != AnyVisible)
continue;
// cannot be the max known write for the epoch, so no need to return it
@@ -1498,7 +1533,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
}
- visitor.visit(p1, p2, txn.summaryStatus(), txn.isDurable() ? Majority : NotDurable, key, txn.plainTxnId());
+ visitor.visit(p1, p2, txn.summaryStatus(), txn.durability(), key, txn.plainTxnId());
}
if (end <= prunedBeforeById)
@@ -1520,7 +1555,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
break;
}
if (best.executeAt.epoch() <= startedBefore.epoch() && !best.equals(startedBefore))
- visitor.visit(p1, p2, best.summaryStatus(), best.isDurable() ? Majority : NotDurable, key, best.plainTxnId());
+ visitor.visit(p1, p2, best.summaryStatus(), best.durability(), key, best.plainTxnId());
}
}
@@ -1604,18 +1639,21 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (maxUniqueHlc <= bounds.gcBefore.hlc() && bounds.gcBefore.is(HLC_BOUND))
return this;
- return new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, minUniqueHlc, loadingPruned, prunedBeforeById, unmanageds);
+ return new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, minUniqueHlc, loadingPruned, prunedBeforeById, unmanageds, true);
}
- public CommandsForKey setDurable(TxnId txnId)
+ public CommandsForKey setDurable(TxnId txnId, Durability durability)
{
TxnInfo txn = get(txnId);
- if (txn == null || !txn.is(APPLIED_NOT_DURABLE))
+ if (txn == null || !durability.isDurablyCommitted())
return this;
- txn.setDurableInPlace();
+ if (durability.isDurable() && txn.is(APPLIED_NOT_DURABLE)) txn.setAppliedDurableInPlace();
+ else if (!txn.isDurablyCommitted()) txn.setDurablyCommittedInPlace();
+ else return this;
+
// return the exact same data as we have updated in place, but change detection relies on identity
- return new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, unmanageds);
+ return new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, unmanageds, true);
}
CommandsForKeyUpdate maybePrunedCallback(SafeCommandStore safeStore, Command update, @Nullable LoadingPruned loading)
@@ -1704,7 +1742,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, cur, newStatus, mayExecute, updated, witnessedBy);
- else if (cur.compareTo(STABLE) >= 0) result = update(pos, txnId, cur, cur.withEncodedStatus(TxnInfo.encode(txnId, newStatus, cur.mayExecute(), cur.statusOverrides())), updated, witnessedBy);
+ else if (cur.compareTo(STABLE) >= 0) result = update(pos, txnId, cur, cur.withEncodedStatus(TxnInfo.encode(txnId, newStatus, cur.mayExecute(), cur.statusOverrides(), cur.isDurablyCommitted())), updated, witnessedBy);
else if (newStatus.hasDeps()) result = update(pos, txnId, cur, newStatus, mayExecute, updated, witnessedBy);
else result = update(pos, txnId, cur, TxnInfo.create(txnId, newStatus, mayExecute, updated), updated, witnessedBy);
}
@@ -1741,7 +1779,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
int statusOverridesXor = newStatus.flags & 1;
TxnInfo newInfo;
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));
+ else newInfo = curInfo.withEncodedStatus(TxnInfo.encode(plainTxnId, newStatus, false, statusOverridesXor, updated.durability().isDurablyCommitted()));
// 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, updated, witnessedBy);
}
@@ -1755,22 +1793,22 @@ public class CommandsForKey extends CommandsForKeyUpdate
newById, newMinUndecidedById, newMaxAppliedPreBootstrapWriteById,
newCommittedByExecuteAt, newMaxAppliedWriteByExecuteAt,
maxUniqueHlc, newLoadingPruned, newPrunedBeforeById,
- unmanageds, curInfo, newInfo);
+ unmanageds, true, curInfo, newInfo);
}
- static CommandsForKey reconstruct(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, TxnId prunedBefore, Unmanaged[] unmanageds)
+ static CommandsForKey reconstruct(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, TxnId prunedBefore, Unmanaged[] unmanageds, boolean expectUpToDate)
{
int prunedBeforeById = Arrays.binarySearch(byId, prunedBefore);
Invariants.require(prunedBeforeById >= 0 || prunedBefore.equals(TxnId.NONE));
- return reconstruct(key, bounds, isNewBoundsInfo, byId, maxUniqueHlc, BTree.empty(), prunedBeforeById, unmanageds);
+ return reconstruct(key, bounds, isNewBoundsInfo, byId, maxUniqueHlc, BTree.empty(), prunedBeforeById, unmanageds, expectUpToDate);
}
- static CommandsForKey reconstruct(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
+ static CommandsForKey reconstruct(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, boolean expectUpToDate)
{
- return reconstruct(key, bounds, isNewBoundsInfo, byId, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, CommandsForKey::new);
+ return reconstruct(key, bounds, isNewBoundsInfo, byId, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, expectUpToDate, CommandsForKey::new);
}
- static <O> O reconstruct(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, Updater<O> updater)
+ static <O> O reconstruct(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, boolean expectUpToDate, Updater<O> updater)
{
int countCommitted = 0;
int minUndecidedById = -1;
@@ -1808,25 +1846,25 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (maxAppliedWriteByExecuteAt >= 0) maxUniqueHlc = Math.max(maxUniqueHlc, committedByExecuteAt[maxAppliedWriteByExecuteAt].executeAt.hlc());
else maxUniqueHlc = Math.max(maxUniqueHlc, bounds.gcBefore.hlc() - 1); // only guaranteed to witness those with strictly lower hlc; might be some txn agreed with higher flag bits
- return updater.update(key, bounds, isNewBoundsInfo, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds);
+ return updater.update(key, bounds, isNewBoundsInfo, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, expectUpToDate);
}
- static CommandsForKeyUpdate reconstructAndUpdateUnmanaged(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
+ static CommandsForKeyUpdate reconstructAndUpdateUnmanaged(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, boolean expectUpToDate)
{
- return reconstruct(key, bounds, isNewBoundsInfo, byId, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, CommandsForKey::updateAndNotifyUnmanageds);
+ return reconstruct(key, bounds, isNewBoundsInfo, byId, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, expectUpToDate, CommandsForKey::updateAndNotifyUnmanageds);
}
- static CommandsForKeyUpdate updateAndNotifyUnmanageds(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById, TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
+ static CommandsForKeyUpdate updateAndNotifyUnmanageds(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById, TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, boolean expectUpToDate)
{
- return updateAndNotifyUnmanageds(key, bounds, isNewBoundsInfo, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, null, null);
+ return updateAndNotifyUnmanageds(key, bounds, isNewBoundsInfo, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, expectUpToDate, null, null);
}
- static CommandsForKeyUpdate updateAndNotifyUnmanageds(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById, TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, @Nullable TxnInfo curInfo, @Nullable TxnInfo newInfo)
+ static CommandsForKeyUpdate updateAndNotifyUnmanageds(RoutingKey key, QuickBounds bounds, boolean isNewBoundsInfo, TxnInfo[] byId, int minUndecidedById, int maxAppliedPreBootstrapWriteById, TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, boolean expectUpToDate, @Nullable TxnInfo curInfo, @Nullable TxnInfo newInfo)
{
NotifyUnmanagedResult notifyUnmanaged = PostProcess.notifyUnmanaged(unmanageds, byId, minUndecidedById, committedByExecuteAt, maxAppliedWriteByExecuteAt, loadingPruned, bounds, isNewBoundsInfo, curInfo, newInfo);
if (notifyUnmanaged != null)
unmanageds = notifyUnmanaged.newUnmanaged;
- CommandsForKey newCfk = new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds);
+ CommandsForKey newCfk = new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, expectUpToDate);
CommandsForKeyUpdate result = newCfk;
if (notifyUnmanaged != null)
result = new CommandsForKeyUpdateWithPostProcess(newCfk, notifyUnmanaged.postProcess);
@@ -1837,12 +1875,12 @@ public class CommandsForKey extends CommandsForKeyUpdate
CommandsForKey update(Unmanaged[] newUnmanageds)
{
- return new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, newUnmanageds);
+ return new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, newUnmanageds, true);
}
CommandsForKey update(Object[] newLoadingPruned)
{
- return new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, newLoadingPruned, prunedBeforeById, unmanageds);
+ return new CommandsForKey(key, bounds, byId, minUndecidedById, maxAppliedPreBootstrapWriteById, committedByExecuteAt, maxAppliedWriteByExecuteAt, maxUniqueHlc, newLoadingPruned, prunedBeforeById, unmanageds, true);
}
CommandsForKeyUpdate registerUnmanaged(SafeCommandStore safeStore, SafeCommand safeCommand, UpdateUnmanagedMode mode)
@@ -1859,7 +1897,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (updated == null || forceNotify)
{
- notifyManaged(safeStore, AnyGloballyVisible, 0, committedByExecuteAt.length, -1, notifySink);
+ notifyManaged(safeStore, AnyVisible, 0, committedByExecuteAt.length, -1, notifySink);
return;
}
@@ -2021,21 +2059,30 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
}
- private static final long WRITE_COUNTERS_DELTA = (1L << 32) + 1L;
- private static final int WRITE_COUNTERS_DELTA_SHIFT = (63 << (ExclusiveSyncPoint.ordinal() * 8)) | (32 << (Read.ordinal() * 8));
+ static final long DELTA_MASK = 0x3;
+ static final long HIGH_BIT = 1L << 32;
+
static
{
- // check if we need to update WRITE_COUNTERS_DELTA_SHIFT
- Invariants.require(Kind.values().length == 4);
+ // check if we need to update unappliedCount / unappliedCountersDelta
+ Invariants.require(Kind.values().length == 5);
+ Invariants.require(Write.ordinal() == 1);
+ Invariants.require((Read.ordinal() & 1) == 0);
+ Invariants.require((EphemeralRead.ordinal() & 1) == 0);
}
private static long unappliedCountersDelta(int kindOrdinal)
{
- return WRITE_COUNTERS_DELTA >>> ((WRITE_COUNTERS_DELTA_SHIFT >>> (kindOrdinal * 8)) & 63);
+ // lowBit -> reads and writes
+ long lowBit = (DELTA_MASK >>> kindOrdinal) & 1;
+ // highBit -> writes only
+ long highBit = HIGH_BIT & ((kindOrdinal ^ 1) - 1);
+ return lowBit | highBit;
}
private static int unappliedCount(long unappliedCounters, int kindOrdinal)
{
- return (int) (unappliedCounters >>> ((WRITE_COUNTERS_DELTA_SHIFT >>> (kindOrdinal * 8)) & 63));
+ Invariants.require(kindOrdinal <= 2);
+ return (int)(unappliedCounters >>> ((~kindOrdinal & 1) << 5));
}
public CommandsForKeyUpdate withRedundantBeforeAtLeast(QuickBounds newBounds, boolean expectUpToDate)
@@ -2071,7 +2118,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
for (int i = 0 ; i < notify.length ; ++i)
notify[i] = unmanageds[i].txnId;
PostProcess newPostProcess = new PostProcess.NotifyNotWaiting(null, notify);
- CommandsForKey newCfk = new CommandsForKey(key, newBounds, NO_INFOS, -1, -1, NO_INFOS, -1, maxUniqueHlc, BTree.empty(), -1, NO_PENDING_UNMANAGED);
+ CommandsForKey newCfk = new CommandsForKey(key, newBounds, NO_INFOS, -1, -1, NO_INFOS, -1, maxUniqueHlc, BTree.empty(), -1, NO_PENDING_UNMANAGED, expectUpToDate);
return new CommandsForKeyUpdateWithPostProcess(newCfk, newPostProcess);
}
@@ -2080,7 +2127,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
int newPrunedBeforeById = prunedBeforeId(newById, prunedBefore(), redundantBefore(newBounds));
Invariants.paranoid(!expectUpToDate || (newPrunedBeforeById < 0 ? prunedBeforeById < 0 || byId[prunedBeforeById].compareTo(newBounds.gcBefore) < 0 : newById[newPrunedBeforeById].equals(byId[prunedBeforeById])));
- return notifyManagedPreBootstrap(this, newBounds, reconstructAndUpdateUnmanaged(key, newBounds, true, newById, maxUniqueHlc, newLoadingPruned, newPrunedBeforeById, unmanageds));
+ return notifyManagedPreBootstrap(this, newBounds, reconstructAndUpdateUnmanaged(key, newBounds, true, newById, maxUniqueHlc, newLoadingPruned, newPrunedBeforeById, unmanageds, expectUpToDate));
}
/**
@@ -2098,7 +2145,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
int newPrunedBeforeById = prunedBeforeId(newById, prunedBefore(), newRedundantBefore);
Invariants.paranoid(!expectUpToDate || (newPrunedBeforeById < 0 ? prunedBeforeById < 0 || byId[prunedBeforeById].compareTo(newRedundantBefore) < 0 : newById[newPrunedBeforeById].equals(byId[prunedBeforeById])));
- return reconstruct(key, newBoundsInfo, true, newById, maxUniqueHlc, newLoadingPruned, newPrunedBeforeById, unmanageds);
+ return reconstruct(key, newBoundsInfo, true, newById, maxUniqueHlc, newLoadingPruned, newPrunedBeforeById, unmanageds, expectUpToDate);
}
/**
@@ -2134,10 +2181,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CommandsForKey that = (CommandsForKey) o;
- return Objects.equals(key, that.key)
- && Arrays.equals(byId, that.byId)
- && Arrays.equals(unmanageds, that.unmanageds)
- && maxUniqueHlc == that.maxUniqueHlc;
+ return Objects.equals(key, that.key) && equalContents(that);
}
@Override
@@ -2226,7 +2270,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
}
- private void checkIntegrity()
+ private void checkIntegrity(boolean expectUpToDate)
{
if (isParanoid())
{
@@ -2319,29 +2363,34 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
}
}
- for (Unmanaged unmanaged : unmanageds)
+ if (expectUpToDate)
{
- switch (unmanaged.pending)
+ for (Unmanaged unmanaged : unmanageds)
{
- case COMMIT:
- {
- int byIdIndex = Arrays.binarySearch(byId, unmanaged.waitingUntil);
- if (byIdIndex < 0)
- byIdIndex = -1 - byIdIndex;
- Invariants.require(byIdIndex >= decidedBefore || isAnyPredecessorWaitingOnPruned(loadingPruned, unmanaged.txnId));
- break;
- }
- case APPLY:
+ switch (unmanaged.pending)
{
- int byExecuteAtIndex = SortedArrays.binarySearch(committedByExecuteAt, 0, committedByExecuteAt.length, unmanaged.waitingUntil, (f, i) -> f.compareTo(i.executeAt), FAST);
- if (byExecuteAtIndex >= 0 && byExecuteAtIndex < appliedBefore)
+ case COMMIT:
{
- Invariants.require(!reportLinearizabilityViolations);
- int i = 0;
- for (; i < appliedBefore && committedByExecuteAt[i].compareTo(APPLIED) >= 0 ; ++i){}
- Invariants.require(i < appliedBefore || isLoadingPruned());
+ int byIdIndex = Arrays.binarySearch(byId, unmanaged.waitingUntil);
+ if (byIdIndex < 0)
+ byIdIndex = -1 - byIdIndex;
+ Invariants.require(byIdIndex >= decidedBefore || isAnyPredecessorWaitingOnPruned(loadingPruned, unmanaged.txnId));
+ break;
+ }
+ case APPLY:
+ {
+ int byExecuteAtIndex = SortedArrays.binarySearch(committedByExecuteAt, 0, committedByExecuteAt.length, unmanaged.waitingUntil, (f, i) -> f.compareTo(i.executeAt), FAST);
+ if (byExecuteAtIndex >= 0 && byExecuteAtIndex < appliedBefore)
+ {
+ Invariants.require(!reportLinearizabilityViolations);
+ int i = 0;
+ for (; i < appliedBefore && committedByExecuteAt[i].compareTo(APPLIED) >= 0; ++i)
+ {
+ }
+ Invariants.require(i < appliedBefore || isLoadingPruned());
+ }
+ break;
}
- break;
}
}
}
@@ -2372,10 +2421,13 @@ public class CommandsForKey extends CommandsForKeyUpdate
return false;
if (!a.ballot().equals(b.ballot()))
return false;
+ if (a.durablyCommittedBit() != b.durablyCommittedBit())
+ return false;
if (!TxnId.equalsStrict(a.missing(), b.missing()))
return false;
}
- return true;
+
+ return (this.hasMaxUniqueHlc() ? this.maxUniqueHlc : 0) == (that.hasMaxUniqueHlc() ? that.maxUniqueHlc : 0);
}
public boolean isEmpty()
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 31a6fff5..7ee47013 100644
--- a/accord-core/src/main/java/accord/local/cfk/Pruning.java
+++ b/accord-core/src/main/java/accord/local/cfk/Pruning.java
@@ -271,7 +271,7 @@ public class Pruning
newMinUndecidedById, newMaxAppliedPreBootstrapWriteById,
cfk.committedByExecuteAt, cfk.maxAppliedWriteByExecuteAt,
cfk.maxUniqueHlc, cfk.loadingPruned, newPrunedBeforeId,
- cfk.unmanageds);
+ cfk.unmanageds, true);
}
int pos = cfk.insertPos(pruneBefore);
if (pos == 0)
@@ -488,7 +488,7 @@ public class Pruning
int newMaxAppliedWriteByExecuteAt = cfk.maxAppliedWriteByExecuteAt - removedCommittedCount;
int newMaxAppliedPreBootstrapWriteById = recomputeMaxAppliedPreBootstrapWriteById(cfk.bounds, newById, cfk.maxAppliedPreBootstrapWriteById);
Invariants.require(newById[retainCount] == newPrunedBefore);
- return new CommandsForKey(cfk.key, cfk.bounds, newById, minUndecidedById, newMaxAppliedPreBootstrapWriteById, newCommittedByExecuteAt, newMaxAppliedWriteByExecuteAt, cfk.maxUniqueHlc, cfk.loadingPruned, retainCount, cfk.unmanageds);
+ return new CommandsForKey(cfk.key, cfk.bounds, newById, minUndecidedById, newMaxAppliedPreBootstrapWriteById, newCommittedByExecuteAt, newMaxAppliedWriteByExecuteAt, cfk.maxUniqueHlc, cfk.loadingPruned, retainCount, cfk.unmanageds, true);
}
/**
@@ -546,7 +546,7 @@ public class Pruning
if (appliedPos < 0) appliedPos = -1 - appliedPos;
if (pos != 0 || appliedPos != 0 || hasRedundantLoadingPruned)
{
- if (Invariants.isParanoid() && testParanoia(LINEAR, NONE, LOW))
+ if (Invariants.isParanoid() && expectUpToDate && testParanoia(LINEAR, NONE, LOW))
{
int startPos = prevBootstrappedAt == null ? 0 : insertPos(byId, prevBootstrappedAt);
for (int i = startPos ; i < pos ; ++i)
@@ -569,14 +569,11 @@ public class Pruning
// and rely on the applied RX to correctly reject recovery of the transaction.
for (int i = pos ; i < appliedPos ; ++i)
{
- if (byId[i].compareTo(APPLIED) < 0)
+ if (byId[i].compareTo(APPLIED) < 0 && byId[i].mayExecute())
{
- if (byId[i].mayExecute())
- {
- Invariants.require(!expectUpToDate || (byId[i].isNot(COMMITTED) && byId[i].isNot(STABLE)) || !reportLinearizabilityViolations(), "%s redundant; expected to be applied, undecided or to execute in a future epoch", byId[i]);
- // we only filter those that would apply locally
- removeUnappliedCount++;
- }
+ Invariants.require(!expectUpToDate || (byId[i].isNot(COMMITTED) && byId[i].isNot(STABLE)) || !reportLinearizabilityViolations(), "%s redundant; expected to be applied, undecided or to execute in a future epoch", byId[i]);
+ // we only filter those that would apply locally
+ removeUnappliedCount++;
}
}
}
diff --git a/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java b/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
index 9b716fce..66540b0b 100644
--- a/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
@@ -29,6 +29,7 @@ import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.local.cfk.NotifySink.DefaultNotifySink;
import accord.primitives.Status;
+import accord.primitives.Status.Durability;
import accord.primitives.TxnId;
public abstract class SafeCommandsForKey implements SafeState<CommandsForKey>
@@ -111,8 +112,8 @@ public abstract class SafeCommandsForKey implements SafeState<CommandsForKey>
updateRedundantBefore(safeStore, safeStore.redundantBefore().get(key));
}
- public void setDurable(TxnId txnId)
+ public void setDurable(TxnId txnId, Durability durability)
{
- set(current().setDurable(txnId));
+ set(current().setDurable(txnId, durability));
}
}
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 a204b42f..c9e3744d 100644
--- a/accord-core/src/main/java/accord/local/cfk/Serialize.java
+++ b/accord-core/src/main/java/accord/local/cfk/Serialize.java
@@ -106,6 +106,7 @@ public class Serialize
*
* In order, for each command, we consume:
* 3 bits for the InternalStatus of the command
+ * 1 optional bit: if the status is not APPLIED_DURABLE for encoding if the transaction is durably committed
* 1 optional bit: if any command has override flags; 2 bits more to read if this bit is set
* 1 optional bit: if the status encodes an executeAt, indicating if the executeAt is not the TxnId
* 1 optional bit: if the status encodes any dependencies and there are non-zero missing ids, indicating if there are any missing for this command
@@ -302,6 +303,8 @@ public class Serialize
headerBits += (headerFlags >>> HAS_MISSING_DEPS_HEADER_BIT_SHIFT) & 1;
if (txn.hasBallot())
headerBits += (headerFlags >>> HAS_BALLOT_HEADER_BIT_SHIFT) & 1;
+ if (txn.compareTo(InternalStatus.APPLIED_DURABLE) < 0)
+ ++headerBits;
maxHeaderBits = Math.max(headerBits, maxHeaderBits);
int basicBytes = (headerBits + payloadBits + 7)/8;
@@ -521,6 +524,12 @@ public class Serialize
bits |= hasBallot << bitIndex;
bitIndex += statusHasBallot & (flagsPlus >>> HAS_BALLOT_HEADER_BIT_SHIFT);
+ if (txn.compareTo(InternalStatus.APPLIED_DURABLE) < 0)
+ {
+ bits |= (long)txn.durablyCommittedBit() << bitIndex;
+ bitIndex += 1;
+ }
+
int encodedFlagBits;
{
int flags = txn.flags();
@@ -842,6 +851,11 @@ public class Serialize
int ballotMask = status.hasBallot ? ((globalFlags >>> HAS_BALLOT_HEADER_BIT_SHIFT) & 0x1) : 0;
commandDecodeFlags |= ((int)header & ballotMask) << 2;
header >>>= ballotMask;
+ if (status.compareTo(InternalStatus.APPLIED_DURABLE) < 0)
+ {
+ commandDecodeFlags |= ((int)header & 1) << 4;
+ header >>>= 1;
+ }
commandFlags[i] = commandDecodeFlags;
}
@@ -1074,7 +1088,8 @@ public class Serialize
int statusIndex = commandDecodeFlags >>> 6;
InternalStatus status = DECODE_STATUS[statusIndex];
int statusOverrides = (commandDecodeFlags >>> 3) & 0x1;
- txns[i] = create(bounds, txnId, status, statusOverrides, executeAt, missing, ballot);
+ boolean durablyCommitted = 0 != (commandDecodeFlags & 0x10);
+ txns[i] = create(bounds, txnId, status, statusOverrides, durablyCommitted, executeAt, missing, ballot);
}
cachedTxnIds().forceDiscard(missingIdBuffer, maxIdBufferCount);
@@ -1087,19 +1102,20 @@ public class Serialize
int statusIndex = commandDecodeFlags >>> 6;
InternalStatus status = DECODE_STATUS[statusIndex];
int statusOverrides = (commandDecodeFlags >>> 3) & 0x1;
- txns[i] = create(bounds, txnIds[i], status, statusOverrides, txnIds[i], NO_TXNIDS, Ballot.ZERO);
+ boolean durablyCommitted = 0 != (commandDecodeFlags & 0x10);
+ txns[i] = create(bounds, txnIds[i], status, statusOverrides, durablyCommitted, txnIds[i], NO_TXNIDS, Ballot.ZERO);
}
}
cachedTxnIds().forceDiscard(txnIds, commandCount);
cachedAny().forceDiscard(nodeIds, nodeIdCount);
- return CommandsForKey.SerializerSupport.create(key, txns, maxUniqueHlc, unmanageds, prunedBeforeIndex == -1 ? TxnId.NONE : txns[prunedBeforeIndex], bounds);
+ return CommandsForKey.SerializerSupport.create(key, txns, maxUniqueHlc, unmanageds, prunedBeforeIndex == -1 ? TxnId.NONE : txns[prunedBeforeIndex], bounds, false);
}
- private static TxnInfo create(QuickBounds bounds, @Nonnull TxnId txnId, InternalStatus status, int statusOverrides, @Nonnull Timestamp executeAt, @Nonnull TxnId[] missing, @Nonnull Ballot ballot)
+ private static TxnInfo create(QuickBounds bounds, @Nonnull TxnId txnId, InternalStatus status, int statusOverrides, boolean durablyCommitted, @Nonnull Timestamp executeAt, @Nonnull TxnId[] missing, @Nonnull Ballot ballot)
{
boolean mayExecute = status.isCommittedToExecute() ? CommandsForKey.executes(bounds, txnId, executeAt)
: CommandsForKey.mayExecute(bounds, txnId);
- return TxnInfo.create(txnId, status, mayExecute, statusOverrides, executeAt, missing, ballot);
+ return TxnInfo.create(txnId, status, mayExecute, statusOverrides, durablyCommitted, executeAt, missing, ballot);
}
private static int getHlcBytes(int lookup, int index)
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 c38c86a2..31d29804 100644
--- a/accord-core/src/main/java/accord/local/cfk/Updating.java
+++ b/accord-core/src/main/java/accord/local/cfk/Updating.java
@@ -87,7 +87,6 @@ import static accord.primitives.Routable.Domain.Range;
import static accord.primitives.SaveStatus.Uninitialised;
import static accord.primitives.Timestamp.Flag.UNSTABLE;
import static accord.primitives.Txn.Kind.EphemeralRead;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.primitives.Txn.Kind.Write;
import static accord.primitives.TxnId.NO_TXNIDS;
import static accord.utils.ArrayBuffers.cachedTxnIds;
@@ -306,14 +305,15 @@ class Updating
MergeCursor<TxnId, DepList> deps = command.partialDeps().txnIds(cfk.key());
deps.find(cfk.redundantBefore());
- return computeInfoAndAdditions(cfk.byId, insertPos, updatePos, plainTxnId, newStatus, mayExecute, ballot, executeAt, cfk.prunedBefore(), depsKnownBefore, deps);
+ boolean durablyCommitted = command.durability().isDurablyCommitted();
+ return computeInfoAndAdditions(cfk.byId, insertPos, updatePos, plainTxnId, newStatus, mayExecute, durablyCommitted, ballot, executeAt, cfk.prunedBefore(), depsKnownBefore, deps);
}
/**
* We return an Object here to avoid wasting allocations; most of the time we expect a new TxnInfo to be returned,
* but if we have transitive dependencies to insert we return an InfoWithAdditions
*/
- static Object computeInfoAndAdditions(TxnInfo[] byId, int insertPos, int updatePos, TxnId plainTxnId, InternalStatus newStatus, boolean mayExecute, Ballot ballot, Timestamp executeAt, TxnInfo prunedBefore, Timestamp depsKnownBefore, MergeCursor<TxnId, DepList> deps)
+ static Object computeInfoAndAdditions(TxnInfo[] byId, int insertPos, int updatePos, TxnId plainTxnId, InternalStatus newStatus, boolean mayExecute, boolean durablyCommitted, Ballot ballot, Timestamp executeAt, TxnInfo prunedBefore, Timestamp depsKnownBefore, MergeCursor<TxnId, DepList> deps)
{
TxnId[] additions = NO_TXNIDS, missing = NO_TXNIDS;
int additionCount = 0, missingCount = 0;
@@ -373,7 +373,7 @@ class Updating
// we can take dependencies on ExclusiveSyncPoints to represent a GC point in the log
// if we don't ordinarily witness a transaction it is meaningless to include it as a dependency
// as we will not logically be able to work with it (the missing collection will not correctly represent it anyway)
- Invariants.require(d.is(ExclusiveSyncPoint));
+ Invariants.require(d.isSyncPoint());
}
deps.advance();
}
@@ -412,7 +412,7 @@ class Updating
}
}
- TxnInfo info = TxnInfo.create(plainTxnId, newStatus, mayExecute, executeAt, cachedTxnIds().completeAndDiscard(missing, missingCount), ballot);
+ TxnInfo info = TxnInfo.create(plainTxnId, newStatus, mayExecute, 0, durablyCommitted, executeAt, cachedTxnIds().completeAndDiscard(missing, missingCount), ballot);
if (additionCount == 0)
return info;
@@ -906,7 +906,7 @@ class Updating
int i = txnIds.find(cfk.redundantOrBootstrappedBefore());
if (i < 0) i = -1 - i;
int waitingFromIndex = i; // the min input index we expect to execute
- if (waitingTxnId.is(ExclusiveSyncPoint) && waitingTxnId.is(Range) && mode == REGISTER)
+ if (waitingTxnId.isSyncPoint() && waitingTxnId.is(Range) && mode == REGISTER)
{
// for RX we register all our transitive dependencies to make sure we can answer coordinated dependency calculations
// in this case we separate out the position from which we insert missing txnId and where we compute readiness to execute
@@ -999,7 +999,7 @@ class Updating
{
if (newById == null)
newById = byId.clone();
- newById[j] = TxnInfo.create(txn, TRANSITIVE_VISIBLE, txn.mayExecute(), txn.statusOverrides(), txn.executeAt, txn.missing(), txn.ballot());
+ newById[j] = TxnInfo.create(txn, TRANSITIVE_VISIBLE, txn.mayExecute(), txn.statusOverrides(), false, txn.executeAt, txn.missing(), txn.ballot());
}
++i;
}
@@ -1119,7 +1119,7 @@ class Updating
{
int prunedBeforeById = cfk.prunedBeforeById;
Invariants.require(prunedBeforeById < 0 || newById[prunedBeforeById].equals(cfk.prunedBefore()));
- newCfk = new CommandsForKey(cfk.key(), cfk.bounds, newById, newMinUndecidedById, newMaxAppliedPreBootstrapWriteById, newCommittedByExecuteAt, cfk.maxAppliedWriteByExecuteAt, cfk.maxUniqueHlc, newLoadingPruned, prunedBeforeById, newUnmanaged);
+ newCfk = new CommandsForKey(cfk.key(), cfk.bounds, newById, newMinUndecidedById, newMaxAppliedPreBootstrapWriteById, newCommittedByExecuteAt, cfk.maxAppliedWriteByExecuteAt, cfk.maxUniqueHlc, newLoadingPruned, prunedBeforeById, newUnmanaged, true);
}
CommandsForKeyUpdate result = newCfk;
diff --git a/accord-core/src/main/java/accord/local/durability/DurabilityRequest.java b/accord-core/src/main/java/accord/local/durability/DurabilityRequest.java
index b3bc0f29..000d2832 100644
--- a/accord-core/src/main/java/accord/local/durability/DurabilityRequest.java
+++ b/accord-core/src/main/java/accord/local/durability/DurabilityRequest.java
@@ -37,6 +37,7 @@ import accord.primitives.Range;
import accord.primitives.Ranges;
import accord.primitives.SyncPoint;
import accord.primitives.Timestamp;
+import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.utils.Invariants;
import accord.utils.async.AsyncResults;
@@ -44,6 +45,7 @@ import accord.utils.async.AsyncResults;
import static accord.local.durability.DurabilityService.SyncRemote.All;
import static accord.primitives.AbstractRanges.UnionMode.MERGE_ADJACENT;
import static accord.primitives.Routables.Slice.Minimal;
+import static accord.primitives.Txn.Kind.VisibilitySyncPoint;
public class DurabilityRequest
{
@@ -65,6 +67,7 @@ public class DurabilityRequest
final AsyncResults.SettableResult<Void> result = new AsyncResults.SettableResult<>();
final Object requestedBy;
+ final Txn.Kind kind;
final Timestamp min;
final Ranges ranges;
final SyncLocal local;
@@ -78,9 +81,10 @@ public class DurabilityRequest
private LinkedHashMap<TxnId, DurableEvents> events;
- DurabilityRequest(Object requestedBy, Timestamp min, Ranges ranges, SyncLocal local, SyncRemote remote, @Nullable Collection<Node.Id> including, long startedAt, long timeoutAt)
+ DurabilityRequest(Object requestedBy, Txn.Kind kind, Timestamp min, Ranges ranges, SyncLocal local, SyncRemote remote, @Nullable Collection<Node.Id> including, long startedAt, long timeoutAt)
{
this.requestedBy = requestedBy;
+ this.kind = kind;
this.min = min == null ? TxnId.NONE : min;
this.ranges = ranges;
this.local = local;
@@ -141,6 +145,9 @@ public class DurabilityRequest
synchronized boolean report(DurabilityResult durability, long finishedAt)
{
SyncPoint<Range> syncPoint = durability.syncPoint;
+ if (kind == VisibilitySyncPoint && !syncPoint.syncId.is(VisibilitySyncPoint))
+ return false;
+
Ranges intersecting = ranges.intersecting(syncPoint.route, Minimal);
if (intersecting.isEmpty())
return false;
diff --git a/accord-core/src/main/java/accord/local/durability/DurabilityService.java b/accord-core/src/main/java/accord/local/durability/DurabilityService.java
index 2df4976b..66f4d7a6 100644
--- a/accord-core/src/main/java/accord/local/durability/DurabilityService.java
+++ b/accord-core/src/main/java/accord/local/durability/DurabilityService.java
@@ -37,6 +37,7 @@ import accord.primitives.Range;
import accord.primitives.Ranges;
import accord.primitives.SyncPoint;
import accord.primitives.Timestamp;
+import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Topology;
import accord.utils.Invariants;
@@ -96,47 +97,47 @@ public class DurabilityService implements ConfigurationService.Listener
global.stop();
}
- public AsyncResult<Void> close(String requestedBy, Ranges ranges, long timeoutDelay, TimeUnit timeoutUnits)
+ public AsyncResult<Void> close(String requestedBy, Txn.Kind kind, Ranges ranges, long timeoutDelay, TimeUnit timeoutUnits)
{
- return close(requestedBy, TxnId.NONE, ranges, timeoutDelay, timeoutUnits);
+ return close(requestedBy, kind, TxnId.NONE, ranges, timeoutDelay, timeoutUnits);
}
- public AsyncResult<Void> close(Object requestedBy, Timestamp minBound, Ranges ranges, long timeoutDelay, TimeUnit timeoutUnits)
+ public AsyncResult<Void> close(Object requestedBy, Txn.Kind kind, Timestamp minBound, Ranges ranges, long timeoutDelay, TimeUnit timeoutUnits)
{
long startedAt = node.elapsed(MICROSECONDS);
long timeoutAt = startedAt + timeoutUnits.toMicros(timeoutDelay);
- return submit(new DurabilityRequest(requestedBy, minBound, ranges, SyncLocal.NoLocal, SyncRemote.NoRemote, null, startedAt, timeoutAt)).result;
+ return submit(new DurabilityRequest(requestedBy, kind, minBound, ranges, SyncLocal.NoLocal, SyncRemote.NoRemote, null, startedAt, timeoutAt)).result;
}
- public AsyncResult<Void> sync(Object requestedBy, Ranges ranges, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
+ public AsyncResult<Void> sync(Object requestedBy, Txn.Kind kind, Ranges ranges, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
{
- return sync(requestedBy, TxnId.NONE, ranges, local, remote, timeoutDelay, timeoutUnits);
+ return sync(requestedBy, kind, TxnId.NONE, ranges, local, remote, timeoutDelay, timeoutUnits);
}
- public AsyncResult<Void> sync(Object requestedBy, Timestamp minBound, Ranges ranges, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
+ public AsyncResult<Void> sync(Object requestedBy, Txn.Kind kind, Timestamp minBound, Ranges ranges, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
{
long startedAt = node.elapsed(MICROSECONDS);
long timeoutAt = startedAt + timeoutUnits.toMicros(timeoutDelay);
- return submit(new DurabilityRequest(requestedBy, minBound, ranges, local, remote, null, startedAt, timeoutAt)).result;
+ return submit(new DurabilityRequest(requestedBy, kind, minBound, ranges, local, remote, null, startedAt, timeoutAt)).result;
}
- public AsyncResult<Void> sync(Object requestedBy, Ranges ranges, @Nullable Collection<Node.Id> include, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
+ public AsyncResult<Void> sync(Object requestedBy, Txn.Kind kind, Ranges ranges, @Nullable Collection<Node.Id> include, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
{
- return sync(requestedBy, TxnId.NONE, ranges, include, local, remote, timeoutDelay, timeoutUnits);
+ return sync(requestedBy, kind, TxnId.NONE, ranges, include, local, remote, timeoutDelay, timeoutUnits);
}
- public AsyncResult<Void> sync(Object requestedBy, Timestamp minBound, Ranges ranges, @Nullable Collection<Node.Id> include, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
+ public AsyncResult<Void> sync(Object requestedBy, Txn.Kind kind, Timestamp minBound, Ranges ranges, @Nullable Collection<Node.Id> include, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
{
long startedAt = node.elapsed(MICROSECONDS);
long timeoutAt = startedAt + timeoutUnits.toMicros(timeoutDelay);
- return submit(new DurabilityRequest(requestedBy, minBound, ranges, local, remote, include, startedAt, timeoutAt)).result;
+ return submit(new DurabilityRequest(requestedBy, kind, minBound, ranges, local, remote, include, startedAt, timeoutAt)).result;
}
public AsyncResult<Void> sync(Object requestedBy, SyncPoint<Range> syncPoint, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
{
long startedAt = node.elapsed(MICROSECONDS);
long timeoutAt = startedAt + timeoutUnits.toMicros(timeoutDelay);
- DurabilityRequest request = new DurabilityRequest(requestedBy, syncPoint.syncId, syncPoint.route.toRanges(), local, remote, null, startedAt, timeoutAt);
+ DurabilityRequest request = new DurabilityRequest(requestedBy, syncPoint.syncId.kind(), syncPoint.syncId, syncPoint.route.toRanges(), local, remote, null, startedAt, timeoutAt);
logger.info("Requesting durability {}", request);
register(request);
shards.queue().submit(syncPoint, request);
diff --git a/accord-core/src/main/java/accord/local/durability/ShardDurability.java b/accord-core/src/main/java/accord/local/durability/ShardDurability.java
index 82db5db2..e533e25a 100644
--- a/accord-core/src/main/java/accord/local/durability/ShardDurability.java
+++ b/accord-core/src/main/java/accord/local/durability/ShardDurability.java
@@ -44,6 +44,7 @@ import accord.primitives.Ranges;
import accord.primitives.Routable.Domain;
import accord.primitives.SyncPoint;
import accord.primitives.Timestamp;
+import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Shard;
import accord.topology.Topology;
@@ -357,13 +358,18 @@ public class ShardDurability
lastStartedAtMicros = node.elapsed(MICROSECONDS);
long minEpoch = 0;
long minHlc = 0;
- if (activeRequest != null && activeRequest.min != null)
+ Txn.Kind kind = ExclusiveSyncPoint;
+ if (activeRequest != null)
{
- minEpoch = activeRequest.min.epoch();
- minHlc = activeRequest.min.hlc();
+ kind = activeRequest.kind;
+ if (activeRequest.min != null)
+ {
+ minEpoch = activeRequest.min.epoch();
+ minHlc = activeRequest.min.hlc();
+ }
}
minHlc = Math.max(minHlc, node.agent().minStaleHlc(node, activeRequest != null));
- TxnId staleId = node.nextStaleTxnId(minEpoch, minHlc, ExclusiveSyncPoint, Domain.Range);
+ TxnId staleId = node.nextStaleTxnId(minEpoch, minHlc, kind, Domain.Range);
if (activeRequest != null) logger.info("Initiating RX requested by {} for {} with TxnId {}. Remaining: {}.", activeRequest.requestedBy, ranges, staleId, active);
else logger.debug("Initiating RX for durability of {} with TxnId {}.", ranges, staleId);
diff --git a/accord-core/src/main/java/accord/messages/Await.java b/accord-core/src/main/java/accord/messages/Await.java
index cdc3dea2..7212e535 100644
--- a/accord-core/src/main/java/accord/messages/Await.java
+++ b/accord-core/src/main/java/accord/messages/Await.java
@@ -161,7 +161,7 @@ public class Await implements Request, MapReduceConsume<SafeCommandStore, Void>,
RemoteListeners.Registration registered = asyncRegistration;
if (registered == null)
{
- registered = node.remoteListeners().register(txnId, blockedUntil.unblockedFrom, blockedUntil.remoteDurability, replyTo, callbackId);
+ registered = node.remoteListeners().register(txnId, blockedUntil.unblockedFrom, blockedUntil.remoteOutcomeDurability, replyTo, callbackId);
if (!registrationUpdater.compareAndSet(this, null, registered))
registered = asyncRegistration;
}
diff --git a/accord-core/src/main/java/accord/messages/BeginRecovery.java b/accord-core/src/main/java/accord/messages/BeginRecovery.java
index 233cd542..5b1b425f 100644
--- a/accord-core/src/main/java/accord/messages/BeginRecovery.java
+++ b/accord-core/src/main/java/accord/messages/BeginRecovery.java
@@ -48,8 +48,10 @@ import accord.utils.UnhandledEnum;
import accord.utils.async.Cancellable;
import static accord.local.CommandSummaries.ComputeIsDep.EITHER;
+import static accord.local.CommandSummaries.SummaryStatus.APPLIED;
import static accord.local.CommandSummaries.SummaryStatus.NOT_DIRECTLY_WITNESSED;
import static accord.local.CommandSummaries.SummaryStatus.ACCEPTED;
+import static accord.local.CommandSummaries.SummaryStatus.STABLE;
import static accord.local.CommandSummaries.TestStartedAt.ANY;
import static accord.messages.BeginRecovery.RecoverReply.Kind.Ok;
import static accord.messages.BeginRecovery.RecoverReply.Kind.Reject;
@@ -62,7 +64,6 @@ import static accord.primitives.Status.AcceptedMedium;
import static accord.primitives.Status.Phase;
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.PrivilegedCoordinatorWithDeps;
@@ -146,7 +147,7 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
boolean supersedingRejects;
Deps earlierNoWait, earlierWait;
Deps laterCoordRejects;
- if (command.hasBeen(AcceptedMedium) || txnId.is(ExclusiveSyncPoint))
+ if (command.hasBeen(AcceptedMedium) || txnId.isSyncPoint())
{
supersedingRejects = !command.hasBeen(AcceptedMedium);
earlierNoWait = earlierWait = Deps.NONE;
@@ -230,7 +231,7 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
@Override
public LoadKeysFor loadKeysFor()
{
- if (txnId.is(ExclusiveSyncPoint))
+ if (txnId.isSyncPoint())
return LoadKeysFor.READ_WRITE;
return LoadKeysFor.RECOVERY;
}
@@ -275,7 +276,7 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
if (c < 0)
{
- if (testTxnId.is(ExclusiveSyncPoint) && testTxnId.hlc() > txnId.hlc() && txnId.is(Write))
+ if (testTxnId.isSyncPoint() && testTxnId.hlc() > txnId.hlc() && txnId.is(Write))
{
// TODO (required): define our invariants and make sure they're enforce elsewhere.
// Specifically, consider whether truncation/GC can lead to erroneous answers here.
@@ -305,11 +306,12 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
switch (dep)
{
default: throw new UnhandledEnum(dep);
- case IS_STABLE_DEP:
- ensureEarlierNoWait().add(keyOrRange, testTxnId);
+ case IS_PROPOSED_OR_STABLE_DEP:
+ if (status == STABLE || status == APPLIED)
+ ensureEarlierNoWait().add(keyOrRange, testTxnId);
break;
- case IS_NOT_STABLE_DEP:
+ case IS_NOT_PROPOSED_OR_STABLE_DEP:
/*
* The idea here is to discover those transactions that have been decided to execute after us
* and did not witness us as part of their pre-accept or accept round, as this means that we CANNOT have
@@ -347,7 +349,7 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
{
switch (dep)
{
- case IS_NOT_STABLE_DEP:
+ case IS_NOT_PROPOSED_OR_STABLE_DEP:
/*
* The idea here is to discover those transactions that were started after us and have been Accepted
* and did not witness us as part of their pre-accept round, as this means that we CANNOT have taken
@@ -359,7 +361,7 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
case NOT_ELIGIBLE:
// the command doesn't have any coordinator deps; or we are its coordinator and cannot commit on the privileged fast path
- case IS_STABLE_DEP:
+ case IS_PROPOSED_OR_STABLE_DEP:
// the command has been committed with stable deps that witness us, so we're a durable dependency
case IS_COORD_DEP:
// the original coordinator witnessed us, so if it takes the fast or medium path we will be a durable dependency
diff --git a/accord-core/src/main/java/accord/messages/CheckStatus.java b/accord-core/src/main/java/accord/messages/CheckStatus.java
index eb76f021..795a1234 100644
--- a/accord-core/src/main/java/accord/messages/CheckStatus.java
+++ b/accord-core/src/main/java/accord/messages/CheckStatus.java
@@ -36,6 +36,8 @@ import accord.primitives.Status;
import accord.local.StoreParticipants;
import accord.primitives.Ballot;
import accord.primitives.KnownMap;
+import accord.primitives.Status.Durability.HasOutcome;
+import accord.primitives.Status.Durability.HasPhase;
import accord.primitives.WithQuorum;
import accord.primitives.PartialDeps;
import accord.primitives.PartialTxn;
@@ -61,17 +63,21 @@ import static accord.messages.MessageType.StandardMessage.CHECK_STATUS_REQ;
import static accord.messages.MessageType.StandardMessage.CHECK_STATUS_RSP;
import static accord.primitives.Known.Definition.DefinitionKnown;
import static accord.primitives.Known.Definition.DefinitionUnknown;
+import static accord.primitives.Known.KnownDeps.DepsKnown;
import static accord.primitives.Known.KnownDeps.DepsUnknown;
+import static accord.primitives.Known.KnownExecuteAt.ExecuteAtKnown;
+import static accord.primitives.Known.KnownExecuteAt.ExecuteAtProposed;
import static accord.primitives.Status.Durability;
-import static accord.primitives.Status.Durability.Local;
-import static accord.primitives.Status.Durability.Majority;
-import static accord.primitives.Status.Durability.ShardUniversal;
-import static accord.primitives.Status.Durability.Universal;
import accord.primitives.Known;
import accord.utils.async.Cancellable;
+import static accord.primitives.Status.Durability.HasOutcome.None;
+import static accord.primitives.Status.Durability.HasOutcome.Quorum;
import static accord.primitives.Status.NotDefined;
+import static accord.primitives.Status.Durability.HasPhase.DurablyCommitted;
+import static accord.primitives.Status.Durability.HasPhase.DurablyStable;
+import static accord.primitives.Status.Durability.HasPhase.FastPathDecided;
import static accord.primitives.Status.Stable;
import static accord.primitives.Status.Truncated;
import static accord.messages.TxnRequest.computeScope;
@@ -314,7 +320,7 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
public ProgressToken toProgressToken()
{
Status status = maxSaveStatus.status;
- return new ProgressToken(durability, status, maxPromised, maxAcceptedOrCommitted);
+ return new ProgressToken(durability.allShardsOrInvalidated(), status, maxPromised, maxAcceptedOrCommitted);
}
public Timestamp executeAtIfKnown()
@@ -327,13 +333,6 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
public CheckStatusOk finish(Unseekables<?> queried, Unseekables<?> requestedFor, Unseekables<?> routeOrParticipants, WithQuorum withQuorum, InvalidIf previouslyKnownToBeInvalidIf)
{
CheckStatusOk finished = this;
- if (withQuorum == HasQuorum)
- {
- Durability durability = this.durability;
- if (durability == Local) durability = Majority;
- else if (durability == ShardUniversal) durability = Universal;
- finished = finished.merge(durability);
- }
if (Route.isRoute(routeOrParticipants))
{
@@ -346,14 +345,30 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
}
Known validForAll = map.computeValidForAll(routeOrParticipants);
- if (withQuorum == HasQuorum && (invalidIf == IfUncommitted || previouslyKnownToBeInvalidIf == IfUncommitted) && queried.containsAll(requestedFor))
+ if (withQuorum == HasQuorum)
{
Known minKnown = finished.minMaxKnown(queried), maxKnown = finished.maxKnown(queried);
- InvalidIf invalidIf = this.invalidIf.inferWithQuorum(minKnown, maxKnown);
- invalidIf = invalidIf.inferWithNewQuorum(previouslyKnownToBeInvalidIf, maxKnown);
- if (invalidIf == IsInvalid)
- validForAll = validForAll.atLeast(Known.Invalidated);
- finished = finished.with(invalidIf);
+ {
+ HasOutcome addShard = Durability.HasOutcome.max(minKnown.outcome().isOrWasApply() ? Quorum : None, finished.durability.shard());
+ HasOutcome addAllShards = None;
+ if (addShard != None && Route.isFullRoute(finished.route) && queried.containsAll(finished.route))
+ addAllShards = addShard;
+ HasPhase addPhase;
+ if (minKnown.is(DepsKnown)) addPhase = DurablyStable;
+ else if (minKnown.is(ExecuteAtKnown)) addPhase = DurablyCommitted;
+ else if (minKnown.is(ExecuteAtProposed)) addPhase = FastPathDecided;
+ else addPhase = Durability.HasPhase.None;
+ finished = finished.merge((Durability.get(addPhase, addShard, addAllShards, minKnown.isInvalidated())));
+ }
+ // TODO (required): should we require that we contacted the coordination epoch?
+ if (invalidIf == IfUncommitted || previouslyKnownToBeInvalidIf == IfUncommitted)
+ {
+ InvalidIf invalidIf = this.invalidIf.inferWithQuorum(minKnown, maxKnown);
+ invalidIf = invalidIf.inferWithNewQuorum(previouslyKnownToBeInvalidIf, minKnown);
+ if (invalidIf == IsInvalid)
+ validForAll = validForAll.atLeast(Known.Invalidated);
+ finished = finished.with(invalidIf);
+ }
}
return finished.with(map.with(validForAll));
@@ -375,7 +390,7 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
public CheckStatusOk merge(@Nonnull Durability durability)
{
- durability = Durability.merge(durability, this.durability);
+ durability = durability.mergeMax(this.durability);
if (durability == this.durability)
return this;
return new CheckStatusOk(map, maxKnowledgeSaveStatus, maxSaveStatus, maxPromised, maxAcceptedOrCommitted, acceptedOrCommitted,
@@ -462,7 +477,7 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
CheckStatusOk maxHomeKey = prefer.homeKey != null || defer.homeKey == null ? prefer : defer;
CheckStatusOk maxExecuteAt = prefer.maxKnown().executeAt().compareTo(defer.maxKnown().executeAt()) >= 0 ? prefer : defer;
Route<?> mergedRoute = Route.merge(prefer.route, (Route)defer.route);
- Durability mergedDurability = Durability.merge(prefer.durability, defer.durability);
+ Durability mergedDurability = prefer.durability.mergeShardsOrReplicas(defer.durability);
InvalidIf invalidIf = prefer.invalidIf.atLeast(defer.invalidIf);
// if the maximum (or preferred equal) is the same on all dimensions, return it
@@ -502,6 +517,11 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
return map.foldlWithDefault(query, Known::nonNullOrMin, MinMax.Nothing, null, i -> false);
}
+ public Known minMaxKnown(RoutingKey key)
+ {
+ return Known.nonNullOrMin(map.get(key), MinMax.Nothing);
+ }
+
@Override
public MessageType type()
{
@@ -553,7 +573,7 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
public CheckStatusOkFull merge(@Nonnull Durability durability)
{
- durability = Durability.merge(durability, this.durability);
+ durability = durability.mergeMax(this.durability);
if (durability == this.durability)
return this;
return new CheckStatusOkFull(map, maxKnowledgeSaveStatus, maxSaveStatus, maxPromised, maxAcceptedOrCommitted, acceptedOrCommitted,
diff --git a/accord-core/src/main/java/accord/messages/InformDecided.java b/accord-core/src/main/java/accord/messages/InformDecided.java
deleted file mode 100644
index 647b5d25..00000000
--- a/accord-core/src/main/java/accord/messages/InformDecided.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package accord.messages;
-
-import accord.api.RoutingKey;
-import accord.local.Node;
-import accord.local.SafeCommandStore;
-import accord.primitives.Route;
-import accord.primitives.TxnId;
-import accord.topology.Shard;
-import accord.topology.Topologies;
-import accord.utils.async.Cancellable;
-
-import static accord.messages.MessageType.StandardMessage.INFORM_DECIDED_REQ;
-
-public class InformDecided extends AbstractRequest<Reply>
-{
- public static class SerializationSupport
- {
- public static InformDecided create(TxnId txnId, RoutingKey homeKey)
- {
- return new InformDecided(txnId, homeKey);
- }
- }
-
- public final RoutingKey homeKey;
- public InformDecided(TxnId txnId, RoutingKey homeKey)
- {
- super(txnId);
- this.homeKey = homeKey;
- }
-
- public static void informHome(Node node, Topologies any, TxnId txnId, Route<?> route)
- {
- Shard homeShard = InformDurable.homeShard(node, any, txnId, route.homeKey());
- node.send(homeShard.nodes, to -> new InformDecided(txnId, route.homeKey()));
- }
-
- @Override
- public Cancellable submit()
- {
- // TODO (expected): do not load from disk to perform this update, just write a delta to any journal
- return node.mapReduceConsumeLocal(this, homeKey, txnId.epoch(), this);
- }
-
- @Override
- public Reply apply(SafeCommandStore safeStore)
- {
- safeStore.progressLog().decided(safeStore, txnId);
- return null;
- }
-
- @Override
- public TxnId primaryTxnId()
- {
- // we don't need the transaction loaded to update the progress log
- return null;
- }
-
- @Override
- protected void acceptInternal(Reply reply, Throwable failure)
- {
- }
-
- @Override
- public String toString()
- {
- return "InformDecided{" +
- "txnId:" + txnId +
- '}';
- }
-
- @Override
- public MessageType type()
- {
- return INFORM_DECIDED_REQ;
- }
-}
diff --git a/accord-core/src/main/java/accord/messages/InformDurable.java b/accord-core/src/main/java/accord/messages/InformDurable.java
index 1a4df25f..51701df4 100644
--- a/accord-core/src/main/java/accord/messages/InformDurable.java
+++ b/accord-core/src/main/java/accord/messages/InformDurable.java
@@ -39,7 +39,7 @@ import accord.topology.Topologies;
import accord.topology.Topology;
import accord.utils.async.Cancellable;
-import static accord.api.ProtocolModifiers.Toggles.DependencyElision.IF_DURABLE;
+import static accord.api.ProtocolModifiers.Toggles.DependencyElision.IF_DURABLY_COMMITTED;
import static accord.api.ProtocolModifiers.Toggles.dependencyElision;
import static accord.api.ProtocolModifiers.Toggles.informOfDurability;
import static accord.messages.MessageType.StandardMessage.INFORM_DURABLE_REQ;
@@ -88,7 +88,7 @@ public class InformDurable extends TxnRequest<Reply> implements PreLoadContext
}
}
- public static void informHome(Node node, Topologies any, TxnId txnId, Route<?> route, Timestamp executeAt, Durability durability)
+ public static void informHome(Node node, Topologies any, TxnId txnId, Route<?> route, @Nullable Timestamp executeAt, Durability durability)
{
Shard homeShard = homeShard(node, any, txnId, route.homeKey());
Topologies homeTopology = new Topologies.Single(any, new Topology(txnId.epoch(), homeShard));
@@ -141,7 +141,7 @@ public class InformDurable extends TxnRequest<Reply> implements PreLoadContext
@Override
public LoadKeys loadKeys()
{
- return dependencyElision() == IF_DURABLE ? LoadKeys.ASYNC : LoadKeys.NONE;
+ return dependencyElision() == IF_DURABLY_COMMITTED ? LoadKeys.ASYNC : LoadKeys.NONE;
}
@Override
diff --git a/accord-core/src/main/java/accord/messages/MessageType.java b/accord-core/src/main/java/accord/messages/MessageType.java
index 8c1d3566..a75cb966 100644
--- a/accord-core/src/main/java/accord/messages/MessageType.java
+++ b/accord-core/src/main/java/accord/messages/MessageType.java
@@ -42,7 +42,6 @@ public interface MessageType
CHECK_STATUS_REQ, CHECK_STATUS_RSP,
FETCH_DATA_REQ, FETCH_DATA_RSP,
INFORM_DURABLE_REQ,
- INFORM_DECIDED_REQ,
GET_LATEST_DEPS_REQ, GET_LATEST_DEPS_RSP,
GET_MAX_CONFLICT_REQ, GET_MAX_CONFLICT_RSP,
GET_DURABLE_BEFORE_REQ, GET_DURABLE_BEFORE_RSP,
diff --git a/accord-core/src/main/java/accord/messages/Propagate.java b/accord-core/src/main/java/accord/messages/Propagate.java
index d0894057..f9c8aa90 100644
--- a/accord-core/src/main/java/accord/messages/Propagate.java
+++ b/accord-core/src/main/java/accord/messages/Propagate.java
@@ -52,6 +52,7 @@ 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;
@@ -73,7 +74,6 @@ import static accord.primitives.Known.Nothing;
import static accord.primitives.SaveStatus.Stable;
import static accord.primitives.Status.NotDefined;
import static accord.primitives.Status.PreApplied;
-import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.primitives.WithQuorum.HasQuorum;
import static accord.utils.Invariants.illegalState;
@@ -302,8 +302,11 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
switch (propagate.status)
{
- default: throw illegalState("Unexpected status: " + propagate);
- case Truncated: throw illegalState("Status expected to be handled elsewhere: " + propagate);
+ default: throw UnhandledEnum.invalid(propagate);
+ case NotDefined:
+ case Truncated:
+ throw illegalState("Status expected to be handled elsewhere: " + propagate);
+
case AcceptedMedium:
case AcceptedSlow:
case AcceptedInvalidate:
@@ -350,14 +353,6 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
tracing.trace(safeStore.commandStore(), "Pre-accepting");
Commands.preaccept(safeStore, safeCommand, participants, txnId, partialTxn, null, false);
}
-
- case NotDefined:
- if (invalidIf == IfUncommitted)
- {
- if (tracing != null)
- tracing.trace(safeStore.commandStore(), "Marking invalidIfUncommitted");
- safeStore.progressLog().invalidIfUncommitted(txnId);
- }
break;
}
@@ -421,7 +416,7 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
Known required = PreApplied.minKnown;
Known requireExtra = required.subtract(command.known()); // the extra information we need to reach pre-applied
- Participants<?> stillOwnsOrMayExecute = txnId.is(ExclusiveSyncPoint) ? participants.stillTouches() : participants.stillOwns();
+ Participants<?> stillOwnsOrMayExecute = txnId.isSyncPoint() ? participants.stillTouches() : participants.stillOwns();
Participants<?> notStaleTouches = known.knownFor(Nothing.with(requireExtra.deps()), stillTouches); // the ranges for which we can already successfully achieve this
Participants<?> notStaleOwnsOrMayExecute = known.knownFor(requireExtra.with(DepsUnknown), stillOwnsOrMayExecute); // the ranges for which we can already successfully achieve this
@@ -507,7 +502,7 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
*/
private Void updateDurability(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants)
{
- if (!durability.isDurable() || homeKey == null)
+ if (!durability.isFastPathDurablyDecided() || homeKey == null)
return null;
Commands.setDurability(safeStore, safeCommand, participants, durability, committedExecuteAt);
diff --git a/accord-core/src/main/java/accord/messages/RecoverAwait.java b/accord-core/src/main/java/accord/messages/RecoverAwait.java
index c6a311ae..87ea73b2 100644
--- a/accord-core/src/main/java/accord/messages/RecoverAwait.java
+++ b/accord-core/src/main/java/accord/messages/RecoverAwait.java
@@ -29,7 +29,6 @@ import accord.local.SafeCommandStore;
import accord.primitives.Ballot;
import accord.primitives.Known.KnownDeps;
import accord.primitives.Participants;
-import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Topologies;
@@ -81,7 +80,7 @@ public class RecoverAwait extends Await
if ((knownDeps.hasCommittedOrDecidedDeps() ? command.executeAt() : txnId).compareTo(recoverId) < 0)
{
- if (txnId.is(Txn.Kind.ExclusiveSyncPoint) && txnId.hlc() > recoverId.hlc() && command.executeAt().is(HLC_BOUND))
+ if (txnId.isSyncPoint() && txnId.hlc() > recoverId.hlc() && command.executeAt().is(HLC_BOUND))
{
rejects = true;
node.reply(replyTo, replyContext, RecoverAwaitOk.Reject, null);
diff --git a/accord-core/src/main/java/accord/messages/SetShardDurable.java b/accord-core/src/main/java/accord/messages/SetShardDurable.java
index 5f27c3e1..77af8e2d 100644
--- a/accord-core/src/main/java/accord/messages/SetShardDurable.java
+++ b/accord-core/src/main/java/accord/messages/SetShardDurable.java
@@ -21,7 +21,7 @@ package accord.messages;
import accord.local.PreLoadContext;
import accord.local.SafeCommandStore;
import accord.primitives.AbstractRanges;
-import accord.primitives.Status.Durability;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.SyncPoint;
import accord.primitives.TxnId;
import accord.utils.Invariants;
@@ -30,20 +30,22 @@ import accord.utils.async.Cancellable;
import static accord.messages.MessageType.StandardMessage.SET_SHARD_DURABLE_REQ;
import static accord.messages.SimpleReply.Ok;
+import static accord.primitives.Status.Durability.HasOutcome.Quorum;
+import static accord.primitives.Status.Durability.HasOutcome.Universal;
import static accord.primitives.Timestamp.Flag.SHARD_BOUND;
public class SetShardDurable extends AbstractRequest<SimpleReply>
implements Request, PreLoadContext, MapReduceConsume<SafeCommandStore, SimpleReply>
{
public final SyncPoint exclusiveSyncPoint;
- public final Durability durability;
+ public final HasOutcome durability;
- public SetShardDurable(SyncPoint exclusiveSyncPoint, Durability durability)
+ public SetShardDurable(SyncPoint exclusiveSyncPoint, HasOutcome durability)
{
super(exclusiveSyncPoint.syncId);
this.exclusiveSyncPoint = exclusiveSyncPoint;
this.durability = durability;
- Invariants.require(durability.compareTo(Durability.MajorityOrInvalidated) >= 0);
+ Invariants.require(durability.compareTo(Quorum) >= 0);
}
private TxnId syncIdWithFlags()
@@ -54,9 +56,9 @@ public class SetShardDurable extends AbstractRequest<SimpleReply>
@Override
public Cancellable submit()
{
- Invariants.require(durability.compareTo(Durability.MajorityOrInvalidated) >= 0);
+ Invariants.require(durability.compareTo(Quorum) >= 0);
TxnId syncIdWithFlags = syncIdWithFlags();
- node.markDurable(exclusiveSyncPoint.route.toRanges(), syncIdWithFlags, durability.compareTo(Durability.UniversalOrInvalidated) >= 0 ? syncIdWithFlags : TxnId.NONE)
+ node.markDurable(exclusiveSyncPoint.route.toRanges(), syncIdWithFlags, durability.compareTo(Universal) >= 0 ? syncIdWithFlags : TxnId.NONE)
.invoke((success, fail) -> {
if (fail != null) node.reply(replyTo, replyContext, null, fail);
else node.mapReduceConsumeLocal(this, exclusiveSyncPoint.route, waitForEpoch(), waitForEpoch(), this);
diff --git a/accord-core/src/main/java/accord/primitives/Known.java b/accord-core/src/main/java/accord/primitives/Known.java
index d716b9b6..6f3df6b8 100644
--- a/accord-core/src/main/java/accord/primitives/Known.java
+++ b/accord-core/src/main/java/accord/primitives/Known.java
@@ -133,6 +133,7 @@ public class Known
{
return a == null | b == null ? a == null ? b : a : a.min(b);
}
+
public Known min(Known that)
{
Invariants.requireArgument(compatibleWith(that));
diff --git a/accord-core/src/main/java/accord/primitives/ProgressToken.java b/accord-core/src/main/java/accord/primitives/ProgressToken.java
index 0fe6f4c2..28178397 100644
--- a/accord-core/src/main/java/accord/primitives/ProgressToken.java
+++ b/accord-core/src/main/java/accord/primitives/ProgressToken.java
@@ -20,10 +20,12 @@ package accord.primitives;
import accord.coordinate.Outcome;
import accord.local.Command;
-import accord.primitives.Status.Durability;
+import accord.primitives.Status.Durability.HasOutcomeOrInvalidated;
import javax.annotation.Nonnull;
+import static accord.primitives.Status.Durability.HasOutcomeOrInvalidated.None;
+import static accord.primitives.Status.Durability.HasOutcomeOrInvalidated.UniversalOrInvalidated;
import static accord.primitives.Status.Phase.Accept;
import static accord.primitives.Status.Phase.Commit;
@@ -32,28 +34,27 @@ import static accord.primitives.Status.Phase.Commit;
*/
public class ProgressToken implements Comparable<ProgressToken>, Outcome
{
- public static final ProgressToken NONE = new ProgressToken(Durability.NotDurable, Status.NotDefined, Ballot.ZERO, false);
- public static final ProgressToken INVALIDATED = new ProgressToken(Durability.MajorityOrInvalidated, Status.Invalidated, Ballot.ZERO, false);
- public static final ProgressToken APPLIED = new ProgressToken(Durability.NotDurable, Status.PreApplied, Ballot.ZERO, false);
- public static final ProgressToken DURABLE = new ProgressToken(Durability.Majority, Status.PreApplied, Ballot.ZERO, false);
- public static final ProgressToken TRUNCATED_DURABLE_OR_INVALIDATED = new ProgressToken(Durability.MajorityOrInvalidated, Status.Truncated, Ballot.ZERO, false);
+ public static final ProgressToken NONE = new ProgressToken(None, Status.NotDefined, Ballot.ZERO, false);
+ public static final ProgressToken INVALIDATED = new ProgressToken(UniversalOrInvalidated, Status.Invalidated, Ballot.ZERO, false);
+ public static final ProgressToken APPLIED = new ProgressToken(None, Status.PreApplied, Ballot.ZERO, false);
+ public static final ProgressToken TRUNCATED_DURABLE_OR_INVALIDATED = new ProgressToken(UniversalOrInvalidated, Status.Truncated, Ballot.ZERO, false);
- public final Durability durability;
+ public final HasOutcomeOrInvalidated outcome;
public final Status status;
public final Ballot promised;
public final boolean isAccepted; // is the *promised ballot* accepted
- public ProgressToken(Durability durability, Status status, Ballot promised, boolean isAccepted)
+ public ProgressToken(HasOutcomeOrInvalidated outcome, Status status, Ballot promised, boolean isAccepted)
{
- this.durability = durability;
+ this.outcome = outcome;
this.status = status;
this.promised = promised;
this.isAccepted = isAccepted;
}
- public ProgressToken(Durability durability, Status status, Ballot promised, Ballot accepted)
+ public ProgressToken(HasOutcomeOrInvalidated outcome, Status status, Ballot promised, Ballot accepted)
{
- this.durability = durability;
+ this.outcome = outcome;
this.status = status;
this.promised = promised;
this.isAccepted = isAccepted(status, promised, accepted);
@@ -61,7 +62,7 @@ public class ProgressToken implements Comparable<ProgressToken>, Outcome
@Override public int compareTo(@Nonnull ProgressToken that)
{
- int c = this.durability.compareTo(that.durability);
+ int c = this.outcome.compareTo(that.outcome);
if (c == 0) c = this.status.phase.compareTo(that.status.phase);
if (c == 0) c = this.promised.compareTo(that.promised);
if (c == 0 && this.isAccepted != that.isAccepted) c = this.isAccepted ? 1 : -1;
@@ -70,7 +71,7 @@ public class ProgressToken implements Comparable<ProgressToken>, Outcome
public int compareTo(@Nonnull Command that)
{
- int c = this.durability.compareTo(that.durability());
+ int c = this.outcome.compareTo(that.durability().allShardsOrInvalidated());
if (c == 0) c = this.status.phase.compareTo(that.status().phase);
if (c == 0) c = this.promised.compareTo(that.promised());
if (c == 0 && this.isAccepted != isAccepted(that.status(), that.promised(), that.acceptedOrCommitted())) c = this.isAccepted ? 1 : -1;
@@ -79,7 +80,7 @@ public class ProgressToken implements Comparable<ProgressToken>, Outcome
public ProgressToken merge(ProgressToken that)
{
- Durability durability = this.durability.compareTo(that.durability) >= 0 ? this.durability : that.durability;
+ HasOutcomeOrInvalidated durability = this.outcome.mergeMax(that.outcome);
Status status = this.status.compareTo(that.status) >= 0 ? this.status : that.status;
Ballot promised = this.promised.compareTo(that.promised) >= 0 ? this.promised : that.promised;
boolean isAccepted = (this.isAccepted && this.promised.equals(promised)) || (that.isAccepted && that.promised.equals(promised));
@@ -92,10 +93,7 @@ public class ProgressToken implements Comparable<ProgressToken>, Outcome
public ProgressToken merge(Command command)
{
- Durability durability = command.durability();
- if (this.durability.compareTo(command.durability()) > 0)
- durability = this.durability;
-
+ HasOutcomeOrInvalidated durability = this.outcome.mergeMax(command.durability().allShardsOrInvalidated());
Status status = command.status();
if (this.status.compareTo(status) > 0)
status = this.status;
@@ -113,9 +111,9 @@ public class ProgressToken implements Comparable<ProgressToken>, Outcome
return new ProgressToken(durability, status, promised, isAccepted);
}
- private boolean isSame(Durability durability, Status status, Ballot promised, boolean isAccepted)
+ private boolean isSame(HasOutcomeOrInvalidated durability, Status status, Ballot promised, boolean isAccepted)
{
- return durability == this.durability && status == this.status && promised.equals(this.promised) && isAccepted == this.isAccepted;
+ return durability == this.outcome && status == this.status && promised.equals(this.promised) && isAccepted == this.isAccepted;
}
@Override
diff --git a/accord-core/src/main/java/accord/primitives/Status.java b/accord-core/src/main/java/accord/primitives/Status.java
index 67d80dee..7736622d 100644
--- a/accord-core/src/main/java/accord/primitives/Status.java
+++ b/accord-core/src/main/java/accord/primitives/Status.java
@@ -18,8 +18,11 @@
package accord.primitives;
+import accord.api.ProgressLog;
import accord.local.CommandSummaries.SummaryStatus;
import accord.messages.BeginRecovery;
+import accord.utils.Invariants;
+import accord.utils.UnhandledEnum;
import java.util.Collection;
import java.util.function.Function;
@@ -27,6 +30,10 @@ import java.util.function.Predicate;
import javax.annotation.Nullable;
+import static accord.api.ProgressLog.BlockedUntil.CanApply;
+import static accord.api.ProgressLog.BlockedUntil.HasDecidedExecuteAt;
+import static accord.api.ProgressLog.BlockedUntil.HasStableDeps;
+import static accord.api.ProgressLog.BlockedUntil.NotBlocked;
import static accord.local.CommandSummaries.SummaryStatus.ACCEPTED;
import static accord.local.CommandSummaries.SummaryStatus.APPLIED;
import static accord.local.CommandSummaries.SummaryStatus.COMMITTED;
@@ -48,7 +55,7 @@ import static accord.primitives.Status.Phase.*;
public enum Status
{
- NotDefined (None, NOT_DIRECTLY_WITNESSED, Nothing),
+ NotDefined (Phase.None, NOT_DIRECTLY_WITNESSED, Nothing),
PreAccepted (PreAccept, PREACCEPTED, DefinitionAndRoute),
AcceptedInvalidate(Accept, NOTACCEPTED, MaybeRoute, DefinitionUnknown, ExecuteAtUnknown, DepsUnknown, Unknown), // may or may not have witnessed
@@ -123,82 +130,402 @@ public enum Status
}
}
- /**
- * Represents the durability of a transaction's Persist phase.
- * NotDurable: the outcome has not been durably recorded
- * Local: the outcome has been durably recorded at least locally
- * ShardUniversalOrInvalidated: the outcome has been durably recorded at all healthy replicas of the shard, or is invalidated
- * ShardUniversal: the outcome has been durably recorded at all healthy replicas of the shard
- * MajorityOrInvalidated: the outcome has been durably recorded to a majority of each participating shard
- * Majority: the outcome has been durably recorded to a majority of each participating shard
- * Universal: the outcome has been durably recorded to every healthy replica
- * DurableOrInvalidated: the outcome was either invalidated, or has been durably recorded to every healthy replica
- */
- public enum Durability
+ public static final class Durability
{
- NotDurable, Local, ShardUniversal,
- MajorityOrInvalidated, Majority,
- UniversalOrInvalidated, Universal;
-
+ private static final int MAYBE_INVALIDATED_BIT = 1;
+ private static final int SHARDS_SHIFT = 3;
+ private static final int PHASE_SHIFT = 1;
+ private static final int PHASE_MASK = 0x3;
+ public static final int TOTAL_ENCODING_BITS = 6;
private static final Durability[] lookup = values();
+ public static final Durability NotDurable = get(HasPhase.None, HasOutcome.None, HasOutcome.None, false);
+ public static final Durability DurablyCommitted = get(HasPhase.DurablyCommitted, HasOutcome.None, HasOutcome.None, false);
+ public static final Durability DurablyStable = get(HasPhase.DurablyStable, HasOutcome.None, HasOutcome.None, false);
+ public static final Durability ShardUniversal = get(HasPhase.None, HasOutcome.Universal, HasOutcome.None, false);
+ public static final Durability AllQuorums = get(HasPhase.DurablyStable, HasOutcome.Quorum, HasOutcome.Quorum, false);
+ public static final Durability Universal = get(HasPhase.DurablyStable, HasOutcome.Universal, HasOutcome.Universal, false);
+ public static final Durability Invalidated = get(HasPhase.None, HasOutcome.None, HasOutcome.None, true);
+ public static final Durability UniversalOrInvalidated = get(HasPhase.None, HasOutcome.Universal, HasOutcome.Universal, true);
+
+ public enum HasPhase
+ {
+ None('N', "None"),
+ FastPathDecided('F', "FastPath"),
+ DurablyCommitted('C', "Committed"),
+ DurablyStable('S', "Stable");
+
+ private static final HasPhase[] lookup = values();
+ final char shortName;
+ final String mediumName;
+
+ HasPhase(char shortName, String mediumName)
+ {
+ this.shortName = shortName;
+ this.mediumName = mediumName;
+ }
+ }
+
+ /**
+ * Represents the durability of a transaction's Persist phase.
+ * NotDurable: the outcome has not been durably recorded
+ * Quorum: the outcome has been durably recorded to a quorum (maybe minority quorum where intersects other quorums) of each participating shard
+ * Universal: the outcome has been durably recorded to every healthy replica
+ */
+ public enum HasOutcome
+ {
+ None, Quorum, Universal;
+ public final boolean isDurable() { return this != None; }
+ public final boolean isUniversal() { return this == Universal; }
+ private static final HasOutcome[] lookup = values();
+ public static HasOutcome forOrdinal(int ordinal) { return lookup[ordinal]; }
+ public static HasOutcome max(HasOutcome a, HasOutcome b) { return a.compareTo(b) >= 0 ? a : b; }
+ public static int maxEncoded() { return lookup.length; }
+ }
+
+ /**
+ * Represents the durability of a transaction's Persist phase.
+ * NotDurable: the outcome has not been durably recorded
+ * Quorum: the outcome has been durably recorded to a quorum (maybe minority quorum where intersects other quorums) of each participating shard
+ * Universal: the outcome has been durably recorded to every healthy replica
+ */
+ public enum HasOutcomeOrInvalidated
+ {
+ None, QuorumOrInvalidated, Quorum, UniversalOrInvalidated, Universal;
+ public final boolean isDurableOrInvalidated() { return this != None; }
+ public final boolean isMaybeInvalidated() { return this == QuorumOrInvalidated || this == UniversalOrInvalidated; }
+ public final HasOutcomeOrInvalidated mergeMax(HasOutcomeOrInvalidated that) { return max(this, that); }
+ private static final HasOutcomeOrInvalidated[] lookup = values();
+ public static HasOutcomeOrInvalidated forOrdinal(int ordinal) { return lookup[ordinal]; }
+ public static HasOutcomeOrInvalidated max(HasOutcomeOrInvalidated a, HasOutcomeOrInvalidated b) { return a.compareTo(b) >= 0 ? a : b; }
+ public static int maxEncoded() { return lookup.length; }
+ }
+
+ private static int encode(HasPhase phase, HasOutcome shardOutcome, HasOutcome allShardsOutcome, boolean isMaybeInvalidated)
+ {
+ return encode(phase.ordinal(), shardOutcome.ordinal(), allShardsOutcome.ordinal(), isMaybeInvalidated ? MAYBE_INVALIDATED_BIT : 0);
+ }
+
+ private static int encode(int phaseOrdinal, int shardOutcome, int allShardsOutcome, int maybeInvalidated)
+ {
+ Invariants.require(allShardsOutcome <= shardOutcome);
+ Invariants.require(phaseOrdinal < HasPhase.DurablyCommitted.ordinal() || (maybeInvalidated == 0));
+ int outcome = ((1 << shardOutcome) | allShardsOutcome) << SHARDS_SHIFT;
+ return (phaseOrdinal << PHASE_SHIFT) | outcome | maybeInvalidated;
+ }
+
+ public final boolean isMaybeInvalidated()
+ {
+ return isMaybeInvalidated(encoded);
+ }
+
+ private static boolean isMaybeInvalidated(int encoded)
+ {
+ return 0 != maybeInvalidated(encoded);
+ }
+
+ private static int maybeInvalidated(int encoded)
+ {
+ return encoded & MAYBE_INVALIDATED_BIT;
+ }
+
+ private static int zeroIfInvalidated(int maybeNonZero, int maybeInvalidated)
+ {
+ return maybeNonZero & (maybeInvalidated - 1);
+ }
+
+ private static HasOutcome notInvalidated(int hasOutcomeOrdinal, int encoded)
+ {
+ return HasOutcome.lookup[zeroIfInvalidated(hasOutcomeOrdinal, maybeInvalidated(encoded))];
+ }
+
+ private static int orInvalidatedOrdinal(int hasOutcomeOrdinal, int encoded)
+ {
+ return (hasOutcomeOrdinal << 1) - maybeInvalidated(encoded);
+ }
+
+ private static HasOutcomeOrInvalidated orInvalidated(int hasOutcomeOrdinal, int encoded)
+ {
+ return HasOutcomeOrInvalidated.lookup[orInvalidatedOrdinal(hasOutcomeOrdinal, encoded)];
+ }
+
+ private static int phaseOrdinal(int encoded)
+ {
+ return (encoded >>> PHASE_SHIFT) & PHASE_MASK;
+ }
+
+ private static int maxPhaseOrdinal(int a, int b)
+ {
+ return Math.max(phaseOrdinal(a), phaseOrdinal(b));
+ }
+
+ private static int shardOrdinal(int encoded)
+ {
+ return 28 - Integer.numberOfLeadingZeros(encoded);
+ }
+
+ private static int maxShardOrdinal(int a, int b)
+ {
+ return shardOrdinal(a | b);
+ }
+
+ private static int minShardOrdinal(int a, int b)
+ {
+ return Math.min(shardOrdinal(a), shardOrdinal(b));
+ }
+
+ private static int allShardsOrdinal(int encoded)
+ {
+ encoded ^= Integer.highestOneBit(encoded);
+ return encoded >>> SHARDS_SHIFT;
+ }
+
+ private static int maxAllShardsOrdinal(int a, int b)
+ {
+ a ^= Integer.highestOneBit(a);
+ b ^= Integer.highestOneBit(b);
+ return Math.max(a, b) >>> SHARDS_SHIFT;
+ }
+
+ private static int mergeMaybeInvalidated(int a, int b, int maxPhase)
+ {
+ int ami = maybeInvalidated(a);
+ int bmi = maybeInvalidated(b);
+ if (ami == bmi)
+ return ami;
+
+ a = zeroIfInvalidated(a, ami);
+ b = zeroIfInvalidated(b, bmi);
+ return maxPhase >= HasPhase.DurablyCommitted.ordinal() || ((a | b) >>> SHARDS_SHIFT) > 1 ?
+ 0 : MAYBE_INVALIDATED_BIT;
+ }
+
+ private final int encoded;
+
+ private Durability(int encoded)
+ {
+ Invariants.require(0 == (encoded & ~0xFF));
+ this.encoded = encoded;
+ }
+
+ public int encoded()
+ {
+ return encoded;
+ }
+
+ public HasPhase phase()
+ {
+ return phase(encoded);
+ }
+
+ private static HasPhase phase(int encoded)
+ {
+ return HasPhase.lookup[phaseOrdinal(encoded)];
+ }
+
+ public HasOutcome shard()
+ {
+ return shard(encoded);
+ }
+
+ private static HasOutcome shard(int encoded)
+ {
+ return HasOutcome.lookup[zeroIfInvalidated(shardOrdinal(encoded), maybeInvalidated(encoded))];
+ }
+
+ private static HasOutcome shardUnsafe(int encoded)
+ {
+ return HasOutcome.lookup[shardOrdinal(encoded)];
+ }
+
+ public HasOutcome allShards()
+ {
+ return allShards(encoded);
+ }
+
+ private static HasOutcome allShards(int encoded)
+ {
+ return notInvalidated(allShardsOrdinal(encoded), encoded);
+ }
+
+ private static HasOutcome allShardsUnsafe(int encoded)
+ {
+ return HasOutcome.lookup[allShardsOrdinal(encoded)];
+ }
+
+ public HasOutcomeOrInvalidated allShardsOrInvalidated()
+ {
+ return allShardsOrInvalidated(encoded);
+ }
+
+ private static HasOutcomeOrInvalidated allShardsOrInvalidated(int encoded)
+ {
+ return orInvalidated(allShardsOrdinal(encoded), encoded);
+ }
+
+ public SaveStatus durableSaveStatus()
+ {
+ HasPhase phase = phase();
+ switch (phase)
+ {
+ default: throw new UnhandledEnum(phase);
+ case None:
+ case FastPathDecided: return SaveStatus.NotDefined;
+ case DurablyCommitted: return SaveStatus.Committed;
+ case DurablyStable: return allShards().isDurable() ? SaveStatus.PreApplied : SaveStatus.Stable;
+ }
+ }
+
+ public ProgressLog.BlockedUntil durablyUnblocked()
+ {
+ HasPhase phase = phase();
+ switch (phase)
+ {
+ default: throw new UnhandledEnum(phase);
+ case None:
+ case FastPathDecided:
+ return NotBlocked;
+
+ case DurablyCommitted:
+ // we could report HasCommittedDeps here, but we don't much care to fetch Committed deps
+ // as it doesn't advance the state machine. The BlockedUntil is used for await in recovery.
+ return HasDecidedExecuteAt;
+
+ case DurablyStable:
+ return allShards().isDurable() ? CanApply : HasStableDeps;
+ }
+ }
+
public boolean isDurable()
{
- return this == Majority || this == Universal;
+ return zeroIfInvalidated(allShardsOrdinal(encoded), maybeInvalidated(encoded)) >= HasOutcome.Quorum.ordinal();
+ }
+
+ public boolean isUniversal()
+ {
+ return zeroIfInvalidated(allShardsOrdinal(encoded), maybeInvalidated(encoded)) >= HasOutcome.Universal.ordinal();
+ }
+
+ public boolean isUniversalOrInvalidated()
+ {
+ return orInvalidatedOrdinal(allShardsOrdinal(encoded), encoded) >= HasOutcomeOrInvalidated.UniversalOrInvalidated.ordinal();
}
public boolean isDurableOrInvalidated()
{
- return compareTo(MajorityOrInvalidated) >= 0;
+ return orInvalidatedOrdinal(allShardsOrdinal(encoded), encoded) >= HasOutcomeOrInvalidated.QuorumOrInvalidated.ordinal();
}
- public boolean isMaybeInvalidated()
+ public boolean isFastPathDurablyDecided()
{
- return this == NotDurable || this == MajorityOrInvalidated || this == UniversalOrInvalidated;
+ return phaseOrdinal(encoded) >= HasPhase.FastPathDecided.ordinal();
}
- public static Durability nonNullOrMerge(@Nullable Durability a, @Nullable Durability b)
+ public boolean isDurablyCommitted()
+ {
+ return phaseOrdinal(encoded) >= HasPhase.DurablyCommitted.ordinal();
+ }
+
+ public boolean isDurablyStable()
+ {
+ return phaseOrdinal(encoded) >= HasPhase.DurablyStable.ordinal();
+ }
+
+ @Override
+ public String toString()
+ {
+ return toString(encoded);
+ }
+
+ private static String toString(int encoded)
+ {
+ HasPhase phase = phase(encoded);
+ HasOutcome shard = shardUnsafe(encoded);
+ HasOutcome allShards = allShardsUnsafe(encoded);
+ return phase.mediumName + "/" + shard.name() + "/" + allShards.name();
+ }
+
+ public static Durability nonNullOrMergeMax(@Nullable Durability a, @Nullable Durability b)
{
if (a == null) return b;
if (b == null) return a;
- return merge(a, b);
+ return a.mergeMax(b);
}
- public static Durability merge(Durability a, Durability b)
+ public final boolean isAtLeast(Durability that)
{
- int c = a.compareTo(b);
- if (c < 0) { Durability tmp = a; a = b; b = tmp; }
- // if we know we are applied, we can remove the OrInvalidated qualifier
- if (a == UniversalOrInvalidated && (b == Majority || b == ShardUniversal || b == Local)) a = Universal;
- // TODO (required, minor cleanup): should ShardUniversal+NotDurable=Local? It might be that we are stale.
- if ((a == ShardUniversal) && (b == Local || b == NotDurable)) a = Local;
- if (b == NotDurable && a.compareTo(MajorityOrInvalidated) < 0) a = NotDurable;
- return a;
+ int phase = phaseOrdinal(this.encoded);
+ return phase >= phaseOrdinal(that.encoded)
+ && shardOrdinal(encoded) >= shardOrdinal(that.encoded)
+ && allShardsOrdinal(encoded) >= allShardsOrdinal(that.encoded)
+ && mergeMaybeInvalidated(encoded, that.encoded, phase) == maybeInvalidated(encoded);
}
- public static Durability mergeAtLeast(Durability a, Durability b)
+ // max of each ordinal, and NOT_INVALIDATED if set on either
+ public Durability mergeMax(Durability that)
{
- int c = a.compareTo(b);
- if (c < 0) { Durability tmp = a; a = b; b = tmp; }
- if (a == UniversalOrInvalidated && (b == Majority || b == ShardUniversal || b == Local)) a = Universal;
- return a;
+ int phase = maxPhaseOrdinal(this.encoded, that.encoded);
+ int shard = maxShardOrdinal(this.encoded, that.encoded);
+ int allShards = maxAllShardsOrdinal(this.encoded, that.encoded);
+ int maybeInvalidated = mergeMaybeInvalidated(this.encoded, that.encoded, phase);
+ return selfOrLookup(encode(phase, shard, allShards, maybeInvalidated));
}
- public static Durability max(Durability a, Durability b)
+ public Durability mergeShardsOrReplicas(Durability that)
{
- return a.compareTo(b) >= 0 ? a : b;
+ int phase = maxPhaseOrdinal(this.encoded, that.encoded);
+ int allShards = maxAllShardsOrdinal(this.encoded, that.encoded);
+ int shard = Math.max(allShards, minShardOrdinal(this.encoded, that.encoded));
+ int maybeInvalidated = mergeMaybeInvalidated(this.encoded, that.encoded, phase);
+ return selfOrLookup(encode(phase, shard, allShards, maybeInvalidated));
}
- public static Durability forOrdinal(int ordinal)
+ private Durability selfOrLookup(int encoded)
{
- if (ordinal < 0 || ordinal > lookup.length)
- throw new IndexOutOfBoundsException(ordinal);
- return lookup[ordinal];
+ if (encoded == this.encoded)
+ return this;
+ return forEncoded(encoded);
}
- public static int maxOrdinal()
+ public static Durability get(HasPhase phase, HasOutcome shardOutcome, HasOutcome allShardsOutcome, boolean isMaybeInvalidated)
{
- return lookup.length;
+ return forEncoded(encode(phase, shardOutcome, allShardsOutcome, isMaybeInvalidated));
+ }
+
+ public static Durability forEncoded(int encoded)
+ {
+ if (encoded < 0 || encoded > lookup.length)
+ throw new IndexOutOfBoundsException(encoded);
+ Durability durability = lookup[encoded];
+ Invariants.require(durability != null, "Invalid durability requested %d", encoded);
+ return durability;
+ }
+
+ private static Durability[] values()
+ {
+ Invariants.require(HasOutcome.lookup.length <= 4);
+ Durability[] result = new Durability[64];
+ for (HasPhase phase : HasPhase.lookup)
+ {
+ for (HasOutcome shard : HasOutcome.lookup)
+ {
+ for (HasOutcome allShards : HasOutcome.lookup)
+ {
+ if (allShards.ordinal() > shard.ordinal())
+ break;
+
+ for (boolean isMaybeInvalidated : new boolean[] { false, true})
+ {
+ if (isMaybeInvalidated && phase.compareTo(HasPhase.DurablyCommitted) >= 0)
+ continue;
+
+ int encoded = encode(phase, shard, allShards, isMaybeInvalidated);
+ result[encoded] = new Durability(encoded);
+ }
+ }
+ }
+ }
+ return result;
}
}
diff --git a/accord-core/src/main/java/accord/primitives/Timestamp.java b/accord-core/src/main/java/accord/primitives/Timestamp.java
index 751fe414..fcd1dacc 100644
--- a/accord-core/src/main/java/accord/primitives/Timestamp.java
+++ b/accord-core/src/main/java/accord/primitives/Timestamp.java
@@ -31,8 +31,9 @@ import static accord.primitives.Timestamp.Flag.UNSTABLE;
* TxnId flag bits:
* [0..1) - TxnId Domain
* [1..4) - TxnId Kind
- * [4..6) - TxnId uses FastPath
- * [6..8) - TxnId uses Medium Path
+ * [4..5) - TxnId Cardinality
+ * [5..7) - TxnId uses FastPath
+ * [7..8) - TxnId uses Medium Path
* [11..12) - TxnId is unstable - used by Dep handling only
*
* Timestamp flag bits
@@ -137,6 +138,7 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
Invariants.requireArgument(hlc >= 0, "hlc must be positive or zero; given %d", hlc);
Invariants.requireArgument(epoch <= MAX_EPOCH, "epoch %d > MAX_EPOCH %d", epoch, MAX_EPOCH);
Invariants.requireArgument(flags <= MAX_FLAGS, "flags %d > MAX_FLAGS %d", flags, MAX_FLAGS);
+ Invariants.requireArgument(flags >= 0, "flags %d < 0", flags);
this.msb = epochMsb(epoch) | hlcMsb(hlc);
this.lsb = hlcLsb(hlc) | flags;
this.node = node;
@@ -166,6 +168,7 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
Timestamp(Timestamp copy, int flags)
{
Invariants.requireArgument(flags <= MAX_FLAGS);
+ Invariants.requireArgument(flags >= 0);
this.msb = copy.msb;
this.lsb = notFlags(copy.lsb) | flags;
this.node = copy.node;
diff --git a/accord-core/src/main/java/accord/primitives/Txn.java b/accord-core/src/main/java/accord/primitives/Txn.java
index bdef6e3b..1745f5d2 100644
--- a/accord-core/src/main/java/accord/primitives/Txn.java
+++ b/accord-core/src/main/java/accord/primitives/Txn.java
@@ -43,20 +43,22 @@ import static accord.primitives.Routables.Slice.Minimal;
public interface Txn
{
+ enum Witnesses { Writes, ReadsOrWrites, AnyVisible }
+ enum WitnessedBy { All, WritesOrSyncPoints, SyncPoints, Nothing }
/**
* NOTE: we keep Read/Write adjacent to make it easier to check for non-standard flags in serialization
*/
enum Kind
{
- Read('R', true, false, false, false),
- Write('W', true, false, false, false),
+ Read('R', true, false, false, false, Witnesses.Writes, WitnessedBy.WritesOrSyncPoints),
+ Write('W', true, false, false, false, Witnesses.ReadsOrWrites, WitnessedBy.All),
/**
* A non-durable read that cannot be recovered and provides only per-key linearizability guarantees.
* This may be used to implement single-partition-key reads with strict serializable isolation OR
* weaker isolation multi-key/range reads for interoperability with weaker isolation systems.
*/
- EphemeralRead('E', false, false, false, true),
+ EphemeralRead('E', false, false, false, true, Witnesses.Writes, WitnessedBy.Nothing),
/**
* A pseudo-transaction whose deps represent the complete set of transactions that may execute before it,
@@ -88,7 +90,12 @@ public interface Txn
*
* Invisible to other transactions.
*/
- ExclusiveSyncPoint('X', true, true, true, true),
+ ExclusiveSyncPoint('X', true, true, true, true, Witnesses.AnyVisible, WitnessedBy.SyncPoints),
+ /**
+ * An ExclusiveSyncPoint that does not filter its dependencies so that they may be used for
+ * ensuring a new epoch's quorum can perform coordination without earlier epochs
+ */
+ VisibilitySyncPoint('V', true, true, true, true, Witnesses.AnyVisible, WitnessedBy.SyncPoints)
;
public static class Kinds extends TinyEnumSet<Kind>
@@ -120,17 +127,20 @@ public interface Txn
private static final int COUNT = VALUES.length;
private static final long ENCODED_ORDINAL_INFO;
private static final long ENCODED_WITNESSES_INFO;
- private static final long IS_VISIBLE_ORDINAL_INFO_OFFSET = 0;
- private static final long IS_SYNCPOINT_ORDINAL_INFO_OFFSET = COUNT;
- private static final long IS_SYSTEM_ORDINAL_INFO_OFFSET = 2 * COUNT;
- private static final long AWAITS_ONLY_DEPS_ORDINAL_INFO_OFFSET = 3 * COUNT;
+ private static final int IS_VISIBLE_ORDINAL_INFO_OFFSET = 0;
+ private static final int IS_SYNCPOINT_ORDINAL_INFO_OFFSET = COUNT;
+ private static final int IS_SYSTEM_ORDINAL_INFO_OFFSET = 2 * COUNT;
+ private static final int AWAITS_ONLY_DEPS_ORDINAL_INFO_OFFSET = 3 * COUNT;
public static final Kinds Nothing = new Kinds();
public static final Kinds Ws = new Kinds(Write);
public static final Kinds RsOrWs = new Kinds(Write, Read);
- public static final Kinds WsOrSyncPoints = new Kinds(Write, ExclusiveSyncPoint);
- public static final Kinds ExclusiveSyncPoints = new Kinds(ExclusiveSyncPoint);
- public static final Kinds AnyGloballyVisible = new Kinds(Write, Read, ExclusiveSyncPoint);
+ public static final Kinds WsOrSyncPoints = new Kinds(Write, ExclusiveSyncPoint, VisibilitySyncPoint);
+ public static final Kinds SyncPoints = new Kinds(ExclusiveSyncPoint, VisibilitySyncPoint);
+ public static final Kinds AnyVisible = new Kinds(Write, Read, ExclusiveSyncPoint, VisibilitySyncPoint);
+ public static final Kinds All = new Kinds(Write, Read, EphemeralRead, ExclusiveSyncPoint, VisibilitySyncPoint);
+ private static final Kinds[] WITNESSES = new Kinds[] { Ws, RsOrWs, AnyVisible };
+ private static final Kinds[] WITNESSED_BY = new Kinds[] { All, WsOrSyncPoints, SyncPoints, Nothing };
static
{
@@ -153,7 +163,7 @@ public interface Txn
{
for (Kind witnessed : VALUES)
{
- if (witness.witnesses().test(witnessed))
+ if (witness.witnessesKinds().test(witnessed))
encodedWitnessesInfo |= 1L << offset;
++offset;
}
@@ -166,14 +176,18 @@ public interface Txn
public final boolean isSyncPoint;
public final boolean isSystem;
public final boolean awaitsOnlyDeps;
+ public final Witnesses witnesses;
+ public final WitnessedBy witnessedBy;
- Kind(char shortName, boolean isVisible, boolean isSyncPoint, boolean isSystem, boolean awaitsOnlyDeps)
+ Kind(char shortName, boolean isVisible, boolean isSyncPoint, boolean isSystem, boolean awaitsOnlyDeps, Witnesses witnesses, WitnessedBy witnessedBy)
{
this.shortName = shortName;
this.isVisible = isVisible;
this.isSyncPoint = isSyncPoint;
this.isSystem = isSystem;
this.awaitsOnlyDeps = awaitsOnlyDeps;
+ this.witnesses = witnesses;
+ this.witnessedBy = witnessedBy;
}
@@ -237,22 +251,12 @@ public interface Txn
public static boolean awaitsPreviouslyOwned(int ordinal)
{
- return ordinal == ExclusiveSyncPoint.ordinal();
+ return ordinal == ExclusiveSyncPoint.ordinal() || ordinal == VisibilitySyncPoint.ordinal();
}
- public Kinds witnesses()
+ public Kinds witnessesKinds()
{
- switch (this)
- {
- default: throw new AssertionError();
- case EphemeralRead:
- case Read:
- return Ws;
- case Write:
- return RsOrWs;
- case ExclusiveSyncPoint:
- return AnyGloballyVisible;
- }
+ return WITNESSES[witnesses.ordinal()];
}
public boolean witnesses(TxnId txnId)
@@ -275,20 +279,9 @@ public interface Txn
return kind.witnesses(this);
}
- public Kinds witnessedBy()
+ public Kinds witnessedByKinds()
{
- switch (this)
- {
- default: throw new AssertionError();
- case EphemeralRead:
- return Nothing;
- case Read:
- return WsOrSyncPoints;
- case Write:
- return AnyGloballyVisible;
- case ExclusiveSyncPoint:
- return ExclusiveSyncPoints;
- }
+ return WITNESSED_BY[witnessedBy.ordinal()];
}
public char shortName()
@@ -340,7 +333,7 @@ public interface Txn
this.update = update;
this.query = query;
this.implementationDefined = implementationDefined;
- Invariants.require(kind != Kind.ExclusiveSyncPoint || keys.domain() == Routable.Domain.Range);
+ Invariants.require(!kind.isSyncPoint() || keys.domain() == Routable.Domain.Range);
}
@Override
diff --git a/accord-core/src/main/java/accord/primitives/TxnId.java b/accord-core/src/main/java/accord/primitives/TxnId.java
index 5c5c223f..8f38413a 100644
--- a/accord-core/src/main/java/accord/primitives/TxnId.java
+++ b/accord-core/src/main/java/accord/primitives/TxnId.java
@@ -345,7 +345,7 @@ public class TxnId extends Timestamp
public final Kinds witnesses()
{
- return kind().witnesses();
+ return kind().witnessesKinds();
}
public final boolean witnesses(TxnId txnId)
@@ -360,7 +360,7 @@ public class TxnId extends Timestamp
public final Kinds witnessedBy()
{
- return kind().witnessedBy();
+ return kind().witnessedByKinds();
}
public final Domain domain()
@@ -456,7 +456,7 @@ public class TxnId extends Timestamp
public static int kindOrdinal(int flags)
{
- return (flags >> 1) & 7;
+ return (flags >>> 1) & 7;
}
public final int kindOrdinal()
diff --git a/accord-core/src/main/java/accord/topology/Topologies.java b/accord-core/src/main/java/accord/topology/Topologies.java
index a727acf3..f624fb7a 100644
--- a/accord-core/src/main/java/accord/topology/Topologies.java
+++ b/accord-core/src/main/java/accord/topology/Topologies.java
@@ -88,9 +88,16 @@ public interface Topologies extends TopologySorter
*/
SortedArrayList<Id> nodes();
- default SortedArrayList<Id> staleNodes()
+ default SortedArrayList<Id> staleOrRemovedIds()
{
- return current().staleNodes;
+ SortedArrayList<Id> cur = current().staleIds;
+ for (int i = size() - 1 ; i >= 1 ; --i)
+ {
+ Topology topology = get(i);
+ if (!topology.removedIds.isEmpty())
+ cur = cur.with(topology.removedIds);
+ }
+ return cur;
}
Ranges computeRangesForNode(Id node);
diff --git a/accord-core/src/main/java/accord/topology/Topology.java b/accord-core/src/main/java/accord/topology/Topology.java
index 00658466..5bb5a4e0 100644
--- a/accord-core/src/main/java/accord/topology/Topology.java
+++ b/accord-core/src/main/java/accord/topology/Topology.java
@@ -64,10 +64,11 @@ public class Topology
public static final long EMPTY_EPOCH = 0;
private static final int[] EMPTY_SUBSET = new int[0];
public static final SortedArrayList<Id> NO_IDS = new SortedArrayList<>(new Id[0]);
- public static final Topology EMPTY = new Topology(null, EMPTY_EPOCH, new Shard[0], Ranges.EMPTY, NO_IDS, NO_IDS, new Int2ObjectHashMap<>(0, 0.9f), Ranges.EMPTY, EMPTY_SUBSET);
+ public static final Topology EMPTY = new Topology(null, EMPTY_EPOCH, new Shard[0], Ranges.EMPTY, NO_IDS, NO_IDS, NO_IDS, new Int2ObjectHashMap<>(0, 0.9f), Ranges.EMPTY, EMPTY_SUBSET);
final long epoch;
- final SortedArrayList<Id> staleNodes;
+ final SortedArrayList<Id> removedIds;
+ final SortedArrayList<Id> staleIds;
final Shard[] shards;
final Ranges ranges;
@@ -136,14 +137,15 @@ public class Topology
@VisibleForTesting
public Topology(long epoch, Shard... shards)
{
- this(epoch, NO_IDS, shards);
+ this(epoch, NO_IDS, NO_IDS, shards);
}
- public Topology(long epoch, SortedArrayList<Id> staleNodes, Shard... shards)
+ public Topology(long epoch, SortedArrayList<Id> removedIds, SortedArrayList<Id> staleIds, Shard... shards)
{
this.global = null;
this.epoch = epoch;
- this.staleNodes = staleNodes;
+ this.removedIds = removedIds;
+ this.staleIds = staleIds;
this.ranges = Ranges.ofSortedAndDeoverlapped(Arrays.stream(shards).map(shard -> shard.range).toArray(Range[]::new));
this.shards = shards;
this.subsetOfRanges = ranges;
@@ -169,11 +171,12 @@ public class Topology
}
@VisibleForTesting
- Topology(@Nullable Topology global, long epoch, Shard[] shards, Ranges ranges, SortedArrayList<Id> staleNodes, SortedArrayList<Id> nodeIds, Int2ObjectHashMap<NodeInfo> nodeById, Ranges subsetOfRanges, int[] supersetIndexes)
+ Topology(@Nullable Topology global, long epoch, Shard[] shards, Ranges ranges, SortedArrayList<Id> removedIds, SortedArrayList<Id> staleIds, SortedArrayList<Id> nodeIds, Int2ObjectHashMap<NodeInfo> nodeById, Ranges subsetOfRanges, int[] supersetIndexes)
{
this.global = global;
this.epoch = epoch;
- this.staleNodes = staleNodes;
+ this.removedIds = removedIds;
+ this.staleIds = staleIds;
this.shards = shards;
this.ranges = ranges;
this.nodeIds = nodeIds;
@@ -185,7 +188,7 @@ public class Topology
@VisibleForTesting
public Topology withEpoch(long epoch)
{
- return new Topology(global, epoch, shards, ranges, staleNodes, nodeIds, nodeLookup, subsetOfRanges, supersetIndexes);
+ return new Topology(global, epoch, shards, ranges, removedIds, staleIds, nodeIds, nodeLookup, subsetOfRanges, supersetIndexes);
}
public Topology global()
@@ -201,11 +204,12 @@ public class Topology
public boolean isEquivalent(Topology topology)
{
- if (!staleNodes.equals(topology.staleNodes))
+ if (!staleIds.equals(topology.staleIds) || !removedIds.equals(topology.removedIds))
return false;
if (shards.length != topology.shards.length)
return false;
+
for (int i = 0; i < shards.length; i++)
{
if (!shards[i].equals(topology.shards[i]))
@@ -217,7 +221,7 @@ public class Topology
public Topology cloneEquivalentWithEpoch(long epoch)
{
- return new Topology(epoch, staleNodes, shards);
+ return new Topology(epoch, removedIds, staleIds, shards);
}
@Override
@@ -245,12 +249,12 @@ public class Topology
return result;
}
- private static Topology select(long epoch, SortedArrayList<Id> staleIds, Shard[] shards, int[] indexes)
+ private static Topology select(long epoch, SortedArrayList<Id> removedIds, SortedArrayList<Id> staleIds, Shard[] shards, int[] indexes)
{
Shard[] subset = new Shard[indexes.length];
for (int i = 0; i < indexes.length; i++)
subset[i] = shards[indexes[i]];
- return new Topology(epoch, staleIds, subset);
+ return new Topology(epoch, removedIds, staleIds, subset);
}
public boolean isEmpty()
@@ -275,12 +279,12 @@ public class Topology
return Topology.EMPTY;
SortedArrayList<Id> nodeIds = new SortedArrayList<>(new Id[] { node });
- return new Topology(global(), epoch, shards, ranges, staleNodes, nodeIds, nodeLookup, info.ranges, info.supersetIndexes);
+ return new Topology(global(), epoch, shards, ranges, removedIds, staleIds, nodeIds, nodeLookup, info.ranges, info.supersetIndexes);
}
public Topology trim()
{
- return select(epoch, staleNodes, shards, this.supersetIndexes);
+ return select(epoch, removedIds, staleIds, shards, this.supersetIndexes);
}
public Ranges rangesForNode(Id node)
@@ -362,7 +366,7 @@ public class Topology
subsetOfRanges = Ranges.ofSortedAndDeoverlapped(ranges);
}
- return new Topology(global(), epoch, this.shards, this.ranges, staleNodes, keepIds, nodeLookup, subsetOfRanges, supersetIndexes);
+ return new Topology(global(), epoch, this.shards, this.ranges, removedIds, staleIds, keepIds, nodeLookup, subsetOfRanges, supersetIndexes);
}
@VisibleForTesting
@@ -394,7 +398,7 @@ public class Topology
for (int i = nodes.firstSetBit() ; i >= 0 ; i = nodes.nextSetBit(i + 1, -1))
nodeIds[count++] = this.nodeIds.get(i);
- return new Topology(global(), epoch, shards, ranges, staleNodes, new SortedArrayList<>(nodeIds), nodeLookup, rangeSubset, newSubset);
+ return new Topology(global(), epoch, shards, ranges, removedIds, staleIds, new SortedArrayList<>(nodeIds), nodeLookup, rangeSubset, newSubset);
}
private int[] subsetFor(Routables<?> select, boolean permitMissing)
@@ -666,9 +670,14 @@ public class Topology
public SortedArrayList<Id> staleIds()
{
- return staleNodes;
+ return staleIds;
}
+ public SortedArrayList<Id> removedIds()
+ {
+ return staleIds;
+ }
+
public Shard[] unsafeGetShards()
{
return shards;
diff --git a/accord-core/src/main/java/accord/topology/TopologyManager.java b/accord-core/src/main/java/accord/topology/TopologyManager.java
index 7708c9cd..e12d6b3a 100644
--- a/accord-core/src/main/java/accord/topology/TopologyManager.java
+++ b/accord-core/src/main/java/accord/topology/TopologyManager.java
@@ -211,6 +211,7 @@ public class TopologyManager
ranges = ranges.without(retired);
if (ranges.isEmpty())
return ranges;
+ synced = synced.union(MERGE_ADJACENT, ranges);
closed = closed.union(MERGE_ADJACENT, ranges);
retired = retired.union(MERGE_ADJACENT, ranges);
Invariants.require(closed.mergeTouching() == closed);
@@ -304,12 +305,8 @@ public class TopologyManager
for (int i = epochs.length - 1; i > 0; i--)
{
EpochState epochState = epochs[i];
- if (epochState.allRetired() &&
- (truncateFrom == -1 || truncateFrom == i + 1))
- {
- Invariants.require(epochs[i].syncComplete());
+ if (epochState.allRetired() && (truncateFrom == -1 || truncateFrom == i + 1))
truncateFrom = i;
- }
}
if (truncateFrom == -1)
diff --git a/accord-core/src/test/java/accord/impl/LocalListenersTest.java b/accord-core/src/test/java/accord/impl/LocalListenersTest.java
index b6e79698..d7768eea 100644
--- a/accord-core/src/test/java/accord/impl/LocalListenersTest.java
+++ b/accord-core/src/test/java/accord/impl/LocalListenersTest.java
@@ -397,7 +397,7 @@ public class LocalListenersTest
static class TestSafeCommand extends SafeCommand
{
Command current;
- public TestSafeCommand(TxnId txnId, SaveStatus saveStatus, final Durability durability)
+ public TestSafeCommand(TxnId txnId, SaveStatus saveStatus, Durability durability)
{
super(txnId);
current = new TestCommand(txnId, saveStatus, durability);
diff --git a/accord-core/src/test/java/accord/impl/RemoteListenersTest.java b/accord-core/src/test/java/accord/impl/RemoteListenersTest.java
index 8472ef79..e9c31670 100644
--- a/accord-core/src/test/java/accord/impl/RemoteListenersTest.java
+++ b/accord-core/src/test/java/accord/impl/RemoteListenersTest.java
@@ -44,7 +44,6 @@ import accord.api.RemoteListeners;
import accord.api.RemoteListeners.Registration;
import accord.api.RoutingKey;
import accord.impl.LocalListenersTest.TestSafeCommand;
-import accord.local.Command;
import accord.local.CommandStore;
import accord.local.CommandStores;
import accord.local.CommandSummaries;
@@ -59,6 +58,7 @@ import accord.primitives.SaveStatus;
import accord.primitives.Status.Durability;
import accord.local.cfk.SafeCommandsForKey;
import accord.primitives.Route;
+import accord.primitives.Status.Durability.HasOutcome;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
@@ -71,6 +71,7 @@ import org.agrona.collections.IntHashSet;
import org.agrona.collections.ObjectHashSet;
import static accord.primitives.SaveStatus.Uninitialised;
+import static accord.primitives.Status.Durability.HasPhase.DurablyStable;
import static accord.primitives.Status.Durability.NotDurable;
import static accord.primitives.Known.KnownRoute.FullRoute;
@@ -99,9 +100,9 @@ public class RemoteListenersTest
static class StateKey implements Comparable<StateKey>
{
final SaveStatus saveStatus;
- final Durability durability;
+ final HasOutcome durability;
- StateKey(SaveStatus saveStatus, Durability durability)
+ StateKey(SaveStatus saveStatus, HasOutcome durability)
{
this.saveStatus = saveStatus;
this.durability = durability;
@@ -181,7 +182,7 @@ public class RemoteListenersTest
final Supplier<TxnId> txnIds;
final Supplier<Node.Id> nodeIds;
final Supplier<SaveStatus> awaits;
- final Supplier<Durability> durabilities;
+ final Supplier<HasOutcome> durabilities;
final IntSupplier storeIds;
final IntSupplier storeIdCount;
@@ -210,7 +211,7 @@ public class RemoteListenersTest
this.awaits = rnd.randomWeightedPicker(Arrays.stream(SaveStatus.values())
.filter(s -> s.known.route() == FullRoute)
.toArray(SaveStatus[]::new));
- this.durabilities = rnd.randomWeightedPicker(Durability.values());
+ this.durabilities = rnd.randomWeightedPicker(Durability.HasOutcome.values());
int maxStoreId = rnd.nextInt(16, 128);
int maxStoreIdCount = rnd.nextInt(2, maxStoreId / 4);
@@ -228,12 +229,12 @@ public class RemoteListenersTest
else
{
SaveStatus saveStatus = awaits.get();
- Durability durability = durabilities.get();
- notifyOne(saveStatus, Command.durability(durability, saveStatus), notifyRatio);
+ HasOutcome durability = durabilities.get();
+ notifyOne(saveStatus, durability, notifyRatio);
}
}
while (!canonical.isEmpty())
- notifyOne(SaveStatus.Invalidated, Durability.Universal, notifyRatio);
+ notifyOne(SaveStatus.Invalidated, Durability.HasOutcome.Universal, notifyRatio);
}
void registerOne()
@@ -244,7 +245,7 @@ public class RemoteListenersTest
while (registerCount-- > 0)
{
SaveStatus awaitSaveStatus = awaits.get();
- Durability awaitDurability = durabilities.get();
+ HasOutcome awaitDurability = durabilities.get();
Node.Id nodeId = nodeIds.get();
int callbackId = rnd.nextInt(0, Integer.MAX_VALUE);
@@ -272,7 +273,7 @@ public class RemoteListenersTest
}
}
- void notifyOne(SaveStatus newStatus, Durability newDurability, float notifyRatio)
+ void notifyOne(SaveStatus newStatus, HasOutcome newDurability, float notifyRatio)
{
TxnId txnId;
{
@@ -281,7 +282,7 @@ public class RemoteListenersTest
}
TreeMap<StateKey, State> stateMap = canonical.get(txnId);
- TestSafeCommand safeCommand = new TestSafeCommand(txnId, newStatus, newDurability);
+ TestSafeCommand safeCommand = new TestSafeCommand(txnId, newStatus, Durability.get(DurablyStable, newDurability, newDurability, false));
Map<StateKey, State> subMap = stateMap.headMap(new StateKey(newStatus, newDurability), true);
subMap.forEach((key, state) -> {
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 8a005c37..e9a266bc 100644
--- a/accord-core/src/test/java/accord/impl/basic/Cluster.java
+++ b/accord-core/src/test/java/accord/impl/basic/Cluster.java
@@ -126,6 +126,7 @@ import static accord.local.Cleanup.INVALIDATE;
import static accord.local.Cleanup.Input.FULL;
import static accord.local.Command.NotDefined.uninitialised;
import static accord.local.StoreParticipants.Filter.LOAD;
+import static accord.primitives.Status.Durability.HasOutcome.Quorum;
import static accord.utils.Invariants.Paranoia.LINEAR;
import static accord.utils.Invariants.ParanoiaCostFactor.HIGH;
import static java.util.Collections.emptyMap;
@@ -986,7 +987,7 @@ public class Cluster
if (store.unsafeGetRedundantBefore().min(beforeCommand.participants().owns(), RedundantBefore.Bounds::shardAndLocallyRedundantBefore).compareTo(txnId) > 0)
continue;
- if (beforeCommand.participants().owns().isEmpty() && store.durableBefore().min(txnId).compareTo(Status.Durability.MajorityOrInvalidated) >= 0)
+ if (beforeCommand.participants().owns().isEmpty() && store.durableBefore().min(txnId).compareTo(Quorum) >= 0)
continue;
if (!beforeCommand.saveStatus().hasBeen(Status.PreCommitted) && store.unsafeGetRedundantBefore().min(beforeCommand.participants().owns(), RedundantBefore.Bounds::locallyRedundantBefore).compareTo(txnId) > 0)
diff --git a/accord-core/src/test/java/accord/local/RedundantBeforeTest.java b/accord-core/src/test/java/accord/local/RedundantBeforeTest.java
index 99eb4c9f..c0b0fec4 100644
--- a/accord-core/src/test/java/accord/local/RedundantBeforeTest.java
+++ b/accord-core/src/test/java/accord/local/RedundantBeforeTest.java
@@ -195,9 +195,9 @@ public class RedundantBeforeTest
else return e.getValue().mergedLt;
}
- private static short merge(short a, short b)
+ private static int merge(int a, int b)
{
- return (short) (a | b);
+ return a | b;
}
private static SomeStatus merge(SomeStatus a, SomeStatus b)
diff --git a/accord-core/src/test/java/accord/topology/TopologyUtils.java b/accord-core/src/test/java/accord/topology/TopologyUtils.java
index a0c4129a..0784955f 100644
--- a/accord-core/src/test/java/accord/topology/TopologyUtils.java
+++ b/accord-core/src/test/java/accord/topology/TopologyUtils.java
@@ -58,7 +58,7 @@ public class TopologyUtils
public static Topology withEpoch(Topology topology, long epoch)
{
return new Topology(topology.global == null ? null : withEpoch(topology.global, epoch), epoch,
- topology.shards, topology.ranges, Topology.NO_IDS, topology.nodeIds,
+ topology.shards, topology.ranges, topology.removedIds, topology.staleIds, topology.nodeIds,
topology.nodeLookup, topology.subsetOfRanges, topology.supersetIndexes);
}
diff --git a/accord-core/src/test/java/accord/utils/AccordGens.java b/accord-core/src/test/java/accord/utils/AccordGens.java
index f75b7c6e..33701e43 100644
--- a/accord-core/src/test/java/accord/utils/AccordGens.java
+++ b/accord-core/src/test/java/accord/utils/AccordGens.java
@@ -600,6 +600,7 @@ public class AccordGens
}
break;
case ExclusiveSyncPoint:
+ case VisibilitySyncPoint:
//TODO (coverage, now):
keyDepsGen = i -> KeyDeps.NONE;
rangeDepsGen = i -> RangeDeps.NONE;
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/TopologyFactory.java b/accord-maelstrom/src/main/java/accord/maelstrom/TopologyFactory.java
index ab6413e9..ca56e906 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/TopologyFactory.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/TopologyFactory.java
@@ -29,7 +29,6 @@ import accord.local.Node.Id;
import accord.maelstrom.Datum.Kind;
import accord.topology.Shard;
import accord.topology.Topology;
-import accord.utils.SortedArrays.SortedArrayList;
import accord.utils.WrapAroundList;
import accord.utils.WrapAroundSet;
@@ -86,6 +85,6 @@ public class TopologyFactory
for (int i = 0 ; i < this.shards ; ++i)
shards.add(Shard.create(ranges[j][i], copyUnsorted(electorates.get(i % electorates.size()), Id[]::new), fastPathElectorates.get(i % fastPathElectorates.size())));
}
- return new Topology(1, SortedArrayList.ofSorted(), toArray(shards, Shard[]::new));
+ return new Topology(1, Topology.NO_IDS, Topology.NO_IDS, toArray(shards, Shard[]::new));
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org