You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by be...@apache.org on 2025/01/14 15:08:18 UTC
(cassandra-accord) branch trunk updated: FetchRequest should report as unavailable any slice that executes in a later epoch that is not owned by the replicas
This is an automated email from the ASF dual-hosted git repository.
benedict pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra-accord.git
The following commit(s) were added to refs/heads/trunk by this push:
new 014f0c22 FetchRequest should report as unavailable any slice that executes in a later epoch that is not owned by the replicas
014f0c22 is described below
commit 014f0c2267b8d8c6b7cbdd63f590af7f84a0e71b
Author: Benedict Elliott Smith <be...@apache.org>
AuthorDate: Sat Jan 4 14:00:16 2025 +0000
FetchRequest should report as unavailable any slice that executes in a later epoch that is not owned by the replicas
Improve:
- Remove GetMaxConflict; use local MaxConflict collection
Fix:
- Invalidated should retain StoreParticipants so we can update CFK on journal replay
- loading pruned uninitialised commands via CFK: make sure hasTouched contains key so that if invalidated we are notified
- updateExecuteAtLeast should always be higher than TxnId
- Async CFK callbacks treated pruned transactions incorrectly
- node.withEpoch when ExecuteEphemeralRead in futureEpoch
- Deps.without should be key/range aware
- Durably mark bootstrapBeganAt and safeToReadAt in MaxConflicts
- Don't attempt to calculate local deps when DepsErased in GetLatestDeps (command has durably applied to this shard)
- filter StoreParticipants before invoking shouldCleanup
- CFK should treat !stillTouches as outOfRange (rather than !touches)
---
.../accord/coordinate/ExecuteEphemeralRead.java | 5 +-
.../java/accord/coordinate/FetchMaxConflict.java | 123 ------------
.../src/main/java/accord/coordinate/Recover.java | 10 +-
.../accord/coordinate/tracking/SimpleTracker.java | 5 -
.../java/accord/impl/AbstractFetchCoordinator.java | 59 ++++--
.../src/main/java/accord/impl/CommandChange.java | 70 +++----
.../src/main/java/accord/local/Bootstrap.java | 139 ++++---------
.../src/main/java/accord/local/Command.java | 23 ++-
.../src/main/java/accord/local/CommandStore.java | 118 +++++++++--
.../src/main/java/accord/local/CommandStores.java | 8 -
.../src/main/java/accord/local/Commands.java | 4 +-
.../main/java/accord/local/SafeCommandStore.java | 14 +-
.../main/java/accord/local/cfk/CommandsForKey.java | 185 +++++++++---------
.../src/main/java/accord/local/cfk/NotifySink.java | 1 -
.../main/java/accord/local/cfk/PostProcess.java | 9 +-
.../src/main/java/accord/local/cfk/Pruning.java | 2 +
.../java/accord/local/cfk/SafeCommandsForKey.java | 9 +-
.../src/main/java/accord/local/cfk/Updating.java | 75 +++++--
.../src/main/java/accord/local/cfk/Utils.java | 25 +++
.../src/main/java/accord/messages/Accept.java | 2 +-
.../main/java/accord/messages/BeginRecovery.java | 152 ++++++++-------
.../main/java/accord/messages/GetLatestDeps.java | 13 +-
.../main/java/accord/messages/GetMaxConflict.java | 133 -------------
.../src/main/java/accord/messages/MessageType.java | 2 -
.../src/main/java/accord/messages/ReadData.java | 4 +-
.../java/accord/messages/ReadEphemeralTxnData.java | 4 +-
.../java/accord/messages/WaitUntilApplied.java | 2 +-
.../src/main/java/accord/primitives/Deps.java | 5 +-
.../src/main/java/accord/primitives/KeyDeps.java | 68 +++----
.../src/main/java/accord/primitives/RangeDeps.java | 118 +++++------
.../accord/utils/BTreeReducingIntervalMap.java | 2 +
.../main/java/accord/utils/RelationMultiMap.java | 216 +++++++++++++++------
.../src/main/java/accord/utils/SortedArrays.java | 109 ++++++++---
.../accord/burn/BurnTestConfigurationService.java | 10 +
.../accord/impl/basic/DelayedCommandStores.java | 34 +++-
.../java/accord/impl/basic/InMemoryJournal.java | 48 ++---
.../src/test/java/accord/impl/list/ListAgent.java | 3 +-
.../accord/impl/list/ListFetchCoordinator.java | 34 +++-
.../test/java/accord/primitives/KeyDepsTest.java | 34 ++--
39 files changed, 948 insertions(+), 929 deletions(-)
diff --git a/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java b/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
index d518595d..cfd5b083 100644
--- a/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
+++ b/accord-core/src/main/java/accord/coordinate/ExecuteEphemeralRead.java
@@ -39,6 +39,7 @@ import accord.primitives.Txn;
import accord.primitives.TxnId;
import accord.topology.Topologies;
import accord.utils.Invariants;
+import accord.utils.WrappableException;
import static accord.coordinate.ReadCoordinator.Action.Aborted;
import static accord.coordinate.ReadCoordinator.Action.Approve;
@@ -98,7 +99,9 @@ public class ExecuteEphemeralRead extends ReadCoordinator<ReadReply>
if (ok.futureEpoch > allTopologies.currentEpoch())
{
// TODO (expected): only submit new requests for the keys that execute in a later epoch
- new ExecuteEphemeralRead(node, node.topology().preciseEpochs(route, ok.futureEpoch, ok.futureEpoch), route, txnId.withEpoch(ok.futureEpoch), txn, ok.futureEpoch, deps, callback).start();
+ node.withEpoch(ok.futureEpoch, callback, t -> WrappableException.wrap(t), () -> {
+ new ExecuteEphemeralRead(node, node.topology().preciseEpochs(route, ok.futureEpoch, ok.futureEpoch), route, txnId.withEpoch(ok.futureEpoch), txn, ok.futureEpoch, deps, callback).start();
+ });
return Aborted;
}
diff --git a/accord-core/src/main/java/accord/coordinate/FetchMaxConflict.java b/accord-core/src/main/java/accord/coordinate/FetchMaxConflict.java
deleted file mode 100644
index b2038f2a..00000000
--- a/accord-core/src/main/java/accord/coordinate/FetchMaxConflict.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package accord.coordinate;
-
-import java.util.Collection;
-
-import accord.coordinate.tracking.QuorumTracker;
-import accord.local.Node;
-import accord.messages.Callback;
-import accord.messages.GetMaxConflict;
-import accord.messages.GetMaxConflict.GetMaxConflictOk;
-import accord.primitives.FullRoute;
-import accord.primitives.Routables;
-import accord.primitives.Timestamp;
-import accord.topology.Topologies;
-import accord.utils.async.AsyncResult;
-import accord.utils.async.AsyncResults;
-
-import static accord.coordinate.tracking.RequestStatus.Failed;
-import static accord.coordinate.tracking.RequestStatus.Success;
-
-/**
- * Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
- * If we are preempted by a recovery coordinator, we abort and let them complete (and notify us about the execution result)
- *
- * TODO (expected): we don't need this anymore, we can just use the local MaxConflicts collection when creating a snapshot for streaming
- */
-public class FetchMaxConflict extends AbstractCoordinatePreAccept<Timestamp, GetMaxConflictOk>
-{
- final QuorumTracker tracker;
- Timestamp maxConflict;
- long executionEpoch;
-
- private FetchMaxConflict(Node node, FullRoute<?> route, long executionEpoch)
- {
- this(node, route, executionEpoch, node.topology().withUnsyncedEpochs(route, executionEpoch, executionEpoch));
- }
-
- private FetchMaxConflict(Node node, FullRoute<?> route, long executionEpoch, Topologies topologies)
- {
- super(node, route, null, topologies);
- this.maxConflict = Timestamp.NONE;
- this.executionEpoch = executionEpoch;
- this.tracker = new QuorumTracker(topologies);
- }
-
- public static AsyncResult<Timestamp> fetchMaxConflict(Node node, Routables<?> keysOrRanges)
- {
- long epoch = node.epoch();
- FullRoute<?> route = node.computeRoute(epoch, keysOrRanges);
- // TODO (required): need to ensure we permanently fail any bootstrap that is now impossible and mark as stale
- TopologyMismatch mismatch = TopologyMismatch.checkForMismatchOrPendingRemoval(node.topology().globalForEpoch(epoch), null, route.homeKey(), keysOrRanges);
- if (mismatch != null)
- return AsyncResults.failure(mismatch);
- FetchMaxConflict coordinate = new FetchMaxConflict(node, route, epoch);
- coordinate.start();
- return coordinate;
- }
-
- @Override
- void contact(Collection<Node.Id> nodes, Topologies topologies, Callback<GetMaxConflictOk> callback)
- {
- node.send(nodes, to -> new GetMaxConflict(to, topologies, route, executionEpoch), callback);
- }
-
- @Override
- void onSuccessInternal(Node.Id from, GetMaxConflictOk reply)
- {
- maxConflict = Timestamp.max(reply.maxConflict, maxConflict);
- executionEpoch = Math.max(executionEpoch, reply.latestEpoch);
-
- if (tracker.recordSuccess(from) == Success)
- onPreAcceptedOrNewEpoch();
- }
-
- @Override
- boolean onExtraSuccessInternal(Node.Id from, GetMaxConflictOk reply)
- {
- maxConflict = Timestamp.max(reply.maxConflict, maxConflict);
- return true;
- }
-
- @Override
- void onFailureInternal(Node.Id from, Throwable failure)
- {
- if (tracker.recordFailure(from) == Failed)
- tryFailure(failure);
- }
-
- @Override
- void onNewEpochTopologyMismatch(TopologyMismatch mismatch)
- {
- tryFailure(mismatch);
- }
-
- @Override
- long executeAtEpoch()
- {
- return executionEpoch;
- }
-
- @Override
- void onPreAccepted(Topologies topologies)
- {
- setSuccess(maxConflict);
- }
-}
diff --git a/accord-core/src/main/java/accord/coordinate/Recover.java b/accord-core/src/main/java/accord/coordinate/Recover.java
index a07a0a2e..3cf0a90f 100644
--- a/accord-core/src/main/java/accord/coordinate/Recover.java
+++ b/accord-core/src/main/java/accord/coordinate/Recover.java
@@ -342,17 +342,17 @@ public class Recover implements Callback<RecoverReply>, BiConsumer<Result, Throw
Invariants.checkState(committedExecuteAt == null || committedExecuteAt.equals(txnId));
// should all be PreAccept
Deps proposeDeps = LatestDeps.mergeProposal(recoverOkList, ok -> ok == null ? null : ok.deps);
- Deps earlierAcceptedNoWitness = Deps.merge(recoverOkList, recoverOkList.size(), List::get, ok -> ok.earlierAcceptedNoWitness);
- Deps earlierCommittedWitness = Deps.merge(recoverOkList, recoverOkList.size(), List::get, ok -> ok.earlierCommittedWitness);
- earlierAcceptedNoWitness = earlierAcceptedNoWitness.without(earlierCommittedWitness::contains);
- if (!earlierAcceptedNoWitness.isEmpty())
+ Deps earlierWait = Deps.merge(recoverOkList, recoverOkList.size(), List::get, ok -> ok.earlierWait);
+ Deps earlierNoWait = Deps.merge(recoverOkList, recoverOkList.size(), List::get, ok -> ok.earlierNoWait);
+ earlierWait = earlierWait.without(earlierNoWait);
+ if (!earlierWait.isEmpty())
{
// If there exist commands that were proposed an earlier 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 finish committing before retrying recovery.
// See whitepaper for more details
- awaitCommits(node, earlierAcceptedNoWitness).addCallback((success, failure) -> {
+ awaitCommits(node, earlierWait).addCallback((success, failure) -> {
if (failure != null) accept(null, failure);
else retry();
});
diff --git a/accord-core/src/main/java/accord/coordinate/tracking/SimpleTracker.java b/accord-core/src/main/java/accord/coordinate/tracking/SimpleTracker.java
index 25c7bb3f..05556235 100644
--- a/accord-core/src/main/java/accord/coordinate/tracking/SimpleTracker.java
+++ b/accord-core/src/main/java/accord/coordinate/tracking/SimpleTracker.java
@@ -34,11 +34,6 @@ public abstract class SimpleTracker<ST extends ShardTracker> extends PreAcceptTr
super(topologies, arrayFactory, trackerFactory);
}
- public SimpleTracker(Topologies topologies, IntFunction<ST[]> arrayFactory, ShardFactory<ST> trackerFactory)
- {
- super(topologies, arrayFactory, trackerFactory);
- }
-
public RequestStatus recordSuccess(Id from, boolean withFastPathTimestamp) { return recordSuccess(from); }
public RequestStatus recordDelayed(Id from) { return NoChange; }
public boolean hasFastPathAccepted() { return false; }
diff --git a/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java b/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
index 085b509a..92d61dc0 100644
--- a/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
+++ b/accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java
@@ -23,6 +23,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import accord.local.Command;
import accord.local.SafeCommandStore;
import accord.messages.ReadData;
import accord.utils.async.AsyncChain;
@@ -50,8 +51,11 @@ import accord.utils.Invariants;
import accord.utils.async.AsyncChains;
import accord.utils.async.AsyncResult;
import accord.utils.async.AsyncResults;
+
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import static accord.messages.ReadEphemeralTxnData.retryInLaterEpoch;
import static accord.primitives.SaveStatus.Applied;
import static accord.primitives.SaveStatus.TruncatedApply;
import static accord.messages.ReadData.CommitOrReadNack.Insufficient;
@@ -123,13 +127,8 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
}
protected abstract PartialTxn rangeReadTxn(Ranges ranges);
-
protected abstract void onReadOk(Node.Id from, CommandStore commandStore, Data data, Ranges ranges);
-
- protected FetchRequest newFetchRequest(long sourceEpoch, TxnId syncId, Ranges ranges, PartialDeps partialDeps, PartialTxn partialTxn)
- {
- return new FetchRequest(sourceEpoch, syncId, ranges, partialDeps, rangeReadTxn(ranges));
- }
+ protected abstract FetchRequest newFetchRequest(long sourceEpoch, TxnId syncId, Ranges ranges, PartialDeps partialDeps, PartialTxn partialTxn);
@Override
public void contact(Node.Id to, Ranges ranges)
@@ -187,7 +186,7 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
}
// TODO (now): make sure it works if invoked in either order
- inflight.remove(key).started(ok.maxApplied);
+ inflight.remove(key).started(ok.safeToReadAfter);
onReadOk(to, commandStore, ok.data, received);
// received must be invoked after submitting the persistence future, as it triggers onDone
// which creates a ReducingFuture over {@code persisting}
@@ -237,11 +236,16 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
// TODO (expected): implement abort
}
- public static class FetchRequest extends ReadData
+ public static abstract class FetchRequest extends ReadData
{
+ // Note for future: we cannot safely execute on an Erased sync point without more work.
+ // Specifically, if the range has partially lost ownership on the recipient, the SyncPoint
+ // will not represent a safe point to snapshot from, and we won't have enough information to
+ // report the range as unavailable.
private static final ExecuteOn EXECUTE_ON = new ExecuteOn(Applied, TruncatedApply);
public final PartialTxn read;
public final PartialDeps partialDeps;
+ private transient Timestamp safeToReadAfter;
public FetchRequest(long sourceEpoch, TxnId syncId, Ranges ranges, PartialDeps partialDeps, PartialTxn partialTxn)
{
@@ -268,22 +272,45 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
return read.read(safeStore, executeAt, unavailable);
}
+ // must be invoked by implementations some time after the read has started OR must override safeToReadAt()
+ protected void readStarted(SafeCommandStore safeStore, Ranges unavailable)
+ {
+ safeToReadAfter = Timestamp.nonNullOrMax(Timestamp.NONE, Timestamp.nonNullOrMax(safeToReadAfter, safeStore.commandStore().unsafeGetMaxConflicts().foldl(Timestamp::nonNullOrMax)));
+ }
+
+ protected Timestamp safeToReadAfter()
+ {
+ return safeToReadAfter;
+ }
+
@Override
protected void readComplete(CommandStore commandStore, Data result, Ranges unavailable)
{
- Ranges reportUnavailable = unavailable.slice((Ranges)this.readScope, Minimal);
+ Ranges reportUnavailable = unavailable == null ? null : unavailable.slice((Ranges)this.readScope, Minimal);
super.readComplete(commandStore, result, reportUnavailable);
}
@Override
protected ReadOk constructReadOk(Ranges unavailable, Data data)
{
- return new FetchResponse(unavailable, data, maxApplied());
+ Timestamp safeToReadAfter = safeToReadAfter();
+ Invariants.checkState(data == null || safeToReadAfter != null);
+ return new FetchResponse(unavailable, data, safeToReadAfter);
}
- protected Timestamp maxApplied()
+ @Override
+ protected void read(SafeCommandStore safeStore, Command command)
{
- return null;
+ long retryInLaterEpoch = retryInLaterEpoch(executeAtEpoch, safeStore, command);
+ if (retryInLaterEpoch > 0)
+ {
+ Ranges unavailable = ((Ranges)readScope).slice(safeStore.ranges().allAt(executeAtEpoch), Minimal);
+ readComplete(safeStore.commandStore(), null, unavailable);
+ }
+ else
+ {
+ super.read(safeStore, command);
+ }
}
@Override
@@ -295,11 +322,13 @@ public abstract class AbstractFetchCoordinator extends FetchCoordinator
public static class FetchResponse extends ReadOk
{
- public final @Nullable Timestamp maxApplied;
- public FetchResponse(@Nullable Ranges unavailable, @Nullable Data data, @Nullable Timestamp maxApplied)
+ // only null if retryInFutureEpoch is set
+ public final @Nullable Timestamp safeToReadAfter;
+
+ public FetchResponse(@Nullable Ranges unavailable, @Nullable Data data, @Nonnull Timestamp safeToReadAfter)
{
super(unavailable, data);
- this.maxApplied = maxApplied;
+ this.safeToReadAfter = safeToReadAfter;
}
@Override
diff --git a/accord-core/src/main/java/accord/impl/CommandChange.java b/accord-core/src/main/java/accord/impl/CommandChange.java
index df74bf7e..5d0bc37d 100644
--- a/accord-core/src/main/java/accord/impl/CommandChange.java
+++ b/accord-core/src/main/java/accord/impl/CommandChange.java
@@ -42,25 +42,22 @@ import accord.utils.Invariants;
import static accord.api.Journal.Load;
import static accord.api.Journal.Load.ALL;
-import static accord.impl.CommandChange.Fields.ACCEPTED;
-import static accord.impl.CommandChange.Fields.CLEANUP;
-import static accord.impl.CommandChange.Fields.DURABILITY;
-import static accord.impl.CommandChange.Fields.EXECUTES_AT_LEAST;
-import static accord.impl.CommandChange.Fields.EXECUTE_AT;
-import static accord.impl.CommandChange.Fields.FIELDS;
-import static accord.impl.CommandChange.Fields.PARTIAL_DEPS;
-import static accord.impl.CommandChange.Fields.PARTIAL_TXN;
-import static accord.impl.CommandChange.Fields.PARTICIPANTS;
-import static accord.impl.CommandChange.Fields.PROMISED;
-import static accord.impl.CommandChange.Fields.RESULT;
-import static accord.impl.CommandChange.Fields.SAVE_STATUS;
-import static accord.impl.CommandChange.Fields.WAITING_ON;
-import static accord.impl.CommandChange.Fields.WRITES;
+import static accord.impl.CommandChange.Field.ACCEPTED;
+import static accord.impl.CommandChange.Field.CLEANUP;
+import static accord.impl.CommandChange.Field.DURABILITY;
+import static accord.impl.CommandChange.Field.EXECUTES_AT_LEAST;
+import static accord.impl.CommandChange.Field.EXECUTE_AT;
+import static accord.impl.CommandChange.Field.FIELDS;
+import static accord.impl.CommandChange.Field.PARTIAL_DEPS;
+import static accord.impl.CommandChange.Field.PARTIAL_TXN;
+import static accord.impl.CommandChange.Field.PARTICIPANTS;
+import static accord.impl.CommandChange.Field.PROMISED;
+import static accord.impl.CommandChange.Field.RESULT;
+import static accord.impl.CommandChange.Field.SAVE_STATUS;
+import static accord.impl.CommandChange.Field.WAITING_ON;
+import static accord.impl.CommandChange.Field.WRITES;
import static accord.local.Cleanup.NO;
import static accord.local.Cleanup.TRUNCATE_WITH_OUTCOME;
-import static accord.primitives.Known.KnownDeps.DepsErased;
-import static accord.primitives.Known.KnownDeps.DepsUnknown;
-import static accord.primitives.Known.KnownDeps.NoDeps;
import static accord.primitives.SaveStatus.TruncatedApplyWithOutcome;
import static accord.primitives.Status.Durability.NotDurable;
import static accord.utils.Invariants.illegalState;
@@ -68,7 +65,7 @@ import static accord.utils.Invariants.illegalState;
public class CommandChange
{
// This enum is order-dependent
- public enum Fields
+ public enum Field
{
PARTICIPANTS, // stored first so we can index it
SAVE_STATUS,
@@ -85,7 +82,7 @@ public class CommandChange
RESULT,
;
- public static final Fields[] FIELDS = values();
+ public static final Field[] FIELDS = values();
}
public static class Builder
@@ -376,10 +373,7 @@ public class CommandChange
attrs.setParticipants(participants.filter(StoreParticipants.Filter.LOAD, redundantBefore, txnId, saveStatus.known.executeAt.isDecidedAndKnownToExecute() ? executeAt : null));
if (participants != null)
attrs.setParticipants(participants);
- if (partialDeps != null &&
- (saveStatus.known.deps != NoDeps &&
- saveStatus.known.deps != DepsErased &&
- saveStatus.known.deps != DepsUnknown))
+ if (partialDeps != null && saveStatus.known.deps.hasProposedOrDecidedDeps())
attrs.partialDeps(partialDeps);
switch (saveStatus.known.outcome)
@@ -403,12 +397,12 @@ public class CommandChange
case PreAccepted:
return Command.PreAccepted.preAccepted(attrs, executeAt, promised);
case AcceptedInvalidate:
+ if (!saveStatus.known.isDefinitionKnown())
+ return Command.AcceptedInvalidateWithoutDefinition.acceptedInvalidate(attrs, promised, acceptedOrCommitted);
case Accepted:
case PreCommitted:
- if (saveStatus == SaveStatus.AcceptedInvalidate)
- return Command.AcceptedInvalidateWithoutDefinition.acceptedInvalidate(attrs, promised, acceptedOrCommitted);
- else
- return Command.Accepted.accepted(attrs, saveStatus, executeAt, promised, acceptedOrCommitted);
+ return Command.Accepted.accepted(attrs, saveStatus, executeAt, promised, acceptedOrCommitted);
+
case Committed:
case Stable:
return Command.Committed.committed(attrs, saveStatus, executeAt, promised, acceptedOrCommitted, waitingOn);
@@ -443,7 +437,7 @@ public class CommandChange
// TODO (expected): why are we saving Durability here for erased commands?
return Command.Truncated.erased(attrs.txnId(), attrs.durability(), attrs.participants());
case Invalidated:
- return Command.Truncated.invalidated(attrs.txnId());
+ return Command.Truncated.invalidated(attrs.txnId(), attrs.participants());
}
}
@@ -486,10 +480,10 @@ public class CommandChange
* Managing masks
*/
- public static int mask(Fields... fields)
+ public static int mask(Field... fields)
{
int mask = -1;
- for (Fields field : fields)
+ for (Field field : fields)
mask &= ~(1 << field.ordinal());
return mask;
}
@@ -541,7 +535,7 @@ public class CommandChange
return flags;
}
- private static <OBJ, VAL> int collectFlags(OBJ lo, OBJ ro, Function<OBJ, VAL> convert, boolean allowClassMismatch, Fields field, int flags)
+ private static <OBJ, VAL> int collectFlags(OBJ lo, OBJ ro, Function<OBJ, VAL> convert, boolean allowClassMismatch, Field field, int flags)
{
VAL l = null;
VAL r = null;
@@ -577,13 +571,13 @@ public class CommandChange
return flags;
}
- public static int setFieldChanged(Fields field, int oldFlags)
+ public static int setFieldChanged(Field field, int oldFlags)
{
return oldFlags | (0x10000 << field.ordinal());
}
@VisibleForTesting
- public static boolean getFieldChanged(Fields field, int oldFlags)
+ public static boolean getFieldChanged(Field field, int oldFlags)
{
return (oldFlags & (0x10000 << field.ordinal())) != 0;
}
@@ -593,29 +587,29 @@ public class CommandChange
return flags >>> 16;
}
- public static Fields nextSetField(int iterable)
+ public static Field nextSetField(int iterable)
{
int i = Integer.numberOfTrailingZeros(Integer.lowestOneBit(iterable));
return i == 32 ? null : FIELDS[i];
}
- public static int unsetIterableFields(Fields field, int iterable)
+ public static int unsetIterableFields(Field field, int iterable)
{
return iterable & ~(1 << field.ordinal());
}
@VisibleForTesting
- public static boolean getFieldIsNull(Fields field, int oldFlags)
+ public static boolean getFieldIsNull(Field field, int oldFlags)
{
return (oldFlags & (1 << field.ordinal())) != 0;
}
- public static int unsetFieldIsNull(Fields field, int oldFlags)
+ public static int unsetFieldIsNull(Field field, int oldFlags)
{
return oldFlags & ~(1 << field.ordinal());
}
- public static int setFieldIsNull(Fields field, int oldFlags)
+ public static int setFieldIsNull(Field field, int oldFlags)
{
return oldFlags | (1 << field.ordinal());
}
diff --git a/accord-core/src/main/java/accord/local/Bootstrap.java b/accord-core/src/main/java/accord/local/Bootstrap.java
index c466a84a..d166fa35 100644
--- a/accord-core/src/main/java/accord/local/Bootstrap.java
+++ b/accord-core/src/main/java/accord/local/Bootstrap.java
@@ -18,11 +18,10 @@
package accord.local;
-import java.util.ArrayList;
-import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
-import javax.annotation.Nullable;
+
+import javax.annotation.Nonnull;
import accord.api.Agent;
import accord.api.DataStore;
@@ -30,13 +29,13 @@ import accord.api.DataStore.FetchRanges;
import accord.api.DataStore.FetchResult;
import accord.api.DataStore.StartingRangeFetch;
import accord.coordinate.CoordinateSyncPoint;
-import accord.coordinate.FetchMaxConflict;
import accord.primitives.Ranges;
import accord.primitives.Routable;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
import accord.utils.DeterministicIdentitySet;
import accord.utils.Invariants;
+import accord.utils.ReducingRangeMap;
import accord.utils.async.AsyncResult;
import accord.utils.async.AsyncResults;
@@ -78,15 +77,11 @@ import static accord.utils.Invariants.illegalState;
*/
class Bootstrap
{
- static class SafeToRead
+ static class UnsafeToRead
{
final Ranges ranges;
- // we default to MAX_VALUE because *starting* commands that haven't *started* _will_ start after those that have already
- int startedAt = Integer.MAX_VALUE;
- Timestamp safeToReadAt;
- List<SafeToRead> overlaps = new ArrayList<>();
- SafeToRead(Ranges ranges)
+ UnsafeToRead(Ranges ranges)
{
this.ranges = ranges;
}
@@ -95,11 +90,12 @@ class Bootstrap
// an attempt to fetch some portion of the range we are bootstrapping
class Attempt implements FetchRanges, BiConsumer<Object, Throwable>
{
- final List<SafeToRead> states = new ArrayList<>();
+ final DeterministicIdentitySet<UnsafeToRead> unsafeToReads = new DeterministicIdentitySet<>();
+ ReducingRangeMap<Timestamp> safeToReadAts = new ReducingRangeMap<>();
+
Runnable cancel;
FetchResult fetch;
- int logicalClock;
/**
* valid: the ranges we are still meant to fetch - i.e. excluding those that have been invalidated or marked failed
*/
@@ -196,16 +192,8 @@ class Bootstrap
store.markUnsafeToRead(ranges);
// find any pre-existing states we may overlap with, mark both as overlaps, and add ourselves to the collection
- SafeToRead newState = new SafeToRead(ranges);
- for (SafeToRead maybeOverlaps : states)
- {
- if (maybeOverlaps.ranges.intersects(newState.ranges))
- {
- maybeOverlaps.overlaps.add(newState);
- newState.overlaps.add(maybeOverlaps);
- }
- }
- states.add(newState);
+ UnsafeToRead newState = new UnsafeToRead(ranges);
+ unsafeToReads.add(newState);
return new StartingRangeFetch()
{
@@ -224,79 +212,34 @@ class Bootstrap
};
}
- private void started(SafeToRead state, @Nullable Timestamp maxApplied)
+ private void started(UnsafeToRead state, @Nonnull Timestamp maxAppliedLessOrEqualTo)
{
- if (maxApplied == null)
- {
- synchronized (this)
- {
- if (state.startedAt == Integer.MAX_VALUE)
- state.startedAt = logicalClock++;
- }
- // TODO (expected): associate callbacks with this CommandStore, to remove synchronization
- FetchMaxConflict.fetchMaxConflict(node, state.ranges)
- .begin((executeAt, failure) -> {
- store.maybeExecuteImmediately(() -> safeToReadCallback(state, executeAt, failure));
- });
- }
- else
+ Invariants.checkState(maxAppliedLessOrEqualTo != null);
+ synchronized (this)
{
- synchronized (this)
- {
- Timestamp safeToReadAt = maxApplied.compareTo(globalSyncId) < 0 ? globalSyncId : maxApplied.next();
- if (state.startedAt == Integer.MAX_VALUE)
- state.startedAt = logicalClock++;
- state.safeToReadAt = safeToReadAt;
- maybeComplete(state);
- }
- }
- }
-
+ if (!unsafeToReads.remove(state))
+ return;
- private void safeToReadCallback(SafeToRead state, Timestamp executeAt, Throwable failure)
- {
- if (failure == null)
- {
- synchronized (this)
- {
- state.safeToReadAt = executeAt;
- maybeComplete(state);
- }
- }
- else
- {
- // TODO (expected): first check to see if we are still relevant
- CommandStore store = CommandStore.current();
- node.agent().onFailedBootstrap("SafeToRead", state.ranges, () -> {
- store.maybeExecuteImmediately(() -> started(state, null));
- }, failure);
+ Timestamp safeToReadAt = maxAppliedLessOrEqualTo.compareTo(globalSyncId) <= 0 ? globalSyncId : maxAppliedLessOrEqualTo.next();
+ safeToReadAts = ReducingRangeMap.add(safeToReadAts, state.ranges, safeToReadAt);
+ 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(SafeToRead state)
+ private synchronized void cancel(UnsafeToRead state)
{
- if (state.startedAt != Integer.MAX_VALUE)
+ if (!unsafeToReads.remove(state))
throw illegalState("Tried to cancel starting a fetch that had already started");
- state.startedAt = Integer.MIN_VALUE;
-
- // unlink from other overlaps, and remove ourselves from states collection
- for (SafeToRead overlap : state.overlaps)
- overlap.overlaps.remove(state);
- states.remove(state);
- // then process those overlaps in case to mark safeToRead
- for (SafeToRead overlap : states)
- {
- if (fetched.intersects(overlap.ranges))
- maybeComplete(overlap);
- }
+ 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(SafeToRead state)
+ private synchronized void abort(UnsafeToRead state)
{
+ unsafeToReads.remove(state);
// TODO (expected, consider): are there any edge cases here?
}
@@ -307,14 +250,7 @@ class Bootstrap
return;
fetched = fetched.with(ranges);
- for (SafeToRead state : states)
- {
- if (ranges.intersects(state.ranges))
- {
- // TODO (desired): try to uncontact if not finished
- maybeComplete(state);
- }
- }
+ maybeComplete(ranges);
}
@Override
@@ -346,28 +282,23 @@ class Bootstrap
* 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(SafeToRead state)
+ private synchronized void maybeComplete(Ranges ranges)
{
- if (state.safeToReadAt == null)
+ Ranges newDone = fetched.slice(ranges.without(fetchedAndSafeToRead), Minimal);
+ if (newDone.isEmpty())
return;
- Ranges newDone = fetched.slice(state.ranges.without(fetchedAndSafeToRead), Minimal);
+ for (UnsafeToRead unsafeToRead : unsafeToReads)
+ newDone = newDone.without(unsafeToRead.ranges);
+
if (newDone.isEmpty())
return;
- for (SafeToRead overlap : state.overlaps)
- {
- // if the overlapping operation took its snapshot after us OR hasn't yet got its snapshot
- // then we are not a definitive bound for safely starting reads, so remove the range
- if (overlap.startedAt > state.startedAt)
- {
- newDone = newDone.without(overlap.ranges);
- if (newDone.isEmpty())
- return;
- }
- }
-
- store.markSafeToRead(globalSyncId, state.safeToReadAt, newDone);
+ safeToReadAts.foldlWithInputAndBounds(newDone, (safeToReadAt, s, start, end, i, j) -> {
+ Ranges mark = s.slice(Ranges.of(start.rangeFactory().newRange(start, end)), Minimal);
+ store.markSafeToRead(globalSyncId, safeToReadAt, mark);
+ return s;
+ }, newDone, i -> false);
fetchedAndSafeToRead = fetchedAndSafeToRead.with(newDone);
maybeComplete();
}
diff --git a/accord-core/src/main/java/accord/local/Command.java b/accord-core/src/main/java/accord/local/Command.java
index 62a85cf9..72cf30e8 100644
--- a/accord-core/src/main/java/accord/local/Command.java
+++ b/accord-core/src/main/java/accord/local/Command.java
@@ -123,9 +123,9 @@ public abstract class Command implements CommonAttributes
return Executed.executed(common, status, executeAt, promised, accepted, waitingOn, writes, result);
}
- public static Truncated invalidated(TxnId txnId)
+ public static Truncated invalidated(TxnId txnId, StoreParticipants participants)
{
- return Truncated.invalidated(txnId);
+ return Truncated.invalidated(txnId, participants);
}
public static Truncated truncatedApply(CommonAttributes common, SaveStatus saveStatus, Timestamp executeAt, Writes writes, Result result)
@@ -768,14 +768,14 @@ public abstract class Command implements CommonAttributes
public static Truncated invalidated(Command command)
{
Invariants.checkState(!command.hasBeen(Status.PreCommitted));
- return invalidated(command.txnId());
+ return invalidated(command.txnId(), command.participants());
}
- public static Truncated invalidated(TxnId txnId)
+ public static Truncated invalidated(TxnId txnId, StoreParticipants participants)
{
// TODO (expected): migrate to using null for executeAt when invalidated
// TODO (expected): is UniversalOrInvalidated correct here? Should we have a lower implication pure Invalidated?
- return validate(new Truncated(txnId, SaveStatus.Invalidated, UniversalOrInvalidated, StoreParticipants.empty(txnId), Timestamp.NONE, null, null));
+ return validate(new Truncated(txnId, SaveStatus.Invalidated, UniversalOrInvalidated, participants, Timestamp.NONE, null, null));
}
@Override
@@ -1488,6 +1488,7 @@ public abstract class Command implements CommonAttributes
private SimpleBitSet waitingOn;
private @Nullable SimpleBitSet appliedOrInvalidated;
private Timestamp executeAtLeast;
+ private boolean executeAtLeastUpdated;
public Update(WaitingOn waitingOn)
{
@@ -1579,7 +1580,8 @@ public abstract class Command implements CommonAttributes
public boolean hasChanges()
{
return !(waitingOn instanceof ImmutableBitSet)
- || (appliedOrInvalidated != null && !(appliedOrInvalidated instanceof ImmutableBitSet));
+ || (appliedOrInvalidated != null && !(appliedOrInvalidated instanceof ImmutableBitSet))
+ || executeAtLeastUpdated;
}
public TxnId txnId(int i)
@@ -1692,9 +1694,14 @@ public abstract class Command implements CommonAttributes
return waitingOn.get(idx + directRangeDeps.txnIdCount());
}
- public void updateExecuteAtLeast(Timestamp executeAtLeast)
+ public void updateExecuteAtLeast(TxnId txnId, Timestamp executeAtLeast)
{
- this.executeAtLeast = Timestamp.nonNullOrMax(executeAtLeast, this.executeAtLeast);
+ Invariants.checkState(executeAtLeast.compareTo(txnId) > 0);
+ if (this.executeAtLeast == null || this.executeAtLeast.compareTo(executeAtLeast) < 0)
+ {
+ this.executeAtLeast = executeAtLeast;
+ this.executeAtLeastUpdated = true;
+ }
}
boolean removeWaitingOnDirectRangeTxnId(int i)
diff --git a/accord-core/src/main/java/accord/local/CommandStore.java b/accord-core/src/main/java/accord/local/CommandStore.java
index 9a0efc42..e13a677c 100644
--- a/accord-core/src/main/java/accord/local/CommandStore.java
+++ b/accord-core/src/main/java/accord/local/CommandStore.java
@@ -80,27 +80,16 @@ public abstract class CommandStore implements AgentExecutor
{
final RangesForEpoch newRangesForEpoch;
final RedundantBefore addRedundantBefore;
- final Ranges addGlobalRanges;
- EpochUpdate(RangesForEpoch newRangesForEpoch, RedundantBefore addRedundantBefore, Ranges addGlobalRanges)
+ EpochUpdate(RangesForEpoch newRangesForEpoch, RedundantBefore addRedundantBefore)
{
this.newRangesForEpoch = newRangesForEpoch;
this.addRedundantBefore = addRedundantBefore;
- this.addGlobalRanges = addGlobalRanges;
}
}
public static class EpochUpdateHolder extends AtomicReference<EpochUpdate>
{
- // TODO (required, eventually): support removing ranges
- public void updateGlobal(Ranges addGlobalRanges)
- {
- EpochUpdate baseUpdate = new EpochUpdate(null, RedundantBefore.EMPTY, addGlobalRanges);
- EpochUpdate cur = get();
- if (cur == null || !compareAndSet(cur, new EpochUpdate(cur.newRangesForEpoch, cur.addRedundantBefore, cur.addGlobalRanges.with(addGlobalRanges))))
- set(baseUpdate);
- }
-
// TODO (desired): can better encapsulate by accepting only the newRangesForEpoch and deriving the add/remove ranges
public void add(long epoch, RangesForEpoch newRangesForEpoch, Ranges addRanges)
{
@@ -116,9 +105,9 @@ public abstract class CommandStore implements AgentExecutor
private void update(RangesForEpoch newRangesForEpoch, RedundantBefore addRedundantBefore)
{
- EpochUpdate baseUpdate = new EpochUpdate(newRangesForEpoch, addRedundantBefore, Ranges.EMPTY);
+ EpochUpdate baseUpdate = new EpochUpdate(newRangesForEpoch, addRedundantBefore);
EpochUpdate cur = get();
- if (cur == null || !compareAndSet(cur, new EpochUpdate(newRangesForEpoch, RedundantBefore.merge(cur.addRedundantBefore, addRedundantBefore), cur.addGlobalRanges)))
+ if (cur == null || !compareAndSet(cur, new EpochUpdate(newRangesForEpoch, RedundantBefore.merge(cur.addRedundantBefore, addRedundantBefore))))
set(baseUpdate);
}
}
@@ -145,7 +134,7 @@ public abstract class CommandStore implements AgentExecutor
protected final EpochUpdateHolder epochUpdateHolder;
// Used in markShardStale to make sure the staleness includes in progress bootstraps
- private transient NavigableMap<TxnId, Ranges> bootstrapBeganAt = ImmutableSortedMap.of(TxnId.NONE, Ranges.EMPTY); // additive (i.e. once inserted, rolled-over until invalidated, and the floor entry contains additions)
+ private transient NavigableMap<TxnId, Ranges> bootstrapBeganAt = emptyBootstrapBeganAt(); // additive (i.e. once inserted, rolled-over until invalidated, and the floor entry contains additions)
private RedundantBefore redundantBefore = RedundantBefore.EMPTY;
private MaxConflicts maxConflicts = MaxConflicts.EMPTY;
private int maxConflictsUpdates = 0;
@@ -168,7 +157,7 @@ public abstract class CommandStore implements AgentExecutor
* TODO (expected): merge with redundantBefore
* TODO (required): if we ever actually erase data on disk (after losing ownership), make sure to mark the range unsafe to read
*/
- private NavigableMap<Timestamp, Ranges> safeToRead = ImmutableSortedMap.of(Timestamp.NONE, Ranges.EMPTY);
+ private NavigableMap<Timestamp, Ranges> safeToRead = emptySafeToRead();
private final Set<Bootstrap> bootstraps = Collections.synchronizedSet(new DeterministicIdentitySet<>());
@Nullable private RejectBefore rejectBefore;
@@ -249,11 +238,22 @@ public abstract class CommandStore implements AgentExecutor
return rangesForEpoch;
}
- public void unsafeSetRangesForEpoch(RangesForEpoch newRangesForEpoch)
+ final void unsafeSetRangesForEpoch(RangesForEpoch newRangesForEpoch)
{
rangesForEpoch = nonNull(newRangesForEpoch);
}
+ protected final void unsafeClearRangesForEpoch()
+ {
+ rangesForEpoch = null;
+ }
+
+ protected void loadRangesForEpoch(RangesForEpoch newRangesForEpoch)
+ {
+ Invariants.checkState(this.rangesForEpoch == null);
+ unsafeSetRangesForEpoch(newRangesForEpoch);
+ }
+
public abstract boolean inStore();
public void maybeExecuteImmediately(Runnable task)
@@ -274,11 +274,23 @@ public abstract class CommandStore implements AgentExecutor
this.rejectBefore = newRejectBefore;
}
- protected void unsafeSetRedundantBefore(RedundantBefore newRedundantBefore)
+ final void unsafeSetRedundantBefore(RedundantBefore newRedundantBefore)
{
redundantBefore = newRedundantBefore;
}
+ protected void unsafeClearRedundantBefore()
+ {
+ unsafeSetRedundantBefore(null);
+ }
+
+ protected void loadRedundantBefore(RedundantBefore newRedundantBefore)
+ {
+ Invariants.checkState(redundantBefore == null || redundantBefore.equals(RedundantBefore.EMPTY));
+ Invariants.checkState(newRedundantBefore != null);
+ unsafeSetRedundantBefore(newRedundantBefore);
+ }
+
protected void unsafeUpsertRedundantBefore(RedundantBefore addRedundantBefore)
{
redundantBefore = RedundantBefore.merge(redundantBefore, addRedundantBefore);
@@ -287,16 +299,42 @@ public abstract class CommandStore implements AgentExecutor
/**
* This method may be invoked on a non-CommandStore thread
*/
- protected synchronized void unsafeSetSafeToRead(NavigableMap<Timestamp, Ranges> newSafeToRead)
+ final void unsafeSetSafeToRead(NavigableMap<Timestamp, Ranges> newSafeToRead)
{
this.safeToRead = newSafeToRead;
}
- protected void unsafeSetBootstrapBeganAt(NavigableMap<TxnId, Ranges> newBootstrapBeganAt)
+ protected final void unsafeClearSafeToRead()
+ {
+ unsafeSetSafeToRead(null);
+ }
+
+ protected void loadSafeToRead(NavigableMap<Timestamp, Ranges> newSafeToRead)
+ {
+ Invariants.checkState(safeToRead == null || safeToRead.equals(emptySafeToRead()));
+ Invariants.checkState(newSafeToRead != null);
+ unsafeSetSafeToRead(newSafeToRead);
+ updateMaxConflicts(newSafeToRead);
+ }
+
+ final void unsafeSetBootstrapBeganAt(NavigableMap<TxnId, Ranges> newBootstrapBeganAt)
{
this.bootstrapBeganAt = newBootstrapBeganAt;
}
+ protected final void unsafeClearBootstrapBeganAt()
+ {
+ unsafeSetBootstrapBeganAt(null);
+ }
+
+ protected synchronized void loadBootstrapBeganAt(NavigableMap<TxnId, Ranges> newBootstrapBeganAt)
+ {
+ Invariants.checkState(bootstrapBeganAt == null || bootstrapBeganAt.equals(emptyBootstrapBeganAt()));
+ Invariants.checkState(newBootstrapBeganAt != null);
+ unsafeSetBootstrapBeganAt(newBootstrapBeganAt);
+ updateMaxConflicts(newBootstrapBeganAt);
+ }
+
/**
* To be overridden by implementations, to ensure the new state is persisted.
*/
@@ -313,8 +351,34 @@ public abstract class CommandStore implements AgentExecutor
if (executeAt == null) return;
if (prev != null && prev.executeAt() != null && prev.executeAt().compareTo(executeAt) >= 0) return;
-
MaxConflicts updatedMaxConflicts = maxConflicts.update(updated.participants().hasTouched(), executeAt);
+ updateMaxConflicts(executeAt, updatedMaxConflicts);
+ }
+
+ protected void updateMaxConflicts(Ranges ranges, Timestamp executeAt)
+ {
+ updateMaxConflicts(executeAt, maxConflicts.update(ranges, executeAt));
+ }
+
+ protected void updateMaxConflicts(NavigableMap<? extends Timestamp, Ranges> map)
+ {
+ Timestamp max = Timestamp.NONE;
+ MaxConflicts updated = maxConflicts;
+ for (Map.Entry<? extends Timestamp, Ranges> e : map.entrySet())
+ {
+ Timestamp at = e.getKey();
+ if (at.compareTo(Timestamp.NONE) > 0)
+ {
+ updated = updated.update(e.getValue(), at);
+ max = Timestamp.max(max, at);
+ }
+ }
+ if (updated != maxConflicts)
+ updateMaxConflicts(max, updated);
+ }
+
+ protected void updateMaxConflicts(Timestamp executeAt, MaxConflicts updatedMaxConflicts)
+ {
if (++maxConflictsUpdates >= agent.maxConflictsPruneInterval())
{
int initialSize = updatedMaxConflicts.size();
@@ -542,6 +606,7 @@ public abstract class CommandStore implements AgentExecutor
final void markBootstrapping(SafeCommandStore safeStore, TxnId globalSyncId, Ranges ranges)
{
safeStore.setBootstrapBeganAt(bootstrap(globalSyncId, ranges, bootstrapBeganAt));
+ updateMaxConflicts(ranges, globalSyncId);
RedundantBefore addRedundantBefore = RedundantBefore.create(ranges, Long.MIN_VALUE, Long.MAX_VALUE, TxnId.NONE, TxnId.NONE, TxnId.NONE, TxnId.NONE, globalSyncId);
safeStore.upsertRedundantBefore(addRedundantBefore);
updatedRedundantBefore(safeStore, globalSyncId, ranges);
@@ -723,6 +788,7 @@ public abstract class CommandStore implements AgentExecutor
execute(empty(), safeStore -> {
Ranges validatedSafeToRead = redundantBefore.validateSafeToRead(forBootstrapAt, ranges);
safeStore.setSafeToRead(purgeAndInsert(safeToRead, at, validatedSafeToRead));
+ updateMaxConflicts(ranges, at);
}).beginAsResult();
}
@@ -779,4 +845,14 @@ public abstract class CommandStore implements AgentExecutor
{
return !bootstraps.isEmpty();
}
+
+ public static NavigableMap<TxnId, Ranges> emptyBootstrapBeganAt()
+ {
+ return ImmutableSortedMap.of(TxnId.NONE, Ranges.EMPTY);
+ }
+
+ public static NavigableMap<Timestamp, Ranges> emptySafeToRead()
+ {
+ return ImmutableSortedMap.of(Timestamp.NONE, Ranges.EMPTY);
+ }
}
diff --git a/accord-core/src/main/java/accord/local/CommandStores.java b/accord-core/src/main/java/accord/local/CommandStores.java
index 09d90163..7ed6bb1c 100644
--- a/accord-core/src/main/java/accord/local/CommandStores.java
+++ b/accord-core/src/main/java/accord/local/CommandStores.java
@@ -488,13 +488,6 @@ public abstract class CommandStores
Topology newLocalTopology = newTopology.forNode(supplier.time.id()).trim();
Ranges addedGlobal = newTopology.ranges().without(prev.global.ranges());
node.addNewRangesToDurableBefore(addedGlobal, epoch);
- if (!addedGlobal.isEmpty())
- {
- for (ShardHolder shard : prev.shards)
- {
- shard.store.epochUpdateHolder.updateGlobal(addedGlobal);
- }
- }
Ranges added = newLocalTopology.ranges().without(prev.local.ranges());
Ranges subtracted = prev.local.ranges().without(newLocalTopology.ranges());
@@ -539,7 +532,6 @@ public abstract class CommandStores
ShardHolder shard = new ShardHolder(supplier.create(nextId++, updateHolder));
shard.ranges = new RangesForEpoch(epoch, addRanges);
shard.store.epochUpdateHolder.add(epoch, shard.ranges, addRanges);
- shard.store.epochUpdateHolder.updateGlobal(newTopology.ranges());
Map<Boolean, Ranges> partitioned = addRanges.partitioningBy(range -> shouldBootstrap(node, prev.global, newLocalTopology, range));
if (partitioned.containsKey(false))
diff --git a/accord-core/src/main/java/accord/local/Commands.java b/accord-core/src/main/java/accord/local/Commands.java
index ca4f61d6..91276a30 100644
--- a/accord-core/src/main/java/accord/local/Commands.java
+++ b/accord-core/src/main/java/accord/local/Commands.java
@@ -659,7 +659,7 @@ public class Commands
Invariants.checkState(dependency.hasBeen(PreCommitted));
TxnId dependencyId = dependency.txnId();
if (waitingId.awaitsOnlyDeps() && dependency.known().executeAt == ExecuteAtKnown && dependency.executeAt().compareTo(waitingId) > 0)
- waitingOn.updateExecuteAtLeast(dependency.executeAt());
+ waitingOn.updateExecuteAtLeast(waitingId, dependency.executeAt());
if (dependency.hasBeen(Truncated))
{
@@ -937,8 +937,8 @@ public class Commands
public static boolean maybeCleanup(SafeCommandStore safeStore, SafeCommand safeCommand, Command command, @Nonnull StoreParticipants newParticipants)
{
- Cleanup cleanup = shouldCleanup(safeStore, command, newParticipants);
StoreParticipants cleanupParticipants = newParticipants.filter(LOAD, safeStore, command.txnId(), command.executeAtIfKnown());
+ Cleanup cleanup = shouldCleanup(safeStore, command, cleanupParticipants);
if (cleanup == NO)
{
if (cleanupParticipants == newParticipants)
diff --git a/accord-core/src/main/java/accord/local/SafeCommandStore.java b/accord-core/src/main/java/accord/local/SafeCommandStore.java
index 9170b51d..c661a1b0 100644
--- a/accord-core/src/main/java/accord/local/SafeCommandStore.java
+++ b/accord-core/src/main/java/accord/local/SafeCommandStore.java
@@ -332,7 +332,7 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
return;
// TODO (expected): we don't want to insert any dependencies for those we only touch; we just need to record them as decided/applied for execution
- PreLoadContext context = PreLoadContext.contextFor(update, INCR);
+ PreLoadContext context = PreLoadContext.contextFor(next.txnId(), update, INCR);
PreLoadContext execute = safeStore.canExecute(context);
if (execute != null)
{
@@ -341,12 +341,16 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
if (execute != context)
{
if (execute != null)
- context = PreLoadContext.contextFor(update.without(execute.keys()), INCR);
+ context = PreLoadContext.contextFor(next.txnId(), update.without(execute.keys()), INCR);
Invariants.checkState(!context.keys().isEmpty());
safeStore = safeStore; // prevent accidental usage inside lambda
- safeStore.commandStore().execute(context, safeStore0 -> updateManagedCommandsForKey(safeStore0, safeStore0.context().keys(), participants, next))
- .begin(safeStore.commandStore().agent);
+ safeStore.commandStore().execute(context, safeStore0 -> {
+ PreLoadContext ctx = safeStore0.context();
+ TxnId txnId = ctx.primaryTxnId();
+ Unseekables<?> keys = ctx.keys();
+ updateManagedCommandsForKey(safeStore0, keys, participants, safeStore0.get(txnId).current());
+ }).begin(safeStore.commandStore().agent);
}
}
@@ -354,7 +358,7 @@ public abstract class SafeCommandStore implements RangesForEpochSupplier, Redund
{
for (RoutingKey key : (AbstractUnseekableKeys)update)
{
- safeStore.get(key).update(safeStore, next, update != participants.stillTouches() && !participants.stillTouches(key));
+ safeStore.get(key).callback(safeStore, next);
}
}
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 6fff4697..f0500ae4 100644
--- a/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/CommandsForKey.java
@@ -64,7 +64,6 @@ import static accord.local.CommandSummaries.IsDep.NOT_ELIGIBLE;
import static accord.local.CommandSummaries.SummaryStatus.APPLIED;
import static accord.local.CommandSummaries.SummaryStatus.COMMITTED;
import static accord.local.CommandSummaries.SummaryStatus.NOT_ACCEPTED;
-import static accord.local.cfk.CommandsForKey.InternalStatus.ACCEPTED;
import static accord.local.cfk.CommandsForKey.InternalStatus.APPLIED_DURABLE;
import static accord.local.cfk.CommandsForKey.InternalStatus.APPLIED_NOT_DURABLE;
import static accord.local.cfk.CommandsForKey.InternalStatus.INVALIDATED;
@@ -73,8 +72,8 @@ import static accord.local.cfk.CommandsForKey.InternalStatus.STABLE;
import static accord.local.cfk.CommandsForKey.InternalStatus.TO_SUMMARY_STATUS;
import static accord.local.cfk.CommandsForKey.InternalStatus.TRANSITIVE;
import static accord.local.cfk.CommandsForKey.InternalStatus.PRUNED;
-import static accord.local.cfk.CommandsForKey.InternalStatus.TRANSITIVE_VISIBLE;
import static accord.local.cfk.CommandsForKey.InternalStatus.from;
+import static accord.local.cfk.CommandsForKey.InternalStatus.prunedFrom;
import static accord.local.cfk.PostProcess.notifyManagedPreBootstrap;
import static accord.local.cfk.Pruning.isAnyPredecessorWaitingOnPruned;
import static accord.local.cfk.Pruning.isWaitingOnPruned;
@@ -808,7 +807,8 @@ public class CommandsForKey extends CommandsForKeyUpdate
TRANSITIVE (SummaryStatus.NOT_DIRECTLY_WITNESSED, false, false, false, false),
TRANSITIVE_VISIBLE (SummaryStatus.NOT_DIRECTLY_WITNESSED, false, false, false, false),
PREACCEPTED_OR_ACCEPTED_INVALIDATE (NOT_ACCEPTED, false, false, true, false),
- ACCEPTED (SummaryStatus.ACCEPTED, false, true, true, false),
+ // even though we don't need the executeAt for deps calculation, we do need it for recovery to decide membership of the earlierWait collection
+ ACCEPTED (SummaryStatus.ACCEPTED, true, true, true, false),
COMMITTED (SummaryStatus.COMMITTED, true, true, true, true),
STABLE (SummaryStatus.STABLE, true, true, false, true),
// TODO (expected): do not encode missing collection for APPLIED transactions,
@@ -917,6 +917,23 @@ public class CommandsForKey extends CommandsForKeyUpdate
return FROM_SAVE_STATUS.get(status);
}
+ @VisibleForTesting
+ public static InternalStatus prunedFrom(SaveStatus saveStatus)
+ {
+ InternalStatus result = from(saveStatus);
+ if (result == null)
+ {
+ if (saveStatus.compareTo(SaveStatus.PreAccepted) < 0)
+ return TRANSITIVE_VISIBLE;
+ return PRUNED;
+ }
+
+ if (result.compareTo(APPLIED) == 0)
+ return PRUNED;
+
+ return result;
+ }
+
public static InternalStatus from(Command command)
{
InternalStatus status = from(command.saveStatus());
@@ -1307,6 +1324,7 @@ public class CommandsForKey extends CommandsForKeyUpdate
switch (txn.status())
{
+ case TRANSITIVE:
case INVALIDATED:
case PRUNED:
continue;
@@ -1354,7 +1372,8 @@ public class CommandsForKey extends CommandsForKeyUpdate
TxnInfo t = byId[j];
if (t.epoch() != epoch)
break;
- if (!t.isWrite() || t.executeAt != t)
+
+ if (!t.isWrite() || t.executeAt != t || !t.isCommittedToExecute())
continue;
if (maxCommittedWriteForEpoch == null || t.compareExecuteAt(maxCommittedWriteForEpoch) > 0)
@@ -1398,31 +1417,21 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
}
- // NOTE: prev MAY NOT be the version that last updated us due to various possible race conditions
- @VisibleForTesting
- public CommandsForKeyUpdate update(Command next, boolean isOutOfRange)
- {
- return update(next, isOutOfRange, false);
- }
-
- public CommandsForKeyUpdate update(Command next)
- {
- return update(next, !next.participants().touches(key));
- }
-
- public CommandsForKeyUpdate callback(Command next)
+ public CommandsForKeyUpdate callback(Command update)
{
- return update(next, !next.participants().touches(key), next.txnId().compareTo(prunedBefore()) < 0);
+ if (wasPruned(update))
+ return prunedCallback(update);
+ return update(update);
}
- private CommandsForKeyUpdate update(Command next, boolean isOutOfRange, boolean wasPruned)
+ public CommandsForKeyUpdate update(Command update)
{
- Invariants.checkState(manages(next.txnId()));
- InternalStatus newStatus = from(next);
+ Invariants.checkState(manages(update.txnId()));
+ InternalStatus newStatus = from(update);
if (newStatus == null)
return this;
- return update(newStatus, next, isOutOfRange, wasPruned);
+ return update(newStatus, update);
}
public CommandsForKey setDurable(TxnId txnId)
@@ -1436,56 +1445,49 @@ public class CommandsForKey extends CommandsForKeyUpdate
return new CommandsForKey(key, boundsInfo, byId, committedByExecuteAt, minUndecidedById, maxAppliedWriteByExecuteAt, maxHlc, loadingPruned, prunedBeforeById, unmanageds);
}
- CommandsForKeyUpdate updatePruned(Command next)
+ CommandsForKeyUpdate prunedCallback(Command update)
{
- boolean wasPruned;
- InternalStatus newStatus = from(next.saveStatus());
- // cannot use original status unless we also populate deps (which we don't for pruned items)
- if (newStatus == null)
- newStatus = TRANSITIVE_VISIBLE;
- switch (newStatus)
- {
- default: throw new AssertionError("Unhandled InternalStatus: " + newStatus);
- case PRUNED: throw illegalState("Invalid InternalStatus: " + newStatus);
- case APPLIED_NOT_DURABLE:
- case APPLIED_DURABLE:
- case APPLIED_NOT_EXECUTED:
- case INVALIDATED:
+ TxnId txnId = update.txnId();
+ InternalStatus newStatus = prunedFrom(update.saveStatus());
+ boolean isLoadingPruned = loadingPrunedFor(loadingPruned, txnId, null) != null;
+ if (!isLoadingPruned)
+ {
+ if (!manages(txnId))
newStatus = PRUNED;
- case TRANSITIVE:
- case TRANSITIVE_VISIBLE:
- wasPruned = true;
- break;
- case ACCEPTED:
- case STABLE:
- case COMMITTED:
- case PREACCEPTED_OR_ACCEPTED_INVALIDATE:
- // either we're loading a command we wouldn't have visited directly, or we've raced with the update on arrival
- // TODO (expected): tighten semantics here, we shouldn't permit any race condition (and indeed already may not)
- wasPruned = !manages(next.txnId());
- if (wasPruned) newStatus = TRANSITIVE_VISIBLE;
+
+ TxnInfo cur = get(txnId);
+ if (newStatus == PRUNED && (cur == null || cur.is(PRUNED)))
+ return this;
}
- return update(newStatus, next, false, wasPruned);
+
+ return update(newStatus, update);
}
- private CommandsForKeyUpdate update(InternalStatus newStatus, Command next, boolean isOutOfRange, boolean wasPruned)
+ private boolean wasPruned(Command command)
{
- TxnId txnId = next.txnId();
- Invariants.checkArgument(wasPruned || manages(txnId));
+ TxnId txnId = command.txnId();
+ TxnInfo prunedBefore = prunedBefore();
+ if (prunedBefore.compareTo(txnId) < 0)
+ return false;
+ if (!manages(txnId))
+ return true;
+ return command.hasBeen(Status.Truncated) || (command.hasBeen(Status.Committed) && prunedBefore.compareTo(command.executeAt()) > 0);
+ }
+
+ private CommandsForKeyUpdate update(InternalStatus newStatus, Command updated)
+ {
+ TxnId txnId = updated.txnId();
+ Invariants.checkArgument(updated.participants().hasTouched(key) || !manages(txnId));
if (txnId.compareTo(redundantBefore()) < 0)
return this;
- boolean mayExecute = mayExecute(txnId, newStatus, next);
- if (isOutOfRange && newStatus.compareTo(INVALIDATED) >= 0) isOutOfRange = false; // invalidated is safe to use anywhere, and erases deps
+ boolean mayExecute = mayExecute(txnId, newStatus, updated);
+ boolean isOutOfRange = !mayExecute && newStatus.compareTo(COMMITTED) >= 0 && newStatus.compareTo(APPLIED) <= 0
+ && manages(txnId) && !updated.participants().stillTouches(key);
TxnId[] loadingAsPrunedFor = loadingPrunedFor(loadingPruned, txnId, null); // we default to null to distinguish between no match, and a match with NO_TXNIDS
- if (wasPruned && loadingAsPrunedFor == null)
- {
- //we may have received the command since we started loading pruned, in which case the pruned status will be faulty
- return this;
- }
- wasPruned |= loadingAsPrunedFor != null;
+ boolean wasPruned = loadingAsPrunedFor != null;
int pos = Arrays.binarySearch(byId, txnId);
CommandsForKeyUpdate result;
@@ -1495,9 +1497,9 @@ public class CommandsForKey extends CommandsForKeyUpdate
return this; // if outOfRange we only need to maintain any existing records; if none, don't update
pos = -1 - pos;
- if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, null, newStatus, mayExecute, wasPruned, loadingAsPrunedFor);
- else if (newStatus.hasDeps() && !wasPruned) result = insert(pos, txnId, newStatus, mayExecute, next);
- else result = insert(pos, txnId, TxnInfo.create(txnId, newStatus, mayExecute, next), wasPruned, loadingAsPrunedFor);
+ if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, null, newStatus, mayExecute, updated, wasPruned, loadingAsPrunedFor);
+ else if (newStatus.hasDeps() && !wasPruned) result = insert(pos, txnId, newStatus, mayExecute, updated);
+ else result = insert(pos, txnId, TxnInfo.create(txnId, newStatus, mayExecute, updated), wasPruned, loadingAsPrunedFor);
}
else
{
@@ -1513,27 +1515,27 @@ public class CommandsForKey extends CommandsForKeyUpdate
return this;
// and only when the new ballot is strictly greater
- if (next.acceptedOrCommitted().compareTo(cur.ballot()) <= 0)
+ if (updated.acceptedOrCommitted().compareTo(cur.ballot()) <= 0)
return this;
}
else if (c == 0)
{
// we're updating to the same state; we only do this with a strictly greater ballot;
// even so, if we have no executeAt or deps there's nothing to record
- if (next.acceptedOrCommitted().compareTo(cur.ballot()) <= 0 && !newStatus.hasExecuteAtOrDeps())
+ if (updated.acceptedOrCommitted().compareTo(cur.ballot()) <= 0 || !newStatus.hasExecuteAtOrDeps())
return this;
}
else
{
// we're advancing to a higher status, but this is only permitted either if the new state is stable or the ballot is higher
- if (cur.compareTo(STABLE) < 0 && next.acceptedOrCommitted().compareTo(cur.ballot()) < 0)
+ if (cur.compareTo(STABLE) < 0 && updated.acceptedOrCommitted().compareTo(cur.ballot()) < 0)
return this;
}
}
- if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, cur, newStatus, mayExecute, wasPruned, loadingAsPrunedFor);
- else if (newStatus.hasDeps() && !wasPruned) result = update(pos, txnId, cur, newStatus, mayExecute, next);
- else result = update(pos, txnId, cur, TxnInfo.create(txnId, newStatus, mayExecute, next), wasPruned, loadingAsPrunedFor);
+ if (isOutOfRange) result = insertOrUpdateOutOfRange(pos, txnId, cur, newStatus, mayExecute, updated, wasPruned, loadingAsPrunedFor);
+ else if (newStatus.hasDeps() && !wasPruned) result = update(pos, txnId, cur, newStatus, mayExecute, updated);
+ else result = update(pos, txnId, cur, TxnInfo.create(txnId, newStatus, mayExecute, updated), wasPruned, loadingAsPrunedFor);
}
return result;
@@ -1562,13 +1564,14 @@ public class CommandsForKey extends CommandsForKeyUpdate
return insertOrUpdate(this, pos, plainTxnId, null, newInfo, wasPruned, loadingAsPrunedFor);
}
- private CommandsForKeyUpdate insertOrUpdateOutOfRange(int updatePos, TxnId plainTxnId, @Nullable TxnInfo curInfo, InternalStatus newStatus, boolean mayExecute, boolean wasPruned, TxnId[] loadingAsPrunedFor)
+ private CommandsForKeyUpdate insertOrUpdateOutOfRange(int updatePos, TxnId plainTxnId, @Nullable TxnInfo curInfo, InternalStatus newStatus, boolean mayExecute, Command update, boolean wasPruned, TxnId[] loadingAsPrunedFor)
{
Invariants.checkArgument(!mayExecute);
- TxnInfo baseInfo = curInfo == null ? NO_INFO : curInfo;
+ int statusOverridesXor = newStatus.flags & 1;
+ TxnInfo newInfo;
+ if (curInfo == null) newInfo = TxnInfo.create(plainTxnId, newStatus, false, statusOverridesXor, plainTxnId, update.acceptedOrCommitted());
+ else newInfo = curInfo.withEncodedStatus(TxnInfo.encode(plainTxnId, newStatus, false, statusOverridesXor));
// out of range means we have no deps, we're just marking committed, so we set HAS_DEPS to 0
- int statusOverridesXor = curInfo == null ? 0 : newStatus.flags & 1;
- TxnInfo newInfo = baseInfo.withEncodedStatus(TxnInfo.encode(plainTxnId, newStatus, false, statusOverridesXor));
return insertOrUpdate(this, updatePos, plainTxnId, curInfo, newInfo, wasPruned, loadingAsPrunedFor);
}
@@ -1880,26 +1883,28 @@ public class CommandsForKey extends CommandsForKeyUpdate
}
}
- public CommandsForKeyUpdate withRedundantBeforeAtLeast(RedundantBefore.Entry newRedundantBeforeEntry)
+ public CommandsForKeyUpdate withRedundantBeforeAtLeast(RedundantBefore.Entry newBoundsInfo)
{
- return withRedundantBeforeAtLeast(newRedundantBeforeEntry, false);
- }
-
- /**
- * Use force=true on load from disk to ensure any notifications that may be needed after an out-of-band truncation are run.
- */
- public CommandsForKeyUpdate withRedundantBeforeAtLeast(RedundantBefore.Entry newBoundsInfo, boolean force)
- {
- // TODO (required): handle receiving an entry from the past, e.g. on reload (OR expunge all CFK on restart)
- if (!force && newBoundsInfo.gcBefore.equals(boundsInfo.gcBefore)
- && newBoundsInfo.bootstrappedAt.equals(boundsInfo.bootstrappedAt)
- && newBoundsInfo.locallyDecidedAndAppliedOrInvalidatedBefore.equals(boundsInfo.locallyDecidedAndAppliedOrInvalidatedBefore)
- && newBoundsInfo.endOwnershipEpoch == boundsInfo.endOwnershipEpoch)
- return this;
-
- // we can't let HLC go backwards as this breaks assumptions around maxHlc tracking
+ // we can't let HLC epoch go backwards as this breaks assumptions around maxHlc tracking
if (newBoundsInfo.gcBefore.hlc() < boundsInfo.gcBefore.hlc())
+ {
+ if (newBoundsInfo.endOwnershipEpoch != boundsInfo.endOwnershipEpoch || !newBoundsInfo.bootstrappedAt.equals(boundsInfo.bootstrappedAt))
+ {
+ newBoundsInfo = boundsInfo.withEpochs(boundsInfo.startOwnershipEpoch, newBoundsInfo.endOwnershipEpoch)
+ .withBootstrappedAtLeast(newBoundsInfo.bootstrappedAt);
+ }
+ else
+ {
+ return this;
+ }
+ }
+ else if (newBoundsInfo.gcBefore.equals(boundsInfo.gcBefore)
+ && newBoundsInfo.bootstrappedAt.equals(boundsInfo.bootstrappedAt)
+ && newBoundsInfo.locallyDecidedAndAppliedOrInvalidatedBefore.equals(boundsInfo.locallyDecidedAndAppliedOrInvalidatedBefore)
+ && newBoundsInfo.endOwnershipEpoch == boundsInfo.endOwnershipEpoch)
+ {
return this;
+ }
long maxHlc = Math.max(this.maxHlc, newBoundsInfo.gcBefore.hlc());
if (newBoundsInfo.gcBefore.epoch() >= newBoundsInfo.endOwnershipEpoch)
diff --git a/accord-core/src/main/java/accord/local/cfk/NotifySink.java b/accord-core/src/main/java/accord/local/cfk/NotifySink.java
index 0e9b5de1..8dfa1e39 100644
--- a/accord-core/src/main/java/accord/local/cfk/NotifySink.java
+++ b/accord-core/src/main/java/accord/local/cfk/NotifySink.java
@@ -126,6 +126,5 @@ interface NotifySink
}).begin(safeStore.agent());
}
}
-
}
}
diff --git a/accord-core/src/main/java/accord/local/cfk/PostProcess.java b/accord-core/src/main/java/accord/local/cfk/PostProcess.java
index 2f4fcc8d..a67b6a1f 100644
--- a/accord-core/src/main/java/accord/local/cfk/PostProcess.java
+++ b/accord-core/src/main/java/accord/local/cfk/PostProcess.java
@@ -26,13 +26,16 @@ import java.util.function.Predicate;
import javax.annotation.Nullable;
import accord.api.RoutingKey;
+import accord.local.Command;
import accord.local.PreLoadContext;
import accord.local.RedundantBefore;
import accord.local.SafeCommand;
import accord.local.SafeCommandStore;
+import accord.local.StoreParticipants;
import accord.local.cfk.CommandsForKey.TxnInfo;
import accord.local.cfk.CommandsForKey.Unmanaged;
import accord.local.cfk.CommandsForKeyUpdate.CommandsForKeyUpdateWithPostProcess;
+import accord.primitives.Routable;
import accord.primitives.RoutingKeys;
import accord.primitives.Timestamp;
import accord.primitives.TxnId;
@@ -104,7 +107,11 @@ abstract class PostProcess
static void load(SafeCommandStore safeStore, SafeCommand safeCommand, SafeCommandsForKey safeCfk, NotifySink notifySink)
{
- safeCfk.updatePruned(safeStore, safeCommand.current(), notifySink);
+ Command command = safeCommand.current();
+ StoreParticipants participants = command.participants();
+ if (participants.owns().domain() == Routable.Domain.Key && !participants.hasTouched(safeCfk.key()))
+ command = safeCommand.updateParticipants(safeStore, participants.supplementHasTouched(RoutingKeys.of(safeCfk.key())));
+ safeCfk.updatePruned(safeStore, command, notifySink);
}
static CommandsForKeyUpdate load(TxnId[] txnIds, CommandsForKeyUpdate result)
diff --git a/accord-core/src/main/java/accord/local/cfk/Pruning.java b/accord-core/src/main/java/accord/local/cfk/Pruning.java
index 527ebf1e..af9cfffe 100644
--- a/accord-core/src/main/java/accord/local/cfk/Pruning.java
+++ b/accord-core/src/main/java/accord/local/cfk/Pruning.java
@@ -272,6 +272,8 @@ public class Pruning
* TODO (desired): we could limit this restriction to epochs where ownership changes; introduce some global summary info to facilitate this
* TODO (desired): we may be able prune more transactions that cross epochs if we have a prune point in both epochs,
* where the execution epoch prune point as ahead of the executeAt, and the coordination epoch prune point is ahead of the TxnId
+ * TODO (expected): remove any unmanaged transactions that precede the prune point
+ * this requires updating txn.missing collections, so might be preferable as a separate pass
*/
static CommandsForKey pruneBefore(CommandsForKey cfk, TxnInfo newPrunedBefore, int pos)
{
diff --git a/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java b/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
index f2f0f96d..7839f3ec 100644
--- a/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
+++ b/accord-core/src/main/java/accord/local/cfk/SafeCommandsForKey.java
@@ -49,16 +49,17 @@ public abstract class SafeCommandsForKey implements SafeState<CommandsForKey>
void updatePruned(SafeCommandStore safeStore, Command nextCommand, NotifySink notifySink)
{
CommandsForKey prevCfk = current();
- update(safeStore, nextCommand, prevCfk, prevCfk.updatePruned(nextCommand), notifySink);
+ update(safeStore, nextCommand, prevCfk, prevCfk.prunedCallback(nextCommand), notifySink);
}
- public void update(SafeCommandStore safeStore, Command nextCommand, boolean isOutOfRange)
+ public void update(SafeCommandStore safeStore, Command nextCommand)
{
CommandsForKey prevCfk = current();
- update(safeStore, nextCommand, prevCfk, prevCfk.update(nextCommand, isOutOfRange));
+ update(safeStore, nextCommand, prevCfk, prevCfk.update(nextCommand));
}
- void callback(SafeCommandStore safeStore, Command nextCommand)
+ // equivalent to update, but for async callbacks with additional validation around pruning
+ public void callback(SafeCommandStore safeStore, Command nextCommand)
{
CommandsForKey prevCfk = current();
update(safeStore, nextCommand, prevCfk, prevCfk.callback(nextCommand));
diff --git a/accord-core/src/main/java/accord/local/cfk/Updating.java b/accord-core/src/main/java/accord/local/cfk/Updating.java
index c27a8f30..a1438603 100644
--- a/accord-core/src/main/java/accord/local/cfk/Updating.java
+++ b/accord-core/src/main/java/accord/local/cfk/Updating.java
@@ -21,6 +21,7 @@ package accord.local.cfk;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -66,6 +67,7 @@ import static accord.local.cfk.Utils.mergeAndFilterMissing;
import static accord.local.cfk.Utils.missingTo;
import static accord.local.cfk.Utils.removeOneMissing;
import static accord.local.cfk.Utils.removePrunedAdditions;
+import static accord.local.cfk.Utils.removeUnmanaged;
import static accord.local.cfk.Utils.validateMissing;
import static accord.primitives.Routable.Domain.Range;
import static accord.primitives.Txn.Kind.EphemeralRead;
@@ -73,6 +75,8 @@ import static accord.primitives.Txn.Kind.ExclusiveSyncPoint;
import static accord.primitives.Txn.Kind.Write;
import static accord.primitives.TxnId.NO_TXNIDS;
import static accord.utils.ArrayBuffers.cachedTxnIds;
+import static accord.utils.Invariants.Paranoia.CONSTANT;
+import static accord.utils.Invariants.Paranoia.LINEAR;
import static accord.utils.Invariants.Paranoia.NONE;
import static accord.utils.Invariants.Paranoia.SUPERLINEAR;
import static accord.utils.Invariants.ParanoiaCostFactor.LOW;
@@ -121,9 +125,13 @@ class Updating
if (prunedIds != NO_TXNIDS)
{
additionCount -= prunedIds.length;
- List<TxnId> insertLoadPruned = new ArrayList<>();
- newLoadingPruned = Pruning.loadPruned(cfk.loadingPruned, prunedIds, plainTxnId, insertLoadPruned);
- prunedIds = insertLoadPruned.isEmpty() ? NO_TXNIDS : insertLoadPruned.toArray(TxnId[]::new);
+ prunedIds = removeUnmanaged(prunedIds);
+ if (prunedIds != NO_TXNIDS)
+ {
+ List<TxnId> insertLoadPruned = new ArrayList<>();
+ newLoadingPruned = Pruning.loadPruned(cfk.loadingPruned, prunedIds, plainTxnId, insertLoadPruned);
+ prunedIds = insertLoadPruned.isEmpty() ? NO_TXNIDS : insertLoadPruned.toArray(TxnId[]::new);
+ }
}
int committedByExecuteAtUpdatePos = committedByExecuteAtUpdatePos(cfk.committedByExecuteAt, curInfo, newInfo);
@@ -924,6 +932,7 @@ class Updating
}
}
+ waitingToExecuteAt = updateExecuteAtLeast(waitingToExecuteAt, effectiveExecutesAt, safeCommand);
if (!readyToApply || missingCount > 0)
{
TxnInfo[] newById = byId, newCommittedByExecuteAt = cfk.committedByExecuteAt;
@@ -965,24 +974,7 @@ class Updating
if (!readyToApply && mode != REGISTER_DEPS_ONLY)
{
CommandsForKey.Unmanaged newPendingRecord;
- if (waitingToApply)
- {
- if (waitingToExecuteAt instanceof TxnInfo)
- waitingToExecuteAt = ((TxnInfo) waitingToExecuteAt).plainExecuteAt();
-
- if (waitingTxnId.awaitsOnlyDeps())
- {
- effectiveExecutesAt = Timestamp.nonNullOrMax(effectiveExecutesAt, waitingToExecuteAt);
- if (effectiveExecutesAt != null && effectiveExecutesAt.compareTo(command.waitingOn.executeAtLeast(Timestamp.NONE)) > 0)
- {
- Command.WaitingOn.Update waitingOn = new Command.WaitingOn.Update(command.waitingOn);
- waitingOn.updateExecuteAtLeast(effectiveExecutesAt);
- safeCommand.updateWaitingOn(waitingOn);
- }
- }
-
- newPendingRecord = new CommandsForKey.Unmanaged(APPLY, command.txnId(), waitingToExecuteAt);
- }
+ if (waitingToApply) newPendingRecord = new CommandsForKey.Unmanaged(APPLY, command.txnId(), waitingToExecuteAt);
else newPendingRecord = new CommandsForKey.Unmanaged(COMMIT, command.txnId(), txnIds.get(toIndex - 1));
if (update != null)
@@ -1008,7 +1000,10 @@ class Updating
result = new CommandsForKeyUpdate.CommandsForKeyUpdateWithPostProcess(newCfk, new LoadPruned(result.postProcess(), prunedIds));
if (readyToApply)
+ {
+ paranoidCheckExecutesAtLeast(newCfk, waitingTxnId, effectiveExecutesAt, waitingToExecuteAt);
result = new CommandsForKeyUpdate.CommandsForKeyUpdateWithPostProcess(newCfk, new PostProcess.NotifyNotWaiting(result.postProcess(), new TxnId[] { safeCommand.txnId() }));
+ }
return result;
}
@@ -1016,4 +1011,42 @@ class Updating
return new CommandsForKeyUpdate.CommandsForKeyUpdateWithPostProcess(cfk, new PostProcess.NotifyNotWaiting(null, new TxnId[] { safeCommand.txnId() }));
}
+
+ private static Timestamp updateExecuteAtLeast(Timestamp waitingToExecuteAt, Timestamp effectiveExecutesAt, SafeCommand safeCommand)
+ {
+ if (waitingToExecuteAt instanceof TxnInfo)
+ waitingToExecuteAt = ((TxnInfo) waitingToExecuteAt).plainExecuteAt();
+
+ TxnId txnId = safeCommand.txnId();
+ if (txnId.awaitsOnlyDeps())
+ {
+ Command.Committed command = safeCommand.current().asCommitted();
+ if (effectiveExecutesAt != null && effectiveExecutesAt.compareTo(command.waitingOn.executeAtLeast(txnId)) > 0)
+ {
+ Command.WaitingOn.Update waitingOn = new Command.WaitingOn.Update(command.waitingOn);
+ waitingOn.updateExecuteAtLeast(txnId, effectiveExecutesAt);
+ safeCommand.updateWaitingOn(waitingOn);
+ }
+ }
+
+ return waitingToExecuteAt;
+ }
+
+ private static void paranoidCheckExecutesAtLeast(CommandsForKey cfk, TxnId waitingId, Timestamp effectiveExecutesAt, Timestamp waitingToExecuteAt)
+ {
+ if (!Invariants.isParanoid() || !Invariants.testParanoia(LINEAR, CONSTANT, LOW))
+ return;
+
+ Timestamp maxExecutesAt = null;
+ int maxi = cfk.indexOf(waitingId);
+ if (maxi < 0) maxi = -1 - maxi;
+ for (int i = 0 ; i < maxi ; ++i)
+ maxExecutesAt = Timestamp.nonNullOrMax(maxExecutesAt, cfk.byId[i].executeAt);
+
+ if (maxExecutesAt == null || maxExecutesAt.compareTo(waitingId) < 0)
+ return;
+
+ effectiveExecutesAt = Timestamp.nonNullOrMax(effectiveExecutesAt, waitingToExecuteAt);
+ Invariants.checkState(Objects.equals(effectiveExecutesAt, maxExecutesAt));
+ }
}
diff --git a/accord-core/src/main/java/accord/local/cfk/Utils.java b/accord-core/src/main/java/accord/local/cfk/Utils.java
index 1406ae79..ce72aff5 100644
--- a/accord-core/src/main/java/accord/local/cfk/Utils.java
+++ b/accord-core/src/main/java/accord/local/cfk/Utils.java
@@ -33,6 +33,7 @@ import net.nicoulaj.compilecommand.annotations.Inline;
import static accord.local.cfk.CommandsForKey.InternalStatus.ACCEPTED;
import static accord.local.cfk.CommandsForKey.InternalStatus.COMMITTED;
import static accord.local.cfk.CommandsForKey.Unmanaged.Pending.COMMIT;
+import static accord.local.cfk.CommandsForKey.manages;
import static accord.primitives.TxnId.NO_TXNIDS;
import static accord.utils.ArrayBuffers.cachedTxnIds;
import static accord.utils.SortedArrays.Search.FAST;
@@ -261,6 +262,30 @@ class Utils
return prunedIds;
}
+ static TxnId[] removeUnmanaged(TxnId[] ids)
+ {
+ // TODO (desired): consider; we perhaps expect manages(id) to normally be true,
+ // so we could optimistically assume we will keep all ids at the cost of some wasted allocations
+ int count = 0;
+ for (TxnId id : ids)
+ count += manages(id) ? 1 : 0;
+
+ if (count == ids.length)
+ return ids;
+
+ if (count == 0)
+ return NO_TXNIDS;
+
+ TxnId[] result = new TxnId[count];
+ count = 0;
+ for (TxnId id : ids)
+ {
+ if (manages(id))
+ result[count++] = id;
+ }
+ return result;
+ }
+
/**
* If a {@code missing} contains {@code removeTxnId}, return a new array without it (or NO_TXNIDS if the only entry)
*/
diff --git a/accord-core/src/main/java/accord/messages/Accept.java b/accord-core/src/main/java/accord/messages/Accept.java
index e4b980dd..14ddbed9 100644
--- a/accord-core/src/main/java/accord/messages/Accept.java
+++ b/accord-core/src/main/java/accord/messages/Accept.java
@@ -104,7 +104,7 @@ public class Accept extends TxnRequest.WithUnsynced<Accept.AcceptReply>
return AcceptReply.redundant(ballot, participants, safeCommand.current());
Invariants.checkState(deps.maxTxnId(txnId).epoch() <= executeAt.epoch());
- return new AcceptReply(calculateDeps(safeStore, participants));
+ return new AcceptReply(deps);
}
}
diff --git a/accord-core/src/main/java/accord/messages/BeginRecovery.java b/accord-core/src/main/java/accord/messages/BeginRecovery.java
index 9cadc725..a258e112 100644
--- a/accord-core/src/main/java/accord/messages/BeginRecovery.java
+++ b/accord-core/src/main/java/accord/messages/BeginRecovery.java
@@ -46,9 +46,8 @@ import accord.utils.Invariants;
import accord.utils.async.Cancellable;
import static accord.local.CommandSummaries.IsDep.IS_NOT_DEP;
-import static accord.local.CommandSummaries.SummaryStatus.ACCEPTED;
-import static accord.local.CommandSummaries.SummaryStatus.INVALIDATED;
import static accord.local.CommandSummaries.ComputeIsDep.EITHER;
+import static accord.local.CommandSummaries.SummaryStatus.NOT_DIRECTLY_WITNESSED;
import static accord.local.CommandSummaries.TestStartedAt.ANY;
import static accord.messages.BeginRecovery.RecoverReply.Kind.Ok;
import static accord.messages.BeginRecovery.RecoverReply.Kind.Reject;
@@ -148,108 +147,113 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
}
boolean supersedingRejects;
- Deps earlierCommittedWitness, earlierAcceptedNoWitness;
+ Deps earlierNoWait, earlierWait;
if (command.hasBeen(Accepted))
{
supersedingRejects = false;
- earlierCommittedWitness = earlierAcceptedNoWitness = Deps.NONE;
+ earlierNoWait = earlierWait = Deps.NONE;
}
else
{
// TODO (expected): modify the mapReduce API to perform this check in a single pass
class Visitor implements CommandSummaries.AllCommandVisitor, AutoCloseable
{
- Deps.Builder nowait;
- Deps.Builder wait;
+ Deps.Builder earlierNoWait, earlierWait;
boolean supersedingRejects;
@Override
- public boolean visit(Unseekable keyOrRange, TxnId testTxnId, Timestamp testExecuteAt, SummaryStatus status, @Nullable IsDep dep)
+ public boolean visit(Unseekable keyOrRange, TxnId testTxnId, Timestamp testExecuteAt, SummaryStatus status, IsDep dep)
{
- if (testTxnId.compareTo(txnId) < 0)
+ if (status == NOT_DIRECTLY_WITNESSED || !txnId.is(testTxnId.witnesses()))
+ return true;
+
+ int c = testTxnId.compareTo(txnId);
+ if (c == 0)
+ return true;
+
+ if (c < 0)
{
- if (status == INVALIDATED)
- {
- ensureNoWait().add(keyOrRange, testTxnId);
- }
- else if (testExecuteAt.compareTo(txnId) > 0)
+ switch (dep)
{
- switch (dep)
- {
- default: throw new AssertionError("Unhandled SummaryDep: " + dep);
- case IS_DEP:
- ensureNoWait().add(keyOrRange, testTxnId);
- break;
-
- case IS_NOT_DEP:
- /*
- * The idea here is to discover those transactions that have been decided to execute after us
- * and did not witness us as part of their pre-accept or accept round, as this means that we CANNOT have
- * 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 it.
- */
- supersedingRejects = true;
- break;
-
- case NOT_ELIGIBLE:
- Invariants.checkState(status.compareTo(ACCEPTED) <= 0);
- if (status == ACCEPTED)
- ensureWait().add(keyOrRange, testTxnId);
- }
+ default: throw new AssertionError("Unhandled IsDep: " + dep);
+ case IS_DEP:
+ ensureEarlierNoWait().add(keyOrRange, testTxnId);
+ break;
+
+ case IS_NOT_DEP:
+ /*
+ * The idea here is to discover those transactions that have been decided to execute after us
+ * and did not witness us as part of their pre-accept or accept round, as this means that we CANNOT have
+ * 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.
+ */
+ supersedingRejects = true;
+ return false;
+
+ case NOT_ELIGIBLE:
+ switch (status)
+ {
+ case INVALIDATED:
+ ensureEarlierNoWait().add(keyOrRange, testTxnId);
+ break;
+
+ case ACCEPTED:
+ if (testExecuteAt.compareTo(txnId) > 0)
+ ensureEarlierWait().add(keyOrRange, testTxnId);
+ break;
+ }
}
}
- else if (dep == IS_NOT_DEP)
+ else
{
- /*
- * The idea here is to discover those transactions that were started after us and have been Accepted
- * and did not witness us as part of their pre-accept round, as this means that we CANNOT have taken
- * 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).
- */
- supersedingRejects = true;
+ if (dep == IS_NOT_DEP)
+ {
+ supersedingRejects = true;
+ return false;
+ }
}
- return !supersedingRejects;
+ return true;
}
- private Deps.Builder ensureNoWait()
+ private Deps.Builder ensureEarlierNoWait()
{
- if (nowait == null)
- nowait = new Deps.Builder(true);
- return nowait;
+ if (earlierNoWait == null)
+ earlierNoWait = new Deps.Builder(true);
+ return earlierNoWait;
}
- private Deps.Builder ensureWait()
+ private Deps.Builder ensureEarlierWait()
{
- if (wait == null)
- wait = new Deps.Builder(true);
- return wait;
+ if (earlierWait == null)
+ earlierWait = new Deps.Builder(true);
+ return earlierWait;
}
@Override
public void close()
{
- if (nowait != null)
+ if (earlierNoWait != null)
{
- nowait.close();
- nowait = null;
+ earlierNoWait.close();
+ earlierNoWait = null;
}
- if (wait != null)
+ if (earlierWait != null)
{
- wait.close();
- wait = null;
+ earlierWait.close();
+ earlierWait = null;
}
}
}
+
try (Visitor visitor = new Visitor())
{
safeStore.visit(participants.owns(), txnId, txnId.witnessedBy(), ANY, txnId, EITHER, visitor);
supersedingRejects = visitor.supersedingRejects;
- earlierCommittedWitness = visitor.nowait == null ? Deps.NONE : visitor.nowait.build();
- earlierAcceptedNoWitness = visitor.wait == null ? Deps.NONE : visitor.wait.build();
+ earlierNoWait = visitor.earlierNoWait == null ? Deps.NONE : visitor.earlierNoWait.build();
+ earlierWait = visitor.earlierWait == null ? Deps.NONE : visitor.earlierWait.build();
}
}
@@ -259,7 +263,7 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
Writes writes = command.writes();
Result result = command.result();
boolean acceptsFastPath = executeAt.equals(txnId) || participants.owns().isEmpty();
- return new RecoverOk(txnId, status, accepted, executeAt, deps, earlierCommittedWitness, earlierAcceptedNoWitness, acceptsFastPath, supersedingRejects, writes, result);
+ return new RecoverOk(txnId, status, accepted, executeAt, deps, earlierWait, earlierNoWait, acceptsFastPath, supersedingRejects, writes, result);
}
@Override
@@ -288,14 +292,14 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
if (!ok1.status.hasBeen(PreAccepted)) throw new IllegalStateException();
LatestDeps deps = LatestDeps.merge(ok1.deps, ok2.deps);
- Deps earlierCommittedWitness = ok1.earlierCommittedWitness.with(ok2.earlierCommittedWitness);
- Deps earlierAcceptedNoWitness = ok1.earlierAcceptedNoWitness.with(ok2.earlierAcceptedNoWitness)
- .without(earlierCommittedWitness::contains);
+ Deps earlierNoWait = ok1.earlierNoWait.with(ok2.earlierNoWait);
+ Deps earlierWait = ok1.earlierWait.with(ok2.earlierWait)
+ .without(earlierNoWait);
Timestamp timestamp = ok1.status == PreAccepted ? Timestamp.max(ok1.executeAt, ok2.executeAt) : ok1.executeAt;
return new RecoverOk(
txnId, ok1.status, ok1.accepted, timestamp,
- deps, earlierCommittedWitness, earlierAcceptedNoWitness,
+ deps, earlierWait, earlierNoWait,
ok1.selfAcceptsFastPath & ok2.selfAcceptsFastPath,
ok1.supersedingRejects | ok2.supersedingRejects,
ok1.writes, ok1.result
@@ -358,22 +362,22 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
public final Ballot accepted;
public final Timestamp executeAt;
public final LatestDeps deps;
- public final Deps earlierCommittedWitness; // counter-point to earlierAcceptedNoWitness
- public final Deps earlierAcceptedNoWitness; // wait for these to commit
+ public final Deps earlierWait; // wait for these to commit
+ public final Deps earlierNoWait; // counter-point to earlierWait, can remove these from any set we wait on
public final boolean selfAcceptsFastPath;
public final boolean supersedingRejects;
public final Writes writes;
public final Result result;
- public RecoverOk(TxnId txnId, Status status, Ballot accepted, Timestamp executeAt, LatestDeps deps, Deps earlierCommittedWitness, Deps earlierAcceptedNoWitness, boolean selfAcceptsFastPath, boolean supersedingRejects, Writes writes, Result result)
+ public RecoverOk(TxnId txnId, Status status, Ballot accepted, Timestamp executeAt, LatestDeps deps, Deps earlierWait, Deps earlierNoWait, boolean selfAcceptsFastPath, boolean supersedingRejects, Writes writes, Result result)
{
this.txnId = txnId;
this.accepted = accepted;
this.executeAt = executeAt;
this.status = status;
this.deps = deps;
- this.earlierCommittedWitness = earlierCommittedWitness;
- this.earlierAcceptedNoWitness = earlierAcceptedNoWitness;
+ this.earlierWait = earlierWait;
+ this.earlierNoWait = earlierNoWait;
this.selfAcceptsFastPath = selfAcceptsFastPath;
this.supersedingRejects = supersedingRejects;
this.writes = writes;
@@ -400,8 +404,8 @@ public class BeginRecovery extends TxnRequest.WithUnsynced<BeginRecovery.Recover
", accepted:" + accepted +
", executeAt:" + executeAt +
", deps:" + deps +
- ", earlierCommittedWitness:" + earlierCommittedWitness +
- ", earlierAcceptedNoWitness:" + earlierAcceptedNoWitness +
+ ", earlierCommittedWitness:" + earlierNoWait +
+ ", earlierAcceptedNoWitness:" + earlierWait +
", selfAcceptsFastPath:" + selfAcceptsFastPath +
", supersedingRejects:" + supersedingRejects +
", writes:" + writes +
diff --git a/accord-core/src/main/java/accord/messages/GetLatestDeps.java b/accord-core/src/main/java/accord/messages/GetLatestDeps.java
index 912e7736..a9eda42c 100644
--- a/accord-core/src/main/java/accord/messages/GetLatestDeps.java
+++ b/accord-core/src/main/java/accord/messages/GetLatestDeps.java
@@ -79,10 +79,17 @@ public class GetLatestDeps extends TxnRequest.WithUnsynced<GetLatestDeps.GetLate
Command command = safeCommand.current();
PartialDeps coordinatedDeps = command.partialDeps();
Deps localDeps = null;
- if (!command.known().deps.hasCommittedOrDecidedDeps())
+ switch (command.known().deps)
{
- // TODO (required): consider owns vs touches - should be touches?
- localDeps = calculateDeps(safeStore, txnId, participants, constant(minEpoch), executeAt, false);
+ default: throw new AssertionError("Unhandled KnownDeps: " + command.known().deps);
+ case NoDeps:
+ case DepsErased:
+ case DepsKnown:
+ case DepsCommitted:
+ break;
+ case DepsUnknown:
+ case DepsProposed:
+ localDeps = calculateDeps(safeStore, txnId, participants, constant(minEpoch), executeAt, false);
}
LatestDeps deps = LatestDeps.create(participants.owns(), command.known().deps, command.acceptedOrCommitted(), coordinatedDeps, localDeps);
diff --git a/accord-core/src/main/java/accord/messages/GetMaxConflict.java b/accord-core/src/main/java/accord/messages/GetMaxConflict.java
deleted file mode 100644
index 3b39a67d..00000000
--- a/accord-core/src/main/java/accord/messages/GetMaxConflict.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package accord.messages;
-
-import javax.annotation.Nonnull;
-
-import accord.local.KeyHistory;
-import accord.local.Node;
-import accord.local.SafeCommandStore;
-import accord.primitives.FullRoute;
-import accord.primitives.Route;
-import accord.primitives.Timestamp;
-import accord.primitives.TxnId;
-import accord.primitives.Unseekables;
-import accord.topology.Topologies;
-import accord.utils.Invariants;
-import accord.utils.async.Cancellable;
-
-public class GetMaxConflict extends TxnRequest.WithUnsynced<GetMaxConflict.GetMaxConflictOk>
-{
- public static final class SerializationSupport
- {
- public static GetMaxConflict create(Route<?> scope, long waitForEpoch, long minEpoch, long executionEpoch)
- {
- return new GetMaxConflict(scope, waitForEpoch, minEpoch, executionEpoch);
- }
- }
-
- public final long executionEpoch;
-
- public GetMaxConflict(Node.Id to, Topologies topologies, FullRoute<?> route, long executionEpoch)
- {
- super(to, topologies, route);
- this.executionEpoch = executionEpoch;
- }
-
- protected GetMaxConflict(Route<?> scope, long waitForEpoch, long minEpoch, long executionEpoch)
- {
- super(TxnId.NONE, scope, waitForEpoch, minEpoch);
- this.executionEpoch = executionEpoch;
- }
-
- @Override
- public Cancellable submit()
- {
- return node.mapReduceConsumeLocal(this, minEpoch, executionEpoch, this);
- }
-
- @Override
- public GetMaxConflictOk apply(SafeCommandStore safeStore)
- {
- Timestamp maxConflict = safeStore.commandStore().maxConflict(scope);
- return new GetMaxConflictOk(maxConflict, Math.max(safeStore.node().epoch(), node.epoch()));
- }
-
- @Override
- public GetMaxConflictOk reduce(GetMaxConflictOk reply1, GetMaxConflictOk reply2)
- {
- return new GetMaxConflictOk(Timestamp.max(reply1.maxConflict, reply2.maxConflict), Math.max(reply1.latestEpoch, reply2.latestEpoch));
- }
-
- @Override
- public MessageType type()
- {
- return MessageType.GET_MAX_CONFLICT_REQ;
- }
-
- @Override
- public String toString()
- {
- return "GetMaxConflict{" +
- ", scope:" + scope +
- '}';
- }
-
- @Override
- public TxnId primaryTxnId()
- {
- return null;
- }
-
- @Override
- public Unseekables<?> keys()
- {
- return scope;
- }
-
- @Override
- public KeyHistory keyHistory()
- {
- return KeyHistory.NONE;
- }
-
- public static class GetMaxConflictOk implements Reply
- {
- public final Timestamp maxConflict;
- public final long latestEpoch;
-
- public GetMaxConflictOk(@Nonnull Timestamp maxConflict, long latestEpoch)
- {
- this.maxConflict = Invariants.nonNull(maxConflict);
- this.latestEpoch = latestEpoch;
- }
-
- @Override
- public String toString()
- {
- return "GetMaxConflictOk(" + maxConflict + ',' + latestEpoch + '}';
- }
-
- @Override
- public MessageType type()
- {
- return MessageType.GET_MAX_CONFLICT_RSP;
- }
- }
-}
diff --git a/accord-core/src/main/java/accord/messages/MessageType.java b/accord-core/src/main/java/accord/messages/MessageType.java
index 1fa6c672..24fb3f6a 100644
--- a/accord-core/src/main/java/accord/messages/MessageType.java
+++ b/accord-core/src/main/java/accord/messages/MessageType.java
@@ -46,8 +46,6 @@ public class MessageType
public static final MessageType GET_LATEST_DEPS_RSP = remote("GET_LATEST_DEPS_RSP", false);
public static final MessageType GET_EPHEMERAL_READ_DEPS_REQ = remote("GET_EPHEMERAL_READ_DEPS_REQ", false);
public static final MessageType GET_EPHEMERAL_READ_DEPS_RSP = remote("GET_EPHEMERAL_READ_DEPS_RSP", false);
- public static final MessageType GET_MAX_CONFLICT_REQ = remote("GET_MAX_CONFLICT_REQ", false);
- public static final MessageType GET_MAX_CONFLICT_RSP = remote("GET_MAX_CONFLICT_RSP", false);
public static final MessageType COMMIT_SLOW_PATH_REQ = remote("COMMIT_SLOW_PATH_REQ", true);
public static final MessageType COMMIT_MAXIMAL_REQ = remote("COMMIT_MAXIMAL_REQ", true );
public static final MessageType STABLE_FAST_PATH_REQ = remote("STABLE_FAST_PATH_REQ", true);
diff --git a/accord-core/src/main/java/accord/messages/ReadData.java b/accord-core/src/main/java/accord/messages/ReadData.java
index 2329d28c..847525c9 100644
--- a/accord-core/src/main/java/accord/messages/ReadData.java
+++ b/accord-core/src/main/java/accord/messages/ReadData.java
@@ -339,7 +339,7 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
return safeStore.unsafeToReadAt(executeAt);
}
- void read(SafeCommandStore safeStore, Command command)
+ protected void read(SafeCommandStore safeStore, Command command)
{
// TODO (required): do we need to check unavailable again on completion, or throughout execution?
// e.g. if we are marked stale and begin processing later commands
@@ -425,7 +425,7 @@ public abstract class ReadData implements PreLoadContext, Request, MapReduceCons
}
}
- boolean cancel()
+ protected boolean cancel()
{
Cancellable clear;
synchronized (this)
diff --git a/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java b/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
index 1f063b08..2b812693 100644
--- a/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
+++ b/accord-core/src/main/java/accord/messages/ReadEphemeralTxnData.java
@@ -135,7 +135,7 @@ public class ReadEphemeralTxnData extends ReadData
}
@Override
- void read(SafeCommandStore safeStore, Command command)
+ protected void read(SafeCommandStore safeStore, Command command)
{
long retryInLaterEpoch = retryInLaterEpoch(executeAtEpoch, safeStore, command);
if (retryInLaterEpoch > 0)
@@ -147,7 +147,7 @@ public class ReadEphemeralTxnData extends ReadData
super.read(safeStore, command);
}
- static long retryInLaterEpoch(long executeAtEpoch, SafeCommandStore safeStore, Command command)
+ public static long retryInLaterEpoch(long executeAtEpoch, SafeCommandStore safeStore, Command command)
{
TxnId txnId = command.txnId();
if (!txnId.awaitsOnlyDeps())
diff --git a/accord-core/src/main/java/accord/messages/WaitUntilApplied.java b/accord-core/src/main/java/accord/messages/WaitUntilApplied.java
index c78b3112..ede5bd11 100644
--- a/accord-core/src/main/java/accord/messages/WaitUntilApplied.java
+++ b/accord-core/src/main/java/accord/messages/WaitUntilApplied.java
@@ -78,7 +78,7 @@ public class WaitUntilApplied extends ReadData
}
@Override
- void read(SafeCommandStore safeStore, Command command)
+ protected void read(SafeCommandStore safeStore, Command command)
{
long retryInLaterEpoch = ReadEphemeralTxnData.retryInLaterEpoch(executeAtEpoch, safeStore, command);
if (retryInLaterEpoch > this.retryInLaterEpoch)
diff --git a/accord-core/src/main/java/accord/primitives/Deps.java b/accord-core/src/main/java/accord/primitives/Deps.java
index 751b8a2c..4079dadf 100644
--- a/accord-core/src/main/java/accord/primitives/Deps.java
+++ b/accord-core/src/main/java/accord/primitives/Deps.java
@@ -30,7 +30,6 @@ import java.util.AbstractList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
-import java.util.function.Predicate;
import javax.annotation.Nullable;
/**
@@ -205,9 +204,9 @@ public class Deps
return new Deps(this.keyDeps.with(that.keyDeps), this.rangeDeps.with(that.rangeDeps), this.directKeyDeps.with(that.directKeyDeps));
}
- public Deps without(Predicate<TxnId> remove)
+ public Deps without(Deps that)
{
- return new Deps(keyDeps.without(remove), rangeDeps.without(remove), directKeyDeps.without(remove));
+ return new Deps(this.keyDeps.without(that.keyDeps), this.rangeDeps.without(that.rangeDeps), this.directKeyDeps.without(that.directKeyDeps));
}
public PartialDeps intersecting(Participants<?> participants)
diff --git a/accord-core/src/main/java/accord/primitives/KeyDeps.java b/accord-core/src/main/java/accord/primitives/KeyDeps.java
index becba4a3..a877018f 100644
--- a/accord-core/src/main/java/accord/primitives/KeyDeps.java
+++ b/accord-core/src/main/java/accord/primitives/KeyDeps.java
@@ -33,7 +33,6 @@ import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
-import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nullable;
@@ -79,7 +78,7 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
{
int[] keysToTxnId = new int[keys.size()];
Arrays.fill(keysToTxnId, keys.size());
- return new KeyDeps(keys, NO_TXNIDS, keysToTxnId);
+ return new KeyDeps(keys, NO_TXNIDS, keysToTxnId, null);
}
/**
@@ -182,10 +181,16 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
}
KeyDeps(RoutingKeys keys, TxnId[] txnIds, int[] keysToTxnIds)
+ {
+ this(keys, txnIds, keysToTxnIds, null);
+ }
+
+ KeyDeps(RoutingKeys keys, TxnId[] txnIds, int[] keysToTxnIds, @Nullable int[] txnIdsToKeys)
{
this.keys = keys;
this.txnIds = txnIds;
this.keysToTxnIds = keysToTxnIds;
+ this.txnIdsToKeys = txnIdsToKeys;
if (!(keys.isEmpty() || keysToTxnIds[keys.size() - 1] == keysToTxnIds.length))
throw illegalArgument(String.format("Last key (%s) in keyToTxnId does not point (%d) to the end of the array (%d);\nkeyToTxnId=%s", keys.get(keys.size() - 1), keysToTxnIds[keys.size() - 1], keysToTxnIds.length, Arrays.toString(keysToTxnIds)));
checkValid(keys.keys, txnIds, keysToTxnIds);
@@ -193,18 +198,11 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
public KeyDeps slice(Ranges ranges)
{
- if (isEmpty())
- return new KeyDeps(keys, txnIds, keysToTxnIds);
-
return select(keys.slice(ranges));
-
}
public KeyDeps intersecting(Unseekables<?> participants)
{
- if (isEmpty())
- return new KeyDeps(keys, txnIds, keysToTxnIds);
-
AbstractUnseekableKeys select = keys.intersecting(participants);
return select(toRoutingKeys(select));
}
@@ -224,7 +222,7 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
{
// TODO (low priority, efficiency): can slice in parallel with selecting keyToTxnId contents to avoid duplicate merging
if (select.isEmpty())
- return new KeyDeps(RoutingKeys.EMPTY, NO_TXNIDS, NO_INTS);
+ return KeyDeps.NONE;
if (select.size() == keys.size())
return this;
@@ -272,7 +270,7 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
return linearUnion(
this.keys.keys, this.keys.keys.length, this.txnIds, this.txnIds.length, this.keysToTxnIds, this.keysToTxnIds.length,
that.keys.keys, that.keys.keys.length, that.txnIds, that.txnIds.length, that.keysToTxnIds, that.keysToTxnIds.length,
- RoutingKey::compareTo, TxnId::compareTo,
+ RoutingKey::compareTo, TxnId::compareTo, null, null,
cachedRoutingKeys(), cachedTxnIds(), cachedInts(),
(keys, keysLength, txnIds, txnIdsLength, out, outLength) ->
new KeyDeps(RoutingKeys.ofSortedUnique(cachedRoutingKeys().complete(keys, keysLength)),
@@ -281,10 +279,19 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
);
}
- public KeyDeps without(Predicate<TxnId> remove)
+ public KeyDeps without(KeyDeps remove)
{
- return remove(this, keys.keys, txnIds, keysToTxnIds, remove,
- NONE, TxnId[]::new, keys, KeyDeps::new);
+ if (isEmpty() || remove.isEmpty()) return this;
+ try (Builder builder = new Builder())
+ {
+ if (!RelationMultiMap.remove(keys.keys, txnIds, keysToTxnIds,
+ remove.keys.keys, remove.txnIds, remove.keysToTxnIds,
+ RoutingKey::compareTo, TxnId::compareTo, builder::add))
+ {
+ return this;
+ }
+ return builder.build();
+ }
}
public boolean contains(TxnId txnId)
@@ -671,30 +678,13 @@ public class KeyDeps implements Iterable<Map.Entry<RoutingKey, TxnId>>
}
private static final KeyDepsAdapter ADAPTER = new KeyDepsAdapter();
- static class KeyDepsAdapter implements Adapter<RoutingKey, TxnId>
- {
- @Override
- public final SymmetricComparator<? super RoutingKey> keyComparator()
- {
- return RoutingKey::compareTo;
- }
-
- @Override
- public final SymmetricComparator<? super TxnId> valueComparator()
- {
- return TxnId::compareTo;
- }
-
- @Override
- public final ObjectBuffers<RoutingKey> cachedKeys()
- {
- return ArrayBuffers.cachedRoutingKeys();
- }
-
- @Override
- public final ObjectBuffers<TxnId> cachedValues()
- {
- return ArrayBuffers.cachedTxnIds();
- }
+ static final class KeyDepsAdapter implements MergeAdapter<RoutingKey, TxnId>
+ {
+ @Override public SymmetricComparator<? super RoutingKey> keyComparator() { return RoutingKey::compareTo; }
+ @Override public SymmetricComparator<? super TxnId> valueComparator() { return TxnId::compareTo; }
+ @Override public int compareKeys(RoutingKey a, RoutingKey b) { return a.compareTo(b); }
+ @Override public int compareValues(TxnId a, TxnId b) { return a.compareTo(b); }
+ @Override public ObjectBuffers<RoutingKey> cachedKeys() { return ArrayBuffers.cachedRoutingKeys(); }
+ @Override public ObjectBuffers<TxnId> cachedValues() { return ArrayBuffers.cachedTxnIds(); }
}
}
diff --git a/accord-core/src/main/java/accord/primitives/RangeDeps.java b/accord-core/src/main/java/accord/primitives/RangeDeps.java
index 2d332f4b..43e7c229 100644
--- a/accord-core/src/main/java/accord/primitives/RangeDeps.java
+++ b/accord-core/src/main/java/accord/primitives/RangeDeps.java
@@ -27,7 +27,6 @@ import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
-import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -41,6 +40,7 @@ import accord.utils.IndexedQuadConsumer;
import accord.utils.IndexedRangeQuadConsumer;
import accord.utils.Invariants;
import accord.utils.RelationMultiMap;
+import accord.utils.RelationMultiMap.MergeAdapter;
import accord.utils.SearchableRangeList;
import accord.utils.SortedArrays;
import accord.utils.SortedArrays.SortedArrayList;
@@ -64,7 +64,6 @@ import static accord.utils.RelationMultiMap.endOffset;
import static accord.utils.RelationMultiMap.invert;
import static accord.utils.RelationMultiMap.linearUnion;
import static accord.utils.RelationMultiMap.newIterator;
-import static accord.utils.RelationMultiMap.remove;
import static accord.utils.RelationMultiMap.startOffset;
import static accord.utils.RelationMultiMap.testEquality;
import static accord.utils.RelationMultiMap.trimUnusedValues;
@@ -646,7 +645,7 @@ public class RangeDeps implements Iterable<Map.Entry<Range, TxnId>>
return linearUnion(
this.ranges, this.ranges.length, this.txnIds, this.txnIds.length, this.rangesToTxnIds, this.rangesToTxnIds.length,
that.ranges, that.ranges.length, that.txnIds, that.txnIds.length, that.rangesToTxnIds, that.rangesToTxnIds.length,
- rangeComparator(), TxnId::compareTo,
+ rangeComparator(), TxnId::compareTo, null, null,
cachedRanges(), cachedTxnIds(), cachedInts(),
(ranges, rangesLength, txnIds, txnIdsLength, out, outLength) ->
new RangeDeps(cachedRanges().complete(ranges, rangesLength),
@@ -655,10 +654,34 @@ public class RangeDeps implements Iterable<Map.Entry<Range, TxnId>>
);
}
- public RangeDeps without(Predicate<TxnId> remove)
+ public RangeDeps without(RangeDeps remove)
{
- return remove(this, ranges, txnIds, rangesToTxnIds, remove,
- NONE, TxnId[]::new, ranges, RangeDeps::new);
+ if (isEmpty() || remove.isEmpty()) return this;
+ try (BuilderByTxnId builder = new BuilderByTxnId())
+ {
+ ensureTxnIdToRange();
+ remove.ensureTxnIdToRange();
+ if (!RelationMultiMap.removeWithPartialMatches(txnIds, ranges, txnIdsToRanges,
+ remove.txnIds, remove.ranges, remove.txnIdsToRanges,
+ TxnId::compareTo, Range::compareIntersecting, builder, (b, id, kr, rr) -> {
+ Range remainder = null;
+ if (rr != null)
+ {
+ int compareStarts = rr.start().compareTo(kr.start());
+ if (rr.end().compareTo(kr.end()) < 0)
+ remainder = rr.newRange(compareStarts >= 0 ? rr.start() : kr.start(), rr.end());
+ if (compareStarts <= 0)
+ return remainder;
+ kr = kr.newRange(kr.start(), rr.start());
+ }
+ b.add(id, kr);
+ return remainder;
+ }))
+ {
+ return this;
+ }
+ return builder.build();
+ }
}
public boolean contains(TxnId txnId)
@@ -1010,7 +1033,24 @@ public class RangeDeps implements Iterable<Map.Entry<Range, TxnId>>
@Override
public void add(Range range, TxnId txnId)
{
- add(txnId, range);
+ if (txnId.equals(lastKey()))
+ {
+ Range last = lastValue();
+ if (range.compareIntersecting(last) == 0)
+ {
+ RoutingKey rstart = range.start(), lstart = last.start();
+ Invariants.checkState(rstart.compareTo(lstart) >= 0);
+ RoutingKey rend = range.end(), lend = last.end();
+ if (rend.compareTo(lend) > 0)
+ updateLast(last.newRange(lstart, rend));
+ return;
+ }
+ }
+ else
+ {
+ nextKey(txnId);
+ }
+ add(range);
}
}
@@ -1020,59 +1060,25 @@ public class RangeDeps implements Iterable<Map.Entry<Range, TxnId>>
}
private static final RangeDepsAdapter ADAPTER = new RangeDepsAdapter();
- private static final class RangeDepsAdapter implements Adapter<Range, TxnId>
+ private static final class RangeDepsAdapter implements MergeAdapter<Range, TxnId>
{
- @Override
- public SymmetricComparator<? super Range> keyComparator()
- {
- return rangeComparator();
- }
-
- @Override
- public SymmetricComparator<? super TxnId> valueComparator()
- {
- return TxnId::compareTo;
- }
-
- @Override
- public ObjectBuffers<Range> cachedKeys()
- {
- return ArrayBuffers.cachedRanges();
- }
-
- @Override
- public ObjectBuffers<TxnId> cachedValues()
- {
- return ArrayBuffers.cachedTxnIds();
- }
+ @Override public SymmetricComparator<? super Range> keyComparator() { return rangeComparator(); }
+ @Override public SymmetricComparator<? super TxnId> valueComparator() { return TxnId::compareTo; }
+ @Override public int compareKeys(Range a, Range b) { return a.compareTo(b); }
+ @Override public int compareValues(TxnId a, TxnId b) { return a.compareTo(b); }
+ @Override public ObjectBuffers<Range> cachedKeys() { return ArrayBuffers.cachedRanges(); }
+ @Override public ObjectBuffers<TxnId> cachedValues() { return ArrayBuffers.cachedTxnIds(); }
}
private static final ReverseRangeDepsAdapter REVERSE_ADAPTER = new ReverseRangeDepsAdapter();
- private static final class ReverseRangeDepsAdapter implements Adapter<TxnId, Range>
- {
- @Override
- public SymmetricComparator<? super TxnId> keyComparator()
- {
- return TxnId::compareTo;
- }
-
- @Override
- public SymmetricComparator<? super Range> valueComparator()
- {
- return rangeComparator();
- }
-
- @Override
- public ObjectBuffers<TxnId> cachedKeys()
- {
- return ArrayBuffers.cachedTxnIds();
- }
-
- @Override
- public ObjectBuffers<Range> cachedValues()
- {
- return ArrayBuffers.cachedRanges();
- }
+ private static final class ReverseRangeDepsAdapter implements MergeAdapter<TxnId, Range>
+ {
+ @Override public SymmetricComparator<? super TxnId> keyComparator() { return TxnId::compareTo; }
+ @Override public SymmetricComparator<? super Range> valueComparator() { return rangeComparator(); }
+ @Override public int compareKeys(TxnId a, TxnId b) { return a.compareTo(b); }
+ @Override public int compareValues(Range a, Range b) { return a.compare(b); }
+ @Override public ObjectBuffers<TxnId> cachedKeys() { return ArrayBuffers.cachedTxnIds(); }
+ @Override public ObjectBuffers<Range> cachedValues() { return ArrayBuffers.cachedRanges(); }
}
}
diff --git a/accord-core/src/main/java/accord/utils/BTreeReducingIntervalMap.java b/accord-core/src/main/java/accord/utils/BTreeReducingIntervalMap.java
index d8b7d0e1..fb8cc5af 100644
--- a/accord-core/src/main/java/accord/utils/BTreeReducingIntervalMap.java
+++ b/accord-core/src/main/java/accord/utils/BTreeReducingIntervalMap.java
@@ -103,6 +103,7 @@ public class BTreeReducingIntervalMap<K extends Comparable<? super K>, V>
public V foldl(BiFunction<V, V, V> reduce)
{
+ // TODO (expected): use BTree fold methods
checkState(!isEmpty());
Iterator<V> iter = valuesIterator(false);
V result = iter.next();
@@ -129,6 +130,7 @@ public class BTreeReducingIntervalMap<K extends Comparable<? super K>, V>
public <V2> V2 foldlWithBounds(QuadFunction<V, V2, K, K, V2> fold, V2 accumulator, Predicate<V2> terminate)
{
+ // TODO (expected): use BTree fold methods
WithBoundsIterator<K, V> iter = withBoundsIterator(true);
while (iter.advance())
{
diff --git a/accord-core/src/main/java/accord/utils/RelationMultiMap.java b/accord-core/src/main/java/accord/utils/RelationMultiMap.java
index 59b8ef44..bf127a18 100644
--- a/accord-core/src/main/java/accord/utils/RelationMultiMap.java
+++ b/accord-core/src/main/java/accord/utils/RelationMultiMap.java
@@ -22,11 +22,15 @@ import accord.primitives.*;
import net.nicoulaj.compilecommand.annotations.Inline;
import java.util.*;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
import java.util.function.IntFunction;
-import java.util.function.Predicate;
import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+
import static accord.utils.ArrayBuffers.*;
+import static accord.utils.Invariants.illegalArgument;
import static accord.utils.Invariants.illegalState;
import static accord.utils.SortedArrays.remap;
import static accord.utils.SortedArrays.remapToSuperset;
@@ -78,10 +82,17 @@ public class RelationMultiMap
{
SymmetricComparator<? super K> keyComparator();
SymmetricComparator<? super V> valueComparator();
+ int compareKeys(K a, K b);
+ int compareValues(V a, V b);
ObjectBuffers<K> cachedKeys();
ObjectBuffers<V> cachedValues();
}
+ public interface MergeAdapter<K, V> extends Adapter<K, V>
+ {
+ default BiFunction<K, K, K> keyMerger() { return null; }
+ default BiFunction<V, V, V> valueMerger() { return null; }
+ }
// TODO (expected, efficiency): cache this object per thread
public static abstract class AbstractBuilder<K, V, T> implements AutoCloseable
@@ -123,7 +134,7 @@ public class RelationMultiMap
public void nextKey(K key)
{
- if (keyCount > 0 && adapter.keyComparator().compare(keys[keyCount - 1], key) >= 0)
+ if (keyCount > 0 && adapter.compareKeys(keys[keyCount - 1], key) >= 0)
hasOrderedKeys = false;
finishKey();
@@ -164,11 +175,11 @@ public class RelationMultiMap
if (!hasOrderedValues)
{
// TODO (low priority, efficiency): this allocates a significant amount of memory: would be preferable to be able to sort using a pre-defined scratch buffer
- Arrays.sort(keysToValues, keyOffset, totalCount);
+ Arrays.sort(keysToValues, keyOffset, totalCount, adapter.valueComparator());
int removed = 0;
for (int i = keyOffset + 1 ; i < totalCount ; ++i)
{
- if (keysToValues[i - 1].equals(keysToValues[i])) ++removed;
+ if (adapter.compareValues(keysToValues[i - 1], keysToValues[i]) == 0) ++removed;
else if (removed > 0) keysToValues[i - removed] = keysToValues[i];
}
totalCount -= removed;
@@ -180,11 +191,26 @@ public class RelationMultiMap
public void add(K key, V value)
{
- if (keyCount == 0 || !keys[keyCount - 1].equals(key))
+ if (keyCount == 0 || adapter.compareKeys(keys[keyCount - 1], key) != 0)
nextKey(key);
add(value);
}
+ protected K lastKey()
+ {
+ return keyCount == 0 ? null : keys[keyCount - 1];
+ }
+
+ protected V lastValue()
+ {
+ return totalCount == 0 ? null : keysToValues[totalCount - 1];
+ }
+
+ protected void updateLast(V value)
+ {
+ keysToValues[totalCount - 1] = value;
+ }
+
/**
* Add this command as a dependency for each intersecting key
*/
@@ -217,7 +243,7 @@ public class RelationMultiMap
int valueCount = 1;
for (int i = 1 ; i < totalCount ; ++i)
{
- if (!uniqueValues[valueCount - 1].equals(uniqueValues[i]))
+ if (0 != adapter.compareValues(uniqueValues[valueCount - 1], uniqueValues[i]))
uniqueValues[valueCount++] = uniqueValues[i];
}
@@ -239,8 +265,8 @@ public class RelationMultiMap
for (int i = 1 ; i < keyCount ; ++i)
{
- if (sortedKeys[i-1].equals(sortedKeys[i]))
- throw new IllegalArgumentException("Key " + sortedKeys[i] + " has been visited more than once ("
+ if (adapter.compareKeys(sortedKeys[i-1], sortedKeys[i]) == 0)
+ throw illegalArgument("Key " + sortedKeys[i] + " has been visited more than once ("
+ Arrays.toString(Arrays.copyOf(keys, keyCount)) + ")");
}
for (int i = 0 ; i < keyCount ; ++i)
@@ -297,7 +323,7 @@ public class RelationMultiMap
*/
public static class LinearMerger<K, V, T> extends PassThroughObjectAndIntBuffers<V> implements Constructor<K, V, Object>, AutoCloseable
{
- final Adapter<K, V> adapter;
+ final MergeAdapter<K, V> adapter;
final PassThroughObjectBuffers<K> keyBuffers;
K[] bufKeys;
V[] bufValues;
@@ -305,10 +331,10 @@ public class RelationMultiMap
int bufKeysLength, bufValuesLength = 0, bufLength = 0;
T from = null;
- public LinearMerger(Adapter<K, V> adapter)
+ public LinearMerger(MergeAdapter<K, V> adapter)
{
super(adapter.cachedValues(), cachedInts());
- keyBuffers = new PassThroughObjectBuffers<>(adapter.cachedKeys());
+ this.keyBuffers = new PassThroughObjectBuffers<>(adapter.cachedKeys());
this.adapter = adapter;
}
@@ -362,6 +388,7 @@ public class RelationMultiMap
bufKeys, bufKeysLength, bufValues, bufValuesLength, buf, bufLength,
keys, keys.length, values, values.length, keysToValues, keysToValues.length,
adapter.keyComparator(), adapter.valueComparator(),
+ adapter.keyMerger(), adapter.valueMerger(),
keyBuffers, this, this, this
);
if (buf == keysToValues)
@@ -593,6 +620,7 @@ public class RelationMultiMap
T linearUnion(K[] leftKeys, int leftKeysLength, V[] leftValues, int leftValuesLength, int[] left, int leftLength,
K[] rightKeys, int rightKeysLength, V[] rightValues, int rightValuesLength, int[] right, int rightLength,
SymmetricComparator<? super K> keyComparator, SymmetricComparator<? super V> valueComparator,
+ @Nullable BiFunction<? super K, ? super K, ? extends K> keyMerger, @Nullable BiFunction<? super V, ? super V, ? extends V> valueMerger,
ObjectBuffers<K> keyBuffers, ObjectBuffers<V> valueBuffers, IntBuffers intBuffers, Constructor<K, V, T> constructor)
{
K[] outKeys = null;
@@ -602,9 +630,10 @@ public class RelationMultiMap
try
{
- outKeys = SortedArrays.linearUnion(leftKeys, leftKeysLength, rightKeys, rightKeysLength, keyComparator, keyBuffers);
+ outKeys = SortedArrays.linearUnion(leftKeys, 0, leftKeysLength, rightKeys, 0, rightKeysLength, keyComparator, keyMerger, keyBuffers);
outKeysLength = keyBuffers.sizeOfLast(outKeys);
- outValues = SortedArrays.linearUnion(leftValues, leftValuesLength, rightValues, rightValuesLength, valueComparator, valueBuffers);
+
+ outValues = SortedArrays.linearUnion(leftValues, 0, leftValuesLength, rightValues, 0, rightValuesLength, valueComparator, valueMerger, valueBuffers);
outValuesLength = valueBuffers.sizeOfLast(outValues);
remapLeft = remapToSuperset(leftValues, leftValuesLength, outValues, outValuesLength, valueComparator, intBuffers);
@@ -870,68 +899,133 @@ public class RelationMultiMap
return result;
}
- public static <K, K2, V, T> T remove(T from, K[] keys, V[] oldValues, int[] oldKeysToValues, Predicate<V> remove, T none, IntFunction<V[]> newValueArray,
- K2 passthroughKeys, SimpleConstructor<K2, V[], T> constructor)
+ public static <K, V> boolean remove(K[] oldKeys, V[] oldValues, int[] oldKeysToValues,
+ K[] removeKeys, V[] removeValues, int[] removeKeysToValues,
+ Comparator<K> keyComparator, Comparator<V> valueComparator,
+ BiConsumer<K, V> keep)
+ {
+ return removeInternal(oldKeys, oldValues, oldKeysToValues,
+ removeKeys, removeValues, removeKeysToValues,
+ keyComparator, valueComparator, keep,
+ (c, k, v, r) -> {
+ if (r == null)
+ c.accept(k, v);
+ return null;
+ }, false);
+ }
+
+ public static <P, K, V> boolean removeWithPartialMatches(K[] oldKeys, V[] oldValues, int[] oldKeysToValues,
+ K[] removeKeys, V[] removeValues, int[] removeKeysToValues,
+ Comparator<K> keyComparator, Comparator<V> valueComparator,
+ P param, QuadFunction<P, K, V, V, V> removeAndSplitValues)
{
- if (isEmpty(keys, oldKeysToValues))
- return from;
+ return removeInternal(oldKeys, oldValues, oldKeysToValues,
+ removeKeys, removeValues, removeKeysToValues,
+ keyComparator, valueComparator,
+ param, removeAndSplitValues, true);
+ }
- IntBuffers cache = ArrayBuffers.cachedInts();
- int[] remapValue = cache.getInts(oldValues.length);
- int[] newKeyToValue = null;
- V[] newValues;
- int o;
- try
+ // TODO (required): add dedicated tests for partial overlap removals
+ private static <P, K, V> boolean removeInternal(K[] oldKeys, V[] oldValues, int[] oldKeysToValues,
+ K[] removeKeys, V[] removeValues, int[] removeKeysToValues,
+ Comparator<K> keyComparator, Comparator<V> valueComparator,
+ P param, QuadFunction<P, K, V, V, V> removeAndSplitValues,
+ boolean withPartialMatches)
+ {
+ if (oldKeys.length == 0 || removeKeys.length == 0)
+ return false;
+
+ boolean removed = false;
+ int ok = 0, rk = 0;
+ while (ok < oldKeys.length && rk < removeKeys.length)
{
- int count = 0;
- for (int i = 0 ; i < oldValues.length ; ++i)
+ K okey = oldKeys[ok], rkey = removeKeys[rk];
+ int c = keyComparator.compare(okey, rkey);
+ if (c > 0)
{
- if (remove.test(oldValues[i])) remapValue[i] = -1;
- else remapValue[i] = count++;
+ ++rk;
}
-
- if (count == oldValues.length)
- return from;
-
- if (count == 0)
- return none;
-
- newValues = newValueArray.apply(count);
- for (int i = 0 ; i < oldValues.length ; ++i)
+ else if (c < 0)
{
- if (remapValue[i] >= 0)
- newValues[remapValue[i]] = oldValues[i];
+ if (removed)
+ {
+ for (int oi = startOffset(oldKeys, oldKeysToValues, ok), maxoi = endOffset(oldKeysToValues, ok) ; oi < maxoi ; ++oi)
+ removeAndSplitValues.apply(param, okey, oldValues[oldKeysToValues[oi]], null);
+ }
+ ++ok;
}
-
- newKeyToValue = cache.getInts(oldKeysToValues.length);
- int k = 0, i = keys.length;
- o = i;
- while (i < oldKeysToValues.length)
+ else
{
- while (oldKeysToValues[k] == i)
- newKeyToValue[k++] = o;
+ int oi = startOffset(oldKeys, oldKeysToValues, ok), maxoi = endOffset(oldKeysToValues, ok);
+ int ri = startOffset(removeKeys, removeKeysToValues, rk), maxri = endOffset(removeKeysToValues, rk);
+ V oval = oldValues[oldKeysToValues[oi]];
+ V rval = removeValues[removeKeysToValues[ri]];
+ while (true)
+ {
+ c = valueComparator.compare(oval, rval);
+ if (c < 0)
+ {
+ if (removed)
+ removeAndSplitValues.apply(param, okey, oval, null);
+ if (++oi == maxoi) break;
+ oval = oldValues[oldKeysToValues[oi]];
+ }
+ else if (c > 0)
+ {
+ if (++ri == maxri) break;
+ rval = removeValues[removeKeysToValues[ri]];
+ }
+ else
+ {
+ if (!removed)
+ {
+ removed = true;
+ for (int tk = 0 ; tk < ok ; tk++)
+ {
+ K key = oldKeys[tk];
+ for (int ti = startOffset(oldKeys, oldKeysToValues, tk), maxti = endOffset(oldKeysToValues, tk) ; ti < maxti ; ++ti)
+ removeAndSplitValues.apply(param, key, oldValues[oldKeysToValues[ti]], null);
+ }
+ for (int ti = startOffset(oldKeys, oldKeysToValues, ok) ; ti < oi ; ++ti)
+ removeAndSplitValues.apply(param, okey, oldValues[oldKeysToValues[ti]], null);
+ }
- int remapped = remapValue[oldKeysToValues[i]];
- if (remapped >= 0)
- newKeyToValue[o++] = remapped;
- ++i;
+ oval = removeAndSplitValues.apply(param, okey, oval, rval);
+ if (oval == null)
+ {
+ if (++oi == maxoi) break;
+ oval = oldValues[oldKeysToValues[oi]];
+ }
+ if (!withPartialMatches)
+ {
+ if (++ri == maxri) break;
+ rval = removeValues[removeKeysToValues[ri]];
+ }
+ }
+ }
+ if (removed && oi < maxoi)
+ {
+ removeAndSplitValues.apply(param, okey, oval, null);
+ while (++oi < maxoi)
+ removeAndSplitValues.apply(param, okey, oldValues[oldKeysToValues[oi]], null);
+ }
+ ++ok;
+ ++rk;
}
-
- while (k < keys.length)
- newKeyToValue[k++] = o;
}
- catch (Throwable t)
- {
- cache.forceDiscard(newKeyToValue);
- throw t;
- }
- finally
+
+ if (!removed)
+ return false;
+
+ while (ok < oldKeys.length)
{
- cache.forceDiscard(remapValue);
+ K key = oldKeys[ok];
+ for (int oi = startOffset(oldKeys, oldKeysToValues, ok), maxoi = endOffset(oldKeysToValues, ok) ; oi < maxoi ; ++oi)
+ removeAndSplitValues.apply(param, key, oldValues[oldKeysToValues[oi]], null);
+ ++ok;
}
- newKeyToValue = cache.completeAndDiscard(newKeyToValue, o);
- return constructor.construct(passthroughKeys, newValues, newKeyToValue);
+ return true;
}
@Inline
diff --git a/accord-core/src/main/java/accord/utils/SortedArrays.java b/accord-core/src/main/java/accord/utils/SortedArrays.java
index 67b1248c..e0751c26 100644
--- a/accord-core/src/main/java/accord/utils/SortedArrays.java
+++ b/accord-core/src/main/java/accord/utils/SortedArrays.java
@@ -24,6 +24,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
+import java.util.function.BiFunction;
import java.util.function.IntBinaryOperator;
import java.util.function.IntFunction;
import java.util.function.Predicate;
@@ -247,39 +248,66 @@ public class SortedArrays
}
public static <O, T extends O> O[] linearUnion(T[] left, int leftStart, int leftEnd, T[] right, int rightStart, int rightEnd, AsymmetricComparator<? super T, ? super T> comparator, ObjectBuffers<O> buffers)
+ {
+ return linearUnion(left, leftStart, leftEnd, right, rightStart, rightEnd, comparator, null, buffers);
+ }
+
+ public static <O, T extends O> O[] linearUnion(T[] left, int leftStart, int leftEnd, T[] right, int rightStart, int rightEnd, AsymmetricComparator<? super T, ? super T> comparator, @Nullable BiFunction<? super T, ? super T, ? extends T> merge, ObjectBuffers<O> buffers)
{
int leftIdx = leftStart;
int rightIdx = rightStart;
- O[] result = null;
- int resultSize = 0;
+ O[] result;
+ int resultSize;
// first, pick the superset candidate and merge the two until we find the first missing item
// if none found, return the superset candidate
if (leftEnd - leftIdx >= rightEnd - rightIdx)
{
- while (leftIdx < leftEnd && rightIdx < rightEnd)
+ int cmp = 0;
+ boolean unfinished;
+ if (merge == null)
{
- T leftKey = left[leftIdx];
- T rightKey = right[rightIdx];
- int cmp = leftKey == rightKey ? 0 : comparator.compare(leftKey, rightKey);
-
- if (cmp <= 0)
+ while (unfinished = (leftIdx < leftEnd && rightIdx < rightEnd))
{
+ T leftKey = left[leftIdx];
+ T rightKey = right[rightIdx];
+
+ cmp = leftKey == rightKey ? 0 : comparator.compare(leftKey, rightKey);
+ if (cmp > 0) break;
+
leftIdx += 1;
rightIdx += cmp == 0 ? 1 : 0;
}
- else
+ }
+ else
+ {
+ while (unfinished = (leftIdx < leftEnd && rightIdx < rightEnd))
{
- resultSize = leftIdx - leftStart;
- result = buffers.get(resultSize + (leftEnd - leftIdx) + (rightEnd - (rightIdx - 1)));
- System.arraycopy(left, leftStart, result, 0, resultSize);
- result[resultSize++] = right[rightIdx++];
- break;
+ T leftKey = left[leftIdx];
+ T rightKey = right[rightIdx];
+ cmp = leftKey == rightKey ? 0 : comparator.compare(leftKey, rightKey);
+ if (cmp > 0) break;
+
+ if (cmp == 0)
+ {
+ if (merge.apply(leftKey, rightKey) != leftKey)
+ break;
+ ++rightIdx;
+ }
+ ++leftIdx;
}
}
- if (result == null)
+ if (unfinished)
+ {
+ resultSize = leftIdx - leftStart;
+ result = buffers.get(resultSize + (leftEnd - leftIdx) + (rightEnd - (rightIdx - 1)));
+ System.arraycopy(left, leftStart, result, 0, resultSize);
+ if (cmp != 0)
+ result[resultSize++] = right[rightIdx++];
+ }
+ else
{
if (rightIdx == rightEnd) // all elements matched, so can return the other array
{
@@ -299,28 +327,50 @@ public class SortedArrays
}
else
{
- while (leftIdx < leftEnd && rightIdx < rightEnd)
+ int cmp = 0;
+ boolean unfinished;
+ if (merge == null)
{
- T leftKey = left[leftIdx];
- T rightKey = right[rightIdx];
- int cmp = leftKey == rightKey ? 0 : comparator.compare(leftKey, rightKey);
-
- if (cmp >= 0)
+ while (unfinished = (leftIdx < leftEnd && rightIdx < rightEnd))
{
+ T leftKey = left[leftIdx];
+ T rightKey = right[rightIdx];
+ cmp = leftKey == rightKey ? 0 : comparator.compare(leftKey, rightKey);
+
+ if (cmp < 0) break;
rightIdx += 1;
leftIdx += cmp == 0 ? 1 : 0;
}
- else
+ }
+ else
+ {
+ while (unfinished = (leftIdx < leftEnd && rightIdx < rightEnd))
{
- resultSize = rightIdx - rightStart;
- result = buffers.get(resultSize + (leftEnd - (leftIdx - 1)) + (rightEnd - rightIdx));
- System.arraycopy(right, rightStart, result, 0, resultSize);
- result[resultSize++] = left[leftIdx++];
- break;
+ T leftKey = left[leftIdx];
+ T rightKey = right[rightIdx];
+ cmp = leftKey == rightKey ? 0 : comparator.compare(leftKey, rightKey);
+
+ if (cmp < 0) break;
+
+ if (cmp == 0)
+ {
+ if (merge.apply(rightKey, leftKey) != rightKey)
+ break;
+ ++leftIdx;
+ }
+ ++rightIdx;
}
}
- if (result == null)
+ if (unfinished)
+ {
+ resultSize = rightIdx - rightStart;
+ result = buffers.get(resultSize + (leftEnd - (leftIdx - 1)) + (rightEnd - rightIdx));
+ System.arraycopy(right, rightStart, result, 0, resultSize);
+ if (cmp != 0)
+ result[resultSize++] = left[leftIdx++];
+ }
+ else
{
if (leftIdx == leftEnd) // all elements matched, so can return the other array
{
@@ -353,7 +403,7 @@ public class SortedArrays
{
leftIdx++;
rightIdx++;
- minKey = leftKey;
+ minKey = merge == null ? leftKey : merge.apply(leftKey, rightKey);
}
else if (cmp < 0)
{
@@ -1309,7 +1359,6 @@ public class SortedArrays
return null;
int[] result = allocator.getInts(srcLength);
-
int i = 0, j = 0;
while (i < srcLength && j < trgLength)
{
diff --git a/accord-core/src/test/java/accord/burn/BurnTestConfigurationService.java b/accord-core/src/test/java/accord/burn/BurnTestConfigurationService.java
index cb078277..574e4493 100644
--- a/accord-core/src/test/java/accord/burn/BurnTestConfigurationService.java
+++ b/accord-core/src/test/java/accord/burn/BurnTestConfigurationService.java
@@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -155,6 +156,15 @@ public class BurnTestConfigurationService extends AbstractConfigurationService.M
}
}
+ @Override
+ public void reportTopology(Topology topology, boolean isLoad, boolean startSync)
+ {
+ // we process via scheduler.selfRecurring only to logically detach from any client task so we can terminate
+ Node node = lookup.apply(localId);
+ if (node == null) super.reportTopology(topology, isLoad, startSync);
+ else node.scheduler().selfRecurring(() -> super.reportTopology(topology, isLoad, startSync), 0, TimeUnit.MILLISECONDS);
+ }
+
@Override
protected void fetchTopologyInternal(long epoch)
{
diff --git a/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java b/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java
index 2e034aca..cb5584e3 100644
--- a/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java
+++ b/accord-core/src/test/java/accord/impl/basic/DelayedCommandStores.java
@@ -29,6 +29,8 @@ import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
+import com.google.common.collect.ImmutableSortedMap;
+
import accord.api.Agent;
import accord.api.DataStore;
import accord.api.Journal;
@@ -180,26 +182,40 @@ public class DelayedCommandStores extends InMemoryCommandStores.SingleThread
protected void loadRedundantBefore(RedundantBefore redundantBefore)
{
- if (redundantBefore != null)
- unsafeSetRedundantBefore(redundantBefore);
+ if (redundantBefore == null)
+ {
+ Invariants.checkState(unsafeGetRedundantBefore().size() == 0);
+ }
+ else
+ {
+ unsafeClearRedundantBefore();
+ super.loadRedundantBefore(redundantBefore);
+ }
}
protected void loadBootstrapBeganAt(NavigableMap<TxnId, Ranges> bootstrapBeganAt)
{
- if (bootstrapBeganAt != null)
- unsafeSetBootstrapBeganAt(bootstrapBeganAt);
+ unsafeClearBootstrapBeganAt();
+ if (bootstrapBeganAt == null) bootstrapBeganAt = ImmutableSortedMap.of(TxnId.NONE, Ranges.EMPTY);
+ super.loadBootstrapBeganAt(bootstrapBeganAt);
}
protected void loadSafeToRead(NavigableMap<Timestamp, Ranges> safeToRead)
{
- if (safeToRead != null)
- unsafeSetSafeToRead(safeToRead);
+ unsafeClearSafeToRead();
+ if (safeToRead == null) safeToRead = ImmutableSortedMap.of(Timestamp.NONE, Ranges.EMPTY);
+ super.loadSafeToRead(safeToRead);
}
- protected void loadRangesForEpoch(CommandStores.RangesForEpoch rangesForEpoch)
+ @Override
+ protected void loadRangesForEpoch(RangesForEpoch newRangesForEpoch)
{
- if (rangesForEpoch != null)
- unsafeSetRangesForEpoch(rangesForEpoch);
+ if (newRangesForEpoch == null) Invariants.checkState(super.rangesForEpoch == null);
+ else
+ {
+ unsafeClearRangesForEpoch();
+ super.loadRangesForEpoch(newRangesForEpoch);
+ }
}
public void restore()
diff --git a/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java b/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
index bc2824e5..6e000b94 100644
--- a/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
+++ b/accord-core/src/test/java/accord/impl/basic/InMemoryJournal.java
@@ -59,30 +59,18 @@ import org.agrona.collections.Int2ObjectHashMap;
import static accord.api.Journal.Load.ALL;
import static accord.impl.CommandChange.*;
-import static accord.impl.CommandChange.Fields.ACCEPTED;
-import static accord.impl.CommandChange.Fields.DURABILITY;
-import static accord.impl.CommandChange.Fields.EXECUTES_AT_LEAST;
-import static accord.impl.CommandChange.Fields.EXECUTE_AT;
-import static accord.impl.CommandChange.Fields.PARTIAL_DEPS;
-import static accord.impl.CommandChange.Fields.PARTIAL_TXN;
-import static accord.impl.CommandChange.Fields.PARTICIPANTS;
-import static accord.impl.CommandChange.Fields.PROMISED;
-import static accord.impl.CommandChange.Fields.RESULT;
-import static accord.impl.CommandChange.Fields.SAVE_STATUS;
-import static accord.impl.CommandChange.Fields.WAITING_ON;
-import static accord.impl.CommandChange.Fields.WRITES;
-import static accord.impl.CommandChange.anyFieldChanged;
-import static accord.impl.CommandChange.getFieldChanged;
-import static accord.impl.CommandChange.getFieldIsNull;
-import static accord.impl.CommandChange.getFlags;
-import static accord.impl.CommandChange.getWaitingOn;
-import static accord.impl.CommandChange.nextSetField;
-import static accord.impl.CommandChange.setFieldChanged;
-import static accord.impl.CommandChange.setFieldIsNull;
-import static accord.impl.CommandChange.toIterableSetFields;
-import static accord.impl.CommandChange.unsetFieldIsNull;
-import static accord.impl.CommandChange.unsetIterableFields;
-import static accord.impl.CommandChange.validateFlags;
+import static accord.impl.CommandChange.Field.ACCEPTED;
+import static accord.impl.CommandChange.Field.DURABILITY;
+import static accord.impl.CommandChange.Field.EXECUTES_AT_LEAST;
+import static accord.impl.CommandChange.Field.EXECUTE_AT;
+import static accord.impl.CommandChange.Field.PARTIAL_DEPS;
+import static accord.impl.CommandChange.Field.PARTIAL_TXN;
+import static accord.impl.CommandChange.Field.PARTICIPANTS;
+import static accord.impl.CommandChange.Field.PROMISED;
+import static accord.impl.CommandChange.Field.RESULT;
+import static accord.impl.CommandChange.Field.SAVE_STATUS;
+import static accord.impl.CommandChange.Field.WAITING_ON;
+import static accord.impl.CommandChange.Field.WRITES;
import static accord.primitives.SaveStatus.ErasedOrVestigial;
import static accord.primitives.SaveStatus.Stable;
import static accord.primitives.Status.Invalidated;
@@ -463,20 +451,20 @@ public class InMemoryJournal implements Journal
private static class Diff
{
public final TxnId txnId;
- public final Map<Fields, Object> changes;
+ public final Map<Field, Object> changes;
public final int flags;
private Diff(int flags, CommandUpdate update)
{
this.flags = flags;
this.txnId = update.txnId;
- this.changes = new EnumMap<>(Fields.class);
+ this.changes = new EnumMap<>(Field.class);
Command after = update.after;
int iterable = toIterableSetFields(flags);
while (iterable != 0)
{
- Fields field = nextSetField(iterable);
+ Field field = nextSetField(iterable);
if (!getFieldChanged(field, flags) || getFieldIsNull(field, flags))
{
iterable = unsetIterableFields(field, iterable);
@@ -547,7 +535,7 @@ public class InMemoryJournal implements Journal
int iterable = toIterableSetFields(diff.flags);
while (iterable != 0)
{
- Fields field = nextSetField(iterable);
+ Field field = nextSetField(iterable);
if (getFieldChanged(field, diff.flags))
{
this.flags = setFieldChanged(field, this.flags);
@@ -567,7 +555,7 @@ public class InMemoryJournal implements Journal
}
}
- private void setNull(Fields field)
+ private void setNull(Field field)
{
switch (field)
{
@@ -612,7 +600,7 @@ public class InMemoryJournal implements Journal
}
}
- private void deserialize(Diff diff, Fields field)
+ private void deserialize(Diff diff, Field field)
{
switch (field)
{
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 c6143726..b7ba4cdf 100644
--- a/accord-core/src/test/java/accord/impl/list/ListAgent.java
+++ b/accord-core/src/test/java/accord/impl/list/ListAgent.java
@@ -28,6 +28,7 @@ import accord.api.Agent;
import accord.api.ProgressLog;
import accord.api.Result;
import accord.coordinate.ExecuteSyncPoint;
+import accord.coordinate.Preempted;
import accord.coordinate.Timeout;
import accord.impl.basic.Packet;
import accord.impl.mock.Network;
@@ -114,7 +115,7 @@ public class ListAgent implements Agent
@Override
public void onUncaughtException(Throwable t)
{
- if (!(t instanceof Timeout) && !(t instanceof ExecuteSyncPoint.SyncPointErased))
+ if (!(t instanceof Timeout) && !(t instanceof ExecuteSyncPoint.SyncPointErased) && !(t instanceof Preempted))
onFailure.accept(t);
}
diff --git a/accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java b/accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java
index 153a3f77..d0ea7f4d 100644
--- a/accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java
+++ b/accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java
@@ -29,6 +29,7 @@ import accord.impl.InMemoryCommandStore;
import accord.local.CommandStore;
import accord.local.Node;
import accord.local.PreLoadContext;
+import accord.local.SafeCommandStore;
import accord.primitives.PartialDeps;
import accord.primitives.PartialTxn;
import accord.primitives.Ranges;
@@ -36,6 +37,7 @@ import accord.primitives.SyncPoint;
import accord.primitives.Timestamp;
import accord.primitives.Txn;
import accord.primitives.TxnId;
+import accord.utils.async.AsyncChain;
import accord.utils.async.AsyncResult;
public class ListFetchCoordinator extends AbstractFetchCoordinator
@@ -71,15 +73,30 @@ public class ListFetchCoordinator extends AbstractFetchCoordinator
}
@Override
- protected FetchRequest newFetchRequest(long sourceEpoch, TxnId syncId, Ranges ranges, PartialDeps partialDeps, PartialTxn partialTxn)
+ protected ListFetchRequest newFetchRequest(long sourceEpoch, TxnId syncId, Ranges ranges, PartialDeps partialDeps, PartialTxn partialTxn)
{
if (((ListAgent)node.agent()).collectMaxApplied())
return new CollectMaxAppliedFetchRequest(sourceEpoch, syncId, ranges, partialDeps, partialTxn);
- return super.newFetchRequest(sourceEpoch, syncId, ranges, partialDeps, partialTxn);
+ return new ListFetchRequest(sourceEpoch, syncId, ranges, partialDeps, partialTxn);
}
- class CollectMaxAppliedFetchRequest extends FetchRequest
+ static class ListFetchRequest extends FetchRequest
+ {
+ public ListFetchRequest(long sourceEpoch, TxnId syncId, Ranges ranges, PartialDeps partialDeps, PartialTxn partialTxn)
+ {
+ super(sourceEpoch, syncId, ranges, partialDeps, partialTxn);
+ }
+
+ @Override
+ protected AsyncChain<Data> beginRead(SafeCommandStore safeStore, Timestamp executeAt, PartialTxn txn, Ranges unavailable)
+ {
+ readStarted(safeStore, unavailable);
+ return super.beginRead(safeStore, executeAt, txn, unavailable);
+ }
+ }
+
+ static class CollectMaxAppliedFetchRequest extends ListFetchRequest
{
private transient Timestamp maxApplied;
@@ -89,10 +106,11 @@ public class ListFetchCoordinator extends AbstractFetchCoordinator
}
@Override
- protected void readComplete(CommandStore commandStore, Data result, Ranges unavailable)
+ protected void readStarted(SafeCommandStore safeStore, Ranges unavailable)
{
- Ranges slice = commandStore.unsafeGetRangesForEpoch().allAt(txnId).without(unavailable);
- ((InMemoryCommandStore)commandStore).maxAppliedFor((Ranges)readScope, slice).begin((newMaxApplied, failure) -> {
+ CommandStore commandStore = safeStore.commandStore();
+ Ranges slice = safeStore.ranges().allAt(txnId).without(unavailable);
+ ((InMemoryCommandStore)commandStore).maxAppliedFor(readScope, slice).begin((newMaxApplied, failure) -> {
if (failure != null)
{
commandStore.agent().onUncaughtException(failure);
@@ -103,17 +121,15 @@ public class ListFetchCoordinator extends AbstractFetchCoordinator
{
if (maxApplied == null) maxApplied = newMaxApplied;
else maxApplied = Timestamp.max(maxApplied, newMaxApplied);
- super.readComplete(commandStore, result, unavailable);
}
}
});
}
@Override
- protected Timestamp maxApplied()
+ protected Timestamp safeToReadAfter()
{
return maxApplied;
}
}
-
}
diff --git a/accord-core/src/test/java/accord/primitives/KeyDepsTest.java b/accord-core/src/test/java/accord/primitives/KeyDepsTest.java
index e3eee0e4..f56a0d31 100644
--- a/accord-core/src/test/java/accord/primitives/KeyDepsTest.java
+++ b/accord-core/src/test/java/accord/primitives/KeyDepsTest.java
@@ -151,34 +151,26 @@ public class KeyDepsTest
{
qt().forAll(Deps::generate).check(deps -> {
// no matches
- Assertions.assertSame(deps.test, deps.test.without(ignore -> false));
+ Assertions.assertSame(deps.test, deps.test.without(KeyDeps.NONE));
// all match
- Assertions.assertSame(accord.primitives.KeyDeps.NONE, deps.test.without(ignore -> true));
+ Assertions.assertSame(accord.primitives.KeyDeps.NONE, deps.test.without(deps.test));
- // remove specific TxnId
- for (TxnId txnId : deps.test.txnIds())
+ // remove specific key
+ for (RoutingKey key : deps.test.keys())
{
- accord.primitives.KeyDeps without = deps.test.without(i -> i.equals(txnId));
- // Was the TxnId removed?
- List<TxnId> expectedTxnId = new ArrayList<>(deps.test.txnIds());
- expectedTxnId.remove(txnId);
- Assertions.assertEquals(expectedTxnId, without.txnIds());
+ RoutingKeys withoutKeys = RoutingKeys.of(key);
+ RoutingKeys expectedKeys = (RoutingKeys) deps.test.keys.without(withoutKeys);
+ accord.primitives.KeyDeps without = deps.test.without(deps.test.intersecting(expectedKeys));
+ Assertions.assertEquals(expectedKeys, without.keys());
- Assertions.assertEquals(RoutingKeys.EMPTY, without.participatingKeys(txnId));
// all other keys are fine?
- for (TxnId other : deps.test.txnIds())
- {
- if (other == txnId)
- continue;
- Assertions.assertEquals(deps.test.participatingKeys(other), without.participatingKeys(other), "someKeys(" + other + ")");
- }
+ for (RoutingKey otherKey : expectedKeys)
+ Assertions.assertEquals(deps.test.txnIds(key), without.txnIds(key), "txnIds(" + otherKey + ")");
- // check each key
- for (RoutingKey key : deps.test.keys())
+ // check each TxnId
+ for (TxnId txnId : deps.test.txnIds())
{
- List<TxnId> expected = get(deps.test, key);
- expected.remove(txnId);
-
+ RoutingKeys expected = (RoutingKeys) deps.test.participatingKeys(txnId).without(withoutKeys);
Assertions.assertEquals(expected, get(without, key), () -> "TxnId " + txnId + " is expected to be removed for key " + key);
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org