This is an automated email from the ASF dual-hosted git repository.

zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-go.git


The following commit(s) were added to refs/heads/main by this push:
     new b09b8e1b9 fix(table): report the error from a rolling writer that left 
the factory (#2672)
b09b8e1b9 is described below

commit b09b8e1b9d3d06587457377d9635549bc1827e5e
Author: Harrison Crosse <[email protected]>
AuthorDate: Mon Nov 23 13:52:18 2026 -0500

    fix(table): report the error from a rolling writer that left the factory 
(#2672)
    
    * fix(table): report the error from a rolling writer that left the factory
    
    A rolling data writer that fails, for example when a data file upload fails 
as it rolls to a new file, removes itself from the writer factory. closeAll and 
abortAll listed only the writers still in the factory, so closeAll missed the 
error whenever the failed writer had left the factory before it ran. Unless a 
fanout worker called Add on that writer first, nothing read the error and the 
write committed without that writer's rows.
    
    Keep every writer that getOrCreateRollingDataWriter makes in a list and 
have writerList return it. closeAll now reads the failed writer's error, and 
abortAll joins the writers that left the factory. This fixes the data fanout 
writer, which partitioned appends, overwrites, copy on write deletes and 
WriteRecords without clustering use, and the position delete fanout writer. 
Partitioned equality deletes share the factory and are fixed too.
    
    Signed-off-by: Harrison Crosse <[email protected]>
    
    * fix(table): clone writer slice returned by writerList
    
    Signed-off-by: Harrison Crosse <[email protected]>
    
    ---------
    
    Signed-off-by: Harrison Crosse <[email protected]>
---
 table/partitioned_fanout_writer_test.go            | 54 +++++++++++++++++++
 table/pos_delete_partitioned_fanout_writer_test.go | 38 ++++++++++++++
 table/rolling_data_writer.go                       | 21 ++++----
 table/rolling_data_writer_test.go                  | 61 ++++++++++++++++++++++
 4 files changed, 164 insertions(+), 10 deletions(-)

diff --git a/table/partitioned_fanout_writer_test.go 
b/table/partitioned_fanout_writer_test.go
index ba9a947fb..c4802aa62 100644
--- a/table/partitioned_fanout_writer_test.go
+++ b/table/partitioned_fanout_writer_test.go
@@ -37,6 +37,7 @@ import (
        "github.com/apache/arrow-go/v18/arrow/memory"
        "github.com/apache/iceberg-go"
        "github.com/apache/iceberg-go/config"
+       "github.com/apache/iceberg-go/internal"
 
        iceio "github.com/apache/iceberg-go/io"
        "github.com/google/uuid"
@@ -214,6 +215,59 @@ func (s *FanoutWriterTestSuite) 
TestCloseAllFlushesAfterFanoutSuccessContextCanc
        s.Equal(int64(totalRows), sum.total)
 }
 
+func (s *FanoutWriterTestSuite) 
TestWriteReportsFailedUploadAfterWriterLeftFactory() {
+       arrSchema := arrow.NewSchema([]arrow.Field{
+               {Name: "id", Type: arrow.PrimitiveTypes.Int64, Nullable: true},
+               {Name: "part", Type: arrow.PrimitiveTypes.Int32, Nullable: 
true},
+       }, nil)
+       icebergSchema, err := ArrowSchemaToIcebergWithFreshIDs(arrSchema, false)
+       s.Require().NoError(err)
+       partField, ok := icebergSchema.FindFieldByName("part")
+       s.Require().True(ok)
+
+       loc := filepath.ToSlash(s.T().TempDir())
+       spec := iceberg.NewPartitionSpec(iceberg.PartitionField{
+               SourceIDs: []int{partField.ID},
+               FieldID:   1000,
+               Transform: iceberg.IdentityTransform{},
+               Name:      "part",
+       })
+       meta, err := NewMetadata(icebergSchema, &spec, UnsortedSortOrder, loc, 
iceberg.Properties{})
+       s.Require().NoError(err)
+       metaBuilder, err := MetadataBuilderFromBase(meta, "")
+       s.Require().NoError(err)
+
+       bldr := array.NewRecordBuilder(s.mem, arrSchema)
+       bldr.Field(0).(*array.Int64Builder).Append(1)
+       bldr.Field(1).(*array.Int32Builder).Append(1)
+       batch := bldr.NewRecordBatch()
+       bldr.Release()
+       defer batch.Release()
+
+       fs := newFailingCloseFS()
+       writeUUID := uuid.New()
+       args := recordWritingArgs{
+               sc:        arrSchema,
+               fs:        fs,
+               writeUUID: &writeUUID,
+               counter:   internal.Counter(0),
+       }
+       // A one byte target rolls to a new file, and so closes it, after the 
batch.
+       factory, err := newWriterFactory(loc, args, metaBuilder, icebergSchema, 
1)
+       s.Require().NoError(err)
+
+       itr := fs.batchThenWriterExit(factory, batch)
+       var writeErr error
+       for _, iterErr := range newPartitionedFanoutWriter(spec, icebergSchema, 
itr, factory).Write(s.ctx, 1) {
+               if iterErr != nil {
+                       writeErr = iterErr
+               }
+       }
+
+       s.Equal(int64(1), fs.created.Load())
+       s.ErrorContains(writeErr, "upload failed")
+}
+
 func (s *FanoutWriterTestSuite) testTransformPartition(transform 
iceberg.Transform, sourceFieldName string, transformName string, testRecord 
arrow.RecordBatch, expectedPartitionCount int) {
        icebergSchema, err := 
ArrowSchemaToIcebergWithFreshIDs(testRecord.Schema(), false)
        s.Require().NoError(err, "Failed to convert Arrow Schema to Iceberg 
Schema")
diff --git a/table/pos_delete_partitioned_fanout_writer_test.go 
b/table/pos_delete_partitioned_fanout_writer_test.go
index 6a1c6a11f..9d18392b5 100644
--- a/table/pos_delete_partitioned_fanout_writer_test.go
+++ b/table/pos_delete_partitioned_fanout_writer_test.go
@@ -406,6 +406,44 @@ func 
TestPositionDeletePartitionedFanoutWriterRoutesPartitionsIndependently(t *t
        assert.Equal(t, int64(1), byPart[2].Count(), "id=2 delete file must 
contain only the one row targeting pathB")
 }
 
+func 
TestPositionDeletePartitionedFanoutWriterReportsFailedUploadAfterWriterLeftFactory(t
 *testing.T) {
+       metadataBuilder := newPositionDeletePartitionedMetadata(t, 2)
+       latestMeta, err := metadataBuilder.Build()
+       require.NoError(t, err)
+
+       const path = "file://namespace/age_bucket=1/test.parquet"
+       pathToCtx := map[string]partitionContext{
+               path: {partitionData: map[int]any{iceberg.PartitionDataIDStart: 
1}, specID: 0},
+       }
+       batch := mustLoadRecordBatchFromJSON(PositionalDeleteArrowSchema,
+               fmt.Sprintf(`[{"file_path": %q, "pos": 0}]`, path))
+       defer batch.Release()
+
+       fs := newFailingCloseFS()
+       writeUUID := uuid.New()
+       // A one byte target rolls to a new file, and so closes it, after the 
batch.
+       factory, err := newWriterFactory(t.TempDir(), recordWritingArgs{
+               fs:        fs,
+               sc:        PositionalDeleteArrowSchema,
+               writeUUID: &writeUUID,
+               counter:   internal.Counter(0),
+       }, metadataBuilder, iceberg.PositionalDeleteSchema, 1,
+               withContentType(iceberg.EntryContentPosDeletes),
+               withFactoryFileSchema(iceberg.PositionalDeleteSchema))
+       require.NoError(t, err)
+
+       itr := fs.batchThenWriterExit(factory, batch)
+       var writeErr error
+       for _, iterErr := range 
newPositionDeletePartitionedFanoutWriter(latestMeta, pathToCtx, itr, 
factory).Write(t.Context()) {
+               if iterErr != nil {
+                       writeErr = iterErr
+               }
+       }
+
+       assert.Equal(t, int64(1), fs.created.Load())
+       assert.ErrorContains(t, writeErr, "upload failed")
+}
+
 func 
TestPositionDeletePartitionedFanoutWriterEarlyStopCancelsRecordProduction(t 
*testing.T) {
        t.Parallel()
 
diff --git a/table/rolling_data_writer.go b/table/rolling_data_writer.go
index 2805d4905..c2d14c422 100644
--- a/table/rolling_data_writer.go
+++ b/table/rolling_data_writer.go
@@ -23,6 +23,7 @@ import (
        "fmt"
        "iter"
        "log/slog"
+       "slices"
        "strings"
        "sync"
        "sync/atomic"
@@ -93,6 +94,11 @@ type writerFactory struct {
        countMu            sync.Mutex
        partitionIDCounter atomic.Int64
        mu                 sync.Mutex
+
+       // created holds every writer getOrCreateRollingDataWriter made, 
guarded by
+       // mu. A writer whose stream fails leaves writers, but closeAll and
+       // abortAll still join it and only closeAll reads its error.
+       created []*RollingDataWriter
 }
 
 type writerFactoryOption func(*writerFactory) error
@@ -405,6 +411,7 @@ func (w *writerFactory) getOrCreateRollingDataWriter(ctx 
context.Context, partit
 
        writer := w.newRollingDataWriter(ctx, partition, partitionValues, 
outputDataFilesCh, spec)
        w.writers.Store(key, writer)
+       w.created = append(w.created, writer)
 
        return writer, nil
 }
@@ -837,15 +844,9 @@ func (w *writerFactory) abortAll() {
        }
 }
 
-func (w *writerFactory) writerList() (writers []*RollingDataWriter) {
-       w.writers.Range(func(key, value any) bool {
-               writer, ok := value.(*RollingDataWriter)
-               if ok {
-                       writers = append(writers, writer)
-               }
-
-               return true
-       })
+func (w *writerFactory) writerList() []*RollingDataWriter {
+       w.mu.Lock()
+       defer w.mu.Unlock()
 
-       return
+       return slices.Clone(w.created)
 }
diff --git a/table/rolling_data_writer_test.go 
b/table/rolling_data_writer_test.go
index 14d274c54..ae3bde171 100644
--- a/table/rolling_data_writer_test.go
+++ b/table/rolling_data_writer_test.go
@@ -20,6 +20,7 @@ package table
 import (
        "context"
        "errors"
+       "iter"
        "maps"
        "os"
        "path/filepath"
@@ -633,6 +634,66 @@ func (s *RollingDataWriterTestSuite) 
TestStreamErrorRemovesWriterFromFactory() {
        s.Error(err)
 }
 
+// failingCloseFS fails Close on the first file it creates. Close reports that
+// it was entered, then blocks until release is closed, so a test can find the
+// writer while it is still in the factory.
+type failingCloseFS struct {
+       iceio.LocalFS
+
+       created atomic.Int64
+       closing chan struct{}
+       release chan struct{}
+}
+
+func newFailingCloseFS() *failingCloseFS {
+       return &failingCloseFS{closing: make(chan struct{}), release: make(chan 
struct{})}
+}
+
+func (f *failingCloseFS) Create(ctx context.Context, name string) 
(iceio.FileWriter, error) {
+       w, err := f.LocalFS.Create(ctx, name)
+       if err != nil || f.created.Add(1) != 1 {
+               return w, err
+       }
+
+       return &failingCloseWriter{FileWriter: w, fs: f}, nil
+}
+
+type failingCloseWriter struct {
+       iceio.FileWriter
+
+       fs *failingCloseFS
+}
+
+func (w *failingCloseWriter) Close() error {
+       _ = w.FileWriter.Close()
+       close(w.fs.closing)
+       <-w.fs.release
+
+       return errors.New("upload failed")
+}
+
+// batchThenWriterExit yields batch, then returns only after the writer whose
+// Close fails has left factory. stream removes the writer from the factory
+// before it calls wg.Done, so closeAll cannot find the writer in the factory.
+func (f *failingCloseFS) batchThenWriterExit(factory *writerFactory, batch 
arrow.RecordBatch) iter.Seq2[arrow.RecordBatch, error] {
+       return func(yield func(arrow.RecordBatch, error) bool) {
+               if !yield(batch, nil) {
+                       close(f.release)
+
+                       return
+               }
+               <-f.closing
+               var writer *RollingDataWriter
+               factory.writers.Range(func(_, v any) bool {
+                       writer = v.(*RollingDataWriter)
+
+                       return false
+               })
+               close(f.release)
+               writer.wg.Wait()
+       }
+}
+
 func (s *RollingDataWriterTestSuite) TestBytesWrittenReflectsCompressedSize() {
        arrSchema := arrow.NewSchema([]arrow.Field{
                {Name: "id", Type: arrow.PrimitiveTypes.Int32, Nullable: true},

Reply via email to