File size: 10,931 Bytes
1c4c66b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | package engine_test
import (
"context"
"fmt"
"math"
"math/rand"
"testing"
"time"
"github.com/brianvoe/gofakeit/v6"
"github.com/oklog/ulid/v2"
"github.com/stretchr/testify/assert"
"github.com/openmeterio/openmeter/openmeter/credit/balance"
"github.com/openmeterio/openmeter/openmeter/credit/engine"
"github.com/openmeterio/openmeter/openmeter/credit/grant"
meterpkg "github.com/openmeterio/openmeter/openmeter/meter"
"github.com/openmeterio/openmeter/openmeter/streaming"
"github.com/openmeterio/openmeter/openmeter/streaming/testutils"
"github.com/openmeterio/openmeter/pkg/models"
"github.com/openmeterio/openmeter/pkg/timeutil"
)
func Test_Fuzzing(t *testing.T) {
t1, err := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z")
assert.NoError(t, err)
meterSlug := "meter-1"
meter := meterpkg.Meter{
ManagedResource: models.ManagedResource{
ID: ulid.Make().String(),
NamespacedModel: models.NamespacedModel{
Namespace: "default",
},
ManagedModel: models.ManagedModel{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
Name: "Meter 1",
},
Key: meterSlug,
EventType: "requests",
Aggregation: meterpkg.MeterAggregationSum,
}
grant1 := makeGrant(grant.Grant{
ID: "grant-1",
Amount: 100.0,
Priority: 1,
EffectiveAt: t1,
Expiration: &grant.ExpirationPeriod{
Duration: grant.ExpirationPeriodDurationDay,
Count: 30,
},
})
grant2 := makeGrant(grant.Grant{
ID: "grant-2",
Amount: 100.0,
Priority: 1,
EffectiveAt: t1,
Expiration: &grant.ExpirationPeriod{
Duration: grant.ExpirationPeriodDurationDay,
Count: 30,
},
})
// tests with multiple engines and fuzzing
tt2 := []struct {
name string
repeat int
run func(t *testing.T, queryFn func(ctx context.Context, from time.Time, to time.Time) (float64, error), use addUsageFunc)
}{
{
name: "Calculating same period in 2 runs yields same result as calculations in one run",
repeat: 1,
run: func(t *testing.T, queryFn func(ctx context.Context, from time.Time, to time.Time) (float64, error), use addUsageFunc) {
// burn down with usage after grant effectiveAt
start := t1
use(2000, start.Add(time.Hour))
intermediate := start.Add(time.Hour * 3)
end := start.Add(time.Hour * 6)
g1 := grant1
g1.EffectiveAt = start
g1.Priority = 5
g1 = makeGrant(g1)
g2 := grant2
g2.EffectiveAt = intermediate.Add(time.Minute * 1)
g2.Priority = 2
g2 = makeGrant(g2)
startingBalance := balance.Map{
g1.ID: 100.0,
g2.ID: 82.0,
}
engine1 := engine.NewEngine(engine.EngineConfig{
QueryUsage: queryFn,
}) // runs for first part
engine2 := engine.NewEngine(engine.EngineConfig{
QueryUsage: queryFn,
}) // runs for second part
engine3 := engine.NewEngine(engine.EngineConfig{
QueryUsage: queryFn,
}) // runs for both parts
res, err := engine1.Run(
context.Background(),
engine.RunParams{
Grants: []grant.Grant{g1, g2},
StartingSnapshot: balance.Snapshot{
Balances: startingBalance,
Overage: 0,
At: start,
},
Meter: meter,
Until: intermediate,
})
assert.NoError(t, err)
res2, err := engine2.Run(
context.Background(),
engine.RunParams{
Grants: []grant.Grant{g1, g2},
StartingSnapshot: res.Snapshot,
Until: end,
})
assert.NoError(t, err)
res3, err := engine3.Run(
context.Background(),
engine.RunParams{
Grants: []grant.Grant{g1, g2},
StartingSnapshot: res.Snapshot,
Until: end,
Meter: meter,
})
assert.NoError(t, err)
// assert equivalence
assert.Equal(t, res2.Snapshot.Balances, res3.Snapshot.Balances)
},
},
{
name: "Deterministic",
repeat: 10,
run: func(t *testing.T, queryFn func(ctx context.Context, from time.Time, to time.Time) (float64, error), use addUsageFunc) {
granularity := time.Minute
// run for 1 month
start := t1.Truncate(granularity)
end := start.AddDate(0, 1, 0).Truncate(granularity)
// params
numOfRuns := rand.Intn(19) + 1
numOfGrants := rand.Intn(19) + 1
numOfUsageEvents := rand.Intn(9999) + 1
// create random grants
grants := make([]grant.Grant, numOfGrants)
for i := 0; i < numOfGrants; i++ {
grant := grant.Grant{
ID: fmt.Sprintf("grant-%d", i),
Amount: float64(gofakeit.IntRange(10000, 1000000)), // input value limited to ints
Priority: gofakeit.Uint8(),
EffectiveAt: gofakeit.DateRange(start, end).Truncate(granularity),
Expiration: &grant.ExpirationPeriod{
Duration: grant.ExpirationPeriodDurationDay,
Count: gofakeit.Uint32(),
},
}
if gofakeit.Bool() {
grant.Recurrence = &timeutil.Recurrence{
Interval: timeutil.RecurrencePeriodDaily,
Anchor: gofakeit.DateRange(start, end).Truncate(granularity),
}
}
grants[i] = makeGrant(grant)
}
// ingest usage events
for i := 0; i < numOfUsageEvents; i++ {
use(float64(gofakeit.IntRange(1, 100)), gofakeit.DateRange(start, end).Truncate(granularity))
}
// configure starting balances
startingBalances := make(balance.Map)
for _, grant := range grants {
startingBalances[grant.ID] = float64(gofakeit.IntRange(1, int(grant.Amount)))
}
// run calculation multiple times
balances := startingBalances.Clone()
results := make([]balance.Map, numOfRuns)
for i := 0; i < numOfRuns; i++ {
eng := engine.NewEngine(engine.EngineConfig{
QueryUsage: queryFn,
})
gCp := make([]grant.Grant, len(grants))
copy(gCp, grants)
result, err := eng.Run(
context.Background(),
engine.RunParams{
Grants: gCp,
StartingSnapshot: balance.Snapshot{
Balances: balances,
Overage: 0,
At: start,
},
Meter: meter,
Until: end,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
results[i] = result.Snapshot.Balances.Clone()
}
sumVals := func(m balance.Map) float64 {
sum := 0.0
for _, v := range m {
sum += v
}
return sum
}
for _, result := range results {
assert.Equal(t, sumVals(results[0]), sumVals(result))
assert.Equal(t, results[0], result)
}
},
},
{
name: "Fuzzing sequences",
repeat: 10,
run: func(t *testing.T, queryFn func(ctx context.Context, from time.Time, to time.Time) (float64, error), use addUsageFunc) {
granularity := time.Minute
// run for 1 month
start := t1.Truncate(granularity)
end := start.AddDate(0, 1, 0).Truncate(granularity)
// fuzz params
numOfEngines := rand.Intn(19) + 1
numOfGrants := rand.Intn(19) + 1
numOfUsageEvents := rand.Intn(99) + 1
// create random grants
grants := make([]grant.Grant, numOfGrants)
for i := 0; i < numOfGrants; i++ {
grant := grant.Grant{
ID: fmt.Sprintf("grant-%d", i),
Amount: float64(gofakeit.IntRange(10000, 1000000)), // input value limited to ints
Priority: gofakeit.Uint8(),
EffectiveAt: gofakeit.DateRange(start, end).Truncate(granularity),
Expiration: &grant.ExpirationPeriod{
Duration: grant.ExpirationPeriodDurationDay,
Count: gofakeit.Uint32(),
},
}
if gofakeit.Bool() {
grant.Recurrence = &timeutil.Recurrence{
Interval: timeutil.RecurrencePeriodDaily,
Anchor: gofakeit.DateRange(start, end).Truncate(granularity),
}
}
grants[i] = makeGrant(grant)
}
// ingest usage events
for i := 0; i < numOfUsageEvents; i++ {
use(float64(gofakeit.IntRange(100, 1000)), gofakeit.DateRange(start.Add(time.Hour), end.Add(-time.Hour)).Truncate(granularity))
}
// configure starting balances
startingBalances := make(balance.Map)
for _, grant := range grants {
startingBalances[grant.ID] = float64(gofakeit.IntRange(1, int(grant.Amount)))
}
// run calculation on single engine
singleEngine := engine.NewEngine(engine.EngineConfig{
QueryUsage: queryFn,
})
gCp := make([]grant.Grant, len(grants))
copy(gCp, grants)
singleEngineResult, err := singleEngine.Run(
context.Background(),
engine.RunParams{
Grants: gCp,
StartingSnapshot: balance.Snapshot{
Balances: startingBalances,
Overage: 0,
At: start,
},
Meter: meter,
Until: end,
})
if err != nil {
// lets save ourselves the calculation if this already fails
t.Fatalf("unexpected error: %v", err)
}
// run calculation on multiple engines
balances := startingBalances.Clone()
pStart := start.Truncate(granularity)
runLength := end.Sub(start) / time.Duration(numOfEngines)
overage := 0.0
// periods := make([]timeutil.Period, 0, numOfEngines)
for i := 0; i < numOfEngines; i++ {
// get period end by even distribution
pEnd := pStart.Add(runLength).Truncate(granularity)
if i == numOfEngines-1 {
pEnd = end
}
eng := engine.NewEngine(engine.EngineConfig{
QueryUsage: queryFn,
})
gCp := make([]grant.Grant, len(grants))
copy(gCp, grants)
res, err := eng.Run(
context.Background(),
engine.RunParams{
Grants: gCp,
StartingSnapshot: balance.Snapshot{
Balances: balances,
Overage: overage,
At: pStart,
},
Until: pEnd,
Meter: meter,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
balances = res.Snapshot.Balances
overage = res.Snapshot.Overage
pStart = pEnd
}
assert.Equal(t, singleEngineResult.Snapshot.Balances, balances)
},
},
}
for _, tc := range tt2 {
for i := 0; i < int(math.Min(float64(tc.repeat), 1.0)); i++ {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
streamingConnector := testutils.NewMockStreamingConnector(t)
queryFeatureUsage := func(ctx context.Context, from, to time.Time) (float64, error) {
rows, err := streamingConnector.QueryMeter(ctx, "default", meter, streaming.QueryParams{
From: &from,
To: &to,
})
if err != nil {
return 0.0, err
}
if len(rows) > 1 {
return 0.0, fmt.Errorf("expected 1 row, got %d", len(rows))
}
if len(rows) == 0 {
return 0.0, nil
}
return rows[0].Value, nil
}
tc.run(t, queryFeatureUsage, func(usage float64, at time.Time) {
streamingConnector.AddSimpleEvent(meterSlug, usage, at)
})
})
}
}
}
func makeGrant(grant grant.Grant) grant.Grant {
grant.ExpiresAt = grant.GetExpiration()
return grant
}
type addUsageFunc func(usage float64, at time.Time)
|