Skip to content

Commit

Permalink
fix: Fix panic on requesting out-of-order Pattern samples (#13010)
Browse files Browse the repository at this point in the history
  • Loading branch information
benclive authored May 28, 2024
1 parent f6529c2 commit 2171f64
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pkg/pattern/drain/chunk.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ func (c Chunk) ForRange(start, end, step model.Time) []logproto.PatternSample {
return c.Samples[i].Timestamp >= end
})
}

if c.Samples[lo].Timestamp > c.Samples[hi-1].Timestamp {
return nil
}

if step == TimeResolution {
return c.Samples[lo:hi]
}
Expand Down Expand Up @@ -110,6 +115,9 @@ func (c *Chunks) Add(ts model.Time) {
*c = append(*c, newChunk(t))
return
}
if ts.Before(last.Samples[len(last.Samples)-1].Timestamp) {
return
}
last.Samples = append(last.Samples, logproto.PatternSample{
Timestamp: t,
Value: 1,
Expand Down
26 changes: 26 additions & 0 deletions pkg/pattern/drain/chunk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ func TestAdd(t *testing.T) {
cks.Add(model.TimeFromUnixNano(time.Hour.Nanoseconds()) + TimeResolution + 1)
require.Equal(t, 2, len(cks))
require.Equal(t, 1, len(cks[1].Samples))
cks.Add(model.TimeFromUnixNano(time.Hour.Nanoseconds()) - TimeResolution)
require.Equal(t, 2, len(cks))
require.Equalf(t, 1, len(cks[1].Samples), "Older samples should not be added if they arrive out of order")
}

func TestIterator(t *testing.T) {
Expand Down Expand Up @@ -52,6 +55,7 @@ func TestForRange(t *testing.T) {
c *Chunk
start model.Time
end model.Time
step model.Time
expected []logproto.PatternSample
}{
{
Expand Down Expand Up @@ -180,6 +184,28 @@ func TestForRange(t *testing.T) {
{Timestamp: 4, Value: 10},
},
},
{
name: "Out-of-order samples generate nil result",
c: &Chunk{Samples: []logproto.PatternSample{
{Timestamp: 5, Value: 2},
{Timestamp: 3, Value: 2},
}},
start: 4,
end: 6,
expected: nil,
},
{
name: "Internally out-of-order samples generate nil result",
c: &Chunk{Samples: []logproto.PatternSample{
{Timestamp: 1, Value: 2},
{Timestamp: 5, Value: 2},
{Timestamp: 3, Value: 2},
{Timestamp: 7, Value: 2},
}},
start: 2,
end: 6,
expected: nil,
},
}

for _, tc := range testCases {
Expand Down

0 comments on commit 2171f64

Please sign in to comment.