dcapwell commented on code in PR #49:
URL: https://github.com/apache/cassandra-accord/pull/49#discussion_r1223501960


##########
accord-core/src/main/java/accord/impl/AbstractConfigurationService.java:
##########
@@ -0,0 +1,337 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.primitives.Ints;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.ConfigurationService;
+import accord.local.Node;
+import accord.topology.Topology;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChain;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+public abstract class AbstractConfigurationService<EpochState extends 
AbstractConfigurationService.AbstractEpochState,

Review Comment:
   reading this class I really wonder if we should have a `CommandStore` for 
metadata (owns no ranges)... this logic would be fine with `CommandStore` but 
feel that it isn't consistent when run outside, so gets harder to be correct



##########
accord-core/src/main/java/accord/impl/AbstractConfigurationService.java:
##########
@@ -0,0 +1,337 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.primitives.Ints;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.ConfigurationService;
+import accord.local.Node;
+import accord.topology.Topology;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChain;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+public abstract class AbstractConfigurationService<EpochState extends 
AbstractConfigurationService.AbstractEpochState,
+                                                   EpochHistory extends 
AbstractConfigurationService.AbstractEpochHistory<EpochState>>
+                      implements ConfigurationService
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractConfigurationService.class);
+
+    protected final Node.Id localId;
+
+    protected final EpochHistory epochs = createEpochHistory();
+
+    protected final List<Listener> listeners = new ArrayList<>();
+
+    public abstract static class AbstractEpochState
+    {
+        protected final long epoch;
+        protected final AsyncResult.Settable<Topology> received = 
AsyncResults.settable();
+        protected final AsyncResult.Settable<Void> acknowledged = 
AsyncResults.settable();
+        protected AsyncResult<Void> reads = null;
+
+        protected Topology topology = null;
+
+        public AbstractEpochState(long epoch)
+        {
+            this.epoch = epoch;
+        }
+
+        public long epoch()
+        {
+            return epoch;
+        }
+
+        @Override
+        public String toString()
+        {
+            return "EpochState{" + epoch + '}';
+        }
+    }
+
+    @VisibleForTesting
+    public abstract static class AbstractEpochHistory<EpochState extends 
AbstractEpochState>
+    {
+        // TODO (low priority): move pendingEpochs / FetchTopology into here?
+        private List<EpochState> epochs = new ArrayList<>();
+
+        protected long lastReceived = 0;
+        protected long lastAcknowledged = 0;
+
+        protected abstract EpochState createEpochState(long epoch);
+
+        public long minEpoch()
+        {
+            return epochs.isEmpty() ? 0L : epochs.get(0).epoch;
+        }
+
+        public long maxEpoch()
+        {
+            int size = epochs.size();
+            return size == 0 ? 0L : epochs.get(size - 1).epoch;
+        }
+
+        @VisibleForTesting
+        EpochState atIndex(int idx)
+        {
+            return epochs.get(idx);
+        }
+
+        @VisibleForTesting
+        int size()
+        {
+            return epochs.size();
+        }
+
+        EpochState getOrCreate(long epoch)
+        {
+            Invariants.checkArgument(epoch > 0, "Epoch must be positive but 
given %d", epoch);
+            if (epochs.isEmpty())
+            {
+                EpochState state = createEpochState(epoch);
+                epochs.add(state);
+                return state;
+            }
+
+            long minEpoch = minEpoch();
+            if (epoch < minEpoch)
+            {
+                int prepend = Ints.checkedCast(minEpoch - epoch);
+                List<EpochState> next = new ArrayList<>(epochs.size() + 
prepend);
+                for (long addEpoch=epoch; addEpoch<minEpoch; addEpoch++)
+                    next.add(createEpochState(addEpoch));
+                next.addAll(epochs);
+                epochs = next;
+                minEpoch = minEpoch();
+                Invariants.checkState(minEpoch == epoch);
+            }
+            long maxEpoch = maxEpoch();
+            int idx = Ints.checkedCast(epoch - minEpoch);
+
+            // add any missing epochs
+            for (long addEpoch = maxEpoch + 1; addEpoch <= epoch; addEpoch++)
+                epochs.add(createEpochState(addEpoch));
+
+            return epochs.get(idx);
+        }
+
+        public void receive(Topology topology)
+        {
+            long epoch = topology.epoch();
+            Invariants.checkState(lastReceived == epoch - 1 || epoch == 0 || 
lastReceived == 0,
+                                  "Epoch %d != %d + 1", epoch, lastReceived);
+            lastReceived = epoch;
+            EpochState state = getOrCreate(epoch);
+            state.topology = topology;
+            state.received.setSuccess(topology);
+        }
+
+        AsyncResult<Topology> receiveFuture(long epoch)
+        {
+            return getOrCreate(epoch).received;
+        }
+
+        Topology topologyFor(long epoch)
+        {
+            return getOrCreate(epoch).topology;
+        }
+
+        public void acknowledge(EpochReady ready)
+        {
+            long epoch = ready.epoch;
+            Invariants.checkState(lastAcknowledged == epoch - 1 || epoch == 0 
|| lastAcknowledged == 0,
+                                  "Epoch %d != %d + 1", epoch, 
lastAcknowledged);
+            lastAcknowledged = epoch;
+            EpochState state = getOrCreate(epoch);
+            Invariants.checkState(state.reads == null, "Reads result was 
already set for epoch", epoch);
+            state.reads = ready.reads;
+            state.acknowledged.setSuccess(null);
+        }
+
+        AsyncResult<Void> acknowledgeFuture(long epoch)
+        {
+            return getOrCreate(epoch).acknowledged;
+        }
+
+        void truncateUntil(long epoch)
+        {
+            Invariants.checkArgument(epoch <= maxEpoch(), "epoch %d > %d", 
epoch, maxEpoch());
+            long minEpoch = minEpoch();
+            int toTrim = Ints.checkedCast(epoch - minEpoch);
+            if (toTrim <=0)

Review Comment:
   ```suggestion
               if (toTrim <= 0)
   ```



##########
accord-core/src/main/java/accord/impl/AbstractConfigurationService.java:
##########
@@ -0,0 +1,337 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.primitives.Ints;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.ConfigurationService;
+import accord.local.Node;
+import accord.topology.Topology;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChain;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+public abstract class AbstractConfigurationService<EpochState extends 
AbstractConfigurationService.AbstractEpochState,
+                                                   EpochHistory extends 
AbstractConfigurationService.AbstractEpochHistory<EpochState>>
+                      implements ConfigurationService
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractConfigurationService.class);
+
+    protected final Node.Id localId;
+
+    protected final EpochHistory epochs = createEpochHistory();
+
+    protected final List<Listener> listeners = new ArrayList<>();
+
+    public abstract static class AbstractEpochState
+    {
+        protected final long epoch;
+        protected final AsyncResult.Settable<Topology> received = 
AsyncResults.settable();
+        protected final AsyncResult.Settable<Void> acknowledged = 
AsyncResults.settable();
+        protected AsyncResult<Void> reads = null;
+
+        protected Topology topology = null;
+
+        public AbstractEpochState(long epoch)
+        {
+            this.epoch = epoch;
+        }
+
+        public long epoch()
+        {
+            return epoch;
+        }
+
+        @Override
+        public String toString()
+        {
+            return "EpochState{" + epoch + '}';
+        }
+    }
+
+    @VisibleForTesting
+    public abstract static class AbstractEpochHistory<EpochState extends 
AbstractEpochState>
+    {
+        // TODO (low priority): move pendingEpochs / FetchTopology into here?
+        private List<EpochState> epochs = new ArrayList<>();
+
+        protected long lastReceived = 0;
+        protected long lastAcknowledged = 0;
+
+        protected abstract EpochState createEpochState(long epoch);
+
+        public long minEpoch()
+        {
+            return epochs.isEmpty() ? 0L : epochs.get(0).epoch;
+        }
+
+        public long maxEpoch()
+        {
+            int size = epochs.size();
+            return size == 0 ? 0L : epochs.get(size - 1).epoch;
+        }
+
+        @VisibleForTesting
+        EpochState atIndex(int idx)
+        {
+            return epochs.get(idx);
+        }
+
+        @VisibleForTesting
+        int size()
+        {
+            return epochs.size();
+        }
+
+        EpochState getOrCreate(long epoch)
+        {
+            Invariants.checkArgument(epoch > 0, "Epoch must be positive but 
given %d", epoch);
+            if (epochs.isEmpty())
+            {
+                EpochState state = createEpochState(epoch);
+                epochs.add(state);
+                return state;
+            }
+
+            long minEpoch = minEpoch();
+            if (epoch < minEpoch)
+            {
+                int prepend = Ints.checkedCast(minEpoch - epoch);
+                List<EpochState> next = new ArrayList<>(epochs.size() + 
prepend);
+                for (long addEpoch=epoch; addEpoch<minEpoch; addEpoch++)
+                    next.add(createEpochState(addEpoch));
+                next.addAll(epochs);
+                epochs = next;
+                minEpoch = minEpoch();
+                Invariants.checkState(minEpoch == epoch);

Review Comment:
   ```suggestion
                   Invariants.checkState(minEpoch == epoch, "Epoch %d != %d", 
epoch, minEpoch);
   ```



##########
accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.Data;
+import accord.api.DataStore;
+import accord.coordinate.FetchCoordinator;
+import accord.local.CommandStore;
+import accord.local.Node;
+import accord.local.Status;
+import accord.messages.Callback;
+import accord.messages.MessageType;
+import accord.messages.ReadData;
+import accord.messages.WaitAndReadData;
+import accord.primitives.PartialDeps;
+import accord.primitives.PartialTxn;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+import static accord.primitives.Routables.Slice.Minimal;
+
+public abstract class AbstractFetchCoordinator extends FetchCoordinator
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractFetchCoordinator.class);
+
+    static class FetchResult extends AsyncResults.SettableResult<Ranges> 
implements DataStore.FetchResult
+    {
+        final AbstractFetchCoordinator coordinator;
+
+        FetchResult(AbstractFetchCoordinator coordinator)
+        {
+            this.coordinator = coordinator;
+        }
+
+        @Override
+        public void abort(Ranges abort)
+        {
+            coordinator.abort(abort);
+        }
+    }
+
+    static class Key
+    {
+        final Node.Id id;
+        final Ranges ranges;
+
+        Key(Node.Id id, Ranges ranges)
+        {
+            this.id = id;
+            this.ranges = ranges;
+        }
+
+        @Override
+        public int hashCode()
+        {
+            return id.hashCode() + ranges.hashCode();
+        }
+
+        @Override
+        public boolean equals(Object obj)
+        {
+            if (this == obj) return true;
+            if (!(obj instanceof Key)) return false;
+            Key that = (Key) obj;
+            return id.equals(that.id) && ranges.equals(that.ranges);
+        }
+    }
+
+    final DataStore.FetchRanges fetchRanges;
+    final CommandStore commandStore;
+    final Map<Key, DataStore.StartingRangeFetch> inflight = new HashMap<>();
+    final FetchResult result = new FetchResult(this);
+    final List<AsyncResult<Void>> persisting = new ArrayList<>();
+
+    protected AbstractFetchCoordinator(Node node, Ranges ranges, SyncPoint 
syncPoint, DataStore.FetchRanges fetchRanges, CommandStore commandStore)
+    {
+        super(node, ranges, syncPoint, fetchRanges);
+        this.fetchRanges = fetchRanges;
+        this.commandStore = commandStore;
+    }
+
+    protected abstract PartialTxn rangeReadTxn(Ranges ranges);
+
+    protected abstract void onReadOk(Node.Id from, CommandStore commandStore, 
Data data, Ranges ranges);
+
+    @Override
+    public void contact(Node.Id to, Ranges ranges)
+    {
+        Key key = new Key(to, ranges);
+        inflight.put(key, starting(to, ranges));
+        Ranges ownedRanges = ownedRangesForNode(to);
+        Invariants.checkArgument(ownedRanges.containsAll(ranges));
+        PartialDeps partialDeps = syncPoint.waitFor.slice(ownedRanges, ranges);
+        node.send(to, new FetchRequest(syncPoint.sourceEpoch(), 
syncPoint.syncId, ranges, partialDeps, rangeReadTxn(ranges)), new 
Callback<ReadData.ReadReply>()
+        {
+            @Override
+            public void onSuccess(Node.Id from, ReadData.ReadReply reply)
+            {
+                if (!reply.isOk())
+                {
+                    fail(to, new RuntimeException(reply.toString()));
+                    inflight.remove(key).cancel();
+                    switch ((ReadData.ReadNack) reply)
+                    {
+                        default: throw new AssertionError("Unhandled enum: " + 
reply);
+                        case Invalid:
+                        case Redundant:
+                        case NotCommitted:
+                            throw new AssertionError(String.format("Unexpected 
reply: %s", reply));
+                        case Error:
+                            // TODO (required): ensure errors are propagated 
to coordinators and can be logged
+                    }
+                    return;
+                }
+
+                FetchResponse ok = (FetchResponse) reply;
+                Ranges received;
+                if (ok.unavailable != null)
+                {
+                    unavailable(to, ok.unavailable);
+                    if (ok.data == null)
+                    {
+                        inflight.remove(key).cancel();
+                        return;
+                    }
+                    received = ranges.difference(ok.unavailable);
+                }
+                else
+                {
+                    received = ranges;
+                }
+
+                // TODO (now): make sure it works if invoked in either order
+                inflight.remove(key).started(ok.maxApplied);
+                onReadOk(to, commandStore, ok.data, received);
+                // received must be invoked after submitting the persistence 
future, as it triggers onDone
+                // which creates a ReducingFuture over {@code persisting}
+            }
+
+            @Override
+            public void onFailure(Node.Id from, Throwable failure)
+            {
+                inflight.remove(key).cancel();
+                fail(from, failure);
+            }
+
+            @Override
+            public void onCallbackFailure(Node.Id from, Throwable failure)
+            {
+                // TODO (soon)
+                logger.error("Fetch coordination failure from " + from, 
failure);
+            }
+        });
+    }
+
+    @Override
+    protected synchronized void success(Node.Id to, Ranges ranges)
+    {
+        super.success(to, ranges);
+    }
+
+    @Override
+    protected synchronized void fail(Node.Id to, Ranges ranges, Throwable 
failure)
+    {
+        super.fail(to, ranges, failure);
+    }
+
+    public FetchResult result()
+    {
+        return result;
+    }
+
+    @Override
+    protected void onDone(Ranges success, Throwable failure)
+    {
+        if (success.isEmpty()) result.setFailure(failure);
+        else if (persisting.isEmpty()) result.setSuccess(Ranges.EMPTY);
+        else AsyncChains.reduce(persisting, (a, b) -> null)
+                        .begin((s, f) -> {
+                            if (f == null) result.setSuccess(ranges);
+                            else result.setFailure(f);
+                        });
+    }
+
+    @Override
+    public void start()
+    {
+        super.start();
+    }
+
+    void abort(Ranges abort)

Review Comment:
   maybe make `abstract` for now?  `ListFetchCoordinator` is the only usage atm 
and could no-op it for now



##########
accord-core/src/main/java/accord/impl/InMemoryCommandStore.java:
##########
@@ -461,6 +461,19 @@ void update(Ranges add)
         }
     }
 
+    public AsyncChain<Timestamp> maxAppliedFor(Seekables<?, ?> keysOrRanges, 
Ranges slice)
+    {
+        Seekables<?, ?> sliced = keysOrRanges.slice(slice, Minimal);
+        Timestamp timestamp = Timestamp.NONE;
+        for (GlobalCommand globalCommand : commands.values())

Review Comment:
   I believe this doesn't include range commands; they are in 
`accord.impl.InMemoryCommandStore#rangeCommands`...  I feel it's best to do 
`mapReduce` here as that would also work in the C* case and makes sure range 
and key are both supported.... this is what we do in C*
   
   ```
   @Override
       public Timestamp maxConflict(Seekables<?, ?> keysOrRanges, Ranges slice)
       {
           return mapReduce(keysOrRanges, slice, (ts, accum) -> 
Timestamp.max(ts.max(), accum), Timestamp.NONE, null);
       }
   ```
   
   
   I think you would need to do `accord.local.SafeCommandStore#mapReduce` for 
that though



##########
accord-core/src/main/java/accord/local/CommandStore.java:
##########
@@ -128,6 +128,8 @@ public RangesForEpochHolder rangesForEpochHolder()
 
     public abstract void shutdown();
 
+    public abstract AsyncChain<Timestamp> maxAppliedFor(Seekables<?, ?> 
keysOrRanges, Ranges slice);

Review Comment:
   I feel this is best in `SafeCommandStore`, at least in the C* case you would 
need to do (logically)
   
   ```
   return submit(PreloadContext.contextFor(keysOrRanges), safe -> 
safe.maxAppliedFor(keysOrRanges, Ranges slice);
   ```



##########
accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.Data;
+import accord.api.DataStore;
+import accord.coordinate.FetchCoordinator;
+import accord.local.CommandStore;
+import accord.local.Node;
+import accord.local.Status;
+import accord.messages.Callback;
+import accord.messages.MessageType;
+import accord.messages.ReadData;
+import accord.messages.WaitAndReadData;
+import accord.primitives.PartialDeps;
+import accord.primitives.PartialTxn;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+import static accord.primitives.Routables.Slice.Minimal;
+
+public abstract class AbstractFetchCoordinator extends FetchCoordinator
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractFetchCoordinator.class);
+
+    static class FetchResult extends AsyncResults.SettableResult<Ranges> 
implements DataStore.FetchResult
+    {
+        final AbstractFetchCoordinator coordinator;
+
+        FetchResult(AbstractFetchCoordinator coordinator)
+        {
+            this.coordinator = coordinator;
+        }
+
+        @Override
+        public void abort(Ranges abort)
+        {
+            coordinator.abort(abort);
+        }
+    }
+
+    static class Key
+    {
+        final Node.Id id;
+        final Ranges ranges;
+
+        Key(Node.Id id, Ranges ranges)
+        {
+            this.id = id;
+            this.ranges = ranges;
+        }
+
+        @Override
+        public int hashCode()
+                         {
+                            return id.hashCode() + ranges.hashCode();
+                                                                     }
+
+        @Override
+        public boolean equals(Object obj)
+        {
+            if (this == obj) return true;
+            if (!(obj instanceof Key)) return false;
+            Key that = (Key) obj;
+            return id.equals(that.id) && ranges.equals(that.ranges);
+        }
+    }
+
+    final DataStore.FetchRanges fetchRanges;
+    final CommandStore commandStore;
+    final Map<Key, DataStore.StartingRangeFetch> inflight = new HashMap<>();
+    final FetchResult result = new FetchResult(this);
+    final List<AsyncResult<Void>> persisting = new ArrayList<>();
+
+    protected AbstractFetchCoordinator(Node node, Ranges ranges, SyncPoint 
syncPoint, DataStore.FetchRanges fetchRanges, CommandStore commandStore)
+    {
+        super(node, ranges, syncPoint, fetchRanges);
+        this.fetchRanges = fetchRanges;
+        this.commandStore = commandStore;
+    }
+
+    protected abstract PartialTxn rangeReadTxn(Ranges ranges);
+
+    protected abstract void onReadOk(Node.Id from, CommandStore commandStore, 
Data data, Ranges ranges);
+
+    @Override
+    public void contact(Node.Id to, Ranges ranges)
+    {
+        Key key = new Key(to, ranges);
+        inflight.put(key, starting(to, ranges));
+        Ranges ownedRanges = ownedRangesForNode(to);
+        Invariants.checkArgument(ownedRanges.containsAll(ranges));
+        PartialDeps partialDeps = syncPoint.waitFor.slice(ownedRanges, ranges);
+        node.send(to, new FetchRequest(syncPoint.sourceEpoch(), 
syncPoint.syncId, ranges, partialDeps, rangeReadTxn(ranges)), new 
Callback<ReadData.ReadReply>()
+        {
+            @Override
+            public void onSuccess(Node.Id from, ReadData.ReadReply reply)
+            {
+                if (!reply.isOk())
+                {
+                    fail(to, new RuntimeException(reply.toString()));
+                    inflight.remove(key).cancel();
+                    switch ((ReadData.ReadNack) reply)
+                    {
+                        default: throw new AssertionError("Unhandled enum");
+                        case Invalid:
+                        case Redundant:
+                        case NotCommitted:
+                            throw new AssertionError();
+                        case Error:
+                            // TODO (required): ensure errors are propagated 
to coordinators and can be logged
+                    }
+                    return;
+                }
+
+                FetchResponse ok = (FetchResponse) reply;
+                Ranges received;
+                if (ok.unavailable != null)
+                {
+                    unavailable(to, ok.unavailable);
+                    if (ok.data == null)
+                    {
+                        inflight.remove(key).cancel();
+                        return;
+                    }
+                    received = ranges.difference(ok.unavailable);
+                }
+                else
+                {
+                    received = ranges;
+                }
+
+                // TODO (now): make sure it works if invoked in either order
+                inflight.remove(key).started(ok.maxApplied);
+                onReadOk(to, commandStore, ok.data, received);
+                // received must be invoked after submitting the persistence 
future, as it triggers onDone
+                // which creates a ReducingFuture over {@code persisting}
+            }
+
+            @Override
+            public void onFailure(Node.Id from, Throwable failure)
+            {
+                inflight.remove(key).cancel();
+                fail(from, failure);
+            }
+
+            @Override
+            public void onCallbackFailure(Node.Id from, Throwable failure)
+            {
+                // TODO (soon)
+                logger.error("Fetch coordination failure from " + from, 
failure);
+            }
+        });
+    }
+
+    @Override
+    protected synchronized void success(Node.Id to, Ranges ranges)
+    {
+        super.success(to, ranges);
+    }
+
+    @Override
+    protected synchronized void fail(Node.Id to, Ranges ranges, Throwable 
failure)
+    {
+        super.fail(to, ranges, failure);
+    }

Review Comment:
   Also, this class runs in `CommandStore`, so is single threaded... so 
`synchronized` doesn't help



##########
accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.Data;
+import accord.api.DataStore;
+import accord.coordinate.FetchCoordinator;
+import accord.local.CommandStore;
+import accord.local.Node;
+import accord.local.Status;
+import accord.messages.Callback;
+import accord.messages.MessageType;
+import accord.messages.ReadData;
+import accord.messages.WaitAndReadData;
+import accord.primitives.PartialDeps;
+import accord.primitives.PartialTxn;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+import static accord.primitives.Routables.Slice.Minimal;
+
+public abstract class AbstractFetchCoordinator extends FetchCoordinator
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractFetchCoordinator.class);
+
+    static class FetchResult extends AsyncResults.SettableResult<Ranges> 
implements DataStore.FetchResult
+    {
+        final AbstractFetchCoordinator coordinator;
+
+        FetchResult(AbstractFetchCoordinator coordinator)
+        {
+            this.coordinator = coordinator;
+        }
+
+        @Override
+        public void abort(Ranges abort)
+        {
+            coordinator.abort(abort);
+        }
+    }
+
+    static class Key
+    {
+        final Node.Id id;
+        final Ranges ranges;
+
+        Key(Node.Id id, Ranges ranges)
+        {
+            this.id = id;
+            this.ranges = ranges;
+        }
+
+        @Override
+        public int hashCode()
+        {
+            return id.hashCode() + ranges.hashCode();

Review Comment:
   should use `java.util.Objects#hash`. that will become
   
   ```
   (31  + id.hashCode()) * 31 + ranges.hashCode()
   ```



##########
accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.Data;
+import accord.api.DataStore;
+import accord.coordinate.FetchCoordinator;
+import accord.local.CommandStore;
+import accord.local.Node;
+import accord.local.Status;
+import accord.messages.Callback;
+import accord.messages.MessageType;
+import accord.messages.ReadData;
+import accord.messages.WaitAndReadData;
+import accord.primitives.PartialDeps;
+import accord.primitives.PartialTxn;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+import static accord.primitives.Routables.Slice.Minimal;
+
+public abstract class AbstractFetchCoordinator extends FetchCoordinator
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractFetchCoordinator.class);
+
+    static class FetchResult extends AsyncResults.SettableResult<Ranges> 
implements DataStore.FetchResult
+    {
+        final AbstractFetchCoordinator coordinator;
+
+        FetchResult(AbstractFetchCoordinator coordinator)
+        {
+            this.coordinator = coordinator;
+        }
+
+        @Override
+        public void abort(Ranges abort)
+        {
+            coordinator.abort(abort);
+        }
+    }
+
+    static class Key
+    {
+        final Node.Id id;
+        final Ranges ranges;
+
+        Key(Node.Id id, Ranges ranges)
+        {
+            this.id = id;
+            this.ranges = ranges;
+        }
+
+        @Override
+        public int hashCode()
+        {
+            return id.hashCode() + ranges.hashCode();
+        }
+
+        @Override
+        public boolean equals(Object obj)
+        {
+            if (this == obj) return true;
+            if (!(obj instanceof Key)) return false;
+            Key that = (Key) obj;
+            return id.equals(that.id) && ranges.equals(that.ranges);
+        }
+    }
+
+    final DataStore.FetchRanges fetchRanges;
+    final CommandStore commandStore;
+    final Map<Key, DataStore.StartingRangeFetch> inflight = new HashMap<>();
+    final FetchResult result = new FetchResult(this);
+    final List<AsyncResult<Void>> persisting = new ArrayList<>();
+
+    protected AbstractFetchCoordinator(Node node, Ranges ranges, SyncPoint 
syncPoint, DataStore.FetchRanges fetchRanges, CommandStore commandStore)
+    {
+        super(node, ranges, syncPoint, fetchRanges);
+        this.fetchRanges = fetchRanges;
+        this.commandStore = commandStore;
+    }
+
+    protected abstract PartialTxn rangeReadTxn(Ranges ranges);
+
+    protected abstract void onReadOk(Node.Id from, CommandStore commandStore, 
Data data, Ranges ranges);
+
+    @Override
+    public void contact(Node.Id to, Ranges ranges)
+    {
+        Key key = new Key(to, ranges);
+        inflight.put(key, starting(to, ranges));
+        Ranges ownedRanges = ownedRangesForNode(to);
+        Invariants.checkArgument(ownedRanges.containsAll(ranges));
+        PartialDeps partialDeps = syncPoint.waitFor.slice(ownedRanges, ranges);
+        node.send(to, new FetchRequest(syncPoint.sourceEpoch(), 
syncPoint.syncId, ranges, partialDeps, rangeReadTxn(ranges)), new 
Callback<ReadData.ReadReply>()
+        {
+            @Override
+            public void onSuccess(Node.Id from, ReadData.ReadReply reply)
+            {
+                if (!reply.isOk())
+                {
+                    fail(to, new RuntimeException(reply.toString()));
+                    inflight.remove(key).cancel();
+                    switch ((ReadData.ReadNack) reply)
+                    {
+                        default: throw new AssertionError("Unhandled enum: " + 
reply);
+                        case Invalid:
+                        case Redundant:
+                        case NotCommitted:
+                            throw new AssertionError(String.format("Unexpected 
reply: %s", reply));
+                        case Error:
+                            // TODO (required): ensure errors are propagated 
to coordinators and can be logged
+                    }
+                    return;
+                }
+
+                FetchResponse ok = (FetchResponse) reply;
+                Ranges received;
+                if (ok.unavailable != null)
+                {
+                    unavailable(to, ok.unavailable);
+                    if (ok.data == null)
+                    {
+                        inflight.remove(key).cancel();
+                        return;
+                    }
+                    received = ranges.difference(ok.unavailable);
+                }
+                else
+                {
+                    received = ranges;
+                }
+
+                // TODO (now): make sure it works if invoked in either order
+                inflight.remove(key).started(ok.maxApplied);
+                onReadOk(to, commandStore, ok.data, received);
+                // received must be invoked after submitting the persistence 
future, as it triggers onDone
+                // which creates a ReducingFuture over {@code persisting}
+            }
+
+            @Override
+            public void onFailure(Node.Id from, Throwable failure)
+            {
+                inflight.remove(key).cancel();
+                fail(from, failure);
+            }
+
+            @Override
+            public void onCallbackFailure(Node.Id from, Throwable failure)
+            {
+                // TODO (soon)
+                logger.error("Fetch coordination failure from " + from, 
failure);
+            }
+        });
+    }
+
+    @Override
+    protected synchronized void success(Node.Id to, Ranges ranges)
+    {
+        super.success(to, ranges);
+    }
+
+    @Override
+    protected synchronized void fail(Node.Id to, Ranges ranges, Throwable 
failure)
+    {
+        super.fail(to, ranges, failure);
+    }
+
+    public FetchResult result()
+    {
+        return result;
+    }
+
+    @Override
+    protected void onDone(Ranges success, Throwable failure)
+    {
+        if (success.isEmpty()) result.setFailure(failure);

Review Comment:
   ```suggestion
           if (failure != null) result.setFailure(failure);
   ```



##########
accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.Data;
+import accord.api.DataStore;
+import accord.coordinate.FetchCoordinator;
+import accord.local.CommandStore;
+import accord.local.Node;
+import accord.local.Status;
+import accord.messages.Callback;
+import accord.messages.MessageType;
+import accord.messages.ReadData;
+import accord.messages.WaitAndReadData;
+import accord.primitives.PartialDeps;
+import accord.primitives.PartialTxn;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+import static accord.primitives.Routables.Slice.Minimal;
+
+public abstract class AbstractFetchCoordinator extends FetchCoordinator
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractFetchCoordinator.class);
+
+    static class FetchResult extends AsyncResults.SettableResult<Ranges> 
implements DataStore.FetchResult
+    {
+        final AbstractFetchCoordinator coordinator;
+
+        FetchResult(AbstractFetchCoordinator coordinator)
+        {
+            this.coordinator = coordinator;
+        }
+
+        @Override
+        public void abort(Ranges abort)
+        {
+            coordinator.abort(abort);
+        }
+    }
+
+    static class Key
+    {
+        final Node.Id id;
+        final Ranges ranges;
+
+        Key(Node.Id id, Ranges ranges)
+        {
+            this.id = id;
+            this.ranges = ranges;
+        }
+
+        @Override
+        public int hashCode()
+        {
+            return id.hashCode() + ranges.hashCode();
+        }
+
+        @Override
+        public boolean equals(Object obj)
+        {
+            if (this == obj) return true;
+            if (!(obj instanceof Key)) return false;
+            Key that = (Key) obj;
+            return id.equals(that.id) && ranges.equals(that.ranges);
+        }
+    }
+
+    final DataStore.FetchRanges fetchRanges;
+    final CommandStore commandStore;
+    final Map<Key, DataStore.StartingRangeFetch> inflight = new HashMap<>();
+    final FetchResult result = new FetchResult(this);
+    final List<AsyncResult<Void>> persisting = new ArrayList<>();
+
+    protected AbstractFetchCoordinator(Node node, Ranges ranges, SyncPoint 
syncPoint, DataStore.FetchRanges fetchRanges, CommandStore commandStore)
+    {
+        super(node, ranges, syncPoint, fetchRanges);
+        this.fetchRanges = fetchRanges;
+        this.commandStore = commandStore;
+    }
+
+    protected abstract PartialTxn rangeReadTxn(Ranges ranges);
+
+    protected abstract void onReadOk(Node.Id from, CommandStore commandStore, 
Data data, Ranges ranges);
+
+    @Override
+    public void contact(Node.Id to, Ranges ranges)
+    {
+        Key key = new Key(to, ranges);
+        inflight.put(key, starting(to, ranges));
+        Ranges ownedRanges = ownedRangesForNode(to);
+        Invariants.checkArgument(ownedRanges.containsAll(ranges));

Review Comment:
   ```suggestion
           Invariants.checkArgument(ownedRanges.containsAll(ranges), "Got a 
reply from %s for ranges %s, but owned ranges %s does not contain all the 
ranges", to, ranges, ownedRanges);
   ```



##########
accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.Data;
+import accord.api.DataStore;
+import accord.coordinate.FetchCoordinator;
+import accord.local.CommandStore;
+import accord.local.Node;
+import accord.local.Status;
+import accord.messages.Callback;
+import accord.messages.MessageType;
+import accord.messages.ReadData;
+import accord.messages.WaitAndReadData;
+import accord.primitives.PartialDeps;
+import accord.primitives.PartialTxn;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+import static accord.primitives.Routables.Slice.Minimal;
+
+public abstract class AbstractFetchCoordinator extends FetchCoordinator
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractFetchCoordinator.class);
+
+    static class FetchResult extends AsyncResults.SettableResult<Ranges> 
implements DataStore.FetchResult
+    {
+        final AbstractFetchCoordinator coordinator;
+
+        FetchResult(AbstractFetchCoordinator coordinator)
+        {
+            this.coordinator = coordinator;
+        }
+
+        @Override
+        public void abort(Ranges abort)
+        {
+            coordinator.abort(abort);
+        }
+    }
+
+    static class Key
+    {
+        final Node.Id id;
+        final Ranges ranges;
+
+        Key(Node.Id id, Ranges ranges)
+        {
+            this.id = id;
+            this.ranges = ranges;
+        }
+
+        @Override
+        public int hashCode()
+        {
+            return id.hashCode() + ranges.hashCode();
+        }
+
+        @Override
+        public boolean equals(Object obj)
+        {
+            if (this == obj) return true;
+            if (!(obj instanceof Key)) return false;
+            Key that = (Key) obj;
+            return id.equals(that.id) && ranges.equals(that.ranges);
+        }
+    }
+
+    final DataStore.FetchRanges fetchRanges;
+    final CommandStore commandStore;
+    final Map<Key, DataStore.StartingRangeFetch> inflight = new HashMap<>();
+    final FetchResult result = new FetchResult(this);
+    final List<AsyncResult<Void>> persisting = new ArrayList<>();
+
+    protected AbstractFetchCoordinator(Node node, Ranges ranges, SyncPoint 
syncPoint, DataStore.FetchRanges fetchRanges, CommandStore commandStore)
+    {
+        super(node, ranges, syncPoint, fetchRanges);
+        this.fetchRanges = fetchRanges;
+        this.commandStore = commandStore;
+    }
+
+    protected abstract PartialTxn rangeReadTxn(Ranges ranges);
+
+    protected abstract void onReadOk(Node.Id from, CommandStore commandStore, 
Data data, Ranges ranges);
+
+    @Override
+    public void contact(Node.Id to, Ranges ranges)
+    {
+        Key key = new Key(to, ranges);
+        inflight.put(key, starting(to, ranges));
+        Ranges ownedRanges = ownedRangesForNode(to);
+        Invariants.checkArgument(ownedRanges.containsAll(ranges));
+        PartialDeps partialDeps = syncPoint.waitFor.slice(ownedRanges, ranges);
+        node.send(to, new FetchRequest(syncPoint.sourceEpoch(), 
syncPoint.syncId, ranges, partialDeps, rangeReadTxn(ranges)), new 
Callback<ReadData.ReadReply>()

Review Comment:
   nit: can lower memory cost if `AbstractFetchCoordinator` impl `Callback`...



##########
accord-core/src/test/java/accord/impl/list/ListFetchCoordinator.java:
##########
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl.list;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import accord.api.Data;
+import accord.api.DataStore;
+import accord.impl.AbstractFetchCoordinator;
+import accord.local.CommandStore;
+import accord.local.Node;
+import accord.local.PreLoadContext;
+import accord.primitives.PartialTxn;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.primitives.Txn;
+import accord.utils.Timestamped;
+import accord.utils.async.AsyncResult;
+
+public class ListFetchCoordinator extends AbstractFetchCoordinator
+{
+    private final ListStore listStore;
+    final List<AsyncResult<Void>> persisting = new ArrayList<>();
+
+    public ListFetchCoordinator(Node node, Ranges ranges, SyncPoint syncPoint, 
DataStore.FetchRanges fetchRanges, CommandStore commandStore, ListStore 
listStore)
+    {
+        super(node, ranges, syncPoint, fetchRanges, commandStore);
+        this.listStore = listStore;
+    }
+
+    @Override
+    protected PartialTxn rangeReadTxn(Ranges ranges)
+    {
+        return new PartialTxn.InMemory(ranges, Txn.Kind.Read, ranges, new 
ListRead(unsafeStore -> unsafeStore, ranges, ranges), new 
ListQuery(Node.Id.NONE, Long.MIN_VALUE), null);

Review Comment:
   ```suggestion
           return new PartialTxn.InMemory(ranges, Txn.Kind.Read, ranges, new 
ListRead(Function.identity(), ranges, ranges), new ListQuery(Node.Id.NONE, 
Long.MIN_VALUE), null);
   ```



##########
accord-core/src/main/java/accord/impl/AbstractFetchCoordinator.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.Data;
+import accord.api.DataStore;
+import accord.coordinate.FetchCoordinator;
+import accord.local.CommandStore;
+import accord.local.Node;
+import accord.local.Status;
+import accord.messages.Callback;
+import accord.messages.MessageType;
+import accord.messages.ReadData;
+import accord.messages.WaitAndReadData;
+import accord.primitives.PartialDeps;
+import accord.primitives.PartialTxn;
+import accord.primitives.Ranges;
+import accord.primitives.SyncPoint;
+import accord.primitives.Timestamp;
+import accord.primitives.TxnId;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncChains;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+import static accord.primitives.Routables.Slice.Minimal;
+
+public abstract class AbstractFetchCoordinator extends FetchCoordinator
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractFetchCoordinator.class);
+
+    static class FetchResult extends AsyncResults.SettableResult<Ranges> 
implements DataStore.FetchResult
+    {
+        final AbstractFetchCoordinator coordinator;
+
+        FetchResult(AbstractFetchCoordinator coordinator)
+        {
+            this.coordinator = coordinator;
+        }
+
+        @Override
+        public void abort(Ranges abort)
+        {
+            coordinator.abort(abort);
+        }
+    }
+
+    static class Key
+    {
+        final Node.Id id;
+        final Ranges ranges;
+
+        Key(Node.Id id, Ranges ranges)
+        {
+            this.id = id;
+            this.ranges = ranges;
+        }
+
+        @Override
+        public int hashCode()
+        {
+            return id.hashCode() + ranges.hashCode();
+        }
+
+        @Override
+        public boolean equals(Object obj)
+        {
+            if (this == obj) return true;
+            if (!(obj instanceof Key)) return false;
+            Key that = (Key) obj;
+            return id.equals(that.id) && ranges.equals(that.ranges);
+        }
+    }
+
+    final DataStore.FetchRanges fetchRanges;
+    final CommandStore commandStore;
+    final Map<Key, DataStore.StartingRangeFetch> inflight = new HashMap<>();
+    final FetchResult result = new FetchResult(this);
+    final List<AsyncResult<Void>> persisting = new ArrayList<>();
+
+    protected AbstractFetchCoordinator(Node node, Ranges ranges, SyncPoint 
syncPoint, DataStore.FetchRanges fetchRanges, CommandStore commandStore)
+    {
+        super(node, ranges, syncPoint, fetchRanges);
+        this.fetchRanges = fetchRanges;
+        this.commandStore = commandStore;
+    }
+
+    protected abstract PartialTxn rangeReadTxn(Ranges ranges);
+
+    protected abstract void onReadOk(Node.Id from, CommandStore commandStore, 
Data data, Ranges ranges);
+
+    @Override
+    public void contact(Node.Id to, Ranges ranges)
+    {
+        Key key = new Key(to, ranges);
+        inflight.put(key, starting(to, ranges));
+        Ranges ownedRanges = ownedRangesForNode(to);
+        Invariants.checkArgument(ownedRanges.containsAll(ranges));
+        PartialDeps partialDeps = syncPoint.waitFor.slice(ownedRanges, ranges);
+        node.send(to, new FetchRequest(syncPoint.sourceEpoch(), 
syncPoint.syncId, ranges, partialDeps, rangeReadTxn(ranges)), new 
Callback<ReadData.ReadReply>()
+        {
+            @Override
+            public void onSuccess(Node.Id from, ReadData.ReadReply reply)
+            {
+                if (!reply.isOk())
+                {
+                    fail(to, new RuntimeException(reply.toString()));
+                    inflight.remove(key).cancel();
+                    switch ((ReadData.ReadNack) reply)
+                    {
+                        default: throw new AssertionError("Unhandled enum: " + 
reply);
+                        case Invalid:
+                        case Redundant:
+                        case NotCommitted:
+                            throw new AssertionError(String.format("Unexpected 
reply: %s", reply));
+                        case Error:
+                            // TODO (required): ensure errors are propagated 
to coordinators and can be logged
+                    }
+                    return;
+                }
+
+                FetchResponse ok = (FetchResponse) reply;
+                Ranges received;
+                if (ok.unavailable != null)
+                {
+                    unavailable(to, ok.unavailable);
+                    if (ok.data == null)
+                    {
+                        inflight.remove(key).cancel();
+                        return;
+                    }
+                    received = ranges.difference(ok.unavailable);
+                }
+                else
+                {
+                    received = ranges;
+                }
+
+                // TODO (now): make sure it works if invoked in either order
+                inflight.remove(key).started(ok.maxApplied);
+                onReadOk(to, commandStore, ok.data, received);
+                // received must be invoked after submitting the persistence 
future, as it triggers onDone
+                // which creates a ReducingFuture over {@code persisting}
+            }
+
+            @Override
+            public void onFailure(Node.Id from, Throwable failure)
+            {
+                inflight.remove(key).cancel();

Review Comment:
   it would be nice if `cancel` could take the failure... so we could have a 
global handling of the throwable rather than the caller of this coordinator 
being the only one that could



##########
accord-core/src/main/java/accord/impl/AbstractConfigurationService.java:
##########
@@ -0,0 +1,337 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package accord.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.primitives.Ints;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import accord.api.ConfigurationService;
+import accord.local.Node;
+import accord.topology.Topology;
+import accord.utils.Invariants;
+import accord.utils.async.AsyncResult;
+import accord.utils.async.AsyncResults;
+
+public abstract class AbstractConfigurationService<EpochState extends 
AbstractConfigurationService.AbstractEpochState,
+                                                   EpochHistory extends 
AbstractConfigurationService.AbstractEpochHistory<EpochState>>
+                      implements ConfigurationService
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AbstractConfigurationService.class);
+
+    protected final Node.Id localId;
+
+    protected final EpochHistory epochs = createEpochHistory();
+
+    protected final List<Listener> listeners = new ArrayList<>();
+
+    public abstract static class AbstractEpochState
+    {
+        protected final long epoch;
+        protected final AsyncResult.Settable<Topology> received = 
AsyncResults.settable();
+        protected final AsyncResult.Settable<Void> acknowledged = 
AsyncResults.settable();
+        protected AsyncResult<Void> reads = null;
+
+        protected Topology topology = null;
+
+        public AbstractEpochState(long epoch)
+        {
+            this.epoch = epoch;
+        }
+
+        public long epoch()
+        {
+            return epoch;
+        }
+
+        @Override
+        public String toString()
+        {
+            return "EpochState{" + epoch + '}';
+        }
+    }
+
+    @VisibleForTesting
+    public abstract static class AbstractEpochHistory<EpochState extends 
AbstractEpochState>
+    {
+        // TODO (low priority): move pendingEpochs / FetchTopology into here?
+        private List<EpochState> epochs = new ArrayList<>();
+
+        protected long lastReceived = 0;
+        protected long lastAcknowledged = 0;
+
+        protected abstract EpochState createEpochState(long epoch);
+
+        public long minEpoch()
+        {
+            return epochs.isEmpty() ? 0L : epochs.get(0).epoch;
+        }
+
+        public long maxEpoch()
+        {
+            int size = epochs.size();
+            return size == 0 ? 0L : epochs.get(size - 1).epoch;
+        }
+
+        @VisibleForTesting
+        EpochState atIndex(int idx)
+        {
+            return epochs.get(idx);
+        }
+
+        @VisibleForTesting
+        int size()
+        {
+            return epochs.size();
+        }
+
+        EpochState getOrCreate(long epoch)
+        {
+            Invariants.checkArgument(epoch > 0);
+            if (epochs.isEmpty())
+            {
+                EpochState state = createEpochState(epoch);
+                epochs.add(state);
+                return state;
+            }
+
+            long minEpoch = minEpoch();
+            if (epoch < minEpoch)
+            {
+                int prepend = Ints.checkedCast(minEpoch - epoch);
+                List<EpochState> next = new ArrayList<>(epochs.size() + 
prepend);
+                for (long addEpoch=epoch; addEpoch<minEpoch; addEpoch++)
+                    next.add(createEpochState(addEpoch));
+                next.addAll(epochs);
+                epochs = next;
+                minEpoch = minEpoch();
+                Invariants.checkState(minEpoch == epoch);
+            }
+            long maxEpoch = maxEpoch();
+            int idx = Ints.checkedCast(epoch - minEpoch);
+
+            // add any missing epochs
+            for (long addEpoch = maxEpoch + 1; addEpoch <= epoch; addEpoch++)
+                epochs.add(createEpochState(addEpoch));
+
+            return epochs.get(idx);
+        }
+
+        public void receive(Topology topology)
+        {
+            long epoch = topology.epoch();
+            Invariants.checkState(lastReceived == epoch - 1 || epoch == 0 || 
lastReceived == 0);
+            lastReceived = epoch;
+            EpochState state = getOrCreate(epoch);
+            if (state != null)
+            {
+                state.topology = topology;
+                state.received.setSuccess(topology);
+            }
+        }
+
+        AsyncResult<Topology> receiveFuture(long epoch)
+        {
+            return getOrCreate(epoch).received;
+        }
+
+        Topology topologyFor(long epoch)
+        {
+            return getOrCreate(epoch).topology;
+        }
+
+        public void acknowledge(EpochReady ready)
+        {
+            long epoch = ready.epoch;
+            Invariants.checkState(lastAcknowledged == epoch - 1 || epoch == 0 
|| lastAcknowledged == 0);
+            lastAcknowledged = epoch;
+            EpochState state = getOrCreate(epoch);
+            state.reads = ready.reads;

Review Comment:
   I don't think we actually do synchronize
   
   ```
   public synchronized void acknowledgeEpoch(EpochReady ready)
   {
       ready.metadata.addCallback(() -> epochs.acknowledge(ready));
   ```
   
   `acknowledgeEpoch` is `synchronized`, but there is no reason to as it just 
adds callbacks to a thread safe type... the callbacks can run wherever so these 
methods are not thread safe atm



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to