You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by ko...@apache.org on 2026/03/08 16:15:30 UTC
(cassandra-accord) 04/07: Introduce Rebootstrap/hard catchup Also: - Soft reject transactions when replicas have a large backlog Fix: - Do not replay pre-bootstrap commands
This is an automated email from the ASF dual-hosted git repository.
konstantinov pushed a commit to branch fixes-260226
in repository https://gitbox.apache.org/repos/asf/cassandra-accord.git
commit 68a94b820dd6fb87abe20016b54a5e9800a125b9
Author: Benedict Elliott Smith <be...@apache.org>
AuthorDate: Thu Jan 15 11:47:28 2026 +0000
Introduce Rebootstrap/hard catchup
Also:
- Soft reject transactions when replicas have a large backlog
Fix:
- Do not replay pre-bootstrap commands
---
accord-core/src/main/java/accord/api/Agent.java | 6 +
.../src/main/java/accord/api/DataStore.java | 28 +-
.../src/main/java/accord/api/ProgressLog.java | 4 +-
.../src/main/java/accord/api/ViolationHandler.java | 4 +-
.../accord/coordinate/CoordinateSyncPoint.java | 1 +
.../accord/coordinate/CoordinateTransaction.java | 55 ++--
.../java/accord/coordinate/ExecuteSyncPoint.java | 6 +-
.../src/main/java/accord/coordinate/Recover.java | 10 +-
.../coordinate/tracking/DurabilityTracker.java | 12 +-
.../main/java/accord/impl/AbstractReplayer.java | 19 +-
.../java/accord/impl/InMemoryCommandStore.java | 6 +-
.../impl/progresslog/DefaultProgressLog.java | 3 +-
.../src/main/java/accord/local/Bootstrap.java | 234 ++---------------
.../src/main/java/accord/local/Catchup.java | 83 +++---
.../src/main/java/accord/local/CatchupHard.java | 176 +++++++++++++
.../src/main/java/accord/local/Command.java | 33 ++-
.../src/main/java/accord/local/CommandStore.java | 63 +++--
.../src/main/java/accord/local/CommandStores.java | 2 +-
.../src/main/java/accord/local/Commands.java | 72 ++++--
.../src/main/java/accord/local/DepsCalculator.java | 24 +-
.../src/main/java/accord/local/DurableBefore.java | 3 +-
.../src/main/java/accord/local/FetchAttempt.java | 287 +++++++++++++++++++++
accord-core/src/main/java/accord/local/Node.java | 7 +
.../main/java/accord/local/RedundantBefore.java | 69 ++++-
.../main/java/accord/local/RedundantStatus.java | 4 +-
.../src/main/java/accord/local/SafeCommand.java | 1 -
.../main/java/accord/local/SafeCommandStore.java | 60 +++--
.../main/java/accord/local/cfk/CommandsForKey.java | 5 +-
.../accord/local/durability/DurabilityQueue.java | 3 +-
.../accord/local/durability/DurabilityRequest.java | 5 -
.../accord/local/durability/DurabilityResult.java | 2 +-
.../accord/local/durability/DurabilityService.java | 45 ++--
.../accord/local/durability/ShardDurability.java | 2 +-
.../src/main/java/accord/messages/Accept.java | 2 +-
.../main/java/accord/messages/BeginRecovery.java | 11 +-
.../src/main/java/accord/messages/CheckStatus.java | 8 +-
.../java/accord/messages/GetEphemeralReadDeps.java | 2 +-
.../src/main/java/accord/messages/PreAccept.java | 2 +-
.../main/java/accord/primitives/AbstractKeys.java | 7 +-
.../java/accord/primitives/AbstractRanges.java | 3 +-
.../src/main/java/accord/primitives/KnownMap.java | 2 +-
.../src/main/java/accord/primitives/Range.java | 2 +-
.../src/main/java/accord/primitives/Timestamp.java | 23 +-
.../src/main/java/accord/utils/Functions.java | 17 ++
.../java/accord/utils/ReducingIntervalMap.java | 10 +
.../main/java/accord/utils/ReducingRangeMap.java | 42 ++-
.../src/main/java/accord/utils/SortedListMap.java | 5 +
.../src/test/java/accord/impl/TestAgent.java | 6 +
.../src/test/java/accord/impl/basic/Cluster.java | 2 +-
.../src/test/java/accord/impl/list/ListAgent.java | 6 +
.../src/test/java/accord/impl/list/ListStore.java | 8 +-
.../src/test/java/accord/impl/mock/MockStore.java | 8 +-
.../java/accord/local/RedundantBeforeTest.java | 2 +
.../src/test/java/accord/local/WaitingOnTest.java | 6 +-
.../java/accord/local/cfk/CommandsForKeyTest.java | 6 +
.../main/java/accord/maelstrom/MaelstromAgent.java | 6 +
.../main/java/accord/maelstrom/MaelstromStore.java | 3 +-
57 files changed, 1068 insertions(+), 455 deletions(-)
diff --git a/accord-core/src/main/java/accord/api/Agent.java b/accord-core/src/main/java/accord/api/Agent.java
index b39d4fae..db5e70b7 100644
--- a/accord-core/src/main/java/accord/api/Agent.java
+++ b/accord-core/src/main/java/accord/api/Agent.java
@@ -78,6 +78,8 @@ public interface Agent extends UncaughtExceptionListener
*
* The number of entries before the candidate prune point that we require before we try to prune.
* This only works to reduce the time wasted pruning when there is limited benefit.
+ *
+ * TODO (desired): come up with a better pruning method
*/
int cfkPruneInterval();
@@ -95,9 +97,13 @@ public interface Agent extends UncaughtExceptionListener
* Controls pruning of MaxConflicts
*
* Every n updates, max conflicts is pruned to the delta, where n is the value returned by this method
+ *
+ * TODO (expected): this isn't a very clean way to prune max conflicts - should be done by size of collection / update rate
*/
long maxConflictsPruneInterval();
+ boolean softReject(long unappliedCount, long cumulativeUnappliedAge);
+
/**
* Create an empty transaction that Accord can use for its own internal transactions.
*/
diff --git a/accord-core/src/main/java/accord/api/DataStore.java b/accord-core/src/main/java/accord/api/DataStore.java
index 74dd68c6..b545066b 100644
--- a/accord-core/src/main/java/accord/api/DataStore.java
+++ b/accord-core/src/main/java/accord/api/DataStore.java
@@ -18,6 +18,8 @@
package accord.api;
+import java.util.Map;
+
import accord.local.CommandStore;
import accord.local.Node;
import accord.local.RedundantBefore;
@@ -25,6 +27,8 @@ import accord.local.SafeCommandStore;
import accord.primitives.Ranges;
import accord.primitives.SyncPoint;
import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.UnhandledEnum;
import accord.utils.async.AsyncResult;
import accord.utils.async.AsyncResults;
@@ -138,7 +142,29 @@ public interface DataStore
* If RequestKind#Sync is used, fetches only a minimal subset of data, assuming there has been some data locally
* (it is to up store's implementer to know how to achieve this)
*/
- FetchResult fetch(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback, FetchKind kind);
+ default FetchResult fetch(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback, FetchKind kind)
+ {
+ switch (kind)
+ {
+ default: throw UnhandledEnum.unknown(kind);
+ case Sync: return sync(node, safeStore, ranges, syncPoint, callback);
+ case Image: return image(node, safeStore, ranges, syncPoint, callback);
+ }
+ }
+
+ FetchResult image(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback);
+
+ default FetchResult sync(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback)
+ {
+ return sync(node, safeStore, Map.of(syncPoint.syncId, ranges), callback);
+ }
+
+ // TODO (desired): standardise on using only TxnId bounds for image/sync, not a full SyncPoint;
+ // leave it to the durability service to ensure the relevant durability via sync point or otherwise
+ default FetchResult sync(Node node, SafeCommandStore safeStore, Map<TxnId, Ranges> atLeast, FetchRanges callback)
+ {
+ throw new UnsupportedOperationException();
+ }
/**
* Logical fsync-like operation: anything within the provided ranges written to the store prior to the
diff --git a/accord-core/src/main/java/accord/api/ProgressLog.java b/accord-core/src/main/java/accord/api/ProgressLog.java
index 29bce360..d5e8d6cf 100644
--- a/accord-core/src/main/java/accord/api/ProgressLog.java
+++ b/accord-core/src/main/java/accord/api/ProgressLog.java
@@ -174,7 +174,7 @@ public interface ProgressLog
/**
* Record an updated local status for the transaction, to clear any waiting state it satisfies.
*/
- void update(SafeCommandStore safeStore, TxnId txnId, Command before, Command after, boolean force);
+ void update(SafeCommandStore safeStore, Command before, Command after, boolean force);
/**
* Process a remote asynchronous callback.
@@ -232,7 +232,7 @@ public interface ProgressLog
class NoOpProgressLog implements ProgressLog
{
- @Override public void update(SafeCommandStore safeStore, TxnId txnId, Command before, Command after, boolean force) {}
+ @Override public void update(SafeCommandStore safeStore, Command before, Command after, boolean force) {}
@Override public void remoteCallback(SafeCommandStore safeStore, SafeCommand safeCommand, SaveStatus remoteStatus, int callbackId, Node.Id from) {}
@Override public void waiting(BlockedUntil blockedUntil, SafeCommandStore safeStore, SafeCommand blockedBy, Route<?> blockedOnRoute, Participants<?> blockedOnParticipants, StoreParticipants participants) {}
@Override public void invalidIfUncommitted(TxnId txnId) {}
diff --git a/accord-core/src/main/java/accord/api/ViolationHandler.java b/accord-core/src/main/java/accord/api/ViolationHandler.java
index 3bb31cba..f7db0510 100644
--- a/accord-core/src/main/java/accord/api/ViolationHandler.java
+++ b/accord-core/src/main/java/accord/api/ViolationHandler.java
@@ -30,7 +30,9 @@ import accord.primitives.Route;
import accord.primitives.Status;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
+import accord.utils.Functions;
+import static accord.utils.Functions.alwaysFalse;
import static accord.utils.Invariants.illegalState;
public interface ViolationHandler
@@ -57,7 +59,7 @@ public interface ViolationHandler
{
message += ". RedundantBefore={";
Participants<?> participants = Participants.merge(Participants.merge(otherParticipants, (Participants)otherRoute), command.route());
- message += safeStore.redundantBefore().foldlWithBounds(participants, (b, m, s, e) -> (m.isEmpty() ? "[" : ", [") + s + ',' + e + "]:" + b, "", ignore -> false) + '}';
+ message += safeStore.redundantBefore().foldlWithBounds(participants, (b, m, s, e) -> (m.isEmpty() ? "[" : ", [") + s + ',' + e + "]:" + b, "", alwaysFalse()) + '}';
}
return message;
}
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
index d3580e2f..d0e93f95 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateSyncPoint.java
@@ -60,6 +60,7 @@ import static accord.messages.Apply.Kind.Maximal;
import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Timestamp.Flag.REJECTED;
import static accord.primitives.Timestamp.mergeMaxAndFlags;
+import static accord.primitives.Timestamp.Flag.SOFT_REJECT;
import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.primitives.TxnId.Cardinality.cardinality;
import static accord.topology.SelectShards.ALL;
diff --git a/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java b/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
index b8719c98..7ad4242a 100644
--- a/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
+++ b/accord-core/src/main/java/accord/coordinate/CoordinateTransaction.java
@@ -70,6 +70,7 @@ import static accord.messages.Accept.Kind.MEDIUM;
import static accord.messages.Accept.Kind.SLOW;
import static accord.primitives.Timestamp.Flag.REJECTED;
import static accord.primitives.Timestamp.mergeMaxAndFlags;
+import static accord.primitives.Timestamp.Flag.SOFT_REJECT;
import static accord.primitives.TxnId.FastPath.PrivilegedCoordinatorWithDeps;
import static accord.topology.SelectShards.LIVE;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
@@ -141,7 +142,22 @@ public class CoordinateTransaction extends CoordinatePreAccept<Result>
node.agent().coordinatorEvents().onRejected(txnId);
return;
}
- else if (tracker.hasFastPathAccepted())
+
+ if (executeAt.is(SOFT_REJECT))
+ {
+ // count soft rejects, and hard reject if too many
+ long count = oks.foldlNonNullValues((ok, v) -> ok.witnessedAt.is(SOFT_REJECT) ? v + 1 : v, 0L);
+ // TODO (expected): make this configurable
+ if (count >= Math.max(2, (oks.size() + 3)/4))
+ {
+ proposeAndCommitInvalidate(node, executor, Ballot.ZERO, txnId, scope.homeKey(), scope, executeAt, finishAndTakeCallback());
+ node.agent().coordinatorEvents().onRejected(txnId);
+ return;
+ }
+ executeAt = executeAt.removeFlag(SOFT_REJECT);
+ }
+
+ if (tracker.hasFastPathAccepted())
{
Deps deps = mergeFastOrMediumDeps(oks);
if (deps != null)
@@ -278,39 +294,26 @@ public class CoordinateTransaction extends CoordinatePreAccept<Result>
StoreParticipants participants = StoreParticipants.update(safeStore, scope, minEpoch, txnId, txnId.epoch());
SafeCommand safeCommand = safeStore.get(txnId, participants);
- ExecuteFlags flags;
+ Timestamp executeAt;
Deps deps;
- if (txnId.is(PrivilegedCoordinatorWithDeps))
+ ExecuteFlags flags;
+ try (DepsCalculator calculator = new DepsCalculator(txnId))
{
- try (DepsCalculator calculator = new DepsCalculator())
- {
- deps = calculator.calculate(safeStore, txnId, participants, minEpoch, txnId, true);
- if (deps == null)
- return PreAcceptNack.INSTANCE;
- flags = calculator.executeFlags(txnId);
- }
-
- Commands.AcceptOutcome outcome = Commands.preaccept(safeStore, safeCommand, participants, txnId, txn, deps, true);
- if (outcome != Success)
+ deps = calculator.calculate(safeStore, txnId, participants, minEpoch, txnId, true);
+ if (deps == null)
return PreAcceptNack.INSTANCE;
- }
- else
- {
- Commands.AcceptOutcome outcome = Commands.preaccept(safeStore, safeCommand, participants, txnId, txn, null, true);
+
+ boolean hasCoordinatorVote = txnId.hasPrivilegedCoordinator();
+ Deps coordinatorDeps = txnId.is(PrivilegedCoordinatorWithDeps) ? deps : null;
+ Commands.AcceptOutcome outcome = Commands.preaccept(safeStore, safeCommand, participants, txnId, txn, coordinatorDeps, hasCoordinatorVote);
if (outcome != Success)
return PreAcceptNack.INSTANCE;
- try (DepsCalculator calculator = new DepsCalculator())
- {
- deps = calculator.calculate(safeStore, txnId, participants, minEpoch, txnId, true);
- if (deps == null)
- return PreAcceptNack.INSTANCE;
- flags = calculator.executeFlags(txnId);
- }
+ executeAt = calculator.executeAt(safeCommand, node);
+ flags = calculator.executeFlags(txnId);
}
- Command command = safeCommand.current();
- return new PreAcceptOk(txnId, command.executeAt(), deps, flags);
+ return new PreAcceptOk(txnId, executeAt, deps, flags);
}
@Override
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java b/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
index 761e72df..3c9f68bb 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteSyncPoint.java
@@ -94,7 +94,7 @@ public class ExecuteSyncPoint extends AbstractCoordination<Route<Range>, Durabil
final DurabilityResult partialResult;
final DurabilityTracker tracker;
final int attempt;
- boolean reportedQuorum, reportedMinorityQuorum;
+ boolean reportedQuorum, reportedMinorityQuorum, knownToSelf;
long retryInFutureEpoch;
protected ExecuteSyncPoint(Node node, SequentialAsyncExecutor executor, Topologies topologies, PartialSyncPoint syncPoint, int attempt, DurabilityResults callback)
@@ -155,6 +155,8 @@ public class ExecuteSyncPoint extends AbstractCoordination<Route<Range>, Durabil
return;
case Waiting:
+ if (from.equals(node.id()))
+ knownToSelf = true;
}
}
else
@@ -258,7 +260,7 @@ public class ExecuteSyncPoint extends AbstractCoordination<Route<Range>, Durabil
DurabilityResult current()
{
- DurabilityResult cur = new DurabilityResult(syncPoint, tracker.results(node.id()), failure());
+ DurabilityResult cur = new DurabilityResult(syncPoint, tracker.results(node.id(), knownToSelf), failure());
if (partialResult == null)
return cur;
return partialResult.min(cur);
diff --git a/accord-core/src/main/java/accord/coordinate/Recover.java b/accord-core/src/main/java/accord/coordinate/Recover.java
index 01f0a50d..e6fad6f1 100644
--- a/accord-core/src/main/java/accord/coordinate/Recover.java
+++ b/accord-core/src/main/java/accord/coordinate/Recover.java
@@ -467,18 +467,18 @@ public class Recover extends AbstractCoordination<FullRoute<?>, Outcome, Recover
case Unknown:
{
// should all be PreAccept
- Deps earlierWait = Deps.merge(okList, okList.size(), List::get, ok -> ok.simpleWait);
- Deps earlierNoWait = Deps.merge(okList, okList.size(), List::get, ok -> ok.simpleNoWait);
- earlierWait = earlierWait.without(earlierNoWait);
+ Deps simpleWait = Deps.merge(okList, okList.size(), List::get, ok -> ok.simpleWait);
+ Deps simpleNoWait = Deps.merge(okList, okList.size(), List::get, ok -> ok.simpleNoWait);
+ simpleWait = simpleWait.without(simpleNoWait);
Deps laterWitnessedCoordRejects = Deps.merge(oks, oks.domainSize(), (map, i) -> selectCoordinatorReplies(map.getKey(i), map.getValue(i)), Function.identity());
- if (!earlierWait.isEmpty() || !laterWitnessedCoordRejects.isEmpty())
+ if (!simpleWait.isEmpty() || !laterWitnessedCoordRejects.isEmpty())
{
// If there exist commands that were proposed a later execution time than us that have not witnessed us,
// we have to be certain these commands have not successfully committed without witnessing us (thereby
// 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.
- awaitToFinish(AsyncChains.reduce(awaitSimple(node, earlierWait, HasCommittedDeps),
+ awaitToFinish(AsyncChains.reduce(awaitSimple(node, simpleWait, HasCommittedDeps),
awaitSupersedingCoord(node, laterWitnessedCoordRejects, CommittedOrNotFastPathCommit, extraCoordVotes),
InferredFastPath::merge)
.invokeIfSuccess((inferred) -> {
diff --git a/accord-core/src/main/java/accord/coordinate/tracking/DurabilityTracker.java b/accord-core/src/main/java/accord/coordinate/tracking/DurabilityTracker.java
index 672e6d0b..09546d83 100644
--- a/accord-core/src/main/java/accord/coordinate/tracking/DurabilityTracker.java
+++ b/accord-core/src/main/java/accord/coordinate/tracking/DurabilityTracker.java
@@ -137,9 +137,13 @@ public class DurabilityTracker extends SimpleTracker<DurabilityTracker.Durabilit
return including.size() + "/" + (shard.rf - exclude.size()) + '(' + shard.rf + ')';
}
- DurabilityLevel result(Node.Id self)
+ DurabilityLevel result(Node.Id self, boolean knownToSelf)
{
- SyncLocal local = including.contains(self) || !shard.nodes.contains(self) ? SyncLocal.Self : SyncLocal.NoLocal;
+ SyncLocal local;
+ if (including.contains(self) || !shard.nodes.contains(self)) local = SyncLocal.Self;
+ else if (knownToSelf) local = SyncLocal.KnownToSelf;
+ else local = SyncLocal.NoLocal;
+
SyncRemote remote;
if (hasSucceeded()) remote = SyncRemote.All;
else if (hasQuorumSuccess()) remote = SyncRemote.Quorum;
@@ -195,7 +199,7 @@ public class DurabilityTracker extends SimpleTracker<DurabilityTracker.Durabilit
return topologies.nodes().without(successes::contains);
}
- public ReducingRangeMap<DurabilityLevel> results(Node.Id self)
+ public ReducingRangeMap<DurabilityLevel> results(Node.Id self, boolean knownToSelf)
{
ReducingRangeMap<DurabilityLevel> result = null;
ReducingRangeMap.Builder<DurabilityLevel> builder = new ReducingRangeMap.Builder<>(trackers.length);
@@ -207,7 +211,7 @@ public class DurabilityTracker extends SimpleTracker<DurabilityTracker.Durabilit
if (tracker == null)
continue;
- builder.appendNoOverlap(tracker.shard.range.start(), tracker.result(self));
+ builder.appendNoOverlap(tracker.shard.range.start(), tracker.result(self, knownToSelf));
builder.appendNoOverlap(tracker.shard.range.end(), null);
}
diff --git a/accord-core/src/main/java/accord/impl/AbstractReplayer.java b/accord-core/src/main/java/accord/impl/AbstractReplayer.java
index 5e97681e..b089dc6a 100644
--- a/accord-core/src/main/java/accord/impl/AbstractReplayer.java
+++ b/accord-core/src/main/java/accord/impl/AbstractReplayer.java
@@ -27,6 +27,7 @@ import accord.local.Command;
import accord.local.CommandStore;
import accord.local.Commands;
import accord.local.RedundantBefore;
+import accord.local.RedundantStatus;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
import accord.local.StoreParticipants;
@@ -42,11 +43,13 @@ import static accord.impl.AbstractReplayer.Replay.TO_COMMAND_STORE;
import static accord.impl.AbstractReplayer.Replay.TO_DATA_STORE;
import static accord.local.RedundantStatus.Property.LOCALLY_DURABLE_TO_COMMAND_STORE;
import static accord.local.RedundantStatus.Property.LOCALLY_DURABLE_TO_DATA_STORE;
+import static accord.local.RedundantStatus.Property.LOG_UNAVAILABLE;
import static accord.primitives.SaveStatus.Applying;
import static accord.primitives.SaveStatus.PreApplied;
import static accord.primitives.SaveStatus.TruncatedApplyWithOutcome;
import static accord.primitives.Status.Applied;
import static accord.primitives.Txn.Kind.Write;
+import static accord.utils.Functions.alwaysFalse;
public abstract class AbstractReplayer implements Journal.Replayer
{
@@ -83,7 +86,7 @@ public abstract class AbstractReplayer implements Journal.Replayer
this.mode = mode;
Invariants.require(redundantBefore.ranges(Objects::nonNull).containsAll(commandStore.unsafeGetRangesForEpoch().all()));
if (mode != Mode.ALL)
- minReplay = redundantBefore.foldl((b, v) -> TxnId.nonNullOrMin(v, replayBound(b)), minReplay, ignore -> false);
+ minReplay = redundantBefore.foldl((b, v) -> TxnId.nonNullOrMin(v, replayBound(b)), minReplay, alwaysFalse());
this.minReplay = TxnId.noneIfNull(minReplay);
}
@@ -100,22 +103,26 @@ public abstract class AbstractReplayer implements Journal.Replayer
{
default: throw new UnhandledEnum(mode);
case ALL: return TO_BOTH;
- case NON_DURABLE: return redundantBefore.foldl(search, (b, v, id) -> v.atMost(replay(b, id)), TO_BOTH, txnId, i -> false);
- case PART_NON_DURABLE: return redundantBefore.foldl(search, (b, v, id) -> v.atLeast(replay(b, id)), NONE, txnId, i -> false);
+ case NON_DURABLE: return redundantBefore.foldl(search, (b, v, id) -> v.atMost(replay(b, id)), TO_BOTH, txnId, alwaysFalse());
+ case PART_NON_DURABLE: return redundantBefore.foldl(search, (b, v, id) -> v.atLeast(replay(b, id)), NONE, txnId, alwaysFalse());
}
}
private static TxnId replayBound(RedundantBefore.Bounds bounds)
{
- return bounds.maxBoundBoth(LOCALLY_DURABLE_TO_COMMAND_STORE, LOCALLY_DURABLE_TO_DATA_STORE);
+ return TxnId.max(bounds.maxBound(LOG_UNAVAILABLE), bounds.maxBoundBoth(LOCALLY_DURABLE_TO_COMMAND_STORE, LOCALLY_DURABLE_TO_DATA_STORE));
}
private static Replay replay(RedundantBefore.Bounds bounds, TxnId txnId)
{
+ RedundantStatus status = bounds.get(txnId, null);
+ if (status.any(LOG_UNAVAILABLE))
+ return NONE;
+
Replay replay = NONE;
- if (bounds.maxBound(LOCALLY_DURABLE_TO_COMMAND_STORE).compareTo(txnId) <= 0)
+ if (!status.all(LOCALLY_DURABLE_TO_COMMAND_STORE))
replay = TO_COMMAND_STORE;
- if (bounds.maxBound(LOCALLY_DURABLE_TO_DATA_STORE).compareTo(txnId) <= 0)
+ if (!status.all(LOCALLY_DURABLE_TO_DATA_STORE))
replay = replay.atLeast(TO_DATA_STORE);
return replay;
}
diff --git a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
index be4a9f59..62651e76 100644
--- a/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
+++ b/accord-core/src/main/java/accord/impl/InMemoryCommandStore.java
@@ -363,7 +363,7 @@ public abstract class InMemoryCommandStore extends CommandStore
if (fail == null)
{
execute((Empty)() -> "Report CommandStore Durable", safeStore -> {
- safeStore.upsertRedundantBefore(onCommandStoreDurable);
+ safeStore.reportDurable(onCommandStoreDurable, 0);
});
}
});
@@ -831,9 +831,9 @@ public abstract class InMemoryCommandStore extends CommandStore
return commandsForRanges;
Invariants.require(context.loadKeysFor() != WRITE);
- // TODO (now): reuse existing loader
MaxDecidedRX maxDecidedRX = commandStore().unsafeGetMaxDecidedRX();
- SummaryLoader loader = SummaryLoader.loader(redundantBefore(), maxDecidedRX, context);
+ SummaryLoader loader = cfrLoad != null ? cfrLoad.loader
+ : SummaryLoader.loader(redundantBefore(), maxDecidedRX, context);
TreeMap<Timestamp, Summary> loaded = new TreeMap<>();
commandStore().commandsForRanges.populateMinFutureRx(loader);
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 ec85d716..c31d3fdf 100644
--- a/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
+++ b/accord-core/src/main/java/accord/impl/progresslog/DefaultProgressLog.java
@@ -225,8 +225,9 @@ public class DefaultProgressLog implements ProgressLog, Consumer<SafeCommandStor
}
@Override
- public void update(SafeCommandStore safeStore, TxnId txnId, Command before, Command after, boolean force)
+ public void update(SafeCommandStore safeStore, Command before, Command after, boolean force)
{
+ TxnId txnId = after.txnId();
if (!txnId.isVisible())
return;
diff --git a/accord-core/src/main/java/accord/local/Bootstrap.java b/accord-core/src/main/java/accord/local/Bootstrap.java
index 891bd1d2..e2d03d02 100644
--- a/accord-core/src/main/java/accord/local/Bootstrap.java
+++ b/accord-core/src/main/java/accord/local/Bootstrap.java
@@ -22,17 +22,11 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-import java.util.function.BiConsumer;
import java.util.function.Consumer;
-import javax.annotation.Nonnull;
-
import accord.api.Agent;
import accord.api.DataStore;
-import accord.api.DataStore.FetchRanges;
-import accord.api.DataStore.FetchResult;
import accord.api.DataStore.FetchKind;
-import accord.api.DataStore.StartingRangeFetch;
import accord.coordinate.CoordinateSyncPoint;
import accord.primitives.Ranges;
import accord.primitives.Routable.Domain;
@@ -41,7 +35,6 @@ import accord.primitives.TxnId;
import accord.primitives.TxnId.Cardinality;
import accord.utils.DeterministicIdentitySet;
import accord.utils.Invariants;
-import accord.utils.ReducingRangeMap;
import accord.utils.async.AsyncResult;
import accord.utils.async.AsyncResults;
@@ -92,28 +85,13 @@ class Bootstrap
}
// an attempt to fetch some portion of the range we are bootstrapping
- class Attempt implements FetchRanges, BiConsumer<Object, Throwable>
+ class Attempt extends FetchAttempt
{
- final DeterministicIdentitySet<UnsafeToRead> unsafeToReads = new DeterministicIdentitySet<>();
- ReducingRangeMap<Timestamp> safeToReadAts = new ReducingRangeMap<>();
-
- Runnable cancel;
- FetchResult fetch;
-
- /**
- * valid: the ranges we are still meant to fetch - i.e. excluding those that have been invalidated or marked failed
- */
- Ranges valid, fetched = Ranges.EMPTY, fetchedAndSafeToRead = Ranges.EMPTY;
- boolean fetchCompleted;
- boolean completed; // we have finished fetching all the data we are able to, but we may still have in-flight fetches
- Throwable fetchOutcome;
TxnId globalSyncId;
- final int attempt;
Attempt(Ranges ranges, int attempt)
{
- this.valid = ranges;
- this.attempt = attempt;
+ super(ranges, attempt);
}
TxnId start(SafeCommandStore safeStore)
@@ -160,133 +138,13 @@ class Bootstrap
return globalSyncId;
}
- // we no longer want to fetch these ranges (perhaps we no longer own them)
- void invalidate(Ranges invalidate)
- {
- FetchResult abort; // the fetch we are coordinating, that may have not started, or may have completed
- Runnable cancel; // the outer future trying to coordinate us, that extends before and after the FetchFuture
- synchronized (this)
- {
- if (!valid.intersects(invalidate))
- return;
-
- valid = valid.without(invalidate);
- abort = fetch;
- // only cancel the outer future if we have no more ranges to fetch
- cancel = valid.isEmpty() ? this.cancel : null;
- if (fetched.containsAll(valid))
- maybeComplete();
- }
- // if we have started the fetch, ask it not to fetch these ranges
- if (abort != null)
- abort.abort(invalidate);
- if (cancel != null)
- cancel.run();
- }
-
- /**
- * our sync point is an inequality, i.e. we may have more data than we want and so before
- * we serve any *reads* we need to make sure we have applied any transaction that might have
- * been included in the data we bootstrapped. to this end we either rely on the implementation
- * to tell us what txnId it included up to, or else initiate a no-op transaction to
- * compute an executeAt from which we can safely begin serving read transactions whose
- * dependencies have all applied
- */
- @Override
- public synchronized StartingRangeFetch starting(Ranges ranges)
- {
- if (!valid.containsAll(ranges))
- throw new IllegalArgumentException();
-
- // mark all ranges unsafe to read
- // TODO (desired): if we have some ranges as safeToRead then we should really invalidate them immediately and not wait to execute under commandStore;
- // could use synchronized to manage updates to these collections
- commandStore.markUnsafeToRead(ranges);
-
- // find any pre-existing states we may overlap with, mark both as overlaps, and add ourselves to the collection
- UnsafeToRead newState = new UnsafeToRead(ranges);
- unsafeToReads.add(newState);
-
- return new StartingRangeFetch()
- {
- @Override
- public DataStore.AbortFetch started(Timestamp maxApplied)
- {
- Attempt.this.started(newState, maxApplied);
- return () -> abort(newState);
- }
-
- @Override
- public void cancel()
- {
- Attempt.this.cancel(newState);
- }
- };
- }
-
- private void started(UnsafeToRead state, @Nonnull Timestamp maxAppliedLessOrEqualTo)
- {
- Invariants.require(maxAppliedLessOrEqualTo != null);
- synchronized (this)
- {
- if (!unsafeToReads.remove(state))
- return;
-
- Timestamp safeToReadAt = maxAppliedLessOrEqualTo.compareTo(globalSyncId) <= 0 ? globalSyncId : maxAppliedLessOrEqualTo.next();
- safeToReadAts = ReducingRangeMap.add(safeToReadAts, state.ranges, safeToReadAt, Timestamp::mergeMax);
- maybeComplete(state.ranges);
- }
- }
-
- // starting cancelled, can just unlink and make sure we invoke onDone on any we may have interfered with
- private synchronized void cancel(UnsafeToRead state)
- {
- if (!unsafeToReads.remove(state))
- throw illegalState("Tried to cancel starting a fetch that had already started");
-
- maybeComplete(state.ranges);
- }
-
- // incomplete fetch cancelled, do we need to do anything?
- // it's fine to leave our no-op to complete, but there might be issues with failure states
- private synchronized void abort(UnsafeToRead state)
- {
- unsafeToReads.remove(state);
- // TODO (expected, consider): are there any edge cases here?
- }
-
@Override
- public synchronized void fetched(Ranges ranges)
+ public void onNewFailure(Throwable failure, Ranges newlyFailed)
{
- if (ranges.isEmpty())
- return;
-
- fetched = fetched.with(ranges);
- maybeComplete(ranges);
- }
-
- @Override
- public void fail(Ranges ranges, Throwable failure)
- {
- boolean hasFailed;
- Ranges newFailures;
- synchronized (this)
- {
- newFailures = ranges.slice(valid, Minimal);
- if (newFailures.isEmpty())
- return;
-
- valid = valid.without(newFailures);
- hasFailed = valid.isEmpty();
- }
-
- if (hasFailed)
- accept(null, failure);
-
Runnable retry = () -> {
node.scheduler().selfRecurring(() -> {
commandStore.execute((PreLoadContext.Empty) () -> "Restart Bootstrap", safeStore -> {
- restart(safeStore, newFailures.slice(allValid, Minimal), attempt + 1);
+ restart(safeStore, newlyFailed.slice(allValid, Minimal), attempt + 1);
}, commandStore.agent());
}, 0L, TimeUnit.NANOSECONDS);
};
@@ -294,88 +152,28 @@ class Bootstrap
reads.tryFailure(failure);
data.tryFailure(failure);
};
- commandStore.agent().ownershipEvents().onFailedBootstrap(attempt, "PartialFetch", newFailures, retry, fail, failure);
- Invariants.require(!newFailures.intersects(fetchedAndSafeToRead));
+ commandStore.agent().ownershipEvents().onFailedBootstrap(attempt, "PartialFetch", newlyFailed, retry, fail, failure);
+ Invariants.require(!newlyFailed.intersects(fetchedAndSafeToRead));
}
- /**
- * Completed successfully or abandoned, we simply process successfully bootstrapped ranges that intersect
- * with this safe-to-read boundary operation, and look to see if there remain newer operations in flight
- * for those ranges; if not, they're done.
- */
- private synchronized void maybeComplete(Ranges ranges)
+ @Override
+ protected AsyncResult<Void> markSafeToRead(Ranges ranges, Timestamp safeToReadAt)
{
- Ranges newDone = fetched.slice(ranges.without(fetchedAndSafeToRead), Minimal);
- if (newDone.isEmpty())
- return;
-
- for (UnsafeToRead unsafeToRead : unsafeToReads)
- newDone = newDone.without(unsafeToRead.ranges);
-
- if (newDone.isEmpty())
- return;
-
- final Ranges safeToRead = newDone;
- List<AsyncResult<Void>> marking = new ArrayList<>();
- safeToReadAts.foldlWithInputAndBounds(newDone, (safeToReadAt, v, start, end, i, j) -> {
- Ranges mark = safeToRead.slice(Ranges.of(start.rangeFactory().newRange(start, end)), Minimal);
- marking.add(commandStore.markSafeToRead(globalSyncId, safeToReadAt, mark));
- return v;
- }, null, i -> false);
-
- AsyncResults.allOf(marking).invoke((success, fail) -> {
- if (fail != null) fail(ranges, fail);
- else
- {
- synchronized (this)
- {
- fetchedAndSafeToRead = fetchedAndSafeToRead.with(safeToRead.slice(valid, Minimal));
- maybeComplete();
- }
- }
- });
+ if (safeToReadAt.compareTo(globalSyncId) < 0)
+ safeToReadAt = globalSyncId;
+ return commandStore.markSafeToRead(globalSyncId, safeToReadAt, ranges);
}
@Override
- public void accept(Object success, Throwable failure)
+ protected void markUnsafeToRead(Ranges ranges)
{
- if (completed)
- return;
-
- // TODO (desired): we shouldn't need this method, as we should have the user implementation invoke us as necessary
- // at most this should interpret failure to account for non-fetch related breakages
- // so as to schedule a retry
- synchronized (this)
- {
- fetchCompleted = true;
- if (failure != null)
- {
- if (fetchOutcome == null) fetchOutcome = failure;
- else fetchOutcome.addSuppressed(failure);
- }
- }
- maybeComplete();
+ commandStore.markUnsafeToRead(ranges);
}
- void maybeComplete()
+ @Override
+ protected void complete(Ranges missing)
{
- Ranges missing;
- synchronized (this)
- {
- if (completed)
- return;
-
- if (!fetchedAndSafeToRead.containsAll(fetchCompleted ? fetched : valid))
- return;
-
- // normalise fetched and fetchedAndSafeToRead against remaining valid ranges before completion
- fetched = fetched.slice(valid, Minimal);
- fetchedAndSafeToRead = fetchedAndSafeToRead.slice(valid, Minimal);
- missing = valid.without(fetchedAndSafeToRead);
- completed = true;
- }
-
- complete(this);
+ Bootstrap.this.complete(this);
if (!missing.isEmpty())
{
Runnable retry = () -> {
diff --git a/accord-core/src/main/java/accord/local/Catchup.java b/accord-core/src/main/java/accord/local/Catchup.java
index 658321d7..88c49085 100644
--- a/accord-core/src/main/java/accord/local/Catchup.java
+++ b/accord-core/src/main/java/accord/local/Catchup.java
@@ -19,9 +19,10 @@
package accord.local;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Objects;
-import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.BiConsumer;
import java.util.function.Consumer;
import org.slf4j.Logger;
@@ -43,7 +44,9 @@ import accord.utils.async.AsyncResults.SettableResult;
import static accord.api.ProgressLog.BlockedUntil.CanApply;
import static accord.local.RedundantStatus.Property.LOCALLY_APPLIED;
+import static accord.local.RedundantStatus.Property.LOCALLY_REDUNDANT;
import static accord.primitives.Routables.Slice.Minimal;
+import static accord.utils.Functions.alwaysFalse;
public class Catchup
{
@@ -81,7 +84,7 @@ public class Catchup
sb.append(range).append(": ").append(entry.quorumBefore);
}
return sb;
- }, new StringBuilder(), ignore -> false));
+ }, new StringBuilder(), alwaysFalse()));
safeStore.register(this);
return true;
}
@@ -124,25 +127,9 @@ public class Catchup
logger.info("{}: {} are retired (or stale)", safeStore.commandStore(), retiredOrStale);
}
- newWaitingOn = durableBefore.foldlWithBounds(newWaitingOn, (DurableBefore.Entry entry, Ranges ranges, RoutingKey entryStart, RoutingKey entryEnd) -> {
- Ranges entryRanges = Ranges.of(Range.create(entryStart, entryEnd));
- return redundantBefore.foldlWithBounds(entryRanges, (RedundantBefore.Bounds bounds, Ranges rs, RoutingKey boundStart, RoutingKey boundEnd) -> {
- TxnId locallyApplied = bounds.maxBound(LOCALLY_APPLIED);
- if (locallyApplied.compareTo(entry.quorumBefore) >= 0)
- {
- Ranges boundRanges = Ranges.of(Range.create(boundStart, boundEnd));
- Ranges caughtUp = rs.slice(boundRanges, Minimal);
- if (!caughtUp.isEmpty())
- {
- rs = rs.without(boundRanges);
- logger.info("{}: caught-up with quorum for {}; {} remaining", safeStore.commandStore(), caughtUp, rs);
- }
- }
- return rs;
- }, ranges, ignore -> false);
- }, newWaitingOn, ignore -> false);
-
- waitingOn = newWaitingOn;
+ waitingOn = removeRedundant(newWaitingOn, durableBefore, redundantBefore, (caughtUp, remaining) -> {
+ logger.info("{}: caught-up with quorum for {}; {} remaining", safeStore.commandStore(), caughtUp, remaining);
+ });
}
@Override
@@ -163,19 +150,55 @@ public class Catchup
}
}
+ static Ranges removeRedundant(Ranges waitingOn, DurableBefore durableBefore, RedundantBefore redundantBefore, BiConsumer<Ranges, Ranges> removedAndRemaining)
+ {
+ return durableBefore.foldlWithBounds(waitingOn, (DurableBefore.Entry entry, Ranges ranges, RoutingKey entryStart, RoutingKey entryEnd) -> {
+ Ranges entryRanges = Ranges.of(Range.of(entryStart, entryEnd));
+ return redundantBefore.foldlWithBounds(entryRanges, (RedundantBefore.Bounds bounds, Ranges rs, RoutingKey boundStart, RoutingKey boundEnd) -> {
+ TxnId locallyRedundant = bounds.maxBound(LOCALLY_REDUNDANT);
+ if (locallyRedundant.compareTo(entry.quorumBefore) >= 0)
+ {
+ Ranges boundRanges = Ranges.of(Range.of(boundStart, boundEnd));
+ Ranges caughtUp = rs.slice(boundRanges, Minimal);
+ if (!caughtUp.isEmpty())
+ {
+ rs = rs.without(boundRanges);
+ removedAndRemaining.accept(caughtUp, rs);
+ }
+ }
+ return rs;
+ }, ranges, alwaysFalse());
+ }, waitingOn, alwaysFalse());
+ }
+
public static AsyncChain<Void> catchup(Node node)
+ {
+ return catchup(node, Arrays.asList(node.commandStores().all()));
+ }
+
+ public static AsyncChain<Void> catchup(Node node, List<CommandStore> commandStores)
{
return FetchDurableBefore.catchup(node).flatMap(durableBefore -> {
- List<AsyncResult<Void>> results = new CopyOnWriteArrayList<>();
- return node.commandStores().forAll("Catchup", safeStore -> {
- CommandStoreListener listener = new CommandStoreListener(durableBefore);
- if (listener.register(safeStore))
- results.add(listener);
- }).flatMap(ignore -> {
- List<AsyncResult<Void>> list = new ArrayList<>(results);
- if (list.isEmpty())
+ List<AsyncChain<CommandStoreListener>> chains = new ArrayList<>();
+ for (CommandStore commandStore : commandStores)
+ {
+ chains.add(commandStore.chain((PreLoadContext.Empty)() -> "Catchup", safeStore -> {
+ CommandStoreListener listener = new CommandStoreListener(durableBefore);
+ if (listener.register(safeStore))
+ return listener;
+ return null;
+ }));
+ }
+ return AsyncChains.allOf(chains).flatMap(listeners -> {
+ List<AsyncResult<Void>> registered = new ArrayList<>(listeners.size());
+ for (CommandStoreListener listener : listeners)
+ {
+ if (listener != null)
+ registered.add(listener);
+ }
+ if (registered.isEmpty())
return AsyncChains.success(null);
- return AsyncResults.reduce(list, Reduce.toNull()).chain();
+ return AsyncResults.reduce(registered, Reduce.toNull()).chain();
});
});
}
diff --git a/accord-core/src/main/java/accord/local/CatchupHard.java b/accord-core/src/main/java/accord/local/CatchupHard.java
new file mode 100644
index 00000000..e94a81c1
--- /dev/null
+++ b/accord-core/src/main/java/accord/local/CatchupHard.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.local;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.DataStore.FetchRanges;
+import accord.coordinate.FetchDurableBefore;
+import accord.local.PreLoadContext.Empty;
+import accord.primitives.Range;
+import accord.primitives.Ranges;
+import accord.primitives.SaveStatus;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.Reduce;
+import accord.utils.ReducingRangeMap;
+import accord.utils.async.AsyncChain;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+import accord.utils.async.AsyncResults.SettableResult;
+
+import static accord.local.RedundantStatus.Property.LOG_UNAVAILABLE;
+import static accord.local.RedundantStatus.SomeStatus.LOG_UNAVAILABLE_ONLY;
+import static accord.primitives.Routables.Slice.Minimal;
+
+/**
+ * Catch up this data store to the point of any quorum
+ */
+public class CatchupHard
+{
+ private static final Logger logger = LoggerFactory.getLogger(CatchupHard.class);
+
+ static class CatchupAttempt extends FetchAttempt
+ {
+ final ReducingRangeMap<TxnId> bounds;
+ final SettableResult<Void> done;
+ final CommandStore commandStore;
+ CatchupAttempt(Ranges ranges, int attempt, ReducingRangeMap<TxnId> bounds, SettableResult<Void> done, CommandStore commandStore)
+ {
+ super(ranges, attempt);
+ this.bounds = bounds;
+ this.done = done;
+ this.commandStore = commandStore;
+ }
+
+ @Override
+ protected AsyncResult<Void> markSafeToRead(Ranges ranges, Timestamp safeToReadAt)
+ {
+ List<AsyncResult<Void>> results = bounds.foldlWithBounds(ranges, (bound, rs, start, end) -> {
+ Timestamp safe = safeToReadAt.compareTo(bound) > 0 ? safeToReadAt : bound;
+ rs.add(commandStore.markSafeToRead(bound, safe, Ranges.of(Range.of(start, end))));
+ return rs;
+ }, new ArrayList<>());
+ return AsyncResults.reduce(results, Reduce.toNull());
+ }
+
+ @Override
+ protected void markUnsafeToRead(Ranges ranges)
+ {
+ commandStore.markUnsafeToRead(ranges);
+ }
+
+ @Override
+ protected void complete(Ranges missing)
+ {
+ if (missing.isEmpty()) done.trySuccess(null);
+ else done.tryFailure(new RuntimeException(missing + " could not be caught-up", fetchOutcome));
+ }
+ }
+
+ private static AsyncResult<Void> start(Node node, SafeCommandStore safeStore, DurableBefore durableBefore)
+ {
+ RedundantBefore redundantBefore = safeStore.redundantBefore();
+ Ranges catchUp;
+ {
+ Ranges tmp = safeStore.ranges().all().slice(durableBefore.ranges(Objects::nonNull), Minimal).mergeTouching();
+ tmp = redundantBefore.removeLostOrStale(tmp);
+ catchUp = Catchup.removeRedundant(tmp, durableBefore, redundantBefore, (caughtUp, remaining) -> {});
+ }
+
+ if (catchUp.isEmpty())
+ {
+ logger.info("No ranges to catchup with quorums");
+ return AsyncResults.success(null);
+ }
+
+ logger.info("Catching up {} with quorums", catchUp);
+ RedundantBefore upsert = durableBefore.foldlWithBounds(catchUp, (e, builder, start, end) -> {
+ Ranges ranges = Ranges.of(Range.of(start, end)).slice(catchUp, Minimal);
+ for (Range range : ranges)
+ builder.append(start, end, RedundantBefore.Bounds.create(range, e.quorumBefore, LOG_UNAVAILABLE_ONLY, null));
+ return builder;
+ }, new RedundantBefore.Builder(catchUp.size())).build();
+
+ ReducingRangeMap<TxnId> bounds = upsert.map(b -> b.maxBound(LOG_UNAVAILABLE), TxnId[]::new);
+
+ Map<TxnId, Ranges> rangesByBound = bounds.foldlWithBounds((t, map, start, end) -> {
+ map.merge(t, Ranges.of(Range.of(start, end)), Ranges::with);
+ return map;
+ }, new HashMap<>());
+
+ safeStore.commandStore().markUnsafeToRead(catchUp);
+ safeStore.upsertRedundantBefore(upsert);
+
+ AsyncResults.SettableResult<Void> synced = new SettableResult<>();
+ FetchRanges fetch = new CatchupAttempt(catchUp, 1, bounds, synced, safeStore.commandStore());
+ safeStore.dataStore().sync(node, safeStore, rangesByBound, fetch);
+
+ CommandStore commandStore = safeStore.commandStore();
+ return synced.flatMap(ignore -> maybeExecuteBounds(commandStore, rangesByBound.keySet()).beginAsResult());
+ }
+
+ private static AsyncChain<Void> maybeExecuteBounds(CommandStore commandStore, Collection<TxnId> bounds)
+ {
+ logger.info("Refreshing and maybe executing hard catchup bounds {}", bounds);
+ List<AsyncChain<Void>> chains = new ArrayList<>(bounds.size());
+ for (TxnId txnId : bounds)
+ {
+ chains.add(commandStore.chain(PreLoadContext.contextFor(txnId,"Mark CatchupHard bounds applied"), safeStore -> {
+ SafeCommand safeCommand = safeStore.get(txnId);
+ Command command = safeCommand.current();
+ if (command.saveStatus() == SaveStatus.PreApplied)
+ {
+ Commands.removeRedundantDependencies(safeStore, safeCommand);
+ Commands.maybeExecute(safeStore, safeCommand, false, true);
+ }
+ }));
+ }
+ return AsyncChains.reduce(chains, Reduce.toNull());
+ }
+
+ public static AsyncChain<Void> catchup(Node node)
+ {
+ return catchup(node, Arrays.asList(node.commandStores().all()));
+ }
+
+ public static AsyncChain<Void> catchup(Node node, List<CommandStore> commandStores)
+ {
+ return FetchDurableBefore.catchup(node).flatMap(durableBefore -> {
+ List<AsyncChain<Void>> chains = new ArrayList<>();
+ for (CommandStore commandStore : commandStores)
+ {
+ chains.add(commandStore.chain((Empty)() -> "Catchup", safeStore -> {
+ return start(node, safeStore, durableBefore);
+ }).flatMapResult(i -> i));
+ }
+ return AsyncChains.reduce(chains, Reduce.toNull());
+ });
+ }
+}
diff --git a/accord-core/src/main/java/accord/local/Command.java b/accord-core/src/main/java/accord/local/Command.java
index 216595ba..335bcece 100644
--- a/accord-core/src/main/java/accord/local/Command.java
+++ b/accord-core/src/main/java/accord/local/Command.java
@@ -282,6 +282,9 @@ public abstract class Command implements ICommand
return route == null ? null : route.homeKey();
}
+ // TODO (expected): rename to e.g. timestamp(),
+ // and introduce executeAt() that first ensures it is >= precommitted,
+ // and applyAt() that confirms >= PreApplied
@Override
public final Timestamp executeAt() { return executeAt; }
@@ -971,18 +974,30 @@ public abstract class Command implements ICommand
return index >= 0 && waitingOn.get(index);
}
- public TxnId nextWaitingOn()
+ public TxnId nextWaitingOnTxn()
{
- int i = nextWaitingOnIndex();
+ int i = nextWaitingOnTxnIndex();
return i < 0 ? null : txnId(i);
}
- private int nextWaitingOnIndex()
+ private int nextWaitingOnTxnIndex()
{
int directRangeTxnIdCount = directRangeDeps.txnIdCount();
return waitingOn.prevSetBit(directRangeTxnIdCount);
}
+ public TxnId minWaitingOnTxn()
+ {
+ int index = minWaitingOnTxnIndex();
+ return index < 0 ? null : txnId(index);
+ }
+
+ public int minWaitingOnTxnIndex()
+ {
+ int directRangeTxnIdCount = directRangeDeps.txnIdCount();
+ return waitingOn.nextSetBitBefore(0, directRangeTxnIdCount);
+ }
+
@Override
public String toString()
{
@@ -1102,7 +1117,7 @@ public abstract class Command implements ICommand
Ranges removed = all.without(ranges.rangesAtIndex(i));
while (txnIdx >= 0 && rDeps.txnId(txnIdx).epoch() >= epoch)
{
- if (!rDeps.txnId(txnIdx).isSyncPoint() && initialise.isWaitingOnDirectRangeTxnIdx(txnIdx))
+ if (!rDeps.txnId(txnIdx).isSyncPoint() && initialise.isWaitingOnTxnIndex(txnIdx))
{
Ranges rs = rDeps.ranges(txnIdx).slice(all, Slice.Minimal);
if (removed.containsAll(rs))
@@ -1177,7 +1192,7 @@ public abstract class Command implements ICommand
public boolean hasUpdatedDirectDependency(WaitingOn prev)
{
- int i = prev.nextWaitingOnIndex();
+ int i = prev.nextWaitingOnTxnIndex();
return i >= 0 && !waitingOn.get(i);
}
@@ -1207,19 +1222,19 @@ public abstract class Command implements ICommand
return !waitingOn.isEmpty();
}
- public TxnId minWaitingOnTxnId()
+ public TxnId minWaitingOnTxn()
{
- int index = minWaitingOnTxnIdx();
+ int index = minWaitingOnTxnIndex();
return index < 0 ? null : txnId(index);
}
- public int minWaitingOnTxnIdx()
+ public int minWaitingOnTxnIndex()
{
int directRangeTxnIdCount = directRangeDeps.txnIdCount();
return waitingOn.nextSetBitBefore(0, directRangeTxnIdCount);
}
- public boolean isWaitingOnDirectRangeTxnIdx(int idx)
+ public boolean isWaitingOnTxnIndex(int idx)
{
Invariants.requireIndex(idx, directRangeDeps.txnIdCount());
return waitingOn.get(idx);
diff --git a/accord-core/src/main/java/accord/local/CommandStore.java b/accord-core/src/main/java/accord/local/CommandStore.java
index c543b622..240281f3 100644
--- a/accord-core/src/main/java/accord/local/CommandStore.java
+++ b/accord-core/src/main/java/accord/local/CommandStore.java
@@ -72,8 +72,10 @@ import accord.utils.async.Cancellable;
import accord.utils.async.AsyncResults.SettableResult;
import org.agrona.collections.LongHashSet;
+import static accord.api.DataStore.FetchKind.Sync;
import static accord.local.RedundantStatus.Property.LOCALLY_APPLIED;
import static accord.local.RedundantStatus.Property.UNREADY;
+import static accord.local.durability.DurabilityService.SyncLocal.KnownToSelf;
import static accord.topology.EpochReady.DONE;
import static accord.topology.EpochReady.done;
import static accord.api.DataStore.FetchKind.Image;
@@ -193,6 +195,9 @@ public abstract class CommandStore implements AbstractAsyncExecutor, SequentialA
final Ranges allRanges;
Ranges waitingOn, waitingOnDurable;
+ // for testing only
+ volatile boolean invalid;
+
WaitingOnVisibility(SettableResult<Void> whenDone, Ranges ranges)
{
this.whenDone = whenDone;
@@ -243,6 +248,7 @@ public abstract class CommandStore implements AbstractAsyncExecutor, SequentialA
maxDecidedRX = MaxDecidedRX.EMPTY;
safeToRead = emptySafeToRead();
listeners.clear();
+ waitingOnVisibility.values().forEach(w -> w.invalid = true);
waitingOnVisibility.clear();
}
@@ -651,6 +657,12 @@ public abstract class CommandStore implements AbstractAsyncExecutor, SequentialA
}
}
+ public AsyncResult<?> rebootstrap(Node node)
+ {
+ RangesForEpoch rfe = unsafeGetRangesForEpoch();
+ return startUnsafeBootstrap(node, rfe.all(), rfe.epochAtIndex(rfe.size() - 1), Sync);
+ }
+
private EpochReady epochReadyAfterBootstrap(Ranges newRanges, long epoch, AsyncResult<EpochReady> bootstrap)
{
return epochReadyAfterBootstrap(newRanges, epoch, EpochReady.wrap(epoch, bootstrap));
@@ -783,37 +795,40 @@ public abstract class CommandStore implements AbstractAsyncExecutor, SequentialA
WaitingOnVisibility prev = waitingOnVisibility.putIfAbsent(epoch, sync);
Invariants.require(prev == null);
}
- ensureReadyToCoordinate(epoch, ranges);
+ ensureReadyToCoordinate(epoch, ranges, sync);
return whenDone;
}
- private void ensureReadyToCoordinate(long epoch, Ranges ranges)
+ private void ensureReadyToCoordinate(long epoch, Ranges ranges, WaitingOnVisibility waiting)
{
- TxnId minForEpoch = TxnId.minForEpoch(epoch);
- node.durability().close("[" + this + " Epoch " + epoch + ']', VisibilitySyncPoint, minForEpoch, ranges, 1, TimeUnit.HOURS)
+ TxnId min = TxnId.nonNullOrMax(TxnId.minForEpoch(epoch), redundantBefore.max(ranges, b -> b == null ? TxnId.NONE : b.maxBound(RedundantStatus.Property.LOG_UNAVAILABLE)));
+ node.durability().close("[" + this + " Epoch " + epoch + ']', VisibilitySyncPoint, min, ranges, KnownToSelf, 1, TimeUnit.HOURS)
.invoke((success, fail) -> {
- if (fail != null)
+ if (waiting.invalid)
+ return;
+
+ Ranges notRetired = redundantBefore.removeLocallyRetired(ranges);
+ Ranges retired = ranges.without(notRetired);
+ Ranges remaining = redundantBefore.removeWitnessed(min, notRetired);
+
+ if (!retired.isEmpty())
+ {
+ logger.info("{}, Failed to close epoch {} for ranges {}, but some are retired; marking these as synced.", this, epoch, ranges, fail);
+ execute((Empty)() -> "Mark Retired Ranges Synced", safeStore -> {
+ markVisibleInternal(safeStore, epoch, retired, "(Retired)");
+ }, agent);
+ }
+ else if (remaining.isEmpty())
{
- Ranges notRetired = redundantBefore.removeRetired(ranges);
- Ranges retired = ranges.without(notRetired);
- Ranges remaining = redundantBefore.removeWitnessed(minForEpoch, notRetired);
+ if (fail != null)
+ logger.info("{}, Failed to close epoch {} for ranges {}, but none remaining. Aborting.", this, epoch, ranges, fail);
+ }
- if (!retired.isEmpty())
- {
- logger.info("Failed to close epoch {} for ranges {} on store {}, but some are retired; marking these as synced.", epoch, ranges, id, fail);
- execute((Empty)() -> "Mark Retired Ranges Synced", safeStore -> {
- markVisibleInternal(safeStore, epoch, retired, "(Retired)");
- }, agent);
- }
- else if (remaining.isEmpty())
- {
- logger.info("Failed to close epoch {} for ranges {} on store {}, but none remaining. Aborting.", epoch, ranges, id, fail);
- }
- if (!remaining.isEmpty())
- {
- logger.warn("Failed to close epoch {} for ranges {} on store {}. Retrying.", epoch, remaining, id, fail);
- node.someExecutor().execute(() -> ensureReadyToCoordinate(epoch, remaining));
- }
+ if (!remaining.isEmpty())
+ {
+ if (fail != null) logger.warn("{} Failed to close epoch {} for ranges {}. Retrying.", this, epoch, remaining, fail);
+ else logger.error("{} DurabilityRequest completed successfully, but still awaiting visibility for ranges: {} on epoch {}. Retrying.", this, remaining, epoch);
+ node.someExecutor().execute(() -> ensureReadyToCoordinate(epoch, remaining, waiting));
}
});
}
diff --git a/accord-core/src/main/java/accord/local/CommandStores.java b/accord-core/src/main/java/accord/local/CommandStores.java
index 29bc2867..b1eca072 100644
--- a/accord-core/src/main/java/accord/local/CommandStores.java
+++ b/accord-core/src/main/java/accord/local/CommandStores.java
@@ -724,7 +724,7 @@ public abstract class CommandStores implements AsyncExecutorFactory
results.add(shard.store.startUnsafeBootstrap(node, shard.ranges.all(), snapshot.global.epoch(), Sync));
return AsyncResults.allOf(results).flatMap(list -> {
return AsyncChains.reduce(list.stream()
- .flatMap(b -> Stream.of(b.reads.chain(), b.coordinate.chain()))
+ .map(b -> b.reads.chain())
.collect(Collectors.toList()),
Reduce.toNull()).beginAsResult();
});
diff --git a/accord-core/src/main/java/accord/local/Commands.java b/accord-core/src/main/java/accord/local/Commands.java
index f5348aa9..eb91362d 100644
--- a/accord-core/src/main/java/accord/local/Commands.java
+++ b/accord-core/src/main/java/accord/local/Commands.java
@@ -779,14 +779,18 @@ public class Commands
return false;
}
- WaitingOn waitingOn = command.asCommitted().waitingOn();
+ WaitingOn waitingOn = command.waitingOn();
if (waitingOn.isWaiting())
{
- if (alwaysNotifyListeners)
- safeStore.notifyListeners(safeCommand, command);
+ if (!removeRedundantDependencies(safeStore, safeCommand) || waitingOn.isWaiting())
+ {
+ if (alwaysNotifyListeners)
+ safeStore.notifyListeners(safeCommand, command);
+
+ if (notifyWaitingOn && waitingOn.isWaitingOnCommand())
+ adapter.notifyWaiting(safeStore, safeCommand);
+ }
- if (notifyWaitingOn && waitingOn.isWaitingOnCommand())
- adapter.notifyWaiting(safeStore, safeCommand);
return false;
}
@@ -836,8 +840,8 @@ public class Commands
protected static Update updateWaitingOn(SafeCommandStore safeStore, ICommand waiting, Timestamp executeAt, WaitingOn.Update initialise)
{
RedundantBefore redundantBefore = safeStore.redundantBefore();
- TxnId minWaitingOnTxnId = initialise.minWaitingOnTxnId();
- if (minWaitingOnTxnId != null && redundantBefore.hasLocallyRedundantDependencies(initialise.minWaitingOnTxnId(), executeAt, waiting.participants().waitsOn()))
+ TxnId minWaitingOnTxnId = initialise.minWaitingOnTxn();
+ if (minWaitingOnTxnId != null && redundantBefore.hasLocallyRedundantDependencies(initialise.minWaitingOnTxn(), executeAt, waiting.participants().waitsOn()))
redundantBefore.removeRedundantDependencies(waiting.participants().waitsOn(), initialise);
initialise.forEachWaitingOnId(safeStore, initialise, waiting, executeAt, (store, upd, w, exec, i) -> {
@@ -856,7 +860,6 @@ public class Commands
if (safeCfk.current().hasUniqueHlcAndIsReadyToExecute(cmd.txnId(), cmd.executeAt(), cmd.partialDeps()))
upd.removeWaitingOnKey(i);
-
});
return initialise;
@@ -922,7 +925,7 @@ public class Commands
Participants<?> waitsOn = participants.intersecting(waiting.participants().stillWaitsOn(), Minimal);
RedundantStatus status = safeStore.redundantBefore().status(dependencyId, waitingExecuteAt, waitsOn);
- if (status.all(LOCALLY_DEFUNCT))
+ if (waitsOn.isEmpty() || status.all(LOCALLY_DEFUNCT))
return false;
throw illegalState("We have a dependency (" + dependency + ") to wait on, but have already finished waiting (" + waiting + ")");
@@ -949,7 +952,7 @@ public class Commands
Command pred = predecessor.current();
if (pred.hasBeen(PreCommitted))
{
- TxnId nextWaitingOn = command.waitingOn().nextWaitingOn();
+ TxnId nextWaitingOn = command.waitingOn().nextWaitingOnTxn();
if (nextWaitingOn != null && nextWaitingOn.equals(pred.txnId()) && !pred.hasBeen(PreApplied))
safeStore.progressLog().waiting(CanApply, safeStore, predecessor, null, null, null);
}
@@ -1253,6 +1256,10 @@ public class Commands
if (depSafe == null) // TODO (required): slice to waiting.participants().waitsOn? can simplify method
depSafe = initialiseOrRemoveDependency(safeStore, waitingSafe, loadDepId, partialDeps.participants(loadDepId));
}
+ else
+ {
+ removeRedundantDependencies(safeStore, waitingSafe);
+ }
while (true)
{
@@ -1263,7 +1270,7 @@ public class Commands
if (depSafe == null)
{
WaitingOn waitingOn = waiting.waitingOn();
- TxnId directlyBlockedOn = waitingOn.nextWaitingOn();
+ TxnId directlyBlockedOn = waitingOn.nextWaitingOnTxn();
if (directlyBlockedOn == null)
{
if (waitingOn.isWaiting())
@@ -1527,20 +1534,47 @@ public class Commands
}
}
- static void removeRedundantDependencies(SafeCommandStore safeStore, SafeCommand safeCommand, @Nullable TxnId redundant)
+ static boolean removeRedundantDependencies(SafeCommandStore safeStore, SafeCommand safeCommand)
{
- Command.Committed current = safeCommand.current().asCommitted();
+ Update update = maybeRemoveRedundantDependencies(safeStore, safeCommand);
+ if (update == null)
+ return false;
- RedundantBefore redundantBefore = safeStore.redundantBefore();
- Update update = new Update(current.waitingOn);
- TxnId minWaitingOnTxnId = update.minWaitingOnTxnId();
- if (minWaitingOnTxnId != null && redundantBefore.hasLocallyRedundantDependencies(update.minWaitingOnTxnId(), current.executeAt(), current.participants().waitsOn()))
- redundantBefore.removeRedundantDependencies(current.participants().waitsOn(), update);
+ safeCommand.updateWaitingOn(safeStore, update);
+ return true;
+ }
+
+ static boolean removeRedundantDependencies(SafeCommandStore safeStore, SafeCommand safeCommand, @Nullable TxnId redundant)
+ {
+ Update update = maybeRemoveRedundantDependencies(safeStore, safeCommand);
- // if we are a range transaction, being redundant for this transaction does not imply we are redundant for all transactions
if (redundant != null)
+ {
+ if (update == null)
+ update = new Update(safeCommand.current().waitingOn());
update.removeWaitingOn(redundant);
+ }
+
+ if (update == null)
+ return false;
+
safeCommand.updateWaitingOn(safeStore, update);
+ return true;
+ }
+
+ private static Update maybeRemoveRedundantDependencies(SafeCommandStore safeStore, SafeCommand safeCommand)
+ {
+ RedundantBefore redundantBefore = safeStore.redundantBefore();
+ Command command = safeCommand.current();
+ WaitingOn waitingOn = command.waitingOn();
+ TxnId minWaitingOnTxnId = waitingOn.minWaitingOnTxn();
+ Participants<?> waitsOn = command.participants().waitsOn();
+ if (minWaitingOnTxnId == null || !redundantBefore.hasLocallyRedundantDependencies(minWaitingOnTxnId, command.executeAt(), waitsOn))
+ return null;
+
+ Update update = new Update(waitingOn);
+ redundantBefore.removeRedundantDependencies(waitsOn, update);
+ return update;
}
static void removeNoLongerOwnedDependency(SafeCommandStore safeStore, SafeCommand safeCommand, @Nonnull TxnId wasOwned)
diff --git a/accord-core/src/main/java/accord/local/DepsCalculator.java b/accord-core/src/main/java/accord/local/DepsCalculator.java
index 66f13435..e96e83eb 100644
--- a/accord-core/src/main/java/accord/local/DepsCalculator.java
+++ b/accord-core/src/main/java/accord/local/DepsCalculator.java
@@ -80,12 +80,15 @@ public class DepsCalculator extends Deps.Builder implements CommandSummaries.Act
// TODO (expected): we can also track whether we have only single-key writes that have been Accepted with ballot 0 (or timestamp != t0), or else Committed[1];
// in this case we can decide immediately if we have a unique hlc as we don't run the risk of other keys inserting some arbitrary timestamp
// [1] probably unsafe to use Accepted with ballot > 0, as there could be a timestamp battle, and the timestamp we see might not be the one that gets decided.
- private boolean hasUnappliedDependency;
+ private final long now;
+ private long unappliedAge;
+ private int unappliedCount;
private long maxAppliedHlc;
- public DepsCalculator()
+ public DepsCalculator(Timestamp timestamp)
{
super(true);
+ this.now = timestamp.hlc();
}
@Override
@@ -97,7 +100,10 @@ public class DepsCalculator extends Deps.Builder implements CommandSummaries.Act
if (self == null || !self.equals(depId))
add(keyOrRange, depId);
if (status.compareTo(APPLIED) < 0)
- hasUnappliedDependency = true;
+ {
+ unappliedCount += 1;
+ unappliedAge += Math.max(0, now - depId.hlc());
+ }
}
@Override
@@ -110,7 +116,7 @@ public class DepsCalculator extends Deps.Builder implements CommandSummaries.Act
public ExecuteFlags executeFlags(TxnId txnId)
{
ExecuteFlags flags = ExecuteFlags.none();
- if (!hasUnappliedDependency)
+ if (unappliedCount == 0)
{
flags = flags.with(READY_TO_EXECUTE);
// we don't know whether hlc is unique unless dependencies have applied
@@ -120,6 +126,14 @@ public class DepsCalculator extends Deps.Builder implements CommandSummaries.Act
return flags;
}
+ public Timestamp executeAt(SafeCommand safeCommand, Node node)
+ {
+ Timestamp executeAt = safeCommand.current().executeAt();
+ if (unappliedCount > 0 && node.agent().softReject(unappliedCount, unappliedAge))
+ executeAt = executeAt.addFlag(Timestamp.Flag.SOFT_REJECT);
+ return executeAt;
+ }
+
public Deps calculate(SafeCommandStore safeStore, TxnId txnId, StoreParticipants participants, long minEpoch, Timestamp executeAt, boolean nullIfRedundant)
{
return calculate(safeStore, txnId, participants.touches(), minEpoch, executeAt, nullIfRedundant);
@@ -162,7 +176,7 @@ public class DepsCalculator extends Deps.Builder implements CommandSummaries.Act
public static Deps calculateDeps(SafeCommandStore safeStore, TxnId txnId, Participants<?> touches, long minEpoch, Timestamp executeAt, boolean nullIfRedundant)
{
- try (DepsCalculator calculator = new DepsCalculator())
+ try (DepsCalculator calculator = new DepsCalculator(executeAt))
{
return calculator.calculate(safeStore, txnId, touches, minEpoch, executeAt, nullIfRedundant);
}
diff --git a/accord-core/src/main/java/accord/local/DurableBefore.java b/accord-core/src/main/java/accord/local/DurableBefore.java
index e7856416..fb11203a 100644
--- a/accord-core/src/main/java/accord/local/DurableBefore.java
+++ b/accord-core/src/main/java/accord/local/DurableBefore.java
@@ -37,6 +37,7 @@ import accord.utils.async.AsyncResults;
import static accord.primitives.Status.Durability.HasOutcome.None;
import static accord.primitives.Status.Durability.HasOutcome.Quorum;
import static accord.primitives.Status.Durability.HasOutcome.Universal;
+import static accord.utils.Functions.alwaysFalse;
public class DurableBefore extends ReducingRangeMap<DurableBefore.Entry>
{
@@ -213,7 +214,7 @@ public class DurableBefore extends ReducingRangeMap<DurableBefore.Entry>
public long maxEpoch()
{
- return foldl((e, v) -> TxnId.max(v, TxnId.max(e.quorumBefore, e.universalBefore)), TxnId.NONE, i -> false).epoch();
+ return foldl((e, v) -> TxnId.max(v, TxnId.max(e.quorumBefore, e.universalBefore)), TxnId.NONE, alwaysFalse()).epoch();
}
private static HasOutcome notDurableIfNull(HasOutcome status)
diff --git a/accord-core/src/main/java/accord/local/FetchAttempt.java b/accord-core/src/main/java/accord/local/FetchAttempt.java
new file mode 100644
index 00000000..2ecc06ae
--- /dev/null
+++ b/accord-core/src/main/java/accord/local/FetchAttempt.java
@@ -0,0 +1,287 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.local;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.BiConsumer;
+
+import javax.annotation.Nonnull;
+
+import accord.api.DataStore;
+import accord.api.DataStore.FetchResult;
+import accord.primitives.Ranges;
+import accord.primitives.Timestamp;
+import accord.utils.DeterministicIdentitySet;
+import accord.utils.Invariants;
+import accord.utils.ReducingRangeMap;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+import static accord.primitives.Routables.Slice.Minimal;
+import static accord.utils.Functions.alwaysFalse;
+import static accord.utils.Invariants.illegalState;
+
+abstract class FetchAttempt implements DataStore.FetchRanges, BiConsumer<Object, Throwable>
+{
+ static class UnsafeToRead
+ {
+ final Ranges ranges;
+
+ UnsafeToRead(Ranges ranges)
+ {
+ this.ranges = ranges;
+ }
+ }
+
+ final DeterministicIdentitySet<UnsafeToRead> unsafeToReads = new DeterministicIdentitySet<>();
+ ReducingRangeMap<Timestamp> safeToReadAts;
+
+ Runnable cancel;
+ FetchResult fetch;
+
+ /**
+ * valid: the ranges we are still meant to fetch - i.e. excluding those that have been invalidated or marked failed
+ */
+ Ranges valid, fetched = Ranges.EMPTY, fetchedAndSafeToRead = Ranges.EMPTY;
+ boolean fetchCompleted;
+ boolean completed; // we have finished fetching all the data we are able to, but we may still have in-flight fetches
+ Throwable fetchOutcome;
+ final int attempt;
+
+ FetchAttempt(Ranges ranges, int attempt)
+ {
+ this.valid = ranges;
+ this.attempt = attempt;
+ }
+
+ // we no longer want to fetch these ranges (perhaps we no longer own them)
+ protected void invalidate(Ranges invalidate)
+ {
+ FetchResult abort; // the fetch we are coordinating, that may have not started, or may have completed
+ Runnable cancel; // the outer future trying to coordinate us, that extends before and after the FetchFuture
+ synchronized (this)
+ {
+ if (!valid.intersects(invalidate))
+ return;
+
+ valid = valid.without(invalidate);
+ abort = fetch;
+ // only cancel the outer future if we have no more ranges to fetch
+ cancel = valid.isEmpty() ? this.cancel : null;
+ if (fetched.containsAll(valid))
+ maybeComplete();
+ }
+ // if we have started the fetch, ask it not to fetch these ranges
+ if (abort != null)
+ abort.abort(invalidate);
+ if (cancel != null)
+ cancel.run();
+ }
+
+ /**
+ * our sync point is an inequality, i.e. we may have more data than we want and so before
+ * we serve any *reads* we need to make sure we have applied any transaction that might have
+ * been included in the data we bootstrapped. to this end we either rely on the implementation
+ * to tell us what txnId it included up to, or else initiate a no-op transaction to
+ * compute an executeAt from which we can safely begin serving read transactions whose
+ * dependencies have all applied
+ */
+ @Override
+ public synchronized DataStore.StartingRangeFetch starting(Ranges ranges)
+ {
+ if (!valid.containsAll(ranges))
+ throw new IllegalArgumentException();
+
+ // mark all ranges unsafe to read
+ // TODO (desired): if we have some ranges as safeToRead then we should really invalidate them immediately and not wait to execute under commandStore;
+ // could use synchronized to manage updates to these collections
+ markUnsafeToRead(ranges);
+
+ // find any pre-existing states we may overlap with, mark both as overlaps, and add ourselves to the collection
+ UnsafeToRead newState = new UnsafeToRead(ranges);
+ unsafeToReads.add(newState);
+
+ return new DataStore.StartingRangeFetch()
+ {
+ @Override
+ public DataStore.AbortFetch started(Timestamp maxApplied)
+ {
+ FetchAttempt.this.started(newState, maxApplied);
+ return () -> abort(newState);
+ }
+
+ @Override
+ public void cancel()
+ {
+ FetchAttempt.this.cancel(newState);
+ }
+ };
+ }
+
+ private void started(UnsafeToRead state, @Nonnull Timestamp maxAppliedLessOrEqualTo)
+ {
+ Invariants.require(maxAppliedLessOrEqualTo != null);
+ synchronized (this)
+ {
+ if (!unsafeToReads.remove(state))
+ return;
+
+ Timestamp safeToReadAt = maxAppliedLessOrEqualTo.next();
+ safeToReadAts = ReducingRangeMap.add(safeToReadAts, state.ranges, safeToReadAt, Timestamp::mergeMax);
+ maybeComplete(state.ranges);
+ }
+ }
+
+ // starting cancelled, can just unlink and make sure we invoke onDone on any we may have interfered with
+ private synchronized void cancel(UnsafeToRead state)
+ {
+ if (!unsafeToReads.remove(state))
+ throw illegalState("Tried to cancel starting a fetch that had already started");
+
+ maybeComplete(state.ranges);
+ }
+
+ // incomplete fetch cancelled, do we need to do anything?
+ // it's fine to leave our no-op to complete, but there might be issues with failure states
+ private synchronized void abort(UnsafeToRead state)
+ {
+ unsafeToReads.remove(state);
+ // TODO (expected, consider): are there any edge cases here?
+ }
+
+ @Override
+ public synchronized void fetched(Ranges ranges)
+ {
+ if (ranges.isEmpty())
+ return;
+
+ fetched = fetched.with(ranges);
+ maybeComplete(ranges);
+ }
+
+ @Override
+ public void fail(Ranges ranges, Throwable failure)
+ {
+ boolean hasFailed;
+ Ranges newlyFailed;
+ synchronized (this)
+ {
+ newlyFailed = ranges.slice(valid, Minimal);
+ if (newlyFailed.isEmpty())
+ return;
+
+ valid = valid.without(newlyFailed);
+ hasFailed = valid.isEmpty();
+ }
+
+ if (hasFailed)
+ accept(null, failure);
+
+ onNewFailure(failure, newlyFailed);
+ }
+
+ protected void onNewFailure(Throwable failure, Ranges newlyFailed)
+ {
+ }
+
+ /**
+ * Completed successfully or abandoned, we simply process successfully bootstrapped ranges that intersect
+ * with this safe-to-read boundary operation, and look to see if there remain newer operations in flight
+ * for those ranges; if not, they're done.
+ */
+ protected synchronized void maybeComplete(Ranges ranges)
+ {
+ Ranges newDone = fetched.slice(ranges.without(fetchedAndSafeToRead), Minimal);
+ if (newDone.isEmpty())
+ return;
+
+ for (UnsafeToRead unsafeToRead : unsafeToReads)
+ newDone = newDone.without(unsafeToRead.ranges);
+
+ if (newDone.isEmpty())
+ return;
+
+ final Ranges safeToRead = newDone;
+ List<AsyncResult<Void>> marking = new ArrayList<>();
+ safeToReadAts.foldlWithInputAndBounds(newDone, (safeToReadAt, v, start, end, i, j) -> {
+ Ranges mark = safeToRead.slice(Ranges.of(start.rangeFactory().newRange(start, end)), Minimal);
+ marking.add(markSafeToRead(mark, safeToReadAt));
+ return v;
+ }, null);
+
+ AsyncResults.allOf(marking).invoke((success, fail) -> {
+ if (fail != null) fail(ranges, fail);
+ else
+ {
+ synchronized (this)
+ {
+ fetchedAndSafeToRead = fetchedAndSafeToRead.with(safeToRead.slice(valid, Minimal));
+ maybeComplete();
+ }
+ }
+ });
+ }
+
+ @Override
+ public void accept(Object success, Throwable failure)
+ {
+ if (completed)
+ return;
+
+ // TODO (desired): we shouldn't need this method, as we should have the user implementation invoke us as necessary
+ // at most this should interpret failure to account for non-fetch related breakages
+ // so as to schedule a retry
+ synchronized (this)
+ {
+ fetchCompleted = true;
+ if (failure != null)
+ {
+ if (fetchOutcome == null) fetchOutcome = failure;
+ else fetchOutcome.addSuppressed(failure);
+ }
+ }
+ maybeComplete();
+ }
+
+ void maybeComplete()
+ {
+ Ranges missing;
+ synchronized (this)
+ {
+ if (completed)
+ return;
+
+ if (!fetchedAndSafeToRead.containsAll(fetchCompleted ? fetched : valid))
+ return;
+
+ // normalise fetched and fetchedAndSafeToRead against remaining valid ranges before completion
+ fetched = fetched.slice(valid, Minimal);
+ fetchedAndSafeToRead = fetchedAndSafeToRead.slice(valid, Minimal);
+ missing = valid.without(fetchedAndSafeToRead);
+ completed = true;
+ }
+
+ complete(missing);
+ }
+
+ protected abstract AsyncResult<Void> markSafeToRead(Ranges ranges, Timestamp safeToReadAt);
+ protected abstract void markUnsafeToRead(Ranges ranges);
+ protected abstract void complete(Ranges missing);
+}
diff --git a/accord-core/src/main/java/accord/local/Node.java b/accord-core/src/main/java/accord/local/Node.java
index 6b843698..c26d5477 100644
--- a/accord-core/src/main/java/accord/local/Node.java
+++ b/accord-core/src/main/java/accord/local/Node.java
@@ -18,6 +18,7 @@
package accord.local;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
@@ -113,6 +114,7 @@ public class Node implements NodeCommandStoreService
{
public static class Id implements Comparable<Id>
{
+ private static final ConcurrentHashMap<Id, Id> interned = new ConcurrentHashMap<>();
public static final Id NONE = new Id(0);
public static final Id MAX = new Id(Integer.MAX_VALUE);
@@ -151,6 +153,11 @@ public class Node implements NodeCommandStoreService
{
return Integer.toString(id);
}
+
+ public Id intern()
+ {
+ return interned.computeIfAbsent(this, Function.identity());
+ }
}
private final Id id;
diff --git a/accord-core/src/main/java/accord/local/RedundantBefore.java b/accord-core/src/main/java/accord/local/RedundantBefore.java
index 76920d13..341518c8 100644
--- a/accord-core/src/main/java/accord/local/RedundantBefore.java
+++ b/accord-core/src/main/java/accord/local/RedundantBefore.java
@@ -28,6 +28,7 @@ import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
+import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -50,6 +51,7 @@ import accord.primitives.Routables;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
import accord.primitives.Unseekables;
+import accord.utils.Functions;
import accord.utils.Invariants;
import accord.utils.ReducingIntervalMap;
import accord.utils.ReducingRangeMap;
@@ -66,6 +68,7 @@ import static accord.local.RedundantStatus.Property.LOCALLY_DURABLE_TO_DATA_STOR
import static accord.local.RedundantStatus.Property.LOCALLY_REDUNDANT;
import static accord.local.RedundantStatus.Property.LOCALLY_SYNCED;
import static accord.local.RedundantStatus.Property.LOCALLY_WITNESSED;
+import static accord.local.RedundantStatus.Property.QUORUM_APPLIED;
import static accord.local.RedundantStatus.Property.UNREADY;
import static accord.local.RedundantStatus.Property.SHARD_APPLIED;
import static accord.local.RedundantStatus.WAS_OWNED_SYNCED;
@@ -80,6 +83,7 @@ import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Timestamp.Flag.SHARD_BOUND;
import static accord.utils.ArrayBuffers.cachedAny;
import static accord.utils.ArrayBuffers.cachedInts;
+import static accord.utils.Functions.alwaysFalse;
import static accord.utils.Invariants.illegalState;
import static accord.utils.Invariants.require;
import static accord.utils.Invariants.requireStrictlyOrdered;
@@ -631,9 +635,24 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
return notWitnessed;
}
- static Ranges withoutAnyRetired(Bounds bounds, @Nonnull Ranges notRetired)
+ static Ranges withoutRetired(Bounds bounds, @Nonnull Ranges notRetired)
{
- if (bounds == null || bounds.endEpoch > bounds.maxBound(SHARD_APPLIED).epoch())
+ return withoutRetired(bounds, notRetired, b -> b.maxBound(SHARD_APPLIED));
+ }
+
+ static Ranges withoutLocallyRetired(Bounds bounds, @Nonnull Ranges notRetired)
+ {
+ return withoutRetired(bounds, notRetired, b -> b.maxBound(LOCALLY_APPLIED));
+ }
+
+ static Ranges withoutQuorumAndLocallyRetired(Bounds bounds, @Nonnull Ranges notRetired)
+ {
+ return withoutRetired(bounds, notRetired, b -> b.maxBoundBoth(QUORUM_APPLIED, LOCALLY_APPLIED));
+ }
+
+ private static Ranges withoutRetired(Bounds bounds, @Nonnull Ranges notRetired, Function<Bounds, TxnId> getBound)
+ {
+ if (bounds == null || bounds.endEpoch > getBound.apply(bounds).epoch())
return notRetired;
return notRetired.without(Ranges.of(bounds.range));
@@ -997,12 +1016,25 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
public Ranges removeRetired(Ranges ranges)
{
- return foldl(ranges, Bounds::withoutAnyRetired, ranges, r -> false);
+ return removeRetired(ranges, Bounds::withoutRetired);
}
public Ranges removeLocallyRetired(Ranges ranges)
{
- return ranges.without(lostRanges);
+ return removeRetired(ranges, Bounds::withoutLocallyRetired);
+ }
+
+ public Ranges removeQuorumAndLocallyRetired(Ranges ranges)
+ {
+ return removeRetired(ranges, Bounds::withoutQuorumAndLocallyRetired);
+ }
+
+ private Ranges removeRetired(Ranges ranges, BiFunction<Bounds, Ranges, Ranges> fold)
+ {
+ if (!lostRanges.intersects(ranges))
+ return ranges;
+
+ return foldl(ranges, fold, ranges, alwaysFalse());
}
public Ranges removeLostOrStale(Ranges ranges)
@@ -1054,6 +1086,26 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
}
}
+ public boolean isAtLeast(RedundantBefore atLeast)
+ {
+ return foldl((b, v, al, e) -> {
+ return al.foldl(Ranges.of(b.range), (lb, v2, ub) -> {
+ int j = 0;
+ for (int i = 0 ; i < lb.bounds.length ; ++i)
+ {
+ TxnId bound = lb.bounds[i];
+ j = Arrays.binarySearch(ub.bounds, j, ub.bounds.length, bound, Comparator.reverseOrder());
+ if (j < 0) j = -2 - j;
+ if (j < 0
+ || (lb.status(i*2) & ~ub.status(j*2)) != 0
+ || (lb.status(i*2+1) & ~ub.status(j*2+1)) != 0)
+ return false;
+ }
+ return v2;
+ }, v, b);
+ }, true, atLeast, null, Functions.identityPredicate());
+ }
+
/**
* Subtract anything we won't execute locally, i.e. are pre-bootstrap or stale (or for RX are on ranges that are already retired)
* but also anything that executes in an epoch we don't own
@@ -1258,7 +1310,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
s.range = e.range;
// TODO (desired): move the bounds check into forEach, matching structure used for keys
d.forEach(e.range, b, s, (b0, s0, txnIdx) -> {
- if (txnIdx < s0.bootstrapIdx && b0.isWaitingOnDirectRangeTxnIdx(txnIdx) && s0.isFullyBootstrapping(txnIdx))
+ if (txnIdx < s0.bootstrapIdx && b0.isWaitingOnTxnIndex(txnIdx) && s0.isFullyBootstrapping(txnIdx))
b0.removeWaitingOnDirectRangeTxnId(txnIdx);
});
}
@@ -1304,7 +1356,7 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
m.computeIfAbsent(bound, ignore -> new ArrayList<>())
.add(e.range);
return m;
- }, map, p1, p2, i -> false);
+ }, map, p1, p2);
if (map.size() == 0 || map.size() == 1 && map.firstKey().equals(TxnId.NONE))
return;
@@ -1316,4 +1368,9 @@ public class RedundantBefore extends ReducingRangeMap<RedundantBefore.Bounds>
.map(e -> (e.getKey().equals(TxnId.NONE) ? "none" : e.getKey().toString()) + ':' + Ranges.ofSorted(e.getValue().toArray(new Range[0])).mergeTouching())
.collect(Collectors.joining(", ", "{", "}")));
}
+
+ public RedundantBefore map(Function<Bounds, Bounds> map)
+ {
+ return map(map, Bounds[]::new, EMPTY, RedundantBefore::new);
+ }
}
diff --git a/accord-core/src/main/java/accord/local/RedundantStatus.java b/accord-core/src/main/java/accord/local/RedundantStatus.java
index 24d30268..e2047442 100644
--- a/accord-core/src/main/java/accord/local/RedundantStatus.java
+++ b/accord-core/src/main/java/accord/local/RedundantStatus.java
@@ -109,13 +109,13 @@ public class RedundantStatus
* We have applied the preceding transactions durably to the store, so that we can safely truncate the Write
* information as we will not need to replay it to the store
*/
- LOCALLY_DURABLE_TO_DATA_STORE (false, true, LE, LOCALLY_APPLIED),
+ LOCALLY_DURABLE_TO_DATA_STORE (false, true, LT, LOCALLY_APPLIED),
/**
* We have applied the preceding transactions durably to all summary structures, so that on restart we do
* not need to replay the transaction to restore any internal state.
*/
- LOCALLY_DURABLE_TO_COMMAND_STORE (false, true, LE, LOCALLY_APPLIED),
+ LOCALLY_DURABLE_TO_COMMAND_STORE (false, false, LT, LOCALLY_APPLIED),
/**
* We have fully executed until across all a majority of replicas for the range in question,
diff --git a/accord-core/src/main/java/accord/local/SafeCommand.java b/accord-core/src/main/java/accord/local/SafeCommand.java
index 794496ff..e190e429 100644
--- a/accord-core/src/main/java/accord/local/SafeCommand.java
+++ b/accord-core/src/main/java/accord/local/SafeCommand.java
@@ -74,7 +74,6 @@ public abstract class SafeCommand
Invariants.require(prev == null || update == SaveStatus.max(update, prev, Command::saveStatus, Command::acceptedOrCommitted) || update.saveStatus() == SaveStatus.Erased || update.saveStatus() == SaveStatus.Vestigial);
set(update);
- safeStore.progressLog().update(safeStore, txnId, prev, update, force);
safeStore.update(prev, update, force);
return update;
}
diff --git a/accord-core/src/main/java/accord/local/SafeCommandStore.java b/accord-core/src/main/java/accord/local/SafeCommandStore.java
index ba0ecca6..4cf2edad 100644
--- a/accord-core/src/main/java/accord/local/SafeCommandStore.java
+++ b/accord-core/src/main/java/accord/local/SafeCommandStore.java
@@ -287,6 +287,7 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
protected void update(Command prev, Command updated, boolean force)
{
+ progressLog().update(this, prev, updated, force);
updateExclusiveSyncPoint(prev, updated, force);
updateMaxConflicts(prev, updated, force);
if (updated.txnId().is(Range))
@@ -478,10 +479,12 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
{
updateUnmanagedCommandsForKey(safeStore, execute.keys(), txnId, mode);
}
+
+ Consumer<SafeCommandStore> registerTransitive = !next.txnId().is(Range) || !next.txnId().is(VisibilitySyncPoint) ? null : registerTransitiveRangeDeps(safeStore.commandStore(), txnId, next);
if (execute == context)
{
- if (next.txnId().is(Range) && next.txnId().is(VisibilitySyncPoint))
- registerTransitiveRangeDeps(safeStore, txnId, next);
+ if (registerTransitive != null)
+ registerTransitive.accept(safeStore);
}
else
{
@@ -491,8 +494,8 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
safeStore = safeStore;
CommandStore unsafeStore = safeStore.commandStore();
AsyncChain<Void> submit = unsafeStore.chain(context, safeStore0 -> { updateUnmanagedCommandsForKey(safeStore0, safeStore0.context().keys() , txnId, mode); });
- if (next.txnId().is(Range))
- submit = submit.flatMap(success -> unsafeStore.chain(PreLoadContext.contextFor(txnId, "Register Transitive Dependencies"), safeStore0 -> { registerTransitiveRangeDeps(safeStore0, txnId, next); }));
+ if (registerTransitive != null)
+ submit = submit.flatMap(success -> unsafeStore.chain(PreLoadContext.contextFor(txnId, "Register Transitive Dependencies"), registerTransitive));
submit.begin(safeStore.commandStore().agent);
}
}
@@ -506,35 +509,40 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
}
}
- private static void registerTransitiveRangeDeps(SafeCommandStore safeStore, TxnId syncId, Command syncCommand)
+ private static Consumer<SafeCommandStore> registerTransitiveRangeDeps(CommandStore commandStore, TxnId syncId, Command syncCommand)
{
if (!syncId.is(VisibilitySyncPoint))
- return;
+ return null;
- CommandStore commandStore = safeStore.commandStore();
Ranges touches = syncCommand.participants().touches().toRanges();
Ranges waitingOn = commandStore.isWaitingOnVisibility(syncId, touches);
if (waitingOn.isEmpty())
- return;
+ return null;
- List<AsyncChain<Void>> async = new ArrayList<>();
- RangeDeps rangeDeps = syncCommand.partialDeps().rangeDeps;
- rangeDeps.forEachUniqueTxnId(waitingOn, null, (ignore, txnIdWithFlags) -> {
- TxnId txnId = txnIdWithFlags.withoutNonIdentityFlags();
- PreLoadContext context = PreLoadContext.contextFor(txnId, "Register Transitive Range Deps");
- Ranges ranges = rangeDeps.ranges(txnId);
- if (safeStore.canExecuteWith(context)) registerTransitive(safeStore, txnId, ranges);
- else async.add(safeStore.commandStore().chain(context, safeStore0 -> {
- registerTransitive(safeStore0, txnId, ranges);
- }));
- });
-
- AsyncChains.chain(() -> commandStore.markingVisible(syncId, waitingOn))
- .flatMap(ignore -> AsyncChains.reduce(async, Reduce.toNull(), null))
- .begin((success, fail) -> {
- if (fail == null) commandStore.execute((PreLoadContext.Empty)() -> "Mark Synced", (Consumer<? super SafeCommandStore>) safeStore0 -> commandStore.markVisible(safeStore0, syncId, waitingOn), commandStore.agent());
- else commandStore.execute((PreLoadContext.Empty)() -> "Unmark Syncing", (Consumer<? super SafeCommandStore>) safeStore0 -> commandStore.cancelMarkingVisible(syncId, waitingOn), commandStore.agent);
- });
+ commandStore.markingVisible(syncId, waitingOn);
+ return safeStore -> {
+ List<AsyncChain<Void>> async = new ArrayList<>();
+ RangeDeps rangeDeps = syncCommand.partialDeps().rangeDeps;
+ rangeDeps.forEachUniqueTxnId(waitingOn, null, (ignore, txnIdWithFlags) -> {
+ TxnId txnId = txnIdWithFlags.withoutNonIdentityFlags();
+ PreLoadContext context = PreLoadContext.contextFor(txnId, "Register Transitive Range Deps");
+ Ranges ranges = rangeDeps.ranges(txnId);
+ if (safeStore.canExecuteWith(context)) registerTransitive(safeStore, txnId, ranges);
+ else async.add(safeStore.commandStore().chain(context, safeStore0 -> {
+ registerTransitive(safeStore0, txnId, ranges);
+ }));
+ });
+
+ AsyncChains.reduce(async, Reduce.toNull(), null)
+ .begin((success, fail) -> {
+ if (fail == null) commandStore.execute((PreLoadContext.Empty)() -> "Mark Synced", (Consumer<? super SafeCommandStore>) safeStore0 -> commandStore.markVisible(safeStore0, syncId, waitingOn), commandStore.agent());
+ else
+ {
+ // TODO (required): reset ensureReadyToCoordinate state
+ commandStore.execute((PreLoadContext.Empty)() -> "Unmark Syncing", (Consumer<? super SafeCommandStore>) safeStore0 -> commandStore.cancelMarkingVisible(syncId, waitingOn), commandStore.agent);
+ }
+ });
+ };
}
private static void registerTransitive(SafeCommandStore safeStore, TxnId txnId, Ranges witnessedBy)
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 7f49e518..ab5a89fc 100644
--- a/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
@@ -219,12 +219,13 @@ import static accord.utils.SortedArrays.Search.FAST;
* 2) when a transaction proposed in a future epoch visits an earlier epoch, it is registered here for recovery
* decisions, so that recovery does not need to contact future epochs to find any superseding transactions
* 3) when an accept round visits a later epoch than the one in which it is agreed.
+ * TODO (desired): by waiting for a prefix to commit before executing we can in theory have old ids proposed that delay execution.
* TODO (desired): track whether a TxnId is a write on this key only for execution (rather than globally)
* TODO (desired): save space by encoding InternalStatus in TxnId.flags(), so that when executeAt==txnId we can save 8 bytes per entry
* TODO (required): better linearizability violation detection
* TODO (expected): cleanup unmanaged transitively known transactions
- * TODO (desired): introduce a new status or other fast and simple mechanism for filtering treatment of range or unmanaged transactions
- * TODO (desired): store missing transactions against the highest known transaction only (this should also permit us to prune better by ignoring the missing collection contents)
+ * TODO (desired): introduce a new status or other fast and simple mechanism for filtering treatment of range or unmanaged transactions
+ * TODO (desired): store missing transactions against the highest known transaction only (this should also permit us to prune better by ignoring the missing collection contents)
*/
public class CommandsForKey extends CommandsForKeyUpdate
{
diff --git a/accord-core/src/main/java/accord/local/durability/DurabilityQueue.java b/accord-core/src/main/java/accord/local/durability/DurabilityQueue.java
index c80d9559..4e7c893e 100644
--- a/accord-core/src/main/java/accord/local/durability/DurabilityQueue.java
+++ b/accord-core/src/main/java/accord/local/durability/DurabilityQueue.java
@@ -69,6 +69,7 @@ import static accord.local.durability.DurabilityService.SyncRemote.All;
import static accord.local.durability.DurabilityService.SyncRemote.Quorum;
import static accord.primitives.Routables.Slice.Minimal;
import static accord.primitives.Txn.Kind.VisibilitySyncPoint;
+import static accord.utils.Functions.alwaysFalse;
import static accord.utils.btree.IntervalBTree.InclusiveEndHelper.endWithStart;
import static accord.utils.btree.IntervalBTree.InclusiveEndHelper.startWithEnd;
import static accord.utils.btree.IntervalBTree.InclusiveEndHelper.startWithStart;
@@ -537,7 +538,7 @@ public class DurabilityQueue
{
if (success == null) achieved = Ranges.EMPTY;
else if (success.min.remote == All) achieved = ranges;
- else achieved = success.achieved.foldlWithBounds((p, r, s, e) -> p.remote == All ? r.with(Ranges.of(s.rangeFactory().newRange(s, e))) : r, Ranges.EMPTY, ignore -> false);
+ else achieved = success.achieved.foldlWithBounds((p, r, s, e) -> p.remote == All ? r.with(Ranges.of(s.rangeFactory().newRange(s, e))) : r, Ranges.EMPTY);
isDone = achieved.containsAll(ranges);
}
else
diff --git a/accord-core/src/main/java/accord/local/durability/DurabilityRequest.java b/accord-core/src/main/java/accord/local/durability/DurabilityRequest.java
index e2e049f1..133b548a 100644
--- a/accord-core/src/main/java/accord/local/durability/DurabilityRequest.java
+++ b/accord-core/src/main/java/accord/local/durability/DurabilityRequest.java
@@ -218,11 +218,6 @@ public class DurabilityRequest
}
}
- private String successString(Ranges success)
- {
- return success.isEmpty() ? "achieved" : "achieved " + require.local + "/" + require.remote + " for " + success + " but only";
- }
-
@Override
public String toString()
{
diff --git a/accord-core/src/main/java/accord/local/durability/DurabilityResult.java b/accord-core/src/main/java/accord/local/durability/DurabilityResult.java
index c462e01b..266efa5e 100644
--- a/accord-core/src/main/java/accord/local/durability/DurabilityResult.java
+++ b/accord-core/src/main/java/accord/local/durability/DurabilityResult.java
@@ -74,6 +74,6 @@ public class DurabilityResult
if (require.isSatisfiedBy(l))
rs = rs.with(Ranges.of(s.rangeFactory().newRange(s, e)));
return rs;
- }, Ranges.EMPTY, ignore -> false);
+ }, Ranges.EMPTY);
}
}
diff --git a/accord-core/src/main/java/accord/local/durability/DurabilityService.java b/accord-core/src/main/java/accord/local/durability/DurabilityService.java
index abd866da..79d1b8fe 100644
--- a/accord-core/src/main/java/accord/local/durability/DurabilityService.java
+++ b/accord-core/src/main/java/accord/local/durability/DurabilityService.java
@@ -32,8 +32,8 @@ import org.slf4j.LoggerFactory;
import accord.api.TopologyListener;
import accord.api.Timeouts.Timeout;
+import accord.local.DurableBefore.Entry;
import accord.local.Node;
-import accord.primitives.SyncPoint;
import accord.primitives.Ranges;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
@@ -53,7 +53,7 @@ public class DurabilityService implements TopologyListener
{
private static final Logger logger = LoggerFactory.getLogger(DurabilityService.class);
- public enum SyncLocal { NoLocal, Self }
+ public enum SyncLocal { NoLocal, KnownToSelf, Self }
public enum SyncRemote { NoRemote, MinorityQuorum, Quorum, All }
private boolean started;
@@ -85,6 +85,11 @@ public class DurabilityService implements TopologyListener
return global;
}
+ public synchronized boolean isStarted()
+ {
+ return started;
+ }
+
public void start()
{
synchronized (this)
@@ -115,16 +120,16 @@ public class DurabilityService implements TopologyListener
global.stop();
}
- public AsyncResult<Void> close(String requestedBy, Txn.Kind kind, Ranges ranges, long timeoutDelay, TimeUnit timeoutUnits)
+ public AsyncResult<Void> close(String requestedBy, Txn.Kind kind, Ranges ranges, SyncLocal local, long timeoutDelay, TimeUnit timeoutUnits)
{
- return close(requestedBy, kind, TxnId.NONE, ranges, timeoutDelay, timeoutUnits);
+ return close(requestedBy, kind, TxnId.NONE, ranges, local, timeoutDelay, timeoutUnits);
}
- public AsyncResult<Void> close(Object requestedBy, Txn.Kind kind, Timestamp minBound, Ranges ranges, long timeoutDelay, TimeUnit timeoutUnits)
+ public AsyncResult<Void> close(Object requestedBy, Txn.Kind kind, Timestamp minBound, Ranges ranges, SyncLocal local, long timeoutDelay, TimeUnit timeoutUnits)
{
long startedAt = node.elapsed(MICROSECONDS);
long timeoutAt = startedAt + timeoutUnits.toMicros(timeoutDelay);
- return submit(new DurabilityRequest(requestedBy, kind, minBound, ranges, new DurabilityLevel(SyncLocal.NoLocal, SyncRemote.NoRemote, null, null), startedAt, timeoutAt)).result;
+ return submit(new DurabilityRequest(requestedBy, kind, minBound, ranges, new DurabilityLevel(local, SyncRemote.NoRemote, null, null), startedAt, timeoutAt)).result;
}
public AsyncResult<Void> sync(Object requestedBy, Txn.Kind kind, Ranges ranges, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
@@ -160,19 +165,25 @@ public class DurabilityService implements TopologyListener
return submit(new DurabilityRequest(requestedBy, kind, minBound, ranges, new DurabilityLevel(local, remote, sortedInclude, null), startedAt, timeoutAt)).result;
}
- public AsyncResult<Void> sync(Object requestedBy, SyncPoint syncPoint, SyncLocal local, SyncRemote remote, long timeoutDelay, TimeUnit timeoutUnits)
- {
- long startedAt = node.elapsed(MICROSECONDS);
- long timeoutAt = startedAt + timeoutUnits.toMicros(timeoutDelay);
- DurabilityRequest request = new DurabilityRequest(requestedBy, syncPoint.syncId.kind(), syncPoint.syncId, syncPoint.route.toRanges(), new DurabilityLevel(local, remote, null, null), startedAt, timeoutAt);
- logger.info("Requesting durability {}", request);
- register(request);
- shards.queue().submit(syncPoint, request);
- return request.result;
- }
-
private DurabilityRequest submit(DurabilityRequest request)
{
+ boolean canUseDurableBefore = request.kind != Txn.Kind.VisibilitySyncPoint
+ && !request.min.equals(TxnId.NONE)
+ && request.require.including == null
+ && request.require.local == SyncLocal.NoLocal;
+
+ if (canUseDurableBefore)
+ {
+ boolean isAlreadyMet = node.durableBefore().foldlWithDefault(request.ranges, (e, b, min, remote) -> {
+ return b && min.compareTo(remote == SyncRemote.All ? e.universalBefore : e.quorumBefore) <= 0;
+ }, Entry.NONE, true, request.min, request.require.remote);
+
+ if (isAlreadyMet)
+ {
+ request.reportSuccess();
+ return request;
+ }
+ }
register(request);
logger.info("Requesting durability {}", request);
shards.request(request);
diff --git a/accord-core/src/main/java/accord/local/durability/ShardDurability.java b/accord-core/src/main/java/accord/local/durability/ShardDurability.java
index 4cbeec68..9c4c79cc 100644
--- a/accord-core/src/main/java/accord/local/durability/ShardDurability.java
+++ b/accord-core/src/main/java/accord/local/durability/ShardDurability.java
@@ -316,7 +316,7 @@ public class ShardDurability
sb.append("]:");
sb.append(entry);
return sb;
- }, new StringBuilder(), ignore -> false).toString();
+ }, new StringBuilder()).toString();
logger.debug("{}", report);
}
else if (min.equals(cycleMin))
diff --git a/accord-core/src/main/java/accord/messages/Accept.java b/accord-core/src/main/java/accord/messages/Accept.java
index 7f0110bb..2bdc47a1 100644
--- a/accord-core/src/main/java/accord/messages/Accept.java
+++ b/accord-core/src/main/java/accord/messages/Accept.java
@@ -216,7 +216,7 @@ public class Accept extends RouteRequest.WithUnsynced<Accept.AcceptReply>
Deps deps;
if (calculateDeps())
{
- try (DepsCalculator calculator = new DepsCalculator())
+ try (DepsCalculator calculator = new DepsCalculator(executeAt))
{
deps = calculator.calculate(safeStore, txnId, participants, minEpoch, executeAt, true);
if (deps == null)
diff --git a/accord-core/src/main/java/accord/messages/BeginRecovery.java b/accord-core/src/main/java/accord/messages/BeginRecovery.java
index 7e88c8cb..435a932b 100644
--- a/accord-core/src/main/java/accord/messages/BeginRecovery.java
+++ b/accord-core/src/main/java/accord/messages/BeginRecovery.java
@@ -171,12 +171,12 @@ public class BeginRecovery extends RouteRequest.WithUnsynced<BeginRecovery.Recov
}
boolean supersedingRejects;
- Deps earlierNoWait, earlierWait;
+ Deps simpleNoWait, simpleWait;
Deps laterCoordRejects;
if (command.hasBeen(AcceptedMedium) || !recoverFastPath())
{
supersedingRejects = true;
- earlierNoWait = earlierWait = Deps.NONE;
+ simpleNoWait = simpleWait = Deps.NONE;
laterCoordRejects = Deps.NONE;
}
else
@@ -185,8 +185,8 @@ public class BeginRecovery extends RouteRequest.WithUnsynced<BeginRecovery.Recov
{
safeStore.visit(participants.owns(), txnId, txnId.witnessedBy(), visitor);
supersedingRejects = visitor.supersedingRejects;
- earlierNoWait = visitor.simpleNoWait == null ? Deps.NONE : visitor.simpleNoWait.build();
- earlierWait = visitor.simpleWait == null ? Deps.NONE : visitor.simpleWait.build();
+ simpleNoWait = visitor.simpleNoWait == null ? Deps.NONE : visitor.simpleNoWait.build();
+ simpleWait = visitor.simpleWait == null ? Deps.NONE : visitor.simpleWait.build();
laterCoordRejects = visitor.supersedingCoordRejects == null ? Deps.NONE : visitor.supersedingCoordRejects.build();
}
}
@@ -198,7 +198,7 @@ public class BeginRecovery extends RouteRequest.WithUnsynced<BeginRecovery.Recov
Result result = command.result();
Participants<?> coordinatorAcceptsFastPath = saveStatus.known.hasPrivilegedVote() ? participants.owns() : null;
boolean acceptsFastPath = acceptsFastPath(txnId, participants, saveStatus, executeAt);
- return new RecoverOk(txnId, saveStatus.status, accepted, executeAt, deps, earlierWait, earlierNoWait, laterCoordRejects, acceptsFastPath, coordinatorAcceptsFastPath, supersedingRejects, writes, result);
+ return new RecoverOk(txnId, saveStatus.status, accepted, executeAt, deps, simpleWait, simpleNoWait, laterCoordRejects, acceptsFastPath, coordinatorAcceptsFastPath, supersedingRejects, writes, result);
}
private boolean recoverFastPath()
@@ -389,7 +389,6 @@ public class BeginRecovery extends RouteRequest.WithUnsynced<BeginRecovery.Recov
* and did not witness us as part of their pre-accept round, as this means that we CANNOT have taken
* the fast path. This is central to safe recovery, as if every transaction that executes later has
* 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).
*/
return markSupersedingRejects();
diff --git a/accord-core/src/main/java/accord/messages/CheckStatus.java b/accord-core/src/main/java/accord/messages/CheckStatus.java
index 18beee32..ccbd1030 100644
--- a/accord-core/src/main/java/accord/messages/CheckStatus.java
+++ b/accord-core/src/main/java/accord/messages/CheckStatus.java
@@ -495,12 +495,12 @@ public class CheckStatus extends ParticipantsRequest<Participants<?>, CheckStatu
public Known maxKnown()
{
- return map.foldl(MinAndMaxKnown::nonNullOrMax, Nothing, i -> false);
+ return map.foldl(MinAndMaxKnown::nonNullOrMax, Nothing);
}
public Known maxKnown(Unseekables<?> query)
{
- return map.foldl(query, MinAndMaxKnown::nonNullOrMax, Nothing, i -> false);
+ return map.foldl(query, MinAndMaxKnown::nonNullOrMax, Nothing);
}
/**
@@ -508,7 +508,7 @@ public class CheckStatus extends ParticipantsRequest<Participants<?>, CheckStatu
*/
public Known minMaxKnown(Unseekables<?> query)
{
- return map.foldlWithDefault(query, MinAndMaxKnown::nonNullOrMinMax, MinAndMaxKnown.Nothing, null, i -> false);
+ return map.foldlWithDefault(query, MinAndMaxKnown::nonNullOrMinMax, MinAndMaxKnown.Nothing, null);
}
/**
@@ -517,7 +517,7 @@ public class CheckStatus extends ParticipantsRequest<Participants<?>, CheckStatu
*/
public Known minKnown(Unseekables<?> query)
{
- Known known = map.foldlWithDefault(query, MinAndMaxKnown::nonNullOrMin, MinAndMaxKnown.Nothing, null, i -> false);
+ Known known = map.foldlWithDefault(query, MinAndMaxKnown::nonNullOrMin, MinAndMaxKnown.Nothing, null);
return known == null ? Nothing : known;
}
diff --git a/accord-core/src/main/java/accord/messages/GetEphemeralReadDeps.java b/accord-core/src/main/java/accord/messages/GetEphemeralReadDeps.java
index b106bc2b..a3b7caf4 100644
--- a/accord-core/src/main/java/accord/messages/GetEphemeralReadDeps.java
+++ b/accord-core/src/main/java/accord/messages/GetEphemeralReadDeps.java
@@ -79,7 +79,7 @@ public class GetEphemeralReadDeps extends RouteRequest.WithUnsynced<GetEphemeral
Deps deps;
ExecuteFlags flags;
- try (DepsCalculator calculator = new DepsCalculator())
+ try (DepsCalculator calculator = new DepsCalculator(txnId))
{
deps = calculator.calculate(safeStore, txnId, participants, minEpoch, Timestamp.MAX, false);
flags = calculator.executeFlags(txnId);
diff --git a/accord-core/src/main/java/accord/messages/PreAccept.java b/accord-core/src/main/java/accord/messages/PreAccept.java
index 5e413ce1..7895114e 100644
--- a/accord-core/src/main/java/accord/messages/PreAccept.java
+++ b/accord-core/src/main/java/accord/messages/PreAccept.java
@@ -138,7 +138,7 @@ public class PreAccept extends WithUnsynced<PreAccept.PreAcceptReply>
case Retired:
ExecuteFlags flags;
Deps deps;
- try (DepsCalculator calculator = new DepsCalculator())
+ try (DepsCalculator calculator = new DepsCalculator(txnId))
{
deps = calculator.calculate(safeStore, txnId, participants, minEpoch, txnId, true);
if (deps == null)
diff --git a/accord-core/src/main/java/accord/primitives/AbstractKeys.java b/accord-core/src/main/java/accord/primitives/AbstractKeys.java
index f7f2ab90..870909fc 100644
--- a/accord-core/src/main/java/accord/primitives/AbstractKeys.java
+++ b/accord-core/src/main/java/accord/primitives/AbstractKeys.java
@@ -41,6 +41,7 @@ import accord.utils.SortedArrays;
import net.nicoulaj.compilecommand.annotations.Inline;
import static accord.primitives.Routable.Domain.Key;
+import static accord.utils.Functions.alwaysFalse;
@SuppressWarnings("rawtypes")
// TODO (desired, efficiency): check that foldl call-sites are inlined and optimised by HotSpot
@@ -311,7 +312,7 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
@Inline
public final <P1, P2, V> V foldl(AbstractRanges intersect, IndexedTriFold<P1, P2, K, V> fold, P1 p1, P2 p2, V accumulator)
{
- return Routables.foldl(this, intersect, fold, p1, p2, accumulator, i -> false);
+ return Routables.foldl(this, intersect, fold, p1, p2, accumulator, alwaysFalse());
}
@Inline
@@ -326,7 +327,7 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
Routables.foldl(this, rs, (p, ignore, k, consumer, i) -> {
consumer.accept(p, k, i);
return consumer;
- }, p1, null, forEach, i -> false);
+ }, p1, null, forEach, alwaysFalse());
}
@Inline
@@ -335,7 +336,7 @@ public abstract class AbstractKeys<K extends RoutableKey> implements Iterable<K>
Routables.foldl(this, rs, (p, ignore, k, consumer, i) -> {
consumer.accept(p, k, i);
return consumer;
- }, p1, null, forEach, i -> false);
+ }, p1, null, forEach, alwaysFalse());
}
@Inline
diff --git a/accord-core/src/main/java/accord/primitives/AbstractRanges.java b/accord-core/src/main/java/accord/primitives/AbstractRanges.java
index 3f01fefa..10c1bbdb 100644
--- a/accord-core/src/main/java/accord/primitives/AbstractRanges.java
+++ b/accord-core/src/main/java/accord/primitives/AbstractRanges.java
@@ -38,6 +38,7 @@ import net.nicoulaj.compilecommand.annotations.Inline;
import static accord.primitives.Ranges.EMPTY;
import static accord.utils.ArrayBuffers.cachedRanges;
+import static accord.utils.Functions.alwaysFalse;
import static accord.utils.Invariants.illegalArgument;
import static accord.utils.SortedArrays.Search.CEIL;
import static accord.utils.SortedArrays.Search.FAST;
@@ -930,7 +931,7 @@ public abstract class AbstractRanges implements Iterable<Range>, Routables<Range
@Inline
public final <P1, P2, V> V foldl(AbstractRanges intersect, IndexedTriFold<P1, P2, Range, V> fold, P1 p1, P2 p2, V accumulator)
{
- return Routables.foldl(this, intersect, fold, p1, p2, accumulator, i -> false);
+ return Routables.foldl(this, intersect, fold, p1, p2, accumulator, alwaysFalse());
}
public Range[] unsafeRanges()
diff --git a/accord-core/src/main/java/accord/primitives/KnownMap.java b/accord-core/src/main/java/accord/primitives/KnownMap.java
index a11d2c6a..dc079513 100644
--- a/accord-core/src/main/java/accord/primitives/KnownMap.java
+++ b/accord-core/src/main/java/accord/primitives/KnownMap.java
@@ -179,7 +179,7 @@ public class KnownMap extends ReducingRangeMap<KnownMap.MinAndMaxKnown>
public Known computeValidForAll(Unseekables<?> routeOrParticipants)
{
- Known validForAll = foldlWithDefault(routeOrParticipants, KnownMap::reduceKnownFor, MinAndMaxKnown.Nothing, null, i -> false);
+ Known validForAll = foldlWithDefault(routeOrParticipants, KnownMap::reduceKnownFor, MinAndMaxKnown.Nothing, null);
return this.validForAll.atLeast(validForAll).validForAll();
}
diff --git a/accord-core/src/main/java/accord/primitives/Range.java b/accord-core/src/main/java/accord/primitives/Range.java
index 5a571890..7bea9c60 100644
--- a/accord-core/src/main/java/accord/primitives/Range.java
+++ b/accord-core/src/main/java/accord/primitives/Range.java
@@ -432,7 +432,7 @@ public abstract class Range implements Comparable<RoutableKey>, Unseekable, Seek
return (startInclusive() ? "[" : "(") + start().printableSuffix() + "," + end().printableSuffix() + (endInclusive() ? ']' : ')');
}
- public static Range create(RoutingKey start, RoutingKey end)
+ public static Range of(RoutingKey start, RoutingKey end)
{
return start.rangeFactory().newRange(start, end);
}
diff --git a/accord-core/src/main/java/accord/primitives/Timestamp.java b/accord-core/src/main/java/accord/primitives/Timestamp.java
index 841c4f38..6005bdba 100644
--- a/accord-core/src/main/java/accord/primitives/Timestamp.java
+++ b/accord-core/src/main/java/accord/primitives/Timestamp.java
@@ -28,6 +28,7 @@ import javax.annotation.Nonnull;
import static accord.primitives.Timestamp.Flag.HLC_BOUND;
import static accord.primitives.Timestamp.Flag.REJECTED;
import static accord.primitives.Timestamp.Flag.SHARD_BOUND;
+import static accord.primitives.Timestamp.Flag.SOFT_REJECT;
import static accord.primitives.Timestamp.Flag.UNSTABLE;
import static accord.utils.Invariants.illegalArgument;
@@ -62,10 +63,15 @@ 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.
+ * To be used only by executeAt responses during PreAccept. Can never be taken at the same time as UNSTABLE.
*/
REJECTED(0x0800),
+ /**
+ * To be used only by executeAt responses during PreAccept. Can never be taken at the same time as HLC_BOUND.
+ */
+ SOFT_REJECT(0x0400),
+
/**
* To be used only by TxnId inside of Dep collections. Can never be taken at the same time as REJECTED.
*/
@@ -97,7 +103,7 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
/**
* The set of flags we want to retain as we merge timestamps (e.g. when taking mergeMax).
*/
- static final int MERGE_FLAGS = REJECTED.bit | UNSTABLE.bit | HLC_BOUND.bit | SHARD_BOUND.bit;
+ static final int MERGE_FLAGS = REJECTED.bit | SOFT_REJECT.bit | UNSTABLE.bit | HLC_BOUND.bit | SHARD_BOUND.bit;
public static final long IDENTITY_LSB = 0xFFFFFFFF_FFFF00FFL;
public static final int IDENTITY_FLAGS = 0x00000000_000000FF;
public static final int NON_IDENTITY_FLAGS_SHIFT = Integer.bitCount(IDENTITY_FLAGS);
@@ -275,6 +281,11 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
return addFlags(flag.bit);
}
+ public Timestamp removeFlag(Flag flag)
+ {
+ return removeFlags(this, flag.bit, Timestamp::fromBits);
+ }
+
public final Timestamp addFlags(Timestamp merge)
{
return addFlags(this, merge, Timestamp::new);
@@ -298,6 +309,14 @@ public class Timestamp implements Comparable<Timestamp>, EpochSupplier
return factory.create(to.msb, newLsb, to.node);
}
+ static <T extends Timestamp> T removeFlags(T to, int addFlags, RawFactory<T> factory)
+ {
+ long newLsb = to.lsb & ~addFlags;
+ if (to.lsb == newLsb)
+ return to;
+ return factory.create(to.msb, newLsb, to.node);
+ }
+
public Timestamp logicalNext(Id node)
{
long lsb = this.lsb + HLC_INCR;
diff --git a/accord-core/src/main/java/accord/utils/Functions.java b/accord-core/src/main/java/accord/utils/Functions.java
index 8e25d80e..3ca5ee5e 100644
--- a/accord-core/src/main/java/accord/utils/Functions.java
+++ b/accord-core/src/main/java/accord/utils/Functions.java
@@ -21,6 +21,7 @@ package accord.utils;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
+import java.util.function.Predicate;
public class Functions
{
@@ -91,4 +92,20 @@ public class Functions
return result;
}
+ public static <T> Predicate<T> alwaysFalse()
+ {
+ return ignore -> false;
+ }
+ public static Predicate<Boolean> identityPredicate() { return v -> v; }
+
+ public static <I, O extends I> long foldlNonNull(I[] array, FoldToLong<O> foldl, long zero)
+ {
+ long result = zero;
+ for (I in : array)
+ {
+ if (in != null)
+ result = foldl.apply((O)in, result);
+ }
+ return result;
+ }
}
diff --git a/accord-core/src/main/java/accord/utils/ReducingIntervalMap.java b/accord-core/src/main/java/accord/utils/ReducingIntervalMap.java
index 9575fec8..0493e116 100644
--- a/accord-core/src/main/java/accord/utils/ReducingIntervalMap.java
+++ b/accord-core/src/main/java/accord/utils/ReducingIntervalMap.java
@@ -34,6 +34,7 @@ import com.google.common.annotations.VisibleForTesting;
import static accord.api.ProtocolModifiers.RangeSpec.isEndInclusive;
import static accord.api.ProtocolModifiers.RangeSpec.isStartExclusive;
import static accord.api.ProtocolModifiers.RangeSpec.isStartInclusive;
+import static accord.utils.Functions.alwaysFalse;
import static accord.utils.Invariants.illegalState;
/**
@@ -87,6 +88,11 @@ public class ReducingIntervalMap<K extends Comparable<? super K>, V>
return result;
}
+ public <V2> V2 foldl(BiFunction<V, V2, V2> reduce, V2 accumulator)
+ {
+ return foldl(reduce, accumulator, alwaysFalse());
+ }
+
public <V2> V2 foldl(BiFunction<V, V2, V2> reduce, V2 accumulator, Predicate<V2> terminate)
{
for (V value : values)
@@ -112,6 +118,10 @@ public class ReducingIntervalMap<K extends Comparable<? super K>, V>
return accumulator;
}
+ public <V2> V2 foldlWithBounds(QuadFunction<V, V2, K, K, V2> fold, V2 accumulator)
+ {
+ return foldlWithBounds(fold, accumulator, alwaysFalse());
+ }
public <V2> V2 foldlWithBounds(QuadFunction<V, V2, K, K, V2> fold, V2 accumulator, Predicate<V2> terminate)
{
for (int i = 0 ; i < values.length ; ++i)
diff --git a/accord-core/src/main/java/accord/utils/ReducingRangeMap.java b/accord-core/src/main/java/accord/utils/ReducingRangeMap.java
index 972df635..cf4b1352 100644
--- a/accord-core/src/main/java/accord/utils/ReducingRangeMap.java
+++ b/accord-core/src/main/java/accord/utils/ReducingRangeMap.java
@@ -28,6 +28,7 @@ import java.util.function.IntFunction;
import java.util.function.Predicate;
import static accord.api.ProtocolModifiers.RangeSpec.isEndInclusive;
+import static accord.utils.Functions.alwaysFalse;
import static accord.utils.SortedArrays.Search.FAST;
import static accord.utils.SortedArrays.exponentialSearch;
@@ -46,6 +47,8 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
}
}
+ public static final ReducingRangeMap EMPTY = new ReducingRangeMap();
+
public ReducingRangeMap()
{
super(RoutingKeys.EMPTY_KEYS_ARRAY, (V[])NO_OBJECTS);
@@ -66,11 +69,21 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
return foldl(routables, (a, b, f, ignore) -> f.apply(a, b), accumulator, fold, null, terminate);
}
+ public <V2> V2 foldlWithBounds(Routables<?> routables, QuadFunction<V, V2, RoutingKey, RoutingKey, V2> fold, V2 accumulator)
+ {
+ return foldlWithBounds(routables, fold, accumulator, alwaysFalse());
+ }
+
public <V2> V2 foldlWithBounds(Routables<?> routables, QuadFunction<V, V2, RoutingKey, RoutingKey, V2> fold, V2 accumulator, Predicate<V2> terminate)
{
return foldl(routables, (a, b, f, self, i, j, k) -> f.apply(a, b, k < 0 ? null : self.starts[k], self.starts[k+1]), accumulator, fold, this, terminate);
}
+ public <R extends Routable, V2> V2 foldlWithInputAndBounds(Routables<R> routables, IndexedRangeQuadFunction<V, V2, RoutingKey, RoutingKey, V2> fold, V2 accumulator)
+ {
+ return foldlWithInputAndBounds(routables, fold, accumulator, alwaysFalse());
+ }
+
public <R extends Routable, V2> V2 foldlWithInputAndBounds(Routables<R> routables, IndexedRangeQuadFunction<V, V2, RoutingKey, RoutingKey, V2> fold, V2 accumulator, Predicate<V2> terminate)
{
return foldl(routables, (a, b, f, self, i, j, k) -> f.apply(a, b, self.starts[k], self.starts[k+1], i, j), accumulator, fold, this, terminate);
@@ -116,6 +129,11 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
return foldlWithDefault(routables, (a, b, f, p) -> f.apply(a, b, p), defaultValue, accumulator, fold, p1, terminate);
}
+ public <V2, P1, P2> V2 foldlWithDefault(Routables<?> routables, QuadFunction<V, V2, P1, P2, V2> fold, V defaultValue, V2 accumulator, P1 p1, P2 p2)
+ {
+ return foldlWithDefault(routables, fold, defaultValue, accumulator, p1, p2, alwaysFalse());
+ }
+
public <V2, P1, P2> V2 foldlWithDefault(Routables<?> routables, QuadFunction<V, V2, P1, P2, V2> fold, V defaultValue, V2 accumulator, P1 p1, P2 p2, Predicate<V2> terminate)
{
return foldlWithDefault(routables, (v, v2, param1, param2, i, j, k) -> fold.apply(v, v2, param1, param2), defaultValue, accumulator, p1, p2, terminate);
@@ -166,6 +184,11 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
return accumulator;
}
+ public <A, P1, P2> A foldl(QuadFunction<V, A, P1, P2, A> fold, A accumulator, P1 p1, P2 p2)
+ {
+ return foldl(fold, accumulator, p1, p2, alwaysFalse());
+ }
+
public <A, P1, P2> A foldl(QuadFunction<V, A, P1, P2, A> fold, A accumulator, P1 p1, P2 p2, Predicate<A> terminate)
{
if (values.length == 0)
@@ -486,7 +509,7 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
for (int i = 0 ; i < values.length ; ++i)
{
if (include.test(values[i]))
- ranges[count++] = Range.create(starts[i], starts[i+1]);
+ ranges[count++] = Range.of(starts[i], starts[i + 1]);
}
if (count < ranges.length)
ranges = Arrays.copyOf(ranges, count);
@@ -494,6 +517,12 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
}
public <V2> ReducingRangeMap<V2> map(Function<V, V2> map, IntFunction<V2[]> allocator)
+ {
+ return map(map, allocator, (ReducingRangeMap<V2>) ReducingRangeMap.EMPTY, ReducingRangeMap::new);
+ }
+
+ // TODO (desired): this doesn't merge equivalent but non-equal V2 values
+ public <V2, M extends ReducingRangeMap<V2>> M map(Function<V, V2> map, IntFunction<V2[]> allocator, M empty, BiFunction<RoutingKey[], V2[], M> factory)
{
RoutingKey[] starts = null;
V2[] output = allocator.apply(values.length);
@@ -501,7 +530,7 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
for (int i = 0 ; i < values.length ; ++i)
{
V2 next = map.apply(values[i]);
- if (count == 0 ? next == null : (Objects.equals(next, output[i - 1])))
+ if (count == 0 ? next == null : (Objects.equals(next, output[count - 1])))
{
if (starts == null)
{
@@ -519,9 +548,8 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
{
if (starts != null)
{
- starts[count] = this.starts[this.starts.length - 1];
- if (output[count - 1] == null)
- --count;
+ if (output[count - 1] == null) --count;
+ else starts[count] = this.starts[this.starts.length - 1];
starts = Arrays.copyOf(starts, count + 1);
output = Arrays.copyOf(output, count);
@@ -534,8 +562,8 @@ public class ReducingRangeMap<V> extends ReducingIntervalMap<RoutingKey, V>
}
if (count == 0)
- return new ReducingRangeMap<>();
+ return empty;
- return new ReducingRangeMap<>(starts, output);
+ return factory.apply(starts, output);
}
}
diff --git a/accord-core/src/main/java/accord/utils/SortedListMap.java b/accord-core/src/main/java/accord/utils/SortedListMap.java
index daf816ae..3243a8b9 100644
--- a/accord-core/src/main/java/accord/utils/SortedListMap.java
+++ b/accord-core/src/main/java/accord/utils/SortedListMap.java
@@ -285,6 +285,11 @@ public class SortedListMap<K extends Comparable<? super K>, V> extends AbstractM
return result;
}
+ public long foldlNonNullValues(FoldToLong<V> foldl, long zero)
+ {
+ return Functions.foldlNonNull(values, foldl, zero);
+ }
+
public <O> O foldlNonNull(TriFunction<K, V, O, O> foldl, O zero)
{
return foldlNonNull(TriFunction::apply, foldl, zero);
diff --git a/accord-core/src/test/java/accord/impl/TestAgent.java b/accord-core/src/test/java/accord/impl/TestAgent.java
index 5b217dfe..1322f3eb 100644
--- a/accord-core/src/test/java/accord/impl/TestAgent.java
+++ b/accord-core/src/test/java/accord/impl/TestAgent.java
@@ -167,6 +167,12 @@ public class TestAgent implements Agent, OwnershipEventListener
return 0;
}
+ @Override
+ public boolean softReject(long unappliedCount, long cumulativeUnappliedAge)
+ {
+ return false;
+ }
+
@Override
public Txn emptySystemTxn(Txn.Kind kind, Domain domain)
{
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 42d18f93..1af21678 100644
--- a/accord-core/src/test/java/accord/impl/basic/Cluster.java
+++ b/accord-core/src/test/java/accord/impl/basic/Cluster.java
@@ -1377,7 +1377,7 @@ public class Cluster
RoutingKey blockedOnKey = waitingOn.lastWaitingOnKey();
if (blockedOnKey == null)
{
- blockedOnId = waitingOn.nextWaitingOn();
+ blockedOnId = waitingOn.nextWaitingOnTxn();
Invariants.require(!command.txnId().equals(blockedOnId));
if (blockedOnId != null)
blockedVia = command.partialDeps().participants(blockedOnId);
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 c5a54bb2..cdcd673e 100644
--- a/accord-core/src/test/java/accord/impl/list/ListAgent.java
+++ b/accord-core/src/test/java/accord/impl/list/ListAgent.java
@@ -204,6 +204,12 @@ public class ListAgent implements InMemoryAgent, CoordinatorEventListener, Owner
return 0;
}
+ @Override
+ public boolean softReject(long unappliedCount, long cumulativeUnappliedAge)
+ {
+ return false;
+ }
+
@Override
public int cfkPruneInterval()
{
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 aaeb0468..36c1cdd9 100644
--- a/accord-core/src/test/java/accord/impl/list/ListStore.java
+++ b/accord-core/src/test/java/accord/impl/list/ListStore.java
@@ -361,7 +361,7 @@ public class ListStore extends Snapshotter<ListStore.Snapshot> implements DataSt
private final Int2ObjectHashMap<Ranges> pendingFetches = new Int2ObjectHashMap<>();
@Override
- public FetchResult fetch(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges delegate, FetchKind kind)
+ public FetchResult image(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges delegate)
{
int storeId = safeStore.commandStore().id();
synchronized (this)
@@ -428,6 +428,12 @@ public class ListStore extends Snapshotter<ListStore.Snapshot> implements DataSt
return coordinator.result();
}
+ @Override
+ public FetchResult sync(Node node, SafeCommandStore safeStore, Map<TxnId, Ranges> atLeast, FetchRanges callback)
+ {
+ throw new UnsupportedOperationException();
+ }
+
static Timestamped<int[]> merge(Timestamped<int[]> a, Timestamped<int[]> b)
{
return Timestamped.merge(a, b, ListStore::isStrictPrefix, Arrays::equals);
diff --git a/accord-core/src/test/java/accord/impl/mock/MockStore.java b/accord-core/src/test/java/accord/impl/mock/MockStore.java
index e75b1362..6b0df3f4 100644
--- a/accord-core/src/test/java/accord/impl/mock/MockStore.java
+++ b/accord-core/src/test/java/accord/impl/mock/MockStore.java
@@ -151,13 +151,19 @@ public class MockStore implements DataStore
}
@Override
- public FetchResult fetch(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback, FetchKind kind)
+ public FetchResult image(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback)
{
callback.starting(ranges).started(Timestamp.NONE);
callback.fetched(ranges);
return new ImmediateFetchFuture(ranges);
}
+ @Override
+ public FetchResult sync(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback)
+ {
+ return image(node, safeStore, ranges, syncPoint, callback);
+ }
+
@Override
public void ensureDurable(CommandStore commandStore, RedundantBefore reportOnSuccess, int flags)
{
diff --git a/accord-core/src/test/java/accord/local/RedundantBeforeTest.java b/accord-core/src/test/java/accord/local/RedundantBeforeTest.java
index cd940a01..0d30fbfa 100644
--- a/accord-core/src/test/java/accord/local/RedundantBeforeTest.java
+++ b/accord-core/src/test/java/accord/local/RedundantBeforeTest.java
@@ -143,7 +143,9 @@ public class RedundantBeforeTest
RoutingKey key = keys[rs.nextInt(keys.length)];
addCanon(txnId, status, canon.get(key));
+ RedundantBefore prev = redundantBefore;
redundantBefore = RedundantBefore.merge(redundantBefore, RedundantBefore.create(Ranges.of(key.asRange()), txnId, status));
+ Assertions.assertThat(redundantBefore.isAtLeast(prev));
++ignore;
}
diff --git a/accord-core/src/test/java/accord/local/WaitingOnTest.java b/accord-core/src/test/java/accord/local/WaitingOnTest.java
index 606adebf..b28a8477 100644
--- a/accord-core/src/test/java/accord/local/WaitingOnTest.java
+++ b/accord-core/src/test/java/accord/local/WaitingOnTest.java
@@ -94,7 +94,7 @@ class WaitingOnTest
private static void validateNextWaitingOn(WaitingOn waitingOn)
{
- TxnId nextWaitingOn = waitingOn.nextWaitingOn();
+ TxnId nextWaitingOn = waitingOn.nextWaitingOnTxn();
List<TxnId> waitingOnTxns = waitingOnTxns(waitingOn);
TxnId maxTxn = waitingOnTxns.stream().max(Comparator.naturalOrder()).orElse(null);
TxnId minTxn = waitingOnTxns.stream().min(Comparator.naturalOrder()).orElse(null);
@@ -103,10 +103,10 @@ class WaitingOnTest
.isEqualTo(maxTxn);
WaitingOn.Update update = new WaitingOn.Update(waitingOn);
- Assertions.assertThat(update.minWaitingOnTxnId())
+ Assertions.assertThat(update.minWaitingOnTxn())
.describedAs("Update.minWaitingOnTxnId did not match expected")
.isEqualTo(minTxn);
- Assertions.assertThat(update.minWaitingOnTxnIdx())
+ Assertions.assertThat(update.minWaitingOnTxnIndex())
.describedAs("Update.minWaitingOnTxnIdx did not match expected")
.isEqualTo(minTxn == null ? -1 : waitingOn.indexOf(minTxn));
}
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 55d566c5..5c092cf3 100644
--- a/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
+++ b/accord-core/src/test/java/accord/local/cfk/CommandsForKeyTest.java
@@ -1100,6 +1100,12 @@ public class CommandsForKeyTest
return maxConflictsPruneInterval;
}
+ @Override
+ public boolean softReject(long unappliedCount, long cumulativeUnappliedAge)
+ {
+ return false;
+ }
+
@Override
public Txn emptySystemTxn(Txn.Kind kind, Domain domain)
{
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
index d68295e5..05edd981 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
@@ -109,6 +109,12 @@ public class MaelstromAgent implements Agent, CoordinatorEventListener, Ownershi
return 0;
}
+ @Override
+ public boolean softReject(long unappliedCount, long cumulativeUnappliedAge)
+ {
+ return false;
+ }
+
@Override
public int cfkPruneInterval()
{
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromStore.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromStore.java
index 75ad833b..44d0ffc6 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromStore.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromStore.java
@@ -30,6 +30,7 @@ import accord.local.RedundantBefore;
import accord.local.SafeCommandStore;
import accord.primitives.Ranges;
import accord.primitives.SyncPoint;
+import accord.primitives.TxnId;
import accord.utils.Timestamped;
import accord.utils.async.AsyncResults.SettableResult;
@@ -56,7 +57,7 @@ public class MaelstromStore implements DataStore
}
@Override
- public FetchResult fetch(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback, FetchKind kind)
+ public FetchResult image(Node node, SafeCommandStore safeStore, Ranges ranges, SyncPoint syncPoint, FetchRanges callback)
{
return new ImmediateFetchResult(ranges);
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org