zeroshade commented on code in PR #1492:
URL: https://github.com/apache/iceberg-go/pull/1492#discussion_r3631902590


##########
catalog/rest/scan_task_decoder_test.go:
##########
@@ -0,0 +1,544 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package rest
+
+import (
+       "encoding/json"
+       "testing"
+
+       "github.com/apache/iceberg-go"
+       "github.com/apache/iceberg-go/table"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+func TestDecodeScanTasksFullPayload(t *testing.T) {
+       t.Parallel()
+
+       metadata := newScanTaskDecoderMetadata()
+       var wire ScanTasks
+       require.NoError(t, json.Unmarshal([]byte(`{
+               "file-scan-tasks": [{
+                       "data-file": {
+                               "spec-id": 7,
+                               "partition": [34, "2026-07-17", "78797A21"],
+                               "content": "data",
+                               "file-path": "s3://bucket/table/data.parquet",
+                               "file-format": "parquet",
+                               "file-size-in-bytes": 4096,
+                               "record-count": 100,
+                               "key-metadata": "0A0B",
+                               "split-offsets": [4, 128],
+                               "sort-order-id": 3,
+                               "first-row-id": 99,
+                               "column-sizes": {"keys": [1, 2], "values": 
[800, 1200]},
+                               "value-counts": {"keys": [1, 2], "values": 
[100, 100]},
+                               "null-value-counts": {"keys": [1, 2], "values": 
[0, 1]},
+                               "nan-value-counts": {"keys": [7], "values": 
[2]},
+                               "lower-bounds": {
+                                       "keys": [8, 9],
+                                       "values": ["01000000", "02000000"]
+                               },
+                               "upper-bounds": {
+                                       "keys": [8, 9],
+                                       "values": ["05000000", "0A000000"]
+                               }
+                       },
+                       "delete-file-references": [0, 1, 2],
+                       "residual-filter": {"type": "eq", "term": "id", 
"value": 34}
+               }],
+               "delete-files": [
+                       {
+                               "spec-id": 7,
+                               "partition": [34, "2026-07-17", "78797A21"],
+                               "content": "position-deletes",
+                               "file-path": 
"s3://bucket/table/pos-delete.parquet",
+                               "file-format": "parquet",
+                               "file-size-in-bytes": 512,
+                               "record-count": 5
+                       },
+                       {
+                               "spec-id": 7,
+                               "partition": [34, "2026-07-17", "78797A21"],
+                               "content": "equality-deletes",
+                               "file-path": 
"s3://bucket/table/eq-delete.parquet",
+                               "file-format": "parquet",
+                               "file-size-in-bytes": 256,
+                               "record-count": 3,
+                               "equality-ids": [1, 2]
+                       },
+                       {
+                               "spec-id": 7,
+                               "partition": [34, "2026-07-17", "78797A21"],
+                               "content": "position-deletes",
+                               "file-path": "s3://bucket/table/deletes.puffin",
+                               "file-format": "puffin",
+                               "file-size-in-bytes": 1024,
+                               "record-count": 7,
+                               "referenced-data-file": 
"s3://bucket/table/data.parquet",
+                               "content-offset": 25,
+                               "content-size-in-bytes": 50
+                       }
+               ]
+       }`), &wire))
+
+       tasks, err := DecodeScanTasks(wire, metadata, metadata.schema, 
iceberg.AlwaysTrue{})
+       require.NoError(t, err)
+       require.Len(t, tasks, 1)
+
+       task := tasks[0]
+       assert.Equal(t, "s3://bucket/table/data.parquet", task.File.FilePath())
+       assert.Equal(t, int64(4096), task.Length)
+       assert.Zero(t, task.Start)
+       assert.Equal(t, map[int]any{
+               1000: int64(34),
+               1001: iceberg.Date(20651),
+               1002: []byte("xyz!"),
+       }, task.File.Partition())
+       assert.Equal(t, []byte{0x0a, 0x0b}, task.File.KeyMetadata())
+       assert.Equal(t, []int64{4, 128}, task.File.SplitOffsets())
+       assert.Equal(t, intPtr(3), task.File.SortOrderID())
+       assert.Equal(t, int64Ptr(99), task.FirstRowID)
+       assert.Equal(t, map[int]int64{1: 800, 2: 1200}, task.File.ColumnSizes())
+       assert.Equal(t, map[int]int64{1: 100, 2: 100}, task.File.ValueCounts())
+       assert.Equal(t, map[int]int64{1: 0, 2: 1}, task.File.NullValueCounts())
+       assert.Equal(t, map[int]int64{7: 2}, task.File.NaNValueCounts())
+
+       // These vectors mirror Java TestContentFileParser: bounds are 
hexadecimal
+       // encodings of raw Iceberg binary values, not typed JSON single-values.
+       assert.Equal(t, []byte{1, 0, 0, 0}, task.File.LowerBoundValues()[8])
+       assert.Equal(t, []byte{2, 0, 0, 0}, task.File.LowerBoundValues()[9])
+       assert.Equal(t, []byte{5, 0, 0, 0}, task.File.UpperBoundValues()[8])
+       assert.Equal(t, []byte{10, 0, 0, 0}, task.File.UpperBoundValues()[9])
+
+       require.NotNil(t, task.Residual)
+       assert.True(t, 
task.Residual.Equals(iceberg.EqualTo(iceberg.Reference("id"), int64(34))))
+       require.Len(t, task.DeleteFiles, 1)
+       assert.Equal(t, "s3://bucket/table/pos-delete.parquet", 
task.DeleteFiles[0].FilePath())
+       require.Len(t, task.EqualityDeleteFiles, 1)
+       assert.Equal(t, []int{1, 2}, 
task.EqualityDeleteFiles[0].EqualityFieldIDs())
+       require.Len(t, task.DeletionVectorFiles, 1)
+       dv := task.DeletionVectorFiles[0]
+       assert.Equal(t, iceberg.PuffinFile, dv.FileFormat())
+       assert.Equal(t, stringPtr("s3://bucket/table/data.parquet"), 
dv.ReferencedDataFile())
+       assert.Equal(t, int64Ptr(25), dv.ContentOffset())
+       assert.Equal(t, int64Ptr(50), dv.ContentSizeInBytes())
+}
+
+func TestDecodeScanTasksUsesFallbackAndAcceptsSpecConstants(t *testing.T) {
+       t.Parallel()
+
+       metadata := newScanTaskDecoderMetadata()
+       fallback := iceberg.GreaterThan(iceberg.Reference("id"), int64(10))
+       wire := validScanTasksWire()
+
+       tasks, err := DecodeScanTasks(wire, metadata, metadata.schema, fallback)
+       require.NoError(t, err)
+       require.Len(t, tasks, 1)
+       assert.Same(t, fallback, tasks[0].Residual)
+
+       wire.FileScanTasks[0].ResidualFilter = 
json.RawMessage(`{"type":"false"}`)
+       tasks, err = DecodeScanTasks(wire, metadata, metadata.schema, fallback)
+       require.NoError(t, err)
+       assert.True(t, tasks[0].Residual.Equals(iceberg.AlwaysFalse{}))
+}
+
+func TestDecodeScanTasksKeepsDeleteReferencesEnvelopeLocal(t *testing.T) {
+       t.Parallel()
+
+       metadata := newScanTaskDecoderMetadata()
+       first := validScanTasksWire()
+       first.FileScanTasks[0].DeleteFileReferences = []int{0}
+       first.DeleteFiles[0].FilePath = "s3://bucket/table/first-delete.parquet"
+       second := validScanTasksWire()
+       second.FileScanTasks[0].DataFile.FilePath = 
"s3://bucket/table/second-data.parquet"
+       second.FileScanTasks[0].DeleteFileReferences = []int{0}
+       second.DeleteFiles[0].FilePath = 
"s3://bucket/table/second-delete.parquet"
+
+       firstTasks, err := DecodeScanTasks(first, metadata, metadata.schema, 
nil)
+       require.NoError(t, err)
+       secondTasks, err := DecodeScanTasks(second, metadata, metadata.schema, 
nil)
+       require.NoError(t, err)
+
+       require.Len(t, firstTasks, 1)
+       require.Len(t, firstTasks[0].DeleteFiles, 1)
+       assert.Equal(t, "s3://bucket/table/first-delete.parquet", 
firstTasks[0].DeleteFiles[0].FilePath())
+       require.Len(t, secondTasks, 1)
+       require.Len(t, secondTasks[0].DeleteFiles, 1)
+       assert.Equal(t, "s3://bucket/table/second-delete.parquet", 
secondTasks[0].DeleteFiles[0].FilePath())
+}
+
+func TestDecodeScanTasksDerivesDeletionVectorTargetWhenOmitted(t *testing.T) {
+       t.Parallel()
+
+       metadata := newScanTaskDecoderMetadata()
+       wire := validScanTasksWire()
+       wire.FileScanTasks[0].DeleteFileReferences = []int{0}
+       wire.DeleteFiles[0].FileFormat = "puffin"
+       wire.DeleteFiles[0].ContentOffset = int64Ptr(10)
+       wire.DeleteFiles[0].ContentSizeInBytes = int64Ptr(20)
+
+       tasks, err := DecodeScanTasks(wire, metadata, metadata.schema, nil)
+       require.NoError(t, err)
+       require.Len(t, tasks, 1)
+       require.Len(t, tasks[0].DeletionVectorFiles, 1)
+       assert.Equal(t, stringPtr("s3://bucket/table/data.parquet"), 
tasks[0].DeletionVectorFiles[0].ReferencedDataFile())
+}
+
+func TestRESTValueMapMatchesJavaContentFileParser(t *testing.T) {

Review Comment:
   Non-blocking: this asserts bounds round-trip to raw bytes (correct, and 
matches how they're stored). Since these vectors mirror Java's 
`TestContentFileParser`, a `LiteralFromBytes(field.Type, ...)` assertion for a 
couple of representative types (e.g. int + decimal + timestamp) would 
additionally pin endianness/type-dispatch. Low priority since it exercises the 
shared decode path rather than this PR's code.



##########
catalog/rest/scan_task_decoder.go:
##########
@@ -0,0 +1,716 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package rest
+
+import (
+       "bytes"
+       "encoding/hex"
+       "encoding/json"
+       "errors"
+       "fmt"
+       "math"
+       "slices"
+
+       "github.com/apache/iceberg-go"
+       "github.com/apache/iceberg-go/table"
+       "github.com/twmb/avro/atype"
+)
+
+// The exported REST wire types below are intentional: the low-level planning
+// methods expose ScanTasks directly, while DecodeScanTasks is the boundary for
+// callers that want table.FileScanTask domain objects.
+
+// RESTCountMap is the REST column-id-to-count representation. Keys and values
+// are parallel arrays because JSON object keys cannot preserve integer IDs.
+type RESTCountMap struct {
+       Keys   []int   `json:"keys"`
+       Values []int64 `json:"values"`
+}
+
+// RESTValueMap is the REST column-id-to-binary representation used for lower
+// and upper bounds. Java's ContentFileParser encodes each raw Iceberg binary
+// value as a hexadecimal string; these are not typed JSON partition values.
+type RESTValueMap struct {
+       Keys   []int    `json:"keys"`
+       Values []string `json:"values"`
+}
+
+// RESTContentFile contains the fields common to REST data and delete files.
+// Partition values remain raw until DecodeScanTasks resolves spec-id and the
+// result type of each partition transform.
+type RESTContentFile struct {
+       SpecID          int               `json:"spec-id"`
+       Partition       []json.RawMessage `json:"partition"`
+       Content         string            `json:"content"`
+       FilePath        string            `json:"file-path"`
+       FileFormat      string            `json:"file-format"`
+       FileSizeInBytes int64             `json:"file-size-in-bytes"`
+       RecordCount     int64             `json:"record-count"`
+       KeyMetadata     *string           `json:"key-metadata,omitempty"`
+       SplitOffsets    []int64           `json:"split-offsets,omitempty"`
+       SortOrderID     *int              `json:"sort-order-id,omitempty"`
+}
+
+// RESTDataFile is the data-file arm of the REST ContentFile union.
+type RESTDataFile struct {
+       RESTContentFile
+
+       FirstRowID      *int64        `json:"first-row-id,omitempty"`
+       ColumnSizes     *RESTCountMap `json:"column-sizes,omitempty"`
+       ValueCounts     *RESTCountMap `json:"value-counts,omitempty"`
+       NullValueCounts *RESTCountMap `json:"null-value-counts,omitempty"`
+       NaNValueCounts  *RESTCountMap `json:"nan-value-counts,omitempty"`
+       LowerBounds     *RESTValueMap `json:"lower-bounds,omitempty"`
+       UpperBounds     *RESTValueMap `json:"upper-bounds,omitempty"`
+}
+
+// RESTFileScanTask is the REST FileScanTask wire payload. Delete references
+// are zero-based indices into the DeleteFiles slice of the same ScanTasks
+// envelope; they must be resolved before responses are combined.
+type RESTFileScanTask struct {
+       DataFile             *RESTDataFile   `json:"data-file"`
+       DeleteFileReferences []int           
`json:"delete-file-references,omitempty"`
+       ResidualFilter       json.RawMessage `json:"residual-filter,omitempty"`
+}
+
+// RESTDeleteFile is the position/equality arm of the REST ContentFile union.
+// Content discriminates the variant. Puffin position deletes are decoded as
+// deletion vectors and associated with the data file that references them.
+type RESTDeleteFile struct {
+       RESTContentFile
+
+       EqualityIDs []int `json:"equality-ids,omitempty"`
+       // ReferencedDataFile is emitted by Java's ContentFileParser for
+       // file-scoped position deletes and deletion vectors. It is not 
currently
+       // declared by the REST OpenAPI DeleteFile schema, so clients must also
+       // support deriving a DV's target from its FileScanTask association.
+       ReferencedDataFile *string `json:"referenced-data-file,omitempty"`
+       ContentOffset      *int64  `json:"content-offset,omitempty"`
+       ContentSizeInBytes *int64  `json:"content-size-in-bytes,omitempty"`
+}
+
+// DecodeScanTasks converts one REST ScanTasks envelope into domain scan tasks.
+// Delete-file references are scoped to one envelope, so callers must invoke
+// this before combining inline and fetchScanTasks responses.
+//
+// schema is the schema selected for the scan and is used to decode residual
+// literals. When nil, metadata.CurrentSchema is used.
+// fallbackResidual is used when a task omits residual-filter, as required by
+// the REST specification; it is commonly the original scan filter.
+func DecodeScanTasks(
+       wire ScanTasks,
+       metadata table.ScanPlanningMetadata,
+       schema *iceberg.Schema,
+       fallbackResidual iceberg.BooleanExpression,
+) ([]table.FileScanTask, error) {
+       if metadata == nil {
+               return nil, fmt.Errorf("%w: decoding scan tasks: table metadata 
is required", ErrRESTError)
+       }
+       if schema == nil {
+               schema = metadata.CurrentSchema()
+       }
+       if schema == nil {
+               return nil, fmt.Errorf("%w: decoding scan tasks: scan schema is 
required", ErrRESTError)
+       }
+       if len(wire.FileScanTasks) == 0 {
+               if len(wire.DeleteFiles) != 0 {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: %d 
delete files have no file scan tasks", ErrRESTError, len(wire.DeleteFiles))
+               }
+
+               return nil, nil
+       }
+
+       // Decode every delete even if the server did not reference it. This 
catches
+       // a malformed response rather than silently ignoring corrupt wire data.
+       deletes := make([]iceberg.DataFile, len(wire.DeleteFiles))
+       for i := range wire.DeleteFiles {
+               decoded, err := decodeRESTDeleteFile(wire.DeleteFiles[i], 
metadata, "")
+               if err != nil {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: 
delete-files[%d]: %w", ErrRESTError, i, err)
+               }
+               deletes[i] = decoded
+       }
+
+       out := make([]table.FileScanTask, 0, len(wire.FileScanTasks))
+       dvOwners := make(map[int]string)
+       for i := range wire.FileScanTasks {
+               wireTask := wire.FileScanTasks[i]
+               if wireTask.DataFile == nil {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: 
file-scan-tasks[%d] is missing data-file", ErrRESTError, i)
+               }
+
+               dataFile, err := decodeRESTDataFile(*wireTask.DataFile, 
metadata)
+               if err != nil {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: 
file-scan-tasks[%d].data-file: %w", ErrRESTError, i, err)
+               }
+
+               residual, err := decodeTaskResidual(wireTask.ResidualFilter, 
schema, fallbackResidual)
+               if err != nil {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: 
file-scan-tasks[%d].residual-filter: %w", ErrRESTError, i, err)
+               }
+
+               task := table.FileScanTask{
+                       File:       dataFile,
+                       Start:      0,
+                       Length:     dataFile.FileSizeBytes(),
+                       Residual:   residual,
+                       FirstRowID: dataFile.FirstRowID(),
+               }
+               // The REST FileScanTask schema does not carry manifest data 
sequence
+               // numbers, so DataSequenceNumber intentionally remains nil.
+
+               seenRefs := make(map[int]struct{}, 
len(wireTask.DeleteFileReferences))
+               for j, ref := range wireTask.DeleteFileReferences {
+                       if ref < 0 || ref >= len(deletes) {
+                               return nil, fmt.Errorf(
+                                       "%w: decoding scan tasks: 
file-scan-tasks[%d].delete-file-references[%d] is %d, want 0 <= index < %d",
+                                       ErrRESTError, i, j, ref, len(deletes))
+                       }
+                       if _, ok := seenRefs[ref]; ok {
+                               return nil, fmt.Errorf(
+                                       "%w: decoding scan tasks: 
file-scan-tasks[%d] repeats delete-file reference %d",
+                                       ErrRESTError, i, ref)
+                       }
+                       seenRefs[ref] = struct{}{}
+
+                       wireDelete := wire.DeleteFiles[ref]
+                       if wireDelete.ReferencedDataFile != nil && 
*wireDelete.ReferencedDataFile != dataFile.FilePath() {
+                               return nil, fmt.Errorf(
+                                       "%w: decoding scan tasks: 
delete-files[%d].referenced-data-file is %q, task data-file is %q",
+                                       ErrRESTError, ref, 
*wireDelete.ReferencedDataFile, dataFile.FilePath())
+                       }
+
+                       deleteFile := deletes[ref]
+                       if deleteFile.FileFormat() == iceberg.PuffinFile {
+                               if owner, ok := dvOwners[ref]; ok && owner != 
dataFile.FilePath() {
+                                       return nil, fmt.Errorf(
+                                               "%w: decoding scan tasks: 
deletion vector %d is referenced by both %q and %q",
+                                               ErrRESTError, ref, owner, 
dataFile.FilePath())
+                               }
+                               dvOwners[ref] = dataFile.FilePath()
+                               // Derive referenced-data-file from the 
FileScanTask association
+                               // when the server omits Java's optional 
extension field.
+                               deleteFile, err = 
decodeRESTDeleteFile(wireDelete, metadata, dataFile.FilePath())
+                               if err != nil {
+                                       return nil, fmt.Errorf("%w: decoding 
scan tasks: delete-files[%d]: %w", ErrRESTError, ref, err)
+                               }
+                       }
+
+                       switch deleteFile.ContentType() {
+                       case iceberg.EntryContentEqDeletes:
+                               task.EqualityDeleteFiles = 
append(task.EqualityDeleteFiles, deleteFile)
+                       case iceberg.EntryContentPosDeletes:
+                               if deleteFile.FileFormat() == 
iceberg.PuffinFile {
+                                       task.DeletionVectorFiles = 
append(task.DeletionVectorFiles, deleteFile)
+                               } else {
+                                       task.DeleteFiles = 
append(task.DeleteFiles, deleteFile)
+                               }
+                       default:
+                               return nil, fmt.Errorf("%w: decoding scan 
tasks: delete-files[%d] has non-delete content", ErrRESTError, ref)
+                       }
+               }
+
+               out = append(out, task)
+       }
+
+       return out, nil
+}
+
+func decodeRESTDataFile(wire RESTDataFile, metadata 
table.ScanPlanningMetadata) (iceberg.DataFile, error) {
+       builder, _, err := contentFileBuilder(wire.RESTContentFile, 
iceberg.EntryContentData, metadata)
+       if err != nil {
+               return nil, err
+       }
+
+       columnSizes, err := decodeCountMap("column-sizes", wire.ColumnSizes)
+       if err != nil {
+               return nil, err
+       }
+       valueCounts, err := decodeCountMap("value-counts", wire.ValueCounts)
+       if err != nil {
+               return nil, err
+       }
+       nullCounts, err := decodeCountMap("null-value-counts", 
wire.NullValueCounts)
+       if err != nil {
+               return nil, err
+       }
+       nanCounts, err := decodeCountMap("nan-value-counts", 
wire.NaNValueCounts)
+       if err != nil {
+               return nil, err
+       }
+       lowerBounds, err := decodeValueMap("lower-bounds", wire.LowerBounds)
+       if err != nil {
+               return nil, err
+       }
+       upperBounds, err := decodeValueMap("upper-bounds", wire.UpperBounds)
+       if err != nil {
+               return nil, err
+       }
+
+       if wire.ColumnSizes != nil {
+               builder.ColumnSizes(columnSizes)
+       }
+       if wire.ValueCounts != nil {
+               builder.ValueCounts(valueCounts)
+       }
+       if wire.NullValueCounts != nil {
+               builder.NullValueCounts(nullCounts)
+       }
+       if wire.NaNValueCounts != nil {
+               builder.NaNValueCounts(nanCounts)
+       }
+       if wire.LowerBounds != nil {
+               builder.LowerBoundValues(lowerBounds)
+       }
+       if wire.UpperBounds != nil {
+               builder.UpperBoundValues(upperBounds)
+       }
+       if wire.FirstRowID != nil {
+               if *wire.FirstRowID < 0 {
+                       return nil, fmt.Errorf("first-row-id must be 
non-negative: %d", *wire.FirstRowID)
+               }
+               builder.FirstRowID(*wire.FirstRowID)
+       }
+
+       return builder.Build(), nil
+}
+
+func decodeRESTDeleteFile(
+       wire RESTDeleteFile,
+       metadata table.ScanPlanningMetadata,
+       referencedDataFile string,
+) (iceberg.DataFile, error) {
+       var content iceberg.ManifestEntryContent
+       switch wire.Content {
+       case "position-deletes":
+               content = iceberg.EntryContentPosDeletes
+       case "equality-deletes":
+               content = iceberg.EntryContentEqDeletes
+       default:
+               return nil, fmt.Errorf("unknown delete content %q", 
wire.Content)
+       }
+
+       builder, format, err := contentFileBuilder(wire.RESTContentFile, 
content, metadata)
+       if err != nil {
+               return nil, err
+       }
+
+       switch content {
+       case iceberg.EntryContentEqDeletes:
+               if wire.ReferencedDataFile != nil || wire.ContentOffset != nil 
|| wire.ContentSizeInBytes != nil {
+                       return nil, errors.New("equality-deletes file must not 
carry position-delete reference or blob offsets")
+               }
+               if len(wire.EqualityIDs) == 0 {
+                       return nil, errors.New("equality-deletes file is 
missing equality-ids")
+               }
+               seen := make(map[int]struct{}, len(wire.EqualityIDs))
+               for i, id := range wire.EqualityIDs {
+                       if id <= 0 {
+                               return nil, fmt.Errorf("equality-ids[%d] must 
be positive: %d", i, id)
+                       }
+                       if _, ok := seen[id]; ok {
+                               return nil, fmt.Errorf("equality-ids contains 
duplicate field ID %d", id)
+                       }
+                       seen[id] = struct{}{}
+               }
+               builder.EqualityFieldIDs(slices.Clone(wire.EqualityIDs))
+       case iceberg.EntryContentPosDeletes:
+               if len(wire.EqualityIDs) != 0 {
+                       return nil, errors.New("position-deletes file must not 
carry equality-ids")
+               }
+               if wire.ContentOffset != nil {
+                       if *wire.ContentOffset < 0 {
+                               return nil, fmt.Errorf("content-offset must be 
non-negative: %d", *wire.ContentOffset)
+                       }
+                       if wire.ContentSizeInBytes == nil {
+                               return nil, errors.New("content-size-in-bytes 
is required when content-offset is present")
+                       }
+                       builder.ContentOffset(*wire.ContentOffset)
+               }
+               if wire.ContentSizeInBytes != nil {
+                       if *wire.ContentSizeInBytes <= 0 {
+                               return nil, fmt.Errorf("content-size-in-bytes 
must be positive: %d", *wire.ContentSizeInBytes)
+                       }
+                       builder.ContentSizeInBytes(*wire.ContentSizeInBytes)
+               }
+               if wire.ReferencedDataFile != nil {
+                       if *wire.ReferencedDataFile == "" {
+                               return nil, errors.New("referenced-data-file 
cannot be empty")
+                       }
+                       if referencedDataFile != "" && *wire.ReferencedDataFile 
!= referencedDataFile {
+                               return nil, fmt.Errorf(
+                                       "referenced-data-file is %q, task 
data-file is %q",
+                                       *wire.ReferencedDataFile, 
referencedDataFile)
+                       }
+                       builder.ReferencedDataFile(*wire.ReferencedDataFile)
+               }
+               if format == iceberg.PuffinFile {
+                       if wire.ContentOffset == nil || wire.ContentSizeInBytes 
== nil {
+                               return nil, errors.New("puffin deletion vector 
requires content-offset and content-size-in-bytes")
+                       }
+                       if wire.ReferencedDataFile == nil && referencedDataFile 
!= "" {
+                               builder.ReferencedDataFile(referencedDataFile)
+                       }
+               }
+       }
+
+       return builder.Build(), nil
+}
+
+func contentFileBuilder(
+       wire RESTContentFile,
+       expectedContent iceberg.ManifestEntryContent,
+       metadata table.ScanPlanningMetadata,
+) (*iceberg.DataFileBuilder, iceberg.FileFormat, error) {
+       wantContent := map[iceberg.ManifestEntryContent]string{
+               iceberg.EntryContentData:       "data",
+               iceberg.EntryContentPosDeletes: "position-deletes",
+               iceberg.EntryContentEqDeletes:  "equality-deletes",
+       }[expectedContent]
+       if wire.Content != wantContent {
+               return nil, "", fmt.Errorf("content is %q, want %q", 
wire.Content, wantContent)
+       }
+       if wire.RecordCount <= 0 {
+               return nil, "", fmt.Errorf("record-count must be positive: %d", 
wire.RecordCount)
+       }
+       if wire.FileSizeInBytes <= 0 {
+               return nil, "", fmt.Errorf("file-size-in-bytes must be 
positive: %d", wire.FileSizeInBytes)
+       }
+
+       spec := metadata.PartitionSpecByID(wire.SpecID)
+       if spec == nil {
+               return nil, "", fmt.Errorf("unknown partition spec ID %d", 
wire.SpecID)
+       }
+       partition, logicalTypes, fixedSizes, err := 
decodePartition(wire.Partition, spec, metadata)
+       if err != nil {
+               return nil, "", err
+       }
+
+       format, err := iceberg.FileFormatFromString(wire.FileFormat)
+       if err != nil {
+               return nil, "", err
+       }
+       builder, err := iceberg.NewDataFileBuilder(
+               *spec,
+               expectedContent,
+               wire.FilePath,
+               format,
+               partition,
+               logicalTypes,
+               fixedSizes,
+               wire.RecordCount,
+               wire.FileSizeInBytes,
+       )
+       if err != nil {
+               return nil, "", err
+       }
+
+       if wire.KeyMetadata != nil {
+               key, err := hex.DecodeString(*wire.KeyMetadata)
+               if err != nil {
+                       return nil, "", fmt.Errorf("invalid key-metadata 
hexadecimal value: %w", err)
+               }
+               builder.KeyMetadata(key)
+       }
+       if wire.SplitOffsets != nil {
+               for i, offset := range wire.SplitOffsets {
+                       if offset < 0 {
+                               return nil, "", fmt.Errorf("split-offsets[%d] 
must be non-negative: %d", i, offset)
+                       }
+                       if i > 0 && offset <= wire.SplitOffsets[i-1] {
+                               return nil, "", errors.New("split-offsets must 
be strictly increasing")
+                       }
+               }
+               builder.SplitOffsets(slices.Clone(wire.SplitOffsets))
+       }
+       if wire.SortOrderID != nil {
+               if *wire.SortOrderID < 0 {
+                       return nil, "", fmt.Errorf("sort-order-id must be 
non-negative: %d", *wire.SortOrderID)
+               }
+               builder.SortOrderID(*wire.SortOrderID)
+       }
+
+       return builder, format, nil
+}
+
+func decodePartition(
+       values []json.RawMessage,
+       spec *iceberg.PartitionSpec,
+       metadata table.ScanPlanningMetadata,
+) (map[int]any, map[int]string, map[int]int, error) {
+       if len(values) != spec.NumFields() {
+               return nil, nil, nil, fmt.Errorf(
+                       "partition for spec ID %d has %d values, want %d", 
spec.ID(), len(values), spec.NumFields())
+       }
+
+       partition := make(map[int]any, len(values))
+       logicalTypes := make(map[int]string)
+       fixedSizes := make(map[int]int)
+       for i, field := range spec.Fields() {
+               raw := values[i]
+               if isJSONNull(raw) {
+                       partition[field.FieldID] = nil
+
+                       continue
+               }
+
+               sourceType, ok := findFieldType(field.SourceID(), metadata)
+               if !ok {
+                       return nil, nil, nil, fmt.Errorf(
+                               "partition field %q (ID %d) has unknown source 
field ID %d",
+                               field.Name, field.FieldID, field.SourceID())
+               }
+               resultType := field.Transform.ResultType(sourceType)
+               literal, err := decodePartitionLiteral(raw, resultType)
+               if err != nil {
+                       return nil, nil, nil, fmt.Errorf("partition[%d] for 
field %q: %w", i, field.Name, err)
+               }
+               partition[field.FieldID] = literal.Any()
+               setPartitionLogicalType(field.FieldID, resultType, 
logicalTypes, fixedSizes)
+       }
+
+       return partition, logicalTypes, fixedSizes, nil
+}
+
+func findFieldType(fieldID int, metadata table.ScanPlanningMetadata) 
(iceberg.Type, bool) {
+       if current := metadata.CurrentSchema(); current != nil {
+               if typ, ok := current.FindTypeByID(fieldID); ok {
+                       return typ, true
+               }
+       }
+       for _, schema := range metadata.Schemas() {
+               if schema == nil {
+                       continue
+               }
+               if typ, ok := schema.FindTypeByID(fieldID); ok {
+                       return typ, true
+               }
+       }
+
+       return nil, false
+}
+
+func setPartitionLogicalType(fieldID int, typ iceberg.Type, logicalTypes 
map[int]string, fixedSizes map[int]int) {
+       switch typ := typ.(type) {
+       case iceberg.DateType:
+               logicalTypes[fieldID] = atype.Date
+       case iceberg.TimeType:
+               logicalTypes[fieldID] = atype.TimeMicros
+       case iceberg.TimestampType, iceberg.TimestampTzType:
+               logicalTypes[fieldID] = atype.TimestampMicros
+       case iceberg.TimestampNsType, iceberg.TimestampTzNsType:
+               logicalTypes[fieldID] = atype.TimestampNanos
+       case iceberg.DecimalType:
+               logicalTypes[fieldID] = atype.Decimal
+               fixedSizes[fieldID] = typ.Scale()
+       case iceberg.UUIDType:
+               logicalTypes[fieldID] = atype.UUID
+       }
+}
+
+func decodeCountMap(name string, wire *RESTCountMap) (map[int]int64, error) {
+       if wire == nil {
+               return nil, nil
+       }
+       if len(wire.Keys) != len(wire.Values) {
+               return nil, fmt.Errorf("%s has %d keys and %d values", name, 
len(wire.Keys), len(wire.Values))
+       }
+
+       out := make(map[int]int64, len(wire.Keys))
+       for i, key := range wire.Keys {
+               if key <= 0 {
+                       return nil, fmt.Errorf("%s contains invalid field ID 
%d", name, key)
+               }
+               if _, ok := out[key]; ok {
+                       return nil, fmt.Errorf("%s contains duplicate field ID 
%d", name, key)
+               }
+               if wire.Values[i] < 0 {
+                       return nil, fmt.Errorf("%s[%d] for field ID %d is 
negative", name, i, key)
+               }
+               out[key] = wire.Values[i]
+       }
+
+       return out, nil
+}
+
+func decodeValueMap(name string, wire *RESTValueMap) (map[int][]byte, error) {

Review Comment:
   Non-blocking / parity note: bounds are stored as raw bytes without 
validating the field ID against the schema or that the bytes decode for the 
field's type. That's actually consistent with the manifest/Avro path — it 
stores `lower_bounds`/`upper_bounds` as `map[int][]byte`, defers to 
`LiteralFromBytes` at evaluation time, and doesn't validate field IDs either. 
So I would *not* add eager validation here (it'd also reject the `Fixed`-length 
padding that `LiteralFromBytes` intentionally tolerates). Flagging only so the 
parity is a conscious choice rather than an oversight.



##########
catalog/rest/scan_task_decoder.go:
##########
@@ -0,0 +1,716 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package rest
+
+import (
+       "bytes"
+       "encoding/hex"
+       "encoding/json"
+       "errors"
+       "fmt"
+       "math"
+       "slices"
+
+       "github.com/apache/iceberg-go"
+       "github.com/apache/iceberg-go/table"
+       "github.com/twmb/avro/atype"
+)
+
+// The exported REST wire types below are intentional: the low-level planning
+// methods expose ScanTasks directly, while DecodeScanTasks is the boundary for
+// callers that want table.FileScanTask domain objects.
+
+// RESTCountMap is the REST column-id-to-count representation. Keys and values
+// are parallel arrays because JSON object keys cannot preserve integer IDs.
+type RESTCountMap struct {
+       Keys   []int   `json:"keys"`
+       Values []int64 `json:"values"`
+}
+
+// RESTValueMap is the REST column-id-to-binary representation used for lower
+// and upper bounds. Java's ContentFileParser encodes each raw Iceberg binary
+// value as a hexadecimal string; these are not typed JSON partition values.
+type RESTValueMap struct {
+       Keys   []int    `json:"keys"`
+       Values []string `json:"values"`
+}
+
+// RESTContentFile contains the fields common to REST data and delete files.
+// Partition values remain raw until DecodeScanTasks resolves spec-id and the
+// result type of each partition transform.
+type RESTContentFile struct {
+       SpecID          int               `json:"spec-id"`
+       Partition       []json.RawMessage `json:"partition"`
+       Content         string            `json:"content"`
+       FilePath        string            `json:"file-path"`
+       FileFormat      string            `json:"file-format"`
+       FileSizeInBytes int64             `json:"file-size-in-bytes"`
+       RecordCount     int64             `json:"record-count"`
+       KeyMetadata     *string           `json:"key-metadata,omitempty"`
+       SplitOffsets    []int64           `json:"split-offsets,omitempty"`
+       SortOrderID     *int              `json:"sort-order-id,omitempty"`
+}
+
+// RESTDataFile is the data-file arm of the REST ContentFile union.
+type RESTDataFile struct {
+       RESTContentFile
+
+       FirstRowID      *int64        `json:"first-row-id,omitempty"`
+       ColumnSizes     *RESTCountMap `json:"column-sizes,omitempty"`
+       ValueCounts     *RESTCountMap `json:"value-counts,omitempty"`
+       NullValueCounts *RESTCountMap `json:"null-value-counts,omitempty"`
+       NaNValueCounts  *RESTCountMap `json:"nan-value-counts,omitempty"`
+       LowerBounds     *RESTValueMap `json:"lower-bounds,omitempty"`
+       UpperBounds     *RESTValueMap `json:"upper-bounds,omitempty"`
+}
+
+// RESTFileScanTask is the REST FileScanTask wire payload. Delete references
+// are zero-based indices into the DeleteFiles slice of the same ScanTasks
+// envelope; they must be resolved before responses are combined.
+type RESTFileScanTask struct {
+       DataFile             *RESTDataFile   `json:"data-file"`
+       DeleteFileReferences []int           
`json:"delete-file-references,omitempty"`
+       ResidualFilter       json.RawMessage `json:"residual-filter,omitempty"`
+}
+
+// RESTDeleteFile is the position/equality arm of the REST ContentFile union.
+// Content discriminates the variant. Puffin position deletes are decoded as
+// deletion vectors and associated with the data file that references them.
+type RESTDeleteFile struct {
+       RESTContentFile
+
+       EqualityIDs []int `json:"equality-ids,omitempty"`
+       // ReferencedDataFile is emitted by Java's ContentFileParser for
+       // file-scoped position deletes and deletion vectors. It is not 
currently
+       // declared by the REST OpenAPI DeleteFile schema, so clients must also
+       // support deriving a DV's target from its FileScanTask association.
+       ReferencedDataFile *string `json:"referenced-data-file,omitempty"`
+       ContentOffset      *int64  `json:"content-offset,omitempty"`
+       ContentSizeInBytes *int64  `json:"content-size-in-bytes,omitempty"`
+}
+
+// DecodeScanTasks converts one REST ScanTasks envelope into domain scan tasks.
+// Delete-file references are scoped to one envelope, so callers must invoke
+// this before combining inline and fetchScanTasks responses.
+//
+// schema is the schema selected for the scan and is used to decode residual
+// literals. When nil, metadata.CurrentSchema is used.
+// fallbackResidual is used when a task omits residual-filter, as required by
+// the REST specification; it is commonly the original scan filter.
+func DecodeScanTasks(
+       wire ScanTasks,
+       metadata table.ScanPlanningMetadata,
+       schema *iceberg.Schema,
+       fallbackResidual iceberg.BooleanExpression,
+) ([]table.FileScanTask, error) {
+       if metadata == nil {
+               return nil, fmt.Errorf("%w: decoding scan tasks: table metadata 
is required", ErrRESTError)
+       }
+       if schema == nil {
+               schema = metadata.CurrentSchema()
+       }
+       if schema == nil {
+               return nil, fmt.Errorf("%w: decoding scan tasks: scan schema is 
required", ErrRESTError)
+       }
+       if len(wire.FileScanTasks) == 0 {
+               if len(wire.DeleteFiles) != 0 {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: %d 
delete files have no file scan tasks", ErrRESTError, len(wire.DeleteFiles))
+               }
+
+               return nil, nil
+       }
+
+       // Decode every delete even if the server did not reference it. This 
catches
+       // a malformed response rather than silently ignoring corrupt wire data.
+       deletes := make([]iceberg.DataFile, len(wire.DeleteFiles))

Review Comment:
   Question (non-blocking): decoding every delete even when no task references 
it (to catch corrupt wire) is a nice touch. But a well-formed yet unreferenced 
delete is then silently dropped rather than surfaced. Is silent dropping the 
intended contract, or should an unreferenced delete be an error? Curious 
whether Java treats a delete with no referencing task as malformed.



##########
catalog/rest/scan_task_decoder.go:
##########
@@ -0,0 +1,716 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package rest
+
+import (
+       "bytes"
+       "encoding/hex"
+       "encoding/json"
+       "errors"
+       "fmt"
+       "math"
+       "slices"
+
+       "github.com/apache/iceberg-go"
+       "github.com/apache/iceberg-go/table"
+       "github.com/twmb/avro/atype"
+)
+
+// The exported REST wire types below are intentional: the low-level planning
+// methods expose ScanTasks directly, while DecodeScanTasks is the boundary for
+// callers that want table.FileScanTask domain objects.
+
+// RESTCountMap is the REST column-id-to-count representation. Keys and values
+// are parallel arrays because JSON object keys cannot preserve integer IDs.
+type RESTCountMap struct {
+       Keys   []int   `json:"keys"`
+       Values []int64 `json:"values"`
+}
+
+// RESTValueMap is the REST column-id-to-binary representation used for lower
+// and upper bounds. Java's ContentFileParser encodes each raw Iceberg binary
+// value as a hexadecimal string; these are not typed JSON partition values.
+type RESTValueMap struct {
+       Keys   []int    `json:"keys"`
+       Values []string `json:"values"`
+}
+
+// RESTContentFile contains the fields common to REST data and delete files.
+// Partition values remain raw until DecodeScanTasks resolves spec-id and the
+// result type of each partition transform.
+type RESTContentFile struct {
+       SpecID          int               `json:"spec-id"`
+       Partition       []json.RawMessage `json:"partition"`
+       Content         string            `json:"content"`
+       FilePath        string            `json:"file-path"`
+       FileFormat      string            `json:"file-format"`
+       FileSizeInBytes int64             `json:"file-size-in-bytes"`
+       RecordCount     int64             `json:"record-count"`
+       KeyMetadata     *string           `json:"key-metadata,omitempty"`
+       SplitOffsets    []int64           `json:"split-offsets,omitempty"`
+       SortOrderID     *int              `json:"sort-order-id,omitempty"`
+}
+
+// RESTDataFile is the data-file arm of the REST ContentFile union.
+type RESTDataFile struct {
+       RESTContentFile
+
+       FirstRowID      *int64        `json:"first-row-id,omitempty"`
+       ColumnSizes     *RESTCountMap `json:"column-sizes,omitempty"`
+       ValueCounts     *RESTCountMap `json:"value-counts,omitempty"`
+       NullValueCounts *RESTCountMap `json:"null-value-counts,omitempty"`
+       NaNValueCounts  *RESTCountMap `json:"nan-value-counts,omitempty"`
+       LowerBounds     *RESTValueMap `json:"lower-bounds,omitempty"`
+       UpperBounds     *RESTValueMap `json:"upper-bounds,omitempty"`
+}
+
+// RESTFileScanTask is the REST FileScanTask wire payload. Delete references
+// are zero-based indices into the DeleteFiles slice of the same ScanTasks
+// envelope; they must be resolved before responses are combined.
+type RESTFileScanTask struct {
+       DataFile             *RESTDataFile   `json:"data-file"`
+       DeleteFileReferences []int           
`json:"delete-file-references,omitempty"`
+       ResidualFilter       json.RawMessage `json:"residual-filter,omitempty"`
+}
+
+// RESTDeleteFile is the position/equality arm of the REST ContentFile union.
+// Content discriminates the variant. Puffin position deletes are decoded as
+// deletion vectors and associated with the data file that references them.
+type RESTDeleteFile struct {
+       RESTContentFile
+
+       EqualityIDs []int `json:"equality-ids,omitempty"`
+       // ReferencedDataFile is emitted by Java's ContentFileParser for
+       // file-scoped position deletes and deletion vectors. It is not 
currently
+       // declared by the REST OpenAPI DeleteFile schema, so clients must also
+       // support deriving a DV's target from its FileScanTask association.
+       ReferencedDataFile *string `json:"referenced-data-file,omitempty"`
+       ContentOffset      *int64  `json:"content-offset,omitempty"`
+       ContentSizeInBytes *int64  `json:"content-size-in-bytes,omitempty"`
+}
+
+// DecodeScanTasks converts one REST ScanTasks envelope into domain scan tasks.
+// Delete-file references are scoped to one envelope, so callers must invoke
+// this before combining inline and fetchScanTasks responses.
+//
+// schema is the schema selected for the scan and is used to decode residual
+// literals. When nil, metadata.CurrentSchema is used.
+// fallbackResidual is used when a task omits residual-filter, as required by
+// the REST specification; it is commonly the original scan filter.
+func DecodeScanTasks(
+       wire ScanTasks,
+       metadata table.ScanPlanningMetadata,
+       schema *iceberg.Schema,
+       fallbackResidual iceberg.BooleanExpression,
+) ([]table.FileScanTask, error) {
+       if metadata == nil {
+               return nil, fmt.Errorf("%w: decoding scan tasks: table metadata 
is required", ErrRESTError)
+       }
+       if schema == nil {
+               schema = metadata.CurrentSchema()
+       }
+       if schema == nil {
+               return nil, fmt.Errorf("%w: decoding scan tasks: scan schema is 
required", ErrRESTError)
+       }
+       if len(wire.FileScanTasks) == 0 {
+               if len(wire.DeleteFiles) != 0 {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: %d 
delete files have no file scan tasks", ErrRESTError, len(wire.DeleteFiles))
+               }
+
+               return nil, nil
+       }
+
+       // Decode every delete even if the server did not reference it. This 
catches
+       // a malformed response rather than silently ignoring corrupt wire data.
+       deletes := make([]iceberg.DataFile, len(wire.DeleteFiles))
+       for i := range wire.DeleteFiles {
+               decoded, err := decodeRESTDeleteFile(wire.DeleteFiles[i], 
metadata, "")
+               if err != nil {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: 
delete-files[%d]: %w", ErrRESTError, i, err)
+               }
+               deletes[i] = decoded
+       }
+
+       out := make([]table.FileScanTask, 0, len(wire.FileScanTasks))
+       dvOwners := make(map[int]string)
+       for i := range wire.FileScanTasks {
+               wireTask := wire.FileScanTasks[i]
+               if wireTask.DataFile == nil {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: 
file-scan-tasks[%d] is missing data-file", ErrRESTError, i)
+               }
+
+               dataFile, err := decodeRESTDataFile(*wireTask.DataFile, 
metadata)
+               if err != nil {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: 
file-scan-tasks[%d].data-file: %w", ErrRESTError, i, err)
+               }
+
+               residual, err := decodeTaskResidual(wireTask.ResidualFilter, 
schema, fallbackResidual)
+               if err != nil {
+                       return nil, fmt.Errorf("%w: decoding scan tasks: 
file-scan-tasks[%d].residual-filter: %w", ErrRESTError, i, err)
+               }
+
+               task := table.FileScanTask{
+                       File:       dataFile,
+                       Start:      0,
+                       Length:     dataFile.FileSizeBytes(),
+                       Residual:   residual,
+                       FirstRowID: dataFile.FirstRowID(),
+               }
+               // The REST FileScanTask schema does not carry manifest data 
sequence
+               // numbers, so DataSequenceNumber intentionally remains nil.
+
+               seenRefs := make(map[int]struct{}, 
len(wireTask.DeleteFileReferences))
+               for j, ref := range wireTask.DeleteFileReferences {
+                       if ref < 0 || ref >= len(deletes) {
+                               return nil, fmt.Errorf(
+                                       "%w: decoding scan tasks: 
file-scan-tasks[%d].delete-file-references[%d] is %d, want 0 <= index < %d",
+                                       ErrRESTError, i, j, ref, len(deletes))
+                       }
+                       if _, ok := seenRefs[ref]; ok {
+                               return nil, fmt.Errorf(
+                                       "%w: decoding scan tasks: 
file-scan-tasks[%d] repeats delete-file reference %d",
+                                       ErrRESTError, i, ref)
+                       }
+                       seenRefs[ref] = struct{}{}
+
+                       wireDelete := wire.DeleteFiles[ref]
+                       if wireDelete.ReferencedDataFile != nil && 
*wireDelete.ReferencedDataFile != dataFile.FilePath() {
+                               return nil, fmt.Errorf(
+                                       "%w: decoding scan tasks: 
delete-files[%d].referenced-data-file is %q, task data-file is %q",
+                                       ErrRESTError, ref, 
*wireDelete.ReferencedDataFile, dataFile.FilePath())
+                       }
+
+                       deleteFile := deletes[ref]
+                       if deleteFile.FileFormat() == iceberg.PuffinFile {
+                               if owner, ok := dvOwners[ref]; ok && owner != 
dataFile.FilePath() {
+                                       return nil, fmt.Errorf(
+                                               "%w: decoding scan tasks: 
deletion vector %d is referenced by both %q and %q",
+                                               ErrRESTError, ref, owner, 
dataFile.FilePath())
+                               }
+                               dvOwners[ref] = dataFile.FilePath()
+                               // Derive referenced-data-file from the 
FileScanTask association
+                               // when the server omits Java's optional 
extension field.
+                               deleteFile, err = 
decodeRESTDeleteFile(wireDelete, metadata, dataFile.FilePath())
+                               if err != nil {
+                                       return nil, fmt.Errorf("%w: decoding 
scan tasks: delete-files[%d]: %w", ErrRESTError, ref, err)
+                               }
+                       }
+
+                       switch deleteFile.ContentType() {
+                       case iceberg.EntryContentEqDeletes:
+                               task.EqualityDeleteFiles = 
append(task.EqualityDeleteFiles, deleteFile)
+                       case iceberg.EntryContentPosDeletes:
+                               if deleteFile.FileFormat() == 
iceberg.PuffinFile {
+                                       task.DeletionVectorFiles = 
append(task.DeletionVectorFiles, deleteFile)
+                               } else {
+                                       task.DeleteFiles = 
append(task.DeleteFiles, deleteFile)
+                               }
+                       default:
+                               return nil, fmt.Errorf("%w: decoding scan 
tasks: delete-files[%d] has non-delete content", ErrRESTError, ref)
+                       }
+               }
+
+               out = append(out, task)
+       }
+
+       return out, nil
+}
+
+func decodeRESTDataFile(wire RESTDataFile, metadata 
table.ScanPlanningMetadata) (iceberg.DataFile, error) {
+       builder, _, err := contentFileBuilder(wire.RESTContentFile, 
iceberg.EntryContentData, metadata)
+       if err != nil {
+               return nil, err
+       }
+
+       columnSizes, err := decodeCountMap("column-sizes", wire.ColumnSizes)
+       if err != nil {
+               return nil, err
+       }
+       valueCounts, err := decodeCountMap("value-counts", wire.ValueCounts)
+       if err != nil {
+               return nil, err
+       }
+       nullCounts, err := decodeCountMap("null-value-counts", 
wire.NullValueCounts)
+       if err != nil {
+               return nil, err
+       }
+       nanCounts, err := decodeCountMap("nan-value-counts", 
wire.NaNValueCounts)
+       if err != nil {
+               return nil, err
+       }
+       lowerBounds, err := decodeValueMap("lower-bounds", wire.LowerBounds)
+       if err != nil {
+               return nil, err
+       }
+       upperBounds, err := decodeValueMap("upper-bounds", wire.UpperBounds)
+       if err != nil {
+               return nil, err
+       }
+
+       if wire.ColumnSizes != nil {
+               builder.ColumnSizes(columnSizes)
+       }
+       if wire.ValueCounts != nil {
+               builder.ValueCounts(valueCounts)
+       }
+       if wire.NullValueCounts != nil {
+               builder.NullValueCounts(nullCounts)
+       }
+       if wire.NaNValueCounts != nil {
+               builder.NaNValueCounts(nanCounts)
+       }
+       if wire.LowerBounds != nil {
+               builder.LowerBoundValues(lowerBounds)
+       }
+       if wire.UpperBounds != nil {
+               builder.UpperBoundValues(upperBounds)
+       }
+       if wire.FirstRowID != nil {
+               if *wire.FirstRowID < 0 {
+                       return nil, fmt.Errorf("first-row-id must be 
non-negative: %d", *wire.FirstRowID)
+               }
+               builder.FirstRowID(*wire.FirstRowID)
+       }
+
+       return builder.Build(), nil
+}
+
+func decodeRESTDeleteFile(
+       wire RESTDeleteFile,
+       metadata table.ScanPlanningMetadata,
+       referencedDataFile string,
+) (iceberg.DataFile, error) {
+       var content iceberg.ManifestEntryContent
+       switch wire.Content {
+       case "position-deletes":
+               content = iceberg.EntryContentPosDeletes
+       case "equality-deletes":
+               content = iceberg.EntryContentEqDeletes
+       default:
+               return nil, fmt.Errorf("unknown delete content %q", 
wire.Content)
+       }
+
+       builder, format, err := contentFileBuilder(wire.RESTContentFile, 
content, metadata)
+       if err != nil {
+               return nil, err
+       }
+
+       switch content {
+       case iceberg.EntryContentEqDeletes:
+               if wire.ReferencedDataFile != nil || wire.ContentOffset != nil 
|| wire.ContentSizeInBytes != nil {
+                       return nil, errors.New("equality-deletes file must not 
carry position-delete reference or blob offsets")
+               }
+               if len(wire.EqualityIDs) == 0 {
+                       return nil, errors.New("equality-deletes file is 
missing equality-ids")
+               }
+               seen := make(map[int]struct{}, len(wire.EqualityIDs))
+               for i, id := range wire.EqualityIDs {
+                       if id <= 0 {
+                               return nil, fmt.Errorf("equality-ids[%d] must 
be positive: %d", i, id)
+                       }
+                       if _, ok := seen[id]; ok {
+                               return nil, fmt.Errorf("equality-ids contains 
duplicate field ID %d", id)
+                       }
+                       seen[id] = struct{}{}
+               }
+               builder.EqualityFieldIDs(slices.Clone(wire.EqualityIDs))
+       case iceberg.EntryContentPosDeletes:
+               if len(wire.EqualityIDs) != 0 {
+                       return nil, errors.New("position-deletes file must not 
carry equality-ids")
+               }
+               if wire.ContentOffset != nil {
+                       if *wire.ContentOffset < 0 {
+                               return nil, fmt.Errorf("content-offset must be 
non-negative: %d", *wire.ContentOffset)
+                       }
+                       if wire.ContentSizeInBytes == nil {
+                               return nil, errors.New("content-size-in-bytes 
is required when content-offset is present")
+                       }
+                       builder.ContentOffset(*wire.ContentOffset)
+               }
+               if wire.ContentSizeInBytes != nil {
+                       if *wire.ContentSizeInBytes <= 0 {
+                               return nil, fmt.Errorf("content-size-in-bytes 
must be positive: %d", *wire.ContentSizeInBytes)
+                       }
+                       builder.ContentSizeInBytes(*wire.ContentSizeInBytes)
+               }
+               if wire.ReferencedDataFile != nil {
+                       if *wire.ReferencedDataFile == "" {
+                               return nil, errors.New("referenced-data-file 
cannot be empty")
+                       }
+                       if referencedDataFile != "" && *wire.ReferencedDataFile 
!= referencedDataFile {
+                               return nil, fmt.Errorf(
+                                       "referenced-data-file is %q, task 
data-file is %q",
+                                       *wire.ReferencedDataFile, 
referencedDataFile)
+                       }
+                       builder.ReferencedDataFile(*wire.ReferencedDataFile)
+               }
+               if format == iceberg.PuffinFile {
+                       if wire.ContentOffset == nil || wire.ContentSizeInBytes 
== nil {
+                               return nil, errors.New("puffin deletion vector 
requires content-offset and content-size-in-bytes")
+                       }
+                       if wire.ReferencedDataFile == nil && referencedDataFile 
!= "" {
+                               builder.ReferencedDataFile(referencedDataFile)
+                       }
+               }
+       }
+
+       return builder.Build(), nil
+}
+
+func contentFileBuilder(
+       wire RESTContentFile,
+       expectedContent iceberg.ManifestEntryContent,
+       metadata table.ScanPlanningMetadata,
+) (*iceberg.DataFileBuilder, iceberg.FileFormat, error) {
+       wantContent := map[iceberg.ManifestEntryContent]string{
+               iceberg.EntryContentData:       "data",
+               iceberg.EntryContentPosDeletes: "position-deletes",
+               iceberg.EntryContentEqDeletes:  "equality-deletes",
+       }[expectedContent]
+       if wire.Content != wantContent {
+               return nil, "", fmt.Errorf("content is %q, want %q", 
wire.Content, wantContent)
+       }
+       if wire.RecordCount <= 0 {
+               return nil, "", fmt.Errorf("record-count must be positive: %d", 
wire.RecordCount)
+       }
+       if wire.FileSizeInBytes <= 0 {
+               return nil, "", fmt.Errorf("file-size-in-bytes must be 
positive: %d", wire.FileSizeInBytes)
+       }
+
+       spec := metadata.PartitionSpecByID(wire.SpecID)
+       if spec == nil {
+               return nil, "", fmt.Errorf("unknown partition spec ID %d", 
wire.SpecID)
+       }
+       partition, logicalTypes, fixedSizes, err := 
decodePartition(wire.Partition, spec, metadata)
+       if err != nil {
+               return nil, "", err
+       }
+
+       format, err := iceberg.FileFormatFromString(wire.FileFormat)
+       if err != nil {
+               return nil, "", err
+       }
+       builder, err := iceberg.NewDataFileBuilder(
+               *spec,
+               expectedContent,
+               wire.FilePath,
+               format,
+               partition,
+               logicalTypes,
+               fixedSizes,
+               wire.RecordCount,
+               wire.FileSizeInBytes,
+       )
+       if err != nil {
+               return nil, "", err
+       }
+
+       if wire.KeyMetadata != nil {
+               key, err := hex.DecodeString(*wire.KeyMetadata)

Review Comment:
   Question (non-blocking): `key-metadata` is hex-decoded here. Bounds/binary 
hex parity with Java's `ContentFileParser` is well covered, but I didn't spot a 
`key-metadata` parity fixture. Could you confirm Java emits `key-metadata` as a 
hex string (not base64), ideally with a small fixture? Just closing the last 
encoding unknown.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to