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
refactor: publish topic state as one frozen table, pass compose argv builders, parameterize the header width budget
aleksandarskrbic8fd10619ecb1
diff --git a/internal/engine/engine.go b/internal/engine/engine.goindex 9eb0dfc..93a82ec 100644--- a/internal/engine/engine.go+++ b/internal/engine/engine.go@@ -133,11 +133,11 @@ type Engine struct {admin *kafka.Admin- // topicStats is keyed by topic name and shared by every producer and consumer on- // that topic.- topicStats map[string]*counters- topicMeta map[string]topicMeta- topicOrder []string+ // topics is the published topic table: every topic with a row, its counters and its+ // consumer groups. Written exactly once, by the last statement of build, and read+ // without a lock by Snapshot and the lag poller for the rest of the run. See+ // topics.go.+ topics *topicTableflowStats map[string]*flowCountersflowOrder []string@@ -211,8 +211,6 @@ func New(ctx context.Context, cfg Config) (*Engine, error) {log: cfg.Logger,reg: newRegistry(),events: events,- topicStats: make(map[string]*counters),- topicMeta: make(map[string]topicMeta),flowStats: make(map[string]*flowCounters),consumerSpecs: make(map[string]consumerSpec),seed: seed,@@ -327,7 +325,12 @@ func (e *Engine) schemaRegistryURL() string {return ""}-// build constructs producers, consumers and flow workers for every scenario.+// build constructs producers, consumers and flow workers for every scenario, then+// publishes the topic table.+//+// The table is assembled in a builder and handed over in one assignment at the end, so+// there is no window in which a half-built table is reachable and no field a later edit+// could append to mid-run.func (e *Engine) build(ctx context.Context) error {var reg *codec.Registryif url := e.schemaRegistryURL(); url != "" {@@ -342,30 +345,30 @@ func (e *Engine) build(ctx context.Context) error {reg = r}+ tb := newTopicTableBuilder()for _, sc := range e.cfg.Scenarios {for _, topic := range sc.Topics {- if err := e.buildTopic(ctx, sc.Name, topic, reg); err != nil {+ if err := e.buildTopic(ctx, tb, sc.Name, topic, reg); err != nil {return fmt.Errorf("topic %q: %w", topic.Name, err)}}for _, flow := range sc.Flows {- if err := e.buildFlow(sc.Name, flow); err != nil {+ if err := e.buildFlow(tb, sc.Name, flow); err != nil {return fmt.Errorf("flow %q: %w", flow.Name, err)}}}+ e.topics = tb.freeze()return nil}// buildTopic wires one declared topic into the engine: shared counters and one shared// codec, then NumProducers producers and NumConsumerGroups x ConsumersPerGroup consumers.//-// Called only from build, before any goroutine exists, which is what lets it write-// topicStats and topicOrder without a lock.-func (e *Engine) buildTopic(ctx context.Context, scenarioName string, t scenario.Topic, reg *codec.Registry) error {- stats := &counters{}- e.topicStats[t.Name] = stats- e.topicOrder = append(e.topicOrder, t.Name)+// Called only from build, before any goroutine exists, which is what lets it add to the+// topic table at all -- tb is unreachable from anything running.+func (e *Engine) buildTopic(ctx context.Context, tb *topicTableBuilder, scenarioName string, t scenario.Topic, reg *codec.Registry) error {+ stats := tb.add(t.Name, scenarioName)// One codec per topic, shared by every producer on it. Unlike the generators, a// codec.Codec is safe to share: New resolves the schema text, the parsed descriptor@@ -413,51 +416,35 @@ func (e *Engine) buildTopic(ctx context.Context, scenarioName string, t scenario}))}- meta := topicMeta{scenarioName: scenarioName}-if !e.cfg.NoConsumers {for gi := 0; gi < t.NumConsumerGroups; gi++ {groupID := fmt.Sprintf("%s-group-%d", t.Name, gi+1)- meta.groups = append(meta.groups, groupID)+ tb.addGroup(t.Name, groupID)e.specMu.Lock()e.consumerSpecs[groupID] = consumerSpec{topic: t.Name, conf: t.ConsumerConfig}e.specMu.Unlock()for ci := 0; ci < t.ConsumersPerGroup; ci++ {- if _, err := e.addConsumer(groupID, t.Name, []string{t.Name}, t.ConsumerDelayMS, t.ConsumerConfig); err != nil {+ if _, err := e.addConsumer(groupID, t.Name, []string{t.Name}, t.ConsumerDelayMS, t.ConsumerConfig, stats); err != nil {return err}}}}- e.topicMeta[t.Name] = metareturn nil}// addConsumer constructs and registers one consumer, returning it so the caller can start// its goroutine.//-// 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) {- // 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 -- 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 {- return nil, fmt.Errorf("no counters registered for topic %q (group %q): a consumer's topic must be registered during build", topic, groupID)- }-+// stats is passed in rather than looked up. It is called both from build and from the+// scheduler mid-run, and the two know the topic's counters by different means -- build+// has them in hand from the topic table builder, the scheduler reads them off the frozen+// table. Taking them as an argument is what keeps this function from touching engine+// state that Snapshot reads unlocked.+func (e *Engine) addConsumer(groupID, topic string, topics []string, delayMS int, conf scenario.ConsumerConf, stats *counters) (*Consumer, error) {client, err := kafka.NewConsumer(e.cfg.Kafka, groupID, topics, conf)if err != nil {return nil, fmt.Errorf("consumer client: %w", err)@@ -518,7 +505,19 @@ func (e *Engine) recreateConsumer(ctx context.Context, groupID string, topics []topic = topics[0]}- c, err := e.addConsumer(groupID, topic, topics, delayMS, conf)+ // Looked up BEFORE addConsumer opens a client, so the failure costs no connection and+ // leaves nothing to close. A nil answer means the topic was never registered during+ // build, which no live path produces -- every group id in consumerSpecs was recorded+ // against a topic the builder had added. Substituting fresh counters here, as this+ // once did, yielded a consumer whose records reached no row and no total; failing is+ // the honest answer, and the scheduler turns it into an alert event rather than+ // ending the run.+ stats := e.topics.counters(topic)+ if stats == nil {+ return fmt.Errorf("no counters registered for topic %q (group %q): a consumer's topic must be registered during build", topic, groupID)+ }++ c, err := e.addConsumer(groupID, topic, topics, delayMS, conf, stats)if err != nil {return err}diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.goindex a7a331e..9e27f2b 100644--- a/internal/engine/engine_test.go+++ b/internal/engine/engine_test.go@@ -502,14 +502,15 @@ func TestEngineReportsUnhealthyOnGeneratorFailure(t *testing.T) {}}-// TestAddConsumerRejectsUnregisteredTopic pins that an unknown topic fails loudly.+// TestRecreateConsumerRejectsUnregisteredTopic 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) {+// The engine used to substitute a fresh, unpublished *counters when no entry existed 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. The check lives on recreateConsumer, the only+// path that looks a topic up rather than being handed its counters. No live path reaches+// it, so this asserts the invariant, not a recovery.+func TestRecreateConsumerRejectsUnregisteredTopic(t *testing.T) {addrs := newFakeCluster(t)sc := &scenario.Scenario{Name: "reg", Topics: []scenario.Topic{jsonTopic("registered-topic")}}@@ -526,27 +527,27 @@ func TestAddConsumerRejectsUnregisteredTopic(t *testing.T) {// 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{})+ err = eng.recreateConsumer(context.Background(), "ghost-group", []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")+ t.Fatal("recreateConsumer for an unregistered topic returned nil, want 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)}}+ // No consumer may have been registered on the way out, or drain would close a client+ // for a row that does not exist.+ if n := len(eng.reg.allConsumers()); n != 1 {+ t.Errorf("consumers registered = %d, want the 1 built for registered-topic", n)+ }- // A registered topic still works, so the check is on registration and not on+ // A registered group 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 err := eng.recreateConsumer(context.Background(), "registered-topic-group-1", []string{"registered-topic"}, 0, scenario.ConsumerConf{}); err != nil {+ t.Fatalf("recreateConsumer for a registered topic: %v", err)}- if good == nil {- t.Fatal("addConsumer returned no consumer and no error")+ if n := len(eng.reg.allConsumers()); n != 2 {+ t.Errorf("consumers registered = %d, want the replacement to have joined", n)}}diff --git a/internal/engine/flow.go b/internal/engine/flow.goindex 71426a1..b193563 100644--- a/internal/engine/flow.go+++ b/internal/engine/flow.go@@ -214,7 +214,7 @@ func (f *flowRunner) emit(ctx context.Context, msgs []generate.FlowMessage) {//// Flows get a client of their own rather than borrowing a topic's, because a flow's steps// span several topics and none of those topics need have a `topics:` entry at all.-func (e *Engine) buildFlow(scenarioName string, f scenario.Flow) error {+func (e *Engine) buildFlow(tb *topicTableBuilder, scenarioName string, f scenario.Flow) error {gen, err := generate.NewFlowGen(f, e.rngFor("flow", f.Name, 0), generate.BoundFillAttempts(cardinalityFillAttempts))if err != nil {return fmt.Errorf("flow generator: %w", err)@@ -226,7 +226,7 @@ func (e *Engine) buildFlow(scenarioName string, f scenario.Flow) error {}e.trackClient(client)- topicC, err := e.buildStepConsumers(scenarioName, f)+ topicC, err := e.buildStepConsumers(tb, scenarioName, f)if err != nil {return err}@@ -245,16 +245,16 @@ func (e *Engine) buildFlow(scenarioName string, f scenario.Flow) error {// that step's topic, each simulating DelayMS of processing per message -- which is how a// scenario builds deliberate lag on a flow topic.//-// A step topic is not necessarily a declared topic, so it may have no counters and no-// place in topicOrder. Those are created here, which is safe for exactly the reason-// buildTopic's writes are: build runs before any goroutine exists. Only topics that-// declare consumers get an entry -- a step topic nobody consumes has nothing to measure-// and stays out of the topic table, as it was before this existed.+// A step topic is not necessarily a declared topic, so it may have no row yet. One is+// added here, which is safe for exactly the reason buildTopic's additions are: build runs+// before any goroutine exists and the builder is unreachable from anything running. Only+// topics that declare consumers get a row -- a step topic nobody consumes has nothing to+// measure and stays out of the topic table.//// Two steps of one flow on the same topic share one set of consumers rather than// subscribing twice: the second block is a restatement of the first, not a request for// more consumers.-func (e *Engine) buildStepConsumers(scenarioName string, f scenario.Flow) (map[string]*counters, error) {+func (e *Engine) buildStepConsumers(tb *topicTableBuilder, scenarioName string, f scenario.Flow) (map[string]*counters, error) {if e.cfg.NoConsumers {return nil, nil}@@ -266,45 +266,32 @@ func (e *Engine) buildStepConsumers(scenarioName string, f scenario.Flow) (map[scontinue}- stats := e.topicStats[step.Topic]- if stats == nil {- // An undeclared step topic. EnsureTopics already created it (see- // Engine.createTopics, which walks Flow.Topics), so only the bookkeeping- // that makes it renderable is missing.- stats = &counters{}- e.topicStats[step.Topic] = stats- e.topicOrder = append(e.topicOrder, step.Topic)- }+ // add is idempotent, so a step naming an already-declared topic shares that+ // topic's row and counters instead of opening a second one.+ stats := tb.add(step.Topic, scenarioName)if topicC == nil {topicC = make(map[string]*counters)}topicC[step.Topic] = stats- meta := e.topicMeta[step.Topic]- if meta.scenarioName == "" {- meta.scenarioName = scenarioName- }-for gi := 0; gi < sc.Groups; gi++ {// The flow name is in the group id because a declared topic may already have// `<topic>-group-N` ids of its own, and two flows may both put consumers on// one topic. Colliding ids would silently join one Kafka group with two// different configurations.groupID := fmt.Sprintf("%s-%s-group-%d", f.Name, step.Topic, gi+1)- meta.groups = append(meta.groups, groupID)+ tb.addGroup(step.Topic, groupID)e.specMu.Lock()e.consumerSpecs[groupID] = consumerSpec{topic: step.Topic, conf: defaultFlowConsumerConf()}e.specMu.Unlock()for ci := 0; ci < sc.PerGroup; ci++ {- if _, err := e.addConsumer(groupID, step.Topic, []string{step.Topic}, sc.DelayMS, defaultFlowConsumerConf()); err != nil {+ if _, err := e.addConsumer(groupID, step.Topic, []string{step.Topic}, sc.DelayMS, defaultFlowConsumerConf(), stats); err != nil {return nil, err}}}-- e.topicMeta[step.Topic] = meta}return topicC, nil}diff --git a/internal/engine/lag.go b/internal/engine/lag.goindex c3e8661..f2d6a90 100644--- a/internal/engine/lag.go+++ b/internal/engine/lag.go@@ -58,10 +58,10 @@ type lagPoller struct {// groups is every consumer group in the run, in a stable order.groups []string- // topics is the engine's topic -> counters map. It is written only during build and- // read-only thereafter, so indexing it from this goroutine is safe; the mutable state- // is the per-topic atomic pointer inside each counters.- topics map[string]*counters+ // topics is the engine's frozen topic table. Read-only by construction, so reading it+ // from this goroutine needs no lock; the mutable state is the atomic pointer inside+ // each of its counters.+ topics *topicTablelog *slog.Loggerevents *eventRing@@ -82,19 +82,9 @@ func (e *Engine) newLagPoller() *lagPoller {return nil}- // topicOrder rather than ranging topicMeta: map order is random, and the group order+ // topicTable.groups is ordered and deduplicated, which matters here: the group order// decides the order of admin calls and therefore of any reported failures.- seen := make(map[string]bool)- var groups []string- for _, name := range e.topicOrder {- for _, g := range e.topicMeta[name].groups {- if seen[g] {- continue- }- seen[g] = true- groups = append(groups, g)- }- }+ groups := e.topics.groups()if len(groups) == 0 {// --no-consumers, or a scenario with no consumer groups. There is no group whose// lag could be measured, and asking about groups that do not exist would be pure@@ -107,7 +97,7 @@ func (e *Engine) newLagPoller() *lagPoller {interval: e.cfg.LagPoll,timeout: lagPollTimeout(e.cfg.LagPoll),groups: groups,- topics: e.topicStats,+ topics: e.topics,log: e.log,events: e.events,reported: make(map[string]string),@@ -157,7 +147,7 @@ func (p *lagPoller) run(ctx context.Context) error {// groups, and it would trade a slower tick for a burst of admin requests at a fixed// interval forever -- the wrong side of that trade for a process that runs for weeks.func (p *lagPoller) pollOnce(ctx context.Context) {- byTopic := make(map[string]map[string]int64, len(p.topics))+ byTopic := make(map[string]map[string]int64, len(p.topics.rows()))for _, group := range p.groups {lag, err := p.fetch(ctx, group)@@ -173,7 +163,7 @@ func (p *lagPoller) pollOnce(ctx context.Context) {p.recovered(group)for topic, parts := range lag {- if _, ok := p.topics[topic]; !ok {+ if p.topics.counters(topic) == nil {// A topic this run does not track: nothing would ever render it.continue}@@ -226,7 +216,8 @@ func (p *lagPoller) fetch(ctx context.Context, group string) (map[string]map[int// reading. Lag from thirty seconds ago rendered as the current value is exactly the kind// of quietly-wrong number this decision exists to eliminate.func (p *lagPoller) publish(byTopic map[string]map[string]int64) {- for name, c := range p.topics {+ for _, name := range p.topics.rows() {+ c := p.topics.counters(name)m := byTopic[name]if len(m) == 0 {c.brokerLag.Store(nil)diff --git a/internal/engine/lag_test.go b/internal/engine/lag_test.goindex 8930e01..dc4f6af 100644--- a/internal/engine/lag_test.go+++ b/internal/engine/lag_test.go@@ -51,23 +51,19 @@ func (s *stubLagSource) Calls() int {func lagEngine(t *testing.T, topics ...string) *Engine {t.Helper()- e := &Engine{- log: slog.New(slog.DiscardHandler),- reg: newRegistry(),- sched: &scheduler{},- events: newEventRing(64),- topicStats: make(map[string]*counters, len(topics)),- topicMeta: make(map[string]topicMeta, len(topics)),- }+ tb := newTopicTableBuilder()for _, name := range topics {- e.topicStats[name] = &counters{}- e.topicOrder = append(e.topicOrder, name)- e.topicMeta[name] = topicMeta{- scenarioName: "lag",- groups: []string{name + "-group-1"},- }+ tb.add(name, "lag")+ tb.addGroup(name, name+"-group-1")+ }++ return &Engine{+ log: slog.New(slog.DiscardHandler),+ reg: newRegistry(),+ sched: &scheduler{},+ events: newEventRing(64),+ topics: tb.freeze(),}- return e}// pollerFor wires a stub source to an engine's topics the way newLagPoller wires the real@@ -75,16 +71,12 @@ func lagEngine(t *testing.T, topics ...string) *Engine {func pollerFor(t *testing.T, e *Engine, src lagSource) *lagPoller {t.Helper()- var groups []string- for _, name := range e.topicOrder {- groups = append(groups, e.topicMeta[name].groups...)- }return &lagPoller{src: src,interval: time.Millisecond,timeout: lagPollTimeout(time.Millisecond),- groups: groups,- topics: e.topicStats,+ groups: e.topics.groups(),+ topics: e.topics,log: e.log,events: e.events,reported: make(map[string]string),diff --git a/internal/engine/run.go b/internal/engine/run.goindex 09843d0..90ed5af 100644--- a/internal/engine/run.go+++ b/internal/engine/run.go@@ -255,12 +255,12 @@ func (e *Engine) Snapshot() Snapshot {}}- for _, name := range e.topicOrder {- cs := e.topicStats[name]+ for _, name := range e.topics.rows() {+ cs := e.topics.counters(name)if cs == nil {continue}- meta := e.topicMeta[name]+ meta := e.topics.metaFor(name)ts := TopicStat{Topic: name,diff --git a/internal/engine/topics.go b/internal/engine/topics.gonew file mode 100644index 0000000..71b48d3--- /dev/null+++ b/internal/engine/topics.go@@ -0,0 +1,121 @@+package engine++// topicTable is the engine's published view of its topics: which topics have a row, in+// what order, and the counters and metadata each row is rendered from.+//+// Its job is to make one invariant structural instead of remembered. Snapshot and the lag+// poller both read this while every producer and consumer in the run is going, and+// neither takes a lock. That is sound only because the table stops changing before the+// run starts. It used to be three maps hanging off Engine, safe only for as long as every+// future edit remembered not to write them mid-run -- an invariant asserted by comments in+// three separate files and enforced by nothing.+//+// A *topicTable has no setter and no exported mutation of any kind: the builder is+// consumed by freeze, so after build there is no way to write one, by accident or+// otherwise. Every method is safe on a nil receiver, which is what an Engine that has not+// finished building has.+//+// The mutable state is the atomic pointer inside each *counters. Those are shared with the+// producers and consumers that write them, and they synchronise themselves.+type topicTable struct {+ order []string+ stats map[string]*counters+ meta map[string]topicMeta+}++// rows returns the topics that have a row, in render order.+func (t *topicTable) rows() []string {+ if t == nil {+ return nil+ }+ return t.order+}++// counters returns a topic's counter set, or nil when the topic has no row. A nil answer+// means the topic was never registered during build.+func (t *topicTable) counters(topic string) *counters {+ if t == nil {+ return nil+ }+ return t.stats[topic]+}++// metaFor returns a topic's metadata, or the zero value when the topic has no row.+func (t *topicTable) metaFor(topic string) topicMeta {+ if t == nil {+ return topicMeta{}+ }+ return t.meta[topic]+}++// groups returns every consumer group in the table, deduplicated, in table order.+//+// Ordered rather than ranged out of a map because the result decides the order of the lag+// poller's admin calls and therefore of any failures it reports; map iteration order would+// make that vary from run to run.+func (t *topicTable) groups() []string {+ seen := make(map[string]bool)+ var out []string+ for _, name := range t.rows() {+ for _, g := range t.metaFor(name).groups {+ if seen[g] {+ continue+ }+ seen[g] = true+ out = append(out, g)+ }+ }+ return out+}++// topicTableBuilder accumulates topics during build.+//+// Not safe for concurrent use, and deliberately not made so: build runs before any+// goroutine in the run exists, and anything that needed to add a topic later would be+// reintroducing exactly the race topicTable exists to rule out.+type topicTableBuilder struct {+ table *topicTable+}++func newTopicTableBuilder() *topicTableBuilder {+ return &topicTableBuilder{table: &topicTable{+ stats: make(map[string]*counters),+ meta: make(map[string]topicMeta),+ }}+}++// add registers a topic and returns its counters, creating them on first mention.+//+// Idempotent by design: a flow step whose `consumers:` block names an already-declared+// topic must share that topic's existing row and counters, not open a second one. The+// first scenario to mention a topic owns its label, for the same reason.+func (b *topicTableBuilder) add(topic, scenarioName string) *counters {+ stats, ok := b.table.stats[topic]+ if !ok {+ stats = &counters{}+ b.table.stats[topic] = stats+ b.table.order = append(b.table.order, topic)+ }+ if m := b.table.meta[topic]; m.scenarioName == "" {+ m.scenarioName = scenarioName+ b.table.meta[topic] = m+ }+ return stats+}++// addGroup records a consumer group against a topic, in registration order.+func (b *topicTableBuilder) addGroup(topic, groupID string) {+ m := b.table.meta[topic]+ m.groups = append(m.groups, groupID)+ b.table.meta[topic] = m+}++// freeze publishes the table and empties the builder.+//+// The builder is unusable afterwards -- a later add panics on a nil map rather than+// mutating a table something is already reading.+func (b *topicTableBuilder) freeze() *topicTable {+ t := b.table+ b.table = nil+ return t+}diff --git a/internal/engine/topics_test.go b/internal/engine/topics_test.gonew file mode 100644index 0000000..3f66413--- /dev/null+++ b/internal/engine/topics_test.go@@ -0,0 +1,105 @@+package engine++import (+ "slices"+ "testing"+)++// TestTopicTableAddIsIdempotent pins the property buildStepConsumers depends on: a flow+// step naming an already-declared topic shares that topic's row and counters rather than+// opening a second one.+func TestTopicTableAddIsIdempotent(t *testing.T) {+ tb := newTopicTableBuilder()++ first := tb.add("orders", "declared")+ second := tb.add("orders", "a-flow")++ if first != second {+ t.Error("add returned different counters for the same topic")+ }++ table := tb.freeze()+ if got := table.rows(); !slices.Equal(got, []string{"orders"}) {+ t.Errorf("rows = %v, want one entry", got)+ }+ // The first mention owns the label: a topic declared under `topics:` and then touched+ // by a flow step belongs to the scenario that declared it.+ if got := table.metaFor("orders").scenarioName; got != "declared" {+ t.Errorf("scenarioName = %q, want the first mention %q", got, "declared")+ }+ if table.counters("orders") != first {+ t.Error("frozen table does not carry the counters add handed out")+ }+}++// TestTopicTableOrderIsFirstMention pins that rows render in the order topics were added,+// not in map order.+func TestTopicTableOrderIsFirstMention(t *testing.T) {+ tb := newTopicTableBuilder()+ for _, name := range []string{"charlie", "alpha", "bravo"} {+ tb.add(name, "s")+ }+ tb.add("alpha", "s") // a repeat must not move it++ want := []string{"charlie", "alpha", "bravo"}+ if got := tb.freeze().rows(); !slices.Equal(got, want) {+ t.Errorf("rows = %v, want %v", got, want)+ }+}++// TestTopicTableGroupsAreOrderedAndDeduplicated pins what the lag poller relies on: the+// group order decides the order of admin calls and therefore of any reported failures, so+// it must not vary from run to run.+func TestTopicTableGroupsAreOrderedAndDeduplicated(t *testing.T) {+ tb := newTopicTableBuilder()+ tb.add("orders", "s")+ tb.addGroup("orders", "orders-group-1")+ tb.addGroup("orders", "orders-group-2")+ tb.add("shipments", "s")+ tb.addGroup("shipments", "shared-group")+ // The same group id against two topics is one group to the broker.+ tb.addGroup("orders", "shared-group")++ want := []string{"orders-group-1", "orders-group-2", "shared-group"}+ if got := tb.freeze().groups(); !slices.Equal(got, want) {+ t.Errorf("groups = %v, want %v", got, want)+ }+}++// TestNilTopicTableIsReadable pins that every reader is safe on an Engine that has not+// finished building, so no caller needs a nil check of its own.+func TestNilTopicTableIsReadable(t *testing.T) {+ var table *topicTable++ if got := table.rows(); got != nil {+ t.Errorf("rows = %v, want nil", got)+ }+ if got := table.counters("orders"); got != nil {+ t.Errorf("counters = %v, want nil", got)+ }+ if got := table.metaFor("orders"); got.scenarioName != "" || got.groups != nil {+ t.Errorf("metaFor = %+v, want the zero value", got)+ }+ if got := table.groups(); got != nil {+ t.Errorf("groups = %v, want nil", got)+ }+}++// TestFreezeEmptiesTheBuilder pins that a frozen table cannot be mutated through the+// builder that produced it, which is the whole reason the table can be read unlocked+// while the run is going.+func TestFreezeEmptiesTheBuilder(t *testing.T) {+ tb := newTopicTableBuilder()+ tb.add("orders", "s")+ table := tb.freeze()++ defer func() {+ if recover() == nil {+ t.Error("add on a frozen builder silently succeeded, want a panic")+ }+ if got := table.rows(); !slices.Equal(got, []string{"orders"}) {+ t.Errorf("published table changed after freeze: rows = %v", got)+ }+ }()+ tb.add("late", "s")+}diff --git a/internal/localcluster/cluster.go b/internal/localcluster/cluster.goindex f2658f6..d7085a6 100644--- a/internal/localcluster/cluster.go+++ b/internal/localcluster/cluster.go@@ -160,22 +160,27 @@ func (c *Cluster) Status(ctx context.Context) ([]ServiceStatus, error) {// StopBroker stops one broker container, leaving the rest of the cluster up.func (c *Cluster) StopBroker(ctx context.Context, name string) error {- return c.serviceAction(ctx, "stop", name)+ return c.serviceAction(ctx, "stop", name, stopArgs)}// StartBroker restarts a broker previously stopped by StopBroker.func (c *Cluster) StartBroker(ctx context.Context, name string) error {- return c.serviceAction(ctx, "start", name)+ return c.serviceAction(ctx, "start", name, startArgs)}-// serviceAction runs `compose stop|start <service>` after confirming there is a cluster-// to act on.+// serviceAction runs one compose command against a single service after confirming there+// is a cluster to act on.//// The check asks the compose project's own service list rather than probing for a// specific container name: once StopBroker has taken kafka-1 down, a name-based probe for// "kafka-1" would find nothing and StartBroker("kafka-1") could never bring it back, while// the service list still reports kafka-2, kafka-3 and kafka-ui as present.-func (c *Cluster) serviceAction(ctx context.Context, action, name string) error {+//+// argv builds the command; action only names it in errors. The two used to be one string,+// with the builder re-derived as `if action == "stop" { ... } else { ... }` -- so the else+// branch meant "start" for any string at all, and a typo at a call site started a broker+// it was asked to stop instead of failing to compile.+func (c *Cluster) serviceAction(ctx context.Context, action, name string, argv func(composeFile, service string) []string) error {file := c.clusterFile()statuses, err := c.Status(ctx)@@ -186,14 +191,7 @@ func (c *Cluster) serviceAction(ctx context.Context, action, name string) errorreturn fmt.Errorf("%s broker %s: %w", action, name, ErrNoActiveCluster)}- var args []string- if action == "stop" {- args = stopArgs(file, name)- } else {- args = startArgs(file, name)- }-- if _, stderr, err := c.run(ctx, args...); err != nil {+ if _, stderr, err := c.run(ctx, argv(file, name)...); err != nil {return classifyComposeError(fmt.Sprintf("%s broker %s", action, name), file, stderr, err)}return nildiff --git a/internal/localcluster/compose_test.go b/internal/localcluster/compose_test.goindex 12efd2e..c585f89 100644--- a/internal/localcluster/compose_test.go+++ b/internal/localcluster/compose_test.go@@ -7,6 +7,7 @@ import ("net""path/filepath""reflect"+ "slices""strings""testing""time"@@ -384,3 +385,55 @@ func TestIsContainerRunning(t *testing.T) {})}}++// TestBrokerActionsIssueTheirOwnVerb pins that StopBroker stops and StartBroker starts.+//+// serviceAction used to re-derive the command from its `action` string with+// `if action == "stop" { stopArgs } else { startArgs }`, so the else branch meant "start"+// for any other string and a typo at a call site would have started a broker it was asked+// to stop -- a runtime surprise where a compile error belongs. The builder is now passed+// in and the string only formats the error prefix.+func TestBrokerActionsIssueTheirOwnVerb(t *testing.T) {+ tests := []struct {+ name string+ call func(*Cluster, context.Context) error+ verb string+ }{+ {"stop", func(c *Cluster, ctx context.Context) error { return c.StopBroker(ctx, "kafka-1") }, "stop"},+ {"start", func(c *Cluster, ctx context.Context) error { return c.StartBroker(ctx, "kafka-1") }, "start"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ f := newFakeRunner()+ f.stdout["ps"] = `{"Service":"kafka-1","State":"running"}`+ c := newTestCluster(t, f)++ if err := tt.call(c, context.Background()); err != nil {+ t.Fatalf("%s: %v", tt.verb, err)+ }++ var verbs []string+ for _, call := range f.calls {+ for i, arg := range call {+ // The subcommand is whatever follows the compose file.+ if arg == "-f" && i+2 < len(call) {+ verbs = append(verbs, call[i+2])+ }+ }+ }+ if !slices.Contains(verbs, tt.verb) {+ t.Errorf("compose subcommands were %v, want one of them to be %q", verbs, tt.verb)+ }+ // The opposite verb must never be issued -- that is the misroute the old+ // else branch made possible.+ other := "start"+ if tt.verb == "start" {+ other = "stop"+ }+ if slices.Contains(verbs, other) {+ t.Errorf("%sBroker issued %q: compose subcommands were %v", tt.name, other, verbs)+ }+ })+ }+}diff --git a/internal/tui/render.go b/internal/tui/render.goindex 7cac4a8..8920245 100644--- a/internal/tui/render.go+++ b/internal/tui/render.go@@ -190,17 +190,21 @@ func (m model) header(w int) string {if s.Scenario != "" {sep = lipgloss.Width(" · ")}- scenMax := func() int {+ // right is a parameter, not a capture. It is reassigned between the two calls below,+ // so a closure over it would return a different number at each site with nothing at+ // either site to say so -- and any later edit that reordered these lines would change+ // the layout without touching this function.+ scenMax := func(right string) int {return w - lipgloss.Width(right) - lipgloss.Width(title) -lipgloss.Width(badge) - lipgloss.Width(stop) - sep - 2}- if scenMax() < 8 {+ if scenMax(right) < 8 {right = buildRight(false)}left := titleif s.Scenario != "" {- if scen := truncate(s.Scenario, max(scenMax(), 0)); scen != "" {+ if scen := truncate(s.Scenario, max(scenMax(right), 0)); scen != "" {left += dimStyle.Render(" · ") + headerStyle.Render(scen)}}diff --git a/internal/tui/render_more_test.go b/internal/tui/render_more_test.goindex 4f25c12..aed59ff 100644--- a/internal/tui/render_more_test.go+++ b/internal/tui/render_more_test.go@@ -396,3 +396,60 @@ func TestProgressBar(t *testing.T) {}func plainStr(s string) string { return ansiRe.ReplaceAllString(s, "") }++// scenarioText returns the scenario name as rendered in a header line, or "" when the+// header dropped it.+func scenarioText(header string) string {+ _, rest, ok := strings.Cut(header, "khaos · ")+ if !ok {+ return ""+ }+ name, _, _ := strings.Cut(rest, " ")+ return name+}++// TestHeaderMeasuresTheScenarioAgainstTheLayoutItGot pins that once the progress bar has+// been dropped, the scenario name is sized against the narrower right-hand side rather+// than the one that included the bar.+//+// The budget used to come from a closure capturing `right`, which is reassigned between+// its two call sites -- so the same call returned a different number each time, with+// nothing at either site saying so. The behaviour was correct and this pins it, because+// the obvious "cleanup" of hoisting that call to a single variable would silently shrink+// the scenario name in exactly this band.+func TestHeaderMeasuresTheScenarioAgainstTheLayoutItGot(t *testing.T) {+ snap := engine.Snapshot{+ At: time.Now(),+ Scenario: "orders-pipeline-with-a-very-long-name",+ Elapsed: time.Minute,+ Deadline: 10 * time.Minute,+ Healthy: false,+ Stopping: true,+ }+ m := model{snap: snap}++ // At 81 the bar still fits, so the scenario is measured against the wide right.+ withBar := plainStr(m.header(81))+ if !strings.Contains(withBar, "█") {+ t.Fatalf("width 81 was expected to keep the progress bar: %q", withBar)+ }++ // 76..80 is the band where the bar is dropped: wide enough for barWidth to offer one,+ // too narrow to leave the scenario 8 cells beside it.+ for w := 76; w <= 80; w++ {+ header := plainStr(m.header(w))+ if strings.Contains(header, "█") {+ t.Errorf("width %d: progress bar should have yielded: %q", w, header)+ }+ if got := lipgloss.Width(header); got > w {+ t.Errorf("width %d: header is %d cells wide: %q", w, got, header)+ }+ // The point of the reassignment: dropping the bar hands its cells to the scenario.+ // Measuring against the stale wide right would leave them empty.+ if len(scenarioText(header)) <= len(scenarioText(withBar)) {+ t.Errorf("width %d: scenario %q is no longer than the with-bar layout at 81 (%q); "++ "the freed cells went nowhere",+ w, scenarioText(header), scenarioText(withBar))+ }+ }+}