You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "SLoeuillet (via GitHub)" <gi...@apache.org> on 2026/09/30 19:26:57 UTC

[PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

SLoeuillet opened a new pull request, #2079:
URL: https://github.com/apache/iceberg-go/pull/2079

   Fixes #2078
   
   `vendedCredentialRefresher.loadFS` caches the FileIO it builds and shares it with every later caller, but built it with the first caller's `ctx`. The GCS filesystem keeps the context it is opened with, so once that `ctx` is cancelled, every later operation through the table fails with `context canceled`, even when called with a live context. A writer that scopes each commit to its own context (`context.WithTimeout`, cancelled on return) sees every commit after the first fail. Renewal and `prefixScopedIO` (which stores `ctx` and opens filesystems lazily) had the same issue.
   
   **Change:** build the cached IO from `context.WithoutCancel(ctx)`, which keeps values and drops cancellation. `fetchCreds` still honours `ctx`.
   
   **Tests:** two new tests register a filesystem that records its opening context and assert it outlives the caller's cancellation, for the table-wide cached IO (initial load and renewal) and for `prefixScopedIO`. Both fail without the fix. `make lint` is clean and `go test ./...` passes.
   
   Verified end to end against Lakekeeper v0.13.3 with a native GCS warehouse: without the fix, the second append on the same table fails with `context canceled`.
   
   It would be great to have this in 0.7.0 if an rc1 is cut.


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "SLoeuillet (via GitHub)" <gi...@apache.org>.
SLoeuillet commented on code in PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#discussion_r4191872057


##########
catalog/rest/vended_creds.go:
##########
@@ -171,33 +176,62 @@ func (v *vendedCredentialRefresher) loadFS(ctx context.Context) (iceio.IO, error
 		maps.Copy(config, freshCreds)
 	}
 
+	// The IO is cached and shared by every later caller, so it must not
+	// inherit this caller's cancellation: a filesystem may keep the context it
+	// is opened with (blobfs does, so every gocloud backend), and a cached IO
+	// built on a per-operation context would fail every later operation with
+	// context.Canceled once that context is done. The refresher owns the IO's
+	// lifetime instead, through ioCancel. fetchCreds above still honours ctx.
+	//
+	// WithoutCancel keeps ctx's values, and the IO depends on them: the S3
+	// factory takes its base AWS config from utils.GetAwsConfig(ctx), so do
+	// not replace this with context.Background(). The flip side is that the
+	// first caller's request-scoped values stay attached to the shared IO.
+	ioCtx, ioCancel := context.WithCancel(context.WithoutCancel(ctx))
+
+	var (
+		newIO     iceio.IO
+		expiresAt time.Time
+		issuedAt  = v.issuedAt
+	)
+
 	if len(v.credentials) > 0 {
-		prefixIO := newPrefixScopedIO(ctx, v.props, v.credentials)
+		prefixIO := newPrefixScopedIO(ioCtx, v.props, v.credentials)
 		prefixIO.nowFunc = v.now
-		v.cachedIO = prefixIO
+		newIO = prefixIO
 		// Expiry is enforced by prefixScopedIO against only the credential
 		// selected for each object location.
-		v.expiresAt = time.Time{}
+	} else {
+		loaded, err := iceio.LoadFS(ioCtx, config, v.location)
+		if err != nil {
+			ioCancel()
 
-		return v.cachedIO, nil
-	}
+			if v.cachedIO == nil {
+				return nil, err
+			}
 
-	newIO, err := iceio.LoadFS(ctx, config, v.location)
-	if err != nil {
-		if v.cachedIO == nil {
-			return nil, err
+			return nil, fmt.Errorf("load filesystem with refreshed credentials for %s: %w", v.location, err)
 		}
 
-		return nil, fmt.Errorf("load filesystem with refreshed credentials for %s: %w", v.location, err)
+		newIO = loaded
+		expiresAt = v.expiresAtFromConfig(config)
+		issuedAt = v.now()
 	}
 
-	v.cachedIO = newIO
-	v.expiresAt = v.expiresAtFromConfig(config)
-	v.issuedAt = v.now()
+	v.replaceIO(newIO, ioCancel)
+	v.expiresAt = expiresAt
+	v.issuedAt = issuedAt
 
 	return v.cachedIO, nil
 }
 
+// replaceIO installs io as the cached IO. The superseded IO is left open:
+// callers that loaded it earlier may still be using it, and its credentials
+// remain valid until their own expiry.
+func (v *vendedCredentialRefresher) replaceIO(io iceio.IO, cancel context.CancelFunc) {
+	v.cachedIO, v.ioCancel = io, cancel

Review Comment:
   Done in 2883aef: the `replaceIO` doc now says the superseded cancel is dropped on purpose, and why.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "SLoeuillet (via GitHub)" <gi...@apache.org>.
SLoeuillet commented on code in PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#discussion_r4163172475


##########
catalog/rest/vended_creds.go:
##########
@@ -171,33 +176,69 @@ func (v *vendedCredentialRefresher) loadFS(ctx context.Context) (iceio.IO, error
 		maps.Copy(config, freshCreds)
 	}
 
+	// The IO is cached and shared by every later caller, so it must not
+	// inherit this caller's cancellation: a filesystem may keep the context it
+	// is opened with (blobfs does, so every gocloud backend), and a cached IO
+	// built on a per-operation context would fail every later operation with
+	// context.Canceled once that context is done. The refresher owns the IO's
+	// lifetime instead, through ioCancel. fetchCreds above still honours ctx.
+	//
+	// WithoutCancel keeps ctx's values, so the first caller's request-scoped
+	// values stay attached to the shared IO.
+	ioCtx, ioCancel := context.WithCancel(context.WithoutCancel(ctx))
+
+	var (
+		newIO     iceio.IO
+		expiresAt time.Time
+		issuedAt  = v.issuedAt
+	)
+
 	if len(v.credentials) > 0 {
-		prefixIO := newPrefixScopedIO(ctx, v.props, v.credentials)
+		prefixIO := newPrefixScopedIO(ioCtx, v.props, v.credentials)
 		prefixIO.nowFunc = v.now
-		v.cachedIO = prefixIO
+		newIO = prefixIO
 		// Expiry is enforced by prefixScopedIO against only the credential
 		// selected for each object location.
-		v.expiresAt = time.Time{}
+	} else {
+		loaded, err := iceio.LoadFS(ioCtx, config, v.location)
+		if err != nil {
+			ioCancel()
 
-		return v.cachedIO, nil
-	}
+			if v.cachedIO == nil {
+				return nil, err
+			}
 
-	newIO, err := iceio.LoadFS(ctx, config, v.location)
-	if err != nil {
-		if v.cachedIO == nil {
-			return nil, err
+			return nil, fmt.Errorf("load filesystem with refreshed credentials for %s: %w", v.location, err)
 		}
 
-		return nil, fmt.Errorf("load filesystem with refreshed credentials for %s: %w", v.location, err)
+		newIO = loaded
+		expiresAt = v.expiresAtFromConfig(config)
+		issuedAt = v.now()
 	}
 
-	v.cachedIO = newIO
-	v.expiresAt = v.expiresAtFromConfig(config)
-	v.issuedAt = v.now()
+	v.replaceIO(newIO, ioCancel)
+	v.expiresAt = expiresAt
+	v.issuedAt = issuedAt
 
 	return v.cachedIO, nil
 }
 
+// replaceIO installs io as the cached IO, then closes the one it supersedes
+// and cancels that one's context. An error closing the superseded IO is not
+// returned: the new IO is already in place, and the caller has no use for it.
+func (v *vendedCredentialRefresher) replaceIO(io iceio.IO, cancel context.CancelFunc) {
+	oldIO, oldCancel := v.cachedIO, v.ioCancel
+	v.cachedIO, v.ioCancel = io, cancel
+
+	if oldIO != nil {
+		_ = closeOptionalIO(oldIO)
+	}
+
+	if oldCancel != nil {
+		oldCancel()
+	}
+}

Review Comment:
   Done in d7ed212: `replaceIO` is swap-only, as you suggested. `close()` still closes the current IO and cancels its context, and the `ioCancel` field comment says so. Thanks for tracing the callers.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +931,168 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// contextCapturingScheme is a filesystem whose factory records every context
+// it is opened with, the way a filesystem that keeps its opening context
+// (blobfs) would, and counts how often each IO it handed out is closed.
+type contextCapturingScheme struct {
+	mu     sync.Mutex
+	opened []context.Context
+	closes []*atomic.Int32
+}
+
+func registerContextCapturingScheme(t *testing.T, scheme string) *contextCapturingScheme {
+	t.Helper()
+
+	c := &contextCapturingScheme{}
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		closes := &atomic.Int32{}
+
+		c.mu.Lock()
+		c.opened = append(c.opened, ctx)
+		c.closes = append(c.closes, closes)
+		c.mu.Unlock()
+
+		return &closeTrackingIO{IO: iceio.LocalFS{}, closeCount: closes}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return c
+}
+
+func (c *contextCapturingScheme) loads() int {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return len(c.opened)
+}
+
+func (c *contextCapturingScheme) ctx(i int) context.Context {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return c.opened[i]
+}
+
+func (c *contextCapturingScheme) closeCount(i int) int32 {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return c.closes[i].Load()
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context. The
+// refresher owns the IO's lifetime instead: renewal closes the superseded IO
+// and ends its context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	fs := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "first"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.Equal(t, 1, fs.loads())
+	require.NoError(t, fs.ctx(0).Err(), "the cached IO must not be bound to the caller's cancellation")
+	// WithoutCancel keeps values, so the first caller's values reach the shared
+	// IO. This documents the current behaviour; it is a trade-off, not a promise.
+	assert.Equal(t, "first", fs.ctx(0).Value(vendedCtxKey{}))
+
+	// Renewal rebuilds the IO on its own context and retires the old one.
+	r.expiresAt = time.Now().Add(-time.Minute)
+	ctx, cancel = context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "second"))
+	_, err = r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.Equal(t, 2, fs.loads(), "renewal must rebuild the IO")
+	assert.NotSame(t, fs.ctx(0), fs.ctx(1), "the renewed IO gets a context of its own")
+	require.NoError(t, fs.ctx(1).Err(), "the renewed IO must not be bound to the caller's cancellation")
+	assert.Equal(t, "second", fs.ctx(1).Value(vendedCtxKey{}))
+
+	require.ErrorIs(t, fs.ctx(0).Err(), context.Canceled, "the superseded IO's context is ended")
+	assert.Equal(t, int32(1), fs.closeCount(0), "the superseded IO is closed")

Review Comment:
   Inverted: after renewal the superseded IO's context is alive and it was not closed. The test also keeps the IO from the first `loadFS`, renews, then writes and reads through it. On 884d962 that read fails with `blob: Bucket has been closed`.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +931,168 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// contextCapturingScheme is a filesystem whose factory records every context
+// it is opened with, the way a filesystem that keeps its opening context
+// (blobfs) would, and counts how often each IO it handed out is closed.
+type contextCapturingScheme struct {
+	mu     sync.Mutex
+	opened []context.Context
+	closes []*atomic.Int32
+}
+
+func registerContextCapturingScheme(t *testing.T, scheme string) *contextCapturingScheme {
+	t.Helper()
+
+	c := &contextCapturingScheme{}
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		closes := &atomic.Int32{}
+
+		c.mu.Lock()
+		c.opened = append(c.opened, ctx)
+		c.closes = append(c.closes, closes)
+		c.mu.Unlock()
+
+		return &closeTrackingIO{IO: iceio.LocalFS{}, closeCount: closes}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return c
+}
+
+func (c *contextCapturingScheme) loads() int {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return len(c.opened)
+}
+
+func (c *contextCapturingScheme) ctx(i int) context.Context {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return c.opened[i]
+}
+
+func (c *contextCapturingScheme) closeCount(i int) int32 {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return c.closes[i].Load()
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context. The
+// refresher owns the IO's lifetime instead: renewal closes the superseded IO
+// and ends its context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	fs := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "first"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.Equal(t, 1, fs.loads())
+	require.NoError(t, fs.ctx(0).Err(), "the cached IO must not be bound to the caller's cancellation")
+	// WithoutCancel keeps values, so the first caller's values reach the shared
+	// IO. This documents the current behaviour; it is a trade-off, not a promise.
+	assert.Equal(t, "first", fs.ctx(0).Value(vendedCtxKey{}))
+
+	// Renewal rebuilds the IO on its own context and retires the old one.
+	r.expiresAt = time.Now().Add(-time.Minute)
+	ctx, cancel = context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "second"))
+	_, err = r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.Equal(t, 2, fs.loads(), "renewal must rebuild the IO")
+	assert.NotSame(t, fs.ctx(0), fs.ctx(1), "the renewed IO gets a context of its own")

Review Comment:
   Dropped. `loads() == 2` and the value check cover the rebuild.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +931,168 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// contextCapturingScheme is a filesystem whose factory records every context
+// it is opened with, the way a filesystem that keeps its opening context
+// (blobfs) would, and counts how often each IO it handed out is closed.
+type contextCapturingScheme struct {

Review Comment:
   Done. The fake now returns a `blobfs.FileIO` over its own memblob bucket, opened on the context it is given. The tests cancel the first caller's context and then read through the cached IO, which fails on main with `context canceled`.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#discussion_r4187723647


##########
catalog/rest/vended_creds.go:
##########
@@ -171,33 +176,62 @@ func (v *vendedCredentialRefresher) loadFS(ctx context.Context) (iceio.IO, error
 		maps.Copy(config, freshCreds)
 	}
 
+	// The IO is cached and shared by every later caller, so it must not
+	// inherit this caller's cancellation: a filesystem may keep the context it
+	// is opened with (blobfs does, so every gocloud backend), and a cached IO
+	// built on a per-operation context would fail every later operation with
+	// context.Canceled once that context is done. The refresher owns the IO's
+	// lifetime instead, through ioCancel. fetchCreds above still honours ctx.
+	//
+	// WithoutCancel keeps ctx's values, and the IO depends on them: the S3
+	// factory takes its base AWS config from utils.GetAwsConfig(ctx), so do
+	// not replace this with context.Background(). The flip side is that the
+	// first caller's request-scoped values stay attached to the shared IO.
+	ioCtx, ioCancel := context.WithCancel(context.WithoutCancel(ctx))
+
+	var (
+		newIO     iceio.IO
+		expiresAt time.Time
+		issuedAt  = v.issuedAt
+	)
+
 	if len(v.credentials) > 0 {
-		prefixIO := newPrefixScopedIO(ctx, v.props, v.credentials)
+		prefixIO := newPrefixScopedIO(ioCtx, v.props, v.credentials)
 		prefixIO.nowFunc = v.now
-		v.cachedIO = prefixIO
+		newIO = prefixIO
 		// Expiry is enforced by prefixScopedIO against only the credential
 		// selected for each object location.
-		v.expiresAt = time.Time{}
+	} else {
+		loaded, err := iceio.LoadFS(ioCtx, config, v.location)
+		if err != nil {
+			ioCancel()
 
-		return v.cachedIO, nil
-	}
+			if v.cachedIO == nil {
+				return nil, err
+			}
 
-	newIO, err := iceio.LoadFS(ctx, config, v.location)
-	if err != nil {
-		if v.cachedIO == nil {
-			return nil, err
+			return nil, fmt.Errorf("load filesystem with refreshed credentials for %s: %w", v.location, err)
 		}
 
-		return nil, fmt.Errorf("load filesystem with refreshed credentials for %s: %w", v.location, err)
+		newIO = loaded
+		expiresAt = v.expiresAtFromConfig(config)
+		issuedAt = v.now()
 	}
 
-	v.cachedIO = newIO
-	v.expiresAt = v.expiresAtFromConfig(config)
-	v.issuedAt = v.now()
+	v.replaceIO(newIO, ioCancel)
+	v.expiresAt = expiresAt
+	v.issuedAt = issuedAt
 
 	return v.cachedIO, nil
 }
 
+// replaceIO installs io as the cached IO. The superseded IO is left open:
+// callers that loaded it earlier may still be using it, and its credentials
+// remain valid until their own expiry.
+func (v *vendedCredentialRefresher) replaceIO(io iceio.IO, cancel context.CancelFunc) {
+	v.cachedIO, v.ioCancel = io, cancel

Review Comment:
   The swap is the subtle part: we deliberately overwrite the old `v.ioCancel` without calling it, because the superseded IO's context has to stay live for callers still holding it. The doc covers "the IO is left open" but not "the old cancel is intentionally dropped", worth spelling out so a future reader doesn't "fix" this with a defensive `if v.ioCancel != nil { v.ioCancel() }` and cancel the context out from under those in-flight callers.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade merged PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "SLoeuillet (via GitHub)" <gi...@apache.org>.
SLoeuillet commented on code in PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#discussion_r4151909966


##########
catalog/rest/vended_creds.go:
##########
@@ -171,8 +171,16 @@ func (v *vendedCredentialRefresher) loadFS(ctx context.Context) (iceio.IO, error
 		maps.Copy(config, freshCreds)
 	}
 
+	// The IO is cached and shared by every later caller, so it must not
+	// inherit this caller's cancellation: a filesystem may keep the context it
+	// is opened with (the GCS one does), so a cached IO built on a
+	// per-operation context would fail every later operation with
+	// context.Canceled once that context is done. Values are kept; fetchCreds
+	// above still honours ctx.
+	ioCtx := context.WithoutCancel(ctx)

Review Comment:
   Done in 884d962. The refresher opens the IO on `context.WithCancel(context.WithoutCancel(ctx))` and stores the cancel. Renewal installs the new IO, then closes the superseded one and cancels its context. A failed renewal cancels only the context it created and keeps the cached IO. `close()` closes the IO and cancels its context. One trade-off: closing the superseded IO also ends any operation still running on it. It is within the renewal buffer of expiry by then, so I kept the close as you suggested.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +928,87 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)

Review Comment:
   Kept it in `loadFS`. With the refresher now owning a cancellable context, `newPrefixScopedIO` has to keep the context it is given: that is how `close()` reaches the filesystems it opens lazily. Moving `WithoutCancel` into the constructor would cut that. I documented it on the constructor and on this test.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +928,87 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// registerContextCapturingScheme registers a filesystem whose factory records
+// the context it is opened with, the way a filesystem that keeps its opening
+// context (GCS) would.
+func registerContextCapturingScheme(t *testing.T, scheme string) func() context.Context {
+	t.Helper()
+
+	var (
+		mu     sync.Mutex
+		opened context.Context
+	)
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		mu.Lock()
+		opened = ctx
+		mu.Unlock()
+
+		return iceio.LocalFS{}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return func() context.Context {
+		mu.Lock()
+		defer mu.Unlock()
+
+		return opened
+	}
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	opened := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "v"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NotNil(t, opened())
+	require.NoError(t, opened().Err(), "the cached IO must not be bound to the caller's cancellation")
+	assert.Equal(t, "v", opened().Value(vendedCtxKey{}), "context values still reach the filesystem")

Review Comment:
   Softened: the test now documents first-caller value inheritance as current behaviour and a trade-off, not a guarantee. The code comment says the same.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +928,87 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// registerContextCapturingScheme registers a filesystem whose factory records
+// the context it is opened with, the way a filesystem that keeps its opening
+// context (GCS) would.
+func registerContextCapturingScheme(t *testing.T, scheme string) func() context.Context {
+	t.Helper()
+
+	var (
+		mu     sync.Mutex
+		opened context.Context
+	)
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		mu.Lock()
+		opened = ctx
+		mu.Unlock()
+
+		return iceio.LocalFS{}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return func() context.Context {
+		mu.Lock()
+		defer mu.Unlock()
+
+		return opened
+	}
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	opened := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "v"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NotNil(t, opened())
+	require.NoError(t, opened().Err(), "the cached IO must not be bound to the caller's cancellation")
+	assert.Equal(t, "v", opened().Value(vendedCtxKey{}), "context values still reach the filesystem")
+
+	// A renewal rebuilds the IO; it must not inherit that caller's cancellation either.
+	r.expiresAt = time.Now().Add(-time.Minute)
+	ctx, cancel = context.WithCancel(context.Background())
+	_, err = r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NoError(t, opened().Err(), "the renewed IO must not be bound to the caller's cancellation")

Review Comment:
   Good catch. The test now records every load: it asserts the factory ran twice, the renewed context is a distinct object, it keeps the second caller's values, and the superseded IO is closed and its context ended.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +928,87 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// registerContextCapturingScheme registers a filesystem whose factory records
+// the context it is opened with, the way a filesystem that keeps its opening
+// context (GCS) would.
+func registerContextCapturingScheme(t *testing.T, scheme string) func() context.Context {
+	t.Helper()
+
+	var (
+		mu     sync.Mutex
+		opened context.Context
+	)
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		mu.Lock()
+		opened = ctx
+		mu.Unlock()
+
+		return iceio.LocalFS{}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return func() context.Context {
+		mu.Lock()
+		defer mu.Unlock()
+
+		return opened
+	}
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	opened := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "v"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NotNil(t, opened())
+	require.NoError(t, opened().Err(), "the cached IO must not be bound to the caller's cancellation")
+	assert.Equal(t, "v", opened().Value(vendedCtxKey{}), "context values still reach the filesystem")
+
+	// A renewal rebuilds the IO; it must not inherit that caller's cancellation either.
+	r.expiresAt = time.Now().Add(-time.Minute)
+	ctx, cancel = context.WithCancel(context.Background())
+	_, err = r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NoError(t, opened().Err(), "the renewed IO must not be bound to the caller's cancellation")
+}
+
+func TestVendedCredsPrefixScopedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-prefix-ctx-detach-test"
+
+	opened := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(nil)
+	r.location = scheme + "://bucket/tbl"
+	r.credentials = []StorageCredential{{Prefix: scheme + "://bucket/", Config: iceberg.Properties{}}}
+
+	ctx, cancel := context.WithCancel(context.Background())
+	fs, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	// prefixScopedIO opens its filesystems lazily, after the call that built it returned.
+	_, err = fs.(*prefixScopedIO).filesystemFor(scheme + "://bucket/tbl/data/file.parquet")

Review Comment:
   Fixed: `p, ok := loaded.(*prefixScopedIO); require.True(t, ok, ...)`.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#discussion_r4148885187


##########
catalog/rest/vended_creds.go:
##########
@@ -171,8 +171,16 @@ func (v *vendedCredentialRefresher) loadFS(ctx context.Context) (iceio.IO, error
 		maps.Copy(config, freshCreds)
 	}
 
+	// The IO is cached and shared by every later caller, so it must not
+	// inherit this caller's cancellation: a filesystem may keep the context it
+	// is opened with (the GCS one does), so a cached IO built on a
+	// per-operation context would fail every later operation with
+	// context.Canceled once that context is done. Values are kept; fetchCreds
+	// above still honours ctx.
+	ioCtx := context.WithoutCancel(ctx)

Review Comment:
   Detaching cancellation here means `close()` is the only thing that can tear down what the IO spawns. For a filesystem that keeps its opening context (the GCS case this targets), background goroutines and credential refreshers now live until `close()`, and renewal replaces the cached IO without closing the old one (further down in `loadFS`), so the superseded one leaks for good, in exactly the setup this PR fixes. Previously the caller's cancellation eventually reaped that work; now nothing does.
   
   I'd have the refresher own the cancel rather than fully detaching:
   
   ```go
   ioCtx, ioCancel := context.WithCancel(context.WithoutCancel(ctx))
   ```
   
   Store `ioCancel` on `v`, cancel the previous one and close the superseded IO before replacing on renewal, and cancel it in `close()`. That keeps the fix and closes the leak the detachment opens.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +928,87 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)

Review Comment:
   This test asserts `newPrefixScopedIO` keeps the caller's cancellation, but the only production caller now hands it a detached context, so the contract it names is dead for the vended path. That splits the detachment contract across two spots and invites a later "fix" back to raw `ctx`. I'd either move the `WithoutCancel` into `newPrefixScopedIO` so detachment lives in one place, or add a line here noting the constructor is context-agnostic and `loadFS` owns the detaching.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +928,87 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// registerContextCapturingScheme registers a filesystem whose factory records
+// the context it is opened with, the way a filesystem that keeps its opening
+// context (GCS) would.
+func registerContextCapturingScheme(t *testing.T, scheme string) func() context.Context {
+	t.Helper()
+
+	var (
+		mu     sync.Mutex
+		opened context.Context
+	)
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		mu.Lock()
+		opened = ctx
+		mu.Unlock()
+
+		return iceio.LocalFS{}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return func() context.Context {
+		mu.Lock()
+		defer mu.Unlock()
+
+		return opened
+	}
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	opened := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "v"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NotNil(t, opened())
+	require.NoError(t, opened().Err(), "the cached IO must not be bound to the caller's cancellation")
+	assert.Equal(t, "v", opened().Value(vendedCtxKey{}), "context values still reach the filesystem")

Review Comment:
   `WithoutCancel` keeps values, so the first caller's request-scoped values (trace spans, loggers, per-request identity) stay attached to the shared IO and reach every later, unrelated caller. Probably harmless for GCS, but asserting it here as a guarantee bakes in a subtlety that's really a trade-off. I'd soften this to document the behavior rather than present first-caller value inheritance as intended.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +928,87 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// registerContextCapturingScheme registers a filesystem whose factory records
+// the context it is opened with, the way a filesystem that keeps its opening
+// context (GCS) would.
+func registerContextCapturingScheme(t *testing.T, scheme string) func() context.Context {
+	t.Helper()
+
+	var (
+		mu     sync.Mutex
+		opened context.Context
+	)
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		mu.Lock()
+		opened = ctx
+		mu.Unlock()
+
+		return iceio.LocalFS{}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return func() context.Context {
+		mu.Lock()
+		defer mu.Unlock()
+
+		return opened
+	}
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	opened := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "v"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NotNil(t, opened())
+	require.NoError(t, opened().Err(), "the cached IO must not be bound to the caller's cancellation")
+	assert.Equal(t, "v", opened().Value(vendedCtxKey{}), "context values still reach the filesystem")
+
+	// A renewal rebuilds the IO; it must not inherit that caller's cancellation either.
+	r.expiresAt = time.Now().Add(-time.Minute)
+	ctx, cancel = context.WithCancel(context.Background())
+	_, err = r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NoError(t, opened().Err(), "the renewed IO must not be bound to the caller's cancellation")
+}
+
+func TestVendedCredsPrefixScopedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-prefix-ctx-detach-test"
+
+	opened := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(nil)
+	r.location = scheme + "://bucket/tbl"
+	r.credentials = []StorageCredential{{Prefix: scheme + "://bucket/", Config: iceberg.Properties{}}}
+
+	ctx, cancel := context.WithCancel(context.Background())
+	fs, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	// prefixScopedIO opens its filesystems lazily, after the call that built it returned.
+	_, err = fs.(*prefixScopedIO).filesystemFor(scheme + "://bucket/tbl/data/file.parquet")

Review Comment:
   Unchecked type assertion: if `loadFS` ever returns a different IO type this panics and skips the cleanup output instead of failing cleanly. `p, ok := fs.(*prefixScopedIO); require.True(t, ok, ...)` reads better.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +928,87 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// registerContextCapturingScheme registers a filesystem whose factory records
+// the context it is opened with, the way a filesystem that keeps its opening
+// context (GCS) would.
+func registerContextCapturingScheme(t *testing.T, scheme string) func() context.Context {
+	t.Helper()
+
+	var (
+		mu     sync.Mutex
+		opened context.Context
+	)
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		mu.Lock()
+		opened = ctx
+		mu.Unlock()
+
+		return iceio.LocalFS{}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return func() context.Context {
+		mu.Lock()
+		defer mu.Unlock()
+
+		return opened
+	}
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	opened := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "v"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NotNil(t, opened())
+	require.NoError(t, opened().Err(), "the cached IO must not be bound to the caller's cancellation")
+	assert.Equal(t, "v", opened().Value(vendedCtxKey{}), "context values still reach the filesystem")
+
+	// A renewal rebuilds the IO; it must not inherit that caller's cancellation either.
+	r.expiresAt = time.Now().Add(-time.Minute)
+	ctx, cancel = context.WithCancel(context.Background())
+	_, err = r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.NoError(t, opened().Err(), "the renewed IO must not be bound to the caller's cancellation")

Review Comment:
   If renewal silently didn't rebuild (`needsRenewal` returned false), `opened()` would still be the first, already-checked context and this passes vacuously; nothing asserts the factory ran a second time. I'd record a call count, or capture the first context before `cancel()` and assert the renewed one is a distinct object. While here, the second ctx is built from `Background()`, so the renewal path never checks values are kept; deriving it with `WithValue` again would cover that too.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#discussion_r4158471446


##########
catalog/rest/vended_creds.go:
##########
@@ -171,33 +176,69 @@ func (v *vendedCredentialRefresher) loadFS(ctx context.Context) (iceio.IO, error
 		maps.Copy(config, freshCreds)
 	}
 
+	// The IO is cached and shared by every later caller, so it must not
+	// inherit this caller's cancellation: a filesystem may keep the context it
+	// is opened with (blobfs does, so every gocloud backend), and a cached IO
+	// built on a per-operation context would fail every later operation with
+	// context.Canceled once that context is done. The refresher owns the IO's
+	// lifetime instead, through ioCancel. fetchCreds above still honours ctx.
+	//
+	// WithoutCancel keeps ctx's values, so the first caller's request-scoped
+	// values stay attached to the shared IO.
+	ioCtx, ioCancel := context.WithCancel(context.WithoutCancel(ctx))
+
+	var (
+		newIO     iceio.IO
+		expiresAt time.Time
+		issuedAt  = v.issuedAt
+	)
+
 	if len(v.credentials) > 0 {
-		prefixIO := newPrefixScopedIO(ctx, v.props, v.credentials)
+		prefixIO := newPrefixScopedIO(ioCtx, v.props, v.credentials)
 		prefixIO.nowFunc = v.now
-		v.cachedIO = prefixIO
+		newIO = prefixIO
 		// Expiry is enforced by prefixScopedIO against only the credential
 		// selected for each object location.
-		v.expiresAt = time.Time{}
+	} else {
+		loaded, err := iceio.LoadFS(ioCtx, config, v.location)
+		if err != nil {
+			ioCancel()
 
-		return v.cachedIO, nil
-	}
+			if v.cachedIO == nil {
+				return nil, err
+			}
 
-	newIO, err := iceio.LoadFS(ctx, config, v.location)
-	if err != nil {
-		if v.cachedIO == nil {
-			return nil, err
+			return nil, fmt.Errorf("load filesystem with refreshed credentials for %s: %w", v.location, err)
 		}
 
-		return nil, fmt.Errorf("load filesystem with refreshed credentials for %s: %w", v.location, err)
+		newIO = loaded
+		expiresAt = v.expiresAtFromConfig(config)
+		issuedAt = v.now()
 	}
 
-	v.cachedIO = newIO
-	v.expiresAt = v.expiresAtFromConfig(config)
-	v.issuedAt = v.now()
+	v.replaceIO(newIO, ioCancel)
+	v.expiresAt = expiresAt
+	v.issuedAt = issuedAt
 
 	return v.cachedIO, nil
 }
 
+// replaceIO installs io as the cached IO, then closes the one it supersedes
+// and cancels that one's context. An error closing the superseded IO is not
+// returned: the new IO is already in place, and the caller has no use for it.
+func (v *vendedCredentialRefresher) replaceIO(io iceio.IO, cancel context.CancelFunc) {
+	oldIO, oldCancel := v.cachedIO, v.ioCancel
+	v.cachedIO, v.ioCancel = io, cancel
+
+	if oldIO != nil {
+		_ = closeOptionalIO(oldIO)
+	}
+
+	if oldCancel != nil {
+		oldCancel()
+	}
+}

Review Comment:
   Renewal closes the superseded IO and cancels its context while other callers can still hold it. `loadFS` hands the same IO to every caller, and the table code keeps it across later `fsF` calls. After gocloud `Bucket.Close()`, `NewRangeReader`/`NewWriter`/`Delete` return `blob: Bucket has been closed` (gocloud v0.46.0 `blob/blob.go:1034`, `:1187`, `:1284`). blobfs opens a range reader on every `ReadAt`, so files that are already open fail as well. The cancel also aborts reads and uploads that are in flight.
   
   In-tree callers this breaks:
   - `table/scanner.go:1181`: `manifestIOBatch.acquire` re-calls the factory at each batch boundary on purpose, as a renewal checkpoint. Sibling errgroup workers (`scanner.go:1280`, `:1435`) are still reading manifests through the previous IO, so a renewal there fails `PlanFiles`.
   - `table/rewrite_data_files.go:624`: `rewriteDataFilesPartial` holds `fs` across `ExecuteCompactionGroup` (`:647`, which reaches `fsF` via `ReadTasks` and `WriteRecords`). It then uses that `fs` for `CollectDeadPositionDeletes` (`:669`) and for cleanup (`:635`). A renewal mid-batch fails the batch, and because cleanup runs on the same closed IO, the new data files are orphaned.
   - `fsF` is shared by every table derived from the load (`table/table.go:824`, `table/transaction.go:3326`, `Scan.ioF`), so concurrent scans and writes, including lazy `ReadTasks` iterators, fail whenever another goroutine triggers renewal.
   
   "Within the renewal buffer" does not cover it. With no vended expiry, `expiresAtFromConfig` falls back to now+60m, so valid credentials get cut every ~55 min where main never failed. With a known expiry, the buffer exists so in-flight work can finish on still-valid creds.
   
   The leak this guards against is not there for our backends: s3blob/gcsblob/azureblob `Close()` return nil (`Bucket.Close` is only a flag flip), `io/gocloud` starts no goroutines tied to the ctx, and `WithCancel(WithoutCancel(ctx))` registers with no parent, so an uncancelled one is just collected.
   
   The close also runs under `v.mu`, with the cancel after it. gocloud `Close()` takes the bucket write lock and waits for in-flight readers, so every other `loadFS` caller stalls behind them. `TestPrefixScopedIODoesNotHoldLockDuringFilesystemClose` exists to prevent that for `prefixScopedIO`.
   
   Fix: make this swap-only, as in f6423dc, and keep cancelling the current IO in `close()`. That is safe for plan-scoped IO because the scan's reader lease keeps it open while readers are active. Update the `ioCancel` field comment to match. If teardown for third-party IOs matters, retire the old IO after its credentials' hard expiry, outside the semaphore.
   
   ```suggestion
   // replaceIO installs io as the cached IO. The superseded IO is left open:
   // callers that loaded it earlier may still be using it, and its credentials
   // remain valid until their own expiry.
   func (v *vendedCredentialRefresher) replaceIO(io iceio.IO, cancel context.CancelFunc) {
   	v.cachedIO, v.ioCancel = io, cancel
   }
   ```



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +931,168 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// contextCapturingScheme is a filesystem whose factory records every context
+// it is opened with, the way a filesystem that keeps its opening context
+// (blobfs) would, and counts how often each IO it handed out is closed.
+type contextCapturingScheme struct {
+	mu     sync.Mutex
+	opened []context.Context
+	closes []*atomic.Int32
+}
+
+func registerContextCapturingScheme(t *testing.T, scheme string) *contextCapturingScheme {
+	t.Helper()
+
+	c := &contextCapturingScheme{}
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		closes := &atomic.Int32{}
+
+		c.mu.Lock()
+		c.opened = append(c.opened, ctx)
+		c.closes = append(c.closes, closes)
+		c.mu.Unlock()
+
+		return &closeTrackingIO{IO: iceio.LocalFS{}, closeCount: closes}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return c
+}
+
+func (c *contextCapturingScheme) loads() int {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return len(c.opened)
+}
+
+func (c *contextCapturingScheme) ctx(i int) context.Context {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return c.opened[i]
+}
+
+func (c *contextCapturingScheme) closeCount(i int) int32 {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return c.closes[i].Load()
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context. The
+// refresher owns the IO's lifetime instead: renewal closes the superseded IO
+// and ends its context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	fs := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "first"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.Equal(t, 1, fs.loads())
+	require.NoError(t, fs.ctx(0).Err(), "the cached IO must not be bound to the caller's cancellation")
+	// WithoutCancel keeps values, so the first caller's values reach the shared
+	// IO. This documents the current behaviour; it is a trade-off, not a promise.
+	assert.Equal(t, "first", fs.ctx(0).Value(vendedCtxKey{}))
+
+	// Renewal rebuilds the IO on its own context and retires the old one.
+	r.expiresAt = time.Now().Add(-time.Minute)
+	ctx, cancel = context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "second"))
+	_, err = r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.Equal(t, 2, fs.loads(), "renewal must rebuild the IO")
+	assert.NotSame(t, fs.ctx(0), fs.ctx(1), "the renewed IO gets a context of its own")
+	require.NoError(t, fs.ctx(1).Err(), "the renewed IO must not be bound to the caller's cancellation")
+	assert.Equal(t, "second", fs.ctx(1).Value(vendedCtxKey{}))
+
+	require.ErrorIs(t, fs.ctx(0).Err(), context.Canceled, "the superseded IO's context is ended")
+	assert.Equal(t, int32(1), fs.closeCount(0), "the superseded IO is closed")

Review Comment:
   These two lines pin the teardown from the `replaceIO` comment. Invert them: after renewal, `fs.ctx(0).Err()` is nil and `closeCount(0)` is 0. Then add the property the table code depends on: keep the IO from the first `loadFS`, renew, and use it afterwards. With a memblob-backed `blobfs` scheme, that read would fail on this head with `blob: Bucket has been closed`.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +931,168 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// contextCapturingScheme is a filesystem whose factory records every context
+// it is opened with, the way a filesystem that keeps its opening context
+// (blobfs) would, and counts how often each IO it handed out is closed.
+type contextCapturingScheme struct {
+	mu     sync.Mutex
+	opened []context.Context
+	closes []*atomic.Int32
+}
+
+func registerContextCapturingScheme(t *testing.T, scheme string) *contextCapturingScheme {
+	t.Helper()
+
+	c := &contextCapturingScheme{}
+
+	iceio.Register(scheme, func(ctx context.Context, _ *url.URL, _ map[string]string) (iceio.IO, error) {
+		closes := &atomic.Int32{}
+
+		c.mu.Lock()
+		c.opened = append(c.opened, ctx)
+		c.closes = append(c.closes, closes)
+		c.mu.Unlock()
+
+		return &closeTrackingIO{IO: iceio.LocalFS{}, closeCount: closes}, nil
+	})
+	t.Cleanup(func() { iceio.Unregister(scheme) })
+
+	return c
+}
+
+func (c *contextCapturingScheme) loads() int {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return len(c.opened)
+}
+
+func (c *contextCapturingScheme) ctx(i int) context.Context {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return c.opened[i]
+}
+
+func (c *contextCapturingScheme) closeCount(i int) int32 {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	return c.closes[i].Load()
+}
+
+type vendedCtxKey struct{}
+
+// The cached IO outlives the call that built it, so a caller that scopes one
+// operation to its own context (cancelled when the operation returns) must not
+// leave every later operation with a filesystem opened on a dead context. The
+// refresher owns the IO's lifetime instead: renewal closes the superseded IO
+// and ends its context.
+func TestVendedCredsCachedIODoesNotInheritCallerCancellation(t *testing.T) {
+	const scheme = "vended-ctx-detach-test"
+
+	fs := registerContextCapturingScheme(t, scheme)
+
+	r := newTestRefresher(func(context.Context, []string) (iceberg.Properties, error) {
+		return iceberg.Properties{}, nil
+	})
+	r.location = scheme + "://bucket/tbl"
+
+	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "first"))
+	_, err := r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.Equal(t, 1, fs.loads())
+	require.NoError(t, fs.ctx(0).Err(), "the cached IO must not be bound to the caller's cancellation")
+	// WithoutCancel keeps values, so the first caller's values reach the shared
+	// IO. This documents the current behaviour; it is a trade-off, not a promise.
+	assert.Equal(t, "first", fs.ctx(0).Value(vendedCtxKey{}))
+
+	// Renewal rebuilds the IO on its own context and retires the old one.
+	r.expiresAt = time.Now().Add(-time.Minute)
+	ctx, cancel = context.WithCancel(context.WithValue(context.Background(), vendedCtxKey{}, "second"))
+	_, err = r.loadFS(ctx)
+	require.NoError(t, err)
+	cancel()
+
+	require.Equal(t, 2, fs.loads(), "renewal must rebuild the IO")
+	assert.NotSame(t, fs.ctx(0), fs.ctx(1), "the renewed IO gets a context of its own")

Review Comment:
   This only passes because `context.WithCancel` returns a `*cancelCtx`. Against a plain `WithoutCancel` context (f6423dc) it fails with `Both arguments must be pointers`; I ran it. It checks how the context type is implemented, not the renewal. `loads() == 2` plus the value check on :1023 already show a new IO was built on the second caller's context, so drop it.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +931,168 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// contextCapturingScheme is a filesystem whose factory records every context
+// it is opened with, the way a filesystem that keeps its opening context
+// (blobfs) would, and counts how often each IO it handed out is closed.
+type contextCapturingScheme struct {

Review Comment:
   Optional: this fake records the context but never uses it, so the real root cause in #2078 is only covered by proxy: `blobfs` keeps the ctx and uses it in `Open`/`ReadAt`/`Create`. A scheme that returns a memblob-backed `blobfs.FileIO` built on the ctx it is given lets the test cancel the first caller's ctx, then open and read through the cached IO. Together with the renewal case on :1025, that covers both the bug and the regression.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#discussion_r4168187042


##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +933,214 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// contextCapturingScheme is a filesystem that behaves like the gocloud
+// backends: every load returns a blobfs.FileIO over its own in-memory bucket,
+// opened on the context it is given, which blobfs keeps and uses for every
+// operation. It records each context and counts closes; closing an IO closes
+// its bucket.
+type contextCapturingScheme struct {
+	scheme string

Review Comment:
   Nit: nothing reads `scheme`, because the factory closure already captures the parameter. It can be removed.



##########
catalog/rest/vended_creds.go:
##########
@@ -171,33 +176,60 @@ func (v *vendedCredentialRefresher) loadFS(ctx context.Context) (iceio.IO, error
 		maps.Copy(config, freshCreds)
 	}
 
+	// The IO is cached and shared by every later caller, so it must not
+	// inherit this caller's cancellation: a filesystem may keep the context it
+	// is opened with (blobfs does, so every gocloud backend), and a cached IO
+	// built on a per-operation context would fail every later operation with
+	// context.Canceled once that context is done. The refresher owns the IO's
+	// lifetime instead, through ioCancel. fetchCreds above still honours ctx.
+	//
+	// WithoutCancel keeps ctx's values, so the first caller's request-scoped

Review Comment:
   Nit: the IO depends on the ctx values that `WithoutCancel` keeps; they aren't just a cost. The S3 factory takes its base AWS config from `utils.GetAwsConfig(ctx)` (`io/gocloud/s3/s3.go:192`) on `ioCtx`. Please say so in the comment so a later cleanup doesn't switch this to `context.Background()`.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "SLoeuillet (via GitHub)" <gi...@apache.org>.
SLoeuillet commented on code in PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#discussion_r4176962549


##########
catalog/rest/vended_creds.go:
##########
@@ -171,33 +176,60 @@ func (v *vendedCredentialRefresher) loadFS(ctx context.Context) (iceio.IO, error
 		maps.Copy(config, freshCreds)
 	}
 
+	// The IO is cached and shared by every later caller, so it must not
+	// inherit this caller's cancellation: a filesystem may keep the context it
+	// is opened with (blobfs does, so every gocloud backend), and a cached IO
+	// built on a per-operation context would fail every later operation with
+	// context.Canceled once that context is done. The refresher owns the IO's
+	// lifetime instead, through ioCancel. fetchCreds above still honours ctx.
+	//
+	// WithoutCancel keeps ctx's values, so the first caller's request-scoped

Review Comment:
   Done in ccbee4c: the comment now says the IO depends on the kept values (`utils.GetAwsConfig(ctx)` in the S3 factory) and must not become `context.Background()`.



##########
catalog/rest/vended_creds_test.go:
##########
@@ -928,3 +933,214 @@ func TestPrefixScopedIOPreservesReadContextCancellation(t *testing.T) {
 	cancel()
 	require.ErrorIs(t, p.ctx.Err(), context.Canceled)
 }
+
+// contextCapturingScheme is a filesystem that behaves like the gocloud
+// backends: every load returns a blobfs.FileIO over its own in-memory bucket,
+// opened on the context it is given, which blobfs keeps and uses for every
+// operation. It records each context and counts closes; closing an IO closes
+// its bucket.
+type contextCapturingScheme struct {
+	scheme string

Review Comment:
   Removed in ccbee4c.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(catalog/rest): don't bind the cached vended-credential FileIO to the caller's context [iceberg-go]

Posted by "SLoeuillet (via GitHub)" <gi...@apache.org>.
SLoeuillet commented on PR #2079:
URL: https://github.com/apache/iceberg-go/pull/2079#issuecomment-5946293892

   @zeroshade @laskoviymishka updated in d7ed212 per the review above: swap-only renewal, teardown kept in `close()`, and tests on a real blobfs/memblob IO. 0.7.0 shipped in the meantime; a 0.7.1 with this would unblock long-running writers on vended credentials.


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org