Subject: Re: [PATCH net-next 2/2] selftests: net: py: ensure defer() is only used within a test case

From: Jakub Kicinski <[email-masked]>
Date: Fri, 9 Jan 2026 06:39:38 -0800

On Fri, 9 Jan 2026 09:23:54 +0100 Petr Machata wrote:
> > I wasted a couple of hours recently after accidentally adding
> > a defer() from within a function which itself was called as
> > part of defer(). This leads to an infinite loop of defer().
> > Make sure this cannot happen and raise a helpful exception.
> >
> > I understand that the pair of _ksft_defer_arm() calls may
> > not be the most Pythonic way to implement this, but it's
> > easy enough to understand.
> >
> > Signed-off-by: Jakub Kicinski <[email-masked]>  
> 
> I think we achieve the same without the extra globals though? Just drain
> the queue and walk through a copy of it?
> 
>     defer_queue = utils.GLOBAL_DEFER_QUEUE
>     utils.GLOBAL_DEFER_QUEUE = []
>     for i, entry in enumerate(defer_queue):
>         ...
>     if utils.GLOBAL_DEFER_QUEUE:
>         warning / exception

That's what I had initially (IIUC), I was assigning None to the queue,
and then [] only while inside a test case. It gets slightly hairy
because either we need to pass in the queue into the flush function;
or we have to restore the queue if something raises and exception during
flush (in which case ksft_run() prints a warning and calls
ksft_flush_defer() one more time).

That approach definitely worked, but unless I'm missing a trick it was
higher complexity and LoC.