Skip to content

Commit 8138e3f

Browse files
craig[bot]kyle-a-wongyuzefovich
committed
148007: sql,log: add new txn_timestamp filed to CommonSqlEventDetails r=kyle-a-wong a=kyle-a-wong Previously, an event's `timestamp` field was either set to the current time, or the read timestamp of the txn emitting the event, if the event was emitted within a txn. This isn't obvious functionality and can result in events to be seemingly out of order. To fix this, we adeded a new `txn_timestamp` field to the CommonSQLEventDetails proto type. This field is responsible for holding the txn's current read timestamp that a structured event was emitted in, if in a transaction. Now, an event's timestamp will always be the time that the event was constructred, and txn_timestamp will transactions current read timestamp. Resolves: #146820 Epic: None Release note (general change): Updated SQL events to have a 'TxnTimestamp' which indicates the read timestamp of the transaction that the sql event was emitted in, if in a transaction. The `Timestamp` of an event will always be the time that the event was created. 148247: explain: shorten some extremely long lines r=yuzefovich a=yuzefovich I just saw a bundle with an ANY clause with a tuple that had 10k elements. As of 4c77e2a, we shortened the tuple itself to not pollute `plan.txt` too much, but the type declaration still had the word "string" printed 10k times. This is the case when explicit `TYPES` format of EXPLAIN is requested, or when the bundle collected via EXPLAIN ANALYZE (DEBUG) (in which case we always request the `TYPES` flag). This commit applies the same shortening logic to the type string as we did in the change mentioned above - if `FmtShortenConstants` flag is set, then only the first two and the last tuple elements are printed, reducing the redundant information (chances are all elements within the tuple are of the same type anyway). When `VERBOSE` option is set, we show physical spans via `SpanFormatFn`. This function could be called for Scan, Vector Search, and Delete Range operators. Unlike in non-verbose case (where we only print the first 4 logical spans), previously we would print any number of physical plans in the verbose mode. In the same bundle we had 10k of spans which significantly polluted `plan.txt`, so this commit introduces a hard limit - now the first 20 physical spans will be printed. Informs: https://cockroachdb.zendesk.com/agent/tickets/27348 Epic: None Release note: None Co-authored-by: Kyle Wong <[email protected]> Co-authored-by: Yahor Yuzefovich <[email protected]>
3 parents af29815 + d81d31a + 8fc2e3d commit 8138e3f

File tree

17 files changed

+362
-162
lines changed

17 files changed

+362
-162
lines changed

docs/generated/eventlog.md

Lines changed: 82 additions & 0 deletions
Large diffs are not rendered by default.

pkg/ccl/logictestccl/testdata/logic_test/multi_region

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1097,7 +1097,7 @@ ALTER DATABASE drop_region_db DROP REGION IF EXISTS "us-east-1"
10971097

10981098
# Ensure that events are generated for dropping the region
10991099
query IT
1100-
SELECT "reportingID", info::JSONB - 'Timestamp' - 'DescriptorID'
1100+
SELECT "reportingID", info::JSONB - 'Timestamp' - 'DescriptorID' - 'TxnTimestamp'
11011101
FROM system.eventlog
11021102
WHERE "eventType" = 'alter_database_drop_region'
11031103
----

pkg/sql/event_log.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -247,12 +247,8 @@ func logEventInternalForSQLStatements(
247247
) error {
248248
// Inject the common fields into the payload provided by the caller.
249249
injectCommonFields := func(event logpb.EventPayload) error {
250-
if txn == nil {
251-
// No txn is set (e.g. for COPY or BEGIN), so use now instead.
252-
event.CommonDetails().Timestamp = timeutil.Now().UnixNano()
253-
} else {
254-
event.CommonDetails().Timestamp = txn.KV().ReadTimestamp().WallTime
255-
}
250+
event.CommonDetails().Timestamp = timeutil.Now().UnixNano()
251+
256252
sqlCommon, ok := event.(eventpb.EventWithCommonSQLPayload)
257253
if !ok {
258254
return errors.AssertionFailedf("unknown event type: %T", event)
@@ -278,6 +274,10 @@ func logEventInternalForSQLStatements(
278274
// Overwrite with the common details.
279275
*m = commonSQLEventDetails
280276

277+
if txn != nil {
278+
m.TxnTimestamp = txn.KV().ReadTimestamp().WallTime
279+
}
280+
281281
// If the common details didn't have a descriptor ID, keep the
282282
// one that was in the event already.
283283
if m.DescriptorID == 0 {

pkg/sql/event_log_test.go

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
2525
"github.com/cockroachdb/cockroach/pkg/util/log/logconfig"
2626
"github.com/cockroachdb/cockroach/pkg/util/log/logpb"
27+
"github.com/cockroachdb/cockroach/pkg/util/log/logtestutils"
2728
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
2829
"github.com/cockroachdb/errors"
2930
"github.com/cockroachdb/redact"
@@ -115,6 +116,46 @@ func TestStructuredEventLogging(t *testing.T) {
115116
}
116117
}
117118

119+
func TestStructuredEventLogging_txnTimestamp(t *testing.T) {
120+
defer leaktest.AfterTest(t)()
121+
defer log.Scope(t).Close(t)
122+
123+
ctx := context.Background()
124+
appLogsSpy := logtestutils.NewStructuredLogSpy(
125+
t,
126+
[]logpb.Channel{logpb.Channel_SQL_SCHEMA},
127+
[]string{"create_table"},
128+
func(entry logpb.Entry) (eventpb.CreateTable, error) {
129+
var cte eventpb.CreateTable
130+
if err := json.Unmarshal([]byte(entry.Message[entry.StructuredStart:entry.StructuredEnd]), &cte); err != nil {
131+
return cte, err
132+
}
133+
return cte, nil
134+
},
135+
)
136+
137+
cleanup := log.InterceptWith(ctx, appLogsSpy)
138+
defer cleanup()
139+
140+
s, conn, _ := serverutils.StartServer(t, base.TestServerArgs{})
141+
defer s.Stopper().Stop(ctx)
142+
143+
runner := sqlutils.MakeSQLRunner(conn)
144+
runner.Exec(t, "CREATE TABLE test (id INT PRIMARY KEY)")
145+
runner.Exec(t, "BEGIN")
146+
runner.Exec(t, "SET autocommit_before_ddl = false")
147+
runner.Exec(t, "CREATE TABLE test1 (id INT PRIMARY KEY)")
148+
runner.Exec(t, "CREATE TABLE test2 (id INT PRIMARY KEY)")
149+
runner.Exec(t, "COMMIT")
150+
151+
createTables := appLogsSpy.GetLogs(logpb.Channel_SQL_SCHEMA)
152+
require.Len(t, createTables, 3)
153+
// Not created in the same transaction, so transaction timestamps are different
154+
require.NotEqual(t, createTables[0].TxnTimestamp, createTables[1].TxnTimestamp)
155+
// Created in the same transaction, so transaction timestamps are the same
156+
require.Equal(t, createTables[1].TxnTimestamp, createTables[2].TxnTimestamp)
157+
}
158+
118159
var execLogRe = regexp.MustCompile(`event_log.go`)
119160

120161
// Test the SQL_PERF and SQL_INTERNAL_PERF logging channels.
@@ -140,7 +181,7 @@ func TestPerfLogging(t *testing.T) {
140181
{
141182
query: `SELECT pg_sleep(0.256)`,
142183
errRe: ``,
143-
logRe: `"EventType":"slow_query","Statement":"SELECT pg_sleep\(‹0.256›\)","Tag":"SELECT","User":"root","ExecMode":"exec","NumRows":1`,
184+
logRe: `"EventType":"slow_query","Statement":"SELECT pg_sleep\(‹0.256›\)","Tag":"SELECT","User":"root","TxnTimestamp":.*,"ExecMode":"exec","NumRows":1`,
144185
logExpected: true,
145186
channel: channel.SQL_PERF,
146187
},
@@ -161,7 +202,7 @@ func TestPerfLogging(t *testing.T) {
161202
{
162203
query: `INSERT INTO t VALUES (2, pg_sleep(0.256), 'x')`,
163204
errRe: ``,
164-
logRe: `"EventType":"slow_query","Statement":"INSERT INTO .*\.t VALUES \(‹2›, pg_sleep\(‹0.256›\), ‹'x'›\)","Tag":"INSERT","User":"root","ExecMode":"exec","NumRows":1`,
205+
logRe: `"EventType":"slow_query","Statement":"INSERT INTO .*\.t VALUES \(‹2›, pg_sleep\(‹0.256›\), ‹'x'›\)","Tag":"INSERT","User":"root","TxnTimestamp":.*,"ExecMode":"exec","NumRows":1`,
165206
logExpected: true,
166207
channel: channel.SQL_PERF,
167208
},
@@ -175,7 +216,7 @@ func TestPerfLogging(t *testing.T) {
175216
{
176217
query: `INSERT INTO t VALUES (4, pg_sleep(0.256), repeat('x', 1024))`,
177218
errRe: ``,
178-
logRe: `"EventType":"slow_query","Statement":"INSERT INTO .*\.t VALUES \(‹4›, pg_sleep\(‹0.256›\), repeat\(‹'x'›, ‹1024›\)\)","Tag":"INSERT","User":"root","ExecMode":"exec","NumRows":1`,
219+
logRe: `"EventType":"slow_query","Statement":"INSERT INTO .*\.t VALUES \(‹4›, pg_sleep\(‹0.256›\), repeat\(‹'x'›, ‹1024›\)\)","Tag":"INSERT","User":"root","TxnTimestamp":.*,"ExecMode":"exec","NumRows":1`,
179220
logExpected: true,
180221
channel: channel.SQL_PERF,
181222
},
@@ -189,7 +230,7 @@ func TestPerfLogging(t *testing.T) {
189230
{
190231
query: `SELECT *, pg_sleep(0.064) FROM t`,
191232
errRe: ``,
192-
logRe: `"EventType":"slow_query","Statement":"SELECT \*, pg_sleep\(‹0.064›\) FROM .*\.t","Tag":"SELECT","User":"root","ExecMode":"exec","NumRows":4`,
233+
logRe: `"EventType":"slow_query","Statement":"SELECT \*, pg_sleep\(‹0.064›\) FROM .*\.t","Tag":"SELECT","User":"root","TxnTimestamp":.*,"ExecMode":"exec","NumRows":4`,
193234
logExpected: true,
194235
channel: channel.SQL_PERF,
195236
},

pkg/sql/explain_plan.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,12 @@ func emitExplain(
223223
if err != nil {
224224
return err.Error()
225225
}
226+
// Show up to 20 physical spans.
227+
var more string
228+
if maxSpans := 20; len(spans) > maxSpans {
229+
more = fmt.Sprintf(" … (%d more)", len(spans)-maxSpans)
230+
spans = spans[:maxSpans]
231+
}
226232
// skip is how many fields to skip when pretty-printing spans.
227233
// Usually 2, but can be 4 when running EXPLAIN from a tenant since there
228234
// will be an extra tenant prefix and ID. For example:
@@ -235,7 +241,7 @@ func emitExplain(
235241
if !codec.ForSystemTenant() {
236242
skip = 4
237243
}
238-
return catalogkeys.PrettySpans(idx, spans, skip)
244+
return catalogkeys.PrettySpans(idx, spans, skip) + more
239245
}
240246

241247
return explain.Emit(ctx, evalCtx, explainPlan, ob, spanFormatFn, createPostQueryPlanIfMissing)

pkg/sql/logictest/testdata/logic_test/distsql_event_log

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ CREATE STATISTICS __auto__ FROM a
2525
# Check explicitly for table id 106. System tables could trigger autostats
2626
# collections at any time.
2727
query IT
28-
SELECT "reportingID", "info"::JSONB - 'Timestamp' - 'DescriptorID' - 'ApplicationName'
28+
SELECT "reportingID", "info"::JSONB - 'Timestamp' - 'DescriptorID' - 'TxnTimestamp' - 'ApplicationName'
2929
FROM system.eventlog
3030
WHERE "eventType" = 'create_statistics' AND ("info"::JSONB ->> 'DescriptorID')::INT = 106
3131
ORDER BY "timestamp", info

0 commit comments

Comments
 (0)