KeyDB icon indicating copy to clipboard operation
KeyDB copied to clipboard

[BUG] SET ... KEEPTTL on a logically expired key replies OK and then loses the value

Open jiren-the-gray opened this issue 1 month ago • 0 comments

Describe the bug

When the key named in SET key value KEEPTTL is still present in the dict but its expire time has already passed, the already-dead expire is moved onto the new value instead of being dropped. The SET is answered OK, and the next read expires the key and deletes it, taking the new value with it. The write is acknowledged and then silently lost.

SET k old PXAT 1       ->  OK        (expire in 1970: the key is logically gone)
SET k new KEEPTTL      ->  OK
GET k                  ->  (nil)     the value just written is gone
EXISTS k               ->  0
TYPE k                 ->  none

This is not confined to artificial timestamps. A key that expired naturally a few milliseconds ago, before the active-expire cycle has reclaimed it, behaves the same way — that is the shape this takes in production, where a short-TTL key (cache entry, lock, session) is rewritten with KEEPTTL just after its TTL lapsed:

SET k old PX 1
(wait 5 ms)
SET k new KEEPTTL      ->  OK
GET k                  ->  (nil)

Retrying does not help. Three SET ... KEEPTTL in a row are all lost and DBSIZE is 0, because nothing on that path reads the key and so nothing triggers lazy expiry.

To reproduce

docker run -d -p 6402:6379 eqalpha/keydb:x86_64_v6.3.4

From a clean keyspace (FLUSHALL), on one connection:

SET k old PXAT 1
SET k new KEEPTTL     -> +OK
GET k                 -> (nil)     expected "new"
EXISTS k              -> :0        expected :1
TYPE k                -> none      expected string

Each row below is an independent sequence from a clean keyspace.

case expected Redis 8.10.2 Garnet Kvrocks Dragonfly KeyDB 6.3.4
SET k old PXAT 1; SET k new KEEPTTL; GET k "new" "new" "new" "new" "new" (nil)
… EXISTS k 1 1 1 1 1 0
… TYPE k string string string string string none
SET k old PX 1; wait 5 ms; SET k new KEEPTTL; GET k "new" "new" "new" "new" "new" (nil)
expired, then three SET ... KEEPTTL, GET k "c" "c" "c" "c" "c" (nil)
control: SET k new (no KEEPTTL), GET k "new" "new" "new" "new" "new" "new"
control: SET k new NX on the expired key, GET k "new" "new" "new" "new" "new" "new"
control: SET k new XX on the expired key (nil) (nil) (nil) (nil) (nil) (nil)
control: live key, SET k new KEEPTTL, TTL k 100 100 100 99 100 100

The last three rows are the point: KeyDB's own NX and XX paths agree with every other server that this key does not exist (XX declines, NX succeeds), and SET without KEEPTTL writes the value fine. Only the KEEPTTL path treats the dead key as present and inherits its expire.

A self-contained Python 3 reproducer (standard library only) that runs every case against KeyDB and against reference servers and prints this table is attached as repro.py; it exits 0 when the bug reproduces.

Expected behavior

GET k should return "new", EXISTS k should be 1 and TYPE k should be string. The SET documentation defines the command, the option and the reply:

Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type.

KEEPTTL — Retain the time to live associated with the key.

Simple string reply: OK: The key was set.

A key whose expire has passed does not exist as far as every other command is concerned — that is lookupKeyWrite's own contract in this file ("Lookup a key for write operations, and as a side effect, if needed, expires the key if its TTL is reached", src/db.cpp:244-248) and it is what KeyDB's XX reply above demonstrates. A key that does not exist has no time to live to retain, so KEEPTTL has nothing to keep; the new value must be stored and visible. Returning OK for a write that is then invisible contradicts the documented reply outright.

Additional information

Version and environment. KeyDB 6.3.4, from the published container image eqalpha/keydb:x86_64_v6.3.4 (digest sha256:eceb1806730c7850395b8262300182c2e15a6e5dacbf0b72cbab110518caf43f); INFO server reports redis_version:6.3.4. Source read at 7e7e5e57d25fe246a8201f0acf5e7363c0bf1e14 (tag v6.3.4). Host: Ubuntu 24.04.5 LTS, kernel 7.0.0-38-generic (x86_64), Docker. Default configuration, single node, no replication.

Potential Cause. genericSetKey never passes through lookupKeyWrite/expireIfNeeded, so it cannot tell a live key from a logically expired one still sitting in the dict (src/db.cpp:410-418):

void genericSetKey(client *c, redisDb *db, robj *key, robj *val, int keepttl, int signal) {
    db->prepOverwriteForSnapshot(szFromObj(key));
    dict_iter iter;
    if (!dbAddCore(db, szFromObj(key), val, true /* fUpdateMvcc */, false /*fAssumeNew*/, &iter)) {
        dbOverwrite(db, key, val, !keepttl, &iter);
    }
    incrRefCount(val);
    if (signal) signalModifiedKey(c,db,key);
}

With KEEPTTL, fRemoveExpire is false, so dbOverwriteCore moves the old (already elapsed) expire onto the new value (src/db.cpp:318-334):

if (old->FExpires()) {
    if (fRemoveExpire) {
        ::removeExpire(this, key);
    }
    else {
        if (val->getrefcount(std::memory_order_relaxed) == OBJ_SHARED_REFCOUNT)
            val = dupStringObject(val);
        ::updateExpire(this, itr.key(), old, val);     // :332
    }
}

updateExpire (src/db.cpp:78-89) transfers valOld->expire to valNew. The new value now carries when = 1, so the first lookupKeyReadWithFlags → expireIfNeeded → keyIsExpired (src/db.cpp:2030, :2090) finds now > 1 and deletes the key.

Every sibling write path in src/t_string.cpp calls lookupKeyWrite first, which is why they all behave correctly: setGenericCommand's NX/XX check (:104-105), incrDecrCommand (:587), incrbyfloatCommand (:647), appendCommand (:680). The KEEPTTL path is the one that skips it. Upstream Redis's genericSetKey calls lookupKeyWrite(db,key) before choosing dbAdd or dbOverwrite, which removes the expired key first; KeyDB's rewrite of this function around dbAddCore/MVCC dropped that call.

The existing test for this option, tests/unit/expire.tcl:422-427 ("SET - use KEEPTTL option, TTL should not be removed"), only covers a live key, which is why this is not caught.

Suggested fix. Expire the key before deciding what to do with its TTL. Either call lookupKeyWrite(db, key) (or expireIfNeeded) at the top of genericSetKey, as upstream does, or — if the MVCC/snapshot handling in dbAddCore makes that awkward — have dbOverwriteCore treat an elapsed expire as absent:

long long when;
if (old->FExpires()) {
    if (fRemoveExpire ||
        (old->expire.FGetPrimaryExpire(&when) && when <= mstime())) {   // elapsed: nothing to keep
        ::removeExpire(this, key);
    } else {
        ...
    }
}

(expireEntry::FGetPrimaryExpire(long long *pwhen) is src/expire.h:280; it returns false when the key carries only subkey expires, in which case the existing branch is still correct.) The first form is preferable because it also keeps KEEPTTL consistent with NX/XX, which already see the key as gone.

jiren-the-gray avatar Oct 20 '26 04:10 jiren-the-gray