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

laskoviymishka 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 af745b135 refactor(io)!: add context to directory operations (#2611)
af745b135 is described below

commit af745b13546a2a9a7b51aa9b3acd171d57a60303
Author: Vu <[email protected]>
AuthorDate: Mon Nov 16 08:46:16 2026 +0100

    refactor(io)!: add context to directory operations (#2611)
    
    Signed-off-by: Vu <[email protected]>
    Co-authored-by: Vu <[email protected]>
---
 catalog/hadoop/hadoop_context_test.go        |  89 +++++++++++++++--
 catalog/hadoop/hadoop_s3_integration_test.go |   2 +-
 catalog/hadoop/namespaces.go                 |   2 +-
 catalog/hadoop/tables.go                     |  10 +-
 io/gocloud/blobfs/blob.go                    |  28 ++++--
 io/gocloud/blobfs/blob_test.go               | 138 +++++++++++++++++++++++++--
 io/io.go                                     |  11 ++-
 io/local.go                                  |  12 ++-
 io/local_test.go                             |  26 +++++
 website/src/releases.md                      |   1 +
 10 files changed, 285 insertions(+), 34 deletions(-)

diff --git a/catalog/hadoop/hadoop_context_test.go 
b/catalog/hadoop/hadoop_context_test.go
index 752798091..f8cfa6c17 100644
--- a/catalog/hadoop/hadoop_context_test.go
+++ b/catalog/hadoop/hadoop_context_test.go
@@ -36,8 +36,8 @@ import (
 type hadoopContextKey struct{}
 
 // contextBoundHadoopFS models cloud filesystems that retain their construction
-// context and use it for later operations. LocalFS provides the other
-// methods; the overridden operations check the retained context.
+// context. MkdirAll also observes its per-operation context. LocalFS provides
+// the remaining methods.
 type contextBoundHadoopFS struct {
        icebergio.LocalFS
        ctx  context.Context
@@ -61,12 +61,12 @@ func (f *contextBoundHadoopFS) Stat(ctx context.Context, 
name string) (fs.FileIn
        return f.LocalFS.Stat(ctx, f.localPath(name))
 }
 
-func (f *contextBoundHadoopFS) MkdirAll(name string) error {
+func (f *contextBoundHadoopFS) MkdirAll(ctx context.Context, name string) 
error {
        if err := f.ctx.Err(); err != nil {
                return err
        }
 
-       return f.LocalFS.MkdirAll(f.localPath(name))
+       return f.LocalFS.MkdirAll(ctx, f.localPath(name))
 }
 
 func (f *contextBoundHadoopFS) ReadFile(ctx context.Context, name string) 
([]byte, error) {
@@ -85,6 +85,30 @@ func (f *contextBoundHadoopFS) WriteFile(ctx 
context.Context, name string, conte
        return f.LocalFS.WriteFile(ctx, f.localPath(name), content)
 }
 
+type directoryContextHadoopFS struct {
+       HadoopCatalogFS
+       mkdirAllValues  []any
+       removeAllValues []any
+}
+
+func (f *directoryContextHadoopFS) MkdirAll(ctx context.Context, name string) 
error {
+       f.mkdirAllValues = append(f.mkdirAllValues, 
ctx.Value(hadoopContextKey{}))
+
+       return f.HadoopCatalogFS.MkdirAll(ctx, name)
+}
+
+func (f *directoryContextHadoopFS) RemoveAll(ctx context.Context, name string) 
error {
+       f.removeAllValues = append(f.removeAllValues, 
ctx.Value(hadoopContextKey{}))
+
+       return f.HadoopCatalogFS.RemoveAll(ctx, name)
+}
+
+func requireLastDirectoryContextValue(t *testing.T, values []any, want string) 
{
+       t.Helper()
+       require.NotEmpty(t, values)
+       require.Equal(t, want, values[len(values)-1])
+}
+
 func registerHadoopContextFS(t *testing.T, scheme string, factory 
icebergio.SchemeFactory) {
        t.Helper()
        icebergio.Register(scheme, factory)
@@ -137,17 +161,20 @@ func TestNewCatalogFilesystemContextLifetime(t 
*testing.T) {
                        require.ErrorIs(t, ctx.Err(), context.Canceled)
                        require.NoError(t, factoryContext.Err())
                        require.NoError(t, 
cat.CreateNamespace(context.Background(), table.Identifier{"ns"}, nil))
+
                        canceledOperationCtx, cancelOperation := 
context.WithCancel(context.Background())
                        cancelOperation()
+                       canceledNamespace := table.Identifier{"ns", "canceled"}
+                       err = cat.CreateNamespace(canceledOperationCtx, 
canceledNamespace, nil)
+                       require.ErrorIs(t, err, context.Canceled)
+                       exists, err := 
cat.CheckNamespaceExists(context.Background(), canceledNamespace)
+                       require.NoError(t, err)
+                       require.False(t, exists, "a canceled namespace creation 
must not create the namespace")
+
                        _, err = cat.CheckNamespaceExists(canceledOperationCtx, 
table.Identifier{"ns"})
                        require.ErrorIs(t, err, context.Canceled)
                        _, err = cat.ListNamespaces(canceledOperationCtx, 
table.Identifier{"ns"})
                        require.ErrorIs(t, err, context.Canceled)
-                       err = cat.CreateNamespace(canceledOperationCtx, 
table.Identifier{"canceled"}, nil)
-                       require.ErrorIs(t, err, context.Canceled)
-                       exists, err := 
cat.CheckNamespaceExists(context.Background(), table.Identifier{"canceled"})
-                       require.NoError(t, err)
-                       require.False(t, exists)
 
                        fs := cat.(*Catalog).filesystem
                        location := warehouse + "/ns/after-cancel.txt"
@@ -160,6 +187,50 @@ func TestNewCatalogFilesystemContextLifetime(t *testing.T) 
{
        }
 }
 
+func TestHadoopCatalogDirectoryOperationsUseOperationContext(t *testing.T) {
+       cat, err := NewCatalog(context.Background(), "test", 
filepath.Join(t.TempDir(), "warehouse"), nil)
+       require.NoError(t, err)
+
+       filesystem := &directoryContextHadoopFS{HadoopCatalogFS: cat.filesystem}
+       cat.filesystem = filesystem
+       operationContext := func(value string) context.Context {
+               return context.WithValue(context.Background(), 
hadoopContextKey{}, value)
+       }
+
+       require.NoError(t, 
cat.CreateNamespace(operationContext("CreateNamespace"), 
table.Identifier{"ns"}, nil))
+       requireLastDirectoryContextValue(t, filesystem.mkdirAllValues, 
"CreateNamespace")
+
+       schema := iceberg.NewSchema(1, iceberg.NestedField{
+               ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int32, 
Required: true,
+       })
+       dropIdent := table.Identifier{"ns", "drop"}
+       dropTable, err := cat.CreateTable(operationContext("CreateTable"), 
dropIdent, schema)
+       require.NoError(t, err)
+       requireLastDirectoryContextValue(t, filesystem.mkdirAllValues, 
"CreateTable")
+
+       _, _, err = cat.CommitTable(operationContext("CommitTable"), dropIdent,
+               
[]table.Requirement{table.AssertTableUUID(dropTable.Metadata().TableUUID())},
+               
[]table.Update{table.NewSetPropertiesUpdate(iceberg.Properties{"context-test": 
"committed"})})
+       require.NoError(t, err)
+       requireLastDirectoryContextValue(t, filesystem.mkdirAllValues, 
"CommitTable")
+
+       require.NoError(t, cat.DropTable(operationContext("DropTable"), 
dropIdent))
+       requireLastDirectoryContextValue(t, filesystem.removeAllValues, 
"DropTable")
+
+       purgeIdent := table.Identifier{"ns", "purge"}
+       _, err = cat.CreateTable(operationContext("CreateTable for 
PurgeTable"), purgeIdent, schema)
+       require.NoError(t, err)
+       require.NoError(t, cat.PurgeTable(operationContext("PurgeTable"), 
purgeIdent))
+       requireLastDirectoryContextValue(t, filesystem.removeAllValues, 
"PurgeTable")
+
+       metadataOnlyPurgeIdent := table.Identifier{"ns", "metadata-only-purge"}
+       _, err = cat.CreateTable(operationContext("CreateTable for gc-disabled 
PurgeTable"), metadataOnlyPurgeIdent, schema,
+               catalog.WithProperties(iceberg.Properties{"gc.enabled": 
"false"}))
+       require.NoError(t, err)
+       require.NoError(t, cat.PurgeTable(operationContext("PurgeTable with gc 
disabled"), metadataOnlyPurgeIdent))
+       requireLastDirectoryContextValue(t, filesystem.removeAllValues, 
"PurgeTable with gc disabled")
+}
+
 func TestNewCatalogHonorsContextCancellation(t *testing.T) {
        for _, useRegistry := range []bool{false, true} {
                name := "direct constructor"
diff --git a/catalog/hadoop/hadoop_s3_integration_test.go 
b/catalog/hadoop/hadoop_s3_integration_test.go
index 78de42e65..bbe59c72f 100644
--- a/catalog/hadoop/hadoop_s3_integration_test.go
+++ b/catalog/hadoop/hadoop_s3_integration_test.go
@@ -77,7 +77,7 @@ func (s *HadoopS3IntegrationSuite) TearDownTest() {
        }
 
        if remover, ok := fs.(icebergio.RemoveAllIO); ok {
-               _ = remover.RemoveAll(s.warehouse)
+               _ = remover.RemoveAll(context.Background(), s.warehouse)
        }
 }
 
diff --git a/catalog/hadoop/namespaces.go b/catalog/hadoop/namespaces.go
index 13ce9c889..1480a6caf 100644
--- a/catalog/hadoop/namespaces.go
+++ b/catalog/hadoop/namespaces.go
@@ -243,5 +243,5 @@ func (c *Catalog) checkedMkdirAll(ctx context.Context, id 
table.Identifier) erro
                return err
        }
 
-       return c.filesystem.MkdirAll(path)
+       return c.filesystem.MkdirAll(ctx, path)
 }
diff --git a/catalog/hadoop/tables.go b/catalog/hadoop/tables.go
index 7f20c0d7c..492f42a3a 100644
--- a/catalog/hadoop/tables.go
+++ b/catalog/hadoop/tables.go
@@ -86,7 +86,7 @@ func (c *Catalog) CreateTable(ctx context.Context, ident 
table.Identifier, sc *i
        }
 
        metaDir := c.metadataDir(ident)
-       if err := c.filesystem.MkdirAll(metaDir); err != nil {
+       if err := c.filesystem.MkdirAll(ctx, metaDir); err != nil {
                return nil, fmt.Errorf("hadoop catalog: failed to create 
metadata directory: %w", err)
        }
 
@@ -232,7 +232,7 @@ func (c *Catalog) CommitTable(ctx context.Context, ident 
table.Identifier, reqs
 
        // Step 7: Create metadata directory if needed (create-via-commit).
        metaDir := c.metadataDir(ident)
-       if err := c.filesystem.MkdirAll(metaDir); err != nil {
+       if err := c.filesystem.MkdirAll(ctx, metaDir); err != nil {
                return nil, "", fmt.Errorf("hadoop catalog: failed to create 
metadata directory: %w", err)
        }
 
@@ -438,7 +438,7 @@ func (c *Catalog) DropTable(ctx context.Context, ident 
table.Identifier) error {
 
        tablePath := c.tableToPath(ident)
 
-       return c.filesystem.RemoveAll(tablePath)
+       return c.filesystem.RemoveAll(ctx, tablePath)
 }
 
 func (c *Catalog) PurgeTable(ctx context.Context, identifier table.Identifier) 
error {
@@ -457,10 +457,10 @@ func (c *Catalog) PurgeTable(ctx context.Context, 
identifier table.Identifier) e
        }
 
        if !tbl.Metadata().Properties().GetBool("gc.enabled", true) {
-               return c.filesystem.RemoveAll(c.metadataDir(identifier))
+               return c.filesystem.RemoveAll(ctx, c.metadataDir(identifier))
        }
 
-       return c.filesystem.RemoveAll(c.tableToPath(identifier))
+       return c.filesystem.RemoveAll(ctx, c.tableToPath(identifier))
 }
 
 func (c *Catalog) RenameTable(_ context.Context, _, _ table.Identifier) 
(*table.Table, error) {
diff --git a/io/gocloud/blobfs/blob.go b/io/gocloud/blobfs/blob.go
index 6cf145dae..399df5883 100644
--- a/io/gocloud/blobfs/blob.go
+++ b/io/gocloud/blobfs/blob.go
@@ -647,7 +647,11 @@ func (bfs *FileIO) DeleteFiles(ctx context.Context, paths 
[]string) ([]string, e
 }
 
 // MkdirAll mimics creating a directory by creating a zero-length object for 
each component of the path
-func (bfs *FileIO) MkdirAll(path string) error {
+func (bfs *FileIO) MkdirAll(ctx context.Context, path string) error {
+       if err := ctx.Err(); err != nil {
+               return &fs.PathError{Op: "mkdir", Path: path, Err: err}
+       }
+
        key, err := bfs.preprocess(path)
        if err != nil {
                return &fs.PathError{Op: "mkdir", Path: path, Err: err}
@@ -660,8 +664,12 @@ func (bfs *FileIO) MkdirAll(path string) error {
 
        parts := strings.Split(key, "/")
        for idx := range parts {
+               if err := ctx.Err(); err != nil {
+                       return &fs.PathError{Op: "mkdir", Path: path, Err: err}
+               }
+
                marker := strings.Join(parts[:idx+1], "/") + "/"
-               if err := bfs.WriteAll(bfs.ctx, marker, nil, nil); err != nil {
+               if err := bfs.WriteAll(ctx, marker, nil, nil); err != nil {
                        return &fs.PathError{Op: "mkdir", Path: path, Err: err}
                }
        }
@@ -804,13 +812,17 @@ func (bfs *FileIO) RenameNoReplace(ctx context.Context, 
oldpath, newpath string)
 
 // RemoveAll removes either a single file or interprets the path as and 
removes both
 // it and and all its children.
-func (bfs *FileIO) RemoveAll(name string) error {
+func (bfs *FileIO) RemoveAll(ctx context.Context, name string) error {
+       if err := ctx.Err(); err != nil {
+               return &fs.PathError{Op: "RemoveAll", Path: name, Err: err}
+       }
+
        key, err := bfs.preprocess(name)
        if err != nil {
                return &fs.PathError{Op: "RemoveAll", Path: name, Err: err}
        }
 
-       if err := bfs.Delete(bfs.ctx, key); err != nil && gcerrors.Code(err) != 
gcerrors.NotFound {
+       if err := bfs.Delete(ctx, key); err != nil && gcerrors.Code(err) != 
gcerrors.NotFound {
                return &fs.PathError{Op: "RemoveAll", Path: name, Err: err}
        }
 
@@ -821,7 +833,11 @@ func (bfs *FileIO) RemoveAll(name string) error {
 
        iter := bfs.List(&blob.ListOptions{Prefix: prefix})
        for {
-               obj, err := iter.Next(bfs.ctx)
+               if err := ctx.Err(); err != nil {
+                       return &fs.PathError{Op: "RemoveAll", Path: name, Err: 
err}
+               }
+
+               obj, err := iter.Next(ctx)
                if err == io.EOF {
                        break
                }
@@ -830,7 +846,7 @@ func (bfs *FileIO) RemoveAll(name string) error {
                }
                // If the err in question was NotFound, that just means the 
object was already deleted,
                // so we can ignore it and continue deleting the rest of the 
objects.
-               if err := bfs.Delete(bfs.ctx, obj.Key); err != nil && 
gcerrors.Code(err) != gcerrors.NotFound {
+               if err := bfs.Delete(ctx, obj.Key); err != nil && 
gcerrors.Code(err) != gcerrors.NotFound {
                        return &fs.PathError{Op: "RemoveAll", Path: name, Err: 
err}
                }
        }
diff --git a/io/gocloud/blobfs/blob_test.go b/io/gocloud/blobfs/blob_test.go
index 658f2a76b..d59fa25a6 100644
--- a/io/gocloud/blobfs/blob_test.go
+++ b/io/gocloud/blobfs/blob_test.go
@@ -221,12 +221,69 @@ func TestBlobFileIOWriteOperationsUseOperationContext(t 
*testing.T) {
        _, err = writer.Write(content)
        require.NoError(t, err)
        require.NoError(t, writer.Close())
+       require.NoError(t, fileIO.MkdirAll(ctx, "s3://my-bucket/mkdir/all"))
 
        for _, key := range []string{"write-file", "create-file"} {
                got, err := bucket.ReadAll(ctx, key)
                require.NoError(t, err)
                assert.Equal(t, content, got)
        }
+       for _, key := range []string{"mkdir/", "mkdir/all/"} {
+               exists, err := bucket.Exists(ctx, key)
+               require.NoError(t, err)
+               assert.True(t, exists, "%s should exist", key)
+       }
+}
+
+type writeContextKey struct{}
+
+type writeContextBucket struct {
+       driver.Bucket
+       writeContexts []context.Context
+}
+
+func (b *writeContextBucket) NewTypedWriter(ctx context.Context, _ string, _ 
string, _ *driver.WriterOptions) (driver.Writer, error) {
+       b.writeContexts = append(b.writeContexts, ctx)
+
+       return discardDriverWriter{}, nil
+}
+
+func (*writeContextBucket) Close() error { return nil }
+
+type discardDriverWriter struct{}
+
+func (discardDriverWriter) Write(p []byte) (int, error) { return len(p), nil }
+func (discardDriverWriter) Close() error                { return nil }
+
+func TestBlobFileIOWriteFilePassesOperationContext(t *testing.T) {
+       driverBucket := &writeContextBucket{}
+       bucket := blob.NewBucket(driverBucket)
+       t.Cleanup(func() { require.NoError(t, bucket.Close()) })
+
+       lifetimeCtx, cancelLifetime := context.WithCancel(context.Background())
+       fileIO := New(lifetimeCtx, bucket, 
DefaultObjectLocationExtractor("my-bucket"))
+       cancelLifetime()
+
+       operationCtx := context.WithValue(context.Background(), 
writeContextKey{}, "operation")
+       require.NoError(t, fileIO.WriteFile(operationCtx, 
"s3://my-bucket/write-file", []byte("content")))
+       require.Len(t, driverBucket.writeContexts, 1)
+       assert.Equal(t, "operation", 
driverBucket.writeContexts[0].Value(writeContextKey{}))
+}
+
+func TestBlobFileIOMkdirAllPassesOperationContext(t *testing.T) {
+       driverBucket := &writeContextBucket{}
+       bucket := blob.NewBucket(driverBucket)
+       t.Cleanup(func() { require.NoError(t, bucket.Close()) })
+
+       lifetimeCtx := context.WithValue(context.Background(), 
writeContextKey{}, "lifetime")
+       fileIO := New(lifetimeCtx, bucket, 
DefaultObjectLocationExtractor("my-bucket"))
+       operationCtx := context.WithValue(context.Background(), 
writeContextKey{}, "operation")
+
+       require.NoError(t, fileIO.MkdirAll(operationCtx, 
"s3://my-bucket/mkdir/all"))
+       require.Len(t, driverBucket.writeContexts, 2, "MkdirAll writes one 
marker for each path component")
+       for _, ctx := range driverBucket.writeContexts {
+               assert.Equal(t, "operation", ctx.Value(writeContextKey{}))
+       }
 }
 
 type statContextKey struct{}
@@ -268,7 +325,8 @@ func TestBlobFileIOStatUsesOperationContext(t *testing.T) {
 
 type statListContextBucket struct {
        driver.Bucket
-       listCtx context.Context
+       listCtx   context.Context
+       deleteCtx []context.Context
 }
 
 func (*statListContextBucket) ErrorCode(err error) gcerrors.ErrorCode {
@@ -291,6 +349,12 @@ func (b *statListContextBucket) ListPaged(ctx 
context.Context, _ *driver.ListOpt
        }, nil
 }
 
+func (b *statListContextBucket) Delete(ctx context.Context, _ string, _ 
*driver.DeleteOptions) error {
+       b.deleteCtx = append(b.deleteCtx, ctx)
+
+       return nil
+}
+
 func (*statListContextBucket) Close() error { return nil }
 
 func TestBlobFileIOStatDirectoryListingUsesOperationContext(t *testing.T) {
@@ -1102,7 +1166,7 @@ func TestBlobFileIOStat(t *testing.T) {
        assert.Equal(t, "data", dirInfo.Name())
        assert.True(t, dirInfo.IsDir())
 
-       require.NoError(t, bfs.MkdirAll("s3://test-bucket/foo"))
+       require.NoError(t, bfs.MkdirAll(ctx, "s3://test-bucket/foo"))
        markerInfoWithSlash, err := bfs.Stat(ctx, "s3://test-bucket/foo/")
        require.NoError(t, err)
        assert.Equal(t, "foo", markerInfoWithSlash.Name())
@@ -1346,13 +1410,35 @@ func TestBlobFileIOMkdirAll(t *testing.T) {
 
        bfs := New(ctx, bucket, DefaultObjectLocationExtractor("test-bucket"))
 
-       require.NoError(t, bfs.MkdirAll("s3://test-bucket/a/b/c"))
+       require.NoError(t, bfs.MkdirAll(ctx, "s3://test-bucket/a/b/c"))
 
        for _, key := range []string{"a/", "a/b/", "a/b/c/"} {
                exists, err := bucket.Exists(ctx, key)
                require.NoError(t, err)
                assert.True(t, exists, "%s should exist", key)
        }
+       require.NoError(t, bfs.MkdirAll(ctx, "s3://test-bucket/a/b/c"))
+}
+
+func TestBlobFileIOMkdirAllUsesOperationContext(t *testing.T) {
+       ctx := context.Background()
+       bucket := memblob.OpenBucket(nil)
+       defer bucket.Close()
+       bfs := testBlobFileIO(ctx, "test-bucket", bucket)
+
+       opCtx, cancel := context.WithCancel(ctx)
+       cancel()
+       err := bfs.MkdirAll(opCtx, "s3://test-bucket/canceled/nested")
+       require.ErrorIs(t, err, context.Canceled)
+       var pathErr *fs.PathError
+       require.ErrorAs(t, err, &pathErr)
+       assert.Equal(t, "mkdir", pathErr.Op)
+       assert.Equal(t, "s3://test-bucket/canceled/nested", pathErr.Path)
+       for _, key := range []string{"canceled/", "canceled/nested/"} {
+               exists, err := bucket.Exists(ctx, key)
+               require.NoError(t, err)
+               assert.False(t, exists)
+       }
 }
 
 func TestBlobFileIOWalkDirSkipsDirectoryMarker(t *testing.T) {
@@ -1364,7 +1450,7 @@ func TestBlobFileIOWalkDirSkipsDirectoryMarker(t 
*testing.T) {
 
        // MkdirAll leaves only a "warehouse/ns/" marker for an empty namespace.
        // Walking "warehouse/ns" should not report that marker as a child file.
-       require.NoError(t, bfs.MkdirAll("s3://test-bucket/warehouse/ns"))
+       require.NoError(t, bfs.MkdirAll(ctx, "s3://test-bucket/warehouse/ns"))
 
        var paths []string
        require.NoError(t, bfs.WalkDir(context.Background(), 
"s3://test-bucket/warehouse/ns", func(path string, d fs.DirEntry, err error) 
error {
@@ -1466,12 +1552,12 @@ func TestBlobFileIORemoveAll(t *testing.T) {
 
        bfs := New(ctx, bucket, DefaultObjectLocationExtractor("test-bucket"))
 
-       require.NoError(t, bfs.RemoveAll("s3://test-bucket/data/file.parquet"))
+       require.NoError(t, bfs.RemoveAll(ctx, 
"s3://test-bucket/data/file.parquet"))
        exists, err := bucket.Exists(ctx, "data/file.parquet")
        require.NoError(t, err)
        assert.False(t, exists)
 
-       require.NoError(t, bfs.RemoveAll("s3://test-bucket/warehouse/ns"))
+       require.NoError(t, bfs.RemoveAll(ctx, "s3://test-bucket/warehouse/ns"))
        for _, key := range []string{
                "warehouse/ns/",
                "warehouse/ns/tbl/metadata/v1.metadata.json",
@@ -1486,7 +1572,45 @@ func TestBlobFileIORemoveAll(t *testing.T) {
        require.NoError(t, err)
        assert.True(t, exists)
 
-       require.NoError(t, bfs.RemoveAll("s3://test-bucket/missing"))
+       require.NoError(t, bfs.RemoveAll(ctx, "s3://test-bucket/missing"))
+}
+
+func TestBlobFileIORemoveAllHonorsOperationCancellation(t *testing.T) {
+       ctx := context.Background()
+       bucket := memblob.OpenBucket(nil)
+       defer bucket.Close()
+       require.NoError(t, bucket.WriteAll(ctx, "data/file.parquet", 
[]byte("content"), nil))
+       bfs := testBlobFileIO(ctx, "test-bucket", bucket)
+
+       opCtx, cancel := context.WithCancel(ctx)
+       cancel()
+       err := bfs.RemoveAll(opCtx, "s3://test-bucket/data")
+       require.ErrorIs(t, err, context.Canceled)
+       var pathErr *fs.PathError
+       require.ErrorAs(t, err, &pathErr)
+       assert.Equal(t, "RemoveAll", pathErr.Op)
+       assert.Equal(t, "s3://test-bucket/data", pathErr.Path)
+       exists, err := bucket.Exists(ctx, "data/file.parquet")
+       require.NoError(t, err)
+       assert.True(t, exists)
+}
+
+func TestBlobFileIORemoveAllPassesOperationContext(t *testing.T) {
+       driverBucket := &statListContextBucket{}
+       bucket := blob.NewBucket(driverBucket)
+       t.Cleanup(func() { require.NoError(t, bucket.Close()) })
+
+       lifetimeCtx := context.WithValue(context.Background(), 
statContextKey{}, "lifetime")
+       fileIO := New(lifetimeCtx, bucket, 
DefaultObjectLocationExtractor("my-bucket"))
+       operationCtx := context.WithValue(context.Background(), 
statContextKey{}, "operation")
+
+       require.NoError(t, fileIO.RemoveAll(operationCtx, 
"s3://my-bucket/data"))
+       require.NotNil(t, driverBucket.listCtx, "RemoveAll should list children 
with the operation context")
+       assert.Equal(t, "operation", 
driverBucket.listCtx.Value(statContextKey{}))
+       require.Len(t, driverBucket.deleteCtx, 2, "RemoveAll should delete the 
path and its listed child")
+       for _, ctx := range driverBucket.deleteCtx {
+               assert.Equal(t, "operation", ctx.Value(statContextKey{}))
+       }
 }
 
 func TestBlobFileIOPreprocessErrorRetainsOriginalPath(t *testing.T) {
diff --git a/io/io.go b/io/io.go
index 79c3d2ab1..1997214a0 100644
--- a/io/io.go
+++ b/io/io.go
@@ -223,7 +223,11 @@ type RenameNoReplaceIO interface {
 type RemoveAllIO interface {
        IO
 
-       RemoveAll(name string) error
+       // RemoveAll removes the named path and any children recursively. The 
context
+       // controls the operation where the implementation supports 
cancellation. A
+       // canceled operation may leave the tree partially removed. The 
returned error
+       // may wrap ctx.Err(), so use errors.Is to check for cancellation.
+       RemoveAll(ctx context.Context, name string) error
 }
 
 // MkdirAllIO is an extension of IO interface that includes the MkdirAll
@@ -233,8 +237,9 @@ type MkdirAllIO interface {
 
        // MkdirAll should not raise an error if the directory already exists,
        // and should create any parent directories in the path if they
-       // do not already exist.
-       MkdirAll(path string) error
+       // do not already exist. The context controls the operation where the
+       // implementation supports cancellation.
+       MkdirAll(ctx context.Context, path string) error
 }
 
 // FS wraps an io/fs.FS as an IO interface. It implements ReadFileIO if the
diff --git a/io/local.go b/io/local.go
index 4141b531b..426880be4 100644
--- a/io/local.go
+++ b/io/local.go
@@ -128,7 +128,11 @@ func (LocalFS) Remove(_ context.Context, name string) 
error {
        return os.Remove(path)
 }
 
-func (LocalFS) RemoveAll(name string) error {
+func (LocalFS) RemoveAll(ctx context.Context, name string) error {
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+
        path, err := localPath(name)
        if err != nil {
                return err
@@ -165,7 +169,11 @@ func (LocalFS) ReadDir(name string) ([]fs.DirEntry, error) 
{
        return os.ReadDir(path)
 }
 
-func (LocalFS) MkdirAll(name string) error {
+func (LocalFS) MkdirAll(ctx context.Context, name string) error {
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+
        path, err := localPath(name)
        if err != nil {
                return err
diff --git a/io/local_test.go b/io/local_test.go
index e1833ef83..02882ebf3 100644
--- a/io/local_test.go
+++ b/io/local_test.go
@@ -104,6 +104,32 @@ func TestLocalFSWalkDirReturnsCanceledContext(t 
*testing.T) {
        assert.False(t, called)
 }
 
+func TestLocalFSMkdirAllReturnsCanceledContext(t *testing.T) {
+       dir := filepath.Join(t.TempDir(), "nested", "dir")
+       ctx, cancel := context.WithCancel(context.Background())
+       cancel()
+
+       err := (LocalFS{}).MkdirAll(ctx, dir)
+       require.ErrorIs(t, err, context.Canceled)
+       _, err = os.Stat(dir)
+       require.ErrorIs(t, err, fs.ErrNotExist)
+}
+
+func TestLocalFSRemoveAllReturnsCanceledContext(t *testing.T) {
+       dir := filepath.Join(t.TempDir(), "data")
+       file := filepath.Join(dir, "file.parquet")
+       require.NoError(t, os.MkdirAll(dir, 0o755))
+       require.NoError(t, os.WriteFile(file, []byte("keep"), 0o644))
+       ctx, cancel := context.WithCancel(context.Background())
+       cancel()
+
+       err := (LocalFS{}).RemoveAll(ctx, dir)
+       require.ErrorIs(t, err, context.Canceled)
+       content, err := os.ReadFile(file)
+       require.NoError(t, err)
+       assert.Equal(t, []byte("keep"), content)
+}
+
 func TestLocalFSWriteFileCreatesParentDirectories(t *testing.T) {
        dir := t.TempDir()
        content := []byte("content")
diff --git a/website/src/releases.md b/website/src/releases.md
index cbd5af17a..b69d0f587 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -78,6 +78,7 @@ Per-release notes (highlights, breaking changes, 
contributors) are published on
 - **`ReplaceFilesWithDeleteFiles` removed.** For delete-file replacements, use 
`tx.NewRewrite(snapshotProps)`, call `DeleteFile` for each source file and 
`AddDeleteFileWithDataSequenceNumber` for each replacement, then commit the 
builder. Rewrites record a `replace` snapshot instead of `overwrite`. The 
five-argument `ReplaceFiles` API is unchanged and remains available for 
compaction and delete-file removals.
 - **Manifest and deletion-vector reads take a context.** `Snapshot.Manifests`, 
`ManifestFile.Entries`, `iceberg.EntriesWithProjection`, `dv.ReadDV` and 
`dv.ReadDVs` now take a `context.Context` first argument and pass it to 
`IO.Open`. Custom `ManifestFile` implementations must add it to `Entries`.
 - **Path-based data-file addition renamed.** Replace `Transaction.AddFiles` 
with `AddDataFilesByPath`, `AddFilesOption` with `AddDataFilesByPathOption`, 
and `WithAddFilesConcurrency` with `WithAddDataFilesByPathConcurrency`. 
Behavior is unchanged.
+- **Directory IO methods take a context.** `RemoveAllIO.RemoveAll` and 
`MkdirAllIO.MkdirAll` now take `context.Context` first, so custom 
implementations and callers must update.
 - **Manifest builder constructor renamed.** Replace 
`iceberg.NewManifestFile(...)` with `iceberg.NewManifestBuilder(...)`. It still 
returns a `ManifestBuilder`.
 - **Manifest sequence APIs use explicit names.** `ManifestBuilder.SequenceNum` 
and `ManifestFile.SequenceNum` become `SequenceNumber`, and 
`ManifestFile.MinSequenceNum` becomes `MinSequenceNumber`. 
`ManifestEntryBuilder.SequenceNum` and `ManifestEntry.SequenceNum` become 
`DataSequenceNumber`. `FileSequenceNum` becomes `FileSequenceNumber` for 
entries and their builder. Avro and JSON field names are unchanged.
 - **`io.ReadFileIO.ReadFile` accepts a context.** The method now takes a 
`context.Context` before the path, so custom `ReadFileIO` implementations and 
callers must pass the operation context.

Reply via email to