Skip to content

Commit c5964d7

Browse files
craig[bot]xinhaoz
andcommitted
Merge #143016
143016: sslocal: stats collector cleanup r=xinhaoz a=xinhaoz Commit 1 ---------- ### sqlstats: reduce stats collector calls from conn exec Previously, separate functions in the stats collector were required to send execution statistics for statements and transactions to sqlstats and insights respectively. This commit consolidates the sending of execution events to sqlstats and insights into one function on the stats collector per event type (one for statements and one for transactions). Epic: none Part of: #141024 Release note: None Commit 2 ---------- ### sqlstats: add FingerprintID to sqlstats.RecordedTxnStats This commit adds the `FingerprintID` field to sqlstats.RecordedTxnStats. Epic: none Part of: #141024 Release note: None Commit 3 ---------- ### sqlstats,insights: add struct conversion functions This commit adds functions converting sqlstats.Recorded{Stmt,Txn}Stats to `insight.{Statement,Transaction}`. Next: insights will only create insight objects if we are putting them into the insights cache, after analyzing `sqlstats.Recorded*` objects. Epic: none Release note: None Co-authored-by: Xin Hao Zhang <[email protected]>
2 parents cb94136 + c4e9a45 commit c5964d7

File tree

12 files changed

+167
-156
lines changed

12 files changed

+167
-156
lines changed

pkg/sql/conn_executor_exec.go

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4330,6 +4330,7 @@ func (ex *connExecutor) recordTransactionFinish(
43304330
commitLat := ex.phaseTimes.GetCommitLatency()
43314331

43324332
recordedTxnStats := sqlstats.RecordedTxnStats{
4333+
FingerprintID: transactionFingerprintID,
43334334
SessionID: ex.planner.extendedEvalCtx.SessionID,
43344335
TransactionID: ev.txnID,
43354336
TransactionTimeSec: elapsedTime.Seconds(),
@@ -4376,13 +4377,7 @@ func (ex *connExecutor) recordTransactionFinish(
43764377
)
43774378
}
43784379

4379-
ex.statsCollector.ObserveTransaction(ctx, transactionFingerprintID, recordedTxnStats)
4380-
4381-
return ex.statsCollector.RecordTransaction(
4382-
ctx,
4383-
transactionFingerprintID,
4384-
recordedTxnStats,
4385-
)
4380+
return ex.statsCollector.RecordTransaction(ctx, recordedTxnStats)
43864381
}
43874382

43884383
// Records a SERIALIZATION_CONFLICT contention event to the contention registry event

pkg/sql/executor_statement_metrics.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,8 +235,6 @@ func (ex *connExecutor) recordStatementSummary(
235235
}
236236
}
237237

238-
ex.statsCollector.ObserveStatement(stmtFingerprintID, recordedStmtStats)
239-
240238
// Do some transaction level accounting for the transaction this statement is
241239
// a part of.
242240

pkg/sql/sqlstats/insights/BUILD.bazel

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ go_library(
1414
"registry.go",
1515
"store.go",
1616
"test_utils.go",
17+
"util.go",
1718
],
1819
embed = [":insights_go_proto"],
1920
importpath = "github.com/cockroachdb/cockroach/pkg/sql/sqlstats/insights",
@@ -24,6 +25,8 @@ go_library(
2425
"//pkg/sql/appstatspb",
2526
"//pkg/sql/clusterunique",
2627
"//pkg/sql/contention/contentionutils",
28+
"//pkg/sql/pgwire/pgerror",
29+
"//pkg/sql/sqlstats",
2730
"//pkg/util/cache",
2831
"//pkg/util/intsets",
2932
"//pkg/util/metric",

pkg/sql/sqlstats/insights/ingester.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@ type eventBufChPayload struct {
5151
events *eventBuffer
5252
}
5353

54-
// ConcurrentBufferIngester buffers the "events" it sees (via ObserveStatement
55-
// and ObserveTransaction) and passes them along to the underlying registry
54+
// ConcurrentBufferIngester buffers the "events" it sees (via observeStatement
55+
// and observeTransaction) and passes them along to the underlying registry
5656
// once its buffer is full. (Or once a timeout has passed, for low-traffic
5757
// clusters and tests.)
5858
//

pkg/sql/sqlstats/insights/util.go

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
// Copyright 2025 The Cockroach Authors.
2+
//
3+
// Use of this software is governed by the CockroachDB Software License
4+
// included in the /LICENSE file.
5+
6+
package insights
7+
8+
import (
9+
"time"
10+
11+
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
12+
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats"
13+
"github.com/cockroachdb/redact"
14+
)
15+
16+
func MakeTxnInsight(value sqlstats.RecordedTxnStats) *Transaction {
17+
var retryReason string
18+
if value.AutoRetryReason != nil {
19+
retryReason = value.AutoRetryReason.Error()
20+
}
21+
22+
var cpuSQLNanos int64
23+
if value.ExecStats.CPUTime.Nanoseconds() >= 0 {
24+
cpuSQLNanos = value.ExecStats.CPUTime.Nanoseconds()
25+
}
26+
27+
var errorCode string
28+
var errorMsg redact.RedactableString
29+
if value.TxnErr != nil {
30+
errorCode = pgerror.GetPGCode(value.TxnErr).String()
31+
errorMsg = redact.Sprint(value.TxnErr)
32+
}
33+
34+
status := Transaction_Failed
35+
if value.Committed {
36+
status = Transaction_Completed
37+
}
38+
39+
var user, appName string
40+
if value.SessionData != nil {
41+
user = value.SessionData.User().Normalized()
42+
appName = value.SessionData.ApplicationName
43+
}
44+
45+
insight := &Transaction{
46+
ID: value.TransactionID,
47+
FingerprintID: value.FingerprintID,
48+
UserPriority: value.Priority.String(),
49+
ImplicitTxn: value.ImplicitTxn,
50+
Contention: &value.ExecStats.ContentionTime,
51+
StartTime: value.StartTime,
52+
EndTime: value.EndTime,
53+
User: user,
54+
ApplicationName: appName,
55+
RowsRead: value.RowsRead,
56+
RowsWritten: value.RowsWritten,
57+
RetryCount: value.RetryCount,
58+
AutoRetryReason: retryReason,
59+
CPUSQLNanos: cpuSQLNanos,
60+
LastErrorCode: errorCode,
61+
LastErrorMsg: errorMsg,
62+
Status: status,
63+
}
64+
65+
return insight
66+
}
67+
68+
func MakeStmtInsight(value sqlstats.RecordedStmtStats) *Statement {
69+
var autoRetryReason string
70+
if value.AutoRetryReason != nil {
71+
autoRetryReason = value.AutoRetryReason.Error()
72+
}
73+
74+
var contention *time.Duration
75+
var cpuSQLNanos int64
76+
if value.ExecStats != nil {
77+
contention = &value.ExecStats.ContentionTime
78+
cpuSQLNanos = value.ExecStats.CPUTime.Nanoseconds()
79+
}
80+
81+
var errorCode string
82+
var errorMsg redact.RedactableString
83+
if value.StatementError != nil {
84+
errorCode = pgerror.GetPGCode(value.StatementError).String()
85+
errorMsg = redact.Sprint(value.StatementError)
86+
}
87+
88+
insight := &Statement{
89+
ID: value.StatementID,
90+
FingerprintID: value.FingerprintID,
91+
LatencyInSeconds: value.ServiceLatencySec,
92+
Query: value.Query,
93+
Status: getInsightStatus(value.StatementError),
94+
StartTime: value.StartTime,
95+
EndTime: value.EndTime,
96+
FullScan: value.FullScan,
97+
PlanGist: value.PlanGist,
98+
Retries: int64(value.AutoRetryCount),
99+
AutoRetryReason: autoRetryReason,
100+
RowsRead: value.RowsRead,
101+
RowsWritten: value.RowsWritten,
102+
Nodes: value.Nodes,
103+
KVNodeIDs: value.KVNodeIDs,
104+
Contention: contention,
105+
IndexRecommendations: value.IndexRecommendations,
106+
Database: value.Database,
107+
CPUSQLNanos: cpuSQLNanos,
108+
ErrorCode: errorCode,
109+
ErrorMsg: errorMsg,
110+
}
111+
112+
return insight
113+
}
114+
115+
func getInsightStatus(statementError error) Statement_Status {
116+
if statementError == nil {
117+
return Statement_Completed
118+
}
119+
120+
return Statement_Failed
121+
}

pkg/sql/sqlstats/persistedsqlstats/bench_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -412,8 +412,10 @@ func BenchmarkSqlStatsMaxFlushTime(b *testing.B) {
412412
}
413413

414414
for i := int64(1); i <= txnFingerprintLimit; i++ {
415-
mockTxnValue := sqlstats.RecordedTxnStats{}
416-
err := appContainer.RecordTransaction(ctx, appstatspb.TransactionFingerprintID(i), mockTxnValue)
415+
mockTxnValue := sqlstats.RecordedTxnStats{
416+
FingerprintID: appstatspb.TransactionFingerprintID(i),
417+
}
418+
err := appContainer.RecordTransaction(ctx, mockTxnValue)
417419
if errors.Is(err, ssmemstorage.ErrFingerprintLimitReached) {
418420
break
419421
}

pkg/sql/sqlstats/sslocal/BUILD.bazel

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ go_library(
2020
"//pkg/settings/cluster",
2121
"//pkg/sql/appstatspb",
2222
"//pkg/sql/clusterunique",
23-
"//pkg/sql/pgwire/pgerror",
2423
"//pkg/sql/sessionphase",
2524
"//pkg/sql/sqlstats",
2625
"//pkg/sql/sqlstats/insights",
@@ -32,7 +31,6 @@ go_library(
3231
"//pkg/util/syncutil",
3332
"//pkg/util/timeutil",
3433
"@com_github_cockroachdb_errors//:errors",
35-
"@com_github_cockroachdb_redact//:redact",
3634
],
3735
)
3836

pkg/sql/sqlstats/sslocal/sql_stats_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,8 @@ func TestExplicitTxnFingerprintAccounting(t *testing.T) {
475475
statsCollector.EndTransaction(ctx, txnFingerprintID)
476476
require.NoError(t,
477477
statsCollector.
478-
RecordTransaction(ctx, txnFingerprintID, sqlstats.RecordedTxnStats{
478+
RecordTransaction(ctx, sqlstats.RecordedTxnStats{
479+
FingerprintID: txnFingerprintID,
479480
SessionData: &sessiondata.SessionData{
480481
SessionData: sessiondatapb.SessionData{
481482
UserProto: username.RootUserName().EncodeProto(),
@@ -607,7 +608,8 @@ func TestAssociatingStmtStatsWithTxnFingerprint(t *testing.T) {
607608

608609
transactionFingerprintID := appstatspb.TransactionFingerprintID(txnFingerprintIDHash.Sum())
609610
statsCollector.EndTransaction(ctx, transactionFingerprintID)
610-
err := statsCollector.RecordTransaction(ctx, transactionFingerprintID, sqlstats.RecordedTxnStats{
611+
err := statsCollector.RecordTransaction(ctx, sqlstats.RecordedTxnStats{
612+
FingerprintID: transactionFingerprintID,
611613
SessionData: &sessiondata.SessionData{
612614
SessionData: sessiondatapb.SessionData{
613615
UserProto: username.RootUserName().EncodeProto(),

0 commit comments

Comments
 (0)