From b5f641ef2e62211a03c8258d2b895423432c9c3b Mon Sep 17 00:00:00 2001 From: Stalin Date: Thu, 3 Dec 2026 15:01:25 +0530 Subject: [PATCH] Fix SET KEEPTTL losing the value of a logically expired key When the key was past its expire time but not yet reclaimed, SET ... KEEPTTL moved the dead expire onto the new value, so the next read expired the key and deleted the value that had just been acknowledged. Expire the key first on the KEEPTTL path, so the write starts from a clean key, as Redis does through its write lookup. Add a regression test. Fixes #983 Signed-off-by: Stalin --- src/t_string.cpp | 5 +++++ tests/unit/expire.tcl | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/t_string.cpp b/src/t_string.cpp index f946ba3a3..9216abfad 100644 --- a/src/t_string.cpp +++ b/src/t_string.cpp @@ -112,6 +112,11 @@ void setGenericCommand(client *c, int flags, robj *key, robj *val, robj *expire, if (getGenericCommand(c) == C_ERR) return; } + /* KEEPTTL carries the existing expire over to the new value. If the key is + * already logically expired but not reclaimed yet, drop it first, otherwise the + * dead expire is moved onto the new value and the write is lost on the next read. */ + if (flags & OBJ_KEEPTTL) expireIfNeeded(c->db, key); + genericSetKey(c,c->db,key, val,flags & OBJ_KEEPTTL,1); g_pserver->dirty++; notifyKeyspaceEvent(NOTIFY_STRING,"set",key,c->db->id); diff --git a/tests/unit/expire.tcl b/tests/unit/expire.tcl index 97b36797f..f355918c0 100644 --- a/tests/unit/expire.tcl +++ b/tests/unit/expire.tcl @@ -426,6 +426,17 @@ start_server {tags {"expire"}} { assert {$ttl <= 100 && $ttl > 80} } + test {SET - KEEPTTL on a logically expired key keeps the new value} { + r flushall + r debug set-active-expire 0 + r set foo old PXAT 1 + assert_equal OK [r set foo new KEEPTTL] + assert_equal new [r get foo] + assert_equal 1 [r exists foo] + assert_equal -1 [r ttl foo] + r debug set-active-expire 1 + } + test {Roundtrip for subkey expires works} { r flushall r sadd testkey foo bar baz