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: reject out-of-range incident values inside groups, unknown data_format, and consumers on unregistered topics
aleksandarskrbicf025131ea1f8
diff --git a/internal/codec/codec.go b/internal/codec/codec.goindex 32d5dbf..27b30fa 100644--- a/internal/codec/codec.go+++ b/internal/codec/codec.go@@ -39,8 +39,12 @@ const (//// Two fallbacks are deliberate: an "avro" or "protobuf" topic with no fields// falls back to JSON rather than failing, since scenario validation already-// rejects that combination for inline schemas; and an unrecognised-// data_format also falls back to JSON.+// rejects that combination for inline schemas. An unrecognised data_format is+// NOT one of them -- it is an error here, even though scenario validation+// rejects it first (validate.go checks against validDataFormats). Falling back+// would mean a caller that skipped validation got JSON records against an Avro+// consumer with nothing said; the duplicate check costs a branch and makes the+// guarantee this function's own rather than borrowed from its caller.//// A schema fetched via schema_provider: registry (Avro or protobuf) is used// verbatim -- its text drives encoding, its id goes into the header -- and is@@ -76,8 +80,13 @@ func New(ctx context.Context, t scenario.Topic, reg *Registry) (Codec, error) {return jsonCodec{}, nil}return newProtoCodec(ctx, t, fields, fetched, reg)- default:+ case formatJSON, "":+ // Empty means a Topic that never went through the decoder, which defaults+ // data_format to json.return jsonCodec{}, nil+ default:+ return nil, fmt.Errorf("codec: topic %q has unsupported data_format %q (valid: %s, %s, %s)",+ t.Name, format, formatAvro, formatJSON, formatProtobuf)}}diff --git a/internal/codec/codec_test.go b/internal/codec/codec_test.goindex 4f7df4f..710654b 100644--- a/internal/codec/codec_test.go+++ b/internal/codec/codec_test.go@@ -4,6 +4,7 @@ import ("context""fmt""reflect"+ "strings""sync""testing"@@ -55,8 +56,8 @@ func TestNewSelectsCodec(t *testing.T) {want: jsonCodec{},},{- name: "an unknown format falls back to json",- topic: topicWith("orders", "yaml", fields),+ name: "no format at all is json",+ topic: topicWith("orders", "", fields),want: jsonCodec{},},}@@ -216,3 +217,29 @@ func TestJSONCodecRoundTrip(t *testing.T) {t.Errorf("round trip:\n got %#v\nwant %#v", out, in)}}++// TestNewRejectsUnknownDataFormat replaces the "an unknown format falls back to json"+// case in TestNew, which pinned the opposite.+//+// New used to return jsonCodec for any format string it did not recognise. That was safe+// only because scenario validation rejects an unknown data_format first -- a guarantee+// borrowed from a caller in another package, and invisible here. Any caller that skips+// validation got JSON records against an Avro consumer with nothing said.+func TestNewRejectsUnknownDataFormat(t *testing.T) {+ fields := []scenario.Field{fld("id", scenario.FieldString)}++ for _, format := range []string{"avroo", "yaml", "AVRO", "json "} {+ t.Run(format, func(t *testing.T) {+ c, err := New(context.Background(), topicWith("orders", format, fields), nil)+ if err == nil {+ t.Fatalf("New(%q) = %T, want an error", format, c)+ }+ if !strings.Contains(err.Error(), format) {+ t.Errorf("error %q does not name the offending format", err)+ }+ if !strings.Contains(err.Error(), "orders") {+ t.Errorf("error %q does not name the topic", err)+ }+ })+ }+}diff --git a/internal/engine/engine.go b/internal/engine/engine.goindex a30c939..9eb0dfc 100644--- a/internal/engine/engine.go+++ b/internal/engine/engine.go@@ -442,18 +442,25 @@ func (e *Engine) buildTopic(ctx context.Context, scenarioName string, t scenario// It is called both from build (single-threaded) and from the scheduler mid-run, which is// why it must not touch any engine map that Snapshot reads without a lock.func (e *Engine) addConsumer(groupID, topic string, topics []string, delayMS int, conf scenario.ConsumerConf) (*Consumer, error) {- client, err := kafka.NewConsumer(e.cfg.Kafka, groupID, topics, conf)- if err != nil {- return nil, fmt.Errorf("consumer client: %w", err)- }-+ // Checked BEFORE any client is created, so the failure costs no connection and+ // nothing needs closing on the way out.+ //// topicStats is written only during build and read by Snapshot for the whole run, so- // a mid-run rebalance must not insert into it. A topic absent from the map is also- // absent from topicOrder, so a fresh entry would never be rendered anyway -- the- // consumer gets unpublished counters instead of a map write racing every Snapshot.+ // a mid-run rebalance must not insert into it -- an unregistered topic is not+ // something this can fix. It must not paper over it either: substituting fresh+ // counters used to yield a consumer that consumed real records whose counts reached+ // nothing, not the topic row and not the totals. No live path produces one (every+ // group id in consumerSpecs was registered during build against a topic that is in+ // the map), so this is the invariant failing loudly rather than a condition to+ // recover from. The scheduler reports it as an alert event and the run continues.stats := e.topicStats[topic]if stats == nil {- stats = &counters{}+ return nil, fmt.Errorf("no counters registered for topic %q (group %q): a consumer's topic must be registered during build", topic, groupID)+ }++ client, err := kafka.NewConsumer(e.cfg.Kafka, groupID, topics, conf)+ if err != nil {+ return nil, fmt.Errorf("consumer client: %w", err)}var dlq *dlqProducerdiff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.goindex 073d9d6..a7a331e 100644--- a/internal/engine/engine_test.go+++ b/internal/engine/engine_test.go@@ -501,3 +501,52 @@ func TestEngineReportsUnhealthyOnGeneratorFailure(t *testing.T) {t.Error("Snapshot reported Healthy after a generator failure aborted the run")}}++// TestAddConsumerRejectsUnregisteredTopic pins that an unknown topic fails loudly.+//+// addConsumer used to substitute a fresh, unpublished *counters when topicStats had no+// entry for the topic. The consumer then consumed real records whose counts reached+// nothing -- not the topic row, not the totals, not Prometheus -- which is exactly the+// wrong-number bug the rest of this package works to avoid. No live path reaches it, so+// this asserts the invariant, not a recovery.+func TestAddConsumerRejectsUnregisteredTopic(t *testing.T) {+ addrs := newFakeCluster(t)++ sc := &scenario.Scenario{Name: "reg", Topics: []scenario.Topic{jsonTopic("registered-topic")}}+ eng, err := New(context.Background(), Config{+ Kafka: kafka.Config{BootstrapServers: addrs},+ Scenarios: []*scenario.Scenario{sc},+ Duration: time.Second,+ Seed: 21,+ })+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ // This test never calls Run, so nothing else would close the clients New and+ // addConsumer open. goleak fails the package without this.+ t.Cleanup(eng.teardown)++ c, err := eng.addConsumer("ghost-group", "never-registered", []string{"never-registered"}, 0, scenario.ConsumerConf{})+ if err == nil {+ // A returned consumer would also be an untracked client, so fail hard.+ t.Fatalf("addConsumer for an unregistered topic returned %v, want an error", c)+ }+ if c != nil {+ t.Errorf("addConsumer returned both a consumer and an error")+ }+ for _, want := range []string{"never-registered", "ghost-group"} {+ if !strings.Contains(err.Error(), want) {+ t.Errorf("error %q does not name %q", err, want)+ }+ }++ // A registered topic still works, so the check is on registration and not on+ // something incidental to the call.+ good, err := eng.addConsumer("extra-group", "registered-topic", []string{"registered-topic"}, 0, scenario.ConsumerConf{})+ if err != nil {+ t.Fatalf("addConsumer for a registered topic: %v", err)+ }+ if good == nil {+ t.Fatal("addConsumer returned no consumer and no error")+ }+}diff --git a/internal/scenario/message_parity_test.go b/internal/scenario/message_parity_test.goindex df0e771..d7dd2e5 100644--- a/internal/scenario/message_parity_test.go+++ b/internal/scenario/message_parity_test.go@@ -273,14 +273,18 @@ func TestValidateMessageTextContract(t *testing.T) {clean: true,},{- // Group members pass a relaxed check, so the key must be PRESENT but its- // value is never range-checked -- delay_ms: -5 is accepted inside a group and- // rejected outside one. An oversight, pinned here on purpose.- name: "group member value checks are relaxed",+ // This case previously asserted clean: true, pinning the oversight where a+ // group member's value was never range-checked -- delay_ms: -5 accepted+ // inside a group, rejected outside one. A group member now produces the same+ // message at the same severity as its standalone twin, which is the parity+ // this file exists to check.+ name: "group member values are checked like standalone ones",doc: "name: s\ntopics:\n - name: t\nincidents:\n - group:\n repeat: 1\n interval_seconds: 30\n" +" incidents:\n - type: increase_consumer_delay\n at_seconds: 5\n" +" delay_ms: -5\n",- clean: true,+ errs: []string{+ "incidents[0].group.incidents[0].delay_ms: Field 'delay_ms' must be a non-negative integer",+ },},})}diff --git a/internal/scenario/validate.go b/internal/scenario/validate.goindex d596000..e35f445 100644--- a/internal/scenario/validate.go+++ b/internal/scenario/validate.go@@ -901,7 +901,7 @@ func (v *validator) incident(n *yaml.Node, path string) {if target := mapGet(n, "target"); target != nil {v.target(target, join(path, "target"))}- v.incidentTypeFields(n, incidentType, path, true)+ v.incidentTypeFields(n, incidentType, path)}// incidentType reads and checks the `type` key shared by both incident paths.@@ -920,15 +920,16 @@ func (v *validator) incidentType(n *yaml.Node, path string) (string, bool) {return incidentType, true}-// incidentTypeFields checks the parameters each incident type requires.+// incidentTypeFields checks the parameters each incident type requires: that the key is+// present, and that its value is in range. Both checks apply wherever an incident+// appears, standalone or inside a group.//-// strict controls whether a present value is also range-checked: a standalone incident-// is strict, a group member is not. Inside a group the key must still be PRESENT, but-// its value is not range-checked, so a group member may carry `delay_ms: -5` while the-// identical standalone incident is rejected. That asymmetry is almost certainly an-// oversight, but it is observable behaviour and is preserved rather than silently-// tightened.-func (v *validator) incidentTypeFields(n *yaml.Node, incidentType, path string, strict bool) {+// The two used to be split by a `strict` parameter that standalone incidents passed true+// and group members passed false, so a group member could carry `delay_ms: -5` while the+// identical standalone incident was rejected. That was not merely untidy: `rate: -5`+// inside a group reached Producer.SetRate, which reads any value <= 0 as rate.Inf, so an+// out-of-range value in a group silently unlimited the producer it targeted.+func (v *validator) incidentTypeFields(n *yaml.Node, incidentType, path string) {switch incidentType {case IncidentStopBroker, IncidentStartBroker:broker := mapGet(n, "broker")@@ -944,7 +945,7 @@ func (v *validator) incidentTypeFields(n *yaml.Node, incidentType, path string,if delay == nil {v.errf(n, join(path, "delay_ms"),"Incident type 'increase_consumer_delay' requires 'delay_ms' field")- } else if strict {+ } else {if ms, ok := intValue(delay); !ok || ms < 0 {v.errf(delay, join(path, "delay_ms"),"Field 'delay_ms' must be a non-negative integer")@@ -956,7 +957,7 @@ func (v *validator) incidentTypeFields(n *yaml.Node, incidentType, path string,if rate == nil {v.errf(n, join(path, "rate"),"Incident type 'change_producer_rate' requires 'rate' field")- } else if strict {+ } else {if r, ok := floatValue(rate); !ok || r < 0 {v.errf(rate, join(path, "rate"), "Field 'rate' must be a non-negative number")}@@ -967,7 +968,7 @@ func (v *validator) incidentTypeFields(n *yaml.Node, incidentType, path string,if duration == nil {v.errf(n, join(path, "duration_seconds"),"Incident type 'pause_consumer' requires 'duration_seconds' field")- } else if strict {+ } else {if seconds, ok := intValue(duration); !ok || seconds < 1 {v.errf(duration, join(path, "duration_seconds"),"Field 'duration_seconds' must be a positive integer")@@ -1094,9 +1095,9 @@ func (v *validator) incidentGroup(n *yaml.Node, path string) {}// groupIncident validates one member of a `group:` block's `incidents:` list. Differs-// from a standalone incident in three ways: no schedule is required (a missing-// at_seconds is a warning), every_seconds is not checked at all, and value checks are-// relaxed (strict=false).+// from a standalone incident in two ways: no schedule is required (a missing at_seconds+// is a warning), and every_seconds is not checked at all. Type-specific field values are+// checked exactly as they are outside a group.func (v *validator) groupIncident(n *yaml.Node, path string) {if !isMapping(n) {v.errf(n, path, "Incident must be an object/dict")@@ -1119,5 +1120,5 @@ func (v *validator) groupIncident(n *yaml.Node, path string) {if target := mapGet(n, "target"); target != nil {v.target(target, join(path, "target"))}- v.incidentTypeFields(n, incidentType, path, false)+ v.incidentTypeFields(n, incidentType, path)}diff --git a/internal/scenario/validate_test.go b/internal/scenario/validate_test.goindex a9c1507..dd96735 100644--- a/internal/scenario/validate_test.go+++ b/internal/scenario/validate_test.go@@ -679,10 +679,13 @@ incidents:clean: true,},{- // QUIRK: group members use a relaxed check, so value checks on delay_ms,- // rate and duration_seconds are skipped INSIDE a group while the identical- // standalone incident below is rejected. Presence is still required.- name: "group members skip value checks",+ // This case previously asserted clean: true, pinning a quirk where value+ // checks on delay_ms, rate and duration_seconds were skipped INSIDE a group+ // while the identical standalone incident was rejected. It was an oversight,+ // not a feature -- `rate: -5` reaches Producer.SetRate, which reads any value+ // <= 0 as rate.Inf, so the relaxed branch was a way to unlimit a producer by+ // accident. Group members are now checked exactly like standalone incidents.+ name: "group members are value-checked like standalone incidents",doc: `name: stopics:@@ -702,7 +705,11 @@ incidents:at_seconds: 2duration_seconds: 0`,- clean: true,+ errs: []string{+ "incidents[0].group.incidents[0].delay_ms: Field 'delay_ms' must be a non-negative integer",+ "incidents[0].group.incidents[1].rate: Field 'rate' must be a non-negative number",+ "incidents[0].group.incidents[2].duration_seconds: Field 'duration_seconds' must be a positive integer",+ },},{name: "group members still require the key itself",