Repository: vitessio/vitess
Pull request #7929 (2021-04-22 11:56:29)

vttablet/tabletmanager: add isInSRVKeyspace/isShardServing
Signed-off-by: Guido Iaquinti <giaquinti@slack-corp.com>

## Description
Add a new metric in `vttablet` to keep track if the keyspace partition it belongs to is serving or not. This metric can be useful for external systems to automatically enable/disable alerts.

In order to don't add additional watches to the topology service (as we don't want those to linearly scale with the number of vttablets), we refresh the serving keyspace view in TabletManager only when `RefreshFromTopoInfo` is called.

Note: this PR is still a WIP but I'll appreciate an early feedback. 

## Related Issue(s)
N/A

## Checklist
- [ ] Should this PR be backported?
- [X] Tests were added or are not required
- [ ] Documentation was added or is not required

## Deployment Notes
N/A

## Impacted Areas in Vitess
Components that this PR will affect:

- [ ]  Query Serving
- [ ]  VReplication
- [X]  Cluster Management
- [ ]  Build/CI
- [ ]  VTAdmin



Patch:
diff --git a/config/mycnf/default.cnf b/config/mycnf/default.cnf
index 06f2b5dd82..8facbbe034 100644
--- a/config/mycnf/default.cnf
+++ b/config/mycnf/default.cnf
@@ -10,10 +10,6 @@ relay-log-index =  {{.RelayLogIndexPath}}
 pid-file = {{.PidFile}}
 port = {{.MysqlPort}}
 
-{{if .SecureFilePriv}}
-secure-file-priv = {{.SecureFilePriv}}
-{{end}}
-
 # all db instances should start in read-only mode - once the db is started and
 # fully functional, we'll push it into read-write mode
 read-only
diff --git a/go/bytes2/buffer.go b/go/bytes2/buffer.go
index 1725274c43..a7dacf2d04 100644
--- a/go/bytes2/buffer.go
+++ b/go/bytes2/buffer.go
@@ -16,8 +16,6 @@ limitations under the License.
 
 package bytes2
 
-import "unsafe"
-
 // Buffer implements a subset of the write portion of
 // bytes.Buffer, but more efficiently. This is meant to
 // be used in very high QPS operations, especially for
@@ -61,18 +59,6 @@ func (buf *Buffer) String() string {
 	return string(buf.bytes)
 }
 
-// StringUnsafe is equivalent to String, but the copy of the string that it returns
-// is _not_ allocated, so modifying this buffer after calling StringUnsafe will lead
-// to undefined behavior.
-func (buf *Buffer) StringUnsafe() string {
-	return *(*string)(unsafe.Pointer(&buf.bytes))
-}
-
-// Reset is equivalent to bytes.Buffer.Reset.
-func (buf *Buffer) Reset() {
-	buf.bytes = buf.bytes[:0]
-}
-
 // Len is equivalent to bytes.Buffer.Len.
 func (buf *Buffer) Len() int {
 	return len(buf.bytes)
diff --git a/go/sqltypes/value.go b/go/sqltypes/value.go
index b73b6ec7f3..51b9e41e1d 100644
--- a/go/sqltypes/value.go
+++ b/go/sqltypes/value.go
@@ -284,36 +284,6 @@ func (v Value) EncodeSQL(b BinWriter) {
 	}
 }
 
-// EncodeSQLStringBuilder is identical to EncodeSQL but it takes a strings.Builder
-// as its writer, so it can be inlined for performance.
-func (v Value) EncodeSQLStringBuilder(b *strings.Builder) {
-	switch {
-	case v.typ == Null:
-		b.Write(nullstr)
-	case v.IsQuoted():
-		encodeBytesSQLStringBuilder(v.val, b)
-	case v.typ == Bit:
-		encodeBytesSQLBits(v.val, b)
-	default:
-		b.Write(v.val)
-	}
-}
-
-// EncodeSQLBytes2 is identical to EncodeSQL but it takes a bytes2.Buffer
-// as its writer, so it can be inlined for performance.
-func (v Value) EncodeSQLBytes2(b *bytes2.Buffer) {
-	switch {
-	case v.typ == Null:
-		b.Write(nullstr)
-	case v.IsQuoted():
-		encodeBytesSQLBytes2(v.val, b)
-	case v.typ == Bit:
-		encodeBytesSQLBits(v.val, b)
-	default:
-		b.Write(v.val)
-	}
-}
-
 // EncodeASCII encodes the value using 7-bit clean ascii bytes.
 func (v Value) EncodeASCII(b BinWriter) {
 	switch {
@@ -417,24 +387,6 @@ func (v *Value) UnmarshalJSON(b []byte) error {
 
 func encodeBytesSQL(val []byte, b BinWriter) {
 	buf := &bytes2.Buffer{}
-	encodeBytesSQLBytes2(val, buf)
-	b.Write(buf.Bytes())
-}
-
-func encodeBytesSQLBytes2(val []byte, buf *bytes2.Buffer) {
-	buf.WriteByte('\'')
-	for _, ch := range val {
-		if encodedChar := SQLEncodeMap[ch]; encodedChar == DontEscape {
-			buf.WriteByte(ch)
-		} else {
-			buf.WriteByte('\\')
-			buf.WriteByte(encodedChar)
-		}
-	}
-	buf.WriteByte('\'')
-}
-
-func encodeBytesSQLStringBuilder(val []byte, buf *strings.Builder) {
 	buf.WriteByte('\'')
 	for _, ch := range val {
 		if encodedChar := SQLEncodeMap[ch]; encodedChar == DontEscape {
@@ -445,6 +397,7 @@ func encodeBytesSQLStringBuilder(val []byte, buf *strings.Builder) {
 		}
 	}
 	buf.WriteByte('\'')
+	b.Write(buf.Bytes())
 }
 
 // BufEncodeStringSQL encodes the string into a strings.Builder
diff --git a/go/vt/discovery/fake_healthcheck.go b/go/vt/discovery/fake_healthcheck.go
index bbb1ec98ba..c762eb48be 100644
--- a/go/vt/discovery/fake_healthcheck.go
+++ b/go/vt/discovery/fake_healthcheck.go
@@ -21,18 +21,20 @@ import (
 	"sort"
 	"sync"
 
+	"vitess.io/vitess/go/sync2"
+
 	"github.com/golang/protobuf/proto"
 
-	"vitess.io/vitess/go/sync2"
+	"vitess.io/vitess/go/vt/proto/vtrpc"
+	"vitess.io/vitess/go/vt/vterrors"
+
 	"vitess.io/vitess/go/vt/topo"
 	"vitess.io/vitess/go/vt/topo/topoproto"
-	"vitess.io/vitess/go/vt/vterrors"
 	"vitess.io/vitess/go/vt/vttablet/queryservice"
 	"vitess.io/vitess/go/vt/vttablet/sandboxconn"
 
 	querypb "vitess.io/vitess/go/vt/proto/query"
 	topodatapb "vitess.io/vitess/go/vt/proto/topodata"
-	vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
 )
 
 var (
@@ -144,23 +146,16 @@ func (fhc *FakeHealthCheck) ReplaceTablet(old, new *topodatapb.Tablet) {
 }
 
 // TabletConnection returns the TabletConn of the given tablet.
-func (fhc *FakeHealthCheck) TabletConnection(alias *topodatapb.TabletAlias, target *querypb.Target) (queryservice.QueryService, error) {
+func (fhc *FakeHealthCheck) TabletConnection(alias *topodatapb.TabletAlias) (queryservice.QueryService, error) {
 	aliasStr := topoproto.TabletAliasString(alias)
 	fhc.mu.RLock()
 	defer fhc.mu.RUnlock()
 	for _, item := range fhc.items {
 		if proto.Equal(alias, item.ts.Tablet.Alias) {
-			if !item.ts.Serving {
-				return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, vterrors.NotServing)
-			}
-			if target != nil && !proto.Equal(item.ts.Target, target) {
-				return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "%s: target mismatch %v vs %v", vterrors.WrongTablet, item.ts.Target, target)
-			}
-
 			return item.ts.Conn, nil
 		}
 	}
-	return nil, vterrors.Errorf(vtrpcpb.Code_NOT_FOUND, "tablet %v not found", aliasStr)
+	return nil, vterrors.Errorf(vtrpc.Code_NOT_FOUND, "tablet %v not found", aliasStr)
 }
 
 // CacheStatus returns the status for each tablet
diff --git a/go/vt/discovery/healthcheck.go b/go/vt/discovery/healthcheck.go
index 513761a2fb..4af9dfd720 100644
--- a/go/vt/discovery/healthcheck.go
+++ b/go/vt/discovery/healthcheck.go
@@ -45,18 +45,19 @@ import (
 	"sync"
 	"time"
 
-	"github.com/golang/protobuf/proto"
+	"vitess.io/vitess/go/vt/proto/vtrpc"
+	"vitess.io/vitess/go/vt/vterrors"
+	"vitess.io/vitess/go/vt/vttablet/queryservice"
 
 	"vitess.io/vitess/go/flagutil"
+
+	"vitess.io/vitess/go/vt/topo"
+
 	"vitess.io/vitess/go/stats"
 	"vitess.io/vitess/go/vt/log"
 	"vitess.io/vitess/go/vt/proto/query"
 	"vitess.io/vitess/go/vt/proto/topodata"
-	"vitess.io/vitess/go/vt/proto/vtrpc"
-	"vitess.io/vitess/go/vt/topo"
 	"vitess.io/vitess/go/vt/topo/topoproto"
-	"vitess.io/vitess/go/vt/vterrors"
-	"vitess.io/vitess/go/vt/vttablet/queryservice"
 )
 
 var (
@@ -176,7 +177,7 @@ type HealthCheck interface {
 	WaitForAllServingTablets(ctx context.Context, targets []*query.Target) error
 
 	// TabletConnection returns the TabletConn of the given tablet.
-	TabletConnection(alias *topodata.TabletAlias, target *query.Target) (queryservice.QueryService, error)
+	TabletConnection(alias *topodata.TabletAlias) (queryservice.QueryService, error)
 
 	// RegisterStats registers the connection counts stats
 	RegisterStats()
@@ -447,14 +448,8 @@ func (hc *HealthCheckImpl) updateHealth(th *TabletHealth, prevTarget *query.Targ
 			}
 		}
 	case isPrimary && !isPrimaryUp:
-		if healthy, ok := hc.healthy[targetKey]; ok && len(healthy) > 0 {
-			// isPrimary is true here therefore we should only have 1 tablet in healthy
-			alias := tabletAliasString(topoproto.TabletAliasString(healthy[0].Tablet.Alias))
-			// Clear healthy list for primary if the existing tablet is down
-			if alias == tabletAlias {
-				hc.healthy[targetKey] = []*TabletHealth{}
-			}
-		}
+		// No healthy master tablet
+		hc.healthy[targetKey] = []*TabletHealth{}
 	}
 
 	if !trivialUpdate {
@@ -698,7 +693,7 @@ func (hc *HealthCheckImpl) waitForTablets(ctx context.Context, targets []*query.
 }
 
 // TabletConnection returns the Connection to a given tablet.
-func (hc *HealthCheckImpl) TabletConnection(alias *topodata.TabletAlias, target *query.Target) (queryservice.QueryService, error) {
+func (hc *HealthCheckImpl) TabletConnection(alias *topodata.TabletAlias) (queryservice.QueryService, error) {
 	hc.mu.Lock()
 	thc := hc.healthByAlias[tabletAliasString(topoproto.TabletAliasString(alias))]
 	hc.mu.Unlock()
@@ -706,12 +701,6 @@ func (hc *HealthCheckImpl) TabletConnection(alias *topodata.TabletAlias, target
 		//TODO: test that throws this error
 		return nil, vterrors.Errorf(vtrpc.Code_NOT_FOUND, "tablet: %v is either down or nonexistent", alias)
 	}
-	if !thc.Serving {
-		return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, vterrors.NotServing)
-	}
-	if target != nil && !proto.Equal(thc.Target, target) {
-		return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "%s: target mismatch %v vs %v", vterrors.WrongTablet, thc.Target, target)
-	}
 	return thc.Connection(), nil
 }
 
diff --git a/go/vt/mysqlctl/mycnf.go b/go/vt/mysqlctl/mycnf.go
index e34af6b55a..af2935a5ec 100644
--- a/go/vt/mysqlctl/mycnf.go
+++ b/go/vt/mysqlctl/mycnf.go
@@ -55,10 +55,6 @@ type Mycnf struct {
 	// (used by vt software for Clone)
 	InnodbLogGroupHomeDir string
 
-	// SecureFilePriv is the path for loading secure files
-	// (used by vt software for bulk loading into tablet instances)
-	SecureFilePriv string
-
 	// SocketFile is the path to the local mysql.sock file.
 	// (used by vt software to check server is running)
 	SocketFile string
@@ -207,7 +203,6 @@ func ReadMycnf(mycnf *Mycnf) (*Mycnf, error) {
 		"master-info-file":          &mycnf.MasterInfoFile,
 		"pid-file":                  &mycnf.PidFile,
 		"tmpdir":                    &mycnf.TmpDir,
-		"secure-file-priv":          &mycnf.SecureFilePriv,
 	}
 	for key, member := range mapping {
 		val, err := mycnf.lookupWithDefault(key, *member)
diff --git a/go/vt/mysqlctl/mycnf_flag.go b/go/vt/mysqlctl/mycnf_flag.go
index a80d00f1d8..7197ec9633 100644
--- a/go/vt/mysqlctl/mycnf_flag.go
+++ b/go/vt/mysqlctl/mycnf_flag.go
@@ -44,7 +44,6 @@ var (
 	flagMasterInfoFile        *string
 	flagPidFile               *string
 	flagTmpDir                *string
-	flagSecureFilePriv        *string
 
 	// the file to use to specify them all
 	flagMycnfFile *string
@@ -70,7 +69,6 @@ func RegisterFlags() {
 	flagMasterInfoFile = flag.String("mycnf_master_info_file", "", "mysql master.info file")
 	flagPidFile = flag.String("mycnf_pid_file", "", "mysql pid file")
 	flagTmpDir = flag.String("mycnf_tmp_dir", "", "mysql tmp directory")
-	flagSecureFilePriv = flag.String("mycnf_secure_file_priv", "", "mysql path for loading secure files")
 
 	flagMycnfFile = flag.String("mycnf-file", "", "path to my.cnf, if reading all config params from there")
 }
@@ -109,7 +107,6 @@ func NewMycnfFromFlags(uid uint32) (mycnf *Mycnf, err error) {
 			MasterInfoFile:        *flagMasterInfoFile,
 			PidFile:               *flagPidFile,
 			TmpDir:                *flagTmpDir,
-			SecureFilePriv:        *flagSecureFilePriv,
 
 			// This is probably not going to be used by anybody,
 			// but fill in a default value. (Note it's used by
diff --git a/go/vt/mysqlctl/mycnf_gen.go b/go/vt/mysqlctl/mycnf_gen.go
index a9d2d5d916..a72e9eee9e 100644
--- a/go/vt/mysqlctl/mycnf_gen.go
+++ b/go/vt/mysqlctl/mycnf_gen.go
@@ -84,8 +84,6 @@ func NewMycnf(tabletUID uint32, mysqlPort int32) *Mycnf {
 	cnf.MasterInfoFile = path.Join(tabletDir, "master.info")
 	cnf.PidFile = path.Join(tabletDir, "mysql.pid")
 	cnf.TmpDir = path.Join(tabletDir, "tmp")
-	// by default the secure-file-priv path is `tmp`
-	cnf.SecureFilePriv = cnf.TmpDir
 	return cnf
 }
 
diff --git a/go/vt/mysqlctl/rice-box.go b/go/vt/mysqlctl/rice-box.go
index c2fd030b42..83e0f71dad 100644
--- a/go/vt/mysqlctl/rice-box.go
+++ b/go/vt/mysqlctl/rice-box.go
@@ -11,103 +11,103 @@ func init() {
 	// define files
 	file2 := &embedded.EmbeddedFile{
 		Filename:    "gomysql.pc.tmpl",
-		FileModTime: time.Unix(1610730002, 0),
+		FileModTime: time.Unix(1539121419, 0),
 
 		Content: string("Name: GoMysql\nDescription: Flags for using mysql C client in go\n"),
 	}
 	file3 := &embedded.EmbeddedFile{
 		Filename:    "init_db.sql",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is executed immediately after mysql_install_db,\n# to initialize a fresh data directory.\n\n###############################################################################\n# WARNING: This sql is *NOT* safe for production use,\n#          as it contains default well-known users and passwords.\n#          Care should be taken to change these users and passwords\n#          for production.\n###############################################################################\n\n###############################################################################\n# Equivalent of mysql_secure_installation\n###############################################################################\n\n# Changes during the init db should not make it to the binlog.\n# They could potentially create errant transactions on replicas.\nSET sql_log_bin = 0;\n# Remove anonymous users.\nDELETE FROM mysql.user WHERE User = '';\n\n# Disable remote root access (only allow UNIX socket).\nDELETE FROM mysql.user WHERE User = 'root' AND Host != 'localhost';\n\n# Remove test database.\nDROP DATABASE IF EXISTS test;\n\n###############################################################################\n# Vitess defaults\n###############################################################################\n\n# Vitess-internal database.\nCREATE DATABASE IF NOT EXISTS _vt;\n# Note that definitions of local_metadata and shard_metadata should be the same\n# as in production which is defined in go/vt/mysqlctl/metadata_tables.go.\nCREATE TABLE IF NOT EXISTS _vt.local_metadata (\n  name VARCHAR(255) NOT NULL,\n  value VARCHAR(255) NOT NULL,\n  db_name VARBINARY(255) NOT NULL,\n  PRIMARY KEY (db_name, name)\n  ) ENGINE=InnoDB;\nCREATE TABLE IF NOT EXISTS _vt.shard_metadata (\n  name VARCHAR(255) NOT NULL,\n  value MEDIUMBLOB NOT NULL,\n  db_name VARBINARY(255) NOT NULL,\n  PRIMARY KEY (db_name, name)\n  ) ENGINE=InnoDB;\n\n# Admin user with all privileges.\nCREATE USER 'vt_dba'@'localhost';\nGRANT ALL ON *.* TO 'vt_dba'@'localhost';\nGRANT GRANT OPTION ON *.* TO 'vt_dba'@'localhost';\n\n# User for app traffic, with global read-write access.\nCREATE USER 'vt_app'@'localhost';\nGRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, PROCESS, FILE,\n  REFERENCES, INDEX, ALTER, SHOW DATABASES, CREATE TEMPORARY TABLES,\n  LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW,\n  SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER\n  ON *.* TO 'vt_app'@'localhost';\n\n# User for app debug traffic, with global read access.\nCREATE USER 'vt_appdebug'@'localhost';\nGRANT SELECT, SHOW DATABASES, PROCESS ON *.* TO 'vt_appdebug'@'localhost';\n\n# User for administrative operations that need to be executed as non-SUPER.\n# Same permissions as vt_app here.\nCREATE USER 'vt_allprivs'@'localhost';\nGRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, PROCESS, FILE,\n  REFERENCES, INDEX, ALTER, SHOW DATABASES, CREATE TEMPORARY TABLES,\n  LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW,\n  SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER\n  ON *.* TO 'vt_allprivs'@'localhost';\n\n# User for slave replication connections.\nCREATE USER 'vt_repl'@'%';\nGRANT REPLICATION SLAVE ON *.* TO 'vt_repl'@'%';\n\n# User for Vitess filtered replication (binlog player).\n# Same permissions as vt_app.\nCREATE USER 'vt_filtered'@'localhost';\nGRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, PROCESS, FILE,\n  REFERENCES, INDEX, ALTER, SHOW DATABASES, CREATE TEMPORARY TABLES,\n  LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW,\n  SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER\n  ON *.* TO 'vt_filtered'@'localhost';\n\n# User for general MySQL monitoring.\nCREATE USER 'vt_monitoring'@'localhost';\nGRANT SELECT, PROCESS, SUPER, REPLICATION CLIENT, RELOAD\n  ON *.* TO 'vt_monitoring'@'localhost';\nGRANT SELECT, UPDATE, DELETE, DROP\n  ON performance_schema.* TO 'vt_monitoring'@'localhost';\n\n# User for Orchestrator (https://github.com/openark/orchestrator).\nCREATE USER 'orc_client_user'@'%' IDENTIFIED BY 'orc_client_user_password';\nGRANT SUPER, PROCESS, REPLICATION SLAVE, RELOAD\n  ON *.* TO 'orc_client_user'@'%';\nGRANT SELECT\n  ON _vt.* TO 'orc_client_user'@'%';\n\nFLUSH PRIVILEGES;\n\nRESET SLAVE ALL;\nRESET MASTER;\n"),
 	}
 	file5 := &embedded.EmbeddedFile{
 		Filename:    "mycnf/default-fast.cnf",
-		FileModTime: time.Unix(1616603510, 0),
+		FileModTime: time.Unix(1600988485, 0),
 
 		Content: string("# This sets some unsafe settings specifically for \n# the test-suite which is currently MySQL 5.7 based\n# In future it should be renamed testsuite.cnf\n\ninnodb_buffer_pool_size = 32M\ninnodb_flush_log_at_trx_commit = 0\ninnodb_log_buffer_size = 1M\ninnodb_log_file_size = 5M\n\n# Native AIO tends to run into aio-max-nr limit during test startup.\ninnodb_use_native_aio = 0\n\nkey_buffer_size = 2M\nsync_binlog=0\ninnodb_doublewrite=0\n\n# These two settings are required for the testsuite to pass, \n# but enabling them does not spark joy. They should be removed\n# in the future. See:\n# https://github.com/vitessio/vitess/issues/5396\n\nsql_mode = STRICT_TRANS_TABLES\n\n# set a short heartbeat interval in order to detect failures quickly\nslave_net_timeout = 4\n"),
 	}
 	file6 := &embedded.EmbeddedFile{
 		Filename:    "mycnf/default.cnf",
-		FileModTime: time.Unix(1618483631, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
-		Content: string("# Global configuration that is auto-included for all MySQL/MariaDB versions\n\ndatadir = {{.DataDir}}\ninnodb_data_home_dir = {{.InnodbDataHomeDir}}\ninnodb_log_group_home_dir = {{.InnodbLogGroupHomeDir}}\nlog-error = {{.ErrorLogPath}}\nlog-bin = {{.BinLogPath}}\nrelay-log = {{.RelayLogPath}}\nrelay-log-index =  {{.RelayLogIndexPath}}\npid-file = {{.PidFile}}\nport = {{.MysqlPort}}\n\n{{if .SecureFilePriv}}\nsecure-file-priv = {{.SecureFilePriv}}\n{{end}}\n\n# all db instances should start in read-only mode - once the db is started and\n# fully functional, we'll push it into read-write mode\nread-only\nserver-id = {{.ServerID}}\n\n# all db instances should skip the slave startup - that way we can do any\n# additional configuration (like enabling semi-sync) before we connect to\n# the master.\nskip_slave_start\nsocket = {{.SocketFile}}\ntmpdir = {{.TmpDir}}\n\nslow-query-log-file = {{.SlowLogPath}}\n\n# These are sensible defaults that apply to all MySQL/MariaDB versions\n\nlong_query_time = 2\nslow-query-log\nskip-name-resolve\nconnect_timeout = 30\ninnodb_lock_wait_timeout = 20\nmax_allowed_packet = 64M\nmax_connections = 500\n\n\n"),
+		Content: string("# Global configuration that is auto-included for all MySQL/MariaDB versions\n\ndatadir = {{.DataDir}}\ninnodb_data_home_dir = {{.InnodbDataHomeDir}}\ninnodb_log_group_home_dir = {{.InnodbLogGroupHomeDir}}\nlog-error = {{.ErrorLogPath}}\nlog-bin = {{.BinLogPath}}\nrelay-log = {{.RelayLogPath}}\nrelay-log-index =  {{.RelayLogIndexPath}}\npid-file = {{.PidFile}}\nport = {{.MysqlPort}}\n\n# all db instances should start in read-only mode - once the db is started and\n# fully functional, we'll push it into read-write mode\nread-only\nserver-id = {{.ServerID}}\n\n# all db instances should skip the slave startup - that way we can do any\n# additional configuration (like enabling semi-sync) before we connect to\n# the master.\nskip_slave_start\nsocket = {{.SocketFile}}\ntmpdir = {{.TmpDir}}\n\nslow-query-log-file = {{.SlowLogPath}}\n\n# These are sensible defaults that apply to all MySQL/MariaDB versions\n\nlong_query_time = 2\nslow-query-log\nskip-name-resolve\nconnect_timeout = 30\ninnodb_lock_wait_timeout = 20\nmax_allowed_packet = 64M\nmax_connections = 500\n\n\n"),
 	}
 	file7 := &embedded.EmbeddedFile{
 		Filename:    "mycnf/master_mariadb100.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is auto-included when MariaDB 10.0 is detected.\n\n# Semi-sync replication is required for automated unplanned failover\n# (when the master goes away). Here we just load the plugin so it's\n# available if desired, but it's disabled at startup.\n#\n# If the -enable_semi_sync flag is used, VTTablet will enable semi-sync\n# at the proper time when replication is set up, or when masters are\n# promoted or demoted.\nplugin-load = rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so\n\nslave_net_timeout = 60\n\n# MariaDB 10.0 is unstrict by default\nsql_mode = STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION\n\n# enable strict mode so it's safe to compare sequence numbers across different server IDs.\ngtid_strict_mode = 1\ninnodb_stats_persistent = 0\n\n# When semi-sync is enabled, don't allow fallback to async\n# if you get no ack, or have no slaves. This is necessary to\n# prevent alternate futures when doing a failover in response to\n# a master that becomes unresponsive.\nrpl_semi_sync_master_timeout = 1000000000000000000\nrpl_semi_sync_master_wait_no_slave = 1\n\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\nexpire_logs_days = 3\n\nsync_binlog = 1\nbinlog_format = ROW\nlog_slave_updates\nexpire_logs_days = 3\n\n# In MariaDB the default charset is latin1\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\n"),
 	}
 	file8 := &embedded.EmbeddedFile{
 		Filename:    "mycnf/master_mariadb101.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is auto-included when MariaDB 10.1 is detected.\n\n# Semi-sync replication is required for automated unplanned failover\n# (when the master goes away). Here we just load the plugin so it's\n# available if desired, but it's disabled at startup.\n#\n# If the -enable_semi_sync flag is used, VTTablet will enable semi-sync\n# at the proper time when replication is set up, or when masters are\n# promoted or demoted.\nplugin-load = rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so\n\nslave_net_timeout = 60\n\n# MariaDB 10.1 default is only no-engine-substitution and no-auto-create-user\nsql_mode = STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION,NO_AUTO_CREATE_USER\n\n# enable strict mode so it's safe to compare sequence numbers across different server IDs.\ngtid_strict_mode = 1\ninnodb_stats_persistent = 0\n\n# When semi-sync is enabled, don't allow fallback to async\n# if you get no ack, or have no slaves. This is necessary to\n# prevent alternate futures when doing a failover in response to\n# a master that becomes unresponsive.\nrpl_semi_sync_master_timeout = 1000000000000000000\nrpl_semi_sync_master_wait_no_slave = 1\n\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\nexpire_logs_days = 3\n\nsync_binlog = 1\nbinlog_format = ROW\nlog_slave_updates\nexpire_logs_days = 3\n\n# In MariaDB the default charset is latin1\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n"),
 	}
 	file9 := &embedded.EmbeddedFile{
 		Filename:    "mycnf/master_mariadb102.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is auto-included when MariaDB 10.2 is detected.\n\n# Semi-sync replication is required for automated unplanned failover\n# (when the master goes away). Here we just load the plugin so it's\n# available if desired, but it's disabled at startup.\n#\n# If the -enable_semi_sync flag is used, VTTablet will enable semi-sync\n# at the proper time when replication is set up, or when masters are\n# promoted or demoted.\nplugin-load = rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so\n\n# enable strict mode so it's safe to compare sequence numbers across different server IDs.\ngtid_strict_mode = 1\ninnodb_stats_persistent = 0\n\n# When semi-sync is enabled, don't allow fallback to async\n# if you get no ack, or have no slaves. This is necessary to\n# prevent alternate futures when doing a failover in response to\n# a master that becomes unresponsive.\nrpl_semi_sync_master_timeout = 1000000000000000000\nrpl_semi_sync_master_wait_no_slave = 1\n\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\nexpire_logs_days = 3\n\nsync_binlog = 1\nbinlog_format = ROW\nlog_slave_updates\nexpire_logs_days = 3\n\n# In MariaDB the default charset is latin1\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n"),
 	}
 	filea := &embedded.EmbeddedFile{
 		Filename:    "mycnf/master_mariadb103.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is auto-included when MariaDB 10.3 is detected.\n\n# enable strict mode so it's safe to compare sequence numbers across different server IDs.\ngtid_strict_mode = 1\ninnodb_stats_persistent = 0\n\n# When semi-sync is enabled, don't allow fallback to async\n# if you get no ack, or have no slaves. This is necessary to\n# prevent alternate futures when doing a failover in response to\n# a master that becomes unresponsive.\nrpl_semi_sync_master_timeout = 1000000000000000000\nrpl_semi_sync_master_wait_no_slave = 1\n\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\nexpire_logs_days = 3\n\nsync_binlog = 1\nbinlog_format = ROW\nlog_slave_updates\nexpire_logs_days = 3\n\n# In MariaDB the default charset is latin1\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\n\n"),
 	}
 	fileb := &embedded.EmbeddedFile{
 		Filename:    "mycnf/master_mariadb104.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is auto-included when MariaDB 10.4 is detected.\n\n# enable strict mode so it's safe to compare sequence numbers across different server IDs.\ngtid_strict_mode = 1\ninnodb_stats_persistent = 0\n\n# When semi-sync is enabled, don't allow fallback to async\n# if you get no ack, or have no slaves. This is necessary to\n# prevent alternate futures when doing a failover in response to\n# a master that becomes unresponsive.\nrpl_semi_sync_master_timeout = 1000000000000000000\nrpl_semi_sync_master_wait_no_slave = 1\n\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\nexpire_logs_days = 3\n\nsync_binlog = 1\nbinlog_format = ROW\nlog_slave_updates\nexpire_logs_days = 3\n\n# In MariaDB the default charset is latin1\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\n\n"),
 	}
 	filec := &embedded.EmbeddedFile{
 		Filename:    "mycnf/master_mysql56.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is auto-included when MySQL 5.6 is detected.\n\n# MySQL 5.6 does not enable the binary log by default, and \n# the default for sync_binlog is unsafe. The format is TABLE, and\n# info repositories also default to file.\n\nsync_binlog = 1\ngtid_mode = ON\nbinlog_format = ROW\nlog_slave_updates\nenforce_gtid_consistency\nexpire_logs_days = 3\nmaster_info_repository = TABLE\nrelay_log_info_repository = TABLE\nrelay_log_purge = 1\nrelay_log_recovery = 1\nslave_net_timeout = 60\n\n# In MySQL 5.6 the default charset is latin1\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\n# MySQL 5.6 is unstrict by default\nsql_mode = STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION\n\n# Semi-sync replication is required for automated unplanned failover\n# (when the master goes away). Here we just load the plugin so it's\n# available if desired, but it's disabled at startup.\n#\n# If the -enable_semi_sync flag is used, VTTablet will enable semi-sync\n# at the proper time when replication is set up, or when masters are\n# promoted or demoted.\nplugin-load = rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so\n\n# When semi-sync is enabled, don't allow fallback to async\n# if you get no ack, or have no slaves. This is necessary to\n# prevent alternate futures when doing a failover in response to\n# a master that becomes unresponsive.\nrpl_semi_sync_master_timeout = 1000000000000000000\nrpl_semi_sync_master_wait_no_slave = 1\n\n"),
 	}
 	filed := &embedded.EmbeddedFile{
 		Filename:    "mycnf/master_mysql57.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is auto-included when MySQL 5.7 is detected.\n\n# MySQL 5.7 does not enable the binary log by default, and \n# info repositories default to file\n\ngtid_mode = ON\nlog_slave_updates\nenforce_gtid_consistency\nexpire_logs_days = 3\nmaster_info_repository = TABLE\nrelay_log_info_repository = TABLE\nrelay_log_purge = 1\nrelay_log_recovery = 1\n\n# In MySQL 5.7 the default charset is latin1\n\ncharacter_set_server = utf8\ncollation_server = utf8_general_ci\n\n# Semi-sync replication is required for automated unplanned failover\n# (when the master goes away). Here we just load the plugin so it's\n# available if desired, but it's disabled at startup.\n#\n# If the -enable_semi_sync flag is used, VTTablet will enable semi-sync\n# at the proper time when replication is set up, or when masters are\n# promoted or demoted.\nplugin-load = rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so\n\n# When semi-sync is enabled, don't allow fallback to async\n# if you get no ack, or have no slaves. This is necessary to\n# prevent alternate futures when doing a failover in response to\n# a master that becomes unresponsive.\nrpl_semi_sync_master_timeout = 1000000000000000000\nrpl_semi_sync_master_wait_no_slave = 1\n\n"),
 	}
 	filee := &embedded.EmbeddedFile{
 		Filename:    "mycnf/master_mysql80.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is auto-included when MySQL 8.0 is detected.\n\n# MySQL 8.0 enables binlog by default with sync_binlog and TABLE info repositories\n# It does not enable GTIDs or enforced GTID consistency\n\ngtid_mode = ON\nenforce_gtid_consistency\nrelay_log_recovery = 1\nbinlog_expire_logs_seconds = 259200\n\n# disable mysqlx\nmysqlx = 0\n\n# 8.0 changes the default auth-plugin to caching_sha2_password\ndefault_authentication_plugin = mysql_native_password\n\n# Semi-sync replication is required for automated unplanned failover\n# (when the master goes away). Here we just load the plugin so it's\n# available if desired, but it's disabled at startup.\n#\n# If the -enable_semi_sync flag is used, VTTablet will enable semi-sync\n# at the proper time when replication is set up, or when masters are\n# promoted or demoted.\nplugin-load = rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so\n\n# MySQL 8.0 will not load plugins during --initialize\n# which makes these options unknown. Prefixing with --loose\n# tells the server it's fine if they are not understood.\nloose_rpl_semi_sync_master_timeout = 1000000000000000000\nloose_rpl_semi_sync_master_wait_no_slave = 1\n\n"),
 	}
 	filef := &embedded.EmbeddedFile{
 		Filename:    "mycnf/sbr.cnf",
-		FileModTime: time.Unix(1610730036, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
 		Content: string("# This file is used to allow legacy tests to pass\n# In theory it should not be required\nbinlog_format=statement\n"),
 	}
 	fileh := &embedded.EmbeddedFile{
 		Filename:    "orchestrator/default.json",
-		FileModTime: time.Unix(1616603510, 0),
+		FileModTime: time.Unix(1600387438, 0),
 
 		Content: string("{\n  \"Debug\": true,\n  \"MySQLTopologyUser\": \"orc_client_user\",\n  \"MySQLTopologyPassword\": \"orc_client_user_password\",\n  \"MySQLReplicaUser\": \"vt_repl\",\n  \"MySQLReplicaPassword\": \"\",\n  \"RecoveryPeriodBlockSeconds\": 5\n}\n"),
 	}
 	filej := &embedded.EmbeddedFile{
 		Filename:    "tablet/default.yaml",
-		FileModTime: time.Unix(1616603510, 0),
+		FileModTime: time.Unix(1599694847, 0),
 
-		Content: string("tabletID: zone-1234\n\ninit:\n  dbName:            # init_db_name_override\n  keyspace:          # init_keyspace\n  shard:             # init_shard\n  tabletType:        # init_tablet_type\n  timeoutSeconds: 60 # init_timeout\n\ndb:\n  socket:     # db_socket\n  host:       # db_host\n  port: 0     # db_port\n  charSet:    # db_charset\n  flags: 0    # db_flags\n  flavor:     # db_flavor\n  sslCa:      # db_ssl_ca\n  sslCaPath:  # db_ssl_ca_path\n  sslCert:    # db_ssl_cert\n  sslKey:     # db_ssl_key\n  serverName: # db_server_name\n  connectTimeoutMilliseconds: 0 # db_connect_timeout_ms\n  app:\n    user: vt_app      # db_app_user\n    password:         # db_app_password\n    useSsl: true      # db_app_use_ssl\n    preferTcp: false\n  dba:\n    user: vt_dba      # db_dba_user\n    password:         # db_dba_password\n    useSsl: true      # db_dba_use_ssl\n    preferTcp: false\n  filtered:\n    user: vt_filtered # db_filtered_user\n    password:         # db_filtered_password\n    useSsl: true      # db_filtered_use_ssl\n    preferTcp: false\n  repl:\n    user: vt_repl     # db_repl_user\n    password:         # db_repl_password\n    useSsl: true      # db_repl_use_ssl\n    preferTcp: false\n  appdebug:\n    user: vt_appdebug # db_appdebug_user\n    password:         # db_appdebug_password\n    useSsl: true      # db_appdebug_use_ssl\n    preferTcp: false\n  allprivs:\n    user: vt_allprivs # db_allprivs_user\n    password:         # db_allprivs_password\n    useSsl: true      # db_allprivs_use_ssl\n    preferTcp: false\n\noltpReadPool:\n  size: 16                 # queryserver-config-pool-size\n  timeoutSeconds: 0        # queryserver-config-query-pool-timeout\n  idleTimeoutSeconds: 1800 # queryserver-config-idle-timeout\n  prefillParallelism: 0    # queryserver-config-pool-prefill-parallelism\n  maxWaiters: 50000        # queryserver-config-query-pool-waiter-cap\n\nolapReadPool:\n  size: 200                # queryserver-config-stream-pool-size\n  timeoutSeconds: 0        # queryserver-config-query-pool-timeout\n  idleTimeoutSeconds: 1800 # queryserver-config-idle-timeout\n  prefillParallelism: 0    # queryserver-config-stream-pool-prefill-parallelism\n  maxWaiters: 0\n\ntxPool:\n  size: 20                 # queryserver-config-transaction-cap\n  timeoutSeconds: 1        # queryserver-config-txpool-timeout\n  idleTimeoutSeconds: 1800 # queryserver-config-idle-timeout\n  prefillParallelism: 0    # queryserver-config-transaction-prefill-parallelism\n  maxWaiters: 50000        # queryserver-config-txpool-waiter-cap\n\noltp:\n  queryTimeoutSeconds: 30 # queryserver-config-query-timeout\n  txTimeoutSeconds: 30    # queryserver-config-transaction-timeout\n  maxRows: 10000          # queryserver-config-max-result-size\n  warnRows: 0             # queryserver-config-warn-result-size\n\nhealthcheck:\n  intervalSeconds: 20             # health_check_interval\n  degradedThresholdSeconds: 30    # degraded_threshold\n  unhealthyThresholdSeconds: 7200 # unhealthy_threshold\n\ngracePeriods:\n  shutdownSeconds:   0 # shutdown_grace_period\n  transitionSeconds: 0 # serving_state_grace_period\n\nreplicationTracker:\n  mode: disable                    # enable_replication_reporter\n  heartbeatIntervalMilliseconds: 0 # heartbeat_enable, heartbeat_interval\n\nhotRowProtection:\n  mode: disable|dryRun|enable # enable_hot_row_protection, enable_hot_row_protection_dry_run\n  # Recommended value: same as txPool.size.\n  maxQueueSize: 20            # hot_row_protection_max_queue_size\n  maxGlobalQueueSize: 1000    # hot_row_protection_max_global_queue_size\n  maxConcurrency: 5           # hot_row_protection_concurrent_transactions\n\nconsolidator: enable|disable|notOnMaster # enable-consolidator, enable-consolidator-replicas\npassthroughDML: false                    # queryserver-config-passthrough-dmls\nstreamBufferSize: 32768                  # queryserver-config-stream-buffer-size\nqueryCacheSize: 5000                     # queryserver-config-query-cache-size\nschemaReloadIntervalSeconds: 1800        # queryserver-config-schema-reload-time\nwatchReplication: false                  # watch_replication_stream\nterseErrors: false                       # queryserver-config-terse-errors\nmessagePostponeParallelism: 4            # queryserver-config-message-postpone-cap\ncacheResultFields: true                  # enable-query-plan-field-caching\n\n\n# The following flags are currently not supported.\n# enforce_strict_trans_tables\n# queryserver-config-strict-table-acl\n# queryserver-config-enable-table-acl-dry-run\n# queryserver-config-acl-exempt-acl\n# enable-tx-throttler\n# tx-throttler-config\n# tx-throttler-healthcheck-cells\n# enable_transaction_limit\n# enable_transaction_limit_dry_run\n# transaction_limit_per_user\n# transaction_limit_by_username\n# transaction_limit_by_principal\n# transaction_limit_by_component\n# transaction_limit_by_subcomponent\n"),
+		Content: string("tabletID: zone-1234\n\ninit:\n  dbName:            # init_db_name_override\n  keyspace:          # init_keyspace\n  shard:             # init_shard\n  tabletType:        # init_tablet_type\n  timeoutSeconds: 60 # init_timeout\n\ndb:\n  socket:     # db_socket\n  host:       # db_host\n  port: 0     # db_port\n  charSet:    # db_charset\n  flags: 0    # db_flags\n  flavor:     # db_flavor\n  sslCa:      # db_ssl_ca\n  sslCaPath:  # db_ssl_ca_path\n  sslCert:    # db_ssl_cert\n  sslKey:     # db_ssl_key\n  serverName: # db_server_name\n  connectTimeoutMilliseconds: 0 # db_connect_timeout_ms\n  app:\n    user: vt_app      # db_app_user\n    password:         # db_app_password\n    useSsl: true      # db_app_use_ssl\n    preferTcp: false\n  dba:\n    user: vt_dba      # db_dba_user\n    password:         # db_dba_password\n    useSsl: true      # db_dba_use_ssl\n    preferTcp: false\n  filtered:\n    user: vt_filtered # db_filtered_user\n    password:         # db_filtered_password\n    useSsl: true      # db_filtered_use_ssl\n    preferTcp: false\n  repl:\n    user: vt_repl     # db_repl_user\n    password:         # db_repl_password\n    useSsl: true      # db_repl_use_ssl\n    preferTcp: false\n  appdebug:\n    user: vt_appdebug # db_appdebug_user\n    password:         # db_appdebug_password\n    useSsl: true      # db_appdebug_use_ssl\n    preferTcp: false\n  allprivs:\n    user: vt_allprivs # db_allprivs_user\n    password:         # db_allprivs_password\n    useSsl: true      # db_allprivs_use_ssl\n    preferTcp: false\n\noltpReadPool:\n  size: 16                 # queryserver-config-pool-size\n  timeoutSeconds: 0        # queryserver-config-query-pool-timeout\n  idleTimeoutSeconds: 1800 # queryserver-config-idle-timeout\n  prefillParallelism: 0    # queryserver-config-pool-prefill-parallelism\n  maxWaiters: 50000        # queryserver-config-query-pool-waiter-cap\n\nolapReadPool:\n  size: 200                # queryserver-config-stream-pool-size\n  timeoutSeconds: 0        # queryserver-config-query-pool-timeout\n  idleTimeoutSeconds: 1800 # queryserver-config-idle-timeout\n  prefillParallelism: 0    # queryserver-config-stream-pool-prefill-parallelism\n  maxWaiters: 0\n\ntxPool:\n  size: 20                 # queryserver-config-transaction-cap\n  timeoutSeconds: 1        # queryserver-config-txpool-timeout\n  idleTimeoutSeconds: 1800 # queryserver-config-idle-timeout\n  prefillParallelism: 0    # queryserver-config-transaction-prefill-parallelism\n  maxWaiters: 50000        # queryserver-config-txpool-waiter-cap\n\noltp:\n  queryTimeoutSeconds: 30 # queryserver-config-query-timeout\n  txTimeoutSeconds: 30    # queryserver-config-transaction-timeout\n  maxRows: 10000          # queryserver-config-max-result-size\n  warnRows: 0             # queryserver-config-warn-result-size\n\nhealthcheck:\n  intervalSeconds: 20             # health_check_interval\n  degradedThresholdSeconds: 30    # degraded_threshold\n  unhealthyThresholdSeconds: 7200 # unhealthy_threshold\n\ngracePeriods:\n  transactionShutdownSeconds: 0 # transaction_shutdown_grace_period\n  transitionSeconds: 0          # serving_state_grace_period\n\nreplicationTracker:\n  mode: disable                    # enable_replication_reporter\n  heartbeatIntervalMilliseconds: 0 # heartbeat_enable, heartbeat_interval\n\nhotRowProtection:\n  mode: disable|dryRun|enable # enable_hot_row_protection, enable_hot_row_protection_dry_run\n  # Recommended value: same as txPool.size.\n  maxQueueSize: 20            # hot_row_protection_max_queue_size\n  maxGlobalQueueSize: 1000    # hot_row_protection_max_global_queue_size\n  maxConcurrency: 5           # hot_row_protection_concurrent_transactions\n\nconsolidator: enable|disable|notOnMaster # enable-consolidator, enable-consolidator-replicas\npassthroughDML: false                    # queryserver-config-passthrough-dmls\nstreamBufferSize: 32768                  # queryserver-config-stream-buffer-size\nqueryCacheSize: 5000                     # queryserver-config-query-cache-size\nschemaReloadIntervalSeconds: 1800        # queryserver-config-schema-reload-time\nwatchReplication: false                  # watch_replication_stream\nterseErrors: false                       # queryserver-config-terse-errors\nmessagePostponeParallelism: 4            # queryserver-config-message-postpone-cap\ncacheResultFields: true                  # enable-query-plan-field-caching\n\n\n# The following flags are currently not supported.\n# enforce_strict_trans_tables\n# queryserver-config-strict-table-acl\n# queryserver-config-enable-table-acl-dry-run\n# queryserver-config-acl-exempt-acl\n# enable-tx-throttler\n# tx-throttler-config\n# tx-throttler-healthcheck-cells\n# enable_transaction_limit\n# enable_transaction_limit_dry_run\n# transaction_limit_per_user\n# transaction_limit_by_username\n# transaction_limit_by_principal\n# transaction_limit_by_component\n# transaction_limit_by_subcomponent\n"),
 	}
 	filek := &embedded.EmbeddedFile{
 		Filename:    "zk-client-dev.json",
-		FileModTime: time.Unix(1610730002, 0),
+		FileModTime: time.Unix(1539121419, 0),
 
 		Content: string("{\n  \"local\": \"localhost:3863\",\n  \"global\": \"localhost:3963\"\n}\n"),
 	}
 	filem := &embedded.EmbeddedFile{
 		Filename:    "zkcfg/zoo.cfg",
-		FileModTime: time.Unix(1610730002, 0),
+		FileModTime: time.Unix(1539121419, 0),
 
 		Content: string("tickTime=2000\ndataDir={{.DataDir}}\nclientPort={{.ClientPort}}\ninitLimit=5\nsyncLimit=2\nmaxClientCnxns=0\n{{range .Servers}}\nserver.{{.ServerId}}={{.Hostname}}:{{.LeaderPort}}:{{.ElectionPort}}\n{{end}}\n"),
 	}
@@ -115,7 +115,7 @@ func init() {
 	// define dirs
 	dir1 := &embedded.EmbeddedDir{
 		Filename:   "",
-		DirModTime: time.Unix(1616603510, 0),
+		DirModTime: time.Unix(1599765277, 0),
 		ChildFiles: []*embedded.EmbeddedFile{
 			file2, // "gomysql.pc.tmpl"
 			file3, // "init_db.sql"
@@ -125,7 +125,7 @@ func init() {
 	}
 	dir4 := &embedded.EmbeddedDir{
 		Filename:   "mycnf",
-		DirModTime: time.Unix(1618483631, 0),
+		DirModTime: time.Unix(1600988485, 0),
 		ChildFiles: []*embedded.EmbeddedFile{
 			file5, // "mycnf/default-fast.cnf"
 			file6, // "mycnf/default.cnf"
@@ -143,7 +143,7 @@ func init() {
 	}
 	dirg := &embedded.EmbeddedDir{
 		Filename:   "orchestrator",
-		DirModTime: time.Unix(1616603510, 0),
+		DirModTime: time.Unix(1600387438, 0),
 		ChildFiles: []*embedded.EmbeddedFile{
 			fileh, // "orchestrator/default.json"
 
@@ -151,7 +151,7 @@ func init() {
 	}
 	diri := &embedded.EmbeddedDir{
 		Filename:   "tablet",
-		DirModTime: time.Unix(1616603510, 0),
+		DirModTime: time.Unix(1599694847, 0),
 		ChildFiles: []*embedded.EmbeddedFile{
 			filej, // "tablet/default.yaml"
 
@@ -159,7 +159,7 @@ func init() {
 	}
 	dirl := &embedded.EmbeddedDir{
 		Filename:   "zkcfg",
-		DirModTime: time.Unix(1610730002, 0),
+		DirModTime: time.Unix(1539121419, 0),
 		ChildFiles: []*embedded.EmbeddedFile{
 			filem, // "zkcfg/zoo.cfg"
 
@@ -182,7 +182,7 @@ func init() {
 	// register embeddedBox
 	embedded.RegisterEmbeddedBox(`../../../config`, &embedded.EmbeddedBox{
 		Name: `../../../config`,
-		Time: time.Unix(1616603510, 0),
+		Time: time.Unix(1599765277, 0),
 		Dirs: map[string]*embedded.EmbeddedDir{
 			"":             dir1,
 			"mycnf":        dir4,
diff --git a/go/vt/servenv/pprof.go b/go/vt/servenv/pprof.go
index 22e0fab089..e81f605d6f 100644
--- a/go/vt/servenv/pprof.go
+++ b/go/vt/servenv/pprof.go
@@ -19,7 +19,6 @@ package servenv
 import (
 	"flag"
 	"fmt"
-	"io"
 	"io/ioutil"
 	"os"
 	"os/signal"
@@ -165,7 +164,11 @@ func stopCallback(stop func()) func() {
 	}
 }
 
-func (prof *profile) mkprofile() io.WriteCloser {
+// init returns a start function that begins the configured profiling process and
+// returns a cleanup function that must be executed before process termination to
+// flush the profile to disk.
+// Based on the profiling code in github.com/pkg/profile
+func (prof *profile) init() (start func(), stop func()) {
 	var (
 		path string
 		err  error
@@ -193,32 +196,20 @@ func (prof *profile) mkprofile() io.WriteCloser {
 	}
 	logf("pprof: %s profiling enabled, %s", string(prof.mode), fn)
 
-	return f
-}
-
-// init returns a start function that begins the configured profiling process and
-// returns a cleanup function that must be executed before process termination to
-// flush the profile to disk.
-// Based on the profiling code in github.com/pkg/profile
-func (prof *profile) init() (start func(), stop func()) {
-	var pf io.WriteCloser
-
 	switch prof.mode {
 	case profileCPU:
 		start = startCallback(func() {
-			pf = prof.mkprofile()
-			pprof.StartCPUProfile(pf)
+			pprof.StartCPUProfile(f)
 		})
 		stop = stopCallback(func() {
 			pprof.StopCPUProfile()
-			pf.Close()
+			f.Close()
 		})
 		return start, stop
 
 	case profileMemHeap, profileMemAllocs:
 		old := runtime.MemProfileRate
 		start = startCallback(func() {
-			pf = prof.mkprofile()
 			runtime.MemProfileRate = prof.rate
 		})
 		stop = stopCallback(func() {
@@ -226,72 +217,65 @@ func (prof *profile) init() (start func(), stop func()) {
 			if prof.mode == profileMemAllocs {
 				tt = "allocs"
 			}
-			pprof.Lookup(tt).WriteTo(pf, 0)
-			pf.Close()
+			pprof.Lookup(tt).WriteTo(f, 0)
+			f.Close()
 			runtime.MemProfileRate = old
 		})
 		return start, stop
 
 	case profileMutex:
 		start = startCallback(func() {
-			pf = prof.mkprofile()
 			runtime.SetMutexProfileFraction(prof.rate)
 		})
 		stop = stopCallback(func() {
 			if mp := pprof.Lookup("mutex"); mp != nil {
-				mp.WriteTo(pf, 0)
+				mp.WriteTo(f, 0)
 			}
-			pf.Close()
+			f.Close()
 			runtime.SetMutexProfileFraction(0)
 		})
 		return start, stop
 
 	case profileBlock:
 		start = startCallback(func() {
-			pf = prof.mkprofile()
 			runtime.SetBlockProfileRate(prof.rate)
 		})
 		stop = stopCallback(func() {
-			pprof.Lookup("block").WriteTo(pf, 0)
-			pf.Close()
+			pprof.Lookup("block").WriteTo(f, 0)
+			f.Close()
 			runtime.SetBlockProfileRate(0)
 		})
 		return start, stop
 
 	case profileThreads:
-		start = startCallback(func() {
-			pf = prof.mkprofile()
-		})
+		start = startCallback(func() {})
 		stop = stopCallback(func() {
 			if mp := pprof.Lookup("threadcreate"); mp != nil {
-				mp.WriteTo(pf, 0)
+				mp.WriteTo(f, 0)
 			}
-			pf.Close()
+			f.Close()
 		})
 		return start, stop
 
 	case profileTrace:
 		start = startCallback(func() {
-			pf = prof.mkprofile()
-			if err := trace.Start(pf); err != nil {
+			if err := trace.Start(f); err != nil {
 				log.Fatalf("pprof: could not start trace: %v", err)
 			}
 		})
 		stop = stopCallback(func() {
 			trace.Stop()
-			pf.Close()
+			f.Close()
 		})
 		return start, stop
 
 	case profileGoroutine:
-		start = startCallback(func() {
-			pf = prof.mkprofile()
-		})
+		start = startCallback(func() {})
 		stop = stopCallback(func() {
 			if mp := pprof.Lookup("goroutine"); mp != nil {
-				mp.WriteTo(pf, 0)
+				mp.WriteTo(f, 0)
 			}
-			pf.Close()
+			f.Close()
 		})
 		return start, stop
 
diff --git a/go/vt/sqlparser/parsed_query.go b/go/vt/sqlparser/parsed_query.go
index 5ce0581e5a..c68b5ee238 100644
--- a/go/vt/sqlparser/parsed_query.go
+++ b/go/vt/sqlparser/parsed_query.go
@@ -21,11 +21,6 @@ import (
 	"fmt"
 	"strings"
 
-	vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
-	"vitess.io/vitess/go/vt/vterrors"
-
-	"vitess.io/vitess/go/bytes2"
-
 	"vitess.io/vitess/go/sqltypes"
 
 	querypb "vitess.io/vitess/go/vt/proto/query"
@@ -85,38 +80,6 @@ func (pq *ParsedQuery) Append(buf *strings.Builder, bindVariables map[string]*qu
 	return nil
 }
 
-// AppendFromRow behaves like Append but takes a querypb.Row directly, assuming that
-// the fields in the row are in the same order as the placeholders in this query.
-func (pq *ParsedQuery) AppendFromRow(buf *bytes2.Buffer, fields []*querypb.Field, row *querypb.Row) error {
-	if len(fields) < len(pq.bindLocations) {
-		return vterrors.Errorf(vtrpcpb.Code_INTERNAL, "wrong number of fields: got %d fields for %d bind locations ", len(fields), len(pq.bindLocations))
-	}
-	var offsetQuery int
-	var offsetRow int64
-	for i, loc := range pq.bindLocations {
-		buf.WriteString(pq.Query[offsetQuery:loc.offset])
-
-		typ := fields[i].Type
-		if typ == querypb.Type_TUPLE {
-			return vterrors.Errorf(vtrpcpb.Code_INTERNAL, "unexpected Type_TUPLE for value %d", i)
-		}
-
-		length := row.Lengths[i]
-		if length < 0 {
-			// -1 means a null variable; serialize it directly
-			buf.WriteString("null")
-		} else {
-			vv := sqltypes.MakeTrusted(typ, row.Values[offsetRow:offsetRow+length])
-			vv.EncodeSQLBytes2(buf)
-			offsetRow += length
-		}
-
-		offsetQuery = loc.offset + loc.length
-	}
-	buf.WriteString(pq.Query[offsetQuery:])
-	return nil
-}
-
 // MarshalJSON is a custom JSON marshaler for ParsedQuery.
 // Note that any queries longer that 512 bytes will be truncated.
 func (pq *ParsedQuery) MarshalJSON() ([]byte, error) {
@@ -128,7 +91,7 @@ func EncodeValue(buf *strings.Builder, value *querypb.BindVariable) {
 	if value.Type != querypb.Type_TUPLE {
 		// Since we already check for TUPLE, we don't expect an error.
 		v, _ := sqltypes.BindVariableToValue(value)
-		v.EncodeSQLStringBuilder(buf)
+		v.EncodeSQL(buf)
 		return
 	}
 
@@ -138,7 +101,7 @@ func EncodeValue(buf *strings.Builder, value *querypb.BindVariable) {
 		if i != 0 {
 			buf.WriteString(", ")
 		}
-		sqltypes.ProtoToValue(bv).EncodeSQLStringBuilder(buf)
+		sqltypes.ProtoToValue(bv).EncodeSQL(buf)
 	}
 	buf.WriteByte(')')
 }
diff --git a/go/vt/sqlparser/parser.go b/go/vt/sqlparser/parser.go
index b1e4c8086d..3cea4eeb59 100644
--- a/go/vt/sqlparser/parser.go
+++ b/go/vt/sqlparser/parser.go
@@ -158,7 +158,7 @@ func parseNext(tokenizer *Tokenizer, strict bool) (Statement, error) {
 }
 
 // ErrEmpty is a sentinel error returned when parsing empty statements.
-var ErrEmpty = vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.EmptyQuery, "query was empty")
+var ErrEmpty = vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.EmptyQuery, "Query was empty")
 
 // SplitStatement returns the first sql statement up to either a ; or EOF
 // and the remainder from the given buffer
diff --git a/go/vt/sqlparser/token.go b/go/vt/sqlparser/token.go
index c87d07b1b3..82ab10e325 100644
--- a/go/vt/sqlparser/token.go
+++ b/go/vt/sqlparser/token.go
@@ -136,8 +136,6 @@ func (tkn *Tokenizer) Scan() (int, string) {
 		if tkn.cur() == '`' {
 			tkn.skip(1)
 			tID, tBytes = tkn.scanLiteralIdentifier()
-		} else if tkn.cur() == eofChar {
-			return LEX_ERROR, ""
 		} else {
 			tID, tBytes = tkn.scanIdentifier(true)
 		}
diff --git a/go/vt/srvtopo/resolver.go b/go/vt/srvtopo/resolver.go
index e668e0e248..7134b0b985 100644
--- a/go/vt/srvtopo/resolver.go
+++ b/go/vt/srvtopo/resolver.go
@@ -40,7 +40,7 @@ type Gateway interface {
 	queryservice.QueryService
 
 	// QueryServiceByAlias returns a QueryService
-	QueryServiceByAlias(alias *topodatapb.TabletAlias, target *querypb.Target) (queryservice.QueryService, error)
+	QueryServiceByAlias(alias *topodatapb.TabletAlias) (queryservice.QueryService, error)
 }
 
 // A Resolver can resolve keyspace ids and key ranges into ResolvedShard*
diff --git a/go/vt/vterrors/constants.go b/go/vt/vterrors/constants.go
deleted file mode 100644
index d66a97464d..0000000000
--- a/go/vt/vterrors/constants.go
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-Copyright 2021 The Vitess Authors.
-
-Licensed 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 vterrors
-
-import "regexp"
-
-// Operation not allowed error
-const (
-	NotServing   = "operation not allowed in state NOT_SERVING"
-	ShuttingDown = "operation not allowed in state SHUTTING_DOWN"
-)
-
-// RxOp regex for operation not allowed error
-var RxOp = regexp.MustCompile("operation not allowed in state (NOT_SERVING|SHUTTING_DOWN)")
-
-// WrongTablet for invalid tablet type error
-const WrongTablet = "wrong tablet type"
-
-// RxWrongTablet regex for invalid tablet type error
-var RxWrongTablet = regexp.MustCompile("(wrong|invalid) tablet type")
diff --git a/go/vt/vtgate/discoverygateway.go b/go/vt/vtgate/discoverygateway.go
index b5d24c2882..e324e998ef 100644
--- a/go/vt/vtgate/discoverygateway.go
+++ b/go/vt/vtgate/discoverygateway.go
@@ -405,6 +405,6 @@ func (dg *DiscoveryGateway) getStatsAggregator(target *querypb.Target) *TabletSt
 }
 
 // QueryServiceByAlias satisfies the Gateway interface
-func (dg *DiscoveryGateway) QueryServiceByAlias(_ *topodatapb.TabletAlias, _ *querypb.Target) (queryservice.QueryService, error) {
+func (dg *DiscoveryGateway) QueryServiceByAlias(_ *topodatapb.TabletAlias) (queryservice.QueryService, error) {
 	return nil, vterrors.New(vtrpcpb.Code_UNIMPLEMENTED, "DiscoveryGateway does not implement QueryServiceByAlias")
 }
diff --git a/go/vt/vtgate/engine/merge_sort.go b/go/vt/vtgate/engine/merge_sort.go
index a93b2ba451..b87aa98176 100644
--- a/go/vt/vtgate/engine/merge_sort.go
+++ b/go/vt/vtgate/engine/merge_sort.go
@@ -79,7 +79,7 @@ func (ms *MergeSort) StreamExecute(vcursor VCursor, bindVars map[string]*querypb
 
 	handles := make([]*streamHandle, len(ms.Primitives))
 	for i, input := range ms.Primitives {
-		handles[i] = runOneStream(ctx, vcursor, input, bindVars, wantfields)
+		handles[i] = runOneStream(vcursor, input, bindVars, wantfields)
 		// Need fields only from first handle, if wantfields was true.
 		wantfields = false
 	}
@@ -182,11 +182,12 @@ type streamHandle struct {
 }
 
 // runOnestream starts a streaming query on one shard, and returns a streamHandle for it.
-func runOneStream(ctx context.Context, vcursor VCursor, input StreamExecutor, bindVars map[string]*querypb.BindVariable, wantfields bool) *streamHandle {
+func runOneStream(vcursor VCursor, input StreamExecutor, bindVars map[string]*querypb.BindVariable, wantfields bool) *streamHandle {
 	handle := &streamHandle{
 		fields: make(chan []*querypb.Field, 1),
 		row:    make(chan []sqltypes.Value, 10),
 	}
+	ctx := vcursor.Context()
 
 	go func() {
 		defer close(handle.fields)
diff --git a/go/vt/vtgate/engine/set.go b/go/vt/vtgate/engine/set.go
index ef27d88875..51ee9934b9 100644
--- a/go/vt/vtgate/engine/set.go
+++ b/go/vt/vtgate/engine/set.go
@@ -420,7 +420,7 @@ func (svss *SysVarSetAware) Execute(vcursor VCursor, env evalengine.ExpressionEn
 			// do nothing
 			break
 		default:
-			return vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "charset/name %v is not supported", str)
+			return vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongValueForVar, "unexpected value for charset/names: %v", str)
 		}
 	case sysvars.ReadAfterWriteGTID.Name:
 		str, err := svss.evalAsString(env)
@@ -445,10 +445,10 @@ func (svss *SysVarSetAware) Execute(vcursor VCursor, env evalengine.ExpressionEn
 		case "own_gtid":
 			vcursor.Session().SetSessionTrackGTIDs(true)
 		default:
-			return vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongValueForVar, "variable 'session_track_gtids' can't be set to the value of '%s'", str)
+			return vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongValueForVar, "Variable 'session_track_gtids' can't be set to the value of '%s'", str)
 		}
 	default:
-		return vterrors.NewErrorf(vtrpcpb.Code_NOT_FOUND, vterrors.UnknownSystemVariable, "unknown system variable '%s'", svss.Name)
+		return vterrors.NewErrorf(vtrpcpb.Code_NOT_FOUND, vterrors.UnknownSystemVariable, "Unknown system variable '%s'", svss.Name)
 	}
 
 	return err
@@ -462,7 +462,7 @@ func (svss *SysVarSetAware) evalAsInt64(env evalengine.ExpressionEnv) (int64, er
 
 	v := value.Value()
 	if !v.IsIntegral() {
-		return 0, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongTypeForVar, "incorrect argument type to variable '%s': %s", svss.Name, value.Value().Type().String())
+		return 0, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongTypeForVar, "Incorrect argument type to variable '%s': %s", svss.Name, value.Value().Type().String())
 	}
 	intValue, err := v.ToInt64()
 	if err != nil {
@@ -480,7 +480,7 @@ func (svss *SysVarSetAware) evalAsFloat(env evalengine.ExpressionEnv) (float64,
 	v := value.Value()
 	floatValue, err := v.ToFloat64()
 	if err != nil {
-		return 0, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongTypeForVar, "incorrect argument type to variable '%s': %s", svss.Name, value.Value().Type().String())
+		return 0, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongTypeForVar, "Incorrect argument type to variable '%s': %s", svss.Name, value.Value().Type().String())
 	}
 	return floatValue, nil
 }
@@ -492,7 +492,7 @@ func (svss *SysVarSetAware) evalAsString(env evalengine.ExpressionEnv) (string,
 	}
 	v := value.Value()
 	if !v.IsText() && !v.IsBinary() {
-		return "", vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongTypeForVar, "incorrect argument type to variable '%s': %s", svss.Name, value.Value().Type().String())
+		return "", vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongTypeForVar, "Incorrect argument type to variable '%s': %s", svss.Name, value.Value().Type().String())
 	}
 
 	return v.ToString(), nil
@@ -505,7 +505,7 @@ func (svss *SysVarSetAware) setBoolSysVar(env evalengine.ExpressionEnv, setter f
 	}
 	boolValue, err := value.ToBooleanStrict()
 	if err != nil {
-		return vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongValueForVar, "variable '%s' can't be set to the value: %s", svss.Name, err.Error())
+		return vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongValueForVar, "Variable '%s' can't be set to the value: %s", svss.Name, err.Error())
 	}
 	return setter(boolValue)
 }
diff --git a/go/vt/vtgate/executor.go b/go/vt/vtgate/executor.go
index 0496d1d5ae..d95dce136d 100644
--- a/go/vt/vtgate/executor.go
+++ b/go/vt/vtgate/executor.go
@@ -22,6 +22,7 @@ import (
 	"errors"
 	"fmt"
 	"net/http"
+	"regexp"
 	"sort"
 	"strconv"
 	"strings"
@@ -76,6 +77,10 @@ var (
 )
 
 const (
+	utf8          = "utf8"
+	utf8mb4       = "utf8mb4"
+	both          = "both"
+	charset       = "charset"
 	bindVarPrefix = "__vt"
 )
 
@@ -475,7 +480,8 @@ func (e *Executor) handleSet(ctx context.Context, sql string, logStats *LogStats
 	for _, expr := range set.Exprs {
 		// This is what correctly allows us to handle queries such as "set @@session.`autocommit`=1"
 		// it will remove backticks and double quotes that might surround the part after the first period
-		_, name := sqlparser.NewStringTokenizer(expr.Name.Lowered()).Scan()
+		_, out := sqlparser.NewStringTokenizer(expr.Name.Lowered()).Scan()
+		name := string(out)
 		switch expr.Scope {
 		case sqlparser.VitessMetadataScope:
 			value, err = getValueFor(expr)
@@ -504,15 +510,15 @@ func getValueFor(expr *sqlparser.SetExpr) (interface{}, error) {
 	case *sqlparser.Literal:
 		switch expr.Type {
 		case sqlparser.StrVal:
-			return strings.ToLower(expr.Val), nil
+			return strings.ToLower(string(expr.Val)), nil
 		case sqlparser.IntVal:
-			num, err := strconv.ParseInt(expr.Val, 0, 64)
+			num, err := strconv.ParseInt(string(expr.Val), 0, 64)
 			if err != nil {
 				return nil, err
 			}
 			return num, nil
 		case sqlparser.FloatVal:
-			num, err := strconv.ParseFloat(expr.Val, 64)
+			num, err := strconv.ParseFloat(string(expr.Val), 64)
 			if err != nil {
 				return nil, err
 			}
@@ -1385,6 +1391,98 @@ func buildVarCharRow(values ...string) []sqltypes.Value {
 	return row
 }
 
+func generateCharsetRows(showFilter *sqlparser.ShowFilter, colNames []string) ([][]sqltypes.Value, error) {
+	if showFilter == nil {
+		return buildCharsetRows(both), nil
+	}
+
+	var filteredColName string
+	var err error
+
+	if showFilter.Like != "" {
+		filteredColName, err = checkLikeOpt(showFilter.Like, colNames)
+		if err != nil {
+			return nil, err
+		}
+
+	} else {
+		cmpExp, ok := showFilter.Filter.(*sqlparser.ComparisonExpr)
+		if !ok {
+			return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.SyntaxError, "expect a 'LIKE' or '=' expression")
+		}
+
+		left, ok := cmpExp.Left.(*sqlparser.ColName)
+		if !ok {
+			return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.SyntaxError, "expect left side to be 'column'")
+		}
+		leftOk := left.Name.EqualString(charset)
+
+		if leftOk {
+			literal, ok := cmpExp.Right.(*sqlparser.Literal)
+			if !ok {
+				return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.SyntaxError, "expect right side to be string")
+			}
+			rightString := string(literal.Val)
+
+			switch cmpExp.Operator {
+			case sqlparser.EqualOp:
+				for _, colName := range colNames {
+					if rightString == colName {
+						filteredColName = colName
+					}
+				}
+			case sqlparser.LikeOp:
+				filteredColName, err = checkLikeOpt(rightString, colNames)
+				if err != nil {
+					return nil, err
+				}
+			}
+		}
+
+	}
+
+	return buildCharsetRows(filteredColName), nil
+}
+
+func buildCharsetRows(colName string) [][]sqltypes.Value {
+	row0 := buildVarCharRow(
+		"utf8",
+		"UTF-8 Unicode",
+		"utf8_general_ci")
+	row0 = append(row0, sqltypes.NewInt32(3))
+	row1 := buildVarCharRow(
+		"utf8mb4",
+		"UTF-8 Unicode",
+		"utf8mb4_general_ci")
+	row1 = append(row1, sqltypes.NewInt32(4))
+
+	switch colName {
+	case utf8:
+		return [][]sqltypes.Value{row0}
+	case utf8mb4:
+		return [][]sqltypes.Value{row1}
+	case both:
+		return [][]sqltypes.Value{row0, row1}
+	}
+
+	return [][]sqltypes.Value{}
+}
+
+func checkLikeOpt(likeOpt string, colNames []string) (string, error) {
+	likeRegexp := strings.ReplaceAll(likeOpt, "%", ".*")
+	for _, v := range colNames {
+		match, err := regexp.MatchString(likeRegexp, v)
+		if err != nil {
+			return "", err
+		}
+		if match {
+			return v, nil
+		}
+	}
+
+	return "", nil
+}
+
 // isValidPayloadSize validates whether a query payload is above the
 // configured MaxPayloadSize threshold. The WarnPayloadSizeExceeded will increment
 // if the payload size exceeds the warnPayloadSize.
diff --git a/go/vt/vtgate/gateway.go b/go/vt/vtgate/gateway.go
index 86a015ab77..1398ad5419 100644
--- a/go/vt/vtgate/gateway.go
+++ b/go/vt/vtgate/gateway.go
@@ -17,8 +17,6 @@ import (
 	"flag"
 	"time"
 
-	querypb "vitess.io/vitess/go/vt/proto/query"
-
 	"context"
 
 	"vitess.io/vitess/go/vt/log"
@@ -70,7 +68,7 @@ type Gateway interface {
 	TabletsCacheStatus() discovery.TabletsCacheStatusList
 
 	// TabletByAlias returns a QueryService
-	QueryServiceByAlias(alias *topodatapb.TabletAlias, target *querypb.Target) (queryservice.QueryService, error)
+	QueryServiceByAlias(alias *topodatapb.TabletAlias) (queryservice.QueryService, error)
 }
 
 // Creator is the factory method which can create the actual gateway object.
diff --git a/go/vt/vtgate/planbuilder/bypass.go b/go/vt/vtgate/planbuilder/bypass.go
index abc42459ab..765fbaa0c0 100644
--- a/go/vt/vtgate/planbuilder/bypass.go
+++ b/go/vt/vtgate/planbuilder/bypass.go
@@ -28,7 +28,7 @@ func buildPlanForBypass(stmt sqlparser.Statement, _ *sqlparser.ReservedVars, vsc
 	switch vschema.Destination().(type) {
 	case key.DestinationExactKeyRange:
 		if _, ok := stmt.(*sqlparser.Insert); ok {
-			return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "INSERT not supported when targeting a key range: %s", vschema.TargetString())
+			return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "range queries are not allowed for insert statement: %s", vschema.TargetString())
 		}
 	}
 
diff --git a/go/vt/vtgate/planbuilder/fuzz.go b/go/vt/vtgate/planbuilder/fuzz.go
deleted file mode 100644
index 07fbc9bf33..0000000000
--- a/go/vt/vtgate/planbuilder/fuzz.go
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
-Copyright 2021 The Vitess Authors.
-
-Licensed 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.
-*/
-// +build gofuzz
-
-package planbuilder
-
-import (
-	"vitess.io/vitess/go/vt/key"
-	topodatapb "vitess.io/vitess/go/vt/proto/topodata"
-	"vitess.io/vitess/go/vt/sqlparser"
-	"vitess.io/vitess/go/vt/vtgate/semantics"
-	"vitess.io/vitess/go/vt/vtgate/vindexes"
-)
-
-var _ semantics.SchemaInformation = (*fakeFuzzSI)(nil)
-
-type fakeFuzzSI struct {
-	tables map[string]*vindexes.Table
-}
-
-// Helper func:
-func (s *fakeFuzzSI) FindTableOrVindex(tablename sqlparser.TableName) (*vindexes.Table, vindexes.Vindex, string, topodatapb.TabletType, key.Destination, error) {
-	return s.tables[sqlparser.String(tablename)], nil, "", 0, nil, nil
-}
-
-// FuzzAnalyse implements the fuzzer
-func FuzzAnalyse(data []byte) int {
-	tree, err := sqlparser.Parse(string(data))
-	if err != nil {
-		return -1
-	}
-	semTable, err := semantics.Analyse(tree, &fakeFuzzSI{})
-	if err != nil {
-		return 0
-	}
-	_, _ = createQGFromSelect(tree.(*sqlparser.Select), semTable)
-	return 1
-}
diff --git a/go/vt/vtgate/planbuilder/grouping.go b/go/vt/vtgate/planbuilder/grouping.go
index a1b8614a64..49324a0e8b 100644
--- a/go/vt/vtgate/planbuilder/grouping.go
+++ b/go/vt/vtgate/planbuilder/grouping.go
@@ -56,7 +56,7 @@ func planGroupBy(pb *primitiveBuilder, input logicalPlan, groupBy sqlparser.Grou
 			case *sqlparser.ColName:
 				c := e.Metadata.(*column)
 				if c.Origin() == node {
-					return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongGroupField, "Can't group on '%s'", sqlparser.String(e))
+					return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.WrongGroupField, "group by expression cannot reference an aggregate function: %v", sqlparser.String(e))
 				}
 				for i, rc := range node.resultColumns {
 					if rc.column == c {
diff --git a/go/vt/vtgate/planbuilder/ordering.go b/go/vt/vtgate/planbuilder/ordering.go
index 57f3b268db..8350a5ed80 100644
--- a/go/vt/vtgate/planbuilder/ordering.go
+++ b/go/vt/vtgate/planbuilder/ordering.go
@@ -48,7 +48,7 @@ func planOrdering(pb *primitiveBuilder, input logicalPlan, orderBy sqlparser.Ord
 	case *orderedAggregate:
 		return planOAOrdering(pb, orderBy, node)
 	case *mergeSort:
-		return nil, vterrors.Errorf(vtrpc.Code_UNIMPLEMENTED, "can't do ORDER BY on top of ORDER BY")
+		return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "can't do ORDER BY on top of ORDER BY")
 	}
 	if orderBy == nil {
 		return input, nil
diff --git a/go/vt/vtgate/planbuilder/queryprojection.go b/go/vt/vtgate/planbuilder/queryprojection.go
index 032fe0e283..e638d651e1 100644
--- a/go/vt/vtgate/planbuilder/queryprojection.go
+++ b/go/vt/vtgate/planbuilder/queryprojection.go
@@ -52,7 +52,7 @@ func createQPFromSelect(sel *sqlparser.Select) (*queryProjection, error) {
 		fExpr, ok := exp.Expr.(*sqlparser.FuncExpr)
 		if ok && fExpr.IsAggregate() {
 			if len(fExpr.Exprs) != 1 {
-				return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.SyntaxError, "aggregate functions take a single argument '%s'", sqlparser.String(fExpr))
+				return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.SyntaxError, "multiple arguments inside the function '%s'", sqlparser.String(fExpr))
 			}
 			qp.aggrExprs = append(qp.aggrExprs, exp)
 			continue
diff --git a/go/vt/vtgate/planbuilder/set.go b/go/vt/vtgate/planbuilder/set.go
index a65059895e..d34e9397ab 100644
--- a/go/vt/vtgate/planbuilder/set.go
+++ b/go/vt/vtgate/planbuilder/set.go
@@ -104,13 +104,13 @@ func buildSetPlan(stmt *sqlparser.Set, vschema ContextVSchema) (engine.Primitive
 
 func buildSetOpReadOnly(s setting) planFunc {
 	return func(expr *sqlparser.SetExpr, schema ContextVSchema, _ *expressionConverter) (engine.SetOp, error) {
-		return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.IncorrectGlobalLocalVar, "variable '%s' is a read only variable", expr.Name)
+		return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.IncorrectGlobalLocalVar, "Variable '%s' is a read only variable", expr.Name)
 	}
 }
 
 func buildNotSupported(setting) planFunc {
 	return func(expr *sqlparser.SetExpr, schema ContextVSchema, _ *expressionConverter) (engine.SetOp, error) {
-		return nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "%s: system setting is not supported", expr.Name)
+		return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%s: system setting is not supported", expr.Name)
 	}
 }
 
diff --git a/go/vt/vtgate/planbuilder/show.go b/go/vt/vtgate/planbuilder/show.go
index 452e143c95..a4b166fdc4 100644
--- a/go/vt/vtgate/planbuilder/show.go
+++ b/go/vt/vtgate/planbuilder/show.go
@@ -311,21 +311,21 @@ func generateCharsetRows(showFilter *sqlparser.ShowFilter, colNames []string) ([
 	} else {
 		cmpExp, ok := showFilter.Filter.(*sqlparser.ComparisonExpr)
 		if !ok {
-			return nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "expect a 'LIKE' or '=' expression")
+			return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.SyntaxError, "expect a 'LIKE' or '=' expression")
 		}
 
 		left, ok := cmpExp.Left.(*sqlparser.ColName)
 		if !ok {
-			return nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "expect left side to be 'charset'")
+			return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.SyntaxError, "expect left side to be 'charset'")
 		}
 		leftOk := left.Name.EqualString(charset)
 
 		if leftOk {
 			literal, ok := cmpExp.Right.(*sqlparser.Literal)
 			if !ok {
-				return nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "we expect the right side to be a string")
+				return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.SyntaxError, "we expect the right side to be a string")
 			}
-			rightString := literal.Val
+			rightString := string(literal.Val)
 
 			switch cmpExp.Operator {
 			case sqlparser.EqualOp:
diff --git a/go/vt/vtgate/safe_session.go b/go/vt/vtgate/safe_session.go
index dd63c2cd30..05db3b7ffa 100644
--- a/go/vt/vtgate/safe_session.go
+++ b/go/vt/vtgate/safe_session.go
@@ -533,7 +533,7 @@ func removeShard(tabletAlias *topodatapb.TabletAlias, sessions []*vtgatepb.Sessi
 		}
 	}
 	if idx == -1 {
-		return nil, vterrors.New(vtrpcpb.Code_INTERNAL, "[BUG] tried to remove missing shard")
+		return sessions, nil
 	}
 	return append(sessions[:idx], sessions[idx+1:]...), nil
 }
diff --git a/go/vt/vtgate/scatter_conn.go b/go/vt/vtgate/scatter_conn.go
index ea8e27b26c..ad8df6b6a0 100644
--- a/go/vt/vtgate/scatter_conn.go
+++ b/go/vt/vtgate/scatter_conn.go
@@ -145,14 +145,6 @@ func (stc *ScatterConn) endAction(startTime time.Time, allErrors *concurrency.Al
 	stc.timings.Record(statsKey, startTime)
 }
 
-type reset int
-
-const (
-	none reset = iota
-	shard
-	newQS
-)
-
 // ExecuteMultiShard is like Execute,
 // but each shard gets its own Sql Queries and BindVariables.
 //
@@ -214,82 +206,60 @@ func (stc *ScatterConn) ExecuteMultiShard(
 
 			if autocommit {
 				// As this is auto-commit, the transactionID is supposed to be zero.
-				if transactionID != int64(0) {
-					return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "in autocommit mode, transactionID should be zero but was: %d", transactionID)
+				if info.transactionID != int64(0) {
+					return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "in autocommit mode, transactionID should be zero but was: %d", info.transactionID)
 				}
 			}
 
 			qs, err = getQueryService(rs, info)
 			if err != nil {
-				// an error here could mean that the tablet we were targeting earlier has changed type.
-				// if we have a transaction, we'll have to fail, but if we only had a reserved connection,
-				// we can create a new reserved connection to a new tablet that is on the right shard
-				// and has the right type
-				switch info.actionNeeded {
-				case nothing:
-					info.actionNeeded = reserve
-				case begin:
-					info.actionNeeded = reserveBegin
-				default:
-					return nil, err
-				}
-				retry := checkAndResetShardSession(info, err, session)
-				if retry != newQS {
-					return nil, err
-				}
-				qs = rs.Gateway
-			}
-
-			retryRequest := func(exec func()) {
-				retry := checkAndResetShardSession(info, err, session)
-				switch retry {
-				case newQS:
-					// Current tablet is not available, try querying new tablet using gateway.
-					qs = rs.Gateway
-					fallthrough
-				case shard:
-					// if we need to reset a reserved connection, here is our chance to try executing again,
-					// against a new connection
-					exec()
-				}
+				return nil, err
 			}
 
 			switch info.actionNeeded {
 			case nothing:
 				innerqr, err = qs.Execute(ctx, rs.Target, queries[i].Sql, queries[i].BindVariables, info.transactionID, info.reservedID, opts)
 				if err != nil {
-					retryRequest(func() {
-						// we seem to have lost our connection. it was a reserved connection, let's try to recreate it
+					shouldRetry := checkAndResetShardSession(info, err, session)
+					if shouldRetry {
+						// we seem to have lost our connection. if it was a reserved connection, let's try to recreate it
 						info.actionNeeded = reserve
 						innerqr, reservedID, alias, err = qs.ReserveExecute(ctx, rs.Target, session.SetPreQueries(), queries[i].Sql, queries[i].BindVariables, 0 /*transactionId*/, opts)
-					})
+					}
+					if err != nil {
+						return info.updateReservedID(reservedID, alias), err
+					}
 				}
 			case begin:
-				innerqr, transactionID, alias, err = qs.BeginExecute(ctx, rs.Target, session.Savepoints, queries[i].Sql, queries[i].BindVariables, reservedID, opts)
+				innerqr, transactionID, alias, err = qs.BeginExecute(ctx, rs.Target, session.Savepoints, queries[i].Sql, queries[i].BindVariables, info.reservedID, opts)
 				if err != nil {
 					if transactionID != 0 {
-						// if we had an open transaction, we can't repair anything and have to exit here.
-						// we still keep the transaction open - an error doesn't immediately close the transaction
-						break
+						return info.updateTransactionID(transactionID, alias), err
 					}
-					retryRequest(func() {
-						// we seem to have lost our connection. it was a reserved connection, let's try to recreate it
+					shouldRetry := checkAndResetShardSession(info, err, session)
+					if shouldRetry {
+						// we seem to have lost our connection. if it was a reserved connection, let's try to recreate it
 						info.actionNeeded = reserveBegin
 						innerqr, transactionID, reservedID, alias, err = qs.ReserveBeginExecute(ctx, rs.Target, session.SetPreQueries(), queries[i].Sql, queries[i].BindVariables, opts)
-					})
+					}
+					if err != nil {
+						return info.updateTransactionAndReservedID(transactionID, reservedID, alias), err
+					}
+
 				}
 			case reserve:
-				innerqr, reservedID, alias, err = qs.ReserveExecute(ctx, rs.Target, session.SetPreQueries(), queries[i].Sql, queries[i].BindVariables, transactionID, opts)
+				innerqr, reservedID, alias, err = qs.ReserveExecute(ctx, rs.Target, session.SetPreQueries(), queries[i].Sql, queries[i].BindVariables, info.transactionID, opts)
+				if err != nil {
+					return info.updateReservedID(reservedID, alias), err
+				}
 			case reserveBegin:
 				innerqr, transactionID, reservedID, alias, err = qs.ReserveBeginExecute(ctx, rs.Target, session.SetPreQueries(), queries[i].Sql, queries[i].BindVariables, opts)
+				if err != nil {
+					return info.updateTransactionAndReservedID(transactionID, reservedID, alias), err
+				}
 			default:
 				return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] unexpected actionNeeded on query execution: %v", info.actionNeeded)
 			}
-			// We need to new shard info irrespective of the error.
-			newInfo := info.updateTransactionAndReservedID(transactionID, reservedID, alias)
-			if err != nil {
-				return newInfo, err
-			}
 			mu.Lock()
 			defer mu.Unlock()
 
@@ -297,7 +267,7 @@ func (stc *ScatterConn) ExecuteMultiShard(
 			if ignoreMaxMemoryRows || len(qr.Rows) <= *maxMemoryRows {
 				qr.AppendResult(innerqr)
 			}
-			return newInfo, nil
+			return info.updateTransactionAndReservedID(transactionID, reservedID, alias), nil
 		},
 	)
 
@@ -308,32 +278,28 @@ func (stc *ScatterConn) ExecuteMultiShard(
 	return qr, allErrors.GetErrors()
 }
 
-func checkAndResetShardSession(info *shardActionInfo, err error, session *SafeSession) reset {
-	retry := none
-	if info.reservedID != 0 && info.transactionID == 0 {
-		if wasConnectionClosed(err) {
-			retry = shard
-		}
-		if requireNewQS(err) {
-			retry = newQS
-		}
-	}
-	if retry != none {
-		_ = session.ResetShard(info.alias)
+var errRegx = regexp.MustCompile("transaction ([a-z0-9:]+) (?:ended|not found)")
+
+func checkAndResetShardSession(info *shardActionInfo, err error, session *SafeSession) bool {
+	if info.reservedID != 0 && info.transactionID == 0 && wasConnectionClosed(err) {
+		session.ResetShard(info.alias)
+		return true
 	}
-	return retry
+	return false
 }
 
 func getQueryService(rs *srvtopo.ResolvedShard, info *shardActionInfo) (queryservice.QueryService, error) {
 	_, usingLegacyGw := rs.Gateway.(*DiscoveryGateway)
-	if usingLegacyGw &&
-		(info.actionNeeded == reserve || info.actionNeeded == reserveBegin) {
-		return nil, vterrors.New(vtrpcpb.Code_UNIMPLEMENTED, "reserved connections are not supported on old gen gateway")
+	if usingLegacyGw {
+		switch info.actionNeeded {
+		case reserve, reserveBegin:
+			return nil, vterrors.New(vtrpcpb.Code_UNIMPLEMENTED, "reserved connections are not supported on old gen gateway")
+		}
 	}
 	if usingLegacyGw || info.alias == nil {
 		return rs.Gateway, nil
 	}
-	return rs.Gateway.QueryServiceByAlias(info.alias, rs.Target)
+	return rs.Gateway.QueryServiceByAlias(info.alias)
 }
 
 func (stc *ScatterConn) processOneStreamingResult(mu *sync.Mutex, fieldSent *bool, qr *sqltypes.Result, callback func(*sqltypes.Result) error) error {
@@ -709,21 +675,12 @@ func (stc *ScatterConn) ExecuteLock(
 	return qr, err
 }
 
-var txClosed = regexp.MustCompile("transaction ([a-z0-9:]+) (?:ended|not found)")
-
 func wasConnectionClosed(err error) bool {
 	sqlErr := mysql.NewSQLErrorFromError(err).(*mysql.SQLError)
-	message := sqlErr.Error()
 
 	return sqlErr.Number() == mysql.CRServerGone ||
 		sqlErr.Number() == mysql.CRServerLost ||
-		(sqlErr.Number() == mysql.ERQueryInterrupted && txClosed.MatchString(message))
-}
-
-func requireNewQS(err error) bool {
-	code := vterrors.Code(err)
-	msg := err.Error()
-	return code == vtrpcpb.Code_FAILED_PRECONDITION && (vterrors.RxOp.MatchString(msg) || vterrors.RxWrongTablet.MatchString(msg))
+		(sqlErr.Number() == mysql.ERQueryInterrupted && errRegx.MatchString(sqlErr.Error()))
 }
 
 // actionInfo looks at the current session, and returns information about what needs to be done for this tablet
@@ -781,9 +738,25 @@ type shardActionInfo struct {
 	alias                     *topodatapb.TabletAlias
 }
 
+func (sai *shardActionInfo) updateTransactionID(txID int64, alias *topodatapb.TabletAlias) *shardActionInfo {
+	if txID == 0 {
+		// As transaction id is ZERO, there is nothing to update in session shard sessions.
+		return nil
+	}
+	return sai.updateTransactionAndReservedID(txID, sai.reservedID, alias)
+}
+
+func (sai *shardActionInfo) updateReservedID(rID int64, alias *topodatapb.TabletAlias) *shardActionInfo {
+	if rID == 0 {
+		// As reserved id is ZERO, there is nothing to update in session shard sessions.
+		return nil
+	}
+	return sai.updateTransactionAndReservedID(sai.transactionID, rID, alias)
+}
+
 func (sai *shardActionInfo) updateTransactionAndReservedID(txID int64, rID int64, alias *topodatapb.TabletAlias) *shardActionInfo {
-	if txID == sai.transactionID && rID == sai.reservedID {
-		// As transaction id and reserved id have not changed, there is nothing to update in session shard sessions.
+	if txID == 0 && rID == 0 {
+		// As transaction id and reserved id is ZERO, there is nothing to update in session shard sessions.
 		return nil
 	}
 	newInfo := *sai
diff --git a/go/vt/vtgate/tabletgateway.go b/go/vt/vtgate/tabletgateway.go
index 504945bd70..5556cafdb8 100644
--- a/go/vt/vtgate/tabletgateway.go
+++ b/go/vt/vtgate/tabletgateway.go
@@ -132,8 +132,8 @@ func NewTabletGateway(ctx context.Context, hc discovery.HealthCheck, serv srvtop
 }
 
 // QueryServiceByAlias satisfies the Gateway interface
-func (gw *TabletGateway) QueryServiceByAlias(alias *topodatapb.TabletAlias, target *querypb.Target) (queryservice.QueryService, error) {
-	return gw.hc.TabletConnection(alias, target)
+func (gw *TabletGateway) QueryServiceByAlias(alias *topodatapb.TabletAlias) (queryservice.QueryService, error) {
+	return gw.hc.TabletConnection(alias)
 }
 
 // RegisterStats registers the stats to export the lag since the last refresh
diff --git a/go/vt/vtgate/tx_conn.go b/go/vt/vtgate/tx_conn.go
index b056b8db50..4747dcf266 100644
--- a/go/vt/vtgate/tx_conn.go
+++ b/go/vt/vtgate/tx_conn.go
@@ -87,7 +87,7 @@ func (txc *TxConn) queryService(alias *topodatapb.TabletAlias) (queryservice.Que
 	if qs != nil {
 		return qs, nil
 	}
-	return txc.gateway.QueryServiceByAlias(alias, nil)
+	return txc.gateway.QueryServiceByAlias(alias)
 }
 
 func (txc *TxConn) commitShard(ctx context.Context, s *vtgatepb.Session_ShardSession) error {
diff --git a/go/vt/vtgate/vcursor_impl.go b/go/vt/vtgate/vcursor_impl.go
index 8ba52d45cf..f60af6dca2 100644
--- a/go/vt/vtgate/vcursor_impl.go
+++ b/go/vt/vtgate/vcursor_impl.go
@@ -525,11 +525,11 @@ func (vc *vcursorImpl) SetTarget(target string) error {
 		return err
 	}
 	if _, ok := vc.vschema.Keyspaces[keyspace]; !ignoreKeyspace(keyspace) && !ok {
-		return vterrors.NewErrorf(vtrpcpb.Code_NOT_FOUND, vterrors.BadDb, "unknown database '%s'", keyspace)
+		return vterrors.NewErrorf(vtrpcpb.Code_NOT_FOUND, vterrors.BadDb, "Unknown database '%s'", keyspace)
 	}
 
 	if vc.safeSession.InTransaction() && tabletType != topodatapb.TabletType_MASTER {
-		return vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.LockOrActiveTransaction, "can't execute the given command because you have an active transaction")
+		return vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.LockOrActiveTransaction, "Can't execute the given command because you have an active transaction")
 	}
 	vc.safeSession.SetTargetString(target)
 	return nil
diff --git a/go/vt/vttablet/sandboxconn/sandboxconn.go b/go/vt/vttablet/sandboxconn/sandboxconn.go
index 3fff1352ae..63d8819d51 100644
--- a/go/vt/vttablet/sandboxconn/sandboxconn.go
+++ b/go/vt/vttablet/sandboxconn/sandboxconn.go
@@ -207,25 +207,10 @@ func (sbc *SandboxConn) StreamExecute(ctx context.Context, target *querypb.Targe
 		return err
 	}
 	parse, _ := sqlparser.Parse(query)
-
-	if sbc.results == nil {
-		nextRs := sbc.getNextResult(parse)
-		sbc.sExecMu.Unlock()
-		return callback(nextRs)
-	}
-
-	for len(sbc.results) > 0 {
-		nextRs := sbc.getNextResult(parse)
-		sbc.sExecMu.Unlock()
-		err := callback(nextRs)
-		if err != nil {
-			return err
-		}
-		sbc.sExecMu.Lock()
-	}
-
+	nextRs := sbc.getNextResult(parse)
 	sbc.sExecMu.Unlock()
-	return nil
+
+	return callback(nextRs)
 }
 
 // Begin is part of the QueryService interface.
@@ -496,7 +481,7 @@ func (sbc *SandboxConn) VStreamResults(ctx context.Context, target *querypb.Targ
 }
 
 // QueryServiceByAlias is part of the Gateway interface.
-func (sbc *SandboxConn) QueryServiceByAlias(_ *topodatapb.TabletAlias, _ *querypb.Target) (queryservice.QueryService, error) {
+func (sbc *SandboxConn) QueryServiceByAlias(_ *topodatapb.TabletAlias) (queryservice.QueryService, error) {
 	return sbc, nil
 }
 
@@ -596,10 +581,6 @@ func (sbc *SandboxConn) setTxReservedID(transactionID int64, reservedID int64) {
 	sbc.txIDToRID[transactionID] = reservedID
 }
 
-func (sbc *SandboxConn) ResultsAllFetched() bool {
-	return len(sbc.results) == 0
-}
-
 func (sbc *SandboxConn) getTxReservedID(txID int64) int64 {
 	sbc.mapMu.Lock()
 	defer sbc.mapMu.Unlock()
diff --git a/go/vt/vttablet/tabletmanager/tm_init.go b/go/vt/vttablet/tabletmanager/tm_init.go
index 8a4f7dd34c..db38b091ea 100644
--- a/go/vt/vttablet/tabletmanager/tm_init.go
+++ b/go/vt/vttablet/tabletmanager/tm_init.go
@@ -94,6 +94,9 @@ var (
 	// statsBackupIsRunning is set to 1 (true) if a backup is running.
 	statsBackupIsRunning *stats.GaugesWithMultiLabels
 
+	// statsIsInSrvKeyspace is set to 1 (true), 0 (false) whether the tablet is in the serving keyspace
+	statsIsInSrvKeyspace *stats.Gauge
+
 	statsKeyspace      = stats.NewString("TabletKeyspace")
 	statsShard         = stats.NewString("TabletShard")
 	statsKeyRangeStart = stats.NewString("TabletKeyRangeStart")
@@ -115,6 +118,7 @@ func init() {
 	statsTabletType = stats.NewString("TabletType")
 	statsTabletTypeCount = stats.NewCountersWithSingleLabel("TabletTypeCount", "Number of times the tablet changed to the labeled type", "type")
 	statsBackupIsRunning = stats.NewGaugesWithMultiLabels("BackupIsRunning", "Whether a backup is running", []string{"mode"})
+	statsIsInSrvKeyspace = stats.NewGauge("IsInSrvKeyspace", "Whether the vttablet is in the serving keyspace (1 = true / 0 = false)")
 }
 
 // TabletManager is the main class for the tablet manager.
diff --git a/go/vt/vttablet/tabletmanager/tm_state.go b/go/vt/vttablet/tabletmanager/tm_state.go
index f52ced1cfe..1eb27d99cd 100644
--- a/go/vt/vttablet/tabletmanager/tm_state.go
+++ b/go/vt/vttablet/tabletmanager/tm_state.go
@@ -62,6 +62,8 @@ type tmState struct {
 	mu                sync.Mutex
 	isOpen            bool
 	isResharding      bool
+	isInSrvKeyspace   bool
+	isShardServing    map[topodatapb.TabletType]bool
 	tabletControls    map[topodatapb.TabletType]bool
 	blacklistedTables map[topodatapb.TabletType][]string
 	tablet            *topodatapb.Tablet
@@ -139,8 +141,17 @@ func (ts *tmState) RefreshFromTopoInfo(ctx context.Context, shardInfo *topo.Shar
 	}
 
 	if srvKeyspace != nil {
+		ts.isShardServing = make(map[topodatapb.TabletType]bool)
 		ts.tabletControls = make(map[topodatapb.TabletType]bool)
+
 		for _, partition := range srvKeyspace.GetPartitions() {
+
+			for _, shard := range partition.GetShardReferences() {
+				if key.KeyRangeEqual(shard.GetKeyRange(), ts.tablet.KeyRange) {
+					ts.isShardServing[partition.GetServedType()] = true
+				}
+			}
+
 			for _, tabletControl := range partition.GetShardTabletControls() {
 				if key.KeyRangeEqual(tabletControl.GetKeyRange(), ts.KeyRange()) {
 					if tabletControl.QueryServiceDisabled {
@@ -252,6 +263,14 @@ func (ts *tmState) updateLocked(ctx context.Context) {
 		}
 	}
 
+	if ts.isShardServing[ts.tablet.Type] {
+		ts.isInSrvKeyspace = true
+		statsIsInSrvKeyspace.Set(1)
+	} else {
+		ts.isInSrvKeyspace = false
+		statsIsInSrvKeyspace.Set(0)
+	}
+
 	// Open TabletServer last so that it advertises serving after all other services are up.
 	if reason == "" {
 		if err := ts.tm.QueryServiceControl.SetServingType(ts.tablet.Type, terTime, true, ""); err != nil {
diff --git a/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go b/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go
index eb7901fa0c..d80ed36322 100644
--- a/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go
+++ b/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go
@@ -22,8 +22,6 @@ import (
 	"sort"
 	"strings"
 
-	"vitess.io/vitess/go/bytes2"
-
 	"vitess.io/vitess/go/vt/binlog/binlogplayer"
 	"vitess.io/vitess/go/vt/vtgate/evalengine"
 
@@ -209,23 +207,27 @@ func (tp *TablePlan) MarshalJSON() ([]byte, error) {
 	return json.Marshal(&v)
 }
 
-func (tp *TablePlan) applyBulkInsert(sqlbuffer *bytes2.Buffer, rows *binlogdatapb.VStreamRowsResponse, executor func(string) (*sqltypes.Result, error)) (*sqltypes.Result, error) {
-	sqlbuffer.Reset()
-	sqlbuffer.WriteString(tp.BulkInsertFront.Query)
-	sqlbuffer.WriteString(" values ")
-
-	for i, row := range rows.Rows {
-		if i > 0 {
-			sqlbuffer.WriteString(", ")
-		}
-		if err := tp.BulkInsertValues.AppendFromRow(sqlbuffer, tp.Fields, row); err != nil {
-			return nil, err
+func (tp *TablePlan) applyBulkInsert(rows *binlogdatapb.VStreamRowsResponse, executor func(string) (*sqltypes.Result, error)) (*sqltypes.Result, error) {
+	bindvars := make(map[string]*querypb.BindVariable, len(tp.Fields))
+	var buf strings.Builder
+	if err := tp.BulkInsertFront.Append(&buf, nil, nil); err != nil {
+		return nil, err
+	}
+	buf.WriteString(" values ")
+	separator := ""
+	for _, row := range rows.Rows {
+		vals := sqltypes.MakeRowTrusted(tp.Fields, row)
+		for i, field := range tp.Fields {
+			bindvars["a_"+field.Name] = sqltypes.ValueBindVariable(vals[i])
 		}
+		buf.WriteString(separator)
+		separator = ", "
+		tp.BulkInsertValues.Append(&buf, bindvars, nil)
 	}
 	if tp.BulkInsertOnDup != nil {
-		sqlbuffer.WriteString(tp.BulkInsertOnDup.Query)
+		tp.BulkInsertOnDup.Append(&buf, nil, nil)
 	}
-	return executor(sqlbuffer.StringUnsafe())
+	return executor(buf.String())
 }
 
 // During the copy phase we run catchup and fastforward, which stream binlogs. While streaming we should only process
diff --git a/go/vt/vttablet/tabletmanager/vreplication/vcopier.go b/go/vt/vttablet/tabletmanager/vreplication/vcopier.go
index c9e796550f..6d3b694d06 100644
--- a/go/vt/vttablet/tabletmanager/vreplication/vcopier.go
+++ b/go/vt/vttablet/tabletmanager/vreplication/vcopier.go
@@ -24,8 +24,6 @@ import (
 	"strings"
 	"time"
 
-	"vitess.io/vitess/go/bytes2"
-
 	"context"
 
 	"github.com/golang/protobuf/proto"
@@ -222,7 +220,6 @@ func (vc *vcopier) copyTable(ctx context.Context, tableName string, copyState ma
 	var pkfields []*querypb.Field
 	var updateCopyState *sqlparser.ParsedQuery
 	var bv map[string]*querypb.BindVariable
-	var sqlbuffer bytes2.Buffer
 	err = vc.vr.sourceVStreamer.VStreamRows(ctx, initialPlan.SendRule.Filter, lastpkpb, func(rows *binlogdatapb.VStreamRowsResponse) error {
 		for {
 			select {
@@ -268,15 +265,17 @@ func (vc *vcopier) copyTable(ctx context.Context, tableName string, copyState ma
 		if err := vc.vr.dbClient.Begin(); err != nil {
 			return err
 		}
-		_, err = vc.tablePlan.applyBulkInsert(&sqlbuffer, rows, func(sql string) (*sqltypes.Result, error) {
+		_, err = vc.tablePlan.applyBulkInsert(rows, func(sql string) (*sqltypes.Result, error) {
 			start := time.Now()
 			qr, err := vc.vr.dbClient.ExecuteWithRetry(ctx, sql)
 			if err != nil {
 				return nil, err
 			}
 			vc.vr.stats.QueryTimings.Record("copy", start)
+
 			vc.vr.stats.CopyRowCount.Add(int64(qr.RowsAffected))
 			vc.vr.stats.QueryCount.Add("copy", 1)
+
 			return qr, err
 		})
 		if err != nil {
diff --git a/go/vt/vttablet/tabletserver/state_manager.go b/go/vt/vttablet/tabletserver/state_manager.go
index 39cab911fd..c1498e43f4 100644
--- a/go/vt/vttablet/tabletserver/state_manager.go
+++ b/go/vt/vttablet/tabletserver/state_manager.go
@@ -348,19 +348,36 @@ func (sm *stateManager) StartRequest(ctx context.Context, target *querypb.Target
 
 	if sm.state != StateServing || !sm.replHealthy {
 		// This specific error string needs to be returned for vtgate buffering to work.
-		return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, vterrors.NotServing)
+		return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "operation not allowed in state NOT_SERVING")
 	}
 
 	shuttingDown := sm.wantState != StateServing
 	if shuttingDown && !allowOnShutdown {
 		// This specific error string needs to be returned for vtgate buffering to work.
-		return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, vterrors.ShuttingDown)
+		return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "operation not allowed in state SHUTTING_DOWN")
 	}
 
-	err = sm.verifyTargetLocked(ctx, target)
-	if err != nil {
-		return err
+	if target != nil {
+		switch {
+		case target.Keyspace != sm.target.Keyspace:
+			return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid keyspace %v does not match expected %v", target.Keyspace, sm.target.Keyspace)
+		case target.Shard != sm.target.Shard:
+			return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid shard %v does not match expected %v", target.Shard, sm.target.Shard)
+		case target.TabletType != sm.target.TabletType:
+			for _, otherType := range sm.alsoAllow {
+				if target.TabletType == otherType {
+					goto ok
+				}
+			}
+			return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "invalid tablet type: %v, want: %v or %v", target.TabletType, sm.target.TabletType, sm.alsoAllow)
+		}
+	} else {
+		if !tabletenv.IsLocalContext(ctx) {
+			return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "No target")
+		}
 	}
+
+ok:
 	sm.requests.Add(1)
 	return nil
 }
@@ -375,10 +392,6 @@ func (sm *stateManager) EndRequest() {
 func (sm *stateManager) VerifyTarget(ctx context.Context, target *querypb.Target) error {
 	sm.mu.Lock()
 	defer sm.mu.Unlock()
-	return sm.verifyTargetLocked(ctx, target)
-}
-
-func (sm *stateManager) verifyTargetLocked(ctx context.Context, target *querypb.Target) error {
 	if target != nil {
 		switch {
 		case target.Keyspace != sm.target.Keyspace:
@@ -391,7 +404,7 @@ func (sm *stateManager) verifyTargetLocked(ctx context.Context, target *querypb.
 					return nil
 				}
 			}
-			return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "%s: %v, want: %v or %v", vterrors.WrongTablet, sm.target.TabletType, sm.target.TabletType, sm.alsoAllow)
+			return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "invalid tablet type: %v, want: %v or %v", target.TabletType, sm.target.TabletType, sm.alsoAllow)
 		}
 	} else {
 		if !tabletenv.IsLocalContext(ctx) {


Test patch:
diff --git a/go/test/endtoend/cluster/cluster_process.go b/go/test/endtoend/cluster/cluster_process.go
index f0e1a9a838..c92de019d9 100644
--- a/go/test/endtoend/cluster/cluster_process.go
+++ b/go/test/endtoend/cluster/cluster_process.go
@@ -48,9 +48,6 @@ var (
 	forceVTDATAROOT    = flag.String("force-vtdataroot", "", "force path for VTDATAROOT, which may already be populated")
 	forcePortStart     = flag.Int("force-port-start", 0, "force assigning ports based on this seed")
 	forceBaseTabletUID = flag.Int("force-base-tablet-uid", 0, "force assigning tablet ports based on this seed")
-
-	// PerfTest controls whether to run the slower end-to-end tests that check the system's performance
-	PerfTest = flag.Bool("perf-test", false, "include end-to-end performance tests")
 )
 
 // LocalProcessCluster Testcases need to use this to iniate a cluster
diff --git a/go/test/endtoend/cluster/vtgate_process.go b/go/test/endtoend/cluster/vtgate_process.go
index c7fc39a77d..ed2c287304 100644
--- a/go/test/endtoend/cluster/vtgate_process.go
+++ b/go/test/endtoend/cluster/vtgate_process.go
@@ -203,7 +203,7 @@ func (vtgate *VtgateProcess) TearDown() error {
 		vtgate.proc = nil
 		return nil
 
-	case <-time.After(30 * time.Second):
+	case <-time.After(10 * time.Second):
 		vtgate.proc.Process.Kill()
 		vtgate.proc = nil
 		return <-vtgate.exit
diff --git a/go/test/endtoend/cluster/vttablet_process.go b/go/test/endtoend/cluster/vttablet_process.go
index 42e14d4a98..b6335d9776 100644
--- a/go/test/endtoend/cluster/vttablet_process.go
+++ b/go/test/endtoend/cluster/vttablet_process.go
@@ -18,11 +18,9 @@ limitations under the License.
 package cluster
 
 import (
-	"bufio"
 	"context"
 	"encoding/json"
 	"fmt"
-	"io"
 	"io/ioutil"
 	"net/http"
 	"os"
@@ -31,7 +29,6 @@ import (
 	"reflect"
 	"strings"
 	"syscall"
-	"testing"
 	"time"
 
 	"vitess.io/vitess/go/mysql"
@@ -107,9 +104,6 @@ func (vttablet *VttabletProcess) Setup() (err error) {
 	if *isCoverage {
 		vttablet.proc.Args = append(vttablet.proc.Args, "-test.coverprofile="+getCoveragePath("vttablet.out"))
 	}
-	if *PerfTest {
-		vttablet.proc.Args = append(vttablet.proc.Args, "-pprof", fmt.Sprintf("cpu,waitSig,path=vttablet_pprof_%s", vttablet.Name))
-	}
 
 	if vttablet.SupportsBackup {
 		vttablet.proc.Args = append(vttablet.proc.Args, "-restore_from_backup")
@@ -320,15 +314,11 @@ func (vttablet *VttabletProcess) QueryTablet(query string, keyspace string, useD
 		keyspace = ""
 	}
 	dbParams := NewConnParams(vttablet.DbPort, vttablet.DbPassword, path.Join(vttablet.Directory, "mysql.sock"), keyspace)
-	conn, err := vttablet.conn(&dbParams)
-	if err != nil {
-		return nil, err
-	}
-	defer conn.Close()
-	return executeQuery(conn, query)
+	return executeQuery(dbParams, query)
 }
 
-func (vttablet *VttabletProcess) defaultConn(dbname string) (*mysql.Conn, error) {
+// QueryTabletWithDB lets you execute query on a specific DB in this tablet and get the result
+func (vttablet *VttabletProcess) QueryTabletWithDB(query string, dbname string) (*sqltypes.Result, error) {
 	dbParams := mysql.ConnParams{
 		Uname:      "vt_dba",
 		UnixSocket: path.Join(vttablet.Directory, "mysql.sock"),
@@ -337,26 +327,18 @@ func (vttablet *VttabletProcess) defaultConn(dbname string) (*mysql.Conn, error)
 	if vttablet.DbPassword != "" {
 		dbParams.Pass = vttablet.DbPassword
 	}
-	return vttablet.conn(&dbParams)
+	return executeQuery(dbParams, query)
 }
 
-func (vttablet *VttabletProcess) conn(dbParams *mysql.ConnParams) (*mysql.Conn, error) {
+func executeQuery(dbParams mysql.ConnParams, query string) (*sqltypes.Result, error) {
 	ctx := context.Background()
-	return mysql.Connect(ctx, dbParams)
-}
-
-// QueryTabletWithDB lets you execute query on a specific DB in this tablet and get the result
-func (vttablet *VttabletProcess) QueryTabletWithDB(query string, dbname string) (*sqltypes.Result, error) {
-	conn, err := vttablet.defaultConn(dbname)
+	dbConn, err := mysql.Connect(ctx, &dbParams)
 	if err != nil {
 		return nil, err
 	}
-	defer conn.Close()
-	return executeQuery(conn, query)
-}
-
-func executeQuery(dbConn *mysql.Conn, query string) (*sqltypes.Result, error) {
-	return dbConn.ExecuteFetch(query, 10000, true)
+	defer dbConn.Close()
+	qr, err := dbConn.ExecuteFetch(query, 10000, true)
+	return qr, err
 }
 
 // GetDBVar returns first matching database variable's value
@@ -380,91 +362,6 @@ func (vttablet *VttabletProcess) getDBSystemValues(placeholder string, value str
 	return "", nil
 }
 
-// ToggleProfiling enables or disables the configured CPU profiler on this vttablet
-func (vttablet *VttabletProcess) ToggleProfiling() error {
-	return vttablet.proc.Process.Signal(syscall.SIGUSR1)
-}
-
-// WaitForVReplicationToCatchup waits for "workflow" to finish copying
-func (vttablet *VttabletProcess) WaitForVReplicationToCatchup(t testing.TB, workflow, database string, duration time.Duration) {
-	queries := [3]string{
-		fmt.Sprintf(`select count(*) from _vt.vreplication where workflow = "%s" and db_name = "%s" and pos = ''`, workflow, database),
-		"select count(*) from information_schema.tables where table_schema='_vt' and table_name='copy_state' limit 1;",
-		fmt.Sprintf(`select count(*) from _vt.copy_state where vrepl_id in (select id from _vt.vreplication where workflow = "%s" and db_name = "%s" )`, workflow, database),
-	}
-	results := [3]string{"[INT64(0)]", "[INT64(1)]", "[INT64(0)]"}
-
-	conn, err := vttablet.defaultConn("")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer conn.Close()
-
-	var lastChecked time.Time
-	for ind, query := range queries {
-		waitDuration := 500 * time.Millisecond
-		for duration > 0 {
-			t.Logf("Executing query %s on %s", query, vttablet.Name)
-			lastChecked = time.Now()
-			qr, err := conn.ExecuteFetch(query, 1000, true)
-			if err != nil {
-				t.Fatal(err)
-			}
-			if qr != nil && qr.Rows != nil && len(qr.Rows) > 0 && fmt.Sprintf("%v", qr.Rows[0]) == string(results[ind]) {
-				break
-			} else {
-				t.Logf("In WaitForVReplicationToCatchup: %s %+v", query, qr.Rows)
-			}
-			time.Sleep(waitDuration)
-			duration -= waitDuration
-		}
-		if duration <= 0 {
-			t.Fatalf("WaitForVReplicationToCatchup timed out for workflow %s, keyspace %s", workflow, database)
-		}
-	}
-	t.Logf("WaitForVReplicationToCatchup succeeded at %v", lastChecked)
-}
-
-// BulkLoad performs a bulk load of rows into a given vttablet.
-func (vttablet *VttabletProcess) BulkLoad(t testing.TB, db, table string, bulkInsert func(io.Writer)) {
-	tmpbulk, err := ioutil.TempFile(path.Join(vttablet.Directory, "tmp"), "bulk_load")
-	if err != nil {
-		t.Fatalf("failed to create tmp file for loading: %v", err)
-	}
-	defer os.Remove(tmpbulk.Name())
-
-	t.Logf("create temporary file for bulk loading %q", tmpbulk.Name())
-	bufStart := time.Now()
-
-	bulkBuffer := bufio.NewWriter(tmpbulk)
-	bulkInsert(bulkBuffer)
-	bulkBuffer.Flush()
-
-	pos, _ := tmpbulk.Seek(0, 1)
-	bufFinish := time.Now()
-	t.Logf("bulk loading %d bytes from %q...", pos, tmpbulk.Name())
-
-	if err := tmpbulk.Close(); err != nil {
-		t.Fatal(err)
-	}
-
-	conn, err := vttablet.defaultConn("vt_" + db)
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer conn.Close()
-
-	query := fmt.Sprintf("LOAD DATA INFILE '%s' INTO TABLE `%s` FIELDS TERMINATED BY ',' ENCLOSED BY '\"'", tmpbulk.Name(), table)
-	_, err = conn.ExecuteFetch(query, 1, false)
-	if err != nil {
-		t.Fatal(err)
-	}
-
-	end := time.Now()
-	t.Logf("bulk insert successful (write tmp file = %v, mysql bulk load = %v, total = %v",
-		bufFinish.Sub(bufStart), end.Sub(bufFinish), end.Sub(bufStart))
-}
-
 // VttabletProcessInstance returns a VttabletProcess handle for vttablet process
 // configured with the given Config.
 // The process must be manually started by calling setup()
diff --git a/go/test/endtoend/vreplication/cluster.go b/go/test/endtoend/vreplication/cluster.go
index e0f41b84bd..0d26fac77d 100644
--- a/go/test/endtoend/vreplication/cluster.go
+++ b/go/test/endtoend/vreplication/cluster.go
@@ -1,6 +1,8 @@
 package vreplication
 
 import (
+	"context"
+	"errors"
 	"fmt"
 	"math/rand"
 	"os"
@@ -12,6 +14,8 @@ import (
 
 	"github.com/stretchr/testify/require"
 
+	"vitess.io/vitess/go/mysql"
+	"vitess.io/vitess/go/sqltypes"
 	"vitess.io/vitess/go/test/endtoend/cluster"
 	"vitess.io/vitess/go/vt/log"
 )
@@ -207,7 +211,7 @@ func (vc *VitessCluster) AddKeyspace(t *testing.T, cells []*Cell, ksName string,
 	keyspace.VSchema = vschema
 	for _, cell := range cells {
 		if len(cell.Vtgates) == 0 {
-			t.Logf("Starting vtgate")
+			fmt.Println("Starting vtgate")
 			vc.StartVtgate(t, cell, cellsToWatch)
 		}
 	}
@@ -216,7 +220,7 @@ func (vc *VitessCluster) AddKeyspace(t *testing.T, cells []*Cell, ksName string,
 }
 
 // AddTablet creates new tablet with specified attributes
-func (vc *VitessCluster) AddTablet(t testing.TB, cell *Cell, keyspace *Keyspace, shard *Shard, tabletType string, tabletID int) (*Tablet, *exec.Cmd, error) {
+func (vc *VitessCluster) AddTablet(t *testing.T, cell *Cell, keyspace *Keyspace, shard *Shard, tabletType string, tabletID int) (*Tablet, *exec.Cmd, error) {
 	tablet := &Tablet{}
 
 	vttablet := cluster.VttabletProcessInstance(
@@ -259,9 +263,9 @@ func (vc *VitessCluster) AddTablet(t testing.TB, cell *Cell, keyspace *Keyspace,
 }
 
 // AddShards creates shards given list of comma-separated keys with specified tablets in each shard
-func (vc *VitessCluster) AddShards(t testing.TB, cells []*Cell, keyspace *Keyspace, names string, numReplicas int, numRdonly int, tabletIDBase int) error {
+func (vc *VitessCluster) AddShards(t *testing.T, cells []*Cell, keyspace *Keyspace, names string, numReplicas int, numRdonly int, tabletIDBase int) error {
 	arrNames := strings.Split(names, ",")
-	t.Logf("Addshards got %d shards with %+v", len(arrNames), arrNames)
+	fmt.Printf("Addshards got %d shards with %+v\n", len(arrNames), arrNames)
 	isSharded := len(arrNames) > 1
 	masterTabletUID := 0
 	for ind, shardName := range arrNames {
@@ -269,9 +273,9 @@ func (vc *VitessCluster) AddShards(t testing.TB, cells []*Cell, keyspace *Keyspa
 		tabletIndex := 0
 		shard := &Shard{Name: shardName, IsSharded: isSharded, Tablets: make(map[string]*Tablet, 1)}
 		if _, ok := keyspace.Shards[shardName]; ok {
-			t.Logf("Shard %s already exists, not adding", shardName)
+			fmt.Printf("Shard %s already exists, not adding\n", shardName)
 		} else {
-			t.Logf("Adding Shard %s", shardName)
+			fmt.Printf("Adding Shard %s\n", shardName)
 			if err := vc.VtctlClient.ExecuteCommand("CreateShard", keyspace.Name+"/"+shardName); err != nil {
 				t.Fatalf("CreateShard command failed with %+v\n", err)
 			}
@@ -282,7 +286,7 @@ func (vc *VitessCluster) AddShards(t testing.TB, cells []*Cell, keyspace *Keyspa
 			tablets := make([]*Tablet, 0)
 			if i == 0 {
 				// only add master tablet for first cell, so first time CreateShard is called
-				t.Logf("Adding Master tablet")
+				fmt.Println("Adding Master tablet")
 				master, proc, err := vc.AddTablet(t, cell, keyspace, shard, "replica", tabletID+tabletIndex)
 				require.NoError(t, err)
 				require.NotNil(t, master)
@@ -294,7 +298,7 @@ func (vc *VitessCluster) AddShards(t testing.TB, cells []*Cell, keyspace *Keyspa
 			}
 
 			for i := 0; i < numReplicas; i++ {
-				t.Logf("Adding Replica tablet")
+				fmt.Println("Adding Replica tablet")
 				tablet, proc, err := vc.AddTablet(t, cell, keyspace, shard, "replica", tabletID+tabletIndex)
 				require.NoError(t, err)
 				require.NotNil(t, tablet)
@@ -303,7 +307,7 @@ func (vc *VitessCluster) AddShards(t testing.TB, cells []*Cell, keyspace *Keyspa
 				dbProcesses = append(dbProcesses, proc)
 			}
 			for i := 0; i < numRdonly; i++ {
-				t.Logf("Adding RdOnly tablet")
+				fmt.Println("Adding RdOnly tablet")
 				tablet, proc, err := vc.AddTablet(t, cell, keyspace, shard, "rdonly", tabletID+tabletIndex)
 				require.NoError(t, err)
 				require.NotNil(t, tablet)
@@ -313,40 +317,40 @@ func (vc *VitessCluster) AddShards(t testing.TB, cells []*Cell, keyspace *Keyspa
 			}
 
 			for ind, proc := range dbProcesses {
-				t.Logf("Waiting for mysql process for tablet %s", tablets[ind].Name)
+				fmt.Printf("Waiting for mysql process for tablet %s\n", tablets[ind].Name)
 				if err := proc.Wait(); err != nil {
 					t.Fatalf("%v :: Unable to start mysql server for %v", err, tablets[ind].Vttablet)
 				}
 			}
 			for ind, tablet := range tablets {
-				t.Logf("Creating vt_keyspace database for tablet %s", tablets[ind].Name)
+				fmt.Printf("Creating vt_keyspace database for tablet %s\n", tablets[ind].Name)
 				if _, err := tablet.Vttablet.QueryTablet(fmt.Sprintf("create database vt_%s", keyspace.Name),
 					keyspace.Name, false); err != nil {
 					t.Fatalf("Unable to start create database vt_%s for tablet %v", keyspace.Name, tablet.Vttablet)
 				}
-				t.Logf("Running Setup() for vttablet %s", tablets[ind].Name)
+				fmt.Printf("Running Setup() for vttablet %s\n", tablets[ind].Name)
 				if err := tablet.Vttablet.Setup(); err != nil {
 					t.Fatalf(err.Error())
 				}
 			}
 		}
 		require.NotEqual(t, 0, masterTabletUID, "Should have created a master tablet")
-		t.Logf("InitShardMaster for %d", masterTabletUID)
+		fmt.Printf("InitShardMaster for %d\n", masterTabletUID)
 		require.NoError(t, vc.VtctlClient.InitShardMaster(keyspace.Name, shardName, cells[0].Name, masterTabletUID))
-		t.Logf("Finished creating shard %s", shard.Name)
+		fmt.Printf("Finished creating shard %s\n", shard.Name)
 	}
 	return nil
 }
 
 // DeleteShard deletes a shard
-func (vc *VitessCluster) DeleteShard(t testing.TB, cellName string, ksName string, shardName string) {
+func (vc *VitessCluster) DeleteShard(t *testing.T, cellName string, ksName string, shardName string) {
 	shard := vc.Cells[cellName].Keyspaces[ksName].Shards[shardName]
 	require.NotNil(t, shard)
 	for _, tab := range shard.Tablets {
-		t.Logf("Shutting down tablet %s", tab.Name)
+		fmt.Printf("Shutting down tablet %s\n", tab.Name)
 		tab.Vttablet.TearDown()
 	}
-	t.Logf("Deleting Shard %s", shardName)
+	fmt.Printf("Deleting Shard %s\n", shardName)
 	//TODO how can we avoid the use of even_if_serving?
 	if output, err := vc.VtctlClient.ExecuteCommandWithOutput("DeleteShard", "-recursive", "-even_if_serving", ksName+"/"+shardName); err != nil {
 		t.Fatalf("DeleteShard command failed with error %+v and output %s\n", err, output)
@@ -355,7 +359,7 @@ func (vc *VitessCluster) DeleteShard(t testing.TB, cellName string, ksName strin
 }
 
 // StartVtgate starts a vtgate process
-func (vc *VitessCluster) StartVtgate(t testing.TB, cell *Cell, cellsToWatch string) {
+func (vc *VitessCluster) StartVtgate(t *testing.T, cell *Cell, cellsToWatch string) {
 	vtgate := cluster.VtgateProcessInstance(
 		vc.ClusterConfig.vtgatePort,
 		vc.ClusterConfig.vtgateGrpcPort,
@@ -375,14 +379,14 @@ func (vc *VitessCluster) StartVtgate(t testing.TB, cell *Cell, cellsToWatch stri
 }
 
 // AddCell adds a new cell to the cluster
-func (vc *VitessCluster) AddCell(t testing.TB, name string) (*Cell, error) {
+func (vc *VitessCluster) AddCell(t *testing.T, name string) (*Cell, error) {
 	cell := &Cell{Name: name, Keyspaces: make(map[string]*Keyspace), Vtgates: make([]*cluster.VtgateProcess, 0)}
 	vc.Cells[name] = cell
 	return cell, nil
 }
 
 // TearDown brings down a cluster, deleting processes, removing topo keys
-func (vc *VitessCluster) TearDown(t testing.TB) {
+func (vc *VitessCluster) TearDown() {
 	for _, cell := range vc.Cells {
 		for _, vtgate := range cell.Vtgates {
 			if err := vtgate.TearDown(); err != nil {
@@ -396,12 +400,12 @@ func (vc *VitessCluster) TearDown(t testing.TB) {
 				for _, tablet := range shard.Tablets {
 					if tablet.DbServer != nil && tablet.DbServer.TabletUID > 0 {
 						if _, err := tablet.DbServer.StopProcess(); err != nil {
-							t.Logf("Error stopping mysql process: %s", err.Error())
+							log.Errorf("Error stopping mysql process: %s", err.Error())
 						}
 					}
-					t.Logf("Stopping vttablet %s", tablet.Name)
+					fmt.Printf("Stopping vttablet %s\n", tablet.Name)
 					if err := tablet.Vttablet.TearDown(); err != nil {
-						t.Logf("Stopped vttablet %s %s", tablet.Name, err.Error())
+						fmt.Printf("Stopped vttablet %s %s\n", tablet.Name, err.Error())
 					}
 				}
 			}
@@ -409,23 +413,73 @@ func (vc *VitessCluster) TearDown(t testing.TB) {
 	}
 
 	if err := vc.Vtctld.TearDown(); err != nil {
-		t.Logf("Error stopping Vtctld:  %s", err.Error())
+		fmt.Printf("Error stopping Vtctld:  %s\n", err.Error())
 	}
 
 	for _, cell := range vc.Cells {
 		if err := vc.Topo.TearDown(cell.Name, originalVtdataroot, vtdataroot, false, "etcd2"); err != nil {
-			t.Logf("Error in etcd teardown - %s", err.Error())
+			fmt.Printf("Error in etcd teardown - %s\n", err.Error())
 		}
 	}
 }
 
+// WaitForVReplicationToCatchup waits for "workflow" to finish copying
+func (vc *VitessCluster) WaitForVReplicationToCatchup(vttablet *cluster.VttabletProcess, workflow string, database string, duration time.Duration) error {
+	queries := [3]string{
+		fmt.Sprintf(`select count(*) from _vt.vreplication where workflow = "%s" and db_name = "%s" and pos = ''`, workflow, database),
+		"select count(*) from information_schema.tables where table_schema='_vt' and table_name='copy_state' limit 1;",
+		fmt.Sprintf(`select count(*) from _vt.copy_state where vrepl_id in (select id from _vt.vreplication where workflow = "%s" and db_name = "%s" )`, workflow, database),
+	}
+	results := [3]string{"[INT64(0)]", "[INT64(1)]", "[INT64(0)]"}
+	var lastChecked time.Time
+	for ind, query := range queries {
+		waitDuration := 500 * time.Millisecond
+		for duration > 0 {
+			fmt.Printf("Executing query %s on %s\n", query, vttablet.Name)
+			lastChecked = time.Now()
+			qr, err := vc.execTabletQuery(vttablet, query)
+			if err != nil {
+				return err
+			}
+			if qr != nil && qr.Rows != nil && len(qr.Rows) > 0 && fmt.Sprintf("%v", qr.Rows[0]) == string(results[ind]) {
+				break
+			} else {
+				fmt.Printf("In WaitForVReplicationToCatchup: %s %+v\n", query, qr.Rows)
+			}
+			time.Sleep(waitDuration)
+			duration -= waitDuration
+		}
+		if duration <= 0 {
+			fmt.Printf("WaitForVReplicationToCatchup timed out for workflow %s, keyspace %s\n", workflow, database)
+			return errors.New("WaitForVReplicationToCatchup timed out")
+		}
+	}
+	fmt.Printf("WaitForVReplicationToCatchup succeeded at %v\n", lastChecked)
+	return nil
+}
+
+func (vc *VitessCluster) execTabletQuery(vttablet *cluster.VttabletProcess, query string) (*sqltypes.Result, error) {
+	vtParams := mysql.ConnParams{
+		UnixSocket: fmt.Sprintf("%s/mysql.sock", vttablet.Directory),
+		Uname:      "vt_dba",
+	}
+	ctx := context.Background()
+	var conn *mysql.Conn
+	conn, err := mysql.Connect(ctx, &vtParams)
+	if err != nil {
+		return nil, err
+	}
+	qr, err := conn.ExecuteFetch(query, 1000, true)
+	return qr, err
+}
+
 func (vc *VitessCluster) getVttabletsInKeyspace(t *testing.T, cell *Cell, ksName string, tabletType string) map[string]*cluster.VttabletProcess {
 	keyspace := cell.Keyspaces[ksName]
 	tablets := make(map[string]*cluster.VttabletProcess)
 	for _, shard := range keyspace.Shards {
 		for _, tablet := range shard.Tablets {
 			if tablet.Vttablet.GetTabletStatus() == "SERVING" && strings.EqualFold(tablet.Vttablet.VreplicationTabletType, tabletType) {
-				t.Logf("Serving status of tablet %s is %s, %s", tablet.Name, tablet.Vttablet.ServingStatus, tablet.Vttablet.GetTabletStatus())
+				fmt.Printf("Serving status of tablet %s is %s, %s\n", tablet.Name, tablet.Vttablet.ServingStatus, tablet.Vttablet.GetTabletStatus())
 				tablets[tablet.Name] = tablet.Vttablet
 			}
 		}
diff --git a/go/test/endtoend/vreplication/migrate_test.go b/go/test/endtoend/vreplication/migrate_test.go
index e9b26ca64f..d327f39788 100644
--- a/go/test/endtoend/vreplication/migrate_test.go
+++ b/go/test/endtoend/vreplication/migrate_test.go
@@ -52,7 +52,7 @@ func TestMigrate(t *testing.T) {
 	require.NotNil(t, vc)
 	defaultReplicas = 0
 	defaultRdonly = 0
-	defer vc.TearDown(t)
+	defer vc.TearDown()
 
 	defaultCell = vc.Cells[defaultCellName]
 	vc.AddKeyspace(t, []*Cell{defaultCell}, "product", "0", initialProductVSchema, initialProductSchema, defaultReplicas, defaultRdonly, 100)
@@ -70,7 +70,7 @@ func TestMigrate(t *testing.T) {
 	extCells := []string{extCell}
 	extVc := NewVitessCluster(t, "TestMigrateExternal", extCells, externalClusterConfig)
 	require.NotNil(t, extVc)
-	defer extVc.TearDown(t)
+	defer extVc.TearDown()
 
 	extCell2 := extVc.Cells[extCell]
 	extVc.AddKeyspace(t, []*Cell{extCell2}, "rating", "0", initialExternalVSchema, initialExternalSchema, 0, 0, 1000)
diff --git a/go/test/endtoend/vreplication/performance_test.go b/go/test/endtoend/vreplication/performance_test.go
deleted file mode 100644
index 435690d93b..0000000000
--- a/go/test/endtoend/vreplication/performance_test.go
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
-Copyright 2021 The Vitess Authors.
-
-Licensed 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 vreplication
-
-import (
-	"fmt"
-	"io"
-	"testing"
-	"time"
-
-	"vitess.io/vitess/go/test/endtoend/cluster"
-
-	"github.com/stretchr/testify/require"
-)
-
-func TestReplicationStress(t *testing.T) {
-	if !*cluster.PerfTest {
-		t.Skip("performance tests disabled")
-	}
-
-	const initialStressVSchema = `
-{
-  "tables": {
-	"largebin": {},
-	"customer": {}
-  }
-}
-`
-	const initialStressSchema = `
-create table largebin(pid int, maindata varbinary(4096), primary key(pid));
-create table customer(cid int, name varbinary(128), meta json default null, typ enum('individual','soho','enterprise'), sport set('football','cricket','baseball'),ts timestamp not null default current_timestamp, primary key(cid))  CHARSET=utf8mb4;
-`
-
-	const defaultCellName = "zone1"
-
-	const sourceKs = "stress_src"
-	const targetKs = "stress_tgt"
-
-	allCells := []string{defaultCellName}
-	allCellNames = defaultCellName
-
-	vc = NewVitessCluster(t, "TestReplicationStress", allCells, mainClusterConfig)
-	require.NotNil(t, vc)
-
-	defer vc.TearDown(t)
-
-	defaultCell = vc.Cells[defaultCellName]
-	vc.AddKeyspace(t, []*Cell{defaultCell}, sourceKs, "0", initialStressVSchema, initialStressSchema, 0, 0, 100)
-	vtgate = defaultCell.Vtgates[0]
-	require.NotNil(t, vtgate)
-
-	vtgate.WaitForStatusOfTabletInShard(fmt.Sprintf("%s.%s.master", "product", "0"), 1)
-
-	vtgateConn = getConnection(t, vc.ClusterConfig.hostname, vc.ClusterConfig.vtgateMySQLPort)
-	defer vtgateConn.Close()
-
-	verifyClusterHealth(t, vc)
-
-	const insertCount = 16 * 1024 * 1024
-
-	tablet := defaultCell.Keyspaces[sourceKs].Shards["0"].Tablets["zone1-100"].Vttablet
-	tablet.BulkLoad(t, "stress_src", "largebin", func(w io.Writer) {
-		for i := 0; i < insertCount; i++ {
-			fmt.Fprintf(w, "\"%d\",%q\n", i, "foobar")
-		}
-	})
-
-	validateCount(t, vtgateConn, "stress_src:0", "largebin", insertCount)
-
-	t.Logf("creating new keysepace '%s'", targetKs)
-	vc.AddKeyspace(t, []*Cell{defaultCell}, targetKs, "0", initialStressVSchema, initialStressSchema, 0, 0, 200)
-	validateCount(t, vtgateConn, "stress_tgt:0", "largebin", 0)
-
-	t.Logf("moving 'largebin' table...")
-	moveStart := time.Now()
-
-	for _, ks := range defaultCell.Keyspaces {
-		for _, shard := range ks.Shards {
-			for _, tablet := range shard.Tablets {
-				tablet.Vttablet.ToggleProfiling()
-			}
-		}
-	}
-
-	moveTables(t, defaultCell.Name, "stress_workflow", sourceKs, targetKs, "largebin")
-
-	keyspaceTgt := defaultCell.Keyspaces[targetKs]
-	for _, shard := range keyspaceTgt.Shards {
-		for _, tablet := range shard.Tablets {
-			t.Logf("catchup shard=%v, tablet=%v", shard.Name, tablet.Name)
-			tablet.Vttablet.WaitForVReplicationToCatchup(t, "stress_workflow", fmt.Sprintf("vt_%s", tablet.Vttablet.Keyspace), 5*time.Minute)
-		}
-	}
-
-	for _, ks := range defaultCell.Keyspaces {
-		for _, shard := range ks.Shards {
-			for _, tablet := range shard.Tablets {
-				tablet.Vttablet.ToggleProfiling()
-			}
-		}
-	}
-
-	t.Logf("finished catching up after MoveTables (%v)", time.Since(moveStart))
-	validateCount(t, vtgateConn, "stress_tgt:0", "largebin", insertCount)
-}
diff --git a/go/test/endtoend/vreplication/resharding_workflows_v2_test.go b/go/test/endtoend/vreplication/resharding_workflows_v2_test.go
index 34f10e392a..cb189b8867 100644
--- a/go/test/endtoend/vreplication/resharding_workflows_v2_test.go
+++ b/go/test/endtoend/vreplication/resharding_workflows_v2_test.go
@@ -233,7 +233,7 @@ func getCurrentState(t *testing.T) string {
 func TestBasicV2Workflows(t *testing.T) {
 	vc = setupCluster(t)
 	defer vtgateConn.Close()
-	defer vc.TearDown(t)
+	defer vc.TearDown()
 
 	testMoveTablesV2Workflow(t)
 	testReshardV2Workflow(t)
@@ -438,7 +438,7 @@ func setupCustomerKeyspace(t *testing.T) {
 
 func TestSwitchReadsWritesInAnyOrder(t *testing.T) {
 	vc = setupCluster(t)
-	defer vc.TearDown(t)
+	defer vc.TearDown()
 	moveCustomerTableSwitchFlows(t, []*Cell{vc.Cells["zone1"]}, "zone1")
 }
 
diff --git a/go/test/endtoend/vreplication/vreplication_test.go b/go/test/endtoend/vreplication/vreplication_test.go
index 8fb71792d3..dfdb39d7af 100644
--- a/go/test/endtoend/vreplication/vreplication_test.go
+++ b/go/test/endtoend/vreplication/vreplication_test.go
@@ -93,7 +93,7 @@ func TestBasicVreplicationWorkflow(t *testing.T) {
 	defaultReplicas = 0 // because of CI resource constraints we can only run this test with master tablets
 	defer func() { defaultReplicas = 1 }()
 
-	defer vc.TearDown(t)
+	defer vc.TearDown()
 
 	defaultCell = vc.Cells[defaultCellName]
 	vc.AddKeyspace(t, []*Cell{defaultCell}, "product", "0", initialProductVSchema, initialProductSchema, defaultReplicas, defaultRdonly, 100)
@@ -140,7 +140,7 @@ func TestMultiCellVreplicationWorkflow(t *testing.T) {
 	defaultCellName := "zone1"
 	defaultCell = vc.Cells[defaultCellName]
 
-	defer vc.TearDown(t)
+	defer vc.TearDown()
 
 	cell1 := vc.Cells["zone1"]
 	cell2 := vc.Cells["zone2"]
@@ -167,7 +167,7 @@ func TestCellAliasVreplicationWorkflow(t *testing.T) {
 	defaultCellName := "zone1"
 	defaultCell = vc.Cells[defaultCellName]
 
-	defer vc.TearDown(t)
+	defer vc.TearDown()
 
 	cell1 := vc.Cells["zone1"]
 	cell2 := vc.Cells["zone2"]
@@ -191,12 +191,12 @@ func TestCellAliasVreplicationWorkflow(t *testing.T) {
 
 func insertInitialData(t *testing.T) {
 	t.Run("insertInitialData", func(t *testing.T) {
-		t.Logf("Inserting initial data")
+		fmt.Printf("Inserting initial data\n")
 		lines, _ := ioutil.ReadFile("unsharded_init_data.sql")
 		execMultipleQueries(t, vtgateConn, "product:0", string(lines))
 		execVtgateQuery(t, vtgateConn, "product:0", "insert into customer_seq(id, next_id, cache) values(0, 100, 100);")
 		execVtgateQuery(t, vtgateConn, "product:0", "insert into order_seq(id, next_id, cache) values(0, 100, 100);")
-		t.Logf("Done inserting initial data")
+		fmt.Printf("Done inserting initial data\n")
 
 		validateCount(t, vtgateConn, "product:0", "product", 2)
 		validateCount(t, vtgateConn, "product:0", "customer", 3)
@@ -472,10 +472,10 @@ func reshard(t *testing.T, ksName string, tableName string, workflow string, sou
 		targetShards = "," + targetShards + ","
 		for _, tab := range tablets {
 			if strings.Contains(targetShards, ","+tab.Shard+",") {
-				t.Logf("Waiting for vrepl to catch up on %s since it IS a target shard", tab.Shard)
+				fmt.Printf("Waiting for vrepl to catch up on %s since it IS a target shard\n", tab.Shard)
 				catchup(t, tab, workflow, "Reshard")
 			} else {
-				t.Logf("Not waiting for vrepl to catch up on %s since it is NOT a target shard", tab.Shard)
+				fmt.Printf("Not waiting for vrepl to catch up on %s since it is NOT a target shard\n", tab.Shard)
 				continue
 			}
 		}
@@ -560,7 +560,7 @@ func shardMerchant(t *testing.T) {
 func vdiff(t *testing.T, workflow, cells string) {
 	t.Run("vdiff", func(t *testing.T) {
 		output, err := vc.VtctlClient.ExecuteCommandWithOutput("VDiff", "-tablet_types=master", "-source_cell="+cells, "-format", "json", workflow)
-		t.Logf("vdiff err: %+v, output: %+v", err, output)
+		fmt.Printf("vdiff err: %+v, output: %+v\n", err, output)
 		require.Nil(t, err)
 		require.NotNil(t, output)
 		diffReports := make([]*wrangler.DiffReport, 0)
@@ -803,7 +803,8 @@ func verifyClusterHealth(t *testing.T, cluster *VitessCluster) {
 
 func catchup(t *testing.T, vttablet *cluster.VttabletProcess, workflow, info string) {
 	const MaxWait = 10 * time.Second
-	vttablet.WaitForVReplicationToCatchup(t, workflow, fmt.Sprintf("vt_%s", vttablet.Keyspace), MaxWait)
+	err := vc.WaitForVReplicationToCatchup(vttablet, workflow, fmt.Sprintf("vt_%s", vttablet.Keyspace), MaxWait)
+	require.NoError(t, err, fmt.Sprintf("%s timed out for workflow %s on tablet %s.%s.%s", info, workflow, vttablet.Keyspace, vttablet.Shard, vttablet.Name))
 }
 
 func moveTables(t *testing.T, cell, workflow, sourceKs, targetKs, tables string) {
@@ -842,7 +843,7 @@ func printSwitchWritesExtraDebug(t *testing.T, ksWorkflow, msg string) {
 	// Temporary code: print lots of info for debugging occasional flaky failures in customer reshard in CI for multicell test
 	debug := true
 	if debug {
-		t.Logf("------------------- START Extra debug info %s SwitchWrites %s", msg, ksWorkflow)
+		fmt.Printf("------------------- START Extra debug info %s SwitchWrites %s\n", msg, ksWorkflow)
 		ksShards := []string{"product/0", "customer/-80", "customer/80-"}
 		printShardPositions(vc, ksShards)
 		custKs := vc.Cells[defaultCell.Name].Keyspaces["customer"]
@@ -860,11 +861,11 @@ func printSwitchWritesExtraDebug(t *testing.T, ksWorkflow, msg string) {
 			for _, query := range queries {
 				qr, err := tab.QueryTablet(query, "", false)
 				require.NoError(t, err)
-				t.Logf("\nTablet:%s.%s.%s.%d\nQuery: %s\n%+v\n",
+				fmt.Printf("\nTablet:%s.%s.%s.%d\nQuery: %s\n%+v\n\n",
 					tab.Cell, tab.Keyspace, tab.Shard, tab.TabletUID, query, qr.Rows)
 			}
 		}
-		t.Logf("------------------- END Extra debug info %s SwitchWrites %s", msg, ksWorkflow)
+		fmt.Printf("------------------- END Extra debug info %s SwitchWrites %s\n", msg, ksWorkflow)
 	}
 }
 
diff --git a/go/test/endtoend/vtgate/reservedconn/main_test.go b/go/test/endtoend/vtgate/reservedconn/main_test.go
index ebe133a2c8..e3b5ec7856 100644
--- a/go/test/endtoend/vtgate/reservedconn/main_test.go
+++ b/go/test/endtoend/vtgate/reservedconn/main_test.go
@@ -126,8 +126,10 @@ func TestMain(m *testing.M) {
 		}
 
 		// Start vtgate
-		clusterInstance.VtGateExtraArgs = []string{"-lock_heartbeat_time", "2s", "-enable_system_settings=true"} // enable reserved connection.
-		if err := clusterInstance.StartVtgate(); err != nil {
+		clusterInstance.VtGateExtraArgs = []string{"-lock_heartbeat_time", "2s"}
+		vtgateProcess := clusterInstance.NewVtgateInstance()
+		vtgateProcess.SysVarSetEnabled = true
+		if err := vtgateProcess.Setup(); err != nil {
 			return 1
 		}
 
diff --git a/go/test/endtoend/vtgate/reservedconn/reconnect1/main_test.go b/go/test/endtoend/vtgate/reservedconn/reconnect1/main_test.go
deleted file mode 100644
index 598d23345f..0000000000
--- a/go/test/endtoend/vtgate/reservedconn/reconnect1/main_test.go
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
-Copyright 2021 The Vitess Authors.
-
-Licensed 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 reservedconn
-
-import (
-	"context"
-	"flag"
-	"os"
-	"testing"
-
-	"github.com/stretchr/testify/assert"
-
-	"github.com/stretchr/testify/require"
-
-	"vitess.io/vitess/go/mysql"
-	"vitess.io/vitess/go/sqltypes"
-	"vitess.io/vitess/go/test/endtoend/cluster"
-)
-
-var (
-	clusterInstance *cluster.LocalProcessCluster
-	vtParams        mysql.ConnParams
-	keyspaceName    = "ks"
-	cell            = "zone1"
-	hostname        = "localhost"
-	sqlSchema       = `create table test(id bigint primary key)Engine=InnoDB;`
-
-	vSchema = `
-		{	
-			"sharded":true,
-			"vindexes": {
-				"hash_index": {
-					"type": "hash"
-				}
-			},	
-			"tables": {
-				"test":{
-					"column_vindexes": [
-						{
-							"column": "id",
-							"name": "hash_index"
-						}
-					]
-				}
-			}
-		}
-	`
-)
-
-func TestMain(m *testing.M) {
-	defer cluster.PanicHandler(nil)
-	flag.Parse()
-
-	exitCode := func() int {
-		clusterInstance = cluster.NewCluster(cell, hostname)
-		defer clusterInstance.Teardown()
-
-		// Start topo server
-		if err := clusterInstance.StartTopo(); err != nil {
-			return 1
-		}
-
-		// Start keyspace
-		keyspace := &cluster.Keyspace{
-			Name:      keyspaceName,
-			SchemaSQL: sqlSchema,
-			VSchema:   vSchema,
-		}
-		if err := clusterInstance.StartKeyspace(*keyspace, []string{"-80", "80-"}, 1, true); err != nil {
-			return 1
-		}
-
-		// Start vtgate
-		clusterInstance.VtGateExtraArgs = []string{"-lock_heartbeat_time", "2s", "-enable_system_settings=true"} // enable reserved connection.
-		if err := clusterInstance.StartVtgate(); err != nil {
-			return 1
-		}
-
-		vtParams = mysql.ConnParams{
-			Host: clusterInstance.Hostname,
-			Port: clusterInstance.VtgateMySQLPort,
-		}
-		return m.Run()
-	}()
-	os.Exit(exitCode)
-}
-
-func TestServingChange(t *testing.T) {
-	conn, err := mysql.Connect(context.Background(), &vtParams)
-	require.NoError(t, err)
-	defer conn.Close()
-
-	checkedExec(t, conn, "use @rdonly")
-	checkedExec(t, conn, "set sql_mode = ''")
-
-	// to see rdonly is available and
-	// also this will create reserved connection on rdonly on -80 and 80- shards.
-	_, err = exec(t, conn, "select * from test")
-	for err != nil {
-		_, err = exec(t, conn, "select * from test")
-	}
-
-	// changing rdonly tablet to spare (non serving).
-	rdonlyTablet := clusterInstance.Keyspaces[0].Shards[0].Rdonly()
-	err = clusterInstance.VtctlclientProcess.ExecuteCommand("ChangeTabletType", rdonlyTablet.Alias, "spare")
-	require.NoError(t, err)
-
-	// this should fail as there is no rdonly present
-	_, err = exec(t, conn, "select * from test")
-	require.Error(t, err)
-
-	// changing replica tablet to rdonly to make rdonly available for serving.
-	replicaTablet := clusterInstance.Keyspaces[0].Shards[0].Replica()
-	err = clusterInstance.VtctlclientProcess.ExecuteCommand("ChangeTabletType", replicaTablet.Alias, "rdonly")
-	require.NoError(t, err)
-
-	// to see/make the new rdonly available
-	err = clusterInstance.VtctlclientProcess.ExecuteCommand("Ping", replicaTablet.Alias)
-	require.NoError(t, err)
-
-	// this should pass now as there is rdonly present
-	_, err = exec(t, conn, "select * from test")
-	assert.NoError(t, err)
-}
-
-func exec(t *testing.T, conn *mysql.Conn, query string) (*sqltypes.Result, error) {
-	t.Helper()
-	return conn.ExecuteFetch(query, 1000, true)
-}
-
-func checkedExec(t *testing.T, conn *mysql.Conn, query string) *sqltypes.Result {
-	t.Helper()
-	qr, err := conn.ExecuteFetch(query, 1000, true)
-	require.NoError(t, err)
-	return qr
-}
diff --git a/go/test/endtoend/vtgate/reservedconn/reconnect2/main_test.go b/go/test/endtoend/vtgate/reservedconn/reconnect2/main_test.go
deleted file mode 100644
index 627f203647..0000000000
--- a/go/test/endtoend/vtgate/reservedconn/reconnect2/main_test.go
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
-Copyright 2021 The Vitess Authors.
-
-Licensed 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 reservedconn
-
-import (
-	"context"
-	"flag"
-	"fmt"
-	"os"
-	"testing"
-
-	"github.com/stretchr/testify/assert"
-
-	"github.com/stretchr/testify/require"
-
-	"vitess.io/vitess/go/mysql"
-	"vitess.io/vitess/go/sqltypes"
-	"vitess.io/vitess/go/test/endtoend/cluster"
-)
-
-var (
-	clusterInstance *cluster.LocalProcessCluster
-	vtParams        mysql.ConnParams
-	keyspaceName    = "ks"
-	cell            = "zone1"
-	hostname        = "localhost"
-	sqlSchema       = `create table test(id bigint primary key)Engine=InnoDB;`
-
-	vSchema = `
-		{	
-			"sharded":true,
-			"vindexes": {
-				"hash_index": {
-					"type": "hash"
-				}
-			},	
-			"tables": {
-				"test":{
-					"column_vindexes": [
-						{
-							"column": "id",
-							"name": "hash_index"
-						}
-					]
-				}
-			}
-		}
-	`
-)
-
-func TestMain(m *testing.M) {
-	defer cluster.PanicHandler(nil)
-	flag.Parse()
-
-	exitCode := func() int {
-		clusterInstance = cluster.NewCluster(cell, hostname)
-		defer clusterInstance.Teardown()
-
-		// Start topo server
-		if err := clusterInstance.StartTopo(); err != nil {
-			return 1
-		}
-
-		// Start keyspace
-		keyspace := &cluster.Keyspace{
-			Name:      keyspaceName,
-			SchemaSQL: sqlSchema,
-			VSchema:   vSchema,
-		}
-		clusterInstance.VtTabletExtraArgs = []string{"-queryserver-config-transaction-timeout", "5"}
-		if err := clusterInstance.StartKeyspace(*keyspace, []string{"-80", "80-"}, 1, true); err != nil {
-			return 1
-		}
-
-		// Start vtgate
-		clusterInstance.VtGateExtraArgs = []string{"-lock_heartbeat_time", "2s", "-enable_system_settings=true"} // enable reserved connection.
-		if err := clusterInstance.StartVtgate(); err != nil {
-			return 1
-		}
-
-		vtParams = mysql.ConnParams{
-			Host: clusterInstance.Hostname,
-			Port: clusterInstance.VtgateMySQLPort,
-		}
-		return m.Run()
-	}()
-	os.Exit(exitCode)
-}
-
-func TestTabletChange(t *testing.T) {
-	conn, err := mysql.Connect(context.Background(), &vtParams)
-	require.NoError(t, err)
-	defer conn.Close()
-
-	checkedExec(t, conn, "use @master")
-	checkedExec(t, conn, "set sql_mode = ''")
-
-	// this will create reserved connection on master on -80 and 80- shards.
-	checkedExec(t, conn, "select * from test")
-
-	// Change Master
-	err = clusterInstance.VtctlclientProcess.ExecuteCommand("PlannedReparentShard", "-keyspace_shard", fmt.Sprintf("%s/%s", keyspaceName, "-80"))
-	require.NoError(t, err)
-
-	// this should pass as there is new master tablet and is serving.
-	_, err = exec(t, conn, "select * from test")
-	assert.NoError(t, err)
-}
-
-func exec(t *testing.T, conn *mysql.Conn, query string) (*sqltypes.Result, error) {
-	t.Helper()
-	return conn.ExecuteFetch(query, 1000, true)
-}
-
-func checkedExec(t *testing.T, conn *mysql.Conn, query string) *sqltypes.Result {
-	t.Helper()
-	qr, err := conn.ExecuteFetch(query, 1000, true)
-	require.NoError(t, err)
-	return qr
-}
diff --git a/go/test/endtoend/vtgate/reservedconn/sysvar_test.go b/go/test/endtoend/vtgate/reservedconn/sysvar_test.go
index f14aa287e5..6953178108 100644
--- a/go/test/endtoend/vtgate/reservedconn/sysvar_test.go
+++ b/go/test/endtoend/vtgate/reservedconn/sysvar_test.go
@@ -393,5 +393,5 @@ func TestSysvarSocket(t *testing.T) {
 	require.True(t, ok, "not a mysql error: %T", err)
 	assert.Equal(t, mysql.ERIncorrectGlobalLocalVar, sqlErr.Number())
 	assert.Equal(t, mysql.SSUnknownSQLState, sqlErr.SQLState())
-	assert.Equal(t, "variable 'socket' is a read only variable (errno 1238) (sqlstate HY000) during query: set socket = '/any/path'", sqlErr.Error())
+	assert.Equal(t, "Variable 'socket' is a read only variable (errno 1238) (sqlstate HY000) during query: set socket = '/any/path'", sqlErr.Error())
 }
diff --git a/go/vt/discovery/healthcheck_test.go b/go/vt/discovery/healthcheck_test.go
index 7edc53a4c4..8d856ca794 100644
--- a/go/vt/discovery/healthcheck_test.go
+++ b/go/vt/discovery/healthcheck_test.go
@@ -324,84 +324,6 @@ func TestHealthCheckErrorOnPrimary(t *testing.T) {
 	assert.Empty(t, a, "wrong result, expected empty list")
 }
 
-func TestHealthCheckErrorOnPrimaryAfterExternalReparent(t *testing.T) {
-	ts := memorytopo.NewServer("cell")
-	hc := createTestHc(ts)
-	defer hc.Close()
-
-	resultChan := hc.Subscribe()
-
-	tablet1 := createTestTablet(0, "cell", "a")
-	input1 := make(chan *querypb.StreamHealthResponse)
-	fc1 := createFakeConn(tablet1, input1)
-	fc1.errCh = make(chan error)
-	hc.AddTablet(tablet1)
-	<-resultChan
-
-	tablet2 := createTestTablet(1, "cell", "b")
-	tablet2.Type = topodatapb.TabletType_REPLICA
-	input2 := make(chan *querypb.StreamHealthResponse)
-	createFakeConn(tablet2, input2)
-	hc.AddTablet(tablet2)
-	<-resultChan
-
-	shr2 := &querypb.StreamHealthResponse{
-		TabletAlias:                         tablet2.Alias,
-		Target:                              &querypb.Target{Keyspace: "k", Shard: "s", TabletType: topodatapb.TabletType_REPLICA},
-		Serving:                             true,
-		TabletExternallyReparentedTimestamp: 0,
-		RealtimeStats:                       &querypb.RealtimeStats{SecondsBehindMaster: 10, CpuUsage: 0.2},
-	}
-	input2 <- shr2
-	<-resultChan
-	shr1 := &querypb.StreamHealthResponse{
-		TabletAlias:                         tablet1.Alias,
-		Target:                              &querypb.Target{Keyspace: "k", Shard: "s", TabletType: topodatapb.TabletType_MASTER},
-		Serving:                             true,
-		TabletExternallyReparentedTimestamp: 10,
-		RealtimeStats:                       &querypb.RealtimeStats{SecondsBehindMaster: 0, CpuUsage: 0.2},
-	}
-	input1 <- shr1
-	<-resultChan
-	// tablet 1 is the primary now
-	health := []*TabletHealth{{
-		Tablet:              tablet1,
-		Target:              &querypb.Target{Keyspace: "k", Shard: "s", TabletType: topodatapb.TabletType_MASTER},
-		Serving:             true,
-		Stats:               &querypb.RealtimeStats{SecondsBehindMaster: 0, CpuUsage: 0.2},
-		MasterTermStartTime: 10,
-	}}
-	a := hc.GetHealthyTabletStats(&querypb.Target{Keyspace: "k", Shard: "s", TabletType: topodatapb.TabletType_MASTER})
-	mustMatch(t, health, a, "unexpected result")
-
-	shr2 = &querypb.StreamHealthResponse{
-		TabletAlias:                         tablet2.Alias,
-		Target:                              &querypb.Target{Keyspace: "k", Shard: "s", TabletType: topodatapb.TabletType_MASTER},
-		Serving:                             true,
-		TabletExternallyReparentedTimestamp: 20,
-		RealtimeStats:                       &querypb.RealtimeStats{SecondsBehindMaster: 0, CpuUsage: 0.2},
-	}
-	input2 <- shr2
-	<-resultChan
-	// reparent: tablet 2 is the primary now
-	health = []*TabletHealth{{
-		Tablet:              tablet2,
-		Target:              &querypb.Target{Keyspace: "k", Shard: "s", TabletType: topodatapb.TabletType_MASTER},
-		Serving:             true,
-		Stats:               &querypb.RealtimeStats{SecondsBehindMaster: 0, CpuUsage: 0.2},
-		MasterTermStartTime: 20,
-	}}
-	a = hc.GetHealthyTabletStats(&querypb.Target{Keyspace: "k", Shard: "s", TabletType: topodatapb.TabletType_MASTER})
-	mustMatch(t, health, a, "unexpected result")
-
-	// Stream error from tablet 1
-	fc1.errCh <- fmt.Errorf("some stream error")
-	<-resultChan
-	// tablet 2 should still be the master
-	a = hc.GetHealthyTabletStats(&querypb.Target{Keyspace: "k", Shard: "s", TabletType: topodatapb.TabletType_MASTER})
-	mustMatch(t, health, a, "unexpected result")
-}
-
 func TestHealthCheckVerifiesTabletAlias(t *testing.T) {
 	ts := memorytopo.NewServer("cell")
 	hc := createTestHc(ts)
diff --git a/go/vt/sqlparser/parse_test.go b/go/vt/sqlparser/parse_test.go
index 89f5b349af..937a22265a 100644
--- a/go/vt/sqlparser/parse_test.go
+++ b/go/vt/sqlparser/parse_test.go
@@ -2004,7 +2004,7 @@ func TestInvalid(t *testing.T) {
 		err:   "syntax error",
 	}, {
 		input: "/*!*/",
-		err:   "query was empty",
+		err:   "Query was empty",
 	}}
 
 	for _, tcase := range invalidSQL {
@@ -2316,16 +2316,10 @@ func TestConvert(t *testing.T) {
 		output: "syntax error at position 33",
 	}, {
 		input:  "/* a comment */",
-		output: "query was empty",
+		output: "Query was empty",
 	}, {
 		input:  "set transaction isolation level 12345",
 		output: "syntax error at position 38 near '12345'",
-	}, {
-		input:  "@",
-		output: "syntax error at position 2",
-	}, {
-		input:  "@@",
-		output: "syntax error at position 3",
 	}}
 
 	for _, tcase := range invalidSQL {
diff --git a/go/vt/vtgate/executor_dml_test.go b/go/vt/vtgate/executor_dml_test.go
index 6af655507c..bce657e799 100644
--- a/go/vt/vtgate/executor_dml_test.go
+++ b/go/vt/vtgate/executor_dml_test.go
@@ -1605,7 +1605,7 @@ func TestKeyDestRangeQuery(t *testing.T) {
 	masterSession.TargetString = "TestExecutor[-]"
 	_, err := executorExec(executor, insertInput, nil)
 
-	require.EqualError(t, err, "INSERT not supported when targeting a key range: TestExecutor[-]")
+	require.EqualError(t, err, "range queries are not allowed for insert statement: TestExecutor[-]")
 
 	masterSession.TargetString = ""
 }
diff --git a/go/vt/vtgate/executor_select_test.go b/go/vt/vtgate/executor_select_test.go
index dd345da3c6..f69fc4a9e5 100644
--- a/go/vt/vtgate/executor_select_test.go
+++ b/go/vt/vtgate/executor_select_test.go
@@ -18,10 +18,8 @@ package vtgate
 
 import (
 	"fmt"
-	"runtime"
 	"strings"
 	"testing"
-	"time"
 
 	"vitess.io/vitess/go/cache"
 	"vitess.io/vitess/go/test/utils"
@@ -2338,36 +2336,3 @@ func TestSelectFromInformationSchema(t *testing.T) {
 	require.NoError(t, err)
 	assert.Equal(t, sbc1.StringQueries(), []string{"select * from INFORMATION_SCHEMA.`TABLES` where TABLE_SCHEMA = :__vtschemaname"})
 }
-
-func TestStreamOrderByLimitWithMultipleResults(t *testing.T) {
-	// Special setup: Don't use createLegacyExecutorEnv.
-	cell := "aa"
-	hc := discovery.NewFakeHealthCheck()
-	s := createSandbox("TestExecutor")
-	s.VSchema = executorVSchema
-	getSandbox(KsTestUnsharded).VSchema = unshardedVSchema
-	serv := new(sandboxTopo)
-	resolver := newTestResolver(hc, serv, cell)
-	shards := []string{"-20", "20-40", "40-60", "60-80", "80-a0", "a0-c0", "c0-e0", "e0-"}
-	count := 1
-	for _, shard := range shards {
-		sbc := hc.AddTestTablet(cell, shard, 1, "TestExecutor", shard, topodatapb.TabletType_MASTER, true, 1, nil)
-		sbc.SetResults([]*sqltypes.Result{
-			sqltypes.MakeTestResult(sqltypes.MakeTestFields("id|col|weight_string(id)", "int32|int32|varchar"), fmt.Sprintf("%d|%d|NULL", count, count)),
-			sqltypes.MakeTestResult(sqltypes.MakeTestFields("id|col|weight_string(id)", "int32|int32|varchar"), fmt.Sprintf("%d|%d|NULL", count+10, count)),
-		})
-		count++
-	}
-	executor := NewExecutor(context.Background(), serv, cell, resolver, true, false, testBufferSize, cache.DefaultConfig)
-	before := runtime.NumGoroutine()
-
-	query := "select id, col from user order by id limit 2"
-	gotResult, err := executorStream(executor, query)
-	require.NoError(t, err)
-
-	wantResult := sqltypes.MakeTestResult(sqltypes.MakeTestFields("id|col", "int32|int32"), "1|1", "2|2")
-	utils.MustMatch(t, wantResult, gotResult)
-	// some sleep to close all goroutines.
-	time.Sleep(100 * time.Millisecond)
-	assert.GreaterOrEqual(t, before, runtime.NumGoroutine(), "left open goroutines lingering")
-}
diff --git a/go/vt/vtgate/executor_set_test.go b/go/vt/vtgate/executor_set_test.go
index 47537ab10c..aa177d77cd 100644
--- a/go/vt/vtgate/executor_set_test.go
+++ b/go/vt/vtgate/executor_set_test.go
@@ -89,10 +89,10 @@ func TestExecutorSet(t *testing.T) {
 		out: &vtgatepb.Session{},
 	}, {
 		in:  "set AUTOCOMMIT = 'aa'",
-		err: "variable 'autocommit' can't be set to the value: 'aa' is not a boolean",
+		err: "Variable 'autocommit' can't be set to the value: 'aa' is not a boolean",
 	}, {
 		in:  "set autocommit = 2",
-		err: "variable 'autocommit' can't be set to the value: 2 is not a boolean",
+		err: "Variable 'autocommit' can't be set to the value: 2 is not a boolean",
 	}, {
 		in:  "set client_found_rows = 1",
 		out: &vtgatepb.Session{Autocommit: true, Options: &querypb.ExecuteOptions{ClientFoundRows: true}},
@@ -110,10 +110,10 @@ func TestExecutorSet(t *testing.T) {
 		err: "cannot use scope and @@",
 	}, {
 		in:  "set client_found_rows = 'aa'",
-		err: "variable 'client_found_rows' can't be set to the value: 'aa' is not a boolean",
+		err: "Variable 'client_found_rows' can't be set to the value: 'aa' is not a boolean",
 	}, {
 		in:  "set client_found_rows = 2",
-		err: "variable 'client_found_rows' can't be set to the value: 2 is not a boolean",
+		err: "Variable 'client_found_rows' can't be set to the value: 2 is not a boolean",
 	}, {
 		in:  "set transaction_mode = 'unspecified'",
 		out: &vtgatepb.Session{Autocommit: true, TransactionMode: vtgatepb.TransactionMode_UNSPECIFIED},
@@ -134,7 +134,7 @@ func TestExecutorSet(t *testing.T) {
 		err: "invalid transaction_mode: aa",
 	}, {
 		in:  "set transaction_mode = 1",
-		err: "incorrect argument type to variable 'transaction_mode': INT64",
+		err: "Incorrect argument type to variable 'transaction_mode': INT64",
 	}, {
 		in:  "set workload = 'unspecified'",
 		out: &vtgatepb.Session{Autocommit: true, Options: &querypb.ExecuteOptions{Workload: querypb.ExecuteOptions_UNSPECIFIED}},
@@ -152,7 +152,7 @@ func TestExecutorSet(t *testing.T) {
 		err: "invalid workload: aa",
 	}, {
 		in:  "set workload = 1",
-		err: "incorrect argument type to variable 'workload': INT64",
+		err: "Incorrect argument type to variable 'workload': INT64",
 	}, {
 		in:  "set transaction_mode = 'twopc', autocommit=1",
 		out: &vtgatepb.Session{Autocommit: true, TransactionMode: vtgatepb.TransactionMode_TWOPC},
@@ -164,10 +164,10 @@ func TestExecutorSet(t *testing.T) {
 		out: &vtgatepb.Session{Autocommit: true, Options: &querypb.ExecuteOptions{SqlSelectLimit: 0}},
 	}, {
 		in:  "set sql_select_limit = 'asdfasfd'",
-		err: "incorrect argument type to variable 'sql_select_limit': VARBINARY",
+		err: "Incorrect argument type to variable 'sql_select_limit': VARBINARY",
 	}, {
 		in:  "set autocommit = 1+1",
-		err: "variable 'autocommit' can't be set to the value: 2 is not a boolean",
+		err: "Variable 'autocommit' can't be set to the value: 2 is not a boolean",
 	}, {
 		in:  "set autocommit = 1+0",
 		out: &vtgatepb.Session{Autocommit: true},
@@ -182,7 +182,7 @@ func TestExecutorSet(t *testing.T) {
 		out: &vtgatepb.Session{Autocommit: true},
 	}, {
 		in:  "set names ascii",
-		err: "charset/name ascii is not supported",
+		err: "unexpected value for charset/names: ascii",
 	}, {
 		in:  "set charset utf8",
 		out: &vtgatepb.Session{Autocommit: true},
@@ -191,7 +191,7 @@ func TestExecutorSet(t *testing.T) {
 		out: &vtgatepb.Session{Autocommit: true},
 	}, {
 		in:  "set character set ascii",
-		err: "charset/name ascii is not supported",
+		err: "unexpected value for charset/names: ascii",
 	}, {
 		in:  "set skip_query_plan_cache = 1",
 		out: &vtgatepb.Session{Autocommit: true, Options: &querypb.ExecuteOptions{SkipQueryPlanCache: true}},
@@ -200,10 +200,10 @@ func TestExecutorSet(t *testing.T) {
 		out: &vtgatepb.Session{Autocommit: true, Options: &querypb.ExecuteOptions{}},
 	}, {
 		in:  "set tx_read_only = 2",
-		err: "variable 'tx_read_only' can't be set to the value: 2 is not a boolean",
+		err: "Variable 'tx_read_only' can't be set to the value: 2 is not a boolean",
 	}, {
 		in:  "set transaction_read_only = 2",
-		err: "variable 'transaction_read_only' can't be set to the value: 2 is not a boolean",
+		err: "Variable 'transaction_read_only' can't be set to the value: 2 is not a boolean",
 	}, {
 		in:  "set session transaction isolation level repeatable read",
 		out: &vtgatepb.Session{Autocommit: true},
@@ -248,7 +248,7 @@ func TestExecutorSet(t *testing.T) {
 		out: &vtgatepb.Session{Autocommit: true, EnableSystemSettings: false},
 	}, {
 		in:  "set @@socket = '/tmp/change.sock'",
-		err: "variable 'socket' is a read only variable",
+		err: "Variable 'socket' is a read only variable",
 	}}
 	for i, tcase := range testcases {
 		t.Run(fmt.Sprintf("%d-%s", i, tcase.in), func(t *testing.T) {
diff --git a/go/vt/vtgate/executor_test.go b/go/vt/vtgate/executor_test.go
index 4a38de511f..2f9fd2f80a 100644
--- a/go/vt/vtgate/executor_test.go
+++ b/go/vt/vtgate/executor_test.go
@@ -195,7 +195,7 @@ func TestLegacyExecutorTransactionsNoAutoCommit(t *testing.T) {
 	// Prevent use of non-master if in_transaction is on.
 	session = NewSafeSession(&vtgatepb.Session{TargetString: "@master", InTransaction: true})
 	_, err = executor.Execute(ctx, "TestExecute", session, "use @replica", nil)
-	require.EqualError(t, err, `can't execute the given command because you have an active transaction`)
+	require.EqualError(t, err, `Can't execute the given command because you have an active transaction`)
 }
 
 func TestDirectTargetRewrites(t *testing.T) {
@@ -943,7 +943,10 @@ func TestExecutorUse(t *testing.T) {
 	}
 
 	_, err = executor.Execute(ctx, "TestExecute", NewSafeSession(&vtgatepb.Session{}), "use UnexistentKeyspace", nil)
-	require.EqualError(t, err, "unknown database 'UnexistentKeyspace'")
+	wantErr = "Unknown database 'UnexistentKeyspace'"
+	if err == nil || err.Error() != wantErr {
+		t.Errorf("got: %v, want %v", err, wantErr)
+	}
 }
 
 func TestExecutorComment(t *testing.T) {
@@ -1803,6 +1806,63 @@ func TestDebugVSchema(t *testing.T) {
 	}
 }
 
+func TestGenerateCharsetRows(t *testing.T) {
+	rows := make([][]sqltypes.Value, 0, 4)
+	rows0 := [][]sqltypes.Value{
+		append(buildVarCharRow(
+			"utf8",
+			"UTF-8 Unicode",
+			"utf8_general_ci"),
+			sqltypes.NewInt32(3)),
+	}
+	rows1 := [][]sqltypes.Value{
+		append(buildVarCharRow(
+			"utf8mb4",
+			"UTF-8 Unicode",
+			"utf8mb4_general_ci"),
+			sqltypes.NewInt32(4)),
+	}
+	rows2 := [][]sqltypes.Value{
+		append(buildVarCharRow(
+			"utf8",
+			"UTF-8 Unicode",
+			"utf8_general_ci"),
+			sqltypes.NewInt32(3)),
+		append(buildVarCharRow(
+			"utf8mb4",
+			"UTF-8 Unicode",
+			"utf8mb4_general_ci"),
+			sqltypes.NewInt32(4)),
+	}
+
+	testcases := []struct {
+		input    string
+		expected [][]sqltypes.Value
+	}{
+		{input: "show charset", expected: rows2},
+		{input: "show character set", expected: rows2},
+		{input: "show charset where charset like 'foo%'", expected: rows},
+		{input: "show charset where charset like 'utf8%'", expected: rows0},
+		{input: "show charset where charset = 'utf8'", expected: rows0},
+		{input: "show charset where charset = 'foo%'", expected: rows},
+		{input: "show charset where charset = 'utf8mb4'", expected: rows1},
+	}
+
+	charsets := []string{"utf8", "utf8mb4"}
+
+	for _, tc := range testcases {
+		t.Run(tc.input, func(t *testing.T) {
+			stmt, err := sqlparser.Parse(tc.input)
+			require.NoError(t, err)
+			match := stmt.(*sqlparser.Show).Internal.(*sqlparser.ShowBasic)
+			filter := match.Filter
+			actual, err := generateCharsetRows(filter, charsets)
+			require.NoError(t, err)
+			require.Equal(t, tc.expected, actual)
+		})
+	}
+}
+
 func TestExecutorMaxPayloadSizeExceeded(t *testing.T) {
 	saveMax := *maxPayloadSize
 	saveWarn := *warnPayloadSize
diff --git a/go/vt/vtgate/mysql_protocol_test.go b/go/vt/vtgate/mysql_protocol_test.go
index 8cce6b3c61..33e1a814f5 100644
--- a/go/vt/vtgate/mysql_protocol_test.go
+++ b/go/vt/vtgate/mysql_protocol_test.go
@@ -120,7 +120,7 @@ func TestMySQLProtocolExecuteUseStatement(t *testing.T) {
 	// No such keyspace this will fail
 	_, err = c.ExecuteFetch("use InvalidKeyspace", 0, false)
 	require.Error(t, err)
-	assert.Contains(t, err.Error(), "unknown database 'InvalidKeyspace' (errno 1049) (sqlstate 42000)")
+	assert.Contains(t, err.Error(), "Unknown database 'InvalidKeyspace' (errno 1049) (sqlstate 42000)")
 
 	// That doesn't reset the vitess_target
 	qr, err = c.ExecuteFetch("show vitess_target", 1, false)
@@ -138,7 +138,7 @@ func TestMySQLProtocolExecuteUseStatement(t *testing.T) {
 
 func TestMysqlProtocolInvalidDB(t *testing.T) {
 	_, err := mysqlConnect(&mysql.ConnParams{DbName: "invalidDB"})
-	require.EqualError(t, err, "unknown database 'invalidDB' (errno 1049) (sqlstate 42000)")
+	require.EqualError(t, err, "Unknown database 'invalidDB' (errno 1049) (sqlstate 42000)")
 }
 
 func TestMySQLProtocolClientFoundRows(t *testing.T) {
diff --git a/go/vt/vtgate/planbuilder/show_test.go b/go/vt/vtgate/planbuilder/show_test.go
deleted file mode 100644
index fc614d7026..0000000000
--- a/go/vt/vtgate/planbuilder/show_test.go
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
-Copyright 2021 The Vitess Authors.
-
-Licensed 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 planbuilder
-
-import (
-	"testing"
-
-	"github.com/stretchr/testify/require"
-
-	"vitess.io/vitess/go/sqltypes"
-	"vitess.io/vitess/go/vt/sqlparser"
-)
-
-func TestGenerateCharsetRows(t *testing.T) {
-	rows := make([][]sqltypes.Value, 0, 4)
-	rows0 := [][]sqltypes.Value{
-		append(buildVarCharRow(
-			"utf8",
-			"UTF-8 Unicode",
-			"utf8_general_ci"),
-			sqltypes.NewInt32(3)),
-	}
-	rows1 := [][]sqltypes.Value{
-		append(buildVarCharRow(
-			"utf8mb4",
-			"UTF-8 Unicode",
-			"utf8mb4_general_ci"),
-			sqltypes.NewInt32(4)),
-	}
-	rows2 := [][]sqltypes.Value{
-		append(buildVarCharRow(
-			"utf8",
-			"UTF-8 Unicode",
-			"utf8_general_ci"),
-			sqltypes.NewInt32(3)),
-		append(buildVarCharRow(
-			"utf8mb4",
-			"UTF-8 Unicode",
-			"utf8mb4_general_ci"),
-			sqltypes.NewInt32(4)),
-	}
-
-	testcases := []struct {
-		input    string
-		expected [][]sqltypes.Value
-	}{
-		{input: "show charset", expected: rows2},
-		{input: "show character set", expected: rows2},
-		{input: "show charset where charset like 'foo%'", expected: rows},
-		{input: "show charset where charset like 'utf8%'", expected: rows0},
-		{input: "show charset where charset = 'utf8'", expected: rows0},
-		{input: "show charset where charset = 'foo%'", expected: rows},
-		{input: "show charset where charset = 'utf8mb4'", expected: rows1},
-	}
-
-	charsets := []string{"utf8", "utf8mb4"}
-
-	for _, tc := range testcases {
-		t.Run(tc.input, func(t *testing.T) {
-			stmt, err := sqlparser.Parse(tc.input)
-			require.NoError(t, err)
-			match := stmt.(*sqlparser.Show).Internal.(*sqlparser.ShowBasic)
-			filter := match.Filter
-			actual, err := generateCharsetRows(filter, charsets)
-			require.NoError(t, err)
-			require.Equal(t, tc.expected, actual)
-		})
-	}
-}
diff --git a/go/vt/vtgate/planbuilder/testdata/aggr_cases.txt b/go/vt/vtgate/planbuilder/testdata/aggr_cases.txt
index cec49eeb0a..59d635dc85 100644
--- a/go/vt/vtgate/planbuilder/testdata/aggr_cases.txt
+++ b/go/vt/vtgate/planbuilder/testdata/aggr_cases.txt
@@ -880,7 +880,7 @@ Gen4 plan same as above
 
 # scatter aggregate group by aggregate function
 " select count(*) b from user group by b"
-"Can't group on 'b'"
+"group by expression cannot reference an aggregate function: b"
 
 # scatter aggregate multiple group by (columns)
 "select a, b, count(*) from user group by b, a"
diff --git a/go/vt/vtgate/planbuilder/testdata/set_cases.txt b/go/vt/vtgate/planbuilder/testdata/set_cases.txt
index d691e8162c..3a29de7278 100644
--- a/go/vt/vtgate/planbuilder/testdata/set_cases.txt
+++ b/go/vt/vtgate/planbuilder/testdata/set_cases.txt
@@ -524,5 +524,5 @@ Gen4 plan same as above
 
 # change read only variable
 "set socket = ''"
-"variable 'socket' is a read only variable"
+"Variable 'socket' is a read only variable"
 Gen4 plan same as above
diff --git a/go/vt/vtgate/scatter_conn_test.go b/go/vt/vtgate/scatter_conn_test.go
index 4a5a8dcd8d..5f84a56246 100644
--- a/go/vt/vtgate/scatter_conn_test.go
+++ b/go/vt/vtgate/scatter_conn_test.go
@@ -19,8 +19,6 @@ package vtgate
 import (
 	"testing"
 
-	vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
-
 	"github.com/stretchr/testify/assert"
 
 	"vitess.io/vitess/go/mysql"
@@ -323,68 +321,6 @@ func TestReservedConnFail(t *testing.T) {
 	assert.Equal(t, 2, len(sbc0.Queries), "one for the failed attempt, and one for the retry")
 	require.Equal(t, 1, len(session.ShardSessions))
 	assert.NotEqual(t, oldRId, session.Session.ShardSessions[0].ReservedId, "should have recreated a reserved connection since the last connection was lost")
-	oldRId = session.Session.ShardSessions[0].ReservedId
-
-	sbc0.Queries = nil
-	sbc0.EphemeralShardErr = vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "operation not allowed in state NOT_SERVING during query: query1")
-	_ = executeOnShardsReturnsErr(t, res, keyspace, sc, session, destinations)
-	assert.Equal(t, 2, len(sbc0.Queries), "one for the failed attempt, and one for the retry")
-	require.Equal(t, 1, len(session.ShardSessions))
-	assert.NotEqual(t, oldRId, session.Session.ShardSessions[0].ReservedId, "should have recreated a reserved connection since the last connection was lost")
-	oldRId = session.Session.ShardSessions[0].ReservedId
-
-	sbc0.Queries = nil
-	sbc0.EphemeralShardErr = vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "invalid tablet type: REPLICA, want: MASTER or MASTER")
-	_ = executeOnShardsReturnsErr(t, res, keyspace, sc, session, destinations)
-	assert.Equal(t, 2, len(sbc0.Queries), "one for the failed attempt, and one for the retry")
-	require.Equal(t, 1, len(session.ShardSessions))
-	assert.NotEqual(t, oldRId, session.Session.ShardSessions[0].ReservedId, "should have recreated a reserved connection since the last connection was lost")
-	oldRId = session.Session.ShardSessions[0].ReservedId
-	oldAlias := session.Session.ShardSessions[0].TabletAlias
-
-	// Test Setup
-	tablet0 := sbc0.Tablet()
-	ths := hc.GetHealthyTabletStats(&querypb.Target{
-		Keyspace:   tablet0.GetKeyspace(),
-		Shard:      tablet0.GetShard(),
-		TabletType: tablet0.GetType(),
-	})
-	sbc0Th := ths[0]
-	sbc0Th.Serving = false
-	sbc0Rep := hc.AddTestTablet("aa", "0", 2, keyspace, "0", topodatapb.TabletType_REPLICA, true, 1, nil)
-
-	sbc0.Queries = nil
-	_ = executeOnShardsReturnsErr(t, res, keyspace, sc, session, destinations)
-	assert.Equal(t, 0, len(sbc0.Queries), "no attempt should be made as the tablet is not serving")
-	assert.Equal(t, 1, len(sbc0Rep.Queries), "first attempt should pass as it is healthy")
-	require.Equal(t, 1, len(session.ShardSessions))
-	assert.NotEqual(t, oldRId, session.Session.ShardSessions[0].ReservedId, "should have recreated a reserved connection since the last connection was lost")
-	assert.NotEqual(t, oldAlias, session.Session.ShardSessions[0].TabletAlias, "tablet alias should have changed as this is a different tablet")
-	oldRId = session.Session.ShardSessions[0].ReservedId
-	oldAlias = session.Session.ShardSessions[0].TabletAlias
-
-	// Test Setup
-	tablet0Rep := sbc0Rep.Tablet()
-	newThs := hc.GetHealthyTabletStats(&querypb.Target{
-		Keyspace:   tablet0Rep.GetKeyspace(),
-		Shard:      tablet0Rep.GetShard(),
-		TabletType: tablet0Rep.GetType(),
-	})
-	sbc0RepTh := newThs[0]
-	sbc0RepTh.Target = &querypb.Target{
-		Keyspace:   tablet0Rep.GetKeyspace(),
-		Shard:      tablet0Rep.GetShard(),
-		TabletType: topodatapb.TabletType_SPARE,
-	}
-	sbc0Th.Serving = true
-
-	sbc0Rep.Queries = nil
-	_ = executeOnShardsReturnsErr(t, res, keyspace, sc, session, destinations)
-	assert.Equal(t, 1, len(sbc0.Queries), "first attempt should pass as it is healthy and matches the target")
-	assert.Equal(t, 0, len(sbc0Rep.Queries), " no attempt should be made as the tablet target is changed")
-	require.Equal(t, 1, len(session.ShardSessions))
-	assert.NotEqual(t, oldRId, session.Session.ShardSessions[0].ReservedId, "should have recreated a reserved connection since the last connection was lost")
-	assert.NotEqual(t, oldAlias, session.Session.ShardSessions[0].TabletAlias, "tablet alias should have changed as this is a different tablet")
 }
 
 func TestIsConnClosed(t *testing.T) {
diff --git a/go/vt/vtgate/vcursor_impl_test.go b/go/vt/vtgate/vcursor_impl_test.go
index 70493008bc..418c53d00e 100644
--- a/go/vt/vtgate/vcursor_impl_test.go
+++ b/go/vt/vtgate/vcursor_impl_test.go
@@ -234,11 +234,11 @@ func TestSetTarget(t *testing.T) {
 	}, {
 		vschema:       vschemaWith2KS,
 		targetString:  "ks3",
-		expectedError: "unknown database 'ks3'",
+		expectedError: "Unknown database 'ks3'",
 	}, {
 		vschema:       vschemaWith2KS,
 		targetString:  "ks2@replica",
-		expectedError: "can't execute the given command because you have an active transaction",
+		expectedError: "Can't execute the given command because you have an active transaction",
 	}}
 
 	for i, tc := range tests {
diff --git a/go/vt/vttablet/tabletconntest/fakequeryservice.go b/go/vt/vttablet/tabletconntest/fakequeryservice.go
index 9fb15d053d..84849ea06e 100644
--- a/go/vt/vttablet/tabletconntest/fakequeryservice.go
+++ b/go/vt/vttablet/tabletconntest/fakequeryservice.go
@@ -720,7 +720,7 @@ func (f *FakeQueryService) VStreamResults(ctx context.Context, target *querypb.T
 }
 
 // QueryServiceByAlias satisfies the Gateway interface
-func (f *FakeQueryService) QueryServiceByAlias(_ *topodatapb.TabletAlias, _ *querypb.Target) (queryservice.QueryService, error) {
+func (f *FakeQueryService) QueryServiceByAlias(_ *topodatapb.TabletAlias) (queryservice.QueryService, error) {
 	panic("not implemented")
 }
 
diff --git a/go/vt/vttablet/tabletmanager/tm_state_test.go b/go/vt/vttablet/tabletmanager/tm_state_test.go
index 81d5b50d3d..d4e9eb7d02 100644
--- a/go/vt/vttablet/tabletmanager/tm_state_test.go
+++ b/go/vt/vttablet/tabletmanager/tm_state_test.go
@@ -22,6 +22,7 @@ import (
 	"testing"
 	"time"
 
+	"vitess.io/vitess/go/vt/key"
 	"vitess.io/vitess/go/vt/servenv"
 
 	"context"
@@ -154,6 +155,158 @@ func TestStateTabletControls(t *testing.T) {
 	assert.False(t, qsc.IsServing())
 }
 
+func TestStateIsShardServingisInSrvKeyspace(t *testing.T) {
+	ctx := context.Background()
+	ts := memorytopo.NewServer("cell1")
+	tm := newTestTM(t, ts, 1, "ks", "0")
+	defer tm.Stop()
+
+	tm.tmState.mu.Lock()
+	tm.tmState.tablet.Type = topodatapb.TabletType_MASTER
+	tm.tmState.mu.Unlock()
+
+	leftKeyRange, err := key.ParseShardingSpec("-80")
+	if err != nil || len(leftKeyRange) != 1 {
+		t.Fatalf("ParseShardingSpec failed. Expected non error and only one element. Got err: %v, len(%v)", err, len(leftKeyRange))
+	}
+
+	rightKeyRange, err := key.ParseShardingSpec("80-")
+	if err != nil || len(rightKeyRange) != 1 {
+		t.Fatalf("ParseShardingSpec failed. Expected non error and only one element. Got err: %v, len(%v)", err, len(rightKeyRange))
+	}
+
+	keyRange, err := key.ParseShardingSpec("0")
+	if err != nil || len(keyRange) != 1 {
+		t.Fatalf("ParseShardingSpec failed. Expected non error and only one element. Got err: %v, len(%v)", err, len(keyRange))
+	}
+
+	// Shard not in the SrvKeyspace, ServedType not in SrvKeyspace
+	ks := &topodatapb.SrvKeyspace{
+		Partitions: []*topodatapb.SrvKeyspace_KeyspacePartition{
+			{
+				ServedType: topodatapb.TabletType_DRAINED,
+				ShardReferences: []*topodatapb.ShardReference{
+					{
+						Name:     "-80",
+						KeyRange: leftKeyRange[0],
+					},
+					{
+						Name:     "80-",
+						KeyRange: rightKeyRange[0],
+					},
+				},
+			},
+		},
+	}
+	want := map[topodatapb.TabletType]bool{}
+	tm.tmState.RefreshFromTopoInfo(ctx, nil, ks)
+
+	tm.tmState.mu.Lock()
+	assert.False(t, tm.tmState.isInSrvKeyspace)
+	assert.Equal(t, want, tm.tmState.isShardServing)
+	tm.tmState.mu.Unlock()
+
+	assert.Equal(t, int64(0), statsIsInSrvKeyspace.Get())
+
+	// Shard not in the SrvKeyspace, ServedType in SrvKeyspace
+	ks = &topodatapb.SrvKeyspace{
+		Partitions: []*topodatapb.SrvKeyspace_KeyspacePartition{
+			{
+				ServedType: topodatapb.TabletType_MASTER,
+				ShardReferences: []*topodatapb.ShardReference{
+					{
+						Name:     "-80",
+						KeyRange: leftKeyRange[0],
+					},
+					{
+						Name:     "80-",
+						KeyRange: rightKeyRange[0],
+					},
+				},
+			},
+		},
+	}
+	want = map[topodatapb.TabletType]bool{}
+	tm.tmState.RefreshFromTopoInfo(ctx, nil, ks)
+
+	tm.tmState.mu.Lock()
+	assert.False(t, tm.tmState.isInSrvKeyspace)
+	assert.Equal(t, want, tm.tmState.isShardServing)
+	tm.tmState.mu.Unlock()
+
+	assert.Equal(t, int64(0), statsIsInSrvKeyspace.Get())
+
+	// Shard in the SrvKeyspace, ServedType in the SrvKeyspace
+	ks = &topodatapb.SrvKeyspace{
+		Partitions: []*topodatapb.SrvKeyspace_KeyspacePartition{
+			{
+				ServedType: topodatapb.TabletType_MASTER,
+				ShardReferences: []*topodatapb.ShardReference{
+					{
+						Name:     "0",
+						KeyRange: keyRange[0],
+					},
+				},
+			},
+		},
+	}
+	want = map[topodatapb.TabletType]bool{
+		topodatapb.TabletType_MASTER: true,
+	}
+	tm.tmState.RefreshFromTopoInfo(ctx, nil, ks)
+
+	tm.tmState.mu.Lock()
+	assert.True(t, tm.tmState.isInSrvKeyspace)
+	assert.Equal(t, want, tm.tmState.isShardServing)
+	tm.tmState.mu.Unlock()
+
+	assert.Equal(t, int64(1), statsIsInSrvKeyspace.Get())
+
+	// Shard in the SrvKeyspace, ServedType not in the SrvKeyspace
+	ks = &topodatapb.SrvKeyspace{
+		Partitions: []*topodatapb.SrvKeyspace_KeyspacePartition{
+			{
+				ServedType: topodatapb.TabletType_RDONLY,
+				ShardReferences: []*topodatapb.ShardReference{
+					{
+						Name:     "0",
+						KeyRange: keyRange[0],
+					},
+				},
+			},
+		},
+	}
+	want = map[topodatapb.TabletType]bool{
+		topodatapb.TabletType_RDONLY: true,
+	}
+	tm.tmState.RefreshFromTopoInfo(ctx, nil, ks)
+
+	tm.tmState.mu.Lock()
+	assert.False(t, tm.tmState.isInSrvKeyspace)
+	assert.Equal(t, want, tm.tmState.isShardServing)
+	tm.tmState.mu.Unlock()
+
+	assert.Equal(t, int64(0), statsIsInSrvKeyspace.Get())
+
+	// Test tablet type change - shard in the SrvKeyspace, ServedType in the SrvKeyspace
+	err = tm.tmState.ChangeTabletType(ctx, topodatapb.TabletType_RDONLY, DBActionNone)
+	require.NoError(t, err)
+	tm.tmState.mu.Lock()
+	assert.True(t, tm.tmState.isInSrvKeyspace)
+	tm.tmState.mu.Unlock()
+
+	assert.Equal(t, int64(1), statsIsInSrvKeyspace.Get())
+
+	// Test tablet type change - shard in the SrvKeyspace, ServedType in the SrvKeyspace
+	err = tm.tmState.ChangeTabletType(ctx, topodatapb.TabletType_DRAINED, DBActionNone)
+	require.NoError(t, err)
+	tm.tmState.mu.Lock()
+	assert.False(t, tm.tmState.isInSrvKeyspace)
+	tm.tmState.mu.Unlock()
+
+	assert.Equal(t, int64(0), statsIsInSrvKeyspace.Get())
+}
+
 func TestStateNonServing(t *testing.T) {
 	ctx := context.Background()
 	ts := memorytopo.NewServer("cell1")
diff --git a/go/vt/vttablet/tabletserver/query_engine_test.go b/go/vt/vttablet/tabletserver/query_engine_test.go
index 685e784cb7..d74dfbb90b 100644
--- a/go/vt/vttablet/tabletserver/query_engine_test.go
+++ b/go/vt/vttablet/tabletserver/query_engine_test.go
@@ -109,7 +109,7 @@ func TestGetPlanPanicDuetoEmptyQuery(t *testing.T) {
 	ctx := context.Background()
 	logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
 	_, err := qe.GetPlan(ctx, logStats, "", false, false /* inReservedConn */)
-	require.EqualError(t, err, "query was empty")
+	require.EqualError(t, err, "Query was empty")
 }
 
 func addSchemaEngineQueries(db *fakesqldb.DB) {
diff --git a/go/vt/vttablet/tabletserver/state_manager_test.go b/go/vt/vttablet/tabletserver/state_manager_test.go
index 53396e052b..577dbc8f6a 100644
--- a/go/vt/vttablet/tabletserver/state_manager_test.go
+++ b/go/vt/vttablet/tabletserver/state_manager_test.go
@@ -531,9 +531,9 @@ func TestStateManagerValidations(t *testing.T) {
 	target.Shard = ""
 	target.TabletType = topodatapb.TabletType_REPLICA
 	err = sm.StartRequest(ctx, target, false)
-	assert.Contains(t, err.Error(), "wrong tablet type")
+	assert.Contains(t, err.Error(), "invalid tablet type")
 	err = sm.VerifyTarget(ctx, target)
-	assert.Contains(t, err.Error(), "wrong tablet type")
+	assert.Contains(t, err.Error(), "invalid tablet type")
 
 	sm.alsoAllow = []topodatapb.TabletType{topodatapb.TabletType_REPLICA}
 	err = sm.StartRequest(ctx, target, false)
diff --git a/test/config.json b/test/config.json
index 2dd9255284..83ea100469 100644
--- a/test/config.json
+++ b/test/config.json
@@ -606,24 +606,6 @@
 			"RetryMax": 0,
 			"Tags": []
 		},
-		"vtgate_reserved_conn1": {
-			"File": "unused.go",
-			"Args": ["vitess.io/vitess/go/test/endtoend/vtgate/reservedconn/reconnect1"],
-			"Command": [],
-			"Manual": false,
-			"Shard": "17",
-			"RetryMax": 0,
-			"Tags": []
-		},
-		"vtgate_reserved_conn2": {
-			"File": "unused.go",
-			"Args": ["vitess.io/vitess/go/test/endtoend/vtgate/reservedconn/reconnect2"],
-			"Command": [],
-			"Manual": false,
-			"Shard": "17",
-			"RetryMax": 0,
-			"Tags": []
-		},
 		"vtgate_transaction": {
 			"File": "unused.go",
 			"Args": ["vitess.io/vitess/go/test/endtoend/vtgate/transaction"],