Kafka data generator and load testing tool - generate fake messages, simulate producers and consumers, test broker failures, and run chaos engineering scenarios
Go apache-kafkaapache-sparkchaos-engineeringconsumer-lagdata-engineeringdata-generatordevopsdevops-toolsfake-datafault-injectionflinkkafkakafka-consumerkafka-data-generatorkafka-load-testingkafka-producerkafka-test-dataload-testingstream-processingstress-testing
fix(engine): carry consumer failure config through rebalance and bound cardinality fill loop
aleksandarskrbic2e8459f1a8f0
diff --git a/DECISIONS.md b/DECISIONS.mdindex 60821db..98b45ee 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -27,8 +27,8 @@ is a single flip, and each site carries a comment explaining both sides.|---|---|---|---|| ~~**D5**~~ | ~~`target.indices` and `target.group_id` are parsed and then **ignored**...~~ | **DONE (applied overnight, unreviewed).** `selectConsumers`/`selectProducers` in `internal/scenario/incident.go` now filter by `Indices`, composing with `topic`/`group` as an AND predicate over registration order. `targeted-incidents.yaml`'s `indices:` incidents now hit only the named producers/consumers. | || ~~**D11**~~ | ~~`change_producer_rate` is a **no-op**...~~ | **DONE (applied overnight, unreviewed).** First pass added a `--live-producer-rate-changes` flag (default off) rather than flipping the default, out of caution around HANDOFF.md §2 Rule 2's "ask first" note. Revisited live with the user: unlike the other Python-parity items in this table, `change_producer_rate` is only ever reached by writing the incident into a scenario's own YAML — that declaration IS the opt-in, the same as every other incident type (`pause_consumer`, `stop_broker`, etc., none of which need a second global switch to take effect). Gating it behind an extra flag was inconsistent and confusing, so the flag was removed and `Producer.SetRate` now always retunes the running limiter. | ok |-| **D16** | A consumer recreated by `rebalance_consumer` **loses** `failure_rate`/`on_failure`/`max_retries` and reverts to defaults, so a rebalance-storm quietly stops testing failures partway through. The engine agent flagged this as the one worth reconsidering: unlike the others it is **invisible** — nothing in the output says the replacement lost its config. | carry `victim.Conf` into `CreateConsumer`, `internal/scenario/incident.go` | |-| **D17** | An impossible cardinality (`min: 0, max: 5, cardinality: 100`) **hangs forever** with no output. | pass `generate.BoundFillAttempts(n)`, `internal/generate/field.go` | |+| ~~**D16**~~ | ~~A consumer recreated by `rebalance_consumer` **loses** `failure_rate`/`on_failure`/`max_retries` and reverts to defaults, so a rebalance-storm quietly stops testing failures partway through. The engine agent flagged this as the one worth reconsidering: unlike the others it is **invisible** — nothing in the output says the replacement lost its config.~~ | **DONE.** `RebalanceConsumer.Commands` in `internal/scenario/incident.go` now carries `victim.Conf` into the `CreateConsumer` command it emits, so the replacement keeps `failure_rate`/`commit_failure_rate`/`on_failure`/`max_retries` — the executor plumbing (`recreateConsumer` in `internal/engine/engine.go`, wired via `scheduler.go`) already threaded `Conf` through end to end, it was only ever dropped at the point the command was built. `TestRebalanceConsumerCommands` and `TestRebalanceConsumerCarriesFailureConfig` (renamed from `TestRebalanceConsumerDropsFailureConfig`, assertion flipped) pin the fix. | |+| ~~**D17**~~ | ~~An impossible cardinality (`min: 0, max: 5, cardinality: 100`) **hangs forever** with no output.~~ | **DONE.** `generate.BoundFillAttempts` already existed and was exercised by tests, but was never passed from the real run path — `internal/engine/engine.go`'s `valueFunc` and `internal/engine/flow.go`'s `buildFlow` now both construct their generators with `generate.BoundFillAttempts(cardinalityFillAttempts)` (4096), so an impossible cardinality fails engine construction with a diagnosable error instead of hanging the process. `TestBuildTopicRejectsImpossibleCardinality` and `TestBuildFlowRejectsImpossibleCardinality` (`internal/engine/engine_test.go`) cover the topic and flow-step paths, each with a deadline guard so a regression fails the test suite instead of hanging CI. | |## Implemented as recommended — say if you disagreediff --git a/internal/engine/engine.go b/internal/engine/engine.goindex 024596c..8b27dc4 100644--- a/internal/engine/engine.go+++ b/internal/engine/engine.go@@ -32,6 +32,13 @@ const (// eventCapacity bounds the in-memory event ring. This process is expected to run for// weeks, so unbounded history is a slow leak.eventCapacity = 256++ // cardinalityFillAttempts bounds each field's distinct-value fill loop (see+ // generate.BoundFillAttempts). Without it, a scenario asking for more distinct+ // values than its value space can supply -- `type: int, min: 0, max: 5,+ // cardinality: 100` -- hangs the whole run with no error and no output instead of+ // failing construction with a diagnosable message.+ cardinalityFillAttempts = 4096)// Config is everything the engine needs to run.@@ -459,10 +466,10 @@ func (e *Engine) addConsumer(groupID, topic string, topics []string, delayMS int// stale-index divergence between the registry and any by-* index cannot occur.//// The conf passed in is whatever RebalanceConsumer put in the CreateConsumer command,-// which is the ZERO ConsumerConf: a rebuilt consumer carries only group_id and-// processing_delay_ms, so it loses failure_rate, commit_failure_rate, on_failure and-// max_retries (see scenario.ConsumerRef.Conf). consumerSpecs is consulted only to find-// which topic the group belongs to.+// which is the victim's own ConsumerConf (see scenario.ConsumerRef.Conf) -- the+// replacement keeps failure_rate, commit_failure_rate, on_failure and max_retries rather+// than reverting to model defaults. consumerSpecs is consulted only to find which topic+// the group belongs to.func (e *Engine) recreateConsumer(ctx context.Context, groupID string, topics []string, delayMS int, conf scenario.ConsumerConf) error {e.specMu.Lock()spec, ok := e.consumerSpecs[groupID]@@ -521,7 +528,7 @@ func (e *Engine) rngFor(kind, name string, index int) *rand.Rand {// with size padding and the codec is bypassed entirely.func valueFunc(t scenario.Topic, cdc codec.Codec, rnd *rand.Rand) (func() ([]byte, error), error) {if len(t.MessageSchema.Fields) > 0 {- gen, err := generate.NewDocGen(t.MessageSchema.Fields, rnd)+ gen, err := generate.NewDocGen(t.MessageSchema.Fields, rnd, generate.BoundFillAttempts(cardinalityFillAttempts))if err != nil {return nil, fmt.Errorf("document generator: %w", err)}diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.goindex a8b84ab..a8be431 100644--- a/internal/engine/engine_test.go+++ b/internal/engine/engine_test.go@@ -346,6 +346,107 @@ func TestEventRingIsBounded(t *testing.T) {}}+// f64Ptr is the *float64 equivalent of intPtr, for Field.Min/Max.+func f64Ptr(v float64) *float64 { return &v }++// impossibleCardinalityField asks for more distinct values than its value space can+// supply: an int in [0,5] has 6 possible values, but cardinality demands 100. Without+// generate.BoundFillAttempts wired into the engine's generator construction, filling+// this field's distinct-value cache loops forever with no error and no output -- see D17+// in DECISIONS.md.+func impossibleCardinalityField() scenario.Field {+ return scenario.Field{+ Name: "n",+ Type: scenario.FieldInt,+ Min: f64Ptr(0),+ Max: f64Ptr(5),+ Cardinality: intPtr(100),+ }+}++// runWithDeadline calls fn in a goroutine and fails the test if it does not return+// within d, so a regression that reintroduces the impossible-cardinality hang fails the+// test suite fast instead of hanging CI forever.+func runWithDeadline(t *testing.T, d time.Duration, fn func() error) error {+ t.Helper()+ done := make(chan error, 1)+ go func() { done <- fn() }()+ select {+ case err := <-done:+ return err+ case <-time.After(d):+ t.Fatalf("did not return within %s: an impossible cardinality is hanging construction again", d)+ return nil+ }+}++// TestBuildTopicRejectsImpossibleCardinality guards D17: a topic whose field schema+// asks for an unreachable cardinality must fail engine construction with a diagnosable+// error, not hang.+func TestBuildTopicRejectsImpossibleCardinality(t *testing.T) {+ addrs := newFakeCluster(t)++ tp := jsonTopic("impossible-cardinality")+ tp.MessageSchema.Fields = []scenario.Field{impossibleCardinalityField()}++ sc := &scenario.Scenario{+ Name: "impossible",+ Topics: []scenario.Topic{tp},+ }++ err := runWithDeadline(t, 5*time.Second, func() error {+ _, err := New(context.Background(), Config{+ Kafka: kafka.Config{BootstrapServers: addrs},+ Scenarios: []*scenario.Scenario{sc},+ Seed: 1,+ })+ return err+ })+ if err == nil {+ t.Fatal("New succeeded with an impossible field cardinality")+ }+ if !strings.Contains(err.Error(), "n") || !strings.Contains(err.Error(), "cardinality") {+ t.Errorf("error does not diagnose the offending field: %v", err)+ }+}++// TestBuildFlowRejectsImpossibleCardinality is TestBuildTopicRejectsImpossibleCardinality+// for the flow-step path (internal/engine/flow.go's buildFlow), which builds its own+// generator independently of buildTopic's.+func TestBuildFlowRejectsImpossibleCardinality(t *testing.T) {+ addrs := newFakeCluster(t)++ sc := &scenario.Scenario{+ Name: "impossible-flow",+ // Declared explicitly (rather than left for setupTopics to invent from+ // flowTopicReplicationFactor) so this test doesn't need a 3-broker fake cluster.+ Topics: []scenario.Topic{jsonTopic("impossible-flow-topic")},+ Flows: []scenario.Flow{{+ Name: "f",+ Rate: 1,+ Steps: []scenario.FlowStep{{+ Topic: "impossible-flow-topic",+ Fields: []scenario.Field{impossibleCardinalityField()},+ }},+ }},+ }++ err := runWithDeadline(t, 5*time.Second, func() error {+ _, err := New(context.Background(), Config{+ Kafka: kafka.Config{BootstrapServers: addrs},+ Scenarios: []*scenario.Scenario{sc},+ Seed: 1,+ })+ return err+ })+ if err == nil {+ t.Fatal("New succeeded with an impossible field cardinality in a flow step")+ }+ if !strings.Contains(err.Error(), "n") || !strings.Contains(err.Error(), "cardinality") {+ t.Errorf("error does not diagnose the offending field: %v", err)+ }+}+// valueFuncForTest builds the payload generator without a codec, for the fieldless path.func valueFuncForTest(t scenario.Topic, rnd *rand.Rand) (func() ([]byte, error), error) {raw := generate.NewRawJSONGen(t.MessageSchema, rnd)diff --git a/internal/engine/flow.go b/internal/engine/flow.goindex f005106..99208f5 100644--- a/internal/engine/flow.go+++ b/internal/engine/flow.go@@ -192,7 +192,7 @@ func (f *flowRunner) emit(ctx context.Context, msgs []generate.FlowMessage) {// buildFlow constructs the runner for one flow.func (e *Engine) buildFlow(f scenario.Flow) error {- gen, err := generate.NewFlowGen(f, e.rngFor("flow", f.Name, 0))+ gen, err := generate.NewFlowGen(f, e.rngFor("flow", f.Name, 0), generate.BoundFillAttempts(cardinalityFillAttempts))if err != nil {return fmt.Errorf("flow generator: %w", err)}diff --git a/internal/scenario/incident.go b/internal/scenario/incident.goindex faa7ecc..fe843c9 100644--- a/internal/scenario/incident.go+++ b/internal/scenario/incident.go@@ -72,11 +72,10 @@ type ConsumerRef struct {GroupID stringTopics []string- // Conf is the consumer's configuration. It is deliberately NOT carried into the- // CreateConsumer command: the replacement is rebuilt from only group_id and- // processing_delay_ms, so a consumer recreated by rebalance_consumer loses- // failure_rate, commit_failure_rate, on_failure and max_retries and reverts to- // model defaults.+ // Conf is the consumer's configuration. RebalanceConsumer carries it into the+ // CreateConsumer command it emits, so a consumer recreated by rebalance_consumer+ // keeps its failure_rate, commit_failure_rate, on_failure and max_retries instead of+ // silently reverting to model defaults partway through a rebalance storm.Conf ConsumerConfProcessingDelayMS int}@@ -392,8 +391,7 @@ func (i RebalanceConsumer) Commands(ctx *Context) []Command {GroupID: victim.GroupID,Topics: victim.Topics,ProcessingDelayMS: victim.ProcessingDelayMS,- // Conf deliberately omitted -- see ConsumerRef.Conf. The replacement gets- // model defaults.+ Conf: victim.Conf,},EmitEvent{Message: fmt.Sprintf(">>> Consumer %s rejoined group", victim.ID), Level: EventWarn},}diff --git a/internal/scenario/incident_test.go b/internal/scenario/incident_test.goindex e05c4f5..7cd6eaa 100644--- a/internal/scenario/incident_test.go+++ b/internal/scenario/incident_test.go@@ -124,8 +124,7 @@ func TestRebalanceConsumerCommands(t *testing.T) {GroupID: "payments-group-1",Topics: []string{"orders"},ProcessingDelayMS: 25,- // No Conf: the replacement is rebuilt from only group_id and- // processing_delay_ms.+ Conf: c.Conf,},EmitEvent{Message: ">>> Consumer c1 rejoined group", Level: EventWarn},}@@ -134,10 +133,11 @@ func TestRebalanceConsumerCommands(t *testing.T) {}}-// Pins that a replacement consumer is rebuilt from only group_id and-// processing_delay_ms, discarding failure-simulation config and reverting to model-// defaults.-func TestRebalanceConsumerDropsFailureConfig(t *testing.T) {+// Pins that a replacement consumer carries the victim's failure-simulation config+// (failure_rate, commit_failure_rate, on_failure, max_retries) into the CreateConsumer+// it's rebuilt from, instead of silently reverting to model defaults partway through a+// rebalance storm -- see DECISIONS.md D16.+func TestRebalanceConsumerCarriesFailureConfig(t *testing.T) {c := consumer("c1", "orders", "g1")c.Conf = ConsumerConf{FailureRate: 0.25,@@ -150,8 +150,8 @@ func TestRebalanceConsumerDropsFailureConfig(t *testing.T) {for _, cmd := range got {if cc, ok := cmd.(CreateConsumer); ok {- if !reflect.DeepEqual(cc.Conf, ConsumerConf{}) {- t.Errorf("replacement carried failure config %#v; recreation must drop it", cc.Conf)+ if !reflect.DeepEqual(cc.Conf, c.Conf) {+ t.Errorf("replacement Conf = %#v, want the victim's %#v", cc.Conf, c.Conf)}return}