Repository navigation
feat: Implemented write-default and initial-default v3 - #779
Conversation
28484ed to
b74839e
Compare
laskoviymishka
left a comment
There was a problem hiding this comment.
Two blocking issues.
-
Wrong default field: spec violation. This is the read path. The spec says initial-default fills in missing columns for rows written before the field was added. write-default is for new writes. Java and PyIceberg both use initial-default in projection. Using write-default here breaks cross-client correctness silently — the values can diverge after schema evolution.
-
All type assertions panic on real metadata. encoding/json unmarshals numbers into any as float64 and strings as string. None of iceberg.Date, iceberg.Timestamp, uuid.UUID, etc. will ever appear in v when the field comes from a REST catalog or metadata file. Every bare type assertion in this switch will panic. The tests pass only because they construct NestedField directly in Go, bypassing deserialization. A round-trip test through json.Unmarshal would expose this immediately.
| dt := retOrPanic(TypeToArrowType(field.Type, false, a.useLargeTypes)) | ||
|
|
||
| arr = array.MakeArrayOfNull(compute.GetAllocator(a.ctx), dt, structArr.Len()) | ||
| if field.WriteDefault != nil { |
There was a problem hiding this comment.
Use field.InitialDefault instead. write-default is for new writes; initial-default is what fills missing columns on the read path. Change the condition and the value passed to writeDefaultToArray.
There was a problem hiding this comment.
Thank you for your comments! I'll fix all of them, but I needed alignment on this one.
The reason I modified this function specifically was because I believed that it was used in the write path. After reading your comments, it seems to me that ToRequestedSchema() and by extension Struct() are used in both the read and write paths. Is my understanding of this correct?
If my understanding is correct, we need to provide information on which path is being executed, to determine which default value to use. I think the safest and most backwards compatible way to solve this would involve adding a flag to the arrowProjectionVisitor struct. Let me know what you think!
There was a problem hiding this comment.
initial-default and write-default are typically the same value when a field is first added. They only diverge if the default is changed after the fact (which the spec allows). So for most real data today the bug would be invisible — but it's still a spec violation and will bite cross-client scenarios where they've diverged.
There was a problem hiding this comment.
I agree, but if I'm not wrong, this code is used on both read and write paths.
Write path: WriteFile -> ToRequestedSchema -> VisitSchemaWithPartner -> visitStructWithPartner -> Struct
As you mentioned it’s used in the read path as well.
Since it’s used on both paths, won’t we need context on which path is being executed? If we use InitialDefault then it will provide the wrong default values on write paths. Feel free to correct me, if there’s any misunderstanding.
There was a problem hiding this comment.
You're correct. ToRequestedSchema is used in both paths — read (arrow_scanner.go) and write (writer.go, rolling_data_writer.go).
A flag is the right fix, but put it on ToRequestedSchema's signature rather than the internal struct, so call sites are explicit. The write-path callers pass true (use write-default), read-path callers pass false (use initial-default). The visitor stores it internally.
There was a problem hiding this comment.
I believe that modifying the signature of ToRequestedSchema would also require me to change the signature of the other listed functions such as VisitSchemaWithPartner, visitStructWithPartner, and Struct to propagate the flag.
My issue with this is that some of these functions such as VisitSchemaWithPartner seem to be used outside the scope of basic reading and writing. For example, VisitSchemaWithPartner is used by name_mapping, and I'm not sure what flag I would pass in here.
I fear that changing all of the signatures may be too large and critical of a change. Let me know your thoughts.
There was a problem hiding this comment.
You don't need to change VisitSchemaWithPartner or any of the visitor interface signatures. The flag belongs on ToRequestedSchema only — it already has multiple bool params. Internally, store it on the arrowProjectionVisitor struct (which is private), and use it in Struct() to decide between field.WriteDefault and field.InitialDefault.
Concretely:
- Add a useWriteDefault bool parameter to ToRequestedSchema
- Store it in arrowProjectionVisitor struct
- In Struct(), check a.useWriteDefault to pick field.WriteDefault vs field.InitialDefault
The call sites are:
- Write path (writer.go:120, rolling_data_writer.go:334): pass true
- Read path (arrow_scanner.go:513, arrow_scanner.go:585): pass false
VisitSchemaWithPartner and name_mapping are untouched — the flag lives entirely within the arrow projection layer.
There was a problem hiding this comment.
Thank you for the clarification, arrowProjectionVisitor was the struct I intended on modifying. Maybe I misunderstood what you meant when you mentioned the internal struct. Now that we have alignment, I'll make the change
| func writeDefaultToScalar(v any, t iceberg.Type, dt arrow.DataType) scalar.Scalar { | ||
| switch t.(type) { | ||
| case iceberg.DateType: | ||
| return scalar.NewDate32Scalar(arrow.Date32(v.(iceberg.Date))) |
There was a problem hiding this comment.
Panics if v is not exactly iceberg.Date. When this field comes from JSON (REST catalog, metadata file), v will be float64 — not iceberg.Date. Same problem applies to every assertion in this
switch: iceberg.Time, iceberg.Timestamp, iceberg.TimestampNano, iceberg.Decimal.
There was a problem hiding this comment.
To clarify the remaining work here: writeDefaultToScalar needs to handle the actual runtime types that appear after JSON deserialization (float64, string, json.Number), not just the Go-native Iceberg types.
For example:
- iceberg.Date → may arrive as float64 from JSON, needs int32(v.(float64))
- uuid.UUID → may arrive as string, needs uuid.Parse(v.(string))
- iceberg.Timestamp → may arrive as float64
- iceberg.Decimal → check how it's deserialized in the schema JSON path
Each case in the switch should handle both the typed Iceberg value (from programmatic construction) and the JSON-deserialized form. Use type switches on v within each case to handle both, and panic with fmt.Errorf including the field type, Go type of v, and value if the conversion fails.
Also, narrow the extension type check to *extensions.UUIDType specifically, as I mentioned earlier.
| case iceberg.TimestampNsType, iceberg.TimestampTzNsType: | ||
| return scalar.NewTimestampScalar(arrow.Timestamp(v.(iceberg.TimestampNano)), dt) | ||
| case iceberg.UUIDType: | ||
| u := v.(uuid.UUID) |
There was a problem hiding this comment.
Same. UUID stored in JSON is a string. v.(uuid.UUID) panics on any deserialized metadata.
|
|
||
| return scalar.NewDecimal128Scalar(d.Val, dt) | ||
| default: | ||
| return retOrPanic(scalar.MakeScalarParam(v, dt)) |
There was a problem hiding this comment.
retOrPanic converts the error into a panic with no context — no field name, no type, no value. Hard to debug in production.
AVOID PANIC AT ALL COST.
There was a problem hiding this comment.
I understand why we shouldn't use retOrPanic now. Since Struct is bound by the visitor interface and can't return an error, how would you suggest propagating errors from writeDefaultToArray? Struct currently panics when handling errors
There was a problem hiding this comment.
fair, seems like visitor will catch this panic and wrap in proper error.
writeDefaultToArray should panic with a descriptive fmt.Errorf(...) and Visit will catch it.
| // writeDefaultToArray creates an Arrow array of length n filled with the write-default value v. | ||
| func writeDefaultToArray(v any, t iceberg.Type, dt arrow.DataType, n int, alloc memory.Allocator) arrow.Array { | ||
| out := retOrPanic(scalar.MakeArrayFromScalar(writeDefaultToScalar(v, t, dt), n, alloc)) | ||
| if _, ok := dt.(arrow.ExtensionType); ok { |
There was a problem hiding this comment.
This branch is UUID-specific but matches all extension types. A future extension type will hit this path and silently produce wrong data (child arrays set to nil).
Either narrow the check to *extensions.UUIDType or add a comment stating this only applies to UUID.
| assert.True(t, array.RecordEqual(rec, rec2)) | ||
| } | ||
|
|
||
| func TestToRequestedSchemaWriteDefaults(t *testing.T) { |
There was a problem hiding this comment.
Worse to add at least one round-trip through JSON.
Add at least one test that unmarshals a NestedField from a JSON snippet (as it would arrive from a metadata file or REST catalog) and then projects it. That test will expose the type assertion panics described above.
There was a problem hiding this comment.
Added tests that cover every type in JSON or both read and write
laskoviymishka
left a comment
There was a problem hiding this comment.
LGTM.
Two nits:
- Add a test for "prefers write-default over initial-default on write path" (the read-path equivalent exists but not the write-path one)
- writeDefaultToScalar/writeDefaultToArray now handle both write-default and initial-default — maybe renaming to defaultToScalar/defaultToArray?
| func numericDefault[T ~int32 | ~int64 | ~float32 | ~float64](v any) T { | ||
| switch val := v.(type) { | ||
| case T: | ||
| return val | ||
| case float64: | ||
| return T(val) | ||
| } |
There was a problem hiding this comment.
we always get either the T we wanted or float64?
There was a problem hiding this comment.
Yeah. The point of this is that when we are unmarshalling, it will always produce a float 64 instead of an actual value.
If the value passed in programatically through Go, then you don't need to unmarshall it and you just return the value.
If it is a float64 from JSON unmarshalling, you want to cast it.
There was a problem hiding this comment.
btw - it could be not just float64, it could be also json.Number (which is basically string wrapper)>
There was a problem hiding this comment.
Good catch. added an additional branch and test for this
| } | ||
|
|
||
| // defaultToScalar converts an Iceberg default value to an Arrow scalar. | ||
| func defaultToScalar(v any, t iceberg.Type, dt arrow.DataType) scalar.Scalar { |
There was a problem hiding this comment.
it might make sense to fix MakeScalarParam for some of these cases instead to simplify this
There was a problem hiding this comment.
MakeScalarParam is not from our codebase. That's owned by Apache Arrow
There was a problem hiding this comment.
yup, which is an apache open source project. 😄 I'll see if I can find some time to improve it on that end, I don't consider this a blocker though.
| if _, ok := dt.(*extensions.UUIDType); ok { | ||
| defer out.Release() | ||
|
|
||
| data := array.NewData(dt, out.Len(), out.Data().Buffers(), nil, out.NullN(), 0) | ||
| defer data.Release() | ||
|
|
||
| return array.MakeFromData(data) | ||
| } |
There was a problem hiding this comment.
MakeArrayFromScalar doesn't support extension scalars in this version of Arrow Go. Instead we give it a FixedSizeBinary scalar, which it can handle. Then we rewrap the array with the UUID type.
There was a problem hiding this comment.
Bah, well that's annoying. I'll have to fix that...
| converted, err := ToRequestedSchema(r.ctx, r.factory.fileSchema, | ||
| r.factory.taskSchema, record, false, true, false) | ||
| r.factory.taskSchema, record, false, true, false, true) |
There was a problem hiding this comment.
okay we REALLY need to convert ToRequestedSchema to take a struct or something instead of this collection of bools so we know what each actually stands for at call sites....
There was a problem hiding this comment.
that's fair. Ill make that change
|
Looks like we have a flaky test "TestIsInFilterTable." This is unrelated to my changes. I can publish it in a separate Github Issue but basically recordBatchesFromTasksAndDeletes spawns multiple worker goroutines which has IsIn. IsIn has internal state which isn't thread safe. It doesn't have anything to do with my changes though. |
|
You don't need to file an issue as @laskoviymishka already pushed a fix to arrow-go in apache/arrow-go@7ae2e33, the fix just hasn't gotten a release yet. It'll get picked up with the next release when we upgrade the dependency here. |
|
@zeroshade. Are there any additional changes you want to see or any blockers? Are we ready to merge? |
zeroshade
left a comment
There was a problem hiding this comment.
This looks good, i don't think the changes I mentioned are blockers. I'll look into making those improvements in arrow-go and then we can come back and simplify this at that point.
Thanks!
## Changes Bumps arrow-go to [88561cf](apache/arrow-go@88561cf) to pick up apache/arrow-go#840 and [#841](apache/arrow-go#841) (variant fixes; neither reachable via iceberg-go's public API). The bump window includes unrelated Parquet encoder changes (arrow-go #779/#786/#807) that produce different output bytes; tests asserting exact file/column sizes are updated accordingly. Adds defensive coverage at the variant boundary in literals_test.go and table/arrow_utils_test.go. Will follow up to swap the pseudo-version for a tagged release when arrow-go cuts one. Refs #929
iceberg-cli 0.6.0 Created-by: HarmonybrewBot Commit-by: HarmonybrewBot Merged-by: HarmonybrewBot Description: Created by `brew bump` --- Created with `brew bump-formula-pr`.<details> <summary>release notes</summary> <pre>## What's Changed * build(deps): bump the gomod_updates group with 18 updates by @dependabot[bot] in apache/iceberg-go#763 * build(deps): bump go.opentelemetry.io/otel/sdk from 1.39.0 to 1.40.0 by @dependabot[bot] in apache/iceberg-go#764 * fix: nil field Type causes unrecovered panic in MarshalJSON by @shtripat in apache/iceberg-go#765 * fix(manifest): handle lifecycle of the decoder in reader by @ferhatelmas in apache/iceberg-go#766 * feat(rest): add RegisterView to REST catalog by @shtripat in apache/iceberg-go#753 * fix(table): fix refcount leak in enrichRecordsWithPosDeleteFields by @laskoviymishka in apache/iceberg-go#762 * chore: Update copyright year in NOTICE file by @zeroshade in apache/iceberg-go#771 * refactor: make partition spec and sort order fields range friendly by @ferhatelmas in apache/iceberg-go#772 * feat(table): roll parquet files based on actual compressed size by @twuebi in apache/iceberg-go#759 * fix(table): ensure partition path is deterministic by @ferhatelmas in apache/iceberg-go#767 * build(deps): bump the gomod_updates group across 1 directory with 12 updates by @dependabot[bot] in apache/iceberg-go#782 * fix: skip pageSize query param when value is 0 by @alessandro-nori in apache/iceberg-go#778 * fix: handle LargeString columns in partition transforms by @hamilton-earthscope in apache/iceberg-go#780 * fix(table): removeSnaphosts postCommit now takes effect by @starpact in apache/iceberg-go#783 * feat: Implemented write-default and initial-default v3 by @PranjalChaitanya in apache/iceberg-go#779 * feat(table): add Scan.ReadTasks for reading pre-planned file scan tasks by @twuebi in apache/iceberg-go#781 * feat(table): export StructLike and GetPartitionRecord by @twuebi in apache/iceberg-go#791 * feat(catalog): refresh oauth tokens by @rockwotj in apache/iceberg-go#793 * feat(table): public write DataFile API by @twuebi in apache/iceberg-go#776 * fix: remove unnecessary safe-guard by @twuebi in apache/iceberg-go#775 * fix(table): don't always set schema.name-mapping.default by @rockwotj in apache/iceberg-go#803 * build(deps): bump google.golang.org/grpc from 1.79.2 to 1.79.3 by @dependabot[bot] in apache/iceberg-go#804 * feat(table): add RowDelta API for atomic row-level mutations by @laskoviymishka in apache/iceberg-go#789 * feate(hive): Add Create View for Hive catalog by @dttung2905 in apache/iceberg-go#788 * build(deps): bump the gomod_updates group with 2 updates by @dependabot[bot] in apache/iceberg-go#807 * fix(table): AddFiles: close file after usage and parallelize by @starpact in apache/iceberg-go#799 * feat(catalog): add TransactionalCatalog interface and REST multi-table commit by @laskoviymishka in apache/iceberg-go#787 * feat(catalog,io): refresh vended credentials by @rockwotj in apache/iceberg-go#795 * fix(table): AddFiles() should respect commit.manifest-merge.enabled by @RSP22 in apache/iceberg-go#806 * feat(table): configure Parquet DataPage version by @laskoviymishka in apache/iceberg-go#812 * chore: add CODEOWNERS file by @zeroshade in apache/iceberg-go#814 * fix(table): deadlock in MapExec when workers error by @laskoviymishka in apache/iceberg-go#810 * fix(table): add warnings for silent data-affecting behavior by @laskoviymishka in apache/iceberg-go#811 * build(deps): bump github.com/moby/buildkit from 0.27.1 to 0.28.1 by @dependabot[bot] in apache/iceberg-go#813 * feat(hive): adding register table in hive catalog by @Hashcode-Ankit in apache/iceberg-go#816 * feat(table): equality delete write path by @laskoviymishka in apache/iceberg-go#809 * feat(catalog): add CommitAndReload, error ctx, and 404 test for multi-tx by @laskoviymishka in apache/iceberg-go#817 * feat(types): add Parquet support for nanosecond timestamp types (v3) by @laskoviymishka in apache/iceberg-go#819 * build(deps): bump the gomod_updates group with 6 updates by @dependabot[bot] in apache/iceberg-go#822 * feat(table): enforce write-default and initial-default for required fields by @laskoviymishka in apache/iceberg-go#820 * feat(table): equality delete read path in scanner by @laskoviymishka in apache/iceberg-go#818 * feat(rest): add audience and resource params to OAuth requests by @lovromazgon in apache/iceberg-go#815 * feat(table): equality delete writing for partitioned tables by @laskoviymishka in apache/iceberg-go#823 * fix(table): goroutine leak in positionDeleteRecordsToDataFiles by @hcrosse in apache/iceberg-go#825 * fix(manifest): default to v1 files by @rockwotj in apache/iceberg-go#826 * feat(table): add Transaction.UpgradeFormatVersion by @rockwotj in apache/iceberg-go#827 * feat(table): multi-arg transforms in partition and sort fields by @laskoviymishka in apache/iceberg-go#824 * build(deps): bump github.com/go-jose/go-jose/v4 from 4.1.3 to 4.1.4 by @dependabot[bot] in apache/iceberg-go#828 * Thread context.Context through deletedEntries() by @Herrtian in apache/iceberg-go#847 * feat(table): Add statistics files to orphan cleanup referenced set by @dttung2905 in apache/iceberg-go#848 * build(deps): bump the gomod_updates group with 5 updates by @dependabot[bot] in apache/iceberg-go#854 * fix(ci): resolve flaky integration-setup by @laskoviymishka in apache/iceberg-go#858 * bench(table): read-perf degradation under equality delete pressure by @laskoviymishka in apache/iceberg-go#852 * fix(table): read Parquet batch size from table properties by @gabrnavarro in apache/iceberg-go#849 * feat(table): Add OpReplace to updateSnapshotSummaries by @dttung2905 in apache/iceberg-go#853 * feat(table): strengthen orphan-cleanup stats referenced-set tests and document empty-path guard by @dttung2905 in apache/iceberg-go#856 * fix: require Transform in NewSortOrder and add related tests by @Narwhal-fish in apache/iceberg-go#859 * feat(table): support delete file removal in overwrite commits by @laskoviymishka in apache/iceberg-go#851 * feat(table): classify deletion vectors in scan planning by @laskoviymishka in apache/iceberg-go#855 * build(deps): bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.41.0 to 1.43.0 by @dependabot[bot] in apache/iceberg-go#864 * feat(table): add bin-pack compaction strategy by @laskoviymishka in apache/iceberg-go#850 * build(deps): bump go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp from 1.38.0 to 1.43.0 by @dependabot[bot] in apache/iceberg-go#862 * fix: handle missing format-version in NewManifestReader for v1 manifests by @rockwotj in apache/iceberg-go#868 * docs: expand CONTRIBUTING.md with issue claiming and PR guidelines by @laskoviymishka in apache/iceberg-go#887 * build(deps): bump the gomod_updates group with 4 updates by @dependabot[bot] in apache/iceberg-go#872 * fix(table): prune StatisticsList and PartitionStatsList in RemoveSnapshots by @alliasgher in apache/iceberg-go#873 * fix(table): read retention table properties as defaults in ExpireSnapshots by @alliasgher in apache/iceberg-go#877 * feat(table): wire bloom filter properties into Parquet writer by @alliasgher in apache/iceberg-go#878 * fix(table): populate WriteTask.SortOrderID in data file writers by @alliasgher in apache/iceberg-go#875 * fix(schema): reject duplicate field IDs at schema construction by @alliasgher in apache/iceberg-go#879 * fix: emit proper Avro fixed schema for FixedType partition columns (#845) by @tanmayrauth in apache/iceberg-go#881 * fix(table): delete statistics files in ExpireSnapshots PostCommit #837 by @tanmayrauth in apache/iceberg-go#882 * refactor(table): collapse DataFileStatistics.ToDataFile args into DataFileOpts by @alliasgher in apache/iceberg-go#888 * perf(table): Decrease memory pressure by releasing records by @abhirathod95 in apache/iceberg-go#886 * fix(deletes): change equality_ids array elements avro schema type from Long to Integer to match spec by @rohilsurana in apache/iceberg-go#880 * feat(avro): replace hamba/avro with twmb/avro v1.5.0 by @twmb in apache/iceberg-go#871 * feat(compaction): add Analyze for dry-run compaction planning by @laskoviymishka in https://github.com/apache/iceberg-go/pull/ See merge request: Harmonybrew/homebrew-core!9291
Part of #589
This PR implements support for write-default values when projecting Arrow batches in
ToRequestedSchema. If a column is not provided but there is aWriteDefaultspecified in the schema, it will create a column populated with the default value.To generate the column, this PR uses the method
MakeArrayFromScalar(). This is similar to how PyIceberg handles write-defaults.One complication I ran into was converting Iceberg default values into Arrow scalars. In the schema, WriteDefault is stored as any, which means the concrete Go type information is lost at compile time. Iceberg default values are often stored using named Go types such as Date, Time, or Timestamp, which wrap primitive values like int32 or int64. Arrow’s scalar helpers (
MakeScalar,MakeScalarParam) infer the scalar type from the Go value, and since these Iceberg types are not the same as Arrow’s own types (such asarrow.Date32), Arrow may interpret them as generic numeric scalars instead of their intended logical types.For example, an iceberg.Date may be interpreted as a generic integer rather than a date32 scalar. While the numeric value would still be correct, the resulting Arrow array would have the wrong logical type.
Java and Python implementations don’t run into this issue in the same way. From what I can tell, Java's core writers do not seem to be using Arrow. In Python, pa.scalar(value, type=...) explicitly specifies the Arrow type during scalar construction, so PyArrow does not need to infer the type from the Python value.
Because Go stores the default as
anyin the schema, some runtime dispatch is required to normalize the value before constructing the Arrow scalar. The implementation in this PR handles those cases to ensure the resulting Arrow array matches the schema’s logical type.I added tests to test Write-Default across different iceberg types.
If there is a simpler or more idiomatic way to perform this conversion within the Arrow or Iceberg-Go codebase, I would be very open to changing the implementation.