You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by bd...@apache.org on 2026/09/17 21:50:00 UTC

(cassandra) branch cep-45-mutation-tracking updated (6459184151 -> 2af323f09d)

This is an automated email from the ASF dual-hosted git repository.

bdeggleston pushed a change to branch cep-45-mutation-tracking
in repository https://gitbox.apache.org/repos/asf/cassandra.git


    from 6459184151 CEP-45: Prevent dropping journal segments referenced by partially reconciled sstables
     new 8b5865ce37 Add -Dno-build-accord to skip the gradle subproject build
     new 2af323f09d CEP-45: Track log domains per memtable and isolate tracked sstable compaction

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .build/build-accord.xml                            |   6 +-
 .../pages/managing/operating/metrics.adoc          |   6 +
 .../db/CassandraKeyspaceWriteHandler.java          |  11 +-
 .../apache/cassandra/db/CassandraWriteContext.java |  10 +-
 .../org/apache/cassandra/db/ColumnFamilyStore.java | 214 ++++--
 src/java/org/apache/cassandra/db/Keyspace.java     |  62 +-
 .../apache/cassandra/db/KeyspaceWriteHandler.java  |   7 +-
 .../java/org/apache/cassandra/db/LogDomain.java    |  30 +-
 .../org/apache/cassandra/db/SystemKeyspace.java    |   7 +-
 .../cassandra/db/commitlog/CommitLogReplayer.java  |   2 +-
 .../db/compaction/AbstractStrategyHolder.java      |  10 +-
 .../compaction/ClearCoordinatorLogOffsetsTask.java |  64 ++
 .../cassandra/db/compaction/CompactionGroup.java   |  69 ++
 .../db/compaction/CompactionStrategyHolder.java    |  40 +-
 .../db/compaction/CompactionStrategyManager.java   | 153 ++++-
 .../cassandra/db/compaction/CompactionTask.java    |   9 +-
 .../db/compaction/PendingRepairHolder.java         |   6 +-
 .../db/compaction/PendingRepairManager.java        |  19 +-
 .../db/compaction/PromoteReconciledTask.java       |  81 +++
 .../db/compaction/TrackedCompactionManager.java    | 641 ++++++++++++++++++
 .../org/apache/cassandra/db/lifecycle/Tracker.java |  90 ++-
 .../org/apache/cassandra/db/lifecycle/View.java    |  55 +-
 .../db/memtable/AbstractAllocatorMemtable.java     |  48 +-
 .../cassandra/db/memtable/AbstractMemtable.java    |  55 +-
 .../db/memtable/AbstractMemtableWithCommitlog.java |  44 +-
 .../db/memtable/AbstractShardedMemtable.java       |   4 +-
 .../cassandra/db/memtable/DomainMemtable.java      | 147 +++++
 .../cassandra/db/memtable/FlushListeners.java      |  65 ++
 .../org/apache/cassandra/db/memtable/Flushing.java | 170 ++++-
 .../cassandra/db/memtable/LogDomainBounds.java     | 138 ++++
 .../cassandra/db/memtable/LogDomainPositions.java  |  84 +++
 .../org/apache/cassandra/db/memtable/Memtable.java | 184 ++----
 .../db/memtable/ShardedSkipListMemtable.java       |  27 +-
 .../cassandra/db/memtable/SkipListMemtable.java    |  10 +-
 .../db/memtable/SkipListMemtableFactory.java       |   7 +-
 .../cassandra/db/memtable/SplitDomainMemtable.java | 422 ++++++++++++
 .../apache/cassandra/db/memtable/TrieMemtable.java |  19 +-
 .../cassandra/db/repair/PendingAntiCompaction.java |   5 +
 .../db/tracked/TrackedKeyspaceWriteHandler.java    |  28 +-
 .../org/apache/cassandra/db/view/TableViews.java   |   4 +-
 .../index/accord/MemtableIndexManager.java         |   8 +-
 .../cassandra/index/accord/RouteJournalIndex.java  |  11 +-
 .../index/accord/RouteMemtableIndexManager.java    |  12 +-
 .../cassandra/index/internal/CassandraIndex.java   |  10 +-
 .../cassandra/index/sai/StorageAttachedIndex.java  |   9 +-
 .../index/sai/StorageAttachedIndexGroup.java       |   7 +-
 .../index/sai/memory/MemtableIndexManager.java     |  18 +-
 .../cassandra/io/sstable/format/SSTableReader.java |  13 +
 .../cassandra/io/sstable/format/SSTableWriter.java |  10 +
 .../io/sstable/format/SortedTableVerifier.java     |  26 +-
 .../io/sstable/metadata/StatsMetadata.java         |  15 +-
 .../org/apache/cassandra/metrics/TableMetrics.java |  29 +
 .../notifications/MemtableRenewedNotification.java |   6 +-
 .../org/apache/cassandra/repair/RepairJob.java     |   2 +-
 .../ImmutableCoordinatorLogOffsets.java            |  33 +-
 .../apache/cassandra/replication/MutationId.java   |   7 -
 .../cassandra/replication/MutationJournal.java     |  11 +
 .../replication/MutationTrackingService.java       |  66 +-
 .../cassandra/replication/ShortMutationId.java     |  22 +-
 .../apache/cassandra/schema/MemtableParams.java    |  18 +-
 .../cassandra/service/accord/AccordKeyspace.java   |   4 +-
 .../replication/migration/MigrationRouter.java     |  13 +-
 .../MutationTrackingMigrationRepairResult.java     |  41 +-
 .../test/MutationTrackingMigrationTest.java        | 429 ++++++++----
 .../test/tracking/CommitLogReplayRoutingTest.java  | 176 +++++
 .../test/tracking/TrackedImportFailureTest.java    | 132 ++--
 .../cassandra/batchlog/BatchlogManagerTest.java    |   4 +-
 .../cql3/validation/operations/AlterTest.java      |   3 +-
 .../cql3/validation/operations/CreateTest.java     |   3 +-
 .../apache/cassandra/db/ColumnFamilyStoreTest.java |  18 +-
 .../db/CoordinatorLogOffsetsLifecycleTest.java     |  41 +-
 .../db/compaction/CompactionGroupTest.java         | 105 +++
 ...CompactionStrategyManagerPendingRepairTest.java |   4 +-
 .../compaction/CompactionStrategyManagerTest.java  |  77 ++-
 .../db/compaction/PromoteReconciledTaskTest.java   | 123 ++++
 .../compaction/TrackedCompactionManagerTest.java   | 348 ++++++++++
 .../TrackedUnreconciledPromotionTest.java          | 685 +++++++++++++++++++
 .../db/lifecycle/LifecycleTransactionTest.java     |   5 +-
 .../apache/cassandra/db/lifecycle/TrackerTest.java |  61 +-
 .../apache/cassandra/db/lifecycle/ViewTest.java    |  10 +-
 .../cassandra/db/memtable/LogDomainBoundsTest.java | 117 ++++
 .../db/memtable/SplitDomainMemtableTest.java       | 731 +++++++++++++++++++++
 .../apache/cassandra/db/memtable/TestMemtable.java |   4 +-
 .../db/memtable/TrieMemtableFlushSetTestBase.java  |   8 +-
 .../index/internal/TrackedIndexFlushTest.java      | 207 ++++++
 .../index/sai/functional/TrackedFlushingTest.java  | 215 ++++++
 .../cassandra/io/sstable/SSTableProvenance.java    |  33 +-
 .../IndexSummaryRedistributionTest.java            |   5 +-
 .../cassandra/replication/ShortMutationIdTest.java |  79 +++
 .../org/apache/cassandra/schema/MockSchema.java    |  10 +-
 .../MutationTrackingMigrationRepairResultTest.java | 103 +++
 91 files changed, 6322 insertions(+), 858 deletions(-)
 copy test/distributed/org/apache/cassandra/distributed/test/ReadRepairUntrackedTest.java => src/java/org/apache/cassandra/db/LogDomain.java (60%)
 create mode 100644 src/java/org/apache/cassandra/db/compaction/ClearCoordinatorLogOffsetsTask.java
 create mode 100644 src/java/org/apache/cassandra/db/compaction/CompactionGroup.java
 create mode 100644 src/java/org/apache/cassandra/db/compaction/PromoteReconciledTask.java
 create mode 100644 src/java/org/apache/cassandra/db/compaction/TrackedCompactionManager.java
 create mode 100644 src/java/org/apache/cassandra/db/memtable/DomainMemtable.java
 create mode 100644 src/java/org/apache/cassandra/db/memtable/FlushListeners.java
 create mode 100644 src/java/org/apache/cassandra/db/memtable/LogDomainBounds.java
 create mode 100644 src/java/org/apache/cassandra/db/memtable/LogDomainPositions.java
 create mode 100644 src/java/org/apache/cassandra/db/memtable/SplitDomainMemtable.java
 create mode 100644 test/distributed/org/apache/cassandra/distributed/test/tracking/CommitLogReplayRoutingTest.java
 create mode 100644 test/unit/org/apache/cassandra/db/compaction/CompactionGroupTest.java
 create mode 100644 test/unit/org/apache/cassandra/db/compaction/PromoteReconciledTaskTest.java
 create mode 100644 test/unit/org/apache/cassandra/db/compaction/TrackedCompactionManagerTest.java
 create mode 100644 test/unit/org/apache/cassandra/db/compaction/TrackedUnreconciledPromotionTest.java
 create mode 100644 test/unit/org/apache/cassandra/db/memtable/LogDomainBoundsTest.java
 create mode 100644 test/unit/org/apache/cassandra/db/memtable/SplitDomainMemtableTest.java
 create mode 100644 test/unit/org/apache/cassandra/index/internal/TrackedIndexFlushTest.java
 create mode 100644 test/unit/org/apache/cassandra/index/sai/functional/TrackedFlushingTest.java
 copy src/java/org/apache/cassandra/notifications/SSTableMetadataChanged.java => test/unit/org/apache/cassandra/io/sstable/SSTableProvenance.java (54%)
 create mode 100644 test/unit/org/apache/cassandra/replication/ShortMutationIdTest.java
 create mode 100644 test/unit/org/apache/cassandra/service/replication/migration/MutationTrackingMigrationRepairResultTest.java


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


(cassandra) 02/02: CEP-45: Track log domains per memtable and isolate tracked sstable compaction

Posted by bd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bdeggleston pushed a commit to branch cep-45-mutation-tracking
in repository https://gitbox.apache.org/repos/asf/cassandra.git

commit 2af323f09d4ed324d36e6fcf20604d789fb5a99a
Author: Blake Eggleston <bl...@ultrablake.com>
AuthorDate: Wed Sep 2 18:33:54 2026 -0700

    CEP-45: Track log domains per memtable and isolate tracked sstable compaction
    
       - Tag memtables with a log domain and track bounds separately for commit log
         and mutation journal positions.
       - Use SplitDomainMemtable during replication migration to accept writes from
         both logs and flush separate sstables per domain.
       - Return domain-specific bounds across flush and truncation APIs via
         LogDomainPositions.
       - Isolate tracked sstables by transfer set in dedicated compaction silos
         managed by TrackedCompactionManager.
       - Promote reconciled sstables to repaired and clear coordinator log offsets
         at promotion time rather than incrementally.
       - Clear coordinator log offsets from sstables when a keyspace migrates away
         from mutation tracking.
       - Require incremental data repairs including all replicas before advancing
         mutation tracking migration.
    
    Patch by Blake Eggleston; Reviewed by Ariel Weisberg for CASSANDRA-21646
---
 .../pages/managing/operating/metrics.adoc          |   6 +
 .../db/CassandraKeyspaceWriteHandler.java          |  11 +-
 .../apache/cassandra/db/CassandraWriteContext.java |  10 +-
 .../org/apache/cassandra/db/ColumnFamilyStore.java | 214 ++++--
 src/java/org/apache/cassandra/db/Keyspace.java     |  62 +-
 .../apache/cassandra/db/KeyspaceWriteHandler.java  |   7 +-
 .../{KeyspaceWriteHandler.java => LogDomain.java}  |  26 +-
 .../org/apache/cassandra/db/SystemKeyspace.java    |   7 +-
 .../cassandra/db/commitlog/CommitLogReplayer.java  |   2 +-
 .../db/compaction/AbstractStrategyHolder.java      |  10 +-
 .../compaction/ClearCoordinatorLogOffsetsTask.java |  64 ++
 .../cassandra/db/compaction/CompactionGroup.java   |  69 ++
 .../db/compaction/CompactionStrategyHolder.java    |  40 +-
 .../db/compaction/CompactionStrategyManager.java   | 153 ++++-
 .../cassandra/db/compaction/CompactionTask.java    |   9 +-
 .../db/compaction/PendingRepairHolder.java         |   6 +-
 .../db/compaction/PendingRepairManager.java        |  19 +-
 .../db/compaction/PromoteReconciledTask.java       |  81 +++
 .../db/compaction/TrackedCompactionManager.java    | 641 ++++++++++++++++++
 .../org/apache/cassandra/db/lifecycle/Tracker.java |  90 ++-
 .../org/apache/cassandra/db/lifecycle/View.java    |  55 +-
 .../db/memtable/AbstractAllocatorMemtable.java     |  48 +-
 .../cassandra/db/memtable/AbstractMemtable.java    |  55 +-
 .../db/memtable/AbstractMemtableWithCommitlog.java |  44 +-
 .../db/memtable/AbstractShardedMemtable.java       |   4 +-
 .../cassandra/db/memtable/DomainMemtable.java      | 147 +++++
 .../cassandra/db/memtable/FlushListeners.java      |  65 ++
 .../org/apache/cassandra/db/memtable/Flushing.java | 170 ++++-
 .../cassandra/db/memtable/LogDomainBounds.java     | 138 ++++
 .../cassandra/db/memtable/LogDomainPositions.java  |  84 +++
 .../org/apache/cassandra/db/memtable/Memtable.java | 184 ++----
 .../db/memtable/ShardedSkipListMemtable.java       |  27 +-
 .../cassandra/db/memtable/SkipListMemtable.java    |  10 +-
 .../db/memtable/SkipListMemtableFactory.java       |   7 +-
 .../cassandra/db/memtable/SplitDomainMemtable.java | 422 ++++++++++++
 .../apache/cassandra/db/memtable/TrieMemtable.java |  19 +-
 .../cassandra/db/repair/PendingAntiCompaction.java |   5 +
 .../db/tracked/TrackedKeyspaceWriteHandler.java    |  28 +-
 .../org/apache/cassandra/db/view/TableViews.java   |   4 +-
 .../index/accord/MemtableIndexManager.java         |   8 +-
 .../cassandra/index/accord/RouteJournalIndex.java  |  11 +-
 .../index/accord/RouteMemtableIndexManager.java    |  12 +-
 .../cassandra/index/internal/CassandraIndex.java   |  10 +-
 .../cassandra/index/sai/StorageAttachedIndex.java  |   9 +-
 .../index/sai/StorageAttachedIndexGroup.java       |   7 +-
 .../index/sai/memory/MemtableIndexManager.java     |  18 +-
 .../cassandra/io/sstable/format/SSTableReader.java |  13 +
 .../cassandra/io/sstable/format/SSTableWriter.java |  10 +
 .../io/sstable/format/SortedTableVerifier.java     |  26 +-
 .../io/sstable/metadata/StatsMetadata.java         |  15 +-
 .../org/apache/cassandra/metrics/TableMetrics.java |  29 +
 .../notifications/MemtableRenewedNotification.java |   6 +-
 .../org/apache/cassandra/repair/RepairJob.java     |   2 +-
 .../ImmutableCoordinatorLogOffsets.java            |  33 +-
 .../apache/cassandra/replication/MutationId.java   |   7 -
 .../cassandra/replication/MutationJournal.java     |  11 +
 .../replication/MutationTrackingService.java       |  66 +-
 .../cassandra/replication/ShortMutationId.java     |  22 +-
 .../apache/cassandra/schema/MemtableParams.java    |  18 +-
 .../cassandra/service/accord/AccordKeyspace.java   |   4 +-
 .../replication/migration/MigrationRouter.java     |  13 +-
 .../MutationTrackingMigrationRepairResult.java     |  41 +-
 .../test/MutationTrackingMigrationTest.java        | 429 ++++++++----
 .../test/tracking/CommitLogReplayRoutingTest.java  | 176 +++++
 .../test/tracking/TrackedImportFailureTest.java    | 132 ++--
 .../cassandra/batchlog/BatchlogManagerTest.java    |   4 +-
 .../cql3/validation/operations/AlterTest.java      |   3 +-
 .../cql3/validation/operations/CreateTest.java     |   3 +-
 .../apache/cassandra/db/ColumnFamilyStoreTest.java |  18 +-
 .../db/CoordinatorLogOffsetsLifecycleTest.java     |  41 +-
 .../db/compaction/CompactionGroupTest.java         | 105 +++
 ...CompactionStrategyManagerPendingRepairTest.java |   4 +-
 .../compaction/CompactionStrategyManagerTest.java  |  77 ++-
 .../db/compaction/PromoteReconciledTaskTest.java   | 123 ++++
 .../compaction/TrackedCompactionManagerTest.java   | 348 ++++++++++
 .../TrackedUnreconciledPromotionTest.java          | 685 +++++++++++++++++++
 .../db/lifecycle/LifecycleTransactionTest.java     |   5 +-
 .../apache/cassandra/db/lifecycle/TrackerTest.java |  61 +-
 .../apache/cassandra/db/lifecycle/ViewTest.java    |  10 +-
 .../cassandra/db/memtable/LogDomainBoundsTest.java | 117 ++++
 .../db/memtable/SplitDomainMemtableTest.java       | 731 +++++++++++++++++++++
 .../apache/cassandra/db/memtable/TestMemtable.java |   4 +-
 .../db/memtable/TrieMemtableFlushSetTestBase.java  |   8 +-
 .../index/internal/TrackedIndexFlushTest.java      | 207 ++++++
 .../index/sai/functional/TrackedFlushingTest.java  | 215 ++++++
 .../cassandra/io/sstable/SSTableProvenance.java    |  52 ++
 .../IndexSummaryRedistributionTest.java            |   5 +-
 .../cassandra/replication/ShortMutationIdTest.java |  79 +++
 .../org/apache/cassandra/schema/MockSchema.java    |  10 +-
 .../MutationTrackingMigrationRepairResultTest.java | 103 +++
 90 files changed, 6348 insertions(+), 841 deletions(-)

diff --git a/doc/modules/cassandra/pages/managing/operating/metrics.adoc b/doc/modules/cassandra/pages/managing/operating/metrics.adoc
index ddc2ac851b..ade34a7197 100644
--- a/doc/modules/cassandra/pages/managing/operating/metrics.adoc
+++ b/doc/modules/cassandra/pages/managing/operating/metrics.adoc
@@ -228,6 +228,12 @@ on disk.
 |BytesPendingRepair |Gauge<Long> |Size of table data isolated for an
 ongoing incremental repair
 
+|UnpromotableSSTables |Gauge<Integer> |Number of sstables on a
+mutation-tracked table that can never be promoted to repaired, because they
+are unrepaired and carry no coordinator log offsets. Reports 0 for untracked
+tables, and for tracked keyspaces still in migration state, where offset-free
+unrepaired sstables are the ordinary state of pre-migration data.
+
 |SpeculativeRetries |Counter |Number of times speculative retries were
 sent for this table.
 
diff --git a/src/java/org/apache/cassandra/db/CassandraKeyspaceWriteHandler.java b/src/java/org/apache/cassandra/db/CassandraKeyspaceWriteHandler.java
index 9b68acc708..41630a406d 100644
--- a/src/java/org/apache/cassandra/db/CassandraKeyspaceWriteHandler.java
+++ b/src/java/org/apache/cassandra/db/CassandraKeyspaceWriteHandler.java
@@ -40,21 +40,22 @@ public class CassandraKeyspaceWriteHandler implements KeyspaceWriteHandler
     }
 
     @Override
-    public WriteContext beginWrite(Mutation mutation, boolean makeDurable) throws RequestExecutionException
+    public WriteContext beginWrite(Mutation mutation, boolean makeDurable, boolean isReplay) throws RequestExecutionException
     {
         OpOrder.Group group = null;
         try
         {
             group = Keyspace.writeOrder.start();
 
-            MigrationRouter.validateUntrackedMutation(mutation);
+            MigrationRouter.validateUntrackedMutation(mutation, isReplay);
+
             // write the mutation to the commitlog and memtables
             CommitLogPosition position = null;
             if (makeDurable)
             {
                 position = addToCommitLog(mutation);
             }
-            return new CassandraWriteContext(group, position);
+            return new CassandraWriteContext(group, position, LogDomain.COMMIT_LOG);
         }
         catch (Throwable t)
         {
@@ -107,7 +108,9 @@ public class CassandraKeyspaceWriteHandler implements KeyspaceWriteHandler
         try
         {
             group = Keyspace.writeOrder.start();
-            return new CassandraWriteContext(group, null);
+            // Index rebuild and read contexts append to neither log. Commit-log domain because the writes they
+            // carry are index updates derived from data already durable, never journal appends of their own.
+            return new CassandraWriteContext(group, null, LogDomain.COMMIT_LOG);
         }
         catch (Throwable t)
         {
diff --git a/src/java/org/apache/cassandra/db/CassandraWriteContext.java b/src/java/org/apache/cassandra/db/CassandraWriteContext.java
index bac1351fbd..aa8fee0aef 100644
--- a/src/java/org/apache/cassandra/db/CassandraWriteContext.java
+++ b/src/java/org/apache/cassandra/db/CassandraWriteContext.java
@@ -27,12 +27,15 @@ public class CassandraWriteContext implements WriteContext
 {
     private final OpOrder.Group opGroup;
     private final CommitLogPosition position;
+    private final LogDomain domain;
 
-    public CassandraWriteContext(OpOrder.Group opGroup, CommitLogPosition position)
+    public CassandraWriteContext(OpOrder.Group opGroup, CommitLogPosition position, LogDomain domain)
     {
         Preconditions.checkArgument(opGroup != null);
+        Preconditions.checkArgument(domain != null);
         this.opGroup = opGroup;
         this.position = position;
+        this.domain = domain;
     }
 
     public static CassandraWriteContext fromContext(WriteContext context)
@@ -51,6 +54,11 @@ public class CassandraWriteContext implements WriteContext
         return position;
     }
 
+    public LogDomain domain()
+    {
+        return domain;
+    }
+
     @Override
     public void close()
     {
diff --git a/src/java/org/apache/cassandra/db/ColumnFamilyStore.java b/src/java/org/apache/cassandra/db/ColumnFamilyStore.java
index 288b419cd7..f370f0fe55 100644
--- a/src/java/org/apache/cassandra/db/ColumnFamilyStore.java
+++ b/src/java/org/apache/cassandra/db/ColumnFamilyStore.java
@@ -58,6 +58,7 @@ import javax.management.openmbean.SimpleType;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Function;
 import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
 import com.google.common.base.Predicate;
 import com.google.common.base.Predicates;
 import com.google.common.base.Strings;
@@ -94,9 +95,13 @@ import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
 import org.apache.cassandra.db.lifecycle.SSTableSet;
 import org.apache.cassandra.db.lifecycle.Tracker;
 import org.apache.cassandra.db.lifecycle.View;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.memtable.Flushing;
+import org.apache.cassandra.db.memtable.LogDomainBounds;
+import org.apache.cassandra.db.memtable.LogDomainPositions;
 import org.apache.cassandra.db.memtable.Memtable;
 import org.apache.cassandra.db.memtable.ShardBoundaries;
+import org.apache.cassandra.db.memtable.SplitDomainMemtable;
 import org.apache.cassandra.db.partitions.CachedPartition;
 import org.apache.cassandra.db.partitions.PartitionUpdate;
 import org.apache.cassandra.db.repair.CassandraTableRepairManager;
@@ -145,6 +150,7 @@ import org.apache.cassandra.schema.CompactionParams;
 import org.apache.cassandra.schema.CompactionParams.TombstoneOption;
 import org.apache.cassandra.schema.CompressionParams;
 import org.apache.cassandra.schema.IndexMetadata;
+import org.apache.cassandra.schema.ReplicationType;
 import org.apache.cassandra.schema.Schema;
 import org.apache.cassandra.schema.SchemaConstants;
 import org.apache.cassandra.schema.TableId;
@@ -180,7 +186,6 @@ import org.apache.cassandra.utils.concurrent.UncheckedInterruptedException;
 
 import static org.apache.cassandra.concurrent.ExecutorFactory.Global.executorFactory;
 import static org.apache.cassandra.config.DatabaseDescriptor.getFlushWriters;
-import static org.apache.cassandra.db.commitlog.CommitLogPosition.NONE;
 import static org.apache.cassandra.utils.Clock.Global.currentTimeMillis;
 import static org.apache.cassandra.utils.Clock.Global.nanoTime;
 import static org.apache.cassandra.utils.Throwables.maybeFail;
@@ -286,7 +291,7 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
     private final String oldMBeanName;
     private volatile boolean valid = true;
 
-    private volatile Memtable.Factory memtableFactory;
+    private volatile DomainMemtable.Factory memtableFactory;
 
     /**
      * Memtables and SSTables on disk for this column family.
@@ -520,18 +525,15 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
         logger.info("Initializing {}.{}", getKeyspaceName(), name);
 
         Memtable initialMemtable = null;
+        LogDomainBounds initialBounds = null;
         if (DatabaseDescriptor.isDaemonInitialized())
         {
-            CommitLogPosition commitLogPosition;
-            if (metadata().replicationType().isTracked())
-                commitLogPosition = MutationJournal.instance().getCurrentPosition();
-            else
-                commitLogPosition = CommitLog.instance.getCurrentPosition();
-            initialMemtable = createMemtable(new AtomicReference<>(commitLogPosition));
+            initialBounds = LogDomainBounds.atCurrentPositions();
+            initialMemtable = createMemtable(initialBounds);
         }
         memtableMetricsReleaser = memtableFactory.createMemtableMetricsReleaser(metadata);
 
-        data = new Tracker(this, initialMemtable, loadSSTables);
+        data = new Tracker(this, initialMemtable, initialBounds, loadSSTables);
 
         // Note that this needs to happen before we load the first sstables, or the global sstable tracker will not
         // be notified on the initial loading.
@@ -1053,16 +1055,28 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
             elseNotify.accept(currentMemtable);
     }
 
+    /**
+     * Whether the given memtable is the current generation, accepting an internal of the current split memtable as well
+     * as the memtable itself. Memtables can flush themselves, so we need to check if they're calling flush from inside
+     * a split domain memtable.
+     */
+    private boolean isCurrentGeneration(Memtable memtable)
+    {
+        Memtable current = data.getView().getCurrentMemtable();
+        return current == memtable
+               || (current instanceof SplitDomainMemtable && ((SplitDomainMemtable) current).isInternal(memtable));
+    }
+
     /**
      * Switches the memtable iff the live memtable is the one provided
      *
      * @param memtable
      */
-    public Future<CommitLogPosition> switchMemtableIfCurrent(Memtable memtable, FlushReason reason)
+    public Future<LogDomainPositions> switchMemtableIfCurrent(Memtable memtable, FlushReason reason)
     {
         synchronized (data)
         {
-            if (data.getView().getCurrentMemtable() == memtable)
+            if (isCurrentGeneration(memtable))
                 return switchMemtable(reason);
         }
         logger.debug("Memtable is no longer current, returning future that completes when current flushing operation completes");
@@ -1077,7 +1091,7 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
      * marked clean up to the position owned by the Memtable.
      */
     @VisibleForTesting
-    public Future<CommitLogPosition> switchMemtable(FlushReason reason)
+    public Future<LogDomainPositions> switchMemtable(FlushReason reason)
     {
         synchronized (data)
         {
@@ -1109,7 +1123,7 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
      * @return a Future yielding the commit log position that can be guaranteed to have been successfully written
      *         to sstables for this table once the future completes
      */
-    public Future<CommitLogPosition> forceFlush(FlushReason reason)
+    public Future<LogDomainPositions> forceFlush(FlushReason reason)
     {
         synchronized (data)
         {
@@ -1133,12 +1147,12 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
         // we don't loop through the remaining memtables since here we only care about commit log dirtiness
         // and this does not vary between a table and its table-backed indexes
         Memtable current = data.getView().getCurrentMemtable();
-        if (current.mayContainDataBefore(flushIfDirtyBefore))
+        if (current.holds(LogDomain.COMMIT_LOG) && current.flushSourceFor(LogDomain.COMMIT_LOG).mayContainDataBefore(flushIfDirtyBefore))
             return flushMemtable(current, FlushReason.COMMITLOG_DIRTY);
         return waitForFlushes();
     }
 
-    private Future<CommitLogPosition> flushMemtable(Memtable current, FlushReason reason)
+    private Future<LogDomainPositions> flushMemtable(Memtable current, FlushReason reason)
     {
         if (current.shouldSwitch(reason))
             return switchMemtableIfCurrent(current, reason);
@@ -1150,15 +1164,14 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
      * @return a Future yielding the commit log position that can be guaranteed to have been successfully written
      *         to sstables for this table once the future completes
      */
-    private Future<CommitLogPosition> waitForFlushes()
+    private Future<LogDomainPositions> waitForFlushes()
     {
         // we grab the current memtable; once any preceding memtables have flushed, we know its
         // commitLogLowerBound has been set (as this it is set with the upper bound of the preceding memtable)
-        final Memtable current = data.getView().getCurrentMemtable();
-        return postFlushExecutor.submit(current::getCommitLogLowerBound);
+        return postFlushExecutor.submit(() -> LogDomainPositions.of(data.getView().currentBounds));
     }
 
-    public CommitLogPosition forceBlockingFlush(FlushReason reason)
+    public LogDomainPositions forceBlockingFlush(FlushReason reason)
     {
         return FBUtilities.waitOnFuture(forceFlush(reason));
     }
@@ -1167,18 +1180,20 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
      * Both synchronises custom secondary indexes and provides ordering guarantees for futures on switchMemtable/flush
      * etc, which expect to be able to wait until the flush (and all prior flushes) requested have completed.
      */
-    private final class PostFlush implements Callable<CommitLogPosition>
+    private final class PostFlush implements Callable<LogDomainPositions>
     {
         final CountDownLatch latch = newCountDownLatch(1);
         final Memtable mainMemtable;
+        final LogDomainBounds upperBounds;
         volatile Throwable flushFailure = null;
 
-        private PostFlush(Memtable mainMemtable)
+        private PostFlush(Memtable mainMemtable, LogDomainBounds upperBounds)
         {
             this.mainMemtable = mainMemtable;
+            this.upperBounds = upperBounds;
         }
 
-        public CommitLogPosition call()
+        public LogDomainPositions call()
         {
             try
             {
@@ -1191,18 +1206,31 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
                 throw new UncheckedInterruptedException(e);
             }
 
-            CommitLogPosition commitLogUpperBound = NONE;
+            LogDomainPositions commitLogUpperBound = LogDomainPositions.NONE;
             // If a flush errored out but the error was ignored, make sure we don't discard the commit log.
             if (flushFailure == null && mainMemtable != null)
             {
-                CommitLogPosition commitLogLowerBound = mainMemtable.getCommitLogLowerBound();
-                commitLogUpperBound = mainMemtable.getFinalCommitLogUpperBound();
                 TableMetadata metadata = metadata();
 
-                if (metadata().replicationType().isTracked())
-                    MutationJournal.instance().notifyFlushed(metadata.id, commitLogLowerBound, commitLogUpperBound);
+                // Each log is told about the span the memtable bounded in that log.
+                for (DomainMemtable source : mainMemtable.flushSources())
+                {
+                    CommitLogPosition lowerBound = source.getCommitLogLowerBound();
+                    CommitLogPosition upperBound = source.getFinalCommitLogUpperBound();
+
+                    if (source.holds(LogDomain.MUTATION_JOURNAL))
+                        MutationJournal.instance().notifyFlushed(metadata.id, lowerBound, upperBound);
+                    else
+                        CommitLog.instance.discardCompletedSegments(metadata.id, lowerBound, upperBound);
+                }
 
-                CommitLog.instance.discardCompletedSegments(metadata.id, commitLogLowerBound, commitLogUpperBound);
+                CommitLogPosition clUpper = mainMemtable.holds(LogDomain.COMMIT_LOG)
+                                            ? mainMemtable.flushSourceFor(LogDomain.COMMIT_LOG).getFinalCommitLogUpperBound()
+                                            : upperBounds.get(LogDomain.COMMIT_LOG);
+                CommitLogPosition jUpper = mainMemtable.holds(LogDomain.MUTATION_JOURNAL)
+                                           ? mainMemtable.flushSourceFor(LogDomain.MUTATION_JOURNAL).getFinalCommitLogUpperBound()
+                                           : upperBounds.get(LogDomain.MUTATION_JOURNAL);
+                commitLogUpperBound = new LogDomainPositions(clUpper, jUpper);
             }
 
             metric.pendingFlushes.dec();
@@ -1229,7 +1257,7 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
     {
         final OpOrder.Barrier writeBarrier;
         final Map<ColumnFamilyStore, Memtable> memtables;
-        final FutureTask<CommitLogPosition> postFlushTask;
+        final FutureTask<LogDomainPositions> postFlushTask;
         final PostFlush postFlush;
         final boolean truncate;
 
@@ -1255,30 +1283,63 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
             memtables = new LinkedHashMap<>();
 
             // submit flushes for the memtable for any indexed sub-cfses, and our own
-            AtomicReference<CommitLogPosition> commitLogUpperBound = new AtomicReference<>();
+            LogDomainBounds previousBounds = data.getView().currentBounds;
+            LogDomainBounds upperBounds = LogDomainBounds.unset();
             for (ColumnFamilyStore cfs : concatWithIndexes())
             {
                 // switch all memtables, regardless of their dirty status, setting the barrier
                 // so that we can reach a coordinated decision about cleanliness once they
                 // are no longer possible to be modified
-                Memtable newMemtable = cfs.createMemtable(commitLogUpperBound);
-                Memtable oldMemtable = cfs.data.switchMemtable(truncate, newMemtable);
-                oldMemtable.switchOut(writeBarrier, commitLogUpperBound);
+                DomainMemtable newMemtable = cfs.createMemtable(upperBounds);
+                Memtable oldMemtable = cfs.data.switchMemtable(truncate, newMemtable, upperBounds);
+                oldMemtable.switchOut(writeBarrier, upperBounds);
                 memtables.put(cfs, oldMemtable);
             }
 
-            // we then ensure an atomic decision is made about the upper bound of the continuous range of commit log
-            // records owned by this memtable
-            setCommitLogUpperBound(commitLogUpperBound, metadata().replicationType().isTracked());
+            // preset positions for domains we don't have memtables for
+            for (LogDomain domain : LogDomain.values())
+            {
+                boolean holdsDomain = false;
+                for (Memtable memtable : memtables.values())
+                {
+                    if (memtable.holds(domain))
+                    {
+                        holdsDomain = true;
+                        break;
+                    }
+                }
+                if (!holdsDomain)
+                {
+                    CommitLogPosition prev = previousBounds != null ? previousBounds.get(domain) : null;
+                    if (prev != null)
+                        upperBounds.forDomain(domain).set(new Memtable.LastCommitLogPosition(prev));
+                }
+            }
+
+            // we then ensure an atomic decision is made about the upper bound of the continuous range of records owned
+            // by this memtable, in each log separately: a position from one log does not compare against a bound from
+            // the other
+            upperBounds.seal();
+
+            Preconditions.checkState(allSealed(upperBounds), "Unsealed bound %s for %s", upperBounds, memtables.values());
 
             // we then issue the barrier; this lets us wait for all operations started prior to the barrier to complete;
             // since this happens after wiring up the commitLogUpperBound, we also know all operations with earlier
             // commit log segment position have also completed, i.e. the memtables are done and ready to flush
             writeBarrier.issue();
-            postFlush = new PostFlush(Iterables.get(memtables.values(), 0, null));
+            postFlush = new PostFlush(Iterables.get(memtables.values(), 0, null), upperBounds);
             postFlushTask = new FutureTask<>(postFlush);
         }
 
+        private boolean allSealed(LogDomainBounds upperBounds)
+        {
+            for (Memtable memtable : memtables.values())
+                for (LogDomain domain : LogDomain.values())
+                    if (memtable.holds(domain) && !upperBounds.isSealed(domain))
+                        return false;
+            return true;
+        }
+
         public void run()
         {
             if (logger.isTraceEnabled())
@@ -1351,11 +1412,22 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
                 try
                 {
                     // flush the memtable
-                    flushRunnables = Flushing.flushRunnables(cfs, memtable, txn);
                     ExecutorPlus[] executors = perDiskflushExecutors.getExecutorsFor(getKeyspaceName(), name);
+                    flushRunnables = new ArrayList<>();
+
+                    // One transaction over every log domain's output, so the generation's sstables become visible
+                    // together and PostFlush can't run against a half-persisted memtable generation.
+                    for (DomainMemtable source : memtable.flushSources())
+                    {
+                        if (source.isClean())
+                            continue;
+
+                        List<Flushing.FlushRunnable> perDisk = Flushing.flushRunnables(cfs, source, txn);
+                        flushRunnables.addAll(perDisk);
+                    }
 
-                    for (int i = 0; i < flushRunnables.size(); i++)
-                        futures.add(executors[i].submit(flushRunnables.get(i)));
+                    for (int i=0, si=flushRunnables.size(); i<si; i++)
+                        futures.add(executors[i % executors.length].submit(flushRunnables.get(i)));
 
                     /**
                      * we can flush 2is as soon as the barrier completes, as they will be consistent with (or ahead of) the
@@ -1464,36 +1536,30 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
         }
     }
 
-    public Memtable createMemtable(AtomicReference<CommitLogPosition> commitLogUpperBound)
+    public DomainMemtable createMemtable(LogDomainBounds lowerBounds)
     {
-        return memtableFactory.create(commitLogUpperBound, metadata, this);
+        LogDomain domain = initialMemtableDomain();
+        return createMemtable(lowerBounds.forDomain(domain), domain);
     }
 
-    // atomically set the upper bound for the commit log
-    private static void setCommitLogUpperBound(AtomicReference<CommitLogPosition> commitLogUpperBound, boolean useMutationJournal)
+    public DomainMemtable createMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound, LogDomain domain)
     {
-        // we attempt to set the holder to the current commit log context. at the same time all writes to the memtables are
-        // also maintaining this value, so if somebody sneaks ahead of us somehow (should be rare) we simply retry,
-        // so that we know all operations prior to the position have not reached it yet
-        CommitLogPosition lastReplayPosition;
-        while (true)
-        {
-            CommitLogPosition commitLogPosition;
-            if (useMutationJournal)
-                commitLogPosition = MutationJournal.instance().getCurrentPosition();
-            else
-                commitLogPosition = CommitLog.instance.getCurrentPosition();
+        return memtableFactory.create(commitLogLowerBound, metadata, this, domain);
+    }
 
-            lastReplayPosition = new Memtable.LastCommitLogPosition(commitLogPosition);
-            CommitLogPosition currentLast = commitLogUpperBound.get();
-            if ((currentLast == null || currentLast.compareTo(lastReplayPosition) <= 0)
-                && commitLogUpperBound.compareAndSet(currentLast, lastReplayPosition))
-                break;
-        }
+    private LogDomain initialMemtableDomain()
+    {
+        // TableMetadata.Builder.kind() nulls keyspaceReplicationType for any non-regular kind, so an index has to ask
+        // the keyspace. replicationType() cannot stand in: it answers untracked for those kinds, which would make every
+        // index of a tracked keyspace start in the wrong domain and wrap on the first write of every generation.
+        ReplicationType replicationType = metadata().keyspaceReplicationType;
+        if (replicationType == null)
+            replicationType = keyspace.getMetadata().params.replicationType;
+        return LogDomain.initialFor(replicationType);
     }
 
     @Override
-    public Future<CommitLogPosition> signalFlushRequired(Memtable memtable, FlushReason reason)
+    public Future<LogDomainPositions> signalFlushRequired(Memtable memtable, FlushReason reason)
     {
         return switchMemtableIfCurrent(memtable, reason);
     }
@@ -1530,11 +1596,15 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
         long start = nanoTime();
         OpOrder.Group opGroup = context.getGroup();
         CommitLogPosition commitLogPosition = context.getPosition();
+
+        // mutation ids aren't passed through to 2i writes, otherwise validate that the mutation id and log domain match
+        Preconditions.checkState(isIndex() || context.domain().isJournal() != mutationId.isNone(),
+                                 "write context domain %s disagrees with mutation id %s", context.domain(), mutationId);
         try
         {
-            Memtable mt = data.getMemtableFor(opGroup, commitLogPosition);
+            Memtable mt = data.getMemtableFor(opGroup, commitLogPosition, context.domain());
             UpdateTransaction indexer = newUpdateTransaction(update, context, updateIndexes, mt);
-            long timeDelta = mt.put(mutationId, update, indexer, opGroup);
+            long timeDelta = mt.put(mutationId, update, indexer, opGroup, context.domain());
             DecoratedKey key = update.partitionKey();
             invalidateCachedPartition(key);
             metric.topWritePartitionFrequency.addSample(key.getKey(), 1);
@@ -2479,16 +2549,20 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
         if (current.isClean())
             return null;
 
+        if (current.holds(LogDomain.COMMIT_LOG) && current.holds(LogDomain.MUTATION_JOURNAL))
+            throw new IllegalStateException("Cannot stream from a memtable holding more than one log domain: " + current);
+        DomainMemtable source = (DomainMemtable) current;
+
         List<Memtable.FlushablePartitionSet<?>> dataSets = new ArrayList<>(ranges.size());
         ImmutableCoordinatorLogOffsets.Builder logOffsetsBuilder = new ImmutableCoordinatorLogOffsets.Builder();
         IntervalSet.Builder<CommitLogPosition> commitLogIntervals = new IntervalSet.Builder();
         long keys = 0;
         for (Range<PartitionPosition> range : ranges)
         {
-            Memtable.FlushablePartitionSet<?> dataSet = current.getFlushSet(range.left, range.right);
+            Memtable.FlushablePartitionSet<?> dataSet = source.getFlushSet(range.left, range.right);
             dataSets.add(dataSet);
             logOffsetsBuilder.addAll(dataSet.coordinatorLogOffsets());
-            commitLogIntervals.add(dataSet.commitLogLowerBound(), dataSet.commitLogUpperBound());
+            commitLogIntervals.addAll(dataSet.commitLogIntervals());
             keys += dataSet.partitionCount();
         }
         if (keys == 0)
@@ -2595,7 +2669,9 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
         for (final ColumnFamilyStore cfs : concatWithIndexes())
         {
             cfs.runWithCompactionsDisabled((Callable<Void>) () -> {
-                cfs.data.reset(memtableFactory.create(new AtomicReference<>(CommitLogPosition.NONE), cfs.metadata, cfs));
+                LogDomainBounds bounds = LogDomainBounds.of(CommitLogPosition.NONE);
+                LogDomain domain = cfs.initialMemtableDomain();
+                cfs.data.reset(memtableFactory.create(bounds.forDomain(domain), cfs.metadata, cfs, domain), bounds);
                 return null;
             }, OperationType.P0, true, false);
         }
@@ -2634,7 +2710,7 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
         viewManager.stopBuild();
 
         final long truncatedAt;
-        final CommitLogPosition replayAfter;
+        final LogDomainPositions replayAfter;
 
         if (!noSnapshot &&
                ((keyspace.getMetadata().params.durableWrites && !memtableWritesAreDurable())  // need to clear dirty regions
@@ -2695,7 +2771,7 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean, Memtable.Owner
      * that cannot have dirty intervals in the commit log (i.e. one which is not durable, or where the memtable itself
      * performs durable writes).
      */
-    public Future<CommitLogPosition> dumpMemtable()
+    public Future<LogDomainPositions> dumpMemtable()
     {
         synchronized (data)
         {
diff --git a/src/java/org/apache/cassandra/db/Keyspace.java b/src/java/org/apache/cassandra/db/Keyspace.java
index 0020306d79..809c2b03f8 100644
--- a/src/java/org/apache/cassandra/db/Keyspace.java
+++ b/src/java/org/apache/cassandra/db/Keyspace.java
@@ -407,7 +407,7 @@ public class Keyspace
     public Future<?> applyFuture(Mutation mutation, boolean writeCommitLog, boolean updateIndexes)
     {
         if (mutation.id().isNone())
-            return applyInternal(mutation, writeCommitLog, updateIndexes, true, true, new AsyncPromise<>());
+            return applyInternal(mutation, writeCommitLog, updateIndexes, true, true, false, new AsyncPromise<>());
         else
             return applyInternalTracked(mutation, false, new AsyncPromise<>());
     }
@@ -445,7 +445,7 @@ public class Keyspace
             applyInternalTracked(mutation, false, null);
         }
         else
-            applyInternal(mutation, makeDurable, updateIndexes, isDroppable, false, null);
+            applyInternal(mutation, makeDurable, updateIndexes, isDroppable, false, false, null);
     }
 
     /**
@@ -457,15 +457,23 @@ public class Keyspace
      * @param updateIndexes  false to disable index updates (used by CollationController "defragmenting")
      * @param isDroppable    true if this should throw WriteTimeoutException if it does not acquire lock within write_request_timeout
      * @param isDeferrable   true if caller is not waiting for future to complete, so that future may be deferred
+     * @param isReplay       true if this is commit log replay, which skips the routing check
      */
     private Future<?> applyInternal(final Mutation mutation,
-                                               final boolean makeDurable,
-                                               boolean updateIndexes,
-                                               boolean isDroppable,
-                                               boolean isDeferrable,
-                                               Promise<?> future)
+                                    final boolean makeDurable,
+                                    boolean updateIndexes,
+                                    boolean isDroppable,
+                                    boolean isDeferrable,
+                                    boolean isReplay,
+                                    Promise<?> future)
     {
-        Preconditions.checkState(!MigrationRouter.isFullyTracked(mutation) && mutation.id().isNone());
+        // An untracked apply must carry no mutation id
+        Preconditions.checkState(mutation.id().isNone());
+
+        // Don't check routing for replay. A replayed mutations's domain is determined by which log it came out of.
+        // We may be replaying a commit log after a migration to tracked has completed
+        if (!isReplay)
+            Preconditions.checkState(!MigrationRouter.isFullyTracked(mutation));
 
         if (TEST_FAIL_WRITES && getMetadata().name.equals(TEST_FAIL_WRITES_KS))
             throw new RuntimeException("Testing write failures");
@@ -522,9 +530,7 @@ public class Keyspace
 
                             // This view update can't happen right now. so rather than keep this thread busy
                             // we will re-apply ourself to the queue and try again later
-                            Stage.MUTATION.execute(() ->
-                                                   applyInternal(mutation, makeDurable, true, isDroppable, true, future)
-                            );
+                            Stage.MUTATION.execute(() -> applyInternal(mutation, makeDurable, true, isDroppable, true, isReplay, future) );
                             return future;
                         }
                         else
@@ -562,7 +568,7 @@ public class Keyspace
                     columnFamilyStores.get(tableId).metric.viewLockAcquireTime.update(acquireTime, MILLISECONDS);
             }
         }
-        try (WriteContext ctx = getWriteHandler().beginWrite(mutation, makeDurable))
+        try (WriteContext ctx = getWriteHandler().beginWrite(mutation, makeDurable, isReplay))
         {
             ConsensusMigrationMutationHelper.validateSafeToExecuteNonTransactionally(mutation);
             for (PartitionUpdate upd : mutation.getPartitionUpdates())
@@ -614,17 +620,12 @@ public class Keyspace
         }
     }
 
-    /**
-     * Apply a tracked mutation read from the {@link org.apache.cassandra.replication.MutationJournal}
-     * during static-segment replay on startup.
-     *
-     * Compared to the normal write apply path, this skips the journal append (since we're replaying from it)
-     * and always writes to the memtable, even when {@link MutationTrackingService#startWriting} reports the offset
-     * as already witnessed.
-     */
     public void applyForReplay(Mutation mutation)
     {
-        applyInternalTracked(mutation, true, null);
+        if (mutation.id().isNone())
+            applyInternal(mutation, false, true, false, false, true, null);
+        else
+            applyInternalTracked(mutation, true, null);
     }
 
     /**
@@ -633,19 +634,28 @@ public class Keyspace
     private Future<?> applyInternalTracked(Mutation mutation, boolean isReplay, Promise<?> future)
     {
         MutationTrackingService.ensureEnabled();
-        if (!MigrationRouter.isFullyTracked(mutation) || mutation.id().isNone())
-            throw new CoordinatorBehindException("Mutation routing mismatch in applyInternalTracked: isFullyTracked=" +
-                                                 MigrationRouter.isFullyTracked(mutation) + ", id.isNone=" + mutation.id().isNone() +
+        // A tracked apply must carry a mutation id, replay or not.
+        if (mutation.id().isNone())
+            throw new CoordinatorBehindException("Mutation routing mismatch in applyInternalTracked: id.isNone=true" +
                                                  ", keyspace=" + mutation.getKeyspaceName());
+
+        // Don't check routing for replay. A replayed mutations's domain is determined by which log it came out of. We may
+        // be replaying a journal after a migration to untracked has completed
+        if (!isReplay && !MigrationRouter.isFullyTracked(mutation))
+            throw new CoordinatorBehindException("Mutation routing mismatch in applyInternalTracked: isFullyTracked=false" +
+                                                 ", keyspace=" + mutation.getKeyspaceName());
+
         ClusterMetadata cm = ClusterMetadata.current();
 
         if (TEST_FAIL_WRITES && getMetadata().name.equals(TEST_FAIL_WRITES_KS))
             throw new RuntimeException("Testing write failures");
 
         boolean started;
-        try (WriteContext ctx = trackedWriteHandler.beginWrite(mutation, !isReplay))
+        try (WriteContext ctx = trackedWriteHandler.beginWrite(mutation, !isReplay, isReplay))
         {
-            started = MutationTrackingService.instance().startWriting(mutation);
+            started = isReplay
+                      ? MutationTrackingService.instance().startWritingForReplay(mutation)
+                      : MutationTrackingService.instance().startWriting(mutation);
 
             if (started || isReplay)
             {
diff --git a/src/java/org/apache/cassandra/db/KeyspaceWriteHandler.java b/src/java/org/apache/cassandra/db/KeyspaceWriteHandler.java
index 19cca72432..803342ca4a 100644
--- a/src/java/org/apache/cassandra/db/KeyspaceWriteHandler.java
+++ b/src/java/org/apache/cassandra/db/KeyspaceWriteHandler.java
@@ -22,8 +22,13 @@ import org.apache.cassandra.exceptions.RequestExecutionException;
 
 public interface KeyspaceWriteHandler
 {
+    default WriteContext beginWrite(Mutation mutation, boolean makeDurable) throws RequestExecutionException
+    {
+        return beginWrite(mutation, makeDurable, false);
+    }
+
     // mutation can be null if makeDurable is false
-    WriteContext beginWrite(Mutation mutation, boolean makeDurable) throws RequestExecutionException;
+    WriteContext beginWrite(Mutation mutation, boolean makeDurable, boolean isReplay) throws RequestExecutionException;
     WriteContext createContextForIndexing();
     WriteContext createContextForRead();
 }
diff --git a/src/java/org/apache/cassandra/db/KeyspaceWriteHandler.java b/src/java/org/apache/cassandra/db/LogDomain.java
similarity index 57%
copy from src/java/org/apache/cassandra/db/KeyspaceWriteHandler.java
copy to src/java/org/apache/cassandra/db/LogDomain.java
index 19cca72432..2b1b622cbd 100644
--- a/src/java/org/apache/cassandra/db/KeyspaceWriteHandler.java
+++ b/src/java/org/apache/cassandra/db/LogDomain.java
@@ -18,12 +18,26 @@
 
 package org.apache.cassandra.db;
 
-import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.schema.ReplicationType;
 
-public interface KeyspaceWriteHandler
+/**
+ * Which log a {@link org.apache.cassandra.db.commitlog.CommitLogPosition} came from.
+ * <p>
+ * The commit log and the mutation journal generate their segment ids independently, so positions from different logs
+ * can't be compared with each other.
+ */
+public enum LogDomain
 {
-    // mutation can be null if makeDurable is false
-    WriteContext beginWrite(Mutation mutation, boolean makeDurable) throws RequestExecutionException;
-    WriteContext createContextForIndexing();
-    WriteContext createContextForRead();
+    COMMIT_LOG,
+    MUTATION_JOURNAL;
+
+    public boolean isJournal()
+    {
+        return this == MUTATION_JOURNAL;
+    }
+
+    public static LogDomain initialFor(ReplicationType keyspaceReplicationType)
+    {
+        return keyspaceReplicationType.isTracked() ? MUTATION_JOURNAL : COMMIT_LOG;
+    }
 }
diff --git a/src/java/org/apache/cassandra/db/SystemKeyspace.java b/src/java/org/apache/cassandra/db/SystemKeyspace.java
index 65d8c4ac4e..44573d0696 100644
--- a/src/java/org/apache/cassandra/db/SystemKeyspace.java
+++ b/src/java/org/apache/cassandra/db/SystemKeyspace.java
@@ -68,6 +68,7 @@ import org.apache.cassandra.db.marshal.TimeUUIDType;
 import org.apache.cassandra.db.marshal.TupleType;
 import org.apache.cassandra.db.marshal.UTF8Type;
 import org.apache.cassandra.db.marshal.UUIDType;
+import org.apache.cassandra.db.memtable.LogDomainPositions;
 import org.apache.cassandra.db.partitions.PartitionUpdate;
 import org.apache.cassandra.db.rows.Row;
 import org.apache.cassandra.db.rows.Rows;
@@ -883,12 +884,12 @@ public final class SystemKeyspace
         return status;
     }
 
-    public static void saveTruncationRecord(ColumnFamilyStore cfs, long truncatedAt, CommitLogPosition position)
+    public static void saveTruncationRecord(ColumnFamilyStore cfs, long truncatedAt, LogDomainPositions position)
     {
         synchronized (truncationRecordLock)
         {
             String req = "UPDATE system.%s SET truncated_at = truncated_at + ? WHERE key = '%s'";
-            executeInternal(format(req, LOCAL, LOCAL), truncationAsMapEntry(cfs, truncatedAt, position));
+            executeInternal(format(req, LOCAL, LOCAL), truncationAsMapEntry(cfs, truncatedAt, position.commitLog));
             truncationRecords = null;
             forceBlockingFlush(LOCAL);
         }
@@ -1115,7 +1116,7 @@ public final class SystemKeyspace
     {
         if (!DatabaseDescriptor.isUnsafeSystem())
         {
-            List<Future<CommitLogPosition>> futures = new ArrayList<>();
+            List<Future<?>> futures = new ArrayList<>();
 
             for (String cfname : cfnames)
             {
diff --git a/src/java/org/apache/cassandra/db/commitlog/CommitLogReplayer.java b/src/java/org/apache/cassandra/db/commitlog/CommitLogReplayer.java
index 21dc349563..7654be7201 100644
--- a/src/java/org/apache/cassandra/db/commitlog/CommitLogReplayer.java
+++ b/src/java/org/apache/cassandra/db/commitlog/CommitLogReplayer.java
@@ -322,7 +322,7 @@ public class CommitLogReplayer implements CommitLogReadHandler
                     {
                         assert !newPUCollector.isEmpty();
 
-                        keyspace.apply(newPUCollector.build(), false, true, false);
+                        keyspace.applyForReplay(newPUCollector.build());
                         commitLogReplayer.keyspacesReplayed.add(keyspace);
                     }
                 }
diff --git a/src/java/org/apache/cassandra/db/compaction/AbstractStrategyHolder.java b/src/java/org/apache/cassandra/db/compaction/AbstractStrategyHolder.java
index 29fc82b1f8..153a22bd0e 100644
--- a/src/java/org/apache/cassandra/db/compaction/AbstractStrategyHolder.java
+++ b/src/java/org/apache/cassandra/db/compaction/AbstractStrategyHolder.java
@@ -155,16 +155,14 @@ public abstract class AbstractStrategyHolder
     protected abstract void setStrategyInternal(CompactionParams params, int numTokenPartitions);
 
     /**
-     * SSTables are grouped by their repaired and pending repair status. This method determines if this holder
-     * holds the sstable for the given repaired/grouped statuses. Holders should be mutually exclusive in the
-     * groups they deal with. IOW, if one holder returns true for a given isRepaired/isPendingRepair combo,
-     * none of the others should.
+     * SSTables are grouped by {@link CompactionGroup}, which is derived from their metadata. This method determines
+     * whether this holder holds the sstables of a given group.
      */
-    public abstract boolean managesRepairedGroup(boolean isRepaired, boolean isPendingRepair);
+    public abstract boolean managesGroup(CompactionGroup group);
 
     public boolean managesSSTable(SSTableReader sstable)
     {
-        return managesRepairedGroup(sstable.isRepaired(), sstable.isPendingRepair());
+        return managesGroup(CompactionGroup.of(sstable));
     }
 
     public abstract AbstractCompactionStrategy getStrategyFor(SSTableReader sstable);
diff --git a/src/java/org/apache/cassandra/db/compaction/ClearCoordinatorLogOffsetsTask.java b/src/java/org/apache/cassandra/db/compaction/ClearCoordinatorLogOffsetsTask.java
new file mode 100644
index 0000000000..ad8f1e9928
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/compaction/ClearCoordinatorLogOffsetsTask.java
@@ -0,0 +1,64 @@
+/*
+ * 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.db.compaction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+
+/**
+ * Clears the coordinator log offsets of tracked sstables whose keyspace has migrated off of mutation tracking.
+ */
+class ClearCoordinatorLogOffsetsTask extends AbstractCompactionTask
+{
+    private static final Logger logger = LoggerFactory.getLogger(ClearCoordinatorLogOffsetsTask.class);
+
+    private final Runnable onCompleted;
+
+    ClearCoordinatorLogOffsetsTask(ColumnFamilyStore cfs, LifecycleTransaction transaction, Runnable onCompleted)
+    {
+        super(cfs, transaction);
+        this.onCompleted = onCompleted;
+    }
+
+    protected void runMayThrow() throws Exception
+    {
+        boolean completed = false;
+        try
+        {
+            logger.info("Clearing coordinator log offsets from {}; {}.{} no longer uses mutation tracking",
+                        transaction.originals(), cfs.metadata.keyspace, cfs.metadata.name);
+            cfs.getCompactionStrategyManager().clearCoordinatorLogOffsets(transaction.originals());
+            completed = true;
+        }
+        finally
+        {
+            transaction.abort();
+            if (completed && onCompleted != null)
+                onCompleted.run();
+        }
+    }
+
+    protected void executeInternal(ActiveCompactionsTracker activeCompactions)
+    {
+        run();
+    }
+}
diff --git a/src/java/org/apache/cassandra/db/compaction/CompactionGroup.java b/src/java/org/apache/cassandra/db/compaction/CompactionGroup.java
new file mode 100644
index 0000000000..116725d14d
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/compaction/CompactionGroup.java
@@ -0,0 +1,69 @@
+/*
+ * 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.db.compaction;
+
+import com.google.common.base.Preconditions;
+
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
+import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.utils.TimeUUID;
+
+/**
+ * Which compaction strategy holder an sstable belongs to.
+ * <p>
+ * Sstables are grouped into separate silos that aren't compacted together for correctness reasons related to
+ * their replication and anti-entropy mechanisms. The group assignment is purely a function of sstable metadata and
+ * this enum lists the top level buckets and contains the logic for classifying a given sstable
+ */
+public enum CompactionGroup
+{
+    UNREPAIRED, // untracked, unrepaired data
+    PENDING_REPAIR,  // sstables currently involved in incremental repair - contains sub buckets per repair session
+    UNRECONCILED,  // tracked data awaiting reconciliation - contains sub buckets per set of activated transfers
+    REPAIRED;  // incrementall repaired or fully reconciled. Data in each bucket should eventually be promoted here
+
+    public static CompactionGroup of(SSTableReader sstable)
+    {
+        StatsMetadata metadata = sstable.getSSTableMetadata();
+        return of(metadata.repairedAt, metadata.pendingRepair, metadata.coordinatorLogOffsets);
+    }
+
+    public static CompactionGroup of(long repairedAt, TimeUUID pendingRepair, ImmutableCoordinatorLogOffsets offsets)
+    {
+        boolean isRepaired = repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE;
+        boolean isPendingRepair = pendingRepair != ActiveRepairService.NO_PENDING_REPAIR;
+        Preconditions.checkArgument(!(isRepaired && isPendingRepair),
+                                    "SSTables cannot be both repaired and pending repair");
+
+        if (isRepaired)
+            return REPAIRED;
+
+        if (isPendingRepair)
+            return PENDING_REPAIR;
+
+        // Transfers and mutations both go here. Which sub bucket an sstable lands in is
+        // TrackedCompactionManager's business, keyed on ImmutableCoordinatorLogOffsets.transferSiloKey().
+        if (offsets != null && !offsets.isEmpty())
+            return UNRECONCILED;
+
+        return UNREPAIRED;
+    }
+}
diff --git a/src/java/org/apache/cassandra/db/compaction/CompactionStrategyHolder.java b/src/java/org/apache/cassandra/db/compaction/CompactionStrategyHolder.java
index 34a0181c3c..5c4715d5cc 100644
--- a/src/java/org/apache/cassandra/db/compaction/CompactionStrategyHolder.java
+++ b/src/java/org/apache/cassandra/db/compaction/CompactionStrategyHolder.java
@@ -39,18 +39,17 @@ import org.apache.cassandra.io.sstable.SSTableMultiWriter;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
 import org.apache.cassandra.schema.CompactionParams;
-import org.apache.cassandra.service.ActiveRepairService;
 import org.apache.cassandra.utils.TimeUUID;
 
 public class CompactionStrategyHolder extends AbstractStrategyHolder
 {
     private final List<AbstractCompactionStrategy> strategies = new ArrayList<>();
-    private final boolean isRepaired;
+    private final CompactionGroup group;
 
-    public CompactionStrategyHolder(ColumnFamilyStore cfs, DestinationRouter router, boolean isRepaired)
+    public CompactionStrategyHolder(ColumnFamilyStore cfs, DestinationRouter router, CompactionGroup group)
     {
         super(cfs, router);
-        this.isRepaired = isRepaired;
+        this.group = group;
     }
 
     @Override
@@ -74,18 +73,14 @@ public class CompactionStrategyHolder extends AbstractStrategyHolder
     }
 
     @Override
-    public boolean managesRepairedGroup(boolean isRepaired, boolean isPendingRepair)
+    public boolean managesGroup(CompactionGroup group)
     {
-        if (!isPendingRepair)
-        {
-            return this.isRepaired == isRepaired;
-        }
-        else
-        {
-            Preconditions.checkArgument(!isRepaired, "SSTables cannot be both repaired and pending repair");
-            return false;
+        return this.group == group;
+    }
 
-        }
+    boolean isRepaired()
+    {
+        return group == CompactionGroup.REPAIRED;
     }
 
     @Override
@@ -204,7 +199,7 @@ public class CompactionStrategyHolder extends AbstractStrategyHolder
 
     Collection<Collection<SSTableReader>> groupForAnticompaction(Iterable<SSTableReader> sstables)
     {
-        Preconditions.checkState(!isRepaired);
+        Preconditions.checkState(!isRepaired());
         GroupedSSTableContainer group = createGroupedSSTableContainer();
         sstables.forEach(group::add);
 
@@ -232,18 +227,9 @@ public class CompactionStrategyHolder extends AbstractStrategyHolder
                                                        Collection<Index.Group> indexGroups,
                                                        ILifecycleTransaction txn)
     {
-        if (isRepaired)
-        {
-            Preconditions.checkArgument(repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE,
-                                        "Repaired CompactionStrategyHolder can't create unrepaired sstable writers");
-        }
-        else
-        {
-            Preconditions.checkArgument(repairedAt == ActiveRepairService.UNREPAIRED_SSTABLE,
-                                        "Unrepaired CompactionStrategyHolder can't create repaired sstable writers");
-        }
-        Preconditions.checkArgument(pendingRepair == null,
-                                    "CompactionStrategyHolder can't create sstable writer with pendingRepair id");
+        Preconditions.checkArgument(managesGroup(CompactionGroup.of(repairedAt, pendingRepair, coordinatorLogOffsets)),
+                                    "%s CompactionStrategyHolder can't create a writer for an sstable it would not manage",
+                                    group);
         // to avoid creating a compaction strategy for the wrong pending repair manager, we get the index based on where the sstable is to be written
         AbstractCompactionStrategy strategy = strategies.get(router.getIndexForSSTableDirectory(descriptor));
         return strategy.createSSTableMultiWriter(descriptor,
diff --git a/src/java/org/apache/cassandra/db/compaction/CompactionStrategyManager.java b/src/java/org/apache/cassandra/db/compaction/CompactionStrategyManager.java
index 1ceda32ff5..ba649eb40a 100644
--- a/src/java/org/apache/cassandra/db/compaction/CompactionStrategyManager.java
+++ b/src/java/org/apache/cassandra/db/compaction/CompactionStrategyManager.java
@@ -25,6 +25,7 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.ConcurrentModificationException;
+import java.util.EnumMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
@@ -36,10 +37,10 @@ import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
-import java.util.stream.Stream;
 import java.util.stream.StreamSupport;
 
 import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
@@ -84,6 +85,7 @@ import org.apache.cassandra.repair.consistent.admin.CleanupSummary;
 import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
 import org.apache.cassandra.schema.CompactionParams;
 import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.utils.Throwables;
 import org.apache.cassandra.utils.TimeUUID;
 
 import static org.apache.cassandra.db.compaction.AbstractStrategyHolder.GroupedSSTableContainer;
@@ -130,8 +132,10 @@ public class CompactionStrategyManager implements INotificationConsumer
     private final PendingRepairHolder pendingRepairs;
     private final CompactionStrategyHolder repaired;
     private final CompactionStrategyHolder unrepaired;
+    private final TrackedCompactionManager tracked;
 
     private final ImmutableList<AbstractStrategyHolder> holders;
+    private final EnumMap<CompactionGroup, AbstractStrategyHolder> holderByGroup;
 
     private volatile CompactionParams params;
     private DiskBoundaries currentBoundaries;
@@ -175,9 +179,23 @@ public class CompactionStrategyManager implements INotificationConsumer
             }
         };
         pendingRepairs = new PendingRepairHolder(cfs, router);
-        repaired = new CompactionStrategyHolder(cfs, router, true);
-        unrepaired = new CompactionStrategyHolder(cfs, router, false);
-        holders = ImmutableList.of(pendingRepairs, repaired, unrepaired);
+        repaired = new CompactionStrategyHolder(cfs, router, CompactionGroup.REPAIRED);
+        unrepaired = new CompactionStrategyHolder(cfs, router, CompactionGroup.UNREPAIRED);
+        tracked = new TrackedCompactionManager(cfs, router);
+        holders = ImmutableList.of(pendingRepairs, repaired, unrepaired, tracked);
+
+        holderByGroup = new EnumMap<>(CompactionGroup.class);
+        for (CompactionGroup group : CompactionGroup.values())
+        {
+            for (AbstractStrategyHolder holder : holders)
+            {
+                if (!holder.managesGroup(group))
+                    continue;
+                AbstractStrategyHolder previous = holderByGroup.put(group, holder);
+                Preconditions.checkState(previous == null, "More than one holder claims %s", group);
+            }
+            Preconditions.checkState(holderByGroup.containsKey(group), "No holder claims %s", group);
+        }
 
         cfs.getTracker().subscribe(this);
         logger.trace("Compaction manager for {}.{} subscribed to the data tracker.", cfs.keyspace.getName(), cfs.name);
@@ -215,6 +233,12 @@ public class CompactionStrategyManager implements INotificationConsumer
             if (repairFinishedTasks != null && !repairFinishedTasks.isEmpty())
                 return repairFinishedTasks;
 
+            // then promote tracked sstables whose mutations or transfers have reconciled, or demote to unrepaire
+            // and remove the offsets if this keyspace is no longer using mutation tracking.
+            Collection<AbstractCompactionTask> trackedTasks = tracked.getNextTrackedTasks();
+            if (trackedTasks != null && !trackedTasks.isEmpty())
+                return trackedTasks;
+
             // sort compaction task suppliers by remaining tasks descending
             List<TaskSupplier> suppliers = new ArrayList<>(numPartitions * holders.size());
             for (AbstractStrategyHolder holder : holders)
@@ -854,9 +878,10 @@ public class CompactionStrategyManager implements INotificationConsumer
         readLock.lock();
         try
         {
-            List<Map<Long, Integer>> countsByBucket = Stream.concat(
-                                                                StreamSupport.stream(repaired.allStrategies().spliterator(), false),
-                                                                StreamSupport.stream(unrepaired.allStrategies().spliterator(), false))
+            Iterable<AbstractCompactionStrategy> strategies = Iterables.concat(repaired.allStrategies(),
+                                                                              unrepaired.allStrategies(),
+                                                                              tracked.allStrategies());
+            List<Map<Long, Integer>> countsByBucket = StreamSupport.stream(strategies.spliterator(), false)
                                                             .filter((TimeWindowCompactionStrategy.class)::isInstance)
                                                             .map(s -> ((TimeWindowCompactionStrategy)s).getSSTableCountByBuckets())
                                                             .collect(Collectors.toList());
@@ -927,32 +952,20 @@ public class CompactionStrategyManager implements INotificationConsumer
 
     private AbstractStrategyHolder getHolder(SSTableReader sstable)
     {
-        for (AbstractStrategyHolder holder : holders)
-        {
-            if (holder.managesSSTable(sstable))
-                return holder;
-        }
-
-        throw new IllegalStateException("No holder claimed " + sstable);
+        return getHolder(CompactionGroup.of(sstable));
     }
 
-    private AbstractStrategyHolder getHolder(long repairedAt, TimeUUID pendingRepair)
+    private AbstractStrategyHolder getHolder(long repairedAt,
+                                             TimeUUID pendingRepair,
+                                             ImmutableCoordinatorLogOffsets coordinatorLogOffsets)
     {
-        return getHolder(repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE,
-                         pendingRepair != ActiveRepairService.NO_PENDING_REPAIR);
+        return getHolder(CompactionGroup.of(repairedAt, pendingRepair, coordinatorLogOffsets));
     }
 
     @VisibleForTesting
-    AbstractStrategyHolder getHolder(boolean isRepaired, boolean isPendingRepair)
+    AbstractStrategyHolder getHolder(CompactionGroup group)
     {
-        for (AbstractStrategyHolder holder : holders)
-        {
-            if (holder.managesRepairedGroup(isRepaired, isPendingRepair))
-                return holder;
-        }
-
-        throw new IllegalStateException(String.format("No holder claimed isPendingRepair: %s, isPendingRepair %s",
-                                                      isRepaired, isPendingRepair));
+        return holderByGroup.get(group);
     }
 
     @VisibleForTesting
@@ -1245,6 +1258,11 @@ public class CompactionStrategyManager implements INotificationConsumer
                 }
                 tasks = CompositeCompactionTask.applyParallelismLimit(tasks, permittedParallelism);
             }
+            catch (Throwable t)
+            {
+                // Abort any txns already created
+                throw Throwables.throwAsUncheckedException(Throwables.perform(t, tasks.stream().map(task -> task::rejected)));
+            }
             finally
             {
                 readLock.unlock();
@@ -1310,6 +1328,10 @@ public class CompactionStrategyManager implements INotificationConsumer
         {
             int tasks = pendingRepairs.getEstimatedRemainingTasks();
 
+            // Every holder the incoming sstables are not distributed over still contributes its current backlog, so
+            // that callers comparing this against a threshold see the whole table.
+            tasks += tracked.getEstimatedRemainingTasks();
+
             Iterable<AbstractCompactionStrategy> strategies;
             if (isIncremental)
             {
@@ -1357,7 +1379,8 @@ public class CompactionStrategyManager implements INotificationConsumer
         {
             return Arrays.asList(Lists.newArrayList(repaired.allStrategies()),
                                  Lists.newArrayList(unrepaired.allStrategies()),
-                                 Lists.newArrayList(pendingRepairs.allStrategies()));
+                                 Lists.newArrayList(pendingRepairs.allStrategies()),
+                                 Lists.newArrayList(tracked.allStrategies()));
         }
         finally
         {
@@ -1410,7 +1433,7 @@ public class CompactionStrategyManager implements INotificationConsumer
         readLock.lock();
         try
         {
-            return getHolder(repairedAt, pendingRepair).createSSTableMultiWriter(descriptor,
+            return getHolder(repairedAt, pendingRepair, coordinatorLogOffsets).createSSTableMultiWriter(descriptor,
                                                                                               keyCount,
                                                                                               repairedAt,
                                                                                               pendingRepair,
@@ -1515,6 +1538,80 @@ public class CompactionStrategyManager implements INotificationConsumer
         }
     }
 
+    /**
+     * Promote reconciled sstables to repaired and clear their coordinator log offsets in the same metadata mutation,
+     * then move them between strategies under the write lock as {@link #mutateRepaired} does.
+     *
+     * @return the sstables that were promoted
+     */
+    public Set<SSTableReader> promoteReconciled(Collection<SSTableReader> sstables, long repairedAt) throws IOException
+    {
+        if (sstables.isEmpty())
+            return Collections.emptySet();
+        Set<SSTableReader> changed = new HashSet<>();
+
+        writeLock.lock();
+        try
+        {
+            for (SSTableReader sstable : sstables)
+            {
+                sstable.mutatePromotedToRepairedAndReload(repairedAt);
+                verifyMetadata(sstable, repairedAt, ActiveRepairService.NO_PENDING_REPAIR);
+                if (!sstable.getSSTableMetadata().coordinatorLogOffsets.isEmpty())
+                    throw new IllegalStateException(String.format("Failed clearing coordinator log offsets on %s", sstable));
+                changed.add(sstable);
+            }
+        }
+        finally
+        {
+            try
+            {
+                cfs.getTracker().notifySSTableRepairedStatusChanged(changed);
+            }
+            finally
+            {
+                writeLock.unlock();
+            }
+        }
+        return changed;
+    }
+
+    /**
+     * Removes the coordinator log offsets of sstables whose keyspace has stopped using mutation tracking, leaving
+     * {@code repairedAt} unset. This moves them from {@link CompactionGroup#UNRECONCILED} to
+     * {@link CompactionGroup#UNREPAIRED}
+     */
+    public Set<SSTableReader> clearCoordinatorLogOffsets(Collection<SSTableReader> sstables) throws IOException
+    {
+        if (sstables.isEmpty())
+            return Collections.emptySet();
+        Set<SSTableReader> changed = new HashSet<>();
+
+        writeLock.lock();
+        try
+        {
+            for (SSTableReader sstable : sstables)
+            {
+                sstable.mutateCoordinatorLogOffsetsAndReload(ImmutableCoordinatorLogOffsets.NONE);
+                if (!sstable.getSSTableMetadata().coordinatorLogOffsets.isEmpty())
+                    throw new IllegalStateException(String.format("Failed clearing coordinator log offsets on %s", sstable));
+                changed.add(sstable);
+            }
+        }
+        finally
+        {
+            try
+            {
+                cfs.getTracker().notifySSTableRepairedStatusChanged(changed);
+            }
+            finally
+            {
+                writeLock.unlock();
+            }
+        }
+        return changed;
+    }
+
     private static void verifyMetadata(SSTableReader sstable, long repairedAt, TimeUUID pendingRepair)
     {
         if (!Objects.equals(pendingRepair, sstable.getPendingRepair()))
diff --git a/src/java/org/apache/cassandra/db/compaction/CompactionTask.java b/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
index 7e41d980de..c2949739a8 100644
--- a/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
+++ b/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
@@ -56,7 +56,6 @@ import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.io.sstable.metadata.MetadataCollector;
 import org.apache.cassandra.io.util.File;
 import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
-import org.apache.cassandra.replication.MutationTrackingService;
 import org.apache.cassandra.service.ActiveRepairService;
 import org.apache.cassandra.service.snapshot.SnapshotManager;
 import org.apache.cassandra.service.snapshot.SnapshotOptions;
@@ -443,12 +442,18 @@ public class CompactionTask extends AbstractCompactionTask
         return ids.iterator().next();
     }
 
+    /**
+     * Union the inputs' coordinator log offsets. Reconciled ids are not purged here.
+     *
+     * Removing ids as they reconcile leaves an sstable that is still journal-derived but no longer says so, and once
+     * its last id goes it cannot be told apart from commit-log-derived data it must not be combined with while
+     * unrepaired. {@link SSTableReader#mutatePromotedToRepairedAndReload} removes them in one step at promotion.
+     */
     public static ImmutableCoordinatorLogOffsets getCoordinatorLogOffsets(Set<SSTableReader> sstables)
     {
         ImmutableCoordinatorLogOffsets.Builder builder = new ImmutableCoordinatorLogOffsets.Builder();
         for (SSTableReader sstable : sstables)
             builder.addAll(sstable.getCoordinatorLogOffsets());
-        builder.purgeTransfers(id -> MutationTrackingService.instance().isDurablyReconciled(id));
         return builder.build();
     }
 
diff --git a/src/java/org/apache/cassandra/db/compaction/PendingRepairHolder.java b/src/java/org/apache/cassandra/db/compaction/PendingRepairHolder.java
index 417bd04af1..2efd7a63a2 100644
--- a/src/java/org/apache/cassandra/db/compaction/PendingRepairHolder.java
+++ b/src/java/org/apache/cassandra/db/compaction/PendingRepairHolder.java
@@ -73,11 +73,9 @@ public class PendingRepairHolder extends AbstractStrategyHolder
     }
 
     @Override
-    public boolean managesRepairedGroup(boolean isRepaired, boolean isPendingRepair)
+    public boolean managesGroup(CompactionGroup group)
     {
-        Preconditions.checkArgument(!isPendingRepair || !isRepaired,
-                                    "SSTables cannot be both repaired and pending repair");
-        return isPendingRepair;
+        return group == CompactionGroup.PENDING_REPAIR;
     }
 
     @Override
diff --git a/src/java/org/apache/cassandra/db/compaction/PendingRepairManager.java b/src/java/org/apache/cassandra/db/compaction/PendingRepairManager.java
index 860c216a7e..6d3595becb 100644
--- a/src/java/org/apache/cassandra/db/compaction/PendingRepairManager.java
+++ b/src/java/org/apache/cassandra/db/compaction/PendingRepairManager.java
@@ -46,6 +46,7 @@ import org.apache.cassandra.repair.consistent.admin.CleanupSummary;
 import org.apache.cassandra.schema.CompactionParams;
 import org.apache.cassandra.service.ActiveRepairService;
 import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.Throwables;
 import org.apache.cassandra.utils.TimeUUID;
 
 /**
@@ -349,15 +350,23 @@ class PendingRepairManager
     synchronized Collection<AbstractCompactionTask> getNextRepairFinishedTasks()
     {
         List<AbstractCompactionTask> tasks = new ArrayList<>();
-        for (TimeUUID sessionID : strategies.keySet())
+        try
         {
-            if (canCleanup(sessionID))
+            for (TimeUUID sessionID : strategies.keySet())
             {
-                RepairFinishedCompactionTask repairFinishedTask = getRepairFinishedCompactionTask(sessionID);
-                if (repairFinishedTask != null)
-                    tasks.add(repairFinishedTask);
+                if (canCleanup(sessionID))
+                {
+                    RepairFinishedCompactionTask repairFinishedTask = getRepairFinishedCompactionTask(sessionID);
+                    if (repairFinishedTask != null)
+                        tasks.add(repairFinishedTask);
+                }
             }
         }
+        catch (Throwable t)
+        {
+            // Abort any txns already created
+            throw Throwables.throwAsUncheckedException(Throwables.perform(t, tasks.stream().map(task -> task::rejected)));
+        }
         return tasks;
     }
 
diff --git a/src/java/org/apache/cassandra/db/compaction/PromoteReconciledTask.java b/src/java/org/apache/cassandra/db/compaction/PromoteReconciledTask.java
new file mode 100644
index 0000000000..48e4204500
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/compaction/PromoteReconciledTask.java
@@ -0,0 +1,81 @@
+/*
+ * 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.db.compaction;
+
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.utils.Clock;
+
+/**
+ * Promotes reconciled tracked sstables to repaired in place. No data is rewritten.
+ */
+class PromoteReconciledTask extends AbstractCompactionTask
+{
+    private static final Logger logger = LoggerFactory.getLogger(PromoteReconciledTask.class);
+
+    private final String reason;
+    private final Runnable onCompleted;
+
+    static AbstractCompactionTask tryPromote(ColumnFamilyStore cfs,
+                                             Set<SSTableReader> candidates,
+                                             String reason,
+                                             Runnable onCompleted)
+    {
+        LifecycleTransaction txn = TrackedCompactionManager.tryLock(cfs, candidates, "promotion of " + reason);
+        return txn == null ? null : new PromoteReconciledTask(cfs, txn, reason, onCompleted);
+    }
+
+    PromoteReconciledTask(ColumnFamilyStore cfs, LifecycleTransaction transaction, String reason, Runnable onCompleted)
+    {
+        super(cfs, transaction);
+        this.reason = reason;
+        this.onCompleted = onCompleted;
+    }
+
+    protected void runMayThrow() throws Exception
+    {
+        boolean completed = false;
+        try
+        {
+            logger.info("Promoting {} to repaired; {} have reconciled", transaction.originals(), reason);
+            // One metadata mutation sets repairedAt and clears the offsets, so a repaired sstable never still claims
+            // journal provenance, and an unrepaired one never loses it.
+            cfs.getCompactionStrategyManager().promoteReconciled(transaction.originals(),
+                                                                Clock.Global.currentTimeMillis());
+            completed = true;
+        }
+        finally
+        {
+            transaction.abort();
+            if (completed && onCompleted != null)
+                onCompleted.run();
+        }
+    }
+
+    protected void executeInternal(ActiveCompactionsTracker activeCompactions)
+    {
+        run();
+    }
+}
diff --git a/src/java/org/apache/cassandra/db/compaction/TrackedCompactionManager.java b/src/java/org/apache/cassandra/db/compaction/TrackedCompactionManager.java
new file mode 100644
index 0000000000..2f7746fb52
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/compaction/TrackedCompactionManager.java
@@ -0,0 +1,641 @@
+/*
+ * 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.db.compaction;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.SerializationHeader;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+import org.apache.cassandra.db.commitlog.IntervalSet;
+import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.index.Index;
+import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.ISSTableScanner;
+import org.apache.cassandra.io.sstable.SSTableMultiWriter;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
+import org.apache.cassandra.replication.MutationTrackingService;
+import org.apache.cassandra.replication.ShortMutationId;
+import org.apache.cassandra.schema.CompactionParams;
+import org.apache.cassandra.schema.KeyspaceMetadata;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.service.replication.migration.KeyspaceMigrationInfo;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.TimeUUID;
+
+/**
+ * Holds {@link CompactionGroup#UNRECONCILED} sstables, isolating them into one silo per set of activated transfer
+ * ids, and promoting the contents of each silo to repaired as its contents are durably reconciled - continuously in
+ * the case of normal writes, all at once in the case of tracked transfers. This is the mutation tracking counterpart
+ * to {@link PendingRepairManager}. SSTables created by the normal write path don't have transfer ids and are in the
+ * silo under the key {@link #NONE}. Like {@link PendingRepairManager}, silos are created lazily per key, and discarded
+ * when empty, with the exception of the {@link #NONE} silo, which is never purged.
+ */
+public class TrackedCompactionManager extends AbstractStrategyHolder
+{
+    private static final Logger logger = LoggerFactory.getLogger(TrackedCompactionManager.class);
+
+    /**
+     * Silo for tracked sstables that carry mutation offsets and no activated transfers. Created with the strategy and
+     * never pruned, because ordinary tracked flushes land here continuously.
+     *
+     * {@link ImmutableCoordinatorLogOffsets#transferSiloKey()} is empty for exactly these sstables, so routing one
+     * needs no separate classification.
+     */
+    static final ImmutableSet<ShortMutationId> NONE = ImmutableSet.of();
+
+    private CompactionParams params;
+    private int numTokenPartitions;
+
+    private volatile ImmutableMap<ImmutableSet<ShortMutationId>, CompactionStrategyHolder> silos = ImmutableMap.of();
+
+    public TrackedCompactionManager(ColumnFamilyStore cfs, DestinationRouter router)
+    {
+        super(cfs, router);
+    }
+
+    static ImmutableSet<ShortMutationId> keyOf(SSTableReader sstable)
+    {
+        return sstable.getSSTableMetadata().coordinatorLogOffsets.transferSiloKey();
+    }
+
+    private static String describe(ImmutableSet<ShortMutationId> key)
+    {
+        return key.isEmpty() ? "reconciled mutations" : "tracked transfers " + key;
+    }
+
+    /**
+     * Marks as many of {@code candidates} compacting as are free, or returns null if none are.
+     */
+    static LifecycleTransaction tryLock(ColumnFamilyStore cfs, Set<SSTableReader> candidates, String reason)
+    {
+        if (candidates.isEmpty())
+            return null;
+
+        Set<SSTableReader> available = new HashSet<>(candidates);
+        available.removeAll(cfs.getTracker().getCompacting());
+        if (available.isEmpty())
+        {
+            logger.trace("Deferring {} for {}.{}; all {} sstables are busy",
+                         reason, cfs.metadata.keyspace, cfs.metadata.name, candidates.size());
+            return null;
+        }
+
+        LifecycleTransaction txn = cfs.getTracker().tryModify(available, OperationType.COMPACTION);
+        if (txn == null)
+        {
+            // if one or more of the sstables are already marked compacted, remove them and try again. Since we try to
+            // handle all eligible sstables in a single task, this keeps compaction from preventing any progress
+            available.removeAll(cfs.getTracker().getCompacting());
+            if (available.isEmpty())
+                return null;
+            txn = cfs.getTracker().tryModify(available, OperationType.COMPACTION);
+            if (txn == null)
+                logger.trace("Deferring {} for {}.{}; lost the race for its sstables",
+                             reason, cfs.metadata.keyspace, cfs.metadata.name);
+        }
+        return txn;
+    }
+
+    @Override
+    public boolean managesGroup(CompactionGroup group)
+    {
+        return group == CompactionGroup.UNRECONCILED;
+    }
+
+    @Override
+    public void setStrategyInternal(CompactionParams params, int numTokenPartitions)
+    {
+        this.params = params;
+        this.numTokenPartitions = numTokenPartitions;
+        this.silos = ImmutableMap.of(NONE, newSilo(NONE));
+    }
+
+    private CompactionStrategyHolder newSilo(ImmutableSet<ShortMutationId> key)
+    {
+        logger.debug("Creating {}.{} compaction strategies for tracked transfers: {}",
+                     cfs.metadata.keyspace, cfs.metadata.name, key);
+        CompactionStrategyHolder silo = new CompactionStrategyHolder(cfs, router, CompactionGroup.UNRECONCILED);
+        silo.setStrategy(params, numTokenPartitions);
+        return silo;
+    }
+
+    @VisibleForTesting
+    CompactionStrategyHolder getIfPresent(ImmutableSet<ShortMutationId> key)
+    {
+        return silos.get(key);
+    }
+
+    @VisibleForTesting
+    CompactionStrategyHolder getIfPresent(SSTableReader sstable)
+    {
+        return getIfPresent(keyOf(sstable));
+    }
+
+    /**
+     * getOrCreate the compaction strategy holder for the given transfer id
+     *
+     * Although this method correctly synchronizes updates to the containing datastructure (silos) on the create path,
+     * it does return an object that's contained in a datastructure guarded by the object monitor. So callers need
+     * to use care when calling this and make sure they're adhering to this class thread safety requirements
+     */
+    @VisibleForTesting
+    CompactionStrategyHolder getOrCreate(ImmutableSet<ShortMutationId> key)
+    {
+        CompactionStrategyHolder silo = silos.get(key);
+        if (silo == null)
+        {
+            synchronized (this)
+            {
+                silo = silos.get(key);
+                if (silo == null)
+                {
+                    silo = newSilo(key);
+                    silos = ImmutableMap.<ImmutableSet<ShortMutationId>, CompactionStrategyHolder>builder()
+                                        .putAll(silos).put(key, silo).build();
+                }
+            }
+        }
+        return silo;
+    }
+
+    CompactionStrategyHolder getOrCreate(SSTableReader sstable)
+    {
+        return getOrCreate(keyOf(sstable));
+    }
+
+    private static Iterable<SSTableReader> sstablesIn(CompactionStrategyHolder silo)
+    {
+        return Iterables.concat(Iterables.transform(silo.allStrategies(), AbstractCompactionStrategy::getSSTables));
+    }
+
+    private static boolean isEmpty(CompactionStrategyHolder silo)
+    {
+        return Iterables.isEmpty(sstablesIn(silo));
+    }
+
+    /**
+     * Drop every transfer silo that holds no sstables. Called from the paths that walk the map anyway, so teardown does
+     * not depend on any particular removal notification arriving. The silo that holds normal writes is never pruned
+     */
+    private synchronized void pruneEmpty()
+    {
+        Set<ImmutableSet<ShortMutationId>> empty = null;
+        for (Map.Entry<ImmutableSet<ShortMutationId>, CompactionStrategyHolder> entry : silos.entrySet())
+        {
+            // don't prune the normal write silo
+            if (entry.getKey().isEmpty())
+                continue;
+
+            if (isEmpty(entry.getValue()))
+            {
+                if (empty == null)
+                    empty = new HashSet<>();
+                empty.add(entry.getKey());
+            }
+        }
+
+        if (empty == null)
+            return;
+
+        Set<ImmutableSet<ShortMutationId>> dropped = empty;
+        logger.debug("Removing {}.{} compaction strategies for reconciled or emptied tracked transfers: {}",
+                     cfs.metadata.keyspace, cfs.metadata.name, dropped);
+        for (ImmutableSet<ShortMutationId> key : dropped)
+            silos.get(key).shutdown();
+        silos = ImmutableMap.copyOf(Maps.filterKeys(silos, k -> !dropped.contains(k)));
+    }
+
+    @Override
+    public synchronized void startup()
+    {
+        silos.values().forEach(CompactionStrategyHolder::startup);
+    }
+
+    @Override
+    public synchronized void shutdown()
+    {
+        silos.values().forEach(CompactionStrategyHolder::shutdown);
+    }
+
+    @Override
+    public AbstractCompactionStrategy getStrategyFor(SSTableReader sstable)
+    {
+        Preconditions.checkArgument(managesSSTable(sstable), "Attempting to get compaction strategy from wrong holder");
+        return getOrCreate(sstable).getStrategyFor(sstable);
+    }
+
+    @Override
+    public Iterable<AbstractCompactionStrategy> allStrategies()
+    {
+        return Iterables.concat(Iterables.transform(silos.values(), AbstractStrategyHolder::allStrategies));
+    }
+
+    @Override
+    public synchronized void addSSTable(SSTableReader sstable)
+    {
+        Preconditions.checkArgument(managesSSTable(sstable), "Attempting to add sstable from wrong holder");
+        getOrCreate(sstable).addSSTable(sstable);
+    }
+
+    @VisibleForTesting
+    synchronized void addSSTables(Iterable<SSTableReader> sstables)
+    {
+        for (SSTableReader sstable : sstables)
+            addSSTable(sstable);
+    }
+
+    @Override
+    public synchronized void addSSTables(GroupedSSTableContainer sstables)
+    {
+        for (Map.Entry<ImmutableSet<ShortMutationId>, GroupedSSTableContainer> entry : splitByKey(sstables).entrySet())
+            getOrCreate(entry.getKey()).addSSTables(entry.getValue());
+    }
+
+    @Override
+    public synchronized void removeSSTables(GroupedSSTableContainer sstables)
+    {
+        for (CompactionStrategyHolder silo : silos.values())
+            silo.removeSSTables(sstables);
+        pruneEmpty();
+    }
+
+    @VisibleForTesting
+    synchronized void removeSSTable(SSTableReader sstable)
+    {
+        for (CompactionStrategyHolder silo : silos.values())
+            silo.getStrategyFor(sstable).removeSSTable(sstable);
+        pruneEmpty();
+    }
+
+    @Override
+    public synchronized void replaceSSTables(GroupedSSTableContainer removed, GroupedSSTableContainer added)
+    {
+        Map<ImmutableSet<ShortMutationId>, GroupedSSTableContainer> addedByKey = splitByKey(added);
+
+        // Removals go to every silo, for the reason given on removeSSTables.
+        for (Map.Entry<ImmutableSet<ShortMutationId>, CompactionStrategyHolder> entry : silos.entrySet())
+        {
+            CompactionStrategyHolder silo = entry.getValue();
+            GroupedSSTableContainer addedForSilo = addedByKey.get(entry.getKey());
+            silo.replaceSSTables(removed, addedForSilo == null ? silo.createGroupedSSTableContainer() : addedForSilo);
+        }
+        pruneEmpty();
+    }
+
+    /**
+     * Regroups a container by silo key, creating any silo it does not find
+     */
+    private Map<ImmutableSet<ShortMutationId>, GroupedSSTableContainer> splitByKey(GroupedSSTableContainer sstables)
+    {
+        Map<ImmutableSet<ShortMutationId>, GroupedSSTableContainer> split = new HashMap<>();
+        for (int i = 0; i < sstables.numGroups(); i++)
+        {
+            for (SSTableReader sstable : sstables.getGroup(i))
+            {
+                ImmutableSet<ShortMutationId> key = keyOf(sstable);
+                split.computeIfAbsent(key, k -> getOrCreate(k).createGroupedSSTableContainer()).add(sstable);
+            }
+        }
+        return split;
+    }
+
+    @Override
+    public synchronized List<ISSTableScanner> getScanners(GroupedSSTableContainer sstables, Collection<Range<Token>> ranges)
+    {
+        List<ISSTableScanner> scanners = new ArrayList<>();
+        try
+        {
+            for (Map.Entry<ImmutableSet<ShortMutationId>, GroupedSSTableContainer> entry : splitByKey(sstables).entrySet())
+                scanners.addAll(getOrCreate(entry.getKey()).getScanners(entry.getValue(), ranges));
+        }
+        catch (Throwable t)
+        {
+            ISSTableScanner.closeAllAndPropagate(scanners, t);
+        }
+        return scanners;
+    }
+
+    @Override
+    public synchronized Collection<AbstractCompactionTask> getUserDefinedTasks(GroupedSSTableContainer sstables, long gcBefore)
+    {
+        List<AbstractCompactionTask> tasks = new ArrayList<>();
+        for (Map.Entry<ImmutableSet<ShortMutationId>, GroupedSSTableContainer> entry : splitByKey(sstables).entrySet())
+        {
+            // CompactionStrategyHolder passes through whatever getUserDefinedTask returns, including null.
+            for (AbstractCompactionTask task : getOrCreate(entry.getKey()).getUserDefinedTasks(entry.getValue(), gcBefore))
+            {
+                if (task != null)
+                    tasks.add(task);
+            }
+        }
+        return tasks;
+    }
+
+    @Override
+    public SSTableMultiWriter createSSTableMultiWriter(Descriptor descriptor,
+                                                      long keyCount,
+                                                      long repairedAt,
+                                                      TimeUUID pendingRepair,
+                                                      ImmutableCoordinatorLogOffsets coordinatorLogOffsets,
+                                                      IntervalSet<CommitLogPosition> commitLogPositions,
+                                                      int sstableLevel,
+                                                      SerializationHeader header,
+                                                      Collection<Index.Group> indexGroups,
+                                                      ILifecycleTransaction txn)
+    {
+        // These guards read pre-write metadata. SSTableWriter.finalizeMetadata() can promote the sstable as it is
+        // written, so the holder that creates the writer and the holder that ends up with the sstable can differ.
+        Preconditions.checkArgument(repairedAt == ActiveRepairService.UNREPAIRED_SSTABLE,
+                                    "TrackedCompactionManager can't create sstable writer with repaired at set");
+        Preconditions.checkArgument(pendingRepair == ActiveRepairService.NO_PENDING_REPAIR,
+                                    "TrackedCompactionManager can't create sstable writer with pendingRepair id");
+
+        // The silo indexes by write destination rather than by token, so this creates no strategy in the wrong place.
+        return getOrCreate(coordinatorLogOffsets.transferSiloKey())
+               .createSSTableMultiWriter(descriptor,
+                                         keyCount,
+                                         repairedAt,
+                                         pendingRepair,
+                                         coordinatorLogOffsets,
+                                         commitLogPositions,
+                                         sstableLevel,
+                                         header,
+                                         indexGroups,
+                                         txn);
+    }
+
+    @Override
+    public int getStrategyIndex(AbstractCompactionStrategy strategy)
+    {
+        for (CompactionStrategyHolder silo : silos.values())
+        {
+            int idx = silo.getStrategyIndex(strategy);
+            if (idx >= 0)
+                return idx;
+        }
+        return -1;
+    }
+
+    @Override
+    public boolean containsSSTable(SSTableReader sstable)
+    {
+        return Iterables.any(silos.values(), silo -> silo.containsSSTable(sstable));
+    }
+
+    @VisibleForTesting
+    boolean isPromotable(SSTableReader sstable)
+    {
+        if (!MutationTrackingService.instance().isStarted())
+            return false;
+
+        if (sstable.isRepaired() || sstable.isPendingRepair())
+            return false;
+
+        ImmutableCoordinatorLogOffsets offsets = sstable.getSSTableMetadata().coordinatorLogOffsets;
+        if (offsets.isEmpty())
+            return false;
+
+        return MutationTrackingService.instance().isDurablyReconciled(offsets);
+    }
+
+    @VisibleForTesting
+    synchronized Set<SSTableReader> promotableSSTables(ImmutableSet<ShortMutationId> key)
+    {
+        CompactionStrategyHolder silo = silos.get(key);
+        if (silo == null)
+            return Collections.emptySet();
+
+        Set<SSTableReader> promotable = new HashSet<>();
+        for (SSTableReader sstable : sstablesIn(silo))
+        {
+            if (isPromotable(sstable))
+                promotable.add(sstable);
+        }
+        return promotable;
+    }
+
+    @VisibleForTesting
+    synchronized Set<SSTableReader> promotableSSTables()
+    {
+        // TODO: consider grabbing a snapshot of reconciled offsets and comparing against
+        //  sstable metadata without allocating collections
+        Set<SSTableReader> promotable = new HashSet<>();
+        for (ImmutableSet<ShortMutationId> key : silos.keySet())
+            promotable.addAll(promotableSSTables(key));
+        return promotable;
+    }
+
+    @VisibleForTesting
+    synchronized Set<SSTableReader> sstablesFor(ImmutableSet<ShortMutationId> key)
+    {
+        CompactionStrategyHolder silo = silos.get(key);
+        return silo == null ? Collections.emptySet() : ImmutableSet.copyOf(sstablesIn(silo));
+    }
+
+    @Override
+    public synchronized int getEstimatedRemainingTasks()
+    {
+        pruneEmpty();
+        int tasks = 0;
+        for (CompactionStrategyHolder silo : silos.values())
+            tasks += silo.getEstimatedRemainingTasks();
+        return tasks;
+    }
+
+    /**
+     * One supplier per strategy, from the silos not awaiting promotion.
+     *
+     * The number each supplier carries is its own strategy's estimate, because that is what its callback compacts.
+     * {@link CompactionStrategyManager#getNextBackgroundTasks} sorts every holder's suppliers together, so a per silo
+     * or per manager total would let tracked compaction outrank a busier strategy elsewhere.
+     */
+    @Override
+    public synchronized Collection<TaskSupplier> getBackgroundTaskSuppliers(long gcBefore)
+    {
+        pruneEmpty();
+        List<TaskSupplier> suppliers = new ArrayList<>();
+        for (CompactionStrategyHolder silo : silos.values())
+            suppliers.addAll(silo.getBackgroundTaskSuppliers(gcBefore));
+        return suppliers;
+    }
+
+    @Override
+    public synchronized Collection<AbstractCompactionTask> getMaximalTasks(long gcBefore, boolean splitOutput)
+    {
+        pruneEmpty();
+
+        // Promotion, or offset discard, first
+        List<AbstractCompactionTask> tasks = new ArrayList<>(getNextTrackedTasks());
+        try
+        {
+            for (CompactionStrategyHolder silo : silos.values())
+            {
+                Collection<AbstractCompactionTask> siloTasks = silo.getMaximalTasks(gcBefore, splitOutput);
+                if (siloTasks != null)
+                    tasks.addAll(siloTasks);
+            }
+        }
+        catch (Throwable t)
+        {
+            // Abort any txns already created
+            throw Throwables.throwAsUncheckedException(Throwables.perform(t, tasks.stream().map(task -> task::rejected)));
+        }
+        return tasks;
+    }
+
+    @VisibleForTesting
+    synchronized boolean hasDataFor(ImmutableSet<ShortMutationId> key)
+    {
+        CompactionStrategyHolder silo = silos.get(key);
+        return silo != null && !isEmpty(silo);
+    }
+
+    @VisibleForTesting
+    synchronized Set<ImmutableSet<ShortMutationId>> keys()
+    {
+        return ImmutableSet.copyOf(silos.keySet());
+    }
+
+    /**
+     * The work that has to happen before any ordinary compaction task is collected, because it is what lets an sstable
+     * leave this holder at all: promotion of the sstables that have reconciled, or, once the keyspace has stopped using
+     * mutation tracking, discarding the coordinator log offsets of everything held here.
+     *
+     * Called ahead of every other task supplier by {@link CompactionStrategyManager#getNextBackgroundTasks} and
+     * {@link #getMaximalTasks}.
+     */
+    synchronized Collection<AbstractCompactionTask> getNextTrackedTasks()
+    {
+        pruneEmpty();
+
+        // Holding nothing means there is nothing to promote and no offsets to discard. Checked before the keyspace
+        // lookup because every untracked table in the cluster reaches this on every compaction round.
+        if (holdsNothing())
+            return Collections.emptyList();
+
+        if (isTrackingAbandoned())
+            return getOffsetsDiscardTasks();
+
+        return getNextPromotionTasks();
+    }
+
+    private boolean holdsNothing()
+    {
+        for (CompactionStrategyHolder silo : silos.values())
+        {
+            if (!isEmpty(silo))
+                return false;
+        }
+        return true;
+    }
+
+    /**
+     * True once the keyspace has left mutation tracking with no ranges still pending migration. Nothing reconciles the
+     * table's tracked writes after that, so its offsets record a reconciliation that will never be confirmed, and
+     * {@link MutationTrackingService#isDurablyReconciled} cannot even resolve their log ids.
+     *
+     * Anything that cannot be determined counts as still tracked. Attempting promotion against a missing shard throws
+     * out of the compaction round, which is recoverable; discarding the offsets of a keyspace that is still tracked is
+     * not.
+     */
+    private boolean isTrackingAbandoned()
+    {
+        ClusterMetadata metadata = ClusterMetadata.currentNullable();
+        if (metadata == null)
+            return false;
+
+        KeyspaceMetadata ksm = metadata.schema.maybeGetKeyspaceMetadata(cfs.metadata.keyspace).orElse(null);
+        if (ksm == null || ksm.params.replicationType.isTracked())
+            return false;
+
+        KeyspaceMigrationInfo migration = metadata.mutationTrackingMigrationState.getKeyspaceInfo(cfs.metadata.keyspace);
+        return migration == null || migration.getPendingRangesForTable(cfs.metadata.id).isEmpty();
+    }
+
+    /**
+     * One task covering every silo, since the offsets are being discarded rather than compared: which transfers an
+     * sstable came from stops mattering as soon as nothing will reconcile them.
+     */
+    private Collection<AbstractCompactionTask> getOffsetsDiscardTasks()
+    {
+        Set<SSTableReader> candidates = new HashSet<>();
+        for (CompactionStrategyHolder silo : silos.values())
+            Iterables.addAll(candidates, sstablesIn(silo));
+
+        LifecycleTransaction txn = tryLock(cfs, candidates, "coordinator log offset discard");
+        if (txn == null)
+            return Collections.emptyList();
+
+        return Collections.singletonList(new ClearCoordinatorLogOffsetsTask(cfs, txn, this::pruneEmpty));
+    }
+
+    synchronized Collection<AbstractCompactionTask> getNextPromotionTasks()
+    {
+        pruneEmpty();
+        List<AbstractCompactionTask> tasks = new ArrayList<>();
+        try
+        {
+
+            for (ImmutableSet<ShortMutationId> key : silos.keySet())
+            {
+                AbstractCompactionTask task = getPromotionTask(key);
+                if (task != null)
+                    tasks.add(task);
+            }
+        }
+        catch (Throwable t)
+        {
+            // Abort any txns already created
+            throw Throwables.throwAsUncheckedException(Throwables.perform(t, tasks.stream().map(task -> task::rejected)));
+        }
+        return tasks;
+    }
+
+    @VisibleForTesting
+    synchronized AbstractCompactionTask getPromotionTask(ImmutableSet<ShortMutationId> key)
+    {
+        if (silos.get(key) == null)
+            return null;
+
+        return PromoteReconciledTask.tryPromote(cfs, promotableSSTables(key), describe(key), this::pruneEmpty);
+    }
+}
diff --git a/src/java/org/apache/cassandra/db/lifecycle/Tracker.java b/src/java/org/apache/cassandra/db/lifecycle/Tracker.java
index 6636f01256..84c6ca2c9b 100644
--- a/src/java/org/apache/cassandra/db/lifecycle/Tracker.java
+++ b/src/java/org/apache/cassandra/db/lifecycle/Tracker.java
@@ -40,9 +40,13 @@ import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.config.DurationSpec;
 import org.apache.cassandra.db.ColumnFamilyStore;
 import org.apache.cassandra.db.Directories;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.db.compaction.OperationType;
+import org.apache.cassandra.db.memtable.DomainMemtable;
+import org.apache.cassandra.db.memtable.LogDomainBounds;
 import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.SplitDomainMemtable;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
 import org.apache.cassandra.io.util.File;
@@ -107,18 +111,19 @@ public class Tracker
     /**
      * @param columnFamilyStore
      * @param memtable Initial Memtable. Can be null.
+     * @param bounds The boundary the current memtable starts at. null only if there's no memtable.
      * @param loadsstables true to indicate to load SSTables (TODO: remove as this is only accessed from 2i)
      */
-    public Tracker(ColumnFamilyStore columnFamilyStore, Memtable memtable, boolean loadsstables)
+    public Tracker(ColumnFamilyStore columnFamilyStore, Memtable memtable, LogDomainBounds bounds, boolean loadsstables)
     {
         this.cfstore = columnFamilyStore;
         this.loadsstables = loadsstables;
-        this.reset(memtable);
+        this.reset(memtable, bounds);
     }
 
     public static Tracker newDummyTracker()
     {
-        return new Tracker(null, null, false);
+        return new Tracker(null, null, null, false);
     }
 
     public LifecycleTransaction tryModify(SSTableReader sstable, OperationType operationType)
@@ -319,7 +324,7 @@ public class Tracker
 
     /** (Re)initializes the tracker, purging all references. */
     @VisibleForTesting
-    public void reset(Memtable memtable)
+    public void reset(Memtable memtable, LogDomainBounds bounds)
     {
         viewUpdateLock.lock();
         try
@@ -328,7 +333,8 @@ public class Tracker
                             Collections.emptyList(),
                             Collections.emptyMap(),
                             Collections.emptyMap(),
-                            SSTableIntervalTree.empty());
+                            SSTableIntervalTree.empty(),
+                            bounds);
         }
         finally
         {
@@ -415,7 +421,7 @@ public class Tracker
     /**
      * get the Memtable that the ordered writeOp should be directed to
      */
-    public Memtable getMemtableFor(OpOrder.Group opGroup, CommitLogPosition commitLogPosition)
+    public Memtable getMemtableFor(OpOrder.Group opGroup, CommitLogPosition commitLogPosition, LogDomain domain)
     {
         // since any new memtables appended to the list after we fetch it will be for operations started
         // after us, we can safely assume that we will always find the memtable that 'accepts' us;
@@ -427,10 +433,69 @@ public class Tracker
         View view = this.view;
         for (Memtable memtable : view.liveMemtables)
         {
-            if (memtable.accepts(opGroup, commitLogPosition))
+            if (memtable.accepts(opGroup, commitLogPosition, domain))
                 return memtable;
         }
-        throw new AssertionError(view.liveMemtables.toString());
+
+        // the only valid reason to leave the loop above without a memtable is if the current memtable doesn't
+        // address the domain we're trying to write for. Otherwise, this we have a bug and need to throw an exception
+        if (view.getCurrentMemtable().holds(domain))
+            throw new AssertionError("No live memtable accepted a " + domain + " write, but the current one holds that "
+                                     + "domain: " + view.liveMemtables);
+
+        // Otherwise we need to install a split memtable for the current generation
+        return installSplit(opGroup, commitLogPosition, domain);
+    }
+
+    private static final int MAX_SPLIT_ATTEMPTS = 64;
+
+    private Memtable installSplit(OpOrder.Group opGroup, CommitLogPosition commitLogPosition, LogDomain domain)
+    {
+        SplitDomainMemtable lastRefused = null;
+
+        View current = null;
+        for (int attempt = 0; attempt < MAX_SPLIT_ATTEMPTS; attempt++)
+        {
+            current = this.view;
+            Memtable oldMemtable = current.getCurrentMemtable();
+            SplitDomainMemtable splitMemtable;
+
+            if (oldMemtable instanceof SplitDomainMemtable)
+            {
+                // Split already, by a writer that beat us here.
+                splitMemtable = (SplitDomainMemtable) oldMemtable;
+            }
+            else
+            {
+                // Construct new memtable and split domain memtable inside the view mutation so it happens once, under
+                // the view lock after the permit has accepted the change
+                DomainMemtable domainMemtable = (DomainMemtable) oldMemtable; // the branch above rejected a generation
+                Pair<View, View> result = apply(View.canSplitMemtable(oldMemtable), view -> {
+                    DomainMemtable newMemtable = cfstore.createMemtable(view.currentBounds.sealIfUnset(domain), domain);
+                    SplitDomainMemtable wrapper = new SplitDomainMemtable(newMemtable, domainMemtable, domainMemtable.getMemtableId());
+                    return View.splitMemtable(oldMemtable, wrapper).apply(view);
+                });
+
+                if (result == null)
+                    continue;
+
+                splitMemtable = (SplitDomainMemtable) result.right.getCurrentMemtable();
+            }
+
+            // Asked of the generation, which delegates to the internal holding the bounds this write is measured
+            // against. The generation is also what is returned, since put routes inside it.
+            if (splitMemtable.accepts(opGroup, commitLogPosition, domain))
+                return splitMemtable;
+
+            // don't loop on the same generation refusing our write
+            if (splitMemtable == lastRefused)
+                throw new AssertionError("A " + domain + " write was refused twice by the same generation " + splitMemtable
+                                         + " in " + current.liveMemtables);
+            lastRefused = splitMemtable;
+        }
+
+        throw new AssertionError("Gave up routing a " + domain + " write after " + MAX_SPLIT_ATTEMPTS
+                                 + " attempts against " + current.liveMemtables);
     }
 
     /**
@@ -439,11 +504,14 @@ public class Tracker
      * discarding(memtable) is called. These two methods must be synchronized/paired, i.e. m = switchMemtable
      * must be followed by discarding(m), they cannot be interleaved.
      *
+     * A switch installs a single-domain memtable. A generation only becomes split in place, in
+     * {@link #installSplit}, so anything keyed on the memtable being retired has to expect several flush sources.
+     *
      * @return the previously active memtable
      */
-    public Memtable switchMemtable(boolean truncating, Memtable newMemtable)
+    public Memtable switchMemtable(boolean truncating, DomainMemtable newMemtable, LogDomainBounds newBounds)
     {
-        Pair<View, View> result = apply(View.switchMemtable(newMemtable));
+        Pair<View, View> result = apply(View.switchMemtable(newMemtable, newBounds));
         if (truncating)
             notifyRenewed(newMemtable);
         else
@@ -600,7 +668,7 @@ public class Tracker
         notify(new TablePreScrubNotification(cfstore));
     }
 
-    public void notifyRenewed(Memtable renewed)
+    public void notifyRenewed(DomainMemtable renewed)
     {
         notify(new MemtableRenewedNotification(renewed));
     }
diff --git a/src/java/org/apache/cassandra/db/lifecycle/View.java b/src/java/org/apache/cassandra/db/lifecycle/View.java
index 1d373203e7..0a00e068b3 100644
--- a/src/java/org/apache/cassandra/db/lifecycle/View.java
+++ b/src/java/org/apache/cassandra/db/lifecycle/View.java
@@ -29,13 +29,16 @@ import javax.annotation.Nullable;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Function;
 import com.google.common.base.Functions;
+import com.google.common.base.Preconditions;
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
 import org.apache.cassandra.db.DecoratedKey;
 import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.db.memtable.LogDomainBounds;
 import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.SplitDomainMemtable;
 import org.apache.cassandra.dht.AbstractBounds;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.metrics.LatencyMetrics;
@@ -87,16 +90,26 @@ public class View
 
     final SSTableIntervalTree intervalTree;
 
-    View(List<Memtable> liveMemtables, List<Memtable> flushingMemtables, Map<SSTableReader, SSTableReader> sstables, Map<SSTableReader, SSTableReader> compacting, SSTableIntervalTree intervalTree)
+    // log domain boundaries the current memtable generation began at
+    public final LogDomainBounds currentBounds;
+
+    View(List<Memtable> liveMemtables,
+         List<Memtable> flushingMemtables,
+         Map<SSTableReader, SSTableReader> sstables,
+         Map<SSTableReader, SSTableReader> compacting,
+         SSTableIntervalTree intervalTree,
+         LogDomainBounds currentBounds)
     {
         assert liveMemtables != null;
         assert flushingMemtables != null;
         assert sstables != null;
         assert compacting != null;
         assert intervalTree != null;
+        assert currentBounds != null || liveMemtables.isEmpty();
 
         this.liveMemtables = liveMemtables;
         this.flushingMemtables = flushingMemtables;
+        this.currentBounds = currentBounds;
 
         this.sstablesMap = sstables;
         this.sstables = sstablesMap.keySet();
@@ -279,7 +292,7 @@ public class View
                 assert all(mark, Helpers.idIn(view.sstablesMap));
                 return new View(view.liveMemtables, view.flushingMemtables, view.sstablesMap,
                                 replace(view.compactingMap, unmark, mark),
-                                view.intervalTree);
+                                view.intervalTree, view.currentBounds);
             }
         };
     }
@@ -314,7 +327,7 @@ public class View
                 SSTableIntervalTree sstableIntervalTree = SSTableIntervalTree.update(view.intervalTree, remove, add);
                 if (sstableIntervalTreeLatency != null)
                     sstableIntervalTreeLatency.addNano(Clock.Global.nanoTime() - treeBuildStart);
-                return new View(view.liveMemtables, view.flushingMemtables, sstableMap, view.compactingMap, sstableIntervalTree);
+                return new View(view.liveMemtables, view.flushingMemtables, sstableMap, view.compactingMap, sstableIntervalTree, view.currentBounds);
             }
         };
     }
@@ -331,13 +344,35 @@ public class View
                 SSTableIntervalTree sstableIntervalTree = SSTableIntervalTree.replace(view.intervalTree, replacementMap);
                 if (sstableIntervalTreeLatency != null)
                     sstableIntervalTreeLatency.addNano(Clock.Global.nanoTime() - treeBuildStart);
-                return new View(view.liveMemtables, view.flushingMemtables, sstableMap, view.compactingMap, sstableIntervalTree);
+                return new View(view.liveMemtables, view.flushingMemtables, sstableMap, view.compactingMap, sstableIntervalTree, view.currentBounds);
             }
         };
     }
 
-    // called prior to initiating flush: add newMemtable to liveMemtables, making it the latest memtable
-    static Function<View, View> switchMemtable(final Memtable newMemtable)
+    /**
+     * Replace the current memtable with a wrapper holding it, at the same position in the list.
+     * <p>
+     * This is used when we encounter writes from 2 different backing log domains.
+     */
+    static Function<View, View> splitMemtable(final Memtable toWrap, final SplitDomainMemtable wrapper)
+    {
+        return view -> {
+            List<Memtable> live = view.liveMemtables;
+            Preconditions.checkArgument(live.get(live.size() - 1) == toWrap, "Only the current memtable can be split");
+            List<Memtable> newLive = ImmutableList.<Memtable>builder()
+                                                  .addAll(live.subList(0, live.size() - 1))
+                                                  .add(wrapper)
+                                                  .build();
+            return new View(newLive, view.flushingMemtables, view.sstablesMap, view.compactingMap, view.intervalTree, view.currentBounds);
+        };
+    }
+
+    static Predicate<View> canSplitMemtable(final Memtable toSplit)
+    {
+        return view -> view.getCurrentMemtable() == toSplit;
+    }
+
+    static Function<View, View> switchMemtable(final Memtable newMemtable, final LogDomainBounds newBounds)
     {
         return new Function<View, View>()
         {
@@ -345,7 +380,7 @@ public class View
             {
                 List<Memtable> newLive = ImmutableList.<Memtable>builder().addAll(view.liveMemtables).add(newMemtable).build();
                 assert newLive.size() == view.liveMemtables.size() + 1;
-                return new View(newLive, view.flushingMemtables, view.sstablesMap, view.compactingMap, view.intervalTree);
+                return new View(newLive, view.flushingMemtables, view.sstablesMap, view.compactingMap, view.intervalTree, newBounds);
             }
         };
     }
@@ -364,7 +399,7 @@ public class View
                                                            filter(flushing, not(lessThan(toFlush)))));
                 assert newLive.size() == live.size() - 1;
                 assert newFlushing.size() == flushing.size() + 1;
-                return new View(newLive, newFlushing, view.sstablesMap, view.compactingMap, view.intervalTree);
+                return new View(newLive, newFlushing, view.sstablesMap, view.compactingMap, view.intervalTree, view.currentBounds);
             }
         };
     }
@@ -381,14 +416,14 @@ public class View
 
                 if (flushed == null || Iterables.isEmpty(flushed))
                     return new View(view.liveMemtables, flushingMemtables, view.sstablesMap,
-                                    view.compactingMap, view.intervalTree);
+                                    view.compactingMap, view.intervalTree, view.currentBounds);
 
                 Map<SSTableReader, SSTableReader> sstableMap = replace(view.sstablesMap, emptySet(), flushed);
                 long treeBuildStart = Clock.Global.nanoTime();
                 SSTableIntervalTree sstableIntervalTree = SSTableIntervalTree.addSSTables(view.intervalTree, flushed);
                 if (sstableIntervalTreeLatency != null)
                     sstableIntervalTreeLatency.addNano(Clock.Global.nanoTime() - treeBuildStart);
-                return new View(view.liveMemtables, flushingMemtables, sstableMap, view.compactingMap, sstableIntervalTree);
+                return new View(view.liveMemtables, flushingMemtables, sstableMap, view.compactingMap, sstableIntervalTree, view.currentBounds);
             }
         };
     }
diff --git a/src/java/org/apache/cassandra/db/memtable/AbstractAllocatorMemtable.java b/src/java/org/apache/cassandra/db/memtable/AbstractAllocatorMemtable.java
index 8e296ac604..a10c9f7c5a 100644
--- a/src/java/org/apache/cassandra/db/memtable/AbstractAllocatorMemtable.java
+++ b/src/java/org/apache/cassandra/db/memtable/AbstractAllocatorMemtable.java
@@ -33,6 +33,7 @@ import org.apache.cassandra.config.Config;
 import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.db.ClusteringComparator;
 import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.schema.TableMetadata;
 import org.apache.cassandra.schema.TableMetadataRef;
@@ -114,9 +115,9 @@ public abstract class AbstractAllocatorMemtable extends AbstractMemtableWithComm
     }
 
     // only to be used by init(), to setup the very first memtable for the cfs
-    public AbstractAllocatorMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadataRef, Owner owner)
+    public AbstractAllocatorMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadataRef, Owner owner, LogDomain domain)
     {
-        super(metadataRef, commitLogLowerBound);
+        super(metadataRef, commitLogLowerBound, domain);
         this.allocator = MEMORY_POOL.newAllocator(metadataRef.toString());
         this.initialComparator = metadata.get().comparator;
         this.initialFactory = metadata().params.memtable.factory();
@@ -129,6 +130,18 @@ public abstract class AbstractAllocatorMemtable extends AbstractMemtableWithComm
         return allocator;
     }
 
+    @Override
+    public Owner owner()
+    {
+        return owner;
+    }
+
+    @Override
+    public boolean allocatesFromMemtablePool()
+    {
+        return true;
+    }
+
     @Override
     public boolean shouldSwitch(ColumnFamilyStore.FlushReason reason, TableMetadata latest)
     {
@@ -161,9 +174,9 @@ public abstract class AbstractAllocatorMemtable extends AbstractMemtableWithComm
         throw new AssertionError("performSnapshot must be implemented if shouldSwitch(SNAPSHOT) can return false.");
     }
 
-    public void switchOut(OpOrder.Barrier writeBarrier, AtomicReference<CommitLogPosition> commitLogUpperBound)
+    public void switchOut(OpOrder.Barrier writeBarrier, LogDomainBounds upperBounds)
     {
-        super.switchOut(writeBarrier, commitLogUpperBound);
+        super.switchOut(writeBarrier, upperBounds);
         allocator.setDiscarding();
     }
 
@@ -217,9 +230,9 @@ public abstract class AbstractAllocatorMemtable extends AbstractMemtableWithComm
         {
             protected void runMayThrow()
             {
-                Memtable current = owner.getCurrentMemtable();
-                if (current instanceof AbstractAllocatorMemtable)
-                    ((AbstractAllocatorMemtable) current).flushIfPeriodExpired();
+                // Asked of the memtable rather than gated on its class, so a generation that delegates still gets the
+                // chance to flush. Gating on AbstractAllocatorMemtable silently stopped periodic flush for one.
+                owner.getCurrentMemtable().flushIfPeriodExpired();
             }
 
             @Override
@@ -231,7 +244,8 @@ public abstract class AbstractAllocatorMemtable extends AbstractMemtableWithComm
         ScheduledExecutors.scheduledTasks.scheduleSelfRecurring(runnable, period, TimeUnit.MILLISECONDS);
     }
 
-    private void flushIfPeriodExpired()
+    @Override
+    public void flushIfPeriodExpired()
     {
         int period = metadata().params.memtableFlushPeriodInMs;
         if (period > 0 && (Clock.Global.nanoTime() - creationNano >= TimeUnit.MILLISECONDS.toNanos(period)))
@@ -257,25 +271,27 @@ public abstract class AbstractAllocatorMemtable extends AbstractMemtableWithComm
     public static Future<Boolean> flushLargestMemtable()
     {
         float largestRatio = 0f;
-        AbstractAllocatorMemtable largestMemtable = null;
+        Memtable largestMemtable = null;
         Memtable.MemoryUsage largestUsage = null;
         float liveOnHeap = 0, liveOffHeap = 0;
         // we take a reference to the current main memtable for the CF prior to snapping its ownership ratios
         // to ensure we have some ordering guarantee for performing the switchMemtableIf(), i.e. we will only
         // swap if the memtables we are measuring here haven't already been swapped by the time we try to swap them
-        for (Memtable currentMemtable : ColumnFamilyStore.activeMemtables())
+        // Candidacy and ownership are asked of the memtable rather than gated on its class. Gating on
+        // AbstractAllocatorMemtable skipped a generation that delegates entirely, so it was never reclaimed however
+        // large it grew, and undercounted a delegating index generation's memory.
+        for (Memtable current : ColumnFamilyStore.activeMemtables())
         {
-            if (!(currentMemtable instanceof AbstractAllocatorMemtable))
+            if (!current.allocatesFromMemtablePool())
                 continue;
-            AbstractAllocatorMemtable current = (AbstractAllocatorMemtable) currentMemtable;
 
             // find the total ownership ratio for the memtable and all SecondaryIndexes owned by this CF,
             // both on- and off-heap, and select the largest of the two ratios to weight this CF
             MemoryUsage usage = Memtable.newMemoryUsage();
             current.addMemoryUsageTo(usage);
 
-            for (Memtable indexMemtable : current.owner.getIndexMemtables())
-                if (indexMemtable instanceof AbstractAllocatorMemtable)
+            for (Memtable indexMemtable : current.owner().getIndexMemtables())
+                if (indexMemtable.allocatesFromMemtablePool())
                     indexMemtable.addMemoryUsageTo(usage);
 
             float ratio = Math.max(usage.ownershipRatioOnHeap, usage.ownershipRatioOffHeap);
@@ -299,10 +315,10 @@ public abstract class AbstractAllocatorMemtable extends AbstractMemtableWithComm
             float flushingOnHeap = MEMORY_POOL.onHeap.reclaimingRatio();
             float flushingOffHeap = MEMORY_POOL.offHeap.reclaimingRatio();
             logger.info("Flushing largest {} to free up room. Used total: {}, live: {}, flushing: {}, this: {}",
-                        largestMemtable.owner, ratio(usedOnHeap, usedOffHeap), ratio(liveOnHeap, liveOffHeap),
+                        largestMemtable.owner(), ratio(usedOnHeap, usedOffHeap), ratio(liveOnHeap, liveOffHeap),
                         ratio(flushingOnHeap, flushingOffHeap), ratio(largestUsage.ownershipRatioOnHeap, largestUsage.ownershipRatioOffHeap));
 
-            Future<CommitLogPosition> flushFuture = largestMemtable.owner.signalFlushRequired(largestMemtable, ColumnFamilyStore.FlushReason.MEMTABLE_LIMIT);
+            Future<LogDomainPositions> flushFuture = largestMemtable.owner().signalFlushRequired(largestMemtable, ColumnFamilyStore.FlushReason.MEMTABLE_LIMIT);
             flushFuture.addListener(() -> {
                 try
                 {
diff --git a/src/java/org/apache/cassandra/db/memtable/AbstractMemtable.java b/src/java/org/apache/cassandra/db/memtable/AbstractMemtable.java
index 1b6f999daa..3fd9856902 100644
--- a/src/java/org/apache/cassandra/db/memtable/AbstractMemtable.java
+++ b/src/java/org/apache/cassandra/db/memtable/AbstractMemtable.java
@@ -18,8 +18,9 @@
 
 package org.apache.cassandra.db.memtable;
 
-import java.util.Collection;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentSkipListSet;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -30,24 +31,24 @@ import java.util.function.Consumer;
 import java.util.function.Supplier;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ImmutableMap;
 
 import org.github.jamm.Unmetered;
 
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.RegularAndStaticColumns;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
-import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
 import org.apache.cassandra.db.partitions.Partition;
 import org.apache.cassandra.db.rows.EncodingStats;
 import org.apache.cassandra.schema.ColumnMetadata;
 import org.apache.cassandra.schema.TableMetadata;
 import org.apache.cassandra.schema.TableMetadataRef;
 
-public abstract class AbstractMemtable implements Memtable
+public abstract class AbstractMemtable implements DomainMemtable
 {
     private static final AtomicLong nextId = new AtomicLong();
 
-    private final AtomicReference<LifecycleTransaction> flushTransaction = new AtomicReference<>(null);
+    private final AtomicReference<ILifecycleTransaction> flushTransaction = new AtomicReference<>(null);
     protected final AtomicLong currentOperations = new AtomicLong(0);
     protected final ColumnsCollector columnsCollector;
     protected final StatsCollector statsCollector = new StatsCollector();
@@ -56,7 +57,7 @@ public abstract class AbstractMemtable implements Memtable
     // The smallest local deletion time for all partitions in this memtable
     protected AtomicLong minLocalDeletionTime = new AtomicLong(Long.MAX_VALUE);
     private final long id = nextId.incrementAndGet();
-    private Map<Object, Consumer<TableMetadata>> onFlush = ImmutableMap.of();
+    private final FlushListeners onFlush = new FlushListeners();
     // Note: statsCollector has corresponding statistics to the two above, but starts with an epoch value which is not
     // correct for their usage.
 
@@ -142,44 +143,40 @@ public abstract class AbstractMemtable implements Memtable
     }
 
     @Override
-    public LifecycleTransaction getFlushTransaction()
+    public List<DomainMemtable> flushSources()
+    {
+        return Collections.singletonList(this);
+    }
+
+    @Override
+    public DomainMemtable flushSourceFor(LogDomain domain)
+    {
+        if (!holds(domain))
+            throw new IllegalArgumentException(String.format("Memtable %s does not hold domain %s", this, domain));
+        return this;
+    }
+
+    @Override
+    public ILifecycleTransaction getFlushTransaction()
     {
         return flushTransaction.get();
     }
 
     @Override
-    public LifecycleTransaction setFlushTransaction(LifecycleTransaction flushTransaction)
+    public ILifecycleTransaction setFlushTransaction(ILifecycleTransaction flushTransaction)
     {
         return this.flushTransaction.getAndSet(flushTransaction);
     }
 
     @Override
-    public synchronized <T extends Consumer<TableMetadata>> T ensureFlushListener(Object key, Supplier<T> factory)
+    public <T extends Consumer<TableMetadata>> T ensureFlushListener(Object key, Supplier<T> factory)
     {
-        if (onFlush == null)
-            return null;
-
-        T listener = (T)onFlush.get(key);
-        if (null == listener)
-        {
-            listener = factory.get();
-            onFlush = ImmutableMap.<Object, Consumer<TableMetadata>>builder()
-                                  .putAll(onFlush)
-                                  .put(key, listener)
-                                  .build();
-        }
-        return listener;
+        return onFlush.ensureFlushListener(key, factory);
     }
 
     public void notifyFlushed()
     {
-        Collection<Consumer<TableMetadata>> run;
-        synchronized (this)
-        {
-            run = onFlush.values();
-            onFlush = null;
-        }
-        run.forEach(c -> c.accept(metadata()));
+        onFlush.notifyFlushed(metadata());
     }
 
     protected static class ColumnsCollector
diff --git a/src/java/org/apache/cassandra/db/memtable/AbstractMemtableWithCommitlog.java b/src/java/org/apache/cassandra/db/memtable/AbstractMemtableWithCommitlog.java
index 4fe39a10ca..e5d1b2112f 100644
--- a/src/java/org/apache/cassandra/db/memtable/AbstractMemtableWithCommitlog.java
+++ b/src/java/org/apache/cassandra/db/memtable/AbstractMemtableWithCommitlog.java
@@ -20,7 +20,7 @@ package org.apache.cassandra.db.memtable;
 
 import java.util.concurrent.atomic.AtomicReference;
 
-import org.apache.cassandra.db.commitlog.CommitLog;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.schema.TableMetadataRef;
 import org.apache.cassandra.utils.concurrent.OpOrder;
@@ -31,33 +31,50 @@ import org.apache.cassandra.utils.concurrent.OpOrder;
  */
 public abstract class AbstractMemtableWithCommitlog extends AbstractMemtable
 {
-    // The approximate lower bound by this memtable; must be <= commitLogLowerBound once our predecessor
-    // has been finalised, and this is enforced in the ColumnFamilyStore.setCommitLogUpperBound
-    private final CommitLogPosition approximateCommitLogLowerBound = CommitLog.instance.getCurrentPosition();
     // the precise lower bound of CommitLogPosition owned by this memtable; equal to its predecessor's commitLogUpperBound
     private final AtomicReference<CommitLogPosition> commitLogLowerBound;
     // the write barrier for directing writes to this memtable or the next during a switch
     private volatile OpOrder.Barrier writeBarrier;
     // the precise upper bound of CommitLogPosition owned by this memtable
     private volatile AtomicReference<CommitLogPosition> commitLogUpperBound;
+    // which log every position above is drawn from; positions from the other log do not compare against them
+    private final LogDomain domain;
 
-    public AbstractMemtableWithCommitlog(TableMetadataRef metadataRef, AtomicReference<CommitLogPosition> commitLogLowerBound)
+    public AbstractMemtableWithCommitlog(TableMetadataRef metadataRef,
+                                        AtomicReference<CommitLogPosition> commitLogLowerBound,
+                                        LogDomain domain)
     {
         super(metadataRef);
         this.commitLogLowerBound = commitLogLowerBound;
+        this.domain = domain;
     }
 
-    public CommitLogPosition getApproximateCommitLogLowerBound()
+    public LogDomain domain()
     {
-        return approximateCommitLogLowerBound;
+        return domain;
     }
 
-    public void switchOut(OpOrder.Barrier writeBarrier, AtomicReference<CommitLogPosition> commitLogUpperBound)
+    @Override
+    public boolean holds(LogDomain writeDomain)
+    {
+        return writeDomain == domain;
+    }
+
+    /**
+     * Refuse a write whose position is in the other log.
+     */
+    protected void requireDomain(LogDomain writeDomain)
+    {
+        if (writeDomain != domain)
+            throw new IllegalArgumentException("Cannot put a " + writeDomain + " write into a " + domain + " memtable");
+    }
+
+    public void switchOut(OpOrder.Barrier writeBarrier, LogDomainBounds upperBounds)
     {
         // This can prepare the memtable data for deletion; it will still be used while the flush is proceeding.
         // A setDiscarded call will follow.
         assert this.writeBarrier == null;
-        this.commitLogUpperBound = commitLogUpperBound;
+        this.commitLogUpperBound = upperBounds.forDomain(domain);
         this.writeBarrier = writeBarrier;
     }
 
@@ -68,8 +85,12 @@ public abstract class AbstractMemtableWithCommitlog extends AbstractMemtable
 
     // decide if this memtable should take the write, or if it should go to the next memtable
     @Override
-    public boolean accepts(OpOrder.Group opGroup, CommitLogPosition commitLogPosition)
+    public boolean accepts(OpOrder.Group opGroup, CommitLogPosition commitLogPosition, LogDomain domain)
     {
+        // we don't accept writes against other backing log domains
+        if (domain != this.domain)
+            return false;
+
         // if the barrier hasn't been set yet, then this memtable is still the newest and is taking ALL writes.
         OpOrder.Barrier barrier = this.writeBarrier;
         if (barrier == null)
@@ -122,6 +143,7 @@ public abstract class AbstractMemtableWithCommitlog extends AbstractMemtable
 
     public boolean mayContainDataBefore(CommitLogPosition position)
     {
-        return approximateCommitLogLowerBound.compareTo(position) < 0;
+        CommitLogPosition lower = commitLogLowerBound.get();
+        return lower == null || lower.compareTo(position) < 0;
     }
 }
diff --git a/src/java/org/apache/cassandra/db/memtable/AbstractShardedMemtable.java b/src/java/org/apache/cassandra/db/memtable/AbstractShardedMemtable.java
index fef13fa667..f72d9e6945 100644
--- a/src/java/org/apache/cassandra/db/memtable/AbstractShardedMemtable.java
+++ b/src/java/org/apache/cassandra/db/memtable/AbstractShardedMemtable.java
@@ -24,6 +24,7 @@ import org.github.jamm.Unmetered;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.schema.TableMetadataRef;
 import org.apache.cassandra.utils.FBUtilities;
@@ -55,9 +56,10 @@ public abstract class AbstractShardedMemtable extends AbstractAllocatorMemtable
     AbstractShardedMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound,
                             TableMetadataRef metadataRef,
                             Owner owner,
+                            LogDomain domain,
                             Integer shardCountOption)
     {
-        super(commitLogLowerBound, metadataRef, owner);
+        super(commitLogLowerBound, metadataRef, owner, domain);
         int shardCount = shardCountOption != null ? shardCountOption : defaultShardCount;
         this.boundaries = owner.localRangeSplits(shardCount);
     }
diff --git a/src/java/org/apache/cassandra/db/memtable/DomainMemtable.java b/src/java/org/apache/cassandra/db/memtable/DomainMemtable.java
new file mode 100644
index 0000000000..e2196058d9
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/memtable/DomainMemtable.java
@@ -0,0 +1,147 @@
+/*
+ * 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.db.memtable;
+
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.cassandra.db.LogDomain;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
+import org.apache.cassandra.schema.TableMetadataRef;
+
+/**
+ * A memtable holding one {@link LogDomain}'s writes. These are the units a flush turns into sstables, so state that a
+ * consumer keys per flushed unit belongs against one of these.
+ */
+public interface DomainMemtable extends Memtable
+{
+
+    /**
+     * Get the collection of data between the given partition boundaries in a form suitable for flushing.
+     */
+    FlushablePartitionSet<?> getFlushSet(PartitionPosition from, PartitionPosition to);
+    /** The commit log position at the time that this memtable was created */
+    CommitLogPosition getCommitLogLowerBound();
+
+    /** The commit log position at the time that this memtable was switched out */
+    LastCommitLogPosition getFinalCommitLogUpperBound();
+
+    /**
+     * True if the memtable can contain any data that was written before the given position in this memtable's log domain.
+     * Callers must only pass a position from this memtable's backing log domain (e.g. obtained via {@link Memtable#flushSourceFor}).
+     */
+    boolean mayContainDataBefore(CommitLogPosition position);
+    // The following two methods provide a way of tracking ongoing flushes
+    ILifecycleTransaction setFlushTransaction(ILifecycleTransaction transaction);
+    ILifecycleTransaction getFlushTransaction();
+
+        // Construction
+
+    /**
+     * Factory interface for constructing memtables, and querying write durability features.
+     *
+     * The factory is chosen using the MemtableParams class (passed as argument to
+     * {@code CREATE TABLE ... WITH memtable = '<configuration_name>'} where the configuration definition is a map given
+     * under {@code memtable_configurations} in cassandra.yaml). To make that possible, implementations must provide
+     * either a static {@code FACTORY} field (if they accept no further option) or a static
+     * {@code factory(Map<String, String>)} method. In the latter case, the method should avoid creating
+     * multiple instances of the factory for the same parameters, or factories should at least implement hashCode and
+     * equals.
+     */
+    interface Factory
+    {
+        /**
+         * Create a memtable.
+         *
+         * @param commitLogLowerBound This memtable's lower bound in the log named by {@code domain}. It is the previous
+         *                            generation's upper bound in that log, and defines the span of positions any
+         *                            flushed sstable will cover.
+         * @param metadaRef Pointer to the up-to-date table metadata.
+         * @param owner Owning objects that will receive flush requests triggered by the memtable (e.g. on expiration).
+         * @param domain Which backing log this memtable's bounds reference.
+         */
+        DomainMemtable create(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadaRef, Owner owner, LogDomain domain);
+
+        /**
+         * Create a release action for the memtable's metrics. This is used to release any resources that are not needed.
+         * @param metadataRef Pointer to the up-to-date table metadata.
+         * @return Runnable that releases the metrics resources.
+         */
+        default Runnable createMemtableMetricsReleaser(TableMetadataRef metadataRef)
+        {
+            return () -> {};
+        }
+
+        /**
+         * If the memtable can achieve write durability directly (i.e. using some feature other than the commitlog, e.g.
+         * persistent memory), it can return true here, in which case the commit log will not store mutations in this
+         * table.
+         * Note that doing so will prevent point-in-time restores and changed data capture, thus a durable memtable must
+         * allow the option of turning commit log writing on even if it does not need it.
+         */
+        default boolean writesShouldSkipCommitLog()
+        {
+            return false;
+        }
+
+        /**
+         * This should be true if the memtable can achieve write durability for crash recovery directly (i.e. using some
+         * feature other than the commitlog, e.g. persistent memory).
+         * Setting this flag to true means that the commitlog should not replay mutations for this table on restart,
+         * and that it should not try to preserve segments that contain relevant data.
+         * Unless writesShouldSkipCommitLog() is also true, writes will be recorded in the commit log as they may be
+         * needed for changed data capture or point-in-time restore.
+         */
+        default boolean writesAreDurable()
+        {
+            return false;
+        }
+
+        /**
+         * Normally we can receive streamed sstables directly, skipping the memtable stage (zero-copy-streaming). When
+         * the memtable is the primary data store (e.g. persistent memtables), it will usually prefer to receive the
+         * data instead.
+         *
+         * If this returns true, all streamed sstables's content will be read and replayed as mutations, disabling
+         * zero-copy streaming.
+         */
+        default boolean streamToMemtable()
+        {
+            return false;
+        }
+
+        /**
+         * When we need to stream data, we usually flush and stream the resulting sstables. This will not work correctly
+         * if the memtable does not want to flush for streaming (e.g. persistent memtables acting as primary data
+         * store), because data (not just recent) will be missing from the streamed view. Such memtables must present
+         * their data separately for streaming.
+         * In other words if the memtable returns false on shouldSwitch(STREAMING/REPAIR), its factory must return true
+         * here.
+         *
+         * If this flag returns true, streaming will write the relevant content that resides in the memtable to
+         * temporary sstables, stream these sstables and then delete them.
+         */
+        default boolean streamFromMemtable()
+        {
+            return false;
+        }
+    }
+
+}
diff --git a/src/java/org/apache/cassandra/db/memtable/FlushListeners.java b/src/java/org/apache/cassandra/db/memtable/FlushListeners.java
new file mode 100644
index 0000000000..435aa129a1
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/memtable/FlushListeners.java
@@ -0,0 +1,65 @@
+/*
+ * 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.db.memtable;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+import com.google.common.collect.ImmutableMap;
+
+import org.apache.cassandra.schema.TableMetadata;
+
+/**
+ * The callbacks to run once a memtable generation is flushed to disk
+ */
+class FlushListeners
+{
+    private Map<Object, Consumer<TableMetadata>> onFlush = ImmutableMap.of();
+
+    @SuppressWarnings("unchecked")
+    synchronized <T extends Consumer<TableMetadata>> T ensureFlushListener(Object key, Supplier<T> factory)
+    {
+        if (onFlush == null)
+            return null;
+
+        T listener = (T) onFlush.get(key);
+        if (null == listener)
+        {
+            listener = factory.get();
+            onFlush = ImmutableMap.<Object, Consumer<TableMetadata>>builder()
+                                  .putAll(onFlush)
+                                  .put(key, listener)
+                                  .build();
+        }
+        return listener;
+    }
+
+    void notifyFlushed(TableMetadata metadata)
+    {
+        Collection<Consumer<TableMetadata>> run;
+        synchronized (this)
+        {
+            run = onFlush.values();
+            onFlush = null;
+        }
+        run.forEach(c -> c.accept(metadata));
+    }
+}
diff --git a/src/java/org/apache/cassandra/db/memtable/Flushing.java b/src/java/org/apache/cassandra/db/memtable/Flushing.java
index c53be17a21..71daade7f0 100644
--- a/src/java/org/apache/cassandra/db/memtable/Flushing.java
+++ b/src/java/org/apache/cassandra/db/memtable/Flushing.java
@@ -19,8 +19,10 @@
 package org.apache.cassandra.db.memtable;
 
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
+import java.util.Set;
 import java.util.concurrent.Callable;
 import java.util.concurrent.TimeUnit;
 
@@ -34,21 +36,25 @@ import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.db.ColumnFamilyStore;
 import org.apache.cassandra.db.Directories;
 import org.apache.cassandra.db.DiskBoundaries;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.PartitionPosition;
 import org.apache.cassandra.db.SerializationHeader;
 import org.apache.cassandra.db.SystemKeyspace;
-import org.apache.cassandra.db.commitlog.IntervalSet;
-import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.db.compaction.OperationType;
+import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
 import org.apache.cassandra.db.partitions.Partition;
 import org.apache.cassandra.db.rows.UnfilteredRowIterator;
 import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.SSTable;
 import org.apache.cassandra.io.sstable.SSTableMultiWriter;
 import org.apache.cassandra.io.sstable.format.SSTableFormat;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.metrics.TableMetrics;
 import org.apache.cassandra.service.ActiveRepairService;
 import org.apache.cassandra.utils.Clock;
 import org.apache.cassandra.utils.FBUtilities;
 import org.apache.cassandra.utils.ThreadStats;
+import org.apache.cassandra.utils.TimeUUID;
 
 public class Flushing
 {
@@ -59,10 +65,11 @@ public class Flushing
     }
 
     public static List<FlushRunnable> flushRunnables(ColumnFamilyStore cfs,
-                                                     Memtable memtable,
-                                                     LifecycleTransaction txn)
+                                                     DomainMemtable memtable,
+                                                     ILifecycleTransaction generationTxn)
     {
-        LifecycleTransaction ongoingFlushTransaction = memtable.setFlushTransaction(txn);
+        ILifecycleTransaction txn = new SourceTransaction(generationTxn, memtable);
+        ILifecycleTransaction ongoingFlushTransaction = memtable.setFlushTransaction(txn);
         Preconditions.checkState(ongoingFlushTransaction == null,
                                  "Attempted to flush Memtable more than once on %s.%s",
                                  cfs.keyspace.getName(),
@@ -100,10 +107,10 @@ public class Flushing
     }
 
     static FlushRunnable flushRunnable(ColumnFamilyStore cfs,
-                                       Memtable memtable,
+                                       DomainMemtable memtable,
                                        PartitionPosition from,
                                        PartitionPosition to,
-                                       LifecycleTransaction txn,
+                                       ILifecycleTransaction txn,
                                        Directories.DataDirectory flushLocation)
     {
         Memtable.FlushablePartitionSet<?> flushSet = memtable.getFlushSet(from, to);
@@ -123,6 +130,150 @@ public class Flushing
         return new FlushRunnable(flushSet, writer, cfs.metric, true);
     }
 
+    /**
+     * One flush source's view of the flush transaction. A flush operation flushes every domain memtable under a single
+     * transaction so that its sstables become visible together, which leaves the transaction unable to say which
+     * source an output came from. Each source is given its own view instead, so anything holding per-memtable state
+     * can recognize its own outputs.
+     *
+     * Tracking is forwarded, since every output still belongs to the one transaction. Committing, aborting and
+     * obsoletion are the generation's to drive and throw here rather than acting on a part of the flush.
+     */
+    private static class SourceTransaction implements ILifecycleTransaction
+    {
+        private final ILifecycleTransaction generationTxn;
+        private final TimeUUID id;
+
+        SourceTransaction(ILifecycleTransaction generationTxn, Memtable source)
+        {
+            this.generationTxn = generationTxn;
+            // Sequence 0 is the generation's own id, so number the domains from 1.
+            this.id = generationTxn.opId() == null
+                      ? null
+                      : generationTxn.opId().withSequence(source.holds(LogDomain.MUTATION_JOURNAL) ? 2 : 1);
+        }
+
+        @Override
+        public void trackNew(SSTable table)
+        {
+            generationTxn.trackNew(table);
+        }
+
+        @Override
+        public void untrackNew(SSTable table)
+        {
+            generationTxn.untrackNew(table);
+        }
+
+        @Override
+        public OperationType opType()
+        {
+            return generationTxn.opType();
+        }
+
+        @Override
+        public boolean isOffline()
+        {
+            return generationTxn.isOffline();
+        }
+
+        @Override
+        public TimeUUID opId()
+        {
+            return id;
+        }
+
+        @Override
+        public void checkpoint()
+        {
+            throw unsupported("checkpoint");
+        }
+
+        @Override
+        public void update(SSTableReader reader, boolean original)
+        {
+            throw unsupported("update");
+        }
+
+        @Override
+        public void update(Collection<SSTableReader> readers, boolean original)
+        {
+            throw unsupported("update");
+        }
+
+        @Override
+        public SSTableReader current(SSTableReader reader)
+        {
+            throw unsupported("current");
+        }
+
+        @Override
+        public void obsolete(SSTableReader reader)
+        {
+            throw unsupported("obsolete");
+        }
+
+        @Override
+        public void obsoleteOriginals()
+        {
+            throw unsupported("obsoleteOriginals");
+        }
+
+        @Override
+        public Set<SSTableReader> originals()
+        {
+            // A flush has no input sstables.
+            return Collections.emptySet();
+        }
+
+        @Override
+        public boolean isObsolete(SSTableReader reader)
+        {
+            return false;
+        }
+
+        @Override
+        public void cancel(SSTableReader removedSSTable)
+        {
+            throw unsupported("cancel");
+        }
+
+        @Override
+        public Throwable commit(Throwable accumulate)
+        {
+            throw unsupported("commit");
+        }
+
+        @Override
+        public Throwable abort(Throwable accumulate)
+        {
+            throw unsupported("abort");
+        }
+
+        @Override
+        public void prepareToCommit()
+        {
+            throw unsupported("prepareToCommit");
+        }
+
+        @Override
+        public void close()
+        {
+            throw unsupported("close");
+        }
+
+        private UnsupportedOperationException unsupported(String operation)
+        {
+            return new UnsupportedOperationException(operation + " called on SourceTransaction");
+        }
+
+        @Override
+        public String toString()
+        {
+            return "SourceTransaction(" + generationTxn + ')';
+        }
+    }
+
     public static Throwable abortRunnables(List<FlushRunnable> runnables, Throwable t)
     {
         if (runnables != null)
@@ -232,7 +383,7 @@ public class Flushing
 
     public static SSTableMultiWriter createFlushWriter(ColumnFamilyStore cfs,
                                                        Memtable.FlushablePartitionSet<?> flushSet,
-                                                       LifecycleTransaction txn,
+                                                       ILifecycleTransaction txn,
                                                        Descriptor descriptor,
                                                        long partitionCount)
     {
@@ -244,8 +395,7 @@ public class Flushing
                                             ActiveRepairService.UNREPAIRED_SSTABLE,
                                             ActiveRepairService.NO_PENDING_REPAIR,
                                             flushSet.coordinatorLogOffsets(),
-                                            new IntervalSet<>(flushSet.commitLogLowerBound(),
-                                                              flushSet.commitLogUpperBound()),
+                                            flushSet.commitLogIntervals(),
                                             new SerializationHeader(true,
                                                                     flushSet.metadata(),
                                                                     flushSet.columns(),
diff --git a/src/java/org/apache/cassandra/db/memtable/LogDomainBounds.java b/src/java/org/apache/cassandra/db/memtable/LogDomainBounds.java
new file mode 100644
index 0000000000..6355ac0195
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/memtable/LogDomainBounds.java
@@ -0,0 +1,138 @@
+/*
+ * 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.db.memtable;
+
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import com.google.common.annotations.VisibleForTesting;
+
+import org.apache.cassandra.db.LogDomain;
+import org.apache.cassandra.db.commitlog.CommitLog;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+import org.apache.cassandra.replication.MutationJournal;
+
+/**
+ * One commit log position per {@link LogDomain}, at the boundary between two memtable generations.
+ *
+ * The same instance is the upper bound of the generation being switched out and the lower bound of its replacement, so
+ * the two generations' spans in each log meet without a gap and without overlapping.
+ */
+public class LogDomainBounds
+{
+    private static final Function<LogDomain, CommitLogPosition> LIVE_LOGS =
+        domain -> domain.isJournal() ? MutationJournal.currentPositionOrNull()
+                                     : CommitLog.instance.getCurrentPosition();
+
+    private final AtomicReference<CommitLogPosition> commitLog;
+    private final AtomicReference<CommitLogPosition> journal;
+
+    private LogDomainBounds(CommitLogPosition commitLog, CommitLogPosition journal)
+    {
+        this.commitLog = new AtomicReference<>(commitLog);
+        this.journal = new AtomicReference<>(journal);
+    }
+
+    public static LogDomainBounds unset()
+    {
+        return new LogDomainBounds(null, null);
+    }
+
+    public static LogDomainBounds atCurrentPositions()
+    {
+        return new LogDomainBounds(CommitLog.instance.getCurrentPosition(), MutationJournal.currentPositionOrNull());
+    }
+
+    public static LogDomainBounds of(CommitLogPosition position)
+    {
+        return new LogDomainBounds(position, position);
+    }
+
+    public AtomicReference<CommitLogPosition> forDomain(LogDomain domain)
+    {
+        return domain.isJournal() ? journal : commitLog;
+    }
+
+    public CommitLogPosition get(LogDomain domain)
+    {
+        return forDomain(domain).get();
+    }
+
+    public boolean isSealed(LogDomain domain)
+    {
+        return get(domain) instanceof Memtable.LastCommitLogPosition;
+    }
+
+    /**
+     * Fix each bound at the end of the log it names, so that no write can take a position at or below it afterwards.
+     */
+    public void seal()
+    {
+        seal(LIVE_LOGS);
+    }
+
+    public AtomicReference<CommitLogPosition> sealIfUnset(LogDomain domain)
+    {
+        return sealIfUnset(domain, LIVE_LOGS);
+    }
+
+    @VisibleForTesting
+    void seal(Function<LogDomain, CommitLogPosition> logs)
+    {
+        seal(commitLog, LogDomain.COMMIT_LOG, logs);
+        seal(journal, LogDomain.MUTATION_JOURNAL, logs);
+    }
+
+    @VisibleForTesting
+    AtomicReference<CommitLogPosition> sealIfUnset(LogDomain domain, Function<LogDomain, CommitLogPosition> logs)
+    {
+        AtomicReference<CommitLogPosition> bound = forDomain(domain);
+        if (bound.get() == null)
+            seal(bound, domain, logs);
+        return bound;
+    }
+
+    private static void seal(AtomicReference<CommitLogPosition> bound,
+                             LogDomain domain,
+                             Function<LogDomain, CommitLogPosition> logs)
+    {
+        if (bound.get() instanceof Memtable.LastCommitLogPosition)
+            return;
+
+        while (true)
+        {
+            // Re-read on every attempt. A write admitted since the last read raises the bound above the position we
+            // hold, and retrying with that stale position could never satisfy the guard below.
+            CommitLogPosition position = logs.apply(domain);
+            if (position == null)
+                return;
+
+            Memtable.LastCommitLogPosition sealed = new Memtable.LastCommitLogPosition(position);
+            CommitLogPosition current = bound.get();
+            if ((current == null || current.compareTo(sealed) <= 0) && bound.compareAndSet(current, sealed))
+                return;
+        }
+    }
+
+    @Override
+    public String toString()
+    {
+        return "LogDomainBounds(commitLog=" + commitLog.get() + ", journal=" + journal.get() + ')';
+    }
+}
diff --git a/src/java/org/apache/cassandra/db/memtable/LogDomainPositions.java b/src/java/org/apache/cassandra/db/memtable/LogDomainPositions.java
new file mode 100644
index 0000000000..72e88e3dd2
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/memtable/LogDomainPositions.java
@@ -0,0 +1,84 @@
+/*
+ * 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.db.memtable;
+
+import java.util.Objects;
+
+import org.apache.cassandra.db.LogDomain;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+
+/**
+ * An immutable snapshot of {@link CommitLogPosition}s for each {@link LogDomain}.
+ */
+public class LogDomainPositions
+{
+    public static final LogDomainPositions NONE = new LogDomainPositions(CommitLogPosition.NONE, CommitLogPosition.NONE);
+
+    public final CommitLogPosition commitLog;
+    public final CommitLogPosition journal;
+
+    public LogDomainPositions(CommitLogPosition commitLog, CommitLogPosition journal)
+    {
+        this.commitLog = commitLog != null ? commitLog : CommitLogPosition.NONE;
+        this.journal = journal != null ? journal : CommitLogPosition.NONE;
+    }
+
+    public static LogDomainPositions of(CommitLogPosition commitLog, CommitLogPosition journal)
+    {
+        return new LogDomainPositions(commitLog, journal);
+    }
+
+    public static LogDomainPositions of(CommitLogPosition position)
+    {
+        return new LogDomainPositions(position, position);
+    }
+
+    public static LogDomainPositions of(LogDomainBounds bounds)
+    {
+        if (bounds == null)
+            return NONE;
+        return new LogDomainPositions(bounds.get(LogDomain.COMMIT_LOG), bounds.get(LogDomain.MUTATION_JOURNAL));
+    }
+
+    public CommitLogPosition forDomain(LogDomain domain)
+    {
+        return domain.isJournal() ? journal : commitLog;
+    }
+
+    @Override
+    public boolean equals(Object o)
+    {
+        if (this == o) return true;
+        if (!(o instanceof LogDomainPositions)) return false;
+        LogDomainPositions that = (LogDomainPositions) o;
+        return Objects.equals(commitLog, that.commitLog) && Objects.equals(journal, that.journal);
+    }
+
+    @Override
+    public int hashCode()
+    {
+        return Objects.hash(commitLog, journal);
+    }
+
+    @Override
+    public String toString()
+    {
+        return "LogDomainPositions(commitLog=" + commitLog + ", journal=" + journal + ')';
+    }
+}
diff --git a/src/java/org/apache/cassandra/db/memtable/Memtable.java b/src/java/org/apache/cassandra/db/memtable/Memtable.java
index bfa17535f8..703414b12e 100644
--- a/src/java/org/apache/cassandra/db/memtable/Memtable.java
+++ b/src/java/org/apache/cassandra/db/memtable/Memtable.java
@@ -18,7 +18,7 @@
 
 package org.apache.cassandra.db.memtable;
 
-import java.util.concurrent.atomic.AtomicReference;
+import java.util.List;
 import java.util.function.Consumer;
 import java.util.function.Supplier;
 
@@ -27,10 +27,11 @@ import javax.annotation.concurrent.NotThreadSafe;
 import org.apache.cassandra.db.CellSourceIdentifier;
 import org.apache.cassandra.db.ColumnFamilyStore;
 import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.PartitionPosition;
 import org.apache.cassandra.db.RegularAndStaticColumns;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
-import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.db.commitlog.IntervalSet;
 import org.apache.cassandra.db.partitions.Partition;
 import org.apache.cassandra.db.partitions.PartitionUpdate;
 import org.apache.cassandra.db.rows.EncodingStats;
@@ -41,7 +42,6 @@ import org.apache.cassandra.io.sstable.format.SSTableWriter;
 import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
 import org.apache.cassandra.replication.MutationId;
 import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.schema.TableMetadataRef;
 import org.apache.cassandra.utils.FBUtilities;
 import org.apache.cassandra.utils.concurrent.Future;
 import org.apache.cassandra.utils.concurrent.OpOrder;
@@ -64,97 +64,6 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
 {
     public static final long NO_MIN_TIMESTAMP = -1;
 
-    // Construction
-
-    /**
-     * Factory interface for constructing memtables, and querying write durability features.
-     *
-     * The factory is chosen using the MemtableParams class (passed as argument to
-     * {@code CREATE TABLE ... WITH memtable = '<configuration_name>'} where the configuration definition is a map given
-     * under {@code memtable_configurations} in cassandra.yaml). To make that possible, implementations must provide
-     * either a static {@code FACTORY} field (if they accept no further option) or a static
-     * {@code factory(Map<String, String>)} method. In the latter case, the method should avoid creating
-     * multiple instances of the factory for the same parameters, or factories should at least implement hashCode and
-     * equals.
-     */
-    interface Factory
-    {
-        /**
-         * Create a memtable.
-         *
-         * @param commitLogLowerBound A commit log lower bound for the new memtable. This will be equal to the previous
-         *                            memtable's upper bound and defines the span of positions that any flushed sstable
-         *                            will cover.
-         * @param metadaRef Pointer to the up-to-date table metadata.
-         * @param owner Owning objects that will receive flush requests triggered by the memtable (e.g. on expiration).
-         */
-        Memtable create(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadaRef, Owner owner);
-
-        /**
-         * Create a release action for the memtable's metrics. This is used to release any resources that are not needed.
-         * @param metadataRef Pointer to the up-to-date table metadata.
-         * @return Runnable that releases the metrics resources.
-         */
-        default Runnable createMemtableMetricsReleaser(TableMetadataRef metadataRef)
-        {
-            return () -> {};
-        }
-
-        /**
-         * If the memtable can achieve write durability directly (i.e. using some feature other than the commitlog, e.g.
-         * persistent memory), it can return true here, in which case the commit log will not store mutations in this
-         * table.
-         * Note that doing so will prevent point-in-time restores and changed data capture, thus a durable memtable must
-         * allow the option of turning commit log writing on even if it does not need it.
-         */
-        default boolean writesShouldSkipCommitLog()
-        {
-            return false;
-        }
-
-        /**
-         * This should be true if the memtable can achieve write durability for crash recovery directly (i.e. using some
-         * feature other than the commitlog, e.g. persistent memory).
-         * Setting this flag to true means that the commitlog should not replay mutations for this table on restart,
-         * and that it should not try to preserve segments that contain relevant data.
-         * Unless writesShouldSkipCommitLog() is also true, writes will be recorded in the commit log as they may be
-         * needed for changed data capture or point-in-time restore.
-         */
-        default boolean writesAreDurable()
-        {
-            return false;
-        }
-
-        /**
-         * Normally we can receive streamed sstables directly, skipping the memtable stage (zero-copy-streaming). When
-         * the memtable is the primary data store (e.g. persistent memtables), it will usually prefer to receive the
-         * data instead.
-         *
-         * If this returns true, all streamed sstables's content will be read and replayed as mutations, disabling
-         * zero-copy streaming.
-         */
-        default boolean streamToMemtable()
-        {
-            return false;
-        }
-
-        /**
-         * When we need to stream data, we usually flush and stream the resulting sstables. This will not work correctly
-         * if the memtable does not want to flush for streaming (e.g. persistent memtables acting as primary data
-         * store), because data (not just recent) will be missing from the streamed view. Such memtables must present
-         * their data separately for streaming.
-         * In other words if the memtable returns false on shouldSwitch(STREAMING/REPAIR), its factory must return true
-         * here.
-         *
-         * If this flag returns true, streaming will write the relevant content that resides in the memtable to
-         * temporary sstables, stream these sstables and then delete them.
-         */
-        default boolean streamFromMemtable()
-        {
-            return false;
-        }
-    }
-
     /**
      * Interface for providing signals back and requesting information from the owner, i.e. the object that controls the
      * memtable. This is usually the ColumnFamilyStore; the interface is used to limit the dependency of memtables on
@@ -163,7 +72,7 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
     interface Owner
     {
         /** Signal to the owner that a flush is required (e.g. in response to hitting space limits) */
-        Future<CommitLogPosition> signalFlushRequired(Memtable memtable, ColumnFamilyStore.FlushReason reason);
+        Future<LogDomainPositions> signalFlushRequired(Memtable memtable, ColumnFamilyStore.FlushReason reason);
 
         /** Get the current memtable for this owner. Used to avoid capturing memtable in scheduled flush tasks. */
         Memtable getCurrentMemtable();
@@ -186,9 +95,9 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
 
     // Main write and read operations
 
-    default long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup)
+    default long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, LogDomain domain)
     {
-        return put(mutationId, update, indexer, opGroup, false);
+        return put(mutationId, update, indexer, opGroup, domain, false);
     }
 
     /**
@@ -198,6 +107,8 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
      * @param indexer receives information about the update's effect
      * @param opGroup write operation group, used to permit the operation to complete if it is needed to complete a
      *                flush to free space.
+     * @param domain which backing log the write's position reference. Attempting to write to the incorrect domain
+     *               throws an exception.
      * @param assumeMissing if true, the implementation MAY clone the key and attempt putIfAbsent without first
      *                      looking for the keys' presence
      *
@@ -205,7 +116,7 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
      * timestamp delta being computed as the difference between the cells and DeletionTimes from any existing partition
      * and those in {@code update}. See CASSANDRA-7979.
      */
-    long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, boolean assumeMissing);
+    long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, LogDomain domain, boolean assumeMissing);
 
     /**
      * Creates a point-in-time snapshot of a partition in this memtable.
@@ -318,11 +229,6 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
 
     // Flushing
 
-    /**
-     * Get the collection of data between the given partition boundaries in a form suitable for flushing.
-     */
-    FlushablePartitionSet<?> getFlushSet(PartitionPosition from, PartitionPosition to);
-
     /**
      * A collection of partitions for flushing plus some information required for writing an sstable.
      *
@@ -332,7 +238,7 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
      */
     interface FlushablePartitionSet<P extends Partition> extends Iterable<P>, SSTableWriter.SSTableSizeParameters
     {
-        Memtable memtable();
+        DomainMemtable memtable();
 
         PartitionPosition from();
         PartitionPosition to();
@@ -342,6 +248,19 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
         /** The commit log position at the time that this memtable was switched out */
         CommitLogPosition commitLogUpperBound();
 
+        /**
+         * The *commit log* span the flushed sstable covers, recorded in its {@code StatsMetadata}.
+         *
+         * Empty for a journal-domain memtable. Journal bounds have one consumer, {@code MutationJournal.notifyFlushed},
+         * and a journal position stored here would be read back as a commit log position;
+         */
+        default IntervalSet<CommitLogPosition> commitLogIntervals()
+        {
+            return memtable().holds(LogDomain.COMMIT_LOG)
+                   ? new IntervalSet<>(commitLogLowerBound(), commitLogUpperBound())
+                   : IntervalSet.empty();
+        }
+
         /** The set of all columns that have been written */
         RegularAndStaticColumns columns();
         /** Statistics required for writing an sstable efficiently */
@@ -372,10 +291,23 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
      * @param writeBarrier The barrier that will signal that all writes to this memtable have completed. That is, the
      *                     point after which writes cannot be accepted by this memtable (it is permitted for writes
      *                     before this barrier to go into the next; see {@link #accepts}).
-     * @param commitLogUpperBound The upper commit log position for this memtable. The value may be modified after this
-     *                            call and will match the next memtable's lower commit log bound.
+     * @param upperBounds The generation boundary this memtable ends at. The position for the memtable's own domain is
+     *                    its upper bound; it may be modified after this call, and is the next generation's lower bound
+     *                    in that log.
      */
-    void switchOut(OpOrder.Barrier writeBarrier, AtomicReference<CommitLogPosition> commitLogUpperBound);
+    void switchOut(OpOrder.Barrier writeBarrier, LogDomainBounds upperBounds);
+
+    /**
+     * The memtables whose contents are written out when this generation flushes. This is where split domain memtables
+     * become 2 memtables for flushing to different memtables
+     */
+    List<DomainMemtable> flushSources();
+
+    /**
+     * The domain memtable a write for {@code domain} is held by, which is the memtable itself unless this generation is
+     * split.
+     */
+    DomainMemtable flushSourceFor(LogDomain domain);
 
     /**
      * This memtable is no longer in use or required for outstanding flushes or operations.
@@ -385,36 +317,40 @@ public interface Memtable extends Comparable<Memtable>, UnfilteredSource, CellSo
 
     /**
      * Decide if this memtable should take a write with the given parameters, or if the write should go to the next
-     * memtable. This enforces that no writes after the barrier set by {@link #switchOut} can be accepted, and
-     * is also used to define a shared commit log bound as the upper for this memtable and lower for the next.
+     * memtable (or split the memtable across domains if the domain doesn't match and this is the current memtable).
+     * This enforces that no writes after the barrier set by {@link #switchOut} can be accepted, and is also used to
+     * define a shared commit log bound as the upper for this memtable and lower for the next.
      */
-    boolean accepts(OpOrder.Group opGroup, CommitLogPosition commitLogPosition);
+    boolean accepts(OpOrder.Group opGroup, CommitLogPosition commitLogPosition, LogDomain domain);
 
     long getMemtableId();
 
-    /** Approximate commit log lower bound, <= getCommitLogLowerBound, used as a time stamp for ordering */
-    CommitLogPosition getApproximateCommitLogLowerBound();
+    /**
+     * Whether this memtable can accept writes from the given log domain
+     */
+    boolean holds(LogDomain domain);
 
-    /** The commit log position at the time that this memtable was created */
-    CommitLogPosition getCommitLogLowerBound();
+    Owner owner();
 
-    /** The commit log position at the time that this memtable was switched out */
-    LastCommitLogPosition getFinalCommitLogUpperBound();
+    default boolean allocatesFromMemtablePool()
+    {
+        return false;
+    }
 
-    /** True if the memtable can contain any data that was written before the given commit log position */
-    boolean mayContainDataBefore(CommitLogPosition position);
+    default void flushIfPeriodExpired()
+    {
+    }
 
     /** True if the memtable contains no data */
     boolean isClean();
 
-    // The following two methods provide a way of tracking ongoing flushes
-    LifecycleTransaction setFlushTransaction(LifecycleTransaction transaction);
-    LifecycleTransaction getFlushTransaction();
-
-    /** Order memtables by time as reflected in the commit log position at time of construction */
+    /**
+     * Order memtables by time as reflected in memtable id at time of construction.
+     * Note that split generations share the id of the generation they replace.
+     */
     default int compareTo(Memtable that)
     {
-        return this.getApproximateCommitLogLowerBound().compareTo(that.getApproximateCommitLogLowerBound());
+        return Long.compare(this.getMemtableId(), that.getMemtableId());
     }
 
     /**
diff --git a/src/java/org/apache/cassandra/db/memtable/ShardedSkipListMemtable.java b/src/java/org/apache/cassandra/db/memtable/ShardedSkipListMemtable.java
index daefbfbf07..4ee7d126bd 100644
--- a/src/java/org/apache/cassandra/db/memtable/ShardedSkipListMemtable.java
+++ b/src/java/org/apache/cassandra/db/memtable/ShardedSkipListMemtable.java
@@ -33,6 +33,7 @@ import org.slf4j.LoggerFactory;
 
 import org.apache.cassandra.db.DataRange;
 import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.PartitionPosition;
 import org.apache.cassandra.db.RegularAndStaticColumns;
 import org.apache.cassandra.db.Slices;
@@ -91,10 +92,11 @@ public class ShardedSkipListMemtable extends AbstractShardedMemtable
     ShardedSkipListMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound,
                             TableMetadataRef metadataRef,
                             Owner owner,
+                            LogDomain domain,
                             Integer shardCountOption,
                             boolean locking)
     {
-        super(commitLogLowerBound, metadataRef, owner, shardCountOption);
+        super(commitLogLowerBound, metadataRef, owner, domain, shardCountOption);
         this.shards = generatePartitionShards(boundaries.shardCount(), allocator, metadataRef, locking);
     }
 
@@ -143,8 +145,9 @@ public class ShardedSkipListMemtable extends AbstractShardedMemtable
      *
      * commitLogSegmentPosition should only be null if this is a secondary index, in which case it is *expected* to be null
      */
-    public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, boolean assumeMissing)
+    public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, LogDomain domain, boolean assumeMissing)
     {
+        requireDomain(domain);
         DecoratedKey key = update.partitionKey();
         MemtableShard shard = shards[boundaries.getShardForKey(key)];
         return shard.put(mutationId, key, update, indexer, opGroup, assumeMissing);
@@ -320,7 +323,7 @@ public class ShardedSkipListMemtable extends AbstractShardedMemtable
         {
             private final TableMetadata tableMetadata = currentTableMetadata;
 
-            public Memtable memtable()
+            public DomainMemtable memtable()
             {
                 return ShardedSkipListMemtable.this;
             }
@@ -531,9 +534,9 @@ public class ShardedSkipListMemtable extends AbstractShardedMemtable
 
     static class Locking extends ShardedSkipListMemtable
     {
-        Locking(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadataRef, Owner owner, Integer shardCountOption)
+        Locking(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadataRef, Owner owner, LogDomain domain, Integer shardCountOption)
         {
-            super(commitLogLowerBound, metadataRef, owner, shardCountOption, true);
+            super(commitLogLowerBound, metadataRef, owner, domain, shardCountOption, true);
         }
 
         /**
@@ -542,8 +545,9 @@ public class ShardedSkipListMemtable extends AbstractShardedMemtable
          *
          * commitLogSegmentPosition should only be null if this is a secondary index, in which case it is *expected* to be null
          */
-        public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, boolean assumeMissing)
+        public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, LogDomain domain, boolean assumeMissing)
         {
+            requireDomain(domain);
             DecoratedKey key = update.partitionKey();
             MemtableShard shard = shards[boundaries.getShardForKey(key)];
             synchronized (shard)
@@ -562,7 +566,7 @@ public class ShardedSkipListMemtable extends AbstractShardedMemtable
         return new Factory(shardCount, isLocking);
     }
 
-    static class Factory implements Memtable.Factory
+    static class Factory implements DomainMemtable.Factory
     {
         final Integer shardCount;
         final boolean isLocking;
@@ -573,13 +577,14 @@ public class ShardedSkipListMemtable extends AbstractShardedMemtable
             this.isLocking = isLocking;
         }
 
-        public Memtable create(AtomicReference<CommitLogPosition> commitLogLowerBound,
+        public DomainMemtable create(AtomicReference<CommitLogPosition> commitLogLowerBound,
                                TableMetadataRef metadataRef,
-                               Owner owner)
+                               Owner owner,
+                               LogDomain domain)
         {
             return isLocking
-                   ? new Locking(commitLogLowerBound, metadataRef, owner, shardCount)
-                   : new ShardedSkipListMemtable(commitLogLowerBound, metadataRef, owner, shardCount, false);
+                   ? new Locking(commitLogLowerBound, metadataRef, owner, domain, shardCount)
+                   : new ShardedSkipListMemtable(commitLogLowerBound, metadataRef, owner, domain, shardCount, false);
         }
 
         public boolean equals(Object o)
diff --git a/src/java/org/apache/cassandra/db/memtable/SkipListMemtable.java b/src/java/org/apache/cassandra/db/memtable/SkipListMemtable.java
index f68eecd3f6..d8fffc4074 100644
--- a/src/java/org/apache/cassandra/db/memtable/SkipListMemtable.java
+++ b/src/java/org/apache/cassandra/db/memtable/SkipListMemtable.java
@@ -34,6 +34,7 @@ import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.db.BufferDecoratedKey;
 import org.apache.cassandra.db.DataRange;
 import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.PartitionPosition;
 import org.apache.cassandra.db.Slices;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
@@ -93,9 +94,9 @@ public class SkipListMemtable extends AbstractAllocatorMemtable
 
     private final AtomicLong liveDataSize = new AtomicLong(0);
 
-    protected SkipListMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadataRef, Owner owner)
+    protected SkipListMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadataRef, Owner owner, LogDomain domain)
     {
-        super(commitLogLowerBound, metadataRef, owner);
+        super(commitLogLowerBound, metadataRef, owner, domain);
     }
 
     @Override
@@ -120,8 +121,9 @@ public class SkipListMemtable extends AbstractAllocatorMemtable
      * commitLogSegmentPosition should only be null if this is a secondary index, in which case it is *expected* to be null
      */
     @Override
-    public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, boolean assumeMissing)
+    public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, LogDomain domain, boolean assumeMissing)
     {
+        requireDomain(domain);
         long initialSize = 0;
         Cloner cloner = allocator.cloner(opGroup);
         AtomicBTreePartition previous = assumeMissing ? null : partitions.get(update.partitionKey());
@@ -310,7 +312,7 @@ public class SkipListMemtable extends AbstractAllocatorMemtable
             private final TableMetadata tableMetadata = currentTableMetadata;
 
             @Override
-            public Memtable memtable()
+            public DomainMemtable memtable()
             {
                 return SkipListMemtable.this;
             }
diff --git a/src/java/org/apache/cassandra/db/memtable/SkipListMemtableFactory.java b/src/java/org/apache/cassandra/db/memtable/SkipListMemtableFactory.java
index 76dee02be1..d2a5f217b9 100644
--- a/src/java/org/apache/cassandra/db/memtable/SkipListMemtableFactory.java
+++ b/src/java/org/apache/cassandra/db/memtable/SkipListMemtableFactory.java
@@ -23,6 +23,7 @@ import java.util.concurrent.atomic.AtomicReference;
 import com.google.common.collect.ImmutableMap;
 
 import org.apache.cassandra.config.InheritingClass;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.schema.TableMetadataRef;
 
@@ -34,12 +35,12 @@ import org.apache.cassandra.schema.TableMetadataRef;
  * Some tests want to setup table parameters before initializing DatabaseDescriptor -- this allows them to do so, and
  * also makes sure the memtable memory pools are not created for offline tools.
  */
-public class SkipListMemtableFactory implements Memtable.Factory
+public class SkipListMemtableFactory implements DomainMemtable.Factory
 {
     @Override
-    public Memtable create(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadaRef, Memtable.Owner owner)
+    public DomainMemtable create(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadaRef, Memtable.Owner owner, LogDomain domain)
     {
-        return new SkipListMemtable(commitLogLowerBound, metadaRef, owner);
+        return new SkipListMemtable(commitLogLowerBound, metadaRef, owner, domain);
     }
 
     public static final SkipListMemtableFactory INSTANCE = new SkipListMemtableFactory();
diff --git a/src/java/org/apache/cassandra/db/memtable/SplitDomainMemtable.java b/src/java/org/apache/cassandra/db/memtable/SplitDomainMemtable.java
new file mode 100644
index 0000000000..915f77449a
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/memtable/SplitDomainMemtable.java
@@ -0,0 +1,422 @@
+/*
+ * 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.db.memtable;
+
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.DataRange;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.LogDomain;
+import org.apache.cassandra.db.Slices;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+import org.apache.cassandra.db.filter.ColumnFilter;
+import org.apache.cassandra.db.partitions.ImmutableBTreePartition;
+import org.apache.cassandra.db.partitions.Partition;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.db.partitions.UnfilteredPartitionIterator;
+import org.apache.cassandra.db.partitions.UnfilteredPartitionIterators;
+import org.apache.cassandra.db.rows.UnfilteredRowIterator;
+import org.apache.cassandra.db.rows.UnfilteredRowIterators;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.index.transactions.UpdateTransaction;
+import org.apache.cassandra.io.sstable.SSTableReadsListener;
+import org.apache.cassandra.replication.MutationId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.OpOrder;
+
+/**
+ * One logical memtable holding a separate internal memtable per {@link LogDomain}.
+ *
+ * A table takes writes from both logs while part of its token range is migrating, and a position from one log does not
+ * compare against a bound from the other. Splitting at the memtable means each write is bounded, flushed and accounted
+ * for against its own log, without any consumer of a bound having to ask which log it came from.
+ *
+ * The internal memtables always flush together, and flushing the generation drains the listeners registered on the
+ * wrapper and on both internals.
+ */
+public class SplitDomainMemtable implements Memtable
+{
+    private final DomainMemtable commitLogInternal;
+    private final DomainMemtable journalInternal;
+    private final List<DomainMemtable> internals;
+    private final long id;
+    private final FlushListeners listeners = new FlushListeners();
+
+    public SplitDomainMemtable(DomainMemtable left, DomainMemtable right, long id)
+    {
+        Preconditions.checkArgument(left.owner() == right.owner());
+        Preconditions.checkArgument(!(left instanceof SplitDomainMemtable) && !(right instanceof SplitDomainMemtable));
+        if (left.holds(LogDomain.COMMIT_LOG))
+        {
+            Preconditions.checkArgument(right.holds(LogDomain.MUTATION_JOURNAL));
+            this.commitLogInternal = left;
+            this.journalInternal = right;
+        }
+        else
+        {
+            Preconditions.checkArgument(left.holds(LogDomain.MUTATION_JOURNAL));
+            Preconditions.checkArgument(right.holds(LogDomain.COMMIT_LOG));
+            this.commitLogInternal = right;
+            this.journalInternal = left;
+        }
+        this.internals = ImmutableList.of(commitLogInternal, journalInternal);
+        this.id = id;
+    }
+
+    @Override
+    public List<DomainMemtable> flushSources()
+    {
+        return internals;
+    }
+
+    @Override
+    public DomainMemtable flushSourceFor(LogDomain domain)
+    {
+        return internalFor(domain);
+    }
+
+    public DomainMemtable internalFor(LogDomain domain)
+    {
+        return domain.isJournal() ? journalInternal : commitLogInternal;
+    }
+
+    public boolean isInternal(Memtable memtable)
+    {
+        return memtable == commitLogInternal || memtable == journalInternal;
+    }
+
+    @Override
+    public boolean accepts(OpOrder.Group opGroup, CommitLogPosition commitLogPosition, LogDomain domain)
+    {
+        return internalFor(domain).accepts(opGroup, commitLogPosition, domain);
+    }
+
+    @Override
+    public boolean holds(LogDomain domain)
+    {
+        return true;
+    }
+
+    @Override
+    public Owner owner()
+    {
+        // One store created both internals, which is asserted on construction
+        return commitLogInternal.owner();
+    }
+
+    @Override
+    public boolean allocatesFromMemtablePool()
+    {
+        return commitLogInternal.allocatesFromMemtablePool() || journalInternal.allocatesFromMemtablePool();
+    }
+
+    @Override
+    public void flushIfPeriodExpired()
+    {
+        commitLogInternal.flushIfPeriodExpired();
+        journalInternal.flushIfPeriodExpired();
+    }
+
+    @Override
+    public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, LogDomain domain, boolean assumeMissing)
+    {
+        return internalFor(domain).put(mutationId, update, indexer, opGroup, domain, assumeMissing);
+    }
+
+    @Override
+    public long partitionCount()
+    {
+        return commitLogInternal.partitionCount() + journalInternal.partitionCount();
+    }
+
+    @Override
+    public long getLiveDataSize()
+    {
+        return commitLogInternal.getLiveDataSize() + journalInternal.getLiveDataSize();
+    }
+
+    @Override
+    public long operationCount()
+    {
+        return commitLogInternal.operationCount() + journalInternal.operationCount();
+    }
+
+    @Override
+    public void addMemoryUsageTo(MemoryUsage usage)
+    {
+        commitLogInternal.addMemoryUsageTo(usage);
+        journalInternal.addMemoryUsageTo(usage);
+    }
+
+    @Override
+    public long getMinTimestamp()
+    {
+        long commitLog = commitLogInternal.getMinTimestamp();
+        long journal = journalInternal.getMinTimestamp();
+        if (commitLog == NO_MIN_TIMESTAMP)
+            return journal;
+        if (journal == NO_MIN_TIMESTAMP)
+            return commitLog;
+        return Math.min(commitLog, journal);
+    }
+
+    @Override
+    public long getMinLocalDeletionTime()
+    {
+        return Math.min(commitLogInternal.getMinLocalDeletionTime(), journalInternal.getMinLocalDeletionTime());
+    }
+
+    /**
+     * Conjoined rather than taken from either internal. Accord's durability path reads this and reports a command store
+     * durable without registering a flush listener when it is true, so reporting clean while the other internal still
+     * holds unflushed data would declare a transaction durable that is not.
+     */
+    @Override
+    public boolean isClean()
+    {
+        return commitLogInternal.isClean() && journalInternal.isClean();
+    }
+
+    @Override
+    public void discard()
+    {
+        commitLogInternal.discard();
+        journalInternal.discard();
+    }
+
+    @Override
+    public void metadataUpdated()
+    {
+        commitLogInternal.metadataUpdated();
+        journalInternal.metadataUpdated();
+    }
+
+    @Override
+    public void localRangesUpdated()
+    {
+        commitLogInternal.localRangesUpdated();
+        journalInternal.localRangesUpdated();
+    }
+
+    @Override
+    public void performSnapshot(String snapshotName)
+    {
+        commitLogInternal.performSnapshot(snapshotName);
+        journalInternal.performSnapshot(snapshotName);
+    }
+
+    @Override
+    public boolean shouldSwitch(ColumnFamilyStore.FlushReason reason, TableMetadata latest)
+    {
+        // Either internal wanting to switch switches the whole generation, since they flush together.
+        return commitLogInternal.shouldSwitch(reason, latest) || journalInternal.shouldSwitch(reason, latest);
+    }
+
+    /**
+     * This is used by external non memtable operations (ie: indexes) to report their memtable adjacent memory
+     * usage. Since there isn't a domain associated with these users, we just charge it to the commit log domain. This
+     * is arbitrary, but it doesn't matter, since operations looking at memtable sizes (ie: flushLargestMemtable) only
+     * look at the combined usage of both memtables.
+     */
+    @Override
+    public void markExtraOnHeapUsed(long additionalSpace, OpOrder.Group opGroup)
+    {
+        commitLogInternal.markExtraOnHeapUsed(additionalSpace, opGroup);
+    }
+
+    /**
+     * This is used by external non memtable operations (ie: indexes) to report their memtable adjacent memory
+     * usage. Since there isn't a domain associated with these users, we just charge it to the commit log domain. This
+     * is arbitrary, but it doesn't matter, since operations looking at memtable sizes (ie: flushLargestMemtable) only
+     * look at the combined usage of both memtables.
+     */
+    @Override
+    public void markExtraOffHeapUsed(long additionalSpace, OpOrder.Group opGroup)
+    {
+        commitLogInternal.markExtraOffHeapUsed(additionalSpace, opGroup);
+    }
+
+    @Override
+    public long getMemtableId()
+    {
+        return id;
+    }
+
+    @Override
+    public TableMetadata metadata()
+    {
+        return commitLogInternal.metadata();
+    }
+
+    @Override
+    public <T extends Consumer<TableMetadata>> T ensureFlushListener(Object key, Supplier<T> factory)
+    {
+        return listeners.ensureFlushListener(key, factory);
+    }
+
+    @Override
+    public void notifyFlushed()
+    {
+        listeners.notifyFlushed(metadata());
+
+        // A listener can be registered on a memtable before it splits, so we need to call notifyFlushed
+        // on the delegate memtables.
+        commitLogInternal.notifyFlushed();
+        journalInternal.notifyFlushed();
+    }
+
+    /**
+     * Both internals take the same boundary and the same barrier, and each reads the position for its own domain from
+     * it. One barrier, because the generation flushes as a whole; see the class javadoc.
+     */
+    @Override
+    public void switchOut(OpOrder.Barrier writeBarrier, LogDomainBounds upperBounds)
+    {
+        commitLogInternal.switchOut(writeBarrier, upperBounds);
+        journalInternal.switchOut(writeBarrier, upperBounds);
+    }
+
+    @Override
+    public Partition snapshotPartition(DecoratedKey key)
+    {
+        Partition fromCommitLog = commitLogInternal.snapshotPartition(key);
+        Partition fromJournal = journalInternal.snapshotPartition(key);
+
+        if (fromCommitLog == null || fromCommitLog.isEmpty())
+            return fromJournal;
+        if (fromJournal == null || fromJournal.isEmpty())
+            return fromCommitLog;
+
+        UnfilteredRowIterator commitLogRows = null;
+        UnfilteredRowIterator journalRows = null;
+        UnfilteredRowIterator merged;
+        try
+        {
+            commitLogRows = fromCommitLog.unfilteredIterator();
+            journalRows = fromJournal.unfilteredIterator();
+            merged = UnfilteredRowIterators.merge(ImmutableList.of(commitLogRows, journalRows));
+        }
+        catch (Throwable t)
+        {
+            Throwables.closeNonNullAndAddSuppressed(t, commitLogRows, journalRows);
+            throw t;
+        }
+
+        try (UnfilteredRowIterator itr = merged)
+        {
+            return ImmutableBTreePartition.create(itr);
+        }
+    }
+
+    @Override
+    public UnfilteredRowIterator rowIterator(DecoratedKey key,
+                                             Slices slices,
+                                             ColumnFilter columnFilter,
+                                             boolean reversed,
+                                             SSTableReadsListener listener)
+    {
+        UnfilteredRowIterator fromCommitLog = null;
+        UnfilteredRowIterator fromJournal = null;
+        try
+        {
+            fromCommitLog = commitLogInternal.rowIterator(key, slices, columnFilter, reversed, listener);
+            fromJournal = journalInternal.rowIterator(key, slices, columnFilter, reversed, listener);
+            return mergeRows(fromCommitLog, fromJournal);
+        }
+        catch (Throwable t)
+        {
+            Throwables.closeNonNullAndAddSuppressed(t, fromCommitLog, fromJournal);
+            throw t;
+        }
+    }
+
+    @Override
+    public UnfilteredRowIterator rowIterator(DecoratedKey key)
+    {
+        UnfilteredRowIterator fromCommitLog = null;
+        UnfilteredRowIterator fromJournal = null;
+        try
+        {
+            fromCommitLog = commitLogInternal.rowIterator(key);
+            fromJournal = journalInternal.rowIterator(key);
+            return mergeRows(fromCommitLog, fromJournal);
+        }
+        catch (Throwable t)
+        {
+            Throwables.closeNonNullAndAddSuppressed(t, fromCommitLog, fromJournal);
+            throw t;
+        }
+    }
+
+    private static UnfilteredRowIterator mergeRows(UnfilteredRowIterator fromCommitLog, UnfilteredRowIterator fromJournal)
+    {
+        if (fromCommitLog == null)
+            return fromJournal;
+        if (fromJournal == null)
+            return fromCommitLog;
+        return UnfilteredRowIterators.merge(ImmutableList.of(fromCommitLog, fromJournal));
+    }
+
+    @Override
+    public UnfilteredPartitionIterator partitionIterator(ColumnFilter columnFilter,
+                                                         DataRange dataRange,
+                                                         SSTableReadsListener listener)
+    {
+        UnfilteredPartitionIterator fromCommitLog = null;
+        UnfilteredPartitionIterator fromJournal = null;
+        try
+        {
+            fromCommitLog = commitLogInternal.partitionIterator(columnFilter, dataRange, listener);
+            fromJournal = journalInternal.partitionIterator(columnFilter, dataRange, listener);
+            return UnfilteredPartitionIterators.merge(ImmutableList.of(fromCommitLog, fromJournal),
+                                                      UnfilteredPartitionIterators.MergeListener.NOOP);
+        }
+        catch (Throwable t)
+        {
+            Throwables.closeNonNullAndAddSuppressed(t, fromCommitLog, fromJournal);
+            throw t;
+        }
+    }
+
+    @Override
+    public Token lastToken()
+    {
+        Token fromCommitLog = commitLogInternal.lastToken();
+        Token fromJournal = journalInternal.lastToken();
+
+        if (fromCommitLog == null)
+            return fromJournal;
+        if (fromJournal == null)
+            return fromCommitLog;
+        return fromCommitLog.compareTo(fromJournal) >= 0 ? fromCommitLog : fromJournal;
+    }
+
+    @Override
+    public String toString()
+    {
+        return "SplitDomainMemtable(id=" + id + ", commitLog=" + commitLogInternal + ", journal=" + journalInternal + ')';
+    }
+}
diff --git a/src/java/org/apache/cassandra/db/memtable/TrieMemtable.java b/src/java/org/apache/cassandra/db/memtable/TrieMemtable.java
index dc165483d6..8c7b7229eb 100644
--- a/src/java/org/apache/cassandra/db/memtable/TrieMemtable.java
+++ b/src/java/org/apache/cassandra/db/memtable/TrieMemtable.java
@@ -41,6 +41,7 @@ import org.apache.cassandra.db.ColumnFamilyStore;
 import org.apache.cassandra.db.DataRange;
 import org.apache.cassandra.db.DecoratedKey;
 import org.apache.cassandra.db.DeletionInfo;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.PartitionPosition;
 import org.apache.cassandra.db.RegularAndStaticColumns;
 import org.apache.cassandra.db.Slices;
@@ -125,9 +126,9 @@ public class TrieMemtable extends AbstractShardedMemtable
     @Unmetered
     private final TrieMemtableMetricsView metrics;
 
-    TrieMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadataRef, Owner owner, Integer shardCountOption)
+    TrieMemtable(AtomicReference<CommitLogPosition> commitLogLowerBound, TableMetadataRef metadataRef, Owner owner, LogDomain domain, Integer shardCountOption)
     {
-        super(commitLogLowerBound, metadataRef, owner, shardCountOption);
+        super(commitLogLowerBound, metadataRef, owner, domain, shardCountOption);
         this.metrics = new TrieMemtableMetricsView(metadataRef.keyspace, metadataRef.name);
         this.shards = generatePartitionShards(boundaries.shardCount(), allocator, metadataRef, metrics);
         this.mergedTrie = makeMergedTrie(shards);
@@ -186,8 +187,9 @@ public class TrieMemtable extends AbstractShardedMemtable
      * commitLogSegmentPosition should only be null if this is a secondary index, in which case it is *expected* to be null
      */
     @Override
-    public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, boolean assumeMissing)
+    public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, OpOrder.Group opGroup, LogDomain domain, boolean assumeMissing)
     {
+        requireDomain(domain);
         try
         {
             DecoratedKey key = update.partitionKey();
@@ -473,7 +475,7 @@ public class TrieMemtable extends AbstractShardedMemtable
         {
             private final TableMetadata tableMetadata = TrieMemtable.this.metadata();
 
-            public Memtable memtable()
+            public DomainMemtable memtable()
             {
                 return TrieMemtable.this;
             }
@@ -790,7 +792,7 @@ public class TrieMemtable extends AbstractShardedMemtable
         return new Factory(shardCount);
     }
 
-    static class Factory implements Memtable.Factory
+    static class Factory implements DomainMemtable.Factory
     {
         final Integer shardCount;
 
@@ -799,11 +801,12 @@ public class TrieMemtable extends AbstractShardedMemtable
             this.shardCount = shardCount;
         }
 
-        public Memtable create(AtomicReference<CommitLogPosition> commitLogLowerBound,
+        public DomainMemtable create(AtomicReference<CommitLogPosition> commitLogLowerBound,
                                TableMetadataRef metadaRef,
-                               Owner owner)
+                               Owner owner,
+                               LogDomain domain)
         {
-            return new TrieMemtable(commitLogLowerBound, metadaRef, owner, shardCount);
+            return new TrieMemtable(commitLogLowerBound, metadaRef, owner, domain, shardCount);
         }
 
         @Override
diff --git a/src/java/org/apache/cassandra/db/repair/PendingAntiCompaction.java b/src/java/org/apache/cassandra/db/repair/PendingAntiCompaction.java
index 35569c7b6f..6006ee5d1a 100644
--- a/src/java/org/apache/cassandra/db/repair/PendingAntiCompaction.java
+++ b/src/java/org/apache/cassandra/db/repair/PendingAntiCompaction.java
@@ -40,6 +40,7 @@ import org.slf4j.LoggerFactory;
 import org.apache.cassandra.concurrent.FutureTask;
 import org.apache.cassandra.config.CassandraRelevantProperties;
 import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.compaction.CompactionGroup;
 import org.apache.cassandra.db.compaction.CompactionInfo;
 import org.apache.cassandra.db.compaction.CompactionManager;
 import org.apache.cassandra.db.compaction.OperationType;
@@ -125,6 +126,10 @@ public class PendingAntiCompaction
             if (metadata.repairedAt != UNREPAIRED_SSTABLE)
                 return false;
 
+            // exclude tracked sstables
+            if (CompactionGroup.of(sstable) == CompactionGroup.UNRECONCILED)
+                return false;
+
             if (!sstable.descriptor.version.hasPendingRepair())
             {
                 String message = String.format("Prepare phase failed because it encountered legacy sstables that don't " +
diff --git a/src/java/org/apache/cassandra/db/tracked/TrackedKeyspaceWriteHandler.java b/src/java/org/apache/cassandra/db/tracked/TrackedKeyspaceWriteHandler.java
index 783b12d3fd..258d72e57b 100644
--- a/src/java/org/apache/cassandra/db/tracked/TrackedKeyspaceWriteHandler.java
+++ b/src/java/org/apache/cassandra/db/tracked/TrackedKeyspaceWriteHandler.java
@@ -20,6 +20,7 @@ package org.apache.cassandra.db.tracked;
 import org.apache.cassandra.db.CassandraWriteContext;
 import org.apache.cassandra.db.Keyspace;
 import org.apache.cassandra.db.KeyspaceWriteHandler;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.Mutation;
 import org.apache.cassandra.db.WriteContext;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
@@ -33,14 +34,14 @@ import org.apache.cassandra.utils.concurrent.OpOrder;
 public class TrackedKeyspaceWriteHandler implements KeyspaceWriteHandler
 {
     @Override
-    public WriteContext beginWrite(Mutation mutation, boolean makeDurable) throws RequestExecutionException
+    public WriteContext beginWrite(Mutation mutation, boolean makeDurable, boolean isReplay) throws RequestExecutionException
     {
         OpOrder.Group group = null;
         try
         {
             group = Keyspace.writeOrder.start();
 
-            MigrationRouter.validateTrackedMutation(mutation);
+            MigrationRouter.validateTrackedMutation(mutation, isReplay);
 
             CommitLogPosition pointer = null;
             if (makeDurable)
@@ -51,7 +52,7 @@ public class TrackedKeyspaceWriteHandler implements KeyspaceWriteHandler
                 pointer = MutationJournal.instance().write(mutation.id(), mutation, isFullReplica);
             }
 
-            return new CassandraWriteContext(group, pointer);
+            return new CassandraWriteContext(group, pointer, LogDomain.MUTATION_JOURNAL);
         }
         catch (Throwable t)
         {
@@ -64,27 +65,14 @@ public class TrackedKeyspaceWriteHandler implements KeyspaceWriteHandler
     @Override
     public WriteContext createContextForIndexing()
     {
-        return createEmptyContext();
+        // all callers of this method use keyspace.getWriteHandler(), which is the standard CassandraWriteHandler
+        throw new UnsupportedOperationException("Can't call createContextForIndexing on TrackedKeyspaceWriteHandler");
     }
 
     @Override
     public WriteContext createContextForRead()
     {
-        return createEmptyContext();
-    }
-
-    private WriteContext createEmptyContext()
-    {
-        OpOrder.Group group = Keyspace.writeOrder.start();
-        try
-        {
-            return new CassandraWriteContext(group, null);
-        }
-        catch (Throwable t)
-        {
-            if (group != null)
-                group.close();
-            throw t;
-        }
+        // all callers of this method use keyspace.getWriteHandler(), which is the standard CassandraWriteHandler
+        throw new UnsupportedOperationException("Can't call createContextForRead on TrackedKeyspaceWriteHandler");
     }
 }
diff --git a/src/java/org/apache/cassandra/db/view/TableViews.java b/src/java/org/apache/cassandra/db/view/TableViews.java
index 66cd6bd6a7..ad20a1bb0a 100644
--- a/src/java/org/apache/cassandra/db/view/TableViews.java
+++ b/src/java/org/apache/cassandra/db/view/TableViews.java
@@ -48,13 +48,13 @@ import org.apache.cassandra.db.SinglePartitionReadCommand;
 import org.apache.cassandra.db.Slice;
 import org.apache.cassandra.db.Slices;
 import org.apache.cassandra.db.SystemKeyspace;
-import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.db.filter.ClusteringIndexFilter;
 import org.apache.cassandra.db.filter.ClusteringIndexNamesFilter;
 import org.apache.cassandra.db.filter.ClusteringIndexSliceFilter;
 import org.apache.cassandra.db.filter.ColumnFilter;
 import org.apache.cassandra.db.filter.DataLimits;
 import org.apache.cassandra.db.filter.RowFilter;
+import org.apache.cassandra.db.memtable.LogDomainPositions;
 import org.apache.cassandra.db.partitions.PartitionUpdate;
 import org.apache.cassandra.db.partitions.UnfilteredPartitionIterators;
 import org.apache.cassandra.db.rows.BTreeRow;
@@ -148,7 +148,7 @@ public class TableViews extends AbstractCollection<View>
             viewCfs.dumpMemtable();
     }
 
-    public void truncateBlocking(CommitLogPosition replayAfter, long truncatedAt)
+    public void truncateBlocking(LogDomainPositions replayAfter, long truncatedAt)
     {
         for (ColumnFamilyStore viewCfs : allViewsCfs())
         {
diff --git a/src/java/org/apache/cassandra/index/accord/MemtableIndexManager.java b/src/java/org/apache/cassandra/index/accord/MemtableIndexManager.java
index 14f8fa543c..0bf23fa57b 100644
--- a/src/java/org/apache/cassandra/index/accord/MemtableIndexManager.java
+++ b/src/java/org/apache/cassandra/index/accord/MemtableIndexManager.java
@@ -29,19 +29,19 @@ import accord.primitives.TxnId;
 
 import org.apache.cassandra.db.DecoratedKey;
 import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
-import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.rows.Row;
 import org.apache.cassandra.schema.TableId;
 
 public interface MemtableIndexManager
 {
-    long index(DecoratedKey key, Row row, Memtable mt);
+    long index(DecoratedKey key, Row row, DomainMemtable mt);
 
     MemtableIndex getPendingMemtableIndex(ILifecycleTransaction txn);
 
-    void discardMemtable(Memtable memtable);
+    void discardMemtable(DomainMemtable memtable);
 
-    void renewMemtable(Memtable renewed);
+    void renewMemtable(DomainMemtable renewed);
 
     void search(int storeId, TableId tableId, byte[] start, byte[] end,
                 TxnId minTxnId, Timestamp maxTxnId, @Nullable DecidedRX decidedRX,
diff --git a/src/java/org/apache/cassandra/index/accord/RouteJournalIndex.java b/src/java/org/apache/cassandra/index/accord/RouteJournalIndex.java
index eb20373a73..8c6c7caa5c 100644
--- a/src/java/org/apache/cassandra/index/accord/RouteJournalIndex.java
+++ b/src/java/org/apache/cassandra/index/accord/RouteJournalIndex.java
@@ -60,6 +60,7 @@ import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
 import org.apache.cassandra.db.lifecycle.Tracker;
 import org.apache.cassandra.db.marshal.AbstractType;
 import org.apache.cassandra.db.marshal.Int32Type;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.memtable.Memtable;
 import org.apache.cassandra.db.partitions.PartitionUpdate;
 import org.apache.cassandra.db.partitions.UnfilteredPartitionIterator;
@@ -350,14 +351,17 @@ public class RouteJournalIndex implements Index, INotificationConsumer
         // since we are attached we only care about update
         if (transactionType != IndexTransaction.Type.UPDATE)
             return null;
+
+        // The index for a row belongs to the domain memtable that will hold it
+        DomainMemtable source = memtable.flushSourceFor(CassandraWriteContext.fromContext(ctx).domain());
         return new Indexer()
         {
             @Override
             public void insertRow(Row row)
             {
-                long size = memtableIndexManager.index(key, row, memtable);
+                long size = memtableIndexManager.index(key, row, source);
                 if (size > 0)
-                    memtable.markExtraOnHeapUsed(size, CassandraWriteContext.fromContext(ctx).getGroup());
+                    source.markExtraOnHeapUsed(size, CassandraWriteContext.fromContext(ctx).getGroup());
             }
 
             @Override
@@ -558,7 +562,8 @@ public class RouteJournalIndex implements Index, INotificationConsumer
         }
         else if (notification instanceof MemtableDiscardedNotification)
         {
-            memtableIndexManager.discardMemtable(((MemtableDiscardedNotification) notification).memtable);
+            for (DomainMemtable source : ((MemtableDiscardedNotification) notification).memtable.flushSources())
+                memtableIndexManager.discardMemtable(source);
         }
     }
 
diff --git a/src/java/org/apache/cassandra/index/accord/RouteMemtableIndexManager.java b/src/java/org/apache/cassandra/index/accord/RouteMemtableIndexManager.java
index 7c9adb6c3d..cfa7be1ff1 100644
--- a/src/java/org/apache/cassandra/index/accord/RouteMemtableIndexManager.java
+++ b/src/java/org/apache/cassandra/index/accord/RouteMemtableIndexManager.java
@@ -32,7 +32,7 @@ import accord.primitives.TxnId;
 
 import org.apache.cassandra.db.DecoratedKey;
 import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
-import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.rows.Row;
 import org.apache.cassandra.schema.TableId;
 import org.apache.cassandra.service.accord.AccordKeyspace;
@@ -42,7 +42,7 @@ import static org.apache.cassandra.utils.Clock.Global.nanoTime;
 
 public class RouteMemtableIndexManager implements MemtableIndexManager
 {
-    private final ConcurrentMap<Memtable, MemtableIndex> liveMemtableIndexMap = new ConcurrentHashMap<>();
+    private final ConcurrentMap<DomainMemtable, MemtableIndex> liveMemtableIndexMap = new ConcurrentHashMap<>();
     private final RouteJournalIndex index;
 
     public RouteMemtableIndexManager(RouteJournalIndex index)
@@ -51,7 +51,7 @@ public class RouteMemtableIndexManager implements MemtableIndexManager
     }
 
     @Override
-    public long index(DecoratedKey key, Row row, Memtable mt)
+    public long index(DecoratedKey key, Row row, DomainMemtable mt)
     {
         if (row.isStatic())
             return 0;
@@ -88,15 +88,15 @@ public class RouteMemtableIndexManager implements MemtableIndexManager
     }
 
     @Override
-    public void discardMemtable(Memtable memtable)
+    public void discardMemtable(DomainMemtable memtable)
     {
         liveMemtableIndexMap.remove(memtable);
     }
 
     @Override
-    public void renewMemtable(Memtable renewed)
+    public void renewMemtable(DomainMemtable renewed)
     {
-        for (Memtable memtable : liveMemtableIndexMap.keySet())
+        for (DomainMemtable memtable : liveMemtableIndexMap.keySet())
         {
             // remove every index but the one that corresponds to the post-truncate Memtable
             if (renewed != memtable)
diff --git a/src/java/org/apache/cassandra/index/internal/CassandraIndex.java b/src/java/org/apache/cassandra/index/internal/CassandraIndex.java
index 54bc677a2a..1bac955064 100644
--- a/src/java/org/apache/cassandra/index/internal/CassandraIndex.java
+++ b/src/java/org/apache/cassandra/index/internal/CassandraIndex.java
@@ -611,7 +611,13 @@ public abstract class CassandraIndex implements Index
                                                                cell));
         Row row = BTreeRow.noCellLiveRow(buildIndexClustering(rowKey, clustering, cell), info);
         PartitionUpdate upd = partitionUpdate(valueKey, row);
-        indexCfs.getWriteHandler().write(MutationId.fixme(), upd, ctx, false);
+
+        // we always use MutationId.NONE for index writes, even if the write itself is originating from a journal
+        // write. This is because the journal's segment bookkeeping is only against the base table, and the 2i memtables
+        // are flushed synchronously with the base table, so it doesn't affect segment dropping. Additionally, the 2i
+        // path isn't involved in replication, and sstable compaction is affected by replication status so it's easier
+        // to just treat all 2i data as untracked. Same way incremental repair doesn't move 2i sstables around.
+        indexCfs.getWriteHandler().write(MutationId.none(), upd, ctx, false);
         logger.trace("Inserted entry into index for value {}", valueKey);
     }
 
@@ -657,7 +663,7 @@ public abstract class CassandraIndex implements Index
     {
         Row row = BTreeRow.emptyDeletedRow(indexClustering, Row.Deletion.regular(deletion));
         PartitionUpdate upd = partitionUpdate(indexKey, row);
-        indexCfs.getWriteHandler().write(MutationId.fixme(), upd, ctx, false);
+        indexCfs.getWriteHandler().write(MutationId.none(), upd, ctx, false);
         logger.trace("Removed index entry for value {}", indexKey);
     }
 
diff --git a/src/java/org/apache/cassandra/index/sai/StorageAttachedIndex.java b/src/java/org/apache/cassandra/index/sai/StorageAttachedIndex.java
index 1dba97d3ea..3428aef0e9 100644
--- a/src/java/org/apache/cassandra/index/sai/StorageAttachedIndex.java
+++ b/src/java/org/apache/cassandra/index/sai/StorageAttachedIndex.java
@@ -58,6 +58,7 @@ import org.apache.cassandra.cql3.statements.schema.IndexTarget;
 import org.apache.cassandra.db.CassandraWriteContext;
 import org.apache.cassandra.db.ColumnFamilyStore;
 import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.ReadCommand;
 import org.apache.cassandra.db.RegularAndStaticColumns;
 import org.apache.cassandra.db.WriteContext;
@@ -69,6 +70,7 @@ import org.apache.cassandra.db.guardrails.MaxThreshold;
 import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
 import org.apache.cassandra.db.marshal.AbstractType;
 import org.apache.cassandra.db.marshal.FloatType;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.memtable.Memtable;
 import org.apache.cassandra.db.partitions.PartitionUpdate;
 import org.apache.cassandra.db.rows.Row;
@@ -599,7 +601,8 @@ public class StorageAttachedIndex implements Index
     {
         if (transactionType == IndexTransaction.Type.UPDATE)
         {
-            return new UpdateIndexer(key, memtable, writeContext);
+            LogDomain domain = CassandraWriteContext.fromContext(writeContext).domain();
+            return new UpdateIndexer(key, memtable.flushSourceFor(domain), writeContext);
         }
 
         // we are only interested in the data from Memtable
@@ -1012,10 +1015,10 @@ public class StorageAttachedIndex implements Index
     private class UpdateIndexer implements Index.Indexer
     {
         private final DecoratedKey key;
-        private final Memtable memtable;
+        private final DomainMemtable memtable;
         private final WriteContext writeContext;
 
-        UpdateIndexer(DecoratedKey key, Memtable memtable, WriteContext writeContext)
+        UpdateIndexer(DecoratedKey key, DomainMemtable memtable, WriteContext writeContext)
         {
             this.key = key;
             this.memtable = memtable;
diff --git a/src/java/org/apache/cassandra/index/sai/StorageAttachedIndexGroup.java b/src/java/org/apache/cassandra/index/sai/StorageAttachedIndexGroup.java
index 56ce6eda2f..4d73a6c57f 100644
--- a/src/java/org/apache/cassandra/index/sai/StorageAttachedIndexGroup.java
+++ b/src/java/org/apache/cassandra/index/sai/StorageAttachedIndexGroup.java
@@ -43,6 +43,7 @@ import org.apache.cassandra.db.WriteContext;
 import org.apache.cassandra.db.filter.RowFilter;
 import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
 import org.apache.cassandra.db.lifecycle.Tracker;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.memtable.Memtable;
 import org.apache.cassandra.db.rows.Row;
 import org.apache.cassandra.index.Index;
@@ -280,11 +281,13 @@ public class StorageAttachedIndexGroup implements Index.Group, INotificationCons
         }
         else if (notification instanceof MemtableSwitchedNotification)
         {
-            indexes.forEach(index -> index.memtableIndexManager().maybeInitializeMemtableIndex(((MemtableSwitchedNotification) notification).next));
+            for (DomainMemtable source : ((MemtableSwitchedNotification) notification).next.flushSources())
+                indexes.forEach(index -> index.memtableIndexManager().maybeInitializeMemtableIndex(source));
         }
         else if (notification instanceof MemtableDiscardedNotification)
         {
-            indexes.forEach(index -> index.memtableIndexManager().discardMemtable(((MemtableDiscardedNotification) notification).memtable));
+            for (DomainMemtable source : ((MemtableDiscardedNotification) notification).memtable.flushSources())
+                indexes.forEach(index -> index.memtableIndexManager().discardMemtable(source));
         }
     }
 
diff --git a/src/java/org/apache/cassandra/index/sai/memory/MemtableIndexManager.java b/src/java/org/apache/cassandra/index/sai/memory/MemtableIndexManager.java
index c2f7087fc9..f16e299216 100644
--- a/src/java/org/apache/cassandra/index/sai/memory/MemtableIndexManager.java
+++ b/src/java/org/apache/cassandra/index/sai/memory/MemtableIndexManager.java
@@ -34,7 +34,7 @@ import com.google.common.annotations.VisibleForTesting;
 import org.apache.cassandra.cql3.statements.schema.IndexTarget;
 import org.apache.cassandra.db.DecoratedKey;
 import org.apache.cassandra.db.lifecycle.ILifecycleTransaction;
-import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.rows.Row;
 import org.apache.cassandra.index.sai.StorageAttachedIndex;
 import org.apache.cassandra.utils.Clock;
@@ -43,7 +43,7 @@ import org.apache.cassandra.utils.FBUtilities;
 public class MemtableIndexManager
 {
     private final StorageAttachedIndex index;
-    private final ConcurrentMap<Memtable, MemtableIndex> liveMemtableIndexMap;
+    private final ConcurrentMap<DomainMemtable, MemtableIndex> liveMemtableIndexMap;
 
     public MemtableIndexManager(StorageAttachedIndex index)
     {
@@ -51,13 +51,13 @@ public class MemtableIndexManager
         this.liveMemtableIndexMap = new ConcurrentHashMap<>();
     }
 
-    public void maybeInitializeMemtableIndex(Memtable memtable)
+    public void maybeInitializeMemtableIndex(DomainMemtable memtable)
     {
         if (index.termType().isVector())
             initializeMemtableIndex(memtable);
     }
 
-    private MemtableIndex initializeMemtableIndex(Memtable mt)
+    private MemtableIndex initializeMemtableIndex(DomainMemtable mt)
     {
         MemtableIndex current = liveMemtableIndexMap.get(mt);
 
@@ -67,7 +67,7 @@ public class MemtableIndexManager
                                : liveMemtableIndexMap.computeIfAbsent(mt, memtable -> new MemtableIndex(index, memtable));
     }
 
-    public long index(DecoratedKey key, Row row, Memtable mt)
+    public long index(DecoratedKey key, Row row, DomainMemtable mt)
     {
         MemtableIndex target = initializeMemtableIndex(mt);
 
@@ -108,7 +108,7 @@ public class MemtableIndexManager
         return bytes;
     }
 
-    public long update(DecoratedKey key, Row oldRow, Row newRow, Memtable memtable)
+    public long update(DecoratedKey key, Row oldRow, Row newRow, DomainMemtable memtable)
     {
         if (!index.termType().isVector())
         {
@@ -124,9 +124,9 @@ public class MemtableIndexManager
         return target.update(key, oldRow.clustering(), oldValue, newValue);
     }
 
-    public void renewMemtable(Memtable renewed)
+    public void renewMemtable(DomainMemtable renewed)
     {
-        for (Memtable memtable : liveMemtableIndexMap.keySet())
+        for (DomainMemtable memtable : liveMemtableIndexMap.keySet())
         {
             // remove every index but the one that corresponds to the post-truncate Memtable
             if (renewed != memtable)
@@ -136,7 +136,7 @@ public class MemtableIndexManager
         }
     }
 
-    public void discardMemtable(Memtable discarded)
+    public void discardMemtable(DomainMemtable discarded)
     {
         liveMemtableIndexMap.remove(discarded);
     }
diff --git a/src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java b/src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
index 7262af49cd..1d8f2a3036 100644
--- a/src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
+++ b/src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
@@ -1413,6 +1413,19 @@ public abstract class SSTableReader extends SSTable implements UnfilteredSource,
         }
     }
 
+    /**
+     * Promote a reconciled sstable to repaired and clear its coordinator log offsets
+     */
+    public void mutatePromotedToRepairedAndReload(long newRepairedAt) throws IOException
+    {
+        Preconditions.checkArgument(newRepairedAt != ActiveRepairService.UNREPAIRED_SSTABLE);
+
+        // setting repaired > UNREPAIRED_SSTABLE automatically clears the offsets
+        mutateRepairedAndReload(newRepairedAt, ActiveRepairService.NO_PENDING_REPAIR);
+
+        Preconditions.checkState(getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+    }
+
     /**
      * Reloads the sstable metadata from disk.
      * <p>
diff --git a/src/java/org/apache/cassandra/io/sstable/format/SSTableWriter.java b/src/java/org/apache/cassandra/io/sstable/format/SSTableWriter.java
index b635f36775..27957132ab 100644
--- a/src/java/org/apache/cassandra/io/sstable/format/SSTableWriter.java
+++ b/src/java/org/apache/cassandra/io/sstable/format/SSTableWriter.java
@@ -373,11 +373,21 @@ public abstract class SSTableWriter extends SSTable implements Transactional
                 if (MutationTrackingService.instance().isDurablyReconciled(coordinatorLogOffsets))
                 {
                     repairedAt = Clock.Global.currentTimeMillis();
+                    // Clear the offsets, as PromoteReconciledTask does. Offsets are only meaningful while an sstable is
+                    // unrepaired, so setting repairedAt and keeping them would leave it claiming journal provenance.
+                    coordinatorLogOffsets = new ImmutableCoordinatorLogOffsets.Builder().build();
                     logger.debug("Marking SSTable {} as reconciled with repairedAt {}", descriptor, repairedAt);
                 }
             }
         }
 
+        // Offsets are only meaningful while an sstable is unrepaired. Compaction and anticompaction outputs inherit
+        // repairedAt from their inputs, so the branch above is skipped and CompactionTask.getCoordinatorLogOffsets()
+        // would write the union of the inputs' offsets through. No path is known to reach this with offsets present:
+        // StatsMetadata.mutateRepairedMetadata() clears them wherever repairedAt is set. This is a backstop.
+        if (repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE)
+            coordinatorLogOffsets = ImmutableCoordinatorLogOffsets.NONE;
+
         return metadataCollector.finalizeMetadata(getPartitioner().getClass().getCanonicalName(),
                                                   metadata().params.bloomFilterFpChance,
                                                   repairedAt,
diff --git a/src/java/org/apache/cassandra/io/sstable/format/SortedTableVerifier.java b/src/java/org/apache/cassandra/io/sstable/format/SortedTableVerifier.java
index 6419695dd9..b47f4b485d 100644
--- a/src/java/org/apache/cassandra/io/sstable/format/SortedTableVerifier.java
+++ b/src/java/org/apache/cassandra/io/sstable/format/SortedTableVerifier.java
@@ -125,7 +125,12 @@ public abstract class SortedTableVerifier<R extends SSTableReaderWithFilter> imp
 
     protected void markAndThrow(Throwable cause, boolean mutateRepaired)
     {
-        if (mutateRepaired && options.mutateRepairStatus) // if we are able to mutate repaired flag, an incremental repair should be enough
+        // Marking the sstable unrepaired exists so that incremental repair notices it and repairs it. That would
+        // create an unreconcilable table on a tracked table
+        boolean tracked = cfs.metadata().replicationType().isTracked();
+        boolean unRepair = mutateRepaired && options.mutateRepairStatus && !tracked;
+
+        if (unRepair)
         {
             try
             {
@@ -137,7 +142,24 @@ public abstract class SortedTableVerifier<R extends SSTableReaderWithFilter> imp
                 outputHandler.output("Error mutating repairedAt for SSTable %s, as part of markAndThrow", sstable.getFilename());
             }
         }
-        Exception e = new Exception(String.format("Invalid SSTable %s, please force %srepair", sstable.getFilename(), (mutateRepaired && options.mutateRepairStatus) ? "" : "a full "), cause);
+
+        Exception e;
+        if (tracked)
+        {
+            // Full repair adds correct data but cannot remove the corrupt row: read resolution is last-write-wins on
+            // timestamp, so a corrupt row with a mangled high timestamp still beats the row repair streams in.
+            String message = String.format("Invalid SSTable %s on tracked table %s.%s; repairedAt left unchanged. " +
+                                           "Run a full repair to restore any missing data, and scrub or replace the " +
+                                           "node to remove the corruption - a corrupt row can still win read " +
+                                           "resolution on timestamp, so full repair alone may not be sufficient.",
+                                           sstable.getFilename(), cfs.metadata.keyspace, cfs.metadata.name);
+            outputHandler.warn(message);
+            e = new Exception(message, cause);
+        }
+        else
+        {
+            e = new Exception(String.format("Invalid SSTable %s, please force %srepair", sstable.getFilename(), unRepair ? "" : "a full "), cause);
+        }
         if (options.invokeDiskFailurePolicy)
             throw new CorruptSSTableException(e, sstable.getFilename());
         else
diff --git a/src/java/org/apache/cassandra/io/sstable/metadata/StatsMetadata.java b/src/java/org/apache/cassandra/io/sstable/metadata/StatsMetadata.java
index 81640ced44..05541474d3 100644
--- a/src/java/org/apache/cassandra/io/sstable/metadata/StatsMetadata.java
+++ b/src/java/org/apache/cassandra/io/sstable/metadata/StatsMetadata.java
@@ -43,6 +43,7 @@ import org.apache.cassandra.io.util.DataInputPlus;
 import org.apache.cassandra.io.util.DataOutputPlus;
 import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
 import org.apache.cassandra.serializers.AbstractTypeSerializer;
+import org.apache.cassandra.service.ActiveRepairService;
 import org.apache.cassandra.utils.ByteBufferUtil;
 import org.apache.cassandra.utils.EstimatedHistogram;
 import org.apache.cassandra.utils.TimeUUID;
@@ -212,8 +213,20 @@ public class StatsMetadata extends MetadataComponent
                                  lastKey);
     }
 
+    /**
+     * Coordinator log offsets are dropped whenever this sets {@code repairedAt}. They are only meaningful while an
+     * sstable is unrepaired: repairing it asserts the data is consistent on every replica, which is what the offsets
+     * exist to establish, and {@code TrackedCompactionManager.isPromotable} declines a repaired sstable, so anything
+     * left behind here could never be cleared afterwards.
+     *
+     * A pending-repair session leaves {@code repairedAt} unset, so the offsets survive it. That matters, because a
+     * failed session returns the sstable to unrepaired and it has to stay promotable.
+     */
     public StatsMetadata mutateRepairedMetadata(long newRepairedAt, TimeUUID newPendingRepair)
     {
+        ImmutableCoordinatorLogOffsets newOffsets = newRepairedAt != ActiveRepairService.UNREPAIRED_SSTABLE
+                                                    ? ImmutableCoordinatorLogOffsets.NONE
+                                                    : coordinatorLogOffsets;
         return new StatsMetadata(estimatedPartitionSize,
                                  estimatedCellPerPartitionCount,
                                  commitLogIntervals,
@@ -236,7 +249,7 @@ public class StatsMetadata extends MetadataComponent
                                  originatingHostId,
                                  newPendingRepair,
                                  hasPartitionLevelDeletions,
-                                 coordinatorLogOffsets,
+                                 newOffsets,
                                  firstKey,
                                  lastKey);
     }
diff --git a/src/java/org/apache/cassandra/metrics/TableMetrics.java b/src/java/org/apache/cassandra/metrics/TableMetrics.java
index 356e9c8e92..2d4c5cc66d 100644
--- a/src/java/org/apache/cassandra/metrics/TableMetrics.java
+++ b/src/java/org/apache/cassandra/metrics/TableMetrics.java
@@ -60,6 +60,7 @@ import org.apache.cassandra.metrics.Sampler.SamplerType;
 import org.apache.cassandra.schema.Schema;
 import org.apache.cassandra.schema.SchemaConstants;
 import org.apache.cassandra.service.reads.ReplicaFilteringProtection;
+import org.apache.cassandra.tcm.ClusterMetadata;
 import org.apache.cassandra.utils.EstimatedHistogram;
 import org.apache.cassandra.utils.ExpMovingAverage;
 import org.apache.cassandra.utils.MovingAverage;
@@ -209,6 +210,8 @@ public class TableMetrics
     public final Gauge<Long> bytesRepaired;
     public final Gauge<Long> bytesUnrepaired;
     public final Gauge<Long> bytesPendingRepair;
+    /** SSTables on a tracked table that can't be promoted, because they are unrepaired and contain no offsets */
+    public final Gauge<Integer> unpromotableSSTables;
     /** Number of started repairs as coordinator on this table */
     public final Counter repairsStarted;
     /** Number of completed repairs as coordinator on this table */
@@ -632,6 +635,32 @@ public class TableMetrics
             }
         });
 
+        // An unrepaired sstable with no coordinator log offsets cannot be promoted by reconciliation, because it names
+        // no mutations to reconcile, and it cannot be promoted by incremental repair once the table is fully migrated.
+        // It therefore occupies the unrepaired pool indefinitely. During migration this is the ordinary state of
+        // pre-migration data, so the gauge reports zero until the keyspace leaves migration state.
+        unpromotableSSTables = createTableGauge("UnpromotableSSTables", new Gauge<Integer>()
+        {
+            public Integer getValue()
+            {
+                if (!cfs.metadata().replicationType().isTracked())
+                    return 0;
+
+                ClusterMetadata metadata = ClusterMetadata.currentNullable();
+                if (metadata == null || metadata.mutationTrackingMigrationState.isMigrating(cfs.getKeyspaceName()))
+                    return 0;
+
+                int count = 0;
+                for (SSTableReader sstable : cfs.getSSTables(SSTableSet.CANONICAL))
+                {
+                    if (!sstable.isRepaired() && !sstable.isPendingRepair()
+                        && sstable.getSSTableMetadata().coordinatorLogOffsets.isEmpty())
+                        count++;
+                }
+                return count;
+            }
+        });
+
         bytesPendingRepair = createTableGauge("BytesPendingRepair", new Gauge<Long>()
         {
             public Long getValue()
diff --git a/src/java/org/apache/cassandra/notifications/MemtableRenewedNotification.java b/src/java/org/apache/cassandra/notifications/MemtableRenewedNotification.java
index 776c9da161..63995ab07f 100644
--- a/src/java/org/apache/cassandra/notifications/MemtableRenewedNotification.java
+++ b/src/java/org/apache/cassandra/notifications/MemtableRenewedNotification.java
@@ -17,13 +17,13 @@
  */
 package org.apache.cassandra.notifications;
 
-import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 
 public class MemtableRenewedNotification implements INotification
 {
-    public final Memtable renewed;
+    public final DomainMemtable renewed;
 
-    public MemtableRenewedNotification(Memtable renewed)
+    public MemtableRenewedNotification(DomainMemtable renewed)
     {
         this.renewed = renewed;
     }
diff --git a/src/java/org/apache/cassandra/repair/RepairJob.java b/src/java/org/apache/cassandra/repair/RepairJob.java
index 35f764c489..4522f06bae 100644
--- a/src/java/org/apache/cassandra/repair/RepairJob.java
+++ b/src/java/org/apache/cassandra/repair/RepairJob.java
@@ -295,7 +295,7 @@ public class RepairJob extends AsyncFuture<RepairResult> implements Runnable
                 cfs.metric.repairsCompleted.inc();
                 logger.info("Completing repair with excludedDeadNodes {}", session.excludedDeadNodes);
                 ConsensusMigrationRepairResult cmrs = ConsensusMigrationRepairResult.fromRepair(repairStartingEpoch, getUnchecked(accordRepair), session.repairData, doPaxosRepair, doAccordRepair, session.excludedDeadNodes, session.isIncremental);
-                MutationTrackingMigrationRepairResult mtmrs = MutationTrackingMigrationRepairResult.fromRepair(repairStartingEpoch, session.repairData, session.allReplicas, session.pullRepair, session.excludedDeadNodes, session.previewKind.isPreview());
+                MutationTrackingMigrationRepairResult mtmrs = MutationTrackingMigrationRepairResult.fromRepair(repairStartingEpoch, session.excludedDeadNodes, session.previewKind.isPreview(), session.isIncremental, session.allReplicas, session.pullRepair, session.repairData);
                 trySuccess(new RepairResult(desc, stats, cmrs, mtmrs));
             }
 
diff --git a/src/java/org/apache/cassandra/replication/ImmutableCoordinatorLogOffsets.java b/src/java/org/apache/cassandra/replication/ImmutableCoordinatorLogOffsets.java
index 441957b1e2..d2de41ca8b 100644
--- a/src/java/org/apache/cassandra/replication/ImmutableCoordinatorLogOffsets.java
+++ b/src/java/org/apache/cassandra/replication/ImmutableCoordinatorLogOffsets.java
@@ -19,13 +19,17 @@
 package org.apache.cassandra.replication;
 
 import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Comparator;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.function.Predicate;
 
 import javax.annotation.concurrent.NotThreadSafe;
 
+import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterators;
 
 import org.agrona.collections.Long2ObjectHashMap;
@@ -45,9 +49,16 @@ public class ImmutableCoordinatorLogOffsets implements CoordinatorLogOffsets<Off
 {
     private static final Logger logger = LoggerFactory.getLogger(ImmutableCoordinatorLogOffsets.class);
 
+    private static final ImmutableSet<ShortMutationId> EMPTY = ImmutableSet.of();
+
     private final ImmutableMutations mutations;
     private final ActivatedTransfers transfers;
 
+    /**
+     * materialized sorted tracked transfer key for unreconciled compaction silo assignment
+     */
+    private final ImmutableSet<ShortMutationId> transferSiloKey;
+
     private ImmutableCoordinatorLogOffsets(Builder builder)
     {
         // Important to set shouldAvoidAllocation=false, otherwise iterators are cached and not thread safe, even when immutable and read-only
@@ -58,6 +69,24 @@ public class ImmutableCoordinatorLogOffsets implements CoordinatorLogOffsets<Off
 
         this.mutations = new ImmutableMutations(ids);
         this.transfers = ActivatedTransfers.copyOf(builder.transfers);
+        this.transferSiloKey = buildTransferSiloKey(this.transfers);
+    }
+
+    private static ImmutableSet<ShortMutationId> buildTransferSiloKey(ActivatedTransfers transfers)
+    {
+        if (transfers == null || transfers.isEmpty())
+            return EMPTY;
+
+        List<ShortMutationId> ids = new ArrayList<>(2);
+        for (ShortMutationId id : transfers)
+            ids.add(id);
+        ids.sort(Comparator.naturalOrder());
+        return ImmutableSet.copyOf(ids);
+    }
+
+    public ImmutableSet<ShortMutationId> transferSiloKey()
+    {
+        return transferSiloKey;
     }
 
     @Override
@@ -147,7 +176,7 @@ public class ImmutableCoordinatorLogOffsets implements CoordinatorLogOffsets<Off
             addAll(logOffsets.mutations());
             ActivatedTransfers newTransfers = logOffsets.transfers();
             if (transfers == null)
-                transfers = newTransfers;
+                transfers = ActivatedTransfers.copyOf(newTransfers);
             else
                 transfers.addAll(newTransfers);
             return this;
@@ -175,7 +204,7 @@ public class ImmutableCoordinatorLogOffsets implements CoordinatorLogOffsets<Off
             if (other.isEmpty())
                 return this;
             if (transfers == null)
-                transfers = other;
+                transfers = ActivatedTransfers.copyOf(other);
             else
                 transfers.addAll(other);
             return this;
diff --git a/src/java/org/apache/cassandra/replication/MutationId.java b/src/java/org/apache/cassandra/replication/MutationId.java
index 4f0464799e..c14b9ca8d9 100644
--- a/src/java/org/apache/cassandra/replication/MutationId.java
+++ b/src/java/org/apache/cassandra/replication/MutationId.java
@@ -19,7 +19,6 @@ package org.apache.cassandra.replication;
 
 import java.io.IOException;
 import java.nio.ByteBuffer;
-import java.util.Comparator;
 
 import org.apache.cassandra.db.TypeSizes;
 import org.apache.cassandra.io.UnversionedSerializer;
@@ -108,12 +107,6 @@ public class MutationId extends ShortMutationId
         return "MutationId{" + hostId + ", " + hostLogId + ", " + offset + ", " + timestamp + '}';
     }
 
-    /**
-     * The comparator is intentionally not overridden by this class, since log id and offset alone
-     * are meant to uniquely identify a mutation, and only offset determines the order within a log.
-     */
-    public static final Comparator<MutationId> comparator = ShortMutationId.comparator::compare;
-
     public ByteBuffer toByteBuffer()
     {
         return ByteBuffer.allocate(16)
diff --git a/src/java/org/apache/cassandra/replication/MutationJournal.java b/src/java/org/apache/cassandra/replication/MutationJournal.java
index fa93fc7a54..22a66f61c6 100644
--- a/src/java/org/apache/cassandra/replication/MutationJournal.java
+++ b/src/java/org/apache/cassandra/replication/MutationJournal.java
@@ -220,6 +220,17 @@ public class MutationJournal
         return journal.currentActiveSegment().currentPosition();
     }
 
+    @Nullable
+    public static CommitLogPosition currentPositionOrNull()
+    {
+        MutationJournal mutationJournal = instance;
+        if (mutationJournal == null)
+            return null;
+
+        ActiveSegment<ShortMutationId, Mutation> segment = mutationJournal.journal.currentActiveSegment();
+        return segment == null ? null : segment.currentPosition();
+    }
+
     // If all Memtables associated with given segment were flushed by the time we have closed active segment
     // and opened it as static, the segment is eligible to be marked as not needing replay. The actual durable
     // recording of needsReplay=false is deferred — we record the segment in pendingClearReplay and let the
diff --git a/src/java/org/apache/cassandra/replication/MutationTrackingService.java b/src/java/org/apache/cassandra/replication/MutationTrackingService.java
index 9f6d4e395a..93291866d0 100644
--- a/src/java/org/apache/cassandra/replication/MutationTrackingService.java
+++ b/src/java/org/apache/cassandra/replication/MutationTrackingService.java
@@ -92,6 +92,7 @@ import org.apache.cassandra.tcm.ownership.ReplicaGroups;
 import org.apache.cassandra.tcm.ownership.VersionedEndpoints;
 import org.apache.cassandra.utils.FBUtilities;
 import org.apache.cassandra.utils.MBeanWrapper;
+import org.apache.cassandra.utils.NoSpamLogger;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 import static java.lang.String.format;
@@ -185,6 +186,7 @@ public class MutationTrackingService implements MutationTrackingServiceMBean
     private static final int SHARD_MULTIPLIER = 1;
 
     private static final Logger logger = LoggerFactory.getLogger(MutationTrackingService.class);
+    private static final NoSpamLogger noSpamLogger = NoSpamLogger.getLogger(logger, 1, TimeUnit.MINUTES);
 
     private final TrackedLocalReads localReads = new TrackedLocalReads();
     private ConcurrentHashMap<String, KeyspaceShards> keyspaceShards = new ConcurrentHashMap<>();
@@ -525,6 +527,42 @@ public class MutationTrackingService implements MutationTrackingServiceMBean
         }
     }
 
+    /**
+     * Register a mutation being replayed from the journal, tolerating a shard that is no longer present.
+     * <p>
+     * Unlike {@link #startWriting}, this never creates shards. {@link KeyspaceShards#make} asserts the keyspace is
+     * still tracked or migrating, which is false once a keyspace has been altered back to untracked — and that flip
+     * is instant, so unflushed journal records are routinely replayed into exactly that state on restart. Creating
+     * shards for a keyspace that is no longer tracked would also resurrect tracking state the operator has just turned
+     * off.
+     * <p>
+     * A replayed record was already registered with its shard when it was originally coordinated. If the shard is
+     * gone there is nothing left to reconcile it against, and the only thing that still has to happen is for the
+     * record to reach the memtable so the data is not lost.
+     *
+     * @return true if the record was registered with a shard, false if no shard covers it
+     */
+    public boolean startWritingForReplay(Mutation mutation)
+    {
+        shardLock.readLock().lock();
+        try
+        {
+            Preconditions.checkArgument(!mutation.id().isNone());
+            KeyspaceShards shards = keyspaceShards.get(mutation.getKeyspaceName());
+            if (shards == null)
+            {
+                noSpamLogger.info("Replaying journal record for {} with no shards; applying without registration",
+                                  mutation.getKeyspaceName());
+                return false;
+            }
+            return shards.startWritingIfShardPresent(mutation);
+        }
+        finally
+        {
+            shardLock.readLock().unlock();
+        }
+    }
+
     public void finishWriting(Mutation mutation)
     {
         shardLock.readLock().lock();
@@ -945,7 +983,8 @@ public class MutationTrackingService implements MutationTrackingServiceMBean
             if (!shardUpdateNeeded(keyspaceShards, prev, next))
                 return;
 
-            // recalculating the shards will repopulate this via the existing callbacks
+            // Emptied and repopulated by the onNewLog callbacks below. Every arm of applyUpdatedMetadata has to
+            // announce the logs of the shards it keeps, whether it rebuilds them or carries them forward.
             log2ShardMap = new ConcurrentHashMap<>();
             keyspaceShards = applyUpdatedMetadata(keyspaceShards, prev, next, this::nextLogId, this::onNewLog);
 
@@ -1019,7 +1058,10 @@ public class MutationTrackingService implements MutationTrackingServiceMBean
                     evictSegmentReferences(keyspace);
                 case NONE:
                     if (current != null)
+                    {
+                        current.reportAllLogsToCallback();
                         updated.put(keyspace, current);
+                    }
                     break;
                 case DROP:
                     // Don't carry forward the state for the dropped keyspace
@@ -1347,6 +1389,11 @@ public class MutationTrackingService implements MutationTrackingServiceMBean
             return new KeyspaceShards(keyspace.name, newShards, new ReplicaGroups(newGroups));
         }
 
+        void reportAllLogsToCallback()
+        {
+            shards.values().forEach(Shard::reportAllLogsToCallback);
+        }
+
         MutationId nextMutationId(Token token)
         {
             return lookUp(token).nextId();
@@ -1365,6 +1412,23 @@ public class MutationTrackingService implements MutationTrackingServiceMBean
             return lookUp(mutation).startWriting(mutation);
         }
 
+        /**
+         * Register a replayed mutation, returning false rather than throwing when no shard covers its token.
+         * See {@link MutationTrackingService#startWritingForReplay}.
+         */
+        boolean startWritingIfShardPresent(Mutation mutation)
+        {
+            VersionedEndpoints.ForRange forRange = groups.matchToken(mutation.key().getToken());
+            Shard shard = forRange == null ? null : shards.get(forRange.range());
+            if (shard == null)
+            {
+                noSpamLogger.info("Replaying journal record for {} with no shard covering token {}; applying without registration",
+                                  keyspace, mutation.key().getToken());
+                return false;
+            }
+            return shard.startWriting(mutation);
+        }
+
         void finishWriting(Mutation mutation)
         {
             lookUp(mutation).finishWriting(mutation);
diff --git a/src/java/org/apache/cassandra/replication/ShortMutationId.java b/src/java/org/apache/cassandra/replication/ShortMutationId.java
index 856790a8a1..6bf464d24a 100644
--- a/src/java/org/apache/cassandra/replication/ShortMutationId.java
+++ b/src/java/org/apache/cassandra/replication/ShortMutationId.java
@@ -19,7 +19,6 @@ package org.apache.cassandra.replication;
 
 import java.io.IOException;
 import java.io.Serializable;
-import java.util.Comparator;
 
 import org.apache.cassandra.db.TypeSizes;
 import org.apache.cassandra.io.UnversionedSerializer;
@@ -34,7 +33,7 @@ import static org.apache.cassandra.replication.CoordinatorLogId.NONE_LOG_ID;
  * MutationId without the timestamp component. This is sufficient for uniquely identifying a mutation,
  * and for lookup in the journal and most tracking data structures.
  */
-public class ShortMutationId implements Serializable
+public class ShortMutationId implements Serializable, Comparable<ShortMutationId>
 {
     static final int NONE_OFFSET = Integer.MIN_VALUE;
 
@@ -76,7 +75,19 @@ public class ShortMutationId implements Serializable
 
     public ShortMutationId(MutationId mutationId)
     {
-        this(mutationId.hostLogId(), mutationId.hostId(), mutationId.offset());
+        this(mutationId.hostId(), mutationId.hostLogId(), mutationId.offset());
+    }
+
+    @Override
+    public int compareTo(ShortMutationId that)
+    {
+        int cmp = Integer.compare(this.hostId, that.hostId);
+        if (cmp != 0) return cmp;
+
+        cmp = Integer.compare(this.hostLogId, that.hostLogId);
+        if (cmp != 0) return cmp;
+
+        return Integer.compare(this.offset, that.offset);
     }
 
     public int hostId()
@@ -130,11 +141,6 @@ public class ShortMutationId implements Serializable
         return "ShortMutationId{" + hostId() + ", " + hostLogId() + ", " + offset() + '}';
     }
 
-    public static final Comparator<ShortMutationId> comparator = (l, r) -> {
-        int cmp = Long.compareUnsigned(l.logId(), r.logId());
-        return cmp != 0 ? cmp : Integer.compare(l.offset, r.offset);
-    };
-
     public static final UnversionedSerializer<ShortMutationId> serializer = new UnversionedSerializer<>()
     {
         @Override
diff --git a/src/java/org/apache/cassandra/schema/MemtableParams.java b/src/java/org/apache/cassandra/schema/MemtableParams.java
index 7d88f6518e..663e70ca6d 100644
--- a/src/java/org/apache/cassandra/schema/MemtableParams.java
+++ b/src/java/org/apache/cassandra/schema/MemtableParams.java
@@ -35,7 +35,7 @@ import org.slf4j.LoggerFactory;
 import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.config.InheritingClass;
 import org.apache.cassandra.config.ParameterizedClass;
-import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.memtable.SkipListMemtableFactory;
 import org.apache.cassandra.exceptions.ConfigurationException;
 
@@ -50,10 +50,10 @@ import org.apache.cassandra.exceptions.ConfigurationException;
   */
 public final class MemtableParams
 {
-    private final Memtable.Factory factory;
+    private final DomainMemtable.Factory factory;
     private final String configurationKey;
 
-    private MemtableParams(Memtable.Factory factory, String configurationKey)
+    private MemtableParams(DomainMemtable.Factory factory, String configurationKey)
     {
         this.configurationKey = configurationKey;
         this.factory = factory;
@@ -64,7 +64,7 @@ public final class MemtableParams
         return configurationKey;
     }
 
-    public Memtable.Factory factory()
+    public DomainMemtable.Factory factory()
     {
         return factory;
     }
@@ -96,7 +96,7 @@ public final class MemtableParams
     }
 
     private static final String DEFAULT_CONFIGURATION_KEY = "default";
-    private static final Memtable.Factory DEFAULT_MEMTABLE_FACTORY = SkipListMemtableFactory.INSTANCE;
+    private static final DomainMemtable.Factory DEFAULT_MEMTABLE_FACTORY = SkipListMemtableFactory.INSTANCE;
     private static final ParameterizedClass DEFAULT_CONFIGURATION = SkipListMemtableFactory.CONFIGURATION;
     private static final Map<String, ParameterizedClass>
         CONFIGURATION_DEFINITIONS = expandDefinitions(DatabaseDescriptor.getMemtableConfigurations());
@@ -214,7 +214,7 @@ public final class MemtableParams
     }
 
 
-    private static Memtable.Factory getMemtableFactory(ParameterizedClass options)
+    private static DomainMemtable.Factory getMemtableFactory(ParameterizedClass options)
     {
         // Special-case this so that we don't initialize memtable class for tests that need to delay that.
         if (options == DEFAULT_CONFIGURATION)
@@ -227,7 +227,7 @@ public final class MemtableParams
         className = className.contains(".") ? className : "org.apache.cassandra.db.memtable." + className;
         try
         {
-            Memtable.Factory factory;
+            DomainMemtable.Factory factory;
             Class<?> clazz = Class.forName(className);
             final Map<String, String> parametersCopy = options.parameters != null
                                                        ? new HashMap<>(options.parameters)
@@ -235,13 +235,13 @@ public final class MemtableParams
             try
             {
                 Method factoryMethod = clazz.getDeclaredMethod("factory", Map.class);
-                factory = (Memtable.Factory) factoryMethod.invoke(null, parametersCopy);
+                factory = (DomainMemtable.Factory) factoryMethod.invoke(null, parametersCopy);
             }
             catch (NoSuchMethodException e)
             {
                 // continue with FACTORY field
                 Field factoryField = clazz.getDeclaredField("FACTORY");
-                factory = (Memtable.Factory) factoryField.get(null);
+                factory = (DomainMemtable.Factory) factoryField.get(null);
             }
             if (!parametersCopy.isEmpty())
                 throw new ConfigurationException("Memtable class " + className + " does not accept any futher parameters, but " +
diff --git a/src/java/org/apache/cassandra/service/accord/AccordKeyspace.java b/src/java/org/apache/cassandra/service/accord/AccordKeyspace.java
index 50d1e17d73..9adf5bc021 100644
--- a/src/java/org/apache/cassandra/service/accord/AccordKeyspace.java
+++ b/src/java/org/apache/cassandra/service/accord/AccordKeyspace.java
@@ -51,6 +51,7 @@ import org.apache.cassandra.db.Columns;
 import org.apache.cassandra.db.DataRange;
 import org.apache.cassandra.db.DecoratedKey;
 import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.PartitionPosition;
 import org.apache.cassandra.db.ReadExecutionController;
 import org.apache.cassandra.db.RegularAndStaticColumns;
@@ -355,7 +356,8 @@ public class AccordKeyspace
                 ColumnFamilyStore cfs = AccordColumnFamilyStores.commandsForKey;
                 try (OpOrder.Group group = Keyspace.writeOrder.start())
                 {
-                    cfs.getCurrentMemtable().put(MutationId.fixme(), upd, UpdateTransaction.NO_OP, group, true);
+                    cfs.getCurrentMemtable().put(MutationId.fixme(), upd, UpdateTransaction.NO_OP, group,
+                                                 LogDomain.COMMIT_LOG, true);
                 }
             };
         }
diff --git a/src/java/org/apache/cassandra/service/replication/migration/MigrationRouter.java b/src/java/org/apache/cassandra/service/replication/migration/MigrationRouter.java
index c500755cd9..1e0cdfe868 100644
--- a/src/java/org/apache/cassandra/service/replication/migration/MigrationRouter.java
+++ b/src/java/org/apache/cassandra/service/replication/migration/MigrationRouter.java
@@ -376,7 +376,7 @@ public class MigrationRouter
         return getMutationRouting(mutation) == MutationRouting.TRACKED;
     }
 
-    private static void validateMutationReplication(IMutation mutation, MutationRouting expected)
+    private static void validateMutationReplication(IMutation mutation, MutationRouting expected, boolean isReplay)
     {
         switch (expected)
         {
@@ -393,19 +393,22 @@ public class MigrationRouter
 
         }
 
+        if (isReplay)
+            return;
+
         MutationRouting actual = getMutationRouting(mutation);
         if (expected != actual)
             throw new CoordinatorBehindException("Mutation replication mismatch: expected " + expected + ", actual " + actual);
     }
 
-    public static void validateTrackedMutation(IMutation mutation)
+    public static void validateTrackedMutation(IMutation mutation, boolean isReplay)
     {
-        validateMutationReplication(mutation, MutationRouting.TRACKED);
+        validateMutationReplication(mutation, MutationRouting.TRACKED, isReplay);
     }
 
-    public static void validateUntrackedMutation(IMutation mutation)
+    public static void validateUntrackedMutation(IMutation mutation, boolean isReplay)
     {
-        validateMutationReplication(mutation, MutationRouting.UNTRACKED);
+        validateMutationReplication(mutation, MutationRouting.UNTRACKED, isReplay);
     }
 
     /**
diff --git a/src/java/org/apache/cassandra/service/replication/migration/MutationTrackingMigrationRepairResult.java b/src/java/org/apache/cassandra/service/replication/migration/MutationTrackingMigrationRepairResult.java
index fb5009f4fb..8b96a8f371 100644
--- a/src/java/org/apache/cassandra/service/replication/migration/MutationTrackingMigrationRepairResult.java
+++ b/src/java/org/apache/cassandra/service/replication/migration/MutationTrackingMigrationRepairResult.java
@@ -33,12 +33,21 @@ public class MutationTrackingMigrationRepairResult
         new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false, "dead nodes were excluded from the repair");
     private static final MutationTrackingMigrationRepairResult PREVIEW =
         new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false, "the repair was a preview");
-    private static final MutationTrackingMigrationRepairResult NO_DATA_REPAIR =
-        new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false, "the repair did not repair data (paxos-only or accord-only repair)");
+    private static final MutationTrackingMigrationRepairResult NOT_INCREMENTAL =
+        new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false,
+                                                 "the repair was not incremental, so it synced the pre-migration data " +
+                                                 "without marking it repaired; migration requires incremental repair");
     private static final MutationTrackingMigrationRepairResult NOT_ALL_REPLICAS =
-        new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false, "the repair did not include all replicas (-local, -dc, or -hosts repair)");
+        new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false,
+                                                 "not all replicas were included in the repair; " +
+                                                 "migration requires repairing all replicas");
     private static final MutationTrackingMigrationRepairResult PULL_REPAIR =
-        new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false, "the repair only streamed data one way (-pull repair)");
+        new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false,
+                                                 "the repair only streamed data one way (-pull repair)");
+    private static final MutationTrackingMigrationRepairResult DATA_NOT_REPAIRED =
+        new MutationTrackingMigrationRepairResult(Epoch.EMPTY, false,
+                                                 "data repair was not performed; " +
+                                                 "migration requires repairing table data");
 
     public final Epoch minEpoch;
     public final boolean eligible;
@@ -54,18 +63,30 @@ public class MutationTrackingMigrationRepairResult
         this.ineligibleReason = ineligibleReason;
     }
 
+    /**
+     * Only an incremental repair may advance migration. A full repair syncs the pre-migration data but leaves it
+     * unrepaired, and nothing can promote it afterwards: reconciliation has no ids to work from, and once the range is
+     * migrated incremental repair no longer anticompacts it. Incremental repair marks exactly the ranges it verified,
+     * which is why migration needs no separate promotion step at completion.
+     *
+     * A tracked keyspace with no migration in progress has its incremental flag cleared by
+     * {@link org.apache.cassandra.repair.RepairCoordinator}, but such a repair never reaches this check: the handler
+     * returns earlier because the keyspace is not migrating.
+     */
     public static MutationTrackingMigrationRepairResult fromRepair(Epoch minEpoch,
-                                                                   boolean dataRepaired,
-                                                                   boolean allReplicas,
-                                                                   boolean pullRepair,
-                                                                   boolean deadNodesExcluded,
-                                                                   boolean isPreview)
+                                                                  boolean deadNodesExcluded,
+                                                                  boolean isPreview,
+                                                                  boolean isIncremental,
+                                                                  boolean allReplicas,
+                                                                  boolean pullRepair,
+                                                                  boolean repairData)
     {
         if (deadNodesExcluded) return DEAD_NODES_EXCLUDED;
         if (isPreview) return PREVIEW;
-        if (!dataRepaired) return NO_DATA_REPAIR;
+        if (!isIncremental) return NOT_INCREMENTAL;
         if (!allReplicas) return NOT_ALL_REPLICAS;
         if (pullRepair) return PULL_REPAIR;
+        if (!repairData) return DATA_NOT_REPAIRED;
         return new MutationTrackingMigrationRepairResult(minEpoch, true, null);
     }
 }
diff --git a/test/distributed/org/apache/cassandra/distributed/test/MutationTrackingMigrationTest.java b/test/distributed/org/apache/cassandra/distributed/test/MutationTrackingMigrationTest.java
index 0ffe1ede6e..b1b3b5b8d8 100644
--- a/test/distributed/org/apache/cassandra/distributed/test/MutationTrackingMigrationTest.java
+++ b/test/distributed/org/apache/cassandra/distributed/test/MutationTrackingMigrationTest.java
@@ -21,6 +21,7 @@ package org.apache.cassandra.distributed.test;
 import java.io.IOException;
 import java.time.Duration;
 import java.util.List;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 
 import org.junit.BeforeClass;
@@ -28,10 +29,14 @@ import org.junit.Test;
 
 import org.apache.cassandra.ServerTestUtils;
 import org.apache.cassandra.config.CassandraRelevantProperties;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.Keyspace;
 import org.apache.cassandra.distributed.Cluster;
 import org.apache.cassandra.distributed.api.ConsistencyLevel;
 import org.apache.cassandra.distributed.api.Feature;
 import org.apache.cassandra.distributed.api.ICoordinator;
+import org.apache.cassandra.io.sstable.SSTableProvenance;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.replication.MutationJournal;
 import org.apache.cassandra.schema.KeyspaceMetadata;
 import org.apache.cassandra.service.replication.migration.MutationTrackingMigrationState;
@@ -43,6 +48,7 @@ import org.apache.cassandra.utils.concurrent.UncheckedInterruptedException;
 import static java.lang.String.format;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertTrue;
 
 /**
@@ -170,32 +176,289 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
         }
     }
 
+    private static void assertNoMixedSSTable(String keyspace, String table)
+    {
+        for (int nodeId = 1; nodeId <= NUM_NODES; nodeId++)
+        {
+            SHARED_CLUSTER.get(nodeId).runOnInstance(() -> {
+                ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(table);
+                for (SSTableReader sstable : cfs.getLiveSSTables())
+                {
+                    assertNotEquals("an unrepaired sstable carries both journal offsets and a commit log span, so it "
+                                    + "mixes two logs: " + sstable + ' ' + sstable.getSSTableMetadata().commitLogIntervals,
+                                    SSTableProvenance.BOTH, SSTableProvenance.of(sstable));
+                }
+            });
+        }
+    }
+
+    /**
+     * Counts, on node 1, how many of a table's sstables came out of each log.
+     *
+     * @return the journal-derived count, then the commit-log-derived count
+     */
+    private static int[] countByProvenance(String keyspace, String table)
+    {
+        return SHARED_CLUSTER.get(1).callOnInstance(() -> {
+            int journalDerived = 0;
+            int commitLogDerived = 0;
+            ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(table);
+            for (SSTableReader sstable : cfs.getLiveSSTables())
+            {
+                switch (SSTableProvenance.of(sstable))
+                {
+                    case MUTATION_JOURNAL:
+                        journalDerived++;
+                        break;
+                    case COMMIT_LOG:
+                        commitLogDerived++;
+                        break;
+                    default:
+                        break;
+                }
+            }
+            return new int[]{ journalDerived, commitLogDerived };
+        });
+    }
+
+    private static void flushEverywhere(String keyspace, String table)
+    {
+        for (int nodeId = 1; nodeId <= NUM_NODES; nodeId++)
+            SHARED_CLUSTER.get(nodeId).nodetoolResult("flush", keyspace, table).asserts().success();
+    }
+
+    private static void insert(String keyspace, String table, int from, int to, String tag)
+    {
+        for (int i = from; i < to; i++)
+            coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (%d, '%s_%d')",
+                                       keyspace, table, i, tag, i),
+                                ConsistencyLevel.QUORUM);
+    }
+
+    private static void createKeyspaceWithTable(String keyspace, String replicationType)
+    {
+        coordinator.execute(format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', "
+                                   + "'replication_factor': 3} AND replication_type='%s'", keyspace, replicationType),
+                            ConsistencyLevel.ALL);
+        coordinator.execute(format("CREATE TABLE %s.%s (pk int PRIMARY KEY, value text)", keyspace, TEST_TABLE),
+                            ConsistencyLevel.ALL);
+        waitForEpochOf(SHARED_CLUSTER, 1);
+    }
+
+    private static void alterReplicationType(String keyspace, String replicationType)
+    {
+        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', "
+                                   + "'replication_factor': 3} AND replication_type='%s'", keyspace, replicationType),
+                            ConsistencyLevel.ALL);
+        waitForEpochOf(SHARED_CLUSTER, 1);
+    }
+
+    /**
+     * Counts, across every node, the sstables a repair session has claimed - either moved into its pending repair
+     * bucket or already promoted to repaired. Split by whether the sstable carries coordinator log offsets.
+     *
+     * @return the count carrying offsets, then the count carrying none
+     */
+    private static int[] countClaimedByRepair(String keyspace, String table)
+    {
+        int withOffsets = 0;
+        int withoutOffsets = 0;
+        for (int nodeId = 1; nodeId <= NUM_NODES; nodeId++)
+        {
+            int[] counts = SHARED_CLUSTER.get(nodeId).callOnInstance(() -> {
+                int tracked = 0;
+                int untracked = 0;
+                ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(table);
+                for (SSTableReader sstable : cfs.getLiveSSTables())
+                {
+                    if (!sstable.isPendingRepair() && !sstable.isRepaired())
+                        continue;
+                    if (sstable.getSSTableMetadata().coordinatorLogOffsets.isEmpty())
+                        untracked++;
+                    else
+                        tracked++;
+                }
+                return new int[]{ tracked, untracked };
+            });
+            withOffsets += counts[0];
+            withoutOffsets += counts[1];
+        }
+        return new int[]{ withOffsets, withoutOffsets };
+    }
+
+    private static int countWithOffsets(String keyspace, String table)
+    {
+        int total = 0;
+        for (int nodeId = 1; nodeId <= NUM_NODES; nodeId++)
+            total += SHARED_CLUSTER.get(nodeId).callOnInstance(() -> {
+                int count = 0;
+                ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(table);
+                for (SSTableReader sstable : cfs.getLiveSSTables())
+                    if (!sstable.getSSTableMetadata().coordinatorLogOffsets.isEmpty())
+                        count++;
+                return count;
+            });
+        return total;
+    }
+
+    /**
+     * Incremental repair must not anticompact an sstable carrying coordinator log offsets. Anticompaction sets
+     * repairedAt, which clears the offsets recording which mutations the sstable holds, so reconciliation could no
+     * longer see this replica as holding them. Tracked data reaches the repaired set through promotion instead.
+     *
+     * The migration window is what produces the mixed population: the ALTER puts the full ring pending while writes
+     * already route tracked, so the table holds commit-log-derived and offset-bearing sstables at once.
+     */
     @Test
-    public void testUntrackedToTrackedMigration() throws Exception
+    public void incrementalRepairLeavesOffsetBearingSSTablesUnrepaired() throws Exception
     {
-        String testKeyspace = "untracked_to_tracked_test";
+        String testKeyspace = "ks_incremental_repair_offsets";
+        createKeyspaceWithTable(testKeyspace, "untracked");
+        for (int nodeId = 1; nodeId <= NUM_NODES; nodeId++)
+            SHARED_CLUSTER.get(nodeId).nodetoolResult("disableautocompaction", testKeyspace, TEST_TABLE).asserts().success();
 
-        // untracked keyspace
-        coordinator.execute(format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='untracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
+        insert(testKeyspace, TEST_TABLE, 0, 20, "untracked");
+        flushEverywhere(testKeyspace, TEST_TABLE);
 
+        alterReplicationType(testKeyspace, "tracked");
+        insert(testKeyspace, TEST_TABLE, 20, 40, "tracked");
+        flushEverywhere(testKeyspace, TEST_TABLE);
 
-        coordinator.execute(format("CREATE TABLE %s.%s (pk int PRIMARY KEY, value text)", testKeyspace, TEST_TABLE),
-                          ConsistencyLevel.ALL);
+        assertTrue("the migration window must leave offset-bearing sstables for repair to encounter",
+                   countWithOffsets(testKeyspace, TEST_TABLE) > 0);
+
+        SHARED_CLUSTER.get(1).nodetoolResult("repair", testKeyspace, TEST_TABLE).asserts().success();
+
+        int[] claimed = countClaimedByRepair(testKeyspace, TEST_TABLE);
+        assertEquals("incremental repair must not claim an sstable carrying coordinator log offsets",
+                     0, claimed[0]);
+        // Proves the filter is selective rather than excluding everything: the commit-log-derived sstables carry no
+        // offsets, so repair still claims them.
+        assertTrue("repair must still claim the sstables that carry no offsets", claimed[1] > 0);
+    }
+
+    /**
+     * Rolling the migration back leaves offset-bearing sstables on disk that nothing will ever reconcile. A background
+     * compaction round discards their offsets, after which incremental repair claims them like any other unrepaired
+     * sstable. Before that discard existed, the offsets stayed for the life of the process and the UNRECONCILED holder
+     * kept refusing them, which failed every repair and every compaction for the table.
+     */
+    @Test
+    public void rollbackDiscardsOffsetsSoRepairCanProceed() throws Exception
+    {
+        String testKeyspace = "ks_rollback_discards_offsets";
+        createKeyspaceWithTable(testKeyspace, "untracked");
+
+        insert(testKeyspace, TEST_TABLE, 0, 20, "untracked");
+        flushEverywhere(testKeyspace, TEST_TABLE);
+
+        alterReplicationType(testKeyspace, "tracked");
+        insert(testKeyspace, TEST_TABLE, 20, 40, "tracked");
+        flushEverywhere(testKeyspace, TEST_TABLE);
+        assertTrue("precondition: a flush inside the migration's pending ranges must carry offsets",
+                   countWithOffsets(testKeyspace, TEST_TABLE) > 0);
+
+        alterReplicationType(testKeyspace, "untracked");
+
+        // A flush is what asks a node for a background compaction round, which is where the discard happens.
+        insert(testKeyspace, TEST_TABLE, 40, 60, "after_rollback");
+        flushEverywhere(testKeyspace, TEST_TABLE);
+
+        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60);
+        while (countWithOffsets(testKeyspace, TEST_TABLE) > 0 && System.nanoTime() < deadline)
+            Thread.sleep(500);
+        assertEquals("the rollback must leave no sstable claiming journal provenance",
+                     0, countWithOffsets(testKeyspace, TEST_TABLE));
+
+        SHARED_CLUSTER.get(1).nodetoolResult("repair", testKeyspace, TEST_TABLE).asserts().success();
+
+        int[] claimed = countClaimedByRepair(testKeyspace, TEST_TABLE);
+        assertEquals("nothing may still carry offsets once repair has claimed it", 0, claimed[0]);
+        assertTrue("repair must claim the sstables the rollback released", claimed[1] > 0);
+    }
+
+    /**
+     * Check sstable provenance info correctness across migration to and from tracked replication
+     */
+    @Test
+    public void sstableProvenanceCorrectnessAcrossMigrationAndReversal() throws Exception
+    {
+        String testKeyspace = "migration_bounds_test";
 
+        createKeyspaceWithTable(testKeyspace, "untracked");
+
+        // Untracked: everything is commit-log-derived.
+        insert(testKeyspace, TEST_TABLE, 0, 50, "untracked");
+        flushEverywhere(testKeyspace, TEST_TABLE);
+        assertNoMixedSSTable(testKeyspace, TEST_TABLE);
+        assertEquals("an untracked table produces no journal-derived sstable",
+                     0, countByProvenance(testKeyspace, TEST_TABLE)[0]);
+
+        alterReplicationType(testKeyspace, "tracked");
+        verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.MIGRATING_TO_TRACKED);
+
+        insert(testKeyspace, TEST_TABLE, 50, 100, "migrating");
+        flushEverywhere(testKeyspace, TEST_TABLE);
+        assertNoMixedSSTable(testKeyspace, TEST_TABLE);
+
+        // Repair only the primary range, so some ranges complete and some stay pending. From here the two logs take
+        // writes for the same table.
+        SHARED_CLUSTER.get(1).nodetoolResult("repair", "-pr", testKeyspace, TEST_TABLE).asserts().success();
         waitForEpochOf(SHARED_CLUSTER, 1);
+        verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.MIGRATING_TO_TRACKED);
+
+        insert(testKeyspace, TEST_TABLE, 100, 200, "partial");
+        flushEverywhere(testKeyspace, TEST_TABLE);
+        assertNoMixedSSTable(testKeyspace, TEST_TABLE);
+        int[] partial = countByProvenance(testKeyspace, TEST_TABLE);
+        assertTrue("a partially migrated table should have taken journal writes; counts were "
+                   + partial[0] + " journal-derived, " + partial[1] + " commit-log-derived",
+                   partial[0] > 0);
+
+        // Repeated flush rounds while both logs are in use, which is the steady state a long migration sits in.
+        int rowsPerRound = 40;
+        int rounds = 10;
+        for (int round = 0; round < rounds; round++)
+        {
+            insert(testKeyspace, TEST_TABLE, 200 + round * rowsPerRound, 200 + (round + 1) * rowsPerRound,
+                   "round" + round);
+            flushEverywhere(testKeyspace, TEST_TABLE);
+            assertNoMixedSSTable(testKeyspace, TEST_TABLE);
+        }
+
+        int[] steadyState = countByProvenance(testKeyspace, TEST_TABLE);
+        assertTrue("the table should still hold sstables from both logs; counts were "
+                   + steadyState[0] + " journal-derived, " + steadyState[1] + " commit-log-derived",
+                   steadyState[0] > 0 && steadyState[1] > 0);
+
+        // tracked -> untracked is instant, so routing goes back to the commit log with no pending window.
+        int afterRounds = 200 + rowsPerRound * rounds;
+        alterReplicationType(testKeyspace, "untracked");
+        verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.UNTRACKED);
+
+        insert(testKeyspace, TEST_TABLE, afterRounds, afterRounds + 50, "reversed");
+        flushEverywhere(testKeyspace, TEST_TABLE);
+        assertNoMixedSSTable(testKeyspace, TEST_TABLE);
+
+        Object[][] results = coordinator.execute(format("SELECT * FROM %s.%s", testKeyspace, TEST_TABLE),
+                                                ConsistencyLevel.QUORUM);
+        assertEquals("no write is lost across the migration, the steady state and the reversal",
+                     afterRounds + 50, results.length);
+    }
+
+    @Test
+    public void testUntrackedToTrackedMigration() throws Exception
+    {
+        String testKeyspace = "untracked_to_tracked_test";
+
+        // untracked keyspace
+        createKeyspaceWithTable(testKeyspace, "untracked");
 
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.UNTRACKED);
 
         long journalEntriesBefore = countJournalEntries();
 
-        for (int i = 0; i < 100; i++)
-        {
-            coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (%d, 'initial_%d')",
-                                     testKeyspace, TEST_TABLE, i, i),
-                              ConsistencyLevel.QUORUM);
-        }
+        insert(testKeyspace, TEST_TABLE, 0, 100, "initial");
 
         // no journal entries written while untracked
         long journalEntriesAfterUntracked = countJournalEntries();
@@ -206,22 +469,13 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
         assertEquals(100, initialResults.length);
 
         // start migration to tracked replication
-        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='tracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        alterReplicationType(testKeyspace, "tracked");
 
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.MIGRATING_TO_TRACKED);
 
         long journalEntriesBeforeMigrationWrites = countJournalEntries();
 
-        for (int i = 100; i < 200; i++)
-        {
-            coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (%d, 'migration_%d')",
-                                     testKeyspace, TEST_TABLE, i, i),
-                              ConsistencyLevel.QUORUM);
-        }
+        insert(testKeyspace, TEST_TABLE, 100, 200, "migration");
 
         // writes should be tracked during migration
         long journalEntriesAfterMigrationWrites = countJournalEntries();
@@ -252,12 +506,7 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
 
         long journalEntriesBeforeTracked = countJournalEntries();
 
-        for (int i = 200; i < 210; i++)
-        {
-            coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (%d, 'tracked_%d')",
-                                     testKeyspace, TEST_TABLE, i, i),
-                              ConsistencyLevel.QUORUM);
-        }
+        insert(testKeyspace, TEST_TABLE, 200, 210, "tracked");
 
         // writes should also be tracked after migration
         long journalEntriesAfterTracked = countJournalEntries();
@@ -282,25 +531,13 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
         String testKeyspace = "tracked_to_untracked_test";
 
         // tracked keyspace
-        coordinator.execute(format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='tracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        coordinator.execute(format("CREATE TABLE %s.%s (pk int PRIMARY KEY, value text)", testKeyspace, TEST_TABLE),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        createKeyspaceWithTable(testKeyspace, "tracked");
 
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.TRACKED);
 
         long journalEntriesBefore = countJournalEntries();
 
-        for (int i = 0; i < 100; i++)
-        {
-            coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (%d, 'initial_%d')",
-                                     testKeyspace, TEST_TABLE, i, i),
-                              ConsistencyLevel.QUORUM);
-        }
+        insert(testKeyspace, TEST_TABLE, 0, 100, "initial");
 
         // writes should be tracked before migration
         long journalEntriesAfterTracked = countJournalEntries();
@@ -310,24 +547,15 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
                                                        ConsistencyLevel.QUORUM);
         assertEquals(100, initialResults.length);
 
-        // switch to untracked replication — tracked→untracked is instant, no migration needed
-        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='untracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        // switch to untracked replication - tracked→untracked is instant, no migration needed
+        alterReplicationType(testKeyspace, "untracked");
 
-        // Should go directly to UNTRACKED — no migration state
+        // Should go directly to UNTRACKED - no migration state
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.UNTRACKED);
 
         long journalEntriesBeforeUntracked = countJournalEntries();
 
-        for (int i = 100; i < 210; i++)
-        {
-            coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (%d, 'untracked_%d')",
-                                     testKeyspace, TEST_TABLE, i, i),
-                              ConsistencyLevel.QUORUM);
-        }
+        insert(testKeyspace, TEST_TABLE, 100, 210, "untracked");
 
         // writes should not be tracked after instant switch to untracked
         long journalEntriesAfterUntracked = countJournalEntries();
@@ -349,51 +577,26 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
         String testKeyspace = "migration_reversal_test";
 
         // untracked keyspace
-        coordinator.execute(format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='untracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        coordinator.execute(format("CREATE TABLE %s.%s (pk int PRIMARY KEY, value text)", testKeyspace, TEST_TABLE),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        createKeyspaceWithTable(testKeyspace, "untracked");
 
-        for (int i = 0; i < 50; i++)
-        {
-            coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (%d, 'initial_%d')",
-                                     testKeyspace, TEST_TABLE, i, i),
-                              ConsistencyLevel.QUORUM);
-        }
+        insert(testKeyspace, TEST_TABLE, 0, 50, "initial");
 
         // Start migration to tracked
-        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='tracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        alterReplicationType(testKeyspace, "tracked");
 
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.MIGRATING_TO_TRACKED);
 
-        for (int i = 50; i < 100; i++)
-        {
-            coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (%d, 'migrating_%d')",
-                                     testKeyspace, TEST_TABLE, i, i),
-                              ConsistencyLevel.QUORUM);
-        }
+        insert(testKeyspace, TEST_TABLE, 50, 100, "migrating");
 
         // only repair the primary range so the migration isn't complete and we have something to reverse
         SHARED_CLUSTER.get(1).nodetoolResult("repair", "-pr", testKeyspace, TEST_TABLE).asserts().success();
         waitForEpochOf(SHARED_CLUSTER, 1);
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.MIGRATING_TO_TRACKED);
 
-        // Reverse the migration by changing back to untracked — tracked→untracked is instant
-        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='untracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        // Reverse the migration by changing back to untracked - tracked→untracked is instant
+        alterReplicationType(testKeyspace, "untracked");
 
-        // Should go directly to UNTRACKED — no migration state
+        // Should go directly to UNTRACKED - no migration state
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.UNTRACKED);
 
         Object[][] results = coordinator.execute(format("SELECT * FROM %s.%s", testKeyspace, TEST_TABLE),
@@ -415,21 +618,10 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
         String newTable = "tbl2";
 
         // untracked keyspace
-        coordinator.execute(format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='untracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        coordinator.execute(format("CREATE TABLE %s.%s (pk int PRIMARY KEY, value text)", testKeyspace, TEST_TABLE),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        createKeyspaceWithTable(testKeyspace, "untracked");
 
         // Start migration to tracked
-        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='tracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        alterReplicationType(testKeyspace, "tracked");
 
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.MIGRATING_TO_TRACKED);
 
@@ -442,14 +634,10 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
         coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (1, 'new_table_data')", testKeyspace, newTable),
                           ConsistencyLevel.QUORUM);
 
-        // Reverse the migration — tracked→untracked is instant
-        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='untracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        // Reverse the migration - tracked→untracked is instant
+        alterReplicationType(testKeyspace, "untracked");
 
-        // Should go directly to UNTRACKED — no migration state
+        // Should go directly to UNTRACKED - no migration state
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.UNTRACKED);
 
         Object[][] results = coordinator.execute(format("SELECT value FROM %s.%s WHERE pk = 1", testKeyspace, newTable),
@@ -488,11 +676,7 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
                           ConsistencyLevel.QUORUM);
 
         // Start migration to tracked
-        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='tracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        alterReplicationType(testKeyspace, "tracked");
 
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.MIGRATING_TO_TRACKED);
 
@@ -529,24 +713,13 @@ public class MutationTrackingMigrationTest extends TestBaseImpl
         String testKeyspace = "keyspace_dropped_test";
 
         // untracked keyspace
-        coordinator.execute(format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='untracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        coordinator.execute(format("CREATE TABLE %s.%s (pk int PRIMARY KEY, value text)", testKeyspace, TEST_TABLE),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        createKeyspaceWithTable(testKeyspace, "untracked");
 
         coordinator.execute(format("INSERT INTO %s.%s (pk, value) VALUES (1, 'test_data')", testKeyspace, TEST_TABLE),
                           ConsistencyLevel.QUORUM);
 
         // Start migration to tracked
-        coordinator.execute(format("ALTER KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3} AND replication_type='tracked'",
-                                 testKeyspace),
-                          ConsistencyLevel.ALL);
-
-        waitForEpochOf(SHARED_CLUSTER, 1);
+        alterReplicationType(testKeyspace, "tracked");
 
         verifyKeyspaceState(testKeyspace, ExpectedKeyspaceState.MIGRATING_TO_TRACKED);
 
diff --git a/test/distributed/org/apache/cassandra/distributed/test/tracking/CommitLogReplayRoutingTest.java b/test/distributed/org/apache/cassandra/distributed/test/tracking/CommitLogReplayRoutingTest.java
new file mode 100644
index 0000000000..0e35d71dfc
--- /dev/null
+++ b/test/distributed/org/apache/cassandra/distributed/test/tracking/CommitLogReplayRoutingTest.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.distributed.test.tracking;
+
+import java.io.IOException;
+import java.util.Set;
+
+import org.junit.Test;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.ConsistencyLevel;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.io.sstable.SSTableProvenance;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.service.StorageService;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Commit log replay must route onto the untracked apply path, not consult schema
+ */
+public class CommitLogReplayRoutingTest extends TestBaseImpl
+{
+    private static final String TABLE = "tbl";
+
+    /**
+     * An untracked write, left unflushed, whose keyspace is then migrated to tracked.
+     */
+    @Test
+    public void replayAppliesUntrackedRecordAfterMigrationToTracked() throws IOException
+    {
+        assertRecordsReplayAcrossAlter("untracked", "tracked");
+    }
+
+    /**
+     * A tracked keyspace altered back to untracked with unflushed journal records.
+     */
+    @Test
+    public void replayAppliesTrackedRecordAfterFlipToUntracked() throws IOException
+    {
+        assertRecordsReplayAcrossAlter("tracked", "untracked");
+    }
+
+    /**
+     * Writes ten records under one replication type, alters the keyspace to the other, and restarts. The records are in
+     * whichever log the first type routes to, and current metadata disagrees with them by the time replay runs.
+     */
+    private void assertRecordsReplayAcrossAlter(String before, String after) throws IOException
+    {
+        // NATIVE_PROTOCOL so isNativeTransportRunning() is meaningful; without it the transport never starts.
+        try (Cluster cluster = init(builder().withNodes(1)
+                                            .withConfig(c -> c.with(Feature.NATIVE_PROTOCOL))
+                                            .start()))
+        {
+            IInvokableInstance node = cluster.get(1);
+
+            cluster.schemaChange("ALTER KEYSPACE " + KEYSPACE + " WITH replication_type='" + before + '\'');
+            cluster.schemaChange(withKeyspace("CREATE TABLE %s." + TABLE + " (k int PRIMARY KEY, v int)"));
+
+            for (int k = 0; k < 10; k++)
+                cluster.coordinator(1).execute(withKeyspace("INSERT INTO %s." + TABLE + " (k, v) VALUES (?, ?)"),
+                                               ConsistencyLevel.ALL, k, k);
+            assertNoSSTables(node);
+
+            cluster.schemaChange("ALTER KEYSPACE " + KEYSPACE + " WITH replication_type='" + after + '\'');
+            assertNoSSTables(node);
+
+            restart(node);
+
+            assertTrue("replay must not have stopped the native transport",
+                       node.callOnInstance(() -> StorageService.instance.isNativeTransportRunning()));
+
+            Object[][] rows = cluster.coordinator(1).execute(withKeyspace("SELECT k, v FROM %s." + TABLE),
+                                                             ConsistencyLevel.ALL);
+            assertEquals("every record written as " + before + " should have been replayed", 10, rows.length);
+        }
+    }
+
+    /**
+     * A token with unflushed writes in both logs replays from both.
+     */
+    @Test
+    public void replayAppliesBothLogsForSameToken() throws IOException
+    {
+        try (Cluster cluster = init(builder().withNodes(1).start()))
+        {
+            IInvokableInstance node = cluster.get(1);
+
+            cluster.schemaChange("ALTER KEYSPACE " + KEYSPACE + " WITH replication_type='untracked'");
+            cluster.schemaChange(withKeyspace("CREATE TABLE %s." + TABLE + " (k int, c int, v int, PRIMARY KEY (k, c))"));
+
+            // Untracked write for k=0 -> commit log.
+            cluster.coordinator(1).execute(withKeyspace("INSERT INTO %s." + TABLE + " (k, c, v) VALUES (0, 0, 0)"),
+                                           ConsistencyLevel.ALL);
+            assertNoSSTables(node);
+
+            // Migrating the keyspace routes subsequent writes to the journal.
+            cluster.schemaChange("ALTER KEYSPACE " + KEYSPACE + " WITH replication_type='tracked'");
+
+            // Tracked write for the same partition -> mutation journal.
+            cluster.coordinator(1).execute(withKeyspace("INSERT INTO %s." + TABLE + " (k, c, v) VALUES (0, 1, 1)"),
+                                           ConsistencyLevel.ALL);
+            assertNoSSTables(node);
+
+            restart(node);
+
+            Object[][] rows = cluster.coordinator(1).execute(withKeyspace("SELECT c, v FROM %s." + TABLE + " WHERE k = 0"),
+                                                             ConsistencyLevel.ALL);
+            assertEquals("both logs should have replayed for the same token", 2, rows.length);
+
+            assertReplayLandsInSeparateSSTables(node);
+        }
+    }
+
+    private static void assertReplayLandsInSeparateSSTables(IInvokableInstance node)
+    {
+        node.runOnInstance(() -> {
+            ColumnFamilyStore cfs = Keyspace.open(KEYSPACE).getColumnFamilyStore(TABLE);
+            cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+
+            Set<SSTableReader> sstables = cfs.getLiveSSTables();
+            assertEquals("one sstable per domain: " + sstables, 2, sstables.size());
+
+            int withSpan = 0;
+            for (SSTableReader sstable : sstables)
+            {
+                SSTableProvenance provenance = SSTableProvenance.of(sstable);
+                assertNotEquals("an sstable claims both logs: " + sstable, SSTableProvenance.BOTH, provenance);
+                if (provenance == SSTableProvenance.COMMIT_LOG)
+                    withSpan++;
+            }
+            assertEquals("exactly one sstable claims a commit log span, and the journal-derived one claims none: "
+                         + sstables, 1, withSpan);
+        });
+    }
+
+    private static void restart(IInvokableInstance node)
+    {
+        ClusterUtils.stopUnchecked(node);
+        node.startup();
+    }
+
+    private static void assertNoSSTables(IInvokableInstance node)
+    {
+        node.runOnInstance(() -> {
+            ColumnFamilyStore cfs = Keyspace.open(KEYSPACE).getColumnFamilyStore(TABLE);
+            // The records must still be in the log only, or the restart replays nothing and the test proves nothing.
+            assertTrue("already flushed: " + cfs.getLiveSSTables(), cfs.getLiveSSTables().isEmpty());
+            assertFalse(cfs.getTracker().getView().getCurrentMemtable().isClean());
+        });
+    }
+}
diff --git a/test/distributed/org/apache/cassandra/distributed/test/tracking/TrackedImportFailureTest.java b/test/distributed/org/apache/cassandra/distributed/test/tracking/TrackedImportFailureTest.java
index ee897a3188..19fc8f9f0f 100644
--- a/test/distributed/org/apache/cassandra/distributed/test/tracking/TrackedImportFailureTest.java
+++ b/test/distributed/org/apache/cassandra/distributed/test/tracking/TrackedImportFailureTest.java
@@ -21,7 +21,6 @@ package org.apache.cassandra.distributed.test.tracking;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.util.Collections;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
@@ -34,23 +33,18 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.cassandra.db.ColumnFamilyStore;
-import org.apache.cassandra.db.marshal.Int32Type;
-import org.apache.cassandra.dht.Murmur3Partitioner;
 import org.apache.cassandra.distributed.Cluster;
 import org.apache.cassandra.distributed.api.ConsistencyLevel;
 import org.apache.cassandra.distributed.api.ICoordinator;
 import org.apache.cassandra.distributed.api.IInvokableInstance;
 import org.apache.cassandra.distributed.api.IIsolatedExecutor;
 import org.apache.cassandra.distributed.shared.AssertUtils;
-import org.apache.cassandra.distributed.shared.ClusterUtils;
 import org.apache.cassandra.distributed.shared.Uninterruptibles;
 import org.apache.cassandra.exceptions.ReadTimeoutException;
 import org.apache.cassandra.io.UnversionedSerializer;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.io.util.File;
-import org.apache.cassandra.replication.ActivatedTransfers;
 import org.apache.cassandra.replication.ActivationRequest;
-import org.apache.cassandra.replication.ShortMutationId;
 import org.apache.cassandra.tcm.ClusterMetadata;
 import org.apache.cassandra.tcm.ownership.DataPlacement;
 
@@ -206,104 +200,74 @@ public class TrackedImportFailureTest extends TrackedTransferTestBase
         }
     }
 
-    /*
-     * Ensure that activation IDs attached to SSTables aren't spread across Token boundaries by compaction.
-     *
-     * For example:
-     * IMPORT_TOKEN is owned by replicas (A, B)
-     * OUTSIDE_IMPORT_TOKEN is owned by replicas (B, C)
-     * Execute import so (A, B) have IMPORT_TOKEN
-     * Execute plain write so (B, C) have OUTSIDE_IMPORT_TOKEN
-     * Do a major compaction on B so IMPORT_TOKEN and OUTSIDE_IMPORT_TOKEN are compacted together into the same SSTable
-     * Execute a data read for OUTSIDE_IMPORT_TOKEN against B, ensure it doesn't contain any activation IDs
-     */
     @Test
-    public void importActivationMergedByCompaction() throws Throwable
+    public void majorCompactionPromotesReconciledImportActivation() throws Throwable
     {
         try (Cluster cluster = cluster((cl, tg, instance, gen) -> ByteBuddyInjections.SkipPurgeTransfers.install().initialise(cl, tg, instance, gen)))
         {
             createSchema(cluster, 2);
 
-            Set<IInvokableInstance> inImportRange = new HashSet<>();
-            cluster.forEach(instance -> {
-                logger.debug("Instance {} ring is {}", ClusterUtils.instanceId(instance), ClusterUtils.ring(instance));
-                boolean isInRange = instance.callOnInstance(() -> {
+            // The import needs a replica of IMPORT_TOKEN to run on. Any of them will do.
+            IInvokableInstance importReplica = null;
+            for (IInvokableInstance instance : cluster)
+            {
+                boolean isReplica = instance.callOnInstance(() -> {
                     ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(KEYSPACE, TABLE);
                     DataPlacement placement = ClusterMetadata.current().placements.get(cfs.keyspace.getMetadata().params.replication);
                     return placement.writes.forToken(IMPORT_TOKEN).get().containsSelf();
                 });
-                if (isInRange)
-                    inImportRange.add(instance);
-            });
-            Assertions.assertThat(inImportRange).hasSize(2);
+                if (isReplica)
+                {
+                    importReplica = instance;
+                    break;
+                }
+            }
+            Assertions.assertThat(importReplica).isNotNull();
 
-            // Find a partition key that's not owned by the same replicas as the import
-            Murmur3Partitioner.LongToken NON_IMPORT_TOKEN = new Murmur3Partitioner.LongToken(IMPORT_TOKEN.getLongValue() * 3);
-            int NON_IMPORT_PK = Int32Type.instance.compose(Murmur3Partitioner.LongToken.keyForToken(NON_IMPORT_TOKEN));
+            doImport(cluster, importReplica);
+            assertLocalSelect(Collections.singleton(importReplica),
+                              (IIsolatedExecutor.SerializableConsumer<Object[][]>) rows -> {
+                                  assertRows(rows, row(IMPORT_PK, IMPORT_PK));
+                              });
 
-            Set<IInvokableInstance> inNonImportRange = new HashSet<>();
-            cluster.forEach(instance -> {
-                boolean isInRange = instance.callOnInstance(() -> {
-                    ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(KEYSPACE, TABLE);
-                    DataPlacement placement = ClusterMetadata.current().placements.get(cfs.keyspace.getMetadata().params.replication);
-                    return placement.writes.forToken(NON_IMPORT_TOKEN).get().containsSelf();
-                });
-                if (isInRange)
-                    inNonImportRange.add(instance);
+            // The import has to have left an activation behind, or the promotion asserted below proves nothing.
+            importReplica.runOnInstance(() -> {
+                ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(KEYSPACE, TABLE);
+                Assertions.assertThat(cfs.getLiveSSTables())
+                          .describedAs("the import should have left an activated transfer")
+                          .anyMatch(sstable -> !sstable.getCoordinatorLogOffsets().transfers().isEmpty());
             });
-            Assertions.assertThat(inNonImportRange).hasSize(2);
-            Assertions.assertThat(inNonImportRange).isNotEqualTo(inImportRange);
-
-            // Import: (A, B)
-            // Plain: (B, C)
-            IInvokableInstance A = null;
-            IInvokableInstance B = null;
-            IInvokableInstance C = null;
-            for (IInvokableInstance instance : cluster)
-            {
-                boolean isImport = inImportRange.contains(instance);
-                boolean isNonImport = inNonImportRange.contains(instance);
-                if (isImport && isNonImport)
-                    B = instance;
-                else if (isImport)
-                    A = instance;
-                else if (isNonImport)
-                    C = instance;
-            }
-            Assertions.assertThat(A).isNotNull();
-            Assertions.assertThat(B).isNotNull();
-            Assertions.assertThat(C).isNotNull();
 
-            doImport(cluster, A);
-            assertLocalSelect(List.of(A, B), (IIsolatedExecutor.SerializableConsumer<Object[][]>) rows -> {
-                assertRows(rows, row(IMPORT_PK, IMPORT_PK));
-            });
+            // Any second partition will do now that replica placement does not matter. At ALL, so every node holds an
+            // sstable with no transfer for the compaction to find beside the import's.
+            int otherPk = IMPORT_PK + 1;
+            cluster.coordinator(1).execute(withKeyspace("INSERT INTO %s." + TABLE + "(k, v) VALUES (?, ?)"),
+                                           ConsistencyLevel.ALL, otherPk, otherPk);
+            assertCompaction(cluster, Collections.singleton(importReplica), NOOP, NOOP);
 
-            ShortMutationId importTransferId = callSerialized(A, () -> ShortMutationId.serializer, () -> {
+            importReplica.runOnInstance(() -> {
                 ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(KEYSPACE, TABLE);
+                int repaired = 0;
                 for (SSTableReader sstable : cfs.getLiveSSTables())
                 {
-                    ActivatedTransfers transfers = sstable.getCoordinatorLogOffsets().transfers();
-                    if (!transfers.isEmpty())
-                        return transfers.iterator().next();
+                    Assertions.assertThat(sstable.getCoordinatorLogOffsets().transfers())
+                              .describedAs("promotion should have cleared the offsets of %s", sstable)
+                              .isEmpty();
+                    if (sstable.isRepaired())
+                        repaired++;
                 }
-                return null;
+                Assertions.assertThat(repaired)
+                          .describedAs("promotion should have taken the transfer and nothing else")
+                          .isEqualTo(1);
             });
-            Assertions.assertThat(importTransferId).isNotNull();
-            C.coordinator().execute(withKeyspace("INSERT INTO %s." + TABLE + "(k, v) VALUES (?, ?)"), ConsistencyLevel.ALL, NON_IMPORT_PK, NON_IMPORT_PK);
-            assertCompaction(cluster, Collections.singleton(B), NOOP, NOOP);
-
-            // Reading from B for a range that doesn't include the import shouldn't include any transfer IDs, even though they've been compacted together
-            long mark = B.logs().mark();
-            Object[][] rows = B.coordinator().execute(withKeyspace("SELECT * FROM %s." + TABLE + " WHERE k = ?"), ConsistencyLevel.ALL, NON_IMPORT_PK);
-            assertRows(rows, row(NON_IMPORT_PK, NON_IMPORT_PK));
-            Assertions.assertThat(B.logs().grep(mark, "Found overlapping activation ID ").getResult()).isEmpty();
-
-            // But if the read range does include a transfer ID, it should have been added
-            mark = B.logs().mark();
-            rows = B.coordinator().execute(withKeyspace("SELECT * FROM %s." + TABLE + " WHERE k = ?"), ConsistencyLevel.ALL, IMPORT_PK);
-            assertRows(rows, row(IMPORT_PK, IMPORT_PK));
-            Assertions.assertThat(B.logs().grep(mark, "Found overlapping activation ID ").getResult()).isNotEmpty();
+
+            // Both partitions survive the import and the compaction.
+            for (int pk : new int[]{ otherPk, IMPORT_PK })
+            {
+                Object[][] rows = cluster.coordinator(1).execute(withKeyspace("SELECT * FROM %s." + TABLE + " WHERE k = ?"),
+                                                                 ConsistencyLevel.ALL, pk);
+                assertRows(rows, row(pk, pk));
+            }
         }
     }
 
diff --git a/test/unit/org/apache/cassandra/batchlog/BatchlogManagerTest.java b/test/unit/org/apache/cassandra/batchlog/BatchlogManagerTest.java
index 5c29fd438d..2194ba32ad 100644
--- a/test/unit/org/apache/cassandra/batchlog/BatchlogManagerTest.java
+++ b/test/unit/org/apache/cassandra/batchlog/BatchlogManagerTest.java
@@ -42,8 +42,8 @@ import org.apache.cassandra.db.Keyspace;
 import org.apache.cassandra.db.Mutation;
 import org.apache.cassandra.db.RowUpdateBuilder;
 import org.apache.cassandra.db.SystemKeyspace;
-import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.db.marshal.BytesType;
+import org.apache.cassandra.db.memtable.LogDomainPositions;
 import org.apache.cassandra.db.partitions.ImmutableBTreePartition;
 import org.apache.cassandra.db.partitions.PartitionUpdate;
 import org.apache.cassandra.db.rows.Row;
@@ -223,7 +223,7 @@ public class BatchlogManagerTest extends CassandraTestBase
             if (i == 500)
                 SystemKeyspace.saveTruncationRecord(Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD2),
                                                     timestamp,
-                                                    CommitLogPosition.NONE);
+                                                    LogDomainPositions.NONE);
 
             // Adjust the timestamp (slightly) to make the test deterministic.
             if (i >= 500)
diff --git a/test/unit/org/apache/cassandra/cql3/validation/operations/AlterTest.java b/test/unit/org/apache/cassandra/cql3/validation/operations/AlterTest.java
index 5bc2f9fc13..867383aaf0 100644
--- a/test/unit/org/apache/cassandra/cql3/validation/operations/AlterTest.java
+++ b/test/unit/org/apache/cassandra/cql3/validation/operations/AlterTest.java
@@ -24,6 +24,7 @@ import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.cql3.CQLTester;
 import org.apache.cassandra.db.ColumnFamilyStore;
 import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.memtable.Memtable;
 import org.apache.cassandra.db.memtable.SkipListMemtable;
 import org.apache.cassandra.db.memtable.TestMemtable;
@@ -683,7 +684,7 @@ public class AlterTest extends CQLTester
                    row(expected));
     }
 
-    private void testMemtableConfig(String memtableConfig, Memtable.Factory factoryInstance, Class<? extends Memtable> memtableClass) throws Throwable
+    private void testMemtableConfig(String memtableConfig, DomainMemtable.Factory factoryInstance, Class<? extends Memtable> memtableClass) throws Throwable
     {
         alterTable("ALTER TABLE %s"
                    + " WITH memtable = '" + memtableConfig + "';");
diff --git a/test/unit/org/apache/cassandra/cql3/validation/operations/CreateTest.java b/test/unit/org/apache/cassandra/cql3/validation/operations/CreateTest.java
index 82a7d18910..6a724223d4 100644
--- a/test/unit/org/apache/cassandra/cql3/validation/operations/CreateTest.java
+++ b/test/unit/org/apache/cassandra/cql3/validation/operations/CreateTest.java
@@ -30,6 +30,7 @@ import org.junit.Test;
 import org.apache.cassandra.cql3.CQLTester;
 import org.apache.cassandra.cql3.Duration;
 import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.memtable.Memtable;
 import org.apache.cassandra.db.memtable.SkipListMemtable;
 import org.apache.cassandra.db.memtable.TestMemtable;
@@ -641,7 +642,7 @@ public class CreateTest extends CQLTester
                                            + " WITH memtable = 'unknown';");
     }
 
-    private void testMemtableConfig(String memtableConfig, Memtable.Factory factoryInstance, Class<? extends Memtable> memtableClass) throws Throwable
+    private void testMemtableConfig(String memtableConfig, DomainMemtable.Factory factoryInstance, Class<? extends Memtable> memtableClass) throws Throwable
     {
         createTable("CREATE TABLE %s (a text, b int, c int, primary key (a, b))"
                     + " WITH memtable = '" + memtableConfig + "';");
diff --git a/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java b/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
index f7921785c6..40e8462c56 100644
--- a/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
+++ b/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
@@ -31,7 +31,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.Consumer;
 import java.util.function.Supplier;
 
@@ -57,6 +56,7 @@ import org.apache.cassandra.db.filter.ColumnFilter;
 import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
 import org.apache.cassandra.db.lifecycle.SSTableSet;
 import org.apache.cassandra.db.memtable.AbstractMemtable;
+import org.apache.cassandra.db.memtable.LogDomainBounds;
 import org.apache.cassandra.db.memtable.Memtable;
 import org.apache.cassandra.db.partitions.FilteredPartition;
 import org.apache.cassandra.db.partitions.Partition;
@@ -847,7 +847,7 @@ public class ColumnFamilyStoreTest
         {
 
             @Override
-            public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, Group opGroup, boolean assumeMissing)
+            public long put(MutationId mutationId, PartitionUpdate update, UpdateTransaction indexer, Group opGroup, LogDomain domain, boolean assumeMissing)
             {
                 return 0;
             }
@@ -886,7 +886,7 @@ public class ColumnFamilyStoreTest
             }
 
             @Override
-            public void switchOut(Barrier writeBarrier, AtomicReference<CommitLogPosition> commitLogUpperBound)
+            public void switchOut(Barrier writeBarrier, LogDomainBounds upperBounds)
             {
             }
 
@@ -896,15 +896,21 @@ public class ColumnFamilyStoreTest
             }
 
             @Override
-            public boolean accepts(Group opGroup, CommitLogPosition commitLogPosition)
+            public boolean accepts(Group opGroup, CommitLogPosition commitLogPosition, LogDomain domain)
             {
                 return false;
             }
 
             @Override
-            public CommitLogPosition getApproximateCommitLogLowerBound()
+            public boolean holds(LogDomain domain)
             {
-                return null;
+                return domain == LogDomain.COMMIT_LOG;
+            }
+
+            @Override
+            public Owner owner()
+            {
+                return cfs;
             }
 
             @Override
diff --git a/test/unit/org/apache/cassandra/db/CoordinatorLogOffsetsLifecycleTest.java b/test/unit/org/apache/cassandra/db/CoordinatorLogOffsetsLifecycleTest.java
index 05acb3d870..bc6f2b2046 100644
--- a/test/unit/org/apache/cassandra/db/CoordinatorLogOffsetsLifecycleTest.java
+++ b/test/unit/org/apache/cassandra/db/CoordinatorLogOffsetsLifecycleTest.java
@@ -20,12 +20,10 @@ package org.apache.cassandra.db;
 
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Comparator;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 
 import org.assertj.core.api.Assertions;
 import org.junit.Assert;
@@ -38,9 +36,10 @@ import org.junit.runners.Parameterized.Parameters;
 
 import org.apache.cassandra.SchemaLoader;
 import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.db.compaction.CompactionGroup;
 import org.apache.cassandra.db.lifecycle.View;
 import org.apache.cassandra.db.marshal.Int32Type;
-import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.DomainMemtable;
 import org.apache.cassandra.db.partitions.PartitionUpdate;
 import org.apache.cassandra.exceptions.ConfigurationException;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
@@ -179,7 +178,7 @@ public class CoordinatorLogOffsetsLifecycleTest
             assertNonEmptyMemtable(view);
             assertNumSSTables(view, 0);
 
-            Memtable memtable = view.getCurrentMemtable();
+            DomainMemtable memtable = (DomainMemtable) view.getCurrentMemtable();
             ImmutableCoordinatorLogOffsets logOffsets = memtable.getFlushSet(null, null).coordinatorLogOffsets();
             Assertions.assertThat(logOffsets.mutations().size()).isEqualTo(1);
             Assertions.assertThat(logOffsets.mutations().offsets(id2.logId()).contains(id2.offset())).isTrue();
@@ -195,25 +194,24 @@ public class CoordinatorLogOffsetsLifecycleTest
             assertNumSSTables(view, 1);
 
             SSTableReader sstable = Iterables.getOnlyElement(view.liveSSTables());
-            ImmutableCoordinatorLogOffsets logOffsets = sstable.getCoordinatorLogOffsets();
-            Assertions.assertThat(logOffsets.mutations().size()).isEqualTo(1);
-            Assertions.assertThat(logOffsets.mutations().offsets(id2.logId()).contains(id2.offset())).isTrue();
-            // Single-participant, so mutations are immediately reconciled once applied
+            // Single-participant, so mutations are immediately reconciled once applied, and a reconciled flush is
+            // promoted as it is written.
             Assertions.assertThat(sstable.isRepaired()).isTrue();
+            Assertions.assertThat(sstable.getCoordinatorLogOffsets().isEmpty()).isTrue();
+            Assertions.assertThat(CompactionGroup.of(sstable)).isEqualTo(CompactionGroup.REPAIRED);
         }
 
-        MutationId id3;
         MutationId id4;
         // apply 2
         {
-            id3 = applyMutation(cfs.metadata(), 3, 3);
+            applyMutation(cfs.metadata(), 3, 3);
             id4 = applyMutation(cfs.metadata(), 4, 4);
 
             View view = cfs.getTracker().getView();
             assertNonEmptyMemtable(view);
             assertNumSSTables(view, 1);
 
-            Memtable memtable = view.getCurrentMemtable();
+            DomainMemtable memtable = (DomainMemtable) view.getCurrentMemtable();
             ImmutableCoordinatorLogOffsets logOffsets = memtable.getFlushSet(null, null).coordinatorLogOffsets();
             Assertions.assertThat(logOffsets.mutations().size()).isEqualTo(1);
             Assertions.assertThat(logOffsets.mutations().offsets(id4.logId()).contains(id4.offset())).isTrue();
@@ -228,21 +226,11 @@ public class CoordinatorLogOffsetsLifecycleTest
             assertEmptyMemtable(view);
             assertNumSSTables(view, 2);
 
-            List<SSTableReader> sstables = Lists.newArrayList(view.liveSSTables());
-            sstables.sort(Comparator.comparing(sst -> sst.descriptor.id.asBytes()));
+            for (SSTableReader sstable : view.liveSSTables())
             {
-                ImmutableCoordinatorLogOffsets logOffsets = sstables.get(0).getCoordinatorLogOffsets();
-                Assertions.assertThat(logOffsets.mutations().size()).isEqualTo(1);
-                Assertions.assertThat(logOffsets.mutations().offsets(id2.logId()).contains(id2.offset())).isTrue();
-            }
-            {
-
-                ImmutableCoordinatorLogOffsets logOffsets = sstables.get(1).getCoordinatorLogOffsets();
-                Assertions.assertThat(logOffsets.mutations().size()).isEqualTo(1);
-                Assertions.assertThat(logOffsets.mutations().offsets(id4.logId()).contains(id4.offset())).isTrue();
-            }
-            for (SSTableReader sstable : sstables)
                 Assertions.assertThat(sstable.isRepaired()).isTrue();
+                Assertions.assertThat(sstable.getCoordinatorLogOffsets().isEmpty()).isTrue();
+            }
         }
 
         // compaction
@@ -254,10 +242,9 @@ public class CoordinatorLogOffsetsLifecycleTest
             assertNumSSTables(view, 1);
 
             SSTableReader sstable = Iterables.getOnlyElement(view.liveSSTables());
-            ImmutableCoordinatorLogOffsets logOffsets = sstable.getCoordinatorLogOffsets();
-            Assertions.assertThat(logOffsets.mutations().size()).isEqualTo(1);
-            Assertions.assertThat(logOffsets.mutations().offsets(id4.logId()).contains(id4.offset())).isTrue();
+            // Compacting repaired inputs yields a repaired output, still with no offsets to carry forward.
             Assertions.assertThat(sstable.isRepaired()).isTrue();
+            Assertions.assertThat(sstable.getCoordinatorLogOffsets().isEmpty()).isTrue();
         }
     }
 }
diff --git a/test/unit/org/apache/cassandra/db/compaction/CompactionGroupTest.java b/test/unit/org/apache/cassandra/db/compaction/CompactionGroupTest.java
new file mode 100644
index 0000000000..b7d3d10dd7
--- /dev/null
+++ b/test/unit/org/apache/cassandra/db/compaction/CompactionGroupTest.java
@@ -0,0 +1,105 @@
+/*
+ * 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.db.compaction;
+
+import org.junit.Test;
+
+import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
+import org.apache.cassandra.replication.MutationId;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.utils.TimeUUID;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+public class CompactionGroupTest
+{
+    private static final long REPAIRED_AT = 1234L;
+    private static final long UNREPAIRED = ActiveRepairService.UNREPAIRED_SSTABLE;
+    private static final TimeUUID NO_PENDING = ActiveRepairService.NO_PENDING_REPAIR;
+
+    private static ImmutableCoordinatorLogOffsets offsets(long logId, int offset)
+    {
+        return new ImmutableCoordinatorLogOffsets.Builder().add(new MutationId(logId, (long) offset)).build();
+    }
+
+    private static ImmutableCoordinatorLogOffsets noOffsets()
+    {
+        return new ImmutableCoordinatorLogOffsets.Builder().build();
+    }
+
+    /**
+     * Repaired wins over offsets. Promotion clears the offsets in the same metadata mutation that sets {@code repairedAt},
+     * so this should be unreachable, but we still don't want repaired and unreconciled data being compacted if that's not
+     * working properly
+     */
+    @Test
+    public void repairedOutranksOffsets()
+    {
+        assertEquals(CompactionGroup.REPAIRED, CompactionGroup.of(REPAIRED_AT, NO_PENDING, noOffsets()));
+        assertEquals(CompactionGroup.REPAIRED, CompactionGroup.of(REPAIRED_AT, NO_PENDING, offsets(1, 0)));
+    }
+
+    /**
+     * Pending repair outranks offsets too, so an sstable in a session is not routed to a tracked silo.
+     */
+    @Test
+    public void pendingRepairOutranksOffsets()
+    {
+        TimeUUID session = TimeUUID.Generator.nextTimeUUID();
+        assertEquals(CompactionGroup.PENDING_REPAIR, CompactionGroup.of(UNREPAIRED, session, noOffsets()));
+        assertEquals(CompactionGroup.PENDING_REPAIR, CompactionGroup.of(UNREPAIRED, session, offsets(1, 0)));
+    }
+
+    /**
+     * Any offsets at all mean tracked data awaiting reconciliation. Transfers and mutations are not told apart here.
+     */
+    @Test
+    public void offsetsOnUnrepairedDataMeanUnreconciled()
+    {
+        assertEquals(CompactionGroup.UNRECONCILED, CompactionGroup.of(UNREPAIRED, NO_PENDING, offsets(1, 0)));
+    }
+
+    /**
+     * No offsets on unrepaired data is untracked. A null offsets object reads the same way, which streaming relies on.
+     */
+    @Test
+    public void noOffsetsOnUnrepairedDataMeansUntracked()
+    {
+        assertEquals(CompactionGroup.UNREPAIRED, CompactionGroup.of(UNREPAIRED, NO_PENDING, noOffsets()));
+        assertEquals(CompactionGroup.UNREPAIRED, CompactionGroup.of(UNREPAIRED, NO_PENDING, null));
+    }
+
+    /**
+     * repairedAt and pendingRepair can't both be set
+     */
+    @Test
+    public void repairedAndPendingIsRejected()
+    {
+        try
+        {
+            CompactionGroup.of(REPAIRED_AT, TimeUUID.Generator.nextTimeUUID(), null);
+            fail("Expected IllegalArgumentException");
+        }
+        catch (IllegalArgumentException expected)
+        {
+            // expected
+        }
+    }
+}
diff --git a/test/unit/org/apache/cassandra/db/compaction/CompactionStrategyManagerPendingRepairTest.java b/test/unit/org/apache/cassandra/db/compaction/CompactionStrategyManagerPendingRepairTest.java
index 694dbf9a1e..1037587ce6 100644
--- a/test/unit/org/apache/cassandra/db/compaction/CompactionStrategyManagerPendingRepairTest.java
+++ b/test/unit/org/apache/cassandra/db/compaction/CompactionStrategyManagerPendingRepairTest.java
@@ -203,7 +203,7 @@ public class CompactionStrategyManagerPendingRepairTest extends AbstractPendingR
         List<List<AbstractCompactionStrategy>> strategies;
 
         strategies = csm.getStrategies();
-        Assert.assertEquals(3, strategies.size());
+        Assert.assertEquals(4, strategies.size());
         Assert.assertTrue(strategies.get(2).isEmpty());
 
         SSTableReader sstable = makeSSTable(true);
@@ -211,7 +211,7 @@ public class CompactionStrategyManagerPendingRepairTest extends AbstractPendingR
         csm.handleNotification(new SSTableAddedNotification(Collections.singleton(sstable), null), cfs.getTracker());
 
         strategies = csm.getStrategies();
-        Assert.assertEquals(3, strategies.size());
+        Assert.assertEquals(4, strategies.size());
         Assert.assertFalse(strategies.get(2).isEmpty());
     }
 
diff --git a/test/unit/org/apache/cassandra/db/compaction/CompactionStrategyManagerTest.java b/test/unit/org/apache/cassandra/db/compaction/CompactionStrategyManagerTest.java
index 74f27c524d..5a63ffaa9e 100644
--- a/test/unit/org/apache/cassandra/db/compaction/CompactionStrategyManagerTest.java
+++ b/test/unit/org/apache/cassandra/db/compaction/CompactionStrategyManagerTest.java
@@ -22,7 +22,10 @@ import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.EnumMap;
+import java.util.EnumSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Random;
 import java.util.Set;
 import java.util.concurrent.CountDownLatch;
@@ -73,7 +76,6 @@ import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 
 /**
  * We use byte ordered partitioner in this test to be able to easily infer an SSTable
@@ -275,56 +277,42 @@ public class CompactionStrategyManagerTest extends CassandraTestBase
         DatabaseDescriptor.setAutomaticSSTableUpgradeEnabled(false);
     }
 
-    private static void assertHolderExclusivity(boolean isRepaired, boolean isPendingRepair, Class<? extends AbstractStrategyHolder> expectedType)
+    @Test
+    public void testMutualExclusiveHolderClassification() throws Exception
     {
+        Map<CompactionGroup, Class<? extends AbstractStrategyHolder>> expected = new EnumMap<>(CompactionGroup.class);
+        expected.put(CompactionGroup.UNREPAIRED, CompactionStrategyHolder.class);
+        expected.put(CompactionGroup.REPAIRED, CompactionStrategyHolder.class);
+        expected.put(CompactionGroup.PENDING_REPAIR, PendingRepairHolder.class);
+        expected.put(CompactionGroup.UNRECONCILED, TrackedCompactionManager.class);
+
+        assertEquals("a new compaction group needs a holder named here before it can be routed",
+                     EnumSet.allOf(CompactionGroup.class), expected.keySet());
+
         ColumnFamilyStore cfs = Keyspace.open(KS_PREFIX).getColumnFamilyStore(TABLE_PREFIX);
         CompactionStrategyManager csm = cfs.getCompactionStrategyManager();
 
-        AbstractStrategyHolder holder = csm.getHolder(isRepaired, isPendingRepair);
-        assertNotNull(holder);
-        assertSame(expectedType, holder.getClass());
-
-        int matches = 0;
-        for (AbstractStrategyHolder other : csm.getHolders())
+        for (CompactionGroup group : CompactionGroup.values())
         {
-            if (other.managesRepairedGroup(isRepaired, isPendingRepair))
+            AbstractStrategyHolder holder = csm.getHolder(group);
+            assertNotNull("no holder claims " + group, holder);
+
+            assertSame(expected.get(group), holder.getClass());
+
+            int matches = 0;
+            for (AbstractStrategyHolder other : csm.getHolders())
             {
-                assertSame("holder assignment should be mutually exclusive", holder, other);
-                matches++;
+                if (other.managesGroup(group))
+                {
+                    assertSame("holder assignment should be mutually exclusive", holder, other);
+                    matches++;
+                }
             }
-        }
-        assertEquals(1, matches);
-    }
+            assertEquals(1, matches);
 
-    private static void assertInvalidHolderConfig(boolean isRepaired, boolean isPendingRepair)
-    {
-        ColumnFamilyStore cfs = Keyspace.open(KS_PREFIX).getColumnFamilyStore(TABLE_PREFIX);
-        CompactionStrategyManager csm = cfs.getCompactionStrategyManager();
-        try
-        {
-            csm.getHolder(isRepaired, isPendingRepair);
-            fail("Expected IllegalArgumentException");
-        }
-        catch (IllegalArgumentException e)
-        {
-            // expected
         }
     }
 
-    /**
-     * If an sstable can be be assigned to a strategy holder, it shouldn't be possibly to
-     * assign it to any of the other holders.
-     */
-    @Test
-    public void testMutualExclusiveHolderClassification() throws Exception
-    {
-        assertHolderExclusivity(false, false, CompactionStrategyHolder.class);
-        assertHolderExclusivity(true, false, CompactionStrategyHolder.class);
-        assertHolderExclusivity(false, true, PendingRepairHolder.class);
-        assertHolderExclusivity(false, true, PendingRepairHolder.class);
-        assertInvalidHolderConfig(true, true);
-    }
-
     PartitionPosition forKey(int key)
     {
         DecoratedKey dk = Util.dk(String.format("%04d", key));
@@ -364,13 +352,20 @@ public class CompactionStrategyManagerTest extends CassandraTestBase
 
         List<GroupedSSTableContainer> grouped = csm.groupSSTables(Iterables.concat( pendingRepair, repaired, unrepaired));
 
+        int placed = 0;
         for (int x=0; x<grouped.size(); x++)
         {
             GroupedSSTableContainer group = grouped.get(x);
             AbstractStrategyHolder holder = csm.getHolders().get(x);
             for (int y=0; y<numDir; y++)
             {
+                // Holders whose group is not represented among these sstables get nothing; the tracked holders are
+                // empty here because none of these sstables carry coordinator log offsets.
+                if (group.isGroupEmpty(y))
+                    continue;
+
                 SSTableReader sstable = Iterables.getOnlyElement(group.getGroup(y));
+                placed++;
                 assertTrue(holder.managesSSTable(sstable));
                 SSTableReader expected;
                 if (sstable.isRepaired())
@@ -385,6 +380,8 @@ public class CompactionStrategyManagerTest extends CassandraTestBase
                 assertSame(expected, sstable);
             }
         }
+        // every sstable landed somewhere, so skipping empty groups above cannot mask a lost sstable
+        assertEquals(3 * numDir, placed);
     }
 
     @Test
diff --git a/test/unit/org/apache/cassandra/db/compaction/PromoteReconciledTaskTest.java b/test/unit/org/apache/cassandra/db/compaction/PromoteReconciledTaskTest.java
new file mode 100644
index 0000000000..2632bce950
--- /dev/null
+++ b/test/unit/org/apache/cassandra/db/compaction/PromoteReconciledTaskTest.java
@@ -0,0 +1,123 @@
+/*
+ * 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.db.compaction;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Test;
+
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+public class PromoteReconciledTaskTest extends AbstractPendingRepairTest
+{
+    private Set<SSTableReader> sstables(int count)
+    {
+        Set<SSTableReader> sstables = new HashSet<>();
+        for (int i = 0; i < count; i++)
+            sstables.add(makeSSTable(true));
+        return sstables;
+    }
+
+    private AbstractCompactionTask tryPromote(Set<SSTableReader> candidates)
+    {
+        return PromoteReconciledTask.tryPromote(cfs, candidates, "test", null);
+    }
+
+    @Test
+    public void noCandidatesYieldsNoTask()
+    {
+        assertNull(tryPromote(Collections.emptySet()));
+    }
+
+    @Test
+    public void allCandidatesBusyYieldsNoTask()
+    {
+        Set<SSTableReader> candidates = sstables(2);
+        AtomicInteger hookRuns = new AtomicInteger();
+
+        try (LifecycleTransaction held = cfs.getTracker().tryModify(candidates, OperationType.COMPACTION))
+        {
+            assertNotNull(held);
+            assertNull("nothing is claimable, so there is nothing to promote",
+                       PromoteReconciledTask.tryPromote(cfs, candidates, "test", hookRuns::incrementAndGet));
+        }
+        assertEquals("no task was produced, so nothing should have been signalled", 0, hookRuns.get());
+    }
+
+    @Test
+    public void allCandidatesFreeClaimsAllOfThem()
+    {
+        Set<SSTableReader> candidates = sstables(3);
+
+        AbstractCompactionTask task = tryPromote(candidates);
+        assertNotNull(task);
+        try
+        {
+            assertEquals(candidates, task.transaction.originals());
+        }
+        finally
+        {
+            task.transaction.abort();
+        }
+    }
+
+    /**
+     * One busy sstable shouldn't block compaction on the others. The task should try to aquire the remaining tables
+     * that aren't referenced
+     */
+    @Test
+    public void busyCandidateDoesntBlockRemainder()
+    {
+        Set<SSTableReader> candidates = sstables(3);
+        SSTableReader busy = candidates.iterator().next();
+
+        try (LifecycleTransaction held = cfs.getTracker().tryModify(Collections.singleton(busy),
+                                                                   OperationType.COMPACTION))
+        {
+            assertNotNull(held);
+
+            AbstractCompactionTask task = tryPromote(candidates);
+            assertNotNull("the free candidates should still have been promoted", task);
+            try
+            {
+                Set<SSTableReader> claimed = task.transaction.originals();
+                // The busy one is left out and every other candidate is claimed.
+                assertEquals(candidates.size() - 1, claimed.size());
+                assertFalse(claimed.contains(busy));
+                Set<SSTableReader> rest = new HashSet<>(candidates);
+                rest.remove(busy);
+                assertTrue(claimed.containsAll(rest));
+            }
+            finally
+            {
+                task.transaction.abort();
+            }
+        }
+    }
+}
diff --git a/test/unit/org/apache/cassandra/db/compaction/TrackedCompactionManagerTest.java b/test/unit/org/apache/cassandra/db/compaction/TrackedCompactionManagerTest.java
new file mode 100644
index 0000000000..7f567479d9
--- /dev/null
+++ b/test/unit/org/apache/cassandra/db/compaction/TrackedCompactionManagerTest.java
@@ -0,0 +1,348 @@
+/*
+ * 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.db.compaction;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.ImmutableSet;
+
+import org.junit.Test;
+
+import org.apache.cassandra.db.compaction.AbstractStrategyHolder.DestinationRouter;
+import org.apache.cassandra.db.compaction.AbstractStrategyHolder.GroupedSSTableContainer;
+import org.apache.cassandra.db.compaction.AbstractStrategyHolder.TaskSupplier;
+import org.apache.cassandra.dht.Bounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
+import org.apache.cassandra.replication.MutationId;
+import org.apache.cassandra.replication.ShortMutationId;
+import org.apache.cassandra.schema.CompactionParams;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+public class TrackedCompactionManagerTest extends AbstractPendingRepairTest
+{
+    private static ShortMutationId id(long logId, int offset)
+    {
+        return new ShortMutationId(logId, offset);
+    }
+
+    private static ImmutableSet<ShortMutationId> key(ShortMutationId... ids)
+    {
+        return ImmutableSet.copyOf(ids);
+    }
+
+    static final DestinationRouter SINGLE_PARTITION = new DestinationRouter()
+    {
+        public int getIndexForSSTable(SSTableReader sstable) { return 0; }
+        public int getIndexForSSTableDirectory(Descriptor descriptor) { return 0; }
+    };
+
+    private TrackedCompactionManager manager()
+    {
+        TrackedCompactionManager manager = new TrackedCompactionManager(cfs, SINGLE_PARTITION);
+        manager.setStrategy(CompactionParams.DEFAULT, 1);
+        return manager;
+    }
+
+    private static GroupedSSTableContainer group(TrackedCompactionManager manager, Iterable<SSTableReader> sstables)
+    {
+        GroupedSSTableContainer container = manager.createGroupedSSTableContainer();
+        sstables.forEach(container::add);
+        return container;
+    }
+
+    private static Collection<AbstractCompactionTask> nextBackgroundTasks(TrackedCompactionManager manager)
+    {
+        for (TaskSupplier supplier : manager.getBackgroundTaskSuppliers(FBUtilities.nowInSeconds()))
+        {
+            Collection<AbstractCompactionTask> tasks = supplier.getTasks();
+            if (tasks != null && !tasks.isEmpty())
+                return tasks;
+        }
+        return Collections.emptyList();
+    }
+
+    /**
+     * Silo keys other than {@link TrackedCompactionManager#NONE}, which is always present.
+     * */
+    private static Set<ImmutableSet<ShortMutationId>> transferKeys(TrackedCompactionManager manager)
+    {
+        return manager.keys().stream().filter(k -> !k.isEmpty()).collect(Collectors.toSet());
+    }
+
+    private static void attachTransfer(SSTableReader sstable, ShortMutationId... ids) throws IOException
+    {
+        ImmutableCoordinatorLogOffsets.Builder builder = new ImmutableCoordinatorLogOffsets.Builder();
+        for (ShortMutationId id : ids)
+        {
+            Bounds<Token> bounds = new Bounds<>(sstable.getFirst().getToken(), sstable.getLast().getToken());
+            builder.addTransfer(id, bounds);
+        }
+        sstable.mutateCoordinatorLogOffsetsAndReload(builder.build());
+    }
+
+    private SSTableReader sstableWithTransfers(ShortMutationId... ids) throws IOException
+    {
+        SSTableReader sstable = makeSSTable(true);
+        attachTransfer(sstable, ids);
+        return sstable;
+    }
+
+    private SSTableReader sstableWithMutations(long logId, int offset) throws IOException
+    {
+        SSTableReader sstable = makeSSTable(true);
+        ImmutableCoordinatorLogOffsets offsets = new ImmutableCoordinatorLogOffsets.Builder()
+                                                .add(new MutationId(logId, (long) offset))
+                                                .build();
+        sstable.mutateCoordinatorLogOffsetsAndReload(offsets);
+        return sstable;
+    }
+
+    /**
+     * Any offsets at all put an sstable in this group
+     */
+    @Test
+    public void anyOffsetsMeanUnreconciled() throws IOException
+    {
+        SSTableReader transfer = sstableWithTransfers(id(1, 0));
+        SSTableReader mutations = sstableWithMutations(1, 0);
+
+        assertEquals(CompactionGroup.UNRECONCILED, CompactionGroup.of(transfer));
+        assertEquals(CompactionGroup.UNRECONCILED, CompactionGroup.of(mutations));
+        assertEquals("no offsets is untracked data", CompactionGroup.UNREPAIRED, CompactionGroup.of(makeSSTable(true)));
+        assertSame(csm.getHolder(CompactionGroup.of(transfer)), csm.getHolder(CompactionGroup.of(mutations)));
+    }
+
+    /**
+     * A silo per distinct transfer set, so no strategy can select across the boundary
+     */
+    @Test
+    public void sstablesAreSiloedByTransferSet() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+
+        SSTableReader a = sstableWithTransfers(id(1, 0));
+        SSTableReader b = sstableWithTransfers(id(1, 1));
+        SSTableReader both = sstableWithTransfers(id(1, 0), id(1, 1));
+        SSTableReader sameAsA = sstableWithTransfers(id(1, 0));
+
+        manager.addSSTable(a);
+        manager.addSSTable(b);
+        manager.addSSTable(both);
+        manager.addSSTable(sameAsA);
+
+        assertEquals(3, transferKeys(manager).size());
+        assertEquals("an equal transfer set must share a silo rather than making a fourth",
+                     ImmutableSet.of(a, sameAsA), manager.sstablesFor(key(id(1, 0))));
+        assertEquals(Collections.singleton(b), manager.sstablesFor(key(id(1, 1))));
+        assertEquals(Collections.singleton(both), manager.sstablesFor(key(id(1, 0), id(1, 1))));
+    }
+
+    /**
+     * Sstables carrying no transfers share the empty-key silo
+     */
+    @Test
+    public void sstablesWithoutTransfersShareOneSilo() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+
+        SSTableReader a = sstableWithMutations(1, 0);
+        SSTableReader b = sstableWithMutations(2, 7);
+        SSTableReader transfer = sstableWithTransfers(id(1, 0));
+        manager.addSSTable(a);
+        manager.addSSTable(b);
+        manager.addSSTable(transfer);
+
+        assertEquals(ImmutableSet.of(a, b), manager.sstablesFor(TrackedCompactionManager.NONE));
+        assertSame(manager.getIfPresent(TrackedCompactionManager.NONE), manager.getIfPresent(a));
+        assertSame(manager.getIfPresent(TrackedCompactionManager.NONE), manager.getIfPresent(b));
+
+        assertNotSame("a transfer must not be compactable with ordinary tracked data",
+                      manager.getIfPresent(transfer), manager.getIfPresent(a));
+        assertEquals(Collections.singleton(transfer), manager.sstablesFor(key(id(1, 0))));
+    }
+
+    /**
+     * An empty transfer silo is pruned however it came to be empty, and holds no data and generates no work in the
+     * meantime. Both routes matter: the delete path reaches past the manager straight to the strategy, and a delete
+     * notification can resurrect a silo that never held anything.
+     */
+    @Test
+    public void emptyTransferSilosArePruned() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+        SSTableReader sstable = sstableWithTransfers(id(1, 0));
+
+        // Resurrected by a lookup, never having held anything.
+        manager.getOrCreate(sstable);
+        // Holds no data and generates no work, and the walk that reads the estimate prunes it.
+        assertFalse(manager.hasDataFor(key(id(1, 0))));
+        assertTrue(nextBackgroundTasks(manager).isEmpty());
+        assertEquals(0, manager.getEstimatedRemainingTasks());
+        assertTrue(transferKeys(manager).isEmpty());
+
+        // Emptied past the manager, so the manager is never told.
+        manager.addSSTable(sstable);
+        assertEquals(1, transferKeys(manager).size());
+        manager.getIfPresent(sstable).getStrategyFor(sstable).removeSSTable(sstable);
+        assertEquals("manager was not notified, so the silo is still there", 1, transferKeys(manager).size());
+        assertEquals(0, manager.getEstimatedRemainingTasks());
+        assertTrue(transferKeys(manager).isEmpty());
+
+        // Emptied through the manager, which prunes without waiting for a walk.
+        manager.addSSTable(sstable);
+        manager.removeSSTable(sstable);
+        assertTrue("removal through the manager prunes immediately", transferKeys(manager).isEmpty());
+    }
+
+    /** The NONE silo takes ordinary unreconciled writes continuously, so unlike a transfer silo it outlives emptying. */
+    @Test
+    public void noneTransfersSiloIsNeverPruned() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+        assertNotNull(manager.getIfPresent(TrackedCompactionManager.NONE));
+
+        SSTableReader sstable = sstableWithMutations(1, 0);
+        manager.addSSTable(sstable);
+        manager.removeSSTable(sstable);
+
+        assertTrue("the NONE silo must survive being emptied where a transfer silo would not",
+                   manager.keys().contains(TrackedCompactionManager.NONE));
+        assertNotNull(manager.getIfPresent(TrackedCompactionManager.NONE));
+        assertFalse(manager.hasDataFor(TrackedCompactionManager.NONE));
+    }
+
+    /**
+     * Membership answers track the sstables held, not whether a silo exists for their key.
+     * */
+    @Test
+    public void sessionHasData() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+        SSTableReader transfer = sstableWithTransfers(id(1, 0));
+        SSTableReader unreconciled = sstableWithMutations(1, 0);
+
+        assertFalse(manager.hasDataFor(key(id(1, 0))));
+        assertFalse(manager.containsSSTable(transfer));
+        assertFalse(manager.containsSSTable(unreconciled));
+        assertNull(manager.getIfPresent(transfer));
+
+        manager.addSSTable(transfer);
+        manager.addSSTable(unreconciled);
+
+        assertTrue(manager.hasDataFor(key(id(1, 0))));
+        assertTrue(manager.containsSSTable(transfer));
+        assertTrue(manager.containsSSTable(unreconciled));
+        assertNotNull(manager.getIfPresent(transfer));
+    }
+
+    /**
+     * The repair-status notification sends a removal for sstables whose group has already changed, so a removal for an
+     * sstable this manager never held must not throw.
+     */
+    @Test
+    public void removingSomethingNeverHeldIsHarmless() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+        manager.removeSSTable(sstableWithMutations(1, 0));
+        manager.removeSSTable(sstableWithTransfers(id(1, 0)));
+    }
+
+    /** Compaction output replaces its inputs in whichever silo each belongs to, without creating a new one. */
+    @Test
+    public void replaceRoutesProperly() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+
+        SSTableReader transfer = sstableWithTransfers(id(1, 0));
+        SSTableReader unreconciled = sstableWithMutations(1, 0);
+        manager.addSSTable(transfer);
+        manager.addSSTable(unreconciled);
+
+        SSTableReader newTransfer = sstableWithTransfers(id(1, 0));
+        SSTableReader newUnreconciled = sstableWithMutations(2, 3);
+
+        manager.replaceSSTables(group(manager, ImmutableSet.of(transfer, unreconciled)),
+                                group(manager, ImmutableSet.of(newTransfer, newUnreconciled)));
+
+        // Each replacement lands in the silo its input came from, and no new silo appears.
+        assertEquals(Collections.singleton(newTransfer), manager.sstablesFor(key(id(1, 0))));
+        assertEquals(Collections.singleton(newUnreconciled),
+                     manager.sstablesFor(TrackedCompactionManager.NONE));
+        assertEquals(1, transferKeys(manager).size());
+    }
+
+    @Test
+    public void replaceWithNothingRemovedIsAnAdd() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+        SSTableReader added = sstableWithMutations(1, 0);
+
+        manager.replaceSSTables(group(manager, Collections.emptySet()),
+                                group(manager, Collections.singleton(added)));
+
+        assertTrue(manager.containsSSTable(added));
+    }
+
+    @Test
+    public void getNextBackgroundTaskNoSessions()
+    {
+        TrackedCompactionManager manager = manager();
+
+        // Neither the always-present silo when empty, nor a silo that does not exist.
+        assertNull(manager.getPromotionTask(TrackedCompactionManager.NONE));
+        assertNull(manager.getPromotionTask(key(id(9, 9))));
+        assertTrue(manager.getNextPromotionTasks().isEmpty());
+    }
+
+    @Test
+    public void userDefinedTaskTest() throws IOException
+    {
+        TrackedCompactionManager manager = manager();
+        SSTableReader sstable = sstableWithTransfers(id(1, 0));
+
+        assertNull(manager.getIfPresent(sstable));
+
+        GroupedSSTableContainer container = group(manager, Collections.singleton(sstable));
+        Collection<AbstractCompactionTask> tasks = manager.getUserDefinedTasks(container, FBUtilities.nowInSeconds());
+        try
+        {
+            assertEquals("the request must be honoured, not dropped", 1, tasks.size());
+            assertNotNull(manager.getIfPresent(sstable));
+        }
+        finally
+        {
+            tasks.forEach(AbstractCompactionTask::rejected);
+        }
+    }
+}
diff --git a/test/unit/org/apache/cassandra/db/compaction/TrackedUnreconciledPromotionTest.java b/test/unit/org/apache/cassandra/db/compaction/TrackedUnreconciledPromotionTest.java
new file mode 100644
index 0000000000..284e644128
--- /dev/null
+++ b/test/unit/org/apache/cassandra/db/compaction/TrackedUnreconciledPromotionTest.java
@@ -0,0 +1,685 @@
+/*
+ * 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.db.compaction;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import org.apache.cassandra.SchemaLoader;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.SimpleBuilders;
+import org.apache.cassandra.db.compaction.AbstractStrategyHolder.TaskSupplier;
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.db.marshal.Int32Type;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.dht.Bounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.replication.CoordinatorLogId;
+import org.apache.cassandra.replication.ImmutableCoordinatorLogOffsets;
+import org.apache.cassandra.replication.MutationId;
+import org.apache.cassandra.replication.MutationJournal;
+import org.apache.cassandra.replication.MutationTrackingService;
+import org.apache.cassandra.replication.Offsets;
+import org.apache.cassandra.replication.ShortMutationId;
+import org.apache.cassandra.schema.CompactionParams;
+import org.apache.cassandra.schema.KeyspaceMetadata;
+import org.apache.cassandra.schema.KeyspaceParams;
+import org.apache.cassandra.schema.ReplicationType;
+import org.apache.cassandra.schema.SchemaTestUtil;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.tcm.ClusterMetadata;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.Clock;
+import org.apache.cassandra.utils.FBUtilities;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+public class TrackedUnreconciledPromotionTest
+{
+    private static final AtomicInteger keyspaceNumber = new AtomicInteger();
+
+    /** Enough that the projection over repaired or unrepaired is non-zero, so a lost addend cannot hide. */
+    private static final long ADDITIONAL_BYTES = 1L << 30;
+
+    static
+    {
+        DatabaseDescriptor.daemonInitialization();
+    }
+
+    @BeforeClass
+    public static void setupClass()
+    {
+        SchemaLoader.prepareServer();
+        MutationJournal.start();
+        MutationTrackingService.start();
+
+        // we want to drive this manually for testing
+        MutationTrackingService.instance().pauseOffsetsPersisterForTesting();
+    }
+
+    @AfterClass
+    public static void tearDownClass()
+    {
+        MutationTrackingService.instance().resumeOffsetsPersisterForTesting();
+    }
+
+    private static void persistLogState()
+    {
+        MutationTrackingService.instance().persistLogStateForTesting(true);
+    }
+
+    private static String nextKeyspaceName()
+    {
+        return "tracked_promotion_" + keyspaceNumber.incrementAndGet();
+    }
+
+    private static ColumnFamilyStore newTrackedTable()
+    {
+        String ks = nextKeyspaceName();
+        TableMetadata tableMetadata =
+            TableMetadata.builder(ks, "tbl")
+                         .addPartitionKeyColumn("k", Int32Type.instance)
+                         .addRegularColumn("v", Int32Type.instance)
+                         .build();
+
+        SchemaLoader.createKeyspace(ks, KeyspaceParams.simple(1, ReplicationType.tracked), tableMetadata);
+
+        ColumnFamilyStore cfs = Keyspace.open(ks).getColumnFamilyStore("tbl");
+        cfs.disableAutoCompaction();
+        return cfs;
+    }
+
+    private static MutationId applyMutation(ColumnFamilyStore cfs, int k, int v)
+    {
+        TableMetadata metadata = cfs.metadata();
+        DecoratedKey key = metadata.partitioner.decorateKey(ByteBufferUtil.bytes(k));
+        MutationId id = MutationTrackingService.instance().nextMutationId(metadata.keyspace, key.getToken());
+        SimpleBuilders.MutationBuilder builder = new SimpleBuilders.MutationBuilder(id, metadata.keyspace, key);
+        PartitionUpdate.SimpleBuilder partition = builder.update(metadata);
+        partition.row().add("v", v);
+        Mutation mutation = builder.build();
+        Assert.assertFalse(mutation.id().isNone());
+        mutation.apply();
+        return mutation.id();
+    }
+
+    private static TrackedCompactionManager manager(ColumnFamilyStore cfs)
+    {
+        return (TrackedCompactionManager) cfs.getCompactionStrategyManager()
+                                             .getHolder(CompactionGroup.UNRECONCILED);
+    }
+
+    private static Set<SSTableReader> promotable(ColumnFamilyStore cfs)
+    {
+        return manager(cfs).promotableSSTables();
+    }
+
+    private static Collection<AbstractCompactionTask> promotionTasks(ColumnFamilyStore cfs)
+    {
+        return manager(cfs).getNextPromotionTasks();
+    }
+
+    private static SSTableReader flushUnreconciled(ColumnFamilyStore cfs, int k)
+    {
+        Set<SSTableReader> before = new HashSet<>(cfs.getLiveSSTables());
+        applyMutation(cfs, k, k);
+        cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+
+        Set<SSTableReader> added = new HashSet<>(cfs.getLiveSSTables());
+        added.removeAll(before);
+        assertEquals(1, added.size());
+
+        SSTableReader written = Iterables.getOnlyElement(added);
+        assertFalse(written.isRepaired());
+        assertFalse(written.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+        assertEquals(CompactionGroup.UNRECONCILED, CompactionGroup.of(written));
+        return written;
+    }
+
+    private static void runPromotion(Collection<AbstractCompactionTask> tasks)
+    {
+        for (AbstractCompactionTask task : tasks)
+            task.execute(ActiveCompactionsTracker.NOOP);
+    }
+
+    @Test
+    public void backlogDrainsInOnePass()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        CompactionStrategyManager csm = cfs.getCompactionStrategyManager();
+
+        // Baselines for the stream projection assertion below, taken while every holder is still empty.
+        int emptyIncremental = csm.getEstimatedRemainingTasks(4, ADDITIONAL_BYTES, true);
+        int emptyFull = csm.getEstimatedRemainingTasks(4, ADDITIONAL_BYTES, false);
+
+        int backlog = 4;
+        Set<SSTableReader> stranded = new HashSet<>();
+        for (int k = 0; k < backlog; k++)
+            stranded.add(flushUnreconciled(cfs, k));
+
+        assertEquals(backlog, cfs.getLiveSSTables().size());
+        assertTrue(promotable(cfs).isEmpty());
+
+        // The size tiered estimate is a side effect of picking a bucket, so run a round and hand the sstables back.
+        for (TaskSupplier supplier : manager(cfs).getBackgroundTaskSuppliers(FBUtilities.nowInSeconds()))
+        {
+            Collection<AbstractCompactionTask> rounds = supplier.getTasks();
+            if (rounds != null)
+                rounds.forEach(AbstractCompactionTask::rejected);
+        }
+
+        int pending = manager(cfs).getEstimatedRemainingTasks();
+        assertTrue(pending > 0);
+        assertEquals(pending, csm.getEstimatedRemainingTasks());
+
+        // check that this increases the pending compaction count
+        assertEquals(emptyIncremental + pending,
+                     csm.getEstimatedRemainingTasks(4, ADDITIONAL_BYTES, true));
+        assertEquals(emptyFull + pending,
+                     csm.getEstimatedRemainingTasks(4, ADDITIONAL_BYTES, false));
+
+        persistLogState();
+        assertEquals(stranded, promotable(cfs));
+
+        Collection<AbstractCompactionTask> tasks = promotionTasks(cfs);
+        assertEquals("the whole backlog should be one task, not one per sstable", 1, tasks.size());
+        runPromotion(tasks);
+
+        for (SSTableReader sstable : cfs.getLiveSSTables())
+        {
+            assertTrue(sstable.isRepaired());
+            assertTrue(sstable.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+            assertEquals(CompactionGroup.REPAIRED, CompactionGroup.of(sstable));
+            // Tombstone purging is gated on repairedAt, so the timestamp has to be real rather than the sentinel.
+            Assert.assertNotEquals(ActiveRepairService.UNREPAIRED_SSTABLE, sstable.getRepairedAt());
+        }
+        assertTrue(promotable(cfs).isEmpty());
+    }
+
+    @Test
+    public void busySSTableDoesntBlockRemainder()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+
+        Set<SSTableReader> stranded = new HashSet<>();
+        for (int k = 0; k < 3; k++)
+            stranded.add(flushUnreconciled(cfs, k));
+
+        persistLogState();
+        assertEquals(stranded, promotable(cfs));
+
+        SSTableReader busy = stranded.iterator().next();
+        try (LifecycleTransaction held = cfs.getTracker().tryModify(Collections.singleton(busy),
+                                                                    OperationType.COMPACTION))
+        {
+            assertNotNull(held);
+
+            Collection<AbstractCompactionTask> tasks = promotionTasks(cfs);
+            assertEquals(1, tasks.size());
+            runPromotion(tasks);
+        }
+
+        for (SSTableReader sstable : cfs.getLiveSSTables())
+        {
+            if (sstable.descriptor.equals(busy.descriptor))
+                assertFalse("the busy sstable should have been left alone", sstable.isRepaired());
+            else
+                assertTrue("the rest of the backlog should have drained anyway", sstable.isRepaired());
+        }
+
+        // The deferred sstable is promoted on a later pass.
+        assertEquals("the busy sstable is still eligible on a later pass", 1, promotable(cfs).size());
+        runPromotion(promotionTasks(cfs));
+        for (SSTableReader sstable : cfs.getLiveSSTables())
+            assertTrue("the whole backlog should eventually drain", sstable.isRepaired());
+    }
+
+    @Test
+    public void neitherRepairedNorOffsetFreeSSTablesArePromotable() throws IOException
+    {
+        ColumnFamilyStore repairedCase = newTrackedTable();
+        SSTableReader repaired = flushUnreconciled(repairedCase, 1);
+        persistLogState();
+        assertTrue(manager(repairedCase).isPromotable(repaired));
+
+        ImmutableCoordinatorLogOffsets offsets = repaired.getSSTableMetadata().coordinatorLogOffsets;
+        repaired.mutateRepairedAndReload(Clock.Global.currentTimeMillis(), null);
+        repaired.mutateCoordinatorLogOffsetsAndReload(offsets);
+
+        assertFalse("precondition: it still carries offsets, so the repaired guard is the one under test",
+                    repaired.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+        assertFalse(manager(repairedCase).isPromotable(repaired));
+        assertTrue(promotable(repairedCase).isEmpty());
+
+        ColumnFamilyStore offsetFreeCase = newTrackedTable();
+        SSTableReader offsetFree = flushUnreconciled(offsetFreeCase, 1);
+        offsetFree.mutateCoordinatorLogOffsetsAndReload(new ImmutableCoordinatorLogOffsets.Builder().build());
+
+        assertFalse("precondition: it stays unrepaired, so the offsets guard is the one under test",
+                    offsetFree.isRepaired());
+        assertTrue(offsetFree.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+        assertFalse(manager(offsetFreeCase).isPromotable(offsetFree));
+        assertTrue(promotable(offsetFreeCase).isEmpty());
+    }
+
+    private static TrackedCompactionManager standaloneManager(ColumnFamilyStore cfs)
+    {
+        TrackedCompactionManager manager =
+            new TrackedCompactionManager(cfs, TrackedCompactionManagerTest.SINGLE_PARTITION);
+        manager.setStrategy(CompactionParams.DEFAULT, 1);
+        return manager;
+    }
+
+    private static ShortMutationId shortIdOf(MutationId id)
+    {
+        return new ShortMutationId(id.logId(), id.offset());
+    }
+
+    private static void setOffsets(SSTableReader sstable, ShortMutationId transferId, MutationId... mutations)
+        throws IOException
+    {
+        Bounds<Token> bounds = new Bounds<>(sstable.getFirst().getToken(), sstable.getLast().getToken());
+        ImmutableCoordinatorLogOffsets.Builder builder = new ImmutableCoordinatorLogOffsets.Builder();
+        builder.addTransfer(transferId, bounds);
+        for (MutationId id : mutations)
+            builder.add(id);
+        sstable.mutateCoordinatorLogOffsetsAndReload(builder.build());
+    }
+
+    /**
+     * SSTable shouldn't contain transfer and mutation ids offsets, but if they do for some reason, both should
+     * be taken into account when promoting to repaired
+     */
+    @Test
+    public void reconciledTransferDoesNotPromoteUnreconciledMutations() throws IOException
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        TrackedCompactionManager manager = standaloneManager(cfs);
+
+        MutationId transferOrigin = applyMutation(cfs, 100, 100);
+        Set<SSTableReader> reconciled = new HashSet<>();
+        for (int k = 0; k < 3; k++)
+            reconciled.add(flushUnreconciled(cfs, k));
+
+        persistLogState();
+        ShortMutationId transferId = shortIdOf(transferOrigin);
+        for (SSTableReader sstable : reconciled)
+            setOffsets(sstable, transferId);
+
+        // Applied after the persist, so this one has not reconciled.
+        MutationId behindId = applyMutation(cfs, 99, 99);
+        SSTableReader behind = flushUnreconciled(cfs, 98);
+        setOffsets(behind, transferId, behindId);
+
+        ImmutableSet<ShortMutationId> key = ImmutableSet.of(transferId);
+        manager.addSSTables(reconciled);
+        manager.addSSTable(behind);
+
+        // It shares the silo, so eligibility is the only thing that can exclude it.
+        assertEquals(key, TrackedCompactionManager.keyOf(behind));
+        assertEquals(4, manager.sstablesFor(key).size());
+        assertFalse("its mutation has not reconciled, so it must not be promotable", manager.isPromotable(behind));
+        assertEquals("promotion takes the reconciled members only", reconciled, manager.promotableSSTables(key));
+
+        // One task covers the eligible members of a silo rather than one task each.
+        AbstractCompactionTask promotion = manager.getPromotionTask(key);
+        try
+        {
+            assertNotNull(promotion);
+            assertEquals(reconciled, promotion.transaction.originals());
+        }
+        finally
+        {
+            // it holds a lifecycle transaction over the silo, which leaks if neither run nor released
+            if (promotion != null)
+                promotion.rejected();
+        }
+    }
+
+    @Test
+    public void partlyEligibleSiloPromotesTheSubset()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+
+        Set<SSTableReader> reconciled = new HashSet<>();
+        for (int k = 0; k < 3; k++)
+            reconciled.add(flushUnreconciled(cfs, k));
+        persistLogState();
+        SSTableReader behind = flushUnreconciled(cfs, 3);
+
+        TrackedCompactionManager manager = manager(cfs);
+        assertEquals(4, manager.sstablesFor(TrackedCompactionManager.NONE).size());
+        assertEquals("only the earlier flushes are eligible", reconciled, promotable(cfs));
+
+        runPromotion(promotionTasks(cfs));
+
+        for (SSTableReader sstable : cfs.getLiveSSTables())
+        {
+            if (sstable.descriptor.equals(behind.descriptor))
+                assertFalse("the unreconciled sstable must be left alone", sstable.isRepaired());
+            else
+                assertTrue(sstable.isRepaired());
+        }
+    }
+    private static AbstractStrategyHolder holderOf(ColumnFamilyStore cfs, SSTableReader sstable)
+    {
+        return cfs.getCompactionStrategyManager().getHolder(CompactionGroup.of(sstable));
+    }
+
+    @Test
+    public void promotionMovesTheSSTableToTheRepairedHolder()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        SSTableReader stranded = flushUnreconciled(cfs, 1);
+
+        AbstractStrategyHolder tracked = manager(cfs);
+        // Starts in the tracked holder, counted as unrepaired.
+        assertTrue(tracked.containsSSTable(stranded));
+        assertTrue(cfs.metric.bytesUnrepaired.getValue() > 0);
+        assertEquals(0L, (long) cfs.metric.bytesRepaired.getValue());
+
+        persistLogState();
+        runPromotion(promotionTasks(cfs));
+
+        SSTableReader promoted = Iterables.getOnlyElement(cfs.getLiveSSTables());
+        AbstractStrategyHolder repaired = holderOf(cfs, promoted);
+
+        assertEquals(CompactionGroup.REPAIRED, CompactionGroup.of(promoted));
+        // Ownership moves between holders, and the byte metrics follow it.
+        assertTrue(repaired.containsSSTable(promoted));
+        assertFalse(tracked.containsSSTable(promoted));
+        assertEquals(0L, (long) cfs.metric.bytesUnrepaired.getValue());
+        assertTrue(cfs.metric.bytesRepaired.getValue() > 0);
+    }
+
+    @Test
+    public void compactionKeepsOffsetsIncludingReconciledOnes()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+
+        SSTableReader first = flushUnreconciled(cfs, 1);
+        persistLogState();                              // first's id reconciles, but nothing rewrites it
+        SSTableReader second = flushUnreconciled(cfs, 2);
+
+        Set<ShortMutationId> before = new HashSet<>();
+        before.addAll(idsOf(first));
+        before.addAll(idsOf(second));
+        assertEquals(2, before.size());
+
+        compact(cfs, first, second);
+
+        SSTableReader merged = Iterables.getOnlyElement(cfs.getLiveSSTables());
+        assertFalse("one id has not reconciled, so the output must not be promoted at write time",
+                    merged.isRepaired());
+        assertEquals("the union must survive, reconciled id included", before, idsOf(merged));
+
+        // ...and a second compaction of the same sstable is equally non-destructive
+        compact(cfs, merged);
+        SSTableReader again = Iterables.getOnlyElement(cfs.getLiveSSTables());
+        assertFalse(again.isRepaired());
+        assertEquals(before, idsOf(again));
+
+        persistLogState();
+        runPromotion(promotionTasks(cfs));
+
+        SSTableReader promoted = Iterables.getOnlyElement(cfs.getLiveSSTables());
+        assertTrue(promoted.isRepaired());
+        assertTrue(promoted.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+    }
+
+    private static Set<ShortMutationId> idsOf(SSTableReader sstable)
+    {
+        Set<ShortMutationId> ids = new HashSet<>();
+        for (Map.Entry<Long, Offsets.Immutable> entry : sstable.getSSTableMetadata().coordinatorLogOffsets.entries())
+            Iterables.addAll(ids, entry.getValue());
+        return ids;
+    }
+
+    private static void compact(ColumnFamilyStore cfs, SSTableReader... sstables)
+    {
+        List<Descriptor> descriptors = new ArrayList<>();
+        for (SSTableReader sstable : sstables)
+            descriptors.add(sstable.descriptor);
+        FBUtilities.waitOnFuture(CompactionManager.instance.submitUserDefined(cfs, descriptors, CompactionManager.NO_GC));
+    }
+
+    @Test
+    public void unpromotableGaugeTest() throws IOException
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        assertEquals(0, (int) cfs.metric.unpromotableSSTables.getValue());
+
+        SSTableReader stranded = flushUnreconciled(cfs, 1);
+        assertEquals("carrying offsets, so it is promotable and does not count",
+                     0, (int) cfs.metric.unpromotableSSTables.getValue());
+
+        // Clearing the offsets while leaving it unrepaired is the state the gauge is for. Promotion cannot produce it,
+        // because it sets repairedAt in the same mutation; nodetool verify resetting repairedAt can.
+        stranded.mutateCoordinatorLogOffsetsAndReload(new ImmutableCoordinatorLogOffsets.Builder().build());
+        assertFalse(stranded.isRepaired());
+        assertEquals("unrepaired with no offsets must be counted",
+                     1, (int) cfs.metric.unpromotableSSTables.getValue());
+
+        // A promoted sstable also has no offsets, but it is repaired, so it must not be counted.
+        ColumnFamilyStore other = newTrackedTable();
+        flushUnreconciled(other, 1);
+        persistLogState();
+        runPromotion(promotionTasks(other));
+        SSTableReader promoted = Iterables.getOnlyElement(other.getLiveSSTables());
+        assertTrue(promoted.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+        assertTrue(promoted.isRepaired());
+        assertEquals("repaired, so not unpromotable however few offsets it carries",
+                     0, (int) other.metric.unpromotableSSTables.getValue());
+    }
+
+    /**
+     * Drops the keyspace out of mutation tracking, as a rollback ALTER does. This wipes the log index for the keyspace
+     * too, so anything the discard path relied on {@link MutationTrackingService#isDurablyReconciled} for would throw
+     * rather than answer.
+     */
+    private static void stopTracking(ColumnFamilyStore cfs)
+    {
+        KeyspaceMetadata ksm = ClusterMetadata.current().schema.getKeyspaceMetadata(cfs.getKeyspaceName());
+        SchemaTestUtil.addOrUpdateKeyspace(ksm.withSwapped(KeyspaceParams.simple(1, ReplicationType.untracked)));
+
+        assertFalse("precondition: the keyspace must have left mutation tracking",
+                    ClusterMetadata.current().schema.getKeyspaceMetadata(cfs.getKeyspaceName())
+                                   .params.replicationType.isTracked());
+        assertNull("precondition: the rollback must leave no ranges pending migration",
+                   ClusterMetadata.current().mutationTrackingMigrationState.getKeyspaceInfo(cfs.getKeyspaceName()));
+    }
+
+    /**
+     * A keyspace that has left mutation tracking has the offsets discarded from every sstable it still holds, which
+     * moves them to {@link CompactionGroup#UNREPAIRED}. Nothing will reconcile them once tracking is off, so repair is
+     * the only mechanism left that can make the data consistent, and unrepaired is what asks for repair.
+     */
+    @Test
+    public void leavingTrackingDiscardsOffsets()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+
+        Set<SSTableReader> stranded = new HashSet<>();
+        for (int k = 0; k < 4; k++)
+            stranded.add(flushUnreconciled(cfs, k));
+
+        // Unreconciled, so promotion would leave them where they are.
+        assertTrue(promotable(cfs).isEmpty());
+        assertTrue("precondition: promotion has nothing to do", promotionTasks(cfs).isEmpty());
+
+        stopTracking(cfs);
+
+        Collection<AbstractCompactionTask> tasks = manager(cfs).getNextTrackedTasks();
+        assertEquals("every silo should be covered by one task, not one task per silo", 1, tasks.size());
+        runPromotion(tasks);
+
+        for (SSTableReader sstable : cfs.getLiveSSTables())
+        {
+            assertTrue("the offsets must be gone: " + sstable,
+                       sstable.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+            assertFalse("discarding offsets must not mark anything repaired: " + sstable, sstable.isRepaired());
+            assertFalse(sstable.isPendingRepair());
+            assertEquals("the sstable must now be classified for the unrepaired holder: " + sstable,
+                         CompactionGroup.UNREPAIRED, CompactionGroup.of(sstable));
+        }
+
+        assertEquals("no data may be lost: the sstables are mutated in place, not rewritten",
+                     stranded.size(), cfs.getLiveSSTables().size());
+    }
+
+    /**
+     * The notification the discard fires has to re-sort the sstables between holders, or the tracked holder keeps
+     * referencing them and every later round scans them again.
+     */
+    @Test
+    public void discardedSSTablesLeaveTheTrackedHolder()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        SSTableReader stranded = flushUnreconciled(cfs, 1);
+
+        assertTrue("precondition: the tracked holder must hold it", manager(cfs).containsSSTable(stranded));
+
+        stopTracking(cfs);
+        runPromotion(manager(cfs).getNextTrackedTasks());
+
+        assertFalse("the tracked holder must have released it", manager(cfs).containsSSTable(stranded));
+        assertTrue("nothing is left for a later round to find", manager(cfs).getNextTrackedTasks().isEmpty());
+        assertTrue(cfs.getCompactionStrategyManager().getHolder(CompactionGroup.UNREPAIRED).containsSSTable(stranded));
+    }
+
+    /** While the keyspace is still tracked, the discard must not fire and promotion must stay in charge. */
+    @Test
+    public void trackedKeyspaceKeepsItsOffsets()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        SSTableReader stranded = flushUnreconciled(cfs, 1);
+
+        assertTrue("an unreconciled sstable in a tracked keyspace has nothing to do yet",
+                   manager(cfs).getNextTrackedTasks().isEmpty());
+        assertFalse(stranded.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+
+        // Once it reconciles, the same entry point promotes it rather than discarding the offsets.
+        persistLogState();
+        runPromotion(manager(cfs).getNextTrackedTasks());
+
+        SSTableReader promoted = Iterables.getOnlyElement(cfs.getLiveSSTables());
+        assertTrue("a tracked keyspace reaches repaired through promotion", promoted.isRepaired());
+    }
+
+    /**
+     * The log to shard index has to survive the keyspace leaving mutation tracking.
+     * {@code MutationTrackingService.onNewClusterMetadata} empties it and depends on each arm of
+     * {@code applyUpdatedMetadata} to announce the logs of the shards it keeps. The arm that carries a rolled back
+     * keyspace forward did not, which left the shards reachable by token and unreachable by log id, so
+     * {@link MutationTrackingService#isDurablyReconciled} threw instead of answering.
+     */
+    @Test
+    public void logIdsStillResolveAfterLeavingTracking()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        MutationId id = applyMutation(cfs, 1, 1);
+        ImmutableCoordinatorLogOffsets offsets = new ImmutableCoordinatorLogOffsets.Builder().add(id).build();
+
+        assertFalse("precondition: the log id resolves and has not reconciled yet",
+                    MutationTrackingService.instance().isDurablyReconciled(offsets));
+
+        stopTracking(cfs);
+
+        assertFalse("the log id must still resolve once the keyspace has left tracking",
+                    MutationTrackingService.instance().isDurablyReconciled(offsets));
+    }
+
+    /**
+     * A holder that throws part way through the maximal task loop must not leave the sstables of the holders already
+     * visited marked compacting. They would be excluded from every later compaction attempt as well, and the reference
+     * reaper reports them as leaked for the life of the process.
+     */
+    @Test
+    public void throwingHolderRejectsExistingTasks() throws IOException
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+
+        // Two sstables for the unrepaired holder, which the maximal task loop visits before the tracked one, so it has
+        // something to hand over before it fails.
+        Set<SSTableReader> unrepaired = new HashSet<>();
+        unrepaired.add(flushUnreconciled(cfs, 1));
+        unrepaired.add(flushUnreconciled(cfs, 2));
+        cfs.getCompactionStrategyManager().clearCoordinatorLogOffsets(unrepaired);
+        for (SSTableReader sstable : unrepaired)
+            assertEquals(CompactionGroup.UNREPAIRED, CompactionGroup.of(sstable));
+
+        // One sstable left in the tracked holder, carrying a log id no shard owns, which is what promotion throws on.
+        SSTableReader stranded = flushUnreconciled(cfs, 3);
+        long unknownLogId = CoordinatorLogId.asLong(99, 99);
+        stranded.mutateCoordinatorLogOffsetsAndReload(new ImmutableCoordinatorLogOffsets.Builder()
+                                                      .add(new MutationId(unknownLogId, 0, 0))
+                                                      .build());
+        assertEquals(CompactionGroup.UNRECONCILED, CompactionGroup.of(stranded));
+
+        try
+        {
+            cfs.getCompactionStrategyManager()
+               .getMaximalTasks(Integer.MAX_VALUE, false, Integer.MAX_VALUE, OperationType.MAJOR_COMPACTION);
+            Assert.fail("collecting maximal tasks should have failed on the unresolvable log id");
+        }
+        catch (Throwable t)
+        {
+            assertTrue("failed for a reason other than the unresolvable log id: " + t, mentionsUnknownShard(t));
+        }
+
+        assertTrue("the failed collection must not leave sstables marked compacting: " + cfs.getTracker().getCompacting(),
+                   cfs.getTracker().getCompacting().isEmpty());
+    }
+
+    private static boolean mentionsUnknownShard(Throwable t)
+    {
+        for (Throwable cause = t; cause != null; cause = cause.getCause() == cause ? null : cause.getCause())
+        {
+            if (cause.getMessage() != null && cause.getMessage().contains("Could not find shard for logId"))
+                return true;
+        }
+        return false;
+    }
+}
diff --git a/test/unit/org/apache/cassandra/db/lifecycle/LifecycleTransactionTest.java b/test/unit/org/apache/cassandra/db/lifecycle/LifecycleTransactionTest.java
index 8a7905dffc..eeaaf7224e 100644
--- a/test/unit/org/apache/cassandra/db/lifecycle/LifecycleTransactionTest.java
+++ b/test/unit/org/apache/cassandra/db/lifecycle/LifecycleTransactionTest.java
@@ -21,7 +21,6 @@ package org.apache.cassandra.db.lifecycle;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
 
 import com.google.common.util.concurrent.Uninterruptibles;
 
@@ -36,6 +35,7 @@ import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.db.compaction.OperationType;
 import org.apache.cassandra.db.lifecycle.LifecycleTransaction.ReaderState;
 import org.apache.cassandra.db.lifecycle.LifecycleTransaction.ReaderState.Action;
+import org.apache.cassandra.db.memtable.LogDomainBounds;
 import org.apache.cassandra.io.sstable.format.SSTableFormat;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.schema.MockSchema;
@@ -315,7 +315,8 @@ public class LifecycleTransactionTest extends AbstractTransactionalTest
 
         private static Tracker tracker(ColumnFamilyStore cfs, List<SSTableReader> readers)
         {
-            Tracker tracker = new Tracker(cfs, cfs.createMemtable(new AtomicReference<>(CommitLogPosition.NONE)), false);
+            LogDomainBounds bounds = LogDomainBounds.of(CommitLogPosition.NONE);
+            Tracker tracker = new Tracker(cfs, cfs.createMemtable(bounds), bounds, false);
             tracker.addInitialSSTables(readers);
             return tracker;
         }
diff --git a/test/unit/org/apache/cassandra/db/lifecycle/TrackerTest.java b/test/unit/org/apache/cassandra/db/lifecycle/TrackerTest.java
index 57e76c9a46..ebb303232a 100644
--- a/test/unit/org/apache/cassandra/db/lifecycle/TrackerTest.java
+++ b/test/unit/org/apache/cassandra/db/lifecycle/TrackerTest.java
@@ -23,7 +23,6 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Optional;
 import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
 
 import com.google.common.base.Predicate;
 import com.google.common.base.Predicates;
@@ -37,10 +36,14 @@ import org.junit.Test;
 import org.apache.cassandra.ServerTestUtils;
 import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.LogDomain;
 import org.apache.cassandra.db.commitlog.CommitLog;
 import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.db.compaction.OperationType;
+import org.apache.cassandra.db.memtable.DomainMemtable;
+import org.apache.cassandra.db.memtable.LogDomainBounds;
 import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.memtable.SplitDomainMemtable;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.io.sstable.keycache.KeyCacheSupport;
 import org.apache.cassandra.notifications.INotification;
@@ -272,21 +275,23 @@ public class TrackerTest
         Tracker tracker = cfs.getTracker();
         tracker.subscribe(listener);
 
-        Memtable prev1 = tracker.switchMemtable(true, cfs.createMemtable(new AtomicReference<>(CommitLog.instance.getCurrentPosition())));
+        LogDomainBounds bounds1 = LogDomainBounds.atCurrentPositions();
+        Memtable prev1 = tracker.switchMemtable(true, cfs.createMemtable(bounds1), bounds1);
         OpOrder.Group write1 = cfs.keyspace.writeOrder.getCurrent();
         OpOrder.Barrier barrier1 = cfs.keyspace.writeOrder.newBarrier();
-        prev1.switchOut(barrier1, new AtomicReference<>(CommitLog.instance.getCurrentPosition()));
+        prev1.switchOut(barrier1, LogDomainBounds.atCurrentPositions());
         barrier1.issue();
-        Memtable prev2 = tracker.switchMemtable(false, cfs.createMemtable(new AtomicReference<>(CommitLog.instance.getCurrentPosition())));
+        LogDomainBounds bounds2 = LogDomainBounds.atCurrentPositions();
+        Memtable prev2 = tracker.switchMemtable(false, cfs.createMemtable(bounds2), bounds2);
         OpOrder.Group write2 = cfs.keyspace.writeOrder.getCurrent();
         OpOrder.Barrier barrier2 = cfs.keyspace.writeOrder.newBarrier();
-        prev2.switchOut(barrier2, new AtomicReference<>(CommitLog.instance.getCurrentPosition()));
+        prev2.switchOut(barrier2, LogDomainBounds.atCurrentPositions());
         barrier2.issue();
         Memtable cur = tracker.getView().getCurrentMemtable();
         OpOrder.Group writecur = cfs.keyspace.writeOrder.getCurrent();
-        Assert.assertEquals(prev1, tracker.getMemtableFor(write1, CommitLogPosition.NONE));
-        Assert.assertEquals(prev2, tracker.getMemtableFor(write2, CommitLogPosition.NONE));
-        Assert.assertEquals(cur, tracker.getMemtableFor(writecur, CommitLogPosition.NONE));
+        Assert.assertEquals(prev1, tracker.getMemtableFor(write1, CommitLogPosition.NONE, LogDomain.COMMIT_LOG));
+        Assert.assertEquals(prev2, tracker.getMemtableFor(write2, CommitLogPosition.NONE, LogDomain.COMMIT_LOG));
+        Assert.assertEquals(cur, tracker.getMemtableFor(writecur, CommitLogPosition.NONE, LogDomain.COMMIT_LOG));
         Assert.assertEquals(2, listener.received.size());
         Assert.assertTrue(listener.received.get(0) instanceof MemtableRenewedNotification);
         Assert.assertTrue(listener.received.get(1) instanceof MemtableSwitchedNotification);
@@ -321,8 +326,9 @@ public class TrackerTest
         tracker = cfs.getTracker();
         listener = new MockListener(false);
         tracker.subscribe(listener);
-        Memtable next1 = cfs.createMemtable(new AtomicReference<>(CommitLog.instance.getCurrentPosition()));
-        prev1 = tracker.switchMemtable(false, next1);
+        LogDomainBounds nextBounds = LogDomainBounds.atCurrentPositions();
+        DomainMemtable next1 = cfs.createMemtable(nextBounds);
+        prev1 = tracker.switchMemtable(false, next1, nextBounds);
         tracker.markFlushing(prev1);
         reader = MockSchema.sstable(0, 10, true, cfs);
         cfs.invalidate(false);
@@ -362,7 +368,7 @@ public class TrackerTest
         tracker.notifySSTableRepairedStatusChanged(singleton(r1));
         Assert.assertEquals(singleton(r1), ((SSTableRepairStatusChanged) listener.received.get(0)).sstables);
         listener.received.clear();
-        Memtable memtable = MockSchema.memtable(cfs);
+        DomainMemtable memtable = MockSchema.memtable(cfs);
         tracker.notifyRenewed(memtable);
         Assert.assertEquals(memtable, ((MemtableRenewedNotification) listener.received.get(0)).renewed);
         listener.received.clear();
@@ -384,4 +390,37 @@ public class TrackerTest
         listener.received.clear();
     }
 
+    /**
+     * {@code Tracker.installSplit} reads the current memtable outside {@code viewUpdateLock}, so it can race with a
+     * flush before the split applies. This test emulates that race and confirms that the split fails and nothing breaks
+     */
+    @Test
+    public void retiredGenerationCantBeSplit()
+    {
+        ColumnFamilyStore cfs = MockSchema.newCFS();
+        Tracker tracker = cfs.getTracker();
+        DomainMemtable retiring = (DomainMemtable) tracker.getView().getCurrentMemtable();
+
+        // Stand in for the flush that wins the race: switchMemtable retires the generation installSplit had read.
+        LogDomainBounds replacementBounds = LogDomainBounds.atCurrentPositions();
+        tracker.switchMemtable(false, cfs.createMemtable(replacementBounds), replacementBounds);
+        // The window the guard covers: no longer current, but not yet moved to flushingMemtables.
+        Assert.assertNotEquals(retiring, tracker.getView().getCurrentMemtable());
+        Assert.assertTrue("still live until marked flushing", tracker.getView().liveMemtables.contains(retiring));
+
+        // The split installSplit would have applied, had it not rechecked under the lock.
+        DomainMemtable journal = cfs.createMemtable(tracker.getView().currentBounds.forDomain(LogDomain.MUTATION_JOURNAL),
+                                              LogDomain.MUTATION_JOURNAL);
+        SplitDomainMemtable wrapper = new SplitDomainMemtable(journal, retiring, retiring.getMemtableId());
+        // Tracker.apply returns null when the permit predicate rejects the view.
+        Assert.assertNull("the split transform must not have run against a retired generation",
+                          tracker.apply(View.canSplitMemtable(retiring), View.splitMemtable(retiring, wrapper)));
+        Assert.assertFalse(Iterables.any(tracker.getView().liveMemtables, m -> m instanceof SplitDomainMemtable));
+
+        // markFlushing is what a split would have broken: it filters retiring out of liveMemtables and asserts the
+        // list shrank by one, which a wrapper in retiring's place would fail.
+        tracker.markFlushing(retiring);
+        Assert.assertTrue(tracker.getView().flushingMemtables.contains(retiring));
+    }
+
 }
diff --git a/test/unit/org/apache/cassandra/db/lifecycle/ViewTest.java b/test/unit/org/apache/cassandra/db/lifecycle/ViewTest.java
index 6bd3896fb9..0f1141a1c0 100644
--- a/test/unit/org/apache/cassandra/db/lifecycle/ViewTest.java
+++ b/test/unit/org/apache/cassandra/db/lifecycle/ViewTest.java
@@ -37,6 +37,8 @@ import org.apache.cassandra.ServerTestUtils;
 import org.apache.cassandra.db.ColumnFamilyStore;
 import org.apache.cassandra.db.PartitionPosition;
 import org.apache.cassandra.db.commitlog.CommitLog;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+import org.apache.cassandra.db.memtable.LogDomainBounds;
 import org.apache.cassandra.db.memtable.Memtable;
 import org.apache.cassandra.dht.AbstractBounds;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
@@ -167,13 +169,13 @@ public class ViewTest
         Memtable memtable1 = initialView.getCurrentMemtable();
         Memtable memtable2 = MockSchema.memtable(cfs);
 
-        cur = View.switchMemtable(memtable2).apply(cur);
+        cur = View.switchMemtable(memtable2, LogDomainBounds.of(CommitLogPosition.NONE)).apply(cur);
         Assert.assertEquals(2, cur.liveMemtables.size());
         Assert.assertEquals(memtable1, cur.liveMemtables.get(0));
         Assert.assertEquals(memtable2, cur.getCurrentMemtable());
 
         Memtable memtable3 = MockSchema.memtable(cfs);
-        cur = View.switchMemtable(memtable3).apply(cur);
+        cur = View.switchMemtable(memtable3, LogDomainBounds.of(CommitLogPosition.NONE)).apply(cur);
         Assert.assertEquals(3, cur.liveMemtables.size());
         Assert.assertEquals(0, cur.flushingMemtables.size());
         Assert.assertEquals(memtable1, cur.liveMemtables.get(0));
@@ -226,6 +228,8 @@ public class ViewTest
         for (int i = 0 ; i < sstableCount ; i++)
             sstables.add(MockSchema.sstable(i, keepRef, cfs));
         return new View(ImmutableList.copyOf(memtables), Collections.<Memtable>emptyList(), Helpers.identityMap(sstables),
-                        Collections.<SSTableReader, SSTableReader>emptyMap(), buildSSTableIntervalTree(sstables));
+                        Collections.<SSTableReader, SSTableReader>emptyMap(), buildSSTableIntervalTree(sstables),
+                        // View requires a boundary when it holds memtables, and none when it holds none.
+                        memtables.isEmpty() ? null : LogDomainBounds.of(CommitLogPosition.NONE));
     }
 }
diff --git a/test/unit/org/apache/cassandra/db/memtable/LogDomainBoundsTest.java b/test/unit/org/apache/cassandra/db/memtable/LogDomainBoundsTest.java
new file mode 100644
index 0000000000..17019055be
--- /dev/null
+++ b/test/unit/org/apache/cassandra/db/memtable/LogDomainBoundsTest.java
@@ -0,0 +1,117 @@
+/*
+ * 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.db.memtable;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Function;
+
+import org.junit.Test;
+
+import org.apache.cassandra.db.LogDomain;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+public class LogDomainBoundsTest
+{
+    @Test(timeout = 30_000)
+    public void basicSeal()
+    {
+        LogDomainBounds bounds = LogDomainBounds.unset();
+
+        bounds.seal(positions(new CommitLogPosition(1, 100), new CommitLogPosition(9000, 0)));
+
+        assertEquals(sealedAt(1, 100), bounds.get(LogDomain.COMMIT_LOG));
+        assertEquals(sealedAt(9000, 0), bounds.get(LogDomain.MUTATION_JOURNAL));
+    }
+
+    @Test(timeout = 30_000)
+    public void sealWithRacingWrite()
+    {
+        LogDomainBounds bounds = LogDomainBounds.unset();
+        AtomicInteger reads = new AtomicInteger();
+
+        // The first read plants a higher position behind it, standing in for the racing write.
+        Function<LogDomain, CommitLogPosition> log = domain -> {
+            int read = reads.incrementAndGet();
+            if (read == 1)
+                bounds.forDomain(LogDomain.COMMIT_LOG).set(new CommitLogPosition(1, 500));
+            return new CommitLogPosition(1, read == 1 ? 100 : 600);
+        };
+
+        bounds.sealIfUnset(LogDomain.COMMIT_LOG, log);
+
+        // Two reads means the loop re-read exactly once
+        assertEquals(2, reads.get());
+        assertEquals(sealedAt(1, 600), bounds.get(LogDomain.COMMIT_LOG));
+    }
+
+    /**
+     * seal shouldn't set positions for log domains not in use
+     */
+    @Test(timeout = 30_000)
+    public void singleDomainSeal()
+    {
+        LogDomainBounds bounds = LogDomainBounds.unset();
+
+        // The state before the journal starts: it reports no position, while the commit log still has one.
+        bounds.seal(positions(new CommitLogPosition(1, 100), null));
+
+        assertEquals(sealedAt(1, 100), bounds.get(LogDomain.COMMIT_LOG));
+        assertNull(bounds.get(LogDomain.MUTATION_JOURNAL));
+    }
+
+    /** sealIfUnset must not move a bound the previous flush already fixed, or two adjacent spans overlap. */
+    @Test(timeout = 30_000)
+    public void sealIfUnset()
+    {
+        LogDomainBounds bounds = LogDomainBounds.unset();
+        CommitLogPosition inherited = new CommitLogPosition(7, 42);
+        bounds.forDomain(LogDomain.COMMIT_LOG).set(inherited);
+
+        bounds.sealIfUnset(LogDomain.COMMIT_LOG, positions(new CommitLogPosition(7, 99), null));
+
+        // commit log domain was already set, so nothing should have changed
+        assertEquals(inherited, bounds.get(LogDomain.COMMIT_LOG));
+    }
+
+    /** seal must not overwrite a bound already sealed as LastCommitLogPosition. */
+    @Test(timeout = 30_000)
+    public void sealSkipsAlreadySealedBound()
+    {
+        LogDomainBounds bounds = LogDomainBounds.unset();
+        Memtable.LastCommitLogPosition propagated = sealedAt(1, 100);
+        bounds.forDomain(LogDomain.COMMIT_LOG).set(propagated);
+
+        bounds.seal(positions(new CommitLogPosition(1, 500), null));
+
+        assertEquals(propagated, bounds.get(LogDomain.COMMIT_LOG));
+    }
+
+    private static Function<LogDomain, CommitLogPosition> positions(CommitLogPosition commitLog, CommitLogPosition journal)
+    {
+        return domain -> domain.isJournal() ? journal : commitLog;
+    }
+
+    private static Memtable.LastCommitLogPosition sealedAt(long segmentId, int position)
+    {
+        return new Memtable.LastCommitLogPosition(new CommitLogPosition(segmentId, position));
+    }
+}
diff --git a/test/unit/org/apache/cassandra/db/memtable/SplitDomainMemtableTest.java b/test/unit/org/apache/cassandra/db/memtable/SplitDomainMemtableTest.java
new file mode 100644
index 0000000000..b8d8ff1c72
--- /dev/null
+++ b/test/unit/org/apache/cassandra/db/memtable/SplitDomainMemtableTest.java
@@ -0,0 +1,731 @@
+/*
+ * 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.db.memtable;
+
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+
+import com.google.common.collect.ImmutableSet;
+
+import org.assertj.core.api.Assertions;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import org.apache.cassandra.SchemaLoader;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.DataRange;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.LogDomain;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.SimpleBuilders;
+import org.apache.cassandra.db.commitlog.CommitLog;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+import org.apache.cassandra.db.commitlog.CommitLogSegment;
+import org.apache.cassandra.db.compaction.OperationType;
+import org.apache.cassandra.db.filter.ColumnFilter;
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.db.marshal.Int32Type;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.db.partitions.UnfilteredPartitionIterator;
+import org.apache.cassandra.db.rows.EncodingStats;
+import org.apache.cassandra.db.rows.UnfilteredRowIterator;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.index.transactions.UpdateTransaction;
+import org.apache.cassandra.io.sstable.SSTableProvenance;
+import org.apache.cassandra.io.sstable.SSTableReadsListener;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.replication.MutationId;
+import org.apache.cassandra.replication.MutationJournal;
+import org.apache.cassandra.replication.MutationTrackingService;
+import org.apache.cassandra.schema.KeyspaceParams;
+import org.apache.cassandra.schema.ReplicationType;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.concurrent.OpOrder;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * A table takes writes from both logs while part of its token range is migrating, and {@link SplitDomainMemtable} holds
+ * one internal memtable per {@link LogDomain} so that each write is bounded against its own log. Every consumer of a
+ * {@link Memtable} keeps working without learning it got a wrapper, so the cases here are grouped by consumer, in three
+ * sections: what a consumer reads off a split generation, how the tracker installs one, and how one flushes.
+ */
+public class SplitDomainMemtableTest
+{
+    private static final AtomicInteger keyspaceNumber = new AtomicInteger();
+
+    static
+    {
+        DatabaseDescriptor.daemonInitialization();
+    }
+
+    @BeforeClass
+    public static void setupClass()
+    {
+        SchemaLoader.prepareServer();
+        MutationJournal.start();
+        MutationTrackingService.start();
+    }
+
+    private static ColumnFamilyStore newTrackedTable()
+    {
+        String ks = "domain_split_" + keyspaceNumber.incrementAndGet();
+        TableMetadata metadata = TableMetadata.builder(ks, "tbl")
+                                              .addPartitionKeyColumn("k", Int32Type.instance)
+                                              .addRegularColumn("v", Int32Type.instance)
+                                              .build();
+        SchemaLoader.createKeyspace(ks, KeyspaceParams.simple(1, ReplicationType.tracked), metadata);
+        ColumnFamilyStore cfs = Keyspace.open(ks).getColumnFamilyStore("tbl");
+        cfs.disableAutoCompaction();
+        return cfs;
+    }
+
+    private static DomainMemtable internal(ColumnFamilyStore cfs, LogDomainBounds bounds, LogDomain domain)
+    {
+        return cfs.createMemtable(bounds.forDomain(domain), domain);
+    }
+
+    private static SplitDomainMemtable newWrapper(ColumnFamilyStore cfs)
+    {
+        LogDomainBounds bounds = LogDomainBounds.atCurrentPositions();
+        return new SplitDomainMemtable(internal(cfs, bounds, LogDomain.COMMIT_LOG),
+                                       internal(cfs, bounds, LogDomain.MUTATION_JOURNAL),
+                                       1L);
+    }
+
+    private static DecoratedKey key(ColumnFamilyStore cfs, int k)
+    {
+        return cfs.metadata().partitioner.decorateKey(ByteBufferUtil.bytes(k));
+    }
+
+    private static void write(ColumnFamilyStore cfs, Memtable memtable, int k, LogDomain domain)
+    {
+        write(cfs, memtable, k, domain, FBUtilities.timestampMicros());
+    }
+
+    private static void write(ColumnFamilyStore cfs, Memtable memtable, int k, LogDomain domain, long timestamp)
+    {
+        TableMetadata metadata = cfs.metadata();
+        DecoratedKey key = key(cfs, k);
+        // An untracked write carries no mutation id, which is what keeps coordinator log offsets off the sstable a
+        // commit-log-domain memtable flushes. MigrationRouter guarantees the two agree for a base table.
+        MutationId id = domain.isJournal()
+                        ? MutationTrackingService.instance().nextMutationId(metadata.keyspace, key.getToken())
+                        : MutationId.none();
+        SimpleBuilders.MutationBuilder builder = new SimpleBuilders.MutationBuilder(id, metadata.keyspace, key);
+        builder.timestamp(timestamp);
+        builder.update(metadata).row().add("v", k);
+        Mutation mutation = builder.build();
+        try (OpOrder.Group group = Keyspace.writeOrder.start())
+        {
+            memtable.put(id, mutation.getPartitionUpdate(metadata), UpdateTransaction.NO_OP, group, domain);
+        }
+    }
+
+    /** The keys a range read finds, which is the one read path that does not take a key. */
+    private static Set<DecoratedKey> partitionKeys(Memtable memtable)
+    {
+        Set<DecoratedKey> keys = new HashSet<>();
+        TableMetadata metadata = memtable.metadata();
+        try (UnfilteredPartitionIterator partitions = memtable.partitionIterator(ColumnFilter.all(metadata),
+                                                                                DataRange.allData(metadata.partitioner),
+                                                                                SSTableReadsListener.NOOP_LISTENER))
+        {
+            while (partitions.hasNext())
+            {
+                try (UnfilteredRowIterator rows = partitions.next())
+                {
+                    keys.add(rows.partitionKey());
+                }
+            }
+        }
+        return keys;
+    }
+
+    // ---- What a consumer reads off a split generation ----------------------------------------------------------
+
+    /**
+     * Commit log segment reclamation asks which memtables still hold data below a position, through
+     * {@link ColumnFamilyStore#forceFlush(CommitLogPosition)}. Only the commit-log internal can hold
+     * commit-log-derived rows, so the wrapper answers from it alone. A generation whose journal internal is the dirty
+     * one holds no commit log data, and must not pin the segment.
+     */
+    @Test
+    public void journalOnlySplitMemtableDoesntPinCommitlogSegments()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        LogDomainBounds bounds = LogDomainBounds.atCurrentPositions();
+        DomainMemtable journalInternal = internal(cfs, bounds, LogDomain.MUTATION_JOURNAL);
+        write(cfs, journalInternal, 1, LogDomain.MUTATION_JOURNAL);
+
+        // Advance the commit log past the journal internal's creation, then
+        // create the commit-log internal above the position under test and leave it clean.
+        appendToCommitLog();
+        CommitLogPosition reclaimBelow = CommitLog.instance.getCurrentPosition();
+        appendToCommitLog();
+        LogDomainBounds clBounds = LogDomainBounds.atCurrentPositions();
+        DomainMemtable commitLogInternal = internal(cfs, clBounds, LogDomain.COMMIT_LOG);
+        SplitDomainMemtable wrapper = new SplitDomainMemtable(commitLogInternal, journalInternal,
+                                                             journalInternal.getMemtableId());
+
+        assertFalse(wrapper.flushSourceFor(LogDomain.COMMIT_LOG).mayContainDataBefore(reclaimBelow));
+    }
+
+    @Test
+    public void splitDomainMemtablePinsCommitlogSegments()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        LogDomainBounds bounds = LogDomainBounds.atCurrentPositions();
+        DomainMemtable commitLogInternal = internal(cfs, bounds, LogDomain.COMMIT_LOG);
+        write(cfs, commitLogInternal, 1, LogDomain.COMMIT_LOG);
+
+        appendToCommitLog();
+        CommitLogPosition reclaimBelow = CommitLog.instance.getCurrentPosition();
+        DomainMemtable journalInternal = internal(cfs, bounds, LogDomain.MUTATION_JOURNAL);
+        SplitDomainMemtable wrapper = new SplitDomainMemtable(commitLogInternal, journalInternal,
+                                                             commitLogInternal.getMemtableId());
+
+        assertTrue(wrapper.flushSourceFor(LogDomain.COMMIT_LOG).mayContainDataBefore(reclaimBelow));
+        assertEquals(commitLogInternal.getCommitLogLowerBound(), wrapper.flushSourceFor(LogDomain.COMMIT_LOG).getCommitLogLowerBound());
+    }
+
+    private static void appendToCommitLog()
+    {
+        String ks = "domain_split_untracked_" + keyspaceNumber.incrementAndGet();
+        TableMetadata metadata = TableMetadata.builder(ks, "tbl")
+                                              .addPartitionKeyColumn("k", Int32Type.instance)
+                                              .addRegularColumn("v", Int32Type.instance)
+                                              .build();
+        SchemaLoader.createKeyspace(ks, KeyspaceParams.simple(1, ReplicationType.untracked), metadata);
+
+        DecoratedKey key = metadata.partitioner.decorateKey(ByteBufferUtil.bytes(1));
+        SimpleBuilders.MutationBuilder builder = new SimpleBuilders.MutationBuilder(MutationId.none(), ks, key);
+        builder.update(metadata).row().add("v", 1);
+        builder.build().apply();
+    }
+
+    /**
+     * What the memtable pool and the read short-circuit read off a generation. Under-reporting a size lets a generation
+     * grow past its flush threshold. Over-reporting a minimum timestamp lets
+     * {@code SinglePartitionReadCommand} and {@code CompactionController} skip an sstable that is still needed.
+     */
+    @Test
+    public void accountingCoversBothInternals()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        SplitDomainMemtable wrapper = newWrapper(cfs);
+        Memtable commitLogInternal = wrapper.internalFor(LogDomain.COMMIT_LOG);
+        Memtable journalInternal = wrapper.internalFor(LogDomain.MUTATION_JOURNAL);
+
+        write(cfs, wrapper, 1, LogDomain.MUTATION_JOURNAL);
+
+        // A clean memtable reports Long.MAX_VALUE, so answering from the commit-log internal alone would report that.
+        assertEquals(Long.MAX_VALUE, commitLogInternal.getMinTimestamp());
+        assertNotEquals(Long.MAX_VALUE, journalInternal.getMinTimestamp());
+        assertEquals(journalInternal.getMinTimestamp(), wrapper.getMinTimestamp());
+
+        write(cfs, commitLogInternal, 2, LogDomain.COMMIT_LOG);
+
+        // One row went to each internal, so a sum differs from either internal's own count.
+        assertEquals(2, wrapper.partitionCount());
+        assertEquals(2, wrapper.operationCount());
+        assertEquals(commitLogInternal.getLiveDataSize() + journalInternal.getLiveDataSize(),
+                     wrapper.getLiveDataSize());
+        assertTrue("neither internal alone accounts for the size",
+                   wrapper.getLiveDataSize() > Math.max(commitLogInternal.getLiveDataSize(),
+                                                        journalInternal.getLiveDataSize()));
+        assertEquals(Math.min(commitLogInternal.getMinTimestamp(), journalInternal.getMinTimestamp()),
+                     wrapper.getMinTimestamp());
+        assertEquals(Math.min(commitLogInternal.getMinLocalDeletionTime(), journalInternal.getMinLocalDeletionTime()),
+                     wrapper.getMinLocalDeletionTime());
+    }
+
+    /**
+     * {@code getMinTimestamp} has two kinds of answer and both are numbers: a real timestamp, or
+     * {@code NO_MIN_TIMESTAMP} (-1) meaning the memtable has no usable timestamp. {@code SinglePartitionReadCommand} and
+     * {@code CompactionController} test for the sentinel before using the value, so a generation answering -1 while it
+     * holds timestamped rows makes them skip a comparison they should make.
+     *
+     * An internal answers -1 when its tracked minimum equals the epoch {@code EncodingStats} substitutes for an update
+     * carrying no liveness timestamp, so the test writes that epoch directly. Since -1 sorts below every real timestamp,
+     * a plain minimum over the two internals returns it.
+     */
+    @Test
+    public void generationWithOneEpochTimestampInternalStillReportsAMinimum()
+    {
+        for (LogDomain epochDomain : LogDomain.values())
+        {
+            ColumnFamilyStore cfs = newTrackedTable();
+            SplitDomainMemtable wrapper = newWrapper(cfs);
+            LogDomain otherDomain = epochDomain.isJournal() ? LogDomain.COMMIT_LOG : LogDomain.MUTATION_JOURNAL;
+            long realTimestamp = FBUtilities.timestampMicros();
+
+            write(cfs, wrapper, 1, epochDomain, EncodingStats.NO_STATS.minTimestamp);
+            write(cfs, wrapper, 2, otherDomain, realTimestamp);
+
+            // we expect the internal memtable to report no timestamp
+            assertEquals(Memtable.NO_MIN_TIMESTAMP, wrapper.internalFor(epochDomain).getMinTimestamp());
+            // but the wrapper needs to report the minimum actual timestamp
+            assertEquals(realTimestamp, wrapper.getMinTimestamp());
+        }
+    }
+
+    /**
+     * Check that writes against split memtables are routed to the proper internal memtable, and that the internal
+     * memtables are presented to readers as a single memtable
+     */
+    @Test
+    public void writesAndReadsSpanBothDomains()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        SplitDomainMemtable wrapper = newWrapper(cfs);
+        Memtable commitLogInternal = wrapper.internalFor(LogDomain.COMMIT_LOG);
+        Memtable journalInternal = wrapper.internalFor(LogDomain.MUTATION_JOURNAL);
+        assertTrue(wrapper.isInternal(commitLogInternal));
+        assertTrue(wrapper.isInternal(journalInternal));
+        assertTrue(wrapper.isClean());
+
+        // Handed to the generation rather than to an internal, so put() does the routing.
+        write(cfs, wrapper, 1, LogDomain.MUTATION_JOURNAL);
+        write(cfs, wrapper, 2, LogDomain.COMMIT_LOG);
+
+        // Each internal took its own domain's row and nothing else.
+        assertEquals(Collections.singleton(key(cfs, 1)), partitionKeys(journalInternal));
+        assertEquals(Collections.singleton(key(cfs, 2)), partitionKeys(commitLogInternal));
+        assertFalse(wrapper.isClean());
+
+        // Every read path answers for both internals, and for neither when the partition is in neither.
+        assertEquals(ImmutableSet.of(key(cfs, 1), key(cfs, 2)), partitionKeys(wrapper));
+        assertNotNull(wrapper.snapshotPartition(key(cfs, 1)));
+        assertNotNull(wrapper.snapshotPartition(key(cfs, 2)));
+        assertNotNull(wrapper.rowIterator(key(cfs, 1)));
+        assertNotNull(wrapper.rowIterator(key(cfs, 2)));
+        assertNull(wrapper.snapshotPartition(key(cfs, 99)));
+        assertNull(wrapper.rowIterator(key(cfs, 99)));
+        assertEquals(maxToken(commitLogInternal.lastToken(), journalInternal.lastToken()), wrapper.lastToken());
+    }
+
+    private static Token maxToken(Token left, Token right)
+    {
+        return left.compareTo(right) >= 0 ? left : right;
+    }
+
+    /**
+     * Both internals take the barrier the generation was switched out with, since the generation flushes as one unit.
+     * An internal left holding no barrier keeps accepting writes after the switch, and those rows miss the flush they
+     * were bounded into.
+     */
+    @Test
+    public void switchingOutGenerationRetiresBothInternals()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        SplitDomainMemtable wrapper = newWrapper(cfs);
+        Memtable commitLogInternal = wrapper.internalFor(LogDomain.COMMIT_LOG);
+        Memtable journalInternal = wrapper.internalFor(LogDomain.MUTATION_JOURNAL);
+
+        OpOrder.Barrier barrier = Keyspace.writeOrder.newBarrier();
+        LogDomainBounds upperBounds = LogDomainBounds.atCurrentPositions();
+        upperBounds.seal();
+        wrapper.switchOut(barrier, upperBounds);
+        barrier.issue();
+
+        // A write that starts after the barrier is refused for either domain, which holds only if both internals took
+        // it. An internal with no barrier reports itself as still the newest and accepts everything.
+        try (OpOrder.Group after = Keyspace.writeOrder.start())
+        {
+            for (LogDomain domain : LogDomain.values())
+            {
+                CommitLogPosition position = upperBounds.get(domain);
+                assertFalse(domain + " internal still accepts writes", wrapper.internalFor(domain)
+                                                                              .accepts(after, position, domain));
+                assertFalse(domain + " write was accepted by the wrapper", wrapper.accepts(after, position, domain));
+            }
+        }
+    }
+
+    /**
+     * The constructor's preconditions are what make {@code internalFor} honest. Two internals holding one domain leave
+     * the other unroutable, and internals from different stores would put one table's rows in another's flush.
+     */
+    @Test
+    public void wrapperRefusesInternalsThatCannotCoverBothDomains()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        LogDomainBounds bounds = LogDomainBounds.atCurrentPositions();
+        DomainMemtable journalInternal = internal(cfs, bounds, LogDomain.MUTATION_JOURNAL);
+
+        Assertions.assertThatThrownBy(() -> new SplitDomainMemtable(journalInternal,
+                                                                    internal(cfs, bounds, LogDomain.MUTATION_JOURNAL),
+                                                                    journalInternal.getMemtableId()))
+                  .describedAs("two journal internals leave the commit log domain unroutable")
+                  .isInstanceOf(IllegalArgumentException.class);
+
+        ColumnFamilyStore otherTable = newTrackedTable();
+        Assertions.assertThatThrownBy(() -> new SplitDomainMemtable(internal(otherTable, bounds, LogDomain.COMMIT_LOG),
+                                                                    journalInternal,
+                                                                    journalInternal.getMemtableId()))
+                  .describedAs("internals must belong to the same store")
+                  .isInstanceOf(IllegalArgumentException.class);
+    }
+
+    // An unsplit memtable refuses a write from the other log, because it's bounds are incompatible
+    @Test
+    public void normalMemtableRefusesForeignDomainWrite()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        DomainMemtable journalInternal = internal(cfs, LogDomainBounds.atCurrentPositions(), LogDomain.MUTATION_JOURNAL);
+
+        TableMetadata metadata = cfs.metadata();
+        DecoratedKey key = metadata.partitioner.decorateKey(ByteBufferUtil.bytes(1));
+        MutationId id = MutationTrackingService.instance().nextMutationId(metadata.keyspace, key.getToken());
+        SimpleBuilders.MutationBuilder builder = new SimpleBuilders.MutationBuilder(id, metadata.keyspace, key);
+        builder.update(metadata).row().add("v", 1);
+        PartitionUpdate update = builder.build().getPartitionUpdate(metadata);
+
+        Assertions.assertThatThrownBy(() -> {
+                      try (OpOrder.Group group = Keyspace.writeOrder.start())
+                      {
+                          journalInternal.put(id, update, UpdateTransaction.NO_OP, group, LogDomain.COMMIT_LOG);
+                      }
+                  })
+                  .describedAs("a commit-log write must not land in a journal memtable")
+                  .isInstanceOf(IllegalArgumentException.class)
+                  .hasMessageContaining("COMMIT_LOG");
+    }
+
+    // ---- Installing one, through Tracker.getMemtableFor --------------------------------------------------------
+
+    /**
+     * A tracked table's memtable refuses an untracked write. The memtable generation splits instead of the write
+     * failing, and keeps the memtable that was already live as one internal.
+     */
+    @Test
+    public void foreignDomainWriteSplitsTheCurrentMemtableGeneration()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        Memtable before = cfs.getTracker().getView().getCurrentMemtable();
+        assertTrue(before.holds(LogDomain.MUTATION_JOURNAL));
+
+        try (OpOrder.Group group = Keyspace.writeOrder.start())
+        {
+            Memtable selected = cfs.getTracker().getMemtableFor(group,
+                                                               CommitLog.instance.getCurrentPosition(),
+                                                               LogDomain.COMMIT_LOG);
+            assertTrue("selection returns the split generation, which routes on put",
+                       selected instanceof SplitDomainMemtable);
+            assertTrue(((SplitDomainMemtable) selected).internalFor(LogDomain.COMMIT_LOG).holds(LogDomain.COMMIT_LOG));
+        }
+
+        Memtable after = cfs.getTracker().getView().getCurrentMemtable();
+        assertTrue(after instanceof SplitDomainMemtable);
+        SplitDomainMemtable wrapper = (SplitDomainMemtable) after;
+        assertEquals("the memtable already live is kept as the journal internal",
+                     before, wrapper.internalFor(LogDomain.MUTATION_JOURNAL));
+        assertEquals("and the wrapper inherits its id, so generation ordering is unbroken",
+                     before.getMemtableId(), wrapper.getMemtableId());
+    }
+
+    @Test
+    public void splitGenerationTakesEitherDomainAndRoutesInside()
+    {
+        // memtable should initially be a normal memtable
+        ColumnFamilyStore cfs = newTrackedTable();
+        assertFalse(selectGenerationFor(cfs, LogDomain.MUTATION_JOURNAL) instanceof SplitDomainMemtable);
+
+        //... but requesting a memtable should install a split domain memtable
+        Memtable installed = selectGenerationFor(cfs, LogDomain.COMMIT_LOG);
+        assertTrue(selectGenerationFor(cfs, LogDomain.COMMIT_LOG) instanceof SplitDomainMemtable);
+
+        //... and continue returning it for either domain
+        Memtable forCommitLog = selectGenerationFor(cfs, LogDomain.COMMIT_LOG);
+        Memtable forJournal = selectGenerationFor(cfs, LogDomain.MUTATION_JOURNAL);
+
+        assertEquals(forCommitLog, forJournal);
+        assertEquals(installed, forCommitLog);
+        assertEquals(forCommitLog, cfs.getTracker().getView().getCurrentMemtable());
+        SplitDomainMemtable wrapper = (SplitDomainMemtable) forCommitLog;
+
+        // writes against one domain shouldn't touch the other domain
+        write(cfs, wrapper, 1, LogDomain.MUTATION_JOURNAL);
+        assertFalse(wrapper.internalFor(LogDomain.MUTATION_JOURNAL).isClean());
+        assertTrue("the commit-log internal must not have taken the journal write",
+                   wrapper.internalFor(LogDomain.COMMIT_LOG).isClean());
+    }
+
+    /**
+     * Retires a generation for routing without flushing it.
+     */
+    private static void retireForRouting(Memtable memtable)
+    {
+        OpOrder.Barrier barrier = Keyspace.writeOrder.newBarrier();
+        LogDomainBounds upperBounds = LogDomainBounds.unset();
+        upperBounds.seal();
+        memtable.switchOut(barrier, upperBounds);
+        barrier.issue();
+    }
+
+    /**
+     * Prior to supporting multiple log domains, having no memtable that would accept an incoming write was an error. Now,
+     * it can mean that we have an illegal condition OR we need to split the current memtable. This tests that we still
+     * throw if none of the memtables will accept the write AND the current memtable holds the domain of the current write
+     * we need to split the current memtable.
+     */
+    @Test
+    public void currentMemtableHoldsDomainRefusesThenThrows()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        Memtable current = cfs.getTracker().getView().getCurrentMemtable();
+        assertTrue(current.holds(LogDomain.MUTATION_JOURNAL));
+
+        // Retired without a replacement being appended, which no production path does - View.switchMemtable appends
+        // first. That leaves a current memtable carrying an issued barrier, so it refuses a write it holds the domain
+        // for.
+        retireForRouting(current);
+
+        Assertions.assertThatThrownBy(() -> {
+                      try (OpOrder.Group group = Keyspace.writeOrder.start())
+                      {
+                          cfs.getTracker().getMemtableFor(group, MutationJournal.instance().getCurrentPosition(),
+                                                          LogDomain.MUTATION_JOURNAL);
+                      }
+                  })
+                  .describedAs("the invariant must be reported, naming the domain the current memtable holds")
+                  .isInstanceOf(AssertionError.class)
+                  .hasMessageContaining("holds that domain");
+    }
+
+    // ---- Flushing one, through ColumnFamilyStore ---------------------------------------------------------------
+
+    @Test
+    public void splitGenerationFlushesAnSSTablePerDomain()
+    {
+        assertFlushOutput(EnumSet.of(SSTableProvenance.MUTATION_JOURNAL, SSTableProvenance.COMMIT_LOG),
+                          LogDomain.MUTATION_JOURNAL, LogDomain.COMMIT_LOG);
+        assertFlushOutput(EnumSet.of(SSTableProvenance.MUTATION_JOURNAL),
+                          LogDomain.MUTATION_JOURNAL);
+    }
+
+    private static void assertFlushOutput(Set<SSTableProvenance> expected, LogDomain... dirty)
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+
+        Memtable generation = selectGenerationFor(cfs, LogDomain.COMMIT_LOG);
+        assertTrue(generation instanceof SplitDomainMemtable);
+        int k = 1;
+        for (LogDomain domain : dirty)
+            write(cfs, generation, k++, domain);
+        assertFalse(generation.isClean());
+
+        cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+
+        Map<SSTableProvenance, SSTableReader> byProvenance = new EnumMap<>(SSTableProvenance.class);
+        for (SSTableReader sstable : cfs.getLiveSSTables())
+            assertNull("two sstables from the same log", byProvenance.put(SSTableProvenance.of(sstable), sstable));
+
+        assertEquals("one sstable per dirty domain, and none claiming both logs", expected, byProvenance.keySet());
+        assertFalse("the generation is gone from the view", cfs.getTracker().getView().liveMemtables.contains(generation));
+    }
+
+    private static Memtable dirtySplitGeneration(ColumnFamilyStore cfs)
+    {
+        Memtable generation = selectGenerationFor(cfs, LogDomain.COMMIT_LOG);
+        write(cfs, generation, 1, LogDomain.COMMIT_LOG);
+        write(cfs, generation, 2, LogDomain.MUTATION_JOURNAL);
+        return generation;
+    }
+
+    /**
+     * A generation can be split after a listener is registered on it, which demotes the memtable holding the listener
+     * to an internal. Only the wrapper is notified on flush, so the internals have to be drained too or the
+     * registration is lost for the life of the generation.
+     */
+    @Test
+    public void flushListenerRegisteredBeforeSplitStillFires()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        Memtable beforeSplit = cfs.getTracker().getView().getCurrentMemtable();
+        assertFalse("a plain generation is the precondition for this test", beforeSplit instanceof SplitDomainMemtable);
+        write(cfs, beforeSplit, 1, LogDomain.MUTATION_JOURNAL);
+
+        AtomicInteger fired = new AtomicInteger();
+        assertNotNull(beforeSplit.ensureFlushListener("durability", () -> metadata -> fired.incrementAndGet()));
+
+        // A foreign-domain write installs the split, so the memtable carrying the listener becomes an internal.
+        Memtable generation = selectGenerationFor(cfs, LogDomain.COMMIT_LOG);
+        assertTrue(generation instanceof SplitDomainMemtable);
+        assertSame("the listener now sits on an internal, not on the current memtable",
+                   beforeSplit, ((SplitDomainMemtable) generation).internalFor(LogDomain.MUTATION_JOURNAL));
+        write(cfs, generation, 2, LogDomain.COMMIT_LOG);
+
+        cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+
+        assertEquals("a listener registered before the split must still fire exactly once", 1, fired.get());
+    }
+
+    /**
+     * For accord. Accord assumes a single active memtable and observes them directly when determining durability.
+     * If the listener fired once per domain memtable, accord would think a memtable was durable before both parts
+     * actually were
+     */
+    @Test
+    public void splitDomainMemtableFiresFlushListenerOnce()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        Memtable generation = dirtySplitGeneration(cfs);
+
+        AtomicInteger fired = new AtomicInteger();
+        AtomicInteger liveWhenFired = new AtomicInteger(-1);
+        Consumer<TableMetadata> registered = generation.ensureFlushListener("durability", () -> metadata -> {
+            fired.incrementAndGet();
+            liveWhenFired.set(cfs.getLiveSSTables().size());
+        });
+        assertNotNull(registered);
+        assertSame("one listener per generation, not per registration",
+                   registered,
+                   generation.ensureFlushListener("durability", () -> { throw new AssertionError("built twice"); }));
+
+        cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+
+        assertEquals("fires exactly once", 1, fired.get());
+        assertEquals("both domains' output must be live before it fires", 2, liveWhenFired.get());
+        assertNull("a flushed generation refuses new listeners, which is what ensureDurable retries on",
+                   generation.ensureFlushListener("later", () -> metadata -> {}));
+    }
+
+    /**
+     * A flush failure must leave both logs alone, or a segment is marked clean for data that never reached disk. The two
+     * log calls and the listener share one {@code flushFailure == null} guard in {@code PostFlush}.
+     */
+    @Test
+    public void flushFailureInOneDomainLeavesTheGenerationUndurable()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        Memtable generation = dirtySplitGeneration(cfs);
+
+        AtomicInteger fired = new AtomicInteger();
+        generation.ensureFlushListener("durability", () -> metadata -> fired.incrementAndGet());
+
+        // Flushing.flushRunnables refuses a memtable that already holds a flush transaction, so the journal internal
+        // fails where a writer error would: inside Flush.flushMemtable, after the barrier has issued.
+        DomainMemtable journalInternal = ((SplitDomainMemtable) generation).internalFor(LogDomain.MUTATION_JOURNAL);
+        journalInternal.setFlushTransaction(LifecycleTransaction.offline(OperationType.FLUSH));
+
+        try
+        {
+            cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+            org.junit.Assert.fail("expected the flush to fail");
+        }
+        catch (RuntimeException expected)
+        {
+            // the failure is rethrown by PostFlush
+        }
+
+        // A failed flush must leave the generation undurable and publish nothing.
+        assertEquals(0, fired.get());
+        assertEquals(0, cfs.getLiveSSTables().size());
+    }
+
+    /**
+     * Checks that the correct log is notified on flush, even if the schema has moved onto a different domain.
+     */
+    @Test
+    public void originatingLogIsNotifiedOnMemtableFlush()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        assertTrue(cfs.metadata().replicationType().isTracked());
+
+        // Split first, so the commit-log internal's lower bound is below the append that follows.
+        Memtable generation = selectGenerationFor(cfs, LogDomain.COMMIT_LOG);
+        assertTrue(generation instanceof SplitDomainMemtable);
+
+        CommitLog.instance.add(untrackedMutation(cfs, 1));
+        assertTrue(commitLogIsDirtyFor(cfs));
+
+        write(cfs, generation, 1, LogDomain.COMMIT_LOG);
+        cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+
+        assertFalse(commitLogIsDirtyFor(cfs));
+    }
+
+    @Test
+    public void flushSourceForEnforcesDomain()
+    {
+        ColumnFamilyStore cfs = newTrackedTable();
+        LogDomainBounds bounds = LogDomainBounds.atCurrentPositions();
+        DomainMemtable commitLogInternal = internal(cfs, bounds, LogDomain.COMMIT_LOG);
+        DomainMemtable journalInternal = internal(cfs, bounds, LogDomain.MUTATION_JOURNAL);
+        SplitDomainMemtable wrapper = new SplitDomainMemtable(commitLogInternal, journalInternal, 1L);
+
+        assertSame(commitLogInternal, commitLogInternal.flushSourceFor(LogDomain.COMMIT_LOG));
+        assertThatThrownBy(() -> commitLogInternal.flushSourceFor(LogDomain.MUTATION_JOURNAL))
+            .isInstanceOf(IllegalArgumentException.class);
+
+        assertSame(journalInternal, journalInternal.flushSourceFor(LogDomain.MUTATION_JOURNAL));
+        assertThatThrownBy(() -> journalInternal.flushSourceFor(LogDomain.COMMIT_LOG))
+            .isInstanceOf(IllegalArgumentException.class);
+
+        assertSame(commitLogInternal, wrapper.flushSourceFor(LogDomain.COMMIT_LOG));
+        assertSame(journalInternal, wrapper.flushSourceFor(LogDomain.MUTATION_JOURNAL));
+    }
+
+    private static Mutation untrackedMutation(ColumnFamilyStore cfs, int k)
+    {
+        TableMetadata metadata = cfs.metadata();
+        DecoratedKey key = metadata.partitioner.decorateKey(ByteBufferUtil.bytes(k));
+        SimpleBuilders.MutationBuilder builder = new SimpleBuilders.MutationBuilder(MutationId.none(), metadata.keyspace, key);
+        builder.update(metadata).row().add("v", k);
+        return builder.build();
+    }
+
+    private static boolean commitLogIsDirtyFor(ColumnFamilyStore cfs)
+    {
+        for (CommitLogSegment segment : CommitLog.instance.segmentManager.getActiveSegments())
+            if (segment.getDirtyTableIds().contains(cfs.metadata().id))
+                return true;
+        return false;
+    }
+
+    private static Memtable selectGenerationFor(ColumnFamilyStore cfs, LogDomain domain)
+    {
+        CommitLogPosition position = domain.isJournal() ? MutationJournal.instance().getCurrentPosition()
+                                                        : CommitLog.instance.getCurrentPosition();
+        try (OpOrder.Group group = Keyspace.writeOrder.start())
+        {
+            return cfs.getTracker().getMemtableFor(group, position, domain);
+        }
+    }
+
+}
diff --git a/test/unit/org/apache/cassandra/db/memtable/TestMemtable.java b/test/unit/org/apache/cassandra/db/memtable/TestMemtable.java
index ec10c1a815..6f1e053783 100644
--- a/test/unit/org/apache/cassandra/db/memtable/TestMemtable.java
+++ b/test/unit/org/apache/cassandra/db/memtable/TestMemtable.java
@@ -22,7 +22,7 @@ import java.util.Map;
 
 public class TestMemtable
 {
-    public static Memtable.Factory factory(Map<String, String> options)
+    public static DomainMemtable.Factory factory(Map<String, String> options)
     {
         String skiplist = options.remove("skiplist");
         if (Boolean.parseBoolean(skiplist))
@@ -31,5 +31,5 @@ public class TestMemtable
             return FACTORY;
     }
 
-    public static Memtable.Factory FACTORY = SkipListMemtable::new;
+    public static DomainMemtable.Factory FACTORY = SkipListMemtable::new;
 }
diff --git a/test/unit/org/apache/cassandra/db/memtable/TrieMemtableFlushSetTestBase.java b/test/unit/org/apache/cassandra/db/memtable/TrieMemtableFlushSetTestBase.java
index 30096f8438..831463dec5 100644
--- a/test/unit/org/apache/cassandra/db/memtable/TrieMemtableFlushSetTestBase.java
+++ b/test/unit/org/apache/cassandra/db/memtable/TrieMemtableFlushSetTestBase.java
@@ -105,8 +105,8 @@ public abstract class TrieMemtableFlushSetTestBase extends CQLTester
             }
         }
 
-        Memtable memtable = cfs.getCurrentMemtable();
-        Memtable memtableToCompare = cfsToCompare.getCurrentMemtable();
+        DomainMemtable memtable = (DomainMemtable) cfs.getCurrentMemtable();
+        DomainMemtable memtableToCompare = (DomainMemtable) cfsToCompare.getCurrentMemtable();
 
         {
             Memtable.FlushablePartitionSet<?> flushSetNull = memtable.getFlushSet(null, null);
@@ -142,7 +142,7 @@ public abstract class TrieMemtableFlushSetTestBase extends CQLTester
 
     }
 
-    private static void testShardRanges(ShardBoundaries shardBoundaries, ColumnFamilyStore cfs, Memtable memtable, Memtable memtableToCompare)
+    private static void testShardRanges(ShardBoundaries shardBoundaries, ColumnFamilyStore cfs, DomainMemtable memtable, DomainMemtable memtableToCompare)
     {
         for (int fromShardIndex = 0; fromShardIndex < shardBoundaries.shardCount(); fromShardIndex++)
         {
@@ -168,7 +168,7 @@ public abstract class TrieMemtableFlushSetTestBase extends CQLTester
         }
     }
 
-    private static void testRange(Memtable memtable, Memtable memtableToCompare, PartitionPosition positionFrom, PartitionPosition positionTo)
+    private static void testRange(DomainMemtable memtable, DomainMemtable memtableToCompare, PartitionPosition positionFrom, PartitionPosition positionTo)
     {
         Memtable.FlushablePartitionSet<?> flushSet = memtable.getFlushSet(positionFrom, positionTo);
         Memtable.FlushablePartitionSet<?> flushSetToCompare = memtableToCompare.getFlushSet(positionFrom, positionTo);
diff --git a/test/unit/org/apache/cassandra/index/internal/TrackedIndexFlushTest.java b/test/unit/org/apache/cassandra/index/internal/TrackedIndexFlushTest.java
new file mode 100644
index 0000000000..b3c292e15c
--- /dev/null
+++ b/test/unit/org/apache/cassandra/index/internal/TrackedIndexFlushTest.java
@@ -0,0 +1,207 @@
+/*
+ * 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.index.internal;
+
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.google.common.collect.Iterables;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import org.apache.cassandra.SchemaLoader;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.ColumnIdentifier;
+import org.apache.cassandra.cql3.statements.schema.IndexTarget;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.LogDomain;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.SimpleBuilders;
+import org.apache.cassandra.db.commitlog.CommitLogPosition;
+import org.apache.cassandra.db.commitlog.IntervalSet;
+import org.apache.cassandra.db.compaction.CompactionManager;
+import org.apache.cassandra.db.marshal.Int32Type;
+import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.replication.MutationId;
+import org.apache.cassandra.replication.MutationJournal;
+import org.apache.cassandra.replication.MutationTrackingService;
+import org.apache.cassandra.schema.IndexMetadata;
+import org.apache.cassandra.schema.Indexes;
+import org.apache.cassandra.schema.KeyspaceParams;
+import org.apache.cassandra.schema.ReplicationType;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.utils.ByteBufferUtil;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class TrackedIndexFlushTest
+{
+    private static final AtomicInteger keyspaceNumber = new AtomicInteger();
+    private static final String INDEX_NAME = "tbl_v_index";
+
+    static
+    {
+        DatabaseDescriptor.daemonInitialization();
+    }
+
+    @BeforeClass
+    public static void setupClass()
+    {
+        SchemaLoader.prepareServer();
+        MutationJournal.start();
+        MutationTrackingService.start();
+    }
+
+    private static ColumnFamilyStore newTableWithIndex(ReplicationType replicationType)
+    {
+        String ks = "tracked_index_flush_" + keyspaceNumber.incrementAndGet();
+
+        TableMetadata.Builder builder =
+        TableMetadata.builder(ks, "tbl")
+                     .addPartitionKeyColumn("k", Int32Type.instance)
+                     .addRegularColumn("v", Int32Type.instance);
+
+        builder.indexes(Indexes.of(IndexMetadata.fromIndexTargets(
+        Collections.singletonList(new IndexTarget(new ColumnIdentifier("v", true), IndexTarget.Type.VALUES)),
+        INDEX_NAME,
+        IndexMetadata.Kind.COMPOSITES,
+        Collections.emptyMap())));
+
+        SchemaLoader.createKeyspace(ks, KeyspaceParams.simple(1, replicationType), builder);
+
+        ColumnFamilyStore cfs = Keyspace.open(ks).getColumnFamilyStore("tbl");
+        cfs.disableAutoCompaction();
+        indexStore(cfs).disableAutoCompaction();
+        return cfs;
+    }
+
+    private static ColumnFamilyStore newTrackedTableWithIndex()
+    {
+        return newTableWithIndex(ReplicationType.tracked);
+    }
+
+    private static ColumnFamilyStore newUntrackedTableWithIndex()
+    {
+        return newTableWithIndex(ReplicationType.untracked);
+    }
+
+    private static ColumnFamilyStore indexStore(ColumnFamilyStore baseCfs)
+    {
+        return Iterables.getOnlyElement(baseCfs.indexManager.getAllIndexColumnFamilyStores());
+    }
+
+    private static ColumnFamilyStore newTrackedTableWithFlushedRow()
+    {
+        ColumnFamilyStore cfs = newTrackedTableWithIndex();
+        write(cfs, 1, 1);
+        cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+        return cfs;
+    }
+
+    private static void write(ColumnFamilyStore cfs, int k, int v)
+    {
+        TableMetadata metadata = cfs.metadata();
+        DecoratedKey key = metadata.partitioner.decorateKey(ByteBufferUtil.bytes(k));
+        MutationId id = MutationTrackingService.instance().nextMutationId(metadata.keyspace, key.getToken());
+        SimpleBuilders.MutationBuilder builder = new SimpleBuilders.MutationBuilder(id, metadata.keyspace, key);
+        PartitionUpdate.SimpleBuilder partition = builder.update(metadata);
+        partition.row().add("v", v);
+        Mutation mutation = builder.build();
+        assertFalse(mutation.id().isNone());
+        mutation.apply();
+    }
+
+    @Test
+    public void untrackedIndexMemtableDomain()
+    {
+        ColumnFamilyStore cfs = newUntrackedTableWithIndex();
+
+        Memtable index = indexStore(cfs).getTracker().getView().getCurrentMemtable();
+
+        assertTrue(index.holds(LogDomain.COMMIT_LOG));
+        assertFalse(index.holds(LogDomain.MUTATION_JOURNAL));
+    }
+
+    @Test
+    public void trackedIndexMemtableDomain()
+    {
+        ColumnFamilyStore cfs = newTrackedTableWithIndex();
+
+        Memtable index = indexStore(cfs).getTracker().getView().getCurrentMemtable();
+
+        assertTrue(index.holds(LogDomain.MUTATION_JOURNAL));
+        assertFalse(index.holds(LogDomain.COMMIT_LOG));
+    }
+
+    @Test
+    public void rebuildingAnIndexOnATrackedTableSucceeds()
+    {
+        ColumnFamilyStore cfs = newTrackedTableWithFlushedRow();
+        ColumnFamilyStore index = indexStore(cfs);
+        assertFalse(cfs.getLiveSSTables().isEmpty());
+
+        cfs.indexManager.rebuildIndexesBlocking(Collections.singleton(INDEX_NAME));
+
+        int withSpan = 0;
+        int withoutSpan = 0;
+        for (SSTableReader sstable : index.getLiveSSTables())
+        {
+            IntervalSet<CommitLogPosition> intervals = sstable.getSSTableMetadata().commitLogIntervals;
+            if (intervals.isEmpty())
+            {
+                withoutSpan++;
+                continue;
+            }
+            withSpan++;
+            for (CommitLogPosition start : intervals.starts())
+                assertTrue(start.compareTo(intervals.upperBound().orElseThrow(AssertionError::new)) <= 0);
+        }
+        assertEquals(1, withoutSpan);
+        assertEquals(1, withSpan);
+    }
+
+    @Test
+    public void trackedIndexSSTableContainsNoOffsets()
+    {
+        ColumnFamilyStore cfs = newTrackedTableWithFlushedRow();
+        ColumnFamilyStore index = indexStore(cfs);
+
+        write(cfs, 2, 2);
+        cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS);
+        assertEquals("precondition: two index sstables to union intervals over", 2, index.getLiveSSTables().size());
+        for (SSTableReader input : index.getLiveSSTables())
+        {
+            assertTrue(input.getSSTableMetadata().commitLogIntervals.isEmpty());
+            assertTrue(input.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+        }
+
+        CompactionManager.instance.performMaximal(index);
+
+        SSTableReader compacted = Iterables.getOnlyElement(index.getLiveSSTables());
+        assertTrue(compacted.getSSTableMetadata().commitLogIntervals.isEmpty());
+        assertTrue(compacted.getSSTableMetadata().coordinatorLogOffsets.isEmpty());
+    }
+}
diff --git a/test/unit/org/apache/cassandra/index/sai/functional/TrackedFlushingTest.java b/test/unit/org/apache/cassandra/index/sai/functional/TrackedFlushingTest.java
new file mode 100644
index 0000000000..763568cbd3
--- /dev/null
+++ b/test/unit/org/apache/cassandra/index/sai/functional/TrackedFlushingTest.java
@@ -0,0 +1,215 @@
+/*
+ * 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.index.sai.functional;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.apache.cassandra.db.memtable.Memtable;
+import org.apache.cassandra.index.sai.SAITester;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.replication.MutationJournal;
+import org.apache.cassandra.replication.MutationTrackingService;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * SAI on a table whose keyspace is migrated to mutation tracking while it is taking writes. The migration splits the
+ * live memtable generation per {@link org.apache.cassandra.db.LogDomain}, so one generation flushes into one sstable
+ * per domain, and each output needs an index covering the rows that sstable holds.
+ *
+ * Every test asserts the unindexed count as well as the indexed one, so a failure says whether the rows or only their
+ * index entries were lost.
+ */
+public class TrackedFlushingTest extends SAITester
+{
+    @Before
+    public void startTracking()
+    {
+        MutationJournal.start();
+        MutationTrackingService.start();
+    }
+
+    @After
+    public void stopTracking() throws InterruptedException
+    {
+        MutationTrackingService.shutdown();
+    }
+
+    @Test
+    public void indexCoversRowsWrittenAfterTheSplit()
+    {
+        createTable(CREATE_TABLE_TEMPLATE);
+        createIndex(String.format(CREATE_INDEX_TEMPLATE, "v1"));
+
+        migrateToTracked();
+        insert(0, 10);
+
+        assertGenerationSplit();
+        assertEquals("precondition: the memtable index answers before the flush", 10, indexedCount());
+
+        flush();
+
+        assertEquals("rows are present after the flush", 10, unindexedCount());
+        assertEquals("rows are indexed after the flush", 10, indexedCount());
+    }
+
+    @Test
+    public void indexCoversRowsWrittenEitherSideOfTheSplit()
+    {
+        createTable(CREATE_TABLE_TEMPLATE);
+        createIndex(String.format(CREATE_INDEX_TEMPLATE, "v1"));
+
+        insert(0, 5);
+        migrateToTracked();
+        insert(5, 10);
+
+        assertGenerationSplit();
+        assertEquals("precondition: the memtable index answers before the flush", 10, indexedCount());
+
+        flush();
+
+        assertOneSSTablePerDomain();
+        assertEquals("rows are present after the flush", 10, unindexedCount());
+        assertEquals("rows are indexed after the flush", 10, indexedCount());
+    }
+
+    /**
+     * The vector path writes its index through {@code MemtableIndex.writeDirect} rather than a row-mapping merge, and
+     * pre-creates the index on switch, so it reaches the flush by a different route than a literal index.
+     */
+    @Test
+    public void vectorIndexCoversRowsWrittenAfterTheSplit()
+    {
+        createTable("CREATE TABLE %s (k int PRIMARY KEY, v vector<float, 3>)");
+        createIndex("CREATE CUSTOM INDEX ON %s(v) USING 'sai'");
+
+        migrateToTracked();
+        insertVectors(0, 10);
+
+        assertGenerationSplit();
+        assertEquals("precondition: the memtable index answers before the flush", 10, annCount());
+
+        flush();
+
+        assertEquals("rows are present after the flush", 10, unindexedCount());
+        assertEquals("rows are indexed after the flush", 10, annCount());
+    }
+
+    @Test
+    public void vectorIndexCoversRowsWrittenEitherSideOfTheSplit()
+    {
+        createTable("CREATE TABLE %s (k int PRIMARY KEY, v vector<float, 3>)");
+        createIndex("CREATE CUSTOM INDEX ON %s(v) USING 'sai'");
+
+        insertVectors(0, 5);
+        migrateToTracked();
+        insertVectors(5, 10);
+
+        assertGenerationSplit();
+        assertEquals("precondition: the memtable index answers before the flush", 10, annCount());
+
+        flush();
+
+        assertOneSSTablePerDomain();
+        assertEquals("rows are present after the flush", 10, unindexedCount());
+        assertEquals("rows are indexed after the flush", 10, annCount());
+    }
+
+    /**
+     * Overwriting a row already resident in the same source reaches {@code MemtableIndexManager.update}, which asserts
+     * for a vector index that the source already has an index.
+     */
+    @Test
+    public void vectorIndexSurvivesOverwriteInASplitGeneration()
+    {
+        createTable("CREATE TABLE %s (k int PRIMARY KEY, v vector<float, 3>)");
+        createIndex("CREATE CUSTOM INDEX ON %s(v) USING 'sai'");
+
+        insertVectors(0, 5);
+        migrateToTracked();
+        insertVectors(5, 10);
+        insertVectors(5, 10);
+
+        assertGenerationSplit();
+
+        flush();
+
+        assertEquals("rows are present after the flush", 10, unindexedCount());
+        assertEquals("rows are indexed after the flush", 10, annCount());
+    }
+
+    private void migrateToTracked()
+    {
+        schemaChange("ALTER KEYSPACE " + KEYSPACE + " WITH replication_type = 'tracked'");
+    }
+
+    private void insert(int fromInclusive, int toExclusive)
+    {
+        for (int i = fromInclusive; i < toExclusive; i++)
+            execute("INSERT INTO %s (id1, v1) VALUES (?, ?)", Integer.toString(i), i);
+    }
+
+    private void insertVectors(int fromInclusive, int toExclusive)
+    {
+        for (int i = fromInclusive; i < toExclusive; i++)
+            execute("INSERT INTO %s (k, v) VALUES (?, ?)", i, vector(1.0f + i, 2.0f + i, 3.0f + i));
+    }
+
+    private int annCount()
+    {
+        return execute("SELECT k FROM %s ORDER BY v ANN OF [1.0, 2.0, 3.0] LIMIT 100").size();
+    }
+
+    private int indexedCount()
+    {
+        return execute("SELECT id1 FROM %s WHERE v1 >= 0").size();
+    }
+
+    private int unindexedCount()
+    {
+        return execute("SELECT * FROM %s").size();
+    }
+
+    private void assertGenerationSplit()
+    {
+        Memtable current = getCurrentColumnFamilyStore().getTracker().getView().getCurrentMemtable();
+        assertEquals("precondition: the generation must hold both log domains", 2, current.flushSources().size());
+    }
+
+    /**
+     * A journal-derived sstable carries coordinator log offsets and no commit log interval, and a commit-log-derived
+     * one carries the reverse. Asserted so that a passing test cannot mean the generation never split.
+     */
+    private void assertOneSSTablePerDomain()
+    {
+        int fromCommitLog = 0;
+        int fromJournal = 0;
+        for (SSTableReader sstable : getCurrentColumnFamilyStore().getLiveSSTables())
+        {
+            if (sstable.getSSTableMetadata().coordinatorLogOffsets.isEmpty())
+                fromCommitLog++;
+            else
+                fromJournal++;
+        }
+        assertEquals("precondition: one sstable flushed from the commit log", 1, fromCommitLog);
+        assertEquals("precondition: one sstable flushed from the journal", 1, fromJournal);
+    }
+}
diff --git a/test/unit/org/apache/cassandra/io/sstable/SSTableProvenance.java b/test/unit/org/apache/cassandra/io/sstable/SSTableProvenance.java
new file mode 100644
index 0000000000..4c626e633c
--- /dev/null
+++ b/test/unit/org/apache/cassandra/io/sstable/SSTableProvenance.java
@@ -0,0 +1,52 @@
+/*
+ * 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.io.sstable;
+
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
+
+/**
+ * Convenience enum for testing sstable metadata indicating if it came from the journal, the commit log, or both
+ */
+public enum SSTableProvenance
+{
+    MUTATION_JOURNAL,
+    COMMIT_LOG,
+    INDETERMINATE,
+    BOTH;
+
+    public static SSTableProvenance of(SSTableReader sstable)
+    {
+        return of(sstable.getSSTableMetadata());
+    }
+
+    public static SSTableProvenance of(StatsMetadata metadata)
+    {
+        boolean journal = !metadata.coordinatorLogOffsets.isEmpty();
+        boolean commitLog = !metadata.commitLogIntervals.isEmpty();
+
+        if (journal && commitLog)
+            return BOTH;
+        if (journal)
+            return MUTATION_JOURNAL;
+        if (commitLog)
+            return COMMIT_LOG;
+        return INDETERMINATE;
+    }
+}
diff --git a/test/unit/org/apache/cassandra/io/sstable/indexsummary/IndexSummaryRedistributionTest.java b/test/unit/org/apache/cassandra/io/sstable/indexsummary/IndexSummaryRedistributionTest.java
index 0c103ab526..42bcf5fd12 100644
--- a/test/unit/org/apache/cassandra/io/sstable/indexsummary/IndexSummaryRedistributionTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/indexsummary/IndexSummaryRedistributionTest.java
@@ -35,7 +35,6 @@ import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.db.ColumnFamilyStore;
 import org.apache.cassandra.db.Keyspace;
 import org.apache.cassandra.db.RowUpdateBuilder;
-import org.apache.cassandra.db.commitlog.CommitLogPosition;
 import org.apache.cassandra.exceptions.ConfigurationException;
 import org.apache.cassandra.io.sstable.format.SSTableReader;
 import org.apache.cassandra.metrics.RestorableMeter;
@@ -136,7 +135,7 @@ public class IndexSummaryRedistributionTest<R extends SSTableReader & IndexSumma
         cfs.truncateBlocking();
         cfs.disableAutoCompaction();
 
-        ArrayList<Future<CommitLogPosition>> futures = new ArrayList<>(numSSTables);
+        ArrayList<Future<?>> futures = new ArrayList<>(numSSTables);
         ByteBuffer value = ByteBuffer.wrap(new byte[100]);
         for (int sstable = 0; sstable < numSSTables; sstable++)
         {
@@ -151,7 +150,7 @@ public class IndexSummaryRedistributionTest<R extends SSTableReader & IndexSumma
             }
             futures.add(cfs.forceFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS));
         }
-        for (Future<CommitLogPosition> future : futures)
+        for (Future<?> future : futures)
         {
             try
             {
diff --git a/test/unit/org/apache/cassandra/replication/ShortMutationIdTest.java b/test/unit/org/apache/cassandra/replication/ShortMutationIdTest.java
new file mode 100644
index 0000000000..ab5d249d0a
--- /dev/null
+++ b/test/unit/org/apache/cassandra/replication/ShortMutationIdTest.java
@@ -0,0 +1,79 @@
+/*
+ * 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.replication;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+public class ShortMutationIdTest
+{
+    private static ShortMutationId id(int hostId, int hostLogId, int offset)
+    {
+        return new ShortMutationId(CoordinatorLogId.asLong(hostId, hostLogId), offset);
+    }
+
+    @Test
+    public void testComparison()
+    {
+        assertTrue(id(1, 0, 0).compareTo(id(2, 0, 0)) < 0);
+        assertTrue(id(1, 0, 0).compareTo(id(1, 1, 0)) < 0);
+        assertTrue(id(1, 1, 0).compareTo(id(1, 1, 1)) < 0);
... 187 lines suppressed ...


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


(cassandra) 01/02: Add -Dno-build-accord to skip the gradle subproject build

Posted by bd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bdeggleston pushed a commit to branch cep-45-mutation-tracking
in repository https://gitbox.apache.org/repos/asf/cassandra.git

commit 8b5865ce37573254f802cea1c43ce562fa590dff
Author: Blake Eggleston <bl...@ultrablake.com>
AuthorDate: Wed Sep 2 18:33:15 2026 -0700

    Add -Dno-build-accord to skip the gradle subproject build
    
    The _build-accord target otherwise runs a full gradle clean build and
    publishToMavenLocal on every ant invocation. It also takes a lock on the
    shared gradle artifact cache, so a second checkout building concurrently
    blocks until the first finishes.
---
 .build/build-accord.xml | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/.build/build-accord.xml b/.build/build-accord.xml
index 0d16197c6b..d47efe55bd 100644
--- a/.build/build-accord.xml
+++ b/.build/build-accord.xml
@@ -18,7 +18,11 @@
 -->
 <project basedir=".." name="apache-cassandra-accord-build"
          xmlns:if="ant:if">
-    <target name="_build-accord" depends="init">
+    <!-- no-build-accord skips the gradle invocation below, for when the jar is already current. Two checkouts building
+         concurrently contend on the shared gradle artifact cache (~/.gradle/caches/modules-2) and one blocks until the
+         other finishes; setting GRADLE_USER_HOME per checkout isolates that instead, at the cost of duplicated
+         downloads. Follows the same convention as no-checkstyle and no-build-test. -->
+    <target name="_build-accord" depends="init" unless="no-build-accord">
       <exec executable="${basedir}/${accord.dir}/gradlew" dir="${basedir}/${accord.dir}" logError="true" failonerror="true" failifexecutionfails="true">
         <!-- Need to call clean as a version change with a jar that didn't have code changes will not produce a new jar with the new version... so need clean to make sure build is stable -->
         <arg value="clean" />


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