diff --git a/src/module.c b/src/module.c index 5fa5ab096..7bf403080 100644 --- a/src/module.c +++ b/src/module.c @@ -12326,6 +12326,12 @@ int VM_ScanKey(ValkeyModuleKey *key, ValkeyModuleScanCursor *cursor, ValkeyModul robj *field = (vstr != NULL) ? createStringObject((char *)vstr, vlen) : createStringObjectFromLongLongWithSds(vll); p = lpNext(objectGetVal(o), p); + /* Skip fields not visible in the current context, like HSCAN. */ + if (!hashTypeListpackFieldIsValid(hashTypeListpackGetExpiry(objectGetVal(o), p))) { + decrRefCount(field); + p = lpNext(objectGetVal(o), p); + continue; + } vstr = lpGetValue(p, &vlen, &vll); robj *value = (vstr != NULL) ? createStringObject((char *)vstr, vlen) : createStringObjectFromLongLongWithSds(vll); @@ -12483,6 +12489,11 @@ int VM_ScanKeyRawBorrowed(ValkeyModuleKey *key, ValkeyModuleScanCursor *cursor, } p = lpNext(lp, p); if (!p) break; + /* Skip fields not visible in the current context, like HSCAN. */ + if (!hashTypeListpackFieldIsValid(hashTypeListpackGetExpiry(lp, p))) { + p = lpNext(lp, p); + continue; + } unsigned int vlen; long long vll; char vbuf[LONG_STR_SIZE]; diff --git a/tests/unit/moduleapi/scan.tcl b/tests/unit/moduleapi/scan.tcl index 89c954437..6426b3548 100644 --- a/tests/unit/moduleapi/scan.tcl +++ b/tests/unit/moduleapi/scan.tcl @@ -24,6 +24,24 @@ start_server {tags {"modules"}} { lsort [r scan.scan_key hh1] } {{f1 1}} + test {Module scan hash listpack skips expired fields} { + r debug set-active-expire 0 + r del hhexp + r hset hhexp f1 v1 f2 v2 + r hpexpire hhexp 1 FIELDS 1 f1 + wait_for_condition 50 10 { + [r hgetall hhexp] eq {f2 v2} + } else { + fail "field f1 did not expire" + } + # f1 is expired but not reaped + assert_equal 2 [r hlen hhexp] + assert_encoding listpack hhexp + set res [lsort [r scan.scan_key hhexp]] + r debug set-active-expire 1 + set res + } {{f2 v2}} {needs:debug} + test {Module scan hash dict} { r config set hash-max-ziplist-entries 2 r hmset hh3 f1 v1 f2 v2 f3 v3 @@ -83,6 +101,24 @@ start_server {tags {"modules"}} { lsort [r scan.scan_key_raw rh1] } {{f1 1}} + test {Module scan_key_raw hash listpack skips expired fields} { + r debug set-active-expire 0 + r del rhexp + r hset rhexp f1 v1 f2 v2 + r hpexpire rhexp 1 FIELDS 1 f1 + wait_for_condition 50 10 { + [r hgetall rhexp] eq {f2 v2} + } else { + fail "field f1 did not expire" + } + # f1 is expired but not reaped + assert_equal 2 [r hlen rhexp] + assert_encoding listpack rhexp + set res [lsort [r scan.scan_key_raw rhexp]] + r debug set-active-expire 1 + set res + } {{f2 v2}} {needs:debug} + test {Module scan_key_raw hash dict} { r del rh3 r hmset rh3 f1 v1 f2 v2 f3 v3