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/01/26 17:26:08 UTC
(cassandra-accord) 01/01: Agree a distributed uniqueHlc to use for Apply - detect and save whether RX can be used as a GC bound for HLCs - have RX durably record if they witnessed any superseding epoch and use this for HLC GC - rework GC to retain applyAt for writes
This is an automated email from the ASF dual-hosted git repository.
benedict pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra-accord.git
commit 41aacd31c93251043154b5f73239345ee68b7957
Author: Benedict Elliott Smith <be...@apache.org>
AuthorDate: Tue Jan 7 12:15:10 2025 +0000
Agree a distributed uniqueHlc to use for Apply
- detect and save whether RX can be used as a GC bound for HLCs
- have RX durably record if they witnessed any superseding epoch and use this for HLC GC
- rework GC to retain applyAt for writes
Also improve:
- PreCommitted overwrites fast path vote, then loses tie-break with NotAccept, so we don't recover
- track executeAtLeast and uniqueHlc separately from WaitingOn in CommandChange
- Always propose executeAt.hlc() >= txnId.hlc()
- Short-circuit recovery if ApplyAt already known
Also fix:
- Dangling recovery when Commit rejected
- Failed epoch fetch handling in DefaultProgressLog
- CommandsForKey must track Accept executeAt for computing earlierWait collection on recovery
- Report DefaultProgressLog exceptions before retrying
- Fix inverted condition in RecoverWithRoute
- Remove laterNoWait from laterWait collection in recovery
- Invalidate incorrectly selected maxNotTruncated if max had a not truncated component
- WaitingState.fetch not request/propagating prior epochs
- CFK visit active pruning was comparing txn against maxCommittedWriteBefore rather than maxCommittedWriteForEpoch
patch by Benedict; reviewed by Alex Petrov for CASSANDRA-20228
---
accord-core/src/main/java/accord/api/Agent.java | 2 +-
.../main/java/accord/api/ConfigurationService.java | 2 +-
.../src/main/java/accord/api/DataStore.java | 14 +-
accord-core/src/main/java/accord/api/Key.java | 4 -
.../main/java/accord/api/ProtocolModifiers.java | 4 +
.../accord/coordinate/CoordinatePreAccept.java | 4 +-
.../accord/coordinate/CoordinateSyncPoint.java | 14 +-
.../main/java/accord/coordinate/ExecuteTxn.java | 15 ++
.../src/main/java/accord/coordinate/FindRoute.java | 2 +-
.../main/java/accord/coordinate/Invalidate.java | 8 +-
.../src/main/java/accord/coordinate/Recover.java | 27 +--
.../java/accord/coordinate/RecoverWithRoute.java | 29 ++-
.../src/main/java/accord/coordinate/Stabilise.java | 6 +
.../accord/impl/AbstractConfigurationService.java | 4 +-
.../java/accord/impl/AbstractFetchCoordinator.java | 2 +-
.../src/main/java/accord/impl/AbstractLoader.java | 3 +-
.../java/accord/impl/AbstractSafeCommandStore.java | 2 +-
.../src/main/java/accord/impl/CommandChange.java | 151 +++++++-----
.../java/accord/impl/DurabilityScheduling.java | 2 +-
.../java/accord/impl/InMemoryCommandStore.java | 25 +-
...sedSafeCommand.java => RetiredSafeCommand.java} | 10 +-
.../impl/progresslog/DefaultProgressLog.java | 77 +++++-
.../java/accord/impl/progresslog/HomeState.java | 1 +
.../java/accord/impl/progresslog/WaitingState.java | 3 +-
.../src/main/java/accord/local/Bootstrap.java | 4 +-
.../src/main/java/accord/local/Cleanup.java | 270 +++++++++++----------
.../src/main/java/accord/local/Command.java | 105 ++++++--
.../src/main/java/accord/local/CommandStore.java | 47 ++--
.../src/main/java/accord/local/CommandStores.java | 18 +-
.../main/java/accord/local/CommandSummaries.java | 4 +-
.../src/main/java/accord/local/Commands.java | 127 ++++------
.../src/main/java/accord/local/MaxConflicts.java | 6 +-
accord-core/src/main/java/accord/local/Node.java | 5 +-
.../main/java/accord/local/RedundantBefore.java | 108 ++++-----
.../main/java/accord/local/RedundantStatus.java | 91 ++++---
.../main/java/accord/local/SafeCommandStore.java | 15 +-
.../main/java/accord/local/StoreParticipants.java | 2 +-
.../main/java/accord/local/cfk/CommandsForKey.java | 165 +++++++------
.../src/main/java/accord/local/cfk/NotifySink.java | 12 +-
.../main/java/accord/local/cfk/PostProcess.java | 2 +-
.../src/main/java/accord/local/cfk/Pruning.java | 4 +-
.../java/accord/local/cfk/SafeCommandsForKey.java | 6 +
.../src/main/java/accord/local/cfk/Serialize.java | 49 ++--
.../src/main/java/accord/local/cfk/Updating.java | 40 ++-
.../src/main/java/accord/local/cfk/Utils.java | 11 +
.../src/main/java/accord/messages/Accept.java | 3 +-
.../src/main/java/accord/messages/Apply.java | 3 +-
.../java/accord/messages/BeginInvalidation.java | 5 +-
.../main/java/accord/messages/BeginRecovery.java | 40 ++-
.../src/main/java/accord/messages/CheckStatus.java | 2 +-
.../src/main/java/accord/messages/Commit.java | 5 +-
.../src/main/java/accord/messages/PreAccept.java | 2 +-
.../src/main/java/accord/messages/Propagate.java | 37 ++-
.../src/main/java/accord/messages/ReadData.java | 58 +++--
.../java/accord/messages/ReadEphemeralTxnData.java | 4 +-
.../main/java/accord/messages/RecoverAwait.java | 11 +-
.../main/java/accord/messages/SetShardDurable.java | 4 +-
.../main/java/accord/messages/StableThenRead.java | 7 +
.../src/main/java/accord/messages/TxnRequest.java | 3 +-
.../java/accord/messages/WaitUntilApplied.java | 10 +-
.../main/java/accord/primitives/AbstractKeys.java | 10 +-
.../java/accord/primitives/AbstractRanges.java | 9 +-
.../src/main/java/accord/primitives/Deps.java | 7 +
.../src/main/java/accord/primitives/Keys.java | 4 +
.../src/main/java/accord/primitives/Known.java | 141 ++++++++---
.../main/java/accord/primitives/LatestDeps.java | 28 +++
.../main/java/accord/primitives/PartialDeps.java | 6 +-
.../src/main/java/accord/primitives/Ranges.java | 1 +
.../main/java/accord/primitives/RoutableKey.java | 2 +
.../src/main/java/accord/primitives/Routables.java | 20 +-
.../main/java/accord/primitives/SaveStatus.java | 39 +--
.../src/main/java/accord/primitives/Seekables.java | 2 +
.../src/main/java/accord/primitives/Status.java | 6 +-
.../src/main/java/accord/primitives/Timestamp.java | 95 +++++---
.../TimestampWithUniqueHlc.java} | 41 ++--
.../src/main/java/accord/primitives/Txn.java | 4 +-
.../{api/Key.java => utils/BiFoldToLong.java} | 24 +-
.../accord/{api/Key.java => utils/FoldToLong.java} | 24 +-
.../{api/Key.java => utils/QuadFoldToLong.java} | 24 +-
.../src/main/java/accord/utils/Timestamped.java | 41 ++--
.../{api/Key.java => utils/TriFoldToLong.java} | 24 +-
.../src/test/java/accord/burn/BurnTest.java | 1 +
.../src/test/java/accord/burn/TopologyUpdates.java | 2 +-
.../accord/coordinate/CoordinateSyncPointTest.java | 6 +-
.../java/accord/coordinate/TopologyChangeTest.java | 4 +-
.../impl/AbstractConfigurationServiceTest.java | 2 +-
.../src/test/java/accord/impl/TestAgent.java | 4 +-
.../src/test/java/accord/impl/basic/Cluster.java | 4 +-
.../java/accord/impl/basic/InMemoryJournal.java | 75 +++---
.../src/test/java/accord/impl/list/ListAgent.java | 9 +-
.../src/test/java/accord/impl/list/ListStore.java | 2 +-
.../java/accord/local/cfk/CommandsForKeyTest.java | 6 +-
.../src/main/java/accord/maelstrom/Json.java | 2 +-
.../main/java/accord/maelstrom/MaelstromAgent.java | 2 +-
94 files changed, 1414 insertions(+), 953 deletions(-)
diff --git a/accord-core/src/main/java/accord/api/Agent.java b/accord-core/src/main/java/accord/api/Agent.java
index d02b71d8..a76dd41f 100644
--- a/accord-core/src/main/java/accord/api/Agent.java
+++ b/accord-core/src/main/java/accord/api/Agent.java
@@ -67,7 +67,7 @@ public interface Agent extends UncaughtExceptionListener
@Override
void onUncaughtException(Throwable t);
- void onHandledException(Throwable t, String context);
+ void onCaughtException(Throwable t, String context);
/**
* @return PreAccept timeout with implementation-defined resolution of the hybrid logical clock
diff --git a/accord-core/src/main/java/accord/api/ConfigurationService.java b/accord-core/src/main/java/accord/api/ConfigurationService.java
index 3650f274..94e97bca 100644
--- a/accord-core/src/main/java/accord/api/ConfigurationService.java
+++ b/accord-core/src/main/java/accord/api/ConfigurationService.java
@@ -159,7 +159,7 @@ public interface ConfigurationService
* Called when all TxnId with an epoch equal to or before this that interact with this range have been executed,
* in whatever epoch they execute in. Once the whole range is covered this epoch is redundant, and may be cleaned up.
*/
- void onEpochRedundant(Ranges ranges, long epoch);
+ void onEpochRetired(Ranges ranges, long epoch);
default void onRemoveNode(long epoch, Node.Id removed) {}
}
diff --git a/accord-core/src/main/java/accord/api/DataStore.java b/accord-core/src/main/java/accord/api/DataStore.java
index bd8d7e38..55327cfd 100644
--- a/accord-core/src/main/java/accord/api/DataStore.java
+++ b/accord-core/src/main/java/accord/api/DataStore.java
@@ -18,8 +18,6 @@
package accord.api;
-import javax.annotation.Nullable;
-
import accord.local.Node;
import accord.local.SafeCommandStore;
import accord.primitives.Ranges;
@@ -45,14 +43,18 @@ public interface DataStore
* To be invoked by implementation once we hear back from the replica that it
* has taken a snapshot to process.
*
- * Optional parameter maxApplied can supply the maximum timestamp of any applied
- * transaction in the data being bootstrapped from this source. If not provided
- * the store will coordinate a cheap global transaction to calculate a lower bound.
+ * Required parameter maxApplied supplies the maximum timestamp of any applied
+ * transaction in the data being bootstrapped from this source. This can be computed from
+ * the node's local MaxConflicts collection.
+ *
+ * An optional UniqueHlcs parameter can be supplied if the data store in question relies
+ * upon unique 8-byte hlcs for storing data. In this case it is a correctness requirement
+ * to provide information that can be used to seed the receiving node's CommandsForKey data.
*
* Note: if the membership has entirely changed, or all other replicas are still themselves
* bootstrapping, then this *must* be provided for the system to make progress.
*/
- AbortFetch started(@Nullable Timestamp maxApplied);
+ AbortFetch started(Timestamp maxApplied);
/**
* To be invoked by implementation once we decide to abort a fetch from a replica,
diff --git a/accord-core/src/main/java/accord/api/Key.java b/accord-core/src/main/java/accord/api/Key.java
index 82dfcdc9..1504b406 100644
--- a/accord-core/src/main/java/accord/api/Key.java
+++ b/accord-core/src/main/java/accord/api/Key.java
@@ -18,8 +18,6 @@
package accord.api;
-import javax.annotation.Nonnull;
-
import accord.primitives.Range;
import accord.primitives.RoutableKey;
import accord.primitives.Seekable;
@@ -37,6 +35,4 @@ public interface Key extends Seekable, RoutableKey
@Override
default Range asRange() { throw new UnsupportedOperationException(); }
-
- default int compareAsRoutingKey(@Nonnull RoutingKey that) { return toUnseekable().compareTo(that); }
}
diff --git a/accord-core/src/main/java/accord/api/ProtocolModifiers.java b/accord-core/src/main/java/accord/api/ProtocolModifiers.java
index f6f7991e..3f6ebf5b 100644
--- a/accord-core/src/main/java/accord/api/ProtocolModifiers.java
+++ b/accord-core/src/main/java/accord/api/ProtocolModifiers.java
@@ -199,6 +199,10 @@ public class ProtocolModifiers
public static boolean permitLocalExecution() { return permitLocalExecution; }
public static void setPermitLocalExecution(boolean newPermitLocalExecution) { permitLocalExecution = newPermitLocalExecution; }
+ private static boolean requiresUniqueHlcs = true;
+ public static boolean requiresUniqueHlcs() { return requiresUniqueHlcs; }
+ public static void setRequiresUniqueHlcs(boolean newRequiresUniqueHlcs) { requiresUniqueHlcs = newRequiresUniqueHlcs; }
+
public enum DependencyElision { OFF, ON, IF_DURABLE }
private static DependencyElision dependencyElision = IF_DURABLE;
public static DependencyElision dependencyElision() { return dependencyElision; }
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java b/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
index 99d302f1..5e580ee3 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinatePreAccept.java
@@ -42,7 +42,7 @@ import accord.utils.WrappableException;
import static accord.api.ProtocolModifiers.QuorumEpochIntersections;
import static accord.coordinate.Propose.NotAccept.proposeInvalidate;
import static accord.coordinate.tracking.RequestStatus.Success;
-import static accord.primitives.Timestamp.mergeMax;
+import static accord.primitives.Timestamp.mergeMaxAndFlags;
/**
* Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
@@ -149,7 +149,7 @@ abstract class CoordinatePreAccept<T> extends AbstractCoordinatePreAccept<T, Pre
void onPreAccepted(Topologies topologies)
{
// TODO (expected): we do not have to take max here if we have enough fast path votes (this may unnecessarily force us onto the slow path)
- Timestamp executeAt = oks.foldlNonNullValues((ok, prev) -> mergeMax(ok.witnessedAt, prev), Timestamp.NONE);
+ Timestamp executeAt = oks.foldlNonNullValues((ok, prev) -> mergeMaxAndFlags(ok.witnessedAt, prev), Timestamp.NONE);
node.withEpoch(executeAt.epoch(), this, t -> WrappableException.wrap(t), () -> {
onPreAccepted(topologies, executeAt, oks);
});
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
index 07a90917..226e252e 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
@@ -52,8 +52,8 @@ import static accord.coordinate.ExecutePath.FAST;
import static accord.coordinate.Propose.NotAccept.proposeAndCommitInvalidate;
import static accord.messages.Apply.Kind.Maximal;
import static accord.messages.Apply.participates;
+import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Timestamp.Flag.REJECTED;
-import static accord.primitives.Timestamp.mergeMax;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.utils.Invariants.checkArgument;
@@ -164,18 +164,20 @@ public class CoordinateSyncPoint<R> extends CoordinatePreAccept<R>
@Override
void onPreAccepted(Topologies topologies, Timestamp executeAt, SortedListMap<Node.Id, PreAcceptOk> oks)
{
- Timestamp checkRejected = oks.foldlNonNullValues((ok, prev) -> mergeMax(ok.witnessedAt, prev), Timestamp.NONE);
- if (checkRejected.is(REJECTED))
+ if (executeAt.is(REJECTED))
{
- proposeAndCommitInvalidate(node, Ballot.ZERO, txnId, route.homeKey(), route, checkRejected, this);
+ proposeAndCommitInvalidate(node, Ballot.ZERO, txnId, route.homeKey(), route, executeAt, this);
}
else
{
+ TxnId withFlags = txnId;
+ if (txnId.is(ExclusiveSyncPoint) && txnId.epoch() == executeAt.epoch())
+ withFlags = txnId.addFlag(HLC_BOUND);
Deps deps = Deps.merge(oks.valuesAsNullableList(), oks.domainSize(), List::get, ok -> ok.deps);
if (tracker.hasFastPathAccepted())
- adapter.execute(node, topologies, route, FAST, txnId, txn, txnId, deps, this);
+ adapter.execute(node, topologies, route, FAST, txnId, txn, withFlags, deps, this);
else if (tracker.hasMediumPathAccepted())
- adapter.propose(node, topologies, route, Accept.Kind.MEDIUM, Ballot.ZERO, txnId, txn, txnId, deps, this);
+ adapter.propose(node, topologies, route, Accept.Kind.MEDIUM, Ballot.ZERO, txnId, txn, withFlags, deps, this);
else
adapter.propose(node, topologies, route, Accept.Kind.SLOW, Ballot.ZERO, txnId, txn, executeAt, deps, this);
}
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java b/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
index 8ec1d43b..a80245b0 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteTxn.java
@@ -48,6 +48,7 @@ import accord.primitives.FullRoute;
import accord.primitives.Participants;
import accord.primitives.Ranges;
import accord.primitives.Timestamp;
+import accord.primitives.TimestampWithUniqueHlc;
import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.primitives.Writes;
@@ -87,8 +88,10 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
final Deps stableDeps;
final Topologies allTopologies;
final BiConsumer<? super Result, Throwable> callback;
+
private Participants<?> readScope;
private Data data;
+ private long uniqueHlc;
ExecuteTxn(Node node, Topologies topologies, FullRoute<?> route, ExecutePath path, TxnId txnId, Txn txn, Timestamp executeAt, Deps stableDeps, BiConsumer<? super Result, Throwable> callback)
{
@@ -178,6 +181,11 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
if (next != null)
data = data == null ? next : data.merge(next);
+ if (txnId.is(Txn.Kind.Write) && ok.uniqueHlc > 0)
+ {
+ Invariants.checkState(ok.uniqueHlc > executeAt.hlc());
+ uniqueHlc = Math.max(uniqueHlc, ok.uniqueHlc);
+ }
return ok.unavailable == null ? Approve : ApprovePartial;
}
@@ -202,6 +210,13 @@ public class ExecuteTxn extends ReadCoordinator<ReadReply>
{
if (failure == null)
{
+ Timestamp executeAt = this.executeAt;
+ if (txnId.is(Txn.Kind.Write) && uniqueHlc != 0)
+ {
+ Invariants.checkState(uniqueHlc > executeAt.hlc());
+ executeAt = new TimestampWithUniqueHlc(executeAt, uniqueHlc);
+ }
+
Writes writes = txnId.is(Txn.Kind.Write) ? txn.execute(txnId, executeAt, data) : null;
Result result = txn.result(txnId, executeAt, data);
adapter().persist(node, allTopologies, route, txnId, txn, executeAt, stableDeps, writes, result, callback);
diff --git a/accord-core/src/main/java/accord/coordinate/FindRoute.java b/accord-core/src/main/java/accord/coordinate/FindRoute.java
index 49a396c7..e37053c2 100644
--- a/accord-core/src/main/java/accord/coordinate/FindRoute.java
+++ b/accord-core/src/main/java/accord/coordinate/FindRoute.java
@@ -47,7 +47,7 @@ public class FindRoute extends CheckShards<Route<?>>
public Result(CheckStatusOk ok)
{
this.route = Route.castToFullRoute(ok.route);
- this.executeAt = ok.maxKnown().executeAt().isDecidedAndKnownToExecute() ? ok.executeAt : null;
+ this.executeAt = ok.maxKnown().isExecuteAtKnown() ? ok.executeAt : null;
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/Invalidate.java b/accord-core/src/main/java/accord/coordinate/Invalidate.java
index 359c9443..98a74ec4 100644
--- a/accord-core/src/main/java/accord/coordinate/Invalidate.java
+++ b/accord-core/src/main/java/accord/coordinate/Invalidate.java
@@ -168,7 +168,7 @@ public class Invalidate implements Callback<InvalidateReply>
// first look to see if it has already been decided/invalidated
// check each shard independently - if we find any that can be invalidated, do so
InvalidateReply max = InvalidateReply.max(replies.unsafeValuesBackingArray());
- InvalidateReply maxNotTruncated = !max.maxKnowledgeStatus.is(Status.Truncated) ? max : InvalidateReply.maxNotTruncated(replies.unsafeValuesBackingArray());
+ InvalidateReply maxNotTruncated = !max.maxStatus.is(Status.Truncated) ? max : InvalidateReply.maxNotTruncated(replies.unsafeValuesBackingArray());
if (maxNotTruncated != null)
{
@@ -183,6 +183,8 @@ public class Invalidate implements Callback<InvalidateReply>
break;
case PreAccepted:
+ case PreNotAccepted:
+ case NotAccepted:
if (tracker.isSafeToInvalidate() || transitivelyInvokedByPriorInvalidation)
break;
@@ -227,11 +229,11 @@ public class Invalidate implements Callback<InvalidateReply>
}
}
- if (max != maxNotTruncated)
+ if (max != maxNotTruncated || max.maxStatus != max.maxKnowledgeStatus)
{
Invariants.checkState(maxNotTruncated == null || !maxNotTruncated.maxKnowledgeStatus.hasBeen(Status.PreCommitted));
isDone = true;
- if (!tracker.isAnyNotTruncated())
+ if (!tracker.isAnyNotTruncated()) // TODO (required): this check may be insufficient unless we do not permit shards to truncate when e.g. pre-bootstrap. If we require this, document it!
{
commitInvalidate();
}
diff --git a/accord-core/src/main/java/accord/coordinate/Recover.java b/accord-core/src/main/java/accord/coordinate/Recover.java
index 1a0f3fac..bdaaaa80 100644
--- a/accord-core/src/main/java/accord/coordinate/Recover.java
+++ b/accord-core/src/main/java/accord/coordinate/Recover.java
@@ -48,7 +48,6 @@ import accord.primitives.ProgressToken;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
-import accord.primitives.Unseekables;
import accord.topology.Shard;
import accord.topology.Topologies;
import accord.topology.Topology;
@@ -75,7 +74,6 @@ import static accord.messages.BeginRecovery.RecoverOk.maxAccepted;
import static accord.messages.BeginRecovery.RecoverOk.maxAcceptedNotTruncated;
import static accord.primitives.Known.KnownDeps.DepsCommitted;
import static accord.primitives.Known.KnownDeps.DepsKnown;
-import static accord.primitives.Known.KnownDeps.DepsUnknown;
import static accord.primitives.ProgressToken.TRUNCATED_DURABLE_OR_INVALIDATED;
import static accord.primitives.Status.AcceptedMedium;
import static accord.primitives.TxnId.MediumPath.MEDIUM_PATH_WAIT_ON_RECOVERY;
@@ -370,7 +368,9 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
Deps earlierWait = Deps.merge(recoverOkList, recoverOkList.size(), List::get, ok -> ok.earlierWait);
Deps earlierNoWait = Deps.merge(recoverOkList, recoverOkList.size(), List::get, ok -> ok.earlierNoWait);
Deps laterWait = Deps.merge(recoverOkList, recoverOkList.size(), List::get, ok -> ok.laterWait);
+ Deps laterNoWait = Deps.merge(recoverOkList, recoverOkList.size(), List::get, ok -> ok.laterNoWait);
earlierWait = earlierWait.without(earlierNoWait);
+ laterWait = laterWait.without(laterNoWait);
if (!earlierWait.isEmpty() || !laterWait.isEmpty())
{
Propose.NotAccept.proposeAndPersistNotAccept(node, ballot, txnId, route.homeKey(), route, node.agent());
@@ -379,7 +379,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
// ruling out a fast path decision for us and changing our recovery decision).
// So, we wait for these commands to commit and recompute supersedingRejects for them.
AsyncChainCombiner.reduce(await(node, earlierWait, HasCommittedDeps),
- await(node, laterWait, CommittedOrNotAccepted), (a, b) -> a|b)
+ await(node, laterWait, CommittedOrNotAccepted), (a, b) -> a|b)
.begin((rejects, failure) -> {
if (failure != null) accept(null, failure);
else if (rejects) invalidate(recoverOks);
@@ -414,26 +414,7 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
private void withCommittedOrStableDeps(KnownDeps atLeast, List<RecoverOk> nullableRecoverOkList, Timestamp executeAt, BiConsumer<?, Throwable> failureCallback, Consumer<Deps> withDeps)
{
LatestDeps.MergedCommitResult merged = LatestDeps.mergeCommit(atLeast, executeAt, nullableRecoverOkList, txnId, ok -> ok == null ? null : ok.deps);
- node.withEpoch(executeAt.epoch(), failureCallback, () -> {
- Unseekables<?> missing = route.without(merged.sufficientFor);
- if (missing.isEmpty())
- {
- withDeps.accept(merged.deps);
- }
- else
- {
- CollectLatestDeps.withLatestDeps(node, txnId, route, missing, executeAt, (extraDeps, fail) -> {
- if (fail != null)
- {
- failureCallback.accept(null, fail);
- }
- else
- {
- withDeps.accept(merged.deps.with(LatestDeps.mergeCommit(DepsUnknown, executeAt, extraDeps, executeAt, i -> i).deps));
- }
- });
- }
- });
+ LatestDeps.withCommitted(node, txnId, executeAt, merged.deps, route, route.without(merged.sufficientFor), failureCallback, withDeps);
}
private void invalidate(SortedListMap<Id, RecoverOk> recoverOks)
diff --git a/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java b/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
index ca899df6..0d038cb2 100644
--- a/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
+++ b/accord-core/src/main/java/accord/coordinate/RecoverWithRoute.java
@@ -47,6 +47,7 @@ import accord.utils.WrappableException;
import static accord.coordinate.CoordinationAdapter.Factory.Kind.Recovery;
import static accord.primitives.Known.KnownDeps.DepsKnown;
import static accord.primitives.Known.KnownDeps.DepsUnknown;
+import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
import static accord.primitives.Known.Outcome.Apply;
import static accord.primitives.ProgressToken.APPLIED;
import static accord.primitives.ProgressToken.INVALIDATED;
@@ -195,7 +196,7 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
else
{
known = full.knownFor(txnId, trySendTo, trySendTo);
- Invariants.checkState(known.executeAt().isDecidedAndKnownToExecute() && known.outcome() == Apply);
+ Invariants.checkState(known.isExecuteAtKnown() && known.outcome() == Apply);
if (!known.is(DepsKnown))
{
@@ -240,13 +241,29 @@ public class RecoverWithRoute extends CheckShards<FullRoute<?>>
}
Txn txn = full.partialTxn.reconstitute(route);
- if (known.executeAt().isDecidedAndKnownToExecute() && known.is(DepsKnown) && known.outcome() == Apply)
+ if (known.is(ApplyAtKnown) && known.outcome() == Apply)
{
- Deps deps = full.stableDeps.reconstitute(route());
- node.withEpoch(full.executeAt.epoch(), node.agent(), t -> WrappableException.wrap(t), () -> {
- node.coordinationAdapter(txnId, Recovery).persist(node, topologies, route(), txnId, txn, full.executeAt, deps, full.writes, full.result, node.agent());
+ Deps deps;
+ Participants<?> missingDeps;
+ if (known.is(DepsKnown))
+ {
+ deps = full.stableDeps.reconstitute(route);
+ missingDeps = route.slice(0, 0);
+ }
+ else
+ {
+ Participants<?> hasDeps = full.map.knownFor(Known.DepsOnly, route);
+ missingDeps = route.without(hasDeps);
+ // convert to plain Deps as when we merge with latest deps we may erroneously keep the
+ // PartialDeps if e.g. an empty range of deps is found
+ deps = new Deps(full.stableDeps.reconstitutePartial(hasDeps));
+ }
+ LatestDeps.withCommitted(node, txnId, full.executeAt, deps, route, missingDeps, callback, mergedDeps -> {
+ node.withEpoch(full.executeAt.epoch(), node.agent(), t -> WrappableException.wrap(t), () -> {
+ node.coordinationAdapter(txnId, Recovery).persist(node, topologies, route, txnId, txn, full.executeAt, mergedDeps, full.writes, full.result, node.agent());
+ });
+ callback.accept(APPLIED, null);
});
- callback.accept(APPLIED, null);
}
else
{
diff --git a/accord-core/src/main/java/accord/coordinate/Stabilise.java b/accord-core/src/main/java/accord/coordinate/Stabilise.java
index 3855ba38..25958400 100644
--- a/accord-core/src/main/java/accord/coordinate/Stabilise.java
+++ b/accord-core/src/main/java/accord/coordinate/Stabilise.java
@@ -113,6 +113,12 @@ public abstract class Stabilise<R> implements Callback<ReadReply>
callback.accept(null, new Redundant(txnId, route.homeKey(), executeAt));
break;
case Rejected:
+ if (stableTracker.recordFailure(from) == Failed)
+ {
+ isDone = true;
+ callback.accept(null, new Preempted(txnId, route.homeKey()));
+ }
+ break;
case Insufficient:
node.send(from, new Commit(CommitWithTxn, from, allTopologies,
txnId, txn, route, ballot, executeAt, stabiliseDeps));
diff --git a/accord-core/src/main/java/accord/impl/AbstractConfigurationService.java b/accord-core/src/main/java/accord/impl/AbstractConfigurationService.java
index 2a8fb94d..63cf5094 100644
--- a/accord-core/src/main/java/accord/impl/AbstractConfigurationService.java
+++ b/accord-core/src/main/java/accord/impl/AbstractConfigurationService.java
@@ -386,10 +386,10 @@ public abstract class AbstractConfigurationService<EpochState extends AbstractCo
listener.onEpochClosed(ranges, epoch);
}
- public void receiveRedundant(Ranges ranges, long epoch)
+ public void receiveRetired(Ranges ranges, long epoch)
{
for (Listener listener : listeners)
- listener.onEpochRedundant(ranges, epoch);
+ listener.onEpochRetired(ranges, epoch);
}
protected void truncateTopologiesPreListenerNotify(long epoch) {}
diff --git a/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java b/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
index 739eb369..35fb7ab1 100644
--- a/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
+++ b/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
@@ -287,7 +287,7 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
}
@Override
- protected ReadOk constructReadOk(Ranges unavailable, Data data)
+ protected ReadOk constructReadOk(Ranges unavailable, Data data, long uniqueHlc)
{
Timestamp safeToReadAfter = safeToReadAfter();
Invariants.checkState(data == null || safeToReadAfter != null);
diff --git a/accord-core/src/main/java/accord/impl/AbstractLoader.java b/accord-core/src/main/java/accord/impl/AbstractLoader.java
index a8e764d6..26a4d68f 100644
--- a/accord-core/src/main/java/accord/impl/AbstractLoader.java
+++ b/accord-core/src/main/java/accord/impl/AbstractLoader.java
@@ -28,6 +28,7 @@ import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.primitives.TxnId;
+import static accord.local.Cleanup.Input.FULL;
import static accord.primitives.SaveStatus.Applying;
import static accord.primitives.SaveStatus.PreApplied;
import static accord.primitives.Status.Invalidated;
@@ -41,7 +42,7 @@ public abstract class AbstractLoader implements Journal.Loader
TxnId txnId = command.txnId();
if (command.status() != Truncated && command.status() != Invalidated)
{
- Cleanup cleanup = Cleanup.shouldCleanup(safeStore, command, command.participants());
+ Cleanup cleanup = Cleanup.shouldCleanup(FULL, safeStore, command, command.participants());
switch (cleanup)
{
case NO:
diff --git a/accord-core/src/main/java/accord/impl/AbstractSafeCommandStore.java b/accord-core/src/main/java/accord/impl/AbstractSafeCommandStore.java
index 22088f6b..3e5e86ab 100644
--- a/accord-core/src/main/java/accord/impl/AbstractSafeCommandStore.java
+++ b/accord-core/src/main/java/accord/impl/AbstractSafeCommandStore.java
@@ -81,7 +81,7 @@ extends SafeCommandStore
if (with.keys().domain() == Routable.Domain.Range)
return with.isSubsetOf(this.context) ? with : null;
- if (!context().keyHistory().satisfies(with.keyHistory()))
+ if (!context().keyHistory().satisfiesIfPresent(with.keyHistory()))
return null;
try (Caches caches = tryGetCaches())
diff --git a/accord-core/src/main/java/accord/impl/CommandChange.java b/accord-core/src/main/java/accord/impl/CommandChange.java
index 2a68b1aa..b179d73d 100644
--- a/accord-core/src/main/java/accord/impl/CommandChange.java
+++ b/accord-core/src/main/java/accord/impl/CommandChange.java
@@ -18,14 +18,18 @@
package accord.impl;
+import java.util.function.BiPredicate;
import java.util.function.Function;
+import java.util.function.ToLongFunction;
import com.google.common.annotations.VisibleForTesting;
import accord.api.Agent;
import accord.api.Result;
import accord.local.Cleanup;
+import accord.local.Cleanup.Input;
import accord.local.Command;
+import accord.local.Command.WaitingOn;
import accord.local.DurableBefore;
import accord.local.RedundantBefore;
import accord.local.StoreParticipants;
@@ -54,11 +58,24 @@ import static accord.impl.CommandChange.Field.PARTICIPANTS;
import static accord.impl.CommandChange.Field.PROMISED;
import static accord.impl.CommandChange.Field.RESULT;
import static accord.impl.CommandChange.Field.SAVE_STATUS;
+import static accord.impl.CommandChange.Field.MIN_UNIQUE_HLC;
import static accord.impl.CommandChange.Field.WAITING_ON;
import static accord.impl.CommandChange.Field.WRITES;
import static accord.local.Cleanup.NO;
import static accord.local.Cleanup.TRUNCATE_WITH_OUTCOME;
+import static accord.local.Command.Accepted.accepted;
+import static accord.local.Command.Committed.committed;
+import static accord.local.Command.Executed.executed;
+import static accord.local.Command.NotAcceptedWithoutDefinition.notAccepted;
+import static accord.local.Command.NotDefined.notDefined;
+import static accord.local.Command.NotDefined.uninitialised;
+import static accord.local.Command.PreAccepted.preaccepted;
+import static accord.local.Command.Truncated.erased;
+import static accord.local.Command.Truncated.invalidated;
+import static accord.local.Command.Truncated.truncatedApply;
+import static accord.local.Command.Truncated.vestigial;
import static accord.local.StoreParticipants.Filter.LOAD;
+import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
import static accord.primitives.Status.Durability.NotDurable;
public class CommandChange
@@ -71,6 +88,7 @@ public class CommandChange
PARTIAL_DEPS,
EXECUTE_AT,
EXECUTES_AT_LEAST,
+ MIN_UNIQUE_HLC,
DURABILITY,
ACCEPTED,
PROMISED,
@@ -93,6 +111,7 @@ public class CommandChange
protected Timestamp executeAt;
protected Timestamp executeAtLeast;
+ protected long minUniqueHlc;
protected SaveStatus saveStatus;
protected Status.Durability durability;
@@ -206,6 +225,7 @@ public class CommandChange
executeAt = null;
executeAtLeast = null;
+ minUniqueHlc = 0;
saveStatus = null;
durability = null;
@@ -237,7 +257,7 @@ public class CommandChange
this.txnId = txnId;
durability = NotDurable;
acceptedOrCommitted = promised = Ballot.ZERO;
- waitingOn = (txn, deps) -> null;
+ waitingOn = (txn, deps, executeAtLeast, uniqueHlc) -> null;
result = null;
}
@@ -251,7 +271,7 @@ public class CommandChange
return count;
}
- public Cleanup shouldCleanup(Agent agent, RedundantBefore redundantBefore, DurableBefore durableBefore, boolean isPartial)
+ public Cleanup shouldCleanup(Input input, Agent agent, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
if (!nextCalled)
return NO;
@@ -259,8 +279,7 @@ public class CommandChange
if (saveStatus == null || participants == null)
return Cleanup.NO;
- Cleanup cleanup = isPartial ? Cleanup.shouldCleanupPartial(agent, txnId, saveStatus, durability, participants, redundantBefore, durableBefore)
- : Cleanup.shouldCleanup(agent, txnId, saveStatus, durability, participants, redundantBefore, durableBefore);
+ Cleanup cleanup = Cleanup.shouldCleanup(input, agent, txnId, executeAt, saveStatus, durability, participants, redundantBefore, durableBefore);
if (this.cleanup != null && this.cleanup.compareTo(cleanup) > 0)
cleanup = this.cleanup;
return cleanup;
@@ -277,9 +296,6 @@ public class CommandChange
case ERASE:
return null;
- case EXPUNGE_PARTIAL:
- return expungePartial(cleanup, saveStatus, true);
-
case VESTIGIAL:
case INVALIDATE:
return saveStatusOnly();
@@ -304,28 +320,28 @@ public class CommandChange
builder.nextCalled = true;
Invariants.checkState(saveStatus != null);
- builder.flags = setFieldChanged(SAVE_STATUS, builder.flags);
+ builder.flags = setChanged(SAVE_STATUS, builder.flags);
builder.saveStatus = saveStatus;
- builder.flags = setFieldChanged(CLEANUP, builder.flags);
+ builder.flags = setChanged(CLEANUP, builder.flags);
builder.cleanup = cleanup;
if (executeAt != null)
{
- builder.flags = setFieldChanged(EXECUTE_AT, builder.flags);
+ builder.flags = setChanged(EXECUTE_AT, builder.flags);
builder.executeAt = executeAt;
}
if (durability != null)
{
- builder.flags = setFieldChanged(DURABILITY, builder.flags);
+ builder.flags = setChanged(DURABILITY, builder.flags);
builder.durability = durability;
}
if (participants != null)
{
- builder.flags = setFieldChanged(PARTICIPANTS, builder.flags);
+ builder.flags = setChanged(PARTICIPANTS, builder.flags);
builder.participants = participants;
}
if (includeOutcome && builder.writes != null)
{
- builder.flags = setFieldChanged(WRITES, builder.flags);
+ builder.flags = setChanged(WRITES, builder.flags);
builder.writes = writes;
}
@@ -342,7 +358,7 @@ public class CommandChange
if (saveStatus != null)
{
- builder.flags = setFieldChanged(SAVE_STATUS, builder.flags);
+ builder.flags = setChanged(SAVE_STATUS, builder.flags);
builder.saveStatus = saveStatus;
}
@@ -366,38 +382,37 @@ public class CommandChange
Invariants.checkState(txnId != null);
if (participants == null) participants = StoreParticipants.empty(txnId);
- else participants = participants.filter(LOAD, redundantBefore, txnId, saveStatus.known.executeAt().isDecidedAndKnownToExecute() ? executeAt : null);
+ else participants = participants.filter(LOAD, redundantBefore, txnId, saveStatus.known.isExecuteAtKnown() ? executeAt : null);
if (durability == null)
durability = NotDurable;
- Command.WaitingOn waitingOn = null;
+ WaitingOn waitingOn = null;
if (this.waitingOn != null)
- waitingOn = this.waitingOn.provide(txnId, partialDeps);
+ waitingOn = this.waitingOn.provide(txnId, partialDeps, executeAtLeast, minUniqueHlc);
switch (saveStatus.status)
{
case NotDefined:
- return saveStatus == SaveStatus.Uninitialised ? Command.NotDefined.uninitialised(txnId)
- : Command.NotDefined.notDefined(txnId, saveStatus, durability, participants, promised);
+ return saveStatus == SaveStatus.Uninitialised ? uninitialised(txnId)
+ : notDefined(txnId, saveStatus, durability, participants, promised);
case PreAccepted:
- return Command.PreAccepted.preaccepted(txnId, saveStatus, durability, participants, promised, executeAt, partialTxn, partialDeps);
+ return preaccepted(txnId, saveStatus, durability, participants, promised, executeAt, partialTxn, partialDeps);
case AcceptedInvalidate:
case PreNotAccepted:
case NotAccepted:
if (!saveStatus.known.isDefinitionKnown())
- return Command.NotAcceptedWithoutDefinition.notAccepted(txnId, saveStatus, durability, participants, promised, acceptedOrCommitted, partialDeps);
+ return notAccepted(txnId, saveStatus, durability, participants, promised, acceptedOrCommitted, partialDeps);
case AcceptedMedium:
case AcceptedSlow:
case PreCommitted:
- return Command.Accepted.accepted(txnId, saveStatus, durability, participants, promised, executeAt, partialTxn, partialDeps, acceptedOrCommitted);
-
+ return accepted(txnId, saveStatus, durability, participants, promised, executeAt, partialTxn, partialDeps, acceptedOrCommitted);
case Committed:
case Stable:
- return Command.Committed.committed(txnId, saveStatus, durability, participants, promised, executeAt, partialTxn, partialDeps, acceptedOrCommitted, waitingOn);
+ return committed(txnId, saveStatus, durability, participants, promised, executeAt, partialTxn, partialDeps, acceptedOrCommitted, waitingOn);
case PreApplied:
case Applied:
- return Command.Executed.executed(txnId, saveStatus, durability, participants, promised, executeAt, partialTxn, partialDeps, acceptedOrCommitted, waitingOn, writes, result);
+ return executed(txnId, saveStatus, durability, participants, promised, executeAt, partialTxn, partialDeps, acceptedOrCommitted, waitingOn, writes, result);
case Truncated:
case Invalidated:
return truncated(txnId, saveStatus, durability, participants, executeAt, executeAtLeast, writes, result);
@@ -414,14 +429,14 @@ public class CommandChange
case TruncatedApplyWithOutcome:
case TruncatedApplyWithDeps:
case TruncatedApply:
- return Command.Truncated.truncatedApply(txnId, status, durability, participants, executeAt, writes, result, executesAtLeast);
- case ErasedOrVestigial:
- return Command.Truncated.erasedOrVestigial(txnId, participants);
+ return truncatedApply(txnId, status, durability, participants, executeAt, writes, result, executesAtLeast);
+ case Vestigial:
+ return vestigial(txnId, participants);
case Erased:
// TODO (expected): why are we saving Durability here for erased commands?
- return Command.Truncated.erased(txnId, durability, participants);
+ return erased(txnId, durability, participants);
case Invalidated:
- return Command.Truncated.invalidated(txnId, participants);
+ return invalidated(txnId, participants);
}
}
@@ -430,6 +445,8 @@ public class CommandChange
return "Builder {" +
"txnId=" + txnId +
", executeAt=" + executeAt +
+ ", executeAtLeast=" + executeAtLeast +
+ ", uniqueHlc=" + minUniqueHlc +
", saveStatus=" + saveStatus +
", durability=" + durability +
", acceptedOrCommitted=" + acceptedOrCommitted +
@@ -449,15 +466,15 @@ public class CommandChange
public interface WaitingOnProvider
{
- Command.WaitingOn provide(TxnId txnId, PartialDeps deps);
+ WaitingOn provide(TxnId txnId, PartialDeps deps, Timestamp executeAtLeast, long uniqueHlc);
}
- public static Command.WaitingOn getWaitingOn(Command command)
+ public static long getMinUniqueHlc(Command command)
{
- if (command instanceof Command.Committed)
- return command.asCommitted().waitingOn();
-
- return null;
+ WaitingOn waitingOn = command.waitingOn();
+ if (waitingOn == null)
+ return 0;
+ return waitingOn.minUniqueHlc();
}
/**
@@ -492,8 +509,11 @@ public class CommandChange
if (before == null && after == null)
return flags;
- flags = collectFlags(before, after, Command::executeAt, true, EXECUTE_AT, flags);
+ // TODO (expected): derive this from precomputed bit masking on Known, only testing equality of objects we can't infer directly
+ flags = collectFlags(before, after, Command::executeAt, Timestamp::equalsStrict, true, EXECUTE_AT, flags);
flags = collectFlags(before, after, Command::executesAtLeast, true, EXECUTES_AT_LEAST, flags);
+ flags = collectFlags(before, after, CommandChange::getMinUniqueHlc, MIN_UNIQUE_HLC, flags);
+
flags = collectFlags(before, after, Command::saveStatus, false, SAVE_STATUS, flags);
flags = collectFlags(before, after, Command::durability, false, DURABILITY, flags);
@@ -503,41 +523,51 @@ public class CommandChange
flags = collectFlags(before, after, Command::participants, true, PARTICIPANTS, flags);
flags = collectFlags(before, after, Command::partialTxn, false, PARTIAL_TXN, flags);
flags = collectFlags(before, after, Command::partialDeps, false, PARTIAL_DEPS, flags);
-
- // TODO: waitingOn vs WaitingOnWithExecutedAt?
- flags = collectFlags(before, after, CommandChange::getWaitingOn, true, WAITING_ON, flags);
+ flags = collectFlags(before, after, Command::waitingOn, WaitingOn::equalBitSets, true, WAITING_ON, flags);
flags = collectFlags(before, after, Command::writes, false, WRITES, flags);
flags = collectFlags(before, after, Command::result, false, RESULT, flags);
+ // make sure we have enough information to decide whether to expunge timestamps (for unique ApplyAt HLC guarantees)
+ if (isChanged(EXECUTE_AT, flags) && after.saveStatus().known.is(ApplyAtKnown))
+ {
+ flags = setChanged(PARTICIPANTS, flags);
+ flags = setChanged(SAVE_STATUS, flags);
+ }
return flags;
}
private static <OBJ, VAL> int collectFlags(OBJ lo, OBJ ro, Function<OBJ, VAL> convert, boolean allowClassMismatch, Field field, int flags)
+ {
+ return collectFlags(lo, ro, convert, Object::equals, allowClassMismatch, field, flags);
+ }
+
+ private static <OBJ, VAL> int collectFlags(OBJ lo, OBJ ro, Function<OBJ, VAL> convert, BiPredicate<VAL, VAL> equals, boolean allowClassMismatch, Field field, int flags)
{
VAL l = null;
VAL r = null;
if (lo != null) l = convert.apply(lo);
if (ro != null) r = convert.apply(ro);
- if (l == r)
- return flags; // no change
-
- if (r == null)
- flags = setFieldIsNull(field, flags);
-
- if (l == null || r == null)
- return setFieldChanged(field, flags);
-
- assert allowClassMismatch || l.getClass() == r.getClass() : String.format("%s != %s", l.getClass(), r.getClass());
+ if (l == r) return flags; // no change
+ if (r == null) return setFieldIsNullAndChanged(field, flags);
+ if (l == null) return setChanged(field, flags);
+ Invariants.checkState(allowClassMismatch || l.getClass() == r.getClass(), "%s != %s", l.getClass(), r.getClass());
+ if (equals.test(l, r)) return flags; // no change
+ return setChanged(field, flags);
+ }
- if (l.equals(r))
- return flags; // no change
+ private static <OBJ> int collectFlags(OBJ lo, OBJ ro, ToLongFunction<OBJ> convert, Field field, int flags)
+ {
+ long l = 0, r = 0;
+ if (lo != null) l = convert.applyAsLong(lo);
+ if (ro != null) r = convert.applyAsLong(ro);
- return setFieldChanged(field, flags);
+ return l == r ? flags:
+ r == 0 ? setFieldIsNullAndChanged(field, flags)
+ : setChanged(field, flags);
}
- // TODO (required): calculate flags once
public static boolean anyFieldChanged(int flags)
{
return (flags >>> 16) != 0;
@@ -549,13 +579,13 @@ public class CommandChange
return flags;
}
- public static int setFieldChanged(Field field, int oldFlags)
+ public static int setChanged(Field field, int oldFlags)
{
return oldFlags | (0x10000 << field.ordinal());
}
@VisibleForTesting
- public static boolean getFieldChanged(Field field, int oldFlags)
+ public static boolean isChanged(Field field, int oldFlags)
{
return (oldFlags & (0x10000 << field.ordinal())) != 0;
}
@@ -571,13 +601,13 @@ public class CommandChange
return i == 32 ? null : FIELDS[i];
}
- public static int unsetIterableFields(Field field, int iterable)
+ public static int unsetIterable(Field field, int iterable)
{
return iterable & ~(1 << field.ordinal());
}
@VisibleForTesting
- public static boolean getFieldIsNull(Field field, int oldFlags)
+ public static boolean isNull(Field field, int oldFlags)
{
return (oldFlags & (1 << field.ordinal())) != 0;
}
@@ -592,4 +622,9 @@ public class CommandChange
return oldFlags | (1 << field.ordinal());
}
+ public static int setFieldIsNullAndChanged(Field field, int oldFlags)
+ {
+ return oldFlags | (0x10001 << field.ordinal());
+ }
+
}
\ No newline at end of file
diff --git a/accord-core/src/main/java/accord/impl/DurabilityScheduling.java b/accord-core/src/main/java/accord/impl/DurabilityScheduling.java
index 278d4139..8fc01541 100644
--- a/accord-core/src/main/java/accord/impl/DurabilityScheduling.java
+++ b/accord-core/src/main/java/accord/impl/DurabilityScheduling.java
@@ -662,7 +662,7 @@ public class DurabilityScheduling implements ConfigurationService.Listener
}
@Override
- public void onEpochRedundant(Ranges ranges, long epoch)
+ public void onEpochRetired(Ranges ranges, long epoch)
{
}
}
\ No newline at end of file
diff --git a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
index d63fb6d8..a798f49f 100644
--- a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
+++ b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
@@ -78,6 +78,7 @@ import accord.primitives.Route;
import accord.primitives.Status;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
+import accord.primitives.Txn.Kind.Kinds;
import accord.primitives.TxnId;
import accord.primitives.Unseekable;
import accord.primitives.Unseekables;
@@ -87,6 +88,7 @@ import accord.utils.async.AsyncChains;
import accord.utils.async.Cancellable;
import org.agrona.collections.ObjectHashSet;
+import static accord.local.Cleanup.Input.FULL;
import static accord.local.KeyHistory.ASYNC;
import static accord.primitives.Known.KnownRoute.MaybeRoute;
import static accord.primitives.Routable.Domain.Range;
@@ -94,7 +96,7 @@ import static accord.primitives.Routables.Slice.Minimal;
import static accord.local.KeyHistory.SYNC;
import static accord.primitives.SaveStatus.Applying;
import static accord.primitives.SaveStatus.Erased;
-import static accord.primitives.SaveStatus.ErasedOrVestigial;
+import static accord.primitives.SaveStatus.Vestigial;
import static accord.primitives.SaveStatus.NotDefined;
import static accord.primitives.SaveStatus.ReadyToExecute;
import static accord.primitives.Status.Applied;
@@ -104,6 +106,8 @@ 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.primitives.Txn.Kind.Read;
+import static accord.primitives.Txn.Kind.SyncPoint;
import static accord.utils.Invariants.illegalState;
import static java.lang.String.format;
@@ -116,9 +120,7 @@ public abstract class InMemoryCommandStore extends CommandStore
final NavigableMap<Timestamp, GlobalCommand> commandsByExecuteAt = new TreeMap<>();
private final NavigableMap<RoutableKey, GlobalCommandsForKey> commandsForKey = new TreeMap<>();
- // TODO (find library, efficiency): this is obviously super inefficient, need some range map
private final TreeMap<TxnId, RangeCommand> rangeCommands = new TreeMap<>();
- // TODO (desired): use `redundantBefore` information instead
protected Timestamp maxRedundant = Timestamp.NONE;
private InMemorySafeStore current;
@@ -284,7 +286,7 @@ public abstract class InMemoryCommandStore extends CommandStore
GlobalCommand globalCommand = commands.get(txnId);
; Invariants.checkState(globalCommand != null && !globalCommand.isEmpty());
Command command = globalCommand.value();
- Cleanup cleanup = Cleanup.shouldCleanup(agent, txnId, command.saveStatus(), command.durability(), command.participants(), unsafeGetRedundantBefore(), durableBefore());
+ Cleanup cleanup = Cleanup.shouldCleanup(FULL, agent, txnId, command.executeAt(), command.saveStatus(), command.durability(), command.participants(), unsafeGetRedundantBefore(), durableBefore());
Invariants.checkState(command.hasBeen(Applied)
|| cleanup.compareTo(Cleanup.TRUNCATE) >= 0
|| (durableBefore().min(txnId) == NotDurable &&
@@ -578,7 +580,7 @@ public abstract class InMemoryCommandStore extends CommandStore
protected final Map<TxnId, InMemorySafeCommand> commands;
private final Map<RoutableKey, InMemorySafeCommandsForKey> commandsForKey;
private final Set<Object> hasLoaded = new ObjectHashSet<>();
- private CommandSummaries.Snapshot commandsForRanges;
+ private ByTxnIdSnapshot commandsForRanges;
public InMemorySafeStore(InMemoryCommandStore commandStore,
RangesForEpoch ranges,
@@ -680,7 +682,7 @@ public abstract class InMemoryCommandStore extends CommandStore
return;
// TODO (expected): consider removing if erased
- if (updated.saveStatus() == Erased || updated.saveStatus() == ErasedOrVestigial)
+ if (updated.saveStatus() == Erased || updated.saveStatus() == Vestigial)
return;
Ranges slice = ranges(txnId, updated.executeAtOrTxnId());
@@ -763,7 +765,12 @@ public abstract class InMemoryCommandStore extends CommandStore
summaries.put(summary.txnId, summary);
}
- return commandsForRanges = () -> summaries;
+ final Kinds kinds = new Kinds(Read, ExclusiveSyncPoint, SyncPoint);
+ return commandsForRanges = new ByTxnIdSnapshot()
+ {
+ @Override public boolean mayContainAny(Txn.Kind kind) { return kinds.test(kind); }
+ @Override public NavigableMap<Timestamp, Summary> byTxnId() { return summaries; }
+ };
}
private boolean visitForKey(Unseekables<?> keysOrRanges, Predicate<CommandsForKey> forEach)
@@ -784,7 +791,7 @@ public abstract class InMemoryCommandStore extends CommandStore
}
@Override
- public <P1, P2> void visit(Unseekables<?> keysOrRanges, Timestamp startedBefore, Txn.Kind.Kinds testKind, ActiveCommandVisitor<P1, P2> visitor, P1 p1, P2 p2)
+ public <P1, P2> void visit(Unseekables<?> keysOrRanges, Timestamp startedBefore, Kinds testKind, ActiveCommandVisitor<P1, P2> visitor, P1 p1, P2 p2)
{
visitForKey(keysOrRanges, cfk -> { cfk.visit(startedBefore, testKind, visitor, p1, p2); return true; });
commandsForRanges().visit(keysOrRanges, startedBefore, testKind, visitor, p1, p2);
@@ -792,7 +799,7 @@ public abstract class InMemoryCommandStore extends CommandStore
// TODO (expected): instead of accepting a slice, accept the min/max epoch and let implementation handle it
@Override
- public boolean visit(Unseekables<?> keysOrRanges, TxnId testTxnId, Txn.Kind.Kinds testKind, TestStartedAt testStartedAt, Timestamp testStartedAtTimestamp, ComputeIsDep computeIsDep, AllCommandVisitor visit)
+ public boolean visit(Unseekables<?> keysOrRanges, TxnId testTxnId, Kinds testKind, TestStartedAt testStartedAt, Timestamp testStartedAtTimestamp, ComputeIsDep computeIsDep, AllCommandVisitor visit)
{
return visitForKey(keysOrRanges, cfk -> cfk.visit(testTxnId, testKind, testStartedAt, testStartedAtTimestamp, computeIsDep, null, visit))
&& commandsForRanges().visit(keysOrRanges, testTxnId, testKind, testStartedAt, testStartedAtTimestamp, computeIsDep, visit);
diff --git a/accord-core/src/main/java/accord/impl/ErasedSafeCommand.java b/accord-core/src/main/java/accord/impl/RetiredSafeCommand.java
similarity index 83%
rename from accord-core/src/main/java/accord/impl/ErasedSafeCommand.java
rename to accord-core/src/main/java/accord/impl/RetiredSafeCommand.java
index 55c8c8fe..ea762732 100644
--- a/accord-core/src/main/java/accord/impl/ErasedSafeCommand.java
+++ b/accord-core/src/main/java/accord/impl/RetiredSafeCommand.java
@@ -26,15 +26,15 @@ import accord.primitives.TxnId;
import accord.utils.Invariants;
import static accord.primitives.SaveStatus.Erased;
-import static accord.primitives.SaveStatus.ErasedOrVestigial;
+import static accord.primitives.SaveStatus.Vestigial;
import static accord.primitives.Status.Durability.NotDurable;
import static accord.primitives.Status.Durability.UniversalOrInvalidated;
-public class ErasedSafeCommand extends SafeCommand
+public class RetiredSafeCommand extends SafeCommand
{
final Command erased;
- public ErasedSafeCommand(TxnId txnId, SaveStatus saveStatus)
+ public RetiredSafeCommand(TxnId txnId, SaveStatus saveStatus)
{
super(txnId);
this.erased = erased(txnId, saveStatus);
@@ -42,8 +42,8 @@ public class ErasedSafeCommand extends SafeCommand
public static Command erased(TxnId txnId, SaveStatus saveStatus)
{
- Invariants.checkArgument(saveStatus.compareTo(Erased) >= 0);
- return new Command.Truncated(txnId, saveStatus, saveStatus == ErasedOrVestigial ? NotDurable : UniversalOrInvalidated, StoreParticipants.empty(txnId), null, null, null);
+ Invariants.checkArgument(saveStatus.compareTo(Vestigial) >= 0);
+ return new Command.Truncated(txnId, saveStatus, saveStatus == Erased ? UniversalOrInvalidated : NotDurable, StoreParticipants.empty(txnId), null, null, null);
}
@Override
diff --git a/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java b/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
index 077fc597..54c72c11 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
@@ -99,11 +99,15 @@ public class DefaultProgressLog implements ProgressLog, Runnable
private final Map<TxnId, StackTraceElement[]> 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];
// The tasks whose timers have elapsed and are going to be run
// The queue is drained here first before processing tasks so that tasks can modify the queue
private Object[] runBuffer;
private int runBufferCount;
+ private RunInvoker[] awaitingEpochBuffer = EMPTY_AWAITING_EPOCH_BUFFER;
+ private int awaitingEpochBufferCount;
+ private boolean isAwaitingEpoch;
private long nextInvokerId;
@@ -437,12 +441,15 @@ public class DefaultProgressLog implements ProgressLog, Runnable
return;
}
- // drain to a buffer to avoid reentrancy
- runBufferCount = 0;
+ processAwaitingEpoch();
+ // drain to a buffer to avoid reentrancy in timers
runBuffer = EMPTY_RUN_BUFFER;
+ runBufferCount = 0;
timers.advance(nowMicros, this, DefaultProgressLog::addToRunBuffer);
processRunBuffer(nowMicros);
cachedAny().forceDiscard(runBuffer, runBufferCount);
+ if (awaitingEpochBufferCount > 0)
+ rerunWithPendingEpoch();
}
catch (Throwable t)
{
@@ -457,23 +464,40 @@ public class DefaultProgressLog implements ProgressLog, Runnable
runBuffer[runBufferCount++] = add;
}
+ private void rerunWithPendingEpoch()
+ {
+ if (isAwaitingEpoch)
+ return;
+
+ long minEpoch = Long.MAX_VALUE;
+ for (int i = 0 ; i < awaitingEpochBufferCount ; ++i)
+ minEpoch = Math.min(awaitingEpochBuffer[i].run.txnId.epoch(), minEpoch);
+ Invariants.checkArgument(minEpoch != Long.MAX_VALUE);
+ isAwaitingEpoch = true;
+ node.withEpoch(minEpoch, (success, fail) -> commandStore.execute(() -> {
+ isAwaitingEpoch = false;
+ run();
+ }));
+ }
+
// TODO (expected): invoke immediately if the command is already loaded
private void processRunBuffer(long nowMicros)
{
+ long hasEpoch = node.topology().epoch();
for (int i = 0; i < runBufferCount; ++i)
{
TxnState run = (TxnState) runBuffer[i];
Invariants.checkState(!run.isScheduled());
TxnStateKind runKind = run.wasScheduledTimer();
validatePreRunState(run, runKind);
-
long pendingTimerDeadline = run.pendingTimerDeadline();
+ boolean invokeBoth = false;
if (pendingTimerDeadline > 0)
{
run.clearPendingTimerDelay();
if (pendingTimerDeadline <= nowMicros)
{
- invoke(run, runKind.other());
+ invokeBoth = true;
}
else
{
@@ -482,27 +506,58 @@ public class DefaultProgressLog implements ProgressLog, Runnable
}
}
- invoke(run, runKind);
+ long epoch = run.txnId.epoch();
+ if (epoch <= hasEpoch)
+ {
+ invoke(invoker(run, runKind));
+ if (invokeBoth) invoke(invoker(run, runKind.other()));
+ }
+ else
+ {
+ int count = invokeBoth ? 2 : 1;
+ if (awaitingEpochBufferCount + count >= awaitingEpochBuffer.length)
+ awaitingEpochBuffer = Arrays.copyOf(awaitingEpochBuffer, Math.max(8, awaitingEpochBufferCount * 2));
+ awaitingEpochBuffer[awaitingEpochBufferCount++] = invoker(run, runKind);
+ if (invokeBoth) awaitingEpochBuffer[awaitingEpochBufferCount++] = invoker(run, runKind.other());
+ }
}
Arrays.fill(runBuffer, 0, runBufferCount, null);
runBufferCount = 0;
}
+ private void processAwaitingEpoch()
+ {
+ long hasEpoch = node.topology().epoch();
+ int retainCount = 0;
+ for (int i = 0 ; i < awaitingEpochBufferCount ; ++i)
+ {
+ RunInvoker awaiting = awaitingEpochBuffer[i];
+ if (awaiting.run.txnId.epoch() <= hasEpoch) invoke(awaiting);
+ else awaitingEpochBuffer[retainCount++] = awaiting;
+ }
+ awaitingEpochBufferCount = retainCount;
+ if (retainCount == 0) awaitingEpochBuffer = EMPTY_AWAITING_EPOCH_BUFFER;
+ else if (retainCount < awaitingEpochBuffer.length / 2) awaitingEpochBuffer = Arrays.copyOf(awaitingEpochBuffer, retainCount);
+ }
+
private void validatePreRunState(TxnState run, TxnStateKind kind)
{
Progress progress = kind == Waiting ? run.waiting().waitingProgress() : run.home().homeProgress();
Invariants.checkState(progress != NoneExpected && progress != Querying);
}
- void invoke(TxnState run, TxnStateKind runKind)
+ void invoke(RunInvoker invoker)
+ {
+ commandStore.execute(contextFor(invoker.run.txnId), invoker)
+ .begin(commandStore.agent());
+ }
+
+ RunInvoker invoker(TxnState run, TxnStateKind runKind)
{
RunInvoker invoker = new RunInvoker(nextInvokerId(), run, runKind);
registerActive(runKind, run.txnId, invoker);
- node.withEpoch(run.txnId.epoch(), commandStore.agent(), () -> {
- commandStore.execute(contextFor(run.txnId), invoker)
- .begin(commandStore.agent());
- });
+ return invoker;
}
class RunInvoker implements Consumer<SafeCommandStore>
@@ -762,4 +817,6 @@ public class DefaultProgressLog implements ProgressLog, Runnable
return current.homeRetryCounter();
}
}
+
+
}
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 47b84c2d..0d0eb590 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/HomeState.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/HomeState.java
@@ -176,6 +176,7 @@ abstract class HomeState extends WaitingState
{
if (fail != null)
{
+ safeStore.agent().onCaughtException(fail, "Failed recovering " + state);
state.incrementHomeRetryCounter();
state.set(safeStore, instance, status, Queued);
}
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 c6e92482..0d6a60a7 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/WaitingState.java
@@ -368,7 +368,7 @@ abstract class WaitingState extends BaseTxnState
}
// TODO (expected): split into txn and deps sources
- Route<?> slicedRoute = slicedRoute(safeStore, txnId, route, txnId, highEpoch);
+ Route<?> slicedRoute = slicedRoute(safeStore, txnId, route, lowEpoch, highEpoch);
Invariants.checkState(!slicedRoute.isEmpty());
if (!command.hasBeen(Status.PreCommitted))
{
@@ -527,6 +527,7 @@ abstract class WaitingState extends BaseTxnState
}
else
{
+ safeStore.agent().onCaughtException(fail, "Failed fetching data for " + state);
state.retry(safeStore, safeCommand, owner, blockedUntil);
}
}
diff --git a/accord-core/src/main/java/accord/local/Bootstrap.java b/accord-core/src/main/java/accord/local/Bootstrap.java
index d166fa35..fda28050 100644
--- a/accord-core/src/main/java/accord/local/Bootstrap.java
+++ b/accord-core/src/main/java/accord/local/Bootstrap.java
@@ -61,8 +61,6 @@ import static accord.utils.Invariants.illegalState;
* We also support aborting ranges that are no longer owned by the store, which may be passed down to the
* FetchCoordinator (or other implementation-defined coordinator).
*
- *
- *
* Important callback points:
* - Bootstrap.Attempt.starting()
* Invoked by system/impl, indicating we have sought a snapshot on a remote replica
@@ -221,7 +219,7 @@ class Bootstrap
return;
Timestamp safeToReadAt = maxAppliedLessOrEqualTo.compareTo(globalSyncId) <= 0 ? globalSyncId : maxAppliedLessOrEqualTo.next();
- safeToReadAts = ReducingRangeMap.add(safeToReadAts, state.ranges, safeToReadAt);
+ safeToReadAts = ReducingRangeMap.add(safeToReadAts, state.ranges, safeToReadAt, Timestamp::mergeMax);
maybeComplete(state.ranges);
}
}
diff --git a/accord-core/src/main/java/accord/local/Cleanup.java b/accord-core/src/main/java/accord/local/Cleanup.java
index 64379909..1244eb31 100644
--- a/accord-core/src/main/java/accord/local/Cleanup.java
+++ b/accord-core/src/main/java/accord/local/Cleanup.java
@@ -19,34 +19,37 @@
package accord.local;
import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
import accord.api.Agent;
-import accord.api.VisibleForImplementation;
import accord.primitives.FullRoute;
import accord.primitives.Participants;
import accord.primitives.Route;
import accord.primitives.SaveStatus;
import accord.primitives.Status.Durability;
+import accord.primitives.Timestamp;
import accord.primitives.TxnId;
+import accord.utils.UnhandledEnum;
+import static accord.api.ProtocolModifiers.Toggles.requiresUniqueHlcs;
+import static accord.local.Cleanup.Input.FULL;
+import static accord.local.Cleanup.Input.PARTIAL;
import static accord.local.RedundantBefore.PreBootstrapOrStale.FULLY;
-import static accord.local.RedundantStatus.GC_BEFORE;
import static accord.local.RedundantStatus.NOT_OWNED;
-import static accord.local.RedundantStatus.SHARD_REDUNDANT;
+import static accord.local.RedundantStatus.TRUNCATE_BEFORE;
+import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
import static accord.primitives.SaveStatus.Erased;
-import static accord.primitives.SaveStatus.ErasedOrVestigial;
import static accord.primitives.SaveStatus.Invalidated;
-import static accord.primitives.SaveStatus.ReadyToExecute;
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.Applied;
-import static accord.primitives.Status.Durability.MajorityOrInvalidated;
import static accord.primitives.Status.Durability.UniversalOrInvalidated;
import static accord.primitives.Status.PreCommitted;
+import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Txn.Kind.EphemeralRead;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
+import static accord.primitives.Txn.Kind.Write;
import static accord.utils.Invariants.illegalState;
/**
@@ -59,13 +62,12 @@ public enum Cleanup
// we don't know if the command has been applied or invalidated as we have incomplete information
// so erase what information we don't need in future to decide this
// TODO (required): tighten up semantics here (and maybe infer more aggressively)
- EXPUNGE_PARTIAL(TruncatedApplyWithOutcome),
TRUNCATE_WITH_OUTCOME(TruncatedApplyWithOutcome),
TRUNCATE(TruncatedApply),
+ VESTIGIAL(Vestigial),
INVALIDATE(Invalidated),
- VESTIGIAL(ErasedOrVestigial),
ERASE(Erased),
- // we can stop storing the record entirely
+ // we can stop storing the (inspected portion of the) record entirely
EXPUNGE(Erased);
private static final Cleanup[] VALUES = values();
@@ -82,132 +84,128 @@ public enum Cleanup
return saveStatus.compareTo(appliesIfNot) >= 0 ? NO : this;
}
- static Cleanup min(Cleanup a, Cleanup b)
- {
- return a.compareTo(b) <= 0 ? a : b;
- }
+ public enum Input { PARTIAL, FULL }
// TODO (required): simulate compaction of log records in burn test
- @VisibleForImplementation
- public static Cleanup shouldCleanupPartial(Agent agent, TxnId txnId, SaveStatus status, Durability durability, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
- {
- return shouldCleanupPartialInternal(agent, txnId, status, durability, participants, redundantBefore, durableBefore).filter(status);
- }
-
- private static Cleanup shouldCleanupPartialInternal(Agent agent, TxnId txnId, SaveStatus status, @Nullable Durability durability, @Nullable StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
- {
- if (txnId.kind() == EphemeralRead)
- return NO; // TODO (required): clean-up based on timeout
-
- if (expunge(txnId, status, durableBefore, redundantBefore))
- return EXPUNGE;
-
- if (participants == null)
- return NO;
-
- if (!participants.hasFullRoute())
- {
- if (!redundantBefore.isAnyOnCoordinationEpoch(txnId, participants.owns(), GC_BEFORE))
- return NO;
-
- // we only need to keep the outcome if we have it; otherwise we can expunge
- switch (status)
- {
- case TruncatedApply:
- case TruncatedApplyWithOutcome:
- case Invalidated:
- return NO;
- case PreApplied:
- case Applied:
- case Applying:
- return TRUNCATE_WITH_OUTCOME;
- default:
- return EXPUNGE_PARTIAL;
- }
- }
-
- return cleanupWithFullRoute(agent, true, participants, txnId, status, durability, redundantBefore, durableBefore);
- }
-
- public static Cleanup shouldCleanup(SafeCommandStore safeStore, Command command)
+ public static Cleanup shouldCleanup(Input input, SafeCommandStore safeStore, Command command)
{
- return shouldCleanup(safeStore, command, command.participants());
+ return shouldCleanup(input, safeStore, command, command.participants());
}
- public static Cleanup shouldCleanup(SafeCommandStore safeStore, Command command, @Nonnull StoreParticipants participants)
+ public static Cleanup shouldCleanup(Input input, SafeCommandStore safeStore, Command command, @Nonnull StoreParticipants participants)
{
- return shouldCleanup(safeStore.agent(), command.txnId(), command.saveStatus(), command.durability(), participants,
+ return shouldCleanup(input, safeStore.agent(), command.txnId(), command.executeAt(), command.saveStatus(), command.durability(), participants,
safeStore.redundantBefore(), safeStore.durableBefore());
}
- public static Cleanup shouldCleanup(Agent agent, Command command, RedundantBefore redundantBefore, DurableBefore durableBefore)
+ public static Cleanup shouldCleanup(Input input, Agent agent, Command command, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
- return shouldCleanup(agent, command.txnId(), command.saveStatus(), command.durability(), command.participants(),
+ return shouldCleanup(input, agent, command.txnId(), command.executeAt(), command.saveStatus(), command.durability(), command.participants(),
redundantBefore, durableBefore);
}
- public static Cleanup shouldCleanup(Agent agent, TxnId txnId, SaveStatus status, Durability durability, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
+ public static Cleanup shouldCleanup(Input input, Agent agent, TxnId txnId, Timestamp executeAt, SaveStatus status, Durability durability, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
- return shouldCleanupInternal(agent, txnId, status, durability, participants, redundantBefore, durableBefore)
- .filter(status);
+ Cleanup cleanup = shouldCleanupInternal(input, agent, txnId, executeAt, status, durability, participants, redundantBefore, durableBefore);
+ return cleanup.filter(status);
}
- private static Cleanup shouldCleanupInternal(Agent agent, TxnId txnId, SaveStatus saveStatus, Durability durability, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
+ /**
+ * Decide if (and how) we can cleanup the transaction in question.
+ * </p>
+ * We can ERASE data once we are certain no other replicas require our information.
+ * We can EXPUNGE data once we can reliably and safely EXPUNGE any partial record.
+ * To achieve the latter, we use only global summary information and the TxnId -
+ * and if present any applyAt.
+ *
+ * [If implementations require unique HLCs they must guarantee to save any applyAt alongside
+ * a Route that can be used to report the applyAt to any participating keys on restart.]
+ *
+ * </p>
+ * A transaction may be truncated as soon as it is durable locally and all shard(s)
+ * the CommandStore participates in, but must retain the transaction Outcome until
+ * it is durable at a majority of replicas on all shards.
+ * This permits other shards to contact us for recovery information.
+ *
+ * Note importantly that we cannot safely truncate commands that are pre-bootstrap that have
+ * not yet been applied, as we may be a member of the quorum that coordinated the command, even
+ * if we have not bootstrapped the range.
+ * TODO (expected): this requirement could be restricted to the home shard.
+ * </p>
+ * If we know a transaction is invalidated, but don't know its FullRoute,
+ * we pessimistically assume the whole cluster may need to see its outcome
+ * TODO (expected): we should be able to rely on replicas to infer Invalidated from an Erased record
+ * </p>
+ *
+ */
+ private static Cleanup shouldCleanupInternal(Input input, Agent agent, TxnId txnId, Timestamp executeAt, SaveStatus saveStatus, Durability durability, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
if (txnId.kind() == EphemeralRead)
return NO;
- if (expunge(txnId, saveStatus, durableBefore, redundantBefore))
- return EXPUNGE;
+ if (expunge(txnId, executeAt, saveStatus, participants, redundantBefore, durableBefore))
+ return expunge();
+
+ if (participants == null)
+ return NO;
if (!participants.hasFullRoute())
- return cleanupIfUndecided(txnId, saveStatus, participants, redundantBefore);
+ return cleanupIfUndecided(input, txnId, saveStatus, participants, redundantBefore);
- Cleanup result = cleanupWithFullRoute(agent, false, participants, txnId, saveStatus, durability, redundantBefore, durableBefore);
- if (result == NO)
- return cleanupIfUndecided(txnId, saveStatus, participants, redundantBefore);
- return result;
+ return cleanupWithFullRoute(input, agent, participants, txnId, executeAt, saveStatus, durability, redundantBefore, durableBefore);
}
- private static Cleanup cleanupIfUndecided(TxnId txnId, SaveStatus saveStatus, StoreParticipants participants, RedundantBefore redundantBefore)
+ private static Cleanup cleanupIfUndecided(Input input, TxnId txnId, SaveStatus saveStatus, StoreParticipants participants, RedundantBefore redundantBefore)
{
- if (saveStatus.hasBeen(PreCommitted))
+ // TODO (expected): consider if we can truncate more aggressively partial records, although we cannot infer anything from the fact they're undecided
+ if (input == PARTIAL || saveStatus.hasBeen(PreCommitted))
return NO;
- // TODO (required): make sure we don't return INVALIDATED for a transaction that's Uninitialised and could simply be ERASED
- // I believe this case is handled by the durableBefore EXPUNGE check, but add Invariant checks to ensure this (and prevent regressions)
- if (redundantBefore.isAnyOnCoordinationEpochAtLeast(txnId, participants.owns(), SHARD_REDUNDANT))
- return Cleanup.INVALIDATE;
-
- if (saveStatus == Uninitialised && redundantBefore.isAnyOnAnyEpochAtLeast(txnId, participants.owns(), SHARD_REDUNDANT))
- return VESTIGIAL;
-
- // Correctness here relies on the fact that owns() must contain any key in hasTouched()
- // that intersects txnId.epoch() for this CommandStore.
- // This handles two edges cases:
- // - A transitive transaction is ruled-out for execution by all owning shards without witnessing it directly
- // (in this case, if VESTIGIAL is returned Invalidate won't know how to proceed)
- // - A pre-bootstrap and shard-only-redundant transaction does not know its route;
- // we clear it from the progress log but cannot logically erase it if we require that a Route is known
- // (requiring a Covering route is an alternative solution to the prior edge case, and incompatible with this edge case)
- if (txnId.compareTo(redundantBefore.minShardRedundantBefore()) < 0)
- return VESTIGIAL;
-
- return NO;
+ if (participants.owns().isEmpty())
+ return txnId.compareTo(redundantBefore.minShardRedundantBefore()) < 0 ? vestigial() : NO;
+
+ RedundantStatus redundant = redundantBefore.status(txnId, null, participants.owns());
+ switch (redundant)
+ {
+ default: throw new UnhandledEnum(redundant);
+ case WAS_OWNED:
+ case WAS_OWNED_CLOSED:
+ case LIVE:
+ case PARTIALLY_PRE_BOOTSTRAP_OR_STALE:
+ case PRE_BOOTSTRAP_OR_STALE:
+ case LOCALLY_REDUNDANT:
+ case PARTIALLY_LOCALLY_REDUNDANT:
+ case PARTIALLY_SHARD_REDUNDANT:
+ return NO;
+
+ case WAS_OWNED_PARTIALLY_RETIRED:
+ case WAS_OWNED_RETIRED:
+ case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
+ return vestigial();
+
+ case SHARD_REDUNDANT:
+ case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
+ case TRUNCATE_BEFORE:
+ case GC_BEFORE:
+ // correctness here relies on the fact that we process expunges first via global properties
+ // so, if we reach here we would expect any Erase/Truncate to still exist and this path would not be taken
+ return invalidate();
+ }
}
- private static Cleanup cleanupWithFullRoute(Agent agent, boolean isPartial, StoreParticipants participants, TxnId txnId, SaveStatus saveStatus, Durability durability, RedundantBefore redundantBefore, DurableBefore durableBefore)
+ private static Cleanup cleanupWithFullRoute(Input input, Agent agent, StoreParticipants participants, TxnId txnId, Timestamp executeAt, SaveStatus saveStatus, Durability durability, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
// We first check if the command is redundant locally, i.e. whether it has been applied to all non-faulty replicas of the local shard
// If not, we don't want to truncate its state else we may make catching up for these other replicas much harder
FullRoute<?> route = Route.castToFullRoute(participants.route());
- RedundantStatus redundant = redundantBefore.status(txnId, route);
+ if (!saveStatus.known.is(ApplyAtKnown)) executeAt = null;
+ RedundantStatus redundant = redundantBefore.status(txnId, executeAt, route);
if (redundant == NOT_OWNED)
illegalState("Command " + txnId + " that is being loaded is not owned by this shard on route " + route);
switch (redundant)
{
- default: throw new AssertionError();
+ default: throw new UnhandledEnum(redundant);
case WAS_OWNED:
case WAS_OWNED_CLOSED:
case LIVE:
@@ -216,7 +214,6 @@ public enum Cleanup
case LOCALLY_REDUNDANT:
case PARTIALLY_LOCALLY_REDUNDANT:
case PARTIALLY_SHARD_REDUNDANT:
- case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
return NO;
case WAS_OWNED_PARTIALLY_RETIRED:
@@ -225,78 +222,91 @@ public enum Cleanup
return NO;
case WAS_OWNED_RETIRED:
- return VESTIGIAL;
+ return vestigial();
case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- return ERASE;
+ return truncate(saveStatus);
case SHARD_REDUNDANT:
- if (saveStatus.hasBeen(PreCommitted))
- {
- // special case coordination-only commands
- Participants<?> executes = participants.stillExecutes();
- if (executes != null && executes.isEmpty() && saveStatus.compareTo(ReadyToExecute) >= 0)
- {
- Durability test = Durability.max(durability, durableBefore.min(txnId, participants.route()));
- if (test.compareTo(MajorityOrInvalidated) >= 0)
- return TRUNCATE;
- }
- return NO;
- }
- return isPartial ? NO : INVALIDATE;
+ case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
+ if (!saveStatus.hasBeen(PreCommitted))
+ return input == FULL ? invalidate() : NO;
+ return NO;
case GC_BEFORE:
- case GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- if (!isPartial)
- {
- if (!saveStatus.hasBeen(PreCommitted))
- return INVALIDATE;
+ case TRUNCATE_BEFORE:
+ if (!saveStatus.hasBeen(PreCommitted))
+ return input == FULL ? invalidate() : NO;
+ if (input == FULL)
+ {
Participants<?> executes = participants.stillExecutes();
if (!saveStatus.hasBeen(Applied) && (executes == null || (!executes.isEmpty() && redundantBefore.preBootstrapOrStale(txnId, executes) != FULLY)))
{
// if we should execute this transaction locally, and we have not done so by the time we reach a GC point, something has gone wrong
- agent.onViolation(String.format("Loading SHARD_REDUNDANT command %s with status %s (that should have been Applied). Expected to be witnessed and executed by %s.", txnId, saveStatus, redundantBefore.max(participants.route(), e -> e.shardAppliedOrInvalidatedBefore)));
- return TRUNCATE;
+ agent.onViolation(String.format("Loading %s command %s with status %s (that should have been Applied). Expected to be witnessed and executed by %s.", redundant, txnId, saveStatus, redundantBefore.max(participants.route(), e -> e.shardAppliedOrInvalidatedBefore)));
+ return truncate(saveStatus);
}
}
Durability test = Durability.max(durability, durableBefore.min(txnId, participants.route()));
switch (test)
{
- default: throw new AssertionError("Unexpected durability: " + durability);
+ default: throw new UnhandledEnum(durability);
case Local:
case NotDurable:
case ShardUniversal:
- return TRUNCATE_WITH_OUTCOME;
+ return truncateWithOutcome();
case MajorityOrInvalidated:
case Majority:
- return TRUNCATE;
+ return truncate();
case UniversalOrInvalidated:
case Universal:
- return ERASE;
+ if (redundant == TRUNCATE_BEFORE)
+ return truncate();
+ return erase();
}
}
}
- private static boolean expunge(TxnId txnId, SaveStatus saveStatus, DurableBefore durableBefore, RedundantBefore redundantBefore)
+ private static boolean expunge(TxnId txnId, Timestamp executeAt, SaveStatus saveStatus, StoreParticipants participants, RedundantBefore redundantBefore, DurableBefore durableBefore)
{
+ // since we cannot guarantee to witness participants for all records, we must use the global durableBefore bounds
+ // TODO (expected): introduce a single-key flag, as this would facilitate faster cleanup of common transactions
if (durableBefore.min(txnId) != UniversalOrInvalidated)
return false;
- if (saveStatus == Invalidated)
- return true;
-
- // TODO (required): we should perhaps weaken this to separately account whether remotely and locally redundant?
+ // TODO (desired): we should perhaps weaken this to separately account whether remotely and locally redundant?
// i.e., if we know that the shard is remotely durable and we know we don't need it locally (e.g. due to bootstrap)
// then we can safely erase. Revisit as part of rationalising RedundantBefore registers.
- return redundantBefore.shardStatus(txnId) == GC_BEFORE;
+
+ TxnId minGcBefore = redundantBefore.minGcBefore();
+ if (minGcBefore.compareTo(txnId) <= 0)
+ return false;
+
+ if (!requiresUniqueHlcs() || !txnId.is(Write)) return true;
+ if (!saveStatus.known.is(ApplyAtKnown)) return true;
+ if (executeAt == null) return true;
+ if (minGcBefore.is(HLC_BOUND) && executeAt.uniqueHlc() < minGcBefore.hlc()) return true;
+ return participants.executes().isEmpty();
}
public static Cleanup forOrdinal(int ordinal)
{
return VALUES[ordinal];
}
+
+ // convenient for debugging
+ private static Cleanup invalidate() { return INVALIDATE; }
+ private static Cleanup truncate(SaveStatus saveStatus)
+ {
+ return saveStatus.known.is(ApplyAtKnown) ? truncate() : vestigial();
+ }
+ private static Cleanup truncateWithOutcome() { return TRUNCATE_WITH_OUTCOME; }
+ private static Cleanup truncate() { return TRUNCATE; }
+ private static Cleanup vestigial() { return VESTIGIAL; }
+ private static Cleanup erase() { return ERASE; }
+ private static Cleanup expunge() { return EXPUNGE; }
}
diff --git a/accord-core/src/main/java/accord/local/Command.java b/accord-core/src/main/java/accord/local/Command.java
index 7b9eb1db..3d34ccba 100644
--- a/accord-core/src/main/java/accord/local/Command.java
+++ b/accord-core/src/main/java/accord/local/Command.java
@@ -61,13 +61,12 @@ import com.google.common.annotations.VisibleForTesting;
import static accord.local.Command.Committed.committed;
import static accord.local.Command.Executed.executed;
import static accord.local.Command.NotAcceptedWithoutDefinition.notAccepted;
-import static accord.primitives.Known.KnownExecuteAt.ExecuteAtKnown;
import static accord.primitives.Known.KnownDeps.DepsUnknown;
import static accord.primitives.Routable.Domain.Key;
import static accord.primitives.Routable.Domain.Range;
import static accord.primitives.Routables.Slice;
import static accord.primitives.SaveStatus.AcceptedInvalidate;
-import static accord.primitives.SaveStatus.ErasedOrVestigial;
+import static accord.primitives.SaveStatus.Vestigial;
import static accord.primitives.SaveStatus.NotAccepted;
import static accord.primitives.SaveStatus.PreNotAccepted;
import static accord.primitives.SaveStatus.ReadyToExecute;
@@ -287,14 +286,21 @@ public abstract class Command implements ICommand
public @Nullable Writes writes() { return null; }
public @Nullable Result result() { return null; }
public @Nullable WaitingOn waitingOn() { return null; }
+
/**
* Only meaningful when txnId.kind().awaitsOnlyDeps()
*/
- public @Nullable Timestamp executesAtLeast() { return null; }
+ public @Nullable Timestamp executesAtLeast()
+ {
+ WaitingOn waitingOn = waitingOn();
+ if (waitingOn == null)
+ return null;
+ return waitingOn.executeAtLeast();
+ }
public final Timestamp executeAtIfKnownElseTxnId()
{
- if (known().is(ExecuteAtKnown))
+ if (known().isExecuteAtKnown())
return executeAt();
return txnId();
}
@@ -306,7 +312,7 @@ public abstract class Command implements ICommand
public final Timestamp executeAtIfKnown(Timestamp orElse)
{
- if (known().is(ExecuteAtKnown))
+ if (known().isExecuteAtKnown())
return executeAt();
return orElse;
}
@@ -402,7 +408,6 @@ public abstract class Command implements ICommand
public static class Truncated extends Command
{
-
public static Truncated erased(Command command)
{
Durability durability = Durability.mergeAtLeast(command.durability(), UniversalOrInvalidated);
@@ -414,14 +419,14 @@ public abstract class Command implements ICommand
return validate(new Truncated(txnId, SaveStatus.Erased, durability, participants, null, null, null));
}
- public static Truncated erasedOrVestigial(Command command)
+ public static Truncated vestigial(Command command)
{
- return erasedOrVestigial(command.txnId(), command.participants());
+ return vestigial(command.txnId(), command.participants());
}
- public static Truncated erasedOrVestigial(TxnId txnId, StoreParticipants participants)
+ public static Truncated vestigial(TxnId txnId, StoreParticipants participants)
{
- return validate(new Truncated(txnId, SaveStatus.ErasedOrVestigial, NotDurable, participants, null, null, null));
+ return validate(new Truncated(txnId, SaveStatus.Vestigial, NotDurable, participants, null, null, null));
}
public static Truncated truncatedApply(Command command)
@@ -431,7 +436,7 @@ public abstract class Command implements ICommand
public static Truncated truncatedApply(Command command, @Nonnull StoreParticipants participants)
{
- Invariants.checkArgument(command.known().executeAt().isDecidedAndKnownToExecute());
+ Invariants.checkArgument(command.known().isExecuteAtKnown());
Durability durability = Durability.mergeAtLeast(command.durability(), ShardUniversal);
if (command.txnId().awaitsOnlyDeps())
{
@@ -736,14 +741,6 @@ public abstract class Command implements ICommand
this.waitingOn = waitingOn;
}
- @Override
- public final Timestamp executesAtLeast()
- {
- if (!txnId().awaitsOnlyDeps()) return null;
- if (status().hasBeen(Stable)) return waitingOn.executeAtLeast(executeAt());
- return null;
- }
-
@Override
public Command updateAttributes(StoreParticipants participants, Ballot promised, Durability durability)
{
@@ -1017,6 +1014,11 @@ public abstract class Command implements ICommand
return other.getClass() == WaitingOn.class && this.equals((WaitingOn) other);
}
+ public boolean equalBitSets(WaitingOn other)
+ {
+ return this.waitingOn.equals(other.waitingOn) && Objects.equals(this.appliedOrInvalidated, other.appliedOrInvalidated);
+ }
+
boolean equals(WaitingOn other)
{
return this.keys.equals(other.keys)
@@ -1063,7 +1065,8 @@ public abstract class Command implements ICommand
private SimpleBitSet waitingOn;
private @Nullable SimpleBitSet appliedOrInvalidated;
private Timestamp executeAtLeast;
- private boolean executeAtLeastUpdated;
+ private long uniqueHlc;
+ private boolean executeAtLeastOrUniqueHlcUpdated;
public Update(WaitingOn waitingOn)
{
@@ -1074,6 +1077,8 @@ public abstract class Command implements ICommand
this.appliedOrInvalidated = waitingOn.appliedOrInvalidated;
if (waitingOn.getClass() == WaitingOnWithExecuteAt.class)
executeAtLeast = ((WaitingOnWithExecuteAt) waitingOn).executeAtLeast;
+ if (waitingOn.getClass() == WaitingOnWithMinUniqueHlc.class)
+ uniqueHlc = ((WaitingOnWithMinUniqueHlc) waitingOn).uniqueHlc;
}
public Update(Committed committed)
@@ -1156,7 +1161,7 @@ public abstract class Command implements ICommand
{
return !(waitingOn instanceof ImmutableBitSet)
|| (appliedOrInvalidated != null && !(appliedOrInvalidated instanceof ImmutableBitSet))
- || executeAtLeastUpdated;
+ || executeAtLeastOrUniqueHlcUpdated;
}
public TxnId txnId(int i)
@@ -1272,11 +1277,22 @@ public abstract class Command implements ICommand
public void updateExecuteAtLeast(TxnId txnId, Timestamp executeAtLeast)
{
Invariants.checkState(txnId.awaitsOnlyDeps());
+ Invariants.checkState(uniqueHlc == 0);
Invariants.checkState(executeAtLeast.compareTo(txnId) > 0);
if (this.executeAtLeast == null || this.executeAtLeast.compareTo(executeAtLeast) < 0)
{
this.executeAtLeast = executeAtLeast;
- this.executeAtLeastUpdated = true;
+ this.executeAtLeastOrUniqueHlcUpdated = true;
+ }
+ }
+
+ public void updateUniqueHlc(Timestamp executeAt, long uniqueHlc)
+ {
+ Invariants.checkState(executeAtLeast == null);
+ if (uniqueHlc > executeAt.hlc() && uniqueHlc > this.uniqueHlc)
+ {
+ this.uniqueHlc = uniqueHlc;
+ this.executeAtLeastOrUniqueHlcUpdated = true;
}
}
@@ -1393,8 +1409,10 @@ public abstract class Command implements ICommand
public WaitingOn build()
{
WaitingOn result = new WaitingOn(keys, directRangeDeps, directKeyDeps, ensureImmutable(waitingOn), ensureImmutable(appliedOrInvalidated));
- if (executeAtLeast == null)
+ if (executeAtLeast == null && uniqueHlc == 0)
return result;
+ if (executeAtLeast == null)
+ return new WaitingOnWithMinUniqueHlc(result, uniqueHlc);
return new WaitingOnWithExecuteAt(result, executeAtLeast);
}
@@ -1411,6 +1429,11 @@ public abstract class Command implements ICommand
return "keys=" + waitingOnKeys + ", txnIds=" + waitingOnTxnIds;
}
}
+
+ public long minUniqueHlc()
+ {
+ return 0;
+ }
}
public static final class WaitingOnWithExecuteAt extends WaitingOn
@@ -1446,6 +1469,33 @@ public abstract class Command implements ICommand
}
}
+ public static final class WaitingOnWithMinUniqueHlc extends WaitingOn
+ {
+ public final long uniqueHlc;
+ public WaitingOnWithMinUniqueHlc(WaitingOn waitingOn, long uniqueHlc)
+ {
+ super(waitingOn);
+ this.uniqueHlc = uniqueHlc;
+ }
+
+ @Override
+ public long minUniqueHlc()
+ {
+ return uniqueHlc;
+ }
+
+ @Override
+ public boolean equals(Object other)
+ {
+ return other.getClass() == WaitingOnWithMinUniqueHlc.class && this.equals((WaitingOnWithMinUniqueHlc) other);
+ }
+
+ boolean equals(WaitingOnWithMinUniqueHlc other)
+ {
+ return super.equals(other) && uniqueHlc == other.uniqueHlc;
+ }
+ }
+
static Command.Committed updateWaitingOn(Committed command, WaitingOn.Update waitingOn)
{
if (!waitingOn.hasChanges())
@@ -1613,7 +1663,7 @@ public abstract class Command implements ICommand
if (txnId.awaitsOnlyDeps())
return validateCommandClass(status, TruncatedAwaitsOnlyDeps.class, klass);
case Erased:
- case ErasedOrVestigial:
+ case Vestigial:
case Invalidated:
return validateCommandClass(status, Truncated.class, klass);
default:
@@ -1656,8 +1706,11 @@ public abstract class Command implements ICommand
Invariants.checkState(executeAt == null || executeAt.compareTo(validate.txnId()) >= 0);
break;
case ExecuteAtKnown:
+ case ApplyAtKnown:
case ExecuteAtProposed:
- Invariants.checkState(executeAt != null && executeAt.compareTo(validate.txnId()) >= 0);
+ Invariants.checkState(executeAt != null);
+ int c = executeAt.compareTo(validate.txnId());
+ Invariants.checkState(c > 0 || (c == 0 && executeAt.getClass() == TxnId.class));
break;
case NoExecuteAt:
Invariants.checkState(executeAt.equals(Timestamp.NONE));
@@ -1727,7 +1780,7 @@ public abstract class Command implements ICommand
public static Durability durability(Durability durability, SaveStatus status)
{
- if (durability == NotDurable && status.compareTo(SaveStatus.PreApplied) >= 0 && status.compareTo(ErasedOrVestigial) < 0)
+ if (durability == NotDurable && status.compareTo(SaveStatus.PreApplied) >= 0 && status.compareTo(Vestigial) < 0)
return Local; // not necessary anywhere, but helps for logical consistency
return durability;
}
diff --git a/accord-core/src/main/java/accord/local/CommandStore.java b/accord-core/src/main/java/accord/local/CommandStore.java
index 6f94caf1..f251cc0d 100644
--- a/accord-core/src/main/java/accord/local/CommandStore.java
+++ b/accord-core/src/main/java/accord/local/CommandStore.java
@@ -62,9 +62,11 @@ import accord.utils.async.AsyncResults;
import org.agrona.collections.LongHashSet;
import static accord.api.ConfigurationService.EpochReady.DONE;
+import static accord.api.ProtocolModifiers.Toggles.requiresUniqueHlcs;
import static accord.local.PreLoadContext.empty;
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.utils.Invariants.checkState;
import static accord.utils.Invariants.illegalState;
@@ -350,8 +352,8 @@ public abstract class CommandStore implements AgentExecutor
{
Timestamp executeAt = updated.executeAt();
if (executeAt == null) return;
- if (prev != null && prev.executeAt() != null && prev.executeAt().compareTo(executeAt) >= 0) return;
-
+ if (prev != null && prev.executeAt() != null && prev.executeAt().compareToStrict(executeAt) >= 0) return;
+ executeAt = executeAt.flattenUniqueHlc(); // this is what guarantees a bootstrap recipient can compute uniqueHlc safely
MaxConflicts updatedMaxConflicts = maxConflicts.update(updated.participants().hasTouched(), executeAt);
updateMaxConflicts(executeAt, updatedMaxConflicts);
}
@@ -439,31 +441,21 @@ public abstract class CommandStore implements AgentExecutor
{
NodeCommandStoreService node = safeStore.node();
- boolean isExpired = node.now() - txnId.hlc() >= safeStore.preAcceptTimeout() && !txnId.isSyncPoint();
+ boolean isExpired = node.now() - txnId.hlc() >= safeStore.agent().preAcceptTimeout() && !txnId.isSyncPoint();
if (rejectBefore != null && !isExpired)
isExpired = rejectBefore.rejects(txnId, keys);
if (isExpired)
return node.uniqueNow(txnId).asRejected();
- if (txnId.is(ExclusiveSyncPoint))
- return txnId;
-
- // TODO (expected): reject if any transaction exists with a higher timestamp OR a higher epoch
- // this permits us to agree fast path decisions across epoch changes
// TODO (expected): we should (perhaps) separate conflicts for reads and writes
- Timestamp min = TxnId.max(txnId, maxConflicts.get(keys));
+ Timestamp min = TxnId.mergeMax(txnId, maxConflicts.get(keys));
if (permitFastPath && txnId == min && txnId.epoch() >= node.epoch())
return txnId;
return node.uniqueNow(min);
}
- public Timestamp maxConflict(Routables<?> keysOrRanges)
- {
- return maxConflicts.get(keysOrRanges);
- }
-
protected void unsafeRunIn(Runnable fn)
{
CommandStore prev = maybeCurrent();
@@ -642,18 +634,22 @@ public abstract class CommandStore implements AgentExecutor
return;
}
- safeStore.dataStore().snapshot(slicedRanges, globalSyncId).begin((success, fail) -> {
- if (fail != null)
- {
- agent.onHandledException(fail, "Unsuccessful dataStore snapshot; unable to update GC markers");
- return;
- }
+ // TODO (desired): not all systems care about HLC_BOUND for GC, make configurable
+ if (globalSyncId.is(HLC_BOUND) || !requiresUniqueHlcs())
+ {
+ safeStore.dataStore().snapshot(slicedRanges, globalSyncId).begin((success, fail) -> {
+ if (fail != null)
+ {
+ agent.onCaughtException(fail, "Unsuccessful dataStore snapshot; unable to update GC markers");
+ return;
+ }
- execute(PreLoadContext.empty(), safeStore0 -> {
- RedundantBefore addGc = RedundantBefore.create(slicedRanges, Long.MIN_VALUE, Long.MAX_VALUE, globalSyncId, globalSyncId, globalSyncId, globalSyncId, TxnId.NONE);
- safeStore0.upsertRedundantBefore(addGc);
- }).begin(agent());
- });
+ execute(PreLoadContext.empty(), safeStore0 -> {
+ RedundantBefore addGc = RedundantBefore.create(slicedRanges, Long.MIN_VALUE, Long.MAX_VALUE, globalSyncId, globalSyncId, globalSyncId, globalSyncId, TxnId.NONE);
+ safeStore0.upsertRedundantBefore(addGc);
+ }).begin(agent());
+ });
+ }
}
protected void updatedRedundantBefore(SafeCommandStore safeStore, TxnId syncId, Ranges ranges)
@@ -795,6 +791,7 @@ public abstract class CommandStore implements AgentExecutor
final synchronized void markSafeToRead(Timestamp forBootstrapAt, Timestamp at, Ranges ranges)
{
execute(empty(), safeStore -> {
+ // TODO (required): handle weird edge cases like newer at having a lower HLC than prior existing at, but higher epoch
Ranges validatedSafeToRead = redundantBefore.validateSafeToRead(forBootstrapAt, ranges);
safeStore.setSafeToRead(purgeAndInsert(safeToRead, at, validatedSafeToRead));
updateMaxConflicts(ranges, at);
diff --git a/accord-core/src/main/java/accord/local/CommandStores.java b/accord-core/src/main/java/accord/local/CommandStores.java
index 02638330..721915d4 100644
--- a/accord-core/src/main/java/accord/local/CommandStores.java
+++ b/accord-core/src/main/java/accord/local/CommandStores.java
@@ -50,11 +50,11 @@ import accord.primitives.EpochSupplier;
import accord.primitives.Participants;
import accord.primitives.Range;
import accord.primitives.Ranges;
-import accord.primitives.Routables;
import accord.primitives.Route;
import accord.primitives.RoutingKeys;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
+import accord.primitives.Unseekables;
import accord.topology.Shard;
import accord.topology.Topology;
import accord.utils.Invariants;
@@ -325,12 +325,12 @@ public abstract class CommandStores
.collect(Collectors.joining(", "));
}
- public long earliestLaterEpochThatFullyCovers(long sinceEpoch, Routables<?> keysOrRanges)
+ public long earliestLaterEpochThatFullyCovers(long sinceEpoch, Unseekables<?> keysOrRanges)
{
return Math.max(sinceEpoch, epochs[0]);
}
- public long latestEarlierEpochThatFullyCovers(long beforeEpoch, Routables<?> keysOrRanges)
+ public long latestEarlierEpochThatFullyCovers(long beforeEpoch, Unseekables<?> keysOrRanges)
{
int i = ceilIndex(beforeEpoch);
long latest = beforeEpoch;
@@ -618,12 +618,12 @@ public abstract class CommandStores
return forEach(context, RoutingKeys.of(key), minEpoch, maxEpoch, forEach, true);
}
- public AsyncChain<Void> forEach(PreLoadContext context, Routables<?> keys, long minEpoch, long maxEpoch, Consumer<SafeCommandStore> forEach)
+ public AsyncChain<Void> forEach(PreLoadContext context, Unseekables<?> keys, long minEpoch, long maxEpoch, Consumer<SafeCommandStore> forEach)
{
return forEach(context, keys, minEpoch, maxEpoch, forEach, true);
}
- private AsyncChain<Void> forEach(PreLoadContext context, Routables<?> keys, long minEpoch, long maxEpoch, Consumer<SafeCommandStore> forEach, boolean matchesMultiple)
+ private AsyncChain<Void> forEach(PreLoadContext context, Unseekables<?> keys, long minEpoch, long maxEpoch, Consumer<SafeCommandStore> forEach, boolean matchesMultiple)
{
return this.mapReduce(context, keys, minEpoch, maxEpoch, new MapReduce<SafeCommandStore, Void>()
{
@@ -652,7 +652,7 @@ public abstract class CommandStores
}
/**
- * See {@link #mapReduceConsume(PreLoadContext, Routables, long, long, MapReduceConsume)}
+ * See {@link #mapReduceConsume(PreLoadContext, Unseekables, long, long, MapReduceConsume)}
*/
public <O> Cancellable mapReduceConsume(PreLoadContext context, RoutingKey key, long minEpoch, long maxEpoch, MapReduceConsume<? super SafeCommandStore, O> mapReduceConsume)
{
@@ -666,9 +666,9 @@ public abstract class CommandStores
* Note that {@code reduce} and {@code accept} are invoked by only one thread, and never concurrently with {@code apply},
* so they do not require mutual exclusion.
*
- * Implementations are expected to invoke {@link #mapReduceConsume(PreLoadContext, Routables, long, long, MapReduceConsume)}
+ * Implementations are expected to invoke {@link #mapReduceConsume(PreLoadContext, Unseekables, long, long, MapReduceConsume)}
*/
- protected <O> Cancellable mapReduceConsume(PreLoadContext context, Routables<?> keys, long minEpoch, long maxEpoch, MapReduceConsume<? super SafeCommandStore, O> mapReduceConsume)
+ protected <O> Cancellable mapReduceConsume(PreLoadContext context, Unseekables<?> keys, long minEpoch, long maxEpoch, MapReduceConsume<? super SafeCommandStore, O> mapReduceConsume)
{
AsyncChain<O> reduced = mapReduce(context, keys, minEpoch, maxEpoch, mapReduceConsume);
return reduced.begin(mapReduceConsume);
@@ -680,7 +680,7 @@ public abstract class CommandStores
return reduced.begin(mapReduceConsume);
}
- public <O> AsyncChain<O> mapReduce(PreLoadContext context, Routables<?> keys, long minEpoch, long maxEpoch, MapReduce<? super SafeCommandStore, O> mapReduce)
+ public <O> AsyncChain<O> mapReduce(PreLoadContext context, Unseekables<?> keys, long minEpoch, long maxEpoch, MapReduce<? super SafeCommandStore, O> mapReduce)
{
AsyncChain<O> chain = null;
BiFunction<O, O, O> reducer = mapReduce::reduce;
diff --git a/accord-core/src/main/java/accord/local/CommandSummaries.java b/accord-core/src/main/java/accord/local/CommandSummaries.java
index 178f4c13..b5da6c8d 100644
--- a/accord-core/src/main/java/accord/local/CommandSummaries.java
+++ b/accord-core/src/main/java/accord/local/CommandSummaries.java
@@ -30,6 +30,7 @@ import accord.primitives.Ranges;
import accord.primitives.Routable;
import accord.primitives.SaveStatus;
import accord.primitives.Timestamp;
+import accord.primitives.Txn;
import accord.primitives.Txn.Kind.Kinds;
import accord.primitives.TxnId;
import accord.primitives.Unseekable;
@@ -265,9 +266,10 @@ public interface CommandSummaries
*/
<P1, P2> void visit(Unseekables<?> keysOrRanges, Timestamp startedBefore, Kinds testKind, ActiveCommandVisitor<P1, P2> visit, P1 p1, P2 p2);
- interface Snapshot extends CommandSummaries
+ interface ByTxnIdSnapshot extends CommandSummaries
{
NavigableMap<Timestamp, Summary> byTxnId();
+ default boolean mayContainAny(Txn.Kind kind) { return true; }
default boolean visit(Unseekables<?> keysOrRanges,
TxnId testTxnId,
diff --git a/accord-core/src/main/java/accord/local/Commands.java b/accord-core/src/main/java/accord/local/Commands.java
index 2307b9a9..cc8853fd 100644
--- a/accord-core/src/main/java/accord/local/Commands.java
+++ b/accord-core/src/main/java/accord/local/Commands.java
@@ -61,15 +61,14 @@ import static accord.api.ProgressLog.BlockedUntil.CanApply;
import static accord.api.ProgressLog.BlockedUntil.HasDecidedExecuteAt;
import static accord.api.ProtocolModifiers.Toggles.DependencyElision.IF_DURABLE;
import static accord.api.ProtocolModifiers.Toggles.dependencyElision;
-import static accord.local.Cleanup.ERASE;
+import static accord.local.Cleanup.Input.FULL;
import static accord.local.Cleanup.NO;
-import static accord.local.Cleanup.VESTIGIAL;
import static accord.local.Cleanup.shouldCleanup;
import static accord.local.Command.Truncated.erased;
-import static accord.local.Command.Truncated.erasedOrVestigial;
import static accord.local.Command.Truncated.invalidated;
import static accord.local.Command.Truncated.truncatedApply;
import static accord.local.Command.Truncated.truncatedApplyWithOutcome;
+import static accord.local.Command.Truncated.vestigial;
import static accord.local.Commands.Validated.INSUFFICIENT;
import static accord.local.Commands.Validated.UPDATE_TXN_IGNORE_DEPS;
import static accord.local.Commands.Validated.UPDATE_TXN_KEEP_DEPS;
@@ -78,12 +77,13 @@ import static accord.local.KeyHistory.INCR;
import static accord.local.KeyHistory.SYNC;
import static accord.local.PreLoadContext.contextFor;
import static accord.local.RedundantBefore.PreBootstrapOrStale.FULLY;
-import static accord.local.RedundantStatus.WAS_OWNED_RETIRED;
import static accord.local.StoreParticipants.Filter.LOAD;
import static accord.local.StoreParticipants.Filter.UPDATE;
import static accord.messages.Commit.Kind.StableMediumPath;
import static accord.primitives.Known.KnownDeps.DepsKnown;
import static accord.primitives.Known.KnownDeps.DepsProposedFixed;
+import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
+import static accord.primitives.Known.Outcome.Apply;
import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.SaveStatus.Applying;
import static accord.primitives.SaveStatus.Erased;
@@ -97,7 +97,6 @@ import static accord.primitives.Status.Applied;
import static accord.primitives.Status.Committed;
import static accord.primitives.Status.Durability;
import static accord.primitives.Status.Invalidated;
-import static accord.primitives.Known.KnownExecuteAt.ExecuteAtKnown;
import static accord.primitives.Known.KnownRoute.FullRoute;
import static accord.primitives.Status.NotDefined;
import static accord.primitives.Status.PreApplied;
@@ -454,9 +453,11 @@ public class Commands
public static ApplyOutcome apply(SafeCommandStore safeStore, SafeCommand safeCommand, StoreParticipants participants, TxnId txnId, Route<?> route, Timestamp executeAt, @Nullable Deps deps, @Nullable Txn txn, Writes writes, Result result)
{
Command command = safeCommand.current();
- if (command.hasBeen(PreApplied) && executeAt.equals(command.executeAt()))
+ if (command.hasBeen(PreApplied))
{
- logger.trace("{}: skipping apply - already executed ({})", txnId, command.status());
+ logger.trace("{}: skipping apply - already preapplied ({})", txnId, command.status());
+ if (command.executeAt() != null && !executeAt.equalsStrict(command.executeAt()) && command.saveStatus().compareTo(Erased) < 0)
+ safeStore.agent().onInconsistentTimestamp(command, command.executeAt(), executeAt);
return ApplyOutcome.Redundant;
}
else if (command.hasBeen(PreCommitted) && !executeAt.equals(command.executeAt()))
@@ -526,15 +527,14 @@ public class Commands
}
}
- protected static void postApply(SafeCommandStore safeStore, TxnId txnId)
+ protected static void postApply(SafeCommandStore safeStore, Command command)
{
- logger.trace("{} applied, setting status to Applied and notifying listeners", txnId);
- SafeCommand safeCommand = safeStore.get(txnId);
- Command original = safeCommand.current();
- if (!original.hasBeen(Applied))
+ logger.trace("{} applied, setting status to Applied and notifying listeners", command);
+ if (!command.hasBeen(Applied))
{
+ SafeCommand safeCommand = safeStore.get(command.txnId());
safeCommand.applied(safeStore);
- safeStore.notifyListeners(safeCommand, original);
+ safeStore.notifyListeners(safeCommand, command);
}
}
@@ -548,17 +548,8 @@ public class Commands
return safeStore.ranges().allAt(executeAt.epoch());
}
- public static AsyncChain<Void> applyChain(SafeCommandStore safeStore, PreLoadContext context, TxnId txnId, Participants<?> executes)
- {
- Command command = safeStore.get(txnId).current();
- if (command.hasBeen(Applied))
- return AsyncChains.success(null);
- return apply(safeStore, context, txnId, executes);
- }
-
- public static AsyncChain<Void> apply(SafeCommandStore safeStore, PreLoadContext context, TxnId txnId, Participants<?> executes)
+ public static AsyncChain<Void> applyChain(SafeCommandStore safeStore, Command.Executed command)
{
- Command.Executed command = safeStore.get(txnId).current().asExecuted();
// TODO (required): make sure we are correctly handling (esp. C* side with validation logic) executing a transaction
// that was pre-bootstrap for some range (so redundant and we may have gone ahead of), but had to be executed locally
// for another range
@@ -567,12 +558,15 @@ public class Commands
// the only reason it will be slow is because Memtable flushes are backed-up (which will be reported elsewhere)
// TODO (required): this is anyway non-monotonic and milliseconds granularity
long t0 = safeStore.node().now();
+ TxnId txnId = command.txnId();
+ Participants<?> executes = command.participants().stillExecutes(); // including any keys we aren't writing
return command.writes().apply(safeStore, executes, command.partialTxn())
- .flatMap(unused -> unsafeStore.submit(context, ss -> {
+ // TODO (expected): once we guarantee execution order KeyHistory can be ASYNC
+ .flatMap(unused -> unsafeStore.submit(contextFor(txnId, executes, SYNC), ss -> {
Command cmd = ss.get(txnId).current();
if (!cmd.hasBeen(Applied))
ss.agent().metricsEventsListener().onApplied(cmd, t0);
- postApply(ss, txnId);
+ postApply(ss, command);
return null;
}));
}
@@ -586,34 +580,13 @@ public class Commands
if (!executes.isEmpty())
return command.writes().apply(safeStore, executes, command.partialTxn())
.flatMap(unused -> unsafeStore.submit(context, ss -> {
- postApply(ss, command.txnId());
+ postApply(ss, command);
return null;
}));
else
return AsyncChains.success(null);
}
- private static void apply(SafeCommandStore safeStore, Command.Executed command, Participants<?> executes)
- {
- CommandStore unsafeStore = safeStore.commandStore();
- TxnId txnId = command.txnId();
- // TODO (expected): there is some coupling going on here - concept of TIMESTAMPS only needed if implementation tracks on apply
- PreLoadContext context = contextFor(command.txnId(), executes, SYNC);
- // this is sometimes called from a listener update, which will not have the keys in context
- if (safeStore.canExecuteWith(context))
- {
- applyChain(safeStore, context, txnId, executes).begin(safeStore.agent());
- }
- else
- {
- unsafeStore.submit(context, ss -> {
- // TODO (expected): should we recompute executes since async?
- applyChain(ss, context, txnId, executes).begin(ss.agent());
- return null;
- }).begin(safeStore.agent());
- }
- }
-
public static boolean maybeExecute(SafeCommandStore safeStore, SafeCommand safeCommand, boolean alwaysNotifyListeners, boolean notifyWaitingOn)
{
return maybeExecute(safeStore, safeCommand, safeCommand.current(), alwaysNotifyListeners, notifyWaitingOn);
@@ -662,21 +635,18 @@ public class Commands
case PreApplied:
Command.Executed executed = command.asExecuted();
- Participants<?> executes = !txnId.is(Write) ? null
- : executed.participants().stillExecutes()
- .intersecting(executed.writes().keys);
- if (executes == null || executes.isEmpty())
+ if (txnId.is(Write) && executed.writes().keys.intersects(executed.participants().stillExecutes()))
{
- logger.trace("{}: applying no-op", txnId);
- safeCommand.applied(safeStore);
+ safeCommand.applying(safeStore);
safeStore.notifyListeners(safeCommand, command);
+ logger.trace("{}: applying", command.txnId());
+ applyChain(safeStore, executed).begin(safeStore.agent());
}
else
{
- safeCommand.applying(safeStore);
+ logger.trace("{}: applying no-op", txnId);
+ safeCommand.applied(safeStore);
safeStore.notifyListeners(safeCommand, command);
- logger.trace("{}: applying", command.txnId());
- apply(safeStore, executed, executes);
}
return true;
default:
@@ -722,7 +692,7 @@ public class Commands
Command dependency = dependencySafeCommand.current();
Invariants.checkState(dependency.hasBeen(PreCommitted));
TxnId dependencyId = dependency.txnId();
- if (waitingId.awaitsOnlyDeps() && dependency.known().is(ExecuteAtKnown) && dependency.executeAt().compareTo(waitingId) > 0)
+ if (waitingId.awaitsOnlyDeps() && dependency.known().isExecuteAtKnown() && dependency.executeAt().compareTo(waitingId) > 0)
waitingOn.updateExecuteAtLeast(waitingId, dependency.executeAt());
if (dependency.hasBeen(Truncated))
@@ -734,7 +704,7 @@ public class Commands
case TruncatedApplyWithOutcome:
case TruncatedApplyWithDeps:
Invariants.checkState(dependency.executeAt().compareTo(waitingExecuteAt) < 0 || waitingId.awaitsOnlyDeps() || !dependency.txnId().witnesses(waitingId));
- case ErasedOrVestigial:
+ case Vestigial:
case Erased:
logger.trace("{}: {} is truncated. Stop listening and removing from waiting on commit set.", waitingId, dependencyId);
break;
@@ -763,7 +733,7 @@ public class Commands
{
Participants<?> participants = waiting.partialDeps().participants(dependency.txnId());
Participants<?> executes = participants.intersecting(waiting.participants().stillExecutes(), Minimal);
- RedundantStatus status = safeStore.redundantBefore().status(dependencyId, executes);
+ RedundantStatus status = safeStore.redundantBefore().status(dependencyId, waitingExecuteAt, executes);
switch (status)
{
case WAS_OWNED_PARTIALLY_RETIRED:
@@ -803,7 +773,7 @@ public class Commands
}
}
- public static void removeWaitingOnKeyAndMaybeExecute(SafeCommandStore safeStore, SafeCommand safeCommand, RoutingKey key)
+ public static void removeWaitingOnKeyAndMaybeExecute(SafeCommandStore safeStore, SafeCommand safeCommand, RoutingKey key, long uniqueHlc)
{
Command current = safeCommand.current();
if (current.saveStatus().compareTo(SaveStatus.Applied) >= 0)
@@ -824,6 +794,8 @@ public class Commands
Update waitingOn = new Update(committed);
waitingOn.removeWaitingOnKey(keyIndex);
+ if (uniqueHlc > 0)
+ waitingOn.updateUniqueHlc(committed.executeAt(), uniqueHlc);
safeCommand.updateWaitingOn(waitingOn);
if (!waitingOn.isWaiting())
maybeExecute(safeStore, safeCommand, false, true);
@@ -839,7 +811,7 @@ public class Commands
if (executeAt == null) executeAt = command.executeAtIfKnown();
if (participants.route() == null || executeAt == null)
{
- safeCommand.update(safeStore, Command.Truncated.erasedOrVestigial(command));
+ safeCommand.update(safeStore, Command.Truncated.vestigial(command));
if (participants.route() != null && !safeStore.coordinateRanges(command.txnId()).contains(participants.route().homeKey()))
safeStore.progressLog().clear(command.txnId());
}
@@ -860,11 +832,6 @@ public class Commands
}
}
- public static void setErased(SafeCommandStore safeStore, SafeCommand safeCommand)
- {
- purge(safeStore, safeCommand, ERASE, true);
- }
-
/**
* Purge all or part of the metadata for a Commmand
*/
@@ -930,7 +897,6 @@ public class Commands
|| store.redundantBefore().preBootstrapOrStale(command.txnId(), participants.owns()) == FULLY
|| (force && participants.executes() != null && participants.stillExecutes().isEmpty())
, "Command %s could not be purged", command);
- Invariants.checkState(cleanup != VESTIGIAL || participants.stillOwns().isEmpty() || store.redundantBefore().status(command.txnId(), participants.owns()).compareTo(WAS_OWNED_RETIRED) <= 0);
return purge(command, participants, cleanup);
}
@@ -948,17 +914,20 @@ public class Commands
case TRUNCATE_WITH_OUTCOME:
Invariants.checkArgument(!command.hasBeen(Truncated), "%s", command);
+ Invariants.checkArgument(command.known().is(Apply));
+ Invariants.checkArgument(command.known().is(ApplyAtKnown));
result = truncatedApplyWithOutcome(command.asExecuted());
break;
case TRUNCATE:
Invariants.checkState(command.saveStatus().compareTo(TruncatedApply) < 0);
+ Invariants.checkArgument(command.known().is(ApplyAtKnown));
result = truncatedApply(command, newParticipants);
break;
case VESTIGIAL:
Invariants.checkState(command.saveStatus().compareTo(Erased) < 0);
- result = erasedOrVestigial(command);
+ result = vestigial(command);
break;
case ERASE:
@@ -973,7 +942,7 @@ public class Commands
private static boolean validateSafeToCleanup(RedundantBefore redundantBefore, Command command, @Nonnull StoreParticipants participants)
{
TxnId txnId = command.txnId();
- RedundantStatus status = redundantBefore.status(txnId, participants.owns());
+ RedundantStatus status = redundantBefore.status(txnId, null, participants.owns());
switch (status)
{
default: throw new UnhandledEnum(status);
@@ -988,7 +957,7 @@ public class Commands
case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
case SHARD_REDUNDANT:
case GC_BEFORE:
- case GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
+ case TRUNCATE_BEFORE:
Invariants.paranoid(!command.hasBeen(PreCommitted) || command.participants().stillExecutes().isEmpty());
case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
case PRE_BOOTSTRAP_OR_STALE:
@@ -1002,7 +971,7 @@ public class Commands
public static boolean maybeCleanup(SafeCommandStore safeStore, SafeCommand safeCommand, Command command, @Nonnull StoreParticipants newParticipants)
{
StoreParticipants cleanupParticipants = newParticipants.filter(LOAD, safeStore, command.txnId(), command.executeAtIfKnown());
- Cleanup cleanup = shouldCleanup(safeStore, command, cleanupParticipants);
+ Cleanup cleanup = shouldCleanup(FULL, safeStore, command, cleanupParticipants);
if (cleanup == NO)
{
if (cleanupParticipants == newParticipants)
@@ -1047,7 +1016,7 @@ public class Commands
if (execute != context)
{
if (execute != null)
- context = PreLoadContext.contextFor(context.keys().without(execute.keys()), INCR);
+ context = contextFor(context.keys().without(execute.keys()), INCR);
Invariants.checkState(!context.keys().isEmpty());
safeStore = safeStore; // prevent accidental usage inside lambda
@@ -1097,7 +1066,7 @@ public class Commands
depSafe = safeStore.get(loadDepId);
if (depSafe.current().saveStatus() == Uninitialised)
{
- RedundantStatus redundantStatus = safeStore.redundantBefore().status(loadDepId, waiting.partialDeps().participants(loadDepId));
+ RedundantStatus redundantStatus = safeStore.redundantBefore().status(loadDepId, null, waiting.partialDeps().participants(loadDepId));
switch (redundantStatus)
{
default: throw new AssertionError("Unexpected redundant status: " + redundantStatus);
@@ -1113,7 +1082,7 @@ public class Commands
case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
case SHARD_REDUNDANT:
case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- case GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
+ case TRUNCATE_BEFORE:
case GC_BEFORE:
removeRedundantDependencies(safeStore, waitingSafe, loadDepId);
depSafe = null;
@@ -1179,7 +1148,7 @@ public class Commands
Command dep = depSafe.current();
SaveStatus depStatus = dep.saveStatus();
SaveStatus.LocalExecution depExecution = depStatus.execution;
- if (!waitingId.awaitsOnlyDeps() && depStatus.known.is(ExecuteAtKnown) && dep.executeAt().compareTo(waiting.executeAt()) > 0)
+ if (!waitingId.awaitsOnlyDeps() && depStatus.known.isExecuteAtKnown() && dep.executeAt().compareTo(waiting.executeAt()) > 0)
depExecution = SaveStatus.LocalExecution.Applied;
Participants<?> participants = null;
@@ -1189,7 +1158,7 @@ public class Commands
participants = waiting.partialDeps().participants(dep.txnId());
Participants<?> executes = participants.intersecting(waiting.participants().stillExecutes(), Minimal);
- RedundantStatus redundantStatus = safeStore.redundantBefore().status(dep.txnId(), executes);
+ RedundantStatus redundantStatus = safeStore.redundantBefore().status(dep.txnId(), null, executes);
switch (redundantStatus)
{
default: throw new AssertionError("Unknown redundant status: " + redundantStatus);
@@ -1213,7 +1182,7 @@ public class Commands
case PARTIALLY_SHARD_REDUNDANT:
case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
case SHARD_REDUNDANT:
- case GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
+ case TRUNCATE_BEFORE:
case GC_BEFORE:
Invariants.checkState(dep.hasBeen(Applied) || !dep.hasBeen(PreCommitted));
case PRE_BOOTSTRAP_OR_STALE:
@@ -1434,10 +1403,10 @@ public class Commands
}
}
- if (!expectKnown.deps().hasPreAcceptedOrProposedOrDecidedDeps())
+ if (!expectKnown.hasAnyDeps())
return UPDATE_TXN_IGNORE_DEPS;
- if (haveKnown.is(DepsKnown) || (haveKnown.deps() == expectKnown.deps() && (ballot == null || ballot.equals(cur.acceptedOrCommitted()))))
+ if (haveKnown.is(DepsKnown) || (haveKnown.equalDeps(expectKnown) && (ballot == null || ballot.equals(cur.acceptedOrCommitted()))))
return UPDATE_TXN_KEEP_DEPS;
if (!containsAll(partialDeps, participants.stillTouches()))
diff --git a/accord-core/src/main/java/accord/local/MaxConflicts.java b/accord-core/src/main/java/accord/local/MaxConflicts.java
index 727d8043..983b188a 100644
--- a/accord-core/src/main/java/accord/local/MaxConflicts.java
+++ b/accord-core/src/main/java/accord/local/MaxConflicts.java
@@ -40,11 +40,15 @@ public class MaxConflicts extends BTreeReducingRangeMap<Timestamp>
Timestamp get(Routables<?> keysOrRanges)
{
- return foldl(keysOrRanges, Timestamp::max, Timestamp.NONE);
+ return foldl(keysOrRanges, Timestamp::mergeMax, Timestamp.NONE);
}
public MaxConflicts update(Unseekables<?> keysOrRanges, Timestamp maxConflict)
{
+ // note: we use mergeMax to ensure we take the maximum epoch and hlc independently from any conflict
+ // this is particularly essential for propagating unique HLCs, so that bootstrap recipients don't
+ // begin serving reads too early
+ // TODO (required): should use mergeMax, but BTreeReducingRangeMap doesn't support merge functions that return neither input
return update(this, keysOrRanges, maxConflict, Timestamp::max, MaxConflicts::new, Builder::new);
}
diff --git a/accord-core/src/main/java/accord/local/Node.java b/accord-core/src/main/java/accord/local/Node.java
index 8d19412b..9d972395 100644
--- a/accord-core/src/main/java/accord/local/Node.java
+++ b/accord-core/src/main/java/accord/local/Node.java
@@ -377,7 +377,7 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
}
@Override
- public void onEpochRedundant(Ranges ranges, long epoch)
+ public void onEpochRetired(Ranges ranges, long epoch)
{
topology.onEpochRedundant(ranges, epoch);
}
@@ -551,7 +551,7 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
return commandStores.mapReduceConsume(context, key, minEpoch, maxEpoch, mapReduceConsume);
}
- public <T> Cancellable mapReduceConsumeLocal(PreLoadContext context, Routables<?> keys, long minEpoch, long maxEpoch, MapReduceConsume<SafeCommandStore, T> mapReduceConsume)
+ public <T> Cancellable mapReduceConsumeLocal(PreLoadContext context, Unseekables<?> keys, long minEpoch, long maxEpoch, MapReduceConsume<SafeCommandStore, T> mapReduceConsume)
{
return commandStores.mapReduceConsume(context, keys, minEpoch, maxEpoch, mapReduceConsume);
}
@@ -690,6 +690,7 @@ public class Node implements ConfigurationService.Listener, NodeCommandStoreServ
*/
public TxnId nextTxnId(Txn.Kind rw, Domain domain, int flags)
{
+ Invariants.checkState(domain == Domain.Key || rw != Txn.Kind.Write, "Range writes not supported without forwarding uniqueHlc information to WaitingOn for direct dependencies");
TxnId txnId = new TxnId(uniqueNow(), flags, rw, domain);
Invariants.checkState((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 70529fc8..eb4145bb 100644
--- a/accord-core/src/main/java/accord/local/RedundantBefore.java
+++ b/accord-core/src/main/java/accord/local/RedundantBefore.java
@@ -48,6 +48,7 @@ import accord.utils.ReducingIntervalMap;
import accord.utils.ReducingRangeMap;
import org.agrona.collections.Int2ObjectHashMap;
+import static accord.api.ProtocolModifiers.Toggles.requiresUniqueHlcs;
import static accord.local.RedundantBefore.PreBootstrapOrStale.FULLY;
import static accord.local.RedundantBefore.PreBootstrapOrStale.POST_BOOTSTRAP;
import static accord.local.RedundantBefore.PreBootstrapOrStale.PARTIALLY;
@@ -58,11 +59,13 @@ import static accord.local.RedundantStatus.NOT_OWNED;
import static accord.local.RedundantStatus.PRE_BOOTSTRAP_OR_STALE;
import static accord.local.RedundantStatus.SHARD_REDUNDANT;
import static accord.local.RedundantStatus.SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE;
+import static accord.local.RedundantStatus.TRUNCATE_BEFORE;
import static accord.local.RedundantStatus.WAS_OWNED;
import static accord.local.RedundantStatus.WAS_OWNED_CLOSED;
import static accord.local.RedundantStatus.WAS_OWNED_PARTIALLY_RETIRED;
import static accord.local.RedundantStatus.WAS_OWNED_RETIRED;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
+import static accord.primitives.Txn.Kind.Write;
import static accord.utils.Invariants.illegalState;
import static accord.utils.Invariants.partiallyOrdered;
@@ -148,6 +151,8 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
/**
* Represents the maximum TxnId we know to have fully executed until across all healthy replicas for the range in question.
* Unless we are stale or pre-bootstrap, in which case no such guarantees can be made.
+ *
+ * TODO (expected): track separate gcHlcBefore (i.e. gcBefore where is(HLC_BOUND))
*/
public final @Nonnull TxnId gcBefore;
@@ -288,11 +293,16 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return entry == null ? prev : entry.shardOnlyAppliedOrInvalidatedBefore.compareTo(txnId) >= 0;
}
- static @Nonnull RedundantStatus getAndMerge(Entry entry, @Nonnull RedundantStatus prev, TxnId txnId, Object ignore)
+ static @Nonnull Boolean isAnyOnCoordinationEpochShardRedundant(Entry entry, @Nonnull Boolean prev, TxnId txnId)
+ {
+ return isAnyOnCoordinationEpochAtLeast(entry, prev, txnId, SHARD_REDUNDANT);
+ }
+
+ static @Nonnull RedundantStatus getAndMerge(Entry entry, @Nonnull RedundantStatus prev, TxnId txnId, @Nullable Timestamp executeAtIfKnown)
{
if (entry == null)
return prev;
- return prev.merge(entry.get(txnId));
+ return prev.merge(entry.get(txnId, executeAtIfKnown));
}
static @Nonnull Boolean isAnyOnCoordinationEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, RedundantStatus status)
@@ -314,41 +324,41 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (entry.startOwnershipEpoch > epoch || entry.endOwnershipEpoch <= epoch)
return prev;
- return predicate.test(entry.getIgnoringOwnership(txnId), test);
+ return predicate.test(entry.getIgnoringOwnership(txnId, null), test);
}
- static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, RedundantStatus test, BiPredicate<RedundantStatus, RedundantStatus> predicate)
+ static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, Timestamp executeAt, RedundantStatus test, BiPredicate<RedundantStatus, RedundantStatus> predicate)
{
if (entry == null || prev)
return prev;
- return predicate.test(entry.get(txnId), test);
+ return predicate.test(entry.get(txnId, executeAt), test);
}
- static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, RedundantStatus status)
+ static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, Timestamp executeAt, RedundantStatus status)
{
- return isAnyOnAnyEpoch(entry, prev, txnId, status, (a, b) -> a == b);
+ return isAnyOnAnyEpoch(entry, prev, txnId, executeAt, status, (a, b) -> a == b);
}
- static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, Predicate<RedundantStatus> testStatus)
+ static @Nonnull Boolean isAnyOnAnyEpoch(Entry entry, @Nonnull Boolean prev, TxnId txnId, Timestamp executeAt, Predicate<RedundantStatus> testStatus)
{
if (entry == null || prev)
return prev;
- return testStatus.test(entry.get(txnId));
+ return testStatus.test(entry.get(txnId, executeAt));
}
static @Nonnull Boolean isAnyOnAnyEpochAtLeast(Entry entry, @Nonnull Boolean prev, TxnId txnId, RedundantStatus status)
{
- return isAnyOnAnyEpoch(entry, prev, txnId, status, (a, b) -> a.compareTo(b) >= 0);
+ return isAnyOnAnyEpoch(entry, prev, txnId, null, status, (a, b) -> a.compareTo(b) >= 0);
}
- static RedundantStatus get(Entry entry, TxnId txnId, EpochSupplier executeAt)
+ static RedundantStatus get(Entry entry, TxnId txnId, Timestamp executeAt)
{
if (entry == null)
return NOT_OWNED;
- return entry.get(txnId);
+ return entry.get(txnId, executeAt);
}
static PreBootstrapOrStale getAndMerge(Entry entry, @Nonnull PreBootstrapOrStale prev, TxnId txnId, Object ignore)
@@ -509,16 +519,16 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return notPreBootstrap;
}
- RedundantStatus get(TxnId txnId)
+ RedundantStatus get(TxnId txnId, @Nullable Timestamp executeAtIfKnown)
{
if (wasOwned(txnId))
return isShardRetired() ? WAS_OWNED_RETIRED :
isLocallyRetired() ? WAS_OWNED_PARTIALLY_RETIRED :
isClosed() ? WAS_OWNED_CLOSED : WAS_OWNED;
- return getIgnoringOwnership(txnId);
+ return getIgnoringOwnership(txnId, executeAtIfKnown);
}
- RedundantStatus getIgnoringOwnership(TxnId txnId)
+ RedundantStatus getIgnoringOwnership(TxnId txnId, @Nullable Timestamp executeAtIfKnown)
{
// we have to first check bootstrappedAt, since we are not locally redundant for the covered range
// if the txnId is partially pre-bootstrap (since we may not have applied it for this range)
@@ -529,7 +539,11 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
if (locallyAppliedOrInvalidatedBefore.compareTo(txnId) > 0)
{
if (gcBefore.compareTo(txnId) > 0)
- return GC_BEFORE;
+ {
+ if (!requiresUniqueHlcs() || executeAtIfKnown == null || gcBefore.hlc() > executeAtIfKnown.uniqueHlc())
+ return GC_BEFORE;
+ return TRUNCATE_BEFORE;
+ }
if (shardOnlyAppliedOrInvalidatedBefore.compareTo(txnId) > 0)
return SHARD_REDUNDANT;
return LOCALLY_REDUNDANT;
@@ -654,15 +668,15 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
public static RedundantBefore EMPTY = new RedundantBefore();
private final Ranges staleRanges;
- private final TxnId maxBootstrap, maxGcBefore, minShardRedundantBefore;
+ private final TxnId maxBootstrap, maxGcBefore;
+ private final TxnId minShardRedundantBefore, minGcBefore;
private final long maxRetiredEpoch;
private RedundantBefore()
{
staleRanges = Ranges.EMPTY;
- maxBootstrap = TxnId.NONE;
- maxGcBefore = TxnId.NONE;
- minShardRedundantBefore = TxnId.MAX;
+ maxBootstrap = maxGcBefore = TxnId.NONE;
+ minShardRedundantBefore = minGcBefore = TxnId.MAX;
maxRetiredEpoch = 0;
}
@@ -670,7 +684,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
{
super(inclusiveEnds, starts, values);
staleRanges = extractStaleRanges(values);
- TxnId maxBootstrap = TxnId.NONE, maxGcBefore = TxnId.NONE, minShardRedundantBefore = TxnId.MAX;
+ TxnId maxBootstrap = TxnId.NONE, maxGcBefore = TxnId.NONE, minShardRedundantBefore = TxnId.MAX, minGcBefore = TxnId.MAX;
long maxRetiredEpoch = 0;
for (Entry entry : values)
{
@@ -681,12 +695,15 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
maxGcBefore = entry.gcBefore;
if (entry.shardRedundantBefore().compareTo(minShardRedundantBefore) < 0)
minShardRedundantBefore = entry.shardRedundantBefore();
+ if (entry.gcBefore.compareTo(minGcBefore) < 0)
+ minGcBefore = entry.gcBefore;
if (entry.isLocallyRetired() && entry.endOwnershipEpoch >= maxRetiredEpoch)
maxRetiredEpoch = entry.endOwnershipEpoch;
}
this.maxBootstrap = maxBootstrap;
this.maxGcBefore = maxGcBefore;
this.minShardRedundantBefore = minShardRedundantBefore;
+ this.minGcBefore = minGcBefore;
this.maxRetiredEpoch = maxRetiredEpoch;
checkParanoid(starts, values);
}
@@ -750,35 +767,17 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return ReducingIntervalMap.mergeIntervals(a, b, Builder::new);
}
- public RedundantStatus get(TxnId txnId, @Nullable EpochSupplier executeAt, RoutingKey participant)
- {
- if (executeAt == null) executeAt = txnId;
- Entry entry = get(participant);
- return Entry.get(entry, txnId, executeAt);
- }
-
- public TxnId shardRedundantBefore(RoutingKey key)
- {
- Entry entry = get(key);
- return entry == null ? TxnId.NONE : entry.gcBefore;
- }
-
- public RedundantStatus shardStatus(TxnId txnId)
- {
- return foldl(Entry::getAndMerge, NOT_OWNED, txnId, null, i -> i == LIVE);
- }
-
- public RedundantStatus status(TxnId txnId, Participants<?> participants)
+ public RedundantStatus status(TxnId txnId, @Nullable Timestamp applyAtIfKnown, Participants<?> participants)
{ // TODO (required): consider how the use of txnId for executeAt affects exclusive sync points for cleanup
// may want to issue synthetic sync points for local evaluation in later epochs
- return foldl(participants, Entry::getAndMerge, NOT_OWNED, txnId, null, ignore -> false);
+ return foldl(participants, Entry::getAndMerge, NOT_OWNED, txnId, applyAtIfKnown, ignore -> false);
}
- public RedundantStatus status(TxnId txnId, RoutingKey key)
+ public RedundantStatus status(TxnId txnId, @Nullable Timestamp applyAtIfKnown, RoutingKey key)
{ // TODO (required): consider how the use of txnId for executeAt affects exclusive sync points for cleanup
// may want to issue synthetic sync points for local evaluation in later epochs
Entry entry = get(key);
- return entry == null ? NOT_OWNED : entry.get(txnId);
+ return entry == null ? NOT_OWNED : entry.get(txnId, applyAtIfKnown);
}
public boolean isAnyOnCoordinationEpoch(TxnId txnId, Unseekables<?> participants, RedundantStatus status)
@@ -796,18 +795,9 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return foldl(participants, Entry::isAnyOnCoordinationEpochAtLeast, false, txnId, status, isDone -> isDone);
}
- public boolean isAnyOnAnyEpoch(TxnId txnId, Unseekables<?> participants, RedundantStatus status)
- {
- return foldl(participants, Entry::isAnyOnAnyEpoch, false, txnId, status, isDone -> isDone);
- }
-
- public boolean isAnyOnAnyEpoch(TxnId txnId, Unseekables<?> participants, Predicate<RedundantStatus> testStatus)
- {
- return foldl(participants, Entry::isAnyOnAnyEpoch, false, txnId, testStatus, isDone -> isDone);
- }
-
public boolean isAnyOnAnyEpochAtLeast(TxnId txnId, Unseekables<?> participants, RedundantStatus status)
{
+ Invariants.checkArgument(status != GC_BEFORE || !txnId.is(Write), "Cannot compute GC_BEFORE for Write without applyAt");
return foldl(participants, Entry::isAnyOnAnyEpochAtLeast, false, txnId, status, isDone -> isDone);
}
@@ -864,6 +854,16 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
return minShardRedundantBefore;
}
+ public TxnId minGcBefore()
+ {
+ return minGcBefore;
+ }
+
+ public TxnId maxGcBefore()
+ {
+ return maxGcBefore;
+ }
+
/**
* Subtract any ranges we consider stale or pre-bootstrap
*/
@@ -1171,6 +1171,6 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Entry>
// TODO (required): consider race conditions when bootstrapping into an active command store, that may have seen a higher txnId than this?
// might benefit from maintaining a per-CommandStore largest TxnId register to ensure we allocate a higher TxnId for our ExclSync,
// or from using whatever summary records we have for the range, once we maintain them
- return status(minimumDependencyId, participantsOfWaitingTxn).compareTo(RedundantStatus.PARTIALLY_PRE_BOOTSTRAP_OR_STALE) >= 0;
+ return status(minimumDependencyId, executeAt, participantsOfWaitingTxn).compareTo(RedundantStatus.PARTIALLY_PRE_BOOTSTRAP_OR_STALE) >= 0;
}
}
diff --git a/accord-core/src/main/java/accord/local/RedundantStatus.java b/accord-core/src/main/java/accord/local/RedundantStatus.java
index 11e5c172..be82ac34 100644
--- a/accord-core/src/main/java/accord/local/RedundantStatus.java
+++ b/accord-core/src/main/java/accord/local/RedundantStatus.java
@@ -24,6 +24,7 @@ import accord.utils.Invariants;
// TODO (desired): is there a better way to represent these states? can we (for instance) collapse WAS_OWNED to a bit flag
// Consider: can we collapse all PARTIALLY_LOCALLY states into simply LOCALLY? Since we know the transaction must be redundant in this case.
+// TODO (required): much better documentation
public enum RedundantStatus
{
/**
@@ -76,7 +77,7 @@ public enum RedundantStatus
/**
* Some of the relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied
- * or invalidated via a sync point that has applied locally, but other ranges may be pre-bootstrap or stale,
+ * or invalidated via a sync point that has applied locally, but these ranges may be pre-bootstrap or stale,
* so that we cannot treat the transaction as having been fully applied locally, and other ranges may still be LIVE
* so that we cannot fully cleanup the transaction.
*
@@ -101,7 +102,11 @@ public enum RedundantStatus
/**
* Some of the relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied
- * or invalidated via a sync point that has applied locally AND on all healthy shards.
+ * or invalidated via a sync point that has applied locally AND remotely, but these ranges may be pre-bootstrap or stale,
+ * so that we cannot treat the transaction as having been fully applied locally, and other ranges may still be LIVE
+ * so that we cannot fully cleanup the transaction.
+ *
+ * Note that this status overrides PRE_BOOTSTRAP_OR_STALE, since it implies the transaction has applied.
*/
PARTIALLY_SHARD_REDUNDANT,
@@ -122,11 +127,17 @@ public enum RedundantStatus
SHARD_REDUNDANT,
/**
- * All of the relevant owned ranges are either shard redundant and pre-bootstrap Or gc-able, meaning any intersecting
- * transaction is known to be applied at a majority of the shard, or invalidated via a sync point that we have
- * applied locally, and that we do not need to know anymore about the command's outcome ourselves and may erase it.
+ * Note: some shards may be SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, others TRUNCATE_BEFORE or GC_BEFORE.
+ *
+ * All of the relevant owned ranges are either shard redundant and pre-bootstrap OR truncatable OR gc-able,
+ * meaning any intersecting transaction is known to be applied at a majority of the shard,
+ * or invalidated via a sync point that we have applied locally.
+ *
+ * We do not need to know anymore about the command's outcome ourselves and may TRUNCATE it.
+ * We cannot ERASE it, because we may yet need the executeAt TIMESTAMP (only) for computing unique HLC
+ * (for implementations where this matters)
*/
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE,
+ TRUNCATE_BEFORE,
/**
* The relevant owned ranges are redundant, meaning any intersecting transaction is known to be either applied or invalidated
@@ -157,7 +168,7 @@ public enum RedundantStatus
NOT_OWNED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
NOT_OWNED.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
NOT_OWNED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- NOT_OWNED.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
+ NOT_OWNED.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
NOT_OWNED.merge.put(GC_BEFORE, GC_BEFORE);
WAS_OWNED.merge = new EnumMap<>(RedundantStatus.class);
WAS_OWNED.merge.put(NOT_OWNED, WAS_OWNED);
@@ -174,7 +185,7 @@ public enum RedundantStatus
WAS_OWNED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ WAS_OWNED.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_CLOSED.merge = new EnumMap<>(RedundantStatus.class);
WAS_OWNED_CLOSED.merge.put(NOT_OWNED, WAS_OWNED_CLOSED);
@@ -191,7 +202,7 @@ public enum RedundantStatus
WAS_OWNED_CLOSED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_CLOSED.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_CLOSED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_CLOSED.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ WAS_OWNED_CLOSED.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_CLOSED.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_PARTIALLY_RETIRED.merge = new EnumMap<>(RedundantStatus.class);
WAS_OWNED_PARTIALLY_RETIRED.merge.put(NOT_OWNED, WAS_OWNED_PARTIALLY_RETIRED);
@@ -208,7 +219,7 @@ public enum RedundantStatus
WAS_OWNED_PARTIALLY_RETIRED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_PARTIALLY_RETIRED.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_PARTIALLY_RETIRED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- WAS_OWNED_PARTIALLY_RETIRED.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ WAS_OWNED_PARTIALLY_RETIRED.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_PARTIALLY_RETIRED.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
WAS_OWNED_RETIRED.merge = new EnumMap<>(RedundantStatus.class);
WAS_OWNED_RETIRED.merge.put(NOT_OWNED, WAS_OWNED_RETIRED);
@@ -225,7 +236,7 @@ public enum RedundantStatus
WAS_OWNED_RETIRED.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
WAS_OWNED_RETIRED.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
WAS_OWNED_RETIRED.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- WAS_OWNED_RETIRED.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
+ WAS_OWNED_RETIRED.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
WAS_OWNED_RETIRED.merge.put(GC_BEFORE, GC_BEFORE);
LIVE.merge = new EnumMap<>(RedundantStatus.class);
LIVE.merge.put(NOT_OWNED, LIVE);
@@ -242,7 +253,7 @@ public enum RedundantStatus
LIVE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
LIVE.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
LIVE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- LIVE.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ LIVE.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
LIVE.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge = new EnumMap<>(RedundantStatus.class);
PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(NOT_OWNED, PARTIALLY_PRE_BOOTSTRAP_OR_STALE);
@@ -259,7 +270,7 @@ public enum RedundantStatus
PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
PRE_BOOTSTRAP_OR_STALE.merge = new EnumMap<>(RedundantStatus.class);
PRE_BOOTSTRAP_OR_STALE.merge.put(NOT_OWNED, PRE_BOOTSTRAP_OR_STALE);
@@ -276,7 +287,7 @@ public enum RedundantStatus
PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PRE_BOOTSTRAP_OR_STALE);
- PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ PRE_BOOTSTRAP_OR_STALE.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_LOCALLY_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
PARTIALLY_LOCALLY_REDUNDANT.merge.put(NOT_OWNED, PARTIALLY_LOCALLY_REDUNDANT);
@@ -294,7 +305,7 @@ public enum RedundantStatus
PARTIALLY_LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_LOCALLY_REDUNDANT.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_LOCALLY_REDUNDANT.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ PARTIALLY_LOCALLY_REDUNDANT.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
LOCALLY_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
LOCALLY_REDUNDANT.merge.put(NOT_OWNED, LOCALLY_REDUNDANT);
LOCALLY_REDUNDANT.merge.put(WAS_OWNED, PARTIALLY_LOCALLY_REDUNDANT);
@@ -310,7 +321,7 @@ public enum RedundantStatus
LOCALLY_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- LOCALLY_REDUNDANT.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
+ LOCALLY_REDUNDANT.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
LOCALLY_REDUNDANT.merge.put(GC_BEFORE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge = new EnumMap<>(RedundantStatus.class);
SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(NOT_OWNED, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
@@ -327,8 +338,8 @@ public enum RedundantStatus
SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
+ SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
+ SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE, TRUNCATE_BEFORE);
PARTIALLY_SHARD_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
PARTIALLY_SHARD_REDUNDANT.merge.put(NOT_OWNED, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_SHARD_REDUNDANT.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
@@ -344,7 +355,7 @@ public enum RedundantStatus
PARTIALLY_SHARD_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_SHARD_REDUNDANT.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_SHARD_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- PARTIALLY_SHARD_REDUNDANT.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ PARTIALLY_SHARD_REDUNDANT.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_SHARD_REDUNDANT.merge.put(GC_BEFORE, PARTIALLY_SHARD_REDUNDANT);
PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(NOT_OWNED, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
@@ -361,7 +372,7 @@ public enum RedundantStatus
PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
+ PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(TRUNCATE_BEFORE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT.merge.put(GC_BEFORE, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
SHARD_REDUNDANT.merge = new EnumMap<>(RedundantStatus.class);
SHARD_REDUNDANT.merge.put(NOT_OWNED, SHARD_REDUNDANT);
@@ -380,25 +391,25 @@ public enum RedundantStatus
SHARD_REDUNDANT.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
SHARD_REDUNDANT.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
SHARD_REDUNDANT.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT);
- SHARD_REDUNDANT.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, SHARD_REDUNDANT);
+ SHARD_REDUNDANT.merge.put(TRUNCATE_BEFORE, SHARD_REDUNDANT);
SHARD_REDUNDANT.merge.put(GC_BEFORE, SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge = new EnumMap<>(RedundantStatus.class);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(NOT_OWNED, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_CLOSED, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(WAS_OWNED_RETIRED, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(LIVE, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE.merge.put(GC_BEFORE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
+ TRUNCATE_BEFORE.merge = new EnumMap<>(RedundantStatus.class);
+ TRUNCATE_BEFORE.merge.put(NOT_OWNED, TRUNCATE_BEFORE);
+ TRUNCATE_BEFORE.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(WAS_OWNED_CLOSED, PARTIALLY_SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(WAS_OWNED_PARTIALLY_RETIRED, PARTIALLY_SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(WAS_OWNED_RETIRED, TRUNCATE_BEFORE);
+ TRUNCATE_BEFORE.merge.put(LIVE, PARTIALLY_SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(PARTIALLY_PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(PRE_BOOTSTRAP_OR_STALE, PARTIALLY_SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(PARTIALLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
+ TRUNCATE_BEFORE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, TRUNCATE_BEFORE);
+ TRUNCATE_BEFORE.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
+ TRUNCATE_BEFORE.merge.put(GC_BEFORE, TRUNCATE_BEFORE);
GC_BEFORE.merge = new EnumMap<>(RedundantStatus.class);
GC_BEFORE.merge.put(NOT_OWNED, GC_BEFORE);
GC_BEFORE.merge.put(WAS_OWNED, PARTIALLY_SHARD_REDUNDANT);
@@ -413,8 +424,8 @@ public enum RedundantStatus
GC_BEFORE.merge.put(PARTIALLY_SHARD_REDUNDANT, PARTIALLY_SHARD_REDUNDANT);
GC_BEFORE.merge.put(PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT, PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT);
GC_BEFORE.merge.put(SHARD_REDUNDANT, SHARD_REDUNDANT);
- GC_BEFORE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
- GC_BEFORE.merge.put(GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE);
+ GC_BEFORE.merge.put(SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE, TRUNCATE_BEFORE);
+ GC_BEFORE.merge.put(TRUNCATE_BEFORE, TRUNCATE_BEFORE);
GC_BEFORE.merge.put(GC_BEFORE, GC_BEFORE);
for (RedundantStatus a : values())
diff --git a/accord-core/src/main/java/accord/local/SafeCommandStore.java b/accord-core/src/main/java/accord/local/SafeCommandStore.java
index 429b0be7..5d672cdb 100644
--- a/accord-core/src/main/java/accord/local/SafeCommandStore.java
+++ b/accord-core/src/main/java/accord/local/SafeCommandStore.java
@@ -210,11 +210,6 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
else throw illegalArgument("%s was not specified in %s", key, context());
}
- public long preAcceptTimeout()
- {
- return agent().preAcceptTimeout();
- }
-
/** Get anything already referenced (should include anything in PreLoadContext). If returned, should be initialised. */
protected abstract SafeCommand getInternal(TxnId txnId);
/** Get if available */
@@ -252,17 +247,17 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
SaveStatus oldSaveStatus = prev == null ? SaveStatus.Uninitialised : prev.saveStatus();
SaveStatus newSaveStatus = updated.saveStatus();
- TxnId txnId = updated.txnId();
if (newSaveStatus.known.isDefinitionKnown() && !oldSaveStatus.known.isDefinitionKnown())
{
Ranges ranges = updated.participants().touches().toRanges();
- commandStore().markExclusiveSyncPoint(this, txnId, ranges);
+ commandStore().markExclusiveSyncPoint(this, updated.txnId(), ranges);
}
if (newSaveStatus == Applied && oldSaveStatus != Applied)
{
Ranges ranges = updated.participants().touches().toRanges();
- commandStore().markExclusiveSyncPointLocallyApplied(this, txnId, ranges);
+ TxnId txnIdWithFlags = (TxnId)updated.executeAt();
+ commandStore().markExclusiveSyncPointLocallyApplied(this, txnIdWithFlags, ranges);
}
}
@@ -388,7 +383,7 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
RoutingKey key = keys.get(i);
TxnId maxTxnId = txnIdsForKey.get(txnIdsForKey.size() - 1);
// TODO (required): convert to O(n) merge
- RedundantStatus status = redundantBefore.status(maxTxnId, key);
+ RedundantStatus status = redundantBefore.status(maxTxnId, null, key);
switch (status)
{
default: throw new UnhandledEnum(status);
@@ -408,7 +403,7 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
case SHARD_REDUNDANT:
- case GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
+ case TRUNCATE_BEFORE:
case GC_BEFORE:
}
}
diff --git a/accord-core/src/main/java/accord/local/StoreParticipants.java b/accord-core/src/main/java/accord/local/StoreParticipants.java
index 7f4e5c6c..b9cf5f0d 100644
--- a/accord-core/src/main/java/accord/local/StoreParticipants.java
+++ b/accord-core/src/main/java/accord/local/StoreParticipants.java
@@ -236,7 +236,7 @@ public class StoreParticipants
/**
* touches, but excluding any stale, pre-bootstrap or retired ranges that are also shard redundant,
- * as we do not need to do anything with these keys locally
+ * as we do not need to do anything with these keys locally.
*/
public Participants<?> stillTouches()
{
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 4fd58bba..5a1876e2 100644
--- a/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
@@ -86,7 +86,9 @@ import static accord.local.cfk.Pruning.prunedBeforeId;
import static accord.local.cfk.UpdateUnmanagedMode.UPDATE;
import static accord.local.cfk.Updating.insertOrUpdate;
import static accord.local.CommandSummaries.ComputeIsDep.IGNORE;
+import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
import static accord.primitives.Routable.Domain.Key;
+import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Timestamp.Flag.UNSTABLE;
import static accord.primitives.Txn.Kind.AnyGloballyVisible;
import static accord.primitives.Txn.Kind.Write;
@@ -222,7 +224,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
private static boolean reportLinearizabilityViolations = true;
- public static final RedundantBefore.Entry NO_BOUNDS_INFO = new RedundantBefore.Entry(null, Long.MIN_VALUE, Long.MAX_VALUE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, null);
+ public static final RedundantBefore.Entry NO_BOUNDS_INFO = new RedundantBefore.Entry(null, 0, Long.MAX_VALUE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, null);
public static final TxnInfo NO_INFO = TxnInfo.create(TxnId.NONE, TRANSITIVE, false, TxnId.NONE, Ballot.ZERO);
public static final TxnInfo[] NO_INFOS = new TxnInfo[0];
public static final Unmanaged[] NO_PENDING_UNMANAGED = new Unmanaged[0];
@@ -289,7 +291,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
{
InternalStatus newStatus = from(updated);
if (newStatus == null)
- return false;
+ return updated.known().is(ApplyAtKnown) && updated.executeAt().hasDistinctHlcAndUniqueHlc();
InternalStatus prevStatus = from(prev);
if (prevStatus != newStatus)
@@ -306,15 +308,15 @@ public class CommandsForKey extends CommandsForKeyUpdate
public static class SerializerSupport
{
- public static CommandsForKey create(RoutingKey key, TxnInfo[] byId, long maxHlc, Unmanaged[] unmanageds, TxnId prunedBefore, RedundantBefore.Entry boundsInfo)
+ public static CommandsForKey create(RoutingKey key, TxnInfo[] byId, long maxUniqueHlc, Unmanaged[] unmanageds, TxnId prunedBefore, RedundantBefore.Entry boundsInfo)
{
- return reconstruct(key, boundsInfo, true, byId, maxHlc, prunedBefore, unmanageds);
+ return reconstruct(key, boundsInfo, true, byId, maxUniqueHlc, prunedBefore, unmanageds);
}
}
interface Updater<O>
{
- O update(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds);
+ O update(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds);
}
/**
@@ -346,6 +348,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
{
super(txnId);
Invariants.checkState(executeAt == txnId || !executeAt.equals(txnId));
+ Invariants.checkArgument((flags() & ~IDENTITY_FLAGS) == 0);
this.encodedStatus = encodedStatus;
this.executeAt = executeAt == txnId ? this : executeAt;
}
@@ -817,7 +820,8 @@ public class CommandsForKey extends CommandsForKeyUpdate
PRENOTACCEPTED_OR_ACCEPTED_INVALIDATE (SummaryStatus.PRENOTACCEPTED_OR_ACCEPTED_INVALIDATE, false, false, true, false),
NOTACCEPTED_WITH_COORDINATOR_DEPS (SummaryStatus.NOTACCEPTED, false, true, true, false),
NOTACCEPTED (SummaryStatus.NOTACCEPTED, false, false, true, false),
- ACCEPTED (SummaryStatus.ACCEPTED, false, true, true, false),
+ // note that while ACCEPTED does not require executeAt for dependencies, it does require executeAt for computing the earlierWait collection for recovery
+ ACCEPTED (SummaryStatus.ACCEPTED, true, true, true, false),
COMMITTED (SummaryStatus.COMMITTED, true, true, true, true),
STABLE (SummaryStatus.STABLE, true, true, false, true),
// TODO (expected): do not encode missing collection for APPLIED transactions,
@@ -826,7 +830,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
// 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_NOT_EXECUTED (APPLIED, true, true, false, true),
+ APPLIED_NOT_EXECUTED /*(reserved)*/ (APPLIED, true, true, false, true),
INVALIDATED (SummaryStatus.INVALIDATED, false,false,false, false),
PRUNED (SummaryStatus.NONE, false,false,false, false)
;
@@ -1000,14 +1004,14 @@ public class CommandsForKey extends CommandsForKeyUpdate
final int prunedBeforeById;
final Unmanaged[] unmanageds;
- final long maxHlc;
+ final long maxUniqueHlc;
- CommandsForKey(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxHlc, Object[] loadingPruned, int prunedBeforeById, Unmanaged[] unmanageds)
+ CommandsForKey(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int prunedBeforeById, Unmanaged[] unmanageds)
{
- this(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxHlc, loadingPruned, prunedBeforeById, unmanageds);
+ this(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, unmanageds);
}
- CommandsForKey(RoutingKey key, RedundantBefore.Entry boundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxHlc, Object[] loadingPruned, int prunedBeforeById, Unmanaged[] unmanageds)
+ CommandsForKey(RoutingKey key, RedundantBefore.Entry boundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int prunedBeforeById, Unmanaged[] unmanageds)
{
this.key = key;
this.boundsInfo = boundsInfo;
@@ -1015,7 +1019,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
this.committedByExecuteAt = committedByExecuteAt;
this.minUndecidedById = minUndecidedById;
this.maxAppliedWriteByExecuteAt = maxAppliedWriteByExecuteAt;
- this.maxHlc = maxHlc;
+ this.maxUniqueHlc = maxUniqueHlc;
this.loadingPruned = loadingPruned;
this.prunedBeforeById = prunedBeforeById;
this.unmanageds = unmanageds;
@@ -1030,7 +1034,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
this.committedByExecuteAt = copy.committedByExecuteAt;
this.minUndecidedById = copy.minUndecidedById;
this.maxAppliedWriteByExecuteAt = copy.maxAppliedWriteByExecuteAt;
- this.maxHlc = copy.maxHlc;
+ this.maxUniqueHlc = copy.maxUniqueHlc;
this.loadingPruned = loadingPruned;
this.prunedBeforeById = copy.prunedBeforeById;
this.unmanageds = unmanageds;
@@ -1038,13 +1042,18 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
public CommandsForKey(RoutingKey key)
+ {
+ this(key, 0);
+ }
+
+ public CommandsForKey(RoutingKey key, long maxUniqueHlc)
{
this.key = key;
this.boundsInfo = NO_BOUNDS_INFO;
this.byId = NO_INFOS;
this.committedByExecuteAt = NO_INFOS;
this.minUndecidedById = this.maxAppliedWriteByExecuteAt = -1;
- this.maxHlc = Long.MIN_VALUE;
+ this.maxUniqueHlc = maxUniqueHlc;
this.loadingPruned = LoadingPruned.empty();
this.prunedBeforeById = -1;
this.unmanageds = NO_PENDING_UNMANAGED;
@@ -1423,7 +1432,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
if (txn.compareTo(maxCommittedWriteForEpoch) < 0
- && txn.executeAt.compareTo(maxCommittedWriteBefore.executeAt) < 0)
+ && txn.executeAt.compareTo(maxCommittedWriteForEpoch.executeAt) < 0)
continue;
}
}
@@ -1468,11 +1477,27 @@ public class CommandsForKey extends CommandsForKeyUpdate
Invariants.checkState(manages(update.txnId()));
InternalStatus newStatus = from(update);
if (newStatus == null)
+ {
+ // handle replay of TruncatedApply with uniqueHlc
+ if (update.known().is(ApplyAtKnown))
+ return updateUniqueHlc(update.executeAt().uniqueHlc());
return this;
+ }
return update(newStatus, update);
}
+ public CommandsForKey updateUniqueHlc(long minUniqueHlc)
+ {
+ if (maxUniqueHlc >= minUniqueHlc)
+ return this;
+
+ if (maxUniqueHlc <= boundsInfo.gcBefore.hlc() && boundsInfo.gcBefore.is(HLC_BOUND))
+ return this;
+
+ return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, minUniqueHlc, loadingPruned, prunedBeforeById, unmanageds);
+ }
+
public CommandsForKey setDurable(TxnId txnId)
{
TxnInfo txn = get(txnId);
@@ -1481,7 +1506,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
txn.setDurableInPlace();
// return the exact same data as we have updated in place, but change detection relies on identity
- return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxHlc, loadingPruned, prunedBeforeById, unmanageds);
+ return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, unmanageds);
}
CommandsForKeyUpdate maybePrunedCallback(Command update)
@@ -1541,7 +1566,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
pos = -1 - pos;
if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, null, newStatus, mayExecute, updated, wasPruned, loadingAsPrunedFor);
else if (newStatus.hasDeps() && !wasPruned) result = insert(pos, txnId, newStatus, mayExecute, updated);
- else result = insert(pos, txnId, TxnInfo.create(txnId, newStatus, mayExecute, updated), wasPruned, loadingAsPrunedFor);
+ else result = insert(pos, txnId, TxnInfo.create(txnId, newStatus, mayExecute, updated), wasPruned, loadingAsPrunedFor, updated);
}
else
{
@@ -1577,7 +1602,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, cur, newStatus, mayExecute, updated, wasPruned, loadingAsPrunedFor);
else if (newStatus.hasDeps() && !wasPruned) result = update(pos, txnId, cur, newStatus, mayExecute, updated);
- else result = update(pos, txnId, cur, TxnInfo.create(txnId, newStatus, mayExecute, updated), wasPruned, loadingAsPrunedFor);
+ else result = update(pos, txnId, cur, TxnInfo.create(txnId, newStatus, mayExecute, updated), wasPruned, loadingAsPrunedFor, updated);
}
return result;
@@ -1593,54 +1618,54 @@ public class CommandsForKey extends CommandsForKeyUpdate
return insertOrUpdate(this, updatePos, updatePos, plainTxnId, curInfo, newStatus, mayExecute, command);
}
- CommandsForKeyUpdate update(int pos, TxnId plainTxnId, TxnInfo curInfo, TxnInfo newInfo, boolean wasPruned, TxnId[] loadingAsPrunedFor)
+ CommandsForKeyUpdate update(int pos, TxnId plainTxnId, TxnInfo curInfo, TxnInfo newInfo, boolean wasPruned, TxnId[] loadingAsPrunedFor, Command command)
{
- return insertOrUpdate(this, pos, plainTxnId, curInfo, newInfo, wasPruned, loadingAsPrunedFor);
+ return insertOrUpdate(this, pos, plainTxnId, curInfo, newInfo, wasPruned, loadingAsPrunedFor, command);
}
/**
* Insert a new txnId and info
*/
- CommandsForKeyUpdate insert(int pos, TxnId plainTxnId, TxnInfo newInfo, boolean wasPruned, TxnId[] loadingAsPrunedFor)
+ CommandsForKeyUpdate insert(int pos, TxnId plainTxnId, TxnInfo newInfo, boolean wasPruned, TxnId[] loadingAsPrunedFor, Command updated)
{
- return insertOrUpdate(this, pos, plainTxnId, null, newInfo, wasPruned, loadingAsPrunedFor);
+ return insertOrUpdate(this, pos, plainTxnId, null, newInfo, wasPruned, loadingAsPrunedFor, updated);
}
- private CommandsForKeyUpdate insertOrUpdateOutOfRange(int updatePos, TxnId plainTxnId, @Nullable TxnInfo curInfo, InternalStatus newStatus, boolean mayExecute, Command update, boolean wasPruned, TxnId[] loadingAsPrunedFor)
+ private CommandsForKeyUpdate insertOrUpdateOutOfRange(int updatePos, TxnId plainTxnId, @Nullable TxnInfo curInfo, InternalStatus newStatus, boolean mayExecute, Command updated, boolean wasPruned, TxnId[] loadingAsPrunedFor)
{
Invariants.checkArgument(!mayExecute);
int statusOverridesXor = newStatus.flags & 1;
TxnInfo newInfo;
- if (curInfo == null) newInfo = TxnInfo.create(plainTxnId, newStatus, false, statusOverridesXor, plainTxnId, update.acceptedOrCommitted());
+ if (curInfo == null) newInfo = TxnInfo.create(plainTxnId, newStatus, false, statusOverridesXor, plainTxnId, updated.acceptedOrCommitted());
else newInfo = curInfo.withEncodedStatus(TxnInfo.encode(plainTxnId, newStatus, false, statusOverridesXor));
// out of range means we have no deps, we're just marking committed, so we set HAS_DEPS to 0
- return insertOrUpdate(this, updatePos, plainTxnId, curInfo, newInfo, wasPruned, loadingAsPrunedFor);
+ return insertOrUpdate(this, updatePos, plainTxnId, curInfo, newInfo, wasPruned, loadingAsPrunedFor, updated);
}
// TODO (required): additional linearizability violation detection, based on expectation of presence in missing set
- CommandsForKeyUpdate update(TxnInfo[] newById, int newMinUndecidedById, TxnInfo[] newCommittedByExecuteAt, int newMaxAppliedWriteByExecuteAt, long maxHlc, Object[] newLoadingPruned, int newPrunedBeforeById, @Nullable TxnInfo curInfo, @Nonnull TxnInfo newInfo)
+ CommandsForKeyUpdate update(TxnInfo[] newById, int newMinUndecidedById, TxnInfo[] newCommittedByExecuteAt, int newMaxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] newLoadingPruned, int newPrunedBeforeById, @Nullable TxnInfo curInfo, @Nonnull TxnInfo newInfo)
{
Invariants.checkState(prunedBeforeById < 0 || newById[newPrunedBeforeById].equals(byId[prunedBeforeById]));
return updateAndNotifyUnmanageds(key, boundsInfo, false,
newById, newCommittedByExecuteAt,
- newMinUndecidedById, newMaxAppliedWriteByExecuteAt, maxHlc,
+ newMinUndecidedById, newMaxAppliedWriteByExecuteAt, maxUniqueHlc,
newLoadingPruned, newPrunedBeforeById, unmanageds, curInfo, newInfo);
}
- static CommandsForKey reconstruct(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, long maxHlc, TxnId prunedBefore, Unmanaged[] unmanageds)
+ static CommandsForKey reconstruct(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, TxnId prunedBefore, Unmanaged[] unmanageds)
{
int prunedBeforeById = Arrays.binarySearch(byId, prunedBefore);
Invariants.checkState(prunedBeforeById >= 0 || prunedBefore.equals(TxnId.NONE));
- return reconstruct(key, boundsInfo, isNewBoundsInfo, byId, maxHlc, BTree.empty(), prunedBeforeById, unmanageds);
+ return reconstruct(key, boundsInfo, isNewBoundsInfo, byId, maxUniqueHlc, BTree.empty(), prunedBeforeById, unmanageds);
}
- static CommandsForKey reconstruct(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, long maxHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
+ static CommandsForKey reconstruct(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
{
- return reconstruct(key, boundsInfo, isNewBoundsInfo, byId, maxHlc, loadingPruned, newPrunedBeforeById, unmanageds, CommandsForKey::new);
+ return reconstruct(key, boundsInfo, isNewBoundsInfo, byId, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, CommandsForKey::new);
}
- static <O> O reconstruct(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, long maxHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, Updater<O> updater)
+ static <O> O reconstruct(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, Updater<O> updater)
{
int countCommitted = 0;
int minUndecidedById = -1;
@@ -1667,28 +1692,28 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (txn.is(Write) && (txn.is(APPLIED) || isPreBootstrap(txn, boundsInfo)))
break;
}
- if (maxAppliedWriteByExecuteAt >= 0)
- maxHlc = Math.max(maxHlc, committedByExecuteAt[maxAppliedWriteByExecuteAt].executeAt.hlc());
+ if (maxAppliedWriteByExecuteAt >= 0) maxUniqueHlc = Math.max(maxUniqueHlc, committedByExecuteAt[maxAppliedWriteByExecuteAt].executeAt.hlc());
+ else maxUniqueHlc = Math.max(maxUniqueHlc, boundsInfo.gcBefore.hlc());
- return updater.update(key, boundsInfo, isNewBoundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxHlc, loadingPruned, newPrunedBeforeById, unmanageds);
+ return updater.update(key, boundsInfo, isNewBoundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds);
}
- static CommandsForKeyUpdate reconstructAndUpdateUnmanaged(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, long maxHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
+ static CommandsForKeyUpdate reconstructAndUpdateUnmanaged(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
{
- return reconstruct(key, boundsInfo, isNewBoundsInfo, byId, maxHlc, loadingPruned, newPrunedBeforeById, unmanageds, CommandsForKey::updateAndNotifyUnmanageds);
+ return reconstruct(key, boundsInfo, isNewBoundsInfo, byId, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, CommandsForKey::updateAndNotifyUnmanageds);
}
- static CommandsForKeyUpdate updateAndNotifyUnmanageds(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
+ static CommandsForKeyUpdate updateAndNotifyUnmanageds(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds)
{
- return updateAndNotifyUnmanageds(key, boundsInfo, isNewBoundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxHlc, loadingPruned, newPrunedBeforeById, unmanageds, null, null);
+ return updateAndNotifyUnmanageds(key, boundsInfo, isNewBoundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds, null, null);
}
- static CommandsForKeyUpdate updateAndNotifyUnmanageds(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, @Nullable TxnInfo curInfo, @Nullable TxnInfo newInfo)
+ static CommandsForKeyUpdate updateAndNotifyUnmanageds(RoutingKey key, RedundantBefore.Entry boundsInfo, boolean isNewBoundsInfo, TxnInfo[] byId, TxnInfo[] committedByExecuteAt, int minUndecidedById, int maxAppliedWriteByExecuteAt, long maxUniqueHlc, Object[] loadingPruned, int newPrunedBeforeById, Unmanaged[] unmanageds, @Nullable TxnInfo curInfo, @Nullable TxnInfo newInfo)
{
NotifyUnmanagedResult notifyUnmanaged = PostProcess.notifyUnmanaged(unmanageds, byId, minUndecidedById, committedByExecuteAt, maxAppliedWriteByExecuteAt, loadingPruned, boundsInfo, isNewBoundsInfo, curInfo, newInfo);
if (notifyUnmanaged != null)
unmanageds = notifyUnmanaged.newUnmanaged;
- CommandsForKey newCfk = new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxHlc, loadingPruned, newPrunedBeforeById, unmanageds);
+ CommandsForKey newCfk = new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, newPrunedBeforeById, unmanageds);
CommandsForKeyUpdate result = newCfk;
if (notifyUnmanaged != null)
result = new CommandsForKeyUpdateWithPostProcess(newCfk, notifyUnmanaged.postProcess);
@@ -1699,12 +1724,12 @@ public class CommandsForKey extends CommandsForKeyUpdate
CommandsForKey update(Unmanaged[] newUnmanageds)
{
- return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxHlc, loadingPruned, prunedBeforeById, newUnmanageds);
+ return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxUniqueHlc, loadingPruned, prunedBeforeById, newUnmanageds);
}
CommandsForKey update(Object[] newLoadingPruned)
{
- return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxHlc, newLoadingPruned, prunedBeforeById, unmanageds);
+ return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxUniqueHlc, newLoadingPruned, prunedBeforeById, unmanageds);
}
CommandsForKeyUpdate registerUnmanaged(SafeCommand safeCommand, UpdateUnmanagedMode mode)
@@ -1713,19 +1738,19 @@ public class CommandsForKey extends CommandsForKeyUpdate
return Updating.updateUnmanaged(this, safeCommand, mode, null);
}
- void postProcess(SafeCommandStore safeStore, CommandsForKey prevCfk, @Nullable Command command, NotifySink notifySink)
+ void postProcess(SafeCommandStore safeStore, CommandsForKey prevCfk, @Nullable Command updated, NotifySink notifySink)
{
TxnInfo minUndecided = minUndecided();
if (minUndecided != null && !minUndecided.equals(prevCfk.minUndecided()))
notifySink.waitingOn(safeStore, minUndecided, key, SaveStatus.Stable, HasStableDeps, true);
- if (command == null)
+ if (updated == null)
{
notifyManaged(safeStore, AnyGloballyVisible, 0, committedByExecuteAt.length, -1, notifySink);
return;
}
- if (!command.hasBeen(Status.Committed))
+ if (!updated.hasBeen(Status.Committed))
return;
/*
@@ -1742,7 +1767,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
* we do not set next or nextWrite, and so do not notify them
*/
- TxnId updatedTxnId = command.txnId();
+ TxnId updatedTxnId = updated.txnId();
TxnInfo newInfo = get(updatedTxnId);
if (newInfo == null)
return;
@@ -1755,7 +1780,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
// We have a read or write that has been made stable before our latest write.
// This is either a linearizability violation, or it is pre-bootstrap.
checkBehindCommitForLinearizabilityViolation(newInfo, maxAppliedWrite);
- notifySink.notWaiting(safeStore, updatedTxnId, key);
+ notifySink.notWaiting(safeStore, updatedTxnId, key, 0);
return;
}
}
@@ -1865,7 +1890,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
if (expectMissingCount == missingCount)
{
TxnId txnId = txn.plainTxnId();
- notifySink.notWaiting(safeStore, txnId, key);
+ notifySink.notWaiting(safeStore, txnId, key, txnId.is(Write) ? maxUniqueHlc + 1 : 0);
// TODO (required): avoid invoking this here; we may do redundant work if we have local dependencies we're already waiting on
notifySink.waitingOn(safeStore, txn, key, SaveStatus.PreApplied, CanApply, false);
txn.setNotifiedReadyInPlace();
@@ -1927,7 +1952,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
public CommandsForKeyUpdate withRedundantBeforeAtLeast(RedundantBefore.Entry newBoundsInfo)
{
- // we can't let HLC epoch go backwards as this breaks assumptions around maxHlc tracking
+ // we can't let HLC epoch go backwards as this breaks assumptions around maxUniqueHlc tracking
if (newBoundsInfo.gcBefore.hlc() < boundsInfo.gcBefore.hlc())
{
if (newBoundsInfo.endOwnershipEpoch != boundsInfo.endOwnershipEpoch || !newBoundsInfo.bootstrappedAt.equals(boundsInfo.bootstrappedAt))
@@ -1948,7 +1973,6 @@ public class CommandsForKey extends CommandsForKeyUpdate
return this;
}
- long maxHlc = Math.max(this.maxHlc, newBoundsInfo.gcBefore.hlc());
if (newBoundsInfo.gcBefore.epoch() >= newBoundsInfo.endOwnershipEpoch)
{
// we should be completely finished; notify every unmanaged and return an empty CFK
@@ -1958,7 +1982,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, newBoundsInfo, NO_INFOS, NO_INFOS, -1, -1, maxHlc, BTree.empty(), -1, NO_PENDING_UNMANAGED);
+ CommandsForKey newCfk = new CommandsForKey(key, newBoundsInfo, NO_INFOS, NO_INFOS, -1, -1, maxUniqueHlc, BTree.empty(), -1, NO_PENDING_UNMANAGED);
return new CommandsForKeyUpdateWithPostProcess(newCfk, newPostProcess);
}
@@ -1966,7 +1990,11 @@ public class CommandsForKey extends CommandsForKeyUpdate
int newPrunedBeforeById = prunedBeforeId(newById, prunedBefore(), redundantBefore(newBoundsInfo));
Object[] newLoadingPruned = Pruning.removeRedundantLoadingPruned(loadingPruned, redundantBefore(newBoundsInfo));
- return notifyManagedPreBootstrap(this, newBoundsInfo, reconstructAndUpdateUnmanaged(key, newBoundsInfo, true, newById, maxHlc, newLoadingPruned, newPrunedBeforeById, unmanageds));
+ long maxUniqueHlc = this.maxUniqueHlc;
+ if (maxUniqueHlc <= newBoundsInfo.gcBefore.hlc() && newBoundsInfo.gcBefore.is(HLC_BOUND))
+ maxUniqueHlc = 0;
+
+ return notifyManagedPreBootstrap(this, newBoundsInfo, reconstructAndUpdateUnmanaged(key, newBoundsInfo, true, newById, maxUniqueHlc, newLoadingPruned, newPrunedBeforeById, unmanageds));
}
/**
@@ -1983,7 +2011,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
int newPrunedBeforeById = prunedBeforeId(newById, prunedBefore(), newRedundantBefore);
Object[] newLoadingPruned = Pruning.removeRedundantLoadingPruned(loadingPruned, newRedundantBefore);
- return reconstruct(key, newBoundsInfo, true, newById, maxHlc, newLoadingPruned, newPrunedBeforeById, unmanageds);
+ return reconstruct(key, newBoundsInfo, true, newById, maxUniqueHlc, newLoadingPruned, newPrunedBeforeById, unmanageds);
}
/**
@@ -2021,7 +2049,8 @@ public class CommandsForKey extends CommandsForKeyUpdate
CommandsForKey that = (CommandsForKey) o;
return Objects.equals(key, that.key)
&& Arrays.equals(byId, that.byId)
- && Arrays.equals(unmanageds, that.unmanageds);
+ && Arrays.equals(unmanageds, that.unmanageds)
+ && maxUniqueHlc == that.maxUniqueHlc;
}
@Override
@@ -2057,19 +2086,6 @@ public class CommandsForKey extends CommandsForKeyUpdate
return maxAppliedWriteByExecuteAt < 0 ? NO_INFO : committedByExecuteAt[maxAppliedWriteByExecuteAt];
}
- public long uniqueHlc(SafeCommandStore safeStore, TxnId txnId, Timestamp executeAt)
- {
- int i = maxAppliedWriteByExecuteAt;
- while (++i < committedByExecuteAt.length)
- {
- if (!committedByExecuteAt[i].is(Write)) continue;
- if (!committedByExecuteAt[i].executeAt.equals(executeAt))
- safeStore.agent().onViolation("Computing HLC value for a write that does not execute next; " + committedByExecuteAt[i] + " vs " + txnId + ":" + executeAt);
- break;
- }
- return Math.max(maxHlc + 1, executeAt.hlc());
- }
-
static int maxContiguousManagedAppliedIndex(TxnInfo[] committedByExecuteAt, int maxAppliedWriteByExecuteAt, TxnId bootstrappedAt)
{
int i = maxAppliedWriteByExecuteAt + 1;
@@ -2132,7 +2148,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
Invariants.checkState(byId.length == 0 || byId[0].compareTo(redundantBefore()) >= 0);
Invariants.checkState(prunedBeforeById == -1 || (prunedBefore().is(APPLIED) && prunedBefore().is(Write)));
Invariants.checkState(minUndecidedById < 0 || (byId[minUndecidedById].status().compareTo(InternalStatus.COMMITTED) < 0 && mayExecute(byId[minUndecidedById])));
- Invariants.checkState(maxHlc >= Math.max(redundantBefore().hlc(), maxAppliedWrite() == null ? 0 : maxAppliedWrite().executeAt.hlc()));
+ Invariants.checkState(maxAppliedWrite() == null || maxUniqueHlc >= maxAppliedWrite().executeAt.hlc());
if (maxAppliedWriteByExecuteAt >= 0)
{
@@ -2271,7 +2287,16 @@ public class CommandsForKey extends CommandsForKeyUpdate
public boolean isEmpty()
{
- return byId.length == 0 && unmanageds.length == 0;
+ return byId.length == 0 && unmanageds.length == 0 && !hasMaxUniqueHlc();
+ }
+
+ public boolean hasMaxUniqueHlc()
+ {
+ TxnInfo maxWrite = maxAppliedWrite();
+ if (maxWrite != null && maxWrite.hlc() >= maxUniqueHlc)
+ return false;
+ TxnId gcBefore = redundantBefore();
+ return gcBefore.hlc() < maxUniqueHlc || !gcBefore.is(HLC_BOUND);
}
public static boolean reportLinearizabilityViolations()
diff --git a/accord-core/src/main/java/accord/local/cfk/NotifySink.java b/accord-core/src/main/java/accord/local/cfk/NotifySink.java
index 35090c6e..f92a32c6 100644
--- a/accord-core/src/main/java/accord/local/cfk/NotifySink.java
+++ b/accord-core/src/main/java/accord/local/cfk/NotifySink.java
@@ -38,7 +38,7 @@ import static accord.primitives.Status.Truncated;
interface NotifySink
{
- void notWaiting(SafeCommandStore safeStore, TxnId txnId, RoutingKey key);
+ void notWaiting(SafeCommandStore safeStore, TxnId txnId, RoutingKey key, long uniqueHlc);
void waitingOn(SafeCommandStore safeStore, TxnInfo txn, RoutingKey key, SaveStatus waitingOnStatus, BlockedUntil blockedUntil, boolean notifyCfk);
@@ -47,21 +47,21 @@ interface NotifySink
static final DefaultNotifySink INSTANCE = new DefaultNotifySink();
@Override
- public void notWaiting(SafeCommandStore safeStore, TxnId txnId, RoutingKey key)
+ public void notWaiting(SafeCommandStore safeStore, TxnId txnId, RoutingKey key, long uniqueHlc)
{
SafeCommand safeCommand = safeStore.ifLoadedAndInitialised(txnId);
- if (safeCommand != null) notWaiting(safeStore, safeCommand, key);
+ if (safeCommand != null) notWaiting(safeStore, safeCommand, key, uniqueHlc);
else
{
PreLoadContext context = PreLoadContext.contextFor(txnId);
- safeStore.commandStore().execute(context, safeStore0 -> notWaiting(safeStore0, safeStore0.unsafeGet(txnId), key))
+ safeStore.commandStore().execute(context, safeStore0 -> notWaiting(safeStore0, safeStore0.unsafeGet(txnId), key, uniqueHlc))
.begin(safeStore.agent());
}
}
- private void notWaiting(SafeCommandStore safeStore, SafeCommand safeCommand, RoutingKey key)
+ private void notWaiting(SafeCommandStore safeStore, SafeCommand safeCommand, RoutingKey key, long uniqueHlc)
{
- Commands.removeWaitingOnKeyAndMaybeExecute(safeStore, safeCommand, key);
+ Commands.removeWaitingOnKeyAndMaybeExecute(safeStore, safeCommand, key, uniqueHlc);
}
@Override
diff --git a/accord-core/src/main/java/accord/local/cfk/PostProcess.java b/accord-core/src/main/java/accord/local/cfk/PostProcess.java
index 2fc85a07..ee694bd7 100644
--- a/accord-core/src/main/java/accord/local/cfk/PostProcess.java
+++ b/accord-core/src/main/java/accord/local/cfk/PostProcess.java
@@ -135,7 +135,7 @@ abstract class PostProcess
void doNotify(SafeCommandStore safeStore, RoutingKey key, NotifySink notifySink)
{
for (TxnId txnId : notify)
- notifySink.notWaiting(safeStore, txnId, key);
+ notifySink.notWaiting(safeStore, txnId, key, 0);
}
}
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 006bd6a5..6f5d9e38 100644
--- a/accord-core/src/main/java/accord/local/cfk/Pruning.java
+++ b/accord-core/src/main/java/accord/local/cfk/Pruning.java
@@ -244,7 +244,7 @@ public class Pruning
}
int newPrunedBeforeId = cfk.prunedBeforeById - prunedCount;
return new CommandsForKey(cfk.key, cfk.boundsInfo, false, newById, cfk.committedByExecuteAt,
- nextUndecided(newById, 0, cfk), cfk.maxAppliedWriteByExecuteAt, cfk.maxHlc,
+ nextUndecided(newById, 0, cfk), cfk.maxAppliedWriteByExecuteAt, cfk.maxUniqueHlc,
cfk.loadingPruned, newPrunedBeforeId, cfk.unmanageds);
}
int pos = cfk.insertPos(pruneBefore);
@@ -459,7 +459,7 @@ public class Pruning
cachedAny().forceDiscard(removedExecuteAts, removedExecuteAtCount);
int newMaxAppliedWriteByExecuteAt = cfk.maxAppliedWriteByExecuteAt - removedCommittedCount;
Invariants.checkState(newById[retainCount] == newPrunedBefore);
- return new CommandsForKey(cfk.key, cfk.boundsInfo, newById, newCommittedByExecuteAt, minUndecidedById, newMaxAppliedWriteByExecuteAt, cfk.maxHlc, cfk.loadingPruned, retainCount, cfk.unmanageds);
+ return new CommandsForKey(cfk.key, cfk.boundsInfo, newById, newCommittedByExecuteAt, minUndecidedById, newMaxAppliedWriteByExecuteAt, cfk.maxUniqueHlc, cfk.loadingPruned, retainCount, cfk.unmanageds);
}
/**
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 d0914d47..0072f9f5 100644
--- a/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
@@ -58,6 +58,12 @@ public abstract class SafeCommandsForKey implements SafeState<CommandsForKey>
update(safeStore, nextCommand, prevCfk, prevCfk.update(nextCommand));
}
+ public void updateUniqueHlc(SafeCommandStore safeStore, long uniqueHlc)
+ {
+ CommandsForKey prevCfk = current();
+ update(safeStore, null, prevCfk, prevCfk.updateUniqueHlc(uniqueHlc));
+ }
+
// equivalent to update, but for async callbacks with additional validation around pruning
public void callback(SafeCommandStore safeStore, Command nextCommand)
{
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 9e210bed..271f8290 100644
--- a/accord-core/src/main/java/accord/local/cfk/Serialize.java
+++ b/accord-core/src/main/java/accord/local/cfk/Serialize.java
@@ -142,7 +142,18 @@ public class Serialize
int commandCount = cfk.size();
if (commandCount == 0)
- return ByteBuffer.allocate(1);
+ {
+ if (!cfk.hasMaxUniqueHlc())
+ return ByteBuffer.allocate(1);
+
+ int size = 1 + VIntCoding.sizeOfUnsignedVInt(cfk.maxUniqueHlc);
+ ByteBuffer result = ByteBuffer.allocate(size);
+ VIntCoding.writeUnsignedVInt32(1, result);
+ VIntCoding.writeUnsignedVInt(cfk.maxUniqueHlc, result);
+ Invariants.checkState(!result.hasRemaining());
+ result.flip();
+ return result;
+ }
int[] nodeIds = cachedInts().getInts(Math.min(64, Math.max(4, commandCount)));
try
@@ -297,7 +308,7 @@ public class Serialize
| (overrideCount > 0 ? HAS_STATUS_OVERRIDES_HEADER_BIT : 0)
| (cfk.bootstrappedAt() != null ? HAS_BOOTSTRAPPED_AT_HEADER_BIT : 0)
| (hasBoundsFlags(cfk) ? HAS_BOUNDS_FLAGS_HEADER_BIT : 0)
- | (hasMaxHlc(cfk) ? HAS_MAX_HLC_HEADER_BIT : 0)
+ | (cfk.hasMaxUniqueHlc() ? HAS_MAX_HLC_HEADER_BIT : 0)
;
int headerBytes = (maxHeaderBits+7)/8;
@@ -326,7 +337,7 @@ public class Serialize
totalBytes += bytesHistogram[minBasicBytes] * (headerBytes + getHlcBytes(hlcBytesLookup, getHlcFlag(hlcFlagLookup, minBasicBytes - headerBytes)));
for (int i = minBasicBytes + 1 ; i <= maxBasicBytes ; ++i)
totalBytes += (bytesHistogram[i] - bytesHistogram[i-1]) * (headerBytes + getHlcBytes(hlcBytesLookup, getHlcFlag(hlcFlagLookup, i - headerBytes)));
- totalBytes += sizeOfUnsignedVInt(commandCount);
+ totalBytes += sizeOfUnsignedVInt(commandCount + 1);
totalBytes += sizeOfUnsignedVInt(nodeIdCount);
totalBytes += sizeOfUnsignedVInt(nodeIds[0]);
for (int i = 1 ; i < nodeIdCount ; ++i)
@@ -362,7 +373,7 @@ public class Serialize
totalBytes += sizeOfUnsignedVInt(Arrays.binarySearch(nodeIds, 0, nodeIdCount, bootstrappedAt.node.id));
}
if (0 != (globalFlags & HAS_MAX_HLC_HEADER_BIT))
- totalBytes += sizeOfUnsignedVInt(cfk.maxHlc - prevHlc);
+ totalBytes += sizeOfVInt(cfk.maxUniqueHlc - prevHlc);
}
totalBytes += sizeOfUnsignedVInt(prunedBeforeIndex + 1);
@@ -425,7 +436,7 @@ public class Serialize
totalBytes += sizeOfUnsignedVInt(cfk.unmanagedCount() - unmanagedPendingCommitCount);
ByteBuffer out = ByteBuffer.allocate(totalBytes);
- VIntCoding.writeUnsignedVInt32(commandCount, out);
+ VIntCoding.writeUnsignedVInt32(commandCount + 1, out);
VIntCoding.writeUnsignedVInt32(nodeIdCount, out);
VIntCoding.writeUnsignedVInt32(nodeIds[0], out);
for (int i = 1 ; i < nodeIdCount ; ++i) // TODO (desired): can encode more efficiently as a stream of N bit integers
@@ -455,7 +466,7 @@ public class Serialize
VIntCoding.writeUnsignedVInt(Arrays.binarySearch(nodeIds, 0, nodeIdCount, bootstrappedAt.node.id), out);
}
if (0 != (globalFlags & HAS_MAX_HLC_HEADER_BIT))
- VIntCoding.writeUnsignedVInt(cfk.maxHlc - prevHlc, out);
+ VIntCoding.writeVInt(cfk.maxUniqueHlc - prevHlc, out);
}
VIntCoding.writeUnsignedVInt32(prunedBeforeIndex + 1, out);
@@ -698,9 +709,15 @@ public class Serialize
return null;
in = in.duplicate();
- int commandCount = VIntCoding.readUnsignedVInt32(in);
- if (commandCount == 0)
- return new CommandsForKey(key);
+ int commandCount = VIntCoding.readUnsignedVInt32(in) - 1;
+ if (commandCount <= 0)
+ {
+ if (commandCount == -1)
+ return new CommandsForKey(key);
+
+ long maxUniqueHlc = VIntCoding.readUnsignedVInt(in);
+ return new CommandsForKey(key).updateUniqueHlc(maxUniqueHlc);
+ }
TxnId[] txnIds = cachedTxnIds().get(commandCount);
int[] commandFlags = cachedInts().getInts(commandCount);
@@ -726,7 +743,7 @@ public class Serialize
}
RedundantBefore.Entry boundsInfo;
- long prevEpoch, prevHlc, maxHlc;
+ long prevEpoch, prevHlc, maxUniqueHlc = 0;
{
long startEpoch, endEpoch;
{
@@ -753,9 +770,8 @@ public class Serialize
Node.Id node = nodeIds[VIntCoding.readUnsignedVInt32(in)];
boundsInfo = boundsInfo.withBootstrappedAtLeast(TxnId.fromValues(epoch, hlc, flags, node));
}
- maxHlc = boundsInfo.gcBefore.hlc();
if (0 != (globalFlags & HAS_MAX_HLC_HEADER_BIT))
- maxHlc += VIntCoding.readUnsignedVInt(in);
+ maxUniqueHlc = boundsInfo.gcBefore.hlc() + VIntCoding.readVInt(in);
}
int prunedBeforeIndex = VIntCoding.readUnsignedVInt32(in) - 1;
@@ -1013,7 +1029,7 @@ public class Serialize
}
cachedTxnIds().forceDiscard(txnIds, commandCount);
- return CommandsForKey.SerializerSupport.create(key, txns, maxHlc, unmanageds, prunedBeforeIndex == -1 ? TxnId.NONE : txns[prunedBeforeIndex], boundsInfo);
+ return CommandsForKey.SerializerSupport.create(key, txns, maxUniqueHlc, unmanageds, prunedBeforeIndex == -1 ? TxnId.NONE : txns[prunedBeforeIndex], boundsInfo);
}
private static TxnInfo create(RedundantBefore.Entry boundsInfo, @Nonnull TxnId txnId, InternalStatus status, int statusOverrides, @Nonnull Timestamp executeAt, @Nonnull TxnId[] missing, @Nonnull Ballot ballot)
@@ -1055,13 +1071,6 @@ public class Serialize
private static final int RX_FLAGS = new TxnId(0, 0, MEDIUM_PATH_TRACK_STABLE.bits, ExclusiveSyncPoint, Domain.Range, Node.Id.NONE).flags();
- private static boolean hasMaxHlc(CommandsForKey cfk)
- {
- long maxHlc = cfk.maxHlc;
- TxnInfo maxWrite = cfk.maxAppliedWrite();
- return cfk.redundantBefore().hlc() < maxHlc && (maxWrite == null || maxWrite.hlc() < maxHlc);
- }
-
private static int hlcBytesLookupToHlcFlagLookup(int bytesLookup)
{
int flagsLookup = 0;
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 90396169..4dcc1365 100644
--- a/accord-core/src/main/java/accord/local/cfk/Updating.java
+++ b/accord-core/src/main/java/accord/local/cfk/Updating.java
@@ -66,6 +66,7 @@ import static accord.local.cfk.UpdateUnmanagedMode.UPDATE;
import static accord.local.cfk.Utils.insertMissing;
import static accord.local.cfk.Utils.mergeAndFilterMissing;
import static accord.local.cfk.Utils.missingTo;
+import static accord.local.cfk.Utils.removeNonIdentityFlags;
import static accord.local.cfk.Utils.removeOneMissing;
import static accord.local.cfk.Utils.removePrunedAdditions;
import static accord.local.cfk.Utils.removeUnmanaged;
@@ -114,7 +115,7 @@ class Updating
// TODO (expected): do not calculate any deps or additions if we're transitioning from Stable to Applied; wasted effort and might trigger LoadPruned
Object newInfoObj = computeInfoAndAdditions(cfk, insertPos, updatePos, plainTxnId, newStatus, mayExecute, command);
if (newInfoObj.getClass() != InfoWithAdditions.class)
- return insertOrUpdate(cfk, insertPos, plainTxnId, curInfo, (TxnInfo)newInfoObj, false, null);
+ return insertOrUpdate(cfk, insertPos, plainTxnId, curInfo, (TxnInfo)newInfoObj, false, null, command);
InfoWithAdditions newInfoWithAdditions = (InfoWithAdditions) newInfoObj;
TxnId[] additions = newInfoWithAdditions.additions;
@@ -135,6 +136,7 @@ class Updating
prunedIds = insertLoadPruned.isEmpty() ? NO_TXNIDS : insertLoadPruned.toArray(TxnId[]::new);
}
}
+ removeNonIdentityFlags(additions, additionCount);
int committedByExecuteAtUpdatePos = committedByExecuteAtUpdatePos(cfk.committedByExecuteAt, curInfo, newInfo);
TxnInfo[] newCommittedByExecuteAt = updateCommittedByExecuteAt(cfk, committedByExecuteAtUpdatePos, newInfo, false);
@@ -193,7 +195,7 @@ class Updating
if (curInfo == null && insertPos <= cfk.prunedBeforeById)
++newPrunedBeforeById;
- long newMaxHlc = updateMaxHlc(cfk, newInfo);
+ long newMaxHlc = updateMaxUniqueHlc(cfk, newInfo, command);
return LoadPruned.load(prunedIds, cfk.update(newById, newMinUndecidedById, newCommittedByExecuteAt, newMaxAppliedWriteByExecuteAt, newMaxHlc, newLoadingPruned, newPrunedBeforeById, curInfo, newInfo));
}
@@ -229,8 +231,9 @@ class Updating
if (depsKnownBefore != plainTxnId)
{
depsKnownBeforePos = Arrays.binarySearch(byId, insertPos, byId.length, depsKnownBefore);
- Invariants.checkState(depsKnownBeforePos < 0);
- depsKnownBeforePos = -1 - depsKnownBeforePos;
+ // depsKnownBeforePos can be positive if we have a uniqueHlc but agreed the TxnId as the executeAt
+ if (depsKnownBeforePos < 0)
+ depsKnownBeforePos = -1 - depsKnownBeforePos;
}
int txnIdsIndex = 0;
@@ -323,7 +326,7 @@ class Updating
return new InfoWithAdditions(info, additions, additionCount);
}
- static CommandsForKeyUpdate insertOrUpdate(CommandsForKey cfk, int pos, TxnId plainTxnId, TxnInfo curInfo, TxnInfo newInfo, boolean wasPruned, @Nullable TxnId[] loadingAsPrunedFor)
+ static CommandsForKeyUpdate insertOrUpdate(CommandsForKey cfk, int pos, TxnId plainTxnId, TxnInfo curInfo, TxnInfo newInfo, boolean wasPruned, @Nullable TxnId[] loadingAsPrunedFor, Command command)
{
if (curInfo == newInfo)
return cfk;
@@ -391,7 +394,7 @@ class Updating
if (curInfo == null && pos <= cfk.prunedBeforeById)
++newPrunedBeforeById;
- long newMaxHlc = updateMaxHlc(cfk, newInfo);
+ long newMaxHlc = updateMaxUniqueHlc(cfk, newInfo, command);
return cfk.update(newById, newMinUndecidedById, newCommittedByExecuteAt, newMaxAppliedWriteByExecuteAt, newMaxHlc, newLoadingPruned, newPrunedBeforeById, curInfo, newInfo);
}
@@ -730,24 +733,16 @@ class Updating
}
}
- private static long updateMaxHlc(CommandsForKey cfk, TxnInfo newInfo)
+ private static long updateMaxUniqueHlc(CommandsForKey cfk, TxnInfo newInfo, Command update)
{
- long maxHlc = cfk.maxHlc;
+ long maxUniqueHlc = cfk.maxUniqueHlc;
if (newInfo.is(APPLIED) && newInfo.is(Write))
{
- long newHlc = newInfo.executeAt.hlc();
- if (maxHlc < newHlc)
- {
- maxHlc = newHlc;
- }
- else
- {
- TxnInfo prevApplied = cfk.maxAppliedWrite();
- if (prevApplied == null || !prevApplied.equals(newInfo))
- ++maxHlc;
- }
+ long newUniqueHlc = update.executeAt().uniqueHlc();
+ if (maxUniqueHlc < newUniqueHlc)
+ maxUniqueHlc = newUniqueHlc;
}
- return maxHlc;
+ return maxUniqueHlc;
}
static void updateUnmanagedAsync(CommandStore commandStore, TxnId txnId, RoutingKey key, NotifySink notifySink)
@@ -969,6 +964,7 @@ class Updating
{
missingCount -= prunedIndex;
System.arraycopy(missing, prunedIndex, missing, 0, missingCount);
+ removeNonIdentityFlags(missing, missingCount);
int minUndecidedMissingIndex = 0;
while (minUndecidedMissingIndex < missingCount && !cfk.mayExecute(missing[minUndecidedMissingIndex]))
++minUndecidedMissingIndex;
@@ -1005,7 +1001,7 @@ class Updating
{
int prunedBeforeById = cfk.prunedBeforeById;
Invariants.checkState(prunedBeforeById < 0 || newById[prunedBeforeById].equals(cfk.prunedBefore()));
- newCfk = new CommandsForKey(cfk.key(), cfk.boundsInfo, newById, newCommittedByExecuteAt, newMinUndecidedById, cfk.maxAppliedWriteByExecuteAt, cfk.maxHlc, newLoadingPruned, prunedBeforeById, newUnmanaged);
+ newCfk = new CommandsForKey(cfk.key(), cfk.boundsInfo, newById, newCommittedByExecuteAt, newMinUndecidedById, cfk.maxAppliedWriteByExecuteAt, cfk.maxUniqueHlc, newLoadingPruned, prunedBeforeById, newUnmanaged);
}
CommandsForKeyUpdate result = newCfk;
@@ -1037,6 +1033,8 @@ class Updating
if (effectiveExecutesAt != null && effectiveExecutesAt.compareTo(command.waitingOn.executeAtLeast(txnId)) > 0)
{
Command.WaitingOn.Update waitingOn = new Command.WaitingOn.Update(command.waitingOn);
+ if (effectiveExecutesAt instanceof TxnInfo)
+ effectiveExecutesAt = ((TxnInfo) effectiveExecutesAt).plainExecuteAt();
waitingOn.updateExecuteAtLeast(txnId, effectiveExecutesAt);
safeCommand.updateWaitingOn(waitingOn);
}
diff --git a/accord-core/src/main/java/accord/local/cfk/Utils.java b/accord-core/src/main/java/accord/local/cfk/Utils.java
index 6a18a4f8..d895106c 100644
--- a/accord-core/src/main/java/accord/local/cfk/Utils.java
+++ b/accord-core/src/main/java/accord/local/cfk/Utils.java
@@ -284,6 +284,17 @@ class Utils
return result;
}
+ static void removeNonIdentityFlags(TxnId[] ids, int count)
+ {
+ while (--count >= 0)
+ {
+ TxnId cur = ids[count];
+ TxnId upd = cur.withoutNonIdentityFlags();
+ if (upd != cur)
+ ids[count] = upd;
+ }
+ }
+
/**
* If a {@code missing} contains {@code removeTxnId}, return a new array without it (or NO_TXNIDS if the only entry)
*/
diff --git a/accord-core/src/main/java/accord/messages/Accept.java b/accord-core/src/main/java/accord/messages/Accept.java
index a4dcab3c..064c9128 100644
--- a/accord-core/src/main/java/accord/messages/Accept.java
+++ b/accord-core/src/main/java/accord/messages/Accept.java
@@ -94,7 +94,8 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
{
StoreParticipants participants = StoreParticipants.update(safeStore, scope, minEpoch, txnId, txnId.epoch(), executeAt.epoch());
SafeCommand safeCommand = safeStore.get(txnId, participants);
- switch (Commands.accept(safeStore, safeCommand, participants, txnId, kind, ballot, scope, executeAt, partialDeps))
+ AcceptOutcome outcome = Commands.accept(safeStore, safeCommand, participants, txnId, kind, ballot, scope, executeAt, partialDeps);
+ switch (outcome)
{
default: throw new IllegalStateException();
case Redundant:
diff --git a/accord-core/src/main/java/accord/messages/Apply.java b/accord-core/src/main/java/accord/messages/Apply.java
index 760d9444..ab881782 100644
--- a/accord-core/src/main/java/accord/messages/Apply.java
+++ b/accord-core/src/main/java/accord/messages/Apply.java
@@ -194,7 +194,8 @@ public class Apply extends TxnRequest<ApplyReply>
@Override
public KeyHistory keyHistory()
{
- return KeyHistory.ASYNC;
+ // TODO (expected): need to guarantee execution order then can make this ASYNC
+ return KeyHistory.SYNC;
}
@Override
diff --git a/accord-core/src/main/java/accord/messages/BeginInvalidation.java b/accord-core/src/main/java/accord/messages/BeginInvalidation.java
index 41857ecb..65b84a1c 100644
--- a/accord-core/src/main/java/accord/messages/BeginInvalidation.java
+++ b/accord-core/src/main/java/accord/messages/BeginInvalidation.java
@@ -66,22 +66,21 @@ public class BeginInvalidation extends AbstractRequest<BeginInvalidation.Invalid
StoreParticipants participants = StoreParticipants.notAccept(safeStore, this.participants, txnId);
SafeCommand safeCommand = safeStore.get(txnId, participants);
Command command = safeCommand.current();
- boolean acceptedFastPath;
Ballot supersededBy;
Participants<?> truncated;
if (command.is(Status.Truncated))
{
- acceptedFastPath = false;
supersededBy = null;
truncated = participants.owns();
}
else
{
boolean promised = Commands.preacceptInvalidate(safeCommand, ballot);
- acceptedFastPath = command.executeAt() != null && command.executeAt().equals(command.txnId());
supersededBy = promised ? null : safeCommand.current().promised();
truncated = null;
}
+
+ boolean acceptedFastPath = BeginRecovery.acceptsFastPath(txnId, participants, command.saveStatus(), command.executeAt());
return new InvalidateReply(supersededBy, command.acceptedOrCommitted(), command.saveStatus(), acceptedFastPath, command.route(), command.homeKey(), truncated);
}
diff --git a/accord-core/src/main/java/accord/messages/BeginRecovery.java b/accord-core/src/main/java/accord/messages/BeginRecovery.java
index ed4eae81..94cfa910 100644
--- a/accord-core/src/main/java/accord/messages/BeginRecovery.java
+++ b/accord-core/src/main/java/accord/messages/BeginRecovery.java
@@ -63,6 +63,8 @@ import static accord.primitives.Known.KnownDeps.DepsUnknown;
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.TxnId.FastPath.PRIVILEGED_COORDINATOR_WITH_DEPS;
import static accord.primitives.TxnId.MediumPath.MEDIUM_PATH_WAIT_ON_RECOVERY;
import static accord.utils.Invariants.illegalState;
@@ -182,6 +184,33 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
if (c < 0)
{
+ if (testTxnId.is(ExclusiveSyncPoint) && testTxnId.hlc() > txnId.hlc())
+ {
+ switch (status)
+ {
+ default: throw new UnhandledEnum(status);
+ case APPLIED:
+ case STABLE:
+ case COMMITTED:
+ case ACCEPTED:
+ if (testExecuteAt.is(HLC_BOUND))
+ {
+ if (txnId.toString().equals("[2,1048,65(RR),15]"))
+ System.out.println();
+ supersedingRejects = true;
+ return false;
+ }
+ if (status != ACCEPTED) break;
+ case PRENOTACCEPTED_OR_ACCEPTED_INVALIDATE:
+ case PREACCEPTED:
+ ensureLaterWait().add(keyOrRange, testTxnId);
+ break;
+ case INVALIDATED:
+ case NOTACCEPTED:
+ case NOT_DIRECTLY_WITNESSED:
+ }
+ return true;
+ }
switch (dep)
{
default: throw new UnhandledEnum(dep);
@@ -197,6 +226,8 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
* witnessed us we are safe to propose the pre-accept timestamp regardless, whereas if any transaction
* has not witnessed us we can safely invalidate.
*/
+ if (txnId.toString().equals("[2,1048,65(RR),15]"))
+ System.out.println();
supersedingRejects = true;
return false;
@@ -242,6 +273,8 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
* witnessed us we are safe to propose the pre-accept timestamp regardless, whereas if any transaction
* has not witnessed us we can safely invalidate (us).
*/
+ if (txnId.toString().equals("[2,1048,65(RR),15]"))
+ System.out.println();
supersedingRejects = true;
return false;
@@ -343,10 +376,15 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
Timestamp executeAt = command.executeAt();
Writes writes = command.writes();
Result result = command.result();
- boolean acceptsFastPath = participants.owns().isEmpty() || (txnId.hasPrivilegedCoordinator() ? saveStatus.known.hasPrivilegedVote() : executeAt.equals(txnId));
+ boolean acceptsFastPath = acceptsFastPath(txnId, participants, saveStatus, executeAt);
return new RecoverOk(txnId, saveStatus.status, accepted, executeAt, deps, earlierWait, earlierNoWait, laterWait, laterNoWait, acceptsFastPath, supersedingRejects, writes, result);
}
+ static boolean acceptsFastPath(TxnId txnId, StoreParticipants participants, SaveStatus saveStatus, @Nullable Timestamp executeAt)
+ {
+ return participants.owns().isEmpty() || (txnId.hasPrivilegedCoordinator() ? saveStatus.known.hasPrivilegedVote() : txnId.equals(executeAt));
+ }
+
@Override
public RecoverReply reduce(RecoverReply r1, RecoverReply r2)
{
diff --git a/accord-core/src/main/java/accord/messages/CheckStatus.java b/accord-core/src/main/java/accord/messages/CheckStatus.java
index 54afe2b8..5f4d78a5 100644
--- a/accord-core/src/main/java/accord/messages/CheckStatus.java
+++ b/accord-core/src/main/java/accord/messages/CheckStatus.java
@@ -307,7 +307,7 @@ public class CheckStatus extends AbstractRequest<CheckStatus.CheckStatusReply>
public Timestamp executeAtIfKnown()
{
- if (maxKnown().executeAt().isDecidedAndKnownToExecute())
+ if (maxKnown().isExecuteAtKnown())
return executeAt;
return null;
}
diff --git a/accord-core/src/main/java/accord/messages/Commit.java b/accord-core/src/main/java/accord/messages/Commit.java
index cf22af55..a7b13cc3 100644
--- a/accord-core/src/main/java/accord/messages/Commit.java
+++ b/accord-core/src/main/java/accord/messages/Commit.java
@@ -265,7 +265,8 @@ public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
@Override
public KeyHistory keyHistory()
{
- return KeyHistory.ASYNC;
+ // TODO (expected): need to guarantee execution order then can make this ASYNC
+ return KeyHistory.SYNC;
}
@Override
@@ -308,7 +309,7 @@ public class Commit extends TxnRequest.WithUnsynced<CommitOrReadNack>
if (reply != null || failure != null)
node.reply(replyTo, replyContext, reply, failure);
else if (kind.saveStatus == Committed)
- node.reply(replyTo, replyContext, new ReadData.ReadOk(null, null), null);
+ node.reply(replyTo, replyContext, new ReadData.ReadOk(null, null, 0), null);
}
@Override
diff --git a/accord-core/src/main/java/accord/messages/PreAccept.java b/accord-core/src/main/java/accord/messages/PreAccept.java
index 613c0828..598309f2 100644
--- a/accord-core/src/main/java/accord/messages/PreAccept.java
+++ b/accord-core/src/main/java/accord/messages/PreAccept.java
@@ -191,7 +191,7 @@ public class PreAccept extends WithUnsynced<PreAccept.PreAcceptReply>
PreAcceptOk okMax = ok1.witnessedAt.compareTo(ok2.witnessedAt) >= 0 ? ok1 : ok2;
PreAcceptOk okMin = okMax == ok1 ? ok2 : ok1;
- Timestamp witnessedAt = Timestamp.mergeMax(okMax.witnessedAt, okMin.witnessedAt);
+ Timestamp witnessedAt = Timestamp.mergeMaxAndFlags(okMax.witnessedAt, okMin.witnessedAt);
Deps deps = ok1.deps.with(ok2.deps);
if (deps == okMax.deps && witnessedAt == okMax.witnessedAt)
diff --git a/accord-core/src/main/java/accord/messages/Propagate.java b/accord-core/src/main/java/accord/messages/Propagate.java
index 20a39f67..b5409703 100644
--- a/accord-core/src/main/java/accord/messages/Propagate.java
+++ b/accord-core/src/main/java/accord/messages/Propagate.java
@@ -58,6 +58,7 @@ import static accord.local.Cleanup.ERASE;
import static accord.local.Cleanup.VESTIGIAL;
import static accord.local.Commands.purge;
import static accord.local.StoreParticipants.Filter.UPDATE;
+import static accord.primitives.Known.KnownDeps.DepsKnown;
import static accord.primitives.Known.KnownDeps.DepsUnknown;
import static accord.primitives.Known.Nothing;
import static accord.primitives.SaveStatus.Stable;
@@ -147,7 +148,7 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
return;
}
- Invariants.checkState(sourceEpoch == txnId.epoch() || (full.executeAt != null && sourceEpoch == full.executeAt.epoch()) || full.maxSaveStatus == SaveStatus.Erased || full.maxSaveStatus == SaveStatus.ErasedOrVestigial);
+ Invariants.checkState(sourceEpoch == txnId.epoch() || (full.executeAt != null && sourceEpoch == full.executeAt.epoch()) || full.maxSaveStatus == SaveStatus.Erased || full.maxSaveStatus == SaveStatus.Vestigial);
// TODO (required): consider and document whether it is safe to infer that we are stale if we have not received responses from all shards we know of
// (in principle, we should at least require responses from our own shard, and the home shard if we know it); if we only hear from a remote shard it may have fully Erased
@@ -223,6 +224,22 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
return null;
}
+ if (command.known().is(DepsKnown))
+ {
+ // keep the deps we already have
+ participants = command.participants().supplement(participants);
+ }
+ else
+ {
+ Participants<?> depsNeeds = participants.stillTouches();
+ if (found.hasDecidedDeps() && stableDeps == null && this.stableDeps != null)
+ {
+ Invariants.checkState(executeAtIfKnown != null);
+ // we don't subtract existing partialDeps, as they cannot be committed deps; we only permit committing deps covering all participating ranges
+ stableDeps = this.stableDeps.intersecting(depsNeeds).reconstitutePartial(depsNeeds);
+ }
+ }
+
Participants<?> txnNeeds = participants.stillOwnsOrMayExecute(txnId);
if (found.isDefinitionKnown() && partialTxn == null && this.partialTxn != null)
{
@@ -231,14 +248,6 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
if (existing != null) neededExtra = neededExtra.without(existing.keys().toParticipants());
partialTxn = this.partialTxn.intersecting(neededExtra, true).reconstitutePartial(neededExtra);
}
-
- Participants<?> depsNeeds = participants.stillTouches();
- if (found.hasDecidedDeps() && stableDeps == null && this.stableDeps != null)
- {
- Invariants.checkState(executeAtIfKnown != null);
- // we don't subtract existing partialDeps, as they cannot be committed deps; we only permit committing deps covering all participating ranges
- stableDeps = this.stableDeps.intersecting(depsNeeds).reconstitutePartial(depsNeeds);
- }
}
SaveStatus propagate = found.atLeast(command.known()).propagatesSaveStatus();
@@ -265,8 +274,9 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
case Applied:
case PreApplied:
- Invariants.checkState(executeAtIfKnown != null);
- confirm(Commands.apply(safeStore, safeCommand, participants, txnId, route, executeAtIfKnown, stableDeps, partialTxn, writes, result));
+ Invariants.checkState(committedExecuteAt != null);
+ // we must use the remote executeAt, as it might have a uniqueHlc we aren't aware of at commit
+ confirm(Commands.apply(safeStore, safeCommand, participants, txnId, route, committedExecuteAt, stableDeps, partialTxn, writes, result));
break;
case Stable:
@@ -344,7 +354,7 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
if (stillTouches.isEmpty())
return known.knownForAny();
- RedundantStatus status = safeStore.redundantBefore().status(txnId, stillTouches);
+ RedundantStatus status = safeStore.redundantBefore().status(txnId, null, stillTouches);
// try to see if we can safely purge the full command
if (tryPurge(safeStore, safeCommand, status))
return null;
@@ -399,8 +409,9 @@ public class Propagate implements PreLoadContext, MapReduceConsume<SafeCommandSt
case PARTIALLY_SHARD_REDUNDANT:
case PARTIALLY_SHARD_FULLY_LOCALLY_REDUNDANT:
case SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
- case GC_BEFORE_OR_SHARD_REDUNDANT_AND_PRE_BOOTSTRAP_OR_STALE:
+ case TRUNCATE_BEFORE:
case GC_BEFORE:
+ // TODO (required): consider HLC clashes
case PRE_BOOTSTRAP_OR_STALE:
purge(safeStore, safeCommand, ERASE, true, true);
return true;
diff --git a/accord-core/src/main/java/accord/messages/ReadData.java b/accord-core/src/main/java/accord/messages/ReadData.java
index 6f63d9c5..331a8951 100644
--- a/accord-core/src/main/java/accord/messages/ReadData.java
+++ b/accord-core/src/main/java/accord/messages/ReadData.java
@@ -41,9 +41,11 @@ import accord.primitives.Participants;
import accord.primitives.Ranges;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
+import accord.primitives.Unseekables;
import accord.topology.Topologies;
import accord.utils.Invariants;
import accord.utils.MapReduceConsume;
+import accord.utils.UnhandledEnum;
import accord.utils.async.AsyncChain;
import accord.utils.async.Cancellable;
import org.agrona.collections.Int2ObjectHashMap;
@@ -56,6 +58,7 @@ import static accord.messages.ReadData.CommitOrReadNack.Insufficient;
import static accord.messages.ReadData.CommitOrReadNack.Redundant;
import static accord.messages.TxnRequest.latestRelevantEpochIndex;
import static accord.primitives.Routables.Slice.Minimal;
+import static accord.primitives.Txn.Kind.Write;
import static accord.utils.Invariants.illegalState;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
@@ -121,6 +124,7 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
transient Timestamp executeAt;
private Data data;
+ private long uniqueHlc;
transient IntHashSet waitingOn, reading;
transient int waitingOnCount;
transient Ranges unavailable;
@@ -324,7 +328,7 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
// Unless failed always ack to indicate setup has completed otherwise the counter never gets to -1
if ((reply == null || !reply.isFinal()) && failure == null)
{
- onOneSuccess(-1, null, true);
+ onOneSuccess(-1, null);
if (reply != null)
reply(reply, null);
}
@@ -355,6 +359,18 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
// TODO (required): do we need to check unavailable again on completion, or throughout execution?
// e.g. if we are marked stale and begin processing later commands
Ranges unavailable = unavailable(safeStore, command);
+ if (txnId.is(Write))
+ {
+ long uniqueHlc = command.asCommitted().waitingOn().minUniqueHlc();
+ if (uniqueHlc > 0)
+ {
+ synchronized (this)
+ {
+ this.uniqueHlc = Math.max(this.uniqueHlc, uniqueHlc);
+ }
+ }
+ }
+
CommandStore unsafeStore = safeStore.commandStore();
beginRead(safeStore, command.executeAt(), command.partialTxn(), unavailable).begin((next, throwable) -> {
if (throwable != null)
@@ -385,18 +401,18 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
int storeId = commandStore.id();
cancelSelf = listeners.remove(storeId);
- clear = onOneSuccessInternal(storeId, unavailable, false);
+ clear = onOneSuccessInternal(storeId, unavailable);
}
cancelSelf.cancel();
cleanup(clear);
}
- protected void onOneSuccess(int storeId, @Nullable Ranges newUnavailable, boolean registration)
+ protected void onOneSuccess(int storeId, @Nullable Ranges newUnavailable)
{
- cleanup(onOneSuccessInternal(storeId, newUnavailable, registration));
+ cleanup(onOneSuccessInternal(storeId, newUnavailable));
}
- protected synchronized Cancellable onOneSuccessInternal(int storeId, @Nullable Ranges newUnavailable, boolean registration)
+ protected synchronized Cancellable onOneSuccessInternal(int storeId, @Nullable Ranges newUnavailable)
{
if (storeId >= 0)
{
@@ -419,9 +435,7 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
switch (state)
{
- default:
- throw new AssertionError("Unknown state: " + state);
-
+ default: throw new UnhandledEnum(state);
case RETURNED:
throw illegalState("ReadOk was sent, yet ack called again");
@@ -432,7 +446,7 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
case PENDING:
state = State.RETURNED;
- reply(constructReadOk(unavailable, data), null);
+ reply(constructReadOk(unavailable, data, uniqueHlc), null);
return clearUnsafe();
}
}
@@ -508,10 +522,16 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
}
}
- protected ReadOk constructReadOk(Ranges unavailable, Data data)
+ @Override
+ public Unseekables<?> keys()
+ {
+ return scope;
+ }
+
+ protected ReadOk constructReadOk(Ranges unavailable, Data data, long uniqueHlc)
{
if (data != null) data.validateReply(txnId, executeAt);
- return new ReadOk(unavailable, data);
+ return new ReadOk(unavailable, data, uniqueHlc);
}
protected void reply(ReadReply reply, Throwable fail)
@@ -594,13 +614,19 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
* TODO (required): narrow to only the *intersecting* ranges that are unavailable, or do so on the recipient
*/
public final @Nullable Ranges unavailable;
-
public final @Nullable Data data;
+ public final long uniqueHlc;
- public ReadOk(@Nullable Ranges unavailable, @Nullable Data data)
+ protected ReadOk(@Nullable Ranges unavailable, @Nullable Data data)
+ {
+ this(unavailable, data, 0);
+ }
+
+ public ReadOk(@Nullable Ranges unavailable, @Nullable Data data, long uniqueHlc)
{
this.unavailable = unavailable;
this.data = data;
+ this.uniqueHlc = uniqueHlc;
}
@Override
@@ -635,7 +661,11 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
@Override
public String toString()
{
- return "ReadOk{" + data + (unavailable == null ? "" : ", unavailable:" + unavailable) + ", futureEpoch=" + futureEpoch + '}';
+ return "ReadOk{" + data
+ + (unavailable == null ? "" : ", unavailable:" + unavailable)
+ + (uniqueHlc == 0 ? "" : ", hlc:" + uniqueHlc)
+ + (futureEpoch == 0 ? "" : ", futureEpoch=" + futureEpoch)
+ + '}';
}
@Override
diff --git a/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java b/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
index 2b812693..05735c0a 100644
--- a/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
+++ b/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
@@ -185,9 +185,9 @@ public class ReadEphemeralTxnData extends ReadData
}
@Override
- protected ReadOk constructReadOk(Ranges unavailable, Data data)
+ protected ReadOk constructReadOk(Ranges unavailable, Data data, long uniqueHlc)
{
- return new ReadOkWithFutureEpoch(unavailable, data, 0);
+ return new ReadOkWithFutureEpoch(unavailable, data, uniqueHlc);
}
@Override
diff --git a/accord-core/src/main/java/accord/messages/RecoverAwait.java b/accord-core/src/main/java/accord/messages/RecoverAwait.java
index 67bd8759..ff6d6336 100644
--- a/accord-core/src/main/java/accord/messages/RecoverAwait.java
+++ b/accord-core/src/main/java/accord/messages/RecoverAwait.java
@@ -25,10 +25,12 @@ import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.primitives.Known.KnownDeps;
import accord.primitives.Participants;
+import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Topologies;
import static accord.primitives.Routables.Slice.Minimal;
+import static accord.primitives.Timestamp.Flag.HLC_BOUND;
public class RecoverAwait extends Await
{
@@ -57,8 +59,15 @@ public class RecoverAwait extends Await
if (!knownDeps.hasProposedOrDecidedDeps())
return;
- if ((knownDeps.hasCommittedOrDecidedDeps() ? command.executeAt() : command.txnId()).compareTo(recoverId) < 0)
+ if ((knownDeps.hasCommittedOrDecidedDeps() ? command.executeAt() : txnId).compareTo(recoverId) < 0)
+ {
+ if (txnId.is(Txn.Kind.ExclusiveSyncPoint) && txnId.hlc() > recoverId.hlc() && command.executeAt().is(HLC_BOUND))
+ {
+ rejects = true;
+ node.reply(replyTo, replyContext, SimpleReply.Nack, null);
+ }
return;
+ }
Participants<?> participants = scope.intersecting(command.participants().owns(), Minimal);
if (!command.partialDeps().participants(recoverId).containsAll(participants))
diff --git a/accord-core/src/main/java/accord/messages/SetShardDurable.java b/accord-core/src/main/java/accord/messages/SetShardDurable.java
index 4d07788b..9b3b6ea5 100644
--- a/accord-core/src/main/java/accord/messages/SetShardDurable.java
+++ b/accord-core/src/main/java/accord/messages/SetShardDurable.java
@@ -22,6 +22,7 @@ import accord.local.PreLoadContext;
import accord.local.SafeCommandStore;
import accord.primitives.AbstractRanges;
import accord.primitives.SyncPoint;
+import accord.primitives.TxnId;
import accord.utils.MapReduceConsume;
import accord.utils.async.Cancellable;
@@ -41,7 +42,8 @@ public class SetShardDurable extends AbstractRequest<SimpleReply>
@Override
public Cancellable submit()
{
- node.markDurable(exclusiveSyncPoint.route.toRanges(), exclusiveSyncPoint.syncId, exclusiveSyncPoint.syncId)
+ TxnId syncIdWithFlags = (TxnId) exclusiveSyncPoint.executeAt;
+ node.markDurable(exclusiveSyncPoint.route.toRanges(), syncIdWithFlags, syncIdWithFlags)
.addCallback((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/messages/StableThenRead.java b/accord-core/src/main/java/accord/messages/StableThenRead.java
index 469f9b1c..3c37f59c 100644
--- a/accord-core/src/main/java/accord/messages/StableThenRead.java
+++ b/accord-core/src/main/java/accord/messages/StableThenRead.java
@@ -21,6 +21,7 @@ package accord.messages;
import javax.annotation.Nullable;
import accord.local.Commands;
+import accord.local.KeyHistory;
import accord.local.Node;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
@@ -105,6 +106,12 @@ public class StableThenRead extends ReadData
return EXECUTE_ON;
}
+ @Override
+ public KeyHistory keyHistory()
+ {
+ return KeyHistory.ASYNC;
+ }
+
@Override
public ReadType kind()
{
diff --git a/accord-core/src/main/java/accord/messages/TxnRequest.java b/accord-core/src/main/java/accord/messages/TxnRequest.java
index 89bf99c1..a74dd27d 100644
--- a/accord-core/src/main/java/accord/messages/TxnRequest.java
+++ b/accord-core/src/main/java/accord/messages/TxnRequest.java
@@ -29,7 +29,6 @@ import accord.local.SafeCommandStore;
import accord.primitives.FullRoute;
import accord.primitives.Participants;
import accord.primitives.Ranges;
-import accord.primitives.Routables;
import accord.primitives.Route;
import accord.primitives.TxnId;
import accord.primitives.Unseekables;
@@ -119,7 +118,7 @@ public abstract class TxnRequest<R extends Reply> extends AbstractRequest<R> imp
protected abstract @Nullable Cancellable submit();
// finds the first topology index that intersects with the node
- protected static int latestRelevantEpochIndex(Node.Id node, Topologies topologies, Routables<?> route)
+ protected static int latestRelevantEpochIndex(Node.Id node, Topologies topologies, Unseekables<?> route)
{
Ranges latest = topologies.current().rangesForNode(node);
diff --git a/accord-core/src/main/java/accord/messages/WaitUntilApplied.java b/accord-core/src/main/java/accord/messages/WaitUntilApplied.java
index ede5bd11..c5d4dfc7 100644
--- a/accord-core/src/main/java/accord/messages/WaitUntilApplied.java
+++ b/accord-core/src/main/java/accord/messages/WaitUntilApplied.java
@@ -28,7 +28,7 @@ import accord.primitives.TxnId;
import accord.topology.Topologies;
import static accord.primitives.SaveStatus.Applied;
-import static accord.primitives.SaveStatus.ErasedOrVestigial;
+import static accord.primitives.SaveStatus.Vestigial;
/**
* Wait until the transaction has been applied locally
@@ -43,7 +43,7 @@ public class WaitUntilApplied extends ReadData
}
}
- private static final ExecuteOn EXECUTE_ON = new ExecuteOn(Applied, ErasedOrVestigial);
+ private static final ExecuteOn EXECUTE_ON = new ExecuteOn(Applied, Vestigial);
private final long minEpoch;
private long retryInLaterEpoch;
@@ -83,15 +83,15 @@ public class WaitUntilApplied extends ReadData
long retryInLaterEpoch = ReadEphemeralTxnData.retryInLaterEpoch(executeAtEpoch, safeStore, command);
if (retryInLaterEpoch > this.retryInLaterEpoch)
this.retryInLaterEpoch = retryInLaterEpoch;
- onOneSuccess(safeStore.commandStore().id(), unavailable(safeStore, command), false);
+ onOneSuccess(safeStore.commandStore().id(), unavailable(safeStore, command));
}
@Override
- protected ReadOk constructReadOk(Ranges unavailable, Data data)
+ protected ReadOk constructReadOk(Ranges unavailable, Data data, long uniqueHlc)
{
if (retryInLaterEpoch > 0)
return new ReadOkWithFutureEpoch(unavailable, data, retryInLaterEpoch);
- return new ReadOk(unavailable, data);
+ return new ReadOk(unavailable, data, uniqueHlc);
}
@Override
diff --git a/accord-core/src/main/java/accord/primitives/AbstractKeys.java b/accord-core/src/main/java/accord/primitives/AbstractKeys.java
index ca10973d..cb8b6fd3 100644
--- a/accord-core/src/main/java/accord/primitives/AbstractKeys.java
+++ b/accord-core/src/main/java/accord/primitives/AbstractKeys.java
@@ -108,7 +108,7 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
}
@Override
- public final boolean intersects(AbstractKeys<?> keys)
+ public final boolean intersects(AbstractUnseekableKeys keys)
{
return findNextIntersection(0, keys, 0) >= 0;
}
@@ -155,12 +155,19 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
return SortedArrays.findNextIntersection(this.keys, thisIdx, that.keys, thatIdx, RoutableKey::compareTo);
}
+ @Override
+ public final long findNextIntersection(int thisIdx, AbstractUnseekableKeys that, int thatIdx)
+ {
+ return SortedArrays.findNextIntersection(this.keys, thisIdx, that.keys, thatIdx, RoutableKey::compareAsRoutingKey);
+ }
+
@Override
public final long findNextIntersection(int thisIndex, Routables<K> with, int withIndex)
{
return findNextIntersection(thisIndex, (AbstractKeys<?>) with, withIndex);
}
+ @Override
public Stream<K> stream()
{
return Stream.of(keys);
@@ -311,6 +318,7 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
forEach.accept(key);
}
+ @Override
public final FullKeyRoute toRoute(RoutingKey homeKey)
{
return toRoutingKeysArray(homeKey, false, (routingKeys, homeKeyIndex, isParticipatingHomeKey) -> new FullKeyRoute(routingKeys[homeKeyIndex], routingKeys));
diff --git a/accord-core/src/main/java/accord/primitives/AbstractRanges.java b/accord-core/src/main/java/accord/primitives/AbstractRanges.java
index e614a4d3..ffee6d0d 100644
--- a/accord-core/src/main/java/accord/primitives/AbstractRanges.java
+++ b/accord-core/src/main/java/accord/primitives/AbstractRanges.java
@@ -157,7 +157,7 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
}
@Override
- public final boolean intersects(AbstractKeys<?> keys)
+ public final boolean intersects(AbstractUnseekableKeys keys)
{
return findNextIntersection(0, keys, 0) >= 0;
}
@@ -168,6 +168,7 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
return SortedArrays.findNextIntersection(this.ranges, 0, that.ranges, 0, Range::compareIntersecting) >= 0;
}
+ @Override
public final boolean intersects(Range that)
{
return indexOf(that, FAST) >= 0;
@@ -190,6 +191,12 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
return swapHighLow32b(SortedArrays.findNextIntersectionWithMultipleMatches(keys.keys, ki, ranges, ri));
}
+ @Override
+ public final long findNextIntersection(int ri, AbstractUnseekableKeys keys, int ki)
+ {
+ return swapHighLow32b(SortedArrays.findNextIntersectionWithMultipleMatches(keys.keys, ki, ranges, ri));
+ }
+
// returns ki in bottom 32 bits, ri in top, or -1 if no match found
@Override
public final long findNextIntersection(int thisi, AbstractRanges that, int thati)
diff --git a/accord-core/src/main/java/accord/primitives/Deps.java b/accord-core/src/main/java/accord/primitives/Deps.java
index f3eadf2c..ec7eb916 100644
--- a/accord-core/src/main/java/accord/primitives/Deps.java
+++ b/accord-core/src/main/java/accord/primitives/Deps.java
@@ -178,6 +178,13 @@ public class Deps
*/
public final KeyDeps directKeyDeps;
+ public Deps(Deps copy)
+ {
+ this.keyDeps = copy.keyDeps;
+ this.directKeyDeps = copy.directKeyDeps;
+ this.rangeDeps = copy.rangeDeps;
+ }
+
public Deps(KeyDeps keyDeps, RangeDeps rangeDeps, KeyDeps directKeyDeps)
{
this.keyDeps = keyDeps;
diff --git a/accord-core/src/main/java/accord/primitives/Keys.java b/accord-core/src/main/java/accord/primitives/Keys.java
index 3469db7d..478de7b0 100644
--- a/accord-core/src/main/java/accord/primitives/Keys.java
+++ b/accord-core/src/main/java/accord/primitives/Keys.java
@@ -101,6 +101,7 @@ public class Keys extends AbstractKeys<Key> implements Seekables<Key, Keys>
return Keys.ofSortedUnique(Arrays.copyOfRange(keys, from, to));
}
+ @Override
public final Keys intersecting(Seekables<?, ?> intersecting)
{
switch (intersecting.domain())
@@ -111,11 +112,13 @@ public class Keys extends AbstractKeys<Key> implements Seekables<Key, Keys>
}
}
+ @Override
public final Keys intersecting(Seekables<?, ?> intersecting, Slice slice)
{
return intersecting(intersecting);
}
+ @Override
public final Keys intersecting(Unseekables<?> intersecting)
{
switch (intersecting.domain())
@@ -126,6 +129,7 @@ public class Keys extends AbstractKeys<Key> implements Seekables<Key, Keys>
}
}
+ @Override
public final Keys intersecting(Unseekables<?> intersecting, Slice slice)
{
return intersecting(intersecting);
diff --git a/accord-core/src/main/java/accord/primitives/Known.java b/accord-core/src/main/java/accord/primitives/Known.java
index ef4b0635..3c60c565 100644
--- a/accord-core/src/main/java/accord/primitives/Known.java
+++ b/accord-core/src/main/java/accord/primitives/Known.java
@@ -25,8 +25,11 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import accord.utils.Invariants;
+import accord.utils.TinyEnumSet;
import accord.utils.UnhandledEnum;
+import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
+import static accord.primitives.Known.KnownExecuteAt.IS_EXECUTE_AT_KNOWN;
import static accord.primitives.Known.PrivilegedVote.VotePreAccept;
import static accord.primitives.Known.PrivilegedVote.NoVote;
import static accord.primitives.Known.Definition.DefinitionErased;
@@ -75,6 +78,7 @@ public class Known
public static final Known Nothing = new Known(MaybeRoute, DefinitionUnknown, ExecuteAtUnknown, DepsUnknown, Unknown, NoVote);
public static final Known DefinitionOnly = new Known(MaybeRoute, DefinitionKnown, ExecuteAtUnknown, DepsUnknown, Unknown, NoVote);
public static final Known DefinitionAndRoute = new Known(FullRoute, DefinitionKnown, ExecuteAtUnknown, DepsUnknown, Unknown, NoVote);
+ public static final Known DepsOnly = new Known(MaybeRoute, DefinitionUnknown, ExecuteAtUnknown, DepsKnown, Unknown, NoVote);
public static final Known Apply = new Known(FullRoute, DefinitionUnknown, ExecuteAtKnown, DepsKnown, Outcome.Apply, NoVote);
public static final Known Invalidated = new Known(MaybeRoute, DefinitionUnknown, ExecuteAtUnknown, DepsUnknown, Outcome.Abort, NoVote);
@@ -262,12 +266,12 @@ public class Known
if (definition() == DefinitionUnknown || definition() == DefinitionErased)
{
- if (executeAt().isDecidedAndKnownToExecute())
+ if (isExecuteAtKnown())
return SaveStatus.PreCommitted;
return SaveStatus.NotDefined;
}
- if (!executeAt().isDecidedAndKnownToExecute())
+ if (!isExecuteAtKnown())
return SaveStatus.PreAccepted;
// cannot propagate proposed deps; and cannot propagate known deps without executeAt
@@ -278,13 +282,15 @@ public class Known
switch (outcome())
{
default: throw new UnhandledEnum(outcome());
+ case Apply:
+ if (is(ApplyAtKnown))
+ return SaveStatus.PreApplied;
+
case Unknown:
case WasApply:
case Erased:
return SaveStatus.Stable;
- case Apply:
- return SaveStatus.PreApplied;
}
}
@@ -344,13 +350,13 @@ public class Known
public boolean isDecidedToExecute()
{
- return executeAt().isDecidedAndKnownToExecute() || outcome().isOrWasApply();
+ return isExecuteAtKnown() || outcome().isOrWasApply();
}
public String toString()
{
return Stream.of(definition().isKnown() ? "Definition" : null,
- executeAt().isDecidedAndKnownToExecute() ? "ExecuteAt" : null,
+ executeAt() == ExecuteAtKnown ? "ExecuteAt" : executeAt() == ApplyAtKnown ? "ApplyAt" : null,
deps().hasDecidedDeps() ? "Deps" : null,
outcome().isDecided() ? outcome().toString() : null
).filter(Objects::nonNull).collect(Collectors.joining(",", "[", "]"));
@@ -413,64 +419,134 @@ public class Known
return (encoded & ROUTE_MASK) - route.ordinal();
}
+ private int definitionOrdinal()
+ {
+ return (encoded & DEFINITION_MASK) >>> DEFINITION_SHIFT;
+ }
+
public Definition definition()
{
- return Definition.VALUES[(encoded & DEFINITION_MASK) >>> DEFINITION_SHIFT];
+ return Definition.VALUES[definitionOrdinal()];
}
public boolean is(Definition definition)
{
- return ((encoded & DEFINITION_MASK) >> DEFINITION_SHIFT) == definition.ordinal();
+ return definitionOrdinal() == definition.ordinal();
}
public int compareTo(Definition definition)
{
- return ((encoded & DEFINITION_MASK) >> DEFINITION_SHIFT) - definition.ordinal();
+ return definitionOrdinal() - definition.ordinal();
+ }
+
+ public boolean equalDefinition(Known that)
+ {
+ return definitionOrdinal() == that.definitionOrdinal();
+ }
+
+ public int compareDefinition(Known that)
+ {
+ return definitionOrdinal() - that.definitionOrdinal();
+ }
+
+ private int executeAtOrdinal()
+ {
+ return (encoded & EXECUTE_AT_MASK) >> EXECUTE_AT_SHIFT;
}
public KnownExecuteAt executeAt()
{
- return KnownExecuteAt.VALUES[(encoded & EXECUTE_AT_MASK) >>> EXECUTE_AT_SHIFT];
+ return KnownExecuteAt.VALUES[executeAtOrdinal()];
}
public boolean is(KnownExecuteAt executeAt)
{
- return ((encoded & EXECUTE_AT_MASK) >> EXECUTE_AT_SHIFT) == executeAt.ordinal();
+ return executeAtOrdinal() == executeAt.ordinal();
+ }
+
+ public boolean isExecuteAtKnown()
+ {
+ return TinyEnumSet.contains(IS_EXECUTE_AT_KNOWN, executeAtOrdinal());
}
public int compareTo(KnownExecuteAt executeAt)
{
- return ((encoded & EXECUTE_AT_MASK) >> EXECUTE_AT_SHIFT) - executeAt.ordinal();
+ return executeAtOrdinal() - executeAt.ordinal();
+ }
+
+ public boolean equalExecuteAt(Known that)
+ {
+ return executeAtOrdinal() == that.executeAtOrdinal();
+ }
+
+ public int compareExecuteAt(Known that)
+ {
+ return executeAtOrdinal() - that.executeAtOrdinal();
}
+ private int depsOrdinal()
+ {
+ return (encoded & DEPS_MASK) >>> DEPS_SHIFT;
+ }
+
public KnownDeps deps()
{
- return KnownDeps.VALUES[(encoded & DEPS_MASK) >>> DEPS_SHIFT];
+ return KnownDeps.VALUES[depsOrdinal()];
+ }
+
+ public boolean hasAnyDeps()
+ {
+ return TinyEnumSet.contains(KnownDeps.HAS_ANY, depsOrdinal());
}
public boolean is(KnownDeps deps)
{
- return ((encoded & DEPS_MASK) >> DEPS_SHIFT) == deps.ordinal();
+ return depsOrdinal() == deps.ordinal();
}
public int compareTo(KnownDeps deps)
{
- return ((encoded & DEPS_MASK) >> DEPS_SHIFT) - deps.ordinal();
+ return depsOrdinal() - deps.ordinal();
+ }
+
+ public boolean equalDeps(Known that)
+ {
+ return depsOrdinal() == that.depsOrdinal();
+ }
+
+ public int compareDeps(Known that)
+ {
+ return depsOrdinal() - that.depsOrdinal();
+ }
+
+ private int outcomeOrdinal()
+ {
+ return (encoded & OUTCOME_MASK) >>> OUTCOME_SHIFT;
}
public Outcome outcome()
{
- return Outcome.VALUES[(encoded & OUTCOME_MASK) >>> OUTCOME_SHIFT];
+ return Outcome.VALUES[outcomeOrdinal()];
}
public boolean is(Outcome outcome)
{
- return ((encoded & OUTCOME_MASK) >> OUTCOME_SHIFT) == outcome.ordinal();
+ return outcomeOrdinal() == outcome.ordinal();
}
public int compareTo(Outcome outcome)
{
- return ((encoded & OUTCOME_MASK) >> OUTCOME_SHIFT) - outcome.ordinal();
+ return outcomeOrdinal() - outcome.ordinal();
+ }
+
+ public boolean equalOutcome(Known that)
+ {
+ return outcomeOrdinal() == that.outcomeOrdinal();
+ }
+
+ public int compareOutcome(Known that)
+ {
+ return outcomeOrdinal() - that.outcomeOrdinal();
}
public boolean is(PrivilegedVote privilegedVote)
@@ -562,12 +638,19 @@ public class Known
*/
ExecuteAtKnown,
+ /**
+ * A decision to execute the transaction is known to have been reached, and the associated executeAt timestamp
+ * as well as any uniqueHlc that may be associated with it
+ */
+ ApplyAtKnown,
+
/**
* A decision to invalidate the transaction is known to have been reached
*/
NoExecuteAt
;
+ static final int IS_EXECUTE_AT_KNOWN = TinyEnumSet.encode(ExecuteAtKnown, ApplyAtKnown);
private static final KnownExecuteAt[] VALUES = values();
/**
@@ -589,9 +672,9 @@ public class Known
/**
* Is known to execute, and when.
*/
- public boolean isDecidedAndKnownToExecute()
+ public boolean isKnown()
{
- return this == ExecuteAtKnown;
+ return this == ExecuteAtKnown | this == ApplyAtKnown;
}
public KnownExecuteAt atLeast(KnownExecuteAt that)
@@ -620,7 +703,7 @@ public class Known
int c = compareTo(that);
KnownExecuteAt max = c >= 0 ? this : that;
KnownExecuteAt min = c <= 0 ? this : that;
- return max != NoExecuteAt || min != ExecuteAtKnown;
+ return max != NoExecuteAt || (min != ExecuteAtKnown && min != ApplyAtKnown);
}
}
@@ -678,6 +761,7 @@ public class Known
*/
NoDeps(Invalidate);
+ private static final int HAS_ANY = TinyEnumSet.encode(DepsFromCoordinator, DepsProposed, DepsProposedFixed, DepsCommitted, DepsKnown);
private static final KnownDeps[] VALUES = values();
public final Status.Phase phase;
@@ -694,20 +778,7 @@ public class Known
public boolean hasPreAcceptedOrProposedOrDecidedDeps()
{
- switch (this)
- {
- default: throw new UnhandledEnum(this);
- case DepsFromCoordinator:
- case DepsCommitted:
- case DepsProposed:
- case DepsProposedFixed:
- case DepsKnown:
- return true;
- case NoDeps:
- case DepsErased:
- case DepsUnknown:
- return false;
- }
+ return TinyEnumSet.contains(HAS_ANY, this);
}
public boolean hasProposedOrDecidedDeps()
diff --git a/accord-core/src/main/java/accord/primitives/LatestDeps.java b/accord-core/src/main/java/accord/primitives/LatestDeps.java
index e8fc4f95..3fc27526 100644
--- a/accord-core/src/main/java/accord/primitives/LatestDeps.java
+++ b/accord-core/src/main/java/accord/primitives/LatestDeps.java
@@ -20,7 +20,9 @@ package accord.primitives;
import java.util.ArrayList;
import java.util.List;
+import java.util.function.BiConsumer;
import java.util.function.BiFunction;
+import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.IntStream;
@@ -30,6 +32,8 @@ import javax.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import accord.api.RoutingKey;
+import accord.coordinate.CollectLatestDeps;
+import accord.local.Node;
import accord.primitives.Known.KnownDeps;
import accord.utils.Invariants;
import accord.utils.ReducingIntervalMap;
@@ -42,6 +46,7 @@ import static accord.primitives.Known.KnownDeps.DepsErased;
import static accord.primitives.Known.KnownDeps.DepsKnown;
import static accord.primitives.Known.KnownDeps.DepsProposed;
import static accord.primitives.Known.KnownDeps.DepsProposedFixed;
+import static accord.primitives.Known.KnownDeps.DepsUnknown;
public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
{
@@ -55,6 +60,29 @@ public class LatestDeps extends ReducingRangeMap<LatestDeps.LatestEntry>
}
}
+ public static void withCommitted(Node node, TxnId txnId, Timestamp executeAt, Deps mergeDeps, FullRoute<?> route, Unseekables<?> missing, BiConsumer<?, Throwable> failureCallback, Consumer<Deps> withDeps)
+ {
+ node.withEpoch(executeAt.epoch(), failureCallback, () -> {
+ if (missing.isEmpty())
+ {
+ withDeps.accept(mergeDeps);
+ }
+ else
+ {
+ CollectLatestDeps.withLatestDeps(node, txnId, route, missing, executeAt, (extraDeps, fail) -> {
+ if (fail != null)
+ {
+ failureCallback.accept(null, fail);
+ }
+ else
+ {
+ withDeps.accept(LatestDeps.mergeCommit(DepsUnknown, executeAt, extraDeps, executeAt, i -> i).deps.with(mergeDeps));
+ }
+ });
+ }
+ });
+ }
+
public static class MergedCommitResult
{
public final Deps deps;
diff --git a/accord-core/src/main/java/accord/primitives/PartialDeps.java b/accord-core/src/main/java/accord/primitives/PartialDeps.java
index 387da8d6..518f77a2 100644
--- a/accord-core/src/main/java/accord/primitives/PartialDeps.java
+++ b/accord-core/src/main/java/accord/primitives/PartialDeps.java
@@ -119,7 +119,7 @@ public class PartialDeps extends Deps
public Deps reconstitute(FullRoute<?> route)
{
if (!covers(route.participants()))
- throw new IllegalArgumentException();
+ throw illegalArgument(covering + " does not cover " + route);
return new Deps(keyDeps, rangeDeps, directKeyDeps);
}
@@ -127,9 +127,9 @@ public class PartialDeps extends Deps
public PartialDeps reconstitutePartial(Participants<?> covering)
{
if (!covers(covering))
- throw new IllegalArgumentException();
+ throw illegalArgument(this.covering + " does not cover " + covering);
if (covers(covering)) return this;
- else throw illegalArgument(this + " does not cover " + covering);
+ else throw illegalArgument(this.covering + " does not cover " + covering);
}
}
diff --git a/accord-core/src/main/java/accord/primitives/Ranges.java b/accord-core/src/main/java/accord/primitives/Ranges.java
index a5b42eb0..b3ffe76f 100644
--- a/accord-core/src/main/java/accord/primitives/Ranges.java
+++ b/accord-core/src/main/java/accord/primitives/Ranges.java
@@ -86,6 +86,7 @@ public class Ranges extends AbstractRanges implements Iterable<Range>, Seekables
return ofSortedAndDeoverlapped(Ranges::ofSortedAndDeoverlappedUnchecked, selection);
}
+ @Override
public Stream<Range> stream()
{
return Stream.of(ranges);
diff --git a/accord-core/src/main/java/accord/primitives/RoutableKey.java b/accord-core/src/main/java/accord/primitives/RoutableKey.java
index b7c0610e..ac7b5840 100644
--- a/accord-core/src/main/java/accord/primitives/RoutableKey.java
+++ b/accord-core/src/main/java/accord/primitives/RoutableKey.java
@@ -35,6 +35,8 @@ public interface RoutableKey extends Routable, Comparable<RoutableKey>
@Override
RoutingKey toUnseekable();
+ default int compareAsRoutingKey(@Nonnull RoutableKey that) { return toUnseekable().compareTo(that.toUnseekable()); }
+
/**
* Some prefix that may be shared by other keys, particularly in a Range or Ranges.
* Mostly used for pretty printing Range and Ranges.
diff --git a/accord-core/src/main/java/accord/primitives/Routables.java b/accord-core/src/main/java/accord/primitives/Routables.java
index cb5134c6..a9a0aaf1 100644
--- a/accord-core/src/main/java/accord/primitives/Routables.java
+++ b/accord-core/src/main/java/accord/primitives/Routables.java
@@ -59,14 +59,15 @@ public interface Routables<K extends Routable> extends Iterable<K>
}
default boolean intersects(Range range) { return findNext(0, range, FAST) >= 0; }
boolean intersects(AbstractRanges ranges);
- boolean intersects(AbstractKeys<?> keys);
- default boolean intersects(Routables<?> routables)
+ default boolean intersects(Ranges ranges) { return intersects((AbstractRanges)ranges); }
+ boolean intersects(AbstractUnseekableKeys keys);
+ default boolean intersects(Unseekables<?> unseekables)
{
- switch (routables.domain())
+ switch (unseekables.domain())
{
- default: throw new AssertionError();
- case Key: return intersects((AbstractKeys<?>) routables);
- case Range: return intersects((AbstractRanges) routables);
+ default: throw new UnhandledEnum(unseekables.domain());
+ case Key: return intersects((AbstractUnseekableKeys) unseekables);
+ case Range: return intersects((AbstractRanges) unseekables);
}
}
@@ -99,6 +100,13 @@ public interface Routables<K extends Routable> extends Iterable<K>
*/
long findNextIntersection(int thisIndex, AbstractKeys<?> with, int withIndex);
+ /**
+ * Search forwards from {code thisIndex} and {@code withIndex} to find the first entries in each collection
+ * that intersect with each other. Return their position packed in a long, with low bits representing
+ * the resultant {@code thisIndex} and high bits {@code withIndex}.
+ */
+ long findNextIntersection(int thisIndex, AbstractUnseekableKeys with, int withIndex);
+
/**
* Search forwards from {code thisIndex} and {@code withIndex} to find the first entries in each collection
* that intersect with each other. Return their position packed in a long, with low bits representing
diff --git a/accord-core/src/main/java/accord/primitives/SaveStatus.java b/accord-core/src/main/java/accord/primitives/SaveStatus.java
index cf126a7a..baf77641 100644
--- a/accord-core/src/main/java/accord/primitives/SaveStatus.java
+++ b/accord-core/src/main/java/accord/primitives/SaveStatus.java
@@ -49,6 +49,7 @@ import static accord.primitives.Known.KnownDeps.DepsProposed;
import static accord.primitives.Known.KnownDeps.DepsUnknown;
import static accord.primitives.Known.KnownExecuteAt.ExecuteAtErased;
import static accord.primitives.Known.KnownExecuteAt.ExecuteAtKnown;
+import static accord.primitives.Known.KnownExecuteAt.ApplyAtKnown;
import static accord.primitives.Known.KnownExecuteAt.ExecuteAtProposed;
import static accord.primitives.Known.KnownExecuteAt.ExecuteAtUnknown;
import static accord.primitives.Known.KnownRoute.FullRoute;
@@ -114,13 +115,14 @@ public enum SaveStatus
// TruncatedApplyWithDeps is a state never adopted within a single replica; it is however a useful state we may enter by combining state from multiple replicas
// TODO (expected): TruncatedApplyWithDeps should be redundant now we have migrated away from SaveStatus in CheckStatusOk to Known; remove in isolated commit once stable
// however: we may want to retain it for the case where we want to truncate its payload but need to be able to answer recovery decisions
- TruncatedApplyWithDeps (Status.Truncated, FullRoute, DefinitionErased, ExecuteAtKnown, DepsKnown, Apply, CleaningUp),
- TruncatedApplyWithOutcome (Status.Truncated, FullRoute, DefinitionErased, ExecuteAtKnown, DepsErased, Apply, CleaningUp),
- TruncatedApply (Status.Truncated, FullRoute, DefinitionErased, ExecuteAtKnown, DepsErased, WasApply,CleaningUp),
+ TruncatedApplyWithDeps (Status.Truncated, FullRoute, DefinitionErased, ApplyAtKnown, DepsKnown, Apply, CleaningUp),
+ TruncatedApplyWithOutcome (Status.Truncated, FullRoute, DefinitionErased, ApplyAtKnown, DepsErased, Apply, CleaningUp),
+// TruncatedApplyWithRoute (Status.Truncated, FullRoute, DefinitionErased, ApplyAtKnown, DepsErased, WasApply,CleaningUp),
+ TruncatedApply (Status.Truncated, MaybeRoute, DefinitionErased, ApplyAtKnown, DepsErased, WasApply,CleaningUp),
+ // Vestigial means the command cannot be completed and is either pre-bootstrap, did not commit, or did not participate in this shard's epoch
+ Vestigial (Status.Truncated, MaybeRoute, DefinitionUnknown, ExecuteAtUnknown, DepsUnknown, Unknown, CleaningUp),
// NOTE: Erased should ONLY be adopted on a replica that knows EVERY shard has successfully applied the transaction at all healthy replicas (or else that it is durably invalidated)
Erased (Status.Truncated, MaybeRoute, DefinitionErased, ExecuteAtErased, DepsErased, Outcome.Erased,CleaningUp),
- // ErasedOrVestigial means the command cannot be completed and is either pre-bootstrap, did not commit, or did not participate in this shard's epoch
- ErasedOrVestigial (Status.Truncated, MaybeRoute, DefinitionUnknown, ExecuteAtUnknown, DepsUnknown, Unknown, CleaningUp),
Invalidated (Status.Invalidated, CleaningUp),
;
@@ -275,7 +277,7 @@ public enum SaveStatus
if (status.compareTo(Status.PreCommitted) < 0)
{
- if (known.executeAt().isDecidedAndKnownToExecute())
+ if (known.isExecuteAtKnown())
{
switch (status)
{
@@ -388,12 +390,12 @@ public enum SaveStatus
switch (status)
{
default: throw new AssertionError("Unexpected status: " + status);
- case ErasedOrVestigial:
+ case Vestigial:
if (known.outcome().isInvalidated())
return Invalidated;
if (!known.outcome().isOrWasApply() || known.is(ExecuteAtKnown))
- return ErasedOrVestigial;
+ return Vestigial;
case Erased:
if (!known.outcome().isOrWasApply() || !known.is(ExecuteAtKnown))
@@ -462,13 +464,20 @@ public enum SaveStatus
SaveStatus status = getStatus.apply(item);
Ballot ballot = getAcceptedOrCommittedBallot.apply(item);
- boolean update = max == null
- || maxStatus.phase.compareTo(status.phase) < 0
- || (maxStatus.phase.tieBreakWithBallot ? maxStatus.phase == status.phase && maxBallot.compareTo(ballot) < 0
- : maxStatus.compareTo(status) < 0);
-
- if (!update)
- continue;
+ if (max != null)
+ {
+ if (maxStatus.phase.compareTo(status.phase) > 0) continue;
+ if (maxStatus.phase == status.phase)
+ {
+ if (maxStatus.phase.tieBreakWithBallot)
+ {
+ int c = maxBallot.compareTo(ballot);
+ if (c > 0) continue;
+ if (c == 0 && maxStatus.compareTo(status) >= 0) continue;
+ }
+ else if (maxStatus.compareTo(status) >= 0) continue;
+ }
+ }
max = item;
maxStatus = status;
diff --git a/accord-core/src/main/java/accord/primitives/Seekables.java b/accord-core/src/main/java/accord/primitives/Seekables.java
index 8ecde4ae..bd6c0724 100644
--- a/accord-core/src/main/java/accord/primitives/Seekables.java
+++ b/accord-core/src/main/java/accord/primitives/Seekables.java
@@ -36,6 +36,7 @@ public interface Seekables<K extends Seekable, U extends Seekables<K, ?>> extend
@Override
U slice(Ranges ranges, Slice slice);
+ @Override
U intersecting(Unseekables<?> intersecting, Slice slice);
Seekables<K, U> without(Ranges ranges);
@@ -43,6 +44,7 @@ public interface Seekables<K extends Seekable, U extends Seekables<K, ?>> extend
Seekables<K, U> with(U with);
Participants<?> toParticipants();
+ @Override
FullRoute<?> toRoute(RoutingKey homeKey);
static Seekables<?, ?> of(Seekable seekable)
diff --git a/accord-core/src/main/java/accord/primitives/Status.java b/accord-core/src/main/java/accord/primitives/Status.java
index 64ad3696..e4d0d7eb 100644
--- a/accord-core/src/main/java/accord/primitives/Status.java
+++ b/accord-core/src/main/java/accord/primitives/Status.java
@@ -92,11 +92,11 @@ public enum Status
* To solve this problem we simply permit the executeAt we discover for B to be propagated to A* without
* its dependencies. Though this does complicate the state machine a little.
*/
- PreCommitted (Accept, PREACCEPTED, FullRoute, DefinitionUnknown, ExecuteAtKnown, DepsUnknown, Unknown),
+ PreCommitted (Commit, PREACCEPTED, FullRoute, DefinitionUnknown, ExecuteAtKnown, DepsUnknown, Unknown),
Committed (Commit, COMMITTED, FullRoute, DefinitionKnown, ExecuteAtKnown, DepsCommitted, Unknown),
Stable (Execute, STABLE, FullRoute, DefinitionKnown, ExecuteAtKnown, DepsKnown, Unknown),
- PreApplied (Persist, STABLE, FullRoute, DefinitionKnown, ExecuteAtKnown, DepsKnown, Outcome.Apply),
- Applied (Persist, APPLIED, FullRoute, DefinitionKnown, ExecuteAtKnown, DepsKnown, Outcome.Apply),
+ PreApplied (Persist, STABLE, FullRoute, DefinitionKnown, ApplyAtKnown, DepsKnown, Outcome.Apply),
+ Applied (Persist, APPLIED, FullRoute, DefinitionKnown, ApplyAtKnown, DepsKnown, Outcome.Apply),
// TODO (required): TruncatedApply should be treated as APPLIED for summary status; when computing recovery decisions
// anything already APPLIED should be treated as not witnessing anything being recovered from preaccept status
// EXCEPT this cannot apply for touches \notin owns... consider some more how we handle this case
diff --git a/accord-core/src/main/java/accord/primitives/Timestamp.java b/accord-core/src/main/java/accord/primitives/Timestamp.java
index f2e6a3fa..4642a248 100644
--- a/accord-core/src/main/java/accord/primitives/Timestamp.java
+++ b/accord-core/src/main/java/accord/primitives/Timestamp.java
@@ -49,8 +49,23 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
public enum Flag
{
+ /**
+ * To be used only by executeAt responses during PreAccept. Can never be taken at the same time as REJECTED.
+ */
REJECTED(0x0800),
- UNSTABLE(0x0800);
+
+ /**
+ * To be used only by TxnId inside of Dep collections. Can never be taken at the same time as REJECTED.
+ */
+ UNSTABLE(0x0800),
+
+ /**
+ * An ExclusiveSyncPoint that marks its executeAt with this flag can be used to cleanup HLCs.
+ * This means it did not witness any conflicts in a future epoch, and so all transactions that
+ * might take a lower HLC must have been witnessed.
+ */
+ HLC_BOUND(0x0400)
+ ;
public final int bit;
Flag(int bit)
@@ -141,7 +156,7 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
}
@Override
- public long epoch()
+ public final long epoch()
{
return epoch(msb);
}
@@ -149,12 +164,19 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
/**
* A hybrid logical clock with implementation-defined resolution
*/
- public long hlc()
+ public final long hlc()
{
return highHlc(msb) | lowHlc(lsb);
}
- public int flags()
+ public long uniqueHlc() { return hlc(); }
+
+ public boolean hasDistinctHlcAndUniqueHlc()
+ {
+ return false;
+ }
+
+ public final int flags()
{
return flags(lsb);
}
@@ -212,22 +234,22 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
return addFlags(this, merge, Timestamp::new);
}
- static <T extends Timestamp> T addFlags(T a, T b, Factory<T> factory)
+ static <T extends Timestamp> T addFlags(T to, T from, Factory<T> factory)
{
- long newLsb = a.lsb | (b.lsb & MERGE_FLAGS);
- if (a.lsb == newLsb)
- return a;
- if (b.lsb == newLsb && a.msb == b.msb && a.node.equals(b.node))
- return b;
- return factory.create(a.msb, newLsb, a.node);
+ long newLsb = to.lsb | (from.lsb & MERGE_FLAGS);
+ if (to.lsb == newLsb)
+ return to;
+ if (from.lsb == newLsb && to.msb == from.msb && to.node.equals(from.node))
+ return from;
+ return factory.create(to.msb, newLsb, to.node);
}
- static <T extends Timestamp> T addFlags(T a, int addFlags, Factory<T> factory)
+ static <T extends Timestamp> T addFlags(T to, int addFlags, Factory<T> factory)
{
- long newLsb = a.lsb | addFlags;
- if (a.lsb == newLsb)
- return a;
- return factory.create(a.msb, newLsb, a.node);
+ long newLsb = to.lsb | addFlags;
+ if (to.lsb == newLsb)
+ return to;
+ return factory.create(to.msb, newLsb, to.node);
}
public Timestamp logicalNext(Id node)
@@ -280,11 +302,20 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
{
if (this == that) return 0;
int c = Long.compareUnsigned(this.msb, that.msb);
- if (c == 0) c = Long.compareUnsigned(this.lsb, that.lsb);
+ if (c == 0) c = Long.compare(lowHlc(this.lsb), lowHlc(that.lsb));
+ if (c == 0) c = Long.compare(this.uniqueHlc(), that.uniqueHlc());
+ if (c == 0) c = Long.compare(this.flags(), that.flags());
if (c == 0) c = this.node.compareTo(that.node);
return c;
}
+ public Timestamp flattenUniqueHlc()
+ {
+ if (!hasDistinctHlcAndUniqueHlc())
+ return this;
+ return new Timestamp(epoch(), uniqueHlc(), flags(), node);
+ }
+
@Override
public int hashCode()
{
@@ -299,11 +330,11 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
}
/**
- * Include flag bits in identity
+ * Include flag bits in identity and any uniqueHlc
*/
public boolean equalsStrict(Timestamp that)
{
- return this.msb == that.msb && this.lsb == that.lsb && this.node.equals(that.node);
+ return this.msb == that.msb && this.lsb == that.lsb && this.node.equals(that.node) && uniqueHlc() == that.uniqueHlc();
}
@Override
@@ -318,9 +349,10 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
}
/**
- * Take the maximum of the two, but merge any mergeable flags
+ * The resulting timestamp will have max(a.hlc,b.hlc) and max(a.epoch, b.epoch),
+ * and any mergeable flag in either a or b
*/
- public static Timestamp mergeMax(Timestamp a, Timestamp b)
+ public static Timestamp mergeMaxAndFlags(Timestamp a, Timestamp b)
{
// Note: it is not safe to take the highest HLC while retaining the current node;
// however, it is safe to take the highest epoch, as the originating node will always advance the hlc()
@@ -328,16 +360,15 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
: b.addFlags(a).withEpochAtLeast(a.epoch());
}
- public static <T extends Timestamp> T rejectedOrMax(T a, T b)
- {
- return a.compareTo(b) >= 0 ? a : b;
- }
-
- public static Timestamp rejectStale(Timestamp maybeReject, Timestamp ifOnOrBefore)
+ /**
+ * The resulting timestamp will have max(a.hlc,b.hlc) and max(a.epoch, b.epoch)
+ */
+ public static Timestamp mergeMax(Timestamp a, Timestamp b)
{
- if (maybeReject.compareTo(ifOnOrBefore) > 0)
- return maybeReject;
- return maybeReject.asRejected();
+ // Note: it is not safe to take the highest HLC while retaining the current node;
+ // however, it is safe to take the highest epoch, as the originating node will always advance the hlc()
+ return a.compareToWithoutEpoch(b) >= 0 ? a.withEpochAtLeast(b.epoch())
+ : b.withEpochAtLeast(a.epoch());
}
public static <T extends Timestamp> T nonNullOrMax(T a, T b)
@@ -421,7 +452,9 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
public String toStandardString()
{
- return "[" + epoch() + ',' + hlc() + ',' + Integer.toBinaryString(flags()) + ',' + node + ']';
+ long hlc = hlc();
+ long uniqueHlc = uniqueHlc();
+ return "[" + epoch() + ',' + hlc + (hlc == uniqueHlc ? "" : "+" + (uniqueHlc - hlc)) + ',' + flags() + ',' + node + ']';
}
public static Timestamp fromString(String string)
diff --git a/accord-core/src/main/java/accord/api/Key.java b/accord-core/src/main/java/accord/primitives/TimestampWithUniqueHlc.java
similarity index 57%
copy from accord-core/src/main/java/accord/api/Key.java
copy to accord-core/src/main/java/accord/primitives/TimestampWithUniqueHlc.java
index 82dfcdc9..6c5f513f 100644
--- a/accord-core/src/main/java/accord/api/Key.java
+++ b/accord-core/src/main/java/accord/primitives/TimestampWithUniqueHlc.java
@@ -16,27 +16,34 @@
* limitations under the License.
*/
-package accord.api;
+package accord.primitives;
-import javax.annotation.Nonnull;
+import accord.local.Node.Id;
-import accord.primitives.Range;
-import accord.primitives.RoutableKey;
-import accord.primitives.Seekable;
-
-/**
- * A key we can find in both the cluster and on disk
- */
-public interface Key extends Seekable, RoutableKey
+public final class TimestampWithUniqueHlc extends Timestamp
{
- @Override
- default Key asKey() { return this; }
+ final long uniqueHlc;
- @Override
- default Key slice(Range range) { return this; }
+ public TimestampWithUniqueHlc(Timestamp copy, long uniqueHlc)
+ {
+ super(copy);
+ this.uniqueHlc = uniqueHlc;
+ }
- @Override
- default Range asRange() { throw new UnsupportedOperationException(); }
+ public TimestampWithUniqueHlc(long epoch, long hlc, long uniqueHlc, int flags, Id node)
+ {
+ super(epoch, hlc, flags, node);
+ this.uniqueHlc = uniqueHlc;
+ }
+
+ public long uniqueHlc()
+ {
+ return uniqueHlc;
+ }
- default int compareAsRoutingKey(@Nonnull RoutingKey that) { return toUnseekable().compareTo(that); }
+ @Override
+ public boolean hasDistinctHlcAndUniqueHlc()
+ {
+ return true;
+ }
}
diff --git a/accord-core/src/main/java/accord/primitives/Txn.java b/accord-core/src/main/java/accord/primitives/Txn.java
index 852633eb..08ddc7cd 100644
--- a/accord-core/src/main/java/accord/primitives/Txn.java
+++ b/accord-core/src/main/java/accord/primitives/Txn.java
@@ -103,12 +103,12 @@ public interface Txn
public static class Kinds extends TinyEnumSet<Kind>
{
- Kinds(Kind ... kinds)
+ public Kinds(Kind ... kinds)
{
super(kinds);
}
- private Kinds(int bitset)
+ public Kinds(int bitset)
{
super(bitset);
}
diff --git a/accord-core/src/main/java/accord/api/Key.java b/accord-core/src/main/java/accord/utils/BiFoldToLong.java
similarity index 57%
copy from accord-core/src/main/java/accord/api/Key.java
copy to accord-core/src/main/java/accord/utils/BiFoldToLong.java
index 82dfcdc9..02f872c9 100644
--- a/accord-core/src/main/java/accord/api/Key.java
+++ b/accord-core/src/main/java/accord/utils/BiFoldToLong.java
@@ -16,27 +16,9 @@
* limitations under the License.
*/
-package accord.api;
+package accord.utils;
-import javax.annotation.Nonnull;
-
-import accord.primitives.Range;
-import accord.primitives.RoutableKey;
-import accord.primitives.Seekable;
-
-/**
- * A key we can find in both the cluster and on disk
- */
-public interface Key extends Seekable, RoutableKey
+public interface BiFoldToLong<P1, P2>
{
- @Override
- default Key asKey() { return this; }
-
- @Override
- default Key slice(Range range) { return this; }
-
- @Override
- default Range asRange() { throw new UnsupportedOperationException(); }
-
- default int compareAsRoutingKey(@Nonnull RoutingKey that) { return toUnseekable().compareTo(that); }
+ long apply(P1 p1, P2 p2, long accumulate);
}
diff --git a/accord-core/src/main/java/accord/api/Key.java b/accord-core/src/main/java/accord/utils/FoldToLong.java
similarity index 57%
copy from accord-core/src/main/java/accord/api/Key.java
copy to accord-core/src/main/java/accord/utils/FoldToLong.java
index 82dfcdc9..03614834 100644
--- a/accord-core/src/main/java/accord/api/Key.java
+++ b/accord-core/src/main/java/accord/utils/FoldToLong.java
@@ -16,27 +16,9 @@
* limitations under the License.
*/
-package accord.api;
+package accord.utils;
-import javax.annotation.Nonnull;
-
-import accord.primitives.Range;
-import accord.primitives.RoutableKey;
-import accord.primitives.Seekable;
-
-/**
- * A key we can find in both the cluster and on disk
- */
-public interface Key extends Seekable, RoutableKey
+public interface FoldToLong<P1>
{
- @Override
- default Key asKey() { return this; }
-
- @Override
- default Key slice(Range range) { return this; }
-
- @Override
- default Range asRange() { throw new UnsupportedOperationException(); }
-
- default int compareAsRoutingKey(@Nonnull RoutingKey that) { return toUnseekable().compareTo(that); }
+ long apply(P1 p1, long accumulate);
}
diff --git a/accord-core/src/main/java/accord/api/Key.java b/accord-core/src/main/java/accord/utils/QuadFoldToLong.java
similarity index 57%
copy from accord-core/src/main/java/accord/api/Key.java
copy to accord-core/src/main/java/accord/utils/QuadFoldToLong.java
index 82dfcdc9..90423eb4 100644
--- a/accord-core/src/main/java/accord/api/Key.java
+++ b/accord-core/src/main/java/accord/utils/QuadFoldToLong.java
@@ -16,27 +16,9 @@
* limitations under the License.
*/
-package accord.api;
+package accord.utils;
-import javax.annotation.Nonnull;
-
-import accord.primitives.Range;
-import accord.primitives.RoutableKey;
-import accord.primitives.Seekable;
-
-/**
- * A key we can find in both the cluster and on disk
- */
-public interface Key extends Seekable, RoutableKey
+public interface QuadFoldToLong<P1, P2, P3, P4>
{
- @Override
- default Key asKey() { return this; }
-
- @Override
- default Key slice(Range range) { return this; }
-
- @Override
- default Range asRange() { throw new UnsupportedOperationException(); }
-
- default int compareAsRoutingKey(@Nonnull RoutingKey that) { return toUnseekable().compareTo(that); }
+ long apply(P1 p1, P2 p2, P3 p3, P4 p4, long accumulate);
}
diff --git a/accord-core/src/main/java/accord/utils/Timestamped.java b/accord-core/src/main/java/accord/utils/Timestamped.java
index 3b7f60a3..effc96c8 100644
--- a/accord-core/src/main/java/accord/utils/Timestamped.java
+++ b/accord-core/src/main/java/accord/utils/Timestamped.java
@@ -44,21 +44,32 @@ public class Timestamped<T>
public static <T> Timestamped<T> merge(Timestamped<T> a, Timestamped<T> b, BiPredicate<T, T> testPrefix, BiPredicate<T, T> testEquality)
{
int c = a.timestamp.compareTo(b.timestamp);
- if (c == 0)
- {
- Invariants.checkArgument(testEquality.test(a.data, b.data), "%s != %s", a, b);
- return a;
- }
- else if (c < 0)
- {
- Invariants.checkArgument(testPrefix.test(a.data, b.data), "%s >= %s", a, b);
- return b;
- }
- else
- {
- Invariants.checkArgument(testPrefix.test(b.data, a.data), "%s <= %s", a, b);
- return a;
- }
+ int c2 = Long.compare(a.timestamp.uniqueHlc(), b.timestamp.uniqueHlc());
+ Invariants.checkState(normaliseCmp(c) == normaliseCmp(c2));
+ validateCmp(c, a, b, testPrefix, testEquality, true);
+ validateCmp(c2, a, b, testPrefix, testEquality, true);
+ return c >= 0 ? a : b;
+ }
+
+ private static int normaliseCmp(int c)
+ {
+ return c < 0 ? -1 : c > 0 ? 1 : 0;
+ }
+
+ public static <T> Timestamped<T> mergeNew(Timestamped<T> a, Timestamped<T> b, BiPredicate<T, T> testPrefix, BiPredicate<T, T> testEquality)
+ {
+ int c = a.timestamp.compareTo(b.timestamp);
+ validateCmp(c, a, b, testPrefix, testEquality, false);
+ validateCmp(Long.compare(a.timestamp.uniqueHlc(), b.timestamp.uniqueHlc()), a, b, testPrefix, testEquality, false);
+ return c >= 0 ? a : b;
+ }
+
+ private static <T> void validateCmp(int cmp, Timestamped<T> a, Timestamped<T> b, BiPredicate<T, T> testPrefix, BiPredicate<T, T> testEquality, boolean permitBackwards)
+ {
+ if (cmp == 0) Invariants.checkArgument(testEquality.test(a.data, b.data), "%s != %s", a, b);
+ else if (cmp < 0) Invariants.checkArgument(testPrefix.test(a.data, b.data), "%s >= %s", a, b);
+ else if (permitBackwards) Invariants.checkArgument(testPrefix.test(b.data, a.data), "%s <= %s", a, b);
+ else Invariants.illegalState("Trying to write old data %s < %s", b, a);
}
public static <T> Timestamped<T> mergeEqual(Timestamped<T> a, Timestamped<T> b, BiPredicate<T, T> testEquality)
diff --git a/accord-core/src/main/java/accord/api/Key.java b/accord-core/src/main/java/accord/utils/TriFoldToLong.java
similarity index 57%
copy from accord-core/src/main/java/accord/api/Key.java
copy to accord-core/src/main/java/accord/utils/TriFoldToLong.java
index 82dfcdc9..6a82c871 100644
--- a/accord-core/src/main/java/accord/api/Key.java
+++ b/accord-core/src/main/java/accord/utils/TriFoldToLong.java
@@ -16,27 +16,9 @@
* limitations under the License.
*/
-package accord.api;
+package accord.utils;
-import javax.annotation.Nonnull;
-
-import accord.primitives.Range;
-import accord.primitives.RoutableKey;
-import accord.primitives.Seekable;
-
-/**
- * A key we can find in both the cluster and on disk
- */
-public interface Key extends Seekable, RoutableKey
+public interface TriFoldToLong<P1, P2, P3>
{
- @Override
- default Key asKey() { return this; }
-
- @Override
- default Key slice(Range range) { return this; }
-
- @Override
- default Range asRange() { throw new UnsupportedOperationException(); }
-
- default int compareAsRoutingKey(@Nonnull RoutingKey that) { return toUnseekable().compareTo(that); }
+ long apply(P1 p1, P2 p2, P3 p3, long accumulate);
}
diff --git a/accord-core/src/test/java/accord/burn/BurnTest.java b/accord-core/src/test/java/accord/burn/BurnTest.java
index cb28cfec..b43601c0 100644
--- a/accord-core/src/test/java/accord/burn/BurnTest.java
+++ b/accord-core/src/test/java/accord/burn/BurnTest.java
@@ -36,6 +36,7 @@ public class BurnTest extends BurnTestBase
run(System.nanoTime());
}
+ // TODO (required): higher NACK rate - since coordinator optimisation maybe? Investigate and make sure we're exploring enough states
public static void main(String[] args)
{
int count = 1;
diff --git a/accord-core/src/test/java/accord/burn/TopologyUpdates.java b/accord-core/src/test/java/accord/burn/TopologyUpdates.java
index 02a1d65b..96024678 100644
--- a/accord-core/src/test/java/accord/burn/TopologyUpdates.java
+++ b/accord-core/src/test/java/accord/burn/TopologyUpdates.java
@@ -107,7 +107,7 @@ public class TopologyUpdates
{
executors.apply(originator.id()).execute(() -> {
MessageTask.begin(originator, cluster, executors.apply(originator.id()), "EpochComplete:" + epoch, (node, from, onDone) -> {
- node.onEpochRedundant(ranges, epoch);
+ node.onEpochRetired(ranges, epoch);
onDone.accept(true);
});
});
diff --git a/accord-core/src/test/java/accord/coordinate/CoordinateSyncPointTest.java b/accord-core/src/test/java/accord/coordinate/CoordinateSyncPointTest.java
index 3cbc438d..294c2e4a 100644
--- a/accord-core/src/test/java/accord/coordinate/CoordinateSyncPointTest.java
+++ b/accord-core/src/test/java/accord/coordinate/CoordinateSyncPointTest.java
@@ -89,7 +89,7 @@ class CoordinateSyncPointTest
awaitApplied(n1, removed);
- n1.onEpochRedundant(Ranges.single(removed), t2.epoch());
+ n1.onEpochRetired(Ranges.single(removed), t2.epoch());
awaitApplied(n1, removed);
n1.onEpochClosed(Ranges.single(removed), t2.epoch());
@@ -128,7 +128,7 @@ class CoordinateSyncPointTest
}
else if (request instanceof Commit)
{
- onSuccess(args, new ReadData.ReadOk(null, null));
+ onSuccess(args, new ReadData.ReadOk(null, null, 0));
}
else if (request instanceof Apply)
{
@@ -136,7 +136,7 @@ class CoordinateSyncPointTest
}
else if (request instanceof WaitUntilApplied)
{
- onSuccess(args, new ReadData.ReadOk(null, null));
+ onSuccess(args, new ReadData.ReadOk(null, null, 0));
}
else
{
diff --git a/accord-core/src/test/java/accord/coordinate/TopologyChangeTest.java b/accord-core/src/test/java/accord/coordinate/TopologyChangeTest.java
index 9c937d1e..f5fd5751 100644
--- a/accord-core/src/test/java/accord/coordinate/TopologyChangeTest.java
+++ b/accord-core/src/test/java/accord/coordinate/TopologyChangeTest.java
@@ -72,7 +72,7 @@ public class TopologyChangeTest
TxnId txnId1 = node1.nextTxnId(Write, Key);
Txn txn1 = writeTxn(keys);
getUninterruptibly(node1.coordinate(txnId1, txn1));
- getUninterruptibly(node1.commandStores().forEach(contextFor(txnId1), keys, 1, 1, safeStore -> {
+ getUninterruptibly(node1.commandStores().forEach(contextFor(txnId1), keys.toParticipants(), 1, 1, safeStore -> {
StoreParticipants participants = StoreParticipants.read(safeStore, keys.toParticipants(), txnId1);
Command command = safeStore.get(txnId1, participants).current();
Assertions.assertTrue(command.partialDeps().isEmpty());
@@ -99,7 +99,7 @@ public class TopologyChangeTest
cluster.nodes(4, 5).forEach(node -> {
try
{
- getUninterruptibly(node.commandStores().forEach(contextFor(txnId1, txnId2), keys, 2, 2, safeStore -> {
+ getUninterruptibly(node.commandStores().forEach(contextFor(txnId1, txnId2), keys.toParticipants(), 2, 2, safeStore -> {
StoreParticipants participants = StoreParticipants.update(safeStore, keys.toParticipants(), txnId2.epoch(), txnId2, txnId2.epoch());
Command command = safeStore.get(txnId2, participants).current();
Assertions.assertTrue(command.partialDeps().contains(txnId1));
diff --git a/accord-core/src/test/java/accord/impl/AbstractConfigurationServiceTest.java b/accord-core/src/test/java/accord/impl/AbstractConfigurationServiceTest.java
index 48e3e73f..03b142d2 100644
--- a/accord-core/src/test/java/accord/impl/AbstractConfigurationServiceTest.java
+++ b/accord-core/src/test/java/accord/impl/AbstractConfigurationServiceTest.java
@@ -91,7 +91,7 @@ public class AbstractConfigurationServiceTest
}
@Override
- public void onEpochRedundant(Ranges ranges, long epoch)
+ public void onEpochRetired(Ranges ranges, long epoch)
{
}
diff --git a/accord-core/src/test/java/accord/impl/TestAgent.java b/accord-core/src/test/java/accord/impl/TestAgent.java
index ec7a9710..089bf5cd 100644
--- a/accord-core/src/test/java/accord/impl/TestAgent.java
+++ b/accord-core/src/test/java/accord/impl/TestAgent.java
@@ -70,7 +70,7 @@ public class TestAgent implements Agent
}
@Override
- public void onHandledException(Throwable t, String context)
+ public void onCaughtException(Throwable t, String context)
{
throw new AssertionError("Unexpected exception", t);
}
@@ -109,7 +109,7 @@ public class TestAgent implements Agent
}
@Override
- public void onHandledException(Throwable t, String context)
+ public void onCaughtException(Throwable t, String context)
{
}
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 b43465e0..770e4a9a 100644
--- a/accord-core/src/test/java/accord/impl/basic/Cluster.java
+++ b/accord-core/src/test/java/accord/impl/basic/Cluster.java
@@ -577,7 +577,7 @@ public class Cluster
{
if (command.txnId().kind() == Txn.Kind.EphemeralRead
|| command.saveStatus() == SaveStatus.Uninitialised
- || command.saveStatus() == SaveStatus.ErasedOrVestigial
+ || command.saveStatus() == SaveStatus.Vestigial
|| command.saveStatus() == SaveStatus.Erased)
return;
@@ -909,7 +909,7 @@ public class Cluster
Command afterCommand = e.getValue().value();
if (beforeCommand == null)
{
- Invariants.checkArgument(afterCommand.is(Status.NotDefined) || afterCommand.saveStatus() == SaveStatus.ErasedOrVestigial);
+ Invariants.checkArgument(afterCommand.is(Status.NotDefined) || afterCommand.saveStatus() == SaveStatus.Vestigial);
continue;
}
if (afterCommand.hasBeen(Status.Truncated))
diff --git a/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java b/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
index 1039adc0..7b210e4a 100644
--- a/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
+++ b/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
@@ -33,10 +33,12 @@ import accord.api.Agent;
import accord.api.Journal;
import accord.api.Result;
import accord.impl.CommandChange;
-import accord.impl.ErasedSafeCommand;
+import accord.impl.RetiredSafeCommand;
import accord.impl.InMemoryCommandStore;
import accord.local.Cleanup;
import accord.local.Command;
+import accord.local.Command.WaitingOnWithExecuteAt;
+import accord.local.Command.WaitingOnWithMinUniqueHlc;
import accord.local.CommandStore;
import accord.local.CommandStores;
import accord.local.Commands;
@@ -63,6 +65,7 @@ import static accord.impl.CommandChange.Field.ACCEPTED;
import static accord.impl.CommandChange.Field.DURABILITY;
import static accord.impl.CommandChange.Field.EXECUTES_AT_LEAST;
import static accord.impl.CommandChange.Field.EXECUTE_AT;
+import static accord.impl.CommandChange.Field.MIN_UNIQUE_HLC;
import static accord.impl.CommandChange.Field.PARTIAL_DEPS;
import static accord.impl.CommandChange.Field.PARTIAL_TXN;
import static accord.impl.CommandChange.Field.PARTICIPANTS;
@@ -71,8 +74,9 @@ import static accord.impl.CommandChange.Field.RESULT;
import static accord.impl.CommandChange.Field.SAVE_STATUS;
import static accord.impl.CommandChange.Field.WAITING_ON;
import static accord.impl.CommandChange.Field.WRITES;
+import static accord.local.Cleanup.Input.FULL;
import static accord.primitives.SaveStatus.Erased;
-import static accord.primitives.SaveStatus.ErasedOrVestigial;
+import static accord.primitives.SaveStatus.Vestigial;
import static accord.primitives.SaveStatus.Stable;
import static accord.primitives.Status.Invalidated;
import static accord.primitives.Status.Truncated;
@@ -107,16 +111,15 @@ public class InMemoryJournal implements Journal
return null;
Builder builder = reconstruct(saved, ALL);
- Cleanup cleanup = builder.shouldCleanup(agent, redundantBefore, durableBefore, false);
+ Cleanup cleanup = builder.shouldCleanup(FULL, agent, redundantBefore, durableBefore);
switch (cleanup)
{
case VESTIGIAL:
- case EXPUNGE_PARTIAL:
- case EXPUNGE:
- return ErasedSafeCommand.erased(txnId, ErasedOrVestigial);
+ return RetiredSafeCommand.erased(txnId, Vestigial);
+ case EXPUNGE:
case ERASE:
- return ErasedSafeCommand.erased(txnId, Erased);
+ return RetiredSafeCommand.erased(txnId, Erased);
}
return builder.construct(redundantBefore);
@@ -129,13 +132,12 @@ public class InMemoryJournal implements Journal
if (builder == null || builder.isEmpty())
return null;
- Cleanup cleanup = builder.shouldCleanup(agent, redundantBefore, durableBefore, false);
+ Cleanup cleanup = builder.shouldCleanup(FULL, agent, redundantBefore, durableBefore);
switch (cleanup)
{
case VESTIGIAL:
- case EXPUNGE_PARTIAL:
- case EXPUNGE:
case ERASE:
+ case EXPUNGE:
return null;
}
@@ -158,6 +160,7 @@ public class InMemoryJournal implements Journal
if (saved == null)
return null;
+ // TODO (expected): match C* and visit in reverse order
Builder builder = null;
for (Diff diff : saved)
{
@@ -311,7 +314,7 @@ public class InMemoryJournal implements Journal
continue; // Already truncated
Command command = builder.construct(store.unsafeGetRedundantBefore());
- Cleanup cleanup = Cleanup.shouldCleanup(store.agent(), command, store.unsafeGetRedundantBefore(), store.durableBefore());
+ Cleanup cleanup = Cleanup.shouldCleanup(FULL, store.agent(), command, store.unsafeGetRedundantBefore(), store.durableBefore());
switch (cleanup)
{
case NO:
@@ -483,9 +486,10 @@ public class InMemoryJournal implements Journal
while (iterable != 0)
{
Field field = nextSetField(iterable);
- if (!getFieldChanged(field, flags) || getFieldIsNull(field, flags))
+ if (isNull(field, flags))
{
- iterable = unsetIterableFields(field, iterable);
+ Invariants.checkState(isChanged(field, flags));
+ iterable = unsetIterable(field, iterable);
continue;
}
@@ -497,6 +501,9 @@ public class InMemoryJournal implements Journal
case EXECUTES_AT_LEAST:
changes.put(EXECUTES_AT_LEAST, after.executesAtLeast());
break;
+ case MIN_UNIQUE_HLC:
+ changes.put(MIN_UNIQUE_HLC, after.waitingOn().minUniqueHlc());
+ break;
case SAVE_STATUS:
changes.put(SAVE_STATUS, after.saveStatus());
break;
@@ -519,8 +526,14 @@ public class InMemoryJournal implements Journal
changes.put(PARTIAL_DEPS, after.partialDeps());
break;
case WAITING_ON:
- Command.WaitingOn waitingOn = getWaitingOn(after);
- changes.put(WAITING_ON, (WaitingOnProvider) (txnId, deps) -> waitingOn);
+ Command.WaitingOn waitingOn = after.waitingOn();
+ changes.put(WAITING_ON, (WaitingOnProvider) (txnId, deps, executeAtLeast, minUniqueHlc) -> {
+ Invariants.checkState(waitingOn.executeAtLeast() == null || waitingOn.executeAtLeast().compareTo(executeAtLeast) <= 0);
+ Invariants.checkState(waitingOn.minUniqueHlc() == 0 || waitingOn.minUniqueHlc() <= minUniqueHlc);
+ if (executeAtLeast != waitingOn.executeAtLeast()) return new WaitingOnWithExecuteAt(waitingOn, executeAtLeast);
+ if (minUniqueHlc != waitingOn.minUniqueHlc()) return new WaitingOnWithMinUniqueHlc(waitingOn, minUniqueHlc);
+ return waitingOn;
+ });
break;
case WRITES:
changes.put(WRITES, after.writes());
@@ -531,7 +544,7 @@ public class InMemoryJournal implements Journal
case CLEANUP:
}
- iterable = unsetIterableFields(field, iterable);
+ iterable = unsetIterable(field, iterable);
}
}
}
@@ -554,22 +567,20 @@ public class InMemoryJournal implements Journal
while (iterable != 0)
{
Field field = nextSetField(iterable);
- if (getFieldChanged(field, diff.flags))
+
+ this.flags = setChanged(field, this.flags);
+ if (isNull(field, diff.flags))
{
- this.flags = setFieldChanged(field, this.flags);
- if (getFieldIsNull(field, diff.flags))
- {
- this.flags = setFieldIsNull(field, this.flags);
- setNull(field);
- }
- else
- {
- this.flags = unsetFieldIsNull(field, this.flags);
- deserialize(diff, field);
- }
+ this.flags = setFieldIsNull(field, this.flags);
+ setNull(field);
+ }
+ else
+ {
+ this.flags = unsetFieldIsNull(field, this.flags);
+ deserialize(diff, field);
}
- iterable = unsetIterableFields(field, iterable);
+ iterable = unsetIterable(field, iterable);
}
}
@@ -583,6 +594,9 @@ public class InMemoryJournal implements Journal
case EXECUTES_AT_LEAST:
executeAtLeast = null;
break;
+ case MIN_UNIQUE_HLC:
+ minUniqueHlc = 0;
+ break;
case SAVE_STATUS:
saveStatus = null;
break;
@@ -628,6 +642,9 @@ public class InMemoryJournal implements Journal
case EXECUTES_AT_LEAST:
executeAtLeast = Invariants.nonNull((Timestamp) diff.changes.get(EXECUTES_AT_LEAST));
break;
+ case MIN_UNIQUE_HLC:
+ minUniqueHlc = (Long)diff.changes.get(MIN_UNIQUE_HLC);
+ break;
case SAVE_STATUS:
saveStatus = Invariants.nonNull((SaveStatus) diff.changes.get(SAVE_STATUS));
break;
diff --git a/accord-core/src/test/java/accord/impl/list/ListAgent.java b/accord-core/src/test/java/accord/impl/list/ListAgent.java
index ddad7c42..d8570cbe 100644
--- a/accord-core/src/test/java/accord/impl/list/ListAgent.java
+++ b/accord-core/src/test/java/accord/impl/list/ListAgent.java
@@ -28,11 +28,11 @@ import java.util.function.LongSupplier;
import accord.api.Agent;
import accord.api.ProgressLog;
import accord.api.Result;
+import accord.coordinate.CoordinationFailed;
import accord.coordinate.ExecuteSyncPoint;
-import accord.coordinate.Preempted;
-import accord.coordinate.Timeout;
import accord.impl.basic.NodeSink;
import accord.impl.basic.Packet;
+import accord.impl.basic.SimulatedFault;
import accord.impl.mock.Network;
import accord.local.Command;
import accord.local.Node;
@@ -120,13 +120,14 @@ public class ListAgent implements Agent
@Override
public void onUncaughtException(Throwable t)
{
- if (!(t instanceof Timeout) && !(t instanceof ExecuteSyncPoint.SyncPointErased) && !(t instanceof Preempted) && !(t instanceof CancellationException) && !(t.getCause() instanceof CancellationException))
+ if (!(t instanceof CoordinationFailed) && !(t instanceof SimulatedFault) && !(t instanceof ExecuteSyncPoint.SyncPointErased) && !(t instanceof CancellationException) && !(t.getCause() instanceof CancellationException))
onFailure.accept(t);
}
@Override
- public void onHandledException(Throwable t, String context)
+ public void onCaughtException(Throwable t, String context)
{
+ onUncaughtException(t);
}
@Override
diff --git a/accord-core/src/test/java/accord/impl/list/ListStore.java b/accord-core/src/test/java/accord/impl/list/ListStore.java
index 7953ce48..1acf796f 100644
--- a/accord-core/src/test/java/accord/impl/list/ListStore.java
+++ b/accord-core/src/test/java/accord/impl/list/ListStore.java
@@ -330,7 +330,7 @@ public class ListStore implements DataStore
public void writeUnsafe(Key key, Timestamped<int[]> value)
{
- data.merge(key,value, ListStore::merge);
+ data.merge(key, value, ListStore::merge);
}
private void checkReadAccess(Timestamp executeAt, Key key)
diff --git a/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java b/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
index 5f54697a..54a89ea8 100644
--- a/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
+++ b/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
@@ -211,13 +211,15 @@ public class CommandsForKeyTest
}
@Override
- public void notWaiting(SafeCommandStore safeStore, TxnId txnId, RoutingKey key)
+ public void notWaiting(SafeCommandStore safeStore, TxnId txnId, RoutingKey key, long uniqueHlc)
{
Command.Committed prev = byId.get(txnId).asCommitted();
Command.WaitingOn.Update waitingOn = new Command.WaitingOn.Update(prev.waitingOn);
if (!waitingOn.removeWaitingOn(key))
return;
+ waitingOn.updateUniqueHlc(prev.executeAt(), uniqueHlc);
+
if (!prev.txnId().kind().awaitsOnlyDeps())
{
for (Command command : committedByExecuteAt.headMap(prev.executeAt(), false).values())
@@ -1038,7 +1040,7 @@ public class CommandsForKeyTest
}
@Override
- public void onHandledException(Throwable t, String context)
+ public void onCaughtException(Throwable t, String context)
{
throw new UnsupportedOperationException();
}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/Json.java b/accord-maelstrom/src/main/java/accord/maelstrom/Json.java
index 202198a4..1ce55b90 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/Json.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/Json.java
@@ -541,7 +541,7 @@ public class Json
in.endArray();
}
in.endArray();
- return new ReadOk(Ranges.EMPTY, result);
+ return new ReadOk(Ranges.EMPTY, result, 0);
}
};
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
index 619b7c6c..8946284c 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
@@ -81,7 +81,7 @@ public class MaelstromAgent implements Agent
}
@Override
- public void onHandledException(Throwable t, String context)
+ public void onCaughtException(Throwable t, String context)
{
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org