#2163·garnet

IndexOutOfRangeException in ReinitializeExpiredRecord when ZADD hits an expired record read back from disk (`--storage-tier`)

Author: liu10725Created Sep 21, 2026Updated Sep 21, 2026

Describe the bug

Summary

With --storage-tier enabled, ZADD on an expired record that was evicted to disk crashes the session with an unhandled System.IndexOutOfRangeException from TsavoriteKV.ReinitializeExpiredRecord.

The exception escapes ProcessMessages, so the client sees Connection reset by peer / Broken pipe instead of an error reply. The server keeps running and the port stays open, so nothing external detects the failure — every subsequent client touching such a key disconnects again.

Reproduces deterministically in ~30 seconds on 2.1.8. The relevant source is identical on main (5c6e595).

Environment

  • Garnet 2.1.8 (ghcr.io/microsoft/garnet:2.1.8), also on main @ 5c6e595
  • Observed in production on linux/arm64 (AWS t4g.small, 2 vCPU / 2 GiB)
  • Reproduced locally on linux/amd64 via Docker
  • Client: redis-py 8.1.0 (RESP3 and RESP2 both affected)

Repro

Three conditions must all hold. Missing any one prevents the bug from triggering — likely why it went unreported:

  1. --storage-tier is enabled (records reach disk, so RMW goes through ContinuePendingRMW)
  2. Data exceeds --memory (records are actually evicted)
  3. A ZADD arrives for a key that has already expired

Steps to reproduce the bug

Server

bash
docker run -d --name garnet-repro -p 127.0.0.1:6418:6379 \
  ghcr.io/microsoft/garnet:2.1.8 \
  --memory 16m --index 64m --page 4m --segment 64m --object-log-segment 64m \
  --storage-tier --logdir /data/store --checkpointdir /checkpoint \
  --compaction-type Lookup

Client

python
import json, sys, time, redis

TTL, KEYS, MEMBERS, BATCH = 4, 1500, 200, 100
r = redis.Redis(host="127.0.0.1", port=6418, socket_timeout=30)
r.flushall()

def write(salt):
    for start in range(0, KEYS, BATCH):
        pipe = r.pipeline(transaction=False)
        for k in range(start, min(start + BATCH, KEYS)):
            key = f"hot_outlink:https://ex-{k}.test/p"
            pipe.zadd(key, {json.dumps(
                {"referrer": f"https://feed-{i}.test/rss", "entry_key": f"url:{i}",
                 "target": f"https://ex-{k}.test/p", "salt": salt,
                 "entry_title": "headline padding " * 8},
                separators=(",", ":")): float(i) for i in range(MEMBERS)}, nx=True)
            pipe.expire(key, TTL)
        pipe.execute()

for rnd, salt in enumerate("abcde", 1):
    write(salt)
    print(f"round {rnd} ok (dbsize={r.dbsize()})", flush=True)
    time.sleep(TTL + 2)

Result

Round 1 succeeds. Round 2 always fails once writes land on expired, evicted records:

round 1 ok (dbsize=1449)
Traceback (most recent call last):
  ...
redis.exceptions.ConnectionError: Error 32 while writing to socket. Broken pipe.

docker logs garnet-repro shows 11 occurrences of the exception below.

Expected: ZADD on an expired key should behave as if the key does not exist (create a fresh sorted set), same as without --storage-tier.

Stack trace

crit: Session[0] [10.0.0.1:37394] [037B0B55] ProcessMessages threw an exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Tsavorite.core.TsavoriteKV`2.ReinitializeExpiredRecord[...](...)
        in .../Implementation/InternalRMW.cs:line 704
   at Tsavorite.core.TsavoriteKV`2.CreateNewRecordRMW[...](...)
        in .../Implementation/InternalRMW.cs:line 542
   at Tsavorite.core.TsavoriteKV`2.ContinuePendingRMW[...](...)
        in .../Implementation/ContinuePending.cs:line 237
   at ...InternalCompletePendingRequestFromContext[...](...)
   at ...CompletePendingForObjectStoreSession[...](...)
   at ...CompletePendingAndGetGarnetStatus[...](...)
   at ...SortedSetAdd[...](...)
   at ...ProcessArrayCommands[...](...)
   at ...ProcessMessages[...](...)
   at ...TryConsumeMessages(...)

Expected behavior

No response

Screenshots

No response

Release version

v2.1.8

IDE

No response

OS version

No response

Additional context

Suspected cause

The source record's disposal is conditional on HasMainLogSrc, but ReinitializeExpiredRecord unconditionally assumes it was already disposed.

Step 1 — ContinuePendingRMW handles the record read back from disk. It sets the address but never sets HasMainLogSrc — correct, since the source is a DiskLogRecord, not in the main log:

csharp
// ContinuePending.cs:276-278
stackCtx.recSrc.LogicalAddress = request.logicalAddress;
status = CreateNewRecordRMW(pendingState.requestKey, in pendingState.diskLogRecord, ...);

Step 2 — In CreateNewRecordRMW, the ExpireAndResume branch disposes the source only when HasMainLogSrc is set, then calls ReinitializeExpiredRecord either way:

csharp
// InternalRMW.cs:534-542
else if (rmwInfo.Action == RMWAction.ExpireAndResume)
{
    if (stackCtx.recSrc.HasMainLogSrc)                 // false on the disk path
        OnDispose(ref srcLogRecord.AsMemoryLogRecordRef(), DisposeReason.Deleted);
    doingCU = false;
    forExpiration = true;
    if (!ReinitializeExpiredRecord<...>(ref newLogRecord, ..., isIpu: false, out status))

Step 3 — ReinitializeExpiredRecord requires the source to have been disposed beforehand:

csharp
// InternalRMW.cs:711-721
// For CU, this is the newly allocated record (source was already disposed at the decision site).
if (isIpu) { ... }
else
{
    OnDispose(ref logRecord, DisposeReason.Deleted);
}

On the disk path this precondition is violated: Step 2 skipped disposal, so the record arriving at Step 3 still has uncleared heap/length fields — the subsequent access indexes out of bounds.

The IPU counterpart at InternalRMW.cs:180-184 explicitly documents and tracks this same obligation, suggesting the CU path's conditional skip is an oversight:

csharp
// ExpireAndResume: for IPU, ReinitializeExpiredRecord already called OnDispose(Deleted).
// If it failed and we fall through to CreateNewRecord, the record is already disposed.

Note: simply removing the HasMainLogSrc guard is not a valid fix — AsMemoryLogRecordRef() is invalid for a DiskLogRecord. The disk path needs its own disposal logic, or ReinitializeExpiredRecord must stop assuming prior disposal.