Kafka data generator and load testing tool - generate fake messages, simulate producers and consumers, test broker failures, and run chaos engineering scenarios
Go apache-kafkaapache-sparkchaos-engineeringconsumer-lagdata-engineeringdata-generatordevopsdevops-toolsfake-datafault-injectionflinkkafkakafka-consumerkafka-data-generatorkafka-load-testingkafka-producerkafka-test-dataload-testingstream-processingstress-testing
fix(codec): replace archived hamba/avro with goavro/v2
aleksandarskrbic5486d8ee8f70
diff --git a/DECISIONS.md b/DECISIONS.mdindex ddae275..60821db 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -42,7 +42,7 @@ is a single flip, and each site carries a comment explaining both sides.|---|---|---|---|| ~~**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. | Using hamba, pinned. Needs an applicability check — if the CVE is in the decode path and khaos only encodes schemas it generated, exposure may be nil. | |+| ~~**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. | |diff --git a/GOAVRO_MIGRATION.md b/GOAVRO_MIGRATION.mdnew file mode 100644index 0000000..d2c0b9d--- /dev/null+++ b/GOAVRO_MIGRATION.md@@ -0,0 +1,133 @@+# Handoff: replace hamba/avro with goavro++Not started yet — this session got interrupted before writing any code. Read this top to+bottom before touching `internal/codec`.++## The ask++Swap the Avro backend in `internal/codec` from `github.com/hamba/avro/v2` to+`github.com/linkedin/goavro/v2`. `DECISIONS.md` D8 already flagged the reason: hamba/avro+is archived upstream with a reported unpatched CVE. goavro is confirmed reachable —+`go list -m -versions github.com/linkedin/goavro/v2` returned versions up to **v2.15.0**+over the proxy in this environment, so `go get github.com/linkedin/goavro/[email protected]` should+work. That `go get` was not run yet (interrupted) — go.mod/go.sum still show only hamba.++This is unrelated to the engine-bugs work done earlier in the same session (metrics wiring,+`target.indices`, `change_producer_rate` — see `git status` / `git diff`, all uncommitted+and already reviewed-pending). Don't conflate the two; this is a fresh, separate task.++## Why this is not a mechanical find-and-replace++hamba/avro and goavro have genuinely different APIs, and the current code leans hard on+hamba's object model. Read `internal/codec/avro.go`, `avro_coerce.go`, and the relevant+bits of `codec.go` in full before starting.++**hamba/avro** (current):+- `avro.ParseWithCache(text, ns, *avro.SchemaCache)` returns a `avro.Schema` — a real object+ model: `*avro.RecordSchema` (`.Fields()`, each with `.Name()`/`.Type()`), `*avro.ArraySchema`+ (`.Items()`), `*avro.MapSchema` (`.Values()`), `*avro.UnionSchema` (`.Types()`),+ `*avro.RefSchema` (`.Schema()`, unwraps a second reference to a named type).+- `avro.Marshal(schema, nativeGoValue)` / `avro.Unmarshal(schema, bytes, &out)` work directly+ against plain Go maps (`map[string]any`) and auto-unwrap/auto-wrap unions (a nullable+ field is just given its bare value or `nil`, never a wrapped union map).+- Decodes `timestamp-millis` to `time.Time` and `time-millis` to `time.Duration`+ automatically — `avroScalar()` in `avro.go` converts these back to plain epoch-millis+ `int64` because khaos always generates/round-trips integers, never `time.Time`.+- `coerceAvro()` in `avro_coerce.go` walks the schema alongside the value converting Go+ types hamba is strict about (int64→int for `int`, float64→float32 for `float`, string→+ []byte for `bytes`), and — this is the part that will need to invert — **unwraps unions**:+ for `*avro.UnionSchema` it just recurses into the first non-null branch, because hamba's+ `Marshal` doesn't want anything union-shaped on the way in.+- `parseAvro()` uses a *fresh* `avro.SchemaCache` per call specifically so that one topic's+ generated schema can never resolve a named-type reference against another topic's cache+ entry (`TestAvroParseDoesNotShareNamesBetweenSchemas` pins this — hamba's default parse+ path publishes into a shared package-level cache, which is the bug being dodged).++**goavro/v2** (target — verify the exact API against the actual fetched module, this is+from general knowledge, not re-checked against v2.15.0 docs in this session):+- `goavro.NewCodec(schemaJSON string) (*goavro.Codec, error)` — no per-parse cache knob, and+ I don't think it has hamba's shared-global-cache problem in the first place (no evidence+ goavro publishes named types outside one schema document), but **confirm this** — if it+ does leak names across `NewCodec` calls the same isolation problem needs solving.+- `codec.BinaryFromNative(buf []byte, native interface{}) ([]byte, error)` and+ `codec.NativeFromBinary(buf []byte) (interface{}, []byte, error)` — the encode/decode+ pair. Note `NativeFromBinary` returns `(interface{}, []byte remaining, error)`, not+ `(value, error)`.+- **Unions are NOT auto-wrapped/unwrapped.** goavro represents an Avro union value as a Go+ `map[string]interface{}` with exactly one key: the branch's type name (e.g. a+ `["null","string"]` field holding "hi" must be handed to `BinaryFromNative` as+ `map[string]interface{}{"string": "hi"}`, and a null value as literal `nil`). Every+ place `coerceAvro` currently *unwraps* a union will need to instead *wrap* it for encode,+ and `avroDecodedValue`/`avroScalar` will need to *unwrap* the `{branchName: value}` map+ goavro hands back on decode. Get the branch-name-to-Avro-type mapping right (it's the+ schema's own type names — `"string"`, `"long"`, a record's `name`, etc.) or every optional+ field breaks.+- **No object schema model exposed the same way.** goavro doesn't hand back a walkable+ `RecordSchema`/`ArraySchema`/`MapSchema` tree — `avroRecordDoc()`'s trick of walking+ `rec.Fields()` in schema order to rebuild a Doc with stable key order won't have that to+ lean on. `avroSchemaJSON()` (already in `avro.go`, used for the registry conversion path)+ parses the schema text into a generic `map[string]any` — that's the fallback to get field+ order back if goavro's package doesn't expose one; check whether goavro's codec object+ exposes anything like a parsed schema tree first (there's some `CodecForStandardJSONFull`+ variant and possibly a `.Schema()` that only returns the *text* back, not a tree) before+ hand-rolling JSON-schema walking.+- Logical type handling (`uuid`, `timestamp-millis`) may or may not be native in whatever+ goavro version lands — verify with a quick round-trip test before assuming `avroScalar`'s+ `time.Time`/`time.Duration` conversion logic is still needed at all. It's plausible goavro+ just hands back a plain `int64` for `timestamp-millis` with no logical-type coercion,+ which would *simplify* `avroScalar`, not complicate it — check before porting that+ function over unchanged.++## Files touched++- `internal/codec/avro.go` — `avroCodec.Encode`/`Decode`, `parseAvro`, `avroRecordDoc`,+ `avroDecodedValue`, `avroScalar`, `derefAvro`. `AvroSchemaText`/`avroFieldEntries`/+ `avroTypeOf` (schema *generation*, not parsing) are format-agnostic and should need **no+ changes** — they just build the JSON schema text via `codec.Doc`, independent of which+ library parses it back.+- `internal/codec/avro_coerce.go` — `coerceAvro` needs a real rewrite (union wrap direction+ flips, per above), not a search-and-replace of type names.+- `internal/codec/codec.go` — `newAvroCodec()` currently type-asserts+ `parsed.(*avro.RecordSchema)` to build `avroCodec{schema, record}`; whatever replaces+ `record` (a wrapper carrying goavro's codec + a field-order list, most likely) gets built+ here.+- `internal/codec/avro_test.go` — imports `github.com/hamba/avro/v2` directly in two tests+ (`TestAvroRoundTrip`, `TestAvroTimestampNormalisation` both do+ `schema.(*avro.RecordSchema)`) — these need to build whatever the new `avroCodec` struct+ shape is instead. **The test *behavior* they assert must not change**: exact schema JSON+ text (`TestAvroSchemaText`), full round-trip identity including nested record/array/map/+ enum/uuid/timestamp *and doc key order* (`TestAvroRoundTrip`), schema-cache isolation+ across topics (`TestAvroParseDoesNotShareNamesBetweenSchemas` — port the intent even if+ goavro's isolation story turns out to be different), timestamp epoch-millis round-trip+ (`TestAvroTimestampNormalisation`).+- Check `internal/codec/registry.go` and `internal/codec/convert.go` for any other direct+ `avro.` references (a stale grep from this session found matches only in avro.go/+ avro_coerce.go/codec.go, but re-grep after starting — state may have shifted).+- `go.mod`/`go.sum`: remove `github.com/hamba/avro/v2`, add `github.com/linkedin/goavro/v2`.++## Why this needs real care, not a quick swap++This is wire-format code. `HANDOFF.md` records that Avro-through-a-live-Schema-Registry was+verified end to end against the **Java** `kafka-avro-console-consumer` — a subtle behavior+drift here (wrong union wrapping, lost field order, a logical type silently mishandled)+would not show up as a compile error or even necessarily a failing unit test if the test+itself gets ported sloppily; it would show up as bytes a real Avro reader chokes on or+silently misinterprets. Budget time for:+1. Writing the new `avroCodec`/`coerceAvro` carefully, matching goavro's actual native-value+ conventions (verify against real `go doc` output / a scratch program, not memory).+2. Porting every existing avro test with the same assertions, not weaker ones.+3. If at all possible, an actual round trip through a running Schema Registry + a real Avro+ reader (Java console consumer, or at minimum `avro-tools` on the CLI) — not just Go+ round-trip tests, since the whole point of switching libraries is not to introduce a new+ interop bug while fixing the CVE/archived-library problem.+4. Once green: update `DECISIONS.md` D8 to reflect it's done (same pattern as D5/D11/D14/D15+ in that file — strike through, note what changed, leave the "You" column for the user+ rather than filling in "ok" yourself).++## Repo state as of this handoff++- `go.mod`/`go.sum`: unchanged, still hamba/avro only. No `go get` was run.+- No code changes made for this task at all.+- Unrelated to this: earlier in the session, three engine bugs were fixed (dead `/metrics`,+ `target.indices` ignored, `change_producer_rate` no-op) — all uncommitted, all tested,+ waiting on the user's review. Don't touch those files as part of this task unless asked.diff --git a/go.mod b/go.modindex 4014af6..6c0218a 100644--- a/go.mod+++ b/go.mod@@ -8,7 +8,7 @@ require (github.com/brianvoe/gofakeit/v7 v7.15.0github.com/bufbuild/protocompile v0.14.1github.com/charmbracelet/x/ansi v0.11.7- github.com/hamba/avro/v2 v2.31.0+ github.com/linkedin/goavro/v2 v2.15.0github.com/prometheus/client_golang v1.23.2github.com/spf13/cobra v1.10.2github.com/twmb/franz-go v1.21.5@@ -34,14 +34,11 @@ require (github.com/charmbracelet/x/windows v0.2.2 // indirectgithub.com/clipperhouse/displaywidth v0.11.0 // indirectgithub.com/clipperhouse/uax29/v2 v2.7.0 // indirect- github.com/go-viper/mapstructure/v2 v2.4.0 // indirect+ github.com/golang/snappy v1.0.0 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirect- github.com/json-iterator/go v1.1.12 // indirectgithub.com/klauspost/compress v1.18.6 // indirectgithub.com/lucasb-eyer/go-colorful v1.4.0 // indirectgithub.com/mattn/go-runewidth v0.0.24 // indirect- github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect- github.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/muesli/cancelreader v0.2.2 // indirectgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirectgithub.com/pierrec/lz4/v4 v4.1.26 // indirectdiff --git a/go.sum b/go.sumindex 01c5a7f..da5b559 100644--- a/go.sum+++ b/go.sum@@ -34,30 +34,23 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6Ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=-github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=+github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=+github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=+github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=-github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=-github.com/hamba/avro/v2 v2.31.0 h1:wv3nmua7lCEIwWsb6vqsTS3pXktTxcKg5eoyNu0VhrU=-github.com/hamba/avro/v2 v2.31.0/go.mod h1:t6lJYAGE5Mswfn17zjtyQsssRQgnqO6TXLBCHHWRqrw=github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=-github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=-github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=+github.com/linkedin/goavro/v2 v2.15.0 h1:pDj1UrjUOO62iXhgBiE7jQkpNIc5/tA5eZsgolMjgVI=+github.com/linkedin/goavro/v2 v2.15.0/go.mod h1:KXx+erlq+RPlGSPmLF7xGo6SAbh8sCQ53x064+ioxhk=github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU=github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=-github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=-github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=-github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=@@ -82,7 +75,9 @@ github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTgithub.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=-github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=github.com/twmb/franz-go v1.21.5 h1:cVYI2+JTTKSvohhy8bCOleYrS7G79ZBrLVFIJsoHm8M=@@ -119,5 +114,6 @@ golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/internal/codec/avro.go b/internal/codec/avro.goindex 5eb9127..d489146 100644--- a/internal/codec/avro.go+++ b/internal/codec/avro.go@@ -6,7 +6,7 @@ import ("sort""time"- "github.com/hamba/avro/v2"+ "github.com/linkedin/goavro/v2""github.com/aleksandarskrbic/khaos/internal/scenario")@@ -116,18 +116,78 @@ func stringsToAny(ss []string) []any {return out}+// avroSchemaNode is one node of a schema tree parsed from Avro schema JSON+// text. It stands in for the walkable schema object model goavro does not+// expose (see parseAvroSchemaNode): goavro.Codec only ever hands back the+// schema's original or canonical *text*, never a tree of Schema objects, so+// khaos re-parses the same text it built (or fetched) into this shape and+// walks it in parallel with values on encode (avro_coerce.go) and decode+// (avroDecodedValue below).+//+// A node's shape is one of:+// - primitive ("null", "boolean", "int", "long", "float", "double",+// "string", "bytes"): typeName set, nothing else.+// - union: union set, to branch nodes in declaration order.+// - record ("record"/"error"): fullName and fields set.+// - array: items set.+// - map: values set.+// - enum: fullName set (no further structure needed: enum symbols+// round-trip as plain strings, not union-wrapped).+// - fixed: fullName set.+//+// Named types (record/enum/fixed) are built once and shared by pointer: a+// later bare-name reference to an already-defined type (legal Avro, and+// exercised by TestAvroParseDoesNotShareNamesBetweenSchemas's "reuses" case)+// resolves to the same *avroSchemaNode rather than a shallow stand-in, which+// is what makes a self-referential or reused named type still walk correctly+// deep into its fields instead of stopping at a name.+type avroSchemaNode struct {+ typeName string+ fullName string // record/enum/fixed: namespace-qualified name, also the union branch key+ fields []avroFieldNode+ items *avroSchemaNode+ values *avroSchemaNode+ union []*avroSchemaNode+}++type avroFieldNode struct {+ name string+ typ *avroSchemaNode+}+// avroCodec encodes documents as Avro binary against a fixed writer schema.//// With frame == nil, Encode produces bare schemaless bytes with no header.type avroCodec struct {- schema avro.Schema- record *avro.RecordSchema- frame *frame+ codec *goavro.Codec+ root avroSchemaNode // always a record node; walked for field order and union shapes+ frame *frame+}++// newAvroCodecFromSchema builds an avroCodec from schema text: it parses the+// text once with goavro (for encode/decode) and once into an avroSchemaNode+// tree (for field order and union wrapping), keeping both for the codec's+// lifetime. Shared by newAvroCodec in codec.go and by the tests, so the two+// never drift on how a codec is put together.+func newAvroCodecFromSchema(text string, fr *frame) (*avroCodec, error) {+ gc, err := goavro.NewCodec(text)+ if err != nil {+ return nil, fmt.Errorf("codec: parse avro schema: %w", err)+ }+ root, err := parseAvroSchemaNode(text)+ if err != nil {+ return nil, err+ }+ if root.typeName != "record" {+ return nil, fmt.Errorf("codec: avro schema is %s, want a record", root.typeName)+ }+ return &avroCodec{codec: gc, root: root, frame: fr}, nil}// Encode writes Avro binary, behind a Confluent header when framed.func (c *avroCodec) Encode(d *Doc) ([]byte, error) {- body, err := avro.Marshal(c.schema, coerceAvro(c.schema, docToMap(d)))+ native := coerceAvro(c.root, docToMap(d))+ body, err := c.codec.BinaryFromNative(nil, native)if err != nil {return nil, fmt.Errorf("codec: avro encode: %w", err)}@@ -148,91 +208,130 @@ func (c *avroCodec) Decode(b []byte) (*Doc, error) {}body = rest}- var m map[string]any- if err := avro.Unmarshal(c.schema, body, &m); err != nil {+ native, _, err := c.codec.NativeFromBinary(body)+ if err != nil {return nil, fmt.Errorf("codec: avro decode: %w", err)}- return avroRecordDoc(c.record, m), nil+ m, ok := native.(map[string]any)+ if !ok {+ return nil, fmt.Errorf("codec: avro decode: expected a record, got %T", native)+ }+ return avroRecordDoc(c.root, m), nil}// avroRecordDoc rebuilds a Doc from a decoded record, using the schema for// ordering.-func avroRecordDoc(rec *avro.RecordSchema, m map[string]any) *Doc {+func avroRecordDoc(rec avroSchemaNode, m map[string]any) *Doc {d := NewDoc()- for _, f := range rec.Fields() {- v, ok := m[f.Name()]+ for _, f := range rec.fields {+ v, ok := m[f.name]if !ok {continue}- d.Set(f.Name(), avroDecodedValue(f.Type(), v))+ d.Set(f.name, avroDecodedValue(*f.typ, v))}return d}-// avroDecodedValue converts one decoded Avro value into the Doc value model.-func avroDecodedValue(s avro.Schema, v any) any {- switch t := derefAvro(s).(type) {- case *avro.RecordSchema:+// avroDecodedValue converts one decoded Avro native value into the Doc value+// model: it unwraps the goavro union representation+// (map[string]interface{}{"branch": value}) back to a bare value, recurses+// into records/arrays/maps in schema order, and undoes the one scalar+// conversion khaos still needs.+//+// goavro decodes bytes to []byte and khaos generates and encodes bytes-typed+// fields (from a registry schema; khaos never emits "bytes" itself) as plain+// Go strings, so decode converts back or a Doc would not survive a round+// trip. Unlike hamba, goavro decodes timestamp-millis, time-millis and uuid+// to plain Go numerics and a plain string respectively (verified against+// v2.15.0), so none of those need any conversion here.+func avroDecodedValue(s avroSchemaNode, v any) any {+ if len(s.union) > 0 {+ if v == nil {+ return nil+ }+ wrapped, ok := v.(map[string]any)+ if !ok || len(wrapped) != 1 {+ return v+ }+ for branchName, branchVal := range wrapped {+ for _, branch := range s.union {+ if branchMatchesName(*branch, branchName) {+ return avroDecodedValue(*branch, branchVal)+ }+ }+ // Unknown branch name (should not happen against our own parsed+ // schema): pass the raw value through rather than dropping it.+ return branchVal+ }+ }++ switch s.typeName {+ case "record":if m, ok := v.(map[string]any); ok {- return avroRecordDoc(t, m)+ return avroRecordDoc(s, m)}- case *avro.ArraySchema:+ case "array":if arr, ok := v.([]any); ok {out := make([]any, len(arr))for i, e := range arr {- out[i] = avroDecodedValue(t.Items(), e)+ if s.items != nil {+ out[i] = avroDecodedValue(*s.items, e)+ } else {+ out[i] = e+ }}return out}- case *avro.MapSchema:+ case "map":if m, ok := v.(map[string]any); ok {d := NewDoc()for _, k := range sortedKeys(m) {- d.Set(k, avroDecodedValue(t.Values(), m[k]))+ if s.values != nil {+ d.Set(k, avroDecodedValue(*s.values, m[k]))+ } else {+ d.Set(k, m[k])+ }}return d}+ case "bytes":+ if bs, ok := v.([]byte); ok {+ return string(bs)+ }}- return avroScalar(v)+ return avroNormaliseScalar(v)}-// avroScalar normalises the Go types hamba hands back for logical types.+// avroNormaliseScalar undoes the one Go-type substitution goavro still makes+// for logical types that khaos generates and encodes as plain integers.//-// hamba decodes timestamp-millis into time.Time and time-millis into-// time.Duration, but khaos generates and encodes those fields as integers, so-// decoding must undo the conversion or a Doc would not survive a round trip.-// timestamp-micros collapses to milliseconds here; khaos never generates one,-// and only registry-supplied schemas can contain it.-func avroScalar(v any) any {+// Verified against goavro v2.15.0: timestamp-millis decodes to time.Time and+// time-millis decodes to time.Duration, exactly like hamba did, so khaos must+// still convert them back to epoch/day milliseconds or a Doc would not+// survive a round trip. uuid decodes to a plain Go string already (goavro has+// no special uuid type), so unlike hamba's decoder it needs no conversion+// here.+func avroNormaliseScalar(v any) any {switch t := v.(type) {case time.Time:return t.UnixMilli()case time.Duration:return t.Milliseconds()- case map[string]any:- d := NewDoc()- for _, k := range sortedKeys(t) {- d.Set(k, avroScalar(t[k]))- }- return d- case []any:- out := make([]any, len(t))- for i, e := range t {- out[i] = avroScalar(e)- }- return outdefault:return v}}-// derefAvro unwraps the reference schemas hamba creates for the second and-// later uses of a named type.-func derefAvro(s avro.Schema) avro.Schema {- if ref, ok := s.(*avro.RefSchema); ok {- return ref.Schema()+// branchMatchesName reports whether branch is the union member named+// branchName in goavro's wrapped-union representation: a named type+// (record/enum/fixed) is keyed by its full name, everything else by its bare+// type name.+func branchMatchesName(branch avroSchemaNode, branchName string) bool {+ if branch.fullName != "" {+ return branch.fullName == branchName}- return s+ return branch.typeName == branchName}func sortedKeys(m map[string]any) []string {@@ -244,17 +343,17 @@ func sortedKeys(m map[string]any) []string {return keys}-// parseAvro parses Avro schema text in isolation from every other schema in-// the process, using a fresh SchemaCache instead of hamba's package-level-// default.+// parseAvro validates that schema text parses as Avro, in isolation from+// every other schema in the process.//-// khaos generates type names from field names in a single shared namespace,-// so two unrelated topics can mint the same full name; a shared cache would-// let one topic's schema silently resolve an unqualified reference to-// another topic's type depending on build order. A per-codec cache turns-// that into a deterministic parse error naming the unresolved type instead.-func parseAvro(text string) (avro.Schema, error) {- return avro.ParseWithCache(text, "", &avro.SchemaCache{})+// goavro.NewCodec gives every call its own private name-resolution scope --+// unlike hamba, which published every named type it saw into a shared+// package-level cache -- so no fresh-cache trick is needed here to stop one+// topic's schema from resolving an unqualified reference against another+// topic's type by accident; that isolation is goavro's default behaviour+// (verified empirically against v2.15.0).+func parseAvro(text string) (*goavro.Codec, error) {+ return goavro.NewCodec(text)}// avroSchemaJSON parses schema text into the generic JSON form the registry@@ -266,3 +365,192 @@ func avroSchemaJSON(text string) (map[string]any, error) {}return raw, nil}++// parseAvroSchemaNode parses schema text into an avroSchemaNode tree, the+// stand-in for the schema object model goavro does not expose. It is used+// only to recover field declaration order and union branch shapes; goavro's+// own NewCodec (called separately) remains the source of truth for whether+// the schema is valid Avro at all.+//+// Each call gets a fresh name registry, exactly like parseAvro/goavro.NewCodec,+// so this walk never leaks named types between schemas either.+func parseAvroSchemaNode(text string) (avroSchemaNode, error) {+ raw, err := avroSchemaJSON(text)+ if err != nil {+ return avroSchemaNode{}, err+ }+ ctx := &avroSchemaBuildCtx{names: make(map[string]*avroSchemaNode)}+ node, err := buildAvroSchemaNode(raw, "", ctx)+ if err != nil {+ return avroSchemaNode{}, fmt.Errorf("codec: walk avro schema: %w", err)+ }+ return *node, nil+}++// avroSchemaBuildCtx tracks named types (record/enum/fixed) seen so far+// during one buildAvroSchemaNode walk, so a later reference to an+// already-defined name resolves to the same node instead of a shallow stub.+// A record is registered under its own pointer before its fields are built,+// so a self-referential type (e.g. a linked-list-shaped record) resolves+// correctly too.+type avroSchemaBuildCtx struct {+ names map[string]*avroSchemaNode+}++// avroPrimitiveNames are the type names that are never namespace-qualified+// and never refer to a named type definition.+var avroPrimitiveNames = map[string]bool{+ "null": true, "boolean": true, "int": true, "long": true,+ "float": true, "double": true, "bytes": true, "string": true,+}++// avroCompoundLogicalTypeNames are the (baseType + "." + logicalType) keys+// goavro pre-compiles its own codec for (see the symbol table literal at the+// top of goavro's codec.go, v2.15.0) rather than falling back to the bare+// base type. For exactly these five, the wire-format identity of the type --+// and therefore the key a union branch must be wrapped/matched under, per+// union.go's makeCodecInfo (fullName := unionMemberCodec.typeName.fullName)+// -- is the compound form, not the base primitive name.+//+// Every other logicalType goavro doesn't recognize (uuid included -- goavro+// has no built-in uuid codec) is stripped by+// buildCodecForTypeDescribedByString's fallback and degrades to the bare+// base type, whose branch key is already the plain typeName the rest of this+// file computes.+var avroCompoundLogicalTypeNames = map[string]bool{+ "long.timestamp-millis": true,+ "long.timestamp-micros": true,+ "int.time-millis": true,+ "long.time-micros": true,+ "int.date": true,+}++// buildAvroSchemaNode converts one already-json.Unmarshal'd schema value+// (string, []any, or map[string]any) into an avroSchemaNode. enclosingNS is+// the namespace inherited from the nearest enclosing named type, per the Avro+// spec's namespace inheritance rule.+func buildAvroSchemaNode(raw any, enclosingNS string, ctx *avroSchemaBuildCtx) (*avroSchemaNode, error) {+ switch t := raw.(type) {+ case string:+ if avroPrimitiveNames[t] {+ return &avroSchemaNode{typeName: t}, nil+ }+ // A bare reference to a previously-defined named type.+ full := qualifyAvroName(t, enclosingNS)+ if ref, ok := ctx.names[full]; ok {+ return ref, nil+ }+ if ref, ok := ctx.names[t]; ok {+ return ref, nil+ }+ // Unresolved reference: should not happen for text that already parsed+ // successfully via goavro.NewCodec. Fall back to a shallow stub rather+ // than failing outright, since the goavro codec itself is still correct+ // even if khaos's own field-order/union bookkeeping can't fully resolve+ // an exotic namespace pattern.+ return &avroSchemaNode{typeName: t, fullName: full}, nil++ case []any:+ branches := make([]*avroSchemaNode, 0, len(t))+ for _, b := range t {+ bn, err := buildAvroSchemaNode(b, enclosingNS, ctx)+ if err != nil {+ return nil, err+ }+ branches = append(branches, bn)+ }+ return &avroSchemaNode{union: branches}, nil++ case map[string]any:+ typeName, _ := t["type"].(string)+ ns := enclosingNS+ if v, ok := t["namespace"].(string); ok && v != "" {+ ns = v+ }+ node := &avroSchemaNode{typeName: typeName}++ switch typeName {+ case "record", "error":+ node.typeName = "record"+ name, _ := t["name"].(string)+ node.fullName = qualifyAvroName(name, ns)+ registerAvroName(ctx, node, name, node.fullName)+ rawFields, _ := t["fields"].([]any)+ for _, rf := range rawFields {+ fm, ok := rf.(map[string]any)+ if !ok {+ continue+ }+ fname, _ := fm["name"].(string)+ ft, err := buildAvroSchemaNode(fm["type"], ns, ctx)+ if err != nil {+ return nil, err+ }+ node.fields = append(node.fields, avroFieldNode{name: fname, typ: ft})+ }+ case "enum":+ name, _ := t["name"].(string)+ node.fullName = qualifyAvroName(name, ns)+ registerAvroName(ctx, node, name, node.fullName)+ case "fixed":+ name, _ := t["name"].(string)+ node.fullName = qualifyAvroName(name, ns)+ registerAvroName(ctx, node, name, node.fullName)+ case "array":+ items, err := buildAvroSchemaNode(t["items"], ns, ctx)+ if err != nil {+ return nil, err+ }+ node.items = items+ case "map":+ values, err := buildAvroSchemaNode(t["values"], ns, ctx)+ if err != nil {+ return nil, err+ }+ node.values = values+ default:+ // A primitive spelled out as {"type":"string",...} (e.g. carrying a+ // logicalType) -- typeName is already set correctly above, unless+ // goavro compiles this particular (type, logicalType) pair under a+ // compound key (see avroCompoundLogicalTypeNames), in which case the+ // node's typeName must match that compound key or union branch+ // wrapping (encode) and matching (decode) picks the wrong name.+ if lt, ok := t["logicalType"].(string); ok && lt != "" {+ compound := typeName + "." + lt+ if avroCompoundLogicalTypeNames[compound] {+ node.typeName = compound+ }+ }+ }+ return node, nil++ default:+ return nil, fmt.Errorf("unsupported schema node %T", raw)+ }+}++// registerAvroName records node under both its bare and namespace-qualified+// names, so a later reference resolves whichever form it uses.+func registerAvroName(ctx *avroSchemaBuildCtx, node *avroSchemaNode, bareName, fullName string) {+ if fullName != "" {+ ctx.names[fullName] = node+ }+ if bareName != "" && bareName != fullName {+ ctx.names[bareName] = node+ }+}++// qualifyAvroName returns name qualified with ns per the Avro spec: a name+// containing a dot is already fully qualified, and an unqualified name+// inherits its enclosing namespace, if any.+func qualifyAvroName(name, ns string) string {+ if name == "" || ns == "" {+ return name+ }+ for i := 0; i < len(name); i++ {+ if name[i] == '.' {+ return name+ }+ }+ return ns + "." + name+}diff --git a/internal/codec/avro_coerce.go b/internal/codec/avro_coerce.goindex 7d286e7..ad999d6 100644--- a/internal/codec/avro_coerce.go+++ b/internal/codec/avro_coerce.go@@ -1,41 +1,56 @@package codec-import (- "time"-- "github.com/hamba/avro/v2"-)--// coerceAvro walks a value alongside its writer schema and converts Go types-// into the exact types hamba's encoder accepts.+// coerceAvro walks a value alongside its writer schema (recovered from the+// schema text as an avroSchemaNode tree, see parseAvroSchemaNode) and wraps+// every union branch into goavro's native representation before+// BinaryFromNative sees it.//-// hamba rejects int64 for "int", float64 for "float" and string for "bytes"-// outright. Generated khaos schemas only ever use long, double, string and-// boolean so they are unaffected, but a registry-supplied schema routinely-// uses the narrow types, and the generator has no idea which Avro type its-// int field will land in.+// Unlike hamba, goavro never auto-wraps or auto-unwraps unions: a union value+// must be handed to BinaryFromNative as literal nil for the null branch, or as+// map[string]interface{}{"branchName": value} for exactly one non-null+// branch, where branchName is the branch's own Avro type name -- a primitive+// type's name ("string", "long", ...), "array", "map", or a named type's full+// name ("ns.Record"/"ns.Enum"/"ns.Fixed"). Passing a bare unwrapped value for+// a non-null union branch is a hard encode error, so every nullable/union+// field khaos generates or converts from a registry schema must be wrapped+// here first.//-// Anything unrecognised is passed through untouched so that hamba reports the-// real type error rather than this function masking it.-func coerceAvro(s avro.Schema, v any) any {- switch s := s.(type) {- case *avro.RefSchema:- return coerceAvro(s.Schema(), v)-- case *avro.UnionSchema:+// khaos's own generated schemas (avroTypeOf) never emit a union at all --+// every field is required -- so this is a no-op walk for them. It only does+// real work against a schema fetched from Schema Registry and used verbatim+// (see resolveSchema in codec.go), which can be an arbitrary union.+//+// Per the verified goavro v2.15.0 behavior, no numeric/byte coercion is+// needed here: unlike hamba, goavro accepts any Go numeric kind for+// int/long/float/double and either string or []byte for string/bytes,+// coercing internally. The one primitive it does not coerce is boolean (exact+// Go bool only), but khaos's own generator already produces bool for a+// boolean field, so there is nothing to convert there either.+func coerceAvro(s avroSchemaNode, v any) any {+ if len(s.union) > 0 {if v == nil {return nil}- // The generator only ever produces the non-null branch, which is also- // the branch the registry converter derived the field type from.- for _, t := range s.Types() {- if t.Type() != avro.Null {- return coerceAvro(t, v)+ for _, branch := range s.union {+ if branch.typeName == "null" {+ continue+ }+ if !avroValueFitsBranch(*branch, v) {+ continue}+ key := branch.typeName+ if branch.fullName != "" {+ key = branch.fullName+ }+ return map[string]any{key: coerceAvro(*branch, v)}}+ // No branch's Go type family matched: let goavro report the real type+ // mismatch rather than masking it here.return v+ }- case *avro.RecordSchema:+ switch s.typeName {+ case "record":m, ok := v.(map[string]any)if !ok {return v@@ -44,62 +59,78 @@ func coerceAvro(s avro.Schema, v any) any {for k, e := range m {out[k] = e}- for _, f := range s.Fields() {- if e, ok := out[f.Name()]; ok {- out[f.Name()] = coerceAvro(f.Type(), e)+ for _, f := range s.fields {+ if e, ok := out[f.name]; ok {+ out[f.name] = coerceAvro(*f.typ, e)}}return out- case *avro.ArraySchema:+ case "array":items, ok := v.([]any)- if !ok {+ if !ok || s.items == nil {return v}out := make([]any, len(items))for i, e := range items {- out[i] = coerceAvro(s.Items(), e)+ out[i] = coerceAvro(*s.items, e)}return out- case *avro.MapSchema:+ case "map":m, ok := v.(map[string]any)- if !ok {+ if !ok || s.values == nil {return v}out := make(map[string]any, len(m))for k, e := range m {- out[k] = coerceAvro(s.Values(), e)+ out[k] = coerceAvro(*s.values, e)}return out}- switch s.Type() {- case avro.Int:- if i, ok := toInt64(v); ok {- return int(i)- }- case avro.Long:- // A timestamp-millis long takes either epoch millis (what khaos- // generates) or a time.Time; leave time.Time for hamba to handle.- if _, ok := v.(time.Time); ok {- return v- }- if i, ok := toInt64(v); ok {- return i- }- case avro.Float:- if f, ok := toFloat64(v); ok {- return float32(f)- }- case avro.Double:- if f, ok := toFloat64(v); ok {- return f+ return v+}++// avroValueFitsBranch reports whether v's Go type family is a plausible match+// for branch, used to pick a union branch by structural shape. khaos's own+// generator only ever emits the non-null branch of a field's declared type+// (see avroTypeOf), so this only has real work to do -- and ambiguity to+// resolve -- against a registry-fetched schema whose union has more than one+// non-null branch.+func avroValueFitsBranch(branch avroSchemaNode, v any) bool {+ switch branch.typeName {+ case "record", "map":+ _, ok := v.(map[string]any)+ return ok+ case "array":+ _, ok := v.([]any)+ return ok+ case "string", "enum":+ _, ok := v.(string)+ return ok+ case "bytes", "fixed":+ switch v.(type) {+ case string, []byte:+ return true+ default:+ return false}- case avro.Bytes:- if s, ok := v.(string); ok {- return []byte(s)+ case "boolean":+ _, ok := v.(bool)+ return ok+ case "int", "long", "float", "double",+ "long.timestamp-millis", "long.timestamp-micros",+ "int.time-millis", "long.time-micros", "int.date":+ switch v.(type) {+ case int, int8, int16, int32, int64,+ uint, uint8, uint16, uint32, uint64,+ float32, float64:+ return true+ default:+ return false}+ default:+ return true}- return v}diff --git a/internal/codec/avro_test.go b/internal/codec/avro_test.goindex 3d85b2d..4014064 100644--- a/internal/codec/avro_test.go+++ b/internal/codec/avro_test.go@@ -4,8 +4,6 @@ import ("reflect""testing"- "github.com/hamba/avro/v2"-"github.com/aleksandarskrbic/khaos/internal/scenario")@@ -153,11 +151,10 @@ func TestAvroRoundTrip(t *testing.T) {if err != nil {t.Fatalf("AvroSchemaText: %v", err)}- schema, err := parseAvro(text)+ c, err := newAvroCodecFromSchema(text, nil)if err != nil {- t.Fatalf("Parse: %v", err)+ t.Fatalf("newAvroCodecFromSchema: %v", err)}- c := &avroCodec{schema: schema, record: schema.(*avro.RecordSchema)}meta := NewDoc()meta.Set("region", "eu")@@ -202,11 +199,12 @@ func TestAvroRoundTrip(t *testing.T) {// TestAvroParseDoesNotShareNamesBetweenSchemas pins the isolation in parseAvro.//-// avro.Parse publishes every named type it sees into the package-global-// avro.DefaultSchemaCache and seeds the next parse from it, so a schema that-// references a type it does not define could bind to a name another topic-// happened to register first. Building "defines" before "references" is exactly-// the order that makes the leak visible: the second schema must still fail.+// goavro.NewCodec gives every call its own private name-resolution scope, with+// no package-level cache a later parse could seed from, so a schema that+// references a type it does not define must fail rather than silently binding+// to a name another topic happened to define first. Building "defines" before+// "references" is exactly the order that would make a leak (if there were one)+// visible: the second schema must still fail.func TestAvroParseDoesNotShareNamesBetweenSchemas(t *testing.T) {const defines = `{"type":"record","name":"Holder","namespace":"leak",` +`"fields":[{"name":"inner","type":{"type":"record","name":"Shared",` +@@ -240,11 +238,10 @@ func TestAvroTimestampNormalisation(t *testing.T) {if err != nil {t.Fatalf("AvroSchemaText: %v", err)}- schema, err := parseAvro(text)+ c, err := newAvroCodecFromSchema(text, nil)if err != nil {- t.Fatalf("Parse: %v", err)+ t.Fatalf("newAvroCodecFromSchema: %v", err)}- c := &avroCodec{schema: schema, record: schema.(*avro.RecordSchema)}in := NewDoc()in.Set("ts", int64(1700000000123))@@ -261,3 +258,56 @@ func TestAvroTimestampNormalisation(t *testing.T) {t.Errorf("ts = %#v, want int64(1700000000123)", got)}}++// TestAvroNullableLogicalTypeRoundTrip covers a schema shape khaos's own+// generator never produces (avroTypeOf always emits a required field) but a+// schema fetched from Schema Registry commonly does -- a nullable/optional+// field of a logical type goavro pre-compiles under a compound symbol-table+// key ("long.timestamp-millis", "long.timestamp-micros", "int.time-millis",+// "long.time-micros", "int.date"), per goavro v2.15.0's codec.go and+// union.go. The union branch wrap key (encode) and match key (decode) must+// be that compound name, not the bare base type ("long"/"int"), or encode+// hard-fails and decode silently hands back an un-normalised time.Time /+// time.Duration instead of the epoch-millis int64 khaos promises.+func TestAvroNullableLogicalTypeRoundTrip(t *testing.T) {+ text := `{"type":"record","name":"R","namespace":"khaos.generated","fields":[` ++ `{"name":"ts","type":["null",{"type":"long","logicalType":"timestamp-millis"}],"default":null}]}`++ c, err := newAvroCodecFromSchema(text, nil)+ if err != nil {+ t.Fatalf("newAvroCodecFromSchema: %v", err)+ }++ in := NewDoc()+ in.Set("ts", int64(1700000000123))+ b, err := c.Encode(in)+ if err != nil {+ t.Fatalf("Encode: %v", err)+ }+ out, err := c.Decode(b)+ if err != nil {+ t.Fatalf("Decode: %v", err)+ }+ got, ok := out.Get("ts")+ if !ok {+ t.Fatalf("ts missing from decoded Doc")+ }+ if i64, ok := got.(int64); !ok || i64 != 1700000000123 {+ t.Errorf("ts = %#v (%T), want int64(1700000000123)", got, got)+ }++ // The null branch must still round-trip too.+ inNull := NewDoc()+ inNull.Set("ts", nil)+ bNull, err := c.Encode(inNull)+ if err != nil {+ t.Fatalf("Encode(nil): %v", err)+ }+ outNull, err := c.Decode(bNull)+ if err != nil {+ t.Fatalf("Decode(nil): %v", err)+ }+ if gotNull, _ := outNull.Get("ts"); gotNull != nil {+ t.Errorf("ts = %#v, want nil", gotNull)+ }+}diff --git a/internal/codec/codec.go b/internal/codec/codec.goindex 320aade..e7b57ed 100644--- a/internal/codec/codec.go+++ b/internal/codec/codec.go@@ -4,7 +4,6 @@ import ("context""fmt"- "github.com/hamba/avro/v2""github.com/twmb/franz-go/pkg/sr""github.com/aleksandarskrbic/khaos/internal/scenario"@@ -89,15 +88,11 @@ func newAvroCodec(ctx context.Context, t scenario.Topic, fields []scenario.Fieldreturn nil, err}- parsed, err := parseAvro(text)+ c, err := newAvroCodecFromSchema(text, fr)if err != nil {- return nil, fmt.Errorf("codec: parse avro schema for topic %q: %w", t.Name, err)+ return nil, fmt.Errorf("codec: avro schema for topic %q: %w", t.Name, err)}- record, ok := parsed.(*avro.RecordSchema)- if !ok {- return nil, fmt.Errorf("codec: avro schema for topic %q is %s, want a record", t.Name, parsed.Type())- }- return &avroCodec{schema: parsed, record: record, frame: fr}, nil+ return c, nil}// newProtoCodec compiles the schema and resolves any registry id, then returnsdiff --git a/internal/engine/engine.go b/internal/engine/engine.goindex dadef08..024596c 100644--- a/internal/engine/engine.go+++ b/internal/engine/engine.go@@ -332,9 +332,9 @@ func (e *Engine) buildTopic(ctx context.Context, scenarioName string, t scenario// One codec per topic, shared by every producer on it. Unlike the generators, a// codec.Codec is safe to share: New resolves the schema text, the parsed descriptor// and the registry id once, and each Encode only reads them (jsonCodec is a stateless- // value, avroCodec holds an immutable *avro.RecordSchema, protoCodec builds a fresh- // dynamicpb message per call). Building one per producer would instead mean one- // registry registration per producer.+ // value, avroCodec holds an immutable *goavro.Codec plus its schema tree, protoCodec+ // builds a fresh dynamicpb message per call). Building one per producer would instead+ // mean one registry registration per producer.cdc, err := codec.New(ctx, t, reg)if err != nil {return fmt.Errorf("codec: %w", err)