Repository: vitessio/vitess
Pull request #9240 (2021-11-15 23:21:16)

Set super_read_only off during restore;  achieves same as PR #8929
In short, we are blindly setting `super_read_only` off in the restore flow, in case the default my.cnf params has `super_read_only=ON`.  This allows us to populate our metadata tables without running into write issues.

Tested manually and by the current DB restore e2e flow.


Patch:
diff --git a/go/vt/mysqlctl/backup.go b/go/vt/mysqlctl/backup.go
index 8480c4615e..d5b6c7681e 100644
--- a/go/vt/mysqlctl/backup.go
+++ b/go/vt/mysqlctl/backup.go
@@ -58,6 +58,8 @@ const (
 const (
 	// replicationStartDeadline is the deadline for starting replication
 	replicationStartDeadline = 30
+
+	Error1193 = "Unknown system variable"
 )
 
 var (
@@ -334,6 +336,21 @@ func Restore(ctx context.Context, params RestoreParams) (*BackupManifest, error)
 		return nil, err
 	}
 
+	// We disable super_read_only, in case it is in the default MySQL startup
+	// parameters and will be blocking the writes we need to do in
+	// PopulateMetadataTables().  We do it blindly, since
+	// this will fail on MariaDB, which doesn't have super_read_only
+	// This is safe, since we're restarting MySQL after the restore anyway
+	params.Logger.Infof("Restore: disabling super_read_only")
+	if err := params.Mysqld.SetSuperReadOnly(false); err != nil {
+		if strings.Contains(err.Error(), Error1193) {
+			params.Logger.Warningf("Restore: server does not know about super_read_only; maybe MariaDB? Continuing anyway.")
+		} else {
+			params.Logger.Errorf("Restore: unexpected error while trying to set super_read_only: %v", err)
+			return nil, err
+		}
+	}
+
 	params.Logger.Infof("Restore: running mysql_upgrade")
 	if err := params.Mysqld.RunMysqlUpgrade(); err != nil {
 		return nil, vterrors.Wrap(err, "mysql_upgrade failed")
diff --git a/go/vt/vtgate/engine/comparer.go b/go/vt/vtgate/engine/comparer.go
index 0b265bd2c6..767799492a 100644
--- a/go/vt/vtgate/engine/comparer.go
+++ b/go/vt/vtgate/engine/comparer.go
@@ -25,7 +25,6 @@ import (
 // comparer is the struct that has the logic for comparing two rows in the result set
 type comparer struct {
 	orderBy, weightString, starColFixedIndex int
-	collationID                              collations.ID
 	desc                                     bool
 }
 
@@ -40,7 +39,8 @@ func (c *comparer) compare(r1, r2 []sqltypes.Value) (int, error) {
 	} else {
 		colIndex = c.orderBy
 	}
-	cmp, err := evalengine.NullsafeCompare(r1[colIndex], r2[colIndex], c.collationID)
+	// TODO(king-11) make collation aware
+	cmp, err := evalengine.NullsafeCompare(r1[colIndex], r2[colIndex], collations.Unknown)
 	if err != nil {
 		_, isComparisonErr := err.(evalengine.UnsupportedComparisonError)
 		if !(isComparisonErr && c.weightString != -1) {
@@ -49,7 +49,8 @@ func (c *comparer) compare(r1, r2 []sqltypes.Value) (int, error) {
 		// in case of a comparison error switch to using the weight string column for ordering
 		c.orderBy = c.weightString
 		c.weightString = -1
-		cmp, err = evalengine.NullsafeCompare(r1[c.orderBy], r2[c.orderBy], c.collationID)
+		// TODO(king-11) make collation aware
+		cmp, err = evalengine.NullsafeCompare(r1[c.orderBy], r2[c.orderBy], collations.Unknown)
 		if err != nil {
 			return 0, err
 		}
@@ -70,7 +71,6 @@ func extractSlices(input []OrderByParams) []*comparer {
 			weightString:      order.WeightStringCol,
 			desc:              order.Desc,
 			starColFixedIndex: order.StarColFixedIndex,
-			collationID:       order.CollationID,
 		})
 	}
 	return result
diff --git a/go/vt/vtgate/engine/route.go b/go/vt/vtgate/engine/route.go
index 72b686f676..b635d9020e 100644
--- a/go/vt/vtgate/engine/route.go
+++ b/go/vt/vtgate/engine/route.go
@@ -24,7 +24,6 @@ import (
 	"strings"
 	"time"
 
-	"vitess.io/vitess/go/mysql/collations"
 	"vitess.io/vitess/go/vt/log"
 	"vitess.io/vitess/go/vt/sqlparser"
 
@@ -135,8 +134,6 @@ type OrderByParams struct {
 	StarColFixedIndex int
 	// v3 specific boolean. Used to also add weight strings originating from GroupBys to the Group by clause
 	FromGroupBy bool
-	// Collation ID for comparison using collation
-	CollationID collations.ID
 }
 
 // String returns a string. Used for plan descriptions
@@ -153,10 +150,6 @@ func (obp OrderByParams) String() string {
 	} else {
 		val += " ASC"
 	}
-	if obp.CollationID != collations.Unknown {
-		collation := collations.Default().LookupByID(obp.CollationID)
-		val += " COLLATE " + collation.Name()
-	}
 	return val
 }
 
diff --git a/go/vt/vtgate/planbuilder/horizon_planning.go b/go/vt/vtgate/planbuilder/horizon_planning.go
index 444545c1ee..0bfcab946e 100644
--- a/go/vt/vtgate/planbuilder/horizon_planning.go
+++ b/go/vt/vtgate/planbuilder/horizon_planning.go
@@ -17,7 +17,6 @@ limitations under the License.
 package planbuilder
 
 import (
-	"vitess.io/vitess/go/mysql/collations"
 	"vitess.io/vitess/go/sqltypes"
 	"vitess.io/vitess/go/vt/vtgate/planbuilder/abstract"
 
@@ -717,11 +716,11 @@ func planOrderByForRoute(orderExprs []abstract.OrderBy, plan *route, semTable *s
 		if err != nil {
 			return nil, false, err
 		}
+
 		plan.eroute.OrderBy = append(plan.eroute.OrderBy, engine.OrderByParams{
 			Col:             offset,
 			WeightStringCol: weightStringOffset,
 			Desc:            order.Inner.Direction == sqlparser.DescOrder,
-			CollationID:     semTable.CollationFor(order.Inner.Expr),
 		})
 	}
 	return plan, origColCount != plan.Select.GetColumnCount(), nil
@@ -836,38 +835,32 @@ func createMemorySortPlanOnAggregation(plan *orderedAggregate, orderExprs []abst
 	}
 
 	for _, order := range orderExprs {
-		offset, woffset, idx, found := findExprInOrderedAggr(plan, order)
+		offset, woffset, found := findExprInOrderedAggr(plan, order)
 		if !found {
 			return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "expected to find the order by expression (%s) in orderedAggregate", sqlparser.String(order.Inner))
 		}
-
-		collationID := collations.Unknown
-		if woffset != -1 {
-			collationID = plan.eaggr.GroupByKeys[idx].CollationID
-		}
 		ms.eMemorySort.OrderBy = append(ms.eMemorySort.OrderBy, engine.OrderByParams{
 			Col:               offset,
 			WeightStringCol:   woffset,
 			Desc:              order.Inner.Direction == sqlparser.DescOrder,
 			StarColFixedIndex: offset,
-			CollationID:       collationID,
 		})
 	}
 	return ms, nil
 }
 
-func findExprInOrderedAggr(plan *orderedAggregate, order abstract.OrderBy) (keyCol int, weightStringCol int, index int, found bool) {
-	for idx, key := range plan.eaggr.GroupByKeys {
+func findExprInOrderedAggr(plan *orderedAggregate, order abstract.OrderBy) (int, int, bool) {
+	for _, key := range plan.eaggr.GroupByKeys {
 		if sqlparser.EqualsExpr(order.WeightStrExpr, key.Expr) {
-			return key.KeyCol, key.WeightStringCol, idx, true
+			return key.KeyCol, key.WeightStringCol, true
 		}
 	}
-	for idx, aggregate := range plan.eaggr.Aggregates {
+	for _, aggregate := range plan.eaggr.Aggregates {
 		if sqlparser.EqualsExpr(order.WeightStrExpr, aggregate.Expr) {
-			return aggregate.Col, -1, idx, true
+			return aggregate.Col, -1, true
 		}
 	}
-	return 0, 0, 0, false
+	return 0, 0, false
 }
 
 func (hp *horizonPlanning) createMemorySortPlan(ctx *planningContext, plan logicalPlan, orderExprs []abstract.OrderBy, useWeightStr bool) (logicalPlan, error) {
@@ -896,7 +889,6 @@ func (hp *horizonPlanning) createMemorySortPlan(ctx *planningContext, plan logic
 			WeightStringCol:   weightStringOffset,
 			Desc:              order.Inner.Direction == sqlparser.DescOrder,
 			StarColFixedIndex: offset,
-			CollationID:       ctx.semTable.CollationFor(order.Inner.Expr),
 		})
 	}
 	return ms, nil
diff --git a/go/vt/vtgate/planbuilder/memory_sort.go b/go/vt/vtgate/planbuilder/memory_sort.go
index 48ed8a7d35..fda47d05d4 100644
--- a/go/vt/vtgate/planbuilder/memory_sort.go
+++ b/go/vt/vtgate/planbuilder/memory_sort.go
@@ -20,7 +20,6 @@ import (
 	"errors"
 	"fmt"
 
-	"vitess.io/vitess/go/mysql/collations"
 	"vitess.io/vitess/go/vt/vtgate/semantics"
 
 	"vitess.io/vitess/go/sqltypes"
@@ -83,14 +82,13 @@ func newMemorySort(plan logicalPlan, orderBy v3OrderBy) (*memorySort, error) {
 		if colNumber == -1 {
 			return nil, fmt.Errorf("unsupported: memory sort: order by must reference a column in the select list: %s", sqlparser.String(order))
 		}
-		// TODO(king-11) need to pass in collation here
+
 		ob := engine.OrderByParams{
 			Col:               colNumber,
 			WeightStringCol:   -1,
 			Desc:              order.Direction == sqlparser.DescOrder,
 			StarColFixedIndex: colNumber,
 			FromGroupBy:       order.fromGroupBy,
-			CollationID:       collations.Unknown,
 		}
 		ms.eMemorySort.OrderBy = append(ms.eMemorySort.OrderBy, ob)
 	}
diff --git a/go/vt/vtgate/planbuilder/ordering.go b/go/vt/vtgate/planbuilder/ordering.go
index ccf13e4de5..24a2d4231e 100644
--- a/go/vt/vtgate/planbuilder/ordering.go
+++ b/go/vt/vtgate/planbuilder/ordering.go
@@ -16,7 +16,6 @@ package planbuilder
 import (
 	"fmt"
 
-	"vitess.io/vitess/go/mysql/collations"
 	vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
 	"vitess.io/vitess/go/vt/sqlparser"
 	"vitess.io/vitess/go/vt/vterrors"
@@ -330,14 +329,12 @@ func planRouteOrdering(orderBy v3OrderBy, node *route) (logicalPlan, error) {
 			}
 		}
 
-		// TODO(king-11) pass in collation here
 		ob := engine.OrderByParams{
 			Col:               colNumber,
 			WeightStringCol:   -1,
 			Desc:              order.Direction == sqlparser.DescOrder,
 			StarColFixedIndex: starColFixedIndex,
 			FromGroupBy:       order.fromGroupBy,
-			CollationID:       collations.Unknown,
 		}
 		node.eroute.OrderBy = append(node.eroute.OrderBy, ob)
 
diff --git a/web/orchestrator/public/css/orchestrator.css b/web/orchestrator/public/css/orchestrator.css
index 0feb835110..616fcb6d0a 100644
--- a/web/orchestrator/public/css/orchestrator.css
+++ b/web/orchestrator/public/css/orchestrator.css
@@ -787,7 +787,7 @@ body {
     margin-bottom: 8px;
 }
 
-.instance .instance-primary-section {
+.instance .instance-master-section {
   position: absolute;
   bottom: 0px;
   left: 0px;
@@ -796,7 +796,7 @@ body {
   width: 48%;
 }
 
-.instance.accept_drop_check .instance-primary-section {
+.instance.accept_drop_check .instance-master-section {
   height: 100%;
 }
 
diff --git a/web/orchestrator/public/js/cluster-analysis-shared.js b/web/orchestrator/public/js/cluster-analysis-shared.js
index 9b6a5dd27a..4285712781 100644
--- a/web/orchestrator/public/js/cluster-analysis-shared.js
+++ b/web/orchestrator/public/js/cluster-analysis-shared.js
@@ -1,25 +1,25 @@
 var interestingAnalysis = {
-	"DeadPrimary" : true,
-	"DeadPrimaryAndReplicas" : true,
-	"DeadPrimaryAndSomeReplicas" : true,
-	"DeadPrimaryWithoutReplicas" : true,
-	"UnreachablePrimaryWithLaggingReplicas": true,
-	"UnreachablePrimary" : true,
-	"LockedSemiSyncPrimary" : true,
-	"AllPrimaryReplicasNotReplicating" : true,
-	"AllPrimaryReplicasNotReplicatingOrDead" : true,
-	"DeadCoPrimary" : true,
-	"DeadCoPrimaryAndSomeReplicas" : true,
-	"DeadIntermediatePrimary" : true,
-	"DeadIntermediatePrimaryWithSingleReplicaFailingToConnect" : true,
-	"DeadIntermediatePrimaryWithSingleReplica" : true,
-	"DeadIntermediatePrimaryAndSomeReplicas" : true,
-	"DeadIntermediatePrimaryAndReplicas" : true,
-	"AllIntermediatePrimaryReplicasFailingToConnectOrDead" : true,
-	"AllIntermediatePrimaryReplicasNotReplicating" : true,
-	"UnreachableIntermediatePrimaryWithLaggingReplicas": true,
-	"UnreachableIntermediatePrimary" : true,
-	"BinlogServerFailingToConnectToPrimary" : true,
+	"DeadMaster" : true,
+	"DeadMasterAndReplicas" : true,
+	"DeadMasterAndSomeReplicas" : true,
+	"DeadMasterWithoutReplicas" : true,
+	"UnreachableMasterWithLaggingReplicas": true,
+	"UnreachableMaster" : true,
+	"LockedSemiSyncMaster" : true,
+	"AllMasterReplicasNotReplicating" : true,
+	"AllMasterReplicasNotReplicatingOrDead" : true,
+	"DeadCoMaster" : true,
+	"DeadCoMasterAndSomeReplicas" : true,
+	"DeadIntermediateMaster" : true,
+	"DeadIntermediateMasterWithSingleReplicaFailingToConnect" : true,
+	"DeadIntermediateMasterWithSingleReplica" : true,
+	"DeadIntermediateMasterAndSomeReplicas" : true,
+	"DeadIntermediateMasterAndReplicas" : true,
+	"AllIntermediateMasterReplicasFailingToConnectOrDead" : true,
+	"AllIntermediateMasterReplicasNotReplicating" : true,
+	"UnreachableIntermediateMasterWithLaggingReplicas": true,
+	"UnreachableIntermediateMaster" : true,
+	"BinlogServerFailingToConnectToMaster" : true,
 };
 
 var errorMapping = {
diff --git a/web/orchestrator/public/js/cluster-tree.js b/web/orchestrator/public/js/cluster-tree.js
index 99c58a2b8d..7ca61c45ae 100644
--- a/web/orchestrator/public/js/cluster-tree.js
+++ b/web/orchestrator/public/js/cluster-tree.js
@@ -15,7 +15,7 @@ function visualizeInstances(nodesMap, onSvgInstanceWrapper, clusterControl) {
       pseudoChild.children.forEach(function(child) {
         child.parent = pseudoChild;
       });
-      pseudoChild.hasPrimary = true;
+      pseudoChild.hasMaster = true;
       pseudoChild.parent = node;
       pseudoChild.isAnchor = true;
       pseudoChild.id += "__virtualnode";
@@ -28,9 +28,9 @@ function visualizeInstances(nodesMap, onSvgInstanceWrapper, clusterControl) {
   // Calculate tree dimensions
   var maxNodeDepth = 20;
   // virtualDepth is the depth in tree excluding virtual nodes.
-  // Virtual nodes are introduced as a means to present co-primaries on same depth while retaining tree structure. This is
-  // merely for visualization purposes. In such case, a virtual node is introduced which is the parent (though not primary) of
-  // said co-primaries. But the virtual node is not displayed, and does not affect the visualized depth positioning of the nodes
+  // Virtual nodes are introduced as a means to present co-masters on same depth while retaining tree structure. This is
+  // merely for visualization purposes. In such case, a virtual node is introduced which is the parent (though not master) of
+  // said co-masters. But the virtual node is not displayed, and does not affect the visualized depth positioning of the nodes
   // underneath it.
   function getNodeDepth(node, recursiveLevel) {
     if (recursiveLevel > maxNodeDepth)
@@ -94,13 +94,13 @@ function visualizeInstances(nodesMap, onSvgInstanceWrapper, clusterControl) {
 
   var root = null;
   nodesList.forEach(function(node) {
-    if (!node.hasPrimary) {
+    if (!node.hasMaster) {
       root = node;
     }
   });
   if (root == null) {
     nodesList.forEach(function(node) {
-      if (node.isCoPrimary) {
+      if (node.isCoMaster) {
         root = node;
       }
     });
diff --git a/web/orchestrator/public/js/cluster.js b/web/orchestrator/public/js/cluster.js
index 105ee2b67b..38646e34a6 100644
--- a/web/orchestrator/public/js/cluster.js
+++ b/web/orchestrator/public/js/cluster.js
@@ -23,8 +23,8 @@ function Cluster() {
       apiCommand("/api/recover-lite/" + _instancesMap[e.draggedNodeId].Key.Hostname + "/" + _instancesMap[e.draggedNodeId].Key.Port);
       return true;
     },
-    "force-primary-failover": function(e) {
-      apiCommand("/api/force-primary-failover/" + _instancesMap[e.draggedNodeId].Key.Hostname + "/" + _instancesMap[e.draggedNodeId].Key.Port);
+    "force-master-failover": function(e) {
+      apiCommand("/api/force-master-failover/" + _instancesMap[e.draggedNodeId].Key.Hostname + "/" + _instancesMap[e.draggedNodeId].Key.Port);
       return true;
     },
     "recover-suggested-successor": function(e) {
@@ -222,7 +222,7 @@ function Cluster() {
 
     renderInstanceElement(instanceEl, node, "cluster");
 
-    var primarySectionEl = $('<div class="instance-primary-section" data-nodeid="' + node.id + '"></div>').appendTo(instanceEl);
+    var masterSectionEl = $('<div class="instance-master-section" data-nodeid="' + node.id + '"></div>').appendTo(instanceEl);
     var normalSectionEl = $('<div class="instance-normal-section" data-nodeid="' + node.id + '"></div>').appendTo(instanceEl);
     if (node.children) {
       var trailerEl = $('<div class="instance-trailer" data-nodeid="' + node.id + '"><div><span class="glyphicon glyphicon-chevron-left" title="Drag and drop replicas of this instance"></span></div></div>').appendTo(instanceEl);
@@ -254,7 +254,7 @@ function Cluster() {
 
     activateInstanceDraggable(instanceEl);
     prepareInstanceDroppable(normalSectionEl);
-    prepareInstancePrimarySectionDroppable(primarySectionEl);
+    prepareInstanceMasterSectionDroppable(masterSectionEl);
   }
 
   function instanceEl_getTrailerEl(instanceEl) {
@@ -350,20 +350,20 @@ function Cluster() {
 
   }
 
-  function prepareInstancePrimarySectionDroppable(instancePrimarySectionEl) {
+  function prepareInstanceMasterSectionDroppable(instanceMasterSectionEl) {
     var nodesMap = _instancesMap;
-    instancePrimarySectionEl.droppable({
+    instanceMasterSectionEl.droppable({
       accept: function(draggable) {
         // Find the objects that accept a draggable (i.e. valid droppables)
         if (!droppableIsActive) {
           return false
         }
-        if (instancePrimarySectionEl[0] == draggable[0])
+        if (instanceMasterSectionEl[0] == draggable[0])
           return false;
         var draggedNodeId = draggable.attr("data-nodeid");
         var draggedNode = nodesMap[draggedNodeId];
-        var targetNode = nodesMap[instancePrimarySectionEl.attr("data-nodeid")];
-        var action = _isDraggingTrailer ? moveChildren : moveInstanceOnPrimary;
+        var targetNode = nodesMap[instanceMasterSectionEl.attr("data-nodeid")];
+        var action = _isDraggingTrailer ? moveChildren : moveInstanceOnMaster;
         var acceptDrop = action(draggedNode, targetNode, false);
         var instanceDiv = $(this).closest(".instance");
         instanceDiv.addClass("accept_drop_check");
@@ -402,7 +402,7 @@ function Cluster() {
       drop: function(e, ui) {
         var draggedNodeId = ui.draggable.attr("data-nodeid");
         var duplicate = ui.helper;
-        var action = _isDraggingTrailer ? moveChildren : moveInstanceOnPrimary;
+        var action = _isDraggingTrailer ? moveChildren : moveInstanceOnMaster;
         action(nodesMap[draggedNodeId], nodesMap[$(this).attr("data-nodeid")], true);
         clearDroppable();
       }
@@ -412,7 +412,7 @@ function Cluster() {
 
   // moveInstance checks whether an instance (node) can be dropped on another (droppableNode).
   // The function consults with the current moveInstanceMethod; the type of action taken is based on that.
-  // For example, actions can be repoint, match-below, relocate, move-up, take-primary etc.
+  // For example, actions can be repoint, match-below, relocate, move-up, take-master etc.
   // When shouldApply is false nothing gets executed, and the function merely serves as a predictive
   // to the possibility of the drop.
   function moveInstance(node, droppableNode, shouldApply) {
@@ -431,15 +431,15 @@ function Cluster() {
           accept: false
         };
       }
-      if (droppableNode.SourceKey.Hostname && droppableNode.SourceKey.Hostname != "_") {
-        // droppableNode has primary
+      if (droppableNode.MasterKey.Hostname && droppableNode.MasterKey.Hostname != "_") {
+        // droppableNode has master
         if (!droppableNode.LogReplicationUpdatesEnabled) {
           // Obviously can't handle.
           return {
             accept: false
           };
         }
-        // It's OK for the primary itself to not have log_slave_updates
+        // It's OK for the master itself to not have log_slave_updates
       }
 
       if (node.id == droppableNode.id) {
@@ -447,18 +447,18 @@ function Cluster() {
           accept: false
         };
       }
-      if (instanceIsChild(droppableNode, node) && node.isPrimary && !node.isCoPrimary) {
+      if (instanceIsChild(droppableNode, node) && node.isMaster && !node.isCoMaster) {
         if (node.hasProblem) {
           return {
             accept: false
           };
         }
         if (shouldApply) {
-          makeCoPrimary(node, droppableNode);
+          makeCoMaster(node, droppableNode);
         }
         return {
           accept: "ok",
-          type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>MAKE CO PRIMARY</strong> with ' + droppableTitle,
+          type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>MAKE CO MASTER</strong> with ' + droppableTitle,
         };
       }
       if (instanceIsDescendant(droppableNode, node)) {
@@ -469,7 +469,7 @@ function Cluster() {
       }
       if (node.isAggregate) {
         if (shouldApply) {
-          relocateReplicas(node.primaryNode, droppableNode, node.aggregatedInstancesPattern);
+          relocateReplicas(node.masterNode, droppableNode, node.aggregatedInstancesPattern);
         }
         return {
           accept: "warning",
@@ -504,15 +504,15 @@ function Cluster() {
           accept: false
         };
       }
-      if (droppableNode.SourceKey.Hostname && droppableNode.SourceKey.Hostname != "_") {
-        // droppableNode has primary
+      if (droppableNode.MasterKey.Hostname && droppableNode.MasterKey.Hostname != "_") {
+        // droppableNode has master
         if (!droppableNode.LogReplicationUpdatesEnabled) {
           // Obviously can't handle.
           return {
             accept: false
           };
         }
-        // It's OK for the primary itself to not have log_slave_updates
+        // It's OK for the master itself to not have log_slave_updates
       }
 
       if (node.id == droppableNode.id) {
@@ -520,18 +520,18 @@ function Cluster() {
           accept: false
         };
       }
-      if (instanceIsChild(droppableNode, node) && node.isPrimary && !node.isCoPrimary) {
+      if (instanceIsChild(droppableNode, node) && node.isMaster && !node.isCoMaster) {
         if (node.hasProblem) {
           return {
             accept: false
           };
         }
         if (shouldApply) {
-          makeCoPrimary(node, droppableNode);
+          makeCoMaster(node, droppableNode);
         }
         return {
           accept: "ok",
-          type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>MAKE CO PRIMARY</strong> with ' + droppableTitle,
+          type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>MAKE CO MASTER</strong> with ' + droppableTitle,
         };
       }
       if (instanceIsDescendant(droppableNode, node)) {
@@ -582,31 +582,31 @@ function Cluster() {
           accept: false
         };
       }
-      if (instanceIsChild(droppableNode, node) && node.isCoPrimary) {
-        // We may allow a co-primary to change its other co-primary under some conditions,
-        // see MakeCoPrimary() in instance_topology.go
+      if (instanceIsChild(droppableNode, node) && node.isCoMaster) {
+        // We may allow a co-master to change its other co-master under some conditions,
+        // see MakeCoMaster() in instance_topology.go
         if (!droppableNode.ReadOnly) {
           return {
             accept: false
           };
         }
-        var coPrimary = node.primaryNode;
-        if (coPrimary.id == droppableNode.id) {
+        var coMaster = node.masterNode;
+        if (coMaster.id == droppableNode.id) {
           return {
             accept: false
           };
         }
-        if (coPrimary.lastCheckInvalidProblem() || coPrimary.notRecentlyCheckedProblem() || coPrimary.ReadOnly) {
+        if (coMaster.lastCheckInvalidProblem() || coMaster.notRecentlyCheckedProblem() || coMaster.ReadOnly) {
           if (shouldApply) {
-            makeCoPrimary(node, droppableNode);
+            makeCoMaster(node, droppableNode);
           }
           return {
             accept: "ok",
-            type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>MAKE CO PRIMARY</strong> with ' + droppableTitle,
+            type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>MAKE CO MASTER</strong> with ' + droppableTitle,
           };
         }
       }
-      if (node.isCoPrimary) {
+      if (node.isCoMaster) {
         return {
           accept: false
         };
@@ -630,8 +630,8 @@ function Cluster() {
           // Typically, when a node has a problem we do not allow moving it up.
           // But there's a special situation when allowing is desired: when the parent has personal issues,
           // (say disk issue or otherwise something heavyweight running which slows down replication)
-          // and you want to move up the replica which is only delayed by its primary.
-          // So to help out, if the instance is identically at its primary's trail, it is allowed to move up.
+          // and you want to move up the replica which is only delayed by its master.
+          // So to help out, if the instance is identically at its master's trail, it is allowed to move up.
           if (!node.isSQLThreadCaughtUpWithIOThread) {
             return {
               accept: false
@@ -646,7 +646,7 @@ function Cluster() {
           type: "moveUp under " + droppableTitle
         };
       }
-      if (instanceIsChild(node, droppableNode) && !droppableNode.isPrimary) {
+      if (instanceIsChild(node, droppableNode) && !droppableNode.isMaster) {
         if (node.hasProblem) {
           // Typically, when a node has a problem we do not allow moving it up.
           // But there's a special situation when allowing is desired: when
@@ -658,25 +658,25 @@ function Cluster() {
           }
         }
         if (shouldApply) {
-          takePrimary(node, droppableNode);
+          takeMaster(node, droppableNode);
         }
         return {
           accept: "ok",
-          type: "takePrimary " + droppableTitle
+          type: "takeMaster " + droppableTitle
         };
       }
-      if (instanceIsChild(droppableNode, node) && node.isPrimary && !node.isCoPrimary) {
+      if (instanceIsChild(droppableNode, node) && node.isMaster && !node.isCoMaster) {
         if (node.hasProblem) {
           return {
             accept: false
           };
         }
         if (shouldApply) {
-          makeCoPrimary(node, droppableNode);
+          makeCoMaster(node, droppableNode);
         }
         return {
           accept: "ok",
-          type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>MAKE CO PRIMARY</strong> with ' + droppableTitle,
+          type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>MAKE CO MASTER</strong> with ' + droppableTitle,
         };
       }
       return {
@@ -699,7 +699,7 @@ function Cluster() {
   }
 
 
-  function moveInstanceOnPrimary(node, droppableNode, shouldApply) {
+  function moveInstanceOnMaster(node, droppableNode, shouldApply) {
     var unaccepted = {
       accept: false
     };
@@ -713,7 +713,7 @@ function Cluster() {
       // Obviously can't handle.
       return unaccepted;
     }
-    if (instanceIsChild(node, droppableNode) && !droppableNode.isPrimary && !droppableNode.isCoPrimary) {
+    if (instanceIsChild(node, droppableNode) && !droppableNode.isMaster && !droppableNode.isCoMaster) {
       if (node.hasProblem) {
         // Typically, when a node has a problem we do not allow moving it up.
         // But there's a special situation when allowing is desired: when
@@ -725,16 +725,16 @@ function Cluster() {
         }
       }
       if (shouldApply) {
-        takePrimary(node, droppableNode);
+        takeMaster(node, droppableNode);
       }
       return {
         accept: "ok",
-        type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>take primary</strong> ' + droppableTitle
+        type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>take master</strong> ' + droppableTitle
       };
     }
     if (instanceIsChild(node, droppableNode) &&
-      droppableNode.isPrimary &&
-      !node.isCoPrimary
+      droppableNode.isMaster &&
+      !node.isCoMaster
     ) {
       if (node.hasProblem) {
         return {
@@ -742,11 +742,11 @@ function Cluster() {
         };
       }
       if (shouldApply) {
-        gracefulPrimaryTakeover(node, droppableNode);
+        gracefulMasterTakeover(node, droppableNode);
       }
       return {
         accept: "ok",
-        type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>PROMOTE AS PRIMARY</strong> '
+        type: '<span class="glyphicon glyphicon-exclamation-sign text-warning"></span> <strong>PROMOTE AS MASTER</strong> '
       };
     }
     return moveInstance(node, droppableNode, shouldApply);
@@ -773,15 +773,15 @@ function Cluster() {
           accept: false
         };
       }
-      if (droppableNode.SourceKey.Hostname && droppableNode.SourceKey.Hostname != "_") {
-        // droppableNode has primary
+      if (droppableNode.MasterKey.Hostname && droppableNode.MasterKey.Hostname != "_") {
+        // droppableNode has master
         if (!droppableNode.LogReplicationUpdatesEnabled) {
           // Obviously can't handle.
           return {
             accept: false
           };
         }
-        // It's OK for the primary itself to not have log_slave_updates
+        // It's OK for the master itself to not have log_slave_updates
       }
 
       if (node.id == droppableNode.id) {
@@ -824,15 +824,15 @@ function Cluster() {
           accept: false
         };
       }
-      if (droppableNode.SourceKey.Hostname && droppableNode.SourceKey.Hostname != "_") {
-        // droppableNode has primary
+      if (droppableNode.MasterKey.Hostname && droppableNode.MasterKey.Hostname != "_") {
+        // droppableNode has master
         if (!droppableNode.LogReplicationUpdatesEnabled) {
           // Obviously can't handle.
           return {
             accept: false
           };
         }
-        // It's OK for the primary itself to not have log_slave_updates
+        // It's OK for the master itself to not have log_slave_updates
       }
       if (node.id == droppableNode.id) {
         if (shouldApply) {
@@ -962,11 +962,11 @@ function Cluster() {
     return executeMoveOperation(message, apiUrl);
   }
 
-  function moveUpReplicas(node, primaryNode) {
+  function moveUpReplicas(node, masterNode) {
     var message = "<h4>move-up-replicas</h4>Are you sure you wish to move up replicas of <code><strong>" +
       node.Key.Hostname + ":" + node.Key.Port +
       "</strong></code> below <code><strong>" +
-      primaryNode.Key.Hostname + ":" + primaryNode.Key.Port +
+      masterNode.Key.Hostname + ":" + masterNode.Key.Port +
       "</strong></code>?";
     var apiUrl = "/api/move-up-replicas/" + node.Key.Hostname + "/" + node.Key.Port;
     return executeMoveOperation(message, apiUrl);
@@ -1002,13 +1002,13 @@ function Cluster() {
     return executeMoveOperation(message, apiUrl);
   }
 
-  function takePrimary(node, primaryNode) {
-    var message = "<h4>take-primary</h4>Are you sure you wish to make <code><strong>" +
+  function takeMaster(node, masterNode) {
+    var message = "<h4>take-master</h4>Are you sure you wish to make <code><strong>" +
       node.Key.Hostname + ":" + node.Key.Port +
-      "</strong></code> primary of <code><strong>" +
-      primaryNode.Key.Hostname + ":" + primaryNode.Key.Port +
+      "</strong></code> master of <code><strong>" +
+      masterNode.Key.Hostname + ":" + masterNode.Key.Port +
       "</strong></code>?";
-    var apiUrl = "/api/take-primary/" + node.Key.Hostname + "/" + node.Key.Port;
+    var apiUrl = "/api/take-master/" + node.Key.Hostname + "/" + node.Key.Port;
     return executeMoveOperation(message, apiUrl);
   }
 
@@ -1032,15 +1032,15 @@ function Cluster() {
     return executeMoveOperation(message, apiUrl);
   }
 
-  function makeCoPrimary(node, childNode) {
-    var message = "<h4>make-co-primary</h4>Are you sure you wish to make <code><strong>" +
+  function makeCoMaster(node, childNode) {
+    var message = "<h4>make-co-master</h4>Are you sure you wish to make <code><strong>" +
       node.Key.Hostname + ":" + node.Key.Port +
       "</strong></code> and <code><strong>" +
       childNode.Key.Hostname + ":" + childNode.Key.Port +
-      "</strong></code> co-primaries?";
+      "</strong></code> co-masters?";
     bootbox.confirm(anonymizeIfNeedBe(message), function(confirm) {
       if (confirm) {
-        apiCommand("/api/make-co-primary/" + childNode.Key.Hostname + "/" + childNode.Key.Port);
+        apiCommand("/api/make-co-master/" + childNode.Key.Hostname + "/" + childNode.Key.Port);
         return true;
       }
     });
@@ -1048,13 +1048,13 @@ function Cluster() {
   }
 
 
-  function gracefulPrimaryTakeover(newPrimaryNode, existingPrimaryNode) {
-    var message = '<h1><span class="glyphicon glyphicon-exclamation-sign text-warning"></span> DANGER ZONE</h1><h4>Graceful-primary-takeover</h4>Are you sure you wish to promote <code><strong>' +
-      newPrimaryNode.Key.Hostname + ':' + newPrimaryNode.Key.Port +
-      '</strong></code> as primary?';
+  function gracefulMasterTakeover(newMasterNode, existingMasterNode) {
+    var message = '<h1><span class="glyphicon glyphicon-exclamation-sign text-warning"></span> DANGER ZONE</h1><h4>Graceful-master-takeover</h4>Are you sure you wish to promote <code><strong>' +
+      newMasterNode.Key.Hostname + ':' + newMasterNode.Key.Port +
+      '</strong></code> as master?';
     bootbox.confirm(anonymizeIfNeedBe(message), function(confirm) {
       if (confirm) {
-        apiCommand("/api/graceful-primary-takeover/" + existingPrimaryNode.Key.Hostname + "/" + existingPrimaryNode.Key.Port + "/" + newPrimaryNode.Key.Hostname + "/" + newPrimaryNode.Key.Port);
+        apiCommand("/api/graceful-master-takeover/" + existingMasterNode.Key.Hostname + "/" + existingMasterNode.Key.Port + "/" + newMasterNode.Key.Hostname + "/" + newMasterNode.Key.Port);
         return true;
       }
     });
@@ -1063,18 +1063,18 @@ function Cluster() {
 
   function instancesAreSiblings(node1, node2) {
     if (node1.id == node2.id) return false;
-    if (node1.primaryNode == null) return false;
-    if (node2.primaryNode == null) return false;
-    if (node1.primaryNode.id != node2.primaryNode.id) return false;
+    if (node1.masterNode == null) return false;
+    if (node2.masterNode == null) return false;
+    if (node1.masterNode.id != node2.masterNode.id) return false;
     return true;
   }
 
 
   function instanceIsChild(node, parentNode) {
-    if (!node.hasPrimary) {
+    if (!node.hasMaster) {
       return false;
     }
-    if (node.primaryNode.id != parentNode.id) {
+    if (node.masterNode.id != parentNode.id) {
       return false;
     }
     if (node.id == parentNode.id) {
@@ -1085,14 +1085,14 @@ function Cluster() {
 
 
   function instanceIsGrandchild(node, grandparentNode) {
-    if (!node.hasPrimary) {
+    if (!node.hasMaster) {
       return false;
     }
-    var primaryNode = node.primaryNode;
-    if (!primaryNode.hasPrimary) {
+    var masterNode = node.masterNode;
+    if (!masterNode.hasMaster) {
       return false;
     }
-    if (primaryNode.primaryNode.id != grandparentNode.id) {
+    if (masterNode.masterNode.id != grandparentNode.id) {
       return false;
     }
     if (node.id == grandparentNode.id) {
@@ -1104,7 +1104,7 @@ function Cluster() {
   function instanceIsDescendant(node, nodeAtQuestion, depth) {
     depth = depth || 0;
     if (depth > node.ReplicationDepth + 1) {
-      // Safety check for primary-primary topologies: avoid infinite loop
+      // Safety check for master-master topologies: avoid infinite loop
       return false;
     }
     if (nodeAtQuestion == null) {
@@ -1113,18 +1113,18 @@ function Cluster() {
     if (node.id == nodeAtQuestion.id) {
       return false;
     }
-    if (!node.hasPrimary) {
+    if (!node.hasMaster) {
       return false;
     }
-    if (node.primaryNode.id == nodeAtQuestion.id) {
+    if (node.masterNode.id == nodeAtQuestion.id) {
       return true;
     }
-    return instanceIsDescendant(node.primaryNode, nodeAtQuestion, depth + 1)
+    return instanceIsDescendant(node.masterNode, nodeAtQuestion, depth + 1)
   }
 
   // Returns true when the two instances are siblings, and 'node' is behind or at same position
-  // (in reltation to shared primary) as its 'sibling'.
-  // i.e. 'sibling' is same as, or more up to date by primary than 'node'.
+  // (in reltation to shared master) as its 'sibling'.
+  // i.e. 'sibling' is same as, or more up to date by master than 'node'.
   function isReplicationBehindSibling(node, sibling) {
     if (!instancesAreSiblings(node, sibling)) {
       return false;
@@ -1141,7 +1141,7 @@ function Cluster() {
 
   function compareInstancesExecBinlogCoordinates(i0, i1) {
     if (i0.ExecBinlogCoordinates.LogFile == i1.ExecBinlogCoordinates.LogFile) {
-      // executing from same primary log file
+      // executing from same master log file
       return i0.ExecBinlogCoordinates.LogPos - i1.ExecBinlogCoordinates.LogPos;
     }
     return (getLogFileNumber(i0.ExecBinlogCoordinates.LogFile) - getLogFileNumber(i1.ExecBinlogCoordinates.LogFile));
@@ -1242,7 +1242,7 @@ function Cluster() {
       if (!instance.hasConnectivityProblem)
         return;
       // The instance has a connectivity problem! Do a client-side recommendation of most advanced replica:
-      // a direct child of the primary, with largest exec binlog coordinates.
+      // a direct child of the master, with largest exec binlog coordinates.
       var sortedChildren = instance.children.slice();
       sortedChildren.sort(compareInstancesExecBinlogCoordinates)
 
@@ -1250,10 +1250,10 @@ function Cluster() {
         if (!child.hasConnectivityProblem) {
           if (compareInstancesExecBinlogCoordinates(child, sortedChildren[sortedChildren.length - 1]) == 0) {
             child.isMostAdvancedOfSiblings = true;
-            if (instance.isPrimary && !instance.isCoPrimary) {
-              // Moreover, the instance is the (only) primary!
-              // Therefore its most advanced replicas are candidate primaries
-              child.isCandidatePrimary = true;
+            if (instance.isMaster && !instance.isCoMaster) {
+              // Moreover, the instance is the (only) master!
+              // Therefore its most advanced replicas are candidate masters
+              child.isCandidateMaster = true;
             }
           }
         }
@@ -1497,8 +1497,8 @@ function Cluster() {
     popoverElement.find(".popover-footer .dropdown").append('<ul class="dropdown-menu" aria-labelledby="recover_dropdown_' + instance.id + '"></ul>');
     var recoveryListing = popoverElement.find(".dropdown ul");
 
-    if (instance.isPrimary) {
-      recoveryListing.append('<li><a href="#" data-btn="force-primary-failover" data-command="force-primary-failover"><div class="glyphicon glyphicon-exclamation-sign text-danger"></div> <span class="text-danger">Force fail over <strong>now</strong> (even if normal handling would not fail over)</span></a></li>');
+    if (instance.isMaster) {
+      recoveryListing.append('<li><a href="#" data-btn="force-master-failover" data-command="force-master-failover"><div class="glyphicon glyphicon-exclamation-sign text-danger"></div> <span class="text-danger">Force fail over <strong>now</strong> (even if normal handling would not fail over)</span></a></li>');
       recoveryListing.append('<li role="separator" class="divider"></li>');
 
       // Suggest successor
@@ -1522,14 +1522,14 @@ function Cluster() {
           '<li><a href="#" data-btn="recover-suggested-successor" data-command="recover-suggested-successor" data-successor-host="' + replica.Key.Hostname + '" data-successor-port="' + replica.Key.Port + '">Recover, try to promote <code>' + replica.title + '</code></a></li>');
       });
     }
-    if (!instance.isPrimary) {
+    if (!instance.isMaster) {
       recoveryListing.append('<li><a href="#" data-btn="auto" data-command="recover-auto">Auto (implies running external hooks/processes)</a></li>');
       recoveryListing.append('<li role="separator" class="divider"></li>');
-      recoveryListing.append('<li><a href="#" data-btn="relocate-replicas" data-command="relocate-replicas" data-successor-host="' + instance.SourceKey.Hostname + '" data-successor-port="' + instance.SourceKey.Port + '">Relocate replicas to <code>' + instance.primaryTitle + '</code></a></li>');
+      recoveryListing.append('<li><a href="#" data-btn="relocate-replicas" data-command="relocate-replicas" data-successor-host="' + instance.MasterKey.Hostname + '" data-successor-port="' + instance.MasterKey.Port + '">Relocate replicas to <code>' + instance.masterTitle + '</code></a></li>');
     }
-    if (instance.primaryNode) {
-      // Intermediate primary; suggest successor
-      instance.primaryNode.children.forEach(function(sibling) {
+    if (instance.masterNode) {
+      // Intermediate master; suggest successor
+      instance.masterNode.children.forEach(function(sibling) {
         if (sibling.id == instance.id) {
           return
         }
@@ -1630,7 +1630,7 @@ function Cluster() {
     reviewReplicationAnalysis(replicationAnalysis);
 
     instances.forEach(function(instance) {
-      if (instance.isPrimary) {
+      if (instance.isMaster) {
         getData("/api/recently-active-instance-recovery/" + instance.Key.Hostname + "/" + instance.Key.Port, function(recoveries) {
           if (!recoveries) {
             return
@@ -1676,15 +1676,15 @@ function Cluster() {
       if (!isAnonymized()) {
         $("#cluster_name").text(visualAlias);
         var clusterSubtitle = '';
-        if (clusterInfo.HasAutomatedPrimaryRecovery === true) {
-          clusterSubtitle += '<span class="glyphicon glyphicon-heart text-info" title="Automated primary recovery for this cluster ENABLED"></span>';
+        if (clusterInfo.HasAutomatedMasterRecovery === true) {
+          clusterSubtitle += '<span class="glyphicon glyphicon-heart text-info" title="Automated master recovery for this cluster ENABLED"></span>';
         } else {
-          clusterSubtitle += '<span class="glyphicon glyphicon-heart text-muted pull-right" title="Automated primary recovery for this cluster DISABLED"></span>';
+          clusterSubtitle += '<span class="glyphicon glyphicon-heart text-muted pull-right" title="Automated master recovery for this cluster DISABLED"></span>';
         }
-        if (clusterInfo.HasAutomatedIntermediatePrimaryRecovery === true) {
-          clusterSubtitle += '<span class="glyphicon glyphicon-heart-empty text-info" title="Automated intermediate primary recovery for this cluster ENABLED"></span>';
+        if (clusterInfo.HasAutomatedIntermediateMasterRecovery === true) {
+          clusterSubtitle += '<span class="glyphicon glyphicon-heart-empty text-info" title="Automated intermediate master recovery for this cluster ENABLED"></span>';
         } else {
-          clusterSubtitle += '<span class="glyphicon glyphicon-heart-empty text-muted pull-right" title="Automated intermediate primary recovery for this cluster DISABLED"></span>';
+          clusterSubtitle += '<span class="glyphicon glyphicon-heart-empty text-muted pull-right" title="Automated intermediate master recovery for this cluster DISABLED"></span>';
         }
         $("#cluster_subtitle").append(clusterSubtitle)
 
diff --git a/web/orchestrator/public/js/clusters.js b/web/orchestrator/public/js/clusters.js
index 7ba07e044d..d32fa03f1f 100644
--- a/web/orchestrator/public/js/clusters.js
+++ b/web/orchestrator/public/js/clusters.js
@@ -126,11 +126,11 @@ $(document).ready(function() {
 
       }
       popoverElement.find("h3 .pull-right").append('<a href="' + compactClusterUri + '"><span class="glyphicon glyphicon-compressed" title="Compact display"></span></a>');
-      if (cluster.HasAutomatedIntermediatePrimaryRecovery === true) {
-        popoverElement.find("h3 .pull-right").prepend('<span class="glyphicon glyphicon-heart-empty text-info" title="Automated intermediate primary recovery for this cluster ENABLED"></span>');
+      if (cluster.HasAutomatedIntermediateMasterRecovery === true) {
+        popoverElement.find("h3 .pull-right").prepend('<span class="glyphicon glyphicon-heart-empty text-info" title="Automated intermediate master recovery for this cluster ENABLED"></span>');
       }
-      if (cluster.HasAutomatedPrimaryRecovery === true) {
-        popoverElement.find("h3 .pull-right").prepend('<span class="glyphicon glyphicon-heart text-info" title="Automated primary recovery for this cluster ENABLED"></span>');
+      if (cluster.HasAutomatedMasterRecovery === true) {
+        popoverElement.find("h3 .pull-right").prepend('<span class="glyphicon glyphicon-heart text-info" title="Automated master recovery for this cluster ENABLED"></span>');
       }
 
       var contentHtml = '' + '<div>Instances: <div class="pull-right"></div></div>';
diff --git a/web/orchestrator/public/js/orchestrator.js b/web/orchestrator/public/js/orchestrator.js
index 9cf398d97e..af157a0df6 100644
--- a/web/orchestrator/public/js/orchestrator.js
+++ b/web/orchestrator/public/js/orchestrator.js
@@ -264,12 +264,12 @@ function openNodeModal(node) {
   if (node.UnresolvedHostname) {
     addNodeModalDataAttribute("Unresolved hostname", node.UnresolvedHostname);
   }
-  if (node.SourceKey.Hostname) {
-    var td = addNodeModalDataAttribute("Primary", node.primaryTitle);
-    if (node.IsDetachedPrimary) {
-      $('#node_modal button[data-btn=reattach-replica-primary-host]').appendTo(td.find("div"));
+  if (node.MasterKey.Hostname) {
+    var td = addNodeModalDataAttribute("Master", node.masterTitle);
+    if (node.IsDetachedMaster) {
+      $('#node_modal button[data-btn=reattach-replica-master-host]').appendTo(td.find("div"));
     } else {
-      $('#node_modal button[data-btn=reattach-replica-primary-host]').appendTo(hiddenZone);
+      $('#node_modal button[data-btn=reattach-replica-master-host]').appendTo(hiddenZone);
     }
     $('#node_modal button[data-btn=reset-replica]').appendTo(td.find("div"))
 
@@ -287,21 +287,21 @@ function openNodeModal(node) {
         addNodeModalDataAttribute("Last IO error", node.LastIOError);
       }
     }
-    addNodeModalDataAttribute("Seconds behind primary", node.SecondsBehindPrimary.Valid ? node.SecondsBehindPrimary.Int64 : "null");
+    addNodeModalDataAttribute("Seconds behind master", node.SecondsBehindMaster.Valid ? node.SecondsBehindMaster.Int64 : "null");
     addNodeModalDataAttribute("Replication lag", node.ReplicationLagSeconds.Valid ? node.ReplicationLagSeconds.Int64 : "null");
     addNodeModalDataAttribute("SQL delay", node.SQLDelay);
 
-    var primaryCoordinatesEl = addNodeModalDataAttribute("Primary coordinates", node.ExecBinlogCoordinates.LogFile + ":" + node.ExecBinlogCoordinates.LogPos);
+    var masterCoordinatesEl = addNodeModalDataAttribute("Master coordinates", node.ExecBinlogCoordinates.LogFile + ":" + node.ExecBinlogCoordinates.LogPos);
     if (node.IsDetached) {
       $('#node_modal button[data-btn=detach-replica]').appendTo(hiddenZone)
-      $('#node_modal button[data-btn=reattach-replica]').appendTo(primaryCoordinatesEl.find("div"))
+      $('#node_modal button[data-btn=reattach-replica]').appendTo(masterCoordinatesEl.find("div"))
     } else {
-      $('#node_modal button[data-btn=detach-replica]').appendTo(primaryCoordinatesEl.find("div"))
+      $('#node_modal button[data-btn=detach-replica]').appendTo(masterCoordinatesEl.find("div"))
       $('#node_modal button[data-btn=reattach-replica]').appendTo(hiddenZone)
     }
   } else {
     $('#node_modal button[data-btn=reset-replica]').appendTo(hiddenZone);
-    $('#node_modal button[data-btn=reattach-replica-primary-host]').appendTo(hiddenZone);
+    $('#node_modal button[data-btn=reattach-replica-master-host]').appendTo(hiddenZone);
     $('#node_modal button[data-btn=skip-query]').appendTo(hiddenZone);
     $('#node_modal button[data-btn=detach-replica]').appendTo(hiddenZone)
     $('#node_modal button[data-btn=reattach-replica]').appendTo(hiddenZone)
@@ -400,8 +400,8 @@ function openNodeModal(node) {
   $('#node_modal button[data-btn=reattach-replica]').click(function() {
     apiCommand("/api/reattach-replica/" + node.Key.Hostname + "/" + node.Key.Port);
   });
-  $('#node_modal button[data-btn=reattach-replica-primary-host]').click(function() {
-    apiCommand("/api/reattach-replica-primary-host/" + node.Key.Hostname + "/" + node.Key.Port);
+  $('#node_modal button[data-btn=reattach-replica-master-host]').click(function() {
+    apiCommand("/api/reattach-replica-master-host/" + node.Key.Hostname + "/" + node.Key.Port);
   });
   $('#node_modal button[data-btn=reset-replica]').click(function() {
     var message = "<p>Are you sure you wish to reset <code><strong>" + node.Key.Hostname + ":" + node.Key.Port +
@@ -415,19 +415,19 @@ function openNodeModal(node) {
     });
     return false;
   });
-  $('#node_modal [data-btn=gtid-errant-reset-primary]').click(function() {
-    var message = "<p>Are you sure you wish to reset primary on <code><strong>" + node.Key.Hostname + ":" + node.Key.Port +
+  $('#node_modal [data-btn=gtid-errant-reset-master]').click(function() {
+    var message = "<p>Are you sure you wish to reset master on <code><strong>" + node.Key.Hostname + ":" + node.Key.Port +
       "</strong></code>?" +
       "<p>This will purge binary logs on server.";
     bootbox.confirm(message, function(confirm) {
       if (confirm) {
-        apiCommand("/api/gtid-errant-reset-primary/" + node.Key.Hostname + "/" + node.Key.Port);
+        apiCommand("/api/gtid-errant-reset-master/" + node.Key.Hostname + "/" + node.Key.Port);
       }
     });
     return false;
   });
   $('#node_modal [data-btn=gtid-errant-inject-empty]').click(function() {
-    var message = "<p>Are you sure you wish to inject empty transactions on the primary of this cluster?";
+    var message = "<p>Are you sure you wish to inject empty transactions on the master of this cluster?";
     bootbox.confirm(message, function(confirm) {
       if (confirm) {
         apiCommand("/api/gtid-errant-inject-empty/" + node.Key.Hostname + "/" + node.Key.Port);
@@ -495,7 +495,7 @@ function openNodeModal(node) {
   $('#node_modal button[data-btn=restart-replica]').hide();
   $('#node_modal button[data-btn=stop-replica]').hide();
 
-  if (node.SourceKey.Hostname) {
+  if (node.MasterKey.Hostname) {
     if (node.replicationRunning || node.replicationAttemptingToRun) {
       $('#node_modal button[data-btn=stop-replica]').show();
       $('#node_modal button[data-btn=restart-replica]').show();
@@ -587,17 +587,17 @@ function normalizeInstance(instance) {
   instance.id = getInstanceId(instance.Key.Hostname, instance.Key.Port);
   instance.title = instance.Key.Hostname + ':' + instance.Key.Port;
   instance.canonicalTitle = instance.title;
-  instance.primaryTitle = instance.SourceKey.Hostname + ":" + instance.SourceKey.Port;
-  // If this host is a replication group member, we set its primaryId to the group primary, unless the instance is itself
-  // the primary. In that case, we set it to its async/semi-sync primary (if configured). Notice that for group members
-  // whose role is not defined (e.g. because they are in ERROR state) we still set their primary ID to the group primary.
-  // Setting the primaryId to the group primary is what allows us to visualize group secondary members as replicating
+  instance.masterTitle = instance.MasterKey.Hostname + ":" + instance.MasterKey.Port;
+  // If this host is a replication group member, we set its masterId to the group primary, unless the instance is itself
+  // the primary. In that case, we set it to its async/semi-sync master (if configured). Notice that for group members
+  // whose role is not defined (e.g. because they are in ERROR state) we still set their master ID to the group primary.
+  // Setting the masterId to the group primary is what allows us to visualize group secondary members as replicating
   // from the group primary.
   if (instance.ReplicationGroupName != "" && (instance.ReplicationGroupMemberRole == "SECONDARY" || instance.ReplicationGroupMemberRole == ""))
-    sourceKey = instance.ReplicationGroupPrimaryInstanceKey;
+    masterKey = instance.ReplicationGroupPrimaryInstanceKey;
   else
-    sourceKey = instance.SourceKey;
-  instance.primaryId = getInstanceId(sourceKey.Hostname, sourceKey.Port);
+    masterKey = instance.MasterKey;
+  instance.masterId = getInstanceId(masterKey.Hostname, masterKey.Port);
 
   instance.replicationRunning = instance.ReplicationSQLThreadRuning && instance.ReplicationIOThreadRuning;
   instance.replicationAttemptingToRun = instance.ReplicationSQLThreadRuning || instance.ReplicationIOThreadRuning;
@@ -610,16 +610,16 @@ function normalizeInstance(instance) {
   // used by cluster-tree
   instance.children = [];
   instance.parent = null;
-  instance.hasPrimary = true;
-  instance.primaryNode = null;
+  instance.hasMaster = true;
+  instance.masterNode = null;
   instance.inMaintenance = false;
   instance.maintenanceReason = "";
   instance.maintenanceEntry = null;
   instance.isFirstChildInDisplay = false
 
-  instance.isPrimary = (instance.title == instance.ClusterName);
-  instance.isCoPrimary = false;
-  instance.isCandidatePrimary = false;
+  instance.isMaster = (instance.title == instance.ClusterName);
+  instance.isCoMaster = false;
+  instance.isCandidateMaster = false;
   instance.isMostAdvancedOfSiblings = false;
   instance.isVirtual = false;
   instance.isAnchor = false;
@@ -685,10 +685,10 @@ function normalizeInstanceProblem(instance) {
     instance.problemDescription = "Replication is not running.\nEither stopped manually or is failing on I/O or SQL error.";
     instance.problemOrder = 4;
   } else if (instance.replicationLagProblem()) {
-    instance.problemDescription = "Replica is lagging.\nThis diagnostic is based on either Seconds_behind_primary or configured ReplicationLagQuery";
+    instance.problemDescription = "Replica is lagging.\nThis diagnostic is based on either Seconds_behind_master or configured ReplicationLagQuery";
     instance.problemOrder = 5;
   } else if (instance.errantGTIDProblem()) {
-    instance.problemDescription = "Replica has GTID entries not found on its primary";
+    instance.problemDescription = "Replica has GTID entries not found on its master";
     instance.problemOrder = 6;
   } else if (instance.replicationGroupMemberStateProblem()) {
     instance.problemDescription = "Replication group member in state " + instance.ReplicationGroupMemberState;
@@ -705,11 +705,11 @@ function createVirtualInstance() {
     id: "orchestrator-virtual-instance-" + (virtualInstanceCounter++),
     children: [],
     parent: null,
-    hasPrimary: false,
+    hasMaster: false,
     inMaintenance: false,
     maintenanceEntry: null,
-    isPrimary: false,
-    isCoPrimary: false,
+    isMaster: false,
+    isCoMaster: false,
     isVirtual: true,
     ReplicationLagSeconds: 0,
     SecondsSinceLastSeen: 0
@@ -753,23 +753,23 @@ function normalizeInstances(instances, maintenanceList) {
   // create the tree array
   instances.forEach(function(instance) {
     // add to parent
-    var parent = instancesMap[instance.primaryId];
+    var parent = instancesMap[instance.masterId];
     if (parent) {
       instance.parent = parent;
-      instance.primaryNode = parent;
+      instance.masterNode = parent;
       // create child array if it doesn't exist
       parent.children.push(instance);
       // (parent.contents || (parent.contents = [])).push(instance);
     } else {
       // parent is null or missing
-      instance.hasPrimary = false;
+      instance.hasMaster = false;
       instance.parent = null;
-      instance.primaryNode = null;
+      instance.masterNode = null;
     }
   });
 
   instances.forEach(function(instance) {
-    if (instance.primaryNode != null) {
+    if (instance.masterNode != null) {
       instance.isSQLThreadCaughtUpWithIOThread = (instance.ExecBinlogCoordinates.LogFile == instance.ReadBinlogCoordinates.LogFile &&
         instance.ExecBinlogCoordinates.LogPos == instance.ReadBinlogCoordinates.LogPos);
     } else {
@@ -778,30 +778,30 @@ function normalizeInstances(instances, maintenanceList) {
   });
 
   instances.forEach(function(instance) {
-    if (instance.isPrimary && instance.parent != null && instance.parent.parent != null && instance.parent.parent.id == instance.id) {
-      // In case there's a primary-primary setup, introduce a virtual node
+    if (instance.isMaster && instance.parent != null && instance.parent.parent != null && instance.parent.parent.id == instance.id) {
+      // In case there's a master-master setup, introduce a virtual node
       // that is parent of both.
       // This is for visualization purposes...
-      var virtualCoPrimariesRoot = createVirtualInstance();
-      coPrimary = instance.parent;
+      var virtualCoMastersRoot = createVirtualInstance();
+      coMaster = instance.parent;
 
-      function setAsCoPrimary(instance, coPrimary) {
-        instance.isCoPrimary = true;
-        instance.hasPrimary = true;
-        instance.primaryId = coPrimary.id;
-        instance.primaryNode = coPrimary;
+      function setAsCoMaster(instance, coMaster) {
+        instance.isCoMaster = true;
+        instance.hasMaster = true;
+        instance.masterId = coMaster.id;
+        instance.masterNode = coMaster;
 
-        var index = coPrimary.children.indexOf(instance);
+        var index = coMaster.children.indexOf(instance);
         if (index >= 0)
-          coPrimary.children.splice(index, 1);
+          coMaster.children.splice(index, 1);
 
-        instance.parent = virtualCoPrimariesRoot;
-        virtualCoPrimariesRoot.children.push(instance);
+        instance.parent = virtualCoMastersRoot;
+        virtualCoMastersRoot.children.push(instance);
       }
-      setAsCoPrimary(instance, coPrimary);
-      setAsCoPrimary(coPrimary, instance);
+      setAsCoMaster(instance, coMaster);
+      setAsCoMaster(coMaster, instance);
 
-      instancesMap[virtualCoPrimariesRoot.id] = virtualCoPrimariesRoot;
+      instancesMap[virtualCoMastersRoot.id] = virtualCoMastersRoot;
     }
   });
   return instancesMap;
@@ -878,7 +878,7 @@ function renderInstanceElement(popoverElement, instance, renderType) {
       popoverElement.attr("data-first-child-in-display", "true");
     }
     if (instance.supportsGTID) {
-      if (instance.hasPrimary && !instance.usingGTID) {
+      if (instance.hasMaster && !instance.usingGTID) {
         popoverElement.find("h3 div.pull-right").prepend('<span class="glyphicon text-muted glyphicon-globe" title="Support GTID but not using it in replication"></span> ');
       } else if (instance.GtidErrant) {
         popoverElement.find("h3 div.pull-right").prepend('<span class="glyphicon text-danger glyphicon-globe" title="Errant GTID found"></span> ');
@@ -898,8 +898,8 @@ function renderInstanceElement(popoverElement, instance, renderType) {
     if (instance.HasReplicationFilters) {
       popoverElement.find("h3 div.pull-right").prepend('<span class="glyphicon glyphicon-filter" title="Using replication filters"></span> ');
     }
-    if (instance.SemiSyncPrimaryStatus) {
-      popoverElement.find("h3 div.pull-right").prepend('<span class="glyphicon glyphicon-check" title="Semi sync enabled (primary side)"></span> ');
+    if (instance.SemiSyncMasterStatus) {
+      popoverElement.find("h3 div.pull-right").prepend('<span class="glyphicon glyphicon-check" title="Semi sync enabled (master side)"></span> ');
     }
     if (instance.SemiSyncReplicaStatus) {
       popoverElement.find("h3 div.pull-right").prepend('<span class="glyphicon glyphicon-saved" title="Semi sync enabled (replica side)"></span> ');
@@ -944,7 +944,7 @@ function renderInstanceElement(popoverElement, instance, renderType) {
       instance.renderHint = "stale";
       indicateLastSeenInStatus = true;
     } else if (instance.notReplicatingProblem()) {
-      // check replicas only; check primary only if it's co-primary where not
+      // check replicas only; check master only if it's co-master where not
       // replicating
       instance.renderHint = "danger";
     } else if (instance.replicationLagProblem()) {
@@ -984,10 +984,10 @@ function renderInstanceElement(popoverElement, instance, renderType) {
     }
 
     var contentHtml = '' + '<div class="pull-right">' + statusMessage + ' </div>' + '<p class="instance-basic-info">' + identityHtml + '</p>';
-    if (instance.isCoPrimary) {
-      contentHtml += '<p><strong>Co primary</strong></p>';
-    } else if (instance.isPrimary) {
-      contentHtml += '<p><strong>Primary</strong></p>';
+    if (instance.isCoMaster) {
+      contentHtml += '<p><strong>Co master</strong></p>';
+    } else if (instance.isMaster) {
+      contentHtml += '<p><strong>Master</strong></p>';
     }
     if (renderType == "search") {
       if (instance.SuggestedClusterAlias) {
diff --git a/web/orchestrator/templates/faq.tmpl b/web/orchestrator/templates/faq.tmpl
index 8661594c2a..ce03e23859 100644
--- a/web/orchestrator/templates/faq.tmpl
+++ b/web/orchestrator/templates/faq.tmpl
@@ -8,7 +8,7 @@
         <strong>Who should use orchestrator?</strong>
       </p>
       <p>
-        DBAs and ops who have more than a mere primary-replica replication topology.
+        DBAs and ops who have more than a mere master-replica replication topology.
       </p>
       <p>
         <strong>Is this yet another monitoring tool?</strong>
@@ -30,19 +30,19 @@
         Yes. Statement Based Replication and Row Based Replication are both supported (and are in fact irrelevant)
       </p>
       <p>
-        <strong>Does orchestrator support Primary-Primary (ring) Replication?</strong>
+        <strong>Does orchestrator support Master-Master (ring) Replication?</strong>
       </p>
       <p>
-        Yes, for a ring of two primaries (active-active, active-passive). Do note that the tree visualization cannot present the circular replication, and will pick an arbitrary primary as the root of the tree.
+        Yes, for a ring of two masters (active-active, active-passive). Do note that the tree visualization cannot present the circular replication, and will pick an arbitrary master as the root of the tree.
       </p>
       <p>
-        Primary-Primary-Primary[-Primary...] topologies, where the ring is composed of 3 or more primaries are not supported and not tested. And are discouraged. And are an abomination.
+        Master-Master-Master[-Master...] topologies, where the ring is composed of 3 or more masters are not supported and not tested. And are discouraged. And are an abomination.
       </p>
       <p>
         <strong>Does orchestrator support Galera Replication?</strong>
       </p>
       <p>
-        Yes and no. <i>Orchestrator</i> is unaware of Galera replication. If you have three Galera primaries and different replica topologies under each primary, then <i>orchestrator</i> sees these as three different topologies.
+        Yes and no. <i>Orchestrator</i> is unaware of Galera replication. If you have three Galera masters and different replica topologies under each master, then <i>orchestrator</i> sees these as three different topologies.
       </p>
       <p>
         <strong>Does orchestrator support GTID Replication?</strong>
@@ -58,10 +58,10 @@
         <code>SHOW SLAVE STATUS</code> is incomplete. There is no expected work on this.
       </p>
       <p>
-        <strong>Does orchestrator support Multi-Primary Replication?</strong>
+        <strong>Does orchestrator support Multi-Master Replication?</strong>
       </p>
       <p>
-        No. Multi Primary Replication (e.g. as in MariaDB 10.0) is not supported.
+        No. Multi Master Replication (e.g. as in MariaDB 10.0) is not supported.
       </p>
       <p>
         <strong>Does orchestrator support Tungsten Replication?</strong>
diff --git a/web/orchestrator/templates/home.tmpl b/web/orchestrator/templates/home.tmpl
index 3053f1987d..acbef7d342 100644
--- a/web/orchestrator/templates/home.tmpl
+++ b/web/orchestrator/templates/home.tmpl
@@ -17,15 +17,15 @@
       It seems like this is your initial installation of <i>orchestrator</i>: there are no known clusters at this stage.
     </p>
     <p>
-      Your next task is to let <i>orchestrator</i> know about your replication topologies. Pick one server from each topology (this could be either primary or replica). <i>Orchestrator</i> will attempt to connect to such a server, and auto-discover the entire
-      replication tree by recursively crawling the server's primary and replicas.
+      Your next task is to let <i>orchestrator</i> know about your replication topologies. Pick one server from each topology (this could be either master or replica). <i>Orchestrator</i> will attempt to connect to such a server, and auto-discover the entire
+      replication tree by recursively crawling the server's master and replicas.
     </p>
     <p>
       Once discovered (and allow for a few minutes for complete replication graph detection), you will be able to easily change your topology via drag & drop, start & stop your replicas, start/end maintenance modes and get quick insight into replication problems.
     </p>
     <p>
       Make sure your configuration file has the proper credentials for accessing all those remote MySQL servers. You will need the <code>SUPER</code> and <code>PROCESS</code> privileges on any node you wish to be able to discover. Make sure to run the
-      following on primaries of your topologies; fill in your own host name (limit <code>'%'</code> to a specific host), user and password:
+      following on masters of your topologies; fill in your own host name (limit <code>'%'</code> to a specific host), user and password:
       <pre>
 GRANT SUPER, PROCESS ON *.* TO 'orchestrator'@'%' IDENTIFIED BY 'secret';
 </pre>
diff --git a/web/orchestrator/templates/layout.tmpl b/web/orchestrator/templates/layout.tmpl
index c193ab0fc5..b19549507b 100644
--- a/web/orchestrator/templates/layout.tmpl
+++ b/web/orchestrator/templates/layout.tmpl
@@ -200,9 +200,9 @@
 						<button type="button" class="btn btn-danger" data-btn="skip-query" title="Skip a single query and resume replication">Skip query</button>
 						<button type="button" class="btn btn-warning" data-btn="set-read-only"><span class="glyphicon glyphicon-eye-open"></span> Set read-only</button>
 						<button type="button" class="btn btn-warning" data-btn="set-writeable"><span class="glyphicon glyphicon-pencil"></span> Set writeable</button>
-						<button type="button" class="btn btn-warning" data-btn="reattach-replica-primary-host" title="Reattach woth detached primary">
+						<button type="button" class="btn btn-warning" data-btn="reattach-replica-master-host" title="Reattach woth detached master">
 							</span> Reattach</button>
-						<button type="button" class="btn btn-danger" data-btn="reset-replica" title="Make this replica forget its primary and stop replicating">Reset replica</button>
+						<button type="button" class="btn btn-danger" data-btn="reset-replica" title="Make this replica forget its master and stop replicating">Reset replica</button>
 						<button type="button" class="btn btn-info" data-btn="take-siblings" title="Take siblings of this replica">Take siblings</button>
 						<button type="button" class="btn btn-success" data-btn="enable-gtid"><span class="glyphicon glyphicon-globe"></span> Enable</button>
 						<button type="button" class="btn btn-danger" data-btn="disable-gtid"><span class="glyphicon glyphicon-remove"></span> Disable</button>
@@ -212,7 +212,7 @@
 								<span class="caret"></span> <span class="sr-only">Toggle Dropdown</span>
 							</button>
 							<ul class="dropdown-menu" role="menu">
-								<li><a href="#" data-btn="gtid-errant-reset-primary">Reset primary</a></li>
+								<li><a href="#" data-btn="gtid-errant-reset-master">Reset master</a></li>
 								<li><a href="#" data-btn="gtid-errant-inject-empty">Inject empty transactions</a></li>
 							</ul>
 						</div>


Test patch:
diff --git a/go/vt/vtgate/engine/memory_sort_test.go b/go/vt/vtgate/engine/memory_sort_test.go
index 62d3ec5b0e..9ddf3e482c 100644
--- a/go/vt/vtgate/engine/memory_sort_test.go
+++ b/go/vt/vtgate/engine/memory_sort_test.go
@@ -19,7 +19,6 @@ package engine
 import (
 	"testing"
 
-	"vitess.io/vitess/go/mysql/collations"
 	"vitess.io/vitess/go/test/utils"
 
 	"github.com/stretchr/testify/require"
@@ -207,152 +206,6 @@ func TestMemorySortExecuteWeightString(t *testing.T) {
 	utils.MustMatch(t, wantResult, result)
 }
 
-func TestMemorySortStreamExecuteCollation(t *testing.T) {
-	fields := sqltypes.MakeTestFields(
-		"normal",
-		"varchar",
-	)
-	fp := &fakePrimitive{
-		results: []*sqltypes.Result{sqltypes.MakeTestResult(
-			fields,
-			"c",
-			"d",
-			"cs",
-			"cs",
-			"c",
-		)},
-	}
-
-	collationID, _ := collations.Default().LookupID("utf8mb4_hu_0900_ai_ci")
-	ms := &MemorySort{
-		OrderBy: []OrderByParams{{
-			Col:         0,
-			CollationID: collationID,
-		}},
-		Input: fp,
-	}
-
-	var results []*sqltypes.Result
-	t.Run("order by collation", func(t *testing.T) {
-		results = nil
-		err := ms.TryStreamExecute(&noopVCursor{}, nil, true, func(qr *sqltypes.Result) error {
-			results = append(results, qr)
-			return nil
-		})
-		require.NoError(t, err)
-
-		wantResults := sqltypes.MakeTestStreamingResults(
-			fields,
-			"c",
-			"c",
-			"cs",
-			"cs",
-			"d",
-		)
-		utils.MustMatch(t, wantResults, results)
-	})
-
-	t.Run("Descending order by collation", func(t *testing.T) {
-		ms.OrderBy[0].Desc = true
-		fp.rewind()
-		results = nil
-		err := ms.TryStreamExecute(&noopVCursor{}, nil, true, func(qr *sqltypes.Result) error {
-			results = append(results, qr)
-			return nil
-		})
-		require.NoError(t, err)
-
-		wantResults := sqltypes.MakeTestStreamingResults(
-			fields,
-			"d",
-			"cs",
-			"cs",
-			"c",
-			"c",
-		)
-		utils.MustMatch(t, wantResults, results)
-	})
-
-	t.Run("Limit test", func(t *testing.T) {
-		fp.rewind()
-		upperlimit, err := sqlparser.NewPlanValue(sqlparser.NewArgument("__upper_limit"))
-		require.NoError(t, err)
-		ms.UpperLimit = upperlimit
-		bv := map[string]*querypb.BindVariable{"__upper_limit": sqltypes.Int64BindVariable(3)}
-
-		results = nil
-		err = ms.TryStreamExecute(&noopVCursor{}, bv, true, func(qr *sqltypes.Result) error {
-			results = append(results, qr)
-			return nil
-		})
-		require.NoError(t, err)
-
-		wantResults := sqltypes.MakeTestStreamingResults(
-			fields,
-			"d",
-			"cs",
-			"cs",
-		)
-		utils.MustMatch(t, wantResults, results)
-	})
-}
-
-func TestMemorySortExecuteCollation(t *testing.T) {
-	fields := sqltypes.MakeTestFields(
-		"c1",
-		"varchar",
-	)
-	fp := &fakePrimitive{
-		results: []*sqltypes.Result{sqltypes.MakeTestResult(
-			fields,
-			"c",
-			"d",
-			"cs",
-			"cs",
-			"c",
-		)},
-	}
-
-	collationID, _ := collations.Default().LookupID("utf8mb4_hu_0900_ai_ci")
-	ms := &MemorySort{
-		OrderBy: []OrderByParams{{
-			Col:         0,
-			CollationID: collationID,
-		}},
-		Input: fp,
-	}
-
-	result, err := ms.TryExecute(&noopVCursor{}, nil, false)
-	require.NoError(t, err)
-
-	wantResult := sqltypes.MakeTestResult(
-		fields,
-		"c",
-		"c",
-		"cs",
-		"cs",
-		"d",
-	)
-	utils.MustMatch(t, wantResult, result)
-
-	fp.rewind()
-	upperlimit, err := sqlparser.NewPlanValue(sqlparser.NewArgument("__upper_limit"))
-	require.NoError(t, err)
-	ms.UpperLimit = upperlimit
-	bv := map[string]*querypb.BindVariable{"__upper_limit": sqltypes.Int64BindVariable(3)}
-
-	result, err = ms.TryExecute(&noopVCursor{}, bv, false)
-	require.NoError(t, err)
-
-	wantResult = sqltypes.MakeTestResult(
-		fields,
-		"c",
-		"c",
-		"cs",
-	)
-	utils.MustMatch(t, wantResult, result)
-}
-
 func TestMemorySortStreamExecute(t *testing.T) {
 	fields := sqltypes.MakeTestFields(
 		"c1|c2",
diff --git a/go/vt/vtgate/engine/merge_sort_test.go b/go/vt/vtgate/engine/merge_sort_test.go
index b9483afce9..d9872ee044 100644
--- a/go/vt/vtgate/engine/merge_sort_test.go
+++ b/go/vt/vtgate/engine/merge_sort_test.go
@@ -20,7 +20,6 @@ import (
 	"errors"
 	"testing"
 
-	"vitess.io/vitess/go/mysql/collations"
 	"vitess.io/vitess/go/test/utils"
 
 	"github.com/stretchr/testify/require"
@@ -148,68 +147,6 @@ func TestMergeSortWeightString(t *testing.T) {
 	utils.MustMatch(t, wantResults, results)
 }
 
-func TestMergeSortCollation(t *testing.T) {
-	idColFields := sqltypes.MakeTestFields("normal", "varchar")
-	shardResults := []*shardResult{{
-		results: sqltypes.MakeTestStreamingResults(idColFields,
-			"c",
-			"---",
-			"d",
-		),
-	}, {
-		results: sqltypes.MakeTestStreamingResults(idColFields,
-			"cs",
-			"---",
-			"d",
-		),
-	}, {
-		results: sqltypes.MakeTestStreamingResults(idColFields,
-			"cs",
-			"---",
-			"lu",
-		),
-	}, {
-		results: sqltypes.MakeTestStreamingResults(idColFields,
-			"a",
-			"---",
-			"c",
-		),
-	}}
-
-	collationID, _ := collations.Default().LookupID("utf8mb4_hu_0900_ai_ci")
-	orderBy := []OrderByParams{{
-		Col:         0,
-		CollationID: collationID,
-	}}
-
-	var results []*sqltypes.Result
-	err := testMergeSort(shardResults, orderBy, func(qr *sqltypes.Result) error {
-		results = append(results, qr)
-		return nil
-	})
-	require.NoError(t, err)
-
-	// Results are returned one row at a time.
-	wantResults := sqltypes.MakeTestStreamingResults(idColFields,
-		"a",
-		"---",
-		"c",
-		"---",
-		"c",
-		"---",
-		"cs",
-		"---",
-		"cs",
-		"---",
-		"d",
-		"---",
-		"d",
-		"---",
-		"lu",
-	)
-	utils.MustMatch(t, wantResults, results)
-}
-
 // TestMergeSortDescending tests the normal flow of a merge
 // sort where all shards return descending rows.
 func TestMergeSortDescending(t *testing.T) {
diff --git a/go/vt/vtgate/engine/route_test.go b/go/vt/vtgate/engine/route_test.go
index aeb1ffd06f..6cf0b91f96 100644
--- a/go/vt/vtgate/engine/route_test.go
+++ b/go/vt/vtgate/engine/route_test.go
@@ -22,7 +22,6 @@ import (
 
 	"github.com/stretchr/testify/assert"
 
-	"vitess.io/vitess/go/mysql/collations"
 	vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
 	"vitess.io/vitess/go/vt/vterrors"
 
@@ -982,137 +981,6 @@ func TestRouteSortWeightStrings(t *testing.T) {
 	})
 }
 
-func TestRouteSortCollation(t *testing.T) {
-	sel := NewRoute(
-		SelectUnsharded,
-		&vindexes.Keyspace{
-			Name:    "ks",
-			Sharded: false,
-		},
-		"dummy_select",
-		"dummy_select_field",
-	)
-
-	collationID, _ := collations.Default().LookupID("utf8mb4_hu_0900_ai_ci")
-
-	sel.OrderBy = []OrderByParams{{
-		Col:         0,
-		CollationID: collationID,
-	}}
-
-	vc := &loggingVCursor{
-		shards: []string{"0"},
-		results: []*sqltypes.Result{
-			sqltypes.MakeTestResult(
-				sqltypes.MakeTestFields(
-					"normal",
-					"varchar",
-				),
-				"c",
-				"d",
-				"cs",
-				"cs",
-				"c",
-			),
-		},
-	}
-
-	var result *sqltypes.Result
-	var wantResult *sqltypes.Result
-	var err error
-	t.Run("Sort using Collation", func(t *testing.T) {
-		result, err = sel.TryExecute(vc, map[string]*querypb.BindVariable{}, false)
-		require.NoError(t, err)
-		vc.ExpectLog(t, []string{
-			`ResolveDestinations ks [] Destinations:DestinationAnyShard()`,
-			`ExecuteMultiShard ks.0: dummy_select {} false false`,
-		})
-		wantResult = sqltypes.MakeTestResult(
-			sqltypes.MakeTestFields(
-				"normal",
-				"varchar",
-			),
-			"c",
-			"c",
-			"cs",
-			"cs",
-			"d",
-		)
-		expectResult(t, "sel.Execute", result, wantResult)
-	})
-
-	t.Run("Descending ordering using Collation", func(t *testing.T) {
-		sel.OrderBy[0].Desc = true
-		vc.Rewind()
-		result, err = sel.TryExecute(vc, map[string]*querypb.BindVariable{}, false)
-		require.NoError(t, err)
-		wantResult = sqltypes.MakeTestResult(
-			sqltypes.MakeTestFields(
-				"normal",
-				"varchar",
-			),
-			"d",
-			"cs",
-			"cs",
-			"c",
-			"c",
-		)
-		expectResult(t, "sel.Execute", result, wantResult)
-	})
-
-	t.Run("Error when Unknown Collation", func(t *testing.T) {
-		sel.OrderBy = []OrderByParams{{
-			Col:         0,
-			CollationID: collations.Unknown,
-		}}
-
-		vc := &loggingVCursor{
-			shards: []string{"0"},
-			results: []*sqltypes.Result{
-				sqltypes.MakeTestResult(
-					sqltypes.MakeTestFields(
-						"normal",
-						"varchar",
-					),
-					"c",
-					"d",
-					"cs",
-					"cs",
-					"c",
-				),
-			},
-		}
-		_, err = sel.TryExecute(vc, map[string]*querypb.BindVariable{}, false)
-		require.EqualError(t, err, "types are not comparable: VARCHAR vs VARCHAR")
-	})
-
-	t.Run("Error when Unsupported Collation", func(t *testing.T) {
-		sel.OrderBy = []OrderByParams{{
-			Col:         0,
-			CollationID: 1111,
-		}}
-
-		vc := &loggingVCursor{
-			shards: []string{"0"},
-			results: []*sqltypes.Result{
-				sqltypes.MakeTestResult(
-					sqltypes.MakeTestFields(
-						"normal",
-						"varchar",
-					),
-					"c",
-					"d",
-					"cs",
-					"cs",
-					"c",
-				),
-			},
-		}
-		_, err = sel.TryExecute(vc, map[string]*querypb.BindVariable{}, false)
-		require.EqualError(t, err, "comparison using collation 1111 isn't possible")
-	})
-}
-
 func TestRouteSortTruncate(t *testing.T) {
 	sel := NewRoute(
 		SelectUnsharded,
diff --git a/go/vt/vtgate/planbuilder/testdata/aggr_cases.txt b/go/vt/vtgate/planbuilder/testdata/aggr_cases.txt
index d70f784453..7b96aadf50 100644
--- a/go/vt/vtgate/planbuilder/testdata/aggr_cases.txt
+++ b/go/vt/vtgate/planbuilder/testdata/aggr_cases.txt
@@ -145,7 +145,7 @@ Gen4 error: Expression of SELECT list is not in GROUP BY clause and contains non
           "Sharded": true
         },
         "FieldQuery": "select count(*), a, textcol1, b, weight_string(a), weight_string(textcol1), weight_string(b) from `user` where 1 != 1 group by a, weight_string(a), textcol1, weight_string(textcol1), b, weight_string(b)",
-        "OrderBy": "(1|4) ASC, (2|5) ASC COLLATE latin1_swedish_ci, (3|6) ASC",
+        "OrderBy": "(1|4) ASC, (2|5) ASC, (3|6) ASC",
         "Query": "select count(*), a, textcol1, b, weight_string(a), weight_string(textcol1), weight_string(b) from `user` group by a, weight_string(a), textcol1, weight_string(textcol1), b, weight_string(b) order by a asc, textcol1 asc, b asc",
         "Table": "`user`"
       }
@@ -246,7 +246,7 @@ Gen4 error: Expression of SELECT list is not in GROUP BY clause and contains non
   "Instructions": {
     "OperatorType": "Sort",
     "Variant": "Memory",
-    "OrderBy": "0 ASC, (2|5) ASC COLLATE latin1_swedish_ci",
+    "OrderBy": "0 ASC, (2|5) ASC",
     "ResultColumns": 4,
     "Inputs": [
       {
@@ -263,7 +263,7 @@ Gen4 error: Expression of SELECT list is not in GROUP BY clause and contains non
               "Sharded": true
             },
             "FieldQuery": "select count(*) as k, a, textcol1, b, weight_string(a), weight_string(textcol1), weight_string(b) from `user` where 1 != 1 group by a, weight_string(a), textcol1, weight_string(textcol1), b, weight_string(b)",
-            "OrderBy": "(1|4) ASC, (2|5) ASC COLLATE latin1_swedish_ci, (3|6) ASC",
+            "OrderBy": "(1|4) ASC, (2|5) ASC, (3|6) ASC",
             "Query": "select count(*) as k, a, textcol1, b, weight_string(a), weight_string(textcol1), weight_string(b) from `user` group by a, weight_string(a), textcol1, weight_string(textcol1), b, weight_string(b) order by a asc, textcol1 asc, b asc",
             "Table": "`user`"
           }
diff --git a/go/vt/vtgate/planbuilder/testdata/from_cases.txt b/go/vt/vtgate/planbuilder/testdata/from_cases.txt
index c50b51f139..82380e2196 100644
--- a/go/vt/vtgate/planbuilder/testdata/from_cases.txt
+++ b/go/vt/vtgate/planbuilder/testdata/from_cases.txt
@@ -493,6 +493,7 @@ Gen4 plan same as above
   }
 }
 
+
 # ',' join
 "select music.col from user, music"
 {
diff --git a/go/vt/vtgate/planbuilder/testdata/memory_sort_cases.txt b/go/vt/vtgate/planbuilder/testdata/memory_sort_cases.txt
index d2050b74ba..d1a32f7f0e 100644
--- a/go/vt/vtgate/planbuilder/testdata/memory_sort_cases.txt
+++ b/go/vt/vtgate/planbuilder/testdata/memory_sort_cases.txt
@@ -234,7 +234,7 @@ Gen4 error: Expression of SELECT list is not in GROUP BY clause and contains non
   "Instructions": {
     "OperatorType": "Sort",
     "Variant": "Memory",
-    "OrderBy": "(2|3) ASC COLLATE latin1_swedish_ci, 1 ASC, (2|3) ASC COLLATE latin1_swedish_ci",
+    "OrderBy": "(2|3) ASC, 1 ASC, (2|3) ASC",
     "ResultColumns": 2,
     "Inputs": [
       {
@@ -251,7 +251,7 @@ Gen4 error: Expression of SELECT list is not in GROUP BY clause and contains non
               "Sharded": true
             },
             "FieldQuery": "select textcol1 as t, count(*) as k, textcol1, weight_string(textcol1) from `user` where 1 != 1 group by textcol1, weight_string(textcol1)",
-            "OrderBy": "(2|3) ASC COLLATE latin1_swedish_ci",
+            "OrderBy": "(2|3) ASC",
             "Query": "select textcol1 as t, count(*) as k, textcol1, weight_string(textcol1) from `user` group by textcol1, weight_string(textcol1) order by textcol1 asc",
             "Table": "`user`"
           }
@@ -627,48 +627,7 @@ Gen4 error: Expression of SELECT list is not in GROUP BY clause and contains non
     ]
   }
 }
-{
-  "QueryType": "SELECT",
-  "Original": "select u.a, u.textcol1, un.col2 from user u join unsharded un order by u.textcol1, un.col2",
-  "Instructions": {
-    "OperatorType": "Sort",
-    "Variant": "Memory",
-    "OrderBy": "(1|3) ASC COLLATE latin1_swedish_ci, (2|4) ASC",
-    "ResultColumns": 3,
-    "Inputs": [
-      {
-        "OperatorType": "Join",
-        "Variant": "Join",
-        "JoinColumnIndexes": "-1,-2,1,-3,2",
-        "TableName": "`user`_unsharded",
-        "Inputs": [
-          {
-            "OperatorType": "Route",
-            "Variant": "SelectScatter",
-            "Keyspace": {
-              "Name": "user",
-              "Sharded": true
-            },
-            "FieldQuery": "select u.a, u.textcol1, weight_string(u.textcol1) from `user` as u where 1 != 1",
-            "Query": "select u.a, u.textcol1, weight_string(u.textcol1) from `user` as u",
-            "Table": "`user`"
-          },
-          {
-            "OperatorType": "Route",
-            "Variant": "SelectUnsharded",
-            "Keyspace": {
-              "Name": "main",
-              "Sharded": false
-            },
-            "FieldQuery": "select un.col2, weight_string(un.col2) from unsharded as un where 1 != 1",
-            "Query": "select un.col2, weight_string(un.col2) from unsharded as un",
-            "Table": "unsharded"
-          }
-        ]
-      }
-    ]
-  }
-}
+Gen4 plan same as above
 
 # Order by for join, on text column in RHS.
 "select u.a, u.textcol1, un.col2 from unsharded un join user u order by u.textcol1, un.col2"
@@ -714,48 +673,7 @@ Gen4 error: Expression of SELECT list is not in GROUP BY clause and contains non
     ]
   }
 }
-{
-  "QueryType": "SELECT",
-  "Original": "select u.a, u.textcol1, un.col2 from unsharded un join user u order by u.textcol1, un.col2",
-  "Instructions": {
-    "OperatorType": "Sort",
-    "Variant": "Memory",
-    "OrderBy": "(1|3) ASC COLLATE latin1_swedish_ci, (2|4) ASC",
-    "ResultColumns": 3,
-    "Inputs": [
-      {
-        "OperatorType": "Join",
-        "Variant": "Join",
-        "JoinColumnIndexes": "1,2,-1,3,-2",
-        "TableName": "unsharded_`user`",
-        "Inputs": [
-          {
-            "OperatorType": "Route",
-            "Variant": "SelectUnsharded",
-            "Keyspace": {
-              "Name": "main",
-              "Sharded": false
-            },
-            "FieldQuery": "select un.col2, weight_string(un.col2) from unsharded as un where 1 != 1",
-            "Query": "select un.col2, weight_string(un.col2) from unsharded as un",
-            "Table": "unsharded"
-          },
-          {
-            "OperatorType": "Route",
-            "Variant": "SelectScatter",
-            "Keyspace": {
-              "Name": "user",
-              "Sharded": true
-            },
-            "FieldQuery": "select u.a, u.textcol1, weight_string(u.textcol1) from `user` as u where 1 != 1",
-            "Query": "select u.a, u.textcol1, weight_string(u.textcol1) from `user` as u",
-            "Table": "`user`"
-          }
-        ]
-      }
-    ]
-  }
-}
+Gen4 plan same as above
 
 # order by for vindex func
 "select id, keyspace_id, range_start, range_end from user_index where id = :id order by range_start"
diff --git a/go/vt/vtgate/planbuilder/testdata/oltp_cases.txt b/go/vt/vtgate/planbuilder/testdata/oltp_cases.txt
index 97d31bdbb1..cf11eb98c6 100644
--- a/go/vt/vtgate/planbuilder/testdata/oltp_cases.txt
+++ b/go/vt/vtgate/planbuilder/testdata/oltp_cases.txt
@@ -106,23 +106,7 @@ Gen4 plan same as above
     "Table": "sbtest1"
   }
 }
-{
-  "QueryType": "SELECT",
-  "Original": "SELECT c FROM sbtest1 WHERE id BETWEEN 50 AND 235 ORDER BY c",
-  "Instructions": {
-    "OperatorType": "Route",
-    "Variant": "SelectScatter",
-    "Keyspace": {
-      "Name": "main",
-      "Sharded": true
-    },
-    "FieldQuery": "select c, weight_string(c) from sbtest1 where 1 != 1",
-    "OrderBy": "(0|1) ASC COLLATE latin1_swedish_ci",
-    "Query": "select c, weight_string(c) from sbtest1 where id between 50 and 235 order by c asc",
-    "ResultColumns": 1,
-    "Table": "sbtest1"
-  }
-}
+Gen4 plan same as above
 
 # OLTP distinct range select
 "SELECT DISTINCT c FROM sbtest30 WHERE id BETWEEN 1 AND 10 ORDER BY c"
@@ -168,7 +152,7 @@ Gen4 plan same as above
           "Sharded": true
         },
         "FieldQuery": "select c, weight_string(c) from sbtest30 where 1 != 1",
-        "OrderBy": "(0|1) ASC COLLATE latin1_swedish_ci, (0|1) ASC COLLATE latin1_swedish_ci",
+        "OrderBy": "(0|1) ASC, (0|1) ASC",
         "Query": "select distinct c, weight_string(c) from sbtest30 where id between 1 and 10 order by c asc, c asc",
         "Table": "sbtest30"
       }
diff --git a/go/vt/vtgate/planbuilder/testdata/postprocess_cases.txt b/go/vt/vtgate/planbuilder/testdata/postprocess_cases.txt
index 9a8fee0479..2bc80f5903 100644
--- a/go/vt/vtgate/planbuilder/testdata/postprocess_cases.txt
+++ b/go/vt/vtgate/planbuilder/testdata/postprocess_cases.txt
@@ -407,23 +407,7 @@ Gen4 plan same as above
     "Table": "authoritative"
   }
 }
-{
-  "QueryType": "SELECT",
-  "Original": "select * from authoritative order by col1",
-  "Instructions": {
-    "OperatorType": "Route",
-    "Variant": "SelectScatter",
-    "Keyspace": {
-      "Name": "user",
-      "Sharded": true
-    },
-    "FieldQuery": "select user_id, col1, col2, weight_string(col1) from authoritative where 1 != 1",
-    "OrderBy": "(1|3) ASC COLLATE latin1_swedish_ci",
-    "Query": "select user_id, col1, col2, weight_string(col1) from authoritative order by col1 asc",
-    "ResultColumns": 3,
-    "Table": "authoritative"
-  }
-}
+Gen4 plan same as above
 
 # ORDER BY on scatter with text column
 "select a, textcol1, b from user order by a, textcol1, b"
@@ -444,23 +428,7 @@ Gen4 plan same as above
     "Table": "`user`"
   }
 }
-{
-  "QueryType": "SELECT",
-  "Original": "select a, textcol1, b from user order by a, textcol1, b",
-  "Instructions": {
-    "OperatorType": "Route",
-    "Variant": "SelectScatter",
-    "Keyspace": {
-      "Name": "user",
-      "Sharded": true
-    },
-    "FieldQuery": "select a, textcol1, b, weight_string(a), weight_string(textcol1), weight_string(b) from `user` where 1 != 1",
-    "OrderBy": "(0|3) ASC, (1|4) ASC COLLATE latin1_swedish_ci, (2|5) ASC",
-    "Query": "select a, textcol1, b, weight_string(a), weight_string(textcol1), weight_string(b) from `user` order by a asc, textcol1 asc, b asc",
-    "ResultColumns": 3,
-    "Table": "`user`"
-  }
-}
+Gen4 plan same as above
 
 # ORDER BY on scatter with text column, qualified name TODO: can plan better
 "select a, user.textcol1, b from user order by a, textcol1, b"
@@ -492,7 +460,7 @@ Gen4 plan same as above
       "Sharded": true
     },
     "FieldQuery": "select a, `user`.textcol1, b, weight_string(a), weight_string(textcol1), weight_string(b) from `user` where 1 != 1",
-    "OrderBy": "(0|3) ASC, (1|4) ASC COLLATE latin1_swedish_ci, (2|5) ASC",
+    "OrderBy": "(0|3) ASC, (1|4) ASC, (2|5) ASC",
     "Query": "select a, `user`.textcol1, b, weight_string(a), weight_string(textcol1), weight_string(b) from `user` order by a asc, textcol1 asc, b asc",
     "ResultColumns": 3,
     "Table": "`user`"
@@ -518,23 +486,7 @@ Gen4 plan same as above
     "Table": "`user`"
   }
 }
-{
-  "QueryType": "SELECT",
-  "Original": "select a, textcol1, b, textcol2 from user order by a, textcol1, b, textcol2",
-  "Instructions": {
-    "OperatorType": "Route",
-    "Variant": "SelectScatter",
-    "Keyspace": {
-      "Name": "user",
-      "Sharded": true
-    },
-    "FieldQuery": "select a, textcol1, b, textcol2, weight_string(a), weight_string(textcol1), weight_string(b), weight_string(textcol2) from `user` where 1 != 1",
-    "OrderBy": "(0|4) ASC, (1|5) ASC COLLATE latin1_swedish_ci, (2|6) ASC, (3|7) ASC COLLATE latin1_swedish_ci",
-    "Query": "select a, textcol1, b, textcol2, weight_string(a), weight_string(textcol1), weight_string(b), weight_string(textcol2) from `user` order by a asc, textcol1 asc, b asc, textcol2 asc",
-    "ResultColumns": 4,
-    "Table": "`user`"
-  }
-}
+Gen4 plan same as above
 
 # ORDER BY invalid col number on scatter
 "select col from user order by 2"