# [Known Issue] Report PessimisticLockNotFound when fair locking is enabled ([tidb#58279](https://github.com/pingcap/tidb/issues/58279))

Source note: adapted from GitHub issue [tidb#58279](https://github.com/pingcap/tidb/issues/58279).

## Issue

- Link: [tidb#58279](https://github.com/pingcap/tidb/issues/58279)
- Symptom: transaction commit may fail with `PessimisticLockNotFound` / `LockMissingAmendFail` when `tidb_pessimistic_txn_fair_locking` is enabled

## Phenomenon

When fair locking mode (`tidb_pessimistic_txn_fair_locking`) is enabled, TiDB may encounter a `PessimisticLockNotFound` error during transaction commit:

```text
Mysql2::Error: tikv aborts txn: Error(Txn(Error(Mvcc(Error(PessimisticLockNotFound { start_ts: TimeStamp(454479204809965680), key: [...], reason: LockMissingAmendFail }))))): COMMIT
```

## Root Cause

The bug is triggered under a specific lock/unlock timing sequence in fair locking mode:

1. When the current key's lock is released, TiKV wakes up the first transaction (txn1) in the waiting queue and grants the lock to it.
2. After receiving the wake-up notification, txn1 calls `retryAggressiveLocking` to retry acquiring the lock and resets its `ttlManager`, assuming the primary key might change.
3. However, if the primary key has not changed, TiDB skips the actual locking operation.
4. Since `ttlManager` only runs when a pessimistic lock request is actually sent, skipping the lock acquisition prevents the heartbeat from starting.
5. As a result, the lock expires and gets cleaned up. When txn1 subsequently commits, TiKV returns `PessimisticLockNotFound`.

## Reproduction Example

```sql
/* init */ drop table if exists t;
/* init */ create table t (id int primary key, v int);
/* init */ insert into t values (1, 1);

/* t2 */ begin;
/* t2 */ update t set v = v + 1 where id = 1;

/* t1 */ begin;
/* t1 */ update t set v = v + 1 where id = 1;

/* t2 */ commit;

/* t1 */ select sleep(30);
/* t1 */ rollback;
```

## Diagnostic Steps

1. Check TiDB logs for the following error during transaction commit:

```text
Mysql2::Error: tikv aborts txn: Error(Txn(Error(Mvcc(Error(PessimisticLockNotFound ...))))): COMMIT
```

1. Confirm fair locking is enabled:

```sql
SHOW VARIABLES LIKE 'tidb_pessimistic_txn_fair_locking';
```

## Workaround

Disable fair locking mode:

```sql
SET GLOBAL tidb_pessimistic_txn_fair_locking = OFF;
```

## Affected Version

- v7.1.0
- v7.5.0
- v8.1.0
- v8.5.0

## Fixed Version

- v8.5.4
- v8.1.3
- v7.5.8
- v7.1.7

## Related Oncall

- v8.1.0 how to fix the PessimisticLockNotFound error TCOC-2917 / TCID-10991
- v7.1.5 PessimisticLockNotFound APID-11148
