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


##########
catalog/rest/scan_task_decoder.go:
##########
@@ -0,0 +1,718 @@
+// 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)
+       }
+       // record-count and file-size may be 0 per the wire contract (e.g. an 
empty
+       // data file); only reject the negative values a conformant server 
never sends.
+       if wire.RecordCount < 0 {
+               return nil, "", fmt.Errorf("record-count must be non-negative: 
%d", wire.RecordCount)
+       }
+       if wire.FileSizeInBytes < 0 {
+               return nil, "", fmt.Errorf("file-size-in-bytes must be 
non-negative: %d", wire.FileSizeInBytes)
+       }

Review Comment:
   This allows `>= 0`  and passed into `iceberg.NewDataFileBuilder` in line 410 
and then the Builder reject `<=0` case
   
https://github.com/apache/iceberg-go/blob/116e58c1432eb06a730054428f2fc8c0b8a00123/manifest.go#L2352-L2358
   
   I think `0` pass the check here but fail later with a confusing `invalid 
argument`. Can we reject `0` here early with a clearer error ?  



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