From 7cc1312789aca0bd25bf21f27801430245a17c5a Mon Sep 17 00:00:00 2001
From: antirez <antirez@gmail.com>
Date: Tue, 12 Jun 2018 10:22:03 +0200
Subject: [PATCH] Streams: fix backward iteration when entry is not flagged
 SAMEFIELD.

See issue #5006. The comment in the code was also wrong and
was rectified as well.
---
 src/t_stream.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/t_stream.c b/src/t_stream.c
index d7515c93..58ffda48 100644
--- a/src/t_stream.c
+++ b/src/t_stream.c
@@ -647,7 +647,12 @@ int streamIteratorGetID(streamIterator *si, streamID *id, int64_t *numfields) {
                 for (int64_t i = 0; i < to_discard; i++)
                     si->lp_ele = lpNext(si->lp,si->lp_ele);
             } else {
-                int prev_times = 4; /* flag + id ms/seq diff + numfields. */
+                int prev_times = 4; /* flag + id ms + id seq + one more to
+                                       go back to the previous entry "count"
+                                       field. */
+                /* If the entry was not flagged SAMEFIELD we also read the
+                 * number of fields, so go back one more. */
+                if (!(flags & STREAM_ITEM_FLAG_SAMEFIELDS)) prev_times++;
                 while(prev_times--) si->lp_ele = lpPrev(si->lp,si->lp_ele);
             }
         }