# [KB]关于 TiCDC 升级后发生 CDC ErrSnapshotLostByGC 导致同步停止的问题.md

## Description

从 4.0.15，5.0.5，5.1.1 升级后，可能会导致某些同步任务（Changefeeed）停止同步，报错为： `\[CDC:ErrSnapshotLostByGC]fail to create or maintain changefeed due to snapshot loss caused by GC`。

```json
{
"id": "kafka-test",
"summary": {
"state": "failed",
"tso": 430093979858763792,
"checkpoint": "2021-12-28 07:58:48.929",
"error": {
"addr": "upstream-ticdc-0.upstream-ticdc-peer.test-1.svc:8301",
"code": "CDC:ErrSnapshotLostByGC",
"message": "[CDC:ErrSnapshotLostByGC]fail to create or maintain changefeed due to snapshot loss caused by GC. checkpoint-ts 430093979858763792 is earlier than or equal to GC safepoint at 430093979858763792"
}
```

## Root Cause

较新版本的 TiCDC 在启动 Changefeed 之前会检查以 Checkpoint-ts - 1 是否小于 TiDB 的 GC Safepoint，如果小于则会报错并停止启动 Changefeed。

Github Issue：[https://github.com/pingcap/tiflow/issues/4115](https://github.com/pingcap/tiflow/issues/4115)

> **注意**
> 
> checkpoint-ts 代表当前 changefeed 中已经成功写入下游的最大事务 TS

## Diagnostic Steps

1. 如果升级过程中，某个 Changefeed 的 CheckpointTs 和 TiDB 的 GC Safepoint 相等，那么有很大可能触发这个问题。

2. 报错的 Changefeed 会满足如下条件：
    1. 它们的 CheckpointTs 都相等，且比任何未报错的 Changefeed 的 CheckpointTs 都要小。

## Resolution

升级前将 TiDB 的 tidb_gc_life_time 设为一个较大值，如 1 天，然后确保 TiCDC 所有 Changefeed 同步延迟均较小（Checkpoint 应显著大于 gc_safe_point），再开始升级。

调整 tidb_gc_life_time 的命令如下：

```sql
mysql -h $TIDBIP -P $PORT -u root -E -e 'update mysql.tidb set VARIABLE_VALUE="24h" where VARIABLE_NAME="tikv_gc_life_time";'
```

升级完成后再将 tidb_gc_life_time 调整回原先设置，以默认配置 10 分钟为例：

```sql
mysql -h $TIDBIP -P $PORT -u root -E -e 'update mysql.tidb set VARIABLE_VALUE="10m" where VARIABLE_NAME="tikv_gc_life_time";'
```

## Workaround

目前，该问题一旦发生只能重建 Changefeed，步骤如下

1. 将 TiDB 的 tidb_gc_life_time 设为一个较大值，如 1 天，

    ```sql
    mysql -h $TIDBIP -P $PORT -u root -E -e 'update mysql.tidb set VARIABLE_VALUE="24h" where VARIABLE_NAME="tikv_gc_life_time";'
    ```

2. 记录 Changefeed 的 checkpoint-ts，如 430093979858763792

    ```shell
    tiup cdc:vX.X.X cli changefeed list
    ```

3. 重新创建 Changefeed，start-ts 需要指定成 checkpoint-ts + 1

    ```shell
    tiup cdc:vX.X.X cli changefeed remove -c $CHANGEFEED
    tiup cdc:vX.X.X cli changefeed create --start-ts=430093979858763793 --sink-uri="YYY"
    ```

4. 将 tidb_gc_life_time 调整回原先设置，以默认配置 10 分钟为例

    ```sql
    mysql -h $TIDBIP -P $PORT -u root -E -e 'update mysql.tidb set VARIABLE_VALUE="10m" where VARIABLE_NAME="tikv_gc_life_time";'
    ```

## Affect Version(optional)

| 老版本 |  4.0.15 |  5.0.5 |  5.1.1 |  |  |  | 
|  --- |  --- |  --- |  --- |  --- |  --- |  --- | 
| 新版本 | ≥ 4.0.16 | ≥ 5.0.6 | ≥ 5.1.2 | 5.2.x | 5.3.x | 5.4.x | 

 **从上述 ”老版本“ 升级到 “新版本”** 有可能触发这个问题。