Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sql: more allocation reductions #57208

Merged
merged 8 commits into from
Nov 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 4 additions & 26 deletions pkg/sql/colexec/materializer.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type Materializer struct {
input colexecop.Operator
typs []*types.T

drainHelper *drainHelper
drainHelper drainHelper

// runtime fields --

Expand Down Expand Up @@ -77,22 +77,6 @@ type drainHelper struct {
}

var _ execinfra.RowSource = &drainHelper{}
var _ execinfra.Releasable = &drainHelper{}

var drainHelperPool = sync.Pool{
New: func() interface{} {
return &drainHelper{}
},
}

func newDrainHelper(
statsCollectors []colexecop.VectorizedStatsCollector, sources colexecop.MetadataSources,
) *drainHelper {
d := drainHelperPool.Get().(*drainHelper)
d.statsCollectors = statsCollectors
d.sources = sources
return d
}

// OutputTypes implements the execinfra.RowSource interface.
func (d *drainHelper) OutputTypes() []*types.T {
Expand Down Expand Up @@ -147,12 +131,6 @@ func (d *drainHelper) ConsumerDone() {}
// ConsumerClosed implements the execinfra.RowSource interface.
func (d *drainHelper) ConsumerClosed() {}

// Release implements the execinfra.Releasable interface.
func (d *drainHelper) Release() {
*d = drainHelper{}
drainHelperPool.Put(d)
}

var materializerPool = sync.Pool{
New: func() interface{} {
return &Materializer{}
Expand All @@ -175,7 +153,6 @@ func NewMaterializer(
ProcessorBaseNoHelper: m.ProcessorBaseNoHelper,
input: input.Root,
typs: typs,
drainHelper: newDrainHelper(input.StatsCollectors, input.MetadataSources),
converter: colconv.NewAllVecToDatumConverter(len(typs)),
row: make(rowenc.EncDatumRow, len(typs)),
// We have to perform a deep copy of closers because the input object
Expand All @@ -185,6 +162,8 @@ func NewMaterializer(
// rowSourceToPlanNode wrappers.
closers: append(m.closers[:0], input.ToClose...),
}
m.drainHelper.statsCollectors = input.StatsCollectors
m.drainHelper.sources = input.MetadataSources

m.Init(
m,
Expand All @@ -205,7 +184,7 @@ func NewMaterializer(
},
},
)
m.AddInputToDrain(m.drainHelper)
m.AddInputToDrain(&m.drainHelper)
return m
}

Expand Down Expand Up @@ -325,7 +304,6 @@ func (m *Materializer) ConsumerClosed() {

// Release implements the execinfra.Releasable interface.
func (m *Materializer) Release() {
m.drainHelper.Release()
m.ProcessorBaseNoHelper.Reset()
m.converter.Release()
for i := range m.closers {
Expand Down
5 changes: 2 additions & 3 deletions pkg/sql/colexecop/operator.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,13 @@ type Closers []Closer
// sense.
func (c Closers) CloseAndLogOnErr(ctx context.Context, prefix string) {
if err := colexecerror.CatchVectorizedRuntimeError(func() {
prefix += ":"
for _, closer := range c {
if err := closer.Close(); err != nil && log.V(1) {
log.Infof(ctx, "%s error closing Closer: %v", prefix, err)
log.Infof(ctx, "%s: error closing Closer: %v", prefix, err)
}
}
}); err != nil && log.V(1) {
log.Infof(ctx, "%s runtime error closing the closers: %v", prefix, err)
log.Infof(ctx, "%s: runtime error closing the closers: %v", prefix, err)
}
}

Expand Down
41 changes: 22 additions & 19 deletions pkg/sql/conn_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ import (
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats/sslocal"
"github.com/cockroachdb/cockroach/pkg/sql/stmtdiagnostics"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/cancelchecker"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/errorutil"
"github.com/cockroachdb/cockroach/pkg/util/fsm"
Expand Down Expand Up @@ -1203,15 +1202,25 @@ type connExecutor struct {
// connExecutor's closure.
prepStmtsNamespaceMemAcc mon.BoundAccount

// onTxnFinish (if non-nil) will be called when txn is finished (either
// committed or aborted). It is set when txn is started but can remain
// unset when txn is executed within another higher-level txn.
onTxnFinish func(context.Context, txnEvent)
// shouldExecuteOnTxnFinish indicates that ex.onTxnFinish will be called
// when txn is finished (either committed or aborted). It is true when
// txn is started but can remain false when txn is executed within
// another higher-level txn.
shouldExecuteOnTxnFinish bool

// onTxnRestart (if non-nil) will be called when a txn is being retried. It
// is set when the txn is started but can remain unset when a txn is
// executed within another higher-level txn.
onTxnRestart func()
// txnFinishClosure contains fields that ex.onTxnFinish uses to execute.
txnFinishClosure struct {
// txnStartTime is the time that the transaction started.
txnStartTime time.Time
// implicit is whether or not the transaction was implicit.
implicit bool
}

// shouldExecuteOnTxnRestart indicates that ex.onTxnRestart will be
// called when txn is being retried. It is true when txn is started but
// can remain false when txn is executed within another higher-level
// txn.
shouldExecuteOnTxnRestart bool

// savepoints maintains the stack of savepoints currently open.
savepoints savepointStack
Expand Down Expand Up @@ -1506,15 +1515,9 @@ func (ex *connExecutor) resetExtraTxnState(ctx context.Context, ev txnEvent) err
delete(ex.extraTxnState.prepStmtsNamespaceAtTxnRewindPos.portals, name)
}
ex.extraTxnState.savepoints.clear()
// After txn is finished, we need to call onTxnFinish (if it's non-nil).
if ex.extraTxnState.onTxnFinish != nil {
ex.extraTxnState.onTxnFinish(ctx, ev)
ex.extraTxnState.onTxnFinish = nil
}
ex.onTxnFinish(ctx, ev)
case txnRestart:
if ex.extraTxnState.onTxnRestart != nil {
ex.extraTxnState.onTxnRestart()
}
ex.onTxnRestart()
ex.state.mu.Lock()
defer ex.state.mu.Unlock()
ex.state.mu.stmtCount = 0
Expand Down Expand Up @@ -2537,7 +2540,7 @@ func (ex *connExecutor) implicitTxn() bool {
// initPlanner initializes a planner so it can can be used for planning a
// query in the context of this session.
func (ex *connExecutor) initPlanner(ctx context.Context, p *planner) {
p.cancelChecker = cancelchecker.NewCancelChecker(ctx)
p.cancelChecker.Reset(ctx)

ex.initEvalCtx(ctx, &p.extendedEvalCtx, p)

Expand Down Expand Up @@ -2635,7 +2638,7 @@ func (ex *connExecutor) txnStateTransitionsApplyWrapper(
case txnStart:
ex.extraTxnState.autoRetryCounter = 0
ex.extraTxnState.autoRetryReason = nil
ex.extraTxnState.onTxnFinish, ex.extraTxnState.onTxnRestart = ex.recordTransactionStart()
ex.recordTransactionStart()
// Bump the txn counter for logging.
ex.extraTxnState.txnCounter++
if !ex.server.cfg.Codec.ForSystemTenant() {
Expand Down
97 changes: 47 additions & 50 deletions pkg/sql/conn_executor_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,30 +287,29 @@ func (ex *connExecutor) execStmtInOpenState(

var timeoutTicker *time.Timer
queryTimedOut := false
doneAfterFunc := make(chan struct{}, 1)
// doneAfterFunc will be allocated only when timeoutTicker is non-nil.
var doneAfterFunc chan struct{}

// Early-associate placeholder info with the eval context,
// so that we can fill in placeholder values in our call to addActiveQuery, below.
if !ex.planner.EvalContext().HasPlaceholders() {
ex.planner.EvalContext().Placeholders = pinfo
}

// Canceling a query cancels its transaction's context so we take a reference
// to the cancelation function here.
unregisterFn := ex.addActiveQuery(ast, formatWithPlaceholders(ast, ex.planner.EvalContext()), queryID, ex.state.cancel)
ex.addActiveQuery(ast, formatWithPlaceholders(ast, ex.planner.EvalContext()), queryID, ex.state.cancel)

// queryDone is a cleanup function dealing with unregistering a query.
// It also deals with overwriting res.Error to a more user-friendly message in
// case of query cancelation. res can be nil to opt out of this.
queryDone := func(ctx context.Context, res RestrictedCommandResult) {
// Make sure that we always unregister the query. It also deals with
// overwriting res.Error to a more user-friendly message in case of query
// cancellation.
defer func(ctx context.Context, res RestrictedCommandResult) {
if timeoutTicker != nil {
if !timeoutTicker.Stop() {
// Wait for the timer callback to complete to avoid a data race on
// queryTimedOut.
<-doneAfterFunc
}
}
unregisterFn()
ex.removeActiveQuery(queryID, ast)

// Detect context cancelation and overwrite whatever error might have been
// set on the result before. The idea is that once the query's context is
Expand Down Expand Up @@ -348,15 +347,7 @@ func (ex *connExecutor) execStmtInOpenState(
res.SetError(sqlerrors.QueryTimeoutError)
retPayload = eventNonRetriableErrPayload{err: sqlerrors.QueryTimeoutError}
}
}
// Generally we want to unregister after the auto-commit below. However, in
// case we'll execute the statement through the parallel execution queue,
// we'll pass the responsibility for unregistering to the queue.
defer func() {
if queryDone != nil {
queryDone(ctx, res)
}
}()
}(ctx, res)

makeErrEvent := func(err error) (fsm.Event, fsm.EventPayload, error) {
ev, payload := ex.makeErrEvent(err, ast)
Expand Down Expand Up @@ -480,6 +471,7 @@ func (ex *connExecutor) execStmtInOpenState(
queryTimedOut = true
return makeErrEvent(sqlerrors.QueryTimeoutError)
}
doneAfterFunc = make(chan struct{}, 1)
timeoutTicker = time.AfterFunc(
timerDuration,
func() {
Expand Down Expand Up @@ -699,7 +691,7 @@ func (ex *connExecutor) execStmtInOpenState(
p.extendedEvalCtx.Placeholders = &p.semaCtx.Placeholders
p.extendedEvalCtx.Annotations = &p.semaCtx.Annotations
p.stmt = stmt
p.cancelChecker = cancelchecker.NewCancelChecker(ctx)
p.cancelChecker.Reset(ctx)
p.autoCommit = os.ImplicitTxn.Get() && !ex.server.cfg.TestingKnobs.DisableAutoCommit

var stmtThresholdSpan *tracing.Span
Expand Down Expand Up @@ -1471,6 +1463,9 @@ func (ex *connExecutor) beginTransactionTimestampsAndReadMode(
return tree.ReadOnly, asOf.Timestamp.GoTime(), &asOf.Timestamp, nil
}

var eventStartImplicitTxn fsm.Event = eventTxnStart{ImplicitTxn: fsm.True}
var eventStartExplicitTxn fsm.Event = eventTxnStart{ImplicitTxn: fsm.False}

// execStmtInNoTxnState "executes" a statement when no transaction is in scope.
// For anything but BEGIN, this method doesn't actually execute the statement;
// it just returns an Event that will generate a transaction. The statement will
Expand All @@ -1496,7 +1491,7 @@ func (ex *connExecutor) execStmtInNoTxnState(
return ex.makeErrEvent(err, s)
}
ex.sessionDataStack.PushTopClone()
return eventTxnStart{ImplicitTxn: fsm.False},
return eventStartExplicitTxn,
makeEventTxnStartPayload(
ex.txnPriorityWithSessionDefault(s.Modes.UserPriority),
mode,
Expand All @@ -1516,7 +1511,7 @@ func (ex *connExecutor) execStmtInNoTxnState(
if err != nil {
return ex.makeErrEvent(err, s)
}
return eventTxnStart{ImplicitTxn: fsm.True},
return eventStartImplicitTxn,
makeEventTxnStartPayload(
ex.txnPriorityWithSessionDefault(tree.UnspecifiedUserPriority),
mode,
Expand Down Expand Up @@ -1790,13 +1785,9 @@ func (ex *connExecutor) enableTracing(modes []string) error {
}

// addActiveQuery adds a running query to the list of running queries.
//
// It returns a cleanup function that needs to be run when the query is no
// longer executing. NOTE(andrei): As of Feb 2018, "executing" does not imply
// that the results have been delivered to the client.
func (ex *connExecutor) addActiveQuery(
ast tree.Statement, rawStmt string, queryID ClusterWideID, cancelFun context.CancelFunc,
) func() {
) {
_, hidden := ast.(tree.HiddenFromShowQueries)
qm := &queryMeta{
txnID: ex.state.mu.txn.ID(),
Expand All @@ -1810,18 +1801,18 @@ func (ex *connExecutor) addActiveQuery(
ex.mu.Lock()
ex.mu.ActiveQueries[queryID] = qm
ex.mu.Unlock()
return func() {
ex.mu.Lock()
_, ok := ex.mu.ActiveQueries[queryID]
if !ok {
ex.mu.Unlock()
panic(errors.AssertionFailedf("query %d missing from ActiveQueries", queryID))
}
delete(ex.mu.ActiveQueries, queryID)
ex.mu.LastActiveQuery = ast
}

func (ex *connExecutor) removeActiveQuery(queryID ClusterWideID, ast tree.Statement) {
ex.mu.Lock()
_, ok := ex.mu.ActiveQueries[queryID]
if !ok {
ex.mu.Unlock()
panic(errors.AssertionFailedf("query %d missing from ActiveQueries", queryID))
}
delete(ex.mu.ActiveQueries, queryID)
ex.mu.LastActiveQuery = ast
ex.mu.Unlock()
}

// handleAutoCommit commits the KV transaction if it hasn't been committed
Expand Down Expand Up @@ -1883,13 +1874,8 @@ func payloadHasError(payload fsm.EventPayload) bool {
return hasErr
}

// recordTransactionStart records the start of the transaction and returns
// closures to be called once the transaction finishes or if the transaction
// restarts.
func (ex *connExecutor) recordTransactionStart() (
onTxnFinish func(context.Context, txnEvent),
onTxnRestart func(),
) {
// recordTransactionStart records the start of the transaction.
func (ex *connExecutor) recordTransactionStart() {
ex.state.mu.RLock()
txnStart := ex.state.mu.txnStart
ex.state.mu.RUnlock()
Expand Down Expand Up @@ -1918,7 +1904,21 @@ func (ex *connExecutor) recordTransactionStart() (

ex.metrics.EngineMetrics.SQLTxnsOpen.Inc(1)

onTxnFinish = func(ctx context.Context, ev txnEvent) {
ex.extraTxnState.shouldExecuteOnTxnFinish = true
ex.extraTxnState.txnFinishClosure.txnStartTime = txnStart
ex.extraTxnState.txnFinishClosure.implicit = implicit
ex.extraTxnState.shouldExecuteOnTxnRestart = true

if !implicit {
ex.statsCollector.StartExplicitTransaction()
}
}

func (ex *connExecutor) onTxnFinish(ctx context.Context, ev txnEvent) {
if ex.extraTxnState.shouldExecuteOnTxnFinish {
ex.extraTxnState.shouldExecuteOnTxnFinish = false
txnStart := ex.extraTxnState.txnFinishClosure.txnStartTime
implicit := ex.extraTxnState.txnFinishClosure.implicit
ex.phaseTimes.SetSessionPhaseTime(sessionphase.SessionEndExecTransaction, timeutil.Now())
transactionFingerprintID :=
roachpb.TransactionFingerprintID(ex.extraTxnState.transactionStatementsHash.Sum())
Expand All @@ -1936,7 +1936,10 @@ func (ex *connExecutor) recordTransactionStart() (
ex.metrics.StatsMetrics.DiscardedStatsCount.Inc(1)
}
}
onTxnRestart = func() {
}

func (ex *connExecutor) onTxnRestart() {
if ex.extraTxnState.shouldExecuteOnTxnRestart {
ex.phaseTimes.SetSessionPhaseTime(sessionphase.SessionMostRecentStartExecTransaction, timeutil.Now())
ex.extraTxnState.transactionStatementFingerprintIDs = nil
ex.extraTxnState.transactionStatementsHash = util.MakeFNV64()
Expand All @@ -1952,12 +1955,6 @@ func (ex *connExecutor) recordTransactionStart() (
ex.server.cfg.TestingKnobs.BeforeRestart(ex.Ctx(), ex.extraTxnState.autoRetryReason)
}
}

if !implicit {
ex.statsCollector.StartExplicitTransaction()
}

return onTxnFinish, onTxnRestart
}

func (ex *connExecutor) recordTransaction(
Expand Down
Loading