Skip to content

Split zfmt into independently versioned formatter modules - #7

Merged
stewartboyd119 merged 1 commit into
mainfrom
zfmt-refactor
Nov 25, 2026
Merged

stewartboyd119 merged 1 commit into
mainfrom
zfmt-refactor

Conversation

@ethaneason

@ethaneason ethaneason commented Aug 15, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

This PR splits the monolithic zfmt module 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, including zkafka and zsqs, pulls in every serialization library we support, including the deprecated github.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:

  • A service that only needs JSON imports zfmtjson, whose library code imports only the standard library. Only zfmtproto imports the protobuf runtime, and only zfmtavro imports heetch/avro.
  • Misconfiguration is a compile error. There is no string to typo.
  • Custom formatters need no zfmt import at all. Any type with Marshal(v any) ([]byte, error) and Unmarshal(data []byte, v any) error works, matching the idiomatic Go pattern where the consumer (zkafka, zsqs) declares the interface it accepts.

Note: see README.md for the module table, the full 1.x migration mapping, and the list of breaking changes.

Implementation Details

Module layout

Module Formatters Third-party imports
github.com/zillow/zfmt/zfmtjson Formatter none
github.com/zillow/zfmt/zfmtbytes Formatter none
github.com/zillow/zfmt/zfmtproto RawFormatter, Base64Formatter, JSONFormatter google.golang.org/protobuf
github.com/zillow/zfmt/zfmtavro Formatter, SchematizedFormatter github.com/heetch/avro

"Third-party imports" counts what the library code imports. Each go.mod also 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/zfmt stays at v1.0.1 for consumers that have not migrated. Package names carry the zfmt prefix so they never collide with encoding/json or google.golang.org/protobuf/proto and 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

1.x FormatterType Replacement
json zfmtjson.Formatter{}
string zfmtbytes.Formatter{}
proto_raw zfmtproto.RawFormatter{}
proto_base64 zfmtproto.Base64Formatter{}
proto_json zfmtproto.JSONFormatter{}
avro zfmtavro.NewFormatter()
avro_schema zfmtavro.NewSchematizedFormatter(schemaID)
json_schema Removed. Use the JSON schema registry marshaler in zkafka.
proto_schema_deprecated Removed. Use the proto schema registry marshaler in zkafka.
  • The zfmtjson, zfmtbytes and zfmtproto formatters are stateless and ready to use as zero values, so they have no constructors. If one gains configuration later, a constructor can be added without breaking the zero value.
  • The zfmtavro formatters must be created with their constructors, because each one owns a cache of compiled decoders. Copies of an avro formatter share that cache.
  • All formatters use value receivers, so a formatter value and a pointer to it are interchangeable.
  • The marshal method is spelled Marshal (1.x used Marshall).

Removed

  • zfmt.FormatterType and all its constants, zfmt.GetFormatter, and the zfmt.Formatter interface. Consumers declare their own interface.
  • Support for github.com/golang/protobuf (APIv1) messages in zfmtproto. Regenerate older .pb.go files with a current protoc-gen-go.
  • Support for github.com/actgardner/gogen-avro types in zfmtavro. Regenerate them with avrogo. gogen-avro remains a transitive dependency because heetch/avro uses its schema compiler internally.
  • zfmt.SchematizedJSONFormatter and zfmt.SchematizedProtoFormatterDeprecated. Use the schema registry marshalers in zkafka instead.
  • zfmtavro.SchematizedFormatter.SchemaID as an exported field. Pass the ID to NewSchematizedFormatter.

Behavior changes

  • JSON: zfmtjson uses encoding/json/v2, configured to keep the wire behavior of encoding/json (v1). Nil slices and maps marshal as null, 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 SingleDecoder per record type, so the compiled decode program is reused across messages instead of rebuilt on every call. The decoders are per type because a SingleDecoder caches writer schemas by schema ID alone. There is no package-level state.

    Benchmark (DemoSchema) Before After
    Formatter.Unmarshal 4842 ns/op, 122 allocs 198 ns/op, 3 allocs
    SchematizedFormatter.Unmarshal 4861 ns/op, 122 allocs 202 ns/op, 3 allocs
    Formatter.Marshal 133 ns/op 129 ns/op

    Encoding 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.SchematizedFormatter keeps the Confluent wire format, now as unexported helpers, and rejects payloads whose first byte is not the 0 magic byte. 1.x skipped that check, so a payload with no header could decode with wrong values when the schema ID was 0.

  • Bytes targets: zfmtbytes (the 1.x string formatter) also unmarshals into *string and *[]byte, and a *[]byte target receives a copy. 1.x rejected *string, the most common target.

  • No panics on bad targets: these now return an error instead of panicking:

    • a pointer to an avro record passed to zfmtavro Marshal;
    • a typed nil target such as (*pb.Msg)(nil) in zfmtproto;
    • a nil or non-pointer target in zfmtavro;
    • a nil *string or *[]byte target in zfmtbytes.
  • Errors: every error names the module and the failing step (for example zfmtproto: decoding base64: ...) and wraps the cause with %w, so errors.Is and errors.As work. Code that matched on 1.x error strings needs updating.

Change list

  • Moves each formatter family into its own directory and module with its own go.mod.
  • Adds go.work for gopls and ad hoc commands across modules. Consumers never see it.
  • Tests:
    • 100% statement coverage in every module, passing under -race.
    • Benchmarks for the avro formatters.
    • testify throughout with an arrange / act / assert layout, wantErr strings with require.ErrorContains, and cmp.Diff (with protocmp for proto) for equality.
    • Tests that pin the JSON wire behavior and that decode two different avro record types through one formatter.
  • Makefile: every target (download, build, test, cover, tidy, tidy-check, lint) loops over all modules with GOWORK=off, so each module is built, tested and linted against its own go.mod the way a consumer resolves it.
  • .github/workflows/go.yml:
    • Runs on Go 1.27 and fails on an untidy go.mod.
    • Uploads per-module coverage to codecov and triggers on prefixed tags (zfmtjson/v* etc.).
    • Uses checkout v7, setup-go v7, codecov-action v7 and golangci-lint-action v9, each pinned by commit SHA, with golangci-lint v2.15.0.
  • .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

References

@ethaneason ethaneason changed the title initial refactor draft: initial refactor Aug 15, 2025
@codecov

codecov Bot commented Aug 15, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9757dff) to head (bec3815).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ethaneason
ethaneason force-pushed the zfmt-refactor branch 4 times, most recently from e3b6445 to 02f4f72 Compare September 3, 2025 21:28
@ethaneason
ethaneason force-pushed the zfmt-refactor branch 4 times, most recently from 55cb9fb to 1d537db Compare October 25, 2026 21:23
@ethaneason ethaneason changed the title draft: initial refactor Split zfmt into independently versioned formatter modules Oct 28, 2026
Comment thread zfmtstring/string.go Resolved
Comment thread zfmtproto/raw.go Resolved
Comment thread zfmtavro/go.mod Resolved
Comment thread zfmtjson/json.go Resolved
Comment thread zfmtavro/go.mod Resolved
Comment thread zfmtproto/schematized_deprecated.go Resolved
Comment thread zfmtjson/schematized.go Resolved

@stewartboyd119 stewartboyd119 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you got this

@stewartboyd119 stewartboyd119 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. [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.StringFormatter name stutters, flagged by Uber and Google. Every other module calls its type Formatter.
  • The seats disagree on test assertions. Google suggests replacing reflect.DeepEqual with cmp.Diff; the test-conventions seat says use testify require everywhere and replace proto.Equal checks with cmp.Diff + protocmp. Recommendation: use testify throughout, as zfmtproto already does, and use protocmp only for proto messages. That also settles whether the unused go-cmp should stay in zfmtproto/go.mod (Correctness: "zfmtproto/go.mod is not tidy").
  • wantErr bool tables and error-path tests that only check that some error occurred are one change: add a wantErr string column and use require.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%, and make lint (golangci-lint 2.13.1) found 0 issues.
  • With GOWORK=off: the root module and zfmtstring build. zfmtavro, zfmtjson and zfmtproto fail with zfmt/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.

Comment thread schema/unmarshal.go Resolved
Comment thread zfmtproto/go.mod Resolved
Comment thread schema/marshal.go Resolved
Comment thread zfmtstring/string.go Resolved
Comment thread schema/marshal.go Resolved
Comment thread zfmtavro/avro_test.go Resolved
Comment thread zfmtproto/raw_test.go Resolved
Comment thread zfmtjson/schematized_test.go Resolved
Comment thread zfmtproto/base64_test.go Resolved
Comment thread schema/marshal.go Resolved
@ethaneason
ethaneason force-pushed the zfmt-refactor branch 2 times, most recently from afb5e30 to 4dfae03 Compare November 24, 2026 18:36
Comment thread zfmtavro/avro.go Resolved

@stewartboyd119 stewartboyd119 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 written func (Formatter).
  • README module and migration tables are misaligned on the zfmtstring rows.

Review drafted with Claude Code.

Comment thread zfmtavro/avro.go Resolved
Comment thread zfmtjson/json.go Resolved
Comment thread zfmtjson/json.go Resolved
Comment thread Makefile Resolved
Comment thread zfmtstring/string.go Resolved
Comment thread zfmtproto/raw.go Resolved
Comment thread zfmtproto/base64.go Resolved
Comment thread zfmtavro/schematized.go Resolved
Comment thread README.md Resolved
Comment thread .github/workflows/go.yml Resolved
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>
@stewartboyd119
stewartboyd119 merged commit 1a24c0d into main Nov 25, 2026
6 checks passed
@ethaneason ethaneason self-assigned this Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants