#20136·tikv

bug: resolved-ts stops advancing permanently when a max-ts update is rejected

Author: YZL0v3ZZCreated Oct 1, 2026Updated Oct 1, 2026
Labelstype/bugcontribution

Bug Report

Summary

resolved_ts advances through a self-perpetuating loop: each round spawns a future that reschedules Task::AdvanceResolvedTs only at its end. When ConcurrencyManager::update_max_ts rejects the TSO fetched by that round, the future logs the error and returns before the reschedule, so the loop stops permanently. The rejection is a per-update result of the max-ts safety check, not a failure of the resolved-ts worker: update_max_ts returns it when storage.max-ts.action-on-invalid-update is set to error and a TSO fails the check after a re-check. That value is the default on the release-8.5 branch and is accepted as an online configuration change on master. Once the loop stops, safe_ts freezes for every region the store observes, stale reads with a larger read_ts are rejected with DataIsNotReady, CheckLeader requests for regions led by the store stop, and the reported min-resolved-ts freezes. No timer or configuration change restarts the loop; the store needs a restart.

What version of TiKV are you using?

I reproduced this on master at commit 7709ab9d738d16f856df990ad9ffb5c1908f84f8 (2026-09-29). The early return was introduced by #17917 (2024-12), which added the max-ts check, and it is present in master and release-8.5. The silent stop requires storage.max-ts.action-on-invalid-update = "error"; this is the default on the release-8.5 branch (see #19756), and master accepts it as an online configuration change.

What operating system and CPU are you using?

Linux x86_64 with cargo +nightly-2026-03-21. The defect is a control-flow issue in the resolved-ts worker and does not depend on the operating system or the CPU.

Steps to reproduce

  1. Run a store with storage.max-ts.action-on-invalid-update = "error" (the default on release-8.5).
  2. Trigger one invalid max-ts update: pd_client.get_tso() returns a value far beyond the drifted limit, and the double_check re-fetch cannot lift the limit above it because that fetch returns a smaller TSO. Issues #18055 and #19755 show that a PD leader clock offset and a PD leader switch, respectively, produce this state.
  3. The round logs failed to advance resolved_ts: failed to update max_ts in concurrency manager, returns, and schedules no further Task::AdvanceResolvedTs.
  4. safe_ts stops moving for the store, and a stale read with a larger read_ts is rejected from then on with DataIsNotReady.

The unit test below reproduces the stop deterministically. It calls the real AdvanceTsWorker::advance_ts_for_regions and asserts that no Task::AdvanceResolvedTs arrives after update_max_ts is rejected; the control case shows that the loop re-arms when the TSO passes the check.

Deterministic PoC test (paste into components/resolved_ts/src/advance.rs, inside the existing #[cfg(test)] mod tests module)
rust
#[cfg(test)]
mod advance_chain_poc {
    use std::{sync::Arc, time::Duration};

    use concurrency_manager::{ActionOnInvalidMaxTs, ConcurrencyManager, TSOProvider};
    use grpcio::EnvBuilder;
    use pd_client::{PdClient, PdFuture};
    use tikv_util::worker::{ReceiverWrapper, dummy_scheduler};
    use txn_types::TimeStamp;

    use super::*;

    const SMALL_TS_MS: u64 = 1_000_000_000_000;
    const LARGE_TS_MS: u64 = SMALL_TS_MS + 600_000; // +10 min

    // PD client used by `AdvanceTsWorker`: returns the pinned TSO on every call.
    struct PinnedPdClient(TimeStamp);

    impl PdClient for PinnedPdClient {
        fn batch_get_tso(&self, _count: u32) -> PdFuture<TimeStamp> {
            let ts = self.0;
            Box::pin(async move { Ok(ts) })
        }
    }

    // TSO provider used by `ConcurrencyManager::double_check`: confirms a
    // smaller TSO, so the update stays rejected.
    struct ConfirmingTso(TimeStamp);

    impl TSOProvider for ConfirmingTso {
        fn get_tso(&self) -> PdFuture<TimeStamp> {
            let ts = self.0;
            Box::pin(async move { Ok(ts) })
        }
    }

    fn build_worker(
        pd_ts: TimeStamp,
        cm: ConcurrencyManager,
    ) -> (AdvanceTsWorker, ReceiverWrapper<Task>) {
        let (scheduler, rx) = dummy_scheduler::<Task>();
        let pd_client: Arc<dyn PdClient> = Arc::new(PinnedPdClient(pd_ts));
        let worker = AdvanceTsWorker::new(pd_client.clone(), scheduler, cm);
        let leader_resolver = LeadershipResolver::new(
            1,
            pd_client,
            Arc::new(EnvBuilder::new().build()),
            Arc::new(SecurityManager::default()),
            RegionReadProgressRegistry::new(),
            Duration::from_secs(60),
        );
        worker.advance_ts_for_regions(
            vec![],
            leader_resolver,
            Duration::from_millis(20),
            Arc::new(Notify::new()),
        );
        (worker, rx)
    }

    // Control: a valid TSO keeps the loop re-arming.
    #[test]
    fn control_valid_tso_keeps_the_advance_chain_alive() {
        let ts = TimeStamp::compose(SMALL_TS_MS, 0);
        let tso: Arc<dyn TSOProvider> = Arc::new(ConfirmingTso(ts));
        let cm = ConcurrencyManager::new_with_config(
            TimeStamp::new(1),
            Duration::from_secs(0),
            ActionOnInvalidMaxTs::Error,
            Some(tso),
            Duration::from_millis(1),
        );
        cm.set_max_ts_limit(ts);
        let (_worker, mut rx) = build_worker(ts, cm);
        let task = rx
            .recv_timeout(Duration::from_secs(3))
            .expect("worker closed or timed out before re-arming")
            .expect("worker closed");
        assert!(
            matches!(&task, Task::AdvanceResolvedTs { .. }),
            "expected the advance loop to re-arm, got {:?}",
            task
        );
    }

    // Fault: a rejected max_ts update returns early, so no reschedule arrives.
    #[test]
    fn rejected_max_ts_update_terminates_the_advance_chain() {
        let small = TimeStamp::compose(SMALL_TS_MS, 0);
        let large = TimeStamp::compose(LARGE_TS_MS, 0);
        let tso: Arc<dyn TSOProvider> = Arc::new(ConfirmingTso(small));
        let cm = ConcurrencyManager::new_with_config(
            TimeStamp::new(1),
            Duration::from_secs(0),
            ActionOnInvalidMaxTs::Error,
            Some(tso),
            Duration::from_millis(1),
        );
        cm.set_max_ts_limit(small);
        assert!(
            cm.update_max_ts(large, "resolved-ts").is_err(),
            "the constructed state must reject the max_ts update"
        );
        let (_worker, mut rx) = build_worker(large, cm);
        let res = rx.recv_timeout(Duration::from_secs(3));
        assert!(
            res.is_err(),
            "advance chain re-armed although the max_ts update was rejected: {:?}",
            res
        );
    }
}

Run it with:

bash
cargo +nightly-2026-03-21 test -p resolved_ts --lib advance_chain_poc -- --nocapture

What did you expect?

A rejected update_max_ts should be a per-round failure. The round should log it, skip the advance, and reschedule Task::AdvanceResolvedTs after advance_ts_interval so the store keeps serving resolved-ts. If the update stays invalid, the loop may keep failing and logging, but it should not disappear.

What did happened?

The future returns before the only reschedule, so the loop is gone. safe_ts freezes at the last successful value, stale reads are rejected indefinitely, and no watchdog, timer, or configuration change restarts the loop. In the test output below the second case finishes in 3.04 seconds, which is the recv_timeout(3s) window with no rescheduled task.

Test output (the second test passes because it detects the missing reschedule)
<user>@<host>:~/work/<project>$ cargo +nightly-2026-03-21 test -p resolved_ts --lib advance_chain_poc -- --nocapture
Running unittests src/lib.rs (target/debug/deps/resolved_ts-9baacb95b8e71e1f)

running 2 tests
test advance::tests::advance_chain_poc::control_valid_tso_keeps_the_advance_chain_alive ... ok
test advance::tests::advance_chain_poc::rejected_max_ts_update_terminates_the_advance_chain ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 12 filtered out; finished in 3.04s

<user>@<host>:~/work/<project>$

Root cause

The loop has a single reschedule point, and the error branch returns before it. Six links explain why one rejected update is permanent.

(1) The only reschedule sits at the end of the future.

rust
// components/resolved_ts/src/advance.rs:107–177 (abridged)
    pub fn advance_ts_for_regions(
        &self,
        regions: Vec<u64>,
        mut leader_resolver: LeadershipResolver,
        advance_ts_interval: Duration,
        advance_notify: Arc<Notify>,
    ) {
        // ...
        let fut = async move {
            let mut min_ts = pd_client.get_tso().await.unwrap_or_default();
            // ...
            if let Err(e) = cm.update_max_ts(min_ts, "resolved-ts") {
                error!("failed to advance resolved_ts: failed to update max_ts in concurrency manager"; "err" => ?e);
                return;
            }
            // ...
            let regions = leader_resolver
                .resolve(regions, min_ts, Some(advance_ts_interval))
                .await;
            if !regions.is_empty() {
                if let Err(e) = scheduler.schedule(Task::ResolvedTsAdvanced {
                    regions,
                    ts: min_ts,
                    ts_source,
                }) {
                    info!("failed to schedule advance event"; "err" => ?e);
                }
            }

            futures::select! {
                _ = timeout.compat().fuse() => (),
                _ = advance_notify.notified().fuse() => (),
            };
            let _ = min_timeout.compat().await;

            // NB: We must schedule the leader resolver even if there is no region,
            //     otherwise we can not advance resolved ts next time.
            if let Err(e) = scheduler.schedule(Task::AdvanceResolvedTs { leader_resolver }) {
                error!("failed to schedule register advance event"; "err" => ?e);
            }
        };
        self.worker.spawn(fut);
    }

The comment at the reschedule states the contract: the round must schedule the next AdvanceResolvedTs, otherwise resolved ts cannot advance again. The return in the update_max_ts branch exits before that line.

(2) The loop starts once, and nothing else reschedules it.

rust
// components/resolved_ts/src/endpoint.rs:727–730
        };
        ep.handle_advance_resolved_ts(leader_resolver);
        ep
    }
rust
// components/resolved_ts/src/endpoint.rs:1010–1018
    fn handle_advance_resolved_ts(&self, leader_resolver: LeadershipResolver) {
        let regions = self.regions.keys().copied().collect();
        self.advance_worker.advance_ts_for_regions(
            regions,
            leader_resolver,
            self.cfg.advance_ts_interval.0,
            self.advance_notify.clone(),
        );
    }
rust
// components/resolved_ts/src/endpoint.rs:1214–1216
            Task::AdvanceResolvedTs { leader_resolver } => {
                self.handle_advance_resolved_ts(leader_resolver)
            }

Endpoint::new calls the worker once, and every later round arrives through Task::AdvanceResolvedTs, which only the tail reschedule produces. The remaining endpoint code does not re-arm the loop:

rust
// components/resolved_ts/src/endpoint.rs:1391–1399
    fn on_timeout(&mut self) {
        let stats = self.collect_stats();
        self.update_metrics(&stats);
        self.log_slow_regions(&stats);
    }

    fn get_interval(&self) -> Duration {
        Duration::from_millis(METRICS_FLUSH_INTERVAL)
    }

handle_change_config only calls advance_notify.notify_waiters() (endpoint.rs:1020–1025), which wakes a round that is still running. It cannot restart a loop whose future has already returned.

(3) update_max_ts rejects a TSO instead of failing the loop.

rust
// components/concurrency_manager/src/lib.rs:243–264 (abridged)
        let request_origin_for_check = source.request_origin_for_check();
        let exact_limit_required =
            exact_limit_required_for_request_origin_check(request_origin_for_check);
        let limits = self.max_ts_limit.load();
        let update_limit = limits.max_ts_update_limit(exact_limit_required);

        if exact_limit_required {
            self.check_exact_max_ts_update_limit(
                new_ts,
                update_limit,
                source,
                request_origin_for_check,
            )?;
        } else {
            self.check_drifted_max_ts_update_limit(
                new_ts,
                limits,
                update_limit,
                source,
                request_origin_for_check,
            )?;
        }

For the "resolved-ts" source, which is a plain &str, the request origin is None, so the drifted check applies. That check calls double_check, which fetches a fresh TSO, updates the limit from it, and then decides:

rust
// components/concurrency_manager/src/lib.rs:435–449 (abridged)
        match self.action_on_invalid_max_ts_update.load() {
            ActionOnInvalidMaxTs::Panic if tso_confirmed => {
                panic!(
                    "invalid max_ts update: {} exceeds the limit {}, source={}",
                    new_ts,
                    update_limit.into_inner(),
                    source
                );
            }
            ActionOnInvalidMaxTs::Error if tso_confirmed => Err(InvalidMaxTsUpdate {
                attempted_ts: new_ts,
                limit: update_limit,
            }),
            _ => Ok(()),
        }

The call returns Err only when the configured action is error and the re-check confirms that the TSO is invalid. That is a rejection of one update, not a reason for the resolved-ts worker to stop.

(4) The rejection path is a supported production configuration, and the release-8.5 default selects it.

rust
// src/storage/config.rs:67
const DEFAULT_ACTION_ON_INVALID_MAX_TS_UPDATE: &str = "panic";

The value above is the master default. The release-8.5 branch sets the same constant to "error" (#19756), so builds from that branch deliver the rejection without any configuration change. On master, the action is a normal storage configuration and can be changed online:

rust
// components/server/src/server.rs:435–447 (abridged)
        let concurrency_manager = ConcurrencyManager::new_with_config(
            latest_ts,
            (config.storage.max_ts.cache_sync_interval * LIMIT_VALID_TIME_MULTIPLIER).into(),
            config
                .storage
                .max_ts
                .action_on_invalid_update
                .as_str()
                .try_into()
                .unwrap(),
            Some(pd_client.clone()),
            config.storage.max_ts.max_drift.0,
        );

src/storage/config_manager.rs:113–121 dispatches an online change of action_on_invalid_update to ConcurrencyManager::set_action_on_invalid_max_ts_update, so the error action is a routine operator choice.

(5) Other callers treat the same rejection as transient, and the analogous CDC loop reschedules from a defer! block.

The raftstore caller keeps its retry loop alive when update_max_ts returns an error:

rust
// components/raftstore/src/store/worker/pd.rs:2231–2240
                    Err(e) => {
                        if last_log_ts.elapsed() > log_interval {
                            warn!(
                                "failed to update max timestamp for region";
                                "region_id" => region_id,
                                "error" => ?e
                            );
                            last_log_ts = Instant::now();
                        }
                    }

The backup path maps the same error into a response to the client (components/backup/src/endpoint.rs:373–379). The CDC advance loop shares the self-perpetuating structure, but it wraps its reschedule in a guard, so an early exit does not lose the next round:

rust
// components/cdc/src/endpoint.rs:1139–1165 (abridged)
            cm.update_max_ts(min_ts, "cdc").unwrap();
            // ...
            let slow_timer = SlowTimer::default();
            defer!({
                slow_log!(T slow_timer, "cdc resolve region leadership");
                if let Ok(leader_resolver) = leader_resolver_rx.try_recv() {
                    match scheduler.schedule(Task::RegisterMinTsEvent {
                        leader_resolver,
                        event_time: Instant::now(),
                    }) {
                        Ok(_) | Err(ScheduleError::Stopped(_)) => (),
                        // Must schedule `RegisterMinTsEvent` event otherwise resolved ts can not
                        // advance normally.
                        Err(err) => panic!("failed to register min ts event, error: {:?}", err),
                    }
                } else {
                    // ...
                    warn!("cdc leader resolver is lost, are we shutdown?");
                }
            });

resolved_ts is the only update_max_ts call site that both handles the error explicitly and relies on tail rescheduling.

(6) The stop reaches the resolved-ts output path immediately.

Resolver::resolve publishes the result into the region read progress, and it is the writer that moves safe_ts:

rust
// components/resolved_ts/src/resolver.rs:469–472
        // Publish an `(apply index, safe ts)` item into the region read progress
        if let Some(rrp) = &self.read_progress {
            rrp.update_safe_ts_with_time(self.tracked_index, self.resolved_ts.into_inner(), now);
        }

With no ResolvedTsAdvanced task, this write never happens again for the store. The consumer then rejects reads whose timestamp is above the frozen value:

rust
// components/raftstore/src/store/peer.rs:5340–5361 (abridged)
        let flags = WriteBatchFlags::from_bits_check(req.get_header().get_flags());
        if flags.contains(WriteBatchFlags::STALE_READ) {
            let read_ts = decode_u64(&mut req.get_header().get_flag_data()).unwrap();
            let safe_ts = self.read_progress.safe_ts();
            if safe_ts < read_ts {
                // ...
                warn!(
                    "read rejected by safe timestamp";
                    "safe_ts" => safe_ts,
                    "read_ts" => read_ts,
                    "tag" => &self.tag,
                );
                let mut response = cmd_resp::new_error(Error::DataIsNotReady {
                    region_id: region.get_id(),
                    peer_id: self.peer_id(),
                    safe_ts,
                });
                cmd_resp::bind_term(&mut response, self.term());
                // ...

The same frozen state stops the CheckLeader requests that the store sends for the regions it leads, so the followers and learners of those regions stop receiving leader safe-ts updates (components/raftstore/src/store/util.rs:1332–1338), and get_min_resolved_ts (components/raftstore/src/store/util.rs:1299–1309) stops reporting a moving value.

Impact

A single rejected max-ts update stops the resolved-ts advance loop of the store until the process restarts. For every region the store observes, safe_ts freezes, so stale reads with a read_ts above the frozen value fail with DataIsNotReady and never recover. The store also stops sending CheckLeader requests for the regions it leads, which freezes the leader safe-ts state on their followers and learners, and the min-resolved-ts value reported to PD stops moving. Normal reads, writes, and transactions are unaffected, and CD