-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
boundedstaleness_test.go
423 lines (387 loc) · 12.1 KB
/
boundedstaleness_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright 2021 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package kvfollowerreadsccl_test
import (
"context"
"flag"
"fmt"
"regexp"
"strconv"
"strings"
"testing"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvbase"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
)
var (
flagIgnoreWaitUntilMatch = flag.Bool(
"ignore-wait-until-match",
false,
`ignore wait-until-match. This is desired in cases `+
`of -rewrite, where we do not want to retry wait-until-match.`,
)
)
func TestBoundedStalenessEnterpriseLicense(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 1, base.TestClusterArgs{})
defer tc.Stopper().Stop(ctx)
testCases := []struct {
query string
args []interface{}
}{
{
query: `SELECT with_max_staleness('10s')`,
},
{
query: `SELECT with_min_timestamp(statement_timestamp())`,
},
{
query: `SELECT $1::TEXT FROM generate_series(1,1) AS OF SYSTEM TIME with_max_staleness('1s')`,
args: []interface{}{"cat"},
},
{
query: `SELECT $1::TEXT FROM generate_series(1,1) AS OF SYSTEM TIME with_min_timestamp(statement_timestamp())`,
args: []interface{}{"cat"},
},
}
defer utilccl.TestingDisableEnterprise()()
t.Run("disabled", func(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.query, func(t *testing.T) {
_, err := tc.Conns[0].QueryContext(ctx, testCase.query, testCase.args...)
require.Error(t, err)
require.Contains(t, err.Error(), "use of bounded staleness requires an enterprise license")
})
}
})
t.Run("enabled", func(t *testing.T) {
defer utilccl.TestingEnableEnterprise()()
for _, testCase := range testCases {
t.Run(testCase.query, func(t *testing.T) {
r, err := tc.Conns[0].QueryContext(ctx, testCase.query, testCase.args...)
require.NoError(t, err)
require.NoError(t, r.Close())
})
}
})
}
// boundedStalenessDataDrivenEvent is an event during a bounded staleness datadriven test.
type boundedStalenessDataDrivenEvent interface {
EventOutput() string
}
// boundedStalenessTraceEvent is a recorded trace of interest during a bounded staleness
// datadriven test.
type boundedStalenessTraceEvent struct {
operation string
nodeIdx int
localRead bool
remoteLeaseholderRead bool
followerRead bool
}
func (ev *boundedStalenessTraceEvent) EventOutput() string {
state := "??? undefined state ???"
switch {
case ev.localRead && ev.remoteLeaseholderRead && !ev.followerRead:
state = "local read then remote leaseholder read"
case ev.localRead && !ev.remoteLeaseholderRead && ev.followerRead:
state = "local follower read"
case ev.localRead && !ev.remoteLeaseholderRead && !ev.followerRead:
state = "local read"
}
return fmt.Sprintf(
"%s trace on node_idx %d: %s",
ev.operation,
ev.nodeIdx,
state,
)
}
// boundedStalenessRetryEvent is a retry that has occurred from within the
// transaction as a result of a nearest_only bounded staleness restart.
type boundedStalenessRetryEvent struct {
nodeIdx int
*roachpb.MinTimestampBoundUnsatisfiableError
asOf eval.AsOfSystemTime
}
func (ev *boundedStalenessRetryEvent) EventOutput() string {
return fmt.Sprintf("transaction retry on node_idx: %d", ev.nodeIdx)
}
// boundedStalenessEvents tracks bounded staleness datadriven related events.
type boundedStalenessEvents struct {
// A mutex is needed as the event handlers (onStmtTrace) can race.
mu struct {
syncutil.Mutex
stmt string
events []boundedStalenessDataDrivenEvent
}
}
func (bse *boundedStalenessEvents) reset() {
bse.mu.Lock()
defer bse.mu.Unlock()
bse.mu.stmt = ""
bse.mu.events = nil
}
func (bse *boundedStalenessEvents) clearEvents() {
bse.mu.Lock()
defer bse.mu.Unlock()
bse.mu.events = nil
}
func (bse *boundedStalenessEvents) setStmt(s string) {
bse.mu.Lock()
defer bse.mu.Unlock()
bse.mu.stmt = s
}
func (bse *boundedStalenessEvents) String() string {
bse.mu.Lock()
defer bse.mu.Unlock()
var sb strings.Builder
sb.WriteString(fmt.Sprintf("events (%d found):\n", len(bse.mu.events)))
for idx, event := range bse.mu.events {
sb.WriteString(
fmt.Sprintf(
" * event %d: %s\n",
idx+1,
event.EventOutput(),
),
)
}
return sb.String()
}
func (bse *boundedStalenessEvents) validate(t *testing.T) {
bse.mu.Lock()
defer bse.mu.Unlock()
var lastTxnRetry *boundedStalenessRetryEvent
for _, ev := range bse.mu.events {
switch ev := ev.(type) {
case *boundedStalenessRetryEvent:
if lastTxnRetry != nil {
require.True(
t,
ev.MinTimestampBound.Less(lastTxnRetry.MinTimestampBound),
ev.MinTimestampBound,
lastTxnRetry.MinTimestampBound,
)
require.Equal(t, ev.asOf.Timestamp, lastTxnRetry.asOf.Timestamp)
}
require.True(t, ev.asOf.BoundedStaleness)
lastTxnRetry = ev
}
}
}
func (bse *boundedStalenessEvents) onTxnRetry(
nodeIdx int, autoRetryReason error, evalCtx *eval.Context,
) {
bse.mu.Lock()
defer bse.mu.Unlock()
if bse.mu.stmt == "" {
return
}
var minTSErr *roachpb.MinTimestampBoundUnsatisfiableError
if autoRetryReason != nil && errors.As(autoRetryReason, &minTSErr) {
ev := &boundedStalenessRetryEvent{
nodeIdx: nodeIdx,
MinTimestampBoundUnsatisfiableError: minTSErr,
asOf: *evalCtx.AsOfSystemTime,
}
bse.mu.events = append(bse.mu.events, ev)
}
}
func (bse *boundedStalenessEvents) onStmtTrace(nodeIdx int, rec tracingpb.Recording, stmt string) {
bse.mu.Lock()
defer bse.mu.Unlock()
if bse.mu.stmt != "" && bse.mu.stmt == stmt {
spans := make(map[tracingpb.SpanID]tracingpb.RecordedSpan)
for _, sp := range rec {
spans[sp.SpanID] = sp
if sp.Operation == "dist sender send" && spans[sp.ParentSpanID].Operation == "colbatchscan" {
bse.mu.events = append(bse.mu.events, &boundedStalenessTraceEvent{
operation: spans[sp.ParentSpanID].Operation,
nodeIdx: nodeIdx,
localRead: tracing.LogsContainMsg(sp, kvbase.RoutingRequestLocallyMsg),
followerRead: kv.OnlyFollowerReads(rec),
remoteLeaseholderRead: tracing.LogsContainMsg(sp, "[NotLeaseHolderError] lease held by different store;") &&
tracing.LogsContainMsg(sp, "trying next peer"),
})
}
}
}
}
func TestBoundedStalenessDataDriven(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderStress(t, "1μs staleness reads may actually succeed due to the slow environment")
defer utilccl.TestingEnableEnterprise()()
ctx := context.Background()
clusterArgs := base.TestClusterArgs{
ServerArgsPerNode: map[int]base.TestServerArgs{},
}
const numNodes = 3
var bse boundedStalenessEvents
for i := 0; i < numNodes; i++ {
i := i
clusterArgs.ServerArgsPerNode[i] = base.TestServerArgs{
Knobs: base.TestingKnobs{
SQLExecutor: &sql.ExecutorTestingKnobs{
WithStatementTrace: func(trace tracingpb.Recording, stmt string) {
bse.onStmtTrace(i, trace, stmt)
},
OnTxnRetry: func(err error, evalCtx *eval.Context) {
bse.onTxnRetry(i, err, evalCtx)
},
},
},
}
}
// Replace errors which are not deterministically output.
// In this case, it is the HLC timestamp of
// MinTimestampBoundUnsatisfiableErrors.
errorRegexp := regexp.MustCompile(
`((minimum timestamp bound|local resolved timestamp) of) [\d.,]*`,
)
replaceOutput := func(s string) string {
return errorRegexp.ReplaceAllString(s, "$1 XXX")
}
datadriven.Walk(t, testutils.TestDataPath(t, "boundedstaleness"), func(t *testing.T, path string) {
tc := testcluster.StartTestCluster(t, 3, clusterArgs)
defer tc.Stopper().Stop(ctx)
// This test may probabilistically execute its SQL as a secondary tenant. It
// also traces queries and makes assertions on whether log lines indicate
// requests were served via follower reads. As these log lines originate
// down in kvserver we disable their redaction.
systemTenantSQL := sqlutils.MakeSQLRunner(tc.StorageClusterConn())
systemTenantSQL.Exec(t, `SET CLUSTER SETTING server.secondary_tenants.redact_trace.enabled = 'false'`)
savedTraceStmt := ""
datadriven.RunTest(t, path, func(t *testing.T, d *datadriven.TestData) string {
// Early exit non-query execution related commands.
switch d.Cmd {
// override-matching-stmt-for-tracing forces the next trace of events to
// only look for the given query instead of using d.Input. This is useful
//for traces of prepared statements.
case "override-matching-stmt-for-tracing":
savedTraceStmt = d.Input
return ""
case "reset-matching-stmt-for-tracing":
savedTraceStmt = ""
return ""
}
var showEvents bool
var waitUntilFollowerReads bool
var waitUntilMatch bool
defer func() {
bse.reset()
}()
dbConn := tc.ServerConn(0)
traceStmt := savedTraceStmt
if traceStmt == "" {
traceStmt = d.Input
}
for _, arg := range d.CmdArgs {
switch arg.Key {
case "wait-until-follower-read":
bse.setStmt(traceStmt)
waitUntilFollowerReads = true
case "wait-until-match":
// We support both wait-until-match and wait-until-follower-read,
// So during `-rewrite -ignore-wait-until-match` we rewrite with
// the desired output after waiting for the follower read.
if !*flagIgnoreWaitUntilMatch {
waitUntilMatch = true
}
case "idx":
serverNum, err := strconv.ParseInt(arg.Vals[0], 10, 64)
require.NoError(t, err)
dbConn = tc.ServerConn(int(serverNum))
default:
t.Fatalf("unknown arg: %s", arg.Key)
}
}
executeCmd := func() (retStr string) {
defer func() {
retStr = replaceOutput(retStr)
}()
switch d.Cmd {
case "exec":
_, err := dbConn.Exec(d.Input)
if err != nil {
return err.Error()
}
return ""
case "query":
// Always show events.
bse.setStmt(traceStmt)
showEvents = true
rows, err := dbConn.Query(d.Input)
if err != nil {
return err.Error()
}
ret, err := sqlutils.RowsToDataDrivenOutput(rows)
require.NoError(t, err)
return ret
}
t.Fatalf("unknown command: %s", d.Cmd)
return "unexpected"
}
var ret string
testutils.SucceedsSoon(t, func() error {
ret = executeCmd()
// Append events to the output if desired.
if showEvents {
if !strings.HasSuffix(ret, "\n") {
ret += "\n"
}
ret += bse.String()
}
// If we're waiting until follower reads, retry until we are always
// reading follower reads from.
if waitUntilFollowerReads {
followerRead := false
func() {
bse.mu.Lock()
defer bse.mu.Unlock()
for _, ev := range bse.mu.events {
switch ev := ev.(type) {
case *boundedStalenessTraceEvent:
followerRead = ev.followerRead
}
}
}()
if !followerRead {
bse.clearEvents()
return errors.AssertionFailedf("not follower reads found:\n%s", bse.String())
}
}
if waitUntilMatch {
if d.Expected != ret {
bse.clearEvents()
return errors.AssertionFailedf("not yet a match, output:\n%s\n", ret)
}
}
return nil
})
bse.validate(t)
return ret
})
})
}