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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
use scylla_cql::{
    errors::{DbError, QueryError, WriteType},
    Consistency,
};
use tracing::debug;

use crate::retry_policy::{QueryInfo, RetryDecision, RetryPolicy, RetrySession};

/// Downgrading consistency retry policy - retries with lower consistency level if it knows\
/// that the initial CL is unreachable. Also, it behaves as [DefaultRetryPolicy](crate::retry_policy::DefaultRetryPolicy)
/// when it believes that the initial CL is reachable.
/// Behaviour based on [DataStax Java Driver]\
///(<https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.html>)
#[derive(Debug)]
pub struct DowngradingConsistencyRetryPolicy;

impl DowngradingConsistencyRetryPolicy {
    pub fn new() -> DowngradingConsistencyRetryPolicy {
        DowngradingConsistencyRetryPolicy
    }
}

impl Default for DowngradingConsistencyRetryPolicy {
    fn default() -> DowngradingConsistencyRetryPolicy {
        DowngradingConsistencyRetryPolicy::new()
    }
}

impl RetryPolicy for DowngradingConsistencyRetryPolicy {
    fn new_session(&self) -> Box<dyn RetrySession> {
        Box::new(DowngradingConsistencyRetrySession::new())
    }

    fn clone_boxed(&self) -> Box<dyn RetryPolicy> {
        Box::new(DowngradingConsistencyRetryPolicy)
    }
}

pub struct DowngradingConsistencyRetrySession {
    was_retry: bool,
}

impl DowngradingConsistencyRetrySession {
    pub fn new() -> DowngradingConsistencyRetrySession {
        DowngradingConsistencyRetrySession { was_retry: false }
    }
}

impl Default for DowngradingConsistencyRetrySession {
    fn default() -> DowngradingConsistencyRetrySession {
        DowngradingConsistencyRetrySession::new()
    }
}

impl RetrySession for DowngradingConsistencyRetrySession {
    fn decide_should_retry(&mut self, query_info: QueryInfo) -> RetryDecision {
        let cl = match query_info.consistency {
            Consistency::Serial | Consistency::LocalSerial => {
                return match query_info.error {
                    QueryError::DbError(DbError::Unavailable { .. }, _) => {
                        // JAVA-764: if the requested consistency level is serial, it means that the operation failed at
                        // the paxos phase of a LWT.
                        // Retry on the next host, on the assumption that the initial coordinator could be network-isolated.
                        RetryDecision::RetryNextNode(None)
                    }
                    _ => RetryDecision::DontRetry,
                };
            }
            cl => cl,
        };

        fn max_likely_to_work_cl(known_ok: i32, previous_cl: Consistency) -> RetryDecision {
            let decision = if known_ok >= 3 {
                RetryDecision::RetrySameNode(Some(Consistency::Three))
            } else if known_ok == 2 {
                RetryDecision::RetrySameNode(Some(Consistency::Two))
            } else if known_ok == 1 || previous_cl == Consistency::EachQuorum {
                // JAVA-1005: EACH_QUORUM does not report a global number of alive replicas
                // so even if we get 0 alive replicas, there might be
                // a node up in some other datacenter
                RetryDecision::RetrySameNode(Some(Consistency::One))
            } else {
                RetryDecision::DontRetry
            };
            if let RetryDecision::RetrySameNode(new_cl) = decision {
                debug!(
                    "Decided to lower required consistency from {} to {:?}.",
                    previous_cl, new_cl
                );
            }
            decision
        }

        match query_info.error {
            // Basic errors - there are some problems on this node
            // Retry on a different one if possible
            QueryError::IoError(_)
            | QueryError::DbError(DbError::Overloaded, _)
            | QueryError::DbError(DbError::ServerError, _)
            | QueryError::DbError(DbError::TruncateError, _) => {
                if query_info.is_idempotent {
                    RetryDecision::RetryNextNode(None)
                } else {
                    RetryDecision::DontRetry
                }
            }
            // Unavailable - the current node believes that not enough nodes
            // are alive to satisfy specified consistency requirements.
            QueryError::DbError(DbError::Unavailable { alive, .. }, _) => {
                if !self.was_retry {
                    self.was_retry = true;
                    max_likely_to_work_cl(*alive, cl)
                } else {
                    RetryDecision::DontRetry
                }
            }
            // ReadTimeout - coordinator didn't receive enough replies in time.
            QueryError::DbError(
                DbError::ReadTimeout {
                    received,
                    required,
                    data_present,
                    ..
                },
                _,
            ) => {
                if self.was_retry {
                    RetryDecision::DontRetry
                } else if received < required {
                    self.was_retry = true;
                    max_likely_to_work_cl(*received, cl)
                } else if !*data_present {
                    self.was_retry = true;
                    RetryDecision::RetrySameNode(None)
                } else {
                    RetryDecision::DontRetry
                }
            }
            // Write timeout - coordinator didn't receive enough replies in time.
            QueryError::DbError(
                DbError::WriteTimeout {
                    write_type,
                    received,
                    ..
                },
                _,
            ) => {
                if self.was_retry || !query_info.is_idempotent {
                    RetryDecision::DontRetry
                } else {
                    self.was_retry = true;
                    match write_type {
                        WriteType::Batch | WriteType::Simple if *received > 0 => {
                            RetryDecision::IgnoreWriteError
                        }

                        WriteType::UnloggedBatch => {
                            // Since only part of the batch could have been persisted,
                            // retry with whatever consistency should allow to persist all
                            max_likely_to_work_cl(*received, cl)
                        }
                        WriteType::BatchLog => RetryDecision::RetrySameNode(None),

                        _ => RetryDecision::DontRetry,
                    }
                }
            }
            // The node is still bootstrapping it can't execute the query, we should try another one
            QueryError::DbError(DbError::IsBootstrapping, _) => RetryDecision::RetryNextNode(None),
            // Connection to the contacted node is overloaded, try another one
            QueryError::UnableToAllocStreamId => RetryDecision::RetryNextNode(None),
            // In all other cases propagate the error to the user
            _ => RetryDecision::DontRetry,
        }
    }

    fn reset(&mut self) {
        *self = DowngradingConsistencyRetrySession::new();
    }
}

#[cfg(test)]
mod tests {
    use std::{io::ErrorKind, sync::Arc};

    use bytes::Bytes;
    use scylla_cql::errors::BadQuery;

    use super::*;

    const CONSISTENCY_LEVELS: &[Consistency] = &[
        Consistency::All,
        Consistency::Any,
        Consistency::EachQuorum,
        Consistency::LocalOne,
        Consistency::LocalQuorum,
        Consistency::One,
        Consistency::Quorum,
        Consistency::Three,
        Consistency::Two,
    ];

    fn make_query_info_with_cl(
        error: &QueryError,
        is_idempotent: bool,
        cl: Consistency,
    ) -> QueryInfo<'_> {
        QueryInfo {
            error,
            is_idempotent,
            consistency: cl,
        }
    }

    // Asserts that downgrading consistency policy never retries for this Error
    fn downgrading_consistency_policy_assert_never_retries(error: QueryError, cl: Consistency) {
        let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
        assert_eq!(
            policy.decide_should_retry(make_query_info_with_cl(&error, false, cl)),
            RetryDecision::DontRetry
        );

        let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
        assert_eq!(
            policy.decide_should_retry(make_query_info_with_cl(&error, true, cl)),
            RetryDecision::DontRetry
        );
    }

    #[test]
    fn downgrading_consistency_never_retries() {
        let never_retried_dberrors = vec![
            DbError::SyntaxError,
            DbError::Invalid,
            DbError::AlreadyExists {
                keyspace: String::new(),
                table: String::new(),
            },
            DbError::FunctionFailure {
                keyspace: String::new(),
                function: String::new(),
                arg_types: vec![],
            },
            DbError::AuthenticationError,
            DbError::Unauthorized,
            DbError::ConfigError,
            DbError::ReadFailure {
                consistency: Consistency::Two,
                received: 1,
                required: 2,
                numfailures: 1,
                data_present: false,
            },
            DbError::WriteFailure {
                consistency: Consistency::Two,
                received: 1,
                required: 2,
                numfailures: 1,
                write_type: WriteType::BatchLog,
            },
            DbError::Unprepared {
                statement_id: Bytes::from_static(b"deadbeef"),
            },
            DbError::ProtocolError,
            DbError::Other(0x124816),
        ];

        for &cl in CONSISTENCY_LEVELS {
            for dberror in never_retried_dberrors.clone() {
                downgrading_consistency_policy_assert_never_retries(
                    QueryError::DbError(dberror, String::new()),
                    cl,
                );
            }

            downgrading_consistency_policy_assert_never_retries(
                QueryError::BadQuery(BadQuery::Other(
                    "Length of provided values must be equal to number of batch statements \
                        (got 1 values, 2 statements)"
                        .to_owned(),
                )),
                cl,
            );
            downgrading_consistency_policy_assert_never_retries(
                QueryError::ProtocolError("test"),
                cl,
            );
        }
    }

    // Asserts that for this error policy retries on next on idempotent queries only
    fn downgrading_consistency_policy_assert_idempotent_next(error: QueryError, cl: Consistency) {
        let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
        assert_eq!(
            policy.decide_should_retry(make_query_info_with_cl(&error, false, cl)),
            RetryDecision::DontRetry
        );

        let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
        assert_eq!(
            policy.decide_should_retry(make_query_info_with_cl(&error, true, cl)),
            RetryDecision::RetryNextNode(None)
        );
    }

    fn max_likely_to_work_cl(known_ok: i32, current_cl: Consistency) -> RetryDecision {
        if known_ok >= 3 {
            RetryDecision::RetrySameNode(Some(Consistency::Three))
        } else if known_ok == 2 {
            RetryDecision::RetrySameNode(Some(Consistency::Two))
        } else if known_ok == 1 || current_cl == Consistency::EachQuorum {
            // JAVA-1005: EACH_QUORUM does not report a global number of alive replicas
            // so even if we get 0 alive replicas, there might be
            // a node up in some other datacenter
            RetryDecision::RetrySameNode(Some(Consistency::One))
        } else {
            RetryDecision::DontRetry
        }
    }

    #[test]
    fn downgrading_consistency_idempotent_next_retries() {
        let idempotent_next_errors = vec![
            QueryError::DbError(DbError::Overloaded, String::new()),
            QueryError::DbError(DbError::TruncateError, String::new()),
            QueryError::DbError(DbError::ServerError, String::new()),
            QueryError::IoError(Arc::new(std::io::Error::new(ErrorKind::Other, "test"))),
        ];

        for &cl in CONSISTENCY_LEVELS {
            for error in idempotent_next_errors.clone() {
                downgrading_consistency_policy_assert_idempotent_next(error, cl);
            }
        }
    }

    // Always retry on next node if current one is bootstrapping
    #[test]
    fn downgrading_consistency_bootstrapping() {
        let error = QueryError::DbError(DbError::IsBootstrapping, String::new());

        for &cl in CONSISTENCY_LEVELS {
            let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(&error, false, cl)),
                RetryDecision::RetryNextNode(None)
            );

            let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(&error, true, cl)),
                RetryDecision::RetryNextNode(None)
            );
        }
    }

    // On Unavailable error we retry one time no matter the idempotence
    #[test]
    fn downgrading_consistency_unavailable() {
        let alive = 1;
        let error = QueryError::DbError(
            DbError::Unavailable {
                consistency: Consistency::Two,
                required: 2,
                alive,
            },
            String::new(),
        );

        for &cl in CONSISTENCY_LEVELS {
            let mut policy_not_idempotent = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy_not_idempotent
                    .decide_should_retry(make_query_info_with_cl(&error, false, cl)),
                max_likely_to_work_cl(alive, cl)
            );
            assert_eq!(
                policy_not_idempotent
                    .decide_should_retry(make_query_info_with_cl(&error, false, cl)),
                RetryDecision::DontRetry
            );

            let mut policy_idempotent = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy_idempotent.decide_should_retry(make_query_info_with_cl(&error, true, cl)),
                max_likely_to_work_cl(alive, cl)
            );
            assert_eq!(
                policy_idempotent.decide_should_retry(make_query_info_with_cl(&error, true, cl)),
                RetryDecision::DontRetry
            );
        }
    }

    // On ReadTimeout we retry one time if there were enough responses and the data was present no matter the idempotence
    #[test]
    fn downgrading_consistency_read_timeout() {
        // Enough responses and data_present == false - coordinator received only checksums
        let enough_responses_no_data = QueryError::DbError(
            DbError::ReadTimeout {
                consistency: Consistency::Two,
                received: 2,
                required: 2,
                data_present: false,
            },
            String::new(),
        );

        for &cl in CONSISTENCY_LEVELS {
            // Not idempotent
            let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(
                    &enough_responses_no_data,
                    false,
                    cl
                )),
                RetryDecision::RetrySameNode(None)
            );
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(
                    &enough_responses_no_data,
                    false,
                    cl
                )),
                RetryDecision::DontRetry
            );

            // Idempotent
            let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(
                    &enough_responses_no_data,
                    true,
                    cl
                )),
                RetryDecision::RetrySameNode(None)
            );
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(
                    &enough_responses_no_data,
                    true,
                    cl
                )),
                RetryDecision::DontRetry
            );
        }
        // Enough responses but data_present == true - coordinator probably timed out
        // waiting for read-repair acknowledgement.
        let enough_responses_with_data = QueryError::DbError(
            DbError::ReadTimeout {
                consistency: Consistency::Two,
                received: 2,
                required: 2,
                data_present: true,
            },
            String::new(),
        );

        for &cl in CONSISTENCY_LEVELS {
            // Not idempotent
            let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(
                    &enough_responses_with_data,
                    false,
                    cl
                )),
                RetryDecision::DontRetry
            );

            // Idempotent
            let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(
                    &enough_responses_with_data,
                    true,
                    cl
                )),
                RetryDecision::DontRetry
            );
        }

        // Not enough responses, data_present == true
        let received = 1;
        let not_enough_responses_with_data = QueryError::DbError(
            DbError::ReadTimeout {
                consistency: Consistency::Two,
                received,
                required: 2,
                data_present: true,
            },
            String::new(),
        );
        for &cl in CONSISTENCY_LEVELS {
            let expected_decision = max_likely_to_work_cl(received, cl);

            // Not idempotent
            let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(
                    &not_enough_responses_with_data,
                    false,
                    cl
                )),
                expected_decision
            );
            if let RetryDecision::RetrySameNode(new_cl) = expected_decision {
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &not_enough_responses_with_data,
                        false,
                        new_cl.unwrap_or(cl)
                    )),
                    RetryDecision::DontRetry
                );
            }

            // Idempotent
            let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
            assert_eq!(
                policy.decide_should_retry(make_query_info_with_cl(
                    &not_enough_responses_with_data,
                    true,
                    cl
                )),
                expected_decision
            );
            if let RetryDecision::RetrySameNode(new_cl) = expected_decision {
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &not_enough_responses_with_data,
                        true,
                        new_cl.unwrap_or(cl)
                    )),
                    RetryDecision::DontRetry
                );
            }
        }
    }

    // WriteTimeout will retry once when the query is idempotent and write_type == BatchLog
    #[test]
    fn downgrading_consistency_write_timeout() {
        for (received, required) in (1..=5).zip(2..=6) {
            // WriteType == BatchLog
            let write_type_batchlog = QueryError::DbError(
                DbError::WriteTimeout {
                    consistency: Consistency::Two,
                    received,
                    required,
                    write_type: WriteType::BatchLog,
                },
                String::new(),
            );

            for &cl in CONSISTENCY_LEVELS {
                // Not idempotent
                let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_batchlog,
                        false,
                        cl
                    )),
                    RetryDecision::DontRetry
                );

                // Idempotent
                let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_batchlog,
                        true,
                        cl
                    )),
                    RetryDecision::RetrySameNode(None)
                );
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_batchlog,
                        true,
                        cl
                    )),
                    RetryDecision::DontRetry
                );
            }

            // WriteType == UnloggedBatch
            let write_type_unlogged_batch = QueryError::DbError(
                DbError::WriteTimeout {
                    consistency: Consistency::Two,
                    received,
                    required,
                    write_type: WriteType::UnloggedBatch,
                },
                String::new(),
            );

            for &cl in CONSISTENCY_LEVELS {
                // Not idempotent
                let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_unlogged_batch,
                        false,
                        cl
                    )),
                    RetryDecision::DontRetry
                );

                // Idempotent
                let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_unlogged_batch,
                        true,
                        cl
                    )),
                    max_likely_to_work_cl(received, cl)
                );
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_unlogged_batch,
                        true,
                        cl
                    )),
                    RetryDecision::DontRetry
                );
            }

            // WriteType == other
            let write_type_other = QueryError::DbError(
                DbError::WriteTimeout {
                    consistency: Consistency::Two,
                    received,
                    required,
                    write_type: WriteType::Simple,
                },
                String::new(),
            );

            for &cl in CONSISTENCY_LEVELS {
                // Not idempotent
                let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_other,
                        false,
                        cl
                    )),
                    RetryDecision::DontRetry
                );

                // Idempotent
                let mut policy = DowngradingConsistencyRetryPolicy::new().new_session();
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_other,
                        true,
                        cl
                    )),
                    RetryDecision::IgnoreWriteError
                );
                assert_eq!(
                    policy.decide_should_retry(make_query_info_with_cl(
                        &write_type_other,
                        true,
                        cl
                    )),
                    RetryDecision::DontRetry
                );
            }
        }
    }
}