Follow-up to CASSANDRA-20228:

- Fix waiting state callback computes different route to initiator
 - Invariants.checkX -> Invariants.requireX (to allow complementary Invariants.expectX as appropriate)

patch by Benedict; reviewed by Alex Petrov for CASSANDRA-20228

Follow-up to CASSANDRA-20228:
 - Fix AccordUpdateParameters to correctly supply List cell paths derived from applyAt
 - Fix ExecuteAtSerialize.serialiseNullable
 - Fix topologies flush regression caused by markRetired forcing a flush on every call

patch by Benedict; reviewed by Ariel Weisberg for CASSANDRA-20228
This commit is contained in:
Benedict Elliott Smith 2025-01-27 16:27:06 +00:00 committed by David Capwell
parent 2e850db02d
commit 7f0e5f8e8b
93 changed files with 353 additions and 398 deletions

@ -1 +1 @@
Subproject commit 41aacd31c93251043154b5f73239345ee68b7957 Subproject commit c7a789b1f424771a4befab6bcb91edd4ab5d7198

View File

@ -272,7 +272,7 @@ public class AccordSpec
return units.convert(nanos, TimeUnit.NANOSECONDS); return units.convert(nanos, TimeUnit.NANOSECONDS);
long flushPeriodNanos = flushPeriod(TimeUnit.NANOSECONDS); long flushPeriodNanos = flushPeriod(TimeUnit.NANOSECONDS);
Invariants.checkState(flushPeriodNanos > 0); Invariants.require(flushPeriodNanos > 0);
nanos = periodicFlushLagBlock.to(TimeUnit.NANOSECONDS) + flushPeriodNanos; nanos = periodicFlushLagBlock.to(TimeUnit.NANOSECONDS) + flushPeriodNanos;
// it is possible for this to race and cache the wrong value after an update // it is possible for this to race and cache the wrong value after an update
flushCombinedBlockPeriod = nanos; flushCombinedBlockPeriod = nanos;

View File

@ -51,10 +51,9 @@ public class UpdateParameters
public final TableMetadata metadata; public final TableMetadata metadata;
public final ClientState clientState; public final ClientState clientState;
public final QueryOptions options; public final QueryOptions options;
public final boolean constructingAccordBaseUpdate;
private final long nowInSec; private final long nowInSec;
private final long timestamp; protected final long timestamp;
private final int ttl; private final int ttl;
private final DeletionTime deletionTime; private final DeletionTime deletionTime;
@ -75,18 +74,6 @@ public class UpdateParameters
long nowInSec, long nowInSec,
int ttl, int ttl,
Map<DecoratedKey, Partition> prefetchedRows) throws InvalidRequestException Map<DecoratedKey, Partition> prefetchedRows) throws InvalidRequestException
{
this(metadata, clientState, options, timestamp, nowInSec, ttl, prefetchedRows, false);
}
public UpdateParameters(TableMetadata metadata,
ClientState clientState,
QueryOptions options,
long timestamp,
long nowInSec,
int ttl,
Map<DecoratedKey, Partition> prefetchedRows,
boolean constructingAccordBaseUpdate) throws InvalidRequestException
{ {
this.metadata = metadata; this.metadata = metadata;
this.clientState = clientState; this.clientState = clientState;
@ -104,8 +91,6 @@ public class UpdateParameters
// it to avoid potential confusion. // it to avoid potential confusion.
if (timestamp == Long.MIN_VALUE) if (timestamp == Long.MIN_VALUE)
throw new InvalidRequestException(String.format("Out of bound timestamp, must be in [%d, %d]", Long.MIN_VALUE + 1, Long.MAX_VALUE)); throw new InvalidRequestException(String.format("Out of bound timestamp, must be in [%d, %d]", Long.MIN_VALUE + 1, Long.MAX_VALUE));
this.constructingAccordBaseUpdate = constructingAccordBaseUpdate;
} }
public <V> void newRow(Clustering<V> clustering) throws InvalidRequestException public <V> void newRow(Clustering<V> clustering) throws InvalidRequestException

View File

@ -969,8 +969,8 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
local, local,
timestamp, timestamp,
nowInSeconds, nowInSeconds,
requestTime, requestTime
constructingAccordBaseUpdate); );
for (ByteBuffer key : keys) for (ByteBuffer key : keys)
{ {
Validation.validateKey(metadata(), key); Validation.validateKey(metadata(), key);
@ -994,7 +994,7 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
if (restrictions.hasClusteringColumnsRestrictions() && clusterings.isEmpty()) if (restrictions.hasClusteringColumnsRestrictions() && clusterings.isEmpty())
return; return;
UpdateParameters params = makeUpdateParameters(keys, clusterings, state, options, local, timestamp, nowInSeconds, requestTime, constructingAccordBaseUpdate); UpdateParameters params = makeUpdateParameters(keys, clusterings, state, options, local, timestamp, nowInSeconds, requestTime);
for (ByteBuffer key : keys) for (ByteBuffer key : keys)
{ {
@ -1052,8 +1052,7 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
boolean local, boolean local,
long timestamp, long timestamp,
long nowInSeconds, long nowInSeconds,
Dispatcher.RequestTime requestTime, Dispatcher.RequestTime requestTime)
boolean constructingAccordBaseUpdate)
{ {
if (clusterings.contains(Clustering.STATIC_CLUSTERING)) if (clusterings.contains(Clustering.STATIC_CLUSTERING))
return makeUpdateParameters(keys, return makeUpdateParameters(keys,
@ -1064,8 +1063,8 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
local, local,
timestamp, timestamp,
nowInSeconds, nowInSeconds,
requestTime, requestTime
constructingAccordBaseUpdate); );
return makeUpdateParameters(keys, return makeUpdateParameters(keys,
new ClusteringIndexNamesFilter(clusterings, false), new ClusteringIndexNamesFilter(clusterings, false),
@ -1075,8 +1074,8 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
local, local,
timestamp, timestamp,
nowInSeconds, nowInSeconds,
requestTime, requestTime
constructingAccordBaseUpdate); );
} }
private UpdateParameters makeUpdateParameters(Collection<ByteBuffer> keys, private UpdateParameters makeUpdateParameters(Collection<ByteBuffer> keys,
@ -1087,8 +1086,7 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
boolean local, boolean local,
long timestamp, long timestamp,
long nowInSeconds, long nowInSeconds,
Dispatcher.RequestTime requestTime, Dispatcher.RequestTime requestTime)
boolean constructingAccordBaseUpdate)
{ {
// Some lists operation requires reading // Some lists operation requires reading
Map<DecoratedKey, Partition> lists = Map<DecoratedKey, Partition> lists =
@ -1106,8 +1104,7 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
getTimestamp(timestamp, options), getTimestamp(timestamp, options),
nowInSeconds, nowInSeconds,
getTimeToLive(options), getTimeToLive(options),
lists, lists);
constructingAccordBaseUpdate);
} }
public static abstract class Parsed extends QualifiedStatement public static abstract class Parsed extends QualifiedStatement

View File

@ -44,7 +44,6 @@ import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.Int32Type; import org.apache.cassandra.db.marshal.Int32Type;
import org.apache.cassandra.db.marshal.ListType; import org.apache.cassandra.db.marshal.ListType;
import org.apache.cassandra.db.marshal.MultiElementType; import org.apache.cassandra.db.marshal.MultiElementType;
import org.apache.cassandra.db.marshal.TimeUUIDType;
import org.apache.cassandra.db.rows.Cell; import org.apache.cassandra.db.rows.Cell;
import org.apache.cassandra.db.rows.CellPath; import org.apache.cassandra.db.rows.CellPath;
import org.apache.cassandra.db.rows.ComplexColumnData; import org.apache.cassandra.db.rows.ComplexColumnData;
@ -52,7 +51,6 @@ import org.apache.cassandra.db.rows.Row;
import org.apache.cassandra.exceptions.InvalidRequestException; import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.schema.ColumnMetadata; import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.TimeUUID;
import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse; import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest; import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
@ -68,13 +66,6 @@ public abstract class Lists
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static final Logger logger = LoggerFactory.getLogger(Lists.class); private static final Logger logger = LoggerFactory.getLogger(Lists.class);
/**
* Sentinel value indicating the cell path should be replaced by Accord with one based on the transaction executeAt
*/
private static final TimeUUID ACCORD_CELL_PATH_SENTINEL_UUID = TimeUUID.atUnixMicrosWithLsb(0, 0);
public static final CellPath ACCORD_DUMMY_CELL_PATH = CellPath.create(ACCORD_CELL_PATH_SENTINEL_UUID.toBytes());
private static final long ACCORD_CELL_PATH_SENTINEL_MSB = ACCORD_CELL_PATH_SENTINEL_UUID.msb();
private Lists() {} private Lists() {}
public static ColumnSpecification indexSpecOf(ColumnSpecification column) public static ColumnSpecification indexSpecOf(ColumnSpecification column)
@ -160,33 +151,6 @@ public abstract class Lists
return type == null ? null : ListType.getInstance(type, false); return type == null ? null : ListType.getInstance(type, false);
} }
/**
* Return a function that given a cell with an ACCORD_CELL_PATH_SENTINEL_MSB will
* return a new CellPath with a TimeUUID that increases monotonically every time it is called or
* the existing cell path if path does not contain ACCORD_CELL_PATH_SENTINEL_MSB.
*
* Only intended to work with list cell paths where list append needs a timestamp based on the executeAt
* of the Accord transaction appending the cell.
* @param timestampMicros executeAt timestamp to use as the MSB for generated cell paths
*/
public static com.google.common.base.Function<Cell, CellPath> accordListPathSupplier(long timestampMicros)
{
return new com.google.common.base.Function<Cell, CellPath>()
{
final long timeUuidMsb = TimeUUID.unixMicrosToMsb(timestampMicros);
long cellIndex = 0;
@Override
public CellPath apply(Cell cell)
{
CellPath path = cell.path();
if (ACCORD_CELL_PATH_SENTINEL_MSB == path.get(0).getLong(0))
return CellPath.create(ByteBuffer.wrap(TimeUUID.toBytes(timeUuidMsb, TimeUUIDType.signedBytesToNativeLong(cellIndex++))));
else
return path;
}
};
}
public static class Literal extends Term.Raw public static class Literal extends Term.Raw
{ {
private final List<Term.Raw> elements; private final List<Term.Raw> elements;
@ -463,17 +427,10 @@ public abstract class Lists
// during SSTable write. // during SSTable write.
Guardrails.itemsPerCollection.guard(type.collectionSize(elements), column.name.toString(), false, params.clientState); Guardrails.itemsPerCollection.guard(type.collectionSize(elements), column.name.toString(), false, params.clientState);
long cellIndex = 0;
int dataSize = 0; int dataSize = 0;
for (ByteBuffer buffer : elements) for (ByteBuffer buffer : elements)
{ {
ByteBuffer cellPath; ByteBuffer cellPath = ByteBuffer.wrap(params.nextTimeUUIDAsBytes());
// Accord will need to replace this value later once it knows the executeAt timestamp
// so just put a TimeUUID with MSB sentinel for now
if (params.constructingAccordBaseUpdate)
cellPath = TimeUUID.atUnixMicrosWithLsb(0, cellIndex++).toBytes();
else
cellPath = ByteBuffer.wrap(params.nextTimeUUIDAsBytes());
Cell<?> cell = params.addCell(column, CellPath.create(cellPath), buffer); Cell<?> cell = params.addCell(column, CellPath.create(cellPath), buffer);
dataSize += cell.dataSize(); dataSize += cell.dataSize();
} }

View File

@ -905,7 +905,7 @@ public class CompactionIterator extends CompactionInfo.Holder implements Unfilte
AccordJournal.Builder commandBuilder = (AccordJournal.Builder) builder; AccordJournal.Builder commandBuilder = (AccordJournal.Builder) builder;
if (commandBuilder.isEmpty()) if (commandBuilder.isEmpty())
{ {
Invariants.checkState(rows.isEmpty()); Invariants.require(rows.isEmpty());
return partition; return partition;
} }
@ -954,9 +954,9 @@ public class CompactionIterator extends CompactionInfo.Holder implements Unfilte
if (lastOffset != -1) if (lastOffset != -1)
{ {
Invariants.checkState(descriptor <= lastDescriptor, Invariants.require(descriptor <= lastDescriptor,
"Descriptors were accessed out of order: %d was accessed after %d", descriptor, lastDescriptor); "Descriptors were accessed out of order: %d was accessed after %d", descriptor, lastDescriptor);
Invariants.checkState(descriptor != lastDescriptor || Invariants.require(descriptor != lastDescriptor ||
offset < lastOffset, offset < lastOffset,
"Offsets within %s were accessed out of order: %d was accessed after %s", offset, lastOffset); "Offsets within %s were accessed out of order: %d was accessed after %s", offset, lastOffset);
} }

View File

@ -108,7 +108,7 @@ public class ByteArrayAccessor implements ValueAccessor<byte[]>
@Override @Override
public byte[] slice(byte[] input, int offset, int length) public byte[] slice(byte[] input, int offset, int length)
{ {
Invariants.checkArgument(offset + length <= input.length); Invariants.requireArgument(offset + length <= input.length);
return Arrays.copyOfRange(input, offset, offset + length); return Arrays.copyOfRange(input, offset, offset + length);
} }

View File

@ -312,9 +312,9 @@ public class CompositeType extends AbstractCompositeType
byte[] result = Arrays.copyOf(bytes, c); byte[] result = Arrays.copyOf(bytes, c);
if (bytes != tmpBytes) tmpFlattenBuffer.set(bytes); if (bytes != tmpBytes) tmpFlattenBuffer.set(bytes);
byte[] test = super.asFlatComparableBytes(accessor, data, version); byte[] test = super.asFlatComparableBytes(accessor, data, version);
if (Invariants.isParanoid() && Invariants.testParanoia(LINEAR, CONSTANT, LOW)) Invariants.checkState(Arrays.equals(test, result)); if (Invariants.isParanoid() && Invariants.testParanoia(LINEAR, CONSTANT, LOW)) Invariants.require(Arrays.equals(test, result));
V roundtrip = fromComparableBytes(accessor, ByteSource.peekable(ByteSource.of(result, version)), version); V roundtrip = fromComparableBytes(accessor, ByteSource.peekable(ByteSource.of(result, version)), version);
Invariants.checkState(accessor.compare(data, roundtrip, accessor) == 0); Invariants.require(accessor.compare(data, roundtrip, accessor) == 0);
return result; return result;
} }

View File

@ -578,7 +578,7 @@ public class AccordDebugKeyspace extends VirtualKeyspace
CommandStoreTxnBlockedGraph.TxnState txn = shard.txns.get(txnId); CommandStoreTxnBlockedGraph.TxnState txn = shard.txns.get(txnId);
if (txn == null) if (txn == null)
{ {
Invariants.checkState(reason == Reason.Self, "Txn %s unknown for reason %s", txnId, reason); Invariants.require(reason == Reason.Self, "Txn %s unknown for reason %s", txnId, reason);
return; return;
} }
// was it applied? If so ignore it // was it applied? If so ignore it

View File

@ -26,7 +26,7 @@ import accord.utils.Invariants;
import org.apache.cassandra.service.accord.api.AccordRoutingKey; import org.apache.cassandra.service.accord.api.AccordRoutingKey;
import org.apache.cassandra.service.accord.api.AccordRoutingKey.SentinelKey; import org.apache.cassandra.service.accord.api.AccordRoutingKey.SentinelKey;
import static accord.utils.Invariants.checkArgument; import static accord.utils.Invariants.requireArgument;
import static java.math.BigInteger.ONE; import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO; import static java.math.BigInteger.ZERO;
@ -50,9 +50,9 @@ public class AccordBytesSplitter extends AccordSplitter
// Since BOP is already not working/supported I think it's fine to punt on this. // Since BOP is already not working/supported I think it's fine to punt on this.
if (bytesLength == 0) if (bytesLength == 0)
{ {
checkArgument(ranges.size() <= 1); requireArgument(ranges.size() <= 1);
checkArgument(ranges.isEmpty() || ranges.get(0).start().getClass() == SentinelKey.class); requireArgument(ranges.isEmpty() || ranges.get(0).start().getClass() == SentinelKey.class);
checkArgument(ranges.isEmpty() || ranges.get(0).end().getClass() == SentinelKey.class); requireArgument(ranges.isEmpty() || ranges.get(0).end().getClass() == SentinelKey.class);
// Intentionally does not match 16 that is used by ServerTestUtils.getRandomToken to elicit breakage // Intentionally does not match 16 that is used by ServerTestUtils.getRandomToken to elicit breakage
bytesLength = 8; bytesLength = 8;
} }
@ -75,7 +75,7 @@ public class AccordBytesSplitter extends AccordSplitter
BigInteger valueForToken(Token token) BigInteger valueForToken(Token token)
{ {
byte[] bytes = ((ByteOrderedPartitioner.BytesToken) token).token; byte[] bytes = ((ByteOrderedPartitioner.BytesToken) token).token;
checkArgument(bytes.length <= byteLength); requireArgument(bytes.length <= byteLength);
BigInteger value = ZERO; BigInteger value = ZERO;
for (int i = 0 ; i < bytes.length ; ++i) for (int i = 0 ; i < bytes.length ; ++i)
value = value.add(BigInteger.valueOf(bytes[i] & 0xffL).shiftLeft((byteLength - 1 - i) * 8)); value = value.add(BigInteger.valueOf(bytes[i] & 0xffL).shiftLeft((byteLength - 1 - i) * 8));
@ -85,7 +85,7 @@ public class AccordBytesSplitter extends AccordSplitter
@Override @Override
Token tokenForValue(BigInteger value) Token tokenForValue(BigInteger value)
{ {
Invariants.checkArgument(value.compareTo(ZERO) >= 0); Invariants.requireArgument(value.compareTo(ZERO) >= 0);
byte[] bytes = new byte[byteLength]; byte[] bytes = new byte[byteLength];
for (int i = 0 ; i < bytes.length ; ++i) for (int i = 0 ; i < bytes.length ; ++i)
bytes[i] = value.shiftRight((byteLength - 1 - i) * 8).byteValue(); bytes[i] = value.shiftRight((byteLength - 1 - i) * 8).byteValue();

View File

@ -81,7 +81,7 @@ public class LocalCompositePrefixPartitioner extends LocalPartitioner
@Override @Override
public int compareTo(Token o) public int compareTo(Token o)
{ {
Invariants.checkArgument(o instanceof AbstractCompositePrefixToken); Invariants.requireArgument(o instanceof AbstractCompositePrefixToken);
AbstractCompositePrefixToken that = (AbstractCompositePrefixToken) o; AbstractCompositePrefixToken that = (AbstractCompositePrefixToken) o;
CompositeType comparator = comparatorForPrefixLength(Math.min(this.prefixSize(), that.prefixSize())); CompositeType comparator = comparatorForPrefixLength(Math.min(this.prefixSize(), that.prefixSize()));
return comparator.compare(this.token, that.token); return comparator.compare(this.token, that.token);
@ -136,7 +136,7 @@ public class LocalCompositePrefixPartitioner extends LocalPartitioner
public PrefixToken(ByteBuffer token, int prefixSize) public PrefixToken(ByteBuffer token, int prefixSize)
{ {
super(token); super(token);
Invariants.checkArgument(prefixSize > 0); Invariants.requireArgument(prefixSize > 0);
this.prefixSize = prefixSize; this.prefixSize = prefixSize;
} }
@ -231,7 +231,7 @@ public class LocalCompositePrefixPartitioner extends LocalPartitioner
public DecoratedKey decoratedKey(Object... values) public DecoratedKey decoratedKey(Object... values)
{ {
Invariants.checkArgument(values.length == prefixComparators.size()); Invariants.requireArgument(values.length == prefixComparators.size());
ByteBuffer key = createPrefixKey(values); ByteBuffer key = createPrefixKey(values);
return decorateKey(key); return decorateKey(key);
} }

View File

@ -48,7 +48,7 @@ import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.ObjectSizes; import org.apache.cassandra.utils.ObjectSizes;
import org.apache.cassandra.utils.Pair; import org.apache.cassandra.utils.Pair;
import static accord.utils.Invariants.checkArgument; import static accord.utils.Invariants.requireArgument;
import static java.lang.Integer.max; import static java.lang.Integer.max;
import static java.math.BigInteger.ONE; import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO; import static java.math.BigInteger.ZERO;
@ -330,7 +330,7 @@ public class OrderPreservingPartitioner implements IPartitioner
BigInteger valueForToken(Token token) BigInteger valueForToken(Token token)
{ {
String chars = ((StringToken) token).token; String chars = ((StringToken) token).token;
checkArgument(chars.length() <= charLength); requireArgument(chars.length() <= charLength);
BigInteger value = ZERO; BigInteger value = ZERO;
for (int i = 0 ; i < chars.length() ; ++i) for (int i = 0 ; i < chars.length() ; ++i)
value = value.add(BigInteger.valueOf(chars.charAt(i) & 0xffffL).shiftLeft((charLength - 1 - i) * 16)); value = value.add(BigInteger.valueOf(chars.charAt(i) & 0xffffL).shiftLeft((charLength - 1 - i) * 16));
@ -341,7 +341,7 @@ public class OrderPreservingPartitioner implements IPartitioner
Token tokenForValue(BigInteger value) Token tokenForValue(BigInteger value)
{ {
// TODO (required): test // TODO (required): test
checkArgument(value.compareTo(ZERO) >= 0); requireArgument(value.compareTo(ZERO) >= 0);
char[] chars = new char[charLength]; char[] chars = new char[charLength];
for (int i = 0 ; i < chars.length ; ++i) for (int i = 0 ; i < chars.length ; ++i)
chars[i] = (char) value.shiftRight((charLength - 1 - i) * 16).shortValue(); chars[i] = (char) value.shiftRight((charLength - 1 - i) * 16).shortValue();

View File

@ -40,8 +40,8 @@ public final class EntrySerializer
{ {
int start = out.position(); int start = out.position();
int totalSize = out.getInt() - start; int totalSize = out.getInt() - start;
Invariants.checkState(totalSize == TypeSizes.INT_SIZE + out.remaining()); Invariants.require(totalSize == TypeSizes.INT_SIZE + out.remaining());
Invariants.checkState(totalSize == headerSize(keySupport, userVersion) + record.remaining() + TypeSizes.INT_SIZE); Invariants.require(totalSize == headerSize(keySupport, userVersion) + record.remaining() + TypeSizes.INT_SIZE);
keySupport.serialize(key, out, userVersion); keySupport.serialize(key, out, userVersion);
@ -50,7 +50,7 @@ public final class EntrySerializer
int recordSize = record.remaining(); int recordSize = record.remaining();
int recordEnd = out.position() + recordSize; int recordEnd = out.position() + recordSize;
Invariants.checkState(out.limit() == recordEnd + TypeSizes.INT_SIZE); Invariants.require(out.limit() == recordEnd + TypeSizes.INT_SIZE);
ByteBufferUtil.copyBytes(record, record.position(), out, out.position(), recordSize); ByteBufferUtil.copyBytes(record, record.position(), out, out.position(), recordSize);
// update and write crcs // update and write crcs
@ -77,7 +77,7 @@ public final class EntrySerializer
int start = from.position(); int start = from.position();
{ {
int totalSize = from.getInt(start) - start; int totalSize = from.getInt(start) - start;
Invariants.checkState(totalSize == from.remaining()); Invariants.require(totalSize == from.remaining());
CRC32 crc = Crc.crc32(); CRC32 crc = Crc.crc32();
int headerSize = EntrySerializer.headerSize(keySupport, userVersion); int headerSize = EntrySerializer.headerSize(keySupport, userVersion);

View File

@ -275,7 +275,7 @@ final class Flusher<K, V>
if (flushPeriodNanos <= 0) if (flushPeriodNanos <= 0)
{ {
Invariants.checkState(params.flushMode() != PERIODIC); Invariants.require(params.flushMode() != PERIODIC);
haveWork.acquire(1); haveWork.acquire(1);
} }
else else
@ -517,7 +517,7 @@ final class Flusher<K, V>
signal.awaitThrowUncheckedOnInterrupt(); signal.awaitThrowUncheckedOnInterrupt();
Journal.State state = journal.state.get(); Journal.State state = journal.state.get();
Invariants.checkState(state == Journal.State.NORMAL, Invariants.require(state == Journal.State.NORMAL,
"Thread %s outlived journal, which is in %s state", Thread.currentThread(), state); "Thread %s outlived journal, which is in %s state", Thread.currentThread(), state);
} }
else else

View File

@ -197,7 +197,7 @@ public class Journal<K, V> implements Shutdownable
public void start() public void start()
{ {
Invariants.checkState(state.compareAndSet(State.UNINITIALIZED, State.INITIALIZING), Invariants.require(state.compareAndSet(State.UNINITIALIZED, State.INITIALIZING),
"Unexpected journal state during initialization", state); "Unexpected journal state during initialization", state);
metrics.register(flusher); metrics.register(flusher);
@ -216,7 +216,7 @@ public class Journal<K, V> implements Shutdownable
releaser = executorFactory().sequential(name + "-releaser"); releaser = executorFactory().sequential(name + "-releaser");
allocator = executorFactory().infiniteLoop(name + "-allocator", new AllocateRunnable(), SAFE, NON_DAEMON, SYNCHRONIZED); allocator = executorFactory().infiniteLoop(name + "-allocator", new AllocateRunnable(), SAFE, NON_DAEMON, SYNCHRONIZED);
advanceSegment(null); advanceSegment(null);
Invariants.checkState(state.compareAndSet(State.INITIALIZING, State.NORMAL), Invariants.require(state.compareAndSet(State.INITIALIZING, State.NORMAL),
"Unexpected journal state after initialization", state); "Unexpected journal state after initialization", state);
flusher.start(); flusher.start();
compactor.start(); compactor.start();
@ -252,7 +252,7 @@ public class Journal<K, V> implements Shutdownable
{ {
try try
{ {
Invariants.checkState(state.compareAndSet(State.NORMAL, State.SHUTDOWN), Invariants.require(state.compareAndSet(State.NORMAL, State.SHUTDOWN),
"Unexpected journal state while trying to shut down", state); "Unexpected journal state while trying to shut down", state);
allocator.shutdown(); allocator.shutdown();
wakeAllocator(); // Wake allocator to force it into shutdown wakeAllocator(); // Wake allocator to force it into shutdown
@ -268,7 +268,7 @@ public class Journal<K, V> implements Shutdownable
releaser.awaitTermination(1, TimeUnit.MINUTES); releaser.awaitTermination(1, TimeUnit.MINUTES);
closeAllSegments(); closeAllSegments();
metrics.deregister(); metrics.deregister();
Invariants.checkState(state.compareAndSet(State.SHUTDOWN, State.TERMINATED), Invariants.require(state.compareAndSet(State.SHUTDOWN, State.TERMINATED),
"Unexpected journal state while trying to shut down", state); "Unexpected journal state while trying to shut down", state);
} }
catch (InterruptedException e) catch (InterruptedException e)
@ -774,7 +774,7 @@ public class Journal<K, V> implements Shutdownable
else else
{ {
Segment<K, V> segment = segments().get(timestamp); Segment<K, V> segment = segments().get(timestamp);
Invariants.checkState(segment != null, "Segment %d expected to be found, but neither current segment %d nor in active segments", timestamp, currentSegmentTimestamp); Invariants.require(segment != null, "Segment %d expected to be found, but neither current segment %d nor in active segments", timestamp, currentSegmentTimestamp);
if (segment == null) if (segment == null)
throw new IllegalArgumentException("Request the active segment " + timestamp + " but this segment does not exist"); throw new IllegalArgumentException("Request the active segment " + timestamp + " but this segment does not exist");
if (!segment.isActive()) if (!segment.isActive())
@ -965,7 +965,7 @@ public class Journal<K, V> implements Shutdownable
StaticSegment.KeyOrderReader<K> next = readers.peek(); StaticSegment.KeyOrderReader<K> next = readers.peek();
if (next == null || !next.key().equals(key)) if (next == null || !next.key().equals(key))
break; break;
Invariants.checkState(next == readers.poll()); Invariants.require(next == readers.poll());
reader.accept(next.descriptor.timestamp, next.offset, next.key(), next.record(), next.descriptor.userVersion); reader.accept(next.descriptor.timestamp, next.offset, next.key(), next.record(), next.descriptor.userVersion);
if (next.advance()) if (next.advance())

View File

@ -171,7 +171,7 @@ final class OnDiskIndex<K> extends Index<K>
if (prev != -1) if (prev != -1)
{ {
long tmp = prev; long tmp = prev;
Invariants.checkState(readOffset(offsetAndSize) < readOffset(prev), Invariants.require(readOffset(offsetAndSize) < readOffset(prev),
() -> String.format("Offsets should be strictly reverse monotonic, but found %d following %d", () -> String.format("Offsets should be strictly reverse monotonic, but found %d following %d",
readOffset(offsetAndSize), readOffset(tmp))); readOffset(offsetAndSize), readOffset(tmp)));
} }

View File

@ -91,7 +91,7 @@ public abstract class Segment<K, V> implements SelfRefCounted<Segment<K, V>>, Co
int size = Index.readSize(offsetAndSize); int size = Index.readSize(offsetAndSize);
if (read(offset, size, into)) if (read(offset, size, into))
{ {
Invariants.checkState(id.equals(into.key), "Index for %s read incorrect key: expected %s but read %s", descriptor, id, into.key); Invariants.require(id.equals(into.key), "Index for %s read incorrect key: expected %s but read %s", descriptor, id, into.key);
consumer.accept(descriptor.timestamp, offset, id, into.value, descriptor.userVersion); consumer.accept(descriptor.timestamp, offset, id, into.value, descriptor.userVersion);
return true; return true;
} }
@ -103,7 +103,7 @@ public abstract class Segment<K, V> implements SelfRefCounted<Segment<K, V>>, Co
long offsetAndSize = index().lookUpLast(id); long offsetAndSize = index().lookUpLast(id);
if (offsetAndSize == -1 || !read(Index.readOffset(offsetAndSize), Index.readSize(offsetAndSize), into)) if (offsetAndSize == -1 || !read(Index.readOffset(offsetAndSize), Index.readSize(offsetAndSize), into))
return false; return false;
Invariants.checkState(id.equals(into.key), "Index for %s read incorrect key: expected %s but read %s", descriptor, id, into.key); Invariants.require(id.equals(into.key), "Index for %s read incorrect key: expected %s but read %s", descriptor, id, into.key);
return true; return true;
} }
@ -115,9 +115,9 @@ public abstract class Segment<K, V> implements SelfRefCounted<Segment<K, V>>, Co
{ {
int offset = Index.readOffset(all[i]); int offset = Index.readOffset(all[i]);
int size = Index.readSize(all[i]); int size = Index.readSize(all[i]);
Invariants.checkState(offset < prevOffset); Invariants.require(offset < prevOffset);
Invariants.checkState(read(offset, size, into), "Read should always return true"); Invariants.require(read(offset, size, into), "Read should always return true");
Invariants.checkState(id.equals(into.key), "Index for %s read incorrect key: expected %s but read %s", descriptor, id, into.key); Invariants.require(id.equals(into.key), "Index for %s read incorrect key: expected %s but read %s", descriptor, id, into.key);
onEntry.accept(descriptor.timestamp, offset, into.key, into.value, into.userVersion); onEntry.accept(descriptor.timestamp, offset, into.key, into.value, into.userVersion);
} }
} }

View File

@ -58,7 +58,7 @@ class Segments<K, V>
{ {
Long2ObjectHashMap<Segment<K, V>> newSegments = new Long2ObjectHashMap<>(segments); Long2ObjectHashMap<Segment<K, V>> newSegments = new Long2ObjectHashMap<>(segments);
Segment<K, V> oldValue = newSegments.put(activeSegment.descriptor.timestamp, activeSegment); Segment<K, V> oldValue = newSegments.put(activeSegment.descriptor.timestamp, activeSegment);
Invariants.checkState(oldValue == null); Invariants.require(oldValue == null);
return new Segments<>(newSegments); return new Segments<>(newSegments);
} }
@ -66,16 +66,16 @@ class Segments<K, V>
{ {
Long2ObjectHashMap<Segment<K, V>> newSegments = new Long2ObjectHashMap<>(segments); Long2ObjectHashMap<Segment<K, V>> newSegments = new Long2ObjectHashMap<>(segments);
Segment<K, V> oldValue = segments.remove(activeSegment.descriptor.timestamp); Segment<K, V> oldValue = segments.remove(activeSegment.descriptor.timestamp);
Invariants.checkState(oldValue.asActive().isEmpty()); Invariants.require(oldValue.asActive().isEmpty());
return new Segments<>(newSegments); return new Segments<>(newSegments);
} }
Segments<K, V> withCompletedSegment(ActiveSegment<K, V> activeSegment, StaticSegment<K, V> staticSegment) Segments<K, V> withCompletedSegment(ActiveSegment<K, V> activeSegment, StaticSegment<K, V> staticSegment)
{ {
Invariants.checkArgument(activeSegment.descriptor.equals(staticSegment.descriptor)); Invariants.requireArgument(activeSegment.descriptor.equals(staticSegment.descriptor));
Long2ObjectHashMap<Segment<K, V>> newSegments = new Long2ObjectHashMap<>(segments); Long2ObjectHashMap<Segment<K, V>> newSegments = new Long2ObjectHashMap<>(segments);
Segment<K, V> oldValue = newSegments.put(staticSegment.descriptor.timestamp, staticSegment); Segment<K, V> oldValue = newSegments.put(staticSegment.descriptor.timestamp, staticSegment);
Invariants.checkState(oldValue == activeSegment, () -> String.format("old value %s != new %s", oldValue, activeSegment)); Invariants.require(oldValue == activeSegment, () -> String.format("old value %s != new %s", oldValue, activeSegment));
return new Segments<>(newSegments); return new Segments<>(newSegments);
} }
@ -85,13 +85,13 @@ class Segments<K, V>
for (StaticSegment<K, V> oldSegment : oldSegments) for (StaticSegment<K, V> oldSegment : oldSegments)
{ {
Segment<K, V> oldValue = newSegments.remove(oldSegment.descriptor.timestamp); Segment<K, V> oldValue = newSegments.remove(oldSegment.descriptor.timestamp);
Invariants.checkState(oldValue == oldSegment); Invariants.require(oldValue == oldSegment);
} }
for (StaticSegment<K, V> compactedSegment : compactedSegments) for (StaticSegment<K, V> compactedSegment : compactedSegments)
{ {
Segment<K, V> oldValue = newSegments.put(compactedSegment.descriptor.timestamp, compactedSegment); Segment<K, V> oldValue = newSegments.put(compactedSegment.descriptor.timestamp, compactedSegment);
Invariants.checkState(oldValue == null); Invariants.require(oldValue == null);
} }
return new Segments<>(newSegments); return new Segments<>(newSegments);

View File

@ -272,7 +272,7 @@ public final class TableId implements Comparable<TableId>
long compact = in.readUnsignedVInt(); long compact = in.readUnsignedVInt();
if (compact > 0) if (compact > 0)
return fromLong(compact - 1); return fromLong(compact - 1);
Invariants.checkState(compact == 0); Invariants.require(compact == 0);
return deserialize(in); return deserialize(in);
} }
@ -281,7 +281,7 @@ public final class TableId implements Comparable<TableId>
long compact = accessor.getUnsignedVInt(src, offset); long compact = accessor.getUnsignedVInt(src, offset);
if (compact > 0) if (compact > 0)
return fromLong(compact - 1); return fromLong(compact - 1);
Invariants.checkState(compact == 0); Invariants.require(compact == 0);
return deserialize(src, accessor, offset + 1); return deserialize(src, accessor, offset + 1);
} }

View File

@ -82,7 +82,7 @@ import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.FBUtilities;
import org.github.jamm.Unmetered; import org.github.jamm.Unmetered;
import static accord.utils.Invariants.checkState; import static accord.utils.Invariants.require;
import static com.google.common.collect.Iterables.any; import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Iterables.transform;
import static java.lang.String.format; import static java.lang.String.format;
@ -619,7 +619,7 @@ public class TableMetadata implements SchemaElement
} }
} }
checkState((params.transactionalMode == TransactionalMode.off && params.transactionalMigrationFrom == TransactionalMigrationFromMode.none) || !isCounter(), "Counters are not supported with Accord for table " + this); require((params.transactionalMode == TransactionalMode.off && params.transactionalMigrationFrom == TransactionalMigrationFromMode.none) || !isCounter(), "Counters are not supported with Accord for table " + this);
} }
/** /**

View File

@ -66,8 +66,8 @@ import org.apache.cassandra.utils.NoSpamLogger;
import org.apache.cassandra.utils.NoSpamLogger.NoSpamLogStatement; import org.apache.cassandra.utils.NoSpamLogger.NoSpamLogStatement;
import org.apache.cassandra.utils.ObjectSizes; import org.apache.cassandra.utils.ObjectSizes;
import static accord.utils.Invariants.checkState;
import static accord.utils.Invariants.illegalState; import static accord.utils.Invariants.illegalState;
import static accord.utils.Invariants.require;
import static org.apache.cassandra.net.MessagingService.current_version; import static org.apache.cassandra.net.MessagingService.current_version;
import static org.apache.cassandra.service.accord.AccordCacheEntry.Status.EVICTED; import static org.apache.cassandra.service.accord.AccordCacheEntry.Status.EVICTED;
import static org.apache.cassandra.service.accord.AccordCacheEntry.Status.LOADED; import static org.apache.cassandra.service.accord.AccordCacheEntry.Status.LOADED;
@ -225,7 +225,7 @@ public class AccordCache implements CacheSize
@VisibleForTesting @VisibleForTesting
private <K, V> void shrinkOrEvict(AccordCacheEntry<K, V> node) private <K, V> void shrinkOrEvict(AccordCacheEntry<K, V> node)
{ {
checkState(node.references() == 0); require(node.references() == 0);
if (shrinkingOn && node.tryShrink()) if (shrinkingOn && node.tryShrink())
{ {
@ -243,7 +243,7 @@ public class AccordCache implements CacheSize
@VisibleForTesting @VisibleForTesting
public <K, V> void tryEvict(AccordCacheEntry<K, V> node) public <K, V> void tryEvict(AccordCacheEntry<K, V> node)
{ {
checkState(node.references() == 0); require(node.references() == 0);
if (node.isNoEvict()) if (node.isNoEvict())
{ {
@ -278,7 +278,7 @@ public class AccordCache implements CacheSize
if (logger.isTraceEnabled()) if (logger.isTraceEnabled())
logger.trace("Evicting {}", node); logger.trace("Evicting {}", node);
checkState(node.isUnqueued()); require(node.isUnqueued());
if (updateUnreferenced) if (updateUnreferenced)
{ {
@ -296,8 +296,8 @@ public class AccordCache implements CacheSize
owner.validateLoadEvicted(node); owner.validateLoadEvicted(node);
AccordCacheEntry<?, ?> self = node.owner.cache.remove(node.key()); AccordCacheEntry<?, ?> self = node.owner.cache.remove(node.key());
Invariants.checkState(self.references() == 0); Invariants.require(self.references() == 0);
checkState(self == node, "Leaked node detected; was attempting to remove %s but cache had %s", node, self); require(self == node, "Leaked node detected; was attempting to remove %s but cache had %s", node, self);
node.notifyListeners(Listener::onEvict); node.notifyListeners(Listener::onEvict);
node.evicted(); node.evicted();
} }
@ -316,10 +316,10 @@ public class AccordCache implements CacheSize
<K, V> void failedToLoad(AccordCacheEntry<K, V> node) <K, V> void failedToLoad(AccordCacheEntry<K, V> node)
{ {
Invariants.checkState(node.references() == 0); Invariants.require(node.references() == 0);
if (node.isUnqueued()) if (node.isUnqueued())
{ {
Invariants.checkState(node.status() == EVICTED); Invariants.require(node.status() == EVICTED);
return; return;
} }
node.unlink(); node.unlink();
@ -422,14 +422,14 @@ public class AccordCache implements CacheSize
public S acquire(AccordCacheEntry<K, V> node) public S acquire(AccordCacheEntry<K, V> node)
{ {
Invariants.checkState(node.owner == this); Invariants.require(node.owner == this);
acquireExisting(node, false); acquireExisting(node, false);
return adapter.safeRef(node); return adapter.safeRef(node);
} }
public void recordPreAcquired(AccordSafeState<K, V> ref) public void recordPreAcquired(AccordSafeState<K, V> ref)
{ {
Invariants.checkState(ref.global().owner == this); Invariants.require(ref.global().owner == this);
incrementCacheHits(); incrementCacheHits();
} }
@ -456,7 +456,7 @@ public class AccordCache implements CacheSize
Object prev = cache.put(key, node); Object prev = cache.put(key, node);
node.initSize(parent()); node.initSize(parent());
Invariants.checkState(prev == null, "%s not absent from cache: %s already present", key, node); Invariants.require(prev == null, "%s not absent from cache: %s already present", key, node);
++size; ++size;
node.notifyListeners(Listener::onAdd); node.notifyListeners(Listener::onAdd);
maybeShrinkOrEvictSomeNodes(); maybeShrinkOrEvictSomeNodes();
@ -494,11 +494,11 @@ public class AccordCache implements CacheSize
AccordCacheEntry<K, V> node = cache.get(key); AccordCacheEntry<K, V> node = cache.get(key);
checkState(!safeRef.invalidated()); require(!safeRef.invalidated());
checkState(safeRef.global() != null, "safeRef node is null for %s", key); require(safeRef.global() != null, "safeRef node is null for %s", key);
checkState(safeRef.global() == node, "safeRef node not in map: %s != %s", safeRef.global(), node); require(safeRef.global() == node, "safeRef node not in map: %s != %s", safeRef.global(), node);
checkState(node.references() > 0, "references (%d) are zero for %s (%s)", node.references(), key, node); require(node.references() > 0, "references (%d) are zero for %s (%s)", node.references(), key, node);
checkState(node.isUnqueued()); require(node.isUnqueued());
boolean evict = false; boolean evict = false;
if (safeRef.hasUpdate()) if (safeRef.hasUpdate())
@ -1174,7 +1174,7 @@ public class AccordCache implements CacheSize
@Override @Override
public Command load(AccordCommandStore commandStore, TxnId txnId) public Command load(AccordCommandStore commandStore, TxnId txnId)
{ {
Invariants.checkState(!txnId.is(Txn.Kind.EphemeralRead)); Invariants.require(!txnId.is(Txn.Kind.EphemeralRead));
return commandStore.loadCommand(txnId); return commandStore.loadCommand(txnId);
} }
@ -1208,7 +1208,7 @@ public class AccordCache implements CacheSize
public Object fullShrink(TxnId txnId, Command value) public Object fullShrink(TxnId txnId, Command value)
{ {
if (txnId.is(Txn.Kind.EphemeralRead)) if (txnId.is(Txn.Kind.EphemeralRead))
Invariants.checkState(value.saveStatus().compareTo(SaveStatus.ReadyToExecute) < 0); Invariants.require(value.saveStatus().compareTo(SaveStatus.ReadyToExecute) < 0);
try try
{ {

View File

@ -84,8 +84,8 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
LOADED.permittedFrom |= 1 << MODIFIED.ordinal(); LOADED.permittedFrom |= 1 << MODIFIED.ordinal();
for (Status status : VALUES) for (Status status : VALUES)
{ {
Invariants.checkState((status.ordinal() & IS_LOADED) != 0 == status.loaded); Invariants.require((status.ordinal() & IS_LOADED) != 0 == status.loaded);
Invariants.checkState(((status.ordinal() & IS_LOADED) != 0 && (status.ordinal() & IS_NESTED) != 0) == status.nested); Invariants.require(((status.ordinal() & IS_LOADED) != 0 && (status.ordinal() & IS_NESTED) != 0) == status.nested);
} }
} }
@ -168,7 +168,7 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
boolean isNested() boolean isNested()
{ {
Invariants.checkState(isLoaded()); Invariants.require(isLoaded());
return (status & IS_NESTED) != 0; return (status & IS_NESTED) != 0;
} }
@ -194,13 +194,13 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
int noEvictGeneration() int noEvictGeneration()
{ {
Invariants.checkState(isNoEvict()); Invariants.require(isNoEvict());
return (status >>> 8) & 0xffff; return (status >>> 8) & 0xffff;
} }
int noEvictMaxAge() int noEvictMaxAge()
{ {
Invariants.checkState(isNoEvict()); Invariants.require(isNoEvict());
return status >>> 24; return status >>> 24;
} }
@ -245,7 +245,7 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
private void setStatus(Status newStatus) private void setStatus(Status newStatus)
{ {
Invariants.checkState((newStatus.permittedFrom & (1 << (status & STATUS_MASK))) != 0, "%s not permitted from %s", newStatus, status()); Invariants.require((newStatus.permittedFrom & (1 << (status & STATUS_MASK))) != 0, "%s not permitted from %s", newStatus, status());
setStatusUnsafe(newStatus); setStatusUnsafe(newStatus);
} }
@ -257,22 +257,22 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
public void initialize(V value) public void initialize(V value)
{ {
Invariants.checkState(state == null); Invariants.require(state == null);
setStatus(LOADED); setStatus(LOADED);
state = value; state = value;
} }
public void readyToLoad() public void readyToLoad()
{ {
Invariants.checkState(state == null); Invariants.require(state == null);
setStatus(WAITING_TO_LOAD); setStatus(WAITING_TO_LOAD);
state = new WaitingToLoad(); state = new WaitingToLoad();
} }
public void markNoEvict(int generation, int maxAge) public void markNoEvict(int generation, int maxAge)
{ {
Invariants.checkState((maxAge & ~0xff) == 0); Invariants.require((maxAge & ~0xff) == 0);
Invariants.checkState((generation & ~0xffff) == 0); Invariants.require((generation & ~0xffff) == 0);
status |= NO_EVICT; status |= NO_EVICT;
status |= generation << 8; status |= generation << 8;
status |= maxAge << 24; status |= maxAge << 24;
@ -325,7 +325,7 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
public <P> Loading load(BiFunction<P, Runnable, Cancellable> loadExecutor, P param, Adapter<K, V, ?> adapter, OnLoaded onLoaded) public <P> Loading load(BiFunction<P, Runnable, Cancellable> loadExecutor, P param, Adapter<K, V, ?> adapter, OnLoaded onLoaded)
{ {
Invariants.checkState(is(WAITING_TO_LOAD), "%s", this); Invariants.require(is(WAITING_TO_LOAD), "%s", this);
Loading loading = ((WaitingToLoad)state).load(loadExecutor.apply(param, () -> { Loading loading = ((WaitingToLoad)state).load(loadExecutor.apply(param, () -> {
V result; V result;
try try
@ -346,7 +346,7 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
public Loading testLoad() public Loading testLoad()
{ {
Invariants.checkState(is(WAITING_TO_LOAD)); Invariants.require(is(WAITING_TO_LOAD));
Loading loading = ((WaitingToLoad)state).load(() -> {}); Loading loading = ((WaitingToLoad)state).load(() -> {});
setStatus(LOADING); setStatus(LOADING);
state = loading; state = loading;
@ -355,7 +355,7 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
public Loading loading() public Loading loading()
{ {
Invariants.checkState(is(LOADING), "%s", this); Invariants.require(is(LOADING), "%s", this);
return (Loading) state; return (Loading) state;
} }
@ -363,8 +363,8 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
// but this one is less obvious so named as to draw attention // but this one is less obvious so named as to draw attention
public V getExclusive() public V getExclusive()
{ {
Invariants.checkState(owner == null || owner.commandStore == null || owner.commandStore.executor().isOwningThread()); Invariants.require(owner == null || owner.commandStore == null || owner.commandStore.executor().isOwningThread());
Invariants.checkState(isLoaded(), "%s", this); Invariants.require(isLoaded(), "%s", this);
if (isShrunk()) if (isShrunk())
{ {
AccordCache.Type<K, V, ?> parent = owner.parent(); AccordCache.Type<K, V, ?> parent = owner.parent();
@ -500,7 +500,7 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
protected void saved() protected void saved()
{ {
Invariants.checkState(is(MODIFIED)); Invariants.require(is(MODIFIED));
setStatus(LOADED); setStatus(LOADED);
} }
@ -525,7 +525,7 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
private boolean tryShrink(K key, Adapter<K, V, ?> adapter) private boolean tryShrink(K key, Adapter<K, V, ?> adapter)
{ {
Invariants.checkState(!isNested()); Invariants.require(!isNested());
if (isShrunk() || state == null) if (isShrunk() || state == null)
return false; return false;
@ -540,7 +540,7 @@ public class AccordCacheEntry<K, V> extends IntrusiveLinkedListNode
private void inflate(AccordCommandStore commandStore, K key, Adapter<K, V, ?> adapter) private void inflate(AccordCommandStore commandStore, K key, Adapter<K, V, ?> adapter)
{ {
Invariants.checkState(isShrunk()); Invariants.require(isShrunk());
if (isNested()) if (isNested())
{ {
Nested nested = (Nested) state; Nested nested = (Nested) state;

View File

@ -75,7 +75,7 @@ import static accord.local.KeyHistory.SYNC;
import static accord.primitives.Status.Committed; import static accord.primitives.Status.Committed;
import static accord.primitives.Status.PreCommitted; import static accord.primitives.Status.PreCommitted;
import static accord.primitives.Status.Truncated; import static accord.primitives.Status.Truncated;
import static accord.utils.Invariants.checkState; import static accord.utils.Invariants.require;
public class AccordCommandStore extends CommandStore public class AccordCommandStore extends CommandStore
{ {
@ -247,7 +247,7 @@ public class AccordCommandStore extends CommandStore
public Caches cachesExclusive() public Caches cachesExclusive()
{ {
Invariants.checkState(executor.isOwningThread()); Invariants.require(executor.isOwningThread());
return caches; return caches;
} }
@ -360,14 +360,14 @@ public class AccordCommandStore extends CommandStore
public AccordSafeCommandStore begin(AccordTask<?> operation, public AccordSafeCommandStore begin(AccordTask<?> operation,
@Nullable CommandsForRanges commandsForRanges) @Nullable CommandsForRanges commandsForRanges)
{ {
checkState(current == null); require(current == null);
current = AccordSafeCommandStore.create(operation, commandsForRanges, this); current = AccordSafeCommandStore.create(operation, commandsForRanges, this);
return current; return current;
} }
void setOwner(Thread thread, Thread self) void setOwner(Thread thread, Thread self)
{ {
Invariants.checkState(thread == null ? currentThread == self : currentThread == null); Invariants.require(thread == null ? currentThread == self : currentThread == null);
currentThread = thread; currentThread = thread;
if (thread != null) CommandStore.register(this); if (thread != null) CommandStore.register(this);
@ -380,7 +380,7 @@ public class AccordCommandStore extends CommandStore
public void complete(AccordSafeCommandStore store) public void complete(AccordSafeCommandStore store)
{ {
checkState(current == store); require(current == store);
current.postExecute(); current.postExecute();
current = null; current = null;
} }
@ -388,7 +388,7 @@ public class AccordCommandStore extends CommandStore
public void abort(AccordSafeCommandStore store) public void abort(AccordSafeCommandStore store)
{ {
checkInStore(); checkInStore();
Invariants.checkState(store == current); Invariants.require(store == current);
current = null; current = null;
} }

View File

@ -243,7 +243,7 @@ public class AccordConfigurationService extends AbstractConfigurationService<Acc
*/ */
public synchronized void start() public synchronized void start()
{ {
Invariants.checkState(state == State.INITIALIZED, "Expected state to be INITIALIZED but was %s", state); Invariants.require(state == State.INITIALIZED, "Expected state to be INITIALIZED but was %s", state);
state = State.LOADING; state = State.LOADING;
EndpointMapping snapshot = mapping; EndpointMapping snapshot = mapping;
@ -557,7 +557,7 @@ public class AccordConfigurationService extends AbstractConfigurationService<Acc
private synchronized void checkStarted() private synchronized void checkStarted()
{ {
State state = this.state; State state = this.state;
Invariants.checkState(state == State.STARTED, "Expected state to be STARTED but was %s", state); Invariants.require(state == State.STARTED, "Expected state to be STARTED but was %s", state);
} }
@VisibleForTesting @VisibleForTesting

View File

@ -51,7 +51,7 @@ import org.apache.cassandra.tcm.ClusterMetadata;
import org.apache.cassandra.utils.concurrent.Future; import org.apache.cassandra.utils.concurrent.Future;
import org.apache.cassandra.utils.concurrent.FutureCombiner; import org.apache.cassandra.utils.concurrent.FutureCombiner;
import static accord.utils.Invariants.checkState; import static accord.utils.Invariants.require;
import static org.apache.cassandra.db.ColumnFamilyStore.FlushReason.ACCORD_TXN_GC; import static org.apache.cassandra.db.ColumnFamilyStore.FlushReason.ACCORD_TXN_GC;
public class AccordDataStore implements DataStore public class AccordDataStore implements DataStore
@ -142,7 +142,7 @@ public class AccordDataStore implements DataStore
if (firstToken != null) if (firstToken != null)
{ {
checkState(lastToken != null); require(lastToken != null);
if (firstToken.equals(lastToken)) if (firstToken.equals(lastToken))
{ {
for (org.apache.cassandra.dht.Range<Token> tableRange : tableRanges) for (org.apache.cassandra.dht.Range<Token> tableRange : tableRanges)
@ -156,7 +156,7 @@ public class AccordDataStore implements DataStore
} }
else else
{ {
checkState(firstToken.compareTo(lastToken) < 0); require(firstToken.compareTo(lastToken) < 0);
org.apache.cassandra.dht.Range<Token> memtableRange = new org.apache.cassandra.dht.Range<>(firstToken, lastToken); org.apache.cassandra.dht.Range<Token> memtableRange = new org.apache.cassandra.dht.Range<>(firstToken, lastToken);
for (org.apache.cassandra.dht.Range<Token> tableRange : tableRanges) for (org.apache.cassandra.dht.Range<Token> tableRange : tableRanges)
{ {

View File

@ -178,7 +178,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
public AccordCache cacheExclusive() public AccordCache cacheExclusive()
{ {
Invariants.checkState(isOwningThread()); Invariants.require(isOwningThread());
return cache; return cache;
} }
@ -270,7 +270,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
continue outer; continue outer;
} }
Invariants.checkState(load != null); Invariants.require(load != null);
AccordCacheEntry.OnLoaded onLoaded = this; AccordCacheEntry.OnLoaded onLoaded = this;
++activeLoads; ++activeLoads;
if (isForRange) if (isForRange)
@ -286,15 +286,15 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
updateQueue(task); updateQueue(task);
} }
Object prev = next.pollWaitingToLoad(); Object prev = next.pollWaitingToLoad();
Invariants.checkState(prev == load); Invariants.require(prev == load);
if (next.peekWaitingToLoad() == null) if (next.peekWaitingToLoad() == null)
break; break;
Invariants.checkState(next.state() == WAITING_TO_LOAD, "Invalid state: %s", next); Invariants.require(next.state() == WAITING_TO_LOAD, "Invalid state: %s", next);
if (activeLoads >= maxQueuedLoads) if (activeLoads >= maxQueuedLoads)
return; return;
} }
Invariants.checkState(next.state().compareTo(LOADING) >= 0, "Invalid state: %s", next); Invariants.require(next.state().compareTo(LOADING) >= 0, "Invalid state: %s", next);
updateQueue(next); updateQueue(next);
} }
} }
@ -377,7 +377,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
private Cancellable submitIOExclusive(Task parent, Runnable run) private Cancellable submitIOExclusive(Task parent, Runnable run)
{ {
Invariants.checkState(isOwningThread()); Invariants.require(isOwningThread());
++tasks; ++tasks;
PlainRunnable task = new PlainRunnable(null, run, null); PlainRunnable task = new PlainRunnable(null, run, null);
// TODO (expected): adopt queue position of the submitting task // TODO (expected): adopt queue position of the submitting task
@ -409,7 +409,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
public <R> void cancel(AccordTask<R> task) public <R> void cancel(AccordTask<R> task)
{ {
Invariants.checkState(task.commandStore.executor() == this, Invariants.require(task.commandStore.executor() == this,
"%s is a wrong command store for %s, should be %s", "%s is a wrong command store for %s, should be %s",
this, task, task); this, task, task);
submit(AccordExecutor::cancelExclusive, CancelAsync::new, task); submit(AccordExecutor::cancelExclusive, CancelAsync::new, task);
@ -575,7 +575,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
{ {
if (task.onLoad(loaded)) if (task.onLoad(loaded))
{ {
Invariants.checkState(task.queued() == loading); Invariants.require(task.queued() == loading);
task.unqueue(); task.unqueue();
waitingToRun(task); waitingToRun(task);
} }
@ -627,14 +627,14 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
@Override @Override
public void setCapacity(long bytes) public void setCapacity(long bytes)
{ {
Invariants.checkState(isOwningThread()); Invariants.require(isOwningThread());
cache.setCapacity(bytes); cache.setCapacity(bytes);
maxWorkingCapacityInBytes = cache.capacity() + maxWorkingSetSizeInBytes; maxWorkingCapacityInBytes = cache.capacity() + maxWorkingSetSizeInBytes;
} }
public void setWorkingSetSize(long bytes) public void setWorkingSetSize(long bytes)
{ {
Invariants.checkState(isOwningThread()); Invariants.require(isOwningThread());
maxWorkingSetSizeInBytes = bytes; maxWorkingSetSizeInBytes = bytes;
maxWorkingCapacityInBytes = cache.capacity() + maxWorkingSetSizeInBytes; maxWorkingCapacityInBytes = cache.capacity() + maxWorkingSetSizeInBytes;
if (maxWorkingCapacityInBytes < maxWorkingSetSizeInBytes) if (maxWorkingCapacityInBytes < maxWorkingSetSizeInBytes)
@ -643,7 +643,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
public void setMaxQueuedLoads(int total, int range) public void setMaxQueuedLoads(int total, int range)
{ {
Invariants.checkState(isOwningThread()); Invariants.require(isOwningThread());
maxQueuedLoads = total; maxQueuedLoads = total;
maxQueuedRangeLoads = range; maxQueuedRangeLoads = range;
} }
@ -729,7 +729,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
@Override @Override
protected void preRunExclusive() protected void preRunExclusive()
{ {
Invariants.checkState(task != null); Invariants.require(task != null);
Thread self = Thread.currentThread(); Thread self = Thread.currentThread();
commandStore.setOwner(self, self); commandStore.setOwner(self, self);
task.preRunExclusive(); task.preRunExclusive();
@ -795,7 +795,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
@Override @Override
public void append(Task task) public void append(Task task)
{ {
Invariants.checkState(!next.isSet()); Invariants.require(!next.isSet());
// TODO (expected): if the new task is higher priority, replace next // TODO (expected): if the new task is higher priority, replace next
next.setNext(task); next.setNext(task);
waitingToRun.append(next); waitingToRun.append(next);
@ -866,9 +866,9 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
public void remove(T remove) public void remove(T remove)
{ {
Invariants.checkState(super.contains(remove)); Invariants.require(super.contains(remove));
super.remove(remove); super.remove(remove);
Invariants.checkState(!super.contains(remove)); Invariants.require(!super.contains(remove));
} }
public boolean contains(T contains) public boolean contains(T contains)
@ -1074,7 +1074,7 @@ public abstract class AccordExecutor implements CacheSize, AccordCacheEntry.OnLo
@Override @Override
protected void addToQueue(TaskQueue queue) protected void addToQueue(TaskQueue queue)
{ {
Invariants.checkState(queue.kind == WAITING_TO_RUN); Invariants.require(queue.kind == WAITING_TO_RUN);
queue.append(this); queue.append(this);
} }

View File

@ -43,7 +43,7 @@ class AccordExecutorInfiniteLoops implements Shutdownable
public AccordExecutorInfiniteLoops(Mode mode, int threads, IntFunction<String> name, Function<Mode, Interruptible.Task> tasks) public AccordExecutorInfiniteLoops(Mode mode, int threads, IntFunction<String> name, Function<Mode, Interruptible.Task> tasks)
{ {
Invariants.checkState(mode == RUN_WITH_LOCK ? threads == 1 : threads >= 1); Invariants.require(mode == RUN_WITH_LOCK ? threads == 1 : threads >= 1);
final LongHashSet threadIds = new LongHashSet(threads, 0.5f); final LongHashSet threadIds = new LongHashSet(threads, 0.5f);
this.loops = new Interruptible[threads]; this.loops = new Interruptible[threads];
for (int i = 0; i < threads; ++i) for (int i = 0; i < threads; ++i)

View File

@ -67,7 +67,7 @@ class AccordExecutorSimple extends AccordExecutor
public AccordExecutorSimple(ReentrantLock lock, int executorId, Mode mode, int threads, IntFunction<String> name, AccordCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent) public AccordExecutorSimple(ReentrantLock lock, int executorId, Mode mode, int threads, IntFunction<String> name, AccordCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
{ {
super(lock, executorId, metrics, loadExecutor, saveExecutor, rangeLoadExecutor, agent); super(lock, executorId, metrics, loadExecutor, saveExecutor, rangeLoadExecutor, agent);
Invariants.checkArgument(threads == 1); Invariants.requireArgument(threads == 1);
this.lock = lock; this.lock = lock;
this.executor = executorFactory().sequential(name.apply(0)); this.executor = executorFactory().sequential(name.apply(0));

View File

@ -117,7 +117,7 @@ public abstract class AccordFastPathCoordinator implements ChangeListener, Confi
public PeerStatus onUpdate(Node.Id node, Status status) public PeerStatus onUpdate(Node.Id node, Status status)
{ {
Invariants.checkArgument(contains(node)); Invariants.requireArgument(contains(node));
PeerStatus peerStatus = new PeerStatus(node, status); PeerStatus peerStatus = new PeerStatus(node, status);
statusMap.put(node, peerStatus); statusMap.put(node, peerStatus);
return peerStatus; return peerStatus;

View File

@ -155,7 +155,7 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
if (that.streams.keySet().stream().anyMatch(this.streams::containsKey)) if (that.streams.keySet().stream().anyMatch(this.streams::containsKey))
throw new IllegalStateException(String.format("Unable to merge: key found in multiple StreamData %s %s", throw new IllegalStateException(String.format("Unable to merge: key found in multiple StreamData %s %s",
this.streams.keySet(), that.streams.keySet())); this.streams.keySet(), that.streams.keySet()));
Invariants.checkState(!that.streams.keySet().stream().anyMatch(this.streams::containsKey)); Invariants.require(!that.streams.keySet().stream().anyMatch(this.streams::containsKey));
ImmutableMap.Builder<TokenRange, SessionInfo> builder = ImmutableMap.builder(); ImmutableMap.Builder<TokenRange, SessionInfo> builder = ImmutableMap.builder();
builder.putAll(this.streams); builder.putAll(this.streams);
builder.putAll(that.streams); builder.putAll(that.streams);
@ -180,8 +180,8 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
{ {
Invariants.nonNull(range); Invariants.nonNull(range);
Invariants.nonNull(from); Invariants.nonNull(from);
Invariants.checkState(this.range == null, "range was not null: %s", this.range); Invariants.require(this.range == null, "range was not null: %s", this.range);
Invariants.checkState(this.from == null, "from was not null: %s", this.from); Invariants.require(this.from == null, "from was not null: %s", this.from);
this.range = range; this.range = range;
this.from = from; this.from = from;
maybeListen(); maybeListen();
@ -190,7 +190,7 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
private void futureReceived(StreamResultFuture future) private void futureReceived(StreamResultFuture future)
{ {
Invariants.nonNull(future); Invariants.nonNull(future);
Invariants.checkState(this.future == null, "future was not null: %s", this.future); Invariants.require(this.future == null, "future was not null: %s", this.future);
this.future = future; this.future = future;
maybeListen(); maybeListen();
} }
@ -254,7 +254,7 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
if (!session.peer.equals(to)) if (!session.peer.equals(to))
continue; continue;
Invariants.checkState(session.getNumRequests() == 0, "Requested to send data: %s", session); Invariants.require(session.getNumRequests() == 0, "Requested to send data: %s", session);
if (session.getNumTransfers() > 0) if (session.getNumTransfers() > 0)
return true; return true;
} }
@ -266,14 +266,14 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
{ {
try try
{ {
Invariants.checkArgument(key.domain() == Routable.Domain.Range, "Required Range but saw %s: %s", key.domain(), key); Invariants.requireArgument(key.domain() == Routable.Domain.Range, "Required Range but saw %s: %s", key.domain(), key);
TokenRange range = (TokenRange) key; TokenRange range = (TokenRange) key;
// TODO (required): check epoch // TODO (required): check epoch
// TODO (required): handle dropped tables // TODO (required): handle dropped tables
TableId tableId = range.table(); TableId tableId = range.table();
TableMetadata table = ClusterMetadata.current().schema.getKeyspaces().getTableOrViewNullable(tableId); TableMetadata table = ClusterMetadata.current().schema.getKeyspaces().getTableOrViewNullable(tableId);
Invariants.checkState(table != null, "Table with id %s not found", tableId); Invariants.require(table != null, "Table with id %s not found", tableId);
// TODO (required): may also be relocation // TODO (required): may also be relocation
StreamPlan plan = new StreamPlan(StreamOperation.BOOTSTRAP, 1, false, StreamPlan plan = new StreamPlan(StreamOperation.BOOTSTRAP, 1, false,
@ -310,7 +310,7 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
@Override @Override
public void serialize(Query t, DataOutputPlus out, int version) public void serialize(Query t, DataOutputPlus out, int version)
{ {
Invariants.checkArgument(t == noopQuery); Invariants.requireArgument(t == noopQuery);
} }
@Override @Override
@ -322,7 +322,7 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
@Override @Override
public long serializedSize(Query t, int version) public long serializedSize(Query t, int version)
{ {
Invariants.checkArgument(t == noopQuery); Invariants.requireArgument(t == noopQuery);
return 0; return 0;
} }
}; };
@ -332,7 +332,7 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
@Override @Override
public void serialize(Update t, DataOutputPlus out, int version) public void serialize(Update t, DataOutputPlus out, int version)
{ {
Invariants.checkArgument(t == null); Invariants.requireArgument(t == null);
} }
@Override @Override
@ -344,7 +344,7 @@ public class AccordFetchCoordinator extends AbstractFetchCoordinator implements
@Override @Override
public long serializedSize(Update t, int version) public long serializedSize(Update t, int version)
{ {
Invariants.checkArgument(t == null); Invariants.requireArgument(t == null);
return 0; return 0;
} }
}; };

View File

@ -98,7 +98,7 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
static static
{ {
// make noise early if we forget to update our version mappings // make noise early if we forget to update our version mappings
Invariants.checkState(MessagingService.current_version == MessagingService.VERSION_51, "Expected current version to be %d but given %d", MessagingService.VERSION_51, MessagingService.current_version); Invariants.require(MessagingService.current_version == MessagingService.VERSION_51, "Expected current version to be %d but given %d", MessagingService.VERSION_51, MessagingService.current_version);
} }
static final ThreadLocal<byte[]> keyCRCBytes = ThreadLocal.withInitial(() -> new byte[JournalKeySupport.TOTAL_SIZE]); static final ThreadLocal<byte[]> keyCRCBytes = ThreadLocal.withInitial(() -> new byte[JournalKeySupport.TOTAL_SIZE]);
@ -162,7 +162,7 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
public AccordJournal start(Node node) public AccordJournal start(Node node)
{ {
Invariants.checkState(status == Status.INITIALIZED); Invariants.require(status == Status.INITIALIZED);
this.node = node; this.node = node;
status = Status.STARTING; status = Status.STARTING;
journal.start(); journal.start();
@ -193,7 +193,7 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
@Override @Override
public void shutdown() public void shutdown()
{ {
Invariants.checkState(status == Status.REPLAY || status == Status.STARTED, "%s", status); Invariants.require(status == Status.REPLAY || status == Status.STARTED, "%s", status);
status = Status.TERMINATING; status = Status.TERMINATING;
journal.shutdown(); journal.shutdown();
status = Status.TERMINATED; status = Status.TERMINATED;
@ -251,7 +251,7 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
case ERASE: case ERASE:
return null; return null;
} }
Invariants.checkState(builder.saveStatus() != null, "No saveSatus loaded, but next was called and cleanup was not: %s", builder); Invariants.require(builder.saveStatus() != null, "No saveSatus loaded, but next was called and cleanup was not: %s", builder);
return builder.asMinimal(); return builder.asMinimal();
} }
@ -411,7 +411,7 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
builder.forceResult(orig.result()); builder.forceResult(orig.result());
// We can only use strict equality if we supply result. // We can only use strict equality if we supply result.
Command reconstructed = builder.construct(redundantBefore); Command reconstructed = builder.construct(redundantBefore);
Invariants.checkState(orig.equals(reconstructed), Invariants.require(orig.equals(reconstructed),
'\n' + '\n' +
"Original: %s\n" + "Original: %s\n" +
"Reconstructed: %s\n" + "Reconstructed: %s\n" +
@ -460,7 +460,7 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
JournalKey finalKey = key; JournalKey finalKey = key;
iter.readAllForKey(key, (segment, position, local, buffer, userVersion) -> { iter.readAllForKey(key, (segment, position, local, buffer, userVersion) -> {
Invariants.checkState(finalKey.equals(local)); Invariants.require(finalKey.equals(local));
try (DataInputBuffer in = new DataInputBuffer(buffer, false)) try (DataInputBuffer in = new DataInputBuffer(buffer, false))
{ {
builder.deserializeNext(in, userVersion); builder.deserializeNext(in, userVersion);
@ -481,7 +481,7 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
{ {
CommandStore commandStore = commandStores.forId(key.commandStoreId); CommandStore commandStore = commandStores.forId(key.commandStoreId);
Command command = builder.construct(commandStore.unsafeGetRedundantBefore()); Command command = builder.construct(commandStore.unsafeGetRedundantBefore());
Invariants.checkState(command.saveStatus() != SaveStatus.Uninitialised, Invariants.require(command.saveStatus() != SaveStatus.Uninitialised,
"Found uninitialized command in the log: %s %s", command.toString(), builder.toString()); "Found uninitialized command in the log: %s %s", command.toString(), builder.toString());
Loader loader = commandStore.loader(); Loader loader = commandStore.loader();
async(loader::load, command).get(); async(loader::load, command).get();
@ -572,7 +572,7 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
private static void serialize(Command command, int flags, DataOutputPlus out, int userVersion) throws IOException private static void serialize(Command command, int flags, DataOutputPlus out, int userVersion) throws IOException
{ {
Invariants.checkState(flags != 0); Invariants.require(flags != 0);
out.writeInt(flags); out.writeInt(flags);
int iterable = toIterableSetFields(flags); int iterable = toIterableSetFields(flags);
@ -679,8 +679,8 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
public void serialize(DataOutputPlus out, RedundantBefore redundantBefore, int userVersion) throws IOException public void serialize(DataOutputPlus out, RedundantBefore redundantBefore, int userVersion) throws IOException
{ {
Invariants.checkState(mask == 0); Invariants.require(mask == 0);
Invariants.checkState(flags != 0); Invariants.require(flags != 0);
int flags = validateFlags(this.flags); int flags = validateFlags(this.flags);
Writer.serialize(construct(redundantBefore), flags, out, userVersion); Writer.serialize(construct(redundantBefore), flags, out, userVersion);
@ -688,9 +688,9 @@ public class AccordJournal implements accord.api.Journal, RangeSearcher.Supplier
public void deserializeNext(DataInputPlus in, int userVersion) throws IOException public void deserializeNext(DataInputPlus in, int userVersion) throws IOException
{ {
Invariants.checkState(txnId != null); Invariants.require(txnId != null);
int flags = in.readInt(); int flags = in.readInt();
Invariants.checkState(flags != 0); Invariants.require(flags != 0);
nextCalled = true; nextCalled = true;
count++; count++;

View File

@ -325,7 +325,7 @@ public class AccordJournalTable<K extends JournalKey, V> implements RangeSearche
{ {
UnfilteredRowIterator next = partitionIterator.next(); UnfilteredRowIterator next = partitionIterator.next();
JournalKey partitionKeyComponents = AccordKeyspace.JournalColumns.getJournalKey(next.partitionKey()); JournalKey partitionKeyComponents = AccordKeyspace.JournalColumns.getJournalKey(next.partitionKey());
Invariants.checkState(partitionKeyComponents.commandStoreId == storeId, Invariants.require(partitionKeyComponents.commandStoreId == storeId,
() -> String.format("table index returned a command store other than the exepcted one; expected %d != %d", storeId, partitionKeyComponents.commandStoreId)); () -> String.format("table index returned a command store other than the exepcted one; expected %d != %d", storeId, partitionKeyComponents.commandStoreId));
return partitionKeyComponents.id; return partitionKeyComponents.id;
} }
@ -372,7 +372,7 @@ public class AccordJournalTable<K extends JournalKey, V> implements RangeSearche
private void readRow(K key, Unfiltered unfiltered, EntryHolder<K> into, RecordConsumer<K> onEntry) private void readRow(K key, Unfiltered unfiltered, EntryHolder<K> into, RecordConsumer<K> onEntry)
{ {
Invariants.checkState(unfiltered.isRow()); Invariants.require(unfiltered.isRow());
Row row = (Row) unfiltered; Row row = (Row) unfiltered;
long descriptor = LongType.instance.compose(ByteBuffer.wrap((byte[]) row.clustering().get(0))); long descriptor = LongType.instance.compose(ByteBuffer.wrap((byte[]) row.clustering().get(0)));

View File

@ -335,7 +335,7 @@ public class AccordJournalValueSerializers
epochs[i] = in.readLong(); epochs[i] = in.readLong();
ranges[i] = KeySerializers.ranges.deserialize(in, messagingVersion); ranges[i] = KeySerializers.ranges.deserialize(in, messagingVersion);
} }
Invariants.checkState(ranges.length == epochs.length); Invariants.require(ranges.length == epochs.length);
into.update(new RangesForEpoch(epochs, ranges)); into.update(new RangesForEpoch(epochs, ranges));
} }
} }
@ -354,7 +354,7 @@ public class AccordJournalValueSerializers
protected NavigableMap<K, V> accumulate(NavigableMap<K, V> accumulator, V newValue) protected NavigableMap<K, V> accumulate(NavigableMap<K, V> accumulator, V newValue)
{ {
V prev = accumulator.put(getKey.apply(newValue), newValue); V prev = accumulator.put(getKey.apply(newValue), newValue);
Invariants.checkState(prev == null || prev.equals(newValue)); Invariants.require(prev == null || prev.equals(newValue));
return accumulator; return accumulator;
} }
} }

View File

@ -131,7 +131,7 @@ import org.apache.cassandra.utils.CloseableIterator;
import org.apache.cassandra.utils.btree.BTreeSet; import org.apache.cassandra.utils.btree.BTreeSet;
import org.apache.cassandra.utils.concurrent.OpOrder; import org.apache.cassandra.utils.concurrent.OpOrder;
import static accord.utils.Invariants.checkState; import static accord.utils.Invariants.require;
import static java.lang.String.format; import static java.lang.String.format;
import static java.util.Collections.emptyMap; import static java.util.Collections.emptyMap;
import static org.apache.cassandra.cql3.QueryProcessor.executeInternal; import static org.apache.cassandra.cql3.QueryProcessor.executeInternal;
@ -327,7 +327,7 @@ public class AccordKeyspace
// TODO (expected): garbage-free filtering, reusing encoding // TODO (expected): garbage-free filtering, reusing encoding
public Row withoutRedundantCommands(TokenKey key, Row row, RedundantBefore.Entry redundantBefore) public Row withoutRedundantCommands(TokenKey key, Row row, RedundantBefore.Entry redundantBefore)
{ {
Invariants.checkState(row.columnCount() == 1); Invariants.require(row.columnCount() == 1);
Cell<?> cell = row.getCell(data); Cell<?> cell = row.getCell(data);
if (cell == null) if (cell == null)
return row; return row;
@ -688,7 +688,7 @@ public class AccordKeyspace
try (RowIterator partition = partitions.next()) try (RowIterator partition = partitions.next())
{ {
Invariants.checkState(partition.hasNext()); Invariants.require(partition.hasNext());
Row row = partition.next(); Row row = partition.next();
ByteBuffer data = cellValue(row, accessor.data); ByteBuffer data = cellValue(row, accessor.data);
return Serialize.fromBytes(key, data); return Serialize.fromBytes(key, data);
@ -714,8 +714,8 @@ public class AccordKeyspace
private EpochDiskState(long minEpoch, long maxEpoch) private EpochDiskState(long minEpoch, long maxEpoch)
{ {
Invariants.checkArgument(minEpoch >= 0, "Min Epoch %d < 0", minEpoch); Invariants.requireArgument(minEpoch >= 0, "Min Epoch %d < 0", minEpoch);
Invariants.checkArgument(maxEpoch >= minEpoch, "Max epoch %d < min %d", maxEpoch, minEpoch); Invariants.requireArgument(maxEpoch >= minEpoch, "Max epoch %d < min %d", maxEpoch, minEpoch);
this.minEpoch = minEpoch; this.minEpoch = minEpoch;
this.maxEpoch = maxEpoch; this.maxEpoch = maxEpoch;
} }
@ -740,14 +740,14 @@ public class AccordKeyspace
@VisibleForTesting @VisibleForTesting
EpochDiskState withNewMaxEpoch(long epoch) EpochDiskState withNewMaxEpoch(long epoch)
{ {
Invariants.checkArgument(epoch > maxEpoch, "Epoch %d <= %d (max)", epoch, maxEpoch); Invariants.requireArgument(epoch > maxEpoch, "Epoch %d <= %d (max)", epoch, maxEpoch);
return EpochDiskState.create(Math.max(1, minEpoch), epoch); return EpochDiskState.create(Math.max(1, minEpoch), epoch);
} }
private EpochDiskState withNewMinEpoch(long epoch) private EpochDiskState withNewMinEpoch(long epoch)
{ {
Invariants.checkArgument(epoch > minEpoch, "epoch %d <= %d (min)", epoch, minEpoch); Invariants.requireArgument(epoch > minEpoch, "epoch %d <= %d (min)", epoch, minEpoch);
Invariants.checkArgument(epoch <= maxEpoch, "epoch %d > %d (max)", epoch, maxEpoch); Invariants.requireArgument(epoch <= maxEpoch, "epoch %d > %d (max)", epoch, maxEpoch);
return EpochDiskState.create(epoch, maxEpoch); return EpochDiskState.create(epoch, maxEpoch);
} }
@ -792,7 +792,7 @@ public class AccordKeyspace
CommandSerializers.txnId.serialize(key.id, id); CommandSerializers.txnId.serialize(key.id, id);
id.flip(); id.flip();
ByteBuffer pk = keyComparator.make(key.commandStoreId, (byte)key.type.id, id).serializeAsPartitionKey(); ByteBuffer pk = keyComparator.make(key.commandStoreId, (byte)key.type.id, id).serializeAsPartitionKey();
Invariants.checkState(getTxnId(splitPartitionKey(pk)).equals(key.id)); Invariants.require(getTxnId(splitPartitionKey(pk)).equals(key.id));
return Journal.partitioner.decorateKey(pk); return Journal.partitioner.decorateKey(pk);
} }
@ -871,7 +871,7 @@ public class AccordKeyspace
{ {
if (diskState.isEmpty()) if (diskState.isEmpty())
return saveEpochDiskState(EpochDiskState.create(epoch)); return saveEpochDiskState(EpochDiskState.create(epoch));
Invariants.checkArgument(epoch >= diskState.minEpoch, "Epoch %d < %d (min)", epoch, diskState.minEpoch); Invariants.requireArgument(epoch >= diskState.minEpoch, "Epoch %d < %d (min)", epoch, diskState.minEpoch);
if (epoch > diskState.maxEpoch) if (epoch > diskState.maxEpoch)
{ {
diskState = diskState.withNewMaxEpoch(epoch); diskState = diskState.withNewMaxEpoch(epoch);
@ -900,20 +900,16 @@ public class AccordKeyspace
diskState = maybeUpdateMaxEpoch(diskState, epoch); diskState = maybeUpdateMaxEpoch(diskState, epoch);
String cql = "UPDATE " + ACCORD_KEYSPACE_NAME + '.' + TOPOLOGIES + ' ' + String cql = "UPDATE " + ACCORD_KEYSPACE_NAME + '.' + TOPOLOGIES + ' ' +
"SET closed = closed + ? WHERE epoch = ?"; "SET closed = closed + ? WHERE epoch = ?";
executeInternal(cql, executeInternal(cql, KeySerializers.rangesToBlobMap(ranges), epoch);
KeySerializers.rangesToBlobMap(ranges), epoch);
return diskState; return diskState;
} }
// TODO (required): unused
public static EpochDiskState markRetired(Ranges ranges, long epoch, EpochDiskState diskState) public static EpochDiskState markRetired(Ranges ranges, long epoch, EpochDiskState diskState)
{ {
diskState = maybeUpdateMaxEpoch(diskState, epoch); diskState = maybeUpdateMaxEpoch(diskState, epoch);
String cql = "UPDATE " + ACCORD_KEYSPACE_NAME + '.' + TOPOLOGIES + ' ' + String cql = "UPDATE " + ACCORD_KEYSPACE_NAME + '.' + TOPOLOGIES + ' ' +
"SET retired = retired + ? WHERE epoch = ?"; "SET retired = retired + ? WHERE epoch = ?";
executeInternal(cql, executeInternal(cql, KeySerializers.rangesToBlobMap(ranges), epoch);
KeySerializers.rangesToBlobMap(ranges), epoch);
flush(Topologies);
return diskState; return diskState;
} }
@ -979,7 +975,7 @@ public class AccordKeyspace
consumer.load(epoch, SyncStatus.NOT_STARTED, Collections.emptySet(), Collections.emptySet(), Ranges.EMPTY, Ranges.EMPTY); consumer.load(epoch, SyncStatus.NOT_STARTED, Collections.emptySet(), Collections.emptySet(), Ranges.EMPTY, Ranges.EMPTY);
return; return;
} }
checkState(!result.isEmpty(), "Nothing found for epoch %d", epoch); require(!result.isEmpty(), "Nothing found for epoch %d", epoch);
UntypedResultSet.Row row = result.one(); UntypedResultSet.Row row = result.one();
SyncStatus syncStatus = row.has("sync_state") SyncStatus syncStatus = row.has("sync_state")

View File

@ -59,7 +59,7 @@ public class AccordSegmentCompactor<V> implements SegmentCompactor<JournalKey, V
@Override @Override
public Collection<StaticSegment<JournalKey, V>> compact(Collection<StaticSegment<JournalKey, V>> segments) public Collection<StaticSegment<JournalKey, V>> compact(Collection<StaticSegment<JournalKey, V>> segments)
{ {
Invariants.checkState(segments.size() >= 2, () -> String.format("Can only compact 2 or more segments, but got %d", segments.size())); Invariants.require(segments.size() >= 2, () -> String.format("Can only compact 2 or more segments, but got %d", segments.size()));
logger.info("Compacting {} static segments: {}", segments.size(), segments); logger.info("Compacting {} static segments: {}", segments.size(), segments);
PriorityQueue<KeyOrderReader<JournalKey>> readers = new PriorityQueue<>(); PriorityQueue<KeyOrderReader<JournalKey>> readers = new PriorityQueue<>();
@ -110,9 +110,9 @@ public class AccordSegmentCompactor<V> implements SegmentCompactor<JournalKey, V
{ {
if (lastDescriptor != -1) if (lastDescriptor != -1)
{ {
Invariants.checkState(reader.descriptor.timestamp <= lastDescriptor, Invariants.require(reader.descriptor.timestamp <= lastDescriptor,
"Descriptors were accessed out of order: %d was accessed after %d", reader.descriptor.timestamp, lastDescriptor); "Descriptors were accessed out of order: %d was accessed after %d", reader.descriptor.timestamp, lastDescriptor);
Invariants.checkState(reader.descriptor.timestamp != lastDescriptor || Invariants.require(reader.descriptor.timestamp != lastDescriptor ||
reader.offset() < lastOffset, reader.offset() < lastOffset,
"Offsets were accessed out of order: %d was accessed after %s", reader.offset(), lastOffset); "Offsets were accessed out of order: %d was accessed after %s", reader.offset(), lastOffset);
} }
@ -156,7 +156,7 @@ public class AccordSegmentCompactor<V> implements SegmentCompactor<JournalKey, V
if (prevKey != null) if (prevKey != null)
{ {
Invariants.checkArgument((decoratedKey.compareTo(prevDecoratedKey) >= 0 ? 1 : -1) == (JournalKey.SUPPORT.compare(key, prevKey) >= 0 ? 1 : -1), Invariants.requireArgument((decoratedKey.compareTo(prevDecoratedKey) >= 0 ? 1 : -1) == (JournalKey.SUPPORT.compare(key, prevKey) >= 0 ? 1 : -1),
String.format("Partition key and JournalKey didn't have matching order, which may imply a serialization issue.\n%s (%s)\n%s (%s)", String.format("Partition key and JournalKey didn't have matching order, which may imply a serialization issue.\n%s (%s)\n%s (%s)",
key, decoratedKey, prevKey, prevDecoratedKey)); key, decoratedKey, prevKey, prevDecoratedKey));
} }

View File

@ -177,7 +177,7 @@ import org.apache.cassandra.utils.concurrent.UncheckedInterruptedException;
import static accord.messages.SimpleReply.Ok; import static accord.messages.SimpleReply.Ok;
import static accord.primitives.Routable.Domain.Key; import static accord.primitives.Routable.Domain.Key;
import static accord.primitives.Routable.Domain.Range; import static accord.primitives.Routable.Domain.Range;
import static accord.utils.Invariants.checkState; import static accord.utils.Invariants.require;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
@ -310,7 +310,7 @@ public class AccordService implements IAccordService, Shutdownable
if (!DatabaseDescriptor.getAccordTransactionsEnabled()) if (!DatabaseDescriptor.getAccordTransactionsEnabled())
return NOOP_SERVICE; return NOOP_SERVICE;
IAccordService i = instance; IAccordService i = instance;
Invariants.checkState(i != null, "AccordService was not started"); Invariants.require(i != null, "AccordService was not started");
return i; return i;
} }
@ -324,7 +324,7 @@ public class AccordService implements IAccordService, Shutdownable
@VisibleForTesting @VisibleForTesting
public AccordService(Id localId) public AccordService(Id localId)
{ {
Invariants.checkState(localId != null, "static localId must be set before instantiating AccordService"); Invariants.require(localId != null, "static localId must be set before instantiating AccordService");
logger.info("Starting accord with nodeId {}", localId); logger.info("Starting accord with nodeId {}", localId);
AccordAgent agent = FBUtilities.construct(CassandraRelevantProperties.ACCORD_AGENT_CLASS.getString(AccordAgent.class.getName()), "AccordAgent"); AccordAgent agent = FBUtilities.construct(CassandraRelevantProperties.ACCORD_AGENT_CLASS.getString(AccordAgent.class.getName()), "AccordAgent");
agent.setNodeId(localId); agent.setNodeId(localId);
@ -702,7 +702,7 @@ public class AccordService implements IAccordService, Shutdownable
if (success == null) if (success == null)
{ {
logger.error("Ran out of retries for barrier"); logger.error("Ran out of retries for barrier");
checkState(existingFailures != null, "Didn't have success, but also didn't have failures"); require(existingFailures != null, "Didn't have success, but also didn't have failures");
Throwables.throwIfUnchecked(existingFailures); Throwables.throwIfUnchecked(existingFailures);
throw new RuntimeException(existingFailures); throw new RuntimeException(existingFailures);
} }
@ -1260,7 +1260,7 @@ public class AccordService implements IAccordService, Shutdownable
if (ranges.isEmpty()) return; // nothing to see here if (ranges.isEmpty()) return; // nothing to see here
ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(id); ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(id);
Invariants.checkState(cfs != null, "Unable to find table %s", id); Invariants.require(cfs != null, "Unable to find table %s", id);
BigInteger targetSplitSize = BigInteger.valueOf(Math.max(1, cfs.estimateKeys() / 1_000_000)); BigInteger targetSplitSize = BigInteger.valueOf(Math.max(1, cfs.estimateKeys() / 1_000_000));
List<AsyncChain<?>> syncs = new ArrayList<>(ranges.size()); List<AsyncChain<?>> syncs = new ArrayList<>(ranges.size());

View File

@ -316,7 +316,7 @@ public class AccordSyncPropagator
@Override @Override
public void onResponse(Message<SimpleReply> msg) public void onResponse(Message<SimpleReply> msg)
{ {
Invariants.checkState(msg.payload == SimpleReply.Ok, "Unexpected message: %s", msg); Invariants.require(msg.payload == SimpleReply.Ok, "Unexpected message: %s", msg);
Set<Long> completedEpochs = new HashSet<>(); Set<Long> completedEpochs = new HashSet<>();
// TODO review is it a good idea to call the listener while not holding the `AccordSyncPropagator` lock? // TODO review is it a good idea to call the listener while not holding the `AccordSyncPropagator` lock?
synchronized (AccordSyncPropagator.this) synchronized (AccordSyncPropagator.this)

View File

@ -287,12 +287,12 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
private void state(State state) private void state(State state)
{ {
Invariants.checkState(state.isPermittedFrom(this.state), "%s forbidden from %s", state, this, AccordTask::toDescription); Invariants.require(state.isPermittedFrom(this.state), "%s forbidden from %s", state, this, AccordTask::toDescription);
this.state = state; this.state = state;
if (state == WAITING_TO_RUN) if (state == WAITING_TO_RUN)
{ {
Invariants.checkState(rangeScanner == null || rangeScanner.scanned); Invariants.require(rangeScanner == null || rangeScanner.scanned);
Invariants.checkState(loading == null && waitingToLoad == null, "WAITING_TO_RUN => no loading or waiting; found %s", this, AccordTask::toDescription); Invariants.require(loading == null && waitingToLoad == null, "WAITING_TO_RUN => no loading or waiting; found %s", this, AccordTask::toDescription);
loadedAt = nanoTime(); loadedAt = nanoTime();
} }
else if (state == RUNNING) else if (state == RUNNING)
@ -317,7 +317,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
@Override @Override
protected Cancellable start(BiConsumer<? super R, Throwable> callback) protected Cancellable start(BiConsumer<? super R, Throwable> callback)
{ {
Invariants.checkState(AccordTask.this.callback == null); Invariants.require(AccordTask.this.callback == null);
AccordTask.this.callback = callback; AccordTask.this.callback = callback;
commandStore.tryPreSetup(AccordTask.this); commandStore.tryPreSetup(AccordTask.this);
commandStore.executor().submit(AccordTask.this); commandStore.executor().submit(AccordTask.this);
@ -396,7 +396,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
case RECOVER: case RECOVER:
if (!isToCompleteRangeScan) if (!isToCompleteRangeScan)
{ {
Invariants.checkState(rangeScanner == null); Invariants.require(rangeScanner == null);
rangeScanner = new RangeTxnScanner(); rangeScanner = new RangeTxnScanner();
} }
@ -443,7 +443,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
AccordCacheEntry<K, V> node = ref.global(); AccordCacheEntry<K, V> node = ref.global();
int refs = node.increment(); int refs = node.increment();
Invariants.checkState(refs > 1); Invariants.require(refs > 1);
loaded.apply(this).put(k, cache.parent().adapter().safeRef(node)); loaded.apply(this).put(k, cache.parent().adapter().safeRef(node));
} }
@ -498,7 +498,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
public boolean onLoad(AccordCacheEntry<?, ?> state) public boolean onLoad(AccordCacheEntry<?, ?> state)
{ {
AccordSafeState<?, ?> safeRef = loading == null ? null : loading.remove(state.key()); AccordSafeState<?, ?> safeRef = loading == null ? null : loading.remove(state.key());
Invariants.checkState(safeRef != null && safeRef.global() == state, "Expected to find %s loading; found %s", state, this, AccordTask::toDescription); Invariants.require(safeRef != null && safeRef.global() == state, "Expected to find %s loading; found %s", state, this, AccordTask::toDescription);
if (safeRef.getClass() == AccordSafeCommand.class) if (safeRef.getClass() == AccordSafeCommand.class)
ensureCommands().put((TxnId)state.key(), (AccordSafeCommand) safeRef); ensureCommands().put((TxnId)state.key(), (AccordSafeCommand) safeRef);
else else
@ -511,7 +511,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
if (this.state.compareTo(State.WAITING_TO_LOAD) < 0) if (this.state.compareTo(State.WAITING_TO_LOAD) < 0)
return false; return false;
Invariants.checkState(waitingToLoad == null, "Invalid state: %s", this, AccordTask::toDescription); Invariants.require(waitingToLoad == null, "Invalid state: %s", this, AccordTask::toDescription);
state(WAITING_TO_RUN); state(WAITING_TO_RUN);
return true; return true;
} }
@ -520,7 +520,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
public boolean onLoading(AccordCacheEntry<?, ?> state) public boolean onLoading(AccordCacheEntry<?, ?> state)
{ {
boolean removed = waitingToLoad != null && waitingToLoad.remove(state); boolean removed = waitingToLoad != null && waitingToLoad.remove(state);
Invariants.checkState(removed, "%s not found in waitingToLoad %s", state, this, AccordTask::toDescription); Invariants.require(removed, "%s not found in waitingToLoad %s", state, this, AccordTask::toDescription);
if (!waitingToLoad.isEmpty()) if (!waitingToLoad.isEmpty())
return false; return false;
@ -575,7 +575,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
private ArrayDeque<AccordCacheEntry<?, ?>> ensureWaitingToLoad() private ArrayDeque<AccordCacheEntry<?, ?>> ensureWaitingToLoad()
{ {
Invariants.checkState(state.compareTo(WAITING_TO_LOAD) <= 0, "Expected status to be on or before WAITING_TO_LOAD; found %s", this, AccordTask::toDescription); Invariants.require(state.compareTo(WAITING_TO_LOAD) <= 0, "Expected status to be on or before WAITING_TO_LOAD; found %s", this, AccordTask::toDescription);
if (waitingToLoad == null) if (waitingToLoad == null)
waitingToLoad = new ArrayDeque<>(); waitingToLoad = new ArrayDeque<>();
return waitingToLoad; return waitingToLoad;
@ -583,7 +583,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
public AccordCacheEntry<?, ?> pollWaitingToLoad() public AccordCacheEntry<?, ?> pollWaitingToLoad()
{ {
Invariants.checkState(state == State.WAITING_TO_LOAD, "Expected status to be WAITING_TO_LOAD; found %s", this, AccordTask::toDescription); Invariants.require(state == State.WAITING_TO_LOAD, "Expected status to be WAITING_TO_LOAD; found %s", this, AccordTask::toDescription);
if (waitingToLoad == null) if (waitingToLoad == null)
return null; return null;
@ -612,7 +612,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
{ {
if (sanityCheck != null) if (sanityCheck != null)
{ {
Invariants.checkState(SANITY_CHECK); Invariants.require(SANITY_CHECK);
Condition condition = Condition.newOneTimeCondition(); Condition condition = Condition.newOneTimeCondition();
this.commandStore.appendCommands(diffs, condition::signal); this.commandStore.appendCommands(diffs, condition::signal);
condition.awaitUninterruptibly(); condition.awaitUninterruptibly();
@ -898,8 +898,8 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
if (state == CANCELLED) if (state == CANCELLED)
return; return;
Invariants.checkState(queue.kind == state || (queue.kind == State.WAITING_TO_LOAD && state == WAITING_TO_SCAN_RANGES), "Invalid queue type: %s vs %s", queue.kind, this, AccordTask::toDescription); Invariants.require(queue.kind == state || (queue.kind == State.WAITING_TO_LOAD && state == WAITING_TO_SCAN_RANGES), "Invalid queue type: %s vs %s", queue.kind, this, AccordTask::toDescription);
Invariants.checkState(this.queued == null, "Already queued with state: %s", this, AccordTask::toDescription); Invariants.require(this.queued == null, "Already queued with state: %s", this, AccordTask::toDescription);
queued = queue; queued = queue;
queue.append(this); queue.append(this);
} }
@ -1089,7 +1089,7 @@ public abstract class AccordTask<R> extends Task implements Runnable, Function<S
public void scannedExclusive() public void scannedExclusive()
{ {
Invariants.checkState(state == SCANNING_RANGES, "Expected SCANNING_RANGES; found %s", AccordTask.this, AccordTask::toDescription); Invariants.require(state == SCANNING_RANGES, "Expected SCANNING_RANGES; found %s", AccordTask.this, AccordTask::toDescription);
scanned = true; scanned = true;
scannedInternal(); scannedInternal();
if (loading == null) state(WAITING_TO_RUN); if (loading == null) state(WAITING_TO_RUN);

View File

@ -102,7 +102,7 @@ public class AccordTopology
FastPathStrategy tableStrategy = metadata.params.fastPath; FastPathStrategy tableStrategy = metadata.params.fastPath;
FastPathStrategy strategy = tableStrategy.kind() != FastPathStrategy.Kind.INHERIT_KEYSPACE FastPathStrategy strategy = tableStrategy.kind() != FastPathStrategy.Kind.INHERIT_KEYSPACE
? tableStrategy : keyspace.params.fastPath; ? tableStrategy : keyspace.params.fastPath;
Invariants.checkState(strategy.kind() != FastPathStrategy.Kind.INHERIT_KEYSPACE); Invariants.require(strategy.kind() != FastPathStrategy.Kind.INHERIT_KEYSPACE);
return strategy; return strategy;
} }
@ -125,11 +125,11 @@ public class AccordTopology
{ {
// TCM doesn't create wrap around ranges // TCM doesn't create wrap around ranges
for (Range<Token> range : ranges) for (Range<Token> range : ranges)
Invariants.checkArgument(!range.isWrapAround() || range.right.equals(range.right.minValue()), Invariants.requireArgument(!range.isWrapAround() || range.right.equals(range.right.minValue()),
"wrap around range %s found", range); "wrap around range %s found", range);
Sets.SetView<InetAddressAndPort> readOnly = Sets.difference(readEndpoints, writeEndpoints); Sets.SetView<InetAddressAndPort> readOnly = Sets.difference(readEndpoints, writeEndpoints);
Invariants.checkState(readOnly.isEmpty(), "Read only replicas detected: %s", readOnly); Invariants.require(readOnly.isEmpty(), "Read only replicas detected: %s", readOnly);
SortedArrayList<Id> nodes = new SortedArrayList<>(writeEndpoints.stream() SortedArrayList<Id> nodes = new SortedArrayList<>(writeEndpoints.stream()
.map(directory::peerId) .map(directory::peerId)

View File

@ -227,7 +227,7 @@ public class CommandsForRanges extends TreeMap<Timestamp, Summary> implements Co
public Summary ifRelevant(Command.Minimal cmd) public Summary ifRelevant(Command.Minimal cmd)
{ {
Invariants.checkState(findAsDep == null); Invariants.require(findAsDep == null);
return ifRelevant(cmd.txnId, cmd.executeAt, cmd.saveStatus, cmd.participants, null); return ifRelevant(cmd.txnId, cmd.executeAt, cmd.saveStatus, cmd.participants, null);
} }
} }

View File

@ -85,16 +85,16 @@ class EndpointMapping implements AccordEndpointMapper
public Builder add(InetAddressAndPort endpoint, Node.Id id) public Builder add(InetAddressAndPort endpoint, Node.Id id)
{ {
Invariants.checkArgument(!mapping.containsKey(id), "Mapping already exists for Node.Id %s", id); Invariants.requireArgument(!mapping.containsKey(id), "Mapping already exists for Node.Id %s", id);
Invariants.checkArgument(!mapping.containsValue(endpoint), "Mapping already exists for %s", endpoint); Invariants.requireArgument(!mapping.containsValue(endpoint), "Mapping already exists for %s", endpoint);
mapping.put(id, endpoint); mapping.put(id, endpoint);
return this; return this;
} }
public Builder removed(InetAddressAndPort endpoint, Node.Id id, long epoch) public Builder removed(InetAddressAndPort endpoint, Node.Id id, long epoch)
{ {
Invariants.checkArgument(!mapping.containsKey(id), "Mapping already exists for Node.Id %s", id); Invariants.requireArgument(!mapping.containsKey(id), "Mapping already exists for Node.Id %s", id);
Invariants.checkArgument(!mapping.containsValue(endpoint), "Mapping already exists for %s", endpoint); Invariants.requireArgument(!mapping.containsValue(endpoint), "Mapping already exists for %s", endpoint);
mapping.put(id, endpoint); mapping.put(id, endpoint);
removed.put(id, epoch); removed.put(id, epoch);
return this; return this;

View File

@ -52,8 +52,8 @@ public final class JournalKey
public JournalKey(TxnId id, Type type, int commandStoreId) public JournalKey(TxnId id, Type type, int commandStoreId)
{ {
Invariants.checkArgument(commandStoreId >= 0); Invariants.requireArgument(commandStoreId >= 0);
Invariants.checkState((id.lsb & (0xffff & ~TxnId.IDENTITY_FLAGS)) == 0); Invariants.require((id.lsb & (0xffff & ~TxnId.IDENTITY_FLAGS)) == 0);
Invariants.nonNull(type); Invariants.nonNull(type);
Invariants.nonNull(id); Invariants.nonNull(id);
this.type = type; this.type = type;

View File

@ -44,7 +44,7 @@ public class TokenRange extends Range.EndInclusive
public static TokenRange create(AccordRoutingKey start, AccordRoutingKey end) public static TokenRange create(AccordRoutingKey start, AccordRoutingKey end)
{ {
Invariants.checkArgument(start.table().equals(end.table()), Invariants.requireArgument(start.table().equals(end.table()),
"Token ranges cannot cover more than one keyspace start:%s, end:%s", "Token ranges cannot cover more than one keyspace start:%s, end:%s",
start, end); start, end);
return new TokenRange(start, end); return new TokenRange(start, end);

View File

@ -204,7 +204,7 @@ public class AccordAgent implements Agent
startTime = nonClashingStartTime(startTime, shard == null ? null : shard.nodes, node.id(), oneSecond, random); startTime = nonClashingStartTime(startTime, shard == null ? null : shard.nodes, node.id(), oneSecond, random);
long nowMicros = MILLISECONDS.toMicros(Clock.Global.currentTimeMillis()); long nowMicros = MILLISECONDS.toMicros(Clock.Global.currentTimeMillis());
long delayMicros = Math.max(1, startTime - nowMicros); long delayMicros = Math.max(1, startTime - nowMicros);
Invariants.checkState(delayMicros < TimeUnit.HOURS.toMicros(1L)); Invariants.require(delayMicros < TimeUnit.HOURS.toMicros(1L));
return units.convert(delayMicros, MICROSECONDS); return units.convert(delayMicros, MICROSECONDS);
} }

View File

@ -199,7 +199,7 @@ public class ParameterizedFastPathStrategy implements FastPathStrategy
cmp = this.sortPos - that.sortPos; cmp = this.sortPos - that.sortPos;
if (cmp != 0) return cmp; if (cmp != 0) return cmp;
Invariants.checkState(this.id.equals(that.id)); Invariants.require(this.id.equals(that.id));
return 0; return 0;
} }
} }
@ -228,7 +228,7 @@ public class ParameterizedFastPathStrategy implements FastPathStrategy
Arrays.sort(array); Arrays.sort(array);
SortedArrayList<Node.Id> electorate = new SortedArrayList<>(array); SortedArrayList<Node.Id> electorate = new SortedArrayList<>(array);
Invariants.checkState(electorate.size() >= slowQuorum); Invariants.require(electorate.size() >= slowQuorum);
return electorate; return electorate;
} }

View File

@ -59,7 +59,7 @@ public class SimpleFastPathStrategy implements FastPathStrategy
Node.Id[] array = new Node.Id[nodes.size() - discarded]; Node.Id[] array = new Node.Id[nodes.size() - discarded];
System.arraycopy(tmp, 0, array, 0, nodes.size() - discarded); System.arraycopy(tmp, 0, array, 0, nodes.size() - discarded);
SortedArrayList<Node.Id> fastPath = new SortedArrayList<>(array); SortedArrayList<Node.Id> fastPath = new SortedArrayList<>(array);
Invariants.checkState(fastPath.size() >= Shard.slowQuorumSize(nodes.size())); Invariants.require(fastPath.size() >= Shard.slowQuorumSize(nodes.size()));
return fastPath; return fastPath;
} }

View File

@ -49,7 +49,7 @@ import org.apache.cassandra.service.accord.AccordMessageSink.AccordMessageType;
import org.apache.cassandra.service.accord.serializers.ApplySerializers.ApplySerializer; import org.apache.cassandra.service.accord.serializers.ApplySerializers.ApplySerializer;
import org.apache.cassandra.service.accord.txn.AccordUpdate; import org.apache.cassandra.service.accord.txn.AccordUpdate;
import static accord.utils.Invariants.checkState; import static accord.utils.Invariants.requireArgument;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
/** /**
@ -101,7 +101,7 @@ public class AccordInteropApply extends Apply implements LocalListeners.ComplexL
public ApplyReply apply(SafeCommandStore safeStore, StoreParticipants participants) public ApplyReply apply(SafeCommandStore safeStore, StoreParticipants participants)
{ {
ApplyReply reply = super.apply(safeStore, participants); ApplyReply reply = super.apply(safeStore, participants);
checkState(reply == ApplyReply.Redundant || reply == ApplyReply.Applied || reply == ApplyReply.Insufficient, "Unexpected ApplyReply"); requireArgument(reply == ApplyReply.Redundant || reply == ApplyReply.Applied || reply == ApplyReply.Insufficient, "Unexpected ApplyReply");
// Hasn't necessarily finished applying yet so need to check and maybe add a listener // Hasn't necessarily finished applying yet so need to check and maybe add a listener
// Redundant means we are competing with a recovery coordinator which is fine // Redundant means we are competing with a recovery coordinator which is fine

View File

@ -99,7 +99,7 @@ import org.apache.cassandra.transport.Dispatcher;
import static accord.coordinate.CoordinationAdapter.Factory.Kind.Standard; import static accord.coordinate.CoordinationAdapter.Factory.Kind.Standard;
import static accord.primitives.Txn.Kind.Write; import static accord.primitives.Txn.Kind.Write;
import static accord.utils.Invariants.checkArgument; import static accord.utils.Invariants.requireArgument;
import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.accordReadMetrics; import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.accordReadMetrics;
import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.accordWriteMetrics; import static org.apache.cassandra.metrics.ClientRequestsMetricsHolder.accordWriteMetrics;
@ -172,7 +172,7 @@ public class AccordInteropExecution implements ReadCoordinator, MaximalCommitSen
public AccordInteropExecution(Node node, TxnId txnId, Txn txn, AccordUpdate.Kind updateKind, FullRoute<?> route, Participants<?> readScope, Timestamp executeAt, Deps deps, BiConsumer<? super Result, Throwable> callback, public AccordInteropExecution(Node node, TxnId txnId, Txn txn, AccordUpdate.Kind updateKind, FullRoute<?> route, Participants<?> readScope, Timestamp executeAt, Deps deps, BiConsumer<? super Result, Throwable> callback,
AgentExecutor executor, ConsistencyLevel consistencyLevel, AccordEndpointMapper endpointMapper) AgentExecutor executor, ConsistencyLevel consistencyLevel, AccordEndpointMapper endpointMapper)
{ {
checkArgument(!txn.read().keys().isEmpty() || updateKind == AccordUpdate.Kind.UNRECOVERABLE_REPAIR); requireArgument(!txn.read().keys().isEmpty() || updateKind == AccordUpdate.Kind.UNRECOVERABLE_REPAIR);
this.node = node; this.node = node;
this.txnId = txnId; this.txnId = txnId;
this.txn = txn; this.txn = txn;
@ -183,7 +183,7 @@ public class AccordInteropExecution implements ReadCoordinator, MaximalCommitSen
this.callback = callback; this.callback = callback;
this.executor = executor; this.executor = executor;
checkArgument(updateKind == AccordUpdate.Kind.UNRECOVERABLE_REPAIR || consistencyLevel == ConsistencyLevel.QUORUM || consistencyLevel == ConsistencyLevel.ALL || consistencyLevel == ConsistencyLevel.SERIAL); requireArgument(updateKind == AccordUpdate.Kind.UNRECOVERABLE_REPAIR || consistencyLevel == ConsistencyLevel.QUORUM || consistencyLevel == ConsistencyLevel.ALL || consistencyLevel == ConsistencyLevel.SERIAL);
this.consistencyLevel = consistencyLevel; this.consistencyLevel = consistencyLevel;
this.endpointMapper = endpointMapper; this.endpointMapper = endpointMapper;
@ -242,7 +242,7 @@ public class AccordInteropExecution implements ReadCoordinator, MaximalCommitSen
@Override @Override
public void sendReadRepairMutation(Message<Mutation> message, InetAddressAndPort to, RequestCallback<Object> callback) public void sendReadRepairMutation(Message<Mutation> message, InetAddressAndPort to, RequestCallback<Object> callback)
{ {
checkArgument(message.payload.allowsPotentialTransactionConflicts()); requireArgument(message.payload.allowsPotentialTransactionConflicts());
Node.Id id = endpointMapper.mappedId(to); Node.Id id = endpointMapper.mappedId(to);
AccordInteropReadRepair readRepair = new AccordInteropReadRepair(id, executes, txnId, readScope, executeAt.epoch(), message.payload); AccordInteropReadRepair readRepair = new AccordInteropReadRepair(id, executes, txnId, readScope, executeAt.epoch(), message.payload);
node.send(id, readRepair, executor, new AccordInteropReadRepair.ReadRepairCallback(id, to, message, callback, this)); node.send(id, readRepair, executor, new AccordInteropReadRepair.ReadRepairCallback(id, to, message, callback, this));

View File

@ -111,14 +111,14 @@ public class AccordInteropPersist extends Persist
public AccordInteropPersist(Node node, Topologies topologies, TxnId txnId, Route<?> sendTo, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, FullRoute<?> fullRoute, ConsistencyLevel consistencyLevel, BiConsumer<? super Result, Throwable> clientCallback) public AccordInteropPersist(Node node, Topologies topologies, TxnId txnId, Route<?> sendTo, Txn txn, Timestamp executeAt, Deps deps, Writes writes, Result result, FullRoute<?> fullRoute, ConsistencyLevel consistencyLevel, BiConsumer<? super Result, Throwable> clientCallback)
{ {
super(node, topologies, txnId, sendTo, txn, executeAt, deps, writes, result, fullRoute); super(node, topologies, txnId, sendTo, txn, executeAt, deps, writes, result, fullRoute);
Invariants.checkArgument(consistencyLevel == ConsistencyLevel.QUORUM || consistencyLevel == ConsistencyLevel.ALL || consistencyLevel == ConsistencyLevel.SERIAL || consistencyLevel == ConsistencyLevel.ONE); Invariants.requireArgument(consistencyLevel == ConsistencyLevel.QUORUM || consistencyLevel == ConsistencyLevel.ALL || consistencyLevel == ConsistencyLevel.SERIAL || consistencyLevel == ConsistencyLevel.ONE);
this.consistencyLevel = consistencyLevel; this.consistencyLevel = consistencyLevel;
registerClientCallback(result, clientCallback); registerClientCallback(result, clientCallback);
} }
public void registerClientCallback(Result result, BiConsumer<? super Result, Throwable> clientCallback) public void registerClientCallback(Result result, BiConsumer<? super Result, Throwable> clientCallback)
{ {
Invariants.checkState(callback == null); Invariants.require(callback == null);
switch (consistencyLevel) switch (consistencyLevel)
{ {
case ONE: // Can safely upgrade ONE to QUORUM/SERIAL to get a synchronous commit case ONE: // Can safely upgrade ONE to QUORUM/SERIAL to get a synchronous commit

View File

@ -60,7 +60,7 @@ public abstract class AccordInteropReadCallback<T> implements Callback<ReadReply
public void onSuccess(Node.Id from, ReadReply reply) public void onSuccess(Node.Id from, ReadReply reply)
{ {
Invariants.checkArgument(from.equals(id)); Invariants.requireArgument(from.equals(id));
if (reply.isOk()) if (reply.isOk())
{ {
wrapped.onResponse(message.responseWith(convertResponse((ReadOk) reply)).withFrom(endpoint)); wrapped.onResponse(message.responseWith(convertResponse((ReadOk) reply)).withFrom(endpoint));

View File

@ -122,7 +122,7 @@ public class AcceptSerializers
} }
else else
{ {
Invariants.checkState(reply == AcceptReply.SUCCESS); Invariants.require(reply == AcceptReply.SUCCESS);
out.writeByte(2); out.writeByte(2);
} }
break; break;

View File

@ -45,7 +45,7 @@ public class ApplySerializers
{ {
public void serialize(Apply.Kind kind, DataOutputPlus out, int version) throws IOException public void serialize(Apply.Kind kind, DataOutputPlus out, int version) throws IOException
{ {
Invariants.checkArgument(kind == Apply.Kind.Maximal || kind == Apply.Kind.Minimal); Invariants.requireArgument(kind == Apply.Kind.Maximal || kind == Apply.Kind.Minimal);
out.writeBoolean(kind == Apply.Kind.Maximal); out.writeBoolean(kind == Apply.Kind.Maximal);
} }

View File

@ -48,7 +48,7 @@ public class AwaitSerializer
out.writeUnsignedVInt(await.maxAwaitEpoch - await.txnId.epoch()); out.writeUnsignedVInt(await.maxAwaitEpoch - await.txnId.epoch());
out.writeUnsignedVInt(await.maxAwaitEpoch - await.minAwaitEpoch); out.writeUnsignedVInt(await.maxAwaitEpoch - await.minAwaitEpoch);
out.writeUnsignedVInt32(await.callbackId + 1); out.writeUnsignedVInt32(await.callbackId + 1);
Invariants.checkState(await.callbackId >= -1); Invariants.require(await.callbackId >= -1);
} }
@Override @Override
@ -62,7 +62,7 @@ public class AwaitSerializer
long maxAwaitEpoch = in.readUnsignedVInt() + txnId.epoch(); long maxAwaitEpoch = in.readUnsignedVInt() + txnId.epoch();
long minAwaitEpoch = maxAwaitEpoch - in.readUnsignedVInt(); long minAwaitEpoch = maxAwaitEpoch - in.readUnsignedVInt();
int callbackId = in.readUnsignedVInt32() - 1; int callbackId = in.readUnsignedVInt32() - 1;
Invariants.checkState(callbackId >= -1); Invariants.require(callbackId >= -1);
return Await.SerializerSupport.create(txnId, scope, blockedUntil, notifyProgressLog, minAwaitEpoch, maxAwaitEpoch, callbackId); return Await.SerializerSupport.create(txnId, scope, blockedUntil, notifyProgressLog, minAwaitEpoch, maxAwaitEpoch, callbackId);
} }

View File

@ -208,7 +208,7 @@ public class CommandSerializers
{ {
if ((flags & 1) != 0) if ((flags & 1) != 0)
return; return;
flags >>= 1; flags >>>= 1;
} }
in.readUnsignedVInt(); in.readUnsignedVInt();
in.readUnsignedVInt(); in.readUnsignedVInt();
@ -233,14 +233,14 @@ public class CommandSerializers
out.writeUnsignedVInt32(flags); out.writeUnsignedVInt32(flags);
if (executeAt == null) if (executeAt == null)
{ {
Invariants.checkState(nullable); Invariants.require(nullable);
} }
else else
{ {
out.writeUnsignedVInt(executeAt.epoch()); out.writeUnsignedVInt(executeAt.epoch());
out.writeUnsignedVInt(executeAt.hlc()); out.writeUnsignedVInt(executeAt.hlc());
out.writeUnsignedVInt32(executeAt.node.id); out.writeUnsignedVInt32(executeAt.node.id);
if ((flags & HAS_UNIQUE_HLC) != 0) if (executeAt.hasDistinctHlcAndUniqueHlc())
out.writeUnsignedVInt(executeAt.uniqueHlc() - executeAt.hlc()); out.writeUnsignedVInt(executeAt.uniqueHlc() - executeAt.hlc());
} }
} }
@ -261,13 +261,13 @@ public class CommandSerializers
long size = TypeSizes.sizeofUnsignedVInt(flags); long size = TypeSizes.sizeofUnsignedVInt(flags);
if (executeAt == null) if (executeAt == null)
{ {
Invariants.checkState(nullable); Invariants.require(nullable);
return size; return size;
} }
size += TypeSizes.sizeofUnsignedVInt(executeAt.epoch()); size += TypeSizes.sizeofUnsignedVInt(executeAt.epoch());
size += TypeSizes.sizeofUnsignedVInt(executeAt.hlc()); size += TypeSizes.sizeofUnsignedVInt(executeAt.hlc());
size += TypeSizes.sizeofUnsignedVInt(executeAt.node.id); size += TypeSizes.sizeofUnsignedVInt(executeAt.node.id);
if ((flags & HAS_UNIQUE_HLC) != 0) if (executeAt.hasDistinctHlcAndUniqueHlc())
size += TypeSizes.sizeofUnsignedVInt(executeAt.uniqueHlc() - executeAt.hlc()); size += TypeSizes.sizeofUnsignedVInt(executeAt.uniqueHlc() - executeAt.hlc());
return size; return size;
} }
@ -276,7 +276,7 @@ public class CommandSerializers
{ {
if (executeAt == null) if (executeAt == null)
{ {
Invariants.checkState(nullable); Invariants.require(nullable);
return 1; return 1;
} }

View File

@ -138,7 +138,7 @@ public class CommandStoreSerializers
public void serialize(RedundantBefore.Entry t, DataOutputPlus out, int version) throws IOException public void serialize(RedundantBefore.Entry t, DataOutputPlus out, int version) throws IOException
{ {
KeySerializers.range.serialize(t.range, out, version); KeySerializers.range.serialize(t.range, out, version);
Invariants.checkState(t.startOwnershipEpoch <= t.endOwnershipEpoch); Invariants.require(t.startOwnershipEpoch <= t.endOwnershipEpoch);
out.writeUnsignedVInt(t.startOwnershipEpoch); out.writeUnsignedVInt(t.startOwnershipEpoch);
if (t.endOwnershipEpoch == Long.MAX_VALUE) out.writeUnsignedVInt(0L); if (t.endOwnershipEpoch == Long.MAX_VALUE) out.writeUnsignedVInt(0L);
else out.writeUnsignedVInt(1 + t.endOwnershipEpoch - t.startOwnershipEpoch); else out.writeUnsignedVInt(1 + t.endOwnershipEpoch - t.startOwnershipEpoch);

View File

@ -39,7 +39,7 @@ public class SmallEnumSerializer<E extends Enum<E>> implements IVersionedSeriali
public SmallEnumSerializer(Class<E> clazz) public SmallEnumSerializer(Class<E> clazz)
{ {
this.values = clazz.getEnumConstants(); this.values = clazz.getEnumConstants();
Invariants.checkArgument(values.length < 255); // allow an extra 1 for nullable variant to ensure consistency Invariants.requireArgument(values.length < 255); // allow an extra 1 for nullable variant to ensure consistency
} }
public E forOrdinal(int ordinal) public E forOrdinal(int ordinal)

View File

@ -41,7 +41,7 @@ public class WaitingOnSerializer
{ {
public static void serializeBitSetsOnly(TxnId txnId, WaitingOn waitingOn, DataOutputPlus out) throws IOException public static void serializeBitSetsOnly(TxnId txnId, WaitingOn waitingOn, DataOutputPlus out) throws IOException
{ {
Invariants.checkState(txnId.is(Key) == (waitingOn.appliedOrInvalidated == null)); Invariants.require(txnId.is(Key) == (waitingOn.appliedOrInvalidated == null));
int keyCount = waitingOn.keys.size(); int keyCount = waitingOn.keys.size();
int txnIdCount = waitingOn.txnIdCount(); int txnIdCount = waitingOn.txnIdCount();
int waitingOnLength = (txnIdCount + keyCount + 63) / 64; int waitingOnLength = (txnIdCount + keyCount + 63) / 64;
@ -78,8 +78,8 @@ public class WaitingOnSerializer
RangeDeps directRangeDeps = deps.rangeDeps; RangeDeps directRangeDeps = deps.rangeDeps;
KeyDeps directKeyDeps = deps.directKeyDeps; KeyDeps directKeyDeps = deps.directKeyDeps;
int txnIdCount = directRangeDeps.txnIdCount() + directKeyDeps.txnIdCount(); int txnIdCount = directRangeDeps.txnIdCount() + directKeyDeps.txnIdCount();
Invariants.checkState(waitingOn.size()/64 == (txnIdCount + keys.size() + 63) / 64); Invariants.require(waitingOn.size()/64 == (txnIdCount + keys.size() + 63) / 64);
Invariants.checkState(appliedOrInvalidated == null || (appliedOrInvalidated.size()/64 == (txnIdCount + 63)/64)); Invariants.require(appliedOrInvalidated == null || (appliedOrInvalidated.size()/64 == (txnIdCount + 63)/64));
WaitingOn result = new WaitingOn(keys, directRangeDeps, directKeyDeps, waitingOn, appliedOrInvalidated); WaitingOn result = new WaitingOn(keys, directRangeDeps, directKeyDeps, waitingOn, appliedOrInvalidated);
if (executeAtLeast != null) return new Command.WaitingOnWithExecuteAt(result, executeAtLeast); if (executeAtLeast != null) return new Command.WaitingOnWithExecuteAt(result, executeAtLeast);
@ -102,7 +102,7 @@ public class WaitingOnSerializer
private static void serialize(int length, SimpleBitSet write, DataOutputPlus out) throws IOException private static void serialize(int length, SimpleBitSet write, DataOutputPlus out) throws IOException
{ {
long[] bits = SimpleBitSet.SerializationSupport.getArray(write); long[] bits = SimpleBitSet.SerializationSupport.getArray(write);
Invariants.checkState(length == bits.length); Invariants.require(length == bits.length);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
out.writeLong(bits[i]); out.writeLong(bits[i]);
} }
@ -118,7 +118,7 @@ public class WaitingOnSerializer
public static long serializedSize(int length, SimpleBitSet write) public static long serializedSize(int length, SimpleBitSet write)
{ {
long[] bits = SimpleBitSet.SerializationSupport.getArray(write); long[] bits = SimpleBitSet.SerializationSupport.getArray(write);
Invariants.checkState(length == bits.length, "Expected length %d != %d", length, bits.length); Invariants.require(length == bits.length, "Expected length %d != %d", length, bits.length);
return (long) TypeSizes.LONG_SIZE * length; return (long) TypeSizes.LONG_SIZE * length;
} }
} }

View File

@ -26,9 +26,13 @@ import com.google.common.collect.ImmutableMap;
import org.apache.cassandra.cql3.QueryOptions; import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.UpdateParameters; import org.apache.cassandra.cql3.UpdateParameters;
import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.marshal.TimeUUIDType;
import org.apache.cassandra.db.partitions.Partition; import org.apache.cassandra.db.partitions.Partition;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.schema.TableMetadata; import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.service.ClientState; import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.paxos.Ballot;
import org.apache.cassandra.utils.TimeUUID;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MICROSECONDS;
@ -46,6 +50,22 @@ public class AccordUpdateParameters
this.timestamp = timestamp; this.timestamp = timestamp;
} }
static class RowUpdateParameters extends UpdateParameters
{
private long timeUuidNanos;
public RowUpdateParameters(TableMetadata metadata, ClientState clientState, QueryOptions options, long timestamp, long nowInSec, int ttl, Map<DecoratedKey, Partition> prefetchedRows) throws InvalidRequestException
{
super(metadata, clientState, options, timestamp, nowInSec, ttl, prefetchedRows);
}
@Override
public byte[] nextTimeUUIDAsBytes()
{
return TimeUUID.toBytes(Ballot.unixMicrosToMsb(timestamp), TimeUUIDType.signedBytesToNativeLong(timeUuidNanos++));
}
}
public TxnData getData() public TxnData getData()
{ {
return data; return data;
@ -60,13 +80,13 @@ public class AccordUpdateParameters
// TODO : How should Accord work with TTL? // TODO : How should Accord work with TTL?
int ttl = metadata.params.defaultTimeToLive; int ttl = metadata.params.defaultTimeToLive;
return new UpdateParameters(metadata, return new RowUpdateParameters(metadata,
disabledGuardrails, disabledGuardrails,
options, options,
timestamp, timestamp,
MICROSECONDS.toSeconds(timestamp), MICROSECONDS.toSeconds(timestamp),
ttl, ttl,
prefetchRow(metadata, dk, rowIndex)); prefetchRow(metadata, dk, rowIndex));
} }
private Map<DecoratedKey, Partition> prefetchRow(TableMetadata metadata, DecoratedKey dk, int index) private Map<DecoratedKey, Partition> prefetchRow(TableMetadata metadata, DecoratedKey dk, int index)

View File

@ -35,7 +35,7 @@ import org.apache.cassandra.utils.Int32Serializer;
import org.apache.cassandra.utils.NullableSerializer; import org.apache.cassandra.utils.NullableSerializer;
import org.apache.cassandra.utils.ObjectSizes; import org.apache.cassandra.utils.ObjectSizes;
import static accord.utils.Invariants.checkArgument; import static accord.utils.Invariants.requireArgument;
import static org.apache.cassandra.service.accord.txn.TxnResult.Kind.txn_data; import static org.apache.cassandra.service.accord.txn.TxnResult.Kind.txn_data;
/** /**
@ -84,7 +84,7 @@ public class TxnData extends Int2ObjectHashMap<TxnDataValue> implements TxnResul
public static int txnDataName(TxnDataNameKind kind, int index) public static int txnDataName(TxnDataNameKind kind, int index)
{ {
checkArgument(index >= 0 && index <= TXN_DATA_NAME_INDEX_MAX); requireArgument(index >= 0 && index <= TXN_DATA_NAME_INDEX_MAX);
int kindInt = (int)(((long)kind.value) << TXN_DATA_NAME_INDEX_BITS); int kindInt = (int)(((long)kind.value) << TXN_DATA_NAME_INDEX_BITS);
return kindInt | index; return kindInt | index;
} }
@ -121,7 +121,7 @@ public class TxnData extends Int2ObjectHashMap<TxnDataValue> implements TxnResul
public static TxnData newWithExpectedSize(int size) public static TxnData newWithExpectedSize(int size)
{ {
checkArgument(size >= 0, "size can't be negative"); requireArgument(size >= 0, "size can't be negative");
size = Math.max(4, size); size = Math.max(4, size);
return new TxnData(size < 1073741824 ? (int)((float)size / 0.75F + 1.0F) : Integer.MAX_VALUE); return new TxnData(size < 1073741824 ? (int)((float)size / 0.75F + 1.0F) : Integer.MAX_VALUE);
} }

View File

@ -53,7 +53,7 @@ import org.apache.cassandra.transport.ProtocolVersion;
import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.ObjectSizes; import org.apache.cassandra.utils.ObjectSizes;
import static accord.utils.Invariants.checkArgument; import static accord.utils.Invariants.requireArgument;
import static accord.utils.SortedArrays.Search.CEIL; import static accord.utils.SortedArrays.Search.CEIL;
import static org.apache.cassandra.service.accord.AccordSerializers.consistencyLevelSerializer; import static org.apache.cassandra.service.accord.AccordSerializers.consistencyLevelSerializer;
import static org.apache.cassandra.service.accord.AccordSerializers.serialize; import static org.apache.cassandra.service.accord.AccordSerializers.serialize;
@ -89,7 +89,7 @@ public class TxnUpdate extends AccordUpdate
public TxnUpdate(List<TxnWrite.Fragment> fragments, TxnCondition condition, @Nullable ConsistencyLevel cassandraCommitCL, boolean preserveTimestamps) public TxnUpdate(List<TxnWrite.Fragment> fragments, TxnCondition condition, @Nullable ConsistencyLevel cassandraCommitCL, boolean preserveTimestamps)
{ {
checkArgument(cassandraCommitCL == null || IAccordService.SUPPORTED_COMMIT_CONSISTENCY_LEVELS.contains(cassandraCommitCL)); requireArgument(cassandraCommitCL == null || IAccordService.SUPPORTED_COMMIT_CONSISTENCY_LEVELS.contains(cassandraCommitCL));
// TODO: Figure out a way to shove keys into TxnCondition, and have it implement slice/merge. // TODO: Figure out a way to shove keys into TxnCondition, and have it implement slice/merge.
this.keys = Keys.of(fragments, fragment -> fragment.key); this.keys = Keys.of(fragments, fragment -> fragment.key);
fragments.sort(TxnWrite.Fragment::compareKeys); fragments.sort(TxnWrite.Fragment::compareKeys);

View File

@ -188,7 +188,7 @@ public class AtomicLongBackedProcessor extends AbstractLocalProcessor
break; break;
if (current.epoch.isEqualOrBefore(start)) if (current.epoch.isEqualOrBefore(start))
{ {
Invariants.checkState(current.epoch.isDirectlyAfter(metadata.epoch)); Invariants.require(current.epoch.isDirectlyAfter(metadata.epoch));
metadata = current.transform.execute(metadata).success().metadata; metadata = current.transform.execute(metadata).success().metadata;
} }
else if (current.epoch.isAfter(start)) else if (current.epoch.isAfter(start))

View File

@ -132,7 +132,7 @@ public interface Processor
cms.add(acc); cms.add(acc);
for (Entry entry : logState.entries) for (Entry entry : logState.entries)
{ {
Invariants.checkState(entry.epoch.isDirectlyAfter(acc.epoch), "%s should have been directly after %s", entry.epoch, acc.epoch); Invariants.require(entry.epoch.isDirectlyAfter(acc.epoch), "%s should have been directly after %s", entry.epoch, acc.epoch);
Transformation.Result res = entry.transform.execute(acc); Transformation.Result res = entry.transform.execute(acc);
assert res.isSuccess() : res.toString(); assert res.isSuccess() : res.toString();
acc = res.success().metadata; acc = res.success().metadata;

View File

@ -161,7 +161,7 @@ public interface LogReader
} }
else else
{ {
Invariants.checkState(closestSnapshot.epoch.isEqualOrAfter(start), Invariants.require(closestSnapshot.epoch.isEqualOrAfter(start),
"Got %s, but requested snapshot of %s", closestSnapshot.epoch, start); "Got %s, but requested snapshot of %s", closestSnapshot.epoch, start);
EntryHolder entryHolder = getEntries(closestSnapshot.epoch, end); EntryHolder entryHolder = getEntries(closestSnapshot.epoch, end);
return new LogState(closestSnapshot, ImmutableList.copyOf(entryHolder.entries)); return new LogState(closestSnapshot, ImmutableList.copyOf(entryHolder.entries));

View File

@ -73,7 +73,7 @@ public class LogState
// Uses Replication rather than an just a list of entries primarily to avoid duplicating the existing serializer // Uses Replication rather than an just a list of entries primarily to avoid duplicating the existing serializer
public LogState(ClusterMetadata baseState, ImmutableList<Entry> entries) public LogState(ClusterMetadata baseState, ImmutableList<Entry> entries)
{ {
Invariants.checkState(baseState == null || Invariants.require(baseState == null ||
entries.isEmpty() || entries.isEmpty() ||
entries.get(0).epoch.isDirectlyAfter(baseState.epoch), entries.get(0).epoch.isDirectlyAfter(baseState.epoch),
"Base state: %s, first entry: %s", baseState == null ? null : baseState.epoch, entries.isEmpty() ? null : entries.get(0).epoch); "Base state: %s, first entry: %s", baseState == null ? null : baseState.epoch, entries.isEmpty() ? null : entries.get(0).epoch);

View File

@ -300,7 +300,7 @@ public class Directory implements MetadataValue<Directory>
public Directory removed(Epoch removedIn, NodeId id, InetAddressAndPort addr) public Directory removed(Epoch removedIn, NodeId id, InetAddressAndPort addr)
{ {
Invariants.checkState(!peers.containsKey(id)); Invariants.require(!peers.containsKey(id));
return new Directory(nextId, return new Directory(nextId,
lastModified, lastModified,
peers, peers,

View File

@ -67,7 +67,7 @@ public abstract class MergeIterator<In,Out> extends AbstractIterator<Out> implem
@Override @Override
protected E getReduced() protected E getReduced()
{ {
Invariants.checkState(first != null); Invariants.require(first != null);
return first; return first;
} }
}); });

View File

@ -143,8 +143,8 @@ public class BTree
public static Object[] unsafeAllocateNonEmptyLeaf(int size) public static Object[] unsafeAllocateNonEmptyLeaf(int size)
{ {
Invariants.checkArgument(size > 0, "size should be non-zero"); Invariants.requireArgument(size > 0, "size should be non-zero");
Invariants.checkArgument(size <= MAX_KEYS, "size (%s) should be no more than %s", size, MAX_KEYS); Invariants.requireArgument(size <= MAX_KEYS, "size (%s) should be no more than %s", size, MAX_KEYS);
return new Object[size | 1]; return new Object[size | 1];
} }

View File

@ -107,7 +107,7 @@ public class LockWithAsyncSignal implements Lock
{ {
Thread thread = Thread.currentThread(); Thread thread = Thread.currentThread();
int restoreDepth = depth; int restoreDepth = depth;
Invariants.checkState(owner == thread); Invariants.require(owner == thread);
depth = 0; depth = 0;
owner = null; owner = null;
@ -117,7 +117,7 @@ public class LockWithAsyncSignal implements Lock
public void unlock() public void unlock()
{ {
Invariants.checkState(owner == Thread.currentThread()); Invariants.require(owner == Thread.currentThread());
if (--depth > 0) if (--depth > 0)
return; return;

View File

@ -158,7 +158,7 @@ public class Coordinator implements ICoordinator
boundBBValues.add(ByteBufferUtil.objectToBytes(boundValue)); boundBBValues.add(ByteBufferUtil.objectToBytes(boundValue));
prepared.validate(clientState); prepared.validate(clientState);
Invariants.checkState(prepared instanceof SelectStatement, "Only SELECT statements can be executed with paging %s", prepared); Invariants.require(prepared instanceof SelectStatement, "Only SELECT statements can be executed with paging %s", prepared);
Dispatcher.RequestTime requestTime = Dispatcher.RequestTime.forImmediateExecution(); Dispatcher.RequestTime requestTime = Dispatcher.RequestTime.forImmediateExecution();
SelectStatement selectStatement = (SelectStatement) prepared; SelectStatement selectStatement = (SelectStatement) prepared;

View File

@ -44,7 +44,7 @@ public class IntegrationTestBase extends TestBaseImpl
protected static void init(int nodes, Consumer<IInstanceConfig> cfg) throws Throwable protected static void init(int nodes, Consumer<IInstanceConfig> cfg) throws Throwable
{ {
Invariants.checkState(!initialized); Invariants.require(!initialized);
cluster = Cluster.build() cluster = Cluster.build()
.withNodes(nodes) .withNodes(nodes)
.withConfig(cfg) .withConfig(cfg)

View File

@ -530,35 +530,35 @@ public abstract class TopologyMixupTestBase<S extends TopologyMixupTestBase.Sche
this.yamlConfigOverrides = CONF_GEN.next(rs); this.yamlConfigOverrides = CONF_GEN.next(rs);
cluster = Cluster.build(topologyHistory.minNodes) cluster = Cluster.build(topologyHistory.minNodes)
.withTokenSupplier(topologyHistory) .withTokenSupplier(topologyHistory)
.withConfig(c -> { .withConfig(c -> {
c.with(Feature.values()) c.with(Feature.values())
.set("write_request_timeout", "10s") .set("write_request_timeout", "10s")
.set("read_request_timeout", "10s") .set("read_request_timeout", "10s")
.set("range_request_timeout", "20s") .set("range_request_timeout", "20s")
.set("request_timeout", "20s") .set("request_timeout", "20s")
.set("transaction_timeout", "15s") .set("transaction_timeout", "15s")
.set("native_transport_timeout", "30s") .set("native_transport_timeout", "30s")
// bound startup to some value larger than the task timeout, this is to allow the // bound startup to some value larger than the task timeout, this is to allow the
// tests to stop blocking when a startup issue is detected. The main reason for // tests to stop blocking when a startup issue is detected. The main reason for
// this is that startup blocks forever, waiting for accord and streaming to // this is that startup blocks forever, waiting for accord and streaming to
// complete... but if there are bugs at these layers then the startup will never // complete... but if there are bugs at these layers then the startup will never
// exit, blocking the JVM from giving the needed information (logs/seed) to debug. // exit, blocking the JVM from giving the needed information (logs/seed) to debug.
.set(Constants.KEY_DTEST_STARTUP_TIMEOUT, "4m") .set(Constants.KEY_DTEST_STARTUP_TIMEOUT, "4m")
.set(Constants.KEY_DTEST_API_STARTUP_FAILURE_AS_SHUTDOWN, false); .set(Constants.KEY_DTEST_API_STARTUP_FAILURE_AS_SHUTDOWN, false);
//TODO (maintenance): where to put this? Anything touching ConfigGenBuilder with jvm-dtest needs this... //TODO (maintenance): where to put this? Anything touching ConfigGenBuilder with jvm-dtest needs this...
((InstanceConfig) c).remove("commitlog_sync_period_in_ms"); ((InstanceConfig) c).remove("commitlog_sync_period_in_ms");
for (Map.Entry<String, Object> e : yamlConfigOverrides.entrySet()) for (Map.Entry<String, Object> e : yamlConfigOverrides.entrySet())
c.set(e.getKey(), e.getValue()); c.set(e.getKey(), e.getValue());
onConfigure(c); onConfigure(c);
}) })
//TODO (maintenance): should TopologyHistory also be a INodeProvisionStrategy.Factory so address information is stored in the Node? //TODO (maintenance): should TopologyHistory also be a INodeProvisionStrategy.Factory so address information is stored in the Node?
//TODO (maintenance): AbstractCluster's Map<Integer, NetworkTopology.DcAndRack> nodeIdTopology makes playing with dc/rack annoying, if this becomes an interface then TopologyHistory could own //TODO (maintenance): AbstractCluster's Map<Integer, NetworkTopology.DcAndRack> nodeIdTopology makes playing with dc/rack annoying, if this becomes an interface then TopologyHistory could own
.withNodeProvisionStrategy((subnet, portMap) -> new INodeProvisionStrategy.AbstractNodeProvisionStrategy(portMap) .withNodeProvisionStrategy((subnet, portMap) -> new INodeProvisionStrategy.AbstractNodeProvisionStrategy(portMap)
{ {
{ {
Invariants.checkArgument(subnet == 0, "Unexpected subnet detected: %d", subnet); Invariants.requireArgument(subnet == 0, "Unexpected subnet detected: %d", subnet);
} }
private final String ipPrefix = "127.0." + subnet + '.'; private final String ipPrefix = "127.0." + subnet + '.';
@ -982,7 +982,7 @@ public abstract class TopologyMixupTestBase<S extends TopologyMixupTestBase.Sche
{ {
String address = addressAndPort.getAddress().getHostAddress(); String address = addressAndPort.getAddress().getHostAddress();
String[] parts = address.split("\\."); String[] parts = address.split("\\.");
Invariants.checkState(parts.length == 4, "Unable to parse address %s", address); Invariants.require(parts.length == 4, "Unable to parse address %s", address);
return Integer.parseInt(parts[3]); return Integer.parseInt(parts[3]);
} }
} }

View File

@ -461,7 +461,7 @@ class SingleOperationVisitBuilder implements SingleOperationBuilder
Relations.Relation[] ckRelations = new Relations.Relation[ckIdxRelations.length]; Relations.Relation[] ckRelations = new Relations.Relation[ckIdxRelations.length];
for (int i = 0; i < ckRelations.length; i++) for (int i = 0; i < ckRelations.length; i++)
{ {
Invariants.checkState(ckIdxRelations[i].column < valueGenerators.ckColumnCount()); Invariants.require(ckIdxRelations[i].column < valueGenerators.ckColumnCount());
ckRelations[i] = new Relations.Relation(ckIdxRelations[i].kind, ckRelations[i] = new Relations.Relation(ckIdxRelations[i].kind,
valueGenerators.ckGen().descriptorAt(ckIdxRelations[i].idx), valueGenerators.ckGen().descriptorAt(ckIdxRelations[i].idx),
ckIdxRelations[i].column); ckIdxRelations[i].column);
@ -470,7 +470,7 @@ class SingleOperationVisitBuilder implements SingleOperationBuilder
Relations.Relation[] regularRelations = new Relations.Relation[regularIdxRelations.length]; Relations.Relation[] regularRelations = new Relations.Relation[regularIdxRelations.length];
for (int i = 0; i < regularRelations.length; i++) for (int i = 0; i < regularRelations.length; i++)
{ {
Invariants.checkState(regularIdxRelations[i].column < valueGenerators.regularColumnCount()); Invariants.require(regularIdxRelations[i].column < valueGenerators.regularColumnCount());
regularRelations[i] = new Relations.Relation(regularIdxRelations[i].kind, regularRelations[i] = new Relations.Relation(regularIdxRelations[i].kind,
valueGenerators.regularColumnGen(regularIdxRelations[i].column).descriptorAt(regularIdxRelations[i].idx), valueGenerators.regularColumnGen(regularIdxRelations[i].column).descriptorAt(regularIdxRelations[i].idx),
regularIdxRelations[i].column); regularIdxRelations[i].column);
@ -479,7 +479,7 @@ class SingleOperationVisitBuilder implements SingleOperationBuilder
Relations.Relation[] staticRelations = new Relations.Relation[staticIdxRelations.length]; Relations.Relation[] staticRelations = new Relations.Relation[staticIdxRelations.length];
for (int i = 0; i < staticRelations.length; i++) for (int i = 0; i < staticRelations.length; i++)
{ {
Invariants.checkState(staticIdxRelations[i].column < valueGenerators.staticColumnCount()); Invariants.require(staticIdxRelations[i].column < valueGenerators.staticColumnCount());
staticRelations[i] = new Relations.Relation(staticIdxRelations[i].kind, staticRelations[i] = new Relations.Relation(staticIdxRelations[i].kind,
valueGenerators.staticColumnGen(staticIdxRelations[i].column).descriptorAt(staticIdxRelations[i].idx), valueGenerators.staticColumnGen(staticIdxRelations[i].column).descriptorAt(staticIdxRelations[i].idx),
staticIdxRelations[i].column); staticIdxRelations[i].column);

View File

@ -54,7 +54,7 @@ public class CQLTesterVisitExecutor extends CQLVisitExecutor
{ {
List<ResultSetRow> actual = new ArrayList<>(); List<ResultSetRow> actual = new ArrayList<>();
// TODO: Have never tested with multiple // TODO: Have never tested with multiple
Invariants.checkState(visit.operations.length == 1); Invariants.require(visit.operations.length == 1);
for (UntypedResultSet.Row row : execute.apply(statement)) for (UntypedResultSet.Row row : execute.apply(statement))
actual.add(resultSetToRow(schema, (Operations.SelectStatement) visit.operations[0], row)); actual.add(resultSetToRow(schema, (Operations.SelectStatement) visit.operations[0], row));
return actual; return actual;
@ -99,7 +99,7 @@ public class CQLTesterVisitExecutor extends CQLVisitExecutor
{ {
for (int j = 0; j < schema.clusteringKeys.size(); j++) for (int j = 0; j < schema.clusteringKeys.size(); j++)
{ {
Invariants.checkState(!row.has(schema.clusteringKeys.get(j).name), Invariants.require(!row.has(schema.clusteringKeys.get(j).name),
"All elements of clustering key should have been null"); "All elements of clustering key should have been null");
} }
clusteringKey = NIL_KEY; clusteringKey = NIL_KEY;

View File

@ -139,7 +139,7 @@ public abstract class CQLVisitExecutor
// All operations are not touching any data // All operations are not touching any data
if (compiledStatement == null) if (compiledStatement == null)
{ {
Invariants.checkArgument(Arrays.stream(visit.operations).allMatch(op -> op.kind() == Operations.Kind.CUSTOM)); Invariants.requireArgument(Arrays.stream(visit.operations).allMatch(op -> op.kind() == Operations.Kind.CUSTOM));
return; return;
} }
@ -150,7 +150,7 @@ public abstract class CQLVisitExecutor
} }
else else
{ {
Invariants.checkState(selects.size() == 1); Invariants.require(selects.size() == 1);
executeValidatingVisit(visit, selects, compiledStatement); executeValidatingVisit(visit, selects, compiledStatement);
} }
dataTracker.end(visit); dataTracker.end(visit);

View File

@ -69,7 +69,7 @@ public interface DataTracker
public void begin(Visit visit) public void begin(Visit visit)
{ {
long prev = started.get(); long prev = started.get();
Invariants.checkState(prev == 0 || visit.lts == (prev + 1)); Invariants.require(prev == 0 || visit.lts == (prev + 1));
started.set(visit.lts); started.set(visit.lts);
for (int i = 0; i < visit.operations.length; i++) for (int i = 0; i < visit.operations.length; i++)
{ {
@ -88,7 +88,7 @@ public interface DataTracker
public void end(Visit visit) public void end(Visit visit)
{ {
long current = started.get(); long current = started.get();
Invariants.checkState(current == visit.lts, "Current stated %d, current visit: %d", current, visit.lts); Invariants.require(current == visit.lts, "Current stated %d, current visit: %d", current, visit.lts);
finished.set(visit.lts); finished.set(visit.lts);
} }

View File

@ -103,7 +103,7 @@ public class InJvmDTestVisitExecutor extends CQLVisitExecutor
protected List<ResultSetRow> executeWithResult(Visit visit, int node, int pageSize, CompiledStatement statement, ConsistencyLevel consistencyLevel) protected List<ResultSetRow> executeWithResult(Visit visit, int node, int pageSize, CompiledStatement statement, ConsistencyLevel consistencyLevel)
{ {
Invariants.checkState(visit.operations.length == 1); Invariants.require(visit.operations.length == 1);
Object[][] rows; Object[][] rows;
if (consistencyLevel == ConsistencyLevel.NODE_LOCAL) if (consistencyLevel == ConsistencyLevel.NODE_LOCAL)
rows = cluster.get(node).executeInternal(statement.cql(), statement.bindings()); rows = cluster.get(node).executeInternal(statement.cql(), statement.bindings());
@ -199,7 +199,7 @@ public class InJvmDTestVisitExecutor extends CQLVisitExecutor
{ {
for (int j = 0; j < schema.clusteringKeys.size(); j++) for (int j = 0; j < schema.clusteringKeys.size(); j++)
{ {
Invariants.checkState(result[selection.indexOf(schema.clusteringKeys.get(j))] == null, Invariants.require(result[selection.indexOf(schema.clusteringKeys.get(j))] == null,
"All elements of clustering key should have been null"); "All elements of clustering key should have been null");
} }
clusteringKey = NIL_KEY; clusteringKey = NIL_KEY;

View File

@ -72,7 +72,7 @@ public class QueryBuildingVisitExecutor extends VisitExecutor
return query; return query;
} }
Invariants.checkState(bindings.isEmpty() && visitedPds.isEmpty() && selects.isEmpty()); Invariants.require(bindings.isEmpty() && visitedPds.isEmpty() && selects.isEmpty());
return null; return null;
} }
@ -107,7 +107,7 @@ public class QueryBuildingVisitExecutor extends VisitExecutor
{ {
if (statements.isEmpty()) if (statements.isEmpty())
{ {
Invariants.checkState(bindings.isEmpty() && visitedPds.isEmpty() && selects.isEmpty()); Invariants.require(bindings.isEmpty() && visitedPds.isEmpty() && selects.isEmpty());
return; return;
} }

View File

@ -119,7 +119,7 @@ public class RingAwareInJvmDTestVisitExecutor extends InJvmDTestVisitExecutor
{ {
try try
{ {
Invariants.checkState(visit.visitedPartitions.size() == 1, Invariants.require(visit.visitedPartitions.size() == 1,
"Ring aware executor can only read and write one partition at a time"); "Ring aware executor can only read and write one partition at a time");
for (TokenPlacementModel.Replica replica : getReplicasFor(visit.visitedPartitions.iterator().next().longValue())) for (TokenPlacementModel.Replica replica : getReplicasFor(visit.visitedPartitions.iterator().next().longValue()))
{ {

View File

@ -282,7 +282,7 @@ public class Generators
{ {
T v = delegate.generate(rng); T v = delegate.generate(rng);
int hashCode = v.hashCode(); int hashCode = v.hashCode();
Invariants.checkState(hashCode != System.identityHashCode(v), "hashCode was not overridden for type %s", v.getClass()); Invariants.require(hashCode != System.identityHashCode(v), "hashCode was not overridden for type %s", v.getClass());
if (hashCodes.contains(hashCode)) if (hashCodes.contains(hashCode))
continue; continue;
hashCodes.add(hashCode); hashCodes.add(hashCode);

View File

@ -74,9 +74,9 @@ public class InvertibleGenerator<T> implements HistoryBuilder.IndexedBijection<T
Generator<T> gen, Generator<T> gen,
Comparator<T> comparator) Comparator<T> comparator)
{ {
Invariants.checkState(population > 0, Invariants.require(population > 0,
"Population should be strictly positive %d", population); "Population should be strictly positive %d", population);
Invariants.checkState(Long.compareUnsigned(typeEntropy, 0) > 0, Invariants.require(Long.compareUnsigned(typeEntropy, 0) > 0,
"Type entropy should be strictly positive, but was %d: %s", typeEntropy, gen); "Type entropy should be strictly positive, but was %d: %s", typeEntropy, gen);
// We can / will generate at most that many values // We can / will generate at most that many values
@ -101,7 +101,7 @@ public class InvertibleGenerator<T> implements HistoryBuilder.IndexedBijection<T
Object inflated = inflate(candidate); Object inflated = inflate(candidate);
int hash = ArrayUtils.hashCode(inflated); int hash = ArrayUtils.hashCode(inflated);
Invariants.checkState(hash != System.identityHashCode(inflated), "hashCode was not overridden for type %s", inflated.getClass()); Invariants.require(hash != System.identityHashCode(inflated), "hashCode was not overridden for type %s", inflated.getClass());
if (hashes.add(hash)) if (hashes.add(hash))
allocatedDescriptors.add(candidate); allocatedDescriptors.add(candidate);
@ -117,7 +117,7 @@ public class InvertibleGenerator<T> implements HistoryBuilder.IndexedBijection<T
for (int i = 1; i < allocatedDescriptors.size(); i++) for (int i = 1; i < allocatedDescriptors.size(); i++)
{ {
T current = inflate(allocatedDescriptors.get(i)); T current = inflate(allocatedDescriptors.get(i));
Invariants.checkState( comparator.compare(current, prev) > 0, Invariants.require( comparator.compare(current, prev) > 0,
() -> String.format("%s should be strictly after %s", prev, current)); () -> String.format("%s should be strictly after %s", prev, current));
} }
} }
@ -138,7 +138,7 @@ public class InvertibleGenerator<T> implements HistoryBuilder.IndexedBijection<T
@Override @Override
public T inflate(long descriptor) public T inflate(long descriptor)
{ {
Invariants.checkState(!MagicConstants.MAGIC_DESCRIPTOR_VALS.contains(descriptor), Invariants.require(!MagicConstants.MAGIC_DESCRIPTOR_VALS.contains(descriptor),
String.format("Should not be able to inflate %d, as it's magic value", descriptor)); String.format("Should not be able to inflate %d, as it's magic value", descriptor));
return SeedableEntropySource.computeWithSeed(descriptor, gen::generate); return SeedableEntropySource.computeWithSeed(descriptor, gen::generate);
} }
@ -158,13 +158,13 @@ public class InvertibleGenerator<T> implements HistoryBuilder.IndexedBijection<T
{ {
Object[] valueArr = (Object[]) value; Object[] valueArr = (Object[]) value;
Object[] expectedArr = (Object[]) expected; Object[] expectedArr = (Object[]) expected;
Invariants.checkState(comparator.compare((T) expected, value) != 0, Invariants.require(comparator.compare((T) expected, value) != 0,
"%s was found: %s", Arrays.toString(expectedArr), Arrays.toString(valueArr)); "%s was found: %s", Arrays.toString(expectedArr), Arrays.toString(valueArr));
} }
else else
{ {
Invariants.checkState(comparator.compare((T) expected, value) != 0, Invariants.require(comparator.compare((T) expected, value) != 0,
"%s was found: %s", expected, value); "%s was found: %s", expected, value);
} }
@ -179,13 +179,13 @@ public class InvertibleGenerator<T> implements HistoryBuilder.IndexedBijection<T
Object[] valueArr = (Object[]) value; Object[] valueArr = (Object[]) value;
Object[] expectedArr = (Object[]) expected; Object[] expectedArr = (Object[]) expected;
Invariants.checkState(comparator.compare((T) expected, value) == 0, Invariants.require(comparator.compare((T) expected, value) == 0,
"%s != %s", Arrays.toString(expectedArr), Arrays.toString(valueArr)); "%s != %s", Arrays.toString(expectedArr), Arrays.toString(valueArr));
} }
else else
{ {
Invariants.checkState(comparator.compare((T) expected, value) == 0, Invariants.require(comparator.compare((T) expected, value) == 0,
"%s != %s", expected, value); "%s != %s", expected, value);
} }

View File

@ -191,7 +191,7 @@ public class QuiescentChecker implements Model
public static boolean vdsEqual(long[] expected, long[] actual) public static boolean vdsEqual(long[] expected, long[] actual)
{ {
Invariants.checkState(expected.length == actual.length); Invariants.require(expected.length == actual.length);
for (int i = 0; i < actual.length; i++) for (int i = 0; i < actual.length; i++)
{ {
long expectedD = expected[i]; long expectedD = expected[i];

View File

@ -471,7 +471,7 @@ public class Operations
} }
else else
{ {
Invariants.checkState(schema.allColumnInSelectOrder.size() == bitSet.size()); Invariants.require(schema.allColumnInSelectOrder.size() == bitSet.size());
Map<ColumnSpec<?>, Integer> columns = new HashMap<>(); Map<ColumnSpec<?>, Integer> columns = new HashMap<>();
for (int i = 0; i < schema.allColumnInSelectOrder.size(); i++) for (int i = 0; i < schema.allColumnInSelectOrder.size(); i++)
{ {

View File

@ -52,7 +52,7 @@ public class SimpleBijectionTest
Object next = generator.inflate(generator.descriptorAt(i)); Object next = generator.inflate(generator.descriptorAt(i));
if (previous != null) if (previous != null)
{ {
Invariants.checkState(column.type.comparator().compare(next, previous) > 0, Invariants.require(column.type.comparator().compare(next, previous) > 0,
"%s should be > %s", next, previous); "%s should be > %s", next, previous);
} }
previous = next; previous = next;

View File

@ -26,7 +26,7 @@ public class RunStartDefiner extends PropertyDefinerBase
{ {
static static
{ {
Invariants.checkState(CassandraRelevantProperties.SIMULATOR_STARTED.getString() != null); Invariants.require(CassandraRelevantProperties.SIMULATOR_STARTED.getString() != null);
} }
@Override @Override

View File

@ -757,7 +757,7 @@ public class HarrySimulatorTest
Visit visit = new Visit(lts, new Operations.Operation[]{ simulation.insertGen.generate(simulation.rng).toOp(lts) }); Visit visit = new Visit(lts, new Operations.Operation[]{ simulation.insertGen.generate(simulation.rng).toOp(lts) });
Visit prev_ = simulation.log.put(lts, visit); Visit prev_ = simulation.log.put(lts, visit);
Invariants.checkState(prev_ == null); Invariants.require(prev_ == null);
actions[i] = new Actions.LambdaAction("", Action.Modifiers.RELIABLE_NO_TIMEOUTS, () -> { actions[i] = new Actions.LambdaAction("", Action.Modifiers.RELIABLE_NO_TIMEOUTS, () -> {
CompiledStatement compiledStatement = simulation.queryBuilder.compile(visit); CompiledStatement compiledStatement = simulation.queryBuilder.compile(visit);

View File

@ -79,8 +79,8 @@ public class HarryValidatingQuery extends SimulatedAction
try try
{ {
TokenPlacementModel.ReplicatedRanges ring = rf.replicate(owernship); TokenPlacementModel.ReplicatedRanges ring = rf.replicate(owernship);
Invariants.checkState(visit.operations.length == 1); Invariants.require(visit.operations.length == 1);
Invariants.checkState(visit.operations[0] instanceof Operations.SelectStatement); Invariants.require(visit.operations[0] instanceof Operations.SelectStatement);
Operations.SelectStatement select = (Operations.SelectStatement) visit.operations[0]; Operations.SelectStatement select = (Operations.SelectStatement) visit.operations[0];
for (TokenPlacementModel.Replica replica : ring.replicasFor(token(select.pd))) for (TokenPlacementModel.Replica replica : ring.replicasFor(token(select.pd)))
{ {

View File

@ -110,7 +110,7 @@ public class ManualExecutor implements ExecutorPlus
Task(Runnable runnable, Callable<?> callable, WithResources withResources, Object result, FutureImpl<?> future) Task(Runnable runnable, Callable<?> callable, WithResources withResources, Object result, FutureImpl<?> future)
{ {
Invariants.checkArgument(runnable != null ^ callable != null); Invariants.requireArgument(runnable != null ^ callable != null);
this.runnable = runnable; this.runnable = runnable;
this.callable = callable; this.callable = callable;

View File

@ -92,7 +92,7 @@ public interface Visitor
public static CompositeVisitor of(List<Visitor> visitors) public static CompositeVisitor of(List<Visitor> visitors)
{ {
Invariants.checkArgument(!visitors.isEmpty(), "Visitors may not be empty"); Invariants.requireArgument(!visitors.isEmpty(), "Visitors may not be empty");
if (Stream.of(visitors).noneMatch(v -> v instanceof CompositeVisitor)) if (Stream.of(visitors).noneMatch(v -> v instanceof CompositeVisitor))
return new CompositeVisitor(visitors); return new CompositeVisitor(visitors);

View File

@ -218,7 +218,7 @@ public class IndexTest
for (long i : value) for (long i : value)
inMemory.update(key, Index.readOffset(i), Index.readSize(i)); inMemory.update(key, Index.readOffset(i), Index.readSize(i));
for (int i = 1 ; i < value.length ; ++i) for (int i = 1 ; i < value.length ; ++i)
Invariants.checkState(value[i - 1] > value[i]); Invariants.require(value[i - 1] > value[i]);
} }
assertIndex(map, inMemory); assertIndex(map, inMemory);

View File

@ -336,7 +336,7 @@ public class EpochSyncTest
if (cms.metadata().inProgressSequences.isEmpty()) if (cms.metadata().inProgressSequences.isEmpty())
throw new IllegalStateException("Attempted to bump epoch when nothing was pending"); throw new IllegalStateException("Attempted to bump epoch when nothing was pending");
Iterator<MultiStepOperation<?>> it = cms.metadata().inProgressSequences.iterator(); Iterator<MultiStepOperation<?>> it = cms.metadata().inProgressSequences.iterator();
Invariants.checkState(it.hasNext()); Invariants.require(it.hasNext());
notify(process(it.next()).metadata); notify(process(it.next()).metadata);
} }
@ -562,8 +562,8 @@ public class EpochSyncTest
void registerNode(Node.Id id, long token) void registerNode(Node.Id id, long token)
{ {
Invariants.checkState(!tokens.contains(token), "Attempted to add token %d for node %s but token is already taken", token, id); Invariants.require(!tokens.contains(token), "Attempted to add token %d for node %s but token is already taken", token, id);
Invariants.checkState(!instances.containsKey(id), "Attempted to add node %s; but already exists", id); Invariants.require(!instances.containsKey(id), "Attempted to add node %s; but already exists", id);
ClusterMetadata.Transformer builder = cms.metadata().transformer(); ClusterMetadata.Transformer builder = cms.metadata().transformer();
@ -598,7 +598,7 @@ public class EpochSyncTest
void removeNode(Node.Id pick) void removeNode(Node.Id pick)
{ {
Instance inst = Objects.requireNonNull(instances.get(pick), "Unknown id " + pick); Instance inst = Objects.requireNonNull(instances.get(pick), "Unknown id " + pick);
Invariants.checkState(!removed.contains(pick), "Can not remove node twice; node " + pick); Invariants.require(!removed.contains(pick), "Can not remove node twice; node " + pick);
removed.add(pick); removed.add(pick);
inst.status = Status.Leaving; inst.status = Status.Leaving;
PrepareLeave prepareLeave = new PrepareLeave(new NodeId(pick.id), false, new UniformRangePlacement(), LeaveStreams.Kind.REMOVENODE); PrepareLeave prepareLeave = new PrepareLeave(new NodeId(pick.id), false, new UniformRangePlacement(), LeaveStreams.Kind.REMOVENODE);
@ -747,19 +747,19 @@ public class EpochSyncTest
switch (status) switch (status)
{ {
case Init: case Init:
Invariants.checkState(!t.nodes().contains(id), "Node was in Init state but present in the Topology!"); Invariants.require(!t.nodes().contains(id), "Node was in Init state but present in the Topology!");
Invariants.checkState(current.directory.peerId(address(id)) != null, "Node exists but not in TCM"); Invariants.require(current.directory.peerId(address(id)) != null, "Node exists but not in TCM");
start(); start();
status = Status.Registered; status = Status.Registered;
break; break;
case Registered: case Registered:
Invariants.checkState(!t.nodes().contains(id), "Node was in Init state but present in the Topology!"); Invariants.require(!t.nodes().contains(id), "Node was in Init state but present in the Topology!");
Invariants.checkState(current.directory.peerId(address(id)) != null, "Node exists but not in TCM"); Invariants.require(current.directory.peerId(address(id)) != null, "Node exists but not in TCM");
if (current.placements.get(replication_params).writes.byEndpoint().keySet().contains(address(id))) if (current.placements.get(replication_params).writes.byEndpoint().keySet().contains(address(id)))
status = Status.Joining; status = Status.Joining;
break; break;
case Joining: case Joining:
Invariants.checkState(current.directory.peerId(address(id)) != null, "Node exists but not in TCM"); Invariants.require(current.directory.peerId(address(id)) != null, "Node exists but not in TCM");
if (joined(current, id)) if (joined(current, id))
status = Status.Joined; status = Status.Joined;
case Removed: case Removed:

View File

@ -87,7 +87,7 @@ public enum MockDiskStateManager implements AccordConfigurationService.DiskState
{ {
if (diskState.isEmpty()) if (diskState.isEmpty())
return AccordKeyspace.EpochDiskState.create(epoch); return AccordKeyspace.EpochDiskState.create(epoch);
Invariants.checkArgument(epoch >= diskState.minEpoch, "Epoch %d < %d (min)", epoch, diskState.minEpoch); Invariants.requireArgument(epoch >= diskState.minEpoch, "Epoch %d < %d (min)", epoch, diskState.minEpoch);
if (epoch > diskState.maxEpoch) if (epoch > diskState.maxEpoch)
diskState = diskState.withNewMaxEpoch(epoch); diskState = diskState.withNewMaxEpoch(epoch);
return diskState; return diskState;

View File

@ -351,7 +351,7 @@ public abstract class SimulatedAccordCommandStoreTestBase extends CQLTester
protected static Gen<Pair<Txn, FullRoute<?>>> randomTxn(Gen<Routable.Domain> domainGen, Gen.LongGen tokenGen) protected static Gen<Pair<Txn, FullRoute<?>>> randomTxn(Gen<Routable.Domain> domainGen, Gen.LongGen tokenGen)
{ {
TableMetadata tbl = reverseTokenTbl; TableMetadata tbl = reverseTokenTbl;
Invariants.checkArgument(tbl.partitioner == Murmur3Partitioner.instance, "Only murmur partitioner is supported; given %s", tbl.partitioner.getClass()); Invariants.requireArgument(tbl.partitioner == Murmur3Partitioner.instance, "Only murmur partitioner is supported; given %s", tbl.partitioner.getClass());
Gen<PartitionKey> keyGen = rs -> new PartitionKey(tbl.id, tbl.partitioner.decorateKey(Murmur3Partitioner.LongToken.keyForToken(tokenGen.nextLong(rs)))); Gen<PartitionKey> keyGen = rs -> new PartitionKey(tbl.id, tbl.partitioner.decorateKey(Murmur3Partitioner.LongToken.keyForToken(tokenGen.nextLong(rs))));
Gen<Range> rangeGen = rs -> { Gen<Range> rangeGen = rs -> {
long a = tokenGen.nextLong(rs); long a = tokenGen.nextLong(rs);

View File

@ -253,7 +253,7 @@ public class SimulatedMiniCluster
if (current.inProgressSequences.isEmpty()) if (current.inProgressSequences.isEmpty())
throw new IllegalStateException("Attempted to bump epoch when nothing was pending"); throw new IllegalStateException("Attempted to bump epoch when nothing was pending");
Iterator<MultiStepOperation<?>> it = current.inProgressSequences.iterator(); Iterator<MultiStepOperation<?>> it = current.inProgressSequences.iterator();
Invariants.checkState(it.hasNext()); Invariants.require(it.hasNext());
notifyMetadataChange(process(it.next()).metadata); notifyMetadataChange(process(it.next()).metadata);
} }