laskoviymishka commented on code in PR #2776: URL: https://github.com/apache/iceberg-go/pull/2776#discussion_r4761364782
########## table/stats_writer.go: ########## @@ -0,0 +1,162 @@ +// 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" + icebergio "github.com/apache/iceberg-go/io" + "github.com/apache/iceberg-go/puffin" + "github.com/google/uuid" +) + +// 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. Review Comment: Could the doc say that a second call replaces the snapshot's registration? `SetStatistics` swaps the entry by snapshot ID ([metadata.go#L2016-L2036](https://github.com/apache/iceberg-go/blob/16bdfc66239a7b19e854ca4780a18cbfe4fcea06/table/metadata.go#L2016-L2036)), as Java does, so a narrower column list drops the other blobs and the old file stays on storage. ```suggestion // 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. ``` ########## table/stats_writer_test.go: ########## @@ -0,0 +1,259 @@ +// 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" + "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) +} + +// failingCommitCatalog fails every commit with err. +type failingCommitCatalog struct{ err error } + +func (c failingCommitCatalog) LoadTable(context.Context, table.Identifier) (*table.Table, error) { + return nil, errors.New("unexpected LoadTable") +} + +func (c failingCommitCatalog) CommitTable(context.Context, table.Identifier, []table.Requirement, []table.Update) (table.Metadata, string, error) { + return nil, "", c.err +} + +// statsFilesOnDisk lists the .stats files in the table's metadata directory. +func statsFilesOnDisk(t *testing.T, tbl *table.Table) []string { + t.Helper() + dir := filepath.Join(strings.TrimPrefix(tbl.Location(), "file://"), "metadata") + files, err := filepath.Glob(filepath.Join(dir, "*.stats")) + require.NoError(t, err) + + return files +} + +func TestWriteStatisticsCommitFailureCleanup(t *testing.T) { + tests := []struct { + name string + commitErr error + wantFiles int + }{ + // A rejected commit references nothing, so the file is removed. + {name: "rejected", commitErr: table.ErrCommitRejected, wantFiles: 0}, + // After an unknown-state failure the catalog may have accepted the + // commit, so the file must be kept. + {name: "unknown state", commitErr: errors.New("500 internal server error"), wantFiles: 1}, Review Comment: Could we add a case for exhausted `ErrCommitFailed` retries, and one for a failing `WriteFile`? As I read `doCommit`, the last `ErrCommitFailed` comes back unwrapped, so the file should go ([table.go#L983-L1002](https://github.com/apache/iceberg-go/blob/16bdfc66239a7b19e854ca4780a18cbfe4fcea06/table/table.go#L983-L1002)), but nothing pins it. `failingCommitCatalog.LoadTable` errors, so a retry would stop at the refresh; `commit.retry.num-retries=0` should avoid that. -- 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]
