crbench//

← all cases

Per-statement fnv.New128() allocation is a hot-path throughput regression

Tier 2 hard go · local · real merged PR from cockroachdb/cockroach #52704

Ground-truth defects

d1 · performance · medium
Statement IDs are built with `h := fnv.New128()`; the stdlib hash/fnv constructor heap-allocates a hash object on every statement, and the ID is constructed even when not required. On hot SQL paths this is a measurable allocation/throughput regression (the fix's microbenchmarks show kv95 +3.42%). The fix uses a lightweight value-type FNV and only builds the ID when needed. (Large-diff stress case: ~2.8k lines, 14 files.)
d2 · correctness · medium
recordTransaction unconditionally records CommitLat via getCommitLatency() for both txnCommit and txnRollback, but sessionStartTransactionCommit/sessionEndTransactionCommit are only set in commitSQLTransaction and never reset between txns, so rolled-back transactions record a stale (prior commit) or zero commit latency into their CommitLat stats.
d3 · correctness · critical
`getStatsForStmtWithKey` returns the nil zero value when the key is absent and `createIfNonexistent` is false, and the diff adds an early return in `recordStatement` that dereferences it unconditionally (`if !createIfNonExistent { return s.ID }`). A statement first seen at or below the configured latency threshold therefore panics with a nil pointer dereference.
d4 · correctness · medium
`resetAndMaybeDumpStats` copies and re-makes `a.stmts` but the diff's new per-fingerprint `a.txns` map is neither transferred to the copy nor cleared. Transaction statistics therefore survive every reset, are never handed to the reported-stats sink, and accumulate one entry per distinct transaction fingerprint for the lifetime of the node.

The change under review

diff (truncated — full diff)
diff --git a/docs/generated/http/full.md b/docs/generated/http/full.md
index db7c618484bf..2fb9bb9ff7db 100644
--- a/docs/generated/http/full.md
+++ b/docs/generated/http/full.md
@@ -1784,6 +1784,7 @@ information about the resources on a node used by that table.
 | statements | [StatementsResponse.CollectedStatementStatistics](#cockroach.server.serverpb.StatementsResponse-cockroach.server.serverpb.StatementsResponse.CollectedStatementStatistics) | repeated |  |
 | last_reset | [google.protobuf.Timestamp](#cockroach.server.serverpb.StatementsResponse-google.protobuf.Timestamp) |  | Timestamp of the last stats reset. |
 | internal_app_name_prefix | [string](#cockroach.server.serverpb.StatementsResponse-string) |  | If set and non-empty, indicates the prefix to application_name used for statements/queries issued internally by CockroachDB. |
+| transactions | [StatementsResponse.ExtendedCollectedTransactionStatistics](#cockroach.server.serverpb.StatementsResponse-cockroach.server.serverpb.StatementsResponse.ExtendedCollectedTransactionStatistics) | repeated | Transactions is transaction-level statistics for the collection of statements in this response. |
 
 
 
@@ -1814,6 +1815,18 @@ information about the resources on a node used by that table.
 
 
 
+<a name="cockroach.server.serverpb.StatementsResponse-cockroach.server.serverpb.StatementsResponse.ExtendedCollectedTransactionStatistics"></a>
+#### StatementsResponse.ExtendedCollectedTransactionStatistics
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| stats_data | [cockroach.sql.CollectedTransactionStatistics](#cockroach.server.serverpb.StatementsResponse-cockroach.sql.CollectedTransactionStatistics) |  |  |
+| node_id | [int32](#cockroach.server.serverpb.StatementsResponse-int32) |  |  |
+
+
+
+
+
 
 ## CreateStatementDiagnosticsReport
 
diff --git a/pkg/roachpb/app_stats.go b/pkg/roachpb/app_stats.go
index 068c9bbfc57f..1acd4180c410 100644
--- a/pkg/roachpb/app_stats.go
+++ b/pkg/roachpb/app_stats.go
@@ -11,11 +11,32 @@
 package roachpb
 
 import (
+	"fmt"
+	"hash/fnv"
 	"math"
 
 	"github.com/cockroachdb/errors"
 )
 
+// StmtID is the type of a Statement ID.
+type StmtID string
+
+// ConstructStatementID constructs an ID by hashing an anonymized query, it's
+// failure status, and if it was part of an implicit txn. At the time of writing,
+// these are the axis' we use to bucket queries for stats collection
+// (see stmtKey).
+func ConstructStatementID(anonymizedStmt string, failed bool, implicitTxn bool) StmtID {
+	h := fnv.New128()
+	h.Write([]byte(anonymizedStmt))
+	if failed {
+		h.Write([]byte("failed"))
+	}
+	if implicitTxn {
+		h.Write([]byte("implicit_txn"))
+	}
+	return StmtID(fmt.Sprintf("%x", h.Sum(nil)))
+}
+
 // GetVariance retrieves the variance of the values.
 func (l *NumericStat) GetVariance(count int64) float64 {
 	return l.SquaredDiffs / (float64(count) - 1)
@@ -73,6 +94,20 @@ func (s *TxnStats) Add(other TxnStats) {
 	s.CommittedCount += other.CommittedCount
 }
 
+// Add combines other into TransactionStatistics.
+func (t *TransactionStatistics) Add(other *TransactionStatistics) {
+	if other.MaxRetries > t.MaxRetries {
+		t.MaxRetries = other.MaxRetries
+	}
+
+	t.CommitLat.Add(other.CommitLat, t.Count, other.Count)
+	t.RetryLat.Add(other.RetryLat, t.Count, other.Count)
+	t.ServiceLat.Add(other.ServiceLat, t.Count, other.Count)
+	t.NumRows.Add(other.NumRows, t.Count, other.Count)
+
+	t.Count += other.Count
+}
+
 // Add combines other into this StatementStatistics.
 func (s *StatementStatistics) Add(other *StatementStatistics) {
 	s.FirstAttemptCount += other.FirstAttemptCount
diff --git a/pkg/roachpb/app_stats.pb.go b/pkg/roachpb/app_stats.pb.go
index f92e55f9b341..7b2dc510c6e7 100644
--- a/pkg/roachpb/app_stats.pb.go
+++ b/pkg/roachpb/app_stats.pb.go
@@ -85,7 +85,7 @@ func (m *StatementStatistics) Reset()         { *m = StatementStatistics{} }
 func (m *StatementStatistics) String() string { return proto.CompactTextString(m) }
 func (*StatementStatistics) ProtoMessage()    {}
 func (*StatementStatistics) Descriptor() ([]byte, []int) {
-	return fileDescriptor_app_stats_e04df53ac4052f7b, []int{0}
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{0}
 }
 func (m *StatementStatistics) XXX_Unmarshal(b []byte) error {
 	return m.Unmarshal(b)
@@ -110,6 +110,55 @@ func (m *StatementStatistics) XXX_DiscardUnknown() {
 
 var xxx_messageInfo_StatementStatistics proto.InternalMessageInfo
 
+type TransactionStatistics struct {
+	// Count is the total number of times this transaction was executed
+	// since the beginning of the reporting period.
+	Count int64 `protobuf:"varint,1,opt,name=count" json:"count"`
+	// MaxRetries collects the maximum observed number of automatic
+	// retries in the reporting period.
+	MaxRetries int64 `protobuf:"varint,2,opt,name=max_retries,json=maxRetries" json:"max_retries"`
+	// NumRows collects the total number of rows returned or observed across all
+	// statements.
+	NumRows NumericStat `protobuf:"bytes,3,opt,name=num_rows,json=numRows" json:"num_rows"`
+	// ServiceLat is the time to service the transaction, from the time a
+	// transaction was received to end of execution.
+	ServiceLat NumericStat `protobuf:"bytes,4,opt,name=service_lat,json=serviceLat" json:"service_lat"`
+	// RetryLat is the amount of time spent retrying the transaction.
+	RetryLat NumericStat `protobuf:"bytes,5,opt,name=retry_lat,json=retryLat" json:"retry_lat"`
+	// CommitLat is the amount of time required to commit the transaction after
+	// all statement operations have been applied.
+	CommitLat NumericStat `protobuf:"bytes,6,opt,name=commit_lat,json=commitLat" json:"commit_lat"`
+}
+
+func (m *TransactionStatistics) Reset()         { *m = TransactionStatistics{} }
+func (m *TransactionStatistics) String() string { return proto.CompactTextString(m) }
+func (*TransactionStatistics) ProtoMessage()    {}
+func (*TransactionStatistics) Descriptor() ([]byte, []int) {
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{1}
+}
+func (m *TransactionStatistics) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *TransactionStatistics) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalTo(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (dst *TransactionStatistics) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_TransactionStatistics.Merge(dst, src)
+}
+func (m *TransactionStatistics) XXX_Size() int {
+	return m.Size()
+}
+func (m *TransactionStatistics) XXX_DiscardUnknown() {
+	xxx_messageInfo_TransactionStatistics.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_TransactionStatistics proto.InternalMessageInfo
+
 type SensitiveInfo struct {
 	// LastErr collects the last error encountered.
 	// It is only reported once it's been redacted.
@@ -124,7 +173,7 @@ func (m *SensitiveInfo) Reset()         { *m = SensitiveInfo{} }
 func (m *SensitiveInfo) String() string { return proto.CompactTextString(m) }
 func (*SensitiveInfo) ProtoMessage()    {}
 func (*SensitiveInfo) Descriptor() ([]byte, []int) {
-	return fileDescriptor_app_stats_e04df53ac4052f7b, []int{1}
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{2}
 }
 func (m *SensitiveInfo) XXX_Unmarshal(b []byte) error {
 	return m.Unmarshal(b)
@@ -166,7 +215,7 @@ func (m *NumericStat) Reset()         { *m = NumericStat{} }
 func (m *NumericStat) String() string { return proto.CompactTextString(m) }
 func (*NumericStat) ProtoMessage()    {}
 func (*NumericStat) Descriptor() ([]byte, []int) {
-	return fileDescriptor_app_stats_e04df53ac4052f7b, []int{2}
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{3}
 }
 func (m *NumericStat) XXX_Unmarshal(b []byte) error {
 	return m.Unmarshal(b)
@@ -205,7 +254,7 @@ func (m *StatementStatisticsKey) Reset()         { *m = StatementStatisticsKey{}
 func (m *StatementStatisticsKey) String() string { return proto.CompactTextString(m) }
 func (*StatementStatisticsKey) ProtoMessage()    {}
 func (*StatementStatisticsKey) Descriptor() ([]byte, []int) {
-	return fileDescriptor_app_stats_e04df53ac4052f7b, []int{3}
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{4}
 }
 func (m *StatementStatisticsKey) XXX_Unmarshal(b []byte) error {
 	return m.Unmarshal(b)
@@ -230,8 +279,13 @@ func (m *StatementStatisticsKey) XXX_DiscardUnknown() {
 
 var xxx_messageInfo_StatementStatisticsKey proto.InternalMessageInfo
 
-// CollectedStats wraps collected timings and metadata for some query's execution.
+// CollectedStatementStatistics wraps collected timings and metadata for some
+// query's execution.
 type CollectedStatementStatistics struct {
+	// ID is a hash of the statement key (query fingerprint, failure status,
+	// implicit txn or not) which can be used to identify the statement
+	// for instance in transaction statistics.
+	ID    StmtID                 `protobuf:"bytes,3,opt,name=id,casttype=StmtID" json:"id"`
 	Key   StatementStatisticsKey `protobuf:"bytes,1,opt,name=key" json:"key"`
 	Stats StatementStatistics    `protobuf:"bytes,2,opt,name=stats" json:"stats"`
 }
@@ -240,7 +294,7 @@ func (m *CollectedStatementStatistics) Reset()         { *m = CollectedStatement
 func (m *CollectedStatementStatistics) String() string { return proto.CompactTextString(m) }
 func (*CollectedStatementStatistics) ProtoMessage()    {}
 func (*CollectedStatementStatistics) Descriptor() ([]byte, []int) {
-	return fileDescriptor_app_stats_e04df53ac4052f7b, []int{4}
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{5}
 }
 func (m *CollectedStatementStatistics) XXX_Unmarshal(b []byte) error {
 	return m.Unmarshal(b)
@@ -265,6 +319,46 @@ func (m *CollectedStatementStatistics) XXX_DiscardUnknown() {
 
 var xxx_messageInfo_CollectedStatementStatistics proto.InternalMessageInfo
 
+// CollectedTransactionStatistics wraps collected timings and metadata for some
+// transaction executions.
+type CollectedTransactionStatistics struct {
+	// StatementIDs is the IDs of the statements which this transaction comprises,
+	// in order.
+	StatementIDs []StmtID `protobuf:"bytes,1,rep,name=statement_ids,json=statementIds,casttype=StmtID" json:"statement_ids,omitempty"`
+	// App is the name of the app which executed the transaction.
+	App   string                `protobuf:"bytes,2,opt,name=app" json:"app"`
+	Stats TransactionStatistics `protobuf:"bytes,3,opt,name=stats" json:"stats"`
+}
+
+func (m *CollectedTransactionStatistics) Reset()         { *m = CollectedTransactionStatistics{} }
+func (m *CollectedTransactionStatistics) String() string { return proto.CompactTextString(m) }
+func (*CollectedTransactionStatistics) ProtoMessage()    {}
+func (*CollectedTransactionStatistics) Descriptor() ([]byte, []int) {
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{6}
+}
+func (m *CollectedTransactionStatistics) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CollectedTransactionStatistics) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalTo(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (dst *CollectedTransactionStatistics) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CollectedTransactionStatistics.Merge(dst, src)
+}
+func (m *CollectedTransactionStatistics) XXX_Size() int {
+	return m.Size()
+}
+func (m *CollectedTransactionStatistics) XXX_DiscardUnknown() {
+	xxx_messageInfo_CollectedTransactionStatistics.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CollectedTransactionStatistics proto.InternalMessageInfo
+
 // ExplainTreePlanNode is a serialized representation of an EXPLAIN tree for a logical plan.
 type ExplainTreePlanNode struct {
 	// Name is the type of node this is, e.g. "scan" or "index-join".
@@ -280,7 +374,7 @@ func (m *ExplainTreePlanNode) Reset()         { *m = ExplainTreePlanNode{} }
 func (m *ExplainTreePlanNode) String() string { return proto.CompactTextString(m) }
 func (*ExplainTreePlanNode) ProtoMessage()    {}
 func (*ExplainTreePlanNode) Descriptor() ([]byte, []int) {
-	return fileDescriptor_app_stats_e04df53ac4052f7b, []int{5}
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{7}
 }
 func (m *ExplainTreePlanNode) XXX_Unmarshal(b []byte) error {
 	return m.Unmarshal(b)
@@ -314,7 +408,7 @@ func (m *ExplainTreePlanNode_Attr) Reset()         { *m = ExplainTreePlanNode_At
 func (m *ExplainTreePlanNode_Attr) String() string { return proto.CompactTextString(m) }
 func (*ExplainTreePlanNode_Attr) ProtoMessage()    {}
 func (*ExplainTreePlanNode_Attr) Descriptor() ([]byte, []int) {
-	return fileDescriptor_app_stats_e04df53ac4052f7b, []int{5, 0}
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{7, 0}
 }
 func (m *ExplainTreePlanNode_Attr) XXX_Unmarshal(b []byte) error {
 	return m.Unmarshal(b)
@@ -353,7 +447,7 @@ func (m *TxnStats) Reset()         { *m = TxnStats{} }
 func (m *TxnStats) String() string { return proto.CompactTextString(m) }
 func (*TxnStats) ProtoMessage()    {}
 func (*TxnStats) Descriptor() ([]byte, []int) {
-	return fileDescriptor_app_stats_e04df53ac4052f7b, []int{6}
+	return fileDescriptor_app_stats_a24711b0410d7623, []int{8}
 }
 func (m *TxnStats) XXX_Unmarshal(b []byte) error {
 	return m.Unmarshal(b)
@@ -380,10 +474,12 @@ var xxx_messageInfo_TxnStats proto.InternalMessageInfo
 
 func init() {
 	proto.RegisterType((*StatementStatistics)(nil), "cockroach.sql.StatementStatistics")
+	proto.RegisterType((*TransactionStatistics)(nil), "cockroach.sql.TransactionStatistics")
 	proto.RegisterType((*SensitiveInfo)(nil), "cockroach.sql.SensitiveInfo")
 	proto.RegisterType((*NumericStat)(nil), "cockroach.sql.NumericStat")
 	proto.RegisterType((*StatementStatisticsKey)(nil), "cockroach.sql.StatementStatisticsKey")
 	proto.RegisterType((*CollectedStatementStatistics)(nil), "cockroach.sql.CollectedStatementStatistics")
+	proto.RegisterType((*CollectedTransactionStatistics)(nil), "cockroach.sql.CollectedTransactionStatistics")
 	proto.RegisterType((*ExplainTreePlanNode)(nil), "cockroach.sql.ExplainTreePlanNode")
 	proto.RegisterType((*ExplainTreePlanNode_Attr)(nil), "cockroach.sql.ExplainTreePlanNode.Attr")
 	proto.RegisterType((*TxnStats)(nil), "cockroach.sql.TxnStats")
@@ -594,6 +690,62 @@ func (m *StatementStatistics) MarshalTo(dAtA []byte) (int, error) {
 	return i, nil
 }
 
+func (m *TransactionStatistics) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalTo(dAtA)
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *TransactionStatistics) MarshalTo(dAtA []byte) (int, error) {
+	var i int
+	_ = i
+	var l int
+	_ = l
+	dAtA[i] = 0x8
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(m.Count))
+	dAtA[i] = 0x10
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(m.MaxRetries))
+	dAtA[i] = 0x1a
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(m.NumRows.Size()))
+	n10, err := m.NumRows.MarshalTo(dAtA[i:])
+	if err != nil {
+		return 0, err
+	}
+	i += n10
+	dAtA[i] = 0x22
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(m.ServiceLat.Size()))
+	n11, err := m.ServiceLat.MarshalTo(dAtA[i:])
+	if err != nil {
+		return 0, err
+	}
+	i += n11
+	dAtA[i] = 0x2a
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(m.RetryLat.Size()))
+	n12, err := m.RetryLat.MarshalTo(dAtA[i:])
+	if err != nil {
+		return 0, err
+	}
+	i += n12
+	dAtA[i] = 0x32
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(m.CommitLat.Size()))
+	n13, err := m.CommitLat.MarshalTo(dAtA[i:])
+	if err != nil {
+		return 0, err
+	}
+	i += n13
+	return i, nil
+}
+
 func (m *SensitiveInfo) Marshal() (dAtA []byte, err error) {
 	size := m.Size()
 	dAtA = make([]byte, size)
@@ -616,19 +768,19 @@ func (m *SensitiveInfo) MarshalTo(dAtA []byte) (int, error) {
 	dAtA[i] = 0x12
 	i++
 	i = encodeVarintAppStats(dAtA, i, uint64(m.MostRecentPlanDescription.Size()))
-	n10, err := m.MostRecentPlanDescription.MarshalTo(dAtA[i:])
+	n14, err := m.MostRecentPlanDescription.MarshalTo(dAtA[i:])
 	if err != nil {
 		return 0, err
 	}
-	i += n10
+	i += n14
 	dAtA[i] = 0x1a
 	i++
 	i = encodeVarintAppStats(dAtA, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(m.MostRecentPlanTimestamp)))
-	n11, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.MostRecentPlanTimestamp, dAtA[i:])
+	n15, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.MostRecentPlanTimestamp, dAtA[i:])
 	if err != nil {
 		return 0, err
 	}
-	i += n11
+	i += n15
 	return i, nil
 }
 
@@ -742,19 +894,68 @@ func (m *CollectedStatementStatistics) MarshalTo(dAtA []byte) (int, error) {
 	dAtA[i] = 0xa
 	i++
 	i = encodeVarintAppStats(dAtA, i, uint64(m.Key.Size()))
-	n12, err := m.Key.MarshalTo(dAtA[i:])
+	n16, err := m.Key.MarshalTo(dAtA[i:])
 	if err != nil {
 		return 0, err
 	}
-	i += n12
+	i += n16
 	dAtA[i] = 0x12
 	i++
 	i = encodeVarintAppStats(dAtA, i, uint64(m.Stats.Size()))
-	n13, err := m.Stats.MarshalTo(dAtA[i:])
+	n17, err := m.Stats.MarshalTo(dAtA[i:])
 	if err != nil {
 		return 0, err
 	}
-	i += n13
+	i += n17
+	dAtA[i] = 0x1a
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(len(m.ID)))
+	i += copy(dAtA[i:], m.ID)
+	return i, nil
+}
+
+func (m *CollectedTransactionStatistics) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalTo(dAtA)
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CollectedTransactionStatistics) MarshalTo(dAtA []byte) (int, error) {
+	var i int
+	_ = i
+	var l int
+	_ = l
+	if len(m.StatementIDs) > 0 {
+		for _, s := range m.StatementIDs {
+			dAtA[i] = 0xa
+			i++
+			l = len(s)
+			for l >= 1<<7 {
+				dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+				l >>= 7
+				i++
+			}
+			dAtA[i] = uint8(l)
+			i++
+			i += copy(dAtA[i:], s)
+		}
+	}
+	dAtA[i] = 0x12
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(len(m.App)))
+	i += copy(dAtA[i:], m.App)
+	dAtA[i] = 0x1a
+	i++
+	i = encodeVarintAppStats(dAtA, i, uint64(m.Stats.Size()))
+	n18, err := m.Stats.MarshalTo(dAtA[i:])
+	if err != nil {
+		return 0, err
+	}
+	i += n18
 	return i, nil
 }
 
@@ -851,11 +1052,11 @@ func (m *TxnStats) MarshalTo(dAtA []byte) (int, error) {
 	dAtA[i] = 0x12
 	i++
 	i = encodeVarintAppStats(dAtA, i, uint64(m.TxnTimeSec.Size()))
-	n14, err := m.TxnTimeSec.MarshalTo(dAtA[i:])
+	n19, err := m.TxnTimeSec.MarshalTo(dAtA[i:])
 	if err != nil {
 		return 0, err
 	}
-	i += n14
+	i += n19
 	dAtA[i] = 0x18
 	i++
 	i = encodeVarintAppStats(dAtA, i, uint64(m.CommittedCount))
@@ -908,6 +1109,25 @@ func (m *StatementStatistics) Size() (n int) {
 	return n
 }
 
+func (m *TransactionStatistics) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	n += 1 + sovAppStats(uint64(m.Count))
+	n += 1 + sovAppStats(uint64(m.MaxRetries))
+	l = m.NumRows.Size()
+	n += 1 + l + sovAppStats(uint64(l))
+	l = m.ServiceLat.Size()
+	n += 1 + l + sovAppStats(uint64(l))
+	l = m.RetryLat.Size()
+	n += 1 + l + sovAppStats(uint64(l))
+	l = m.CommitLat.Size()
+	n += 1 + l + sovAppStats(uint64(l))
+	return n
+}
+
 func (m *SensitiveInfo) Size() (n int) {
 	if m == nil {
 		return 0
@@ -962,6 +1182,27 @@ func (m *CollectedStatementStatistics) Size() (n int) {
 	n += 1 + l + sovAppStats(uint64(l))
 	l = m.Stats.Size()
 	n += 1 + l + sovAppStats(uint64(l))

Leaderboard for this case

hard · 2 of 9 bots fully caught it (22% solve rate) · 64% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 Drape (Deep Review) solved 4/4 100.0% 8 0
2 Drape (Review) solved 4/4 100.0% 6 0
3 Cubic partial 3/4 85.7% 5 0
4 greptile partial 3/4 85.7% 6 0
5 Mjolnir (Opus 5.5) partial 3/4 85.7% 7 0
6 Claude Code (Opus 5.5) partial 2/4 71.4% 4 0
7 cursor partial 2/4 71.4% 5 0
8 Mjolnir (Sonnet 5.5) partial 2/4 71.4% 4 0
9 qodo miss 0/4 0.0% 0 0

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 medium ✓ exact
d3 critical ✓ off by one
d4 medium ✗ —
valid · matches d3 · impact critical
valid · matches d2 · impact medium
valid · impact low
recordTransaction records Count, ServiceLat, RetryLat, CommitLat and MaxRetries, but never NumRows. No row count is passed in either, so TransactionStatistics.NumRows is always zero even though the API exposes it. [grounded: tree pkg/sql/app_stats.go] [consensus 3/3: valid=3]
minor · impact low
The doc comment is inaccurate: the function returns unscrubbed stats and filters nothing. This is a documentation problem, not a behaviour bug. [grounded: diff-section pkg/sql/conn_executor.go] [consensus 3/3: minor=3]
raw comments (4)
pkg/sql/app_stats.go:183
Nil pointer dereference. When `sql.metrics.statement_details.threshold` is set and a statement runs faster than it, `getStatsForStmt` is called with `createIfNonexistent=false`. If that fingerprint has no entry in `a.stmts` yet (always true the first time), it returns nil, and `return s.ID` panics. Any fast new statement fingerprint crashes the node once the threshold setting is non-zero. Fix: compute the ID from the stmtKey (`constructStatementIDFromStmtKey`) without needing the map entry, or nil-check `s`.
pkg/sql/conn_executor_exec.go:1473
Commit latency can be stale or negative. `sessionStartTransactionCommit` and `sessionEndTransactionCommit` are only written in `commitSQLTransaction` and are never reset per transaction. Several cases read old values: rolled-back transactions; commits via `RELEASE SAVEPOINT cockroach_restart`, which calls `commitSQLTransactionInternal` directly; auto-commit where `txn.IsCommitted()` is already true (1PC); and failed commits, where only the start time is updated so end − start is negative. In each case `getCommitLatency()` uses the previous transaction's timestamps, or an end time older than the start, which corrupts the CommitLat stats.
pkg/sql/app_stats.go:408
`TransactionStatistics.NumRows` is defined in the proto, exposed in the API and merged in `Add`, but `recordTransaction` never records it, so it is always zero.
pkg/sql/conn_executor.go:382
The doc comment on `GetUnscrubbedTxnStats` says the queries are scrubbed and that unscrubbable statements are omitted. Neither is true: it returns unscrubbed transaction stats and filters nothing.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 medium ✓ exact
d3 critical ✓ off by one
d4 medium ✓ exact
valid · matches d3 · impact critical
valid · matches d4 · impact medium
valid · impact low
ConstructStatementID writes the statement text and then the literal markers "failed"/"implicit_txn" with no delimiter. So ("...bfailed", failed=false) and ("...b", failed=true) hash the same bytes and get the same StmtID. The per-statement stats map is keyed on the stmtKey struct, so those buckets stay separate. But the transaction key is built from StmtIDs, so the collision can merge transaction fingerprints. It is real but rarely triggered. [grounded: tree pkg/roachpb/app_stats.go] [consensus 5/5: valid=5]
valid · matches d2 · impact medium
minor · impact low
The newly added doc comment says the stats are scrubbed, but the method does no scrubbing. The finding is accurate, but it only asks for the comment to be fixed and does not claim any behaviour bug. [grounded: tree pkg/sql/conn_executor.go] [consensus 5/5: minor=5]
raw comments (6)
pkg/sql/app_stats.go:184
<!-- cubic:v=72edcbda-c6ee-4eb3-b933-c0f6120a7b20 --> <!-- cubic:review-run=09e7a4dd-4ce6-5d24-af30-8d0859e9c794 --> <!-- metadata:{"confidence":7} --> P1: When sql.metrics.statement_details.threshold is set above zero and the statement is faster than it, getStatsForStmt is now called with createIfNonExistent=false, and getStatsForStmtWithKey returns nil for a fingerprint that is not already in a.stmts. `return s.ID` then dereferences nil and panics on the first sub-threshold execution of each fingerprint. Return the statement ID derived from the key instead of reading s.ID (or nil-check s before use). <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/sql/app_stats.go, line 184: <comment>When sql.metrics.statement_details.threshold is set above zero and the statement is faster than it, getStatsForStmt is now called with createIfNonExistent=false, and getStatsForStmtWithKey returns nil for a fingerprint that is not already in a.stmts. `return s.ID` then dereferences nil and panics on the first sub-threshold execution of each fingerprint. Return the statement ID derived from the key instead of reading s.ID (or nil-check s before use).</comment> <file context> @@ -131,48 +159,60 @@ func (a *appStats) recordStatement( + // be recorded. We still need to return the statement ID though, for + // transaction level metrics tracking. + if !createIfNonExistent { + return s.ID + } + </file context> ``` </details>
pkg/sql/app_stats.go:34
<!-- cubic:v=ac551a7a-0016-4127-93d4-76aa6b843726 --> <!-- cubic:review-run=09e7a4dd-4ce6-5d24-af30-8d0859e9c794 --> <!-- metadata:{"confidence":6} --> P2: The new txns map is never cleared by resetAndMaybeDumpStats, which only copies and resets a.stmts, so per-transaction stats stay in a.txns for the lifetime of the node instead of being flushed into the target (reportedStats) and released. Reset and copy a.txns alongside a.stmts, e.g. include txns in aCopy and replace a.txns with a fresh map of len(a.txns)/2. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/sql/app_stats.go, line 60: <comment>The new txns map is never cleared by resetAndMaybeDumpStats, which only copies and resets a.stmts, so per-transaction stats stay in a.txns for the lifetime of the node instead of being flushed into the target (reportedStats) and released. Reset and copy a.txns alongside a.stmts, e.g. include txns in aCopy and replace a.txns with a fresh map of len(a.txns)/2.</comment> <file context> @@ -34,40 +34,68 @@ import ( + st *cluster.Settings + stmts map[stmtKey]*stmtStats + txnCounts transactionCounts + txns map[txnKey]*txnStats +} + </file context> ``` </details>
pkg/roachpb/app_stats.go:30
<!-- cubic:v=fc66799a-1ad8-422b-8c21-1f0da92a22f7 --> <!-- cubic:review-run=09e7a4dd-4ce6-5d24-af30-8d0859e9c794 --> <!-- metadata:{"confidence":6} --> P2: ConstructStatementID concatenates the anonymized statement with the "failed"/"implicit_txn" markers and no separator, so distinct keys hash identical bytes: ("SELECT a FROM t bfailed", failed=false) and ("SELECT a FROM t b", failed=true) both hash "SELECT a FROM t bfailed". Those two fingerprints then share one StmtID, one statement stats bucket, and one transaction fingerprint. Write a delimiter after the statement text, e.g. h.Write([]byte{0}). <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/roachpb/app_stats.go, line 30: <comment>ConstructStatementID concatenates the anonymized statement with the "failed"/"implicit_txn" markers and no separator, so distinct keys hash identical bytes: ("SELECT a FROM t bfailed", failed=false) and ("SELECT a FROM t b", failed=true) both hash "SELECT a FROM t bfailed". Those two fingerprints then share one StmtID, one statement stats bucket, and one transaction fingerprint. Write a delimiter after the statement text, e.g. h.Write([]byte{0}).</comment> <file context> @@ -11,11 +11,32 @@ +// (see stmtKey). +func ConstructStatementID(anonymizedStmt string, failed bool, implicitTxn bool) StmtID { + h := fnv.New128() + h.Write([]byte(anonymizedStmt)) + if failed { + h.Write([]byte("failed")) </file context> ``` </details> ```suggestion h.Write([]byte(anonymizedStmt)) h.Write([]byte{0}) ```
pkg/sql/conn_executor_exec.go:735
<!-- cubic:v=af29a6aa-710a-43fb-b404-48c7206969f3 --> <!-- cubic:review-run=09e7a4dd-4ce6-5d24-af30-8d0859e9c794 --> <!-- metadata:{"confidence":7} --> P2: When a commit fails (`commitSQLTransactionInternal` returns an error) or a transaction is rolled back, `sessionEndTransactionCommit` is never set, yet `recordTransaction` still records `getCommitLatency()` for every finished transaction. The result is a stale or negative `CommitLat` (commit start minus an earlier end, or minus the zero time on a session's first failure) in the transaction statistics. Record the end time on all paths, e.g. with a `defer` covering the error return, or skip recording commit latency when the transaction did not commit. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/sql/conn_executor_exec.go, line 730: <comment>When a commit fails (`commitSQLTransactionInternal` returns an error) or a transaction is rolled back, `sessionEndTransactionCommit` is never set, yet `recordTransaction` still records `getCommitLatency()` for every finished transaction. The result is a stale or negative `CommitLat` (commit start minus an earlier end, or minus the zero time on a session's first failure) in the transaction statistics. Record the end time on all paths, e.g. with a `defer` covering the error return, or skip recording commit latency when the transaction did not commit.</comment> <file context> @@ -726,10 +727,12 @@ func (ex *connExecutor) checkDescriptorTwoVersionInvariant(ctx context.Context) func (ex *connExecutor) commitSQLTransaction( ctx context.Context, stmt tree.Statement, ) (fsm.Event, fsm.EventPayload) { + ex.phaseTimes[sessionStartTransactionCommit] = timeutil.Now() err := ex.commitSQLTransactionInternal(ctx, stmt) if err != nil { </file context> ``` </details> ```suggestion ex.phaseTimes[sessionStartTransactionCommit] = timeutil.Now() defer func() { ex.phaseTimes[sessionEndTransactionCommit] = timeutil.Now() }() err := ex.commitSQLTransactionInternal(ctx, stmt) if err != nil { return ex.makeErrEvent(err, stmt) } ```
pkg/sql/conn_executor.go:384
<!-- cubic:v=2a28b1b5-6b51-4562-b47c-d6cf10e73b0d --> <!-- cubic:review-run=09e7a4dd-4ce6-5d24-af30-8d0859e9c794 --> <!-- metadata:{"confidence":9} --> P3: The doc comment on `GetUnscrubbedTxnStats` describes scrubbed behavior: it claims the queries are "scrubbed of their identifiers" and that statements which cannot be scrubbed are omitted. The method actually calls `getUnscrubbedTxnStats`, which does no scrubbing, so the comment contradicts both the name and the implementation (and it mentions a "returned map" that does not exist). Rewrite the comment to state that identifiers are not scrubbed. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/sql/conn_executor.go, line 382: <comment>The doc comment on `GetUnscrubbedTxnStats` describes scrubbed behavior: it claims the queries are "scrubbed of their identifiers" and that statements which cannot be scrubbed are omitted. The method actually calls `getUnscrubbedTxnStats`, which does no scrubbing, so the comment contradicts both the name and the implementation (and it mentions a "returned map" that does not exist). Rewrite the comment to state that identifiers are not scrubbed.</comment> <file context> @@ -379,6 +379,13 @@ func (s *Server) GetUnscrubbedStmtStats() []roachpb.CollectedStatementStatistics return s.sqlStats.getUnscrubbedStmtStats(s.cfg.VirtualSchemas) } +// GetUnscrubbedTxnStats returns the same transaction statistics by app, with +// the queries scrubbed of their identifiers. Any statement which cannot be +// scrubbed will be omitted from the returned map. </file context> ``` </details> ```suggestion // GetUnscrubbedTxnStats returns the transaction statistics by app, with // identifiers (e.g. table and column names) not scrubbed from the statements. ```
PR-level
<!-- cubic:review-summary:start --> **5 issues found** across 14 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="pkg/sql/app_stats.go"> <violation number="1" location="pkg/sql/app_stats.go:60"> P2: The new txns map is never cleared by resetAndMaybeDumpStats, which only copies and resets a.stmts, so per-transaction stats stay in a.txns for the lifetime of the node instead of being flushed into the target (reportedStats) and released. Reset and copy a.txns alongside a.stmts, e.g. include txns in aCopy and replace a.txns with a fresh map of len(a.txns)/2.</violation> <violation number="2" location="pkg/sql/app_stats.go:184"> P1: When sql.metrics.statement_details.threshold is set above zero and the statement is faster than it, getStatsForStmt is now called with createIfNonExistent=false, and getStatsForStmtWithKey returns nil for a fingerprint that is not already in a.stmts. `return s.ID` then dereferences nil and panics on the first sub-threshold execution of each fingerprint. Return the statement ID derived from the key instead of reading s.ID (or nil-check s before use).</violation> </file> <file name="pkg/roachpb/app_stats.go"> <violation number="1" location="pkg/roachpb/app_stats.go:30"> P2: ConstructStatementID concatenates the anonymized statement with the "failed"/"implicit_txn" markers and no separator, so distinct keys hash identical bytes: ("SELECT a FROM t bfailed", failed=false) and ("SELECT a FROM t b", failed=true) both hash "SELECT a FROM t bfailed". Those two fingerprints then share one StmtID, one statement stats bucket, and one transaction fingerprint. Write a delimiter after the statement text, e.g. h.Write([]byte{0}).</violation> </file> <file name="pkg/sql/conn_executor_exec.go"> <violation number="1" location="pkg/sql/conn_executor_exec.go:730"> P2: When a commit fails (`commitSQLTransactionInternal` returns an error) or a transaction is rolled back, `sessionEndTransactionCommit` is never set, yet `recordTransaction` still records `getCommitLatency()` for every finished transaction. The result is a stale or negative `CommitLat` (commit start minus an earlier end, or minus the zero time on a session's first failure) in the transaction statistics. Record the end time on all paths, e.g. with a `defer` covering the error return, or skip recording commit latency when the transaction did not commit.</violation> </file> <file name="pkg/sql/conn_executor.go"> <violation number="1" location="pkg/sql/conn_executor.go:382"> P3: The doc comment on `GetUnscrubbedTxnStats` describes scrubbed behavior: it claims the queries are "scrubbed of their identifiers" and that statements which cannot be scrubbed are omitted. The method actually calls `getUnscrubbedTxnStats`, which does no scrubbing, so the comment contradicts both the name and the implementation (and it mentions a "returned map" that does not exist). Rewrite the comment to state that identifiers are not scrubbed.</violation> </file> ``` </details> <sub>**Tip**: cubic can generate docs of your entire codebase and keep them up to date. Try it [here](https://docs.cubic.dev/wiki/ai-wiki?utm_source=github).<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/28/ai_pr_review_github_delivery_477ec7f79682a44271fdb6a3e7076659dd9bdf1b94b03cb369d10414c51bf788?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F28)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_477ec7f79682a44271fdb6a3e7076659dd9bdf1b94b03cb369d10414c51bf788:e4f365716ea5a16a2c56bae7c0bda207dc991e5a:09e7a4dd-4ce6-5d24-af30-8d0859e9c794 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 medium ✗ —
d3 critical ✓ off by one
d4 medium ✓ off by one
valid · matches d3 · impact critical
valid · matches d4 · impact medium
valid · impact low
The change adds ID to roachpb.CollectedStatementStatistics and exposes txn statement_ids, but StatementsLocal only copies KeyData/NodeID and Stats, and the serverpb message has no id field, so the IDs cannot be joined via the API. [grounded: tree pkg/server/statements.go] [consensus 5/5: valid=5]
valid · impact low
recordTransaction records Count, ServiceLat, RetryLat, CommitLat and MaxRetries but never NumRows, so the documented num_rows field is always zero. [grounded: diff] [consensus 5/5: valid=5]
valid · impact medium
With stmt stats disabled, recordStatement returns "" and it is still appended to transactionStatementIDs; hashing only empty strings gives the same txnKey for every transaction, merging all txn stats into one bucket while txn stats remain enabled. [grounded: diff] [consensus 5/5: valid=5]
raw comments (6)
pkg/sql/app_stats.go:184
### Nil panic below latency threshold **High Severity** <!-- DESCRIPTION START --> When `sql.metrics.statement_details.threshold` is set and a statement is below that latency, `getStatsForStmt` can return nil, and `return s.ID` dereferences it. That panics the SQL session on the first execution of a fast fingerprint. The default threshold is zero, so this only triggers once the public setting is non-zero. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 6d0c8110-5323-4b3b-837b-9265e178fe51 --> <!-- LOCATIONS START pkg/sql/app_stats.go#L182-L184 pkg/sql/app_stats.go#L166-L178 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`pkg/sql/app_stats.go#L166-L178`](https://github.com/drape-io/crbench-cursor-2026-09/blob/f322ed633431e4f75a3eba6df94453774151d12c/pkg/sql/app_stats.go#L166-L178) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjcwZjVmNmM4LWFiYTYtNDcyMi04ZTZhLWViYzdiMGFlOGIxMSIsImVuY3J5cHRpb25LZXkiOiI5Y0RXd2pFLWlwS1lfaHdGTEdzTTMxVTdKNVgxOUVic2Mwak1uamRieE93IiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjcwZjVmNmM4LWFiYTYtNDcyMi04ZTZhLWViYzdiMGFlOGIxMSIsImVuY3J5cHRpb25LZXkiOiI5Y0RXd2pFLWlwS1lfaHdGTEdzTTMxVTdKNVgxOUVic2Mwak1uamRieE93IiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MjksImNvbW1pdFNoYSI6ImYzMjJlZDYzMzQzMWU0Zjc1YTNlYmE2ZGY5NDQ1Mzc3NDE1MWQxMmMiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f322ed633431e4f75a3eba6df94453774151d12c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
pkg/sql/app_stats.go:520
### Txn stats not reset or flushed **High Severity** <!-- DESCRIPTION START --> `resetAndMaybeDumpStats` copies and replaces only `a.stmts`. The new `a.txns` map is neither flushed into `target` nor cleared. Periodic reset therefore never releases transaction fingerprints, statement stats look fresh while txn stats keep accumulating, and transaction details never land in the reported-stats pool. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: c4a13ea8-f470-4f60-85c9-21f25a6e30f2 --> <!-- LOCATIONS START pkg/sql/app_stats.go#L507-L516 pkg/sql/app_stats.go#L465-L469 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`pkg/sql/app_stats.go#L465-L469`](https://github.com/drape-io/crbench-cursor-2026-09/blob/f322ed633431e4f75a3eba6df94453774151d12c/pkg/sql/app_stats.go#L465-L469) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmJhOTZmYzcwLWI0NjEtNDViOS1hNzg1LWUyMWNkN2RmNzExMiIsImVuY3J5cHRpb25LZXkiOiJIMTR1ZVVRTzJCZW1rNEhkcTlDbUZVbjAxOUk4VGwzRkZKVlc3bTVUVzU0IiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmJhOTZmYzcwLWI0NjEtNDViOS1hNzg1LWUyMWNkN2RmNzExMiIsImVuY3J5cHRpb25LZXkiOiJIMTR1ZVVRTzJCZW1rNEhkcTlDbUZVbjAxOUk4VGwzRkZKVlc3bTVUVzU0IiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MjksImNvbW1pdFNoYSI6ImYzMjJlZDYzMzQzMWU0Zjc1YTNlYmE2ZGY5NDQ1Mzc3NDE1MWQxMmMiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f322ed633431e4f75a3eba6df94453774151d12c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
pkg/server/statements.go:106
### Statement IDs dropped from API **Medium Severity** <!-- DESCRIPTION START --> Transaction stats expose `statement_ids`, but `StatementsLocal` copies only `key` and `stats` into the HTTP/gRPC response, and `StatementsResponse.CollectedStatementStatistics` has no `id` field. Clients cannot join transactions to statements in the same payload without reimplementing the FNV-128 ID. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: cee02477-435e-4938-8896-2bd0ee38724f --> <!-- LOCATIONS START pkg/server/statements.go#L108-L116 pkg/server/serverpb/status.proto#L811-L815 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`pkg/server/serverpb/status.proto#L811-L815`](https://github.com/drape-io/crbench-cursor-2026-09/blob/f322ed633431e4f75a3eba6df94453774151d12c/pkg/server/serverpb/status.proto#L811-L815) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjZiOThmMTk2LThjNzctNDc5Yy05MGE4LTQ5MmM3OWU2MzA5NiIsImVuY3J5cHRpb25LZXkiOiI3c3AzMGhlVURSLWlWSDg4NV83WnFKa0VyaTgwYjl0ckg4dXQ1UkJwQzBVIiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjZiOThmMTk2LThjNzctNDc5Yy05MGE4LTQ5MmM3OWU2MzA5NiIsImVuY3J5cHRpb25LZXkiOiI3c3AzMGhlVURSLWlWSDg4NV83WnFKa0VyaTgwYjl0ckg4dXQ1UkJwQzBVIiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MjksImNvbW1pdFNoYSI6ImYzMjJlZDYzMzQzMWU0Zjc1YTNlYmE2ZGY5NDQ1Mzc3NDE1MWQxMmMiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f322ed633431e4f75a3eba6df94453774151d12c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
pkg/sql/app_stats.go:413
### Transaction num_rows never recorded **Medium Severity** <!-- DESCRIPTION START --> `TransactionStatistics` documents `num_rows` as rows returned or observed across the transaction, and `Add` merges it, but `recordTransaction` never records a row count. Every transaction in the API therefore reports `num_rows` as zero. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 4cf8af93-14fa-4fce-aaee-81b4dcc916c5 --> <!-- LOCATIONS START pkg/sql/app_stats.go#L380-L414 pkg/roachpb/app_stats.proto#L100-L103 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`pkg/roachpb/app_stats.proto#L100-L103`](https://github.com/drape-io/crbench-cursor-2026-09/blob/f322ed633431e4f75a3eba6df94453774151d12c/pkg/roachpb/app_stats.proto#L100-L103) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjE5OTBkNzhkLWJiM2YtNGI2Yi1hM2VmLWMwYTBkMzc2N2FjMiIsImVuY3J5cHRpb25LZXkiOiItalpMS2U4bElPNUVXQXB0aktJT2pTdjJDTE5jTEVhM0ZfUTRpcEFkRUdVIiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjE5OTBkNzhkLWJiM2YtNGI2Yi1hM2VmLWMwYTBkMzc2N2FjMiIsImVuY3J5cHRpb25LZXkiOiItalpMS2U4bElPNUVXQXB0aktJT2pTdjJDTE5jTEVhM0ZfUTRpcEFkRUdVIiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MjksImNvbW1pdFNoYSI6ImYzMjJlZDYzMzQzMWU0Zjc1YTNlYmE2ZGY5NDQ1Mzc3NDE1MWQxMmMiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f322ed633431e4f75a3eba6df94453774151d12c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
pkg/sql/app_stats.go:165
### Empty IDs collapse all transactions **Medium Severity** <!-- DESCRIPTION START --> If `sql.metrics.statement_details.enabled` is false, every statement returns an empty ID that is still appended onto the transaction. Transaction fingerprints hash those IDs with no separators, so every transaction shares one bucket and `statement_ids` cannot be joined to statements. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: b125f8cb-abf8-412a-915f-fbfeea528f37 --> <!-- LOCATIONS START pkg/sql/app_stats.go#L162-L165 pkg/sql/executor_statement_metrics.go#L185-L189 pkg/sql/conn_executor_exec.go#L1463-L1470 LOCATIONS END --> <details> <summary>Additional Locations (2)</summary> - [`pkg/sql/executor_statement_metrics.go#L185-L189`](https://github.com/drape-io/crbench-cursor-2026-09/blob/f322ed633431e4f75a3eba6df94453774151d12c/pkg/sql/executor_statement_metrics.go#L185-L189) - [`pkg/sql/conn_executor_exec.go#L1463-L1470`](https://github.com/drape-io/crbench-cursor-2026-09/blob/f322ed633431e4f75a3eba6df94453774151d12c/pkg/sql/conn_executor_exec.go#L1463-L1470) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjFmNTc2OTNiLWVlODAtNDU3OC05Mjk0LTZkZGM4YTVlYmNiOSIsImVuY3J5cHRpb25LZXkiOiJfaFN1TjgwRlJyYUFIcjliMG92U0RCZlFVVjNVSTAtMHotMmloYUNYZUx3IiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjFmNTc2OTNiLWVlODAtNDU3OC05Mjk0LTZkZGM4YTVlYmNiOSIsImVuY3J5cHRpb25LZXkiOiJfaFN1TjgwRlJyYUFIcjliMG92U0RCZlFVVjNVSTAtMHotMmloYUNYZUx3IiwiYnJhbmNoIjoidDItY29ja3JvYWNoLTUyNzA0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MjksImNvbW1pdFNoYSI6ImYzMjJlZDYzMzQzMWU0Zjc1YTNlYmE2ZGY5NDQ1Mzc3NDE1MWQxMmMiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f322ed633431e4f75a3eba6df94453774151d12c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 5 potential issues. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTozNDEzNGI3My1mOWRmLTQ3OGUtOTU1NC1kMTg0ZDJhMTIyNjgiLCJlbmNyeXB0aW9uS2V5IjoiVUdFUmgzc2NodEZnUlEzdklMN013NTBrUmRMaU5JRHFSQnZGYUR2ZUd4RSIsImJyYW5jaCI6InQyLWNvY2tyb2FjaC01MjcwNCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f322ed633431e4f75a3eba6df94453774151d12c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ off by one
d2 medium ✓ exact
d3 critical ✓ off by one
d4 medium ✓ exact
valid · impact medium
With statement stats disabled, every statement ID is "". The txn key is an FNV hash of the concatenated IDs, so hashing only empty writes gives the same key for every transaction. Unrelated transactions are then merged into one entry. [grounded: tree pkg/sql/app_stats.go] [consensus 3/3: valid=3]
valid · matches d3 · impact critical
valid · impact low
recordTransaction records ServiceLat, RetryLat and CommitLat but has no NumRows.Record call. The newly exposed NumRows field therefore always stays zero. [grounded: tree pkg/sql/app_stats.go] [consensus 3/3: valid=3]
valid · matches d2 · impact medium
valid · matches d4 · impact medium
valid · impact low
The start-of-commit time is set before the commit, but the end-of-commit time is only set on success. When the commit fails and the txn is later finished, getCommitLatency subtracts the new start from a stale end, which gives a negative or bogus value. [grounded: tree pkg/sql/conn_executor_exec.go] [consensus 3/3: valid=3]
valid · matches d1 · impact medium
valid · impact medium
Transactions in the response carry StatementIDs, but StatementsLocal never copies stmt.ID into the statement entries, and the serverpb message has no ID field. Consumers cannot match the transaction IDs to statements, so the change is incomplete. [grounded: tree pkg/server/statements.go] [consensus 3/3: valid=3]
raw comments (8)
pkg/sql/executor_statement_metrics.go:191
**All transactions merged when statement stats are off** With statement stats disabled but transaction stats on, `recordStatement` returns an empty ID for every statement, so hashing empty IDs gives the same key for every transaction regardless of contents. Compute the statement ID independently of whether statement stats are enabled, or skip txn stats when IDs are invalid. ``` pkg/sql/app_stats.go:163 if !stmtStatsEnable.Get(&a.st.SV) { pkg/sql/app_stats.go:164 return invalidStmtID pkg/sql/executor_statement_metrics.go:189 ex.extraTxnState.transactionStatementIDs, stmtID) pkg/sql/executor_statement_metrics.go:191 if log.V(2) { pkg/sql/app_stats.go:256 func (a *appStats) getStatsForTxnWithKey(key txnKey, stmtIDs []roachpb.StmtID) *txnStats { pkg/sql/app_stats.go:257 a.Lock() pkg/sql/app_stats.go:258 defer a.Unlock() pkg/sql/app_stats.go:259 // Retrieve the per-transaction statistic object, and create it if it doesn't pkg/sql/app_stats.go:260 // exist yet. pkg/sql/app_stats.go:261 s, ok := a.txns[key] ```
pkg/sql/app_stats.go:184
**Nil pointer panic for fast statements under threshold** When `sql.metrics.statement_details.threshold` is set and a statement that has no stats entry yet runs faster than it, `getStatsForStmt` returns nil (no entry is created), and `return s.ID` then panics. When the entry is nil, compute the ID with constructStatementIDFromStmtKey instead of reading s.ID. ``` pkg/sql/app_stats.go:167 createIfNonExistent := true pkg/sql/app_stats.go:168 // If the statement is below the latency threshold, we don't need to create pkg/sql/app_stats.go:169 // an entry in the stmts map for it. pkg/sql/app_stats.go:170 if t := sqlStatsCollectionLatencyThreshold.Get(&a.st.SV); t > 0 && t.Seconds() >= svcLat { pkg/sql/app_stats.go:242 ) *stmtStats { pkg/sql/app_stats.go:243 a.Lock() pkg/sql/app_stats.go:244 // Retrieve the per-statement statistic object, and create it if it pkg/sql/app_stats.go:245 // doesn't exist yet. pkg/sql/app_stats.go:246 s, ok := a.stmts[key] pkg/sql/app_stats.go:247 if !ok && createIfNonexistent { ```
pkg/sql/app_stats.go:406
**Transaction NumRows is never recorded** `recordTransaction` updates Count and the latencies but never `NumRows`, so `TransactionStatistics.NumRows` is always zero even though the API exposes it. Add up rowsAffected for each statement in the txn and record it. ``` pkg/sql/app_stats.go:381 func (a *appStats) recordTransaction( pkg/sql/app_stats.go:382 key txnKey, pkg/sql/app_stats.go:383 retryCount int64, pkg/sql/app_stats.go:384 statementIDs []roachpb.StmtID, pkg/roachpb/app_stats.proto:101 // NumRows collects the total number of rows returned or observed across all pkg/roachpb/app_stats.proto:102 // statements. pkg/roachpb/app_stats.proto:103 optional NumericStat num_rows = 3 [(gogoproto.nullable) = false]; ```
pkg/sql/conn_executor_exec.go:1474
**Commit latency uses stale timestamps from earlier txns** Commit phase times are only set in `commitSQLTransaction` on success. Rollbacks, failed commits, and 1PC implicit commits make `getCommitLatency` read a previous transaction's timestamps. Reset both commit phase times when the txn starts. ``` pkg/sql/conn_executor_exec.go:730 ex.phaseTimes[sessionStartTransactionCommit] = timeutil.Now() pkg/sql/conn_executor_exec.go:731 err := ex.commitSQLTransactionInternal(ctx, stmt) pkg/sql/conn_executor_exec.go:732 if err != nil { pkg/sql/conn_executor_exec.go:733 return ex.makeErrEvent(err, stmt) pkg/sql/conn_executor_exec.go:1391 if txn.IsCommitted() { pkg/sql/conn_executor_exec.go:1392 log.Event(ctx, "statement execution committed the txn") pkg/sql/conn_executor_exec.go:1393 return eventTxnFinish{}, eventTxnFinishPayload{commit: true} pkg/sql/conn_executor_exec.go:1394 } pkg/sql/conn_executor_exec.go:734 } pkg/sql/conn_executor_exec.go:735 ex.phaseTimes[sessionEndTransactionCommit] = timeutil.Now() ```
pkg/sql/app_stats.go:460
**Transaction stats never reset and grow forever** `resetAndMaybeDumpStats` clears and copies only `a.stmts`, never the new `a.txns` map. Transaction stats survive every reset and never reach the reported stats. Copy `txns` into aCopy and reset `a.txns` alongside `a.stmts`. ``` pkg/sql/app_stats.go:457 a := &appStats{ pkg/sql/app_stats.go:458 st: s.st, pkg/sql/app_stats.go:459 stmts: make(map[stmtKey]*stmtStats), pkg/sql/app_stats.go:460 txns: make(map[txnKey]*txnStats), pkg/sql/app_stats.go:509 aCopy := &appStats{st: a.st, stmts: a.stmts} pkg/sql/app_stats.go:515 a.stmts = make(map[stmtKey]*stmtStats, len(a.stmts)/2) ```
pkg/sql/conn_executor_exec.go:733
**Failed commit records negative commit latency** On commit error the start time is updated but the end time keeps the previous transaction's value, so the recorded commit latency is negative. Skip commit latency when the commit failed. ``` pkg/sql/conn_executor_exec.go:730 ex.phaseTimes[sessionStartTransactionCommit] = timeutil.Now() pkg/sql/conn_executor_exec.go:731 err := ex.commitSQLTransactionInternal(ctx, stmt) pkg/sql/conn_executor_exec.go:732 if err != nil { pkg/sql/conn_executor_exec.go:733 return ex.makeErrEvent(err, stmt) pkg/sql/executor_statement_metrics.go:96 func (p *phaseTimes) getCommitLatency() time.Duration { pkg/sql/executor_statement_metrics.go:97 return p[sessionEndTransactionCommit].Sub(p[sessionStartTransactionCommit]) pkg/sql/executor_statement_metrics.go:98 } ```
pkg/sql/app_stats.go:235
**Statement ID hashed and formatted on every execution** `getStatsForStmt` now runs an FNV-128 hash plus `fmt.Sprintf` for every statement execution, even when the entry already exists and its ID is already stored. Compute the ID only inside getStatsForStmtWithKey when creating a new entry. ``` pkg/sql/app_stats.go:235 stmtID := constructStatementIDFromStmtKey(key) pkg/sql/app_stats.go:237 return a.getStatsForStmtWithKey(key, stmtID, createIfNonexistent) pkg/roachpb/app_stats.go:28 func ConstructStatementID(anonymizedStmt string, failed bool, implicitTxn bool) StmtID { pkg/roachpb/app_stats.go:29 h := fnv.New128() pkg/roachpb/app_stats.go:30 h.Write([]byte(anonymizedStmt)) pkg/roachpb/app_stats.go:31 if failed { pkg/roachpb/app_stats.go:32 h.Write([]byte("failed")) pkg/roachpb/app_stats.go:33 } pkg/roachpb/app_stats.go:34 if implicitTxn { pkg/roachpb/app_stats.go:35 h.Write([]byte("implicit_txn")) ```
pkg/server/statements.go:115
**Statement IDs missing from the statements response** Transactions report `StatementIDs`, but `StatementsLocal` drops `stmt.ID` when building each statement entry, and the response message has no field for it. API consumers can't match a transaction's IDs to statements. Add an ID field to `StatementsResponse.CollectedStatementStatistics` and fill it from `stmt.ID`. ``` pkg/server/statements.go:102 for i, txn := range txnStats { pkg/server/statements.go:103 resp.Transactions[i] = serverpb.StatementsResponse_ExtendedCollectedTransactionStatistics{ pkg/server/statements.go:104 StatsData: txn, pkg/server/statements.go:105 NodeID: s.gossip.NodeID.Get(), pkg/server/serverpb/status.proto:812 message CollectedStatementStatistics { pkg/server/serverpb/status.proto:813 ExtendedStatementStatisticsKey key = 1 [(gogoproto.nullable) = false]; pkg/server/serverpb/status.proto:814 cockroach.sql.StatementStatistics stats = 2 [(gogoproto.nullable) = false]; pkg/server/serverpb/status.proto:815 } pkg/sql/app_stats.go:679 ret = append(ret, roachpb.CollectedStatementStatistics{ pkg/sql/app_stats.go:680 Key: k, ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ off by one
d2 medium ✓ exact
d3 critical ✓ off by one
d4 medium ✓ exact
valid · matches d3 · impact critical
valid · impact low
recordTransaction records ServiceLat, RetryLat, CommitLat and MaxRetries but never NumRows. The NumRows field this PR added is therefore always zero, yet it is still merged and returned by the API. [grounded: tree pkg/sql/app_stats.go] [consensus 3/3: valid=3]
valid · matches d4 · impact medium
valid · matches d2 · impact medium
valid · matches d1 · impact medium
minor · impact low
The new doc comment says the function scrubs and omits statements, but getUnscrubbedTxnStats does neither. The comment is inaccurate, and fixing it is a documentation correction rather than a code behavior bug. [grounded: tree pkg/sql/conn_executor.go] [consensus 3/3: minor=3]
raw comments (6)
pkg/sql/app_stats.go:187
**Nil pointer panic for fast statements below threshold** When the latency threshold is set and a statement is fast, `createIfNonExistent` is false, so `getStatsForStmt` returns nil for a fingerprint never recorded before. The code then reads `s.ID` on that nil pointer and panics. Compute the ID with constructStatementIDFromStmtKey (or handle nil s) instead of dereferencing s.ID. ``` pkg/sql/app_stats.go:168 // If the statement is below the latency threshold, we don't need to create pkg/sql/app_stats.go:169 // an entry in the stmts map for it. pkg/sql/app_stats.go:170 if t := sqlStatsCollectionLatencyThreshold.Get(&a.st.SV); t > 0 && t.Seconds() >= svcLat { pkg/sql/app_stats.go:171 createIfNonExistent = false ```
pkg/sql/app_stats.go:408
**Transaction NumRows stat is never recorded** `TransactionStatistics.num_rows` is documented as the rows returned across all statements, but `recordTransaction` never records it and takes no row count. It is always zero and still merged and returned by the API. Accumulate rows per transaction and record them in recordTransaction, or drop the field. ``` pkg/sql/app_stats.go:381 func (a *appStats) recordTransaction( pkg/sql/app_stats.go:382 key txnKey, pkg/sql/app_stats.go:383 retryCount int64, pkg/sql/app_stats.go:384 statementIDs []roachpb.StmtID, ```
pkg/sql/app_stats.go:460
**Transaction stats map never reset** `resetStats` clears `a.stmts` but not the new `a.txns` map. Transaction stats never reset and grow without bound, one entry per distinct statement-ID sequence. Reset `a.txns` alongside `a.stmts` in resetStats. ``` pkg/sql/app_stats.go:457 a := &appStats{ pkg/sql/app_stats.go:458 st: s.st, pkg/sql/app_stats.go:459 stmts: make(map[stmtKey]*stmtStats), pkg/sql/app_stats.go:460 txns: make(map[txnKey]*txnStats), ```
pkg/sql/conn_executor_exec.go:730
**Commit latency uses stale timestamps** `sessionStartTransactionCommit`/`sessionEndTransactionCommit` are only set in `commitSQLTransaction` and never reset at txn start. Implicit txns, rollbacks, and failed commits compute `getCommitLatency` from values left over by an earlier txn. Reset both commit phase times in recordTransactionStart (and set end on failure too). ``` pkg/sql/conn_executor_exec.go:730 ex.phaseTimes[sessionStartTransactionCommit] = timeutil.Now() pkg/sql/conn_executor_exec.go:731 err := ex.commitSQLTransactionInternal(ctx, stmt) pkg/sql/conn_executor_exec.go:732 if err != nil { pkg/sql/conn_executor_exec.go:733 return ex.makeErrEvent(err, stmt) ```
pkg/sql/app_stats.go:236
**Statement ID hashed on every execution** `getStatsForStmt` computes an FNV-128 hash plus `fmt.Sprintf("%x")` on every statement execution, though the ID is only needed on creation. `shouldSaveLogicalPlanDescription` pays this for an unused ID. Compute the ID only on creation, or cache it on stmtStats. ``` pkg/sql/app_stats.go:230 key.anonymizedStmt = stmt.AnonymizedStr pkg/sql/app_stats.go:231 } else { pkg/sql/app_stats.go:232 key.anonymizedStmt = anonymizeStmt(stmt.AST) pkg/sql/app_stats.go:233 } ```
pkg/sql/conn_executor.go:382
**Doc comment claims scrubbing that doesn't happen** The `GetUnscrubbedTxnStats` comment says queries are scrubbed and unscrubbable statements are omitted. The function returns transaction stats keyed by statement IDs and does no scrubbing or omission. Fix the comment to say it returns unscrubbed per-app transaction stats. ``` pkg/sql/conn_executor.go:382 // GetUnscrubbedTxnStats returns the same transaction statistics by app, with pkg/sql/conn_executor.go:383 // the queries scrubbed of their identifiers. Any statement which cannot be pkg/sql/conn_executor.go:384 // scrubbed will be omitted from the returned map. pkg/sql/conn_executor.go:385 func (s *Server) GetUnscrubbedTxnStats() []roachpb.CollectedTransactionStatistics { ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 medium ✓ off by one
d3 critical ✓ off by one
d4 medium ✓ off by one
valid · matches d3 · impact critical
valid · impact medium
With stmt stats disabled, recordStatement returns the empty invalidStmtID; recordTransaction only checks txnStatsEnable, and hashing empty strings yields the same key for every transaction, collapsing all shapes into one bucket. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d2 · impact medium
valid · impact low
recordTransaction records only service/retry/commit latency and max retries; NumRows is never recorded, so the exported field is always zero. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
ConstructStatementID writes the fingerprint followed by unframed suffixes into the hash, so a failed 'SELECT * FROM t' and a successful 'SELECT * FROM tfailed' hash identical input and get the same ID. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d4 · impact medium
raw comments (6)
pkg/sql/app_stats.go:184
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Threshold filtering panics** When a positive `sql.metrics.statement_details.threshold` filters the first execution of a statement fingerprint, `getStatsForStmtWithKey` returns nil because entry creation is disabled. This branch then dereferences `s.ID`, causing the SQL connection to panic and close instead of completing the statement normally.
pkg/sql/app_stats.go:164
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Empty IDs merge transactions** Statement and transaction statistics can be configured independently, but disabling statement statistics makes every recorded statement ID empty. Transaction statistics still hash those empty IDs, so all transaction shapes for an application collapse into the same bucket, corrupting counts, latencies, and statement references.
pkg/sql/conn_executor_exec.go:1474
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Invalid commit latencies recorded** Commit latency is calculated for every transaction finish, including rollbacks and failed commits, although both timestamps are initialized only after a successful commit. A failed first commit records an enormous negative duration, while later failures can combine a new start with a stale prior end, corrupting the exported latency statistics.
pkg/sql/app_stats.go:410
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Transaction rows stay zero** `TransactionStatistics.NumRows` is defined as the rows returned or observed across all statements, but transaction recording neither receives nor records a row count. Transactions that return or affect rows are therefore exported with a zero-valued `NumRows`, making this API field consistently incorrect.
pkg/roachpb/app_stats.go:36
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Statement IDs can collide** The ID input concatenates the raw fingerprint with unframed status suffixes, so distinct statement keys can deterministically receive the same ID. For example, failed `SELECT * FROM t` and successful `SELECT * FROM tfailed` both hash `SELECT * FROM tfailed`, making their transaction references and aggregation indistinguishable.
PR-level
<h3>Greptile Summary</h3> This PR adds statement identifiers and per-transaction SQL statistics, records transaction timing and retry data in the executor, and exposes the results through the cluster statements status API and generated documentation. - Adds protobuf models for transaction counts, row counts, retries, and latencies. - Tracks ordered statement IDs to fingerprint transaction shapes. - Aggregates transaction statistics across nodes in the status endpoint. - Introduces correctness and lifecycle defects in threshold handling, independent settings, timing, row accounting, map reset, and ID construction. <h3>Confidence Score: 0/5</h3> The PR is not safe to merge because ordinary supported configurations and transaction outcomes can panic connections or publish corrupted statistics, while transaction-shape memory is never reclaimed. The implementation dereferences a missing statement-stat entry under positive latency thresholds, collapses transaction identities when statement collection is disabled, records invalid commit timing on failure paths, leaves transaction row counts unset, never resets an unbounded transaction map, and permits deterministic statement-ID collisions. **Files Needing Attention:** pkg/sql/app_stats.go, pkg/sql/conn_executor_exec.go, pkg/roachpb/app_stats.go, pkg/roachpb/app_stats.proto <details open><summary><h3>Security Review</h3></summary> The new transaction-shape map has no cardinality bound and is omitted from SQL-statistics reset, allowing authenticated SQL workloads to retain increasing amounts of node memory indefinitely. </details> <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | pkg/sql/app_stats.go | Adds per-transaction storage and aggregation but introduces a threshold-path panic, broken independent-setting behavior, missing row accounting, and transaction entries that survive resets. | | pkg/sql/conn_executor_exec.go | Adds transaction timing and sequence fingerprinting, but records invalid commit durations for rollback and failed-commit paths. | | pkg/roachpb/app_stats.go | Adds statement-ID construction and transaction-stat merging, but the unframed hash input permits deterministic ID collisions. | | pkg/roachpb/app_stats.proto | Defines statement IDs and transaction statistics, including a NumRows field that the implementation does not populate. | | pkg/server/statements.go | Exposes local transaction statistics and aggregates records returned by cluster nodes. | | pkg/sql/executor_statement_metrics.go | Appends statement IDs and defines transaction timing calculations consumed by the new statistics path. | | pkg/server/status_test.go | Adds end-to-end status API coverage, but does not exercise threshold filtering, disabled statement statistics, rollback timing, row counts, or reset behavior. | </details> <details open><summary><h3>Sequence Diagram</h3></summary> ```mermaid sequenceDiagram participant Client participant Executor participant StatementStats participant TransactionStats participant StatusAPI Client->>Executor: Execute SQL transaction loop Each statement Executor->>StatementStats: Record fingerprint and return StmtID Executor->>Executor: Append StmtID to transaction sequence end Executor->>Executor: Hash ordered StmtIDs Executor->>TransactionStats: Record retries and latencies StatusAPI->>StatementStats: Read statement statistics StatusAPI->>TransactionStats: Read transaction statistics StatusAPI-->>Client: Cluster StatementsResponse ``` </details> <!-- greptile_failed_comments --> <details><summary><h3>Comments Outside Diff (1)</h3></summary> 1. `pkg/sql/app_stats.go`, line 513-515 ([link](https://github.com/drape-io/crbench-greptile-2026-09/blob/dca55a99172139c4f40e24e74b79abb51f6f11ea/pkg/sql/app_stats.go#L513-L515)) <a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> <a href="#"><img alt="security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2" align="top"></a> **Transaction stats never reset** The normal statistics reset replaces only `a.stmts`; it neither clears nor snapshots the new `a.txns` map. Because every distinct ordered statement sequence creates an entry that retains its full ID slice, a SQL workload can continually create transaction shapes whose memory survives every reset and grows for the node's lifetime. **How this was verified:** SQL statement sequences directly determine persistent transaction-map keys, and the reset path leaves that map reachable without any size limit or eviction. </details> <!-- /greptile_failed_comments --> <sub>Reviews (1): Last reviewed commit: ["Update docs/generated/http/full.md and 1..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/dca55a99172139c4f40e24e74b79abb51f6f11ea) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284320)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 medium ✓ off by one
d3 critical ✓ off by one
d4 medium ✓ exact
valid · matches d3 · impact critical
valid · impact medium
resetAndMaybeDumpStats only resets a.stmts and copies only stmts. The new txns map is never cleared or flushed to the reporting target, so it grows without bound and ignores the reset. [grounded: tree pkg/sql/app_stats.go] [consensus 3/3: valid=3]
valid · matches d2 · impact medium
valid · impact high
When the threshold is above 0 and the statement runs under it, createIfNonExistent is false. getStatsForStmtWithKey then returns nil for a new key, and s.ID dereferences nil. The old code returned early instead. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d4 · impact medium
valid · impact medium
The commit start and end slots are written only in commitSQLTransaction, and the end slot only on success. They are never reset in recordTransactionStart. Rollbacks, failed commits, RELEASE SAVEPOINT commits and already-committed autocommits therefore compute CommitLat from stale or mismatched timestamps. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
recordTransaction records ServiceLat, RetryLat, CommitLat and MaxRetries but never NumRows, so the new NumRows field is always zero. [grounded: diff] [consensus 3/3: valid=3]
raw comments (7)
pkg/sql/app_stats.go:444
[P1] Nil pointer dereference when a statement is below the latency threshold. Location When `sql.stats.statement_collection_latency_threshold` (`sqlStatsCollectionLatencyThreshold`) is set to a value above zero and a statement runs faster than it, `getStatsForStmt` is called with `createIfNonexistent=false`. If that fingerprint isn't already in `a.stmts`, which is the usual case for fast statements and is always the case right after a stats reset, the function returns nil. The new code then runs `return s.ID` on that nil `*stmtStats`. Before this change the function simply returned early, so it never touched the result. Now every fast query panics under that setting. A fix is to compute the ID directly, for example with `constructStatementIDFromStmtKey`, and not read it from the possibly-nil stats object
pkg/sql/app_stats.go:367
[P2] Transaction stats are never reset, so the map can grow without limit. Location The new `appStats.txns` map is never cleared by `resetAndMaybeDumpStats`, which only replaces `a.stmts`. The copy that function passes to the reporting target, `&appStats{st: a.st, stmts: a.stmts}`, also leaves `txns` out. As a result, transaction statistics build up for the whole life of the node and ignore the periodic stats reset, so `LastReset` in the Statements response is wrong for them. Memory use also grows with every distinct transaction shape. Statement stats are bounded by the reset; this new map has no equivalent bound
pkg/sql/conn_executor_exec.go:730
[P3] Commit latency uses stale or mismatched phase times when a transaction doesn't commit successfully. Location sessionStartTransactionCommit` and `sessionEndTransactionCommit` are only set inside `commitSQLTransaction`, and the end time is only set when the commit succeeds. Neither is cleared per transaction. A transaction that ends in ROLLBACK, or that aborts, records the commit latency left over from an earlier transaction on the same session. A transaction whose commit fails without a retry records the new start time minus the old end time, which gives a negative commit latency. Both cases skew the `CommitLat` reported in the new `TransactionStatistics
pkg/sql/app_stats.go:453
[P1] Nil pointer dereference for statements under the latency threshold When `sql.metrics.statement_details.threshold` is set above 0 and a statement runs faster than the threshold, `getStatsForStmt` is called with `createIfNonexistent=false`. If the fingerprint has no entry in `a.stmts` yet, which is always the case for a statement that has never gone over the threshold, `getStatsForStmtWithKey` returns nil. The `return s.ID` then panics on that nil pointer. Before this change the function returned early. Now, once an operator sets this public cluster setting, any fast query with a new fingerprint crashes the node. The ID should be built from the key without depending on a map entry, for example with `constructStatementIDFromStmtKey`.
pkg/sql/app_stats.go:369
[P2] Transaction stats map is never cleared on stats reset, so it grows without bound The new `appStats.txns` map gets an entry for every distinct sequence of statement IDs. `resetAndMaybeDumpStats` (app_stats.go:496-516) only swaps out `a.stmts`: it never resets `a.txns`, and the `aCopy` passed to the reported-stats pool contains only `stmts`. Two results follow. Transaction statistics keep accumulating for the life of the process and are never reset at the end of a reporting period, even though the proto says counts are "since the beginning of the reporting period". The map also grows without limit as workloads produce new transaction fingerprints, which is a memory leak on long-running nodes.
pkg/sql/conn_executor_exec.go:919
[P2] Commit latency uses stale phase times for transactions that don't go through `commitSQLTransaction` `sessionStartTransactionCommit` and `sessionEndTransactionCommit` are only written in `commitSQLTransaction`, and the end time only when the commit succeeds. Other transactions never reset these slots in `phaseTimes`. That covers rolled-back transactions, transactions whose commit fails (start is set but end is not), and transactions committed through `RELEASE SAVEPOINT cockroach_restart`, which calls `commitSQLTransactionInternal` directly. `getCommitLatency` then works from timestamps left by an earlier transaction, or from a new start minus an old end. The result is a bogus or negative `CommitLat` that gets folded into the per-transaction mean and variance.
pkg/sql/app_stats.go:700
[P3] `TransactionStatistics.NumRows` is never recorded The new proto field `num_rows` is documented as the total number of rows returned or observed, and `TransactionStatistics.Add` merges it. However, `appStats.recordTransaction` only records `ServiceLat`, `RetryLat`, `CommitLat` and `MaxRetries`. Nothing passes a row count through `recordTransaction`, so the `num_rows` exposed through the status API is always zero.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 medium ✓ exact
d3 critical ✓ off by one
d4 medium ✗ —
valid · matches d3 · impact critical
valid · matches d2 · impact medium
valid · impact high
getStatsForStmtWithKey returns nil when the key is absent and createIfNonexistent is false; the new early return dereferences s.ID on that nil pointer, panicking. Previously the function returned before fetching stats. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
Commit phase times are set only in commitSQLTransaction (end only on success); 1PC implicit commits, rollbacks and failed commits never refresh them, yet recordTransaction always records getCommitLatency, yielding stale or negative CommitLat values. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
pkg/sql/app_stats.go:178
[P1] Nil pointer dereference when statement is below the latency threshold When `sql.metrics.statement_details.threshold` is › 0 and the statement's service latency is at or below it, `createIfNonExistent` is false. `getStatsForStmt` then returns a nil `*stmtStats` if no entry exists for that key yet, because `getStatsForStmtWithKey` only allocates when `createIfNonexistent` is true. `return s.ID` dereferences that nil pointer and panics the connection goroutine. Any fast statement that has not been recorded before will hit this once the threshold is set. Compute the ID from the key, for example via `constructStatementIDFromStmtKey`, instead of reading it off the stats object.
pkg/sql/conn_executor_exec.go:1472
[P2] Commit latency reads stale phase timestamps when no COMMIT ran in this txn `getCommitLatency` is `phaseTimes[sessionEndTransactionCommit] - phaseTimes[sessionStartTransactionCommit]`. Those two slots are only written in `commitSQLTransaction`, and nothing resets them at txn start. If a txn ends by ROLLBACK, or its commit fails (start is set but end is not), the values left over from an earlier txn on the same connection are used. The result is a bogus positive commit latency, or a negative one when the failed commit's start is newer than the old end. That value is recorded into `CommitLat` and skews the mean and variance. Reset the two commit phase times in `recordTransactionStart`, and only record commit latency when a commit actually completed.
pkg/sql/app_stats.go:181
[P1] Nil dereference when the stats latency threshold skips a new statement When `sql.metrics.statement_details.threshold` is › 0 and a fast statement's key isn't already in `a.stmts`, `createIfNonExistent` is false and `getStatsForStmt` returns a nil `*stmtStats`. The new early return `return s.ID` then dereferences that nil pointer and panics the connection goroutine. The setting is user-configurable, and any statement under the threshold that has no existing entry hits this. The statement ID has to be computed from the key without needing the stats object, for example by calling `constructStatementIDFromStmtKey` directly. The same applies when `a.stmts` has no entry for the key after a reset.
pkg/sql/conn_executor_exec.go:730
[P2] Commit latency is read from stale or unset phase times for implicit, rolled-back and failed-commit transactions `sessionStartTransactionCommit` and `sessionEndTransactionCommit` are only written in `commitSQLTransaction`, which handles explicit COMMIT. Implicit transactions that auto-commit don't go through it. Rolled-back transactions don't either, and neither do transactions whose COMMIT fails, because the end time is set only on success. `recordTransaction` still calls `getCommitLatency()` for every transaction, so it can use values left by an earlier transaction on the same connection. It can also produce a negative or huge duration when the start was set but the end is stale or zero. These values are recorded into `CommitLat` and skew the aggregated txn stats. The commit phase times need to be reset at transaction start, and commit latency should only be recorded when a commit actually ran.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 medium ✗ —
d3 critical ✗ —
d4 medium ✗ —
raw comments (2)
PR-level
<h3>Qodo is busy working</h3> Check back in a few minutes. Qodo's code review agents are on it. <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
PR-level
<h3>PR Summary by Qodo</h3> Expose transaction-level SQL statistics through the status API <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>📝 Documentation</code> <code>🕐 40+ Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Aggregate transaction counts, retries, statement fingerprints, and execution latencies by > application. >• Expose node-attributed transaction statistics through local and cluster status responses. >• Add protobuf contracts, generated HTTP documentation, and multi-node API coverage. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD A["SQL Client"] -->|"executes transaction"| B["SQL Executor"] -->|"returns statement IDs"| C["Stats Collector"] -->|"aggregates metrics"| D["App Stats"] -->|"serves local data"| E["Status Server"] -->|"returns node stats"| F["Statements Response"] ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The approach is appropriate because it extends the existing in-memory, per-application SQL statistics pipeline and existing statements status endpoint rather than introducing a parallel subsystem. Hashing normalized statement identities keeps transaction keys compact, preserves statement order, and reuses established aggregation and cluster fan-out mechanisms; direct raw-query transaction keys or a separate endpoint would duplicate data and API infrastructure. </dd> </dl> </details> <details> <summary> Files changed (14) <code> +2065 / -714 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (9) <code> +458 / -100 </code></summary> <dl> <dd> <details> <summary>app_stats.go<code>Add statement identifiers and transaction-stat merging</code> <code>+35/-0</code></summary> <br/> >Add statement identifiers and transaction-stat merging > ><pre> >• Introduces deterministic FNV-based statement IDs derived from normalized query properties. Adds aggregation logic for transaction counts, maximum retries, row statistics, and latency distributions. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-d4b081e2bce1ff166a730f914b3b36fac433c541d4c50900a8131be3d4ea1284'>pkg/roachpb/app_stats.go</a> </details> <details> <summary>app_stats.proto<code>Define collected transaction statistics schema</code> <code>+45/-1</code></summary> <br/> >Define collected transaction statistics schema > ><pre> >• Defines transaction execution metrics including counts, retries, rows, and service, retry, and commit latencies. Adds statement IDs to statement records and introduces application-scoped transactions containing ordered statement IDs. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-9823f8036ea4bb763dcb06a3204887e12bb0496200acd854cb04a3bbb385bc2d'>pkg/roachpb/app_stats.proto</a> </details> <details> <summary>status.proto<code>Extend statements response with transaction statistics</code> <code>+10/-0</code></summary> <br/> >Extend statements response with transaction statistics > ><pre> >• Adds a transaction collection to StatementsResponse. Each transaction record includes its collected metrics and originating node ID. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-bdf84dc546a641c13d616508d4f49a4fdef55eaa1ee8a1eccb38114e3b37777d'>pkg/server/serverpb/status.proto</a> </details> <details> <summary>statements.go<code>Serve and aggregate transaction statistics across nodes</code> <code>+12/-2</code></summary> <br/> >Serve and aggregate transaction statistics across nodes > ><pre> >• Reads local transaction statistics alongside statement statistics and attaches the local node ID. Cluster-wide requests now combine transaction records returned by every node. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-d28d1df344cf88c7cdf0d6bc6d76ec3f230a0e418184527ffc42241461a8e2d9'>pkg/server/statements.go</a> </details> <details> <summary>app_stats.go<code>Collect per-application transaction execution metrics</code> <code>+240/-77</code></summary> <br/> >Collect per-application transaction execution metrics > ><pre> >• Adds transaction aggregation keyed by ordered statement IDs, including counts, retry maxima, and timing distributions subject to the SQL statistics latency threshold. Refactors statement statistics locking and identifiers, supports merging statistics pools, and exposes unscrubbed transaction records. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-c0ad8f0279367eca9cb3b851cc06b584511731d99eb3c600467f427a5bd24160'>pkg/sql/app_stats.go</a> </details> <details> <summary>conn_executor.go<code>Track transaction statement IDs and restart callbacks</code> <code>+22/-2</code></summary> <br/> >Track transaction statement IDs and restart callbacks > ><pre> >• Extends executor transaction state with ordered statement IDs and a restart callback. Transaction restarts now reset attempt-specific statement tracking while preserving lifecycle accounting. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-30926eec6a83d84431b319a14fc9081df5096743cff7914a77f3bdbfa5a251c7'>pkg/sql/conn_executor.go</a> </details> <details> <summary>conn_executor_exec.go<code>Measure and record complete transaction executions</code> <code>+45/-4</code></summary> <br/> >Measure and record complete transaction executions > ><pre> >• Captures transaction execution, retry, and commit timestamps, hashes the ordered statement-ID sequence into a transaction key, and records the resulting metrics at transaction completion. Restart and finish callbacks reset attempt-local statement tracking. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-e10255c339480f882118842fb00bc6a10857be5bf2aa1bf09a1fd5f8ace7bd44'>pkg/sql/conn_executor_exec.go</a> </details> <details> <summary>exec_util.go<code>Forward statement IDs and transaction metrics</code> <code>+18/-6</code></summary> <br/> >Forward statement IDs and transaction metrics > ><pre> >• Changes statement recording to return its generated ID. Expands transaction recording to forward the transaction key, statement IDs, retry count, and timing measurements while retaining legacy count statistics. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-cac22f70970154948cf8958f45e3fb5946f5dfb71a96aac384e99ccf310119b1'>pkg/sql/exec_util.go</a> </details> <details> <summary>executor_statement_metrics.go<code>Track transaction phases and executed statements</code> <code>+31/-8</code></summary> <br/> >Track transaction phases and executed statements > ><pre> >• Adds phase timestamps for transaction service, retry, execution, and commit latency calculations. Appends each recorded statement ID to the current transaction&#x27;s ordered statement sequence. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-4a4b401eecbec55bb4d77d3b6d6eb96fb30338435515a6f2bc63b29d87f33cc5'>pkg/sql/executor_statement_metrics.go</a> </details> </dd> </dl> </details> <details> <summary>Refactor (1) <code> +30 / -29 </code></summary> <dl> <dd> <details> <summary>crdb_internal.go<code>Adapt internal statistics tables to refactored storage</code> <code>+30/-29</code></summary> <br/> >Adapt internal statistics tables to refactored storage > ><pre> >• Updates statement statistics access for renamed fingerprint fields and mutex-protected data. Keeps legacy transaction count reporting connected to the separated transaction-count accumulator. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-65f052c474cf6d0a03a10a28dfb98c38f2584b7bf340039c1762124031ca07bf'>pkg/sql/crdb_internal.go</a> </details> </dd> </dl> </details> <details> <summary>Tests (1) <code> +116 / -0 </code></summary> <dl> <dd> <details> <summary>status_test.go<code>Test transaction statistics through the status API</code> <code>+116/-0</code></summary> <br/> >Test transaction statistics through the status API > ><pre> >• Adds a three-node integration test covering implicit and explicit transactions, repeated executions, forced retries, application attribution, counts, and latency values. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-b45ca7536e7e9a0c438915417715b828026ca3564ebcaeca33a8db1f7d33277a'>pkg/server/status_test.go</a> </details> </dd> </dl> </details> <details> <summary>Documentation (1) <code> +13 / -0 </code></summary> <dl> <dd> <details> <summary>full.md<code>Document transaction statistics in statements responses</code> <code>+13/-0</code></summary> <br/> >Document transaction statistics in statements responses > ><pre> >• Adds the transaction collection and its node-attributed nested message to the generated HTTP API reference. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-e4aac67cf7c23cf821f7ee2aebb8c3a7e26fa600bb95244157c9feae02be81f3'>docs/generated/http/full.md</a> </details> </dd> </dl> </details> <details> <summary>Other (2) <code> +1448 / -585 </code></summary> <dl> <dd> <details> <summary>app_stats.pb.go<code>Regenerate application statistics protobuf bindings</code> <code>+729/-104</code></summary> <br/> >Regenerate application statistics protobuf bindings > ><pre> >• Adds generated Go bindings and serialization support for transaction statistics, collected transactions, and statement IDs. Updates descriptors and message indexes for the expanded schema. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-7da6b0050657aa7d088d90a6c15efae1763cf306e45206f6d32744c9170ef1d3'>pkg/roachpb/app_stats.pb.go</a> </details> <details> <summary>status.pb.go<code>Regenerate status API protobuf bindings</code> <code>+719/-481</code></summary> <br/> >Regenerate status API protobuf bindings > ><pre> >• Adds generated response fields and serialization support for node-attributed collected transaction statistics. Refreshes protobuf descriptors for the status schema. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/28/files#diff-aec30b6f9a73b04cab267b0231f6c0dfee470619b59ea54f2f5dcbd432ce3e96'>pkg/server/serverpb/status.pb.go</a> </details> </dd> </dl> </details> </dd> </dl> </details>