Skip to content

armgit / khaos

Public Imported from GitHub
0

Kafka data generator and load testing tool - generate fake messages, simulate producers and consumers, test broker failures, and run chaos engineering scenarios

docs: sweep low-value comments, expand package docs, add architecture diagrams

aleksandarskrbicb11462df13df
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 05908b0..b783e35 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,9 +2,9 @@
Thanks for your interest in contributing!
-## Development Setup
+## Development setup
-Requires Go 1.26+.
+Requires Go 1.26 or newer (`go.mod` declares 1.26.5).
```bash
git clone https://github.com/aleksandarskrbic/khaos.git
@@ -13,39 +13,77 @@ go build -o khaos ./cmd/khaos
./khaos --help
```
-No Docker required to work on khaos itself — tests run against
-[kfake](https://pkg.go.dev/github.com/twmb/franz-go/pkg/kfake), an in-process broker that speaks
-the real Kafka protocol. Docker is only needed if you want to run `khaos run` against the bundled
-local cluster manually while testing changes.
+The test suite needs no Docker. It runs against
+[kfake](https://pkg.go.dev/github.com/twmb/franz-go/pkg/kfake), an in-process broker that
+speaks the real Kafka protocol, so the engine, the clients and the CLI are all exercised
+without a container. Docker is only needed to drive the bundled cluster by hand --
+`khaos cluster-up`, or `khaos run` against it -- while trying a change out end to end.
-## Before Submitting a PR
-
-Run all checks:
+## Before submitting a PR
```bash
-./scripts/check.sh
-
-# add -r to also run the race detector (what CI runs)
-./scripts/check.sh -r
+./scripts/check.sh # gofmt, go vet, go test, static build + `khaos --version`
+./scripts/check.sh -r # the same with -race, which is what CI runs
```
-This runs:
-- `gofmt` — formatting
-- `go vet` — static analysis
-- `go test` — the test suite
-- a static build (`CGO_ENABLED=0`) plus a smoke check (`khaos --version`)
+`check.sh` is the local equivalent of the `test` job in `.github/workflows/ci.yml`:
+
+- `gofmt -l cmd internal` must print nothing.
+- `go vet ./...`
+- `go test ./...` -- `-race -timeout 15m` under `-r` and in CI, `-timeout 10m` otherwise.
+- `CGO_ENABLED=0 go build ./cmd/khaos`, then run the result. The static binary is the
+ product, so it gets built the way it ships. CI goes one step further and smoke-tests it
+ with `--version`, `list` and `validate traffic/high-throughput`.
+
+CI runs two jobs `check.sh` does not:
+
+- **cross-compile** builds linux/amd64, linux/arm64, darwin/amd64, darwin/arm64 and
+ windows/amd64. Anything that drags in cgo fails here first.
+- **govulncheck** is advisory. It reports vulnerabilities in required modules even when the
+ calling code path is unreachable, so it never fails the build on its own.
-## Code Style
+Pull requests touching `website/` get their own workflow, `website-ci.yml`: `npm ci`,
+`npm run lint`, `npm run build` and an `opennextjs-cloudflare build`, all from `website/` on
+Node 22. Merging them to `main` runs `deploy-website.yml`, which deploys the site.
-- Run `gofmt` before committing; `./scripts/check.sh` will catch anything unformatted.
-- Match the existing package structure (see the Architecture section in `README.md`) — the
- scenario engine (`internal/engine`) stays independent of any UI (`internal/tui`), and
- `internal/kafka` stays the only package that talks to franz-go directly.
+## Code style
+
+- Run `gofmt` before committing; `./scripts/check.sh` catches anything unformatted.
+- Match the existing package structure (see the Architecture section in `README.md`):
+ `internal/engine` stays independent of any UI (`internal/tui`), `internal/kafka` is the
+ only package that constructs Kafka (`kgo`/`kadm`) clients -- `internal/codec` owns the
+ Schema Registry client -- and `internal/scenario` depends on nothing else in the repo.
+- Comments say why, not what. The dash used throughout the codebase is ` -- `, not an em
+ dash.
- Tests are required for new features.
+- Commit subjects follow conventional commits. `scripts/release.sh` drafts the CHANGELOG
+ entry from `feat:`, `fix:`, `perf:`, `refactor:` and `docs:` subjects since the last tag
+ and skips everything else, so a user-visible change described as `chore:` silently misses
+ the release notes.
+
+## Adding a scenario
+
+Scenario YAML lives in `scenarios/<category>/<name>.yaml`, and the binary embeds a copy
+under `internal/scenario/bundled/`. Add the file in both places, byte for byte:
+`TestBundledCopyMatchesRepo` fails the moment the two drift, and `TestShippedScenariosValidate`
+and `TestBundledScenariosAreGeneratable` check that everything shipped both validates and
+actually generates data.
+
+`khaos list` and `khaos validate` pick the new file up with no code change. A new category
+directory also wants an entry in `categoryOrder` and `categoryInfo` in
+`cmd/khaos/scenarios.go`, or it sorts last in `khaos list` under a title-cased directory
+name with no description.
+
+## Pull request process
-## Pull Request Process
+1. Fork the repo and branch from `main`.
+2. Run `./scripts/check.sh -r` and make sure it passes.
+3. Update the docs if behaviour changed. User-facing documentation is
+ `website/content/docs/`, and the flag tables live in
+ `website/content/docs/reference/cli.mdx`.
+4. Open the PR with a clear description of what changed and why.
-1. Fork the repo and create your branch from `main`.
-2. Run `./scripts/check.sh -r` and ensure all checks pass.
-3. Update documentation if needed — the website source lives in `website/content/docs/`.
-4. Submit PR with a clear description of changes.
+Two other files are worth knowing about: `RUNBOOK.md` covers building, releasing and driving
+a cluster by hand, and `DECISIONS.md` records the deliberate behavioural choices (which
+partitioner, which rebalance protocol, whether topics are recreated) together with the line
+of code each one is set on.
diff --git a/DECISIONS.md b/DECISIONS.md
index 98b45ee..6de2b25 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1,51 +1,53 @@
# Open decisions
-Seventeen decisions. Four are still open; the rest are settled and struck through. Each one is live in the code right now at the
-value in **Current**. To change one, edit the file in **Where** — nothing else needs touching.
+Seventeen decisions. Nine are settled and struck through; the other eight are still
+waiting on you. Every row in the first table is live in the code right now at the value in
+**Current** -- to change one, edit the symbol named in **Where** and nothing else.
Write your answer in the **You** column. If you agree with the default, put `ok`.
---
-## Already wired — flip by editing one line
+## Already wired -- flip by editing one line
| # | Question | Current | Where | If you flip it | You |
|---|---|---|---|---|---|
-| **D1** | Which partition does a key land on? Python inherits librdkafka CRC32; franz-go defaults to murmur2 (what Java uses). | **CRC32 — matches Python** (hand-written, `internal/kafka/partitioner.go`) | `internal/kafka/policy.go:26` | Set `kgo.StickyKeyPartitioner(nil)` for Java-compatible murmur2. A *different* partition then goes hot in `hot-partition`/`single_key`. | |
-| **D2** | Consumer-group rebalance protocol. Python inherits eager range+roundrobin; franz-go defaults to cooperative-sticky. | eager range+roundrobin | `internal/kafka/policy.go:55` | `rebalance-storm` and `uneven-assignment` behave visibly differently — they're *about* rebalances. | |
-| **D4** | Delete + recreate topics on every run? Python does, unconditionally. | **on — matches Python** | `internal/kafka/policy.go:74` | Set `false`, or pass `--recreate-topics=false`, to leave existing topics and their data alone. | |
-| **D9** | Producer buffer full: block or drop? Python lets the error kill the producer permanently. | block (backpressure) | `internal/kafka/policy.go:89` | Affects the numbers during broker-chaos, which is exactly when it happens. | |
-| **D10** | Hardcoded `kafka-1/2/3` broker names and `replication_factor <= 3`. Rejects any external cluster. | Python's values kept | `internal/scenario/validate.go:42` | Reassign `Cluster` to relax. Blocks your 24/7 multi-cluster use until you do. | |
-| **D13** | Flow instances in flight at once. Python is unbounded and untracked. | **0 = unbounded — matches Python** | `internal/engine/flow.go:35` | Set a positive value to bound the pool; issuance then blocks at saturation and shows as `Saturated` in the snapshot. | |
+| **D1** | Which partition does a key land on? Python inherits librdkafka CRC32; franz-go defaults to murmur2 (what Java uses). | **CRC32 -- matches Python** (hand-written, `internal/kafka/partitioner.go`) | `internal/kafka/policy.go`, `var Partitioner` | Set `kgo.StickyKeyPartitioner(nil)` for Java-compatible murmur2. A *different* partition then goes hot in `hot-partition`/`single_key`. | |
+| **D2** | Consumer-group rebalance protocol. Python inherits eager range+roundrobin; franz-go defaults to cooperative-sticky. | eager range+roundrobin | `internal/kafka/policy.go`, `var Balancers` | `rebalance-storm` and `uneven-assignment` behave visibly differently -- they're *about* rebalances. | |
+| **D4** | Delete + recreate topics on every run? Python does, unconditionally. | **on -- matches Python** | `internal/kafka/policy.go`, `var RecreateTopicsByDefault` | Set `false`, or pass `--recreate-topics=false`, to leave existing topics and their data alone. | |
+| **D9** | Producer buffer full: block or drop? Python lets the error kill the producer permanently. | block (backpressure) | `internal/kafka/policy.go`, `var BlockOnBufferFull` | Affects the numbers during broker-chaos, which is exactly when it happens. | |
+| **D10** | Hardcoded `kafka-1/2/3` broker names and `replication_factor <= 3`. Rejects any external cluster. | Python's values kept | `internal/scenario/validate.go`, `var Cluster` | Reassign `Cluster` to relax. Blocks your 24/7 multi-cluster use until you do. | |
+| **D13** | Flow instances in flight at once. Python is unbounded and untracked. | **0 = unbounded -- matches Python** | `internal/engine/flow.go`, `var DefaultFlowConcurrency` | Set a positive value to bound the pool; issuance then blocks at saturation and shows as `Saturated` in the snapshot. | |
-## Python bugs reproduced on purpose — flip if you'd rather have the fix
+## Python bugs reproduced on purpose -- all four have since been fixed
-You said behaviour must match Python, so each of these reproduces a Python defect. Every one
-is a single flip, and each site carries a comment explaining both sides.
+You said behaviour must match Python, so each of these started out reproducing a Python
+defect, as a single flip with a comment at the site explaining both sides. All four have
+since been flipped to the fix; the rows record what changed.
-| # | Python's behaviour, now reproduced | Flip it at | You |
+| # | Python's behaviour, originally reproduced | Flip it at | You |
|---|---|---|---|
| ~~**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.~~ | **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. | |
+| ~~**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.~~ | **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 disagree
+## Implemented as recommended -- say if you disagree
| # | Question | What I did | Where | You |
|---|---|---|---|---|
| **D7** | `--ssl-key-password` (encrypted keys). Go stdlib can't read PKCS#8-encrypted keys. | Rejected up front with an error naming the flag and the `openssl pkcs8 -nocrypt` fix. | `internal/kafka/security.go` | |
-## Not done — need your answer before I build them
+## Raised as blocking -- all but D6 have since been resolved
| # | Question | Status | You |
|---|---|---|---|
-| ~~**D3**~~ | ~~Lag is Python's fake `produced − consumed`.~~ | **DONE, opt-in.** `--lag-poll 5s` asks the brokers for real committed-offset-vs-end-offset lag on a slow independent ticker. Default 0 = off, so the column is unchanged unless you ask. Shows **both** columns (`LAG(SELF)` / `LAG(BROKER)`) rather than silently swapping one for the other. A denied DESCRIBE, a timeout, or a partial answer renders **`unknown`** — never a zero — is logged once rather than every tick, and never fails the run. Headless logs get `broker_lag` too. | |
+| ~~**D3**~~ | ~~Lag is Python's fake `produced − consumed`.~~ | **DONE, opt-in.** `--lag-poll 5s` asks the brokers for real committed-offset-vs-end-offset lag on a slow independent ticker. Default 0 = off, so the column is unchanged unless you ask. Shows **both** columns (`LAG(SELF)` / `LAG(BROKER)`) rather than silently swapping one for the other. A denied DESCRIBE, a timeout, or a partial answer renders **`unknown`** -- never a zero -- is logged once rather than every tick, and never fails the run. Headless logs get `broker_lag` too. | |
| **D6** | Faker → gofakeit. Names differ (`street_address`→`street`, `postcode`→`zip`, `country_code`→`countryabr`), `date_this_month` has no equivalent, **locale is gone entirely**. | Alias table built for the ~20 providers your scenarios and README use. Unmapped names error clearly. `locale:` is accepted and ignored. **User scenario YAML can break here.** | |
-| ~~**D8**~~ | ~~Avro library. `hamba/avro v2.31.0` is archived with a reported unpatched CVE; `goavro` is in maintenance mode.~~ | **DONE.** `internal/codec` now uses `github.com/linkedin/goavro/v2 v2.15.0`; hamba/avro is fully removed from go.mod/go.sum. Rewrote the encode/decode path around goavro's actual native-value conventions rather than a mechanical port: unions are wrapped/unwrapped as goavro's `map[string]interface{}{branchName: value}` (including folding compound logical-type keys like `long.timestamp-millis` into the union branch name — goavro compiles those under a `type.logicalType` key, which the first pass missed and an adversarial review caught before merge), field order is recovered by walking a hand-built schema tree since goavro exposes no walkable object model, and per-topic name isolation across schema parses holds natively (no shared/global cache the way hamba had). All existing avro tests pass with unchanged assertions, plus a new regression test for a nullable/optional logical-type field pulled from a Schema-Registry-shaped schema (khaos's own generator never emits unions, so nothing previously exercised that path). Not yet round-tripped through a live Schema Registry + a real external Avro reader (Java `kafka-avro-console-consumer` or `avro-tools`) — only Go-side round-trip tests. | |
-| ~~**D12**~~ | ~~Schema Registry auth impossible — blocked Confluent Cloud and Aiven.~~ | **DONE.** `--schema-registry-username/-password/-token/-ca-location/-cert-location/-key-location`. Credentials are exercised by the startup probe, so a bad one fails immediately rather than on first produce. A 401/403 now names the URL and the likely wrong flag, including that **the SR API key is not the Kafka API key** — the most common Confluent Cloud mistake. Basic+bearer together, half a credential pair, and TLS files against a non-`https` URL are all rejected up front. | |
-| ~~**D14**~~ | ~~`--skip-topic-creation` did not skip topic creation.~~ | **FIXED.** `engine.Config.SkipTopicCreation` now short-circuits `setupTopics`, so no topic admin call is issued at all — matching Python, which never invokes TopicManager when the flag is set. Two tests: one proves the topic is absent with the flag, the paired one proves it IS created without, so the first cannot pass vacuously. | |
-| ~~**D15**~~ | ~~`cluster-down` always removed data volumes.~~ | **FIXED.** `Down(ctx, removeVolumes bool)`; `--volumes`/`-v` controls it, default false as in Python. Note this changes nothing observable today: **none of the four compose files declares a volume** — the brokers keep their logs at `KAFKA_LOG_DIRS=/tmp/kraft-combined-logs` inside the container layer, which `compose down` discards either way. So the earlier "silent data loss" framing was wrong. Fixed so the flag stops lying and stays correct if a volume is ever added. | |
+| ~~**D8**~~ | ~~Avro library. `hamba/avro v2.31.0` is archived with a reported unpatched CVE; `goavro` is in maintenance mode.~~ | **DONE.** `internal/codec` now uses `github.com/linkedin/goavro/v2 v2.15.0`; hamba/avro is fully removed from go.mod/go.sum. Rewrote the encode/decode path around goavro's actual native-value conventions rather than a mechanical port: unions are wrapped/unwrapped as goavro's `map[string]interface{}{branchName: value}` (including folding compound logical-type keys like `long.timestamp-millis` into the union branch name -- goavro compiles those under a `type.logicalType` key, which the first pass missed and an adversarial review caught before merge), field order is recovered by walking a hand-built schema tree since goavro exposes no walkable object model, and per-topic name isolation across schema parses holds natively (no shared/global cache the way hamba had). All existing avro tests pass with unchanged assertions, plus a new regression test for a nullable/optional logical-type field pulled from a Schema-Registry-shaped schema (khaos's own generator never emits unions, so nothing previously exercised that path). Not yet round-tripped through a live Schema Registry + a real external Avro reader (Java `kafka-avro-console-consumer` or `avro-tools`) -- only Go-side round-trip tests. | |
+| ~~**D12**~~ | ~~Schema Registry auth impossible -- blocked Confluent Cloud and Aiven.~~ | **DONE.** `--schema-registry-username/-password/-token/-ca-location/-cert-location/-key-location`. Credentials are exercised by the startup probe, so a bad one fails immediately rather than on first produce. A 401/403 now names the URL and the likely wrong flag, including that **the SR API key is not the Kafka API key** -- the most common Confluent Cloud mistake. Basic+bearer together, half a credential pair, and TLS files against a non-`https` URL are all rejected up front. | |
+| ~~**D14**~~ | ~~`--skip-topic-creation` did not skip topic creation.~~ | **FIXED.** `engine.Config.SkipTopicCreation` now short-circuits `setupTopics`, so no topic admin call is issued at all -- matching Python, which never invokes TopicManager when the flag is set. Two tests: one proves the topic is absent with the flag, the paired one proves it IS created without, so the first cannot pass vacuously. | |
+| ~~**D15**~~ | ~~`cluster-down` always removed data volumes.~~ | **FIXED.** `Down(ctx, removeVolumes bool)`; `--volumes`/`-v` controls it, default false as in Python. This changes nothing observable today: **none of the four compose files declares a volume** -- the brokers keep their logs at `KAFKA_LOG_DIRS=/tmp/kraft-combined-logs` inside the container layer, which `compose down` discards either way. So the earlier "silent data loss" framing was wrong. Fixed so the flag stops lying and stays correct if a volume is ever added. | |
---
diff --git a/README.md b/README.md
index c32818a..4b7438c 100644
--- a/README.md
+++ b/README.md
@@ -20,12 +20,17 @@
## What it does
-- **Generate realistic Kafka test data**: structured, faker-backed records in JSON, Avro, or Protobuf.
-- **Simulate producer and consumer traffic**: configurable throughput, key distributions, and consumer group topology.
-- **Load test Kafka clusters** and the applications that consume from them, including Kafka Streams and Flink jobs.
-- **Reproduce failure conditions on purpose**: consumer lag, hot partitions, rebalances, and broker failures, scheduled on a timeline.
+- **Generate realistic Kafka test data**: structured, faker-backed records in JSON, Avro
+ or Protobuf.
+- **Simulate producer and consumer traffic**: configurable throughput, key distributions
+ and consumer group topology.
+- **Load test Kafka clusters** and the applications that consume from them, including
+ Kafka Streams and Flink jobs.
+- **Reproduce failure conditions on purpose**: consumer lag, hot partitions, rebalances
+ and broker failures, scheduled on a timeline.
-Scenarios are plain YAML. No code, no client library, no instrumentation in the system under test.
+Scenarios are plain YAML. No code, no client library, no instrumentation in the system
+under test.
## Quick start
@@ -36,8 +41,13 @@ khaos list # see the bundled scenarios
khaos run traffic/high-throughput # auto-starts a local 3-broker Kafka cluster
```
-`khaos run` manages its own local Kafka cluster via Docker Compose. To target a cluster you
-already have, including managed clusters needing SASL/SSL, use `khaos simulate` instead. See the
+`khaos run` starts the bundled three-broker cluster with Docker Compose if it is not already
+up, and stops it again when the run ends -- pass `-k` to keep it. While it is up, Kafka UI is
+on <http://localhost:8080>. `khaos cluster-up` and `khaos cluster-down` drive the same cluster
+by hand.
+
+To target a cluster you already have, including managed clusters needing SASL/SSL, use
+`khaos simulate -b broker:9092` instead; it never touches Docker. See the
[Quick Start guide](https://getkhaos.dev/docs/quickstart) and
[Installation](https://getkhaos.dev/docs/installation) for release binaries and Docker.
@@ -50,8 +60,9 @@ khaos run chaos/broker-chaos # brokers stop and restart while traffic k
khaos run chaos/rebalance-storm # a consumer group rebalances repeatedly
```
-`khaos validate` checks a scenario file's structure without running it: the same command Khaos's
-own CI runs against every bundled scenario. See the
+`khaos validate path/to/scenario.yaml` checks a file's structure without running it, reporting
+every problem it finds with a line number rather than stopping at the first. With no arguments
+it checks every bundled scenario, which is what makes it usable as a CI gate. See the
[Scenarios](https://getkhaos.dev/docs/scenarios/consumer-lag) and
[Guides](https://getkhaos.dev/docs/guides/kafka-load-testing) sections of the docs for what
each one actually configures and why.
@@ -70,20 +81,172 @@ testing, data generation, and each failure scenario, lives at
## Architecture
-Khaos is a single Go binary. The scenario engine is independent of any user interface: it exposes
-one read method, `Snapshot()`, and the terminal UI, the headless log loop, and the final summary
-table all poll it. Nothing in the engine knows about terminals, so a headless run in CI behaves
-identically to an interactive one, and a stalled UI can't stall a run.
+One Go module, one binary. `cmd/khaos` is the cobra CLI -- flags, wiring and the static
+output -- and everything else lives under `internal/`, forming a one-way chain from a scenario
+file to Kafka records.
+
+```mermaid
+%%{init: {'flowchart': {'curve': 'linear', 'nodeSpacing': 50, 'rankSpacing': 58, 'padding': 16}, 'themeVariables': {'fontSize': '15px'}}}%%
+flowchart TD
+ cmd(["cmd/khaos"])
+ tui["tui"]
+ localcluster["localcluster"]
+ theme["theme"]
+ engine["engine"]
+ generate["generate"]
+ codec["codec"]
+ kafka["kafka"]
+ telemetry["telemetry"]
+ scenario["scenario"]
+
+ cmd --> tui
+ cmd --> engine
+ cmd --> localcluster
+ tui -. "Snapshot" .-> engine
+ tui --> theme
+ engine --> generate
+ engine --> codec
+ engine --> kafka
+ engine --> telemetry
+ generate --> scenario
+ codec --> scenario
+ kafka --> scenario
+
+ classDef entry fill:#0E6B77,stroke:#083F47,stroke-width:1px,color:#FFFFFF
+ classDef surface fill:#1F7C89,stroke:#0E4C55,stroke-width:1px,color:#FFFFFF
+ classDef core fill:#245F45,stroke:#0F3A2A,stroke-width:1px,color:#FFFFFF
+ classDef pipeline fill:#2F7A52,stroke:#16452E,stroke-width:1px,color:#FFFFFF
+ classDef foundation fill:#44619F,stroke:#243761,stroke-width:1px,color:#FFFFFF
+ classDef infra fill:#55686E,stroke:#323E42,stroke-width:1px,color:#FFFFFF
+
+ class cmd entry
+ class tui,theme,telemetry surface
+ class engine core
+ class generate,codec,kafka pipeline
+ class scenario foundation
+ class localcluster infra
+
+ linkStyle default stroke:#7E9AA0,stroke-width:1.4px
+```
+
+Every node except `cmd/khaos` lives under `internal/`, and arrows point from importer to
+imported. `cmd/khaos` actually imports every internal package except `generate`; only its three
+structural edges are drawn, because eight lines leaving one node buries the shape the diagram
+exists to show. The graph has no cycles and `scenario` is the sink: it imports nothing in the
+repo and everything else speaks its vocabulary. The one edge that is not a plain import is
+`tui -> engine`, drawn dotted because it is a read -- the dashboard polls `Snapshot()` and has no
+other way to reach a run.
+
+Colour is the layer: teal is the CLI and its output surfaces, green is the run itself and the
+record pipeline feeding it, indigo is the shared vocabulary, slate is infrastructure.
+
+### Packages
+
+- **`internal/scenario`** -- the YAML domain model, decoding, validation, and the bundled
+ scenario corpus embedded in the binary. It imports nothing else in the repo; everything that
+ touches a scenario imports it.
+- **`internal/generate`** -- builds values from a topic's `message_schema`: field values, whole
+ documents, keys with a given distribution and cardinality, and correlated multi-step flow
+ messages. Every generator takes an explicit `*rand.Rand` and none touch the global
+ source, which is what lets `--seed` replay the same records.
+- **`internal/codec`** -- encodes those documents as JSON, Avro or Protobuf, with the schema
+ inline or fetched from Schema Registry, including the Confluent wire header.
+- **`internal/kafka`** -- builds the [franz-go](https://github.com/twmb/franz-go) Kafka clients
+ and runs the admin calls that prepare topics. Every deliberate departure from a franz-go
+ default is collected in `policy.go`. No other package constructs a `kgo` client --
+ `internal/engine` is handed the ones it uses -- and the only other franz-go client in the
+ repo is the Schema Registry client in `internal/codec`.
+- **`internal/engine`** -- the run itself: producers, consumer groups, per-producer rate
+ limiting, the incident scheduler, and the counters behind `Snapshot()`.
+- **`internal/tui`**, **`internal/telemetry`**, **`internal/theme`** -- output: the live
+ terminal dashboard, the structured logger plus the Prometheus `/metrics` and `/healthz`
+ server, and the colour palette the dashboard and the CLI's own tables share.
+- **`internal/localcluster`** -- the bundled three-broker cluster, driven by the `docker` CLI
+ against compose files embedded in the binary. It depends on nothing else in the repo, and
+ `khaos simulate` never calls into it.
+
+The engine is independent of any user interface. It exposes one read method, `Snapshot()`, and
+the terminal UI, the headless log loop and the final summary table all poll it. Nothing in the
+engine knows about terminals, so a headless run in CI behaves identically to an interactive one,
+and a stalled UI cannot stall a run.
+
+franz-go is a pure-Go Kafka client, which is what makes `CGO_ENABLED=0`, cross-compilation,
+`go install` and a `distroless/static` image all work without a C toolchain.
+
+### What a run does
+
+```mermaid
+%%{init: {'flowchart': {'curve': 'linear', 'nodeSpacing': 50, 'rankSpacing': 58, 'padding': 16}, 'themeVariables': {'fontSize': '15px'}}}%%
+flowchart TD
+ cmd(["khaos run"])
+ load["load and validate YAML"]
+ up["start local cluster"]
+ new["engine.New"]
+ run["engine.Run"]
+ producers["producers"]
+ consumers["consumer groups"]
+ incidents["incident scheduler"]
+ snapshot(["Snapshot()"])
+ dashboard["live dashboard"]
+ logs["headless log loop"]
+ summary["summary table"]
+ down["stop local cluster"]
+
+ cmd --> load
+ load --> up
+ up --> new
+ new --> run
+ run --> producers
+ run --> consumers
+ run --> incidents
+ incidents -. "retune rate" .-> producers
+ incidents -. "pause / rebalance" .-> consumers
+ producers --> snapshot
+ consumers --> snapshot
+ snapshot --> dashboard
+ snapshot --> logs
+ run --> summary
+ summary --> down
+
+ classDef entry fill:#0E6B77,stroke:#083F47,stroke-width:1px,color:#FFFFFF
+ classDef setup fill:#55686E,stroke:#323E42,stroke-width:1px,color:#FFFFFF
+ classDef traffic fill:#2F7A52,stroke:#16452E,stroke-width:1px,color:#FFFFFF
+ classDef chaos fill:#9B4585,stroke:#5C2850,stroke-width:1px,color:#FFFFFF
+ classDef read fill:#1F7C89,stroke:#0E4C55,stroke-width:1px,color:#FFFFFF
+
+ class cmd entry
+ class load,up,new,down setup
+ class run,producers,consumers traffic
+ class incidents chaos
+ class snapshot,dashboard,logs,summary read
+
+ linkStyle default stroke:#7E9AA0,stroke-width:1.4px
+```
+
+`engine.New` is where topics are created, unless `--skip-topic-creation` says otherwise.
+Incidents also stop and restart brokers, which is the one thing `khaos simulate` cannot do: it
+runs the same path without the two cluster steps, and broker incidents become no-ops there
+because Khaos cannot stop someone else's broker. Whether the dashboard or the log loop reads
+`Snapshot()` is decided once at startup from whether stdout is a TTY; the summary table prints
+from a final `Snapshot()` either way.
+
+Slate is setup and teardown, green is traffic, magenta is the chaos, teal is everything that
+reads a run rather than driving it.
-Kafka access is [franz-go](https://github.com/twmb/franz-go), a pure-Go client, which is what makes
-`CGO_ENABLED=0`, cross-compilation, `go install`, and a `distroless/static` image all work without
-a C toolchain. See the [Concepts](https://getkhaos.dev/docs/concepts) page for the full picture.
+**Where to start reading:** `cmd/khaos/run.go` for the flags and the wiring, then
+`internal/engine/run.go` for what a run actually does. `internal/scenario/types.go` is the
+vocabulary every other package speaks. The [Concepts](https://getkhaos.dev/docs/concepts) page
+covers the same ground for users rather than contributors.
## Rewritten in Go
-Khaos was rewritten from Python to Go: a single static binary, no runtime dependencies, and a pure
-Go Kafka client that cross-compiles cleanly. See the
-[release notes](https://github.com/aleksandarskrbic/khaos/releases) for details.
+Khaos 0.8.0 replaced the Python implementation with this one: a single static binary with the
+scenarios and compose files embedded, no virtualenv and no librdkafka. Commands, flags,
+shorthands and the scenario YAML format carried over unchanged, so existing scenario files still
+run. The PyPI package is gone: install a release binary, `go install`, `brew install khaos`,
+or use the multi-arch image at `ghcr.io/aleksandarskrbic/khaos`. See
+[CHANGELOG.md](CHANGELOG.md) and the
+[release notes](https://github.com/aleksandarskrbic/khaos/releases).
## Contributing
diff --git a/RUNBOOK.md b/RUNBOOK.md
index 1ea6cfb..f345aa2 100644
--- a/RUNBOOK.md
+++ b/RUNBOOK.md
@@ -1,20 +1,30 @@
-# Runbook: build, test, release
+# khaos runbook
-Everything you need to drive the Go rewrite by hand.
+How to build khaos, exercise it by hand against a real cluster, and cut a release.
+
+The manual test plan in section 2 is the part worth reading before a release: it walks the
+paths that CI cannot reach, because they need Docker, a Schema Registry, a JVM consumer or
+a human pressing Ctrl-C.
+
+- [1. Build and run locally](#1-build-and-run-locally)
+- [2. Manual test plan](#2-manual-test-plan)
+- [3. Releasing with GoReleaser](#3-releasing-with-goreleaser)
---
-# 1. Build and run locally
+## 1. Build and run locally
-## Prerequisites
+### Prerequisites
-- **Go 1.26+** — `go version`
-- **Docker** — only for the local cluster. `khaos simulate` against your own broker needs nothing else.
+- **Go 1.26+** -- `go version`. `go.mod` pins `go 1.26.5`.
+- **Docker** -- only for the local cluster. `khaos simulate` against your own broker needs
+ nothing else.
-That is the whole list. There is no Python, no `uv`, no virtualenv, and no librdkafka:
-the Kafka client is pure Go.
+That is the whole list. There is no Python, no `uv`, no virtualenv, and no librdkafka: the
+Kafka client is pure Go, which is also why section 3 can cross-compile five targets in one
+CI job.
-## Build
+### Build
```bash
cd ~/GoProjects/khaos
@@ -40,25 +50,31 @@ Install onto your PATH:
go install ./cmd/khaos # lands in $(go env GOPATH)/bin
```
-## The check script
+### The check script
-`./scripts/check.sh` is what CI runs: gofmt, vet, tests, static build, smoke test.
-Add `-r` for the race detector. **It needs no Docker** — the tests use an in-process
-Kafka broker (`kfake`).
+`./scripts/check.sh` is the local equivalent of the CI job: gofmt over `cmd` and
+`internal`, `go vet`, the test suite, a static `CGO_ENABLED=0` build, and a `--version`
+smoke test. Pass `-r` as the first argument for the race detector. **It needs no Docker**
+-- the tests run against `kfake`, an in-process broker that speaks the real Kafka protocol.
```bash
./scripts/check.sh # ~1 min
./scripts/check.sh -r # ~3 min, race detector
```
+`.github/workflows/ci.yml` inlines those same steps rather than calling the script, and
+adds two jobs the script does not have: `govulncheck` (advisory, `continue-on-error`) and a
+cross-compile of all five release targets to `/dev/null`. So a green `check.sh` is a strong
+signal, not a complete one.
+
---
-# 2. Manual test plan
+## 2. Manual test plan
Work through these in order. Each step says what to look for, so a wrong result is
obvious. Times assume a warm Docker.
-## Step 0 — automated suite first
+### Step 0 -- the automated suite first
```bash
./scripts/check.sh -r
@@ -66,7 +82,7 @@ obvious. Times assume a warm Docker.
**Expect:** `All checks passed.` If this fails, stop; nothing below will be meaningful.
-## Step 1 — no cluster needed
+### Step 1 -- no cluster needed
```bash
./khaos --version
@@ -77,11 +93,13 @@ obvious. Times assume a warm Docker.
./khaos validate ./scenarios/chaos/broker-chaos.yaml
```
-**Expect:** `list` prints a two-column table of 21 scenarios grouped into five categories,
-starting with the line `Available Scenarios` (the homebrew formula asserts that string).
-Every `validate` call prints `valid` per scenario and a closing `all N scenario(s) valid`,
-and exits 0 (`echo $?`). Bare `./khaos validate` covers all 21 and reports four warnings —
-warnings do not fail it.
+**Expect:** `list` prints a two-column table of 21 scenarios grouped into five categories
+(Traffic Patterns, Chaos Engineering, Event Flows, Serialization, Testing), starting with
+the line `Available Scenarios` -- the homebrew-core formula's test block asserts that
+string, so it is a compatibility surface, not decoration. Every `validate` call prints
+`valid` per scenario and a closing `all N scenario(s) valid`, and exits 0 (`echo $?`). Bare
+`./khaos validate` covers all 21 and reports four warnings -- two schemaless-serialization
+ones and two DLQ ones. Warnings do not fail it.
Check the exit codes, which scripts branch on:
@@ -93,10 +111,11 @@ Check the exit codes, which scripts branch on:
./khaos validate no/such/scenario; echo "exit=$?" # exit=1
```
-**Expect:** `2` for a bad invocation, `1` for a command that ran and failed. This is what
-Click did under the Python version.
+**Expect:** `2` for a bad invocation, `1` for a command that ran and failed. That split is
+what Click gave the Python version, and scripts in the wild depend on it;
+`cmd/khaos/cli_contract_test.go` pins it.
-Now prove validation actually reports everything at once:
+Now prove validation reports everything at once rather than stopping at the first problem:
```bash
cat > /tmp/bad.yaml <<'EOF'
@@ -111,33 +130,34 @@ EOF
./khaos validate /tmp/bad.yaml; echo "exit=$?"
```
-**Expect:** three separate errors — `partitions`, `replication_factor` and
-`producer_config.acks` — each with a **line number**, then a `1 of 1 scenario(s) invalid`
-tally and `exit=1`. Not one error — all of them. (Python had no line numbers; this is the
-one deliberate improvement.)
+**Expect:** three separate errors -- `partitions`, `replication_factor` and
+`producer_config.acks` -- each with a **line number**, then a `1 of 1 scenario(s) invalid`
+tally and `exit=1`. Not one error, all of them. (Python had no line numbers; this is the
+one deliberate improvement over its output.)
`--strict` additionally rejects keys no khaos version has ever read, which catches a typo
-in a field name rather than silently ignoring it:
+in a field name instead of silently ignoring it:
```bash
printf 'name: typo\ntopics:\n - name: orders\n partitons: 6\n' > /tmp/typo.yaml
-./khaos validate /tmp/typo.yaml; echo "lenient exit=$?"
-./khaos validate --strict /tmp/typo.yaml; echo "strict exit=$?"
+./khaos validate /tmp/typo.yaml; echo "lenient exit=$?" # valid, exit=0
+./khaos validate --strict /tmp/typo.yaml; echo "strict exit=$?" # Unknown field, exit=1
```
-## Step 2 — start the cluster
+### Step 2 -- start the cluster
```bash
./khaos cluster-up
./khaos cluster-status
```
-**Expect:** `cluster ready: 127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094`, then three
-brokers `running` on 9092/9093/9094.
+**Expect:** `✓ Kafka cluster ready 127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094`, then a
+table from `cluster-status` with three brokers `running` on 9092/9093/9094 (plus kafka-ui
+on 8080).
> **Port 8080 conflict.** The stack also starts `kafka-ui` on 8080. If something else holds
-> it (nocodb, for example) `cluster-up` fails and now tells you *which* port. Free it, or
-> ignore kafka-ui — the brokers work regardless.
+> it (nocodb, for example) `cluster-up` fails and names the port it could not bind. Free it,
+> or ignore kafka-ui -- the brokers work regardless.
`cluster-up` is idempotent; running it again is safe.
@@ -150,7 +170,7 @@ ZooKeeper mode uses the same ports and the same compose project, so it is a drop
./khaos cluster-down
```
-## Step 3 — a basic run
+### Step 3 -- a basic run
```bash
./khaos run traffic/high-throughput -d 15 -k
@@ -159,10 +179,11 @@ ZooKeeper mode uses the same ports and the same compose project, so it is a drop
`-k` keeps the cluster up for the following steps.
**Expect:** a live terminal UI with a topic table, counts climbing, lag near zero. After
-15s it exits and prints a summary. Roughly 60k produced. Errors should be **0**.
+15s it exits and prints a summary. Roughly 60k produced -- the scenario's two topics each
+run two producers at 1000 msg/s, and the rate is per producer. Errors should be **0**.
-The `LAG` column here is khaos's own produced−consumed count, exactly as the Python
-version reported it — no broker is asked anything. Step 6b covers the real one.
+The `LAG` column here is khaos's own produced-minus-consumed count, exactly as the Python
+version reported it; no broker is asked anything. Step 6b covers the real one.
Then the headless path, which is what runs in a container:
@@ -170,7 +191,7 @@ Then the headless path, which is what runs in a container:
./khaos run traffic/high-throughput -d 15 -k --tui off --log-json
```
-**Expect:** one JSON log line every 10s, then the summary. No TUI. This must work when
+**Expect:** one JSON log line every 10s, then the summary. No TUI. This must survive being
piped: `... --tui off | cat` should not corrupt anything.
A typo in either flag is rejected rather than silently falling back:
@@ -199,12 +220,12 @@ docker ps --filter name=kafka- # three brokers still up
./khaos cluster-down
```
-**Expect:** `stopping Kafka cluster...` on the first two, `Kafka cluster left running` on
-the third, and `exit=1` on the two failures. Leaking a three-broker cluster on every failed
-run is the most expensive thing this CLI could get wrong; `cmd/khaos/run_teardown_test.go`
-pins all four combinations in CI.
+**Expect:** `✓ Kafka cluster stopped` on the first two, `Kafka cluster left running ·
+khaos cluster-down to stop` on the third, and `exit=1` on the two failures. Leaking a
+three-broker cluster on every failed run is the most expensive thing this CLI could get
+wrong; `cmd/khaos/run_teardown_test.go` pins all four combinations in CI.
-## Step 4 — Ctrl-C actually works
+### Step 4 -- Ctrl-C stops the run
```bash
./khaos run traffic/high-throughput -k # -d defaults to 0 = run forever
@@ -212,13 +233,13 @@ pins all four combinations in CI.
Let it run ~10s, then press **Ctrl-C once**.
-**Expect:** it stops within a couple of seconds and prints a summary. Press Ctrl-C twice
-in quick succession and it dies immediately. Neither should hang.
+**Expect:** it stops within a couple of seconds and prints a summary. Press Ctrl-C twice in
+quick succession and it dies immediately. Neither should hang.
This is the specific defect the rewrite targets: in the Python version the render loop
owned the shutdown path, so a stalled UI could wedge an infinite run.
-## Step 5 — broker faults
+### Step 5 -- broker faults
```bash
cat > /tmp/fault.yaml <<'EOF'
@@ -246,7 +267,7 @@ EOF
**Expect:** events at ~8s (`Stopping kafka-2`) and ~20s (`Starting kafka-2`). Production
continues throughout; errors stay 0 because `acks: all` plus RF 3 survives one broker.
-Verify the broker really was killed:
+Confirm the container really went down, rather than only the event being logged:
```bash
docker ps --filter name=kafka- --format '{{.Names}}\t{{.Status}}'
@@ -254,7 +275,7 @@ docker ps --filter name=kafka- --format '{{.Names}}\t{{.Status}}'
**Expect:** `kafka-2` uptime is much lower than kafka-1/kafka-3.
-## Step 6 — client-side incidents
+### Step 6 -- client-side incidents
```bash
./khaos run chaos/rebalance-storm -d 80 -k --tui off # consumers torn down and recreated
@@ -264,12 +285,12 @@ docker ps --filter name=kafka- --format '{{.Names}}\t{{.Status}}'
Both durations are chosen to outlast the incident schedules in the YAML, which is easy to
get wrong: `rebalance-storm` waits `initial_delay_seconds: 15` and only then starts its
`every_seconds: 20` ticker, so the first rebalance lands at **T+35s** and the second at
-T+55s — a 40s run sees none at all. `throughput-drop` fires once at `at_seconds: 30`.
+T+55s -- a 40s run sees none at all. `throughput-drop` fires once at `at_seconds: 30`.
**Expect:** rebalance-storm ends with `rebalances 2` or more in the summary;
throughput-drop shows lag climbing from T+30s onwards.
-## Step 6b — real consumer-group lag
+### Step 6b -- real consumer-group lag
Off by default. Everything above ran with the self-reported `LAG` column and must keep
doing so; this step is the only one that asks the brokers.
@@ -278,12 +299,12 @@ doing so; this step is the only one that asks the brokers.
./khaos run chaos/throughput-drop -d 60 -k --lag-poll 5s
```
-**Expect:** the topic table now carries **two** lag columns, `LAG(SELF)` and
-`LAG(BROKER)`, and per-group rows carry their own broker figure. `LAG(BROKER)` is usually
-far larger than `LAG(SELF)` in short runs: khaos auto-commits every 5s, so a group that
-has read everything but committed nothing is genuinely behind by the whole log, and only
-the broker column knows that. A group whose row reads `unknown` was not measured — that
-is not a zero.
+**Expect:** the topic table now carries **two** lag columns, `LAG(SELF)` and `LAG(BROKER)`,
+and per-group rows carry their own broker figure. `LAG(BROKER)` is usually far larger than
+`LAG(SELF)` in short runs: khaos auto-commits every 5s (`autoCommitInterval` in
+`internal/kafka/consumer.go`), so a group that has read everything but committed nothing is
+genuinely behind by the whole log, and only the broker column knows that. A group whose row
+reads `unknown` was not measured -- that is not a zero.
Then prove it is off by default and that it never becomes load-bearing:
@@ -295,12 +316,12 @@ The failure path matters more than the happy one, because managed clusters routi
`DESCRIBE` on consumer groups. Point khaos at a cluster where the credentials lack that
right (or revoke it) and re-run with `--lag-poll 5s`:
-**Expect:** the run behaves *identically* — same throughput, same exit code, errors still
+**Expect:** the run behaves *identically* -- same throughput, same exit code, errors still
0. One warning is logged naming the group and the reason, **once**, not once per poll, and
-the broker column reads `unknown` for the whole run. Leave it running for a few minutes
-and confirm the warning does not repeat.
+the broker column reads `unknown` for the whole run. Leave it running for a few minutes and
+confirm the warning does not repeat.
-## Step 7 — flows
+### Step 7 -- flows
```bash
./khaos run flows/order-flow -d 20 -k --tui off
@@ -309,7 +330,7 @@ and confirm the warning does not repeat.
**Expect:** a flow section in the summary with `started`, `completed` and `messages`.
Completed should track started closely.
-## Step 8 — Avro and Protobuf against a real Schema Registry
+### Step 8 -- Avro and Protobuf against a real Schema Registry
```bash
./khaos cluster-up --schema-registry
@@ -321,7 +342,7 @@ curl -s localhost:8081/subjects # []
curl -s localhost:8081/subjects # ["orders-value","shipments-value"]
```
-Now the test that matters — can a **Java** consumer read what Go wrote? A wrong Confluent
+Now the test that matters: can a **Java** consumer read what Go wrote? A wrong Confluent
header or protobuf message index round-trips fine in Go and fails only on the JVM.
```bash
@@ -336,13 +357,13 @@ docker exec schema-registry kafka-protobuf-console-consumer \
--property schema.registry.url=http://localhost:8081
```
-**Expect:** three decoded JSON records from each. Note `created_at` is an **integer**
-(epoch millis, not ISO-8601) — that is Python's behaviour, deliberately preserved.
+**Expect:** three decoded JSON records from each. `created_at` comes out as an **integer**
+(epoch millis, not ISO-8601) -- that is Python's behaviour, deliberately preserved.
-This registry is open, which is the default path and must keep working with no extra
-flags. Step 8b covers the secured one.
+This registry is open, which is the default path and must keep working with no extra flags.
+Step 8b covers the secured one.
-## Step 8b — a Schema Registry that requires credentials
+### Step 8b -- a Schema Registry that requires credentials
Confluent Cloud and Aiven put the registry behind auth, which Python could not reach at
all. Stand up the same thing locally: nginx with basic auth, proxying the registry from
@@ -370,7 +391,10 @@ curl -s -o /dev/null -w '%{http_code}\n' localhost:8082/subjects # 401
curl -s -u sruser:srsecret localhost:8082/subjects # the subject list
```
-**1. No credentials — the error has to be diagnosable.**
+The compose project is always `khaos` (`localcluster.ProjectName`), which is where the
+`khaos_kafka-net` network name comes from.
+
+**1. No credentials -- the error has to be diagnosable.**
```bash
./khaos run serialization/avro-example -d 5 -k --tui off \
@@ -379,8 +403,8 @@ curl -s -u sruser:srsecret localhost:8082/subjects # the subject
**Expect:** a failure *before any message is produced*, naming the URL and both flags:
`schema registry at "http://localhost:8082" rejected the startup reachability check with
-HTTP 401 Unauthorized: this registry requires authentication but no credentials were
-given; pass --schema-registry-username and --schema-registry-password …`. A bare
+HTTP 401 Unauthorized: this registry requires authentication but no credentials were given;
+pass --schema-registry-username and --schema-registry-password ...`. A bare
`401 Unauthorized` here is a bug.
**2. Wrong password.**
@@ -395,7 +419,7 @@ given; pass --schema-registry-username and --schema-registry-password …`. A ba
`--schema-registry-password` and noting that on Confluent Cloud those are the **Schema
Registry** API key and secret, not the Kafka cluster's.
-**3. Correct credentials — a normal run.**
+**3. Correct credentials -- a normal run.**
```bash
./khaos run serialization/avro-example -d 10 -k --tui off \
@@ -405,7 +429,7 @@ Registry** API key and secret, not the Kafka cluster's.
curl -s -u sruser:srsecret localhost:8082/subjects # ["orders-value"]
```
-**Expect:** identical output to step 8 — the credentials are used for the startup probe,
+**Expect:** identical output to step 8 -- the credentials are used for the startup probe,
the schema registration and every fetch.
**4. Incoherent flags fail at startup, not on the first message.**
@@ -420,26 +444,34 @@ the schema registration and every fetch.
--schema-registry-ca-location /tmp/khaos-sr.conf
```
-**Expect:** three different errors — password required with username; token cannot be
-combined with basic auth; TLS files given against a URL that is not `https` (which would
-have connected in the clear with the CA silently ignored).
+**Expect:** three different errors -- password required with username; token cannot be
+combined with basic auth; TLS files given against a URL that is not `https`, which would
+otherwise have connected in the clear with the CA silently ignored.
```bash
docker rm -f sr-auth
```
-## Step 9 — external cluster path
+### Step 9 -- external cluster path
```bash
./khaos simulate traffic/high-throughput \
-b 127.0.0.1:9092 -d 10 --tui off
```
-**Expect:** identical behaviour to `run`, but broker-fault incidents report as *skipped*
-because khaos does not own the cluster. Try `./khaos simulate chaos/leadership-churn -b 127.0.0.1:9092 -d 50 --tui off`
-and look for the skip event rather than a failure.
+**Expect:** identical behaviour to `run`, but broker-fault incidents report as *skipped*,
+because khaos does not own the cluster and will not pretend to restart someone else's
+broker. `simulate` also requires `-b`: with no bootstrap servers it fails on that before it
+even looks at the scenario list.
-## Step 10 — multiple scenarios together
+```bash
+./khaos simulate chaos/leadership-churn -b 127.0.0.1:9092 -d 50 --tui off
+```
+
+**Expect:** a skip event at ~T+45s, where the scenario's `stop_broker` would have fired,
+rather than a failure.
+
+### Step 10 -- multiple scenarios together
```bash
./khaos run traffic/high-throughput traffic/consumer-lag -d 15 -k --tui off
@@ -447,7 +479,7 @@ and look for the skip event rather than a failure.
**Expect:** topics from both scenarios in one run.
-## Step 11 — tear down
+### Step 11 -- tear down
```bash
./khaos cluster-down
@@ -455,11 +487,12 @@ docker ps # no kafka-* containers
docker volume ls # no khaos_* volumes either
```
-**Expect:** `Kafka cluster stopped`. Schema Registry goes down with it if step 8 started it.
-Data volumes are kept by default; pass `--volumes`/`-v` to remove them too — though none of
-the bundled compose files declare a volume, so `docker volume ls` shows nothing either way.
+**Expect:** `✓ Kafka cluster stopped`. Schema Registry goes down with it if step 8 started
+it. Data volumes are kept by default; pass `--volumes`/`-v` to remove them too -- though
+none of the bundled compose files declares a volume, so `docker volume ls` shows nothing
+either way.
-## Step 12 — the container image
+### Step 12 -- the container image
```bash
docker build -t khaos:local .
@@ -467,14 +500,14 @@ docker run --rm khaos:local --version
docker run --rm khaos:local list
```
-**Expect:** builds with no C toolchain, and the image is tiny — scenarios and compose files
-are embedded in the binary.
+**Expect:** builds with no C toolchain, and the image is tiny -- scenarios and compose
+files are embedded in the binary, so nothing has to be copied in beside it.
---
-# 3. Releasing with GoReleaser
+## 3. Releasing with GoReleaser
-## What it does
+### What it does
On a pushed tag, GoReleaser reads `.goreleaser.yaml` and, in one run:
@@ -482,20 +515,24 @@ On a pushed tag, GoReleaser reads `.goreleaser.yaml` and, in one run:
windows/arm64 is excluded);
2. packs each into a `.tar.gz` (`.zip` on Windows) with README, LICENSE and CHANGELOG;
3. writes `checksums.txt`;
-4. generates a changelog from commit messages since the previous tag;
-5. builds **two container images** (amd64, arm64), pushes them to `ghcr.io`, and joins
- them under one multi-arch tag;
+4. generates a changelog from commit messages since the previous tag, dropping `docs:`,
+ `test:` and `chore:`;
+5. builds **two container images** (amd64, arm64), pushes them to `ghcr.io`, and joins them
+ under one multi-arch tag;
6. creates the **GitHub Release** and attaches everything.
Cross-compiling to five targets in one job is only possible because the Kafka client is
pure Go. With a cgo client each target would need its own C toolchain.
-## Credentials
+There is deliberately no `brews:` block: khaos is already in homebrew-core, and shipping a
+competing formula from a personal tap would give users two different `khaos` packages.
+
+### Credentials
**You need to set up nothing.** `.github/workflows/release.yml` uses only
-`secrets.GITHUB_TOKEN`, which GitHub Actions injects automatically. It covers both
-creating the release and pushing to `ghcr.io`, because ghcr accepts the Actions token for
-the repo's own namespace.
+`secrets.GITHUB_TOKEN`, which GitHub Actions injects automatically. It covers both creating
+the release and pushing to `ghcr.io`, because ghcr accepts the Actions token for the repo's
+own namespace.
The workflow declares the permissions it needs:
@@ -508,13 +545,13 @@ permissions:
One thing to check once, in the GitHub UI: **Settings → Actions → General → Workflow
permissions** must allow read *and* write. If it is read-only the release fails with a 403.
-## Cutting a release
+### Cutting a release
```bash
# 1. Make sure main is green
./scripts/check.sh -r
-# 2. Dry run — builds everything locally, publishes nothing
+# 2. Dry run -- builds everything locally, publishes nothing
go install github.com/goreleaser/goreleaser/v2@latest
goreleaser check # validate the config
goreleaser release --snapshot --clean
@@ -527,12 +564,13 @@ ls dist/ # inspect the artifacts
`--snapshot --clean` is the safe rehearsal: it does the whole build without needing a tag,
without touching GitHub, and without pushing images.
-`scripts/release.sh <version>` buckets `feat:`/`fix:`/`perf:`/`refactor:`/`docs:` commits
-since the last tag into a Keep a Changelog-style entry (skipping `chore:`/`ci:`/`test:`/
-`build:`/`style:` and merge commits), shows you the draft, and on confirmation commits it,
-pushes `main`, tags `vX.Y.Z`, and pushes the tag — which triggers the release workflow.
-Pass `--yes` to skip the confirmation prompt. It refuses to run off `main`, with a dirty
-tree, or if the tag already exists. The draft is mechanical, not narrative — read it before
-confirming and hand-edit `CHANGELOG.md` afterward if a bullet needs better wording.
+`scripts/release.sh <version>` takes the version without a leading `v`. It buckets
+`feat:`/`fix:`/`perf:`/`refactor:`/`docs:` commits since the last tag into a Keep a
+Changelog-style entry (skipping merge commits and anything else, which covers
+`chore:`/`ci:`/`test:`/`build:`/`style:`), shows you the draft, and on confirmation commits
+it, pushes `main`, tags `vX.Y.Z`, and pushes the tag. Pass `--yes` to skip the confirmation
+prompt. It refuses to run off `main`, with a dirty tree, or if the tag already exists. The
+draft is mechanical, not narrative -- read it before confirming and hand-edit `CHANGELOG.md`
+afterward if a bullet needs better wording.
The tag push triggers the release workflow above. Watch it under Actions.
diff --git a/cmd/khaos/cli_contract_test.go b/cmd/khaos/cli_contract_test.go
index 5b13fc9..b145801 100644
--- a/cmd/khaos/cli_contract_test.go
+++ b/cmd/khaos/cli_contract_test.go
@@ -13,8 +13,13 @@ import (
"github.com/spf13/cobra"
)
-// The CLI surface is a compatibility contract: these flags and shorthands are what the
-// README documents, so scripts in the wild depend on them.
+// The CLI surface is a compatibility contract: the flags, shorthands, defaults, exit
+// codes and stream discipline pinned in this file are what the README documents, so
+// scripts in the wild depend on every one of them.
+
+// --duration takes either a bare count of seconds or a Go duration string, so a user who
+// reaches for `-d 60` and one who reaches for `-d 90s` both get what they meant, and a
+// value that is neither is rejected rather than quietly read as zero.
func TestDurationAcceptsSecondsAndDurations(t *testing.T) {
t.Parallel()
tests := []struct {
@@ -151,7 +156,8 @@ func TestCommandSetPreserved(t *testing.T) {
}
}
-// A LIST of scenarios runs together in one invocation.
+// Several scenarios named in one invocation are merged into a single run rather than the
+// first one winning: their topics, incidents and flows all have to end up in one engine.
func TestMultipleScenariosRunTogether(t *testing.T) {
t.Parallel()
brokers := fakeBrokers(t)
diff --git a/cmd/khaos/cluster.go b/cmd/khaos/cluster.go
index 70f2042..a877680 100644
--- a/cmd/khaos/cluster.go
+++ b/cmd/khaos/cluster.go
@@ -83,10 +83,10 @@ func newClusterDownCmd() *cobra.Command {
)
cmd := &cobra.Command{
Use: "cluster-down",
- Short: "Stop the local Kafka cluster and remove its volumes",
+ Short: "Stop the local Kafka cluster",
Long: "Stop the bundled Kafka cluster.\n\n" +
- "Pass --volumes to remove data volumes as well. Note that the bundled compose\n" +
- "files declare no volumes -- the brokers keep their logs inside the container --\n" +
+ "Pass --volumes to remove data volumes as well. The bundled compose files\n" +
+ "declare no volumes -- the brokers keep their logs inside the container --\n" +
"so today the next `cluster-up` starts empty either way.",
Args: usageArgs(cobra.NoArgs),
RunE: func(c *cobra.Command, _ []string) error {
@@ -94,7 +94,6 @@ func newClusterDownCmd() *cobra.Command {
if err != nil {
return err
}
- // --volumes/-v: volumes are kept unless asked for.
err = spin(c.OutOrStdout(), "Stopping Kafka cluster", "",
func() error { return cl.Down(c.Context(), volumes) })
if err != nil {
diff --git a/cmd/khaos/help.go b/cmd/khaos/help.go
index 115e146..c9d5025 100644
--- a/cmd/khaos/help.go
+++ b/cmd/khaos/help.go
@@ -15,6 +15,12 @@ func setHelpStyle(root *cobra.Command) {
root.SetUsageFunc(styledUsage)
}
+// styledHelp replaces cobra's help template: the command path as a title, then Long (or
+// Short when a command has no Long), then the usage block.
+//
+// It writes to c.OutOrStdout() rather than to os.Stdout, which is what lets the root
+// command send a bare `khaos` invocation's help to stderr instead -- it swaps that writer
+// before calling Help.
func styledHelp(c *cobra.Command, _ []string) {
w := c.OutOrStdout()
fmt.Fprintln(w, styTitle.Render(c.CommandPath()))
@@ -34,6 +40,9 @@ func styledHelp(c *cobra.Command, _ []string) {
}
}
+// styledUsage backs cobra's Usage()/UsageString() and writes to stderr. The root sets
+// SilenceUsage, so a bad invocation prints the error alone; the same block reached
+// deliberately through --help goes to stdout, via styledHelp.
func styledUsage(c *cobra.Command) error {
fmt.Fprint(c.OutOrStderr(), styledUsageString(c))
return nil
@@ -111,6 +120,8 @@ func colorizeFlagNames(usages string) string {
})
}
+// rpad mirrors the unexported helper of the same name in cobra's default usage template,
+// so the additional-help-topics block lines up the way cobra would have rendered it.
func rpad(s string, padding int) string {
return fmt.Sprintf(fmt.Sprintf("%%-%ds", padding), s)
}
diff --git a/cmd/khaos/main.go b/cmd/khaos/main.go
index 81ea3e0..b87fa56 100644
--- a/cmd/khaos/main.go
+++ b/cmd/khaos/main.go
@@ -74,6 +74,8 @@ func usageArgs(fn cobra.PositionalArgs) cobra.PositionalArgs {
}
}
+// newRootCmd builds the whole command tree. Tests call it directly instead of exec'ing
+// the binary, which is why nothing below reaches for os.Stdout or os.Args by name.
func newRootCmd() *cobra.Command {
root := &cobra.Command{
Use: "khaos",
@@ -96,8 +98,9 @@ func newRootCmd() *cobra.Command {
},
}
- // Unknown or malformed flags are Click UsageErrors too. FlagErrorFunc is inherited by
- // every subcommand, so setting it once on the root covers the whole tree.
+ // An unknown or malformed flag is a bad invocation as well, so it exits 2 like the
+ // rest. FlagErrorFunc is inherited by every subcommand, so setting it once on the
+ // root covers the whole tree.
root.SetFlagErrorFunc(func(_ *cobra.Command, err error) error {
return usageError{err}
})
diff --git a/cmd/khaos/main_test.go b/cmd/khaos/main_test.go
index 5f05890..a6eb3a8 100644
--- a/cmd/khaos/main_test.go
+++ b/cmd/khaos/main_test.go
@@ -50,8 +50,8 @@ func runCLI(t *testing.T, ctx context.Context, args ...string) (string, error) {
// these tests assert that the whole pipeline runs and tears down cleanly, not that any
// particular throughput is reached. Every incident in the shipped chaos scenarios is
// scheduled well past this (T+15s at the earliest), so a longer run would not cover more
-// of them either -- only the schedule-and-shutdown path, which TestIncidentSchedule covers
-// directly.
+// of them either. TestIncidentFiresEndToEnd below covers an incident actually firing,
+// using a scenario written for the purpose instead.
const runDuration = "2s"
// TestSimulateAgainstFakeCluster runs several shipped scenarios end to end through the
diff --git a/cmd/khaos/run.go b/cmd/khaos/run.go
index f0e6e7c..a25ff94 100644
--- a/cmd/khaos/run.go
+++ b/cmd/khaos/run.go
@@ -49,6 +49,8 @@ type runFlags struct {
metricsAddr string
}
+// bind registers the flags run and simulate have in common. They are declared once, here,
+// so the two commands cannot drift apart on a default or a shorthand.
func (f *runFlags) bind(c *cobra.Command) {
// --duration/-d accepts a bare integer of seconds (DEFAULT 0, meaning "run until
// Ctrl-C") or a Go duration string like "10m", so `-d 60` and `-d 90s` both work; see
@@ -316,7 +318,6 @@ func (d *durationValue) Set(v string) error {
func (d *durationValue) Type() string { return "duration" }
-// registry assembles the Schema Registry configuration from the flags.
func (f *runFlags) registry() codec.RegistryConfig {
return codec.RegistryConfig{
URL: f.schemaRegistryURL,
@@ -361,7 +362,7 @@ func execute(ctx context.Context, stdout, stderr io.Writer, names []string, kcfg
}
// A registry is only built when --metrics-addr is set: an idle Metrics struct nobody
- // scrapes just adds a WithLabelValues call to every hot-path increment for nothing.
+ // scrapes adds a WithLabelValues call to every hot-path increment for nothing.
var metricsReg *prometheus.Registry
var metrics *telemetry.Metrics
if f.metricsAddr != "" {
@@ -589,6 +590,8 @@ func parseMode(mode string) (kraft bool, err error) {
// `simulate`.
var errNoScenario = errors.New("please specify at least one scenario (use `khaos list` to see them)")
+// splitServers splits a comma-separated broker list, trimming each entry and dropping
+// empty ones, so a stray space or trailing comma in `-b "a:9092, b:9092,"` costs nothing.
func splitServers(s string) []string {
parts := strings.Split(s, ",")
out := make([]string, 0, len(parts))
diff --git a/cmd/khaos/run_teardown_test.go b/cmd/khaos/run_teardown_test.go
index 10acef6..33b9f00 100644
--- a/cmd/khaos/run_teardown_test.go
+++ b/cmd/khaos/run_teardown_test.go
@@ -13,10 +13,13 @@ import (
)
// fakeCluster stands in for the Docker-backed localcluster.Cluster so `run`'s teardown
-// path can be exercised in CI. Every field is atomic because the engine may call
-// StopBroker/StartBroker from its own goroutines while the test reads the counters.
+// path can be exercised in CI.
+//
+// The four call counters are atomic because the engine drives StopBroker and StartBroker
+// from its own goroutines while the test reads them. The plain fields above them are
+// touched only by the command goroutine, through Up, Down and Running.
type fakeCluster struct {
- running bool // whether BootstrapServers succeeds before Up is called
+ running bool // is the cluster up: set at construction, then flipped by Up and Down
brokers string
upErr error
downErr error
diff --git a/cmd/khaos/scenarios.go b/cmd/khaos/scenarios.go
index 0466d21..01a369d 100644
--- a/cmd/khaos/scenarios.go
+++ b/cmd/khaos/scenarios.go
@@ -52,12 +52,14 @@ func printDiagnostics(w io.Writer, name string, diags scenario.Diagnostics) {
}
}
-// categoryInfo is the display name and blurb for each scenario directory.
-//
-// The ORDER matters: categories sort by their position in categoryOrder and fall back to
-// a title-cased directory name for anything unlisted.
+// categoryOrder fixes the order of the headings in `khaos list`. A directory that is not
+// named here sorts last, under a title-cased version of its own name, so dropping a new
+// scenario directory into scenarios/ still lists it. list_contract_test.go pins both
+// halves of that.
var categoryOrder = []string{"traffic", "chaos", "flows", "serialization"}
+// categoryInfo is the heading and the one-line blurb for each known scenario directory:
+// {heading, blurb}.
var categoryInfo = map[string][2]string{
"traffic": {"Traffic Patterns", "Basic traffic generation scenarios"},
"chaos": {"Chaos Engineering", "Fault injection and incident scenarios"},
@@ -80,7 +82,6 @@ func newListCmd() *cobra.Command {
return nil
}
- // Group by leading directory.
byCategory := make(map[string][]string)
for name := range found {
category, _, ok := strings.Cut(name, "/")
@@ -135,6 +136,9 @@ func newListCmd() *cobra.Command {
// tableWidth caps output at the terminal width so a long description wraps instead of
// blowing the table past the edge of the window. 100 is the fallback when stdout is not a
// terminal, which keeps piped output stable rather than dependent on the environment.
+//
+// colorEnabled doubles as the is-a-terminal test, so NO_COLOR and TERM=dumb pin the
+// width at 100 as well.
func tableWidth() int {
if !colorEnabled {
return 100
@@ -175,7 +179,6 @@ func newValidateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "validate [scenario...]",
Short: "Validate scenario files",
- // With no arguments every bundled scenario is checked.
Long: "Validate scenarios without running them.\n\n" +
"A scenario may be a bundled name (e.g. traffic/high-throughput) or a path to a\n" +
"YAML file. With no arguments every bundled scenario is checked.\n\n" +
diff --git a/cmd/khaos/style.go b/cmd/khaos/style.go
index 95c4742..daff92c 100644
--- a/cmd/khaos/style.go
+++ b/cmd/khaos/style.go
@@ -14,7 +14,10 @@ import (
// the same palette the live TUI uses, so every khaos screen reads as one product.
//
// Colour is suppressed when stdout is not a terminal, so piping into a file or another
-// process yields clean text with no escape sequences.
+// process yields clean text with no escape sequences. The decision is made once, at init,
+// from the process's real stdout rather than from whatever writer a command was handed --
+// which is why `go test` sees plain text and the contract tests can match on it with
+// strings.Contains.
var (
colorEnabled = detectColor()
diff --git a/internal/codec/avro.go b/internal/codec/avro.go
index d489146..9af8055 100644
--- a/internal/codec/avro.go
+++ b/internal/codec/avro.go
@@ -16,8 +16,8 @@ const avroNamespace = "khaos.generated"
// avroPrimitive maps khaos field types to their Avro type name.
//
-// Note that "int" maps to Avro "long" and "float" to Avro "double". That is not
-// a mistake to be corrected: khaos has always written 64-bit values, and
+// "int" maps to Avro "long" and "float" to Avro "double", which is not a
+// mistake waiting to be corrected: khaos has always written 64-bit values, and
// narrowing them now would break every consumer holding an older reader schema.
var avroPrimitive = map[string]string{
scenario.FieldString: "string",
@@ -254,6 +254,8 @@ func avroDecodedValue(s avroSchemaNode, v any) any {
if !ok || len(wrapped) != 1 {
return v
}
+ // wrapped has exactly one entry, checked above; ranging is how to reach
+ // it. Every path inside returns, so this loop never takes a second turn.
for branchName, branchVal := range wrapped {
for _, branch := range s.union {
if branchMatchesName(*branch, branchName) {
diff --git a/internal/codec/codec.go b/internal/codec/codec.go
index e7b57ed..32d5dbf 100644
--- a/internal/codec/codec.go
+++ b/internal/codec/codec.go
@@ -45,7 +45,10 @@ const (
// 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
// never re-registered, so pointing khaos at an existing subject never mutates
-// it.
+// it. The subject also wins outright over the topic's own message_schema: both
+// data_format and the field list come from the fetched schema, so a topic that
+// declares data_format: json alongside a registry Avro subject produces Avro.
+// Anything else would encode records the subject's consumers cannot read.
func New(ctx context.Context, t scenario.Topic, reg *Registry) (Codec, error) {
format := t.MessageSchema.DataFormat
fields := t.MessageSchema.Fields
diff --git a/internal/codec/codec_test.go b/internal/codec/codec_test.go
index 41b0955..4f7df4f 100644
--- a/internal/codec/codec_test.go
+++ b/internal/codec/codec_test.go
@@ -105,6 +105,9 @@ func TestNewWithoutRegistryEmitsBareBytes(t *testing.T) {
}
}
+// schema_provider: registry with no registry configured has to fail while the topic is
+// being built. Falling back to JSON instead would produce records no consumer of that
+// subject can read, and nothing would say so.
func TestNewRegistryProviderWithoutRegistry(t *testing.T) {
topic := topicWith("orders", formatAvro, nil)
topic.SchemaProvider = "registry"
diff --git a/internal/codec/convert.go b/internal/codec/convert.go
index a89ad21..e9b2911 100644
--- a/internal/codec/convert.go
+++ b/internal/codec/convert.go
@@ -139,9 +139,9 @@ func avroFieldToField(entry map[string]any) (scenario.Field, bool) {
return convertedField(name, scenario.FieldString), true
}
-// avroItemField converts an array's item type. It deliberately handles less
-// than avroFieldToField does: an array of logical types or an array of arrays
-// degrades to the underlying primitive or to a string.
+// avroItemField converts an array's item type. It deliberately covers less
+// ground than avroFieldToField: an array of logical types or an array of
+// arrays degrades to the underlying primitive or to a string.
func avroItemField(name string, items any) scenario.Field {
if s, ok := items.(string); ok {
if mapped, ok := avroFieldTypes[s]; ok {
@@ -232,7 +232,6 @@ func protoMessageFields(md protoreflect.MessageDescriptor, seen map[protoreflect
return out
}
-// protoFieldToField converts one protobuf field.
func protoFieldToField(fd protoreflect.FieldDescriptor, seen map[protoreflect.FullName]bool) scenario.Field {
name := string(fd.Name())
switch {
diff --git a/internal/codec/convert_test.go b/internal/codec/convert_test.go
index b34fa59..86da1b7 100644
--- a/internal/codec/convert_test.go
+++ b/internal/codec/convert_test.go
@@ -217,8 +217,9 @@ message Node {
}
}
-// An unparseable .proto is now a real error instead of a silently truncated
-// regex match.
+// A .proto that does not compile must fail loudly. Field extraction used to be a regex
+// over the source text, which quietly returned a short field list and then generated data
+// that did not match the subject's schema.
func TestProtoFieldsFromSourceRejectsGarbage(t *testing.T) {
if _, err := protoFieldsFromSource(context.Background(), "this is not a proto file"); err == nil {
t.Error("expected a compile error")
diff --git a/internal/codec/doc.go b/internal/codec/doc.go
index e0ca30e..61009df 100644
--- a/internal/codec/doc.go
+++ b/internal/codec/doc.go
@@ -1,6 +1,16 @@
// Package codec turns generated message documents into Kafka record bytes and
-// back, for the four wire shapes khaos supports: JSON, Avro (inline schema or
-// Schema Registry) and Protobuf (inline schema or Schema Registry).
+// back, in the three formats khaos speaks: JSON, Avro and Protobuf. Avro and
+// Protobuf each come two ways -- a schema khaos generates from the scenario's
+// field list, or one fetched verbatim from a Schema Registry subject -- and
+// both carry the Confluent wire header once a registry is configured. JSON is
+// always bare UTF-8 with no schema and no header.
+//
+// [New] is the entry point: it resolves all of that once per topic and returns
+// the single [Codec] that topic uses for the whole run. internal/engine builds
+// one Codec per topic, converts each document internal/generate produced into a
+// [Doc], and hands that same Codec to every producer on the topic -- which is
+// why a Codec has to be immutable once constructed. [Registry] is the Schema
+// Registry client the fetch-and-register paths go through.
//
// Every string that reaches the wire -- generated Avro schema JSON, generated
// .proto source, mangled type names, the Confluent header layout -- must stay
@@ -27,7 +37,6 @@ type Doc struct {
vals map[string]any
}
-// NewDoc returns an empty Doc.
func NewDoc() *Doc {
return &Doc{vals: make(map[string]any)}
}
@@ -55,7 +64,6 @@ func (d *Doc) Keys() []string {
return out
}
-// Len returns the number of keys.
func (d *Doc) Len() int { return len(d.keys) }
// MarshalJSON writes the document as a JSON object with keys in insertion
diff --git a/internal/codec/proto.go b/internal/codec/proto.go
index ebe54dc..5fdcc93 100644
--- a/internal/codec/proto.go
+++ b/internal/codec/proto.go
@@ -98,9 +98,10 @@ func (c *protoCodec) Decode(b []byte) (*Doc, error) {
return nil, fmt.Errorf("codec: decode protobuf: %w", err)
}
- // UseProtoNames keeps field names as declared in the schema; note its
- // consequences: 64-bit integers come back as decimal strings and bytes as
- // base64.
+ // UseProtoNames keeps field names as declared in the schema instead of
+ // lowerCamelCasing them. Routing through protojson at all costs two points
+ // of fidelity that the round-trip tests pin rather than hide: 64-bit
+ // integers come back as decimal strings and bytes as base64.
raw, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(msg)
if err != nil {
return nil, fmt.Errorf("codec: protobuf to json: %w", err)
diff --git a/internal/codec/proto_source.go b/internal/codec/proto_source.go
index 8f66eaf..d9fde87 100644
--- a/internal/codec/proto_source.go
+++ b/internal/codec/proto_source.go
@@ -104,9 +104,10 @@ func writeProtoMessage(b *strings.Builder, name string, fields []scenario.Field,
// protoArrayItemType resolves the element type of a repeated field, declaring
// a nested message for arrays of objects.
//
-// Note the fallthrough: an array whose items are an enum, or an array with no
-// items at all, becomes `repeated string` -- only "object" gets special-cased,
-// everything else falls back to string.
+// Only "object" is special-cased. An array whose items are an enum, and an
+// array with no items at all, both become `repeated string`; that degradation
+// is baked into the registered schema text, so widening it later changes the
+// .proto every existing scenario generates.
func protoArrayItemType(nested *strings.Builder, f scenario.Field, depth int) (string, error) {
if f.Items == nil {
return "string", nil
diff --git a/internal/codec/registry.go b/internal/codec/registry.go
index 7083f29..43cb748 100644
--- a/internal/codec/registry.go
+++ b/internal/codec/registry.go
@@ -318,6 +318,12 @@ func (r *Registry) FieldsFor(ctx context.Context, subject string) (string, []sce
}
// fetch returns the cached schema for a subject, fetching it on first use.
+//
+// The mutex is released before the network call rather than held across it, so
+// one slow subject lookup cannot block every other caller. Two callers racing
+// on the same cold subject therefore both fetch, and the second overwrites the
+// first: a subjectSchema is read-only once built, so the duplicate request is
+// the whole cost.
func (r *Registry) fetch(ctx context.Context, subject string) (*subjectSchema, error) {
r.mu.Lock()
cached, ok := r.subjects[subject]
diff --git a/internal/codec/registry_auth_test.go b/internal/codec/registry_auth_test.go
index 545f00c..e0d4cfc 100644
--- a/internal/codec/registry_auth_test.go
+++ b/internal/codec/registry_auth_test.go
@@ -55,8 +55,9 @@ func (a *authRecorder) seen() []string {
return append([]string(nil), a.headers...)
}
-// The credentials must reach the registry on the wire, and -- the point of DEFAULTS
-// UNCHANGED -- a config with only a URL must send no Authorization header at all.
+// The credentials must reach the registry on the wire, and a config carrying nothing but
+// a URL must still send no Authorization header at all: adding authentication support must
+// not change a single byte of what an unauthenticated khaos run puts on the wire.
func TestRegistryAuthSendsHeader(t *testing.T) {
tests := []struct {
name string
@@ -415,8 +416,8 @@ func TestRegistryTLSConfigFromPEMFiles(t *testing.T) {
})
}
-// End to end over real TLS: the CA file must actually be what lets the probe succeed, and
-// a client certificate must actually be presented.
+// End to end over real TLS: the CA file must be what lets the probe succeed, and a
+// configured client certificate must actually reach the server's handshake.
func TestRegistryOverTLS(t *testing.T) {
ca := newTestCA(t)
dir := t.TempDir()
diff --git a/internal/codec/registry_test.go b/internal/codec/registry_test.go
index ec66a5f..f5b0e45 100644
--- a/internal/codec/registry_test.go
+++ b/internal/codec/registry_test.go
@@ -41,6 +41,8 @@ func newFakeRegistry(t *testing.T) (*srfake.Registry, *Registry) {
return fake, reg
}
+// A registry that cannot be reached is a startup error, not a surprise on the first
+// serialised message: NewRegistry probes before returning a client.
func TestNewRegistryRejectsUnreachable(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/engine/consumer.go b/internal/engine/consumer.go
index f293527..3a11834 100644
--- a/internal/engine/consumer.go
+++ b/internal/engine/consumer.go
@@ -69,6 +69,12 @@ func (g *pauseGate) wait(ctx context.Context) error {
}
// Consumer polls one topic as part of a consumer group, optionally simulating failures.
+//
+// Whether it commits at all depends on failure simulation. With it off, the client
+// auto-commits every 5s and this type never calls CommitRecords. With it on,
+// kafka.NewConsumer disables auto-commit and committing becomes maybeCommit's job, which
+// is what lets a simulated failure withhold an offset and have the broker redeliver it
+// on the next rebalance.
type Consumer struct {
ID scenario.ID
Topic string
@@ -142,10 +148,10 @@ func (c *Consumer) SetDelay(ms int) { c.delayMS.Store(int64(ms)) }
// Pause stops consuming without tearing the consumer down.
func (c *Consumer) Pause() { c.gate.pause() }
-// Resume unblocks a paused consumer; the original goroutine simply continues.
+// Resume unblocks a paused consumer. The original goroutine carries on from where it
+// parked; no new goroutine is started.
func (c *Consumer) Resume() { c.gate.resume() }
-// Paused reports whether this consumer is currently parked.
func (c *Consumer) Paused() bool { return c.gate.paused() }
// Run consumes until ctx is cancelled.
@@ -205,8 +211,8 @@ func (c *Consumer) handle(ctx context.Context, rec *kgo.Record) {
}
// Failure simulation: roll for failure, dispatch on on_failure, and only commit on
- // success. The commit itself is subject to an independent commit_failure_rate that
- // "fails" simply by not committing.
+ // success. The commit is then subject to an independent commit_failure_rate whose
+ // "failure" is declining to commit rather than an error from the broker.
attempts := 0
for {
if c.rnd.Float64() >= c.Conf.FailureRate {
@@ -261,6 +267,11 @@ func (c *Consumer) maybeCommit(ctx context.Context, rec *kgo.Record) {
}
}
+// sendDLQ routes a failed record to the dead-letter topic.
+//
+// A DLQ write that itself fails counts as a consume error rather than a DLQ delivery,
+// which is what surfaces the usual cause: on a cluster with auto-creation off, nothing
+// created "{topic}-dlq". See dlqProducer.
func (c *Consumer) sendDLQ(ctx context.Context, rec *kgo.Record) {
if c.dlq == nil {
return
diff --git a/internal/engine/engine.go b/internal/engine/engine.go
index 8b27dc4..7fb34d6 100644
--- a/internal/engine/engine.go
+++ b/internal/engine/engine.go
@@ -1,3 +1,26 @@
+// Package engine runs a scenario: it builds the producers, consumers and flows the
+// scenario describes, drives them against a Kafka cluster, applies the incidents
+// scheduled against them, and reports what happened.
+//
+// Three entry points, in the order a run uses them. New does the setup I/O -- topic
+// creation, codec construction, schema registration, client dials -- so an unusable
+// scenario or an unreachable cluster is diagnosed before any traffic exists. Run owns the
+// run's goroutines for its whole lifetime and tears them down under a hard deadline.
+// Snapshot is how a run is read from outside: a fully-owned value a caller polls on its
+// own schedule (Healthy backs /healthz alongside it).
+//
+// The concurrency shape is flat and has no worker pool. One goroutine per producer, per
+// consumer and per flow runner, plus the incident scheduler and -- only when --lag-poll
+// asked for it -- the lag poller, all members of one errgroup that Run owns. Consumers
+// created mid-run by a rebalance incident join that same group through Engine.pending, so
+// nothing in a run is unowned or unawaited.
+//
+// Neighbours: internal/scenario supplies the validated model and expands each incident
+// into commands; internal/kafka builds the clients; internal/generate and internal/codec
+// build and encode payloads; internal/telemetry receives the Prometheus counters. Nothing
+// here knows a TUI exists -- cmd/khaos and internal/tui are consumers of Snapshot and
+// nothing else, so a wedged renderer cannot apply backpressure to a run. The one write to
+// a terminal is teardown's goroutine dump to stderr when the shutdown deadline is blown.
package engine
import (
@@ -148,6 +171,9 @@ type topicMeta struct {
groups []string
}
+// flowCounters are the hot-path counters for one flow. Separate from counters because a
+// flow is measured in instances -- issued, completed, still in flight -- rather than in
+// records.
type flowCounters struct {
started atomic.Int64
completed atomic.Int64
@@ -310,7 +336,7 @@ func (e *Engine) build(ctx context.Context) error {
r, err := codec.NewRegistryWithConfig(rc)
if err != nil {
// The codec error already names the URL and, for a 401/403, which flag is
- // probably wrong. Repeating the URL here just doubled it in the output.
+ // probably wrong. Repeating the URL here only doubled it in the output.
return fmt.Errorf("schema registry: %w", err)
}
reg = r
@@ -331,6 +357,11 @@ func (e *Engine) build(ctx context.Context) error {
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
@@ -490,7 +521,7 @@ func (e *Engine) recreateConsumer(ctx context.Context, groupID string, topics []
// awaited at shutdown.
//
// If the run is already shutting down nobody is reading pending. The consumer is
- // registered either way, so drain still closes its client; it simply never polls.
+ // registered either way, so drain still closes its client; it never polls.
if e.pending != nil {
select {
case e.pending <- c:
@@ -507,6 +538,11 @@ func (e *Engine) trackClient(c *kgo.Client) {
}
// rngFor derives a deterministic per-component RNG from the run seed.
+//
+// The stream is keyed by the (kind, name, index) tuple rather than drawn in construction
+// order, so adding a producer to one topic does not shift the values every other
+// component generates. That is what makes --seed reproducible across scenario edits and
+// not only across identical reruns.
func (e *Engine) rngFor(kind, name string, index int) *rand.Rand {
h := uint64(14695981039346656037)
mix := func(s string) {
diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go
index a8be431..c424329 100644
--- a/internal/engine/engine_test.go
+++ b/internal/engine/engine_test.go
@@ -29,9 +29,10 @@ func TestMain(m *testing.M) {
)
}
-// newFakeCluster starts an in-process Kafka speaking the real protocol: millisecond
-// startup, no Docker, real wire protocol, making the engine's whole pipeline testable in
-// CI.
+// newFakeCluster starts an in-process broker that speaks the real Kafka wire protocol. It
+// boots in milliseconds and needs no Docker, which is what lets the engine's whole
+// pipeline -- produce, consume, commit, rebalance -- be exercised on every `go test` run
+// rather than only where a cluster happens to be available.
func newFakeCluster(t *testing.T) []string {
t.Helper()
c, err := kfake.NewCluster(kfake.NumBrokers(1), kfake.AllowAutoTopicCreation())
@@ -346,7 +347,6 @@ 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
diff --git a/internal/engine/flow.go b/internal/engine/flow.go
index 99208f5..6072712 100644
--- a/internal/engine/flow.go
+++ b/internal/engine/flow.go
@@ -103,7 +103,7 @@ func (f *flowRunner) Run(ctx context.Context) error {
}
// Acquire before issuing, when bounded. Unbounded (the default) skips this
- // entirely and instances simply accumulate.
+ // entirely and instances accumulate.
if f.concurrency != nil {
select {
case f.concurrency <- struct{}{}:
@@ -190,7 +190,10 @@ func (f *flowRunner) emit(ctx context.Context, msgs []generate.FlowMessage) {
f.stats.completed.Add(1)
}
-// buildFlow constructs the runner for one flow.
+// buildFlow registers one flow: its generator, its own producer client, and its counters.
+//
+// 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(f scenario.Flow) error {
gen, err := generate.NewFlowGen(f, e.rngFor("flow", f.Name, 0), generate.BoundFillAttempts(cardinalityFillAttempts))
if err != nil {
diff --git a/internal/engine/flow_test.go b/internal/engine/flow_test.go
index 71e6e00..f58c34f 100644
--- a/internal/engine/flow_test.go
+++ b/internal/engine/flow_test.go
@@ -25,6 +25,8 @@ func newStrictFakeCluster(t *testing.T) []string {
return c.ListenAddrs()
}
+// twoStepFlow is the smallest flow that proves correlation: two steps on two topics, so a
+// completed instance means both records were produced in order under one correlation id.
func twoStepFlow(name string, secondStepDelayMS int) scenario.Flow {
return scenario.Flow{
Name: name,
diff --git a/internal/engine/incident_test.go b/internal/engine/incident_test.go
index cac56f8..282d11a 100644
--- a/internal/engine/incident_test.go
+++ b/internal/engine/incident_test.go
@@ -13,7 +13,9 @@ import (
func intPtr(v int) *int { return &v }
-// consumerIDSet is the set of ids currently registered.
+// consumerIDSet snapshots which consumers are registered, so a before/after comparison
+// can tell a replacement apart from a survivor. An id is never reused, which is what
+// makes the comparison meaningful.
func consumerIDSet(e *Engine) map[scenario.ID]bool {
out := make(map[scenario.ID]bool)
for _, c := range e.reg.allConsumers() {
diff --git a/internal/engine/lag_test.go b/internal/engine/lag_test.go
index 5bf0fe5..8930e01 100644
--- a/internal/engine/lag_test.go
+++ b/internal/engine/lag_test.go
@@ -91,7 +91,6 @@ func pollerFor(t *testing.T, e *Engine, src lagSource) *lagPoller {
}
}
-// countEvents reports how many events in the ring contain substr.
func countEvents(e *Engine, substr string) int {
n := 0
for _, ev := range e.events.snapshot() {
@@ -102,6 +101,10 @@ func countEvents(e *Engine, substr string) int {
return n
}
+// TestLagPollTimeoutIsBounded pins both ends of the clamp. The interval is the user's
+// knob and the timeout is derived from it, so an unclamped derivation turns --lag-poll
+// 100ms into a deadline every real cluster misses, and --lag-poll 1h into a request that
+// can hang for an hour.
func TestLagPollTimeoutIsBounded(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/engine/producer.go b/internal/engine/producer.go
index 6fce2f4..f4b943d 100644
--- a/internal/engine/producer.go
+++ b/internal/engine/producer.go
@@ -36,6 +36,9 @@ type Producer struct {
dupRate float64
rnd *rand.Rand
+ // stats is this producer's own tally, topicC the shared per-topic one. Only topicC
+ // reaches Snapshot -- nothing reads a single producer's counters today, and no
+ // per-producer row is rendered anywhere.
stats *counters
topicC *counters
events *eventRing
diff --git a/internal/engine/registry.go b/internal/engine/registry.go
index 9ea3a1e..98a03ae 100644
--- a/internal/engine/registry.go
+++ b/internal/engine/registry.go
@@ -59,8 +59,8 @@ func (r *registry) addConsumer(c *Consumer) {
// removeConsumer drops a consumer from the registry.
//
// The ID is not reused and the ordering slot is left in place, so index-based targeting
-// keeps referring to the same logical position while a departed consumer simply stops
-// matching anything.
+// keeps referring to the same logical position while a departed consumer stops matching
+// anything.
func (r *registry) removeConsumer(id scenario.ID) {
r.mu.Lock()
defer r.mu.Unlock()
diff --git a/internal/engine/run.go b/internal/engine/run.go
index 935698b..ef774ff 100644
--- a/internal/engine/run.go
+++ b/internal/engine/run.go
@@ -97,7 +97,7 @@ func (e *Engine) Run(ctx context.Context) error {
}
// allIncidents flattens incidents and groups across every scenario. Scenarios lose their
-// identity at this point -- their incidents are simply concatenated.
+// identity at this point -- their incidents are concatenated.
func (e *Engine) allIncidents() ([]scenario.Incident, []scenario.IncidentGroup) {
var incidents []scenario.Incident
var groups []scenario.IncidentGroup
@@ -304,7 +304,12 @@ func (e *Engine) Snapshot() Snapshot {
return snap
}
-// Healthy reports whether the engine is in a state it can recover from. It backs /healthz.
+// Healthy reports whether the engine has recorded a condition it cannot recover from. It
+// backs /healthz.
+//
+// Nothing clears the flag today, so a live engine always reports healthy. It exists as
+// the single place such a condition would land, already wired to the endpoint, rather
+// than as a signal anything currently raises.
func (e *Engine) Healthy() error {
if !e.healthy.Load() {
return fmt.Errorf("engine unhealthy")
diff --git a/internal/engine/scheduler.go b/internal/engine/scheduler.go
index 5e889f0..9b121cb 100644
--- a/internal/engine/scheduler.go
+++ b/internal/engine/scheduler.go
@@ -61,7 +61,7 @@ type scheduler struct {
// applyMu serialises mutations so two concurrently-firing incidents cannot interleave
// halfway through a command sequence.
//
- // Note it is NOT held across a Delay command. Command sequences embed blocking delays
+ // It is NOT held across a Delay command. Command sequences embed blocking delays
// -- PauseConsumers emits [StopConsumers, Delay(duration), ResumeConsumers] -- so
// holding the lock across one would stall every other due incident for the length of
// this one's delay and change scenario timing. Each incident is scheduled
@@ -150,6 +150,10 @@ func (s *scheduler) runIncident(ctx context.Context, inc scenario.Incident) erro
}
// runGroup repeats a set of incidents on an interval.
+//
+// Within a group the incidents run SEQUENTIALLY on this one goroutine, unlike top-level
+// incidents, which each get their own. That is the point of a group: its members are a
+// story told in order, and each one's schedule runs from the previous one finishing.
func (s *scheduler) runGroup(ctx context.Context, grp scenario.IncidentGroup) error {
repeat := grp.Repeat
if repeat <= 0 {
@@ -226,6 +230,12 @@ func (s *scheduler) apply(ctx context.Context, cmds []scenario.Command) error {
return nil
}
+// applyOne applies one command under the mutation lock.
+//
+// The two commands whose duration is set by the scenario rather than by the work itself
+// -- Delay and StopConsumer -- are intercepted by apply and never arrive here, so the
+// lock is never held for a scripted wait. The rest are either pure registry mutations or
+// a single call out to the broker controller.
func (s *scheduler) applyOne(ctx context.Context, cmd scenario.Command) error {
s.applyMu.Lock()
defer s.applyMu.Unlock()
diff --git a/internal/engine/stats.go b/internal/engine/stats.go
index c09ff47..cff70ee 100644
--- a/internal/engine/stats.go
+++ b/internal/engine/stats.go
@@ -103,10 +103,14 @@ type FlowStat struct {
Messages int64
Errors int64
- // InFlight is the number of flow instances currently executing their step delays.
- // The pool is bounded and this depth is reported live.
- InFlight int64
- Saturated int64 // times issuance blocked because the pool was full
+ // InFlight is the number of flow instances currently working through their step
+ // delays. Issuance is unbounded by default, so this climbs to whatever the rate and
+ // the step delays imply -- a few hundred at rate 50 with multi-second delays.
+ InFlight int64
+
+ // Saturated counts the times issuance had to block on a full pool, and stays at zero
+ // unless DefaultFlowConcurrency was raised above zero.
+ Saturated int64
}
// EventLevel mirrors scenario.EventLevel for output consumers that should not need to
@@ -148,8 +152,11 @@ type Snapshot struct {
Rebalances int64
// Healthy is false when the engine has recorded a condition it cannot recover from
- // on its own. It drives /healthz.
- Healthy bool
+ // on its own. It drives /healthz. See Engine.Healthy for what does and does not set it.
+ Healthy bool
+
+ // Stopping is true once Run has left its supervision loop, so a renderer can say the
+ // run is shutting down while teardown is still flushing.
Stopping bool
}
diff --git a/internal/generate/bounds_test.go b/internal/generate/bounds_test.go
index cfd6ea7..3a4732a 100644
--- a/internal/generate/bounds_test.go
+++ b/internal/generate/bounds_test.go
@@ -242,6 +242,9 @@ func TestRawJSONGenExtremeSizeBounds(t *testing.T) {
}
}
+// growHint has to clamp both ends, because strings.Builder.Grow panics on a
+// negative count and a hint of max_size_bytes would reserve that much memory
+// for every message even when the message comes out a few hundred bytes long.
func TestGrowHint(t *testing.T) {
tests := []struct {
in, want int
diff --git a/internal/generate/faker.go b/internal/generate/faker.go
index 8e6298f..02aa404 100644
--- a/internal/generate/faker.go
+++ b/internal/generate/faker.go
@@ -109,11 +109,13 @@ var fakerProviders = map[string]func(*gofakeit.Faker) any{
// newFakerGen builds the generator for a `type: faker` field.
//
-// Locale is accepted and ignored: gofakeit has no locale concept, so
+// Locale is accepted and ignored: gofakeit v7 has no locale concept, so
// `locale: de_DE` silently produces the same en_US-flavoured data as
// everything else. That is a documented no-op rather than an error, since
// rejecting it would break existing scenarios for no gain.
-// o is unused: faker fields have no cardinality cache, so no fill loop to bound.
+//
+// The options argument goes unused because faker fields have no cardinality
+// cache, and so no fill loop to bound.
func newFakerGen(f scenario.Field, r *rand.Rand, _ options) (func() any, error) {
if f.Provider == "" {
return nil, fmt.Errorf("faker field %q requires 'provider'", f.Name)
@@ -130,8 +132,10 @@ func newFakerGen(f scenario.Field, r *rand.Rand, _ options) (func() any, error)
return func() any { return fn(fake) }, nil
}
-// FakerProviders lists the supported `provider:` names, sorted. Exported so the
-// CLI can show them when a scenario names an unsupported provider.
+// FakerProviders lists the supported `provider:` names, sorted.
+//
+// The sort is what keeps newFakerGen's "supported providers are: ..." error stable;
+// ranging over the map unsorted would reshuffle that list on every run.
func FakerProviders() []string {
out := make([]string, 0, len(fakerProviders))
for name := range fakerProviders {
diff --git a/internal/generate/faker_test.go b/internal/generate/faker_test.go
index 4fd3133..c4f53b8 100644
--- a/internal/generate/faker_test.go
+++ b/internal/generate/faker_test.go
@@ -46,7 +46,10 @@ func TestFakerProvidersUsedByShippedScenarios(t *testing.T) {
}
}
-// Provider output must match the expected shape for each format.
+// Provider output shapes are a contract, so a gofakeit upgrade that changes
+// what Email() or IPv4Address() returns has to fail here rather than silently
+// reshape every message built from these providers. The date cases pin
+// something this package owns instead: the isoDate and isoDateTime layouts.
func TestFakerProviderShapes(t *testing.T) {
tests := []struct {
provider string
@@ -123,6 +126,8 @@ func TestFakerLocaleIsAcceptedAndIgnored(t *testing.T) {
}
}
+// The list is complete and sorted: it is spliced into the "supported providers are: ..."
+// error a mistyped provider produces.
func TestFakerProvidersListIsSorted(t *testing.T) {
list := FakerProviders()
if len(list) != len(fakerProviders) {
diff --git a/internal/generate/field.go b/internal/generate/field.go
index b6dab5f..2cc305d 100644
--- a/internal/generate/field.go
+++ b/internal/generate/field.go
@@ -25,11 +25,9 @@ const (
defaultFloatMax = 1000.0
)
-// maxCardinalityAttempts bounds the rejection loop that fills the
-// distinct-value cache for one cardinality slot, so a value space smaller
-// than the requested cardinality -- `type: int, min: 0, max: 5, cardinality:
-// 100` -- fails with a diagnosable error instead of spinning forever; see
-// NewFieldGen.
+// maxCardinalityAttempts is unreferenced: nothing in the package reads it. The live bound
+// on the distinct-value fill loop is whatever the caller passes to BoundFillAttempts -- the
+// engine passes 4096 -- and with no option the loop in withCardinality is unbounded.
const maxCardinalityAttempts = 1000
// lowercaseAlphabet is the character set generated string fields draw from.
@@ -67,8 +65,9 @@ const maxInt64AsFloat = 9223372036854775808.0
// it saturates on arm64 and wraps on amd64 -- so `max: 1e30` would silently
// become a different number on different machines and then panic inside the
// range draw. Values that don't fit, including NaN and the infinities, are
-// reported as an error instead; note that `min: .nan` passes schema
-// validation, because every comparison against NaN is false.
+// reported as an error instead. `min: .nan` gets this far at all because every
+// comparison against NaN is false, so the validator's min <= max check waves it
+// through.
func float64ToInt64(v float64) (int64, bool) {
if math.IsNaN(v) || v >= maxInt64AsFloat || v < -maxInt64AsFloat {
return 0, false
@@ -284,6 +283,11 @@ func newArrayGen(f scenario.Field, r *rand.Rand, o options) (func() any, error)
// The cache is filled eagerly, at construction, rather than lazily on the
// first N calls, because a bounded fill loop needs to be able to report
// failure, and the closure NewFieldGen returns cannot return an error.
+//
+// Only string and int fields route through here, and that is a constraint
+// rather than an accident: the duplicate check keys a map by the drawn value,
+// so wrapping an array field would panic with "hash of unhashable type []any"
+// on the first insert.
func withCardinality(f scenario.Field, draw func() any, o options) (func() any, error) {
card := cardinalityOf(f)
if card < 0 {
diff --git a/internal/generate/flow.go b/internal/generate/flow.go
index 7ac15d0..4976ff9 100644
--- a/internal/generate/flow.go
+++ b/internal/generate/flow.go
@@ -146,8 +146,12 @@ func (g *FlowGen) Instance() ([]FlowMessage, error) {
return msgs, nil
}
-// Steps returns the flow's steps, so the engine can set up producers and
-// consumers without re-reading the scenario.
+// Steps returns the flow's steps.
+//
+// Unlike Doc.Keys and DocGen.Fields this is not a copy: it is the same slice
+// the scenario was decoded into. Reordering it reorders what Instance emits
+// while the per-step field generators stay where they are, so step 0 would get
+// step 1's topic and step 0's fields.
func (g *FlowGen) Steps() []scenario.FlowStep { return g.steps }
// correlationID resolves the correlation id for a flow instance from the
diff --git a/internal/generate/key_test.go b/internal/generate/key_test.go
index 06f89c6..4906e1f 100644
--- a/internal/generate/key_test.go
+++ b/internal/generate/key_test.go
@@ -185,6 +185,9 @@ func TestEmptyDistributionDefaultsToUniform(t *testing.T) {
}
}
+// Equally seeded generators agree call for call. round_robin and single_key draw nothing
+// from the source, so for those two this pins only that a fresh generator always starts
+// from the same place: key-0 for round_robin, hot-key for single_key.
func TestKeyGenSeededReproducibility(t *testing.T) {
for _, dist := range []string{KeyUniform, KeyZipfian, KeyRoundRobin, KeySingleKey} {
t.Run(dist, func(t *testing.T) {
diff --git a/internal/generate/payload.go b/internal/generate/payload.go
index a8ee858..ef1d27b 100644
--- a/internal/generate/payload.go
+++ b/internal/generate/payload.go
@@ -97,7 +97,8 @@ func (g *RawJSONGen) Next() []byte {
if g.includeSequence {
fmt.Fprintf(&b, `,"sequence":%d`, seq)
}
- // Closing brace is not written yet; "data" may still be appended.
+ // The +1 is the closing brace, still unwritten because "data" may yet be appended:
+ // `current` measures the finished document, not the buffer so far.
current := b.Len() + 1
if current < target {
@@ -114,8 +115,9 @@ func (g *RawJSONGen) Next() []byte {
return []byte(b.String())
}
-// Sequence returns the number of payloads generated so far, for tests and
-// metrics.
+// Sequence returns the number of payloads generated so far. It is the same
+// counter that fills the "id" and "sequence" fields, so it also names the last
+// message produced: "msg-{Sequence()}".
func (g *RawJSONGen) Sequence() int64 { return g.sequence }
// maxGrowHint caps the buffer reservation for one message.
diff --git a/internal/generate/payload_test.go b/internal/generate/payload_test.go
index 2b08b24..e181dfa 100644
--- a/internal/generate/payload_test.go
+++ b/internal/generate/payload_test.go
@@ -85,8 +85,8 @@ func TestRawJSONGenPaddingUndershootsTargetByTen(t *testing.T) {
t.Fatalf("data key present = %v, want %v (payload %s)", padded, tt.wantPadding, raw)
}
if !tt.wantPadding {
- // No truncation either: a target smaller than the base document
- // simply yields the base document, since padding only ever adds.
+ // No truncation either: padding only ever adds bytes, so a target
+ // below the base document yields the base document unchanged.
return
}
if len(raw) != tt.wantLen {
diff --git a/internal/kafka/admin.go b/internal/kafka/admin.go
index c313bb8..a7a929c 100644
--- a/internal/kafka/admin.go
+++ b/internal/kafka/admin.go
@@ -24,6 +24,9 @@ const defaultRetentionMS = 604800000
// deleting the topics a scenario uses, checking reachability, and reading consumer-group
// lag.
type Admin struct {
+ // client is kept alongside adm -- which is only a wrapper around it -- because
+ // topicsPresent sends a kmsg.MetadataRequest directly and kadm offers no uncached
+ // equivalent. Closing either closes the same connections.
client *kgo.Client
adm *kadm.Client
diff --git a/internal/kafka/client_test.go b/internal/kafka/client_test.go
index 9d691fe..1179e8a 100644
--- a/internal/kafka/client_test.go
+++ b/internal/kafka/client_test.go
@@ -121,6 +121,8 @@ func TestNewProducerRejectsBadValues(t *testing.T) {
}
}
+// TestCompressionCodecs pins the accepted compression_type spellings, including the
+// "uncompressed" alias and the empty string a hand-built ProducerConf leaves behind.
func TestCompressionCodecs(t *testing.T) {
t.Parallel()
_, cfg := newFakeCluster(t)
@@ -296,6 +298,8 @@ func TestNewConsumerRebalanceHooks(t *testing.T) {
}
}
+// TestNewDLQProducer pins the -dlq suffix and that the acks=all client builds with
+// franz-go's idempotency left on, so a dead-letter record is not itself lost.
func TestNewDLQProducer(t *testing.T) {
t.Parallel()
_, cfg := newFakeCluster(t, kfake.SeedTopics(1, DLQTopic("orders")))
diff --git a/internal/kafka/config.go b/internal/kafka/config.go
index 261a3b4..5a10166 100644
--- a/internal/kafka/config.go
+++ b/internal/kafka/config.go
@@ -22,6 +22,8 @@ type Config struct {
// BootstrapServers is the seed broker list.
BootstrapServers []string
+ // Security is the protocol, SASL credentials and TLS material used to reach the
+ // brokers. The zero value is plaintext with no authentication.
Security Security
// External marks a cluster khaos does not own -- one reached via
diff --git a/internal/kafka/partitioner.go b/internal/kafka/partitioner.go
index bf49a7c..9cf296c 100644
--- a/internal/kafka/partitioner.go
+++ b/internal/kafka/partitioner.go
@@ -48,6 +48,12 @@ func (p *consistentRandomTopicPartitioner) RequiresConsistency(r *kgo.Record) bo
return len(r.Key) > 0
}
+// Partition returns the index, among n partitions, that r belongs on.
+//
+// The n <= 0 guard is defensive. kgo fails a record before partitioning when no partition
+// is usable, so it never calls this with a non-positive n, but both branches below panic
+// on zero -- IntN and the modulo alike -- and a panic on the produce path would take the
+// whole run down with it.
func (p *consistentRandomTopicPartitioner) Partition(r *kgo.Record, n int) int {
if n <= 0 {
return 0
diff --git a/internal/kafka/partitioner_test.go b/internal/kafka/partitioner_test.go
index 95090f9..8651281 100644
--- a/internal/kafka/partitioner_test.go
+++ b/internal/kafka/partitioner_test.go
@@ -50,7 +50,12 @@ func TestConsistentRandomNeverNegative(t *testing.T) {
}
}
-// TestConsistentRandomSpreadsKeylessRecords asserts the "random" half.
+// TestConsistentRandomSpreadsKeylessRecords asserts the "random" half: keyless records
+// must not pile onto one partition.
+//
+// The 10-of-12 threshold is slack on purpose. A working generator covers all 12 in 2000
+// draws with overwhelming probability, and a broken one collapses onto one or two
+// partitions, so the loose bound still catches the real failure and cannot flake.
func TestConsistentRandomSpreadsKeylessRecords(t *testing.T) {
tp := consistentRandomPartitioner{}.ForTopic("t")
seen := make(map[int]bool)
diff --git a/internal/kafka/policy.go b/internal/kafka/policy.go
index abcd07f..7beb0b0 100644
--- a/internal/kafka/policy.go
+++ b/internal/kafka/policy.go
@@ -42,7 +42,7 @@ var Balancers = []kgo.GroupBalancer{kgo.RangeBalancer(), kgo.RoundRobinBalancer(
// topics that merely share a name.
//
// - true (current): every run starts from empty topics, which is what makes lag numbers
-// readable from the first message. Opt out per run with --no-recreate-topics.
+// readable from the first message. Opt out per run with --recreate-topics=false.
// - false: EnsureTopics only creates what is missing and leaves existing data alone --
// safer against shared clusters.
var RecreateTopicsByDefault = true
diff --git a/internal/kafka/producer.go b/internal/kafka/producer.go
index bc456f5..1691486 100644
--- a/internal/kafka/producer.go
+++ b/internal/kafka/producer.go
@@ -11,9 +11,9 @@ import (
)
// NewProducer builds a producing client for the given scenario producer configuration:
-// batch size, linger, acks and compression, plus the options forced by the
-// acks/idempotency interaction described on producerAcks, plus the partitioner from
-// policy.go.
+// batch size, linger, acks and compression, plus the partitioner from policy.go and the
+// options that acks=0 or acks=1 force on franz-go's idempotent-write default -- see the
+// !idempotent branch below.
//
// Any extra options are applied last and therefore win, which is how the engine attaches
// metrics hooks or a logger without this package knowing about them.
diff --git a/internal/kafka/security_test.go b/internal/kafka/security_test.go
index 6561b73..75ee897 100644
--- a/internal/kafka/security_test.go
+++ b/internal/kafka/security_test.go
@@ -15,11 +15,12 @@ import (
"time"
)
+// TestSecurityValidate pins the flag-coupling rules: protocol and mechanism enum
+// membership, the credentials a SASL protocol demands, the all-or-nothing mTLS pair, and
+// the encrypted-key rejection.
func TestSecurityValidate(t *testing.T) {
t.Parallel()
- // Coupling rules under test: protocol/mechanism enum membership and the SASL/mTLS
- // field pairing.
tests := []struct {
name string
sec Security
@@ -119,10 +120,11 @@ func TestSecurityValidate(t *testing.T) {
}
}
+// TestSecurityOptions pins one kgo option per active feature -- kgo.SASL for SASL,
+// kgo.DialTLSConfig for TLS -- and that TLS material is inert under a plaintext protocol.
func TestSecurityOptions(t *testing.T) {
t.Parallel()
- // One option per active feature: SASL adds kgo.SASL, TLS adds kgo.DialTLSConfig.
tests := []struct {
name string
sec Security
@@ -202,6 +204,10 @@ func TestSecuritySASLMechanismNames(t *testing.T) {
}
}
+// TestSecurityOptionsTLSFromPEMFiles pins the TLS loader against real PEM files: a CA that
+// parses lands in the pool, a CA that parses into nothing is rejected at load time instead
+// of as an unknown-authority handshake failure later, and an encrypted key is refused
+// before any file is opened.
func TestSecurityOptionsTLSFromPEMFiles(t *testing.T) {
t.Parallel()
diff --git a/internal/localcluster/assets_test.go b/internal/localcluster/assets_test.go
index 8bdc039..68186d3 100644
--- a/internal/localcluster/assets_test.go
+++ b/internal/localcluster/assets_test.go
@@ -111,6 +111,10 @@ func TestMaterializeAssetsRepairsDivergedFile(t *testing.T) {
}
}
+// Every khaos invocation calls composeDir independently, so it has to resolve to the same
+// path each time and land under <user cache>/khaos/compose. Materialization is keyed on
+// that path: a directory that varied per call would rewrite all four files on every
+// command instead of only when the embedded copies change.
func TestComposeDirIsStable(t *testing.T) {
first, err := composeDir()
if err != nil {
diff --git a/internal/localcluster/compose.go b/internal/localcluster/compose.go
index 0822af8..a55f96f 100644
--- a/internal/localcluster/compose.go
+++ b/internal/localcluster/compose.go
@@ -83,7 +83,8 @@ func containerRunningArgs(nameFilter string) []string {
}
// isContainerRunning reports whether a container whose name contains nameFilter is up.
-// The match is by substring, not exact name.
+// Both `docker ps --filter name=` and the stdout check below match on a substring, not on
+// the exact container name.
func (c *Cluster) isContainerRunning(ctx context.Context, nameFilter string) bool {
stdout, _, err := c.run(ctx, containerRunningArgs(nameFilter)...)
if err != nil {
diff --git a/internal/localcluster/compose_test.go b/internal/localcluster/compose_test.go
index 6b14112..12efd2e 100644
--- a/internal/localcluster/compose_test.go
+++ b/internal/localcluster/compose_test.go
@@ -185,6 +185,9 @@ func TestComposeFileSelectionByMode(t *testing.T) {
}
}
+// Teardown order is load-bearing. The registry stack joins the cluster stack's bridge as
+// an external network (NetworkName), so bringing the cluster down first asks docker to
+// remove a network the registry container is still attached to.
func TestDownTearsDownRegistryBeforeCluster(t *testing.T) {
f := newFakeRunner()
c := newTestCluster(t, f, WithSchemaRegistry(true))
@@ -234,6 +237,9 @@ func TestBrokerActionRequiresRunningCluster(t *testing.T) {
}
}
+// A failed `compose up` must abort Up, not fall through to the readiness poll: the call
+// count is the real assertion here, because polling a cluster that never started would
+// sit on kafkaReadyTimeout for two minutes before reporting the same failure.
func TestUpSurfacesClassifiedComposeError(t *testing.T) {
f := newFakeRunner()
f.fail["up"] = true
diff --git a/internal/localcluster/ready.go b/internal/localcluster/ready.go
index c7327d6..ede1817 100644
--- a/internal/localcluster/ready.go
+++ b/internal/localcluster/ready.go
@@ -12,6 +12,9 @@ import (
)
// Readiness budgets for the broker and Schema Registry poll loops.
+//
+// `docker compose up -d` returns once the containers are created, not once they serve, so
+// the entire broker startup falls inside kafkaReadyTimeout rather than inside the up call.
const (
kafkaReadyTimeout = 120 * time.Second
kafkaPollInterval = 3 * time.Second
@@ -41,6 +44,10 @@ func poll(ctx context.Context, timeout, interval time.Duration, what string, pro
if ctx.Err() != nil {
return fmt.Errorf("waiting for %s: %w", what, ctx.Err())
}
+ // Give up once the next tick would land past the deadline, instead of sleeping
+ // out a full interval only to fail anyway. So poll can return up to one interval
+ // short of the stated budget, which is the right side to err on: the extra wait
+ // would be spent on a cluster the previous probe already found unready.
if !time.Now().Add(interval).Before(deadline) {
return fmt.Errorf("%s %w (waited %s, last error: %v); try: docker compose -p %s logs",
what, ErrNotReady, timeout, lastErr, ProjectName)
diff --git a/internal/localcluster/ready_test.go b/internal/localcluster/ready_test.go
index 7a981cd..91b9edb 100644
--- a/internal/localcluster/ready_test.go
+++ b/internal/localcluster/ready_test.go
@@ -10,6 +10,8 @@ import (
"time"
)
+// The first probe runs before any wait, so `khaos run` against an already-healthy cluster
+// does not pay a poll interval on every start.
func TestPollSucceedsOnFirstProbe(t *testing.T) {
calls := 0
err := poll(context.Background(), time.Second, time.Millisecond, "thing", func(context.Context) error {
@@ -41,6 +43,9 @@ func TestPollRetriesUntilReady(t *testing.T) {
}
}
+// Exhausting the budget must wrap ErrNotReady rather than returning the last probe error
+// on its own, so the timeout stays distinguishable with errors.Is from the connection
+// refusals that produced it.
func TestPollTimesOut(t *testing.T) {
err := poll(context.Background(), 20*time.Millisecond, 5*time.Millisecond, "kafka cluster", func(context.Context) error {
return errors.New("connection refused")
@@ -160,6 +165,9 @@ func deadAddress(t *testing.T) string {
return addr
}
+// The literal 127.0.0.1 is the point: "localhost" can resolve to ::1, where docker's
+// published ports may not be listening, so a "localhost" bootstrap string can fail against
+// a cluster that is perfectly healthy.
func TestHostPort(t *testing.T) {
if got := hostPort(9092); got != "127.0.0.1:9092" {
t.Fatalf("hostPort = %q, want 127.0.0.1:9092", got)
diff --git a/internal/localcluster/status.go b/internal/localcluster/status.go
index 7e4d66c..aefe27e 100644
--- a/internal/localcluster/status.go
+++ b/internal/localcluster/status.go
@@ -25,6 +25,11 @@ const (
kafkaUIServiceName = "kafka-ui"
)
+// kafkaClientPorts holds the container-side ports the brokers put their EXTERNAL listener
+// on (assets/docker-compose.kraft.yml:15,47,79). selectPublishedPort matches it against a
+// publisher's TargetPort, never its PublishedPort: the host side of a mapping can be
+// remapped freely in the compose file, so only the container side identifies which
+// listener a publisher belongs to.
var kafkaClientPorts = map[int]bool{9092: true, 9093: true, 9094: true}
// composePublisher is the subset of compose's ps JSON publisher object we need.
@@ -35,6 +40,8 @@ type composePublisher struct {
Protocol string `json:"Protocol"`
}
+// composePS is one row of compose's ps JSON. Service can come through empty, which is
+// why parsePS falls back to Name before giving up and calling the service "unknown".
type composePS struct {
Service string `json:"Service"`
Name string `json:"Name"`
diff --git a/internal/localcluster/status_test.go b/internal/localcluster/status_test.go
index 23fd8b1..21ae5f0 100644
--- a/internal/localcluster/status_test.go
+++ b/internal/localcluster/status_test.go
@@ -181,6 +181,9 @@ func TestBootstrapServersAvoidsJMXPort(t *testing.T) {
}
}
+// A `compose ps` failure that is not docker itself being unusable -- here a project with no
+// configuration file -- comes back as an empty service list rather than an error, so `khaos
+// cluster status` does not fail on a machine whose only problem is that nothing is running.
func TestStatusTolerantOfUnstartedProject(t *testing.T) {
f := newFakeRunner()
f.fail["ps"] = true
diff --git a/internal/scenario/decode.go b/internal/scenario/decode.go
index 7e0a0c3..6125494 100644
--- a/internal/scenario/decode.go
+++ b/internal/scenario/decode.go
@@ -121,10 +121,6 @@ type rawScenario struct {
SchemaRegistry *SchemaRegistry `yaml:"schema_registry"`
}
-// ---------------------------------------------------------------------------
-// Defaults
-// ---------------------------------------------------------------------------
-//
// Every type below needs an UnmarshalYAML because Go's zero value and khaos's default
// value disagree: an omitted `partitions:` must become 12, not 0. The `type raw T` alias
// makes this safe -- raw has no methods, so node.Decode fills the pre-seeded struct
@@ -221,10 +217,6 @@ func (c *Correlation) UnmarshalYAML(node *yaml.Node) error {
return nil
}
-// ---------------------------------------------------------------------------
-// Incidents
-// ---------------------------------------------------------------------------
-
// rawIncident is the YAML shape of one incident.
//
// The schedule keys sit at the same flat level as the incident's own parameters rather
diff --git a/internal/scenario/decode_test.go b/internal/scenario/decode_test.go
index c049a3c..4089c5b 100644
--- a/internal/scenario/decode_test.go
+++ b/internal/scenario/decode_test.go
@@ -186,6 +186,9 @@ topics:
}
}
+// TestDecodeFlowDefaults pins the flow defaults and, with them, the nil-vs-empty
+// distinction on a step's consumers block: `consumers: {}` decodes to the defaults,
+// while an absent block stays nil.
func TestDecodeFlowDefaults(t *testing.T) {
sc := decodeOK(t, `
name: s
@@ -365,6 +368,9 @@ incidents:
}
}
+// TestDecodeIncidentTargets pins that each selector reaches the right target type and
+// that an absent `target:` decodes to the zero value, which every incident reads as
+// "match everything".
func TestDecodeIncidentTargets(t *testing.T) {
sc := decodeOK(t, `
name: s
@@ -529,6 +535,8 @@ topics:
}
}
+// TestDecodeReturnsNilScenarioOnError pins the half of Decode's contract that callers
+// rely on to skip a nil check: errors and a scenario never come back together.
func TestDecodeReturnsNilScenarioOnError(t *testing.T) {
sc, diags := Decode([]byte("topics: []\n"))
if !diags.HasErrors() {
@@ -539,6 +547,8 @@ func TestDecodeReturnsNilScenarioOnError(t *testing.T) {
}
}
+// TestDecodeReturnsScenarioWithWarnings pins the other half: a warning is advisory and
+// must not suppress the scenario.
func TestDecodeReturnsScenarioWithWarnings(t *testing.T) {
sc, diags := Decode([]byte("name: s\ntopics:\n - name: orders\n partitions: 500\n"))
if diags.HasErrors() {
@@ -586,6 +596,9 @@ topics:
}
}
+// TestDiagnosticsHelpers pins the rendering contract: errors before warnings whatever
+// order they were found in, no "line N:" prefix when a finding has no node, and Err()
+// nil unless something was reported at error severity.
func TestDiagnosticsHelpers(t *testing.T) {
diags := Diagnostics{
{Path: "a", Message: "first", Severity: SeverityError, Line: 3},
diff --git a/internal/scenario/incident.go b/internal/scenario/incident.go
index fe843c9..c00a793 100644
--- a/internal/scenario/incident.go
+++ b/internal/scenario/incident.go
@@ -57,9 +57,9 @@ type ProducerTarget struct {
// ID is a stable opaque handle for one producer or consumer.
//
-// A recreated consumer always gets a new ID; the old one is simply gone from the
-// registry. This makes it impossible for a targeted incident scheduled after a
-// rebalance to silently select a closed consumer.
+// A recreated consumer always gets a new ID; the old one is gone from the registry.
+// This makes it impossible for a targeted incident scheduled after a rebalance to
+// silently select a closed consumer.
type ID string
// ConsumerRef is the engine-independent view of a consumer that incidents need.
@@ -115,9 +115,15 @@ type EmitEvent struct {
type EventLevel int
const (
+ // EventInfo is ordinary narration; the TUI renders it dim.
EventInfo EventLevel = iota
+ // EventWarn covers what an incident is expected to cause ("ISR will shrink"),
+ // a target that matched nothing, and degradation the run notices on its own.
EventWarn
+ // EventAlert is a fault going in.
EventAlert
+ // EventRecovery is a fault being undone: a broker coming back, consumers
+ // resuming.
EventRecovery
)
@@ -156,8 +162,12 @@ type CreateConsumer struct {
Conf ConsumerConf
}
-// StopBroker / StartBroker act on the local Docker cluster. Against an external
-// cluster they are filtered out entirely.
+// StopBroker stops one broker container of the local Docker cluster.
+//
+// Against an external cluster the engine wires a no-op BrokerController instead, which
+// records "broker fault skipped" as a warning event. The incident still fires and still
+// reaches the output layer, so the user learns why nothing happened rather than
+// watching a broker incident pass in silence.
type StopBroker struct{ Broker string }
// StartBroker restarts a broker stopped by StopBroker.
@@ -184,6 +194,13 @@ func (StartBroker) isCommand() {}
func (Delay) isCommand() {}
// Incident is one scheduled fault, implemented by six concrete types below.
+//
+// Commands returns the ordered command list to apply and performs no I/O of its own: it
+// reads the registry view in ctx and, when the incident picks targets at random, draws
+// from ctx.Rand. That is what lets every incident be tested without a broker. An incident
+// whose target matched nothing still returns a list -- a single warning event -- rather
+// than an empty one, so a mistargeted incident is visible in the output instead of
+// passing unnoticed.
type Incident interface {
Type() string
Sched() Schedule
@@ -198,10 +215,6 @@ type IncidentGroup struct {
Incidents []Incident
}
-// ---------------------------------------------------------------------------
-// Target selection
-// ---------------------------------------------------------------------------
-
// selectConsumers applies target filters in order: topic, then group, then indices,
// then a random subset by count or percentage. With no narrowing at all, every consumer
// matches.
@@ -297,10 +310,6 @@ func consumerIDs(cs []ConsumerRef) []ID {
return out
}
-// ---------------------------------------------------------------------------
-// Incident implementations
-// ---------------------------------------------------------------------------
-
// StopBrokerIncident stops a broker container.
type StopBrokerIncident struct {
Broker string
diff --git a/internal/scenario/incident_test.go b/internal/scenario/incident_test.go
index 7cd6eaa..2a2e78f 100644
--- a/internal/scenario/incident_test.go
+++ b/internal/scenario/incident_test.go
@@ -110,6 +110,9 @@ func TestPauseConsumersEmbedsDelayInSequence(t *testing.T) {
}
}
+// TestRebalanceConsumerCommands pins the whole close-wait-recreate sequence, including
+// the hardcoded 3s gap: shortening it would change how long the group spends rebalancing
+// in every scenario that uses this incident.
func TestRebalanceConsumerCommands(t *testing.T) {
c := consumer("c1", "orders", "payments-group-1")
c.ProcessingDelayMS = 25
@@ -190,6 +193,9 @@ func TestChangeProducerRateCommands(t *testing.T) {
}
}
+// TestNoMatchProducesWarningOnly pins that a target matching nothing yields exactly one
+// warning event and no mutation, so a mistargeted incident shows up in the output
+// instead of passing unnoticed.
func TestNoMatchProducesWarningOnly(t *testing.T) {
tests := []struct {
name string
@@ -212,10 +218,8 @@ func TestNoMatchProducesWarningOnly(t *testing.T) {
}
}
-// ---------------------------------------------------------------------------
-// Target selection.
-// ---------------------------------------------------------------------------
-
+// TestSelectConsumers pins the filter algebra: topic, group and indices AND together,
+// and count/percentage then draw a random subset of whatever survived.
func TestSelectConsumers(t *testing.T) {
all := []ConsumerRef{
consumer("c0", "orders", "g1"),
diff --git a/internal/scenario/loader.go b/internal/scenario/loader.go
index 38441fd..8f20332 100644
--- a/internal/scenario/loader.go
+++ b/internal/scenario/loader.go
@@ -88,7 +88,7 @@ func Discover(roots ...string) (map[string]string, error) {
found := make(map[string]string)
for _, root := range roots {
if info, err := os.Stat(root); err != nil || !info.IsDir() {
- continue // a missing root simply yields nothing
+ continue // a missing root contributes nothing, it is not an error
}
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
diff --git a/internal/scenario/loader_test.go b/internal/scenario/loader_test.go
index 8a02a38..8293218 100644
--- a/internal/scenario/loader_test.go
+++ b/internal/scenario/loader_test.go
@@ -75,6 +75,9 @@ func TestBundledCopyMatchesRepo(t *testing.T) {
}
}
+// TestDiscover pins the naming rule -- a scenario's name is its path under the root
+// without the extension -- and the two skips that keep discovery quiet: .yml files and
+// files that do not parse or carry no `name:`.
func TestDiscover(t *testing.T) {
root := t.TempDir()
write(t, filepath.Join(root, "traffic", "high-throughput.yaml"), "name: high-throughput\ntopics: [{name: a}]\n")
@@ -114,6 +117,10 @@ func TestDiscoverMissingRootIsEmpty(t *testing.T) {
}
}
+// TestDiscoverEarlierRootWins pins that a duplicate name goes to the earlier root and
+// that later roots still contribute the names the earlier one does not have. Every
+// caller in the CLI passes no roots at all today; this is the contract multi-root
+// lookup would rest on.
func TestDiscoverEarlierRootWins(t *testing.T) {
first, second := t.TempDir(), t.TempDir()
write(t, filepath.Join(first, "a.yaml"), "name: from-first\ntopics: [{name: a}]\n")
@@ -180,6 +187,9 @@ func TestDiscoverPrefersOnDiskDir(t *testing.T) {
}
}
+// TestResolve pins all three input forms Resolve accepts -- an explicit file path, an
+// extensionless path, and a bundled scenario name -- plus the wording of each failure,
+// which is what a user sees when they mistype a scenario name.
func TestResolve(t *testing.T) {
root := tempDir(t)
write(t, filepath.Join(root, "traffic", "high-throughput.yaml"), "name: high-throughput\ntopics: [{name: a}]\n")
diff --git a/internal/scenario/message_parity_test.go b/internal/scenario/message_parity_test.go
index 0939b2e..df0e771 100644
--- a/internal/scenario/message_parity_test.go
+++ b/internal/scenario/message_parity_test.go
@@ -8,9 +8,7 @@ import "testing"
// per-key type errors, and the flow and group rules.
func TestValidateMessageTextContract(t *testing.T) {
runValidationCases(t, []validationCase{
- // -------------------------------------------------------------------
// "must be an object/dict" -- one per container, each with its own wording.
- // -------------------------------------------------------------------
{
name: "topic is not a mapping",
doc: "name: s\ntopics:\n - just-a-string\n",
@@ -90,9 +88,7 @@ func TestValidateMessageTextContract(t *testing.T) {
errs: []string{"topics[0].message_schema.fields: fields must be a list"},
},
- // -------------------------------------------------------------------
// Per-key type and range errors on a field definition.
- // -------------------------------------------------------------------
{
name: "type is not a string",
doc: "name: s\ntopics:\n - name: t\n message_schema:\n fields:\n - name: a\n type: 7\n",
@@ -151,9 +147,7 @@ func TestValidateMessageTextContract(t *testing.T) {
errs: []string{"topics[0].message_schema.fields[0].locale: Field 'locale' must be a string"},
},
- // -------------------------------------------------------------------
// message_schema rules that depend on the defaults rather than on the file.
- // -------------------------------------------------------------------
{
// The pairing check compares against the MODEL default, so setting only
// min_size_bytes is enough to trip it against the default max of 500.
@@ -171,9 +165,7 @@ func TestValidateMessageTextContract(t *testing.T) {
warns: []string{"schema_registry: Using Avro without Schema Registry (schemaless mode)"},
},
- // -------------------------------------------------------------------
// Flow steps.
- // -------------------------------------------------------------------
{
name: "step missing topic and event_type",
doc: "name: s\nflows:\n - name: f\n steps:\n - {}\n - {}\n",
@@ -241,9 +233,7 @@ func TestValidateMessageTextContract(t *testing.T) {
errs: []string{"flows[0].correlation.field: Field 'field' must be a string"},
},
- // -------------------------------------------------------------------
// Incident targets and groups.
- // -------------------------------------------------------------------
{
name: "target topic and group types",
doc: "name: s\ntopics:\n - name: t\nincidents:\n - type: rebalance_consumer\n at_seconds: 5\n" +
diff --git a/internal/scenario/types.go b/internal/scenario/types.go
index c89160a..01713ab 100644
--- a/internal/scenario/types.go
+++ b/internal/scenario/types.go
@@ -1,5 +1,15 @@
// Package scenario holds the khaos scenario domain model together with the YAML
-// decoding and validation that produces it.
+// decoding, validation and file lookup that produce it. Everything downstream -- the
+// engine, the generators, the CLI -- consumes the types declared here and never parses
+// YAML itself.
+//
+// Load is the usual entry point: it reads a file and returns a *Scenario plus
+// Diagnostics. Decode does the same for bytes already in hand, in two passes -- the
+// validator walks the raw yaml.Node tree and collects every finding (validate.go),
+// then the typed decode runs only if nothing came back at error severity (decode.go).
+// Discover and Resolve turn a scenario name such as "chaos/broker-chaos" into a path,
+// falling back to the corpus embedded in the binary when no scenarios/ directory
+// exists (loader.go).
//
// Every default value used when a key is omitted from a scenario file is collected in
// one place below, so there is exactly one answer per field.
@@ -292,7 +302,13 @@ func (f Flow) Topics() []string {
return out
}
-// FlowStep is one step of a flow.
+// FlowStep is one message of a flow instance: an event produced to Topic, DelayMS after
+// the step before it.
+//
+// Every step's document leads with correlation_id and event_type, injected by the
+// generator, and Fields supplies the rest. A step with no Fields is legal and produces
+// those two keys alone -- unlike a topic, a flow step has no size bounds and no
+// synthetic padding.
type FlowStep struct {
Topic string `yaml:"topic"`
EventType string `yaml:"event_type"`
@@ -301,7 +317,13 @@ type FlowStep struct {
Consumers *StepConsumer `yaml:"consumers"`
}
-// StepConsumer configures the consumers spawned for one flow step.
+// StepConsumer is a step's `consumers:` block: Groups consumer groups of PerGroup
+// consumers each, each consumer simulating DelayMS of processing per message.
+//
+// Decoded and validated, but no engine code reads it today -- a flow step spawns no
+// consumers of its own, whatever this block says. FlowStep.Consumers stays a pointer so
+// "no block" and "an empty block filled with defaults" remain distinguishable for
+// whoever wires it up.
type StepConsumer struct {
Groups int `yaml:"groups"`
PerGroup int `yaml:"per_group"`
diff --git a/internal/scenario/validate.go b/internal/scenario/validate.go
index 62b6787..d596000 100644
--- a/internal/scenario/validate.go
+++ b/internal/scenario/validate.go
@@ -137,10 +137,6 @@ func (v *validator) knownKeys(n *yaml.Node, path string, known ...string) {
}
}
-// ---------------------------------------------------------------------------
-// Top level
-// ---------------------------------------------------------------------------
-
func (v *validator) scenario(n *yaml.Node) {
n = resolveNode(n)
if !isMapping(n) {
@@ -160,9 +156,9 @@ func (v *validator) scenario(n *yaml.Node) {
v.errf(name, "name", "Field 'name' must not be empty")
}
- // At least one of topics/flows. Note both a missing key and a key whose value is
- // not a non-empty list count as absent here, which is why a bare `topics:`
- // produces this error as well as the "must be a list" one below.
+ // At least one of topics/flows. Both a missing key and a key whose value is not
+ // a non-empty list count as absent here, which is why a bare `topics:` produces
+ // this error as well as the "must be a list" one below.
topics, flows := mapGet(n, "topics"), mapGet(n, "flows")
hasTopics := isSequence(topics) && len(seqItems(topics)) > 0
hasFlows := isSequence(flows) && len(seqItems(flows)) > 0
@@ -506,10 +502,6 @@ func (v *validator) rate01(n *yaml.Node, path, key, errMessage, warnFormat strin
// percent renders a rate as a whole-number percentage, e.g. 0.75 -> "75%".
func percent(rate float64) string { return fmt.Sprintf("%.0f%%", rate*100) }
-// ---------------------------------------------------------------------------
-// Fields
-// ---------------------------------------------------------------------------
-
func (v *validator) fields(n *yaml.Node, path string) {
if !isSequence(n) {
v.errf(n, path, "fields must be a list")
@@ -524,8 +516,8 @@ func (v *validator) fields(n *yaml.Node, path string) {
//
// asItem distinguishes a named field from an array's `items:` schema, which differ in
// two ways preserved verbatim: an array item needs no `name`, and an array item of type
-// faker is NOT checked for a `provider` since the item dispatch below simply has no
-// faker branch.
+// faker is NOT checked for a `provider`, because the dispatch below skips fakerField
+// when asItem is set.
//
// A YAML anchor can make a field definition contain itself:
//
@@ -535,10 +527,10 @@ func (v *validator) fields(n *yaml.Node, path string) {
// type: array
// items: *f
//
-// Without a guard that recurses forever, walking a hand-built node tree until the
-// machine runs out of memory. Nodes on the current recursion stack are therefore
-// tracked and re-entry is reported. A finite tree, however deeply nested, is
-// unaffected: only an alias can revisit a node.
+// Without a guard that recurses forever, appending another ".items" to the diagnostic
+// path on each pass until the process is killed. Nodes on the current recursion stack
+// are therefore tracked and re-entry is reported as an error. A finite tree, however
+// deeply nested, is unaffected: only an alias can revisit a node.
func (v *validator) field(n *yaml.Node, path string, asItem bool) {
n = resolveNode(n)
if v.visiting[n] {
@@ -726,10 +718,6 @@ func (v *validator) fakerField(n *yaml.Node, path string) {
}
}
-// ---------------------------------------------------------------------------
-// Flows
-// ---------------------------------------------------------------------------
-
func (v *validator) flows(n *yaml.Node, path string) {
if !isSequence(n) {
v.errf(n, path, "Field 'flows' must be a list")
@@ -843,8 +831,7 @@ func (v *validator) flowStep(n *yaml.Node, path string, isFirst bool) {
// `delay_ms: 1.5` produces BOTH the range error and this warning. Reading the
// value as a float here (rather than only as an int) is what surfaces the
// warning even when the range check already failed. A non-numeric delay_ms
- // simply fails the isNum check below and skips the warning instead of
- // crashing.
+ // fails the isNum check below, so it produces the range error alone.
if value, isNum := floatValue(delay); isFirst && isNum && value > 0 {
v.warnf(delay, join(path, "delay_ms"),
"First step has delay_ms - delay applies before flow starts")
@@ -871,10 +858,6 @@ func (v *validator) stepConsumers(n *yaml.Node, path string) {
v.intAtLeast(n, path, "delay_ms", 0, "Field 'delay_ms' must be a non-negative integer")
}
-// ---------------------------------------------------------------------------
-// Incidents
-// ---------------------------------------------------------------------------
-
// incidentKeys is the union of every key any incident type reads, plus `group`.
var incidentKeys = []string{
"type", "group", "at_seconds", "every_seconds", "initial_delay_seconds",
diff --git a/internal/scenario/validate_test.go b/internal/scenario/validate_test.go
index 00a7f7c..a9c1507 100644
--- a/internal/scenario/validate_test.go
+++ b/internal/scenario/validate_test.go
@@ -462,7 +462,8 @@ func TestValidateFields(t *testing.T) {
errs: []string{"topics[0].message_schema.fields[0].items.fields[0]: min cannot be greater than max"},
},
{
- // An array item needs no name -- _validate_array_item never checks for one.
+ // An array item needs no name: validator.field skips the name check when
+ // asItem is set.
name: "array item needs no name",
doc: prefix + " - name: tags\n type: array\n items:\n type: string\n",
clean: true,
diff --git a/internal/telemetry/logger.go b/internal/telemetry/logger.go
index 891fff2..3bef288 100644
--- a/internal/telemetry/logger.go
+++ b/internal/telemetry/logger.go
@@ -1,6 +1,12 @@
// Package telemetry provides khaos's structured logger, its Prometheus metric set and the
// small HTTP server that exposes /healthz and /metrics.
//
+// The three are independent and wired up separately by cmd/khaos. NewLogger (logger.go)
+// stands alone, NewMetrics (metrics.go) registers the whole counter set against a registry
+// the caller owns, and NewServer (server.go) needs that registry plus a health func. A run
+// without --metrics-addr builds the logger and neither of the other two, so an unscraped
+// metric set costs a run nothing.
+//
// Nothing in this package ever touches os.Stdout or os.Stderr. The caller supplies the
// writer, and under a bubbletea TUI that writer is a file or a pipe, never the terminal.
package telemetry
diff --git a/internal/telemetry/metrics_test.go b/internal/telemetry/metrics_test.go
index d874260..4a9fc24 100644
--- a/internal/telemetry/metrics_test.go
+++ b/internal/telemetry/metrics_test.go
@@ -72,6 +72,9 @@ func familyNames(t *testing.T, reg *prometheus.Registry) []string {
return names
}
+// The want list is the full exported metric surface. Metric names are what dashboards and
+// alert rules are written against, so adding or renaming one has to be a deliberate edit
+// here rather than something a change to NewMetrics can do quietly.
func TestNewMetricsRegistersTheWholeSet(t *testing.T) {
reg := prometheus.NewRegistry()
m := NewMetrics(reg)
@@ -104,6 +107,9 @@ func TestNewMetricsRegistersTheWholeSet(t *testing.T) {
}
}
+// Label sets are part of the contract too, not only the names: dropping "group" from
+// messages_consumed_total would collapse the per-group series into one, and a dashboard
+// grouping by consumer group would go blank rather than fail loudly.
func TestCounterValues(t *testing.T) {
reg := prometheus.NewRegistry()
m := NewMetrics(reg)
diff --git a/internal/theme/theme.go b/internal/theme/theme.go
index 3da16f0..0f28ba4 100644
--- a/internal/theme/theme.go
+++ b/internal/theme/theme.go
@@ -15,6 +15,9 @@ import (
"charm.land/lipgloss/v2"
)
+// The palette, as bright-ANSI indices. Gray is index 8, "bright black", which both light
+// and dark terminal themes render as a mid-grey: it is what the dashboard's table borders
+// are drawn in, and base black would vanish into a dark background.
var (
Red color.Color = lipgloss.Color("9")
Green color.Color = lipgloss.Color("10")
diff --git a/internal/tui/format.go b/internal/tui/format.go
index cb89c33..354d8f3 100644
--- a/internal/tui/format.go
+++ b/internal/tui/format.go
@@ -94,6 +94,9 @@ func sparkline(vals []float64) string {
case v <= 0:
// zero stays visually zero regardless of the window's range
case hi-lo < hi*0.05:
+ // A window this flat has no range worth scaling against, and hi == lo would
+ // divide by zero in the branch below. Mid-height reads as "steady"; scaling a
+ // constant rate to its own range would paint it as a wall of full blocks.
i = 4
default:
i = 1 + int((v-lo)/(hi-lo)*6.99)
@@ -114,6 +117,8 @@ func truncate(s string, n int) string {
return ansi.Truncate(s, n, "…")
}
+// fmtDuration renders a run time as 1m30s, growing an hours field only once there is one.
+// The header prints two of these side by side, so the short form is what keeps it narrow.
func fmtDuration(d time.Duration) string {
d = d.Round(time.Second)
h := int(d.Hours())
diff --git a/internal/tui/rates.go b/internal/tui/rates.go
index 4a41b84..7143396 100644
--- a/internal/tui/rates.go
+++ b/internal/tui/rates.go
@@ -11,6 +11,10 @@ const rateWindow = 5 * time.Second
// is worse than showing nothing.
const minRateSpan = 900 * time.Millisecond
+// rate is delta over span in per-second terms, never below zero. The engine's counters only
+// climb, so a negative result would mean the sampling went wrong rather than that traffic
+// reversed. A non-positive span returns 0, which leaves the callers' minRateSpan check to
+// be about display steadiness rather than about dividing by zero.
func rate(delta int64, span time.Duration) float64 {
if span <= 0 {
return 0
diff --git a/internal/tui/render.go b/internal/tui/render.go
index 96decc2..7cac4a8 100644
--- a/internal/tui/render.go
+++ b/internal/tui/render.go
@@ -52,6 +52,10 @@ const (
// titles compact, buying the name column room it otherwise loses whole names to.
const narrowWidth = 96
+// render draws the frame top-down: header, topic table, optional flow table, rule, totals,
+// issues, events, quit hint. An unknown terminal size falls back to 100x40, the same
+// default New starts at, so every frame before the first WindowSizeMsg renders at that
+// size.
func (m model) render() string {
s := m.snap
w := m.width
@@ -208,6 +212,9 @@ func (m model) header(w int) string {
return truncate(left+strings.Repeat(" ", gap)+right, w)
}
+// barWidth is how many cells the progress bar may claim, and zero below 76 columns. Down
+// there the bar would take its width out of the name column, which is already truncating
+// topic names, to repeat what the elapsed/deadline text says exactly.
func barWidth(w int) int {
switch {
case w >= 110:
@@ -349,9 +356,10 @@ func padHeader(h string, n int) string {
return h
}
-// Width thresholds for the derived columns, a function of terminal width and the
-// config-gated column set only -- never of how many digits the counters have grown to --
-// so a column present at the first frame stays present for the whole run.
+// rateThreshold is the terminal width at which the MSG/S column joins; BYTES joins 16
+// cells later. It is a function of the config-gated column set only -- never of how many
+// digits the counters have grown to -- so a column present at the first frame stays
+// present for the whole run instead of appearing the moment a counter crosses 1,000.
func rateThreshold(broker, failures bool) int {
t := 78
if broker {
@@ -363,6 +371,13 @@ func rateThreshold(broker, failures bool) int {
return t
}
+// topicTable renders topics with their consumer groups as child rows, at most budget rows
+// tall, closing with a "… N more rows" note when the budget cuts the list.
+//
+// The column set is settled here before anything is drawn, because the dependency runs one
+// way: which columns exist fixes the numeric block's width, which fixes what is left for
+// the name column, which fixes the table width -- and that width is the frame the header,
+// flow table, totals and events all align to.
func (m model) topicTable(w, budget int) string {
broker := m.showBrokerLag()
failures := m.showFailures()
@@ -527,7 +542,7 @@ func groupCells(t engine.TopicStat, g engine.GroupStat, broker, failures bool) m
"consumed": dimStyle.Render(comma(g.Consumed)),
}
if broker {
- // The group row is where broker lag actually belongs -- lag is per group, and the
+ // The group row is where broker lag belongs -- lag is per group, and the
// topic figure above is only their sum. "unknown" is deliberate: a dash or blank
// cell would read as zero at a glance, which nil BrokerLag must never imply.
if lag, known := t.BrokerLag[g.GroupID]; known {
@@ -585,7 +600,7 @@ func blankZero(n int64, sty lipgloss.Style) string {
// topicBrokerLag sums a topic's measured lag across consumer groups, the same convention
// the self-reported Lag column uses, keeping the two comparable at a glance. The bool is
// false when the topic was not measured at all; a group missing from a measured topic is
-// simply absent from the sum, making the total a lower bound.
+// absent from the sum, making the total a lower bound.
func topicBrokerLag(t engine.TopicStat) (int64, bool) {
if t.BrokerLag == nil {
return 0, false
diff --git a/internal/tui/render_more_test.go b/internal/tui/render_more_test.go
index 6e3989c..4f25c12 100644
--- a/internal/tui/render_more_test.go
+++ b/internal/tui/render_more_test.go
@@ -355,6 +355,8 @@ func TestHumanUnits(t *testing.T) {
}
}
+// The block mapping, which is where a sparkline misleads most easily: a steady rate must
+// not look saturated, and a zero must not look like a small value.
func TestSparkline(t *testing.T) {
if got := sparkline(nil); got != "" {
t.Errorf("sparkline(nil) = %q, want empty", got)
@@ -376,6 +378,9 @@ func TestSparkline(t *testing.T) {
}
}
+// The bar clamps at full rather than overflowing. A run can outlive its -d budget while
+// shutdown drains, and past 100% the unfilled remainder would be a negative repeat count,
+// which panics -- inside the one component whose job is to survive anything.
func TestProgressBar(t *testing.T) {
if got := progressBar(time.Minute, 0, 20); got != "" {
t.Errorf("no deadline must render no bar, got %q", got)
diff --git a/internal/tui/render_test.go b/internal/tui/render_test.go
index c294ce6..31c2ef6 100644
--- a/internal/tui/render_test.go
+++ b/internal/tui/render_test.go
@@ -258,6 +258,8 @@ func TestPausedMarkerDoesNotBreakColumnAlignment(t *testing.T) {
}
}
+// The events block is a tail, not a head: when there are more events than lines, the ones
+// dropped are the oldest. During an incident the line being waited for is the newest one.
func TestRecentEventsKeepsTheNewest(t *testing.T) {
events := make([]engine.Event, 20)
for i := range events {
@@ -297,6 +299,8 @@ func TestRecentEventsKeepsTheNewest(t *testing.T) {
}
}
+// Every level gets its own colour. Alerts are the load-bearing row: the events block is
+// where an incident announces itself, and an alert rendered dim is one the eye skips.
func TestEventLevelsAreColoured(t *testing.T) {
tests := []struct {
level scenario.EventLevel
@@ -318,6 +322,9 @@ func TestEventLevelsAreColoured(t *testing.T) {
}
}
+// truncate's contract is a cell budget, not a rune budget: whatever goes in, what comes out
+// is valid UTF-8 and occupies at most n terminal cells. Every column width in the tables is
+// sized against that promise, so a single overshoot shears the row it happens on.
func TestTruncate(t *testing.T) {
tests := []struct {
name string
@@ -405,6 +412,10 @@ func TestHeaderReportsRunState(t *testing.T) {
}
}
+// A run with no flows pays nothing for the flow table -- no header, no frame, no lines out
+// of the height budget. A run with flows also gets the saturation marker, which says the
+// configured concurrency bound, not the configured rate, is what is holding the flow back
+// (see DefaultFlowConcurrency in internal/engine/flow.go).
func TestFlowTableRendersOnlyWhenThereAreFlows(t *testing.T) {
without := plain(viewOf(t, engine.Snapshot{Topics: []engine.TopicStat{{Topic: "orders"}}}))
if strings.Contains(without, "INFLIGHT") {
@@ -419,6 +430,8 @@ func TestFlowTableRendersOnlyWhenThereAreFlows(t *testing.T) {
}
}
+// The totals line names errors and rebalances only when there are some. A permanent
+// "0 errors" trains the eye to skip the exact spot where a real count would appear.
func TestTotalsLineReportsErrorsAndRebalances(t *testing.T) {
out := plain(viewOf(t, sampleSnapshot()))
for _, want := range []string{"TOTAL", "12,845", "12,498", "4 errors", "2 rebalances"} {
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
index 7fcd312..c2eef68 100644
--- a/internal/tui/tui.go
+++ b/internal/tui/tui.go
@@ -1,5 +1,11 @@
// Package tui renders live run state in the terminal.
//
+// Run is the entry point: it drives a Bubble Tea program over a Source -- engine.Engine in
+// the binary, a stub in tests -- until the run ends or a quit key cancels it. Everything
+// under that is layout. render.go assembles the frame and decides which columns fit,
+// rates.go derives per-second figures from successive snapshots, and format.go does the
+// number and width arithmetic the tables are aligned on.
+//
// The single most important property of this package is what it does NOT do: it never
// mutates engine state, never owns the run deadline, and never decides when the run stops.
// It polls engine.Snapshot on its own timer and draws whatever it gets, so a wedged UI
diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go
index ccc410c..b95678f 100644
--- a/internal/tui/tui_test.go
+++ b/internal/tui/tui_test.go
@@ -104,6 +104,9 @@ func sampleSnapshot() engine.Snapshot {
}
}
+// keyPress builds the key message bubbletea/v2 would deliver for a key name. v2 carries a
+// rune code plus modifier bits rather than a string, so the named keys are spelled out by
+// hand; Update matches on msg.String(), which is what these have to reproduce faithfully.
func keyPress(s string) tea.KeyPressMsg {
switch s {
case "ctrl+c":
@@ -135,6 +138,9 @@ func TestSourceIsTheEntireEngineContract(t *testing.T) {
var _ Source = (*engine.Engine)(nil)
}
+// Init starts the clock and pulls nothing. The ticker being the only thing that calls
+// Snapshot is what makes one pull equal one sample, which is the assumption every rate in
+// rates.go is derived under.
func TestInitStartsTheTickerWithoutPulling(t *testing.T) {
src := newStubSource(sampleSnapshot())
m := New(src, func() {})
@@ -147,6 +153,8 @@ func TestInitStartsTheTickerWithoutPulling(t *testing.T) {
}
}
+// One pull per tick, and the frame shows that pull rather than the one before it. A
+// dashboard that repaints stale numbers during an incident is worse than one that stops.
func TestTickPullsAFreshSnapshotAndRendersIt(t *testing.T) {
first := sampleSnapshot()
second := sampleSnapshot()
@@ -180,6 +188,10 @@ func TestTickPullsAFreshSnapshotAndRendersIt(t *testing.T) {
}
}
+// q, ctrl-c and esc quit; nothing else does, not even shift+Q. Quitting goes through the
+// cancel func, not tea.Quit alone: the engine stops because its context was cancelled, and
+// a key that only tore down the UI would leave producers writing to a broker behind a dead
+// screen.
func TestQuitKeysCancelTheRun(t *testing.T) {
tests := []struct {
name string
@@ -279,6 +291,9 @@ func TestUpdateIsPure(t *testing.T) {
}
}
+// The ordinary end of every run: the context is cancelled under a live program and Run
+// reports that as success. Bubble Tea surfaces it as a kill, so without isCleanExit every
+// completed run would end by printing an error.
func TestRunReturnsNilWhenTheContextIsCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
@@ -345,6 +360,10 @@ func killed(cause error) error {
return fmt.Errorf("%w: %w", tea.ErrProgramKilled, cause)
}
+// The classification that decides whether cmd/khaos prints to stderr after a run. The rows
+// that earn the table are the panics: ErrProgramPanic arrives wrapped in exactly the same
+// ErrProgramKilled as a cancellation, and swallowing a crash alongside them would hide the
+// one failure an operator has to know about.
func TestIsCleanExit(t *testing.T) {
tests := []struct {
name string
diff --git a/manual_testing/README.md b/manual_testing/README.md
index 09409ec..1ca1345 100644
--- a/manual_testing/README.md
+++ b/manual_testing/README.md
@@ -1,30 +1,42 @@
-# Manual Testing with Schema Registry
+# Manual testing: Schema Registry
-This folder helps you test the Schema Registry integration manually.
+The automated tests cover the Schema Registry paths against `srfake`, an in-memory registry,
+and the Kafka side against kfake. Neither is a real Confluent Schema Registry, so this folder
+is how you check the combination by hand: a schema registered out of band, fetched by subject,
+used to generate and encode records, and its id written into the Confluent wire header.
-## Quick Start
+## Prerequisites
-### 1. Start Kafka and Schema Registry
+Docker, `curl` and `jq`, plus a binary built at the repo root:
```bash
-# From project root
+go build -o khaos ./cmd/khaos
+```
+
+## 1. Start Kafka and Schema Registry
+
+```bash
+# From the project root
./khaos cluster-up --schema-registry
# Verify Schema Registry is running
curl http://localhost:8081/subjects
```
-### 2. Upload Schema
+`--schema-registry` is only on `cluster-up`. Starting the cluster this way first is what makes
+the rest work: `khaos run` would otherwise start the cluster itself, without a registry.
+
+## 2. Upload a schema
```bash
cd manual_testing
-chmod +x upload-schema.sh
-
-# Upload the order schema
./upload-schema.sh orders-value order-schema.avsc
```
-### 3. Verify Schema
+Both arguments are optional and default to exactly those values. The registry URL comes from
+`$SCHEMA_REGISTRY_URL`, defaulting to `http://localhost:8081`.
+
+## 3. Verify the schema landed
```bash
# List subjects
@@ -34,21 +46,29 @@ curl http://localhost:8081/subjects
curl http://localhost:8081/subjects/orders-value/versions/latest | jq
```
-### 4. Run Scenario
+## 4. Run a scenario against the registered schema
```bash
-# Use the built-in registry-provider scenario
-./khaos run serialization/registry-provider --duration 30
+./khaos run serialization/registry-provider -d 30 -k
```
+`-k` matters here. Without it `khaos run` stops the cluster when the scenario ends, including
+the one you started by hand, and the registry goes with it.
+
+`scenarios/serialization/registry-provider.yaml` sets `schema_provider: registry` and
+`subject_name: orders-value` for its `orders` topic, so the schema you uploaded is what decides
+both the fields khaos generates and how the records are encoded. The subject is read, never
+re-registered, so a run cannot mutate it. Watch for Avro-specific breakage: the sample schema
+carries a `uuid` logical type on a string, an enum, and a `timestamp-millis` long.
+
## Files
| File | Description |
|------|-------------|
-| `order-schema.avsc` | Sample Avro schema |
-| `upload-schema.sh` | Script to upload schema to Schema Registry |
+| `order-schema.avsc` | Sample Avro record: uuid, enum and timestamp-millis fields. |
+| `upload-schema.sh` | Registers a schema file under a subject via the registry's REST API. |
-## Upload Custom Schema
+## Upload a custom schema
```bash
./upload-schema.sh <subject-name> <schema-file>
@@ -58,6 +78,11 @@ curl http://localhost:8081/subjects/orders-value/versions/latest | jq
./upload-schema.sh payments-value payment-schema.avsc
```
+Whatever subject you pick has to match the `subject_name` of the topic in your scenario file.
+When khaos registers an inline schema itself it uses the Confluent TopicNameStrategy -- topic
+`orders` becomes subject `orders-value` -- so following that convention here keeps the two
+directions consistent.
+
## Cleanup
```bash