Skip to content

Commit a9ff0e6

Browse files
pingyuemmanuel-keller
authored andcommitted
transaction: Handle "commit ts expired" error (tikv#491)
Signed-off-by: Ping Yu <[email protected]> (cherry picked from commit ac95421)
1 parent bc9e522 commit a9ff0e6

File tree

6 files changed

+67
-15
lines changed

6 files changed

+67
-15
lines changed

src/common/errors.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ pub enum Error {
104104
#[error("{}", message)]
105105
InternalError { message: String },
106106
#[error("{0}")]
107-
StringError(String),
107+
OtherError(String),
108108
#[error("PessimisticLock error: {:?}", inner)]
109109
PessimisticLockError {
110110
inner: Box<Error>,

src/kv/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ pub use key::Key;
1313
pub use kvpair::KvPair;
1414
pub use value::Value;
1515

16-
struct HexRepr<'a>(pub &'a [u8]);
16+
pub struct HexRepr<'a>(pub &'a [u8]);
1717

1818
impl fmt::Display for HexRepr<'_> {
1919
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

src/region_cache.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ impl<C: RetryClientTrait> RegionCache<C> {
117117
return self.read_through_region_by_id(id).await;
118118
}
119119
}
120-
Err(Error::StringError(format!(
120+
Err(Error::OtherError(format!(
121121
"Concurrent PD requests failed for {MAX_RETRY_WAITING_CONCURRENT_REQUEST} times"
122122
)))
123123
}
@@ -316,7 +316,7 @@ mod test {
316316
.filter(|(_, r)| r.contains(&key.clone().into()))
317317
.map(|(_, r)| r.clone())
318318
.next()
319-
.ok_or_else(|| Error::StringError("MockRetryClient: region not found".to_owned()))
319+
.ok_or_else(|| Error::OtherError("MockRetryClient: region not found".to_owned()))
320320
}
321321

322322
async fn get_region_by_id(
@@ -331,7 +331,7 @@ mod test {
331331
.filter(|(id, _)| id == &&region_id)
332332
.map(|(_, r)| r.clone())
333333
.next()
334-
.ok_or_else(|| Error::StringError("MockRetryClient: region not found".to_owned()))
334+
.ok_or_else(|| Error::OtherError("MockRetryClient: region not found".to_owned()))
335335
}
336336

337337
async fn get_store(

src/store/errors.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
22

3-
use std::fmt::Display;
4-
53
use crate::proto::kvrpcpb;
64
use crate::Error;
75

@@ -164,11 +162,15 @@ impl HasKeyErrors for kvrpcpb::PessimisticRollbackResponse {
164162
}
165163
}
166164

167-
impl<T: HasKeyErrors, E: Display> HasKeyErrors for Result<T, E> {
165+
impl<T: HasKeyErrors> HasKeyErrors for Result<T, Error> {
168166
fn key_errors(&mut self) -> Option<Vec<Error>> {
169167
match self {
170168
Ok(x) => x.key_errors(),
171-
Err(e) => Some(vec![Error::StringError(e.to_string())]),
169+
Err(Error::MultipleKeyErrors(errs)) => Some(std::mem::take(errs)),
170+
Err(e) => Some(vec![std::mem::replace(
171+
e,
172+
Error::OtherError("".to_string()), // placeholder, no use.
173+
)]),
172174
}
173175
}
174176
}

src/transaction/transaction.rs

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,14 @@ use derive_new::new;
1010
use fail::fail_point;
1111
use futures::prelude::*;
1212
use log::debug;
13+
use log::error;
14+
use log::info;
1315
use log::warn;
1416
use tokio::time::Duration;
1517

1618
use crate::backoff::Backoff;
1719
use crate::backoff::DEFAULT_REGION_BACKOFF;
20+
use crate::kv::HexRepr;
1821
use crate::pd::PdClient;
1922
use crate::pd::PdRpcClient;
2023
use crate::proto::kvrpcpb;
@@ -1278,7 +1281,7 @@ impl<PdC: PdClient> Committer<PdC> {
12781281
let min_commit_ts = self.prewrite().await?;
12791282

12801283
fail_point!("after-prewrite", |_| {
1281-
Err(Error::StringError(
1284+
Err(Error::OtherError(
12821285
"failpoint: after-prewrite return error".to_owned(),
12831286
))
12841287
});
@@ -1292,7 +1295,7 @@ impl<PdC: PdClient> Committer<PdC> {
12921295
// FIXME: min_commit_ts == 0 => fallback to normal 2PC
12931296
min_commit_ts.unwrap()
12941297
} else {
1295-
match self.commit_primary().await {
1298+
match self.commit_primary_with_retry().await {
12961299
Ok(commit_ts) => commit_ts,
12971300
Err(e) => {
12981301
return if self.undetermined {
@@ -1395,6 +1398,11 @@ impl<PdC: PdClient> Committer<PdC> {
13951398
.plan();
13961399
plan.execute()
13971400
.inspect_err(|e| {
1401+
debug!(
1402+
"commit primary error: {:?}, start_ts: {}",
1403+
e,
1404+
self.start_version.version()
1405+
);
13981406
// We don't know whether the transaction is committed or not if we fail to receive
13991407
// the response. Then, we mark the transaction as undetermined and propagate the
14001408
// error to the user.
@@ -1407,6 +1415,48 @@ impl<PdC: PdClient> Committer<PdC> {
14071415
Ok(commit_version)
14081416
}
14091417

1418+
async fn commit_primary_with_retry(&mut self) -> Result<Timestamp> {
1419+
loop {
1420+
match self.commit_primary().await {
1421+
Ok(commit_version) => return Ok(commit_version),
1422+
Err(Error::ExtractedErrors(mut errors)) => match errors.pop() {
1423+
Some(Error::KeyError(key_err)) => {
1424+
if let Some(expired) = key_err.commit_ts_expired {
1425+
// Ref: https://github.com/tikv/client-go/blob/tidb-8.5/txnkv/transaction/commit.go
1426+
info!("2PC commit_ts rejected by TiKV, retry with a newer commit_ts, start_ts: {}",
1427+
self.start_version.version());
1428+
1429+
let primary_key = self.primary_key.as_ref().unwrap();
1430+
if primary_key != expired.key.as_ref() {
1431+
error!("2PC commit_ts rejected by TiKV, but the key is not the primary key, start_ts: {}, key: {}, primary: {:?}",
1432+
self.start_version.version(), HexRepr(&expired.key), primary_key);
1433+
return Err(Error::OtherError("2PC commitTS rejected by TiKV, but the key is not the primary key".to_string()));
1434+
}
1435+
1436+
// Do not retry for a txn which has a too large min_commit_ts.
1437+
// 3600000 << 18 = 943718400000
1438+
if expired
1439+
.min_commit_ts
1440+
.saturating_sub(expired.attempted_commit_ts)
1441+
> 943718400000
1442+
{
1443+
let msg = format!("2PC min_commit_ts is too large, we got min_commit_ts: {}, and attempted_commit_ts: {}",
1444+
expired.min_commit_ts, expired.attempted_commit_ts);
1445+
return Err(Error::OtherError(msg));
1446+
}
1447+
continue;
1448+
} else {
1449+
return Err(Error::KeyError(key_err));
1450+
}
1451+
}
1452+
Some(err) => return Err(err),
1453+
None => unreachable!(),
1454+
},
1455+
Err(err) => return Err(err),
1456+
}
1457+
}
1458+
}
1459+
14101460
async fn commit_secondary(self, commit_version: Timestamp) -> Result<()> {
14111461
debug!("committing secondary");
14121462
let mutations_len = self.mutations.len();
@@ -1424,7 +1474,7 @@ impl<PdC: PdClient> Committer<PdC> {
14241474
let percent = percent.unwrap().parse::<usize>().unwrap();
14251475
new_len = mutations_len * percent / 100;
14261476
if new_len == 0 {
1427-
Err(Error::StringError(
1477+
Err(Error::OtherError(
14281478
"failpoint: before-commit-secondary return error".to_owned(),
14291479
))
14301480
} else {

tests/common/ctl.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,16 @@ use crate::common::Result;
1010
pub async fn get_region_count() -> Result<u64> {
1111
let res = reqwest::get(format!("http://{}/pd/api/v1/regions", pd_addrs()[0]))
1212
.await
13-
.map_err(|e| Error::StringError(e.to_string()))?;
13+
.map_err(|e| Error::OtherError(e.to_string()))?;
1414

1515
let body = res
1616
.text()
1717
.await
18-
.map_err(|e| Error::StringError(e.to_string()))?;
18+
.map_err(|e| Error::OtherError(e.to_string()))?;
1919
let value: serde_json::Value = serde_json::from_str(body.as_ref()).unwrap_or_else(|err| {
2020
panic!("invalid body: {:?}, error: {:?}", body, err);
2121
});
2222
value["count"]
2323
.as_u64()
24-
.ok_or_else(|| Error::StringError("pd region count does not return an integer".to_owned()))
24+
.ok_or_else(|| Error::OtherError("pd region count does not return an integer".to_owned()))
2525
}

0 commit comments

Comments
 (0)