Skip to content

Fix @noreentry breaking contextlib ExitStack support for decorated context managers — Closes #306#307

Merged
conradbzura merged 2 commits into
wool-labs:releasefrom
conradbzura:306-fix-noreentry-exitstack
Jul 13, 2026
Merged

Fix @noreentry breaking contextlib ExitStack support for decorated context managers — Closes #306#307
conradbzura merged 2 commits into
wool-labs:releasefrom
conradbzura:306-fix-noreentry-exitstack

Conversation

@conradbzura

Copy link
Copy Markdown
Contributor

Summary

contextlib enters a context manager by looking the special method up on the type and calling it unbound (cls = type(cm); _enter = cls.__enter__; result = _enter(cm)). For a @noreentry-decorated __enter__ that class access returns the descriptor itself, so contextlib called it directly and landed in __call__ — whose only job was to reject bare functions. Any guarded context manager therefore blew up with TypeError: @noreentry only decorates methods, not bare functions the moment it was pushed onto a stack. WorkerPool is affected on release today: a pool cannot be composed onto an AsyncExitStack alongside other resources.

Record the owning class with __set_name__ and teach __call__ to recognise the unbound-call form — an owned descriptor invoked with an instance of its owner is the bound call it actually is — delegating through __get__ so the guard, the coroutine-ness, and the per-instance wrapper cache all still apply. __get__ is deliberately left alone: class-level access keeps returning the descriptor, so asyncio.iscoroutinefunction, __name__, and the existing zero-argument TypeError all behave exactly as before. A bare function never gets an owner, so it is still rejected.

The alternative — having __get__(None, ...) return an unbound wrapper — was prototyped and rejected: it silently breaks iscoroutinefunction on the class attribute (the wrapper is a sync function returning a coroutine) and changes the bare-function error message. Discriminating in __call__ preserves all ten pre-existing tests unchanged.

Closes #306

Proposed changes

Record the owning class

Add __set_name__, which Python calls when the descriptor is bound into a class body. A bare module-level function never triggers it, so _owner stays None — and that absence is precisely what distinguishes a genuine bare-function invocation from contextlib's unbound call.

Recognise the unbound-call form in __call__

__call__ now delegates when the descriptor is owned and its first argument is an instance of that owner, forwarding the remaining arguments; otherwise it raises TypeError as before. Delegation routes through __get__, reusing the existing per-instance wrapper rather than re-implementing the guard, so bound and unbound calls share one guard and one piece of state. isinstance (not type(...) is) is used deliberately: contextlib looks the method up on type(cm), which may be a subclass of the class the method was defined on.

This also fixes teardown, which the issue did not mention: contextlib registers exit as MethodType(cls.__exit__, cm), so a guarded __exit__ is routed through the same path and receives its exception triple as trailing arguments.

Correct the decorator's parameter documentation

:param fn: advertised "the bound instance or class method to decorate", but @classmethod composed with @noreentry raises TypeError in both stacking orders and always has. Narrow the claim to what the decorator actually accepts.

Test cases

# Test Suite Given When Then Coverage Target
1 TestNoReentry A sync manager whose __enter__ is guarded It is pushed onto an ExitStack It enters and yields the manager The reported failure
2 TestNoReentry A sync manager already entered on a stack It is pushed a second time It raises RuntimeError The guard is not bypassed by the new path
3 TestNoReentry An async manager whose __aenter__ is guarded It is pushed onto an AsyncExitStack It enters and yields the manager The awaitable return path
4 TestNoReentry An async manager already entered on a stack It is pushed a second time It raises RuntimeError The guard on the async path
5 TestNoReentry A manager whose __enter__ and __exit__ are both guarded An exception is raised inside an ExitStack body __exit__ receives the exception details and the exception propagates Trailing-argument forwarding through the descriptor
6 TestNoReentry An async manager whose __aenter__ and __aexit__ are both guarded An exception is raised inside an AsyncExitStack body __aexit__ receives the exception details and the exception propagates Trailing-argument forwarding on the async exit path
7 TestNoReentry A guarded manager already entered with a plain with statement It is pushed onto an ExitStack It raises RuntimeError The guard is shared across bound and unbound call forms
8 TestNoReentry Any non-empty sequence of bound and unbound call forms The sequence is applied to one fresh instance Exactly the first invocation succeeds and every later one raises RuntimeError Single-use semantics under arbitrary interleavings
9 TestNoReentry A subclass of a class whose __enter__ is guarded on the base An instance of the subclass is pushed onto an ExitStack It enters successfully Dispatch admits subclass instances
10 TestNoReentry A guarded sync manager It is used in a plain with statement It enters and yields the manager The implicit special-method path still works
11 TestNoReentry A guarded async manager It is used in a plain async with statement It enters and yields the manager The implicit async path still works
12 TestNoReentry A guarded method taking a positional and a keyword-only argument It is called unbound with the instance first, then both arguments It returns the result computed from both forwarded arguments Keyword-argument forwarding
13 TestNoReentry A @noreentry-decorated module-level function owned by no class It is called It raises TypeError Bare-function rejection, which previously had no real test
14 TestNoReentry A guarded method accessed unbound It is called with an instance of another class It raises TypeError Foreign instances are not admitted
15 TestNoReentry A guarded method accessed unbound It is called with no arguments It raises TypeError The no-instance rejection branch
16 TestWorkerPool A WorkerPool, whose __aenter__ is guarded It is pushed onto an AsyncExitStack and the stack unwinds It enters, yields the pool, and is torn down on unwind The user-facing symptom from the issue

Two pre-existing tests are also reworked: test_noreentry_bare_function_raises_error is renamed to say what it actually asserts (it calls an owned descriptor with no arguments — a distinct rejection branch from a genuinely unowned function, which case 13 now covers), and test_noreentry_unbound_access_returns_descriptor is dropped, its only assertion being assert unbound is not None, which cannot fail.

Mutation-checked: cases 5, 6, and 12 fail if __call__ stops forwarding trailing arguments, and case 9 fails if isinstance is weakened to type(...) is. Before these were added, both mutations passed the entire 146-test suite.

@conradbzura conradbzura self-assigned this Jul 13, 2026
Pushing a guarded context manager onto an ExitStack or AsyncExitStack
raised TypeError, the error the decorator emits for bare functions.
contextlib looks special methods up on the type and calls them unbound,
so type(cm).__enter__(cm) reaches the descriptor itself rather than a
bound wrapper, and __call__ rejected it. WorkerPool was affected: a pool
could not be composed onto a stack alongside other resources.

Record the owning class via __set_name__ and treat an owned descriptor
invoked with an instance of its owner as the bound call it actually is,
delegating through __get__ so the guard, the coroutine-ness, and the
wrapper cache all still apply. Class-level access keeps returning the
descriptor, so introspection is unchanged, and a bare function still has
no owner and is still rejected. Teardown works the same way: contextlib
registers exit as a method of the type, so a guarded __exit__ receives
its exception triple through the same path.
Pin the reported failure at both the utility and the WorkerPool level:
a guarded manager enters through ExitStack and AsyncExitStack, and the
guard still rejects a second entry there.

Guard the argument-forwarding half of the contract, which nothing
exercised. contextlib registers teardown as a method of the type, so a
guarded exit is routed through the descriptor with its exception triple
as trailing arguments; every prior test entered with no arguments at
all, so an implementation that dropped them silently passed. Cover the
exception details reaching a guarded exit through both stacks, and
argument forwarding on a direct unbound call.

Pin the guard as shared across the bound and unbound call forms, by
example and by a property over arbitrary interleavings of the two, so
the widened dispatch cannot become a way around single-use semantics.
Cover a subclass entering through a stack, since dispatch admits any
instance of the owning class rather than only exact instances, and the
plain statement form, which had no coverage of its own.

Rename the bare-function test to say what it asserts: it calls an owned
descriptor with no instance, which is a distinct rejection branch from a
genuinely unowned function. Drop the unbound-access test, whose only
assertion could not fail.
@conradbzura conradbzura force-pushed the 306-fix-noreentry-exitstack branch from 13c191c to 63ad271 Compare July 13, 2026 20:03
@conradbzura conradbzura changed the title Fix @noreentry breaking contextlib ExitStack support for decorated __enter__ and __aenter__ — Closes #306 Fix @noreentry breaking contextlib ExitStack support for decorated context managers — Closes #306 Jul 13, 2026
@conradbzura conradbzura marked this pull request as ready for review July 13, 2026 20:05
@conradbzura conradbzura merged commit 2107979 into wool-labs:release Jul 13, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix @noreentry breaking contextlib ExitStack support for decorated context managers

1 participant