Skip to content

refactor(arrow/avro): migrate from hamba/avro to twmb/avro - #830

Merged
zeroshade merged 5 commits into
apache:mainfrom
prochac:refactor/avro-lib-migration
Aug 5, 2026
Merged

zeroshade merged 5 commits into
apache:mainfrom
prochac:refactor/avro-lib-migration

Conversation

@prochac

@prochac prochac commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Rationale for this change

Closes #813

What changes are included in this PR?

arrow/avro moves from hamba/avro/v2 to twmb/avro.

The parsing side is simplified: twmb/avro hands union values to the decoder
directly instead of wrapping them in a map[string]any tagged with the branch
name, so the reader no longer has to unwrap {"long.timestamp-millis": v}
shapes on every appender.

Also included:

  • timestamp-nanos and local-timestamp-nanos logical types are now supported
    and map to timestamp[ns, tz=UTC] / timestamp[ns].
  • A fixed(16) field annotated logicalType: "uuid" now keeps its logical
    type and decodes to extensions.UUIDType instead of falling back to
    fixed_size_binary[16].
  • Named-type references are resolved against fully-qualified names. A bare
    short name that is defined under more than one namespace is now rejected;
    previously the hamba schema cache was keyed on the short name alone, so such
    a reference silently resolved to whichever definition was parsed last.
  • The top-level schema must be a record. OCF requires this, and anything else
    previously produced a degenerate or empty Arrow schema.
  • Appender errors raised for map values and list items now propagate out of
    loadDatum instead of being dropped.

Are these changes tested?

Yes. All existing tests pass, and the suite gained coverage for:

  • timestamp-nanos / local-timestamp-nanos, in the alltypes.avsc fixture
    and end to end
  • nullable logical timestamps, with time.Local pinned to a non-UTC zone so a
    machine's TZ cannot shift decoded values
  • rejection of every union shape other than ["null", T], including nested
    ones
  • the uuid logical type, on both string and fixed(16)
  • ambiguous bare named-type references
  • Reuse(), both the accept path and the schema-mismatch rejection
  • positive WithChunk(n) sizes, including the short final batch
  • records made up only of enum columns

Are there any user-facing changes?

Yes, three.

ArrowSchemaFromAvro is deprecated. Its signature takes a
hamba/avro/v2.Schema, which couples callers to a third-party Avro module.
Use ArrowSchemaFromAvroJSON(string) instead. The deprecated function still
works — it marshals the hamba schema back to JSON and forwards.

Custom decoders registered with hamba are no longer applied. Anyone who
called hamba/avro/v2.Register
to map an Avro type onto their own Go type was, in effect, changing what the
appenders received. Those registrations are invisible to twmb/avro, so values
that previously arrived as a custom type now arrive as the decoder's native Go
type — and where a registration produced something the appenders did not expect,
the reader now returns avro: unsupported value of type X for ... column rather
than silently accepting it. There is no equivalent hook to carry these
registrations across, since the global registry was never part of the arrow-go
API. Callers that relied on it need to do the conversion after reading.

Ambiguous bare named-type references now error. See the note above: a
schema that defines Foo in two namespaces and then refers to a bare
{"type": "Foo"} used to resolve to one of them arbitrarily and now returns an
error asking for a fully-qualified name. This only affects schemas that were
already ambiguous.

@prochac
prochac requested a review from zeroshade as a code owner May 26, 2026 23:09

@zeroshade zeroshade 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.

Can you rebase and resolve the conflicts please?

Comment thread arrow/avro/schema.go Outdated
Comment on lines +91 to +94
node.namedCache[s.Name] = s
if s.Namespace != "" {
node.namedCache[s.Namespace+"."+s.Name] = s
}

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.

It's worth noting that the hamba SchemaCache keyed on full name only, so for schemas with two records named Foo in different namespaces a bare {"type": "Foo"} will resolve to whichever was defined latest as opposed to being an error (the previous behavior under hamba).

We should either restrict to full-name lookups or document the change in behavior here that where a malformed schema may now silently produce something where hamba would have errored.

Comment on lines -663 to -676
case []byte:
buf := bytes.NewBuffer(dt)
if len(dt) <= 38 {
var intData int64
err := binary.Read(buf, binary.BigEndian, &intData)
if err != nil {
return err
}
b.Append(decimal128.FromI64(intData))
} else {
var bigIntData big.Int
b.Append(decimal128.FromBigInt(bigIntData.SetBytes(buf.Bytes())))
}
case map[string]any:

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.

If anyone was using custom-decoders that emitted []byte or map[string]any etc. they are now going to see "unsupported value of type X" errors where old code would have accepted the input. Let's update the description on the PR (and therefore the resulting changelog later) to note this change in behavior for anyone who was using custom-decoders.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This was possible only if they used the global type registry. The map[string]any shouldn't affect people who were using only the arrow-go API. But those who used https://pkg.go.dev/github.com/hamba/avro/v2#Register ... There is no good way to handle that :/

Comment thread arrow/avro/reader_types.go Outdated
Comment on lines +570 to +571
case 36:
return b.AppendValueFromString(string(dt))

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.

let's add a comment here explaining why we have a case for 36 (i guess, hex-dash UUID string?)

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.

as far as I'm aware, I don't think twmb ever yields a 36-byte []byte for a uuid case, so what scenario is this testing? If this is unreachable can we just remove it?

Comment thread arrow/avro/schema.go Outdated
Comment on lines +350 to +351
for i := range s.Branches {
b := s.Branches[i]

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.

Suggested change
for i := range s.Branches {
b := s.Branches[i]
for _, b := range s.Branches {

Comment thread arrow/avro/schema.go
Comment on lines +144 to +147
root := schema.Root()
n := newSchemaNode()
n.schema = schema
c := n.newChild(n.schema.(avro.NamedSchema).Name(), n.schema)
n.node = root
c := n.newChild(root.Name, root)

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.

OCF requires a named record at the top, we should probably add a guard or explicit "must be named record" check here (the hamba code would have panic'd).

@zeroshade

Copy link
Copy Markdown
Member

@prochac are you still working on this?

@prochac
prochac force-pushed the refactor/avro-lib-migration branch from ce682aa to 6092d57 Compare June 20, 2026 14:08

@zeroshade zeroshade 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.

Looks great! Only the loadDatum comment is blocking, the rest are nitpicks.

Also can we add some test scenarios for:

  • timestamp-nanos/local-timestamp-nanos: you added them but they aren't in the alltypes.avsc or testdata.go fixtures.
  • non-utc local-timestamp: a small unit test to assert the local-timestamp value in a non-utc TZ
  • heterogeneous-union rejection: something like ["int", "string"], ["null", A, B] will properly panic -> error, but the test TestComplexUnionReportsError was removed and not replaced, let's add a test for it and assert the new "unsupported avro union" message
  • We need tests for Reuse(), a positive WithChunk(n) and enum-only columns. The code looks correct, but there's no tests for them currently.

return err
}

func (d *dataLoader) loadDatum(data any) error {

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.

this currently propagates errors for top-level scalar fields, but discards them everywhere else:

  • mapValue struct loader (line 96)
  • recursive calls to a child's loadDatum (lines 137, 155, 160, 162, 164, 195, 198, 222-223)
  • list append and items: lines 172, 174, 177, 203, 206, 227-228
  • map branch append/key/value: lines 234, 237, 239, 241, 243

The original test being replaced asserted that the map-value and list-item type mismatches would have surfaced as errors. Can we re-wrap the nested appendFunc/loadDatum calls with the same error/ErrNullStructData handling used in the scalar loops? And can we restore a TestLoadDatumPropagatesNestedAppendErrors unit test (using twmb of course)

Comment thread arrow/avro/reader_types.go Outdated
Comment on lines +570 to +571
case 36:
return b.AppendValueFromString(string(dt))

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.

as far as I'm aware, I don't think twmb ever yields a 36-byte []byte for a uuid case, so what scenario is this testing? If this is unreachable can we just remove it?

Comment thread arrow/avro/reader.go Resolved
prochac and others added 5 commits July 29, 2026 13:03
Switch the avro reader from hamba/avro to twmb/avro for schema parsing
and value decoding. The new library hands back typed Go values (e.g.
*big.Rat for decimals, [16]byte for fixed-uuid) instead of []byte, which
shortens the data-side helpers and lets us fix a stack of bugs the old
[]byte arms were masking.

The exported arrow/avro surface is preserved: NewOCFReader, OCFReader
and its methods, the Option/With… helpers, and ArrowSchemaFromAvro
all keep their signatures. A new ArrowSchemaFromAvroJSON is added
alongside as the recommended entry point — it doesn't couple callers
to a particular Avro library through its type signature.
ArrowSchemaFromAvro is now marked Deprecated and serializes the hamba
schema via json.Marshal before re-parsing with twmb; the
github.com/hamba/avro/v2 dependency is kept so downstream callers
continue to compile.

Newly supported logical types (the mapping had them commented out
under hamba):
- local-timestamp-millis
- local-timestamp-micros
- local-timestamp-nanos
- timestamp-nanos

Fixes:
- fixed(16)+uuid rows are no longer silently dropped — the
  UUIDBuilder now handles [16]byte directly.
- ArrowSchemaFromAvro (deprecated wrapper) preserves logical-type
  annotations on fixed (uuid/decimal/duration). The wrapper now uses
  json.Marshal, which dispatches to each schema type's MarshalJSON;
  hambaAvro.Schema.String() returns Avro Parsing Canonical Form,
  which strips logical types by spec, and was the wrong serializer
  to bridge between libraries.
- Heterogeneous and non-nullable multi-branch unions (e.g.
  ["null", A, B], ["int", "string"]) used to silently mis-decode
  against the wrong branch or fall through to an opaque downstream
  nil-field error. They now fail upfront with "unsupported avro
  union at <path>".
- Nullable unions written as ["T", "null"] (with null in the second
  position) now resolve to T as expected; the old code always took
  Types()[1] and produced a Null-typed column for that ordering.
- Map-of-primitive schemas (e.g. {"type":"map","values":"int"}) now
  parse; the old code asserted the value type to NamedSchema and
  panicked on primitive values.
- Unknown SchemaNode types used to leave a nameless nil-typed field
  that exploded in the record builder; now they fail with
  "unhandled avro type %q", surfaced as "invalid avro schema".
- Duration's []byte arm read Uint16 with gaps and overflowed uint32
  on the milli multiply — gone; only the avro.Duration arm remains.
- append*Data helpers no longer silently no-op or fmt.Sprint-coerce
  unknown inputs; they return "unsupported value of type %T".
- Enum-symbol mismatches in appendBinaryDictData surface a clear
  error instead of a generic dictionary builder failure.
- Schema-conversion errors wrap with %w so callers can
  errors.Unwrap past arrow.ErrInvalid.

OCF wire format is unchanged: twmb/avro/ocf supports the same codecs
(null, deflate, snappy, zstd) and files written by hamba remain
readable.
- Reject ambiguous bare named-type references: key the named-type cache by
  full name and error when an unqualified reference matches a short name
  defined under multiple namespaces, instead of resolving to an arbitrary one.
- Guard that the top-level schema is a record (OCF requirement) and fail up
  front otherwise; the parser already guarantees a record has a name.
- Simplify the union-branch loop in nullableBranch.
- Document the 36-byte (hex-dash UUID text) case in appendUUIDData.
- Add tests for the root guard (non-record and parser-rejected empty name) and
  the ambiguous-reference rejection.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
loadDatum only surfaced appender errors for top-level scalar fields and
silently dropped them for map values, list items and recursive child
loads. Wrap every appendFunc/loadDatum call in a shared appendValue
helper that returns the error while still treating ErrNullStructData as
the expected "sub-fields already null-filled" signal.

Also:
- compare schemas by parsing canonical form in OCFReader.Reuse so
  semantically identical schemas that differ only in formatting are
  accepted
- drop the unreachable 36-byte hex-dash UUID case; twmb/avro never
  yields a 36-byte []byte for a uuid

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Port TestOCFReaderNullableTimestamps from upstream apache#935, which the
hamba->twmb migration displaced. Extends it with the nanos variants and
pins time.Local to a non-UTC zone so a machine's TZ cannot shift the
decoded value.

The OCF writer is given the raw schema JSON via ocf.WithSchema: twmb
defaults the header to the parsing canonical form, which by spec strips
logical types and would make the fixture meaningless.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…nums

Fills the gaps raised in review:

- alltypes.avsc/testdata.go gain timestamp-nanos and local-timestamp-nanos
  fields, so the logical types the migration added are exercised by the
  end-to-end fixture rather than only by the schema mapping.
- TestUnsupportedUnionReportsError replaces the dropped
  TestComplexUnionReportsError and asserts the new "unsupported avro
  union" message for every non-["null", T] shape, including nested ones.
- TestOCFReaderReuse covers both the accept path (a semantically
  identical but reformatted schema) and the mismatch rejection.
- TestOCFReaderWithChunk covers positive chunk sizes, including the
  short final batch.
- TestOCFReaderEnumOnlyColumns covers a record of enums only, plain and
  through a ["null", enum] union.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@prochac
prochac force-pushed the refactor/avro-lib-migration branch from 6092d57 to 37f16ab Compare July 29, 2026 11:48

@zeroshade zeroshade 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.

Thanks for working through all of this — the nested loadDatum error propagation is exactly what I was after, and the added coverage (nanos fixtures, non-UTC local-timestamp, union rejection, Reuse, WithChunk, enum-only) all looks great.

I also verified the local-timestamp change: twmb/avro decodes both the global and local timestamp logical types through time.Unix…().UTC() (local types map to the same UTC deserializers), so dropping the old hamba wall-clock reinterpretation is correct — and the non-UTC time.Local test confirms the value doesn't shift. Build, go test -race, and go vet are all green for me, and it merges cleanly onto current main.

LGTM. Two small non-blocking follow-ups that are fine to handle in a later PR:

  1. Reuse() compares Canonical() (Parsing Canonical Form), which by spec drops logicalType. So a second file whose schema differs only by a logical-type annotation would be accepted for reuse. It fails safe today (you'd hit a decode-time type mismatch rather than silent corruption), so it's not blocking — just noting it in case we want a stricter check later.

  2. Dropping the golang/snappy indirect dep relies on twmb/avro/ocf handling snappy-compressed OCF internally. We don't currently have a test that reads a snappy-compressed file — worth adding one so we don't silently regress OCF codec support.

Approving; will squash-merge once CI is green.

@zeroshade
zeroshade merged commit b21e0c5 into apache:main Aug 5, 2026
23 checks passed
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.

[Avro] hamba/avro is abandoned

2 participants