laskoviymishka commented on code in PR #2776:
URL: https://github.com/apache/iceberg-go/pull/2776#discussion_r4814041789


##########
table/stats_writer_test.go:
##########
@@ -0,0 +1,308 @@
+// 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 table_test
+
+import (
+       "bytes"
+       "context"
+       "errors"
+       "io"
+       "path"
+       "path/filepath"
+       "strconv"
+       "strings"
+       "testing"
+
+       "github.com/apache/iceberg-go"
+       icebergio "github.com/apache/iceberg-go/io"
+       "github.com/apache/iceberg-go/puffin"
+       "github.com/apache/iceberg-go/table"
+       "github.com/apache/iceberg-go/table/stats"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+func TestWriteStatisticsEndToEnd(t *testing.T) {
+       tbl, ctx := ndvTestTable(t, "stats_write")
+
+       updated, err := tbl.WriteStatistics(ctx, 0)
+       require.NoError(t, err)
+
+       snap := updated.CurrentSnapshot()
+       require.NotNil(t, snap)
+
+       var files []table.StatisticsFile
+       for sf := range updated.Metadata().Statistics() {
+               files = append(files, sf)
+       }

Review Comment:
   This loop is the `statisticsFiles` helper further down, which the other 
tests already use.
   
   ```suggestion
        files := statisticsFiles(updated)
   ```



##########
table/stats_writer.go:
##########
@@ -0,0 +1,165 @@
+// 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 table
+
+import (
+       "bytes"
+       "context"
+       "errors"
+       "fmt"
+       "slices"
+       "strconv"
+
+       "github.com/apache/iceberg-go"
+       "github.com/apache/iceberg-go/internal/uuid"
+       icebergio "github.com/apache/iceberg-go/io"
+       "github.com/apache/iceberg-go/puffin"
+)
+
+// ndvBlobProperty is the blob-metadata property key under which the estimated
+// number of distinct values is recorded, matching Iceberg-Java.
+const ndvBlobProperty = "ndv"
+
+// WriteStatistics computes NDV Theta sketches for a snapshot, writes them to a
+// Puffin statistics file, registers the file via SetStatistics, and commits.
+// The updated table is returned.
+//
+// When snapshotID is 0 the current snapshot is used; a table without a
+// snapshot is returned unchanged, as in Iceberg-Java's ComputeTableStats. When
+// columns is empty all top-level primitive columns are analyzed (see
+// ComputeNDVs); it is an error if none can be. Sketch blobs are
+// zstd-compressed, as in Iceberg-Java.
+//
+// If registering or committing the statistics file fails, the file is removed
+// on a best-effort basis. It is kept when the commit outcome is unknown, since
+// the catalog may have accepted it; orphan-file cleanup can remove it later if
+// it turns out to be unreferenced.
+//
+// Each call replaces the statistics file registered for the snapshot, so a
+// narrower column list drops the other columns' blobs. The previously
+// registered file is not deleted.
+func (t Table) WriteStatistics(ctx context.Context, snapshotID int64, columns 
...string) (*Table, error) {
+       ndv, err := t.ComputeNDVs(ctx, snapshotID, columns...)
+       if err != nil {
+               return nil, err
+       }
+       if ndv.Snapshot == nil {
+               return &t, nil
+       }
+       if len(ndv.Columns) == 0 {
+               return nil, fmt.Errorf("%w: no columns found to compute 
statistics", iceberg.ErrInvalidArgument)
+       }
+
+       statsFile, wfs, err := t.writeStatisticsFile(ctx, ndv.Snapshot, 
ndv.Columns)
+       if err != nil {
+               return nil, err
+       }
+
+       tx := t.NewTransaction()
+       if err := tx.SetStatistics(*statsFile); err != nil {
+               _ = wfs.Remove(context.WithoutCancel(ctx), 
statsFile.StatisticsPath)
+
+               return nil, fmt.Errorf("write statistics: %w", err)
+       }
+
+       updated, err := tx.Commit(ctx)
+       if err != nil && updated == nil {
+               // Only a definite failure means nothing references the file. 
After an
+               // unknown-state failure the catalog may have accepted the 
commit.

Review Comment:
   Could this comment name the `doCommit` contract it relies on? The delete is 
safe only because every ambiguous catalog failure comes back as 
`commitStateUnknownError` 
([table.go#L993-L999](https://github.com/apache/iceberg-go/blob/c1b57cd756c23b0026c69293b6a6e1f61725bc6c/table/table.go#L993-L999))
 and `Commit` returns a nil table only when nothing landed. Saying so here 
keeps a later `doCommit` change from quietly turning this into a delete of a 
referenced file.
   
   ```suggestion
                // Only a definite failure means nothing references the file. 
After an
                // unknown-state failure the catalog may have accepted the 
commit. This
                // relies on doCommit wrapping every ambiguous failure in
                // commitStateUnknownError.
   ```



##########
table/stats_writer_test.go:
##########
@@ -0,0 +1,308 @@
+// 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 table_test
+
+import (
+       "bytes"
+       "context"
+       "errors"
+       "io"
+       "path"
+       "path/filepath"
+       "strconv"
+       "strings"
+       "testing"
+
+       "github.com/apache/iceberg-go"
+       icebergio "github.com/apache/iceberg-go/io"
+       "github.com/apache/iceberg-go/puffin"
+       "github.com/apache/iceberg-go/table"
+       "github.com/apache/iceberg-go/table/stats"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+func TestWriteStatisticsEndToEnd(t *testing.T) {
+       tbl, ctx := ndvTestTable(t, "stats_write")
+
+       updated, err := tbl.WriteStatistics(ctx, 0)
+       require.NoError(t, err)
+
+       snap := updated.CurrentSnapshot()
+       require.NotNil(t, snap)
+
+       var files []table.StatisticsFile
+       for sf := range updated.Metadata().Statistics() {
+               files = append(files, sf)
+       }
+       require.Len(t, files, 1)
+
+       sf := files[0]
+       assert.Equal(t, snap.SnapshotID, sf.SnapshotID)
+       require.Len(t, sf.BlobMetadata, 2)
+       assert.Positive(t, sf.FileSizeInBytes)
+       assert.Positive(t, sf.FileFooterSizeInBytes)
+
+       // Every blob targets the analyzed snapshot and records an ndv property.
+       for _, bm := range sf.BlobMetadata {
+               assert.Equal(t, puffin.BlobTypeDataSketchesTheta, bm.Type)
+               assert.Equal(t, snap.SnapshotID, bm.SnapshotID)
+               assert.Contains(t, bm.Properties, "ndv")
+       }
+
+       // The file lives in the metadata directory and is named like Java's
+       // <snapshot-id>-<uuid>.stats.
+       assert.Equal(t, "metadata", path.Base(path.Dir(sf.StatisticsPath)))
+       assert.True(t, strings.HasPrefix(path.Base(sf.StatisticsPath), 
strconv.FormatInt(snap.SnapshotID, 10)+"-"))
+       assert.True(t, strings.HasSuffix(sf.StatisticsPath, ".stats"))
+
+       r, data := openStatisticsFile(t, ctx, updated, sf)
+       assert.Equal(t, int64(len(data)), sf.FileSizeInBytes)
+       blobs := r.Blobs()
+       require.Len(t, blobs, 2)
+
+       // The blob metadata registered in table metadata mirrors the Puffin 
footer.
+       for i, b := range blobs {
+               bm := sf.BlobMetadata[i]
+               assert.Equal(t, b.Type, bm.Type)
+               assert.Equal(t, b.SnapshotID, bm.SnapshotID)
+               assert.Equal(t, snap.SequenceNumber, bm.SequenceNumber)
+               assert.Equal(t, b.SequenceNumber, bm.SequenceNumber)
+               assert.Equal(t, b.Fields, bm.Fields)
+               assert.Equal(t, b.Properties, bm.Properties)
+
+               // Blobs are zstd-compressed, as in Iceberg-Java.
+               require.NotNil(t, b.CompressionCodec)
+               assert.Equal(t, puffin.CompressionCodecZstd, 
*b.CompressionCodec)
+       }
+
+       // Blobs are emitted in field-ID order: id (100 distinct) then category 
(3).
+       wantNDV := map[int32]int64{1: 100, 2: 3}
+       for i, b := range blobs {
+               require.Len(t, b.Fields, 1)
+               blob, err := r.ReadBlob(i)
+               require.NoError(t, err)
+               ndv, err := stats.NDVFromBytes(blob.Data)
+               require.NoError(t, err)
+               assert.Equal(t, wantNDV[b.Fields[0]], ndv)
+               assert.Equal(t, strconv.FormatInt(ndv, 10), b.Properties["ndv"])
+       }
+}
+
+// openStatisticsFile reads the Puffin file registered by sf.
+func openStatisticsFile(t *testing.T, ctx context.Context, tbl *table.Table, 
sf table.StatisticsFile) (*puffin.Reader, []byte) {
+       t.Helper()
+       fs, err := tbl.FS(ctx)
+       require.NoError(t, err)
+       f, err := fs.Open(ctx, sf.StatisticsPath)
+       require.NoError(t, err)
+       defer f.Close()
+       data, err := io.ReadAll(f)
+       require.NoError(t, err)
+
+       r, err := puffin.NewReader(bytes.NewReader(data))
+       require.NoError(t, err)
+
+       return r, data
+}
+
+func statisticsFiles(tbl *table.Table) []table.StatisticsFile {
+       var files []table.StatisticsFile
+       for sf := range tbl.Metadata().Statistics() {
+               files = append(files, sf)
+       }
+
+       return files
+}
+
+func TestWriteStatisticsSelectedColumns(t *testing.T) {
+       tbl, ctx := ndvTestTable(t, "stats_write_selected")
+
+       updated, err := tbl.WriteStatistics(ctx, 0, "category")
+       require.NoError(t, err)
+
+       files := statisticsFiles(updated)
+       require.Len(t, files, 1)
+       require.Len(t, files[0].BlobMetadata, 1)
+       assert.Equal(t, []int32{2}, files[0].BlobMetadata[0].Fields)
+       assert.Equal(t, "3", files[0].BlobMetadata[0].Properties["ndv"])
+}
+
+func TestWriteStatisticsExplicitSnapshot(t *testing.T) {
+       tbl, ctx := ndvTestTable(t, "stats_write_snapshot")
+       first := tbl.CurrentSnapshot()
+       require.NotNil(t, first)
+       tbl = appendNDVRows(t, ctx, tbl, ndvRows(101, 150))
+       require.NotEqual(t, first.SnapshotID, tbl.CurrentSnapshot().SnapshotID)
+
+       // Statistics target the requested older snapshot, not the current one.
+       updated, err := tbl.WriteStatistics(ctx, first.SnapshotID, "id")
+       require.NoError(t, err)
+
+       files := statisticsFiles(updated)
+       require.Len(t, files, 1)
+       assert.Equal(t, first.SnapshotID, files[0].SnapshotID)
+       require.Len(t, files[0].BlobMetadata, 1)
+       bm := files[0].BlobMetadata[0]
+       assert.Equal(t, first.SnapshotID, bm.SnapshotID)
+       assert.Equal(t, first.SequenceNumber, bm.SequenceNumber)
+       assert.Equal(t, "100", bm.Properties["ndv"])
+}
+
+func TestWriteStatisticsUnknownSnapshot(t *testing.T) {
+       tbl, ctx := ndvTestTable(t, "stats_write_missing")
+
+       _, err := tbl.WriteStatistics(ctx, 12345)
+       require.ErrorIs(t, err, table.ErrInvalidOperation)
+}
+
+func TestWriteStatisticsNoSnapshot(t *testing.T) {
+       tbl, ctx := newNDVTable(t, "stats_write_empty", ndvTestSchema, nil)
+       require.Nil(t, tbl.CurrentSnapshot())
+
+       // Like Java's EMPTY_RESULT: nothing to compute, the table is unchanged.
+       updated, err := tbl.WriteStatistics(ctx, 0)
+       require.NoError(t, err)
+       assert.Equal(t, tbl.MetadataLocation(), updated.MetadataLocation())
+       assert.Empty(t, statisticsFiles(updated))
+}
+
+func TestWriteStatisticsNoColumns(t *testing.T) {
+       // The only column is of type unknown, which the default column set 
skips.
+       sc := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "v", Type: 
iceberg.PrimitiveTypes.Unknown},
+       )
+       tbl, ctx := newNDVTable(t, "stats_write_no_columns", sc, 
iceberg.Properties{table.PropertyFormatVersion: "3"})
+       tbl = appendNDVRows(t, ctx, tbl, []string{`{"v": null}`})
+
+       // Like Java's "No columns found to compute stats".
+       _, err := tbl.WriteStatistics(ctx, 0)
+       require.ErrorIs(t, err, iceberg.ErrInvalidArgument)
+       assert.ErrorContains(t, err, "no columns found to compute statistics")
+}
+
+func TestWriteStatisticsReplacesPrevious(t *testing.T) {
+       tbl, ctx := ndvTestTable(t, "stats_write_replace")
+
+       first, err := tbl.WriteStatistics(ctx, 0, "id")
+       require.NoError(t, err)
+       second, err := first.WriteStatistics(ctx, 0)
+       require.NoError(t, err)
+
+       // Rewriting statistics for the same snapshot replaces the registration.
+       before := statisticsFiles(first)
+       after := statisticsFiles(second)
+       require.Len(t, before, 1)
+       require.Len(t, after, 1)
+       assert.NotEqual(t, before[0].StatisticsPath, after[0].StatisticsPath)
+       assert.Len(t, after[0].BlobMetadata, 2)

Review Comment:
   Could this also pin the doc line "The previously registered file is not 
deleted"? The test only checks the registered metadata. `first` and `second` 
share the metadata directory, so `statsFilesOnDisk` should see both files.
   
   ```suggestion
        assert.Len(t, after[0].BlobMetadata, 2)
        // The replaced file stays on storage.
        assert.Len(t, statsFilesOnDisk(t, second), 2)
   ```



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