Simplify rule group's EvalTimestamp formula

I found it hard to understand how EvalTimestamp works, so I wanted to simplify the math there. This PR should be a noop.

Current formula is:

```
offset        = g.hash % g.interval
adjNow        = startTime - offset
base          = adjNow - (adjNow % g.interval)
EvalTimestamp = base + offset
```

I simplify `EvalTimestamp`

```
EvalTimestamp = base + offset
                # expand base
              = adjNow - (adjNow % g.interval) + offset
                # expand adjNow
              = startTime - offset - ((startTime - offset) % g.interval) + offset
                # cancel out offset
              = startTime - ((startTime - offset) % g.interval)
                # expand A+B (mod M) = (A (mod M) + B (mod M)) (mod M)
              = startTime - (startTime % g.interval - offset % g.interval) % g.interval
                # expand offset
              = startTime - (startTime % g.interval - ((g.hash % g.interval) % g.interval)) % g.interval
                # remove redundant mod g.interval
              = startTime - (startTime % g.interval - g.hash % g.interval) % g.interval
                # simplify (A (mod M) + B (mod M)) (mod M) = A+B (mod M)
              = startTime - (startTime - g.hash) % g.interval

offset            = (startTime - g.hash) % g.interval
EvalTimestamp     = startTime - offset
```

Signed-off-by: Dimitar Dimitrov <dimitar.dimitrov@grafana.com>
This commit is contained in:
Dimitar Dimitrov 2022-09-11 11:21:03 +02:00
parent 161a3010d1
commit 3fb881af26
No known key found for this signature in database
GPG key ID: 4541B04E6C90EBC3

View file

@ -532,13 +532,9 @@ func (g *Group) setLastEvaluation(ts time.Time) {
// EvalTimestamp returns the immediately preceding consistently slotted evaluation time.
func (g *Group) EvalTimestamp(startTime int64) time.Time {
var (
offset = int64(g.hash() % uint64(g.interval))
adjNow = startTime - offset
base = adjNow - (adjNow % int64(g.interval))
)
offset := (uint64(startTime) - g.hash()) % uint64(g.interval)
return time.Unix(0, base+offset).UTC()
return time.Unix(0, startTime-int64(offset)).UTC()
}
func nameAndLabels(rule Rule) string {