You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by "belliottsmith (via GitHub)" <gi...@apache.org> on 2024/11/04 09:55:25 UTC

[PR] Accord: Improved work queueing and execution [cassandra]

belliottsmith opened a new pull request, #3651:
URL: https://github.com/apache/cassandra/pull/3651

   - Work can now be cancelled, and commands serving remote requests now cancel queued work if they time out. This prevents run-away work growth, as work does not outlive its useful lifespan.
   - Accord state reads can be scheduled and completed from any thread, so that we do not incur multiple queue delays when preparing work for the command store
   - Work is scheduled by first arrival time, not by read completion time - work that is slow to read jumps the queue once data is in memory to serve it, to reduce latency variability
   - Some operations may now partially execute without waiting for all state to be brought into memory
   
   CommandStores, threads and caches are now only loosely coupled, with it possible to independently tune: 
   - the total number of threads
   - the number of work queue/cache units we distribute the threads amongst
   - the number of CommandStores per table/shard (which are distributed between queue/cache units, the threads of which will execute CommandStore work)
   
   Mutual exclusivity is managed separately for the queue/cache unit and each CommandStore, and the locks are held only for as long as necessary so we can have multiple threads servicing the same CommandStore(s). Given this threading model, it is now possible for Accord threads to perform all of the loading/saving work, reducing the queueing delay and context switching costs - and this is also configurable. The default configuration is now to do this work on the Accord work pool (as already the case with Paxos for most IO).
   
   There are further improvements that can be made here to permit the event loop to answer in-cache queries, and under a future async-io model to directly submit read requests.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "ifesdjeen (via GitHub)" <gi...@apache.org>.
ifesdjeen commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1830720345


##########
src/java/org/apache/cassandra/service/accord/AccordCachingState.java:
##########
@@ -184,61 +176,164 @@ protected State<K, V> state()
         return state;
     }
 
-    public AsyncChain<V> loading()
+    public void readyToLoad()
+    {
+        state(state.readyToLoad());
+    }
+
+    public LoadingOrWaiting<K, V> loadingOrWaiting()
+    {
+        return state.loadingOrWaiting();
+    }
+
+    void notifyListeners(BiConsumer<AccordStateCache.Listener<K, V>, AccordCachingState<K, V>> notify)
+    {
+        owner.notifyListeners(notify, this);
+    }
+
+    public interface OnLoaded
+    {
+        <K, V> void onLoaded(AccordCachingState<K, V> state, V value, Throwable fail);
+
+        static OnLoaded immediate()

Review Comment:
   Looks like this one is only used in tests; should we move it to the test package? In prod code, we might want to avoid an allocation when we do not have to load. But there's no precedent as of now.



##########
src/java/org/apache/cassandra/config/AccordSpec.java:
##########
@@ -35,18 +37,71 @@ public class AccordSpec
 
     public volatile boolean enable_journal_compaction = true;
 
-    public volatile OptionaldPositiveInt shard_count = OptionaldPositiveInt.UNDEFINED;
+    public enum QueueShardModel
+    {
+        /**
+         * Same number of threads as queue shards, but the shard lock is held only while managing the queue,
+         * so that submitting threads may queue load/save work.
+         *
+         * The global READ and WRITE stages are used for IO.
+         */
+        THREAD_PER_SHARD,
+
+        /**
+         * Same number of threads as shards, and the shard lock is held for the duration of serving requests.
+         * The global READ and WRITE stages are used for IO.
+         */
+        THREAD_PER_SHARD_SYNC_QUEUE,
+
+        /**
+         * More threads than shards. Threads update transaction state as well as performing IO, minimising context switching.
+         * Fewer shards is generally better, until queue-contention is encountered.
+         */
+        THREAD_POOL_PER_SHARD,
+
+        /**
+         * More threads than shards. Threads update transaction state only, relying on READ and WRITE stages for IO.
+         * Fewer shards is generally better, until queue-contention is encountered.
+         */
+        THREAD_POOL_PER_SHARD_EXCLUDES_IO,
+    }
+
+    public enum QueueSubmissionModel
+    {
+        SYNC, SEMI_SYNC, ASYNC

Review Comment:
   Could you add docs here similar to the above? I think sync and async are more or less clear, semi sync is less so. 
   



##########
src/java/org/apache/cassandra/service/accord/AccordTask.java:
##########
@@ -0,0 +1,880 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.service.accord;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandStore;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommandStore;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.AbstractRanges;
+import accord.primitives.AbstractUnseekableKeys;
+import accord.primitives.Range;
+import accord.primitives.Ranges;
+import accord.primitives.TxnId;
+import accord.primitives.Unseekables;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChain;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.Cancellable;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.agrona.collections.ObjectHashSet;
+import org.apache.cassandra.service.accord.AccordCachingState.Status;
+import org.apache.cassandra.service.accord.AccordCommandStore.Caches;
+import org.apache.cassandra.service.accord.AccordExecutor.TaskQueue;
+import org.apache.cassandra.service.accord.api.AccordRoutingKey;
+import org.apache.cassandra.utils.NoSpamLogger;
+import org.apache.cassandra.utils.concurrent.Condition;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.config.CassandraRelevantProperties.DTEST_ACCORD_JOURNAL_SANITY_CHECK_ENABLED;
+import static org.apache.cassandra.service.accord.AccordTask.State.CANCELLED;
+import static org.apache.cassandra.service.accord.AccordTask.State.FAILED;
+import static org.apache.cassandra.service.accord.AccordTask.State.FINISHED;
+import static org.apache.cassandra.service.accord.AccordTask.State.INITIALIZED;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.PERSISTING;
+import static org.apache.cassandra.service.accord.AccordTask.State.RUNNING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_SCAN_RANGES;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordTask<R> extends AccordExecutor.Task implements Runnable, Function<SafeCommandStore, R>, Cancellable
+{
+    private static final Logger logger = LoggerFactory.getLogger(AccordTask.class);
+    private static final NoSpamLogger noSpamLogger = NoSpamLogger.getLogger(logger, 1, TimeUnit.MINUTES);
+    private static final boolean SANITY_CHECK = DTEST_ACCORD_JOURNAL_SANITY_CHECK_ENABLED.getBoolean();
+
+    private static class LoggingProps
+    {
+        private static final String COMMAND_STORE = "command_store";
+        private static final String ACCORD_TASK = "accord_task";
+    }
+
+    static class ForFunction<R> extends AccordTask<R>
+    {
+        private final Function<? super SafeCommandStore, R> function;
+
+        public ForFunction(AccordCommandStore commandStore, PreLoadContext loadCtx, Function<? super SafeCommandStore, R> function)
+        {
+            super(commandStore, loadCtx);
+            this.function = function;
+        }
+
+        @Override
+        public R apply(SafeCommandStore commandStore)
+        {
+            return function.apply(commandStore);
+        }
+    }
+
+    // TODO (desired): these anonymous ops are somewhat tricky to debug. We may want to at least give them names.
+    static class ForConsumer extends AccordTask<Void>
+    {
+        private final Consumer<? super SafeCommandStore> consumer;
+
+        public ForConsumer(AccordCommandStore commandStore, PreLoadContext loadCtx, Consumer<? super SafeCommandStore> consumer)
+        {
+            super(commandStore, loadCtx);
+            this.consumer = consumer;
+        }
+
+        @Override
+        public Void apply(SafeCommandStore commandStore)
+        {
+            consumer.accept(commandStore);
+            return null;
+        }
+    }
+
+    public static <T> AccordTask<T> create(CommandStore commandStore, PreLoadContext ctx, Function<? super SafeCommandStore, T> function)
+    {
+        return new ForFunction<>((AccordCommandStore) commandStore, ctx, function);
+    }
+
+    public static AccordTask<Void> create(CommandStore commandStore, PreLoadContext ctx, Consumer<? super SafeCommandStore> consumer)
+    {
+        return new ForConsumer((AccordCommandStore) commandStore, ctx, consumer);
+    }
+
+    public enum State
+    {
+        INITIALIZED(),
+        WAITING_TO_SCAN_RANGES(INITIALIZED),
+        SCANNING_RANGES(WAITING_TO_SCAN_RANGES),
+        WAITING_TO_LOAD(INITIALIZED, SCANNING_RANGES),
+        LOADING(INITIALIZED, SCANNING_RANGES, WAITING_TO_LOAD),
+        WAITING_TO_RUN(INITIALIZED, SCANNING_RANGES, WAITING_TO_LOAD, LOADING),
+        RUNNING(WAITING_TO_RUN),
+        PERSISTING(RUNNING),
+        FINISHED(RUNNING, PERSISTING),
+        CANCELLED(WAITING_TO_SCAN_RANGES, SCANNING_RANGES, WAITING_TO_LOAD, LOADING, WAITING_TO_RUN),
+        FAILED(WAITING_TO_SCAN_RANGES, SCANNING_RANGES, WAITING_TO_LOAD, LOADING, WAITING_TO_RUN, RUNNING, PERSISTING);
+
+        private final int permittedFrom;
+
+        State()
+        {
+            this.permittedFrom = 0;
+        }
+
+        State(State ... permittedFroms)
+        {
+            int permittedFrom = 0;
+            for (State state : permittedFroms)
+                permittedFrom |= 1 << state.ordinal();
+            this.permittedFrom = permittedFrom;
+        }
+
+        boolean isPermittedFrom(State prev)
+        {
+            return (permittedFrom & (1 << prev.ordinal())) != 0;
+        }
+
+        boolean isExecuted()
+        {
+            return this.compareTo(PERSISTING) >= 0;
+        }
+
+        boolean isComplete()
+        {
+            return this.compareTo(FINISHED) >= 0;
+        }
+    }
+
+    private State state = INITIALIZED;
+    private final PreLoadContext preLoadContext;
+    private final String loggingId;
+
+    @Nullable Object2ObjectHashMap<TxnId, AccordSafeCommand> commands;

Review Comment:
   nit: worth to limit to `Map` here? We are not using any special APIs from argona, too



##########
src/java/org/apache/cassandra/service/accord/AccordCommandStore.java:
##########
@@ -248,12 +203,13 @@ public void markShardDurable(SafeCommandStore safeStore, TxnId globalSyncId, Ran
     {
         store.snapshot(ranges, globalSyncId);
         super.markShardDurable(safeStore, globalSyncId, ranges);
+        commandsForRangesLoader.gcBefore(globalSyncId, ranges);
     }
 
     @Override
     public boolean inStore()
     {
-        return executor.isInThread();
+        return currentThread == Thread.currentThread();
     }
 
     public void checkInStoreThread()

Review Comment:
   Looks like these aren't used anymore.



##########
test/distributed/org/apache/cassandra/distributed/test/accord/AccordLoadTest.java:
##########
@@ -98,17 +98,17 @@ public boolean matches(int i, int i1, IMessage iMessage)
                      ICoordinator coordinator = cluster.coordinator(1);
                      final int repairInterval = Integer.MAX_VALUE;
     //                 final int repairInterval = 3000;
-//                     final int compactionInterval = Integer.MAX_VALUE;
-                     final int compactionInterval = 3000;
-//                     final int flushInterval = Integer.MAX_VALUE;
-                     final int flushInterval = 1000;
+                     final int compactionInterval = Integer.MAX_VALUE;
+//                     final int compactionInterval = 3000;

Review Comment:
   Is it intended to reduce these here?



##########
src/java/org/apache/cassandra/service/accord/AccordExecutorTest.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+
+import accord.api.Agent;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Stage;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+
+import static org.apache.cassandra.concurrent.ExecutorFactory.Global.executorFactory;
+
+// TODO (expected): move to test package

Review Comment:
   looks like we can just move it, really, or?



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)

Review Comment:
   on closer inspection; we have another nested while loop below which can change this count.



##########
src/java/org/apache/cassandra/service/accord/CommandsForRangesLoader.java:
##########
@@ -82,293 +84,217 @@ public void onEvict(AccordCachingState<TxnId, Command> state)
             cachedRangeTxns.remove(txnId);
     }
 
-    public AsyncResult<Pair<Watcher, NavigableMap<TxnId, Summary>>> get(@Nullable TxnId primaryTxnId, KeyHistory keyHistory, Ranges ranges)
+    public Loader loader(@Nullable TxnId primaryTxnId, KeyHistory keyHistory, Ranges ranges)
     {
-        RedundantBefore redundantBefore = store.unsafeGetRedundantBefore();
-        TxnId minTxnId = redundantBefore.minGcBefore(ranges);
-        Timestamp maxTxnId = primaryTxnId == null || keyHistory == KeyHistory.RECOVERY || !primaryTxnId.is(ExclusiveSyncPoint) ? Timestamp.MAX : primaryTxnId;
-        TxnId findAsDep = primaryTxnId != null && keyHistory == KeyHistory.RECOVERY ? primaryTxnId : null;
-        var watcher = fromCache(findAsDep, ranges, minTxnId, maxTxnId, redundantBefore);
-        var before = ImmutableMap.copyOf(watcher.get());
-        return AsyncChains.ofCallable(Stage.ACCORD_RANGE_LOADER.executor(), () -> get(ranges, before, findAsDep, minTxnId, maxTxnId, redundantBefore))
-                          .map(map -> Pair.create(watcher, map), store)
-               .beginAsResult();
+        RedundantBefore redundantBefore = commandStore.unsafeGetRedundantBefore();
+        TxnId minTxnId = redundantBefore.min(ranges, e -> e.gcBefore);
+        Timestamp maxTxnId = primaryTxnId == null || keyHistory == KeyHistory.RECOVER || !primaryTxnId.is(ExclusiveSyncPoint) ? Timestamp.MAX : primaryTxnId;
+        TxnId findAsDep = primaryTxnId != null && keyHistory == KeyHistory.RECOVER ? primaryTxnId : null;
+        return new Loader(ranges, redundantBefore, minTxnId, maxTxnId, findAsDep);
     }
 
-    private NavigableMap<TxnId, Summary> get(Ranges ranges, Map<TxnId, Summary> cacheHits, @Nullable TxnId findAsDep, TxnId minTxnId, Timestamp maxTxnId, RedundantBefore redundantBefore)
+    public void mergeTransitive(TxnId txnId, Ranges ranges, BiFunction<? super Ranges, ? super Ranges, ? extends Ranges> remappingFunction)
     {
-        Set<TxnId> matches = new ObjectHashSet<>();
-        for (Range range : ranges)
-            matches.addAll(intersects(range, minTxnId, maxTxnId));
-        if (matches.isEmpty())
-            return new TreeMap<>();
-        return load(ranges, cacheHits, matches, findAsDep, redundantBefore);
+        transitive.merge(txnId, ranges, remappingFunction);
     }
 
-    private Collection<TxnId> intersects(Range range, TxnId minTxnId, Timestamp maxTxnId)
+    public void gcBefore(TxnId gcBefore, Ranges ranges)
     {
-        assert range instanceof TokenRange : "Require TokenRange but given " + range.getClass();
-        Set<TxnId> intersects = searcher.intersects(store.id(), (TokenRange) range, minTxnId, maxTxnId);
-        if (!historicalTransaction.isEmpty())
+        Iterator<Map.Entry<TxnId, Ranges>> iterator = transitive.headMap(gcBefore).entrySet().iterator();
+        while (iterator.hasNext())
         {
-            if (intersects.isEmpty())
-                intersects = new ObjectHashSet<>();
-            for (var e : historicalTransaction.tailMap(minTxnId, true).entrySet())
-            {
-                if (e.getValue().intersects(range))
-                    intersects.add(e.getKey());
-            }
-            if (intersects.isEmpty())
-                intersects = Collections.emptySet();
+            Map.Entry<TxnId, Ranges> e = iterator.next();
+            Ranges newRanges = e.getValue().without(ranges);
+            if (newRanges.isEmpty())
+                iterator.remove();
+            e.setValue(newRanges);
         }
-        return intersects;
     }
 
-    public class Watcher implements AccordStateCache.Listener<TxnId, Command>, AutoCloseable
+    public static class Summary
     {
-        private final Ranges ranges;
-        private final @Nullable TxnId findAsDep;
-        private final TxnId minTxnId;
-        private final Timestamp maxTxnId;
-        private final RedundantBefore redundantBefore;
+        public final TxnId txnId;
+        @Nullable public final Timestamp executeAt;
+        @Nullable public final SaveStatus saveStatus;
+        @Nullable public final Ranges ranges;
 
-        private NavigableMap<TxnId, Summary> summaries = null;
-        private Set<AccordCachingState<TxnId, Command>> needToDoubleCheck = null;
+        // TODO (required): this logic is still broken (was already): needs to consider exact range matches
+        public final TxnId findAsDep;
+        public final boolean hasAsDep;
 
-        public Watcher(Ranges ranges, @Nullable TxnId findAsDep, TxnId minTxnId, Timestamp maxTxnId, RedundantBefore redundantBefore)
+        @VisibleForTesting
+        Summary(TxnId txnId, @Nullable Timestamp executeAt, SaveStatus saveStatus, Ranges ranges, TxnId findAsDep, boolean hasAsDep)
         {
+            this.txnId = txnId;
+            this.executeAt = executeAt;
+            this.saveStatus = saveStatus;
             this.ranges = ranges;
             this.findAsDep = findAsDep;
-            this.minTxnId = minTxnId;
-            this.maxTxnId = maxTxnId;
-            this.redundantBefore = redundantBefore;
+            this.hasAsDep = hasAsDep;
         }
 
-        public NavigableMap<TxnId, Summary> get()
+        public Summary slice(Ranges slice)
         {
-            return summaries == null ? Collections.emptyNavigableMap() : summaries;
+            return new Summary(txnId, executeAt, saveStatus, ranges == null ? null : ranges.slice(slice, Minimal), findAsDep, hasAsDep);
         }
 
         @Override
-        public void onAdd(AccordCachingState<TxnId, Command> n)
+        public String toString()
+        {
+            return "Summary{" +
+                   "txnId=" + txnId +
+                   ", executeAt=" + executeAt +
+                   ", saveStatus=" + saveStatus +
+                   ", ranges=" + ranges +
+                   ", findAsDep=" + findAsDep +
+                   ", hasAsDep=" + hasAsDep +
+                   '}';
+        }
+    }
+
+    public class Loader
+    {
+        final Ranges searchRanges;
+        final RedundantBefore redundantBefore;
+        final TxnId minTxnId;
+        final Timestamp maxTxnId;
+        @Nullable final TxnId findAsDep;
+
+        public Loader(Ranges searchRanges, RedundantBefore redundantBefore, TxnId minTxnId, Timestamp maxTxnId, @Nullable TxnId findAsDep)
         {
-            if (n.key().domain() != Domain.Range)
-                return;
-            if (n.key().compareTo(minTxnId) < 0 || n.key().compareTo(maxTxnId) >= 0)
-                return;
+            this.searchRanges = searchRanges;
+            this.redundantBefore = redundantBefore;
+            this.minTxnId = minTxnId;
+            this.maxTxnId = maxTxnId;
+            this.findAsDep = findAsDep;
+        }
 
-            var state = n.state();
-            if (state instanceof AccordCachingState.Loading)
+        public Collection<TxnId> intersects()
+        {
+            ObjectHashSet<TxnId> txnIds = new ObjectHashSet<>();
+            for (Range range : searchRanges)
             {
-                if (needToDoubleCheck == null)
-                    needToDoubleCheck = new ObjectHashSet<>();
-                needToDoubleCheck.add(n);
-                return;
+                searcher.intersects(commandStore.id(), (TokenRange) range, minTxnId, maxTxnId, txnIds::add);
             }
-            //TODO (required): include FailedToSave?  Most likely need to, but need to improve test coverage to have failed writes
-            if (!(state instanceof AccordCachingState.Loaded
-                  || state instanceof AccordCachingState.Modified
-                  || state instanceof AccordCachingState.Saving))
-                return;
-
-            var cmd = state.get();
-            if (cmd == null)
-                return;
-            Summary summary = create(cmd, ranges, findAsDep, redundantBefore);
-            if (summary != null)
+            if (!transitive.isEmpty())
             {
-                if (summaries == null)
-                    summaries = new TreeMap<>();
-                summaries.put(summary.txnId, summary);
+                for (var e : transitive.tailMap(minTxnId, true).entrySet())
+                {
+                    if (e.getValue().intersects(searchRanges))
+                        txnIds.add(e.getKey());
+                }
             }
+            return txnIds;
         }
 
-        @Override
-        public void onEvict(AccordCachingState<TxnId, Command> state)
+        public void forEachInCache(Consumer<Summary> forEach, Caches caches)
         {
-            if (needToDoubleCheck == null)
-                return;
-            if (!needToDoubleCheck.remove(state))
-                return;
-            if (state.state() instanceof AccordCachingState.Loading)
-                return; // can't double check
-            onAdd(state);
-        }
-
-        @Override
-        public void close()
-        {
-            store.commandCache().unregister(this);
-            if (needToDoubleCheck != null)
+            for (TxnId txnId : cachedRangeTxns)
             {
-                var copy = needToDoubleCheck;
-                needToDoubleCheck = null;
-                copy.forEach(this::onAdd);
+                AccordCachingState<TxnId, Command> state = caches.commands().getUnsafe(txnId);
+                Summary summary = from(state);
+                if (summary != null)
+                    forEach.accept(summary);
             }
-            needToDoubleCheck = null;
         }
-    }
-
-    private Watcher fromCache(@Nullable TxnId findAsDep, Ranges ranges, TxnId minTxnId, Timestamp maxTxnId, RedundantBefore redundantBefore)
-    {
-        Watcher watcher = new Watcher(ranges, findAsDep, minTxnId, maxTxnId, redundantBefore);
-        for (TxnId rangeTxnId : cachedRangeTxns)
-            watcher.onAdd(store.commandCache().getUnsafe(rangeTxnId));
-        store.commandCache().register(watcher);
-        return watcher;
-    }
 
-    private NavigableMap<TxnId, Summary> load(Ranges ranges, Map<TxnId, Summary> cacheHits, Collection<TxnId> possibleTxns, @Nullable TxnId findAsDep, RedundantBefore redundantBefore)
-    {
-        //TODO (required): this logic is kinda duplicate of org.apache.cassandra.service.accord.CommandsForRange.mapReduce
-        // should figure out if this can be improved... also what is correct?
-        NavigableMap<TxnId, Summary> map = new TreeMap<>();
-        for (TxnId txnId : possibleTxns)
+        public Summary load(TxnId txnId)
         {
-            if (cacheHits.containsKey(txnId))
-                continue;
             if (findAsDep == null)
             {
-                var cmd = store.loadMinimal(txnId);
-                if (cmd == null)
-                    continue; // unknown command
-                var summary = create(cmd, ranges, redundantBefore);
-                if (summary == null)
-                    continue;
-                map.put(txnId, summary);
-
+                SavedCommand.MinimalCommand cmd = commandStore.loadMinimal(txnId);
+                return cmd == null ? null : from(cmd);
             }
             else
             {
-                var cmd = store.loadCommand(txnId);
-                if (cmd == null)
-                    continue; // unknown command
-                var summary = create(cmd, ranges, findAsDep, redundantBefore);
-                if (summary == null)
-                    continue;
-                map.put(txnId, summary);
+                Command cmd = commandStore.loadCommand(txnId);
+                return cmd == null ? null : from(cmd);
             }
         }
-        return map;
-    }
 
-    private static Summary create(Command cmd, Ranges cacheRanges, @Nullable TxnId findAsDep, @Nullable RedundantBefore redundantBefore)
-    {
-        //TODO (required, correctness): C* did Invalidated, accord-core did Erased... what is correct?
-        SaveStatus saveStatus = cmd.saveStatus();
-        if (saveStatus == SaveStatus.Invalidated
-            || saveStatus == SaveStatus.Erased
-            || !saveStatus.hasBeen(Status.PreAccepted))
-            return null;
-        if (cmd.partialTxn() == null)
-            return null;
-
-        var keysOrRanges = cmd.participants().touches().toRanges();
-        if (keysOrRanges.domain() != Domain.Range)
-            throw new AssertionError(String.format("Txn keys are not range for %s", cmd.partialTxn()));
-        Ranges ranges = (Ranges) keysOrRanges;
-
-        ranges = ranges.slice(cacheRanges, Routables.Slice.Minimal);
-        if (ranges.isEmpty())
-            return null;
-
-        if (redundantBefore != null)
+        public Summary from(AccordCachingState<TxnId, Command> state)
         {
-            Ranges newRanges = redundantBefore.foldlWithBounds(ranges, (e, accum, start, end) -> {
-                if (e.gcBefore.compareTo(cmd.txnId()) < 0)
-                    return accum;
-                return accum.without(Ranges.of(new TokenRange((AccordRoutingKey) start, (AccordRoutingKey) end)));
-            }, ranges, ignore -> false);
+            if (state.key().domain() != Domain.Range)
+                return null;
 
-            if (newRanges.isEmpty())
+            switch (state.status())
+            {
+                default: throw new AssertionError("Unhandled status: " + state.status());
+                case LOADING:
+                case WAITING_TO_LOAD:
+                case UNINITIALIZED:
+                    return null;
+
+                case LOADED:
+                case MODIFIED:
+                case SAVING:
+                case FAILED_TO_SAVE:
+            }
+
+            TxnId txnId = state.key();
+            if (txnId.compareTo(minTxnId) < 0 || txnId.compareTo(maxTxnId) >= 0)
                 return null;
+
+            Command command = state.get();
+            if (command == null)
+                return null;
+            return from(command);
         }
 
-        var partialDeps = cmd.partialDeps();
-        boolean hasAsDep = findAsDep != null && partialDeps != null && partialDeps.rangeDeps.intersects(findAsDep, ranges);
-        return new Summary(cmd.txnId(), cmd.executeAt(), saveStatus, ranges, findAsDep, hasAsDep);
-    }
+        public Summary from(Command cmd)
+        {
+            return from(cmd.txnId(), cmd.executeAt(), cmd.saveStatus(), cmd.participants(), cmd.partialDeps());
+        }
 
-    private static Summary create(SavedCommand.MinimalCommand cmd, Ranges cacheRanges, @Nullable RedundantBefore redundantBefore)
-    {
-        //TODO (required, correctness): C* did Invalidated, accord-core did Erased... what is correct?
-        SaveStatus saveStatus = cmd.saveStatus;
-        if (saveStatus == null
-            || saveStatus == SaveStatus.Invalidated
-            || saveStatus == SaveStatus.Erased
-            || !saveStatus.hasBeen(Status.PreAccepted))
-            return null;
-
-        if (cmd.participants == null)
-            return null;
-
-        var keysOrRanges = cmd.participants.touches().toRanges();
-        if (keysOrRanges.domain() != Domain.Range)
-            throw new AssertionError(String.format("Txn keys are not range for %s", cmd.participants));
-        Ranges ranges = (Ranges) keysOrRanges;
-
-        ranges = ranges.slice(cacheRanges, Routables.Slice.Minimal);
-        if (ranges.isEmpty())
-            return null;
-
-        if (redundantBefore != null)
+        public Summary from(SavedCommand.MinimalCommand cmd)

Review Comment:
   pre-existing, but we can create summaries without creating minimal commands, maybe add todo?



##########
src/java/org/apache/cassandra/config/AccordSpec.java:
##########
@@ -35,18 +37,71 @@ public class AccordSpec
 
     public volatile boolean enable_journal_compaction = true;
 
-    public volatile OptionaldPositiveInt shard_count = OptionaldPositiveInt.UNDEFINED;
+    public enum QueueShardModel
+    {
+        /**
+         * Same number of threads as queue shards, but the shard lock is held only while managing the queue,
+         * so that submitting threads may queue load/save work.
+         *
+         * The global READ and WRITE stages are used for IO.
+         */
+        THREAD_PER_SHARD,
+
+        /**
+         * Same number of threads as shards, and the shard lock is held for the duration of serving requests.
+         * The global READ and WRITE stages are used for IO.
+         */
+        THREAD_PER_SHARD_SYNC_QUEUE,
+
+        /**
+         * More threads than shards. Threads update transaction state as well as performing IO, minimising context switching.
+         * Fewer shards is generally better, until queue-contention is encountered.
+         */
+        THREAD_POOL_PER_SHARD,
+
+        /**
+         * More threads than shards. Threads update transaction state only, relying on READ and WRITE stages for IO.
+         * Fewer shards is generally better, until queue-contention is encountered.
+         */
+        THREAD_POOL_PER_SHARD_EXCLUDES_IO,
+    }
+
+    public enum QueueSubmissionModel
+    {
+        SYNC, SEMI_SYNC, ASYNC
+    }
+
+    public QueueShardModel queue_shard_model = THREAD_POOL_PER_SHARD;
+    public QueueSubmissionModel queue_submission_model = SYNC;
+
+    /**
+     * The number of queue (and cache) shards.
+     */
+    public volatile OptionaldPositiveInt queue_shard_count = OptionaldPositiveInt.UNDEFINED;
+
+    /**
+     * The target number of command stores to create per topology shard.
+     * This determines the amount of execution parallelism possible for a given table/shard on the host.
+     * More shards means more parallelism, but more state.
+     *
+     * TODO (expected): make this a table property
+     * TODO (expected): adjust this by proportion of ring
+     */
+    public volatile OptionaldPositiveInt command_store_shard_count = OptionaldPositiveInt.UNDEFINED;

Review Comment:
   Oh right yes. I have just seen the addition. 



##########
src/java/org/apache/cassandra/service/accord/AccordCommandStore.java:
##########
@@ -505,75 +448,42 @@ public void shutdown()
     {
     }
 
-    protected ConfigurationService.EpochReady syncInternal(Node node, Ranges ranges, long epoch, boolean isLoad)
-    {
-        if (!isLoad)
-            return super.syncInternal(node, ranges, epoch, false);
-
-        List<Pair<Range, Deps>> loaded = journal.loadHistoricalTransactions(epoch, id);
-        // synchronously load and register historical, so we don't have unlimited numbers of epochs in flight
-        for (Pair<Range, Deps> pair : loaded)
-        {
-            cancelFetch(pair.left, epoch);
-            try
-            {
-                logger.info("Restoring sync'd deps for {} at epoch {}", pair.left, epoch);
-                AsyncChains.getBlocking(submit(PreLoadContext.contextFor(null, pair.right.keyDeps.keys(), COMMANDS), safeStore -> {
-                    registerHistoricalTransactions(pair.left, pair.right, safeStore);
-                    return null;
-                }).beginAsResult(), 5L, TimeUnit.MINUTES);
-            }
-            catch (InterruptedException | TimeoutException | ExecutionException e)
-            {
-                throw new RuntimeException(e);
-            }
-            ranges = ranges.without(Ranges.of(pair.left));
-        }
-
-        if (ranges.isEmpty())
-        {
-            AsyncResult<Void> done = AsyncResults.success(null);
-            return new ConfigurationService.EpochReady(epoch, DONE, done, done, done);
-        }
-
-        return super.syncInternal(node, ranges, epoch, false);
-    }
-
-    public void registerHistoricalTransactions(Range range, Deps deps, SafeCommandStore safeStore)
+    public AsyncResult<Void> registerTransitive(SafeCommandStore safeStore, RangeDeps rangeDeps)

Review Comment:
   Does this one have to be async?



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,952 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable

Review Comment:
   Some general remarks that I have no good solution for: I feel like polls from different queues, migration between queues, and state transitions are scattered AccordExecutor, AccordTask, and multiple subclasses. I have tried to consolidate at least state transition for loadings in a suggestion branch. I think we need to spend a bit more time on this, trying to make this logic more accessible, since this is a heart of Accord scheduling. I'd be happy to take a stab on it; if you have ideas - I'll be happy to discuss them.



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,952 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;

Review Comment:
   Should this one be private, or maybe protected?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1830905025


##########
src/java/org/apache/cassandra/service/accord/AccordCommandStore.java:
##########
@@ -505,75 +448,42 @@ public void shutdown()
     {
     }
 
-    protected ConfigurationService.EpochReady syncInternal(Node node, Ranges ranges, long epoch, boolean isLoad)
-    {
-        if (!isLoad)
-            return super.syncInternal(node, ranges, epoch, false);
-
-        List<Pair<Range, Deps>> loaded = journal.loadHistoricalTransactions(epoch, id);
-        // synchronously load and register historical, so we don't have unlimited numbers of epochs in flight
-        for (Pair<Range, Deps> pair : loaded)
-        {
-            cancelFetch(pair.left, epoch);
-            try
-            {
-                logger.info("Restoring sync'd deps for {} at epoch {}", pair.left, epoch);
-                AsyncChains.getBlocking(submit(PreLoadContext.contextFor(null, pair.right.keyDeps.keys(), COMMANDS), safeStore -> {
-                    registerHistoricalTransactions(pair.left, pair.right, safeStore);
-                    return null;
-                }).beginAsResult(), 5L, TimeUnit.MINUTES);
-            }
-            catch (InterruptedException | TimeoutException | ExecutionException e)
-            {
-                throw new RuntimeException(e);
-            }
-            ranges = ranges.without(Ranges.of(pair.left));
-        }
-
-        if (ranges.isEmpty())
-        {
-            AsyncResult<Void> done = AsyncResults.success(null);
-            return new ConfigurationService.EpochReady(epoch, DONE, done, done, done);
-        }
-
-        return super.syncInternal(node, ranges, epoch, false);
-    }
-
-    public void registerHistoricalTransactions(Range range, Deps deps, SafeCommandStore safeStore)
+    public AsyncResult<Void> registerTransitive(SafeCommandStore safeStore, RangeDeps rangeDeps)

Review Comment:
   I think this is defunct, was from the prior patch that I've since made sync. Will rebase.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1829170726


##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)

Review Comment:
   no, you're right



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#issuecomment-2466843639

   Merge as part of #3652 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1829171793


##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)
+                    {
+                        parkRangeLoad(next);
+                    }
+                    else
+                    {
+                        ++activeRangeLoads;
+                        ++activeLoads;
+                        next.rangeLoader().start(rangeLoadExecutor);
+                        updateQueue(next, false);
+                    }
+                    break;
+
+                case WAITING_TO_LOAD:
+                    while (true)
+                    {
+                        AccordCachingState<?, ?> load = next.peekWaitingToLoad();
+                        boolean isForRange = isForRange(next, load);
+                        if (isForRange && activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)
+                        {
+                            parkRangeLoad(next);
+                            continue outer;
+                        }
+
+                        Invariants.checkState(load != null);
+                        AccordCachingState.OnLoaded onLoaded = this;
+                        ++activeLoads;
+                        if (isForRange)
+                        {
+                            ++activeRangeLoads;
+                            onLoaded = onRangeLoaded;
+                        }
+
+                        for (AccordTask<?> task : cache.load(loadExecutor, load, onLoaded))
+                        {
+                            if (task == next) continue;
+                            if (task.onLoading(load))
+                                updateQueue(task, false);
+                        }
+                        Object prev = next.pollWaitingToLoad();
+                        Invariants.checkState(prev == load);
+                        if (next.peekWaitingToLoad() == null)
+                            break;
+
+                        Invariants.checkState(next.state() == WAITING_TO_LOAD, "Invalid state: %s", next);
+                        if (activeLoads >= MAX_QUEUED_LOADS_PER_EXECUTOR)
+                            return;
+                    }
+                    Invariants.checkState(next.state().compareTo(LOADING) >= 0, "Invalid state: %s", next);
+                    updateQueue(next, false);
+            }
+        }
+    }
+
+    private boolean isForRange(AccordTask<?> task, AccordCachingState<?, ?> load)
+    {
+        boolean isForRangeTxn = task.hasRanges();
+        if (!isForRangeTxn)
+            return false;
+
+        for (AccordTask<?> t : load.loadingOrWaiting().waiters())
+        {
+            if (!t.hasRanges())
+                return false;
+        }
+        return true;
+    }
+
+    private void parkRangeLoad(AccordTask<?> task)
+    {
+        if (task.queued() != waitingToLoadRangeTxnsCollection)
+        {
+            task.unqueueIfQueued();
+            if (waitingToLoadRangeTxns == null)
+                waitingToLoadRangeTxns = waitingToLoadRangeTxnsCollection;
+            task.addToQueue(waitingToLoadRangeTxns);
+        }
+    }
+
+    void consumeExclusive(Object object)
+    {
+        try
+        {
+            if (object instanceof AccordTask<?>)
+                loadExclusive((AccordTask<?>) object);
+            else
+                ((SubmitAsync) object).acceptExclusive(this);
+        }
+        catch (Throwable t)
+        {
+            agent.onUncaughtException(t);
+        }
+    }
+
+    private void updateQueue(AccordTask<?> task, boolean enqueueLoads)
+    {
+        removeFromQueue(task);
+        switch (task.state())
+        {
+            default: throw new AssertionError("Unexpected state: " + task.toDescription());
+            case WAITING_TO_SCAN_RANGES:
+            case WAITING_TO_LOAD:
+                task.addToQueue(waitingToLoad);
+                if (enqueueLoads) enqueueLoadsExclusive();
+                break;
+            case SCANNING_RANGES:
+                task.addToQueue(scanningRanges);
+                break;
+            case LOADING:
+                task.addToQueue(loading);
+                break;
+            case WAITING_TO_RUN:
+                task.runQueuedAt = nanoTime();
+                commandStoreQueues.computeIfAbsent(task.commandStore, CommandStoreQueue::new)
+                                  .append(task);
+                break;
+        }
+    }
+    
+    private void waitingToRun(Task task)
+    {
+        if (task.commandStore == null)
+        {
+            waitingToRun.append(task);
+        }
+        else
+        {
+            commandStoreQueues.computeIfAbsent(task.commandStore, CommandStoreQueue::new)
+                              .append(task);
+        }
+    }
+
+    private void removeFromQueue(AccordTask<?> task)
+    {
+        TaskQueue<?> queue = task.unqueueIfQueued();
+        if (queue == waitingToLoadRangeTxnsCollection && waitingToLoadRangeTxnsCollection.isEmpty())
+            waitingToLoadRangeTxns = null;
+    }
+
+    private Future<?> submitIOExclusive(Runnable run)
+    {
+        Invariants.checkState(isInThread());
+        ++tasks;
+        AsyncPromise<Void> result = new AsyncPromise<>();
+        PlainRunnable task = new PlainRunnable(result, run, null);
+        // TODO (expected): adopt queue position of the submitting task
+        task.queuePosition = ++nextPosition;
+        waitingToRun.append(task);
+        return result;
+    }
+
+    public Executor executor(AccordCommandStore commandStore)
+    {
+        return task -> AccordExecutor.this.submit(task, commandStore);
+    }
+
+    public <R> void submit(AccordTask<R> operation)
+    {
+        submit(AccordExecutor::loadExclusive, Function.identity(), operation);
+    }
+
+    public <R> void cancel(AccordTask<R> operation)
+    {
+        submit(AccordExecutor::cancelExclusive, OnCancel::new, operation);
+    }
+
+    public void onScannedRanges(AccordTask<?> task, Throwable fail)
+    {
+        submit(AccordExecutor::onScannedRangesExclusive, OnScannedRanges::new, task, fail);
+    }
+
+    public <K, V> void onSaved(AccordCachingState<K, V> saved, Object identity, Throwable fail)
+    {
+        submit(AccordExecutor::onSavedExclusive, OnSaved::new, saved, identity, fail);
+    }
+
+    @Override
+    public <K, V> void onLoaded(AccordCachingState<K, V> loaded, V value, Throwable fail)
+    {
+        submit(AccordExecutor::onLoadedExclusive, OnLoaded::new, loaded, value, fail, false);
+    }
+
+    public <K, V> void onRangeLoaded(AccordCachingState<K, V> loaded, V value, Throwable fail)
+    {
+        submit(AccordExecutor::onLoadedExclusive, OnLoaded::new, loaded, value, fail, true);
+    }
+
+    private <P1> void submit(BiConsumer<AccordExecutor, P1> sync, Function<P1, ?> async, P1 p1)
+    {
+        submit((e, c, p1a, p2a, p3) -> c.accept(e, p1a), (f, p1a, p2a, p3) -> f.apply(p1a), sync, async, p1, null, null);
+    }
+
+    private <P1, P2> void submit(TriConsumer<AccordExecutor, P1, P2> sync, BiFunction<P1, P2, ?> async, P1 p1, P2 p2)
+    {
+        submit((e, c, p1a, p2a, p3) -> c.accept(e, p1a, p2a), (f, p1a, p2a, p3) -> f.apply(p1a, p2a), sync, async, p1, p2, null);
+    }
+
+    private <P1, P2, P3> void submit(QuadConsumer<AccordExecutor, P1, P2, P3> sync, TriFunction<P1, P2, P3, ?> async, P1 p1, P2 p2, P3 p3)
+    {
+        submit((e, c, p1a, p2a, p3a) -> c.accept(e, p1a, p2a, p3a), TriFunction::apply, sync, async, p1, p2, p3);
+    }
+
+    private <P1, P2, P3, P4> void submit(QuintConsumer<AccordExecutor, P1, P2, P3, P4> sync, QuadFunction<P1, P2, P3, P4, Object> async, P1 p1, P2 p2, P3 p3, P4 p4)
+    {
+        submit(sync, async, p1, p1, p2, p3, p4);
+    }
+
+    abstract <P1s, P1a, P2, P3, P4> void submit(QuintConsumer<AccordExecutor, P1s, P2, P3, P4> sync, QuadFunction<P1a, P2, P3, P4, Object> async, P1s p1s, P1a p1a, P2 p2, P3 p3, P4 p4);
+
+    private void submitExclusive(AsyncPromise<Void> result, Runnable run, AccordCommandStore commandStore)
+    {
+        ++tasks;
+        PlainRunnable task = new PlainRunnable(result, run, commandStore);
+        task.queuePosition = ++nextPosition;
+        waitingToRun(task);
+    }
+
+    private void loadExclusive(AccordTask<?> task)
+    {
+        ++tasks;
+        task.queuePosition = ++nextPosition;
+        task.setupExclusive();
+        updateQueue(task, true);

Review Comment:
   yep, good idea



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)
+                    {
+                        parkRangeLoad(next);
+                    }
+                    else
+                    {
+                        ++activeRangeLoads;
+                        ++activeLoads;
+                        next.rangeLoader().start(rangeLoadExecutor);
+                        updateQueue(next, false);
+                    }
+                    break;
+
+                case WAITING_TO_LOAD:
+                    while (true)
+                    {
+                        AccordCachingState<?, ?> load = next.peekWaitingToLoad();
+                        boolean isForRange = isForRange(next, load);
+                        if (isForRange && activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)
+                        {
+                            parkRangeLoad(next);
+                            continue outer;
+                        }
+
+                        Invariants.checkState(load != null);
+                        AccordCachingState.OnLoaded onLoaded = this;
+                        ++activeLoads;
+                        if (isForRange)
+                        {
+                            ++activeRangeLoads;
+                            onLoaded = onRangeLoaded;
+                        }
+
+                        for (AccordTask<?> task : cache.load(loadExecutor, load, onLoaded))
+                        {
+                            if (task == next) continue;
+                            if (task.onLoading(load))
+                                updateQueue(task, false);
+                        }
+                        Object prev = next.pollWaitingToLoad();
+                        Invariants.checkState(prev == load);
+                        if (next.peekWaitingToLoad() == null)
+                            break;
+
+                        Invariants.checkState(next.state() == WAITING_TO_LOAD, "Invalid state: %s", next);
+                        if (activeLoads >= MAX_QUEUED_LOADS_PER_EXECUTOR)
+                            return;
+                    }
+                    Invariants.checkState(next.state().compareTo(LOADING) >= 0, "Invalid state: %s", next);
+                    updateQueue(next, false);
+            }
+        }
+    }
+
+    private boolean isForRange(AccordTask<?> task, AccordCachingState<?, ?> load)
+    {
+        boolean isForRangeTxn = task.hasRanges();
+        if (!isForRangeTxn)
+            return false;
+
+        for (AccordTask<?> t : load.loadingOrWaiting().waiters())
+        {
+            if (!t.hasRanges())
+                return false;
+        }
+        return true;
+    }
+
+    private void parkRangeLoad(AccordTask<?> task)
+    {
+        if (task.queued() != waitingToLoadRangeTxnsCollection)
+        {
+            task.unqueueIfQueued();
+            if (waitingToLoadRangeTxns == null)
+                waitingToLoadRangeTxns = waitingToLoadRangeTxnsCollection;
+            task.addToQueue(waitingToLoadRangeTxns);
+        }
+    }
+
+    void consumeExclusive(Object object)
+    {
+        try
+        {
+            if (object instanceof AccordTask<?>)
+                loadExclusive((AccordTask<?>) object);
+            else
+                ((SubmitAsync) object).acceptExclusive(this);
+        }
+        catch (Throwable t)
+        {
+            agent.onUncaughtException(t);
+        }
+    }
+
+    private void updateQueue(AccordTask<?> task, boolean enqueueLoads)
+    {
+        removeFromQueue(task);
+        switch (task.state())
+        {
+            default: throw new AssertionError("Unexpected state: " + task.toDescription());
+            case WAITING_TO_SCAN_RANGES:
+            case WAITING_TO_LOAD:
+                task.addToQueue(waitingToLoad);
+                if (enqueueLoads) enqueueLoadsExclusive();
+                break;
+            case SCANNING_RANGES:
+                task.addToQueue(scanningRanges);
+                break;
+            case LOADING:
+                task.addToQueue(loading);
+                break;
+            case WAITING_TO_RUN:
+                task.runQueuedAt = nanoTime();
+                commandStoreQueues.computeIfAbsent(task.commandStore, CommandStoreQueue::new)
+                                  .append(task);
+                break;
+        }
+    }
+    
+    private void waitingToRun(Task task)
+    {
+        if (task.commandStore == null)
+        {
+            waitingToRun.append(task);
+        }
+        else
+        {
+            commandStoreQueues.computeIfAbsent(task.commandStore, CommandStoreQueue::new)
+                              .append(task);
+        }
+    }
+
+    private void removeFromQueue(AccordTask<?> task)
+    {
+        TaskQueue<?> queue = task.unqueueIfQueued();
+        if (queue == waitingToLoadRangeTxnsCollection && waitingToLoadRangeTxnsCollection.isEmpty())
+            waitingToLoadRangeTxns = null;
+    }
+
+    private Future<?> submitIOExclusive(Runnable run)
+    {
+        Invariants.checkState(isInThread());
+        ++tasks;
+        AsyncPromise<Void> result = new AsyncPromise<>();
+        PlainRunnable task = new PlainRunnable(result, run, null);
+        // TODO (expected): adopt queue position of the submitting task
+        task.queuePosition = ++nextPosition;
+        waitingToRun.append(task);
+        return result;
+    }
+
+    public Executor executor(AccordCommandStore commandStore)
+    {
+        return task -> AccordExecutor.this.submit(task, commandStore);
+    }
+
+    public <R> void submit(AccordTask<R> operation)
+    {
+        submit(AccordExecutor::loadExclusive, Function.identity(), operation);
+    }
+
+    public <R> void cancel(AccordTask<R> operation)
+    {
+        submit(AccordExecutor::cancelExclusive, OnCancel::new, operation);
+    }
+
+    public void onScannedRanges(AccordTask<?> task, Throwable fail)
+    {
+        submit(AccordExecutor::onScannedRangesExclusive, OnScannedRanges::new, task, fail);
+    }
+
+    public <K, V> void onSaved(AccordCachingState<K, V> saved, Object identity, Throwable fail)
+    {
+        submit(AccordExecutor::onSavedExclusive, OnSaved::new, saved, identity, fail);
+    }
+
+    @Override
+    public <K, V> void onLoaded(AccordCachingState<K, V> loaded, V value, Throwable fail)
+    {
+        submit(AccordExecutor::onLoadedExclusive, OnLoaded::new, loaded, value, fail, false);
+    }
+
+    public <K, V> void onRangeLoaded(AccordCachingState<K, V> loaded, V value, Throwable fail)
+    {
+        submit(AccordExecutor::onLoadedExclusive, OnLoaded::new, loaded, value, fail, true);
+    }
+
+    private <P1> void submit(BiConsumer<AccordExecutor, P1> sync, Function<P1, ?> async, P1 p1)
+    {
+        submit((e, c, p1a, p2a, p3) -> c.accept(e, p1a), (f, p1a, p2a, p3) -> f.apply(p1a), sync, async, p1, null, null);
+    }
+
+    private <P1, P2> void submit(TriConsumer<AccordExecutor, P1, P2> sync, BiFunction<P1, P2, ?> async, P1 p1, P2 p2)
+    {
+        submit((e, c, p1a, p2a, p3) -> c.accept(e, p1a, p2a), (f, p1a, p2a, p3) -> f.apply(p1a, p2a), sync, async, p1, p2, null);
+    }
+
+    private <P1, P2, P3> void submit(QuadConsumer<AccordExecutor, P1, P2, P3> sync, TriFunction<P1, P2, P3, ?> async, P1 p1, P2 p2, P3 p3)
+    {
+        submit((e, c, p1a, p2a, p3a) -> c.accept(e, p1a, p2a, p3a), TriFunction::apply, sync, async, p1, p2, p3);
+    }
+
+    private <P1, P2, P3, P4> void submit(QuintConsumer<AccordExecutor, P1, P2, P3, P4> sync, QuadFunction<P1, P2, P3, P4, Object> async, P1 p1, P2 p2, P3 p3, P4 p4)
+    {
+        submit(sync, async, p1, p1, p2, p3, p4);
+    }
+
+    abstract <P1s, P1a, P2, P3, P4> void submit(QuintConsumer<AccordExecutor, P1s, P2, P3, P4> sync, QuadFunction<P1a, P2, P3, P4, Object> async, P1s p1s, P1a p1a, P2 p2, P3 p3, P4 p4);
+
+    private void submitExclusive(AsyncPromise<Void> result, Runnable run, AccordCommandStore commandStore)
+    {
+        ++tasks;
+        PlainRunnable task = new PlainRunnable(result, run, commandStore);
+        task.queuePosition = ++nextPosition;
+        waitingToRun(task);
+    }
+
+    private void loadExclusive(AccordTask<?> task)
+    {
+        ++tasks;
+        task.queuePosition = ++nextPosition;
+        task.setupExclusive();
+        updateQueue(task, true);

Review Comment:
   yep, good idea



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1829172665


##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)
+                    {
+                        parkRangeLoad(next);
+                    }
+                    else
+                    {
+                        ++activeRangeLoads;
+                        ++activeLoads;
+                        next.rangeLoader().start(rangeLoadExecutor);
+                        updateQueue(next, false);
+                    }
+                    break;
+
+                case WAITING_TO_LOAD:
+                    while (true)
+                    {
+                        AccordCachingState<?, ?> load = next.peekWaitingToLoad();
+                        boolean isForRange = isForRange(next, load);
+                        if (isForRange && activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)
+                        {
+                            parkRangeLoad(next);
+                            continue outer;
+                        }
+
+                        Invariants.checkState(load != null);
+                        AccordCachingState.OnLoaded onLoaded = this;
+                        ++activeLoads;
+                        if (isForRange)
+                        {
+                            ++activeRangeLoads;
+                            onLoaded = onRangeLoaded;
+                        }
+
+                        for (AccordTask<?> task : cache.load(loadExecutor, load, onLoaded))
+                        {
+                            if (task == next) continue;
+                            if (task.onLoading(load))
+                                updateQueue(task, false);
+                        }
+                        Object prev = next.pollWaitingToLoad();
+                        Invariants.checkState(prev == load);
+                        if (next.peekWaitingToLoad() == null)
+                            break;
+
+                        Invariants.checkState(next.state() == WAITING_TO_LOAD, "Invalid state: %s", next);
+                        if (activeLoads >= MAX_QUEUED_LOADS_PER_EXECUTOR)
+                            return;
+                    }
+                    Invariants.checkState(next.state().compareTo(LOADING) >= 0, "Invalid state: %s", next);
+                    updateQueue(next, false);
+            }
+        }
+    }
+
+    private boolean isForRange(AccordTask<?> task, AccordCachingState<?, ?> load)
+    {
+        boolean isForRangeTxn = task.hasRanges();
+        if (!isForRangeTxn)
+            return false;
+
+        for (AccordTask<?> t : load.loadingOrWaiting().waiters())
+        {
+            if (!t.hasRanges())
+                return false;
+        }
+        return true;
+    }
+
+    private void parkRangeLoad(AccordTask<?> task)
+    {
+        if (task.queued() != waitingToLoadRangeTxnsCollection)
+        {
+            task.unqueueIfQueued();
+            if (waitingToLoadRangeTxns == null)
+                waitingToLoadRangeTxns = waitingToLoadRangeTxnsCollection;
+            task.addToQueue(waitingToLoadRangeTxns);
+        }
+    }
+
+    void consumeExclusive(Object object)
+    {
+        try
+        {
+            if (object instanceof AccordTask<?>)
+                loadExclusive((AccordTask<?>) object);
+            else
+                ((SubmitAsync) object).acceptExclusive(this);
+        }
+        catch (Throwable t)
+        {
+            agent.onUncaughtException(t);
+        }
+    }
+
+    private void updateQueue(AccordTask<?> task, boolean enqueueLoads)
+    {
+        removeFromQueue(task);
+        switch (task.state())
+        {
+            default: throw new AssertionError("Unexpected state: " + task.toDescription());
+            case WAITING_TO_SCAN_RANGES:
+            case WAITING_TO_LOAD:
+                task.addToQueue(waitingToLoad);
+                if (enqueueLoads) enqueueLoadsExclusive();
+                break;
+            case SCANNING_RANGES:
+                task.addToQueue(scanningRanges);
+                break;
+            case LOADING:
+                task.addToQueue(loading);
+                break;
+            case WAITING_TO_RUN:
+                task.runQueuedAt = nanoTime();
+                commandStoreQueues.computeIfAbsent(task.commandStore, CommandStoreQueue::new)
+                                  .append(task);
+                break;
+        }
+    }
+    
+    private void waitingToRun(Task task)
+    {
+        if (task.commandStore == null)
+        {
+            waitingToRun.append(task);
+        }
+        else
+        {
+            commandStoreQueues.computeIfAbsent(task.commandStore, CommandStoreQueue::new)
+                              .append(task);
+        }
+    }
+
+    private void removeFromQueue(AccordTask<?> task)
+    {
+        TaskQueue<?> queue = task.unqueueIfQueued();
+        if (queue == waitingToLoadRangeTxnsCollection && waitingToLoadRangeTxnsCollection.isEmpty())
+            waitingToLoadRangeTxns = null;
+    }
+
+    private Future<?> submitIOExclusive(Runnable run)
+    {
+        Invariants.checkState(isInThread());
+        ++tasks;
+        AsyncPromise<Void> result = new AsyncPromise<>();
+        PlainRunnable task = new PlainRunnable(result, run, null);
+        // TODO (expected): adopt queue position of the submitting task
+        task.queuePosition = ++nextPosition;
+        waitingToRun.append(task);
+        return result;
+    }
+
+    public Executor executor(AccordCommandStore commandStore)
+    {
+        return task -> AccordExecutor.this.submit(task, commandStore);
+    }
+
+    public <R> void submit(AccordTask<R> operation)
+    {
+        submit(AccordExecutor::loadExclusive, Function.identity(), operation);
+    }
+
+    public <R> void cancel(AccordTask<R> operation)
+    {
+        submit(AccordExecutor::cancelExclusive, OnCancel::new, operation);
+    }
+
+    public void onScannedRanges(AccordTask<?> task, Throwable fail)
+    {
+        submit(AccordExecutor::onScannedRangesExclusive, OnScannedRanges::new, task, fail);
+    }
+
+    public <K, V> void onSaved(AccordCachingState<K, V> saved, Object identity, Throwable fail)
+    {
+        submit(AccordExecutor::onSavedExclusive, OnSaved::new, saved, identity, fail);
+    }
+
+    @Override
+    public <K, V> void onLoaded(AccordCachingState<K, V> loaded, V value, Throwable fail)
+    {
+        submit(AccordExecutor::onLoadedExclusive, OnLoaded::new, loaded, value, fail, false);
+    }
+
+    public <K, V> void onRangeLoaded(AccordCachingState<K, V> loaded, V value, Throwable fail)
+    {
+        submit(AccordExecutor::onLoadedExclusive, OnLoaded::new, loaded, value, fail, true);
+    }
+
+    private <P1> void submit(BiConsumer<AccordExecutor, P1> sync, Function<P1, ?> async, P1 p1)
+    {
+        submit((e, c, p1a, p2a, p3) -> c.accept(e, p1a), (f, p1a, p2a, p3) -> f.apply(p1a), sync, async, p1, null, null);
+    }
+
+    private <P1, P2> void submit(TriConsumer<AccordExecutor, P1, P2> sync, BiFunction<P1, P2, ?> async, P1 p1, P2 p2)
+    {
+        submit((e, c, p1a, p2a, p3) -> c.accept(e, p1a, p2a), (f, p1a, p2a, p3) -> f.apply(p1a, p2a), sync, async, p1, p2, null);
+    }
+
+    private <P1, P2, P3> void submit(QuadConsumer<AccordExecutor, P1, P2, P3> sync, TriFunction<P1, P2, P3, ?> async, P1 p1, P2 p2, P3 p3)
+    {
+        submit((e, c, p1a, p2a, p3a) -> c.accept(e, p1a, p2a, p3a), TriFunction::apply, sync, async, p1, p2, p3);
+    }
+
+    private <P1, P2, P3, P4> void submit(QuintConsumer<AccordExecutor, P1, P2, P3, P4> sync, QuadFunction<P1, P2, P3, P4, Object> async, P1 p1, P2 p2, P3 p3, P4 p4)
+    {
+        submit(sync, async, p1, p1, p2, p3, p4);
+    }
+
+    abstract <P1s, P1a, P2, P3, P4> void submit(QuintConsumer<AccordExecutor, P1s, P2, P3, P4> sync, QuadFunction<P1a, P2, P3, P4, Object> async, P1s p1s, P1a p1a, P2 p2, P3 p3, P4 p4);
+
+    private void submitExclusive(AsyncPromise<Void> result, Runnable run, AccordCommandStore commandStore)
+    {
+        ++tasks;
+        PlainRunnable task = new PlainRunnable(result, run, commandStore);
+        task.queuePosition = ++nextPosition;
+        waitingToRun(task);
+    }
+
+    private void loadExclusive(AccordTask<?> task)
+    {
+        ++tasks;
+        task.queuePosition = ++nextPosition;
+        task.setupExclusive();
+        updateQueue(task, true);

Review Comment:
   yes, good idea



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1830903979


##########
src/java/org/apache/cassandra/service/accord/AccordCachingState.java:
##########
@@ -184,61 +176,164 @@ protected State<K, V> state()
         return state;
     }
 
-    public AsyncChain<V> loading()
+    public void readyToLoad()
+    {
+        state(state.readyToLoad());
+    }
+
+    public LoadingOrWaiting<K, V> loadingOrWaiting()
+    {
+        return state.loadingOrWaiting();
+    }
+
+    void notifyListeners(BiConsumer<AccordStateCache.Listener<K, V>, AccordCachingState<K, V>> notify)
+    {
+        owner.notifyListeners(notify, this);
+    }
+
+    public interface OnLoaded
+    {
+        <K, V> void onLoaded(AccordCachingState<K, V> state, V value, Throwable fail);
+
+        static OnLoaded immediate()

Review Comment:
   Sure, can do yes.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1830905825


##########
src/java/org/apache/cassandra/service/accord/AccordCommandStore.java:
##########
@@ -248,12 +203,13 @@ public void markShardDurable(SafeCommandStore safeStore, TxnId globalSyncId, Ran
     {
         store.snapshot(ranges, globalSyncId);
         super.markShardDurable(safeStore, globalSyncId, ranges);
+        commandsForRangesLoader.gcBefore(globalSyncId, ranges);
     }
 
     @Override
     public boolean inStore()
     {
-        return executor.isInThread();
+        return currentThread == Thread.currentThread();
     }
 
     public void checkInStoreThread()

Review Comment:
   I think it is? Looks to be called from at least four places in accord-core



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1830903506


##########
src/java/org/apache/cassandra/service/accord/AccordTask.java:
##########
@@ -0,0 +1,880 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.service.accord;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandStore;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommandStore;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.AbstractRanges;
+import accord.primitives.AbstractUnseekableKeys;
+import accord.primitives.Range;
+import accord.primitives.Ranges;
+import accord.primitives.TxnId;
+import accord.primitives.Unseekables;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChain;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.Cancellable;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.agrona.collections.ObjectHashSet;
+import org.apache.cassandra.service.accord.AccordCachingState.Status;
+import org.apache.cassandra.service.accord.AccordCommandStore.Caches;
+import org.apache.cassandra.service.accord.AccordExecutor.TaskQueue;
+import org.apache.cassandra.service.accord.api.AccordRoutingKey;
+import org.apache.cassandra.utils.NoSpamLogger;
+import org.apache.cassandra.utils.concurrent.Condition;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.config.CassandraRelevantProperties.DTEST_ACCORD_JOURNAL_SANITY_CHECK_ENABLED;
+import static org.apache.cassandra.service.accord.AccordTask.State.CANCELLED;
+import static org.apache.cassandra.service.accord.AccordTask.State.FAILED;
+import static org.apache.cassandra.service.accord.AccordTask.State.FINISHED;
+import static org.apache.cassandra.service.accord.AccordTask.State.INITIALIZED;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.PERSISTING;
+import static org.apache.cassandra.service.accord.AccordTask.State.RUNNING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_SCAN_RANGES;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordTask<R> extends AccordExecutor.Task implements Runnable, Function<SafeCommandStore, R>, Cancellable
+{
+    private static final Logger logger = LoggerFactory.getLogger(AccordTask.class);
+    private static final NoSpamLogger noSpamLogger = NoSpamLogger.getLogger(logger, 1, TimeUnit.MINUTES);
+    private static final boolean SANITY_CHECK = DTEST_ACCORD_JOURNAL_SANITY_CHECK_ENABLED.getBoolean();
+
+    private static class LoggingProps
+    {
+        private static final String COMMAND_STORE = "command_store";
+        private static final String ACCORD_TASK = "accord_task";
+    }
+
+    static class ForFunction<R> extends AccordTask<R>
+    {
+        private final Function<? super SafeCommandStore, R> function;
+
+        public ForFunction(AccordCommandStore commandStore, PreLoadContext loadCtx, Function<? super SafeCommandStore, R> function)
+        {
+            super(commandStore, loadCtx);
+            this.function = function;
+        }
+
+        @Override
+        public R apply(SafeCommandStore commandStore)
+        {
+            return function.apply(commandStore);
+        }
+    }
+
+    // TODO (desired): these anonymous ops are somewhat tricky to debug. We may want to at least give them names.
+    static class ForConsumer extends AccordTask<Void>
+    {
+        private final Consumer<? super SafeCommandStore> consumer;
+
+        public ForConsumer(AccordCommandStore commandStore, PreLoadContext loadCtx, Consumer<? super SafeCommandStore> consumer)
+        {
+            super(commandStore, loadCtx);
+            this.consumer = consumer;
+        }
+
+        @Override
+        public Void apply(SafeCommandStore commandStore)
+        {
+            consumer.accept(commandStore);
+            return null;
+        }
+    }
+
+    public static <T> AccordTask<T> create(CommandStore commandStore, PreLoadContext ctx, Function<? super SafeCommandStore, T> function)
+    {
+        return new ForFunction<>((AccordCommandStore) commandStore, ctx, function);
+    }
+
+    public static AccordTask<Void> create(CommandStore commandStore, PreLoadContext ctx, Consumer<? super SafeCommandStore> consumer)
+    {
+        return new ForConsumer((AccordCommandStore) commandStore, ctx, consumer);
+    }
+
+    public enum State
+    {
+        INITIALIZED(),
+        WAITING_TO_SCAN_RANGES(INITIALIZED),
+        SCANNING_RANGES(WAITING_TO_SCAN_RANGES),
+        WAITING_TO_LOAD(INITIALIZED, SCANNING_RANGES),
+        LOADING(INITIALIZED, SCANNING_RANGES, WAITING_TO_LOAD),
+        WAITING_TO_RUN(INITIALIZED, SCANNING_RANGES, WAITING_TO_LOAD, LOADING),
+        RUNNING(WAITING_TO_RUN),
+        PERSISTING(RUNNING),
+        FINISHED(RUNNING, PERSISTING),
+        CANCELLED(WAITING_TO_SCAN_RANGES, SCANNING_RANGES, WAITING_TO_LOAD, LOADING, WAITING_TO_RUN),
+        FAILED(WAITING_TO_SCAN_RANGES, SCANNING_RANGES, WAITING_TO_LOAD, LOADING, WAITING_TO_RUN, RUNNING, PERSISTING);
+
+        private final int permittedFrom;
+
+        State()
+        {
+            this.permittedFrom = 0;
+        }
+
+        State(State ... permittedFroms)
+        {
+            int permittedFrom = 0;
+            for (State state : permittedFroms)
+                permittedFrom |= 1 << state.ordinal();
+            this.permittedFrom = permittedFrom;
+        }
+
+        boolean isPermittedFrom(State prev)
+        {
+            return (permittedFrom & (1 << prev.ordinal())) != 0;
+        }
+
+        boolean isExecuted()
+        {
+            return this.compareTo(PERSISTING) >= 0;
+        }
+
+        boolean isComplete()
+        {
+            return this.compareTo(FINISHED) >= 0;
+        }
+    }
+
+    private State state = INITIALIZED;
+    private final PreLoadContext preLoadContext;
+    private final String loggingId;
+
+    @Nullable Object2ObjectHashMap<TxnId, AccordSafeCommand> commands;

Review Comment:
   It can actually help the JDK to use concrete classes as it can invoke concrete methods (rather than interface methods), but I don't have a strong opinion



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1829181820


##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }

Review Comment:
   perhaps I shouldn't be



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1829171320


##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;

Review Comment:
   in the follow-up perf patch I've made these configurable, I'll add a comment there



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "ifesdjeen (via GitHub)" <gi...@apache.org>.
ifesdjeen commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1827795430


##########
src/java/org/apache/cassandra/service/accord/AccordTask.java:
##########
@@ -0,0 +1,880 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.service.accord;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import accord.api.RoutingKey;
+import accord.local.Command;
+import accord.local.CommandStore;
+import accord.local.PreLoadContext;
+import accord.local.SafeCommandStore;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.AbstractRanges;
+import accord.primitives.AbstractUnseekableKeys;
+import accord.primitives.Range;
+import accord.primitives.Ranges;
+import accord.primitives.TxnId;
+import accord.primitives.Unseekables;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChain;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.Cancellable;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.agrona.collections.ObjectHashSet;
+import org.apache.cassandra.service.accord.AccordCachingState.Status;
+import org.apache.cassandra.service.accord.AccordCommandStore.Caches;
+import org.apache.cassandra.service.accord.AccordExecutor.TaskQueue;
+import org.apache.cassandra.service.accord.api.AccordRoutingKey;
+import org.apache.cassandra.utils.NoSpamLogger;
+import org.apache.cassandra.utils.concurrent.Condition;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.config.CassandraRelevantProperties.DTEST_ACCORD_JOURNAL_SANITY_CHECK_ENABLED;
+import static org.apache.cassandra.service.accord.AccordTask.State.CANCELLED;
+import static org.apache.cassandra.service.accord.AccordTask.State.FAILED;
+import static org.apache.cassandra.service.accord.AccordTask.State.FINISHED;
+import static org.apache.cassandra.service.accord.AccordTask.State.INITIALIZED;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.PERSISTING;
+import static org.apache.cassandra.service.accord.AccordTask.State.RUNNING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_SCAN_RANGES;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordTask<R> extends AccordExecutor.Task implements Runnable, Function<SafeCommandStore, R>, Cancellable
+{
+    private static final Logger logger = LoggerFactory.getLogger(AccordTask.class);
+    private static final NoSpamLogger noSpamLogger = NoSpamLogger.getLogger(logger, 1, TimeUnit.MINUTES);
+    private static final boolean SANITY_CHECK = DTEST_ACCORD_JOURNAL_SANITY_CHECK_ENABLED.getBoolean();
+
+    private static class LoggingProps
+    {
+        private static final String COMMAND_STORE = "command_store";
+        private static final String ACCORD_TASK = "accord_task";
+    }
+
+    static class ForFunction<R> extends AccordTask<R>
+    {
+        private final Function<? super SafeCommandStore, R> function;
+
+        public ForFunction(AccordCommandStore commandStore, PreLoadContext loadCtx, Function<? super SafeCommandStore, R> function)
+        {
+            super(commandStore, loadCtx);
+            this.function = function;
+        }
+
+        @Override
+        public R apply(SafeCommandStore commandStore)
+        {
+            return function.apply(commandStore);
+        }
+    }
+
+    // TODO (desired): these anonymous ops are somewhat tricky to debug. We may want to at least give them names.
+    static class ForConsumer extends AccordTask<Void>
+    {
+        private final Consumer<? super SafeCommandStore> consumer;
+
+        public ForConsumer(AccordCommandStore commandStore, PreLoadContext loadCtx, Consumer<? super SafeCommandStore> consumer)

Review Comment:
   Nit: I realize this is pre-existing, but it may make sense to make this one private, as this constructor is used only in tests



##########
src/java/org/apache/cassandra/config/AccordSpec.java:
##########
@@ -35,18 +37,71 @@ public class AccordSpec
 
     public volatile boolean enable_journal_compaction = true;
 
-    public volatile OptionaldPositiveInt shard_count = OptionaldPositiveInt.UNDEFINED;
+    public enum QueueShardModel
+    {
+        /**
+         * Same number of threads as queue shards, but the shard lock is held only while managing the queue,
+         * so that submitting threads may queue load/save work.
+         *
+         * The global READ and WRITE stages are used for IO.
+         */
+        THREAD_PER_SHARD,
+
+        /**
+         * Same number of threads as shards, and the shard lock is held for the duration of serving requests.
+         * The global READ and WRITE stages are used for IO.
+         */
+        THREAD_PER_SHARD_SYNC_QUEUE,
+
+        /**
+         * More threads than shards. Threads update transaction state as well as performing IO, minimising context switching.
+         * Fewer shards is generally better, until queue-contention is encountered.
+         */
+        THREAD_POOL_PER_SHARD,
+
+        /**
+         * More threads than shards. Threads update transaction state only, relying on READ and WRITE stages for IO.
+         * Fewer shards is generally better, until queue-contention is encountered.
+         */
+        THREAD_POOL_PER_SHARD_EXCLUDES_IO,
+    }
+
+    public enum QueueSubmissionModel
+    {
+        SYNC, SEMI_SYNC, ASYNC
+    }
+
+    public QueueShardModel queue_shard_model = THREAD_POOL_PER_SHARD;
+    public QueueSubmissionModel queue_submission_model = SYNC;
+
+    /**
+     * The number of queue (and cache) shards.
+     */
+    public volatile OptionaldPositiveInt queue_shard_count = OptionaldPositiveInt.UNDEFINED;
+
+    /**
+     * The target number of command stores to create per topology shard.
+     * This determines the amount of execution parallelism possible for a given table/shard on the host.
+     * More shards means more parallelism, but more state.
+     *
+     * TODO (expected): make this a table property
+     * TODO (expected): adjust this by proportion of ring
+     */
+    public volatile OptionaldPositiveInt command_store_shard_count = OptionaldPositiveInt.UNDEFINED;

Review Comment:
   nit: this looks like a typo in the workd Optional



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)
+                    {
+                        parkRangeLoad(next);
+                    }
+                    else
+                    {
+                        ++activeRangeLoads;
+                        ++activeLoads;
+                        next.rangeLoader().start(rangeLoadExecutor);
+                        updateQueue(next, false);
+                    }
+                    break;
+
+                case WAITING_TO_LOAD:
+                    while (true)
+                    {
+                        AccordCachingState<?, ?> load = next.peekWaitingToLoad();
+                        boolean isForRange = isForRange(next, load);
+                        if (isForRange && activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)
+                        {
+                            parkRangeLoad(next);
+                            continue outer;
+                        }
+
+                        Invariants.checkState(load != null);
+                        AccordCachingState.OnLoaded onLoaded = this;
+                        ++activeLoads;
+                        if (isForRange)
+                        {
+                            ++activeRangeLoads;
+                            onLoaded = onRangeLoaded;
+                        }
+
+                        for (AccordTask<?> task : cache.load(loadExecutor, load, onLoaded))
+                        {
+                            if (task == next) continue;
+                            if (task.onLoading(load))
+                                updateQueue(task, false);
+                        }
+                        Object prev = next.pollWaitingToLoad();
+                        Invariants.checkState(prev == load);
+                        if (next.peekWaitingToLoad() == null)
+                            break;
+
+                        Invariants.checkState(next.state() == WAITING_TO_LOAD, "Invalid state: %s", next);
+                        if (activeLoads >= MAX_QUEUED_LOADS_PER_EXECUTOR)
+                            return;
+                    }
+                    Invariants.checkState(next.state().compareTo(LOADING) >= 0, "Invalid state: %s", next);
+                    updateQueue(next, false);
+            }
+        }
+    }
+
+    private boolean isForRange(AccordTask<?> task, AccordCachingState<?, ?> load)
+    {
+        boolean isForRangeTxn = task.hasRanges();
+        if (!isForRangeTxn)
+            return false;
+
+        for (AccordTask<?> t : load.loadingOrWaiting().waiters())
+        {
+            if (!t.hasRanges())
+                return false;
+        }
+        return true;
+    }
+
+    private void parkRangeLoad(AccordTask<?> task)
+    {
+        if (task.queued() != waitingToLoadRangeTxnsCollection)
+        {
+            task.unqueueIfQueued();
+            if (waitingToLoadRangeTxns == null)
+                waitingToLoadRangeTxns = waitingToLoadRangeTxnsCollection;
+            task.addToQueue(waitingToLoadRangeTxns);
+        }
+    }
+
+    void consumeExclusive(Object object)
+    {
+        try
+        {
+            if (object instanceof AccordTask<?>)
+                loadExclusive((AccordTask<?>) object);
+            else
+                ((SubmitAsync) object).acceptExclusive(this);
+        }
+        catch (Throwable t)
+        {
+            agent.onUncaughtException(t);
+        }
+    }
+
+    private void updateQueue(AccordTask<?> task, boolean enqueueLoads)
+    {
+        removeFromQueue(task);
+        switch (task.state())
+        {
+            default: throw new AssertionError("Unexpected state: " + task.toDescription());
+            case WAITING_TO_SCAN_RANGES:
+            case WAITING_TO_LOAD:
+                task.addToQueue(waitingToLoad);
+                if (enqueueLoads) enqueueLoadsExclusive();
+                break;
+            case SCANNING_RANGES:
+                task.addToQueue(scanningRanges);
+                break;
+            case LOADING:
+                task.addToQueue(loading);
+                break;
+            case WAITING_TO_RUN:
+                task.runQueuedAt = nanoTime();
+                commandStoreQueues.computeIfAbsent(task.commandStore, CommandStoreQueue::new)
+                                  .append(task);
+                break;
+        }
+    }
+    
+    private void waitingToRun(Task task)
+    {
+        if (task.commandStore == null)
+        {
+            waitingToRun.append(task);
+        }
+        else
+        {
+            commandStoreQueues.computeIfAbsent(task.commandStore, CommandStoreQueue::new)
+                              .append(task);
+        }
+    }
+
+    private void removeFromQueue(AccordTask<?> task)
+    {
+        TaskQueue<?> queue = task.unqueueIfQueued();
+        if (queue == waitingToLoadRangeTxnsCollection && waitingToLoadRangeTxnsCollection.isEmpty())
+            waitingToLoadRangeTxns = null;
+    }
+
+    private Future<?> submitIOExclusive(Runnable run)
+    {
+        Invariants.checkState(isInThread());
+        ++tasks;
+        AsyncPromise<Void> result = new AsyncPromise<>();
+        PlainRunnable task = new PlainRunnable(result, run, null);
+        // TODO (expected): adopt queue position of the submitting task
+        task.queuePosition = ++nextPosition;
+        waitingToRun.append(task);
+        return result;
+    }
+
+    public Executor executor(AccordCommandStore commandStore)
+    {
+        return task -> AccordExecutor.this.submit(task, commandStore);
+    }
+
+    public <R> void submit(AccordTask<R> operation)
+    {
+        submit(AccordExecutor::loadExclusive, Function.identity(), operation);
+    }
+
+    public <R> void cancel(AccordTask<R> operation)
+    {
+        submit(AccordExecutor::cancelExclusive, OnCancel::new, operation);
+    }
+
+    public void onScannedRanges(AccordTask<?> task, Throwable fail)
+    {
+        submit(AccordExecutor::onScannedRangesExclusive, OnScannedRanges::new, task, fail);
+    }
+
+    public <K, V> void onSaved(AccordCachingState<K, V> saved, Object identity, Throwable fail)
+    {
+        submit(AccordExecutor::onSavedExclusive, OnSaved::new, saved, identity, fail);
+    }
+
+    @Override
+    public <K, V> void onLoaded(AccordCachingState<K, V> loaded, V value, Throwable fail)
+    {
+        submit(AccordExecutor::onLoadedExclusive, OnLoaded::new, loaded, value, fail, false);
+    }
+
+    public <K, V> void onRangeLoaded(AccordCachingState<K, V> loaded, V value, Throwable fail)
+    {
+        submit(AccordExecutor::onLoadedExclusive, OnLoaded::new, loaded, value, fail, true);
+    }
+
+    private <P1> void submit(BiConsumer<AccordExecutor, P1> sync, Function<P1, ?> async, P1 p1)
+    {
+        submit((e, c, p1a, p2a, p3) -> c.accept(e, p1a), (f, p1a, p2a, p3) -> f.apply(p1a), sync, async, p1, null, null);
+    }
+
+    private <P1, P2> void submit(TriConsumer<AccordExecutor, P1, P2> sync, BiFunction<P1, P2, ?> async, P1 p1, P2 p2)
+    {
+        submit((e, c, p1a, p2a, p3) -> c.accept(e, p1a, p2a), (f, p1a, p2a, p3) -> f.apply(p1a, p2a), sync, async, p1, p2, null);
+    }
+
+    private <P1, P2, P3> void submit(QuadConsumer<AccordExecutor, P1, P2, P3> sync, TriFunction<P1, P2, P3, ?> async, P1 p1, P2 p2, P3 p3)
+    {
+        submit((e, c, p1a, p2a, p3a) -> c.accept(e, p1a, p2a, p3a), TriFunction::apply, sync, async, p1, p2, p3);
+    }
+
+    private <P1, P2, P3, P4> void submit(QuintConsumer<AccordExecutor, P1, P2, P3, P4> sync, QuadFunction<P1, P2, P3, P4, Object> async, P1 p1, P2 p2, P3 p3, P4 p4)
+    {
+        submit(sync, async, p1, p1, p2, p3, p4);
+    }
+
+    abstract <P1s, P1a, P2, P3, P4> void submit(QuintConsumer<AccordExecutor, P1s, P2, P3, P4> sync, QuadFunction<P1a, P2, P3, P4, Object> async, P1s p1s, P1a p1a, P2 p2, P3 p3, P4 p4);
+
+    private void submitExclusive(AsyncPromise<Void> result, Runnable run, AccordCommandStore commandStore)
+    {
+        ++tasks;
+        PlainRunnable task = new PlainRunnable(result, run, commandStore);
+        task.queuePosition = ++nextPosition;
+        waitingToRun(task);
+    }
+
+    private void loadExclusive(AccordTask<?> task)
+    {
+        ++tasks;
+        task.queuePosition = ++nextPosition;
+        task.setupExclusive();
+        updateQueue(task, true);

Review Comment:
   minor: could it be better to remove  `boolean` argument from `updateQueue`, and call `enqueueLoadsExclusive` explicitly? We should not be able to be in any other state here, right?



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;

Review Comment:
   worth mentioning that the above includes these 8?



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)

Review Comment:
   Should this be possible, given we'd pick from another queue if `activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR`?



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)

Review Comment:
   on closer inspection; we have another nested while loop below which can change this count.



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }

Review Comment:
   nit: we can just allocate an exception, pass it to `failExclusive` and then throw it. Am I missing something?



##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }
+                    catch (Throwable t)
+                    {
+                        failExclusive(next, t);
+                        throw t;
+                    }
+                }
+                case WAITING_TO_SCAN_RANGES:
+                    if (activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR)

Review Comment:
   on closer inspection; we have another nested while loop below which can change this count.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1829042341


##########
src/java/org/apache/cassandra/config/AccordSpec.java:
##########
@@ -35,18 +37,71 @@ public class AccordSpec
 
     public volatile boolean enable_journal_compaction = true;
 
-    public volatile OptionaldPositiveInt shard_count = OptionaldPositiveInt.UNDEFINED;
+    public enum QueueShardModel
+    {
+        /**
+         * Same number of threads as queue shards, but the shard lock is held only while managing the queue,
+         * so that submitting threads may queue load/save work.
+         *
+         * The global READ and WRITE stages are used for IO.
+         */
+        THREAD_PER_SHARD,
+
+        /**
+         * Same number of threads as shards, and the shard lock is held for the duration of serving requests.
+         * The global READ and WRITE stages are used for IO.
+         */
+        THREAD_PER_SHARD_SYNC_QUEUE,
+
+        /**
+         * More threads than shards. Threads update transaction state as well as performing IO, minimising context switching.
+         * Fewer shards is generally better, until queue-contention is encountered.
+         */
+        THREAD_POOL_PER_SHARD,
+
+        /**
+         * More threads than shards. Threads update transaction state only, relying on READ and WRITE stages for IO.
+         * Fewer shards is generally better, until queue-contention is encountered.
+         */
+        THREAD_POOL_PER_SHARD_EXCLUDES_IO,
+    }
+
+    public enum QueueSubmissionModel
+    {
+        SYNC, SEMI_SYNC, ASYNC
+    }
+
+    public QueueShardModel queue_shard_model = THREAD_POOL_PER_SHARD;
+    public QueueSubmissionModel queue_submission_model = SYNC;
+
+    /**
+     * The number of queue (and cache) shards.
+     */
+    public volatile OptionaldPositiveInt queue_shard_count = OptionaldPositiveInt.UNDEFINED;
+
+    /**
+     * The target number of command stores to create per topology shard.
+     * This determines the amount of execution parallelism possible for a given table/shard on the host.
+     * More shards means more parallelism, but more state.
+     *
+     * TODO (expected): make this a table property
+     * TODO (expected): adjust this by proportion of ring
+     */
+    public volatile OptionaldPositiveInt command_store_shard_count = OptionaldPositiveInt.UNDEFINED;

Review Comment:
   If it’s a typo, it’s been there a while… I didn’t rename the type I don’t think?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1829168547


##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }

Review Comment:
   yes, I think you're right



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith commented on code in PR #3651:
URL: https://github.com/apache/cassandra/pull/3651#discussion_r1829181217


##########
src/java/org/apache/cassandra/service/accord/AccordExecutor.java:
##########
@@ -0,0 +1,968 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service.accord;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.Lock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+
+import javax.annotation.Nullable;
+
+import accord.api.Agent;
+import accord.api.RoutingKey;
+import accord.impl.TimestampsForKey;
+import accord.local.Command;
+import accord.local.cfk.CommandsForKey;
+import accord.primitives.TxnId;
+import accord.utils.ArrayBuffers.BufferList;
+import accord.utils.IntrusivePriorityHeap;
+import accord.utils.Invariants;
+import accord.utils.QuadConsumer;
+import accord.utils.QuadFunction;
+import accord.utils.QuintConsumer;
+import accord.utils.TriConsumer;
+import accord.utils.TriFunction;
+import org.agrona.collections.Object2ObjectHashMap;
+import org.apache.cassandra.cache.CacheSize;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.Shutdownable;
+import org.apache.cassandra.metrics.AccordStateCacheMetrics;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import static org.apache.cassandra.service.accord.AccordCachingState.Status.EVICTED;
+import static org.apache.cassandra.service.accord.AccordStateCache.registerJfrListener;
+import static org.apache.cassandra.service.accord.AccordTask.State.LOADING;
+import static org.apache.cassandra.service.accord.AccordTask.State.SCANNING_RANGES;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_LOAD;
+import static org.apache.cassandra.service.accord.AccordTask.State.WAITING_TO_RUN;
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+
+public abstract class AccordExecutor implements CacheSize, AccordCachingState.OnLoaded, AccordCachingState.OnSaved, Shutdownable
+{
+    public interface AccordExecutorFactory
+    {
+        AccordExecutor get(int executorId, Mode mode, int threads, IntFunction<String> name, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent);
+    }
+
+    public enum Mode { RUN_WITH_LOCK, RUN_WITHOUT_LOCK }
+
+    public interface ExecutorFunction extends Function<Runnable, Future<?>> {}
+    public interface ExecutorFunctionFactory extends Function<AccordExecutor, ExecutorFunction> {}
+
+    // WARNING: this is a shared object, so close is NOT idempotent
+    public static final class ExclusiveGlobalCaches implements AutoCloseable
+    {
+        final Lock lock;
+        public final AccordStateCache global;
+        public final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        public final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        public final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+
+        public ExclusiveGlobalCaches(Lock lock, AccordStateCache global, AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands, AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey, AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey)
+        {
+            this.lock = lock;
+            this.global = global;
+            this.commands = commands;
+            this.timestampsForKey = timestampsForKey;
+            this.commandsForKey = commandsForKey;
+        }
+
+        @Override
+        public void close()
+        {
+            lock.unlock();
+        }
+    }
+
+    private static final int MAX_QUEUED_LOADS_PER_EXECUTOR = 64;
+    private static final int MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR = 8;
+
+    final Lock lock;
+    final Agent agent;
+    final int executorId;
+    private final AccordStateCache cache;
+    private final ExecutorFunction loadExecutor;
+    private final ExecutorFunction rangeLoadExecutor;
+
+    private final TaskQueue<AccordTask<?>> scanningRanges = new TaskQueue<>(SCANNING_RANGES); // never queried, just parked here while scanning
+    private final TaskQueue<AccordTask<?>> loading = new TaskQueue<>(LOADING); // never queried, just parked here while loading
+
+    private @Nullable TaskQueue<AccordTask<?>> waitingToLoadRangeTxns; // this is kept null whenever the queue is empty (i.e. normally)
+    private final TaskQueue<AccordTask<?>> waitingToLoadRangeTxnsCollection = new TaskQueue<>(WAITING_TO_LOAD);
+
+    private final TaskQueue<AccordTask<?>> waitingToLoad = new TaskQueue<>(WAITING_TO_LOAD);
+    private final TaskQueue<Task> waitingToRun = new TaskQueue<>(WAITING_TO_RUN);
+    private final Object2ObjectHashMap<AccordCommandStore, CommandStoreQueue> commandStoreQueues = new Object2ObjectHashMap<>();
+
+    private final AccordCachingState.OnLoaded onRangeLoaded = this::onRangeLoaded;
+    private final ExclusiveGlobalCaches locked;
+
+    private long maxWorkingSetSizeInBytes;
+    private long maxWorkingCapacityInBytes;
+    private int nextPosition;
+    private int activeLoads, activeRangeLoads;
+    private boolean hasPausedLoading;
+    int tasks;
+    int running;
+
+    AccordExecutor(Lock lock, int executorId, AccordStateCacheMetrics metrics, ExecutorFunctionFactory loadExecutor, ExecutorFunctionFactory saveExecutor, ExecutorFunctionFactory rangeLoadExecutor, Agent agent)
+    {
+        this.lock = lock;
+        this.executorId = executorId;
+        this.cache = new AccordStateCache(saveExecutor.apply(this), this, 0, metrics);
+        this.loadExecutor = loadExecutor.apply(this);
+        this.rangeLoadExecutor = rangeLoadExecutor.apply(this);
+        this.agent = agent;
+
+        final AccordStateCache.Type<TxnId, Command, AccordSafeCommand> commands;
+        final AccordStateCache.Type<RoutingKey, TimestampsForKey, AccordSafeTimestampsForKey> timestampsForKey;
+        final AccordStateCache.Type<RoutingKey, CommandsForKey, AccordSafeCommandsForKey> commandsForKey;
+        commands = cache.newType(TxnId.class,
+                                 AccordSafeCommand.class,
+                                 AccordSafeCommand.safeRefFactory(),
+                                 AccordCommandStore::loadCommand,
+                                 AccordCommandStore::appendToKeyspace,
+                                 AccordCommandStore::validateCommand,
+                                 // TODO (expected): size diff method, so we only revisit portions that have changed
+                                 AccordObjectSizes::command);
+        registerJfrListener(executorId, commands, "Command");
+        timestampsForKey = cache.newType(RoutingKey.class,
+                                         AccordSafeTimestampsForKey.class,
+                                         AccordSafeTimestampsForKey::new,
+                                         AccordCommandStore::loadTimestampsForKey,
+                                         AccordCommandStore::saveTimestampsForKey,
+                                         AccordCommandStore::validateTimestampsForKey,
+                                         AccordObjectSizes::timestampsForKey);
+        registerJfrListener(executorId, timestampsForKey, "TimestampsForKey");
+        commandsForKey = cache.newType(RoutingKey.class,
+                                       AccordSafeCommandsForKey.class,
+                                       AccordSafeCommandsForKey::new,
+                                       AccordCommandStore::loadCommandsForKey,
+                                       AccordCommandStore::saveCommandsForKey,
+                                       AccordCommandStore::validateCommandsForKey,
+                                       AccordObjectSizes::commandsForKey);
+        registerJfrListener(executorId, commandsForKey, "CommandsForKey");
+
+        this.locked = new ExclusiveGlobalCaches(lock, cache, commands, timestampsForKey, commandsForKey);
+    }
+
+    public int executorId()
+    {
+        return executorId;
+    }
+
+    public ExclusiveGlobalCaches lockCaches()
+    {
+        //noinspection LockAcquiredButNotSafelyReleased
+        lock.lock();
+        return locked;
+    }
+
+    public AccordStateCache cacheUnsafe()
+    {
+        return cache;
+    }
+
+    boolean hasWaitingToRun()
+    {
+        updateWaitingToRunExclusive();
+        return !waitingToRun.isEmpty();
+    }
+
+    Task pollWaitingToRunExclusive()
+    {
+        updateWaitingToRunExclusive();
+        return waitingToRun.poll();
+    }
+
+    void updateWaitingToRunExclusive()
+    {
+        maybeUnpauseLoading();
+    }
+
+    void maybeUnpauseLoading()
+    {
+        if (!hasPausedLoading)
+            return;
+
+        if (cache.weightedSize() < maxWorkingCapacityInBytes || (loading.isEmpty() && waitingToRun.isEmpty()))
+        {
+            hasPausedLoading = false;
+            enqueueLoadsExclusive();
+        }
+    }
+
+    abstract boolean hasTasks();
+    abstract boolean isInThread();
+
+    private void enqueueLoadsExclusive()
+    {
+        outer: while (true)
+        {
+            if (hasPausedLoading || cache.weightedSize() >= maxWorkingCapacityInBytes)
+            {
+                // we have too much in memory already, and we have work waiting to run, so let that complete before queueing more
+                if (!loading.isEmpty() || !waitingToRun.isEmpty())
+                {
+                    hasPausedLoading = true;
+                    return;
+                }
+            }
+
+            TaskQueue<AccordTask<?>> queue = waitingToLoadRangeTxns == null || activeRangeLoads >= MAX_QUEUED_RANGE_LOADS_PER_EXECUTOR ? waitingToLoad : waitingToLoadRangeTxns;
+            AccordTask<?> next = queue.peek();
+            if (next == null)
+                return;
+
+            switch (next.state())
+            {
+                default:
+                {
+                    try { throw new AssertionError("Unexpected state: " + next.toDescription()); }

Review Comment:
   oh, I'm also throwing this exception



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] Accord: Improved work queueing and execution [cassandra]

Posted by "belliottsmith (via GitHub)" <gi...@apache.org>.
belliottsmith closed pull request #3651: Accord: Improved work queueing and execution
URL: https://github.com/apache/cassandra/pull/3651


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org