Repository navigation
Split zfmt into independently versioned formatter modules - #7
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #7 +/- ##
============================================
+ Coverage 70.83% 100.00% +29.16%
============================================
Files 10 10
Lines 168 145 -23
============================================
+ Hits 119 145 +26
+ Misses 42 0 -42
+ Partials 7 0 -7 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
e3b6445 to
02f4f72
Compare
55cb9fb to
1d537db
Compare
stewartboyd119
left a comment
There was a problem hiding this comment.
zfmt PR #7 — review panel (full codebase)
Target: #7, branch zfmt-refactor @ 1d537db. All modules: ., zfmtavro, zfmtjson, zfmtproto, zfmtstring. The whole codebase was reviewed, not just the diff.
Date: 2026-10-28
| Seat | Findings | Severity |
|---|---|---|
| Correctness | 2 | 2 low |
| Uber style | 5 | 1 medium, 4 low |
| Google style | 6 | 1 medium, 5 low |
| Test conventions | 3 | 2 medium, 1 low |
Build/test: with go.work, every module passes build, vet, test -race and lint, with 100% coverage. With GOWORK=off, zfmtavro, zfmtjson and zfmtproto don't build yet. That's expected until zfmt/v2@v2.0.0 is tagged (see README "Releasing").
Fix before merging / tagging
- [medium] Avro Unmarshal converts and recompiles the schema on every message. (details below)
Cross-seat notes
- Error wrapping was flagged by three seats (Uber, Google and test conventions). Treat it as one fix.
- The
zfmtstring.StringFormattername stutters, flagged by Uber and Google. Every other module calls its typeFormatter. - The seats disagree on test assertions. Google suggests replacing
reflect.DeepEqualwithcmp.Diff; the test-conventions seat says use testifyrequireeverywhere and replaceproto.Equalchecks withcmp.Diff+protocmp. Recommendation: use testify throughout, as zfmtproto already does, and useprotocmponly for proto messages. That also settles whether the unusedgo-cmpshould stay inzfmtproto/go.mod(Correctness: "zfmtproto/go.mod is not tidy"). wantErr booltables and error-path tests that only check that some error occurred are one change: add awantErr stringcolumn and userequire.ErrorContains.
Findings are posted as inline comments on this review.
Correctness checks run
Commands run in each module (., zfmtavro, zfmtjson, zfmtproto, zfmtstring):
- With go.work:
go build ./... && go vet ./... && go test -race -count=1 ./...passed, coverage is 100%, andmake lint(golangci-lint 2.13.1) found 0 issues. - With
GOWORK=off: the root module and zfmtstring build. zfmtavro, zfmtjson and zfmtproto fail withzfmt/v2@v2.0.0: unknown revision. go mod tidy -diff: clean except zfmtproto.
Findings without a commentable line in this diff
[medium] Avro Unmarshal converts and recompiles the schema on every message (Uber style)
zfmtavro/avro.go:49: compiler.CompileSchemaBytes([]byte(m.Schema()), []byte(m.Schema())) makes two string-to-byte conversions of the same constant schema and recompiles the VM program on every decode. This is the per-message hot path. Fix: convert once (s := []byte(m.Schema())). Better, cache the compiled program by schema string in a sync.Map, which removes the compile cost entirely. This behavior is carried over unchanged from 1.0.1. Guide: Avoid repeated string-to-byte conversions.
[low] Underlying errors returned with no context about which step failed (Google style)
zfmtavro/avro.go:51, zfmtavro/avro.go:57, zfmtproto/base64.go:46, zfmtproto/base64.go:55 — Schema-compile, schema-parse and base64-decode errors are returned bare, so a caller cannot tell "the embedded schema is invalid" from "the payload is corrupt". The type-mismatch errors in the same functions do carry context, so this is inconsistent. Fix: wrap with %w, e.g. fmt.Errorf("zfmtavro: compiling schema for %T: %w", v, err) and fmt.Errorf("zfmtproto: decoding base64: %w", err). Guide: best-practices "Adding information to errors" (https://google.github.io/styleguide/go/best-practices#error-extra-info).
Review generated by Claude Code (multi-seat review panel) on behalf of stewartboyd119.
afb5e30 to
4dfae03
Compare
stewartboyd119
left a comment
There was a problem hiding this comment.
The overall direction is right: concrete formatter types, consumer-declared interfaces, per-module deps, and no string registry. Because this is a breaking release, some of the inline comments are API changes worth making now, while consumers are already forced to touch their call sites.
Severity tags: [important] should change before tagging · [api] idiomatic improvement worth taking in this breaking window · [nit] optional.
Small style items that don't need their own thread:
- Unused receivers (
func (f Formatter)) can be writtenfunc (Formatter). - README module and migration tables are misaligned on the
zfmtstringrows.
Review drafted with Claude Code.
Replaces the monolithic module and its string-driven registry (FormatterType, GetFormatter) with per-format modules whose formatters are constructed in code and passed to the transport library at the call site. Because consumers must make a deliberate major-version move, this also drops support that 1.x kept only for legacy reasons. Modules - github.com/zillow/zfmt/zfmtjson, zfmtproto, zfmtavro, zfmtbytes: one module per formatter family so consumers only pull the serialization libraries they use. Package names carry the zfmt prefix so they never collide with encoding/json or google.golang.org/protobuf/proto. - There is no root module. The modules do not depend on each other, build and tidy standalone, and can be tagged in any order. github.com/zillow/zfmt stays at v1.0.1. go.work exists only for gopls and ad hoc commands. - All modules target Go 1.27 and use the latest dependency releases (protobuf v1.36.12, heetch/avro v0.4.79). Removed - FormatterType, GetFormatter and the Formatter interface; transport libraries declare the interface they accept. - github.com/golang/protobuf (APIv1) message support in zfmtproto. - gogen-avro generated type support in zfmtavro (heetch/avro only). - The JSON schematized formatter and the deprecated proto schematized formatter; zkafka's schema registry marshalers replace them. Behavior - zfmtjson uses encoding/json/v2 configured for v1 wire behavior: nil slices and maps marshal as null and names match case-insensitively. Invalid UTF-8 and duplicate names are errors. - zfmtavro decodes through one heetch SingleDecoder per record type, owned by the formatter, so the compiled decode program is reused: Unmarshal is about 24x faster with 3 allocations instead of 122. Decoding assumes the writer schema equals the target type's schema, as in 1.x. - zfmtavro.SchematizedFormatter keeps the Confluent wire format and rejects payloads without the 0 magic byte. - zfmtavro Marshal accepts pointers to generated records instead of panicking inside heetch/avro. - zfmtbytes (was the string formatter) also unmarshals into *string and *[]byte; *[]byte receives a copy. - Nil and typed nil targets return errors instead of panicking in zfmtproto, zfmtavro and zfmtbytes. - Errors carry the module name and failing step and wrap the cause with %w. - The marshal method is spelled Marshal. Stateless formatters are used as zero values with no constructors; the avro formatters, which hold decoder caches, are created with NewFormatter and NewSchematizedFormatter. Tests - 100% statement coverage in every module, passing under -race, with benchmarks for the avro formatters. - testify throughout with arrange / act / assert layout, wantErr strings with require.ErrorContains, cmp.Diff (protocmp for proto) for equality, and tests pinning the JSON wire behavior and per-type avro decoding. Tooling and docs - Every Makefile target runs with GOWORK=off, so each module is downloaded, built, tested, linted and tidy-checked against its own go.mod. CI fails on an untidy go.mod. - CI runs on Go 1.27 with checkout v7, setup-go v7, codecov-action v7 and golangci-lint-action v9 pinned by commit SHA, and golangci-lint v2.15.0. - README: module table, usage, 1.x migration table and breaking changes, release process. CHANGELOG: split note and 1.0.0 entries per module. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4dfae03 to
bec3815
Compare
Overview
This PR splits the monolithic
zfmtmodule into four independently versioned Go modules and removes the string-driven formatter registry (zfmt.FormatterType/zfmt.GetFormatter). Formatters are now constructed in code and passed to the transport library at the call site.Today every consumer of
zfmt, includingzkafkaandzsqs, pulls in every serialization library we support, including the deprecatedgithub.com/golang/protobuf, even if it only needs JSON. Because formatter selection happened through a config string, removing a dependency or renaming a formatter would not produce a compile error for most users, so a bad upgrade would surface as a runtime failure in a deployed pod rather than at build time.Since consumers have to make a deliberate major-version move anyway, this PR also drops support that 1.x kept only for legacy reasons: protobuf APIv1 messages, gogen-avro types, and the schematized formatters that never worked reliably.
After this change:
zfmtjson, whose library code imports only the standard library. Onlyzfmtprotoimports the protobuf runtime, and onlyzfmtavroimports heetch/avro.zfmtimport at all. Any type withMarshal(v any) ([]byte, error)andUnmarshal(data []byte, v any) errorworks, matching the idiomatic Go pattern where the consumer (zkafka, zsqs) declares the interface it accepts.Note: see
README.mdfor the module table, the full 1.x migration mapping, and the list of breaking changes.Implementation Details
Module layout
github.com/zillow/zfmt/zfmtjsonFormattergithub.com/zillow/zfmt/zfmtbytesFormattergithub.com/zillow/zfmt/zfmtprotoRawFormatter,Base64Formatter,JSONFormattergoogle.golang.org/protobufgithub.com/zillow/zfmt/zfmtavroFormatter,SchematizedFormattergithub.com/heetch/avro"Third-party imports" counts what the library code imports. Each
go.modalso lists test-only dependencies such as testify and go-cmp, so those still appear in a consumer's module graph.There is no root module. The four modules do not depend on each other, each builds and tidies standalone, and they can be tagged in any order.
github.com/zillow/zfmtstays at v1.0.1 for consumers that have not migrated. Package names carry thezfmtprefix so they never collide withencoding/jsonorgoogle.golang.org/protobuf/protoand need no import alias.All modules target Go 1.27 and are on the latest dependency releases (protobuf v1.36.12, heetch/avro v0.4.79). No dependency has a newer major version.
Public API
FormatterTypejsonzfmtjson.Formatter{}stringzfmtbytes.Formatter{}proto_rawzfmtproto.RawFormatter{}proto_base64zfmtproto.Base64Formatter{}proto_jsonzfmtproto.JSONFormatter{}avrozfmtavro.NewFormatter()avro_schemazfmtavro.NewSchematizedFormatter(schemaID)json_schemaproto_schema_deprecatedMarshal(1.x usedMarshall).Removed
zfmt.FormatterTypeand all its constants,zfmt.GetFormatter, and thezfmt.Formatterinterface. Consumers declare their own interface.github.com/golang/protobuf(APIv1) messages inzfmtproto. Regenerate older.pb.gofiles with a currentprotoc-gen-go.github.com/actgardner/gogen-avrotypes inzfmtavro. Regenerate them withavrogo. gogen-avro remains a transitive dependency because heetch/avro uses its schema compiler internally.zfmt.SchematizedJSONFormatterandzfmt.SchematizedProtoFormatterDeprecated. Use the schema registry marshalers in zkafka instead.zfmtavro.SchematizedFormatter.SchemaIDas an exported field. Pass the ID toNewSchematizedFormatter.Behavior changes
JSON:
zfmtjsonusesencoding/json/v2, configured to keep the wire behavior ofencoding/json(v1). Nil slices and maps marshal asnull, and object names match struct fields case-insensitively without ignoring_or-. v2's stricter input checks stay on, so invalid UTF-8 and duplicate object names are errors instead of being repaired or overwritten.Avro decode performance: each avro formatter decodes through one heetch
SingleDecoderper record type, so the compiled decode program is reused across messages instead of rebuilt on every call. The decoders are per type because aSingleDecodercaches writer schemas by schema ID alone. There is no package-level state.DemoSchema)Formatter.UnmarshalSchematizedFormatter.UnmarshalFormatter.MarshalEncoding was already cached per Go type inside heetch, so it is unchanged.
Avro schema resolution: decoding assumes the message was written with the target type's own schema, as in 1.x. Messages written with a different, even compatible, schema are not resolved. This is now documented on both avro formatters. Use a schema registry aware marshaler, such as zkafka's, when producers and consumers evolve schemas independently.
Wire format:
zfmtavro.SchematizedFormatterkeeps the Confluent wire format, now as unexported helpers, and rejects payloads whose first byte is not the0magic byte. 1.x skipped that check, so a payload with no header could decode with wrong values when the schema ID was0.Bytes targets:
zfmtbytes(the 1.xstringformatter) also unmarshals into*stringand*[]byte, and a*[]bytetarget receives a copy. 1.x rejected*string, the most common target.No panics on bad targets: these now return an error instead of panicking:
zfmtavroMarshal;(*pb.Msg)(nil)inzfmtproto;zfmtavro;*stringor*[]bytetarget inzfmtbytes.Errors: every error names the module and the failing step (for example
zfmtproto: decoding base64: ...) and wraps the cause with%w, soerrors.Isanderrors.Aswork. Code that matched on 1.x error strings needs updating.Change list
go.mod.go.workfor gopls and ad hoc commands across modules. Consumers never see it.-race.wantErrstrings withrequire.ErrorContains, andcmp.Diff(withprotocmpfor proto) for equality.Makefile: every target (download,build,test,cover,tidy,tidy-check,lint) loops over all modules withGOWORK=off, so each module is built, tested and linted against its owngo.modthe way a consumer resolves it..github/workflows/go.yml:go.mod.zfmtjson/v*etc.)..golangci.yml: rewritten for golangci-lint v2. The previous file was misindented and effectively enabled no linters.README.md: module table, install, usage, migration table and breaking changes, development and release process.CHANGELOG.md: module split note and 1.0.0 entries per module.Release
Tags are per module using the directory prefix convention:
zfmtjson/v1.0.0,zfmtproto/v1.0.0,zfmtavro/v1.0.0,zfmtbytes/v1.0.0. Order does not matter.Companion changes
zfmt-refactorbranch replace the formatter registry with injected formatters and drop their dependency onzfmt.examplemodules still point at this branch through local replace directives. They need updating for Go 1.27, the removed root module, thezfmtbytesrename and the zero-value formatters before those tags are swapped in.References
encoding/json/v2: https://pkg.go.dev/encoding/json/v2SingleDecoder: https://pkg.go.dev/github.com/heetch/avro#SingleDecoder