Skip to content

fix: replace panics with proper error returns - #758

Merged
zeroshade merged 5 commits into
apache:mainfrom
shtripat:input-validation-with-error-no-panic
Feb 26, 2026
Merged

zeroshade merged 5 commits into
apache:mainfrom
shtripat:input-validation-with-error-no-panic

Conversation

@shtripat

@shtripat shtripat commented Feb 25, 2026 •

Copy link
Copy Markdown
Contributor

Two related bug classes existed in the schema layer that could surface as confusing runtime behaviour:

  1. panic() used as an error-signalling mechanism in visitor code. Several internal functions (addField, pruneColVisitor.Field/List/Map/projectSelectedStruct, validAvroName, sanitizeColumnNameVisitor.Field) used panic to signal validation errors. This was partially masked by a defer recover() in Visit, PreOrderVisit, and VisitSchemaWithPartner, but those recover blocks had two problems of their own:
  • String panics (e.g. panic("cannot validate empty name")) were wrapped with %s rather than %w, so the recovered error had no ErrInvalidSchema in its chain and errors.Is(err, ErrInvalidSchema) returned false.
  • All panics — both string and error — were re-wrapped with the prefix "error encountered during schema visitor: ...", leaking the internal panic/recover mechanism into caller-visible error messages.
  1. NestedField.UnmarshalJSON performs no validation of required fields. Go's encoding/json silently discards unknown keys, so a payload using "field_id" instead of "id", or "field_name" instead of "name", is accepted without error and leaves ID = 0 / Name = "". These zero values then propagate downstream and trigger the panics described above.

Changes

schema.go

  • Visit, PreOrderVisit, VisitSchemaWithPartner: recover block fixed — string panics wrapped with ErrInvalidSchema, error panics passed through directly.
  • validAvroName: panic("cannot validate empty name") → return false.
  • sanitizeName: guard added for empty input.
  • addField: reverts to panic(fmt.Errorf("%w: ...", ErrInvalidSchema, ...)) — no err field on indexByName.
  • pruneColVisitor.Field/List/Map: reverts to panic(...) — no err field, no if p.err != nil guards.
  • pruneColVisitor.projectSelectedStruct: bare string panic upgraded to typed error panic.
  • sanitizeColumnNameVisitor.Field: s.err accumulation → panic(fmt.Errorf("%w: ...", ErrInvalidSchema, ...)) — struct reverts to stateless struct{}, value receiver.
  • FindFieldByName, FindFieldByNameCaseInsensitive: propagate lazyNameToID errors instead of discarding with _.
  • Select: propagates lazyNameToID/lazyNameToIDLower errors instead of discarding with _.

types.go

  • NestedField.UnmarshalJSON: validates ID != 0 and Name != "" after decoding; returns ErrInvalidSchema on failure.

schema_test.go — two new tests:

  • TestIndexByNameDuplicateFieldNames: asserts IndexByName returns errors.Is(err, ErrInvalidSchema) with message containing "multiple fields for name".
  • TestSanitizeColumnNamesEmptyFieldName: asserts SanitizeColumnNames returns errors.Is(err, ErrInvalidSchema) with message containing "field name cannot be empty".

types_test.go — three new tests:

  • TestNestedFieldUnmarshalMissingID: absent "id" key → ErrInvalidSchema.
  • TestNestedFieldUnmarshalWrongIDKey: "field_id" instead of "id" → ErrInvalidSchema.
  • TestNestedFieldUnmarshalMissingName: absent "name" key → ErrInvalidSchema.

table/metadata_schema_compatibility_test.go

  • TestNewMetadata_DuplicateValues: replaced assert.Contains(t, err.Error(), "invalid schema: error encountered during schema visitor") with assert.ErrorIs(t, err,
    iceberg.ErrInvalidSchema) — the old assertion tested for the panic/recover wrapper that no longer appears in error messages.

table/table_test.go

  • TestAddFilesFailsSchemaMismatch: updated expected error prefix from "error encountered during schema visitor:" to "invalid schema:" — the string panic in arrow_utils.go is now
    wrapped with ErrInvalidSchema by the fixed recover.

Behaviour after this change

Scenario: json.Unmarshal with "field_id" instead of "id"
Before: Silent ID=0, no error
After: ErrInvalidSchema
────────────────────────────────────────
Scenario: json.Unmarshal with "field_name" instead of "name"
Before: Silent Name="", no error
After: ErrInvalidSchema
────────────────────────────────────────
Scenario: SanitizeColumnNames with empty field name
Before: Opaque error, errors.Is returns false
After: ErrInvalidSchema, errors.Is returns true
────────────────────────────────────────
Scenario: IndexByName with duplicate field names
Before: errors.Is works but message contained "error encountered during schema visitor:"
After: Clean message, errors.Is works
────────────────────────────────────────
Scenario: All visitor errors
Before: May contain "error encountered during schema visitor:" prefix
After: No prefix; all errors carry ErrInvalidSchema

Fixes: #757

Comment thread schema.go Resolved
Comment thread schema.go Resolved
Comment thread schema.go Resolved

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

I agree that the identified error scenarios should be properly returning an error, but I don't like the solution here. Rather than adding an err property to the visitor, the top level Visit should be properly returning that error instead. Consumers should not have to check both the err return from Visit and an err property on the visitor (which isn't exported anyways, so consumers wouldn't be able to check it)

@shtripat

Copy link
Copy Markdown
Contributor Author

I agree that the identified error scenarios should be properly returning an error, but I don't like the solution here. Rather than adding an err property to the visitor, the top level Visit should be properly returning that error instead. Consumers should not have to check both the err return from Visit and an err property on the visitor (which isn't exported anyways, so consumers wouldn't be able to check it)

Agreed, and the PR has been updated to follow this principle throughout.

The root cause was not in the visitors themselves — it was in Visit's recover block, which had two problems:

  1. String panics were wrapped with %s instead of %w, so the recovered error was not typed as ErrInvalidSchema and errors.Is returned false.
  2. Error panics were re-wrapped with "error encountered during schema visitor: %w", adding an extra prefix that leaked the internal panic/recover mechanism to callers.

Fixing those two lines in Visit (and PreOrderVisit) was all that was needed:

// before
case string:
err = fmt.Errorf("error encountered during schema visitor: %s", e)
case error:
err = fmt.Errorf("error encountered during schema visitor: %w", e)

// after
case string:
err = fmt.Errorf("%w: %s", ErrInvalidSchema, e)
case error:
err = e

With that fix in place:

  • addField, pruneColVisitor.Field/List/Map, and sanitizeColumnNameVisitor.Field all panic with a properly wrapped ErrInvalidSchema error on invalid input — no err field on any visitor struct.
  • Visit catches the panic via recover and returns it directly as the function's error return — callers only ever check the single error from Visit.
  • errors.Is(err, ErrInvalidSchema) works correctly for all paths.
  • The "error encountered during schema visitor:" prefix is gone from all error messages.

The only additional change was converting the bare string panics (panic("cannot validate empty name"), panic("expected a struct")) into error panics (panic(fmt.Errorf("%w: ...", ErrInvalidSchema, ...))) so they flow through the case error branch cleanly.

Will send new commit to take care accordingly. Thanks for valuable feedback.

@shtripat
shtripat force-pushed the input-validation-with-error-no-panic branch from cbe6f7e to 3816063 Compare February 26, 2026 05:06
Comment thread table/table_test.go Resolved
Comment thread schema.go Resolved
Comment thread schema.go Resolved
Comment thread schema.go Resolved
Comment thread schema.go Resolved
in schema visitors and add JSON field validation

This PR fixes two classes of bug that could cause runtime panics in the schema
layer:

1. **`panic()` used as an error-signalling mechanism** in schema visitor
   implementations (`indexByName`, `pruneColVisitor`, `sanitizeColumnNameVisitor`,
   `validAvroName`, `sanitizeName`). While `Visit`'s `defer recover()` masked
   these as errors at the surface, relying on panic-as-control-flow is
   non-idiomatic, loses stack context, and is fragile.

2. **Silent JSON key mismatches producing zero-value fields**. Go's
   `json.Unmarshal` ignores unknown keys, so a payload using `"field_id"`
   instead of `"id"` (or `"field_name"` instead of `"name"`) silently produces
   `ID=0` / `Name=""`. These zero values then propagate to the visitor code,
   triggering the panics described above.

The `SchemaVisitor[T]` generic interface returns only `T` per method, so error
returns cannot be added without a breaking API change. Instead, **error
accumulation** is used: visitors store a first-error in an `err` field, visitor
methods short-circuit with `if x.err != nil { return <zero> }` after an error
is set, and the calling function (`PruneColumns`, `IndexByName`, etc.) checks
the accumulated error after `Visit` returns.

Signed-off-by: Shubhendu Ram Tripathi <[email protected]>
Signed-off-by: Shubhendu Ram Tripathi <[email protected]>
@shtripat
shtripat force-pushed the input-validation-with-error-no-panic branch from 3816063 to 392b362 Compare February 26, 2026 16:20
@zeroshade

Copy link
Copy Markdown
Member

You missed one 😄 #758 (comment)

Signed-off-by: Shubhendu Ram Tripathi <[email protected]>
Comment thread types_test.go Resolved
Comment thread types_test.go Resolved
Comment thread types_test.go Resolved

@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!

@zeroshade
zeroshade merged commit 95df02c into apache:main Feb 26, 2026
12 checks passed
shtripat added a commit to shtripat/iceberg-go that referenced this pull request Mar 2, 2026
Problem

When a NestedField has a nil Type — which happens when the JSON payload uses the wrong
key (e.g. "field_type" instead of "type") or omits the "type" key entirely — two failure
modes exist:

1. NestedField.UnmarshalJSON silently accepts nil types.

Go's encoding/json leaves fields at their zero value when a key is absent or unrecognised.
Since typeIFace wraps a Type interface, the zero value is nil. UnmarshalJSON already
validates id but applies no equivalent guard to type, so a payload with a missing or misspelled
type key produces a NestedField with Type == nil and returns no error.

2. typeIFace.MarshalJSON panics on nil type.

// before
func (t *typeIFace) MarshalJSON() ([]byte, error) {
    if nested, ok := t.Type.(NestedType); ok {
        return json.Marshal(nested)
    }
    return []byte(`"` + t.Type.Type() + `"`), nil  // nil pointer dereference if t.Type == nil
}

When a schema containing a nil-type field is later marshalled (e.g. during CreateTable, CommitTable,
or any serialisation path), t.Type.Type() is a method call on a nil interface — an unrecovered panic.
There is no defer recover() in the json.Marshal call path, so the process crashes.

Example triggering input:
{
  "type": "struct",
  "fields": [
    {"id": 1, "name": "col", "field_type": "long", "required": true}
  ]
}
Before this fix: json.Unmarshal succeeds silently, subsequent json.Marshal panics.
After this fix: json.Unmarshal returns ErrInvalidSchema immediately.

Changes

types.go

NestedField.UnmarshalJSON — add a nil-type guard after decoding, consistent with the existing id and name guards introduced in PRs apache#758 and apache#761:
if n.Type == nil {
    return fmt.Errorf("%w: field %q is missing required 'type' key in JSON", ErrInvalidSchema, n.Name)
}

typeIFace.MarshalJSON — add a defensive nil guard so that a NestedField constructed programmatically with Type == nil returns an error instead of panicking:
if t.Type == nil {
    return nil, fmt.Errorf("%w: field type is nil; use the \"type\" JSON key with a valid Iceberg type such as \"long\", \"string\", or \"boolean\"", ErrInvalidSchema)
}

types_test.go — three new tests:

- TestNestedFieldUnmarshalMissingType: absent "type" key → ErrInvalidSchema
- TestNestedFieldUnmarshalWrongTypeKey: "field_type" instead of "type" → ErrInvalidSchema
- TestTypeIFaceMarshalJSONNilType: programmatically constructed NestedField{Type: nil} → json.Marshal returns ErrInvalidSchema, no panic

Behaviour after this change

|                   Scenario                    |              Before               |             After             |
|-----------------------------------------------|-----------------------------------|-------------------------------|
| "type" key absent from JSON                   | Silent nil type, panic on marshal | ErrInvalidSchema at unmarshal |
| Wrong key ("field_type") used                 | Silent nil type, panic on marshal | ErrInvalidSchema at unmarshal |
| NestedField with nil type marshalled directly | Unrecovered panic                 | ErrInvalidSchema returned     |
| Valid field with correct "type" key           | OK                                | OK (unchanged)                |

Signed-off-by: Shubhendu Ram Tripathi <[email protected]>
zeroshade pushed a commit that referenced this pull request Mar 2, 2026
### Problem

When a NestedField has a nil Type — which happens when the JSON payload
uses the wrong key (e.g. "field_type" instead of "type") or omits the
"type" key entirely — two failure modes exist:

1. NestedField.UnmarshalJSON silently accepts nil types.

Go's encoding/json leaves fields at their zero value when a key is
absent or unrecognised. Since typeIFace wraps a Type interface, the zero
value is nil. UnmarshalJSON already validates id but applies no
equivalent guard to type, so a payload with a missing or misspelled type
key produces a NestedField with Type == nil and returns no error.

2. typeIFace.MarshalJSON panics on nil type.
```
// before
func (t *typeIFace) MarshalJSON() ([]byte, error) {
    if nested, ok := t.Type.(NestedType); ok {
        return json.Marshal(nested)
    }
    return []byte(`"` + t.Type.Type() + `"`), nil  // nil pointer dereference if t.Type == nil
}
```

When a schema containing a nil-type field is later marshalled (e.g.
during CreateTable, CommitTable, or any serialisation path),
t.Type.Type() is a method call on a nil interface — an unrecovered
panic. There is no defer recover() in the json.Marshal call path, so the
process crashes.

```
Example triggering input:
{
  "type": "struct",
  "fields": [
    {"id": 1, "name": "col", "field_type": "long", "required": true}
  ]
}
```

Before this fix: json.Unmarshal succeeds silently, subsequent
json.Marshal panics. After this fix: json.Unmarshal returns
ErrInvalidSchema immediately.

### Changes

* types.go

NestedField.UnmarshalJSON — add a nil-type guard after decoding,
consistent with the existing id and name guards introduced in PRs #758
and #761: if n.Type == nil {
return fmt.Errorf("%w: field %q is missing required 'type' key in JSON",
ErrInvalidSchema, n.Name)
}

typeIFace.MarshalJSON — add a defensive nil guard so that a NestedField
constructed programmatically with Type == nil returns an error instead
of panicking: if t.Type == nil {
return nil, fmt.Errorf("%w: field type is nil; use the \"type\" JSON key
with a valid Iceberg type such as \"long\", \"string\", or \"boolean\"",
ErrInvalidSchema)
}

* types_test.go — three new tests:

** TestNestedFieldUnmarshalMissingType: absent "type" key →
ErrInvalidSchema
** TestNestedFieldUnmarshalWrongTypeKey: "field_type" instead of "type"
→ ErrInvalidSchema
** TestTypeIFaceMarshalJSONNilType: programmatically constructed
NestedField{Type: nil} → json.Marshal returns ErrInvalidSchema, no panic

### Behaviour after this change

| Scenario | Before | After |

|-----------------------------------------------|-----------------------------------|-------------------------------|
| "type" key absent from JSON | Silent nil type, panic on marshal |
ErrInvalidSchema at unmarshal |
| Wrong key ("field_type") used | Silent nil type, panic on marshal |
ErrInvalidSchema at unmarshal |
| NestedField with nil type marshalled directly | Unrecovered panic |
ErrInvalidSchema returned |
| Valid field with correct "type" key | OK | OK (unchanged) |

Signed-off-by: Shubhendu Ram Tripathi <[email protected]>
rockwotj pushed a commit to rockwotj/iceberg-go that referenced this pull request Mar 18, 2026
Two related bug classes existed in the schema layer that could surface
as confusing runtime behaviour:

1. panic() used as an error-signalling mechanism in visitor code.
Several internal functions (addField,
pruneColVisitor.Field/List/Map/projectSelectedStruct, validAvroName,
sanitizeColumnNameVisitor.Field) used panic to signal validation errors.
This was partially masked by a defer recover() in Visit, PreOrderVisit,
and VisitSchemaWithPartner, but those recover blocks had two problems of
their own:
- String panics (e.g. panic("cannot validate empty name")) were wrapped
with %s rather than %w, so the recovered error had no ErrInvalidSchema
in its chain and errors.Is(err, ErrInvalidSchema) returned false.
- All panics — both string and error — were re-wrapped with the prefix
"error encountered during schema visitor: ...", leaking the internal
panic/recover mechanism into caller-visible error messages.
2. NestedField.UnmarshalJSON performs no validation of required fields.
Go's encoding/json silently discards unknown keys, so a payload using
"field_id" instead of "id", or "field_name" instead of "name", is
accepted without error and leaves ID = 0 / Name = "". These zero values
then propagate downstream and trigger the panics described above.

### Changes

schema.go
- Visit, PreOrderVisit, VisitSchemaWithPartner: recover block fixed —
string panics wrapped with ErrInvalidSchema, error panics passed through
directly.
- validAvroName: panic("cannot validate empty name") → return false.
- sanitizeName: guard added for empty input.
- addField: reverts to panic(fmt.Errorf("%w: ...", ErrInvalidSchema,
...)) — no err field on indexByName.
- pruneColVisitor.Field/List/Map: reverts to panic(...) — no err field,
no if p.err != nil guards.
- pruneColVisitor.projectSelectedStruct: bare string panic upgraded to
typed error panic.
- sanitizeColumnNameVisitor.Field: s.err accumulation →
panic(fmt.Errorf("%w: ...", ErrInvalidSchema, ...)) — struct reverts to
stateless struct{}, value receiver.
- FindFieldByName, FindFieldByNameCaseInsensitive: propagate
lazyNameToID errors instead of discarding with _.
- Select: propagates lazyNameToID/lazyNameToIDLower errors instead of
discarding with _.

types.go
- NestedField.UnmarshalJSON: validates ID != 0 and Name != "" after
decoding; returns ErrInvalidSchema on failure.

schema_test.go — two new tests:
- TestIndexByNameDuplicateFieldNames: asserts IndexByName returns
errors.Is(err, ErrInvalidSchema) with message containing "multiple
fields for name".
- TestSanitizeColumnNamesEmptyFieldName: asserts SanitizeColumnNames
returns errors.Is(err, ErrInvalidSchema) with message containing "field
name cannot be empty".

types_test.go — three new tests:
- TestNestedFieldUnmarshalMissingID: absent "id" key → ErrInvalidSchema.
- TestNestedFieldUnmarshalWrongIDKey: "field_id" instead of "id" →
ErrInvalidSchema.
- TestNestedFieldUnmarshalMissingName: absent "name" key →
ErrInvalidSchema.

table/metadata_schema_compatibility_test.go
- TestNewMetadata_DuplicateValues: replaced assert.Contains(t,
err.Error(), "invalid schema: error encountered during schema visitor")
with assert.ErrorIs(t, err,
iceberg.ErrInvalidSchema) — the old assertion tested for the
panic/recover wrapper that no longer appears in error messages.

table/table_test.go
- TestAddFilesFailsSchemaMismatch: updated expected error prefix from
"error encountered during schema visitor:" to "invalid schema:" — the
string panic in arrow_utils.go is now
wrapped with ErrInvalidSchema by the fixed recover.

### Behaviour after this change

Scenario: json.Unmarshal with "field_id" instead of "id"
Before: Silent ID=0, no error
After: ErrInvalidSchema
────────────────────────────────────────
Scenario: json.Unmarshal with "field_name" instead of "name"
Before: Silent Name="", no error
After: ErrInvalidSchema
────────────────────────────────────────
Scenario: SanitizeColumnNames with empty field name
Before: Opaque error, errors.Is returns false
After: ErrInvalidSchema, errors.Is returns true
────────────────────────────────────────
Scenario: IndexByName with duplicate field names
Before: errors.Is works but message contained "error encountered during
schema visitor:"
After: Clean message, errors.Is works
────────────────────────────────────────
Scenario: All visitor errors
Before: May contain "error encountered during schema visitor:" prefix
After: No prefix; all errors carry ErrInvalidSchema

Fixes: apache#757

---------

Signed-off-by: Shubhendu Ram Tripathi <[email protected]>
Co-authored-by: Matt Topol <[email protected]>
rockwotj pushed a commit to rockwotj/iceberg-go that referenced this pull request Mar 18, 2026
### Problem

When a NestedField has a nil Type — which happens when the JSON payload
uses the wrong key (e.g. "field_type" instead of "type") or omits the
"type" key entirely — two failure modes exist:

1. NestedField.UnmarshalJSON silently accepts nil types.

Go's encoding/json leaves fields at their zero value when a key is
absent or unrecognised. Since typeIFace wraps a Type interface, the zero
value is nil. UnmarshalJSON already validates id but applies no
equivalent guard to type, so a payload with a missing or misspelled type
key produces a NestedField with Type == nil and returns no error.

2. typeIFace.MarshalJSON panics on nil type.
```
// before
func (t *typeIFace) MarshalJSON() ([]byte, error) {
    if nested, ok := t.Type.(NestedType); ok {
        return json.Marshal(nested)
    }
    return []byte(`"` + t.Type.Type() + `"`), nil  // nil pointer dereference if t.Type == nil
}
```

When a schema containing a nil-type field is later marshalled (e.g.
during CreateTable, CommitTable, or any serialisation path),
t.Type.Type() is a method call on a nil interface — an unrecovered
panic. There is no defer recover() in the json.Marshal call path, so the
process crashes.

```
Example triggering input:
{
  "type": "struct",
  "fields": [
    {"id": 1, "name": "col", "field_type": "long", "required": true}
  ]
}
```

Before this fix: json.Unmarshal succeeds silently, subsequent
json.Marshal panics. After this fix: json.Unmarshal returns
ErrInvalidSchema immediately.

### Changes

* types.go

NestedField.UnmarshalJSON — add a nil-type guard after decoding,
consistent with the existing id and name guards introduced in PRs apache#758
and apache#761: if n.Type == nil {
return fmt.Errorf("%w: field %q is missing required 'type' key in JSON",
ErrInvalidSchema, n.Name)
}

typeIFace.MarshalJSON — add a defensive nil guard so that a NestedField
constructed programmatically with Type == nil returns an error instead
of panicking: if t.Type == nil {
return nil, fmt.Errorf("%w: field type is nil; use the \"type\" JSON key
with a valid Iceberg type such as \"long\", \"string\", or \"boolean\"",
ErrInvalidSchema)
}

* types_test.go — three new tests:

** TestNestedFieldUnmarshalMissingType: absent "type" key →
ErrInvalidSchema
** TestNestedFieldUnmarshalWrongTypeKey: "field_type" instead of "type"
→ ErrInvalidSchema
** TestTypeIFaceMarshalJSONNilType: programmatically constructed
NestedField{Type: nil} → json.Marshal returns ErrInvalidSchema, no panic

### Behaviour after this change

| Scenario | Before | After |

|-----------------------------------------------|-----------------------------------|-------------------------------|
| "type" key absent from JSON | Silent nil type, panic on marshal |
ErrInvalidSchema at unmarshal |
| Wrong key ("field_type") used | Silent nil type, panic on marshal |
ErrInvalidSchema at unmarshal |
| NestedField with nil type marshalled directly | Unrecovered panic |
ErrInvalidSchema returned |
| Valid field with correct "type" key | OK | OK (unchanged) |

Signed-off-by: Shubhendu Ram Tripathi <[email protected]>
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.

panic() used as error-signal in schema visitor paths; silent JSON key ignore cascades to panic

2 participants