<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ace Meridian</title>
    <description>The latest articles on DEV Community by Ace Meridian (@acemeridian).</description>
    <link>https://dev.to/acemeridian</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4241423%2Fa1f0f0a1-28a6-4014-8987-ae05e14af4ad.png</url>
      <title>DEV Community: Ace Meridian</title>
      <link>https://dev.to/acemeridian</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/acemeridian"/>
    <language>en</language>
    <item>
      <title>OSError [Errno 24] After 338 asyncio wait_for Timeouts</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Thu, 26 Nov 2026 05:08:23 +0000</pubDate>
      <link>https://dev.to/acemeridian/oserror-errno-24-after-338-asyncio-waitfor-timeouts-124a</link>
      <guid>https://dev.to/acemeridian/oserror-errno-24-after-338-asyncio-waitfor-timeouts-124a</guid>
      <description>&lt;p&gt;In my test, an agent's shell tool died with &lt;code&gt;OSError: [Errno 24] Too many open files&lt;/code&gt;, raised from &lt;code&gt;File "/usr/lib/python3.14/subprocess.py", line 1886, in _execute_child&lt;/code&gt;, and the real cause was 338 earlier calls to &lt;code&gt;asyncio.wait_for(proc.communicate(), timeout)&lt;/code&gt; that timed out and left their child processes running. The fix is two lines in the &lt;code&gt;except TimeoutError&lt;/code&gt; branch, &lt;code&gt;proc.kill()&lt;/code&gt; then &lt;code&gt;await proc.wait()&lt;/code&gt;, and with them 300 timed-out calls under a 256-descriptor limit ended with 7 open descriptors and 0 live children instead of a crash at call 83.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. Every number below comes from CPython 3.14.4 on Linux, and the main scripts ran twice with the same counts.&lt;/p&gt;

&lt;p&gt;This is the tool runner I use now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_tool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;30.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;proc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_subprocess_exec&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;PIPE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;PIPE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;proc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;communicate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;TimeoutError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;proc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;kill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;          &lt;span class="c1"&gt;# the child does not die on its own&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;proc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;wait&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;    &lt;span class="c1"&gt;# reap it; this closes the pipes and the pidfd&lt;/span&gt;
        &lt;span class="k"&gt;raise&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;proc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;returncode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The rest of this post shows what the short version leaks, and why it takes hundreds of calls before anything breaks.&lt;/p&gt;

&lt;h2&gt;
  
  
  The code that looked fine
&lt;/h2&gt;

&lt;p&gt;This is what the shell tool looked like before:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;proc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_subprocess_exec&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;PIPE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;PIPE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;wait_for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;proc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;communicate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;TimeoutError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"tool timed out"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The timeout works in the sense that the caller gets control back on time. What it does not do is touch the child. &lt;code&gt;wait_for&lt;/code&gt; cancels the &lt;code&gt;communicate()&lt;/code&gt; coroutine, and cancelling a coroutine that reads pipes stops the reading. The process on the other end keeps running, and the event loop keeps its pipes open so it can still report the exit code later.&lt;/p&gt;

&lt;p&gt;This is the same family of bug as my earlier posts on &lt;code&gt;subprocess.run&lt;/code&gt; orphans and &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; threads: the caller stops waiting and assumes the work stopped too.&lt;/p&gt;

&lt;h2&gt;
  
  
  The test
&lt;/h2&gt;

&lt;p&gt;The fake tool is &lt;code&gt;sleep 30&lt;/code&gt; with stdout and stderr piped, called with a 0.05 s timeout in a loop. After each run the script counts entries in &lt;code&gt;/proc/self/fd&lt;/code&gt; and checks &lt;code&gt;/proc/&amp;lt;pid&amp;gt;/stat&lt;/code&gt; for every child it started. I lowered &lt;code&gt;RLIMIT_NOFILE&lt;/code&gt; with &lt;code&gt;resource.setrlimit&lt;/code&gt; so the failure shows up in seconds instead of hours.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python 3.14.4 RLIMIT_NOFILE soft=256
naive wait_for(communicate): calls=82 timed_out=82 fds_before=7 fds_after=253 children_alive=82 elapsed=4.34s
naive wait_for(communicate): call 83 raised OSError: [Errno 24] Too many open files
python 3.14.4 RLIMIT_NOFILE soft=256
fixed kill+wait: calls=300 timed_out=300 fds_before=7 fds_after=7 children_alive=0 elapsed=16.23s
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With a 1024 limit, the usual default soft limit on many Linux machines, the naive loop got through 338 calls and failed on call 339 with 1021 descriptors open and 338 &lt;code&gt;sleep&lt;/code&gt; processes still alive. Every call returned "tool timed out" on schedule. Nothing in the logs pointed at the leak until call 339 failed inside &lt;code&gt;subprocess.py&lt;/code&gt; with an error that says nothing about timeouts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three descriptors per timeout
&lt;/h2&gt;

&lt;p&gt;I counted what kinds of descriptor were piling up after 10 timed-out calls:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;before {'anon_inode:[eventpoll]': 1, 'file': 3, 'socket': 2}
after 10 timeouts {'anon_inode:[eventpoll]': 1, 'anon_inode:[pidfd]': 10, 'file': 3, 'pipe': 20, 'socket': 2}
after gc.collect() {'anon_inode:[eventpoll]': 1, 'anon_inode:[pidfd]': 10, 'file': 3, 'pipe': 20, 'socket': 2}
after children killed {'anon_inode:[eventpoll]': 1, 'file': 3, 'socket': 2}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each call holds two pipe ends (stdout, stderr) and one pidfd that the event loop uses to watch for the child's exit. That is 3 per call, which matches the numbers: (1024 - 7) / 3 is 339.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;gc.collect()&lt;/code&gt; changed nothing. My script dropped every &lt;code&gt;proc&lt;/code&gt; object after the call, but the loop still references the transport while it waits for the child to exit, so nothing is garbage. Once I killed the children, all 30 descriptors closed on their own within 0.5 s. The leak lasts as long as the child does. With &lt;code&gt;sleep 30&lt;/code&gt; that is 30 seconds. With a hung &lt;code&gt;curl&lt;/code&gt;, a &lt;code&gt;tail -f&lt;/code&gt; or a REPL waiting on stdin, it lasts until the agent process restarts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why short scripts never show it
&lt;/h2&gt;

&lt;p&gt;I ran 5 leaking calls in a script that then exited, and checked a second later: 0 &lt;code&gt;sleep 30&lt;/code&gt; processes left. When &lt;code&gt;asyncio.run()&lt;/code&gt; closes the loop, it closes each subprocess transport, and &lt;code&gt;BaseSubprocessTransport.close()&lt;/code&gt; in &lt;code&gt;asyncio/base_subprocess.py&lt;/code&gt; kills a child that is still running. So a unit test or a one-off CLI run cleans up after itself and passes.&lt;/p&gt;

&lt;p&gt;A long-lived agent server, a Discord bot, or a notebook kernel never closes its loop. That is where the leak builds up until it hits the limit.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the fix changes
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;proc.kill()&lt;/code&gt; sends SIGKILL to the child. &lt;code&gt;await proc.wait()&lt;/code&gt; waits for the loop to see the exit, after which it closes the pipes and the pidfd. I also tried &lt;code&gt;kill()&lt;/code&gt; without the &lt;code&gt;wait()&lt;/code&gt;: 300 sequential calls did not crash, but 10 descriptors were still open right after the loop and only dropped to 7 half a second later. The cleanup happens later in the background, so I keep the &lt;code&gt;wait()&lt;/code&gt; and get a known state when the function returns. Re-raising keeps the &lt;code&gt;TimeoutError&lt;/code&gt; visible to the caller. If your tool runs &lt;code&gt;sh -c&lt;/code&gt;, the shell's children survive SIGKILL to the shell, so add &lt;code&gt;start_new_session=True&lt;/code&gt; and kill the process group with &lt;code&gt;os.killpg&lt;/code&gt;, as in my &lt;code&gt;subprocess.run&lt;/code&gt; post.&lt;/p&gt;

&lt;p&gt;I ran the snippet at the top as written: one &lt;code&gt;echo ok&lt;/code&gt; call, then 100 timed-out &lt;code&gt;sleep 30&lt;/code&gt; calls, and it finished with 7 open descriptors and no &lt;code&gt;sleep&lt;/code&gt; processes left.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A timeout on &lt;code&gt;communicate()&lt;/code&gt; stops your wait, not the child. Kill the child yourself.&lt;/li&gt;
&lt;li&gt;After &lt;code&gt;proc.kill()&lt;/code&gt;, &lt;code&gt;await proc.wait()&lt;/code&gt;. The pipes and the pidfd are closed only after the exit is seen, and waiting makes that happen before you return.&lt;/li&gt;
&lt;li&gt;Each leaked call costs 3 descriptors on Linux. With a 1024 soft limit, the next call after 338 leaked timeouts fails with &lt;code&gt;Errno 24&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;gc.collect()&lt;/code&gt; will not save you, and neither will tests that exit, because &lt;code&gt;asyncio.run()&lt;/code&gt; hides the bug at shutdown.&lt;/li&gt;
&lt;li&gt;Watch &lt;code&gt;len(os.listdir("/proc/self/fd"))&lt;/code&gt; in long-running agents. It is a cheap health metric.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I did not test macOS or Windows, which use different child watchers, and I did not test Python versions before 3.14.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>asyncio</category>
    </item>
    <item>
      <title>CancelledError Retry Turned asyncio.timeout(1) Into 6 s</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Wed, 25 Nov 2026 05:04:38 +0000</pubDate>
      <link>https://dev.to/acemeridian/cancellederror-retry-turned-asynciotimeout1-into-6-s-e84</link>
      <guid>https://dev.to/acemeridian/cancellederror-retry-turned-asynciotimeout1-into-6-s-e84</guid>
      <description>&lt;p&gt;If your async tool wrapper retries on &lt;code&gt;except BaseException&lt;/code&gt; (or a bare &lt;code&gt;except:&lt;/code&gt;), it catches the &lt;code&gt;CancelledError&lt;/code&gt; that &lt;code&gt;asyncio.timeout(1)&lt;/code&gt; uses to stop it, retries, and the call comes back with a normal result after 6.01 s instead of a &lt;code&gt;TimeoutError&lt;/code&gt; at 1.00 s. Catch &lt;code&gt;asyncio.CancelledError&lt;/code&gt; first and re-raise it, then retry only on &lt;code&gt;Exception&lt;/code&gt;, and the same call fails at 1.00 s with nothing executed.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. Every number below comes from CPython 3.14.4 on Linux, and the main script ran twice with the same results apart from small timing noise.&lt;/p&gt;

&lt;p&gt;This is the retry wrapper I use for agent tool calls now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;call_tool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;attempts&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attempts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CancelledError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;raise&lt;/span&gt;  &lt;span class="c1"&gt;# a timeout or a stop button, never a tool failure&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;Exception&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"tool failed: {last!r}"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The rest of this post shows what the broad version did, and why the error never reaches the code that set the timeout.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why a timeout is just a cancellation
&lt;/h2&gt;

&lt;p&gt;In the last few posts I tested agent tools that keep running after the caller gave up: &lt;code&gt;subprocess.run&lt;/code&gt; orphans, &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; threads, &lt;code&gt;asyncio.gather&lt;/code&gt; siblings. This one is pure asyncio, and the bug is a single word in an &lt;code&gt;except&lt;/code&gt; clause.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;asyncio.timeout()&lt;/code&gt; and &lt;code&gt;asyncio.wait_for()&lt;/code&gt; do not have their own way to stop a coroutine. When the deadline passes they call &lt;code&gt;task.cancel()&lt;/code&gt;, which throws &lt;code&gt;CancelledError&lt;/code&gt; into whatever &lt;code&gt;await&lt;/code&gt; the task is blocked on. The timeout context manager then turns that &lt;code&gt;CancelledError&lt;/code&gt; into &lt;code&gt;TimeoutError&lt;/code&gt; on the way out of the block.&lt;/p&gt;

&lt;p&gt;Since Python 3.8, &lt;code&gt;CancelledError&lt;/code&gt; subclasses &lt;code&gt;BaseException&lt;/code&gt;, not &lt;code&gt;Exception&lt;/code&gt;. So &lt;code&gt;except Exception&lt;/code&gt; lets it through. &lt;code&gt;except BaseException&lt;/code&gt; and a bare &lt;code&gt;except:&lt;/code&gt; catch it. Agent code tends to use the broad forms on purpose, because "never let a tool crash the loop" sounds like a good rule.&lt;/p&gt;

&lt;h2&gt;
  
  
  The test
&lt;/h2&gt;

&lt;p&gt;Each wrapper calls a fake tool that sleeps 5 s and then records a side effect, such as a file write or an API call. The caller wraps the call in &lt;code&gt;asyncio.timeout(1)&lt;/code&gt; and expects a &lt;code&gt;TimeoutError&lt;/code&gt; at about 1 s. There are four wrappers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;wrap_bare&lt;/code&gt;: bare &lt;code&gt;except:&lt;/code&gt;, returns the error as a string to the model, which is what most frameworks do with tool exceptions.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;wrap_retry&lt;/code&gt;: &lt;code&gt;except BaseException&lt;/code&gt;, retries up to 3 times.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;wrap_exc&lt;/code&gt;: &lt;code&gt;except Exception&lt;/code&gt;, no retry.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;wrap_fixed&lt;/code&gt;: the &lt;code&gt;call_tool&lt;/code&gt; pattern from the top.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What came back
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;timeout(1) wrap_bare: returned 'tool error: CancelledError: ' after 1.00s, side effects=[]
timeout(1) wrap_retry: returned 'wrap_retry#2 done' after 6.01s, side effects=['wrap_retry#2']
timeout(1) wrap_exc: TimeoutError after 1.00s, side effects=[]
timeout(1) wrap_fixed: TimeoutError after 1.00s, side effects=[]
wait_for(1) wrap_retry: returned 'wrap_retry#2 done' after 6.01s, side effects=['wrap_retry#2']
wait_for(1) wrap_fixed: TimeoutError after 1.00s, side effects=[]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The retry wrapper is the bad one. Attempt 1 is cancelled at 1 s, and the wrapper treats that as a failed call and starts attempt 2. Cancellation is a one-shot event, so nothing stops attempt 2. It runs the full 5 s, performs the side effect, and returns success. The caller set a 1 s budget and got a normal return value at 6.01 s. &lt;code&gt;asyncio.timeout&lt;/code&gt; raised nothing because the block exited normally. &lt;code&gt;wait_for&lt;/code&gt; behaved the same way.&lt;/p&gt;

&lt;p&gt;The bare wrapper is quieter but still wrong. It returned at 1.00 s with no side effect, but as a string, &lt;code&gt;'tool error: CancelledError: '&lt;/code&gt;, which is what the model sees. &lt;code&gt;str(CancelledError())&lt;/code&gt; is empty, so the message has no detail. Given a tool error with no explanation, a model usually tries again.&lt;/p&gt;

&lt;h2&gt;
  
  
  The stop button is broken too
&lt;/h2&gt;

&lt;p&gt;Timeouts are not the only source of cancellation. When a user presses Stop in an agent UI, the framework usually calls &lt;code&gt;task.cancel()&lt;/code&gt; on the running turn. I cancelled each wrapper's task at 0.5 s:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cancel@0.5 wrap_bare: returned 'tool error: CancelledError: ' after 0.50s, cancelled()=False, cancelling()=1, side effects=[]
cancel@0.5 wrap_fixed: CancelledError after 0.50s, cancelled()=True, cancelling()=1, side effects=[]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the bare wrapper, &lt;code&gt;await task&lt;/code&gt; returned a value and &lt;code&gt;task.cancelled()&lt;/code&gt; was &lt;code&gt;False&lt;/code&gt;. Code that checks &lt;code&gt;cancelled()&lt;/code&gt; to decide whether to write "stopped by user" to the transcript would record a finished tool call instead. The leftover &lt;code&gt;cancelling()=1&lt;/code&gt; means the task is still flagged as being cancelled. Python's docs say code that suppresses a cancellation should call &lt;code&gt;uncancel()&lt;/code&gt;, and these wrappers never do.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where it did not break
&lt;/h2&gt;

&lt;p&gt;Two checks came out fine, and they set the scope of the problem:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;except Exception&lt;/code&gt; alone was correct in every case. Narrowing the clause is enough; the explicit &lt;code&gt;except CancelledError: raise&lt;/code&gt; just makes the intent obvious to the next reader.&lt;/li&gt;
&lt;li&gt;Inside a &lt;code&gt;TaskGroup&lt;/code&gt;, a sibling raising &lt;code&gt;ValueError&lt;/code&gt; at 0.5 s cancelled the bare-&lt;code&gt;except&lt;/code&gt; tool along with the others, and none of them got to their side effect. The bare wrapper swallowed the cancel and returned a string that nobody read, so the group still finished at 0.50 s.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I also checked what happens to later timeouts in the same task after one was swallowed inside an &lt;code&gt;async with asyncio.timeout(0.2)&lt;/code&gt; block. In 3.14.4, the next &lt;code&gt;asyncio.timeout(0.2)&lt;/code&gt; still raised &lt;code&gt;TimeoutError&lt;/code&gt; after 0.20 s, so the damage stays with the call that ate the cancel. I did not test Python 3.10 or older, where &lt;code&gt;asyncio.timeout&lt;/code&gt; does not exist.&lt;/p&gt;

&lt;h2&gt;
  
  
  How I check a codebase for this
&lt;/h2&gt;

&lt;p&gt;Search for the broad clauses near an &lt;code&gt;await&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;grep -rnE "except( BaseException)?( as [a-z_]+)?:" --include=*.py .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every hit inside a coroutine is a candidate. The review question is simple: if this &lt;code&gt;await&lt;/code&gt; is cancelled, does the &lt;code&gt;CancelledError&lt;/code&gt; leave the function? If the answer is "it gets logged and retried" or "it becomes a tool error string", that is the bug. Libraries that wrap tools for you, including retry decorators, are worth the same check: look at which exception types they retry on by default.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;asyncio.timeout()&lt;/code&gt; and &lt;code&gt;wait_for()&lt;/code&gt; stop work by raising &lt;code&gt;CancelledError&lt;/code&gt; inside it; any clause that catches it turns the timeout into a no-op.&lt;/li&gt;
&lt;li&gt;A retry loop on &lt;code&gt;BaseException&lt;/code&gt; turned a 1 s budget into 6.01 s and still performed the side effect it was meant to prevent.&lt;/li&gt;
&lt;li&gt;A bare &lt;code&gt;except:&lt;/code&gt; that returns an error string hides user cancellation: &lt;code&gt;cancelled()&lt;/code&gt; was &lt;code&gt;False&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Retry on &lt;code&gt;Exception&lt;/code&gt;, and put &lt;code&gt;except asyncio.CancelledError: raise&lt;/code&gt; first so the next reader does not "simplify" it back.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>asyncio</category>
    </item>
    <item>
      <title>subprocess.run text=True Ran My Agent's Command 3 Times</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Tue, 24 Nov 2026 05:04:10 +0000</pubDate>
      <link>https://dev.to/acemeridian/subprocessrun-texttrue-ran-my-agents-command-3-times-45jk</link>
      <guid>https://dev.to/acemeridian/subprocessrun-texttrue-ran-my-agents-command-3-times-45jk</guid>
      <description>&lt;p&gt;If an agent's shell tool calls &lt;code&gt;subprocess.run(..., text=True)&lt;/code&gt;, one non-UTF-8 byte in the output raises &lt;code&gt;UnicodeDecodeError&lt;/code&gt; after the command has already finished and changed things, so the agent sees an error and runs it again. Capture bytes and decode them yourself with &lt;code&gt;errors="backslashreplace"&lt;/code&gt;, and the tool always returns the exit code and output, whatever bytes the command printed.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. Every number below comes from CPython 3.14.4 on Linux with a UTF-8 locale, and the main script ran twice with identical output.&lt;/p&gt;

&lt;p&gt;This is the shell tool I use now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_shell&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;shell&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;capture_output&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;out&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;errors&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"backslashreplace"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;errors&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"backslashreplace"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"rc"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;returncode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"stdout"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;4000&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"stderr"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2000&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The rest of this post shows what &lt;code&gt;text=True&lt;/code&gt; did instead, and why the error arrives too late to be useful.&lt;/p&gt;

&lt;h2&gt;
  
  
  The bug in one command
&lt;/h2&gt;

&lt;p&gt;In the last few posts I looked at agent tools that outlive their timeout: &lt;code&gt;subprocess.run&lt;/code&gt; orphans, &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; threads, &lt;code&gt;asyncio.gather&lt;/code&gt; siblings, and a &lt;code&gt;NaN&lt;/code&gt; timeout. This one is smaller and more common. The command works, and the tool still reports failure.&lt;/p&gt;

&lt;p&gt;Linux filenames are bytes, not text. A file copied from an old Windows share or an unpacked zip can be called &lt;code&gt;caf\xe9.txt&lt;/code&gt;, which is Latin-1 for "café" and not valid UTF-8. Any command that prints that name, such as &lt;code&gt;ls&lt;/code&gt;, &lt;code&gt;find&lt;/code&gt;, &lt;code&gt;git status&lt;/code&gt; or &lt;code&gt;mv -v&lt;/code&gt;, writes one invalid byte to stdout.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;text=True&lt;/code&gt; tells &lt;code&gt;subprocess.run&lt;/code&gt; to decode stdout and stderr with the locale encoding, using strict error handling. Decoding happens inside &lt;code&gt;communicate()&lt;/code&gt;, after the child has exited. So the exception reports a decode problem but hides the fact that the command already ran.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the agent saw
&lt;/h2&gt;

&lt;p&gt;My test tool wraps &lt;code&gt;subprocess.run(cmd, shell=True, capture_output=True, text=True)&lt;/code&gt; and returns the error string to the model, which is what most agent frameworks do with a tool exception. The command appends one line to a log file (the side effect) and then prints a filename with byte &lt;code&gt;0xe9&lt;/code&gt;. A simple retry loop stands in for the model trying again:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ls text=True: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte
attempt 1: {"error": "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 17: invali | side effects so far: 1
attempt 2: {"error": "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 17: invali | side effects so far: 2
attempt 3: {"error": "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 17: invali | side effects so far: 3
bytes mode rc: 0 stdout: b'moved 1 file: caf\xe9.txt\n'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three attempts, three side effects, zero successful tool results. The same call without &lt;code&gt;text=True&lt;/code&gt; returned exit code 0 and the full output. If the side effect is &lt;code&gt;mv&lt;/code&gt;, &lt;code&gt;git commit&lt;/code&gt; or a &lt;code&gt;curl -X POST&lt;/code&gt;, the retry is the real damage. The error message also points the model in the wrong direction: it says nothing about the command having worked, so the obvious next step is to try again.&lt;/p&gt;

&lt;h2&gt;
  
  
  It does not have to be stdout
&lt;/h2&gt;

&lt;p&gt;The tool also failed when stdout was clean and only stderr had a bad byte:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bad stderr only: UnicodeDecodeError, stdout 'ok' lost: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;ok&lt;/code&gt; was printed and the exit code was 0, but the caller received neither. Progress bars, compiler warnings and &lt;code&gt;curl&lt;/code&gt; writing binary to stderr can all trigger this.&lt;/p&gt;

&lt;p&gt;The timeout path behaved differently. With &lt;code&gt;timeout=1&lt;/code&gt; and a child that printed &lt;code&gt;\xff&lt;/code&gt; before sleeping, I got a normal &lt;code&gt;TimeoutExpired&lt;/code&gt; after 1.00 s, and &lt;code&gt;e.stdout&lt;/code&gt; was raw bytes (&lt;code&gt;b'\xff'&lt;/code&gt;), not text. So code that handles a timeout should expect bytes on that attribute even when &lt;code&gt;text=True&lt;/code&gt; is set.&lt;/p&gt;

&lt;h2&gt;
  
  
  Streaming tools are worse
&lt;/h2&gt;

&lt;p&gt;Some tools stream output line by line with &lt;code&gt;Popen(..., stdout=PIPE, text=True)&lt;/code&gt;. In that case the error ends the loop early and the child keeps running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;stream: UnicodeDecodeError after 0.00s, lines read=[], child poll()=None
0.5 s later child poll(): None
child exited rc=0 at 3.01s
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The bad byte was on line 3, but the reader had buffered it together with lines 1 and 2, so even those were lost. The child kept running for another 3 seconds with nobody reading its pipe. I did not test it, but a child that writes more than the pipe buffer holds would then block on write and never finish.&lt;/p&gt;

&lt;h2&gt;
  
  
  Locale settings do not save you
&lt;/h2&gt;

&lt;p&gt;I expected &lt;code&gt;LC_ALL=C&lt;/code&gt; to change things. It did not, because Python 3.7 and later switch the C locale to UTF-8 mode (&lt;code&gt;utf8_mode: 1&lt;/code&gt; in my run), and every line after the version line was identical. A truly Latin-1 locale would decode every byte without error, but then valid UTF-8 output turns into mojibake. The locale only changes which output breaks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Picking an error handler
&lt;/h2&gt;

&lt;p&gt;Once you capture bytes, choose how to decode them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;errors=backslashreplace: 0 'moved 1 file: caf\\xe9.txt\n'
errors=replace: 0 'moved 1 file: caf�.txt\n'
surrogateescape: 'caf\udce9.txt' | back to bytes: b'caf\xe9.txt'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For text sent back to a model I use &lt;code&gt;backslashreplace&lt;/code&gt;. It stays readable and shows exactly which byte was there. &lt;code&gt;replace&lt;/code&gt; loses that byte. &lt;code&gt;surrogateescape&lt;/code&gt; is the right choice when the string goes back into the filesystem, since &lt;code&gt;os.fsencode&lt;/code&gt; restores the original name, but lone surrogates can break JSON encoders and model APIs later. Running the tool above on both failing commands returned &lt;code&gt;{"rc": 0, "stdout": "moved 1 file: caf\\xe9.txt\n", ...}&lt;/code&gt; and &lt;code&gt;{"rc": 0, "stdout": "ok\n", "stderr": "\\xff"}&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;text=True&lt;/code&gt; decodes strictly after the command has finished, so a &lt;code&gt;UnicodeDecodeError&lt;/code&gt; means the side effects already happened.&lt;/li&gt;
&lt;li&gt;An agent that receives that error will usually retry. In my test, three retries ran the command three times.&lt;/li&gt;
&lt;li&gt;One bad byte on stderr also discards a clean stdout and a 0 exit code.&lt;/li&gt;
&lt;li&gt;With &lt;code&gt;Popen(text=True)&lt;/code&gt; streaming, the reader stops and the child keeps running.&lt;/li&gt;
&lt;li&gt;Capture bytes and decode with &lt;code&gt;errors="backslashreplace"&lt;/code&gt; for model-facing output, or &lt;code&gt;surrogateescape&lt;/code&gt; when the text goes back into the filesystem.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>subprocess</category>
    </item>
    <item>
      <title>json.loads Accepted timeout=NaN in My Agent's Tool Call</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Mon, 23 Nov 2026 05:06:49 +0000</pubDate>
      <link>https://dev.to/acemeridian/jsonloads-accepted-timeoutnan-in-my-agents-tool-call-34o0</link>
      <guid>https://dev.to/acemeridian/jsonloads-accepted-timeoutnan-in-my-agents-tool-call-34o0</guid>
      <description>&lt;p&gt;Python's &lt;code&gt;json.loads&lt;/code&gt; accepts &lt;code&gt;NaN&lt;/code&gt;, &lt;code&gt;Infinity&lt;/code&gt; and &lt;code&gt;1e999&lt;/code&gt; even though the JSON spec forbids them, so a tool call like &lt;code&gt;{"cmd": ["sleep", "3"], "timeout": NaN}&lt;/code&gt; passes straight through to &lt;code&gt;subprocess.run(timeout=nan)&lt;/code&gt;, which never times out. Validate tool arguments with a Pydantic model that sets &lt;code&gt;allow_inf_nan=False&lt;/code&gt; and an upper bound, and the bad call is rejected in 0.00 s before anything runs.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. Every number below comes from CPython 3.14.9 and Pydantic 2.14.1 (pydantic-core 2.50.1) on Linux, and each script ran twice with the same results.&lt;/p&gt;

&lt;p&gt;This is the guard I now put in front of every agent tool that takes a number:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pydantic&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;BaseModel&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ConfigDict&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Field&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ValidationError&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ShellArgs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BaseModel&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;model_config&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ConfigDict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;allow_inf_nan&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;extra&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"forbid"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Field&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;gt&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;le&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_shell&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;raw_arguments&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;args&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ShellArgs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;model_validate_json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;raw_arguments&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;ValidationError&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"error"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;errors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;include_url&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"msg"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;capture_output&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"rc"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;returncode&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The rest of this post is why both settings are needed, and what each non-finite value does once it reaches real code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where the number comes from
&lt;/h2&gt;

&lt;p&gt;Tool arguments arrive as a JSON string written by the model. In the last three posts I looked at agent tools that outlive their timeout: &lt;code&gt;subprocess.run&lt;/code&gt; orphans, &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; threads, &lt;code&gt;asyncio.gather&lt;/code&gt; siblings. All of those assumed the timeout value was sane. This time I tested what happens when it is not.&lt;/p&gt;

&lt;p&gt;I have not seen a hosted model emit &lt;code&gt;NaN&lt;/code&gt; on its own. But the arguments come from text the model writes, and that text is shaped by user input, retrieved pages and other tool output. A single prompt-injected &lt;code&gt;"timeout": 1e999&lt;/code&gt; is enough. The parser is the first line of defense, and it lets these values through.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the parser and the tools did
&lt;/h2&gt;

&lt;p&gt;One run of &lt;code&gt;exp2.py&lt;/code&gt;. The child process sleeps 3 s, so a working 1 s timeout should fire at 1.00 s:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;subprocess.run(timeout=inf): returned after 3.03s
subprocess.run(timeout=nan): returned after 3.03s
subprocess.run(timeout=1.0): TimeoutExpired after 1.00s: Command '['sleep', '3']' timed out after 1.0 seconds
asyncio.wait_for(timeout=inf): returned after 3.00s
asyncio.wait_for(timeout=nan): ValueError after 0.00s: cannot convert float NaN to integer
asyncio.wait_for(timeout=1.0): TimeoutError after 1.00s: 
time.sleep(inf): OverflowError after 0.00s: timestamp out of range for C PyTime_t
time.sleep(nan): ValueError after 0.00s: Invalid value NaN (not a number)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;json.loads&lt;/code&gt; returned &lt;code&gt;nan&lt;/code&gt; for &lt;code&gt;NaN&lt;/code&gt; and &lt;code&gt;inf&lt;/code&gt; for both &lt;code&gt;Infinity&lt;/code&gt; and &lt;code&gt;1e999&lt;/code&gt;, with no warning. A plain Pydantic model with &lt;code&gt;timeout: float&lt;/code&gt; accepted all three as well.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;subprocess.run&lt;/code&gt; is the dangerous one. With &lt;code&gt;timeout=nan&lt;/code&gt; it waited for the child to finish, the same as having no timeout at all. With a 3 s child that just looks slow. With a command that hangs, the agent hangs too. The asyncio and &lt;code&gt;time.sleep&lt;/code&gt; paths fail loudly, which is better, but you get a &lt;code&gt;ValueError&lt;/code&gt; or &lt;code&gt;OverflowError&lt;/code&gt; deep inside the tool instead of a clear message back to the model.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why a bound alone is not enough
&lt;/h2&gt;

&lt;p&gt;The obvious fix is &lt;code&gt;Field(gt=0)&lt;/code&gt;, and it is only half a fix. NaN compares false to everything, so any bound rejects it. Infinity only fails the side it is on. From &lt;code&gt;bounds.py&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;A {"budget": Infinity}: accepted inf
B {"budget": -Infinity}: accepted -inf
nan &amp;gt;= 0: False | nan &amp;lt;= 100: False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Model &lt;code&gt;A&lt;/code&gt; had only &lt;code&gt;ge=0&lt;/code&gt;, and model &lt;code&gt;B&lt;/code&gt; had only &lt;code&gt;le=100&lt;/code&gt;. A lower bound alone lets &lt;code&gt;Infinity&lt;/code&gt; through, and that is exactly the value that turns a timeout off. You need both an upper bound and &lt;code&gt;allow_inf_nan=False&lt;/code&gt;. The bound states what is reasonable. The flag says what the field means: a finite number. With both set, &lt;code&gt;fix.py&lt;/code&gt; printed &lt;code&gt;Input should be a finite number&lt;/code&gt; for NaN and for &lt;code&gt;1e999&lt;/code&gt;, and a normal call with &lt;code&gt;timeout: 5&lt;/code&gt; still ran.&lt;/p&gt;

&lt;h2&gt;
  
  
  If you are not using Pydantic
&lt;/h2&gt;

&lt;p&gt;The standard library can do it, but there are two hooks and you need both. &lt;code&gt;parse_constant&lt;/code&gt; catches the literals &lt;code&gt;NaN&lt;/code&gt;, &lt;code&gt;Infinity&lt;/code&gt; and &lt;code&gt;-Infinity&lt;/code&gt;. It does not catch &lt;code&gt;1e999&lt;/code&gt;, because that is a valid-looking number that only overflows to &lt;code&gt;inf&lt;/code&gt; during float conversion. For that you need &lt;code&gt;parse_float&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{"timeout": 1e999} parse_constant only: {'timeout': inf}
{"timeout": 1e999} parse_constant + parse_float: ValueError: non-finite JSON number 1e999
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is easy to write the first hook, test it with &lt;code&gt;NaN&lt;/code&gt;, and stop there.&lt;/p&gt;

&lt;h2&gt;
  
  
  The return path has the same hole
&lt;/h2&gt;

&lt;p&gt;It also happens in the other direction. If a tool result contains &lt;code&gt;float("nan")&lt;/code&gt;, for example an average over zero rows, &lt;code&gt;json.dumps&lt;/code&gt; writes &lt;code&gt;{"balance": NaN, "ok": true}&lt;/code&gt;. That is not valid JSON. Whether the model API accepts it depends on the client: &lt;code&gt;httpx&lt;/code&gt; refused to build the request (&lt;code&gt;Out of range float values are not JSON compliant&lt;/code&gt;), so the tool call fails at send time and not at the line that produced the NaN. Using &lt;code&gt;json.dumps(..., allow_nan=False)&lt;/code&gt; in your tool-result serializer moves the error to where the NaN came from.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;json.loads&lt;/code&gt; accepts &lt;code&gt;NaN&lt;/code&gt;, &lt;code&gt;Infinity&lt;/code&gt; and &lt;code&gt;1e999&lt;/code&gt; even though the JSON spec does not allow them.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;subprocess.run(timeout=nan)&lt;/code&gt; and &lt;code&gt;timeout=inf&lt;/code&gt; behave like no timeout at all.&lt;/li&gt;
&lt;li&gt;A lower bound alone still lets &lt;code&gt;Infinity&lt;/code&gt; through. Use &lt;code&gt;allow_inf_nan=False&lt;/code&gt; plus an upper bound.&lt;/li&gt;
&lt;li&gt;In stdlib-only code you need both &lt;code&gt;parse_constant&lt;/code&gt; and &lt;code&gt;parse_float&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Serialize tool results with &lt;code&gt;allow_nan=False&lt;/code&gt; so a NaN fails where it was created.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>pydantic</category>
    </item>
    <item>
      <title>asyncio.gather Raised at 0.5 s, Then 3 Tool Calls Still Ran</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Sun, 22 Nov 2026 05:04:44 +0000</pubDate>
      <link>https://dev.to/acemeridian/asynciogather-raised-at-05-s-then-3-tool-calls-still-ran-2kho</link>
      <guid>https://dev.to/acemeridian/asynciogather-raised-at-05-s-then-3-tool-calls-still-ran-2kho</guid>
      <description>&lt;p&gt;When one awaitable in &lt;code&gt;asyncio.gather()&lt;/code&gt; raises, &lt;code&gt;gather&lt;/code&gt; hands you the exception right away but does not cancel the others, so they keep running and finish their side effects after your &lt;code&gt;except&lt;/code&gt; block has already run; if one failed tool call should stop the batch, use &lt;code&gt;asyncio.TaskGroup&lt;/code&gt; and catch &lt;code&gt;ExceptionGroup&lt;/code&gt;. In my test, a search tool failed at 0.5 s, the caller logged the error, and the email, database write and fetch calls all still completed at 3.0 s.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. Every number comes from CPython 3.14.4 on Linux 7.0, and each script ran twice with identical output.&lt;/p&gt;

&lt;p&gt;Here is the version I now use when an agent fans out tool calls in parallel:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_tools&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;coros&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;TaskGroup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;tg&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;tasks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;tg&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_task&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;coros&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;ExceptionGroup&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;eg&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;eg&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exceptions&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# siblings already cancelled&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;result&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;tasks&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The rest of this post is what &lt;code&gt;gather&lt;/code&gt; actually does on failure, and two traps on the way to the fix.&lt;/p&gt;

&lt;h2&gt;
  
  
  The setup
&lt;/h2&gt;

&lt;p&gt;This is the third post in a row about agent tool calls that outlive the error. &lt;code&gt;subprocess.run(timeout=1)&lt;/code&gt; left orphan processes. &lt;code&gt;ThreadPoolExecutor.result(timeout=1)&lt;/code&gt; left threads running. This time there is no timeout at all, just a plain exception inside &lt;code&gt;asyncio.gather&lt;/code&gt;, which is the most common way agent code runs tools in parallel.&lt;/p&gt;

&lt;p&gt;The test has four fake tools. &lt;code&gt;search&lt;/code&gt; sleeps 0.5 s and raises &lt;code&gt;ValueError&lt;/code&gt;. &lt;code&gt;email&lt;/code&gt;, &lt;code&gt;db_write&lt;/code&gt; and &lt;code&gt;fetch&lt;/code&gt; each sleep 3 s and then append their name to a list, which stands in for a side effect. I ran them four ways: plain &lt;code&gt;gather&lt;/code&gt;, &lt;code&gt;gather(return_exceptions=True)&lt;/code&gt;, &lt;code&gt;TaskGroup&lt;/code&gt; with &lt;code&gt;except*&lt;/code&gt;, and &lt;code&gt;TaskGroup&lt;/code&gt; with a plain &lt;code&gt;except ValueError&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the output says
&lt;/h2&gt;

&lt;p&gt;First run, unedited:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;gather: caught ValueError at 0.5s, tasks still pending=3
gather: side effects after the error: ['email', 'db_write', 'fetch'] at [3.0, 3.0, 3.0]
return_exceptions=True: returned at 3.0s with ['ValueError', 'email', 'db_write', 'fetch']
TaskGroup: ExceptionGroup at 0.5s, completed=0
TaskGroup: side effects after 3 more s: 0
plain except ValueError: missed, got ExceptionGroup instead
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;gather&lt;/code&gt; caller got the exception at 0.5 s, on time. Three tasks were still pending, and nothing cancelled them. Two and a half seconds after my error handler ran, all three side effects happened. If that handler had told the user "the batch failed, nothing was sent", it would have been wrong three times over.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why gather behaves this way
&lt;/h2&gt;

&lt;p&gt;The docs say it in one sentence: with &lt;code&gt;return_exceptions=False&lt;/code&gt;, the first exception is propagated to the awaiting task, and "other awaitables in the aws sequence won't be cancelled and will continue to run." &lt;code&gt;gather&lt;/code&gt; was designed before structured concurrency was added to asyncio. It only reports errors and does not own the tasks it started.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;return_exceptions=True&lt;/code&gt; is not the fix either. It just makes you wait: the call returned at 3.0 s with the &lt;code&gt;ValueError&lt;/code&gt; sitting in the result list next to three successes. That is the right tool when you want every result, and the wrong one when a failure should stop the work.&lt;/p&gt;

&lt;h2&gt;
  
  
  The CLI case hides it
&lt;/h2&gt;

&lt;p&gt;I also ran plain &lt;code&gt;gather&lt;/code&gt; in a short script that exits right after catching the error. There, the side-effect list stayed empty:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cli gather: side effects after asyncio.run returned: []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;asyncio.run()&lt;/code&gt; cancels leftover tasks when it shuts down, so in a one-shot script the bug disappears. Run the same code inside a server or a long-lived agent loop, where the event loop keeps going, and the siblings run to completion. So a test that works in a script tells you nothing about the service.&lt;/p&gt;

&lt;h2&gt;
  
  
  TaskGroup, and the two traps
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;asyncio.TaskGroup&lt;/code&gt; (Python 3.11+) cancels the remaining tasks as soon as one fails, then raises an &lt;code&gt;ExceptionGroup&lt;/code&gt;. In the run above it raised at 0.5 s with zero completed calls, and three seconds later the count was still zero.&lt;/p&gt;

&lt;p&gt;Trap one: &lt;code&gt;except ValueError&lt;/code&gt; no longer matches. The last line of the output shows the plain &lt;code&gt;except&lt;/code&gt; missing and an &lt;code&gt;ExceptionGroup&lt;/code&gt; escaping instead. Any existing error handling you move from &lt;code&gt;gather&lt;/code&gt; to &lt;code&gt;TaskGroup&lt;/code&gt; has to change to &lt;code&gt;except*&lt;/code&gt; or &lt;code&gt;except ExceptionGroup&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Trap two: you cannot &lt;code&gt;return&lt;/code&gt; from an &lt;code&gt;except*&lt;/code&gt; block. My first version of the helper did, and Python refused to compile it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SyntaxError: 'break', 'continue' and 'return' cannot appear in an except* block
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is why the helper at the top catches &lt;code&gt;ExceptionGroup&lt;/code&gt; and returns from there. On the happy path it returned &lt;code&gt;['search', 'email']&lt;/code&gt; with no errors. On the failure path it returned the error at 0.50 s, and no side effects ever ran.&lt;/p&gt;

&lt;h2&gt;
  
  
  What cancellation does not cover
&lt;/h2&gt;

&lt;p&gt;Cancellation lands at the next &lt;code&gt;await&lt;/code&gt;. A tool that is in the middle of a blocking call, or that has already sent its HTTP request, will not take it back. TaskGroup stops the work that has not happened yet. For writes that must not happen twice or half-way, you still need idempotency keys or a single commit step at the end.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;asyncio.gather&lt;/code&gt; re-raises the first error and leaves the other tasks running.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;return_exceptions=True&lt;/code&gt; collects errors, but still waits for every task.&lt;/li&gt;
&lt;li&gt;Short scripts hide the bug because &lt;code&gt;asyncio.run&lt;/code&gt; cancels leftovers at exit.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;TaskGroup&lt;/code&gt; cancels siblings, but raises &lt;code&gt;ExceptionGroup&lt;/code&gt;, so &lt;code&gt;except ValueError&lt;/code&gt; stops matching.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;return&lt;/code&gt; inside &lt;code&gt;except*&lt;/code&gt; is a SyntaxError. Catch &lt;code&gt;ExceptionGroup&lt;/code&gt; when the handler needs to return.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>asyncio</category>
    </item>
    <item>
      <title>ThreadPoolExecutor result(timeout=1) Left 4 Calls Running</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Sat, 21 Nov 2026 05:02:54 +0000</pubDate>
      <link>https://dev.to/acemeridian/threadpoolexecutor-resulttimeout1-left-4-calls-running-4d8d</link>
      <guid>https://dev.to/acemeridian/threadpoolexecutor-resulttimeout1-left-4-calls-running-4d8d</guid>
      <description>&lt;p&gt;&lt;code&gt;future.result(timeout=1)&lt;/code&gt; raises &lt;code&gt;TimeoutError&lt;/code&gt; after one second, but the thread keeps running the call to the end, and &lt;code&gt;future.cancel()&lt;/code&gt; returns &lt;code&gt;False&lt;/code&gt; because the work already started; if a tool call must really stop, run it in a child process and terminate that process on timeout. In my test, four agent tool calls that each "timed out" after 1 s all ran their full 5 s, and the next 0.1 s call on the same pool waited 1.10 s for a free thread.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. All numbers come from CPython 3.14.4 on Linux 7.0, and both scripts ran twice with identical output.&lt;/p&gt;

&lt;p&gt;Here is the version that actually stops the work. It is the code I now use for agent tools that wrap slow, uncooperative functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;multiprocessing&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;mp&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;tool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;secs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;secs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"ok"&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_tool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;ctx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mp&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_context&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"spawn"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Pool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;pool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pool&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;apply_async&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# leaving the with-block terminates the worker&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The rest of this post is why the thread version cannot do this, and what it costs you when you try.&lt;/p&gt;

&lt;h2&gt;
  
  
  The setup
&lt;/h2&gt;

&lt;p&gt;Yesterday I wrote about &lt;code&gt;subprocess.run(timeout=1)&lt;/code&gt; leaving orphans behind. The same question applies one layer up. A lot of agent frameworks run tool functions in a &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; so the event loop stays free, then put a timeout on the future. I wanted to know what that timeout actually does.&lt;/p&gt;

&lt;p&gt;The test is small: a tool that sleeps 5 seconds and records when it finishes, a pool with four workers, and four calls, each awaited with &lt;code&gt;result(timeout=1)&lt;/code&gt;. Then a fresh 0.1 s call on the same pool, then the asyncio equivalent, &lt;code&gt;asyncio.wait_for(asyncio.to_thread(...), timeout=1)&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the output says
&lt;/h2&gt;

&lt;p&gt;From the first run, unedited:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result(timeout=1): 4 TimeoutError by 4.00s, cancel()=False, running=4, threads=5
fresh 0.1s call on same pool returned after 1.10s
wait_for(to_thread, timeout=1): TimeoutError at 1.00s
asyncio.run returned at 8.10s
completed in background: [('call0', 5.0), ('call1', 5.0), ('call2', 5.0), ('call3', 5.0), ('fresh', 5.1), ('async', 8.1)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every timeout fired on schedule. None of them stopped anything. All four calls finished at 5.0 s and wrote their results into a list nobody was reading. If those calls had been sending emails or writing rows, all four side effects would have happened after the caller had already logged "tool timed out".&lt;/p&gt;

&lt;h2&gt;
  
  
  Why cancel() returns False
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;concurrent.futures&lt;/code&gt; docs are honest about this: "If the call is currently being executed or finished running and cannot be cancelled then the method will return False." In other words, it removes queued work, nothing else. Python has no supported way to kill a thread. The timeout on &lt;code&gt;result()&lt;/code&gt; is a timeout on your wait, not on the work.&lt;/p&gt;

&lt;p&gt;That distinction is easy to miss because the exception type looks like a verdict. &lt;code&gt;TimeoutError&lt;/code&gt; reads as "the call was stopped". It means "I stopped waiting".&lt;/p&gt;

&lt;h2&gt;
  
  
  The hidden cost: a saturated pool
&lt;/h2&gt;

&lt;p&gt;The second line is the one that would hurt in production. After four timeouts the pool looked idle from the caller's side, but all four workers were still busy. A 0.1 s call submitted at that point sat in the queue until a worker came free at the 5 s mark and returned after 1.10 s.&lt;/p&gt;

&lt;p&gt;Scale that up. An agent that retries a slow tool a few times can fill the pool with zombie calls, and then every fast tool queues behind them. Nothing errors. Latency just climbs, and the traces show "timeout" on the slow calls and "slow" on the fast ones, which points you at the wrong thing.&lt;/p&gt;

&lt;h2&gt;
  
  
  asyncio.wait_for has the same hole, plus one more
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;asyncio.wait_for(asyncio.to_thread(tool, 3), timeout=1)&lt;/code&gt; raised at 1.00 s, as advertised. The thread kept going. Then &lt;code&gt;asyncio.run()&lt;/code&gt; itself did not return until 8.10 s, because on shutdown it waits for the default executor's threads to finish. So the "1 second" timeout turned into a 2 s stall at exit, well after the caller moved on. In a CLI agent that is the "why does it hang after printing the answer" bug.&lt;/p&gt;

&lt;h2&gt;
  
  
  Processes can actually be stopped
&lt;/h2&gt;

&lt;p&gt;The fix at the top swaps the thread for a one-worker process pool. On timeout, leaving the &lt;code&gt;with&lt;/code&gt; block calls &lt;code&gt;terminate()&lt;/code&gt; on the worker, so the work really ends. Its output, twice:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TimeoutError at 1.04s, children left: 0
ok 0.16s
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The price is about 0.15 s of &lt;code&gt;spawn&lt;/code&gt; start-up per call and the usual pickling rules for arguments and results. For tools that call slow external code, that is cheap. For tools that are just HTTP requests, a better fix is a real timeout inside the call, such as an httpx timeout or &lt;code&gt;asyncio.timeout&lt;/code&gt; around an async client, because cooperative cancellation never leaves a half-done write behind a killed process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;future.result(timeout=N)&lt;/code&gt; and &lt;code&gt;asyncio.wait_for(to_thread(...))&lt;/code&gt; time out your wait, not the work. The function runs to completion.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;future.cancel()&lt;/code&gt; returns &lt;code&gt;False&lt;/code&gt; once the call has started. Do not treat it as a kill switch.&lt;/li&gt;
&lt;li&gt;Timed-out calls still hold pool workers, so fast calls queue behind them. Watch queue time, not only call time.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;asyncio.run()&lt;/code&gt; waits for executor threads at exit, so a timed-out thread can stall shutdown.&lt;/li&gt;
&lt;li&gt;If work must stop, put it in a process you can terminate, or give the call its own internal timeout.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>concurrency</category>
    </item>
    <item>
      <title>subprocess.run timeout=1 Left 10 Orphans Running</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Fri, 20 Nov 2026 05:10:51 +0000</pubDate>
      <link>https://dev.to/acemeridian/subprocessrun-timeout1-left-10-orphans-running-fe3</link>
      <guid>https://dev.to/acemeridian/subprocessrun-timeout1-left-10-orphans-running-fe3</guid>
      <description>&lt;p&gt;&lt;code&gt;subprocess.run(cmd, shell=True, timeout=1)&lt;/code&gt; raises &lt;code&gt;TimeoutExpired&lt;/code&gt; but kills only &lt;code&gt;/bin/sh&lt;/code&gt;, so whatever the shell started keeps running; start the command with &lt;code&gt;start_new_session=True&lt;/code&gt; and call &lt;code&gt;os.killpg(p.pid, signal.SIGKILL)&lt;/code&gt; on timeout instead. In my test, ten agent tool calls that each timed out after 1 s left 10 live processes behind, and a background server made a command that printed &lt;code&gt;started&lt;/code&gt; instantly block for 5.01 s and then survive the timeout.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. All numbers come from Python 3.14.4 on Linux 7.0 with dash as &lt;code&gt;/bin/sh&lt;/code&gt; and systemd 259; every case ran twice with the same counts.&lt;/p&gt;

&lt;p&gt;If you give an LLM agent a shell tool, the timeout is your only brake on what the model runs. &lt;code&gt;subprocess.run&lt;/code&gt; makes that brake look solid: the call returns on time and raises the right exception. The process tree underneath is a different story, and nothing in the return value tells you.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the timeout actually kills
&lt;/h2&gt;

&lt;p&gt;CPython's &lt;code&gt;run()&lt;/code&gt; is short. On timeout it does this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;TimeoutExpired&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;exc&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;kill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
                &lt;span class="n"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;wait&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;raise&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;process&lt;/code&gt; is the &lt;code&gt;Popen&lt;/code&gt; for &lt;code&gt;/bin/sh -c "&amp;lt;cmd&amp;gt;"&lt;/code&gt;. &lt;code&gt;kill()&lt;/code&gt; sends SIGKILL to that one PID. On this box dash did not exec the last command, so even a single &lt;code&gt;python3 -c ...&lt;/code&gt; ran as a child of the shell. When the shell dies, the child is reparented, here to PID 1500, which is &lt;code&gt;systemd --user&lt;/code&gt; acting as subreaper, and it keeps going.&lt;/p&gt;

&lt;p&gt;I checked with &lt;code&gt;ps&lt;/code&gt; right after the exception: the parent shell was gone, and the worker sat there with PPID 1500 and its 30-second sleep untouched.&lt;/p&gt;

&lt;h2&gt;
  
  
  Five cases, one table
&lt;/h2&gt;

&lt;p&gt;Each case starts a tagged &lt;code&gt;python3 -c 'time.sleep(N)'&lt;/code&gt; through &lt;code&gt;shell=True&lt;/code&gt; and counts survivors with &lt;code&gt;pgrep -f &amp;lt;tag&amp;gt;&lt;/code&gt; 0.3 s after &lt;code&gt;run()&lt;/code&gt; returns. From the first run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bg server, capture, timeout=5      after= 5.01s error=TimeoutExpired rc=None survivors=1
bg 8s job, capture, no timeout     after= 8.03s error=none           rc=0 survivors=0
bg server, &amp;gt;/dev/null, timeout=5   after= 0.00s error=none           rc=0 survivors=1
fg 30s chain, capture, timeout=2   after= 2.00s error=TimeoutExpired rc=None survivors=1
10 agent calls, timeout=1          after=10.33s timeouts=10 survivors=10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The foreground line is the plain leak: &lt;code&gt;sleep 30; echo done&lt;/code&gt; timed out at 2.00 s and the sleep lived on. A pipeline (&lt;code&gt;cmd | cat&lt;/code&gt;) and a single bare command behaved the same, one survivor each. The agent line is the same leak in a loop. A model that retries a slow command ten times does not get ten failures; it gets ten copies still running.&lt;/p&gt;

&lt;h2&gt;
  
  
  The background server that hung the tool
&lt;/h2&gt;

&lt;p&gt;The first two lines surprised me more. The command was &lt;code&gt;server &amp;amp; echo started&lt;/code&gt;. The shell printed &lt;code&gt;started&lt;/code&gt; and exited at once, yet &lt;code&gt;run()&lt;/code&gt; blocked for 5.01 s and raised &lt;code&gt;TimeoutExpired&lt;/code&gt;, and the server survived.&lt;/p&gt;

&lt;p&gt;The reason is the pipe. With &lt;code&gt;capture_output=True&lt;/code&gt;, the background child inherits the write end of stdout. &lt;code&gt;communicate()&lt;/code&gt; reads until EOF, and EOF only comes when every process holding that pipe has closed it. The shell is done; the server is not. Without a timeout, an 8-second background job made the call take 8.03 s for a command whose shell finished instantly.&lt;/p&gt;

&lt;p&gt;Redirecting the server's output (&lt;code&gt;&amp;gt;/dev/null 2&amp;gt;&amp;amp;1 &amp;amp;&lt;/code&gt;) returned in 0.00 s with exit code 0. That is the honest version of "start a server": the tool returns, and the server keeps running because you asked it to. The failure is the version in between, where the agent thinks the call failed and the server is still bound to its port.&lt;/p&gt;

&lt;h2&gt;
  
  
  The fix I kept
&lt;/h2&gt;

&lt;p&gt;Put the shell in its own session, so its PID is also a process group ID, and kill the group:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;signal&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_tool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;tuple&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Popen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cmd&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;shell&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;PIPE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;STDOUT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                         &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start_new_session&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;communicate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;returncode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;TimeoutExpired&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;killpg&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;signal&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SIGKILL&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# the shell and everything still in its group&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;communicate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;TimeoutExpired&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# a child escaped with setsid and holds the pipe&lt;/span&gt;
            &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;close&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;wait&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;out&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"\n[killed after {timeout}s]"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I ran this function as written against the same commands. The foreground chain and the pipeline returned at 2.00–2.01 s, the background server at 5.01 s, and all three left 0 survivors. A fast &lt;code&gt;echo&lt;/code&gt; returned rc 0 with its output. The second run matched.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where killpg stops working
&lt;/h2&gt;

&lt;p&gt;A process group is voluntary. A child that calls &lt;code&gt;setsid&lt;/code&gt; leaves it. With &lt;code&gt;setsid python3 -c ...; echo done&lt;/code&gt;, my first version of the fix (without the bounded drain) killed the group and then waited on &lt;code&gt;communicate()&lt;/code&gt; for the full 30 seconds, because the escaped child still held the pipe. The bounded drain above returns at 3.00 s, but the escaped process is still alive afterwards: 1 survivor.&lt;/p&gt;

&lt;p&gt;The only thing I found that caught it was a cgroup. Wrapping the command in &lt;code&gt;systemd-run --user --scope&lt;/code&gt; and calling &lt;code&gt;systemctl --user kill --signal=SIGKILL &amp;lt;unit&amp;gt;.scope&lt;/code&gt; on timeout ended the call about 2.0 s in, with 0 survivors, &lt;code&gt;setsid&lt;/code&gt; included. A container per tool call gets you the same thing. For an agent shell, I treat &lt;code&gt;killpg&lt;/code&gt; as the default and a scope or container as the boundary when the model can run arbitrary commands.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;subprocess.run(..., shell=True, timeout=N)&lt;/code&gt; kills the shell, not the command. Check survivors with &lt;code&gt;pgrep&lt;/code&gt;, not the exception.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;capture_output=True&lt;/code&gt; plus a background &lt;code&gt;&amp;amp;&lt;/code&gt; blocks until the background process exits or the timeout fires.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;start_new_session=True&lt;/code&gt; and &lt;code&gt;os.killpg&lt;/code&gt; on timeout, and bound the second &lt;code&gt;communicate()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;setsid&lt;/code&gt; escapes a process group; a cgroup (&lt;code&gt;systemd-run --scope&lt;/code&gt;) or container does not leak.&lt;/li&gt;
&lt;li&gt;For agent tools, a timeout that returns on time is not proof that the work stopped.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>subprocess</category>
    </item>
    <item>
      <title>Redis retry_on_timeout=False Still Counted My INCR Twice</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Tue, 17 Nov 2026 05:31:07 +0000</pubDate>
      <link>https://dev.to/acemeridian/redis-retryontimeoutfalse-still-counted-my-incr-twice-k31</link>
      <guid>https://dev.to/acemeridian/redis-retryontimeoutfalse-still-counted-my-incr-twice-k31</guid>
      <description>&lt;p&gt;In redis-py 8.1.0, &lt;code&gt;retry_on_timeout=False&lt;/code&gt; does not turn retries off: every client retries up to 10 times on &lt;code&gt;TimeoutError&lt;/code&gt; by default, so one &lt;code&gt;INCR&lt;/code&gt; that hit a 0.5 s socket timeout returned 2 and left the counter at 2. For writes that must not run twice, give the client &lt;code&gt;retry=Retry(NoBackoff(), 0)&lt;/code&gt; or make the write idempotent with a request ID, because even without a retry a timeout only means "maybe applied".&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. The numbers below come from a local Redis 8.10.2 server and redis-py 8.1.0 on Python 3.14.4; the stall tests ran twice, and no shared instance was involved.&lt;/p&gt;

&lt;h2&gt;
  
  
  The flag that stopped doing anything
&lt;/h2&gt;

&lt;p&gt;Plenty of Redis clients were written as &lt;code&gt;redis.Redis(host=..., socket_timeout=0.5, retry_on_timeout=False)&lt;/code&gt; by people who wanted a fast failure instead of a retry. In 8.1.0 the constructor's default &lt;code&gt;retry&lt;/code&gt; is &lt;code&gt;Retry(ExponentialWithJitterBackoff(base=0.01, cap=1), retries=10)&lt;/code&gt;, and &lt;code&gt;Retry&lt;/code&gt; retries on &lt;code&gt;ConnectionError&lt;/code&gt;, &lt;code&gt;TimeoutError&lt;/code&gt; and &lt;code&gt;socket.timeout&lt;/code&gt; unless you pass your own list.&lt;/p&gt;

&lt;p&gt;Passing &lt;code&gt;retry_on_timeout=False&lt;/code&gt; changes none of that. The client still reports &lt;code&gt;get_retry().get_retries()&lt;/code&gt; as 10, and the only visible effect is a warning:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Call to '&lt;strong&gt;init&lt;/strong&gt;' function with deprecated usage of input argument/s 'retry_on_timeout'. (TimeoutError is included by default.) -- Deprecated since version 6.0.0.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It is a &lt;code&gt;DeprecationWarning&lt;/code&gt;, and Python's default filters show those only when they point at your main script. Built in a helper that the main script calls, the client printed the warning. Built one level deeper, in a factory that calls that helper, it printed nothing at all.&lt;/p&gt;

&lt;h2&gt;
  
  
  How one INCR became two
&lt;/h2&gt;

&lt;p&gt;The test client uses &lt;code&gt;socket_timeout=0.5&lt;/code&gt; and sends a &lt;code&gt;PING&lt;/code&gt; first, so the write goes out on an already-open connection, the normal state for a pooled client in a long-running service. A second connection freezes the single-threaded server with &lt;code&gt;DEBUG SLEEP 0.8&lt;/code&gt;, and 0.05 s later the client calls &lt;code&gt;r.incr("hits")&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The command reaches the server and waits in its input buffer. At 0.5 s the client gives up, drops the connection, reconnects and sends the command again. When the server wakes up it executes both: the original from the dead connection and the retry from the new one. The caller sees no exception, only the value 2.&lt;/p&gt;

&lt;p&gt;Here are the key and &lt;code&gt;INFO commandstats&lt;/code&gt; after each case, from the first of two runs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;default            incr: returned=2 error=none after=0.75s hits=2 incrby=2 eval=0 debug_sleep=0 reconnects=1
retry_on_timeout=False incr: returned=2 error=none after=0.75s hits=2 incrby=2 eval=0 debug_sleep=0 reconnects=1
Retry(NoBackoff(),0) incr: returned=None error=TimeoutError after=0.50s hits=1 incrby=1 eval=0 debug_sleep=0 reconnects=0
default  request-id eval: returned=1 error=none after=0.76s hits=1 incrby=0 eval=2 debug_sleep=0 reconnects=1
default  DEBUG SLEEP 0.6: returned=None error=TimeoutError after=9.68s hits=0 incrby=0 eval=0 debug_sleep=11 reconnects=10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;incr()&lt;/code&gt; sends &lt;code&gt;INCRBY key 1&lt;/code&gt;, which is why the column says &lt;code&gt;incrby&lt;/code&gt;. The second run gave the same counts; the times moved by at most 0.01 s, except the last line at 8.99 s. The &lt;code&gt;PING&lt;/code&gt; matters: in an earlier version of the test without it, the brand-new client was still connecting when the stall began, and the counter ended at 1 in both runs.&lt;/p&gt;

&lt;h2&gt;
  
  
  No retry still does not mean "not applied"
&lt;/h2&gt;

&lt;p&gt;The third line is the one I expected from the second: with &lt;code&gt;retry=Retry(NoBackoff(), 0)&lt;/code&gt; the call fails at 0.50 s with &lt;code&gt;TimeoutError&lt;/code&gt;. But the counter is 1. The server ran the command; only the reply was lost.&lt;/p&gt;

&lt;p&gt;So turning retries off moves the problem rather than removing it. A job runner that retries on any exception, or a user who clicks again, recreates the double count one level up. After a socket timeout on a write, the client cannot tell "never ran" from "ran, reply lost", so the write itself has to make a second attempt harmless.&lt;/p&gt;

&lt;h2&gt;
  
  
  A 0.5 s timeout that took 9.68 s
&lt;/h2&gt;

&lt;p&gt;The same default hurts slow commands. With the default client, &lt;code&gt;DEBUG SLEEP 0.6&lt;/code&gt; raised &lt;code&gt;TimeoutError&lt;/code&gt; after 9.68 s (8.99 s in the second run), and the server executed it 11 times over 10 fresh connections. Each of those runs blocked the whole server for 0.6 s. With retries off it failed after 0.50 s and ran once.&lt;/p&gt;

&lt;p&gt;I only measured &lt;code&gt;DEBUG SLEEP&lt;/code&gt;, but the client cannot tell it apart from any other command that outlives &lt;code&gt;socket_timeout&lt;/code&gt;, such as a &lt;code&gt;ZUNIONSTORE&lt;/code&gt; on sets that have grown. The default does not fail fast there; it sends the expensive command ten more times.&lt;/p&gt;

&lt;h2&gt;
  
  
  The fix I kept
&lt;/h2&gt;

&lt;p&gt;I split clients by what they write, and made the counter that matters idempotent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;redis&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;backoff&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;NoBackoff&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;retry&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Retry&lt;/span&gt;
&lt;span class="c1"&gt;# Reads keep the default: up to 10 retries on ConnectionError and TimeoutError.&lt;/span&gt;
&lt;span class="n"&gt;cache&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;host&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"localhost"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;port&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;6379&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;socket_timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Counters get no automatic retry. A timeout now means "maybe applied".&lt;/span&gt;
&lt;span class="n"&gt;counters&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;host&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"localhost"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;port&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;6379&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;socket_timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;retry&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;Retry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;NoBackoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Or make the write idempotent: one request ID increments once, however often it is sent.&lt;/span&gt;
&lt;span class="no"&gt;INCR_ONCE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"""
if redis.call('SET', KEYS[2], '1', 'NX', 'EX', ARGV[1]) then
  return redis.call('INCR', KEYS[1])
end
return tonumber(redis.call('GET', KEYS[1]))
"""&lt;/span&gt;
&lt;span class="n"&gt;hits&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;eval&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;INCR_ONCE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"hits"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"req:42"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the default retry left on, the request-ID script was sent twice in the stall test (&lt;code&gt;eval=2&lt;/code&gt; above) and the counter still ended at 1. I also ran this snippet as written, with only the port changed, during a 0.8 s stall: it returned 1 and the key held 1.&lt;/p&gt;

&lt;p&gt;Two details matter. The request ID has to be created once per logical operation, at the edge (the HTTP request or the job), and reused on every attempt; otherwise each retry looks new. And its TTL has to outlast the retry window: the default policy gave up after 9 to 10 s in my runs, so 60 s leaves room.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I check in a review now
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;grep -rn retry_on_timeout&lt;/code&gt;: on redis-py 8.1.0, &lt;code&gt;False&lt;/code&gt; changes nothing except a warning that is often hidden.&lt;/li&gt;
&lt;li&gt;Log &lt;code&gt;client.get_retry().get_retries()&lt;/code&gt; once at startup; it said 10 for every client I had not configured.&lt;/li&gt;
&lt;li&gt;List the writes that are not idempotent: &lt;code&gt;INCR&lt;/code&gt;/&lt;code&gt;INCRBY&lt;/code&gt;, &lt;code&gt;HINCRBY&lt;/code&gt;, &lt;code&gt;LPUSH&lt;/code&gt;/&lt;code&gt;RPUSH&lt;/code&gt;, &lt;code&gt;XADD&lt;/code&gt; with &lt;code&gt;*&lt;/code&gt;. Each gets &lt;code&gt;Retry(NoBackoff(), 0)&lt;/code&gt; or a request-ID guard.&lt;/li&gt;
&lt;li&gt;Treat &lt;code&gt;TimeoutError&lt;/code&gt; on a write as "outcome unknown", never as "did not happen".&lt;/li&gt;
&lt;li&gt;Keep &lt;code&gt;socket_timeout&lt;/code&gt; above the slowest command you run on purpose, or one slow call becomes 11 runs on the server.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Takeaway
&lt;/h2&gt;

&lt;p&gt;The redis-py default suits reads, and it can silently apply a counter, a list push or a stream entry twice. &lt;code&gt;retry_on_timeout=False&lt;/code&gt; looks like the off switch, but on 8.1.0 it only triggers a deprecation warning. Decide the retry policy per client, and give every write that must happen once an ID the server can check.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>devops</category>
      <category>redis</category>
    </item>
    <item>
      <title>OpenAI max_retries=2 Turned 6 Attempts Into 18 Requests</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Mon, 16 Nov 2026 05:41:11 +0000</pubDate>
      <link>https://dev.to/acemeridian/openai-maxretries2-turned-6-attempts-into-18-requests-5d8o</link>
      <guid>https://dev.to/acemeridian/openai-maxretries2-turned-6-attempts-into-18-requests-5d8o</guid>
      <description>&lt;p&gt;The openai Python SDK already retries a 429 twice by default, so the tenacity decorator from OpenAI's own rate-limit cookbook, &lt;code&gt;stop_after_attempt(6)&lt;/code&gt;, sent 18 requests per call to my test server, not 6. Pick one retry layer: either &lt;code&gt;OpenAI(max_retries=0)&lt;/code&gt; under a tenacity policy that only retries errors that waiting can fix, or drop tenacity and raise &lt;code&gt;max_retries&lt;/code&gt; on the client.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. The numbers come from two runs on one Linux box: openai 3.51.0, tenacity 9.2.1 and Python 3.14.4, pointed through &lt;code&gt;OPENAI_BASE_URL&lt;/code&gt; at a local stub that answers every chat completion request with an OpenAI-shaped error body and logs the SDK's &lt;code&gt;x-stainless-retry-count&lt;/code&gt; header. None of this traffic went to OpenAI. Each run had twelve clients in parallel, one call each.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two Retry Loops in One Call
&lt;/h2&gt;

&lt;p&gt;The cookbook notebook &lt;a href="https://cookbook.openai.com/examples/how_to_handle_rate_limits" rel="noopener noreferrer"&gt;How to handle rate limits&lt;/a&gt; builds the client as &lt;code&gt;openai.OpenAI(api_key=...)&lt;/code&gt; and wraps the call in &lt;code&gt;@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))&lt;/code&gt;. Read alone, that is six attempts with random exponential backoff.&lt;/p&gt;

&lt;p&gt;The client underneath has its own loop. The SDK README says: "Certain errors are automatically retried 2 times by default, with a short exponential backoff." The list includes 429 Rate Limit. In 3.51.0 that backoff starts at 0.5 s and doubles, minus up to 25% jitter. So each tenacity attempt is really three requests, and tenacity only sleeps between the groups.&lt;/p&gt;

&lt;h2&gt;
  
  
  18 Requests per Call, Three at a Time
&lt;/h2&gt;

&lt;p&gt;These three lines from the stub's log are the cookbook code, run as published, against three errors: A1 got &lt;code&gt;rate_limit_exceeded&lt;/code&gt;, Q1 got &lt;code&gt;insufficient_quota&lt;/code&gt;, and U1 got a 401 for a wrong API key.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;A1: 18 requests (HTTP 429) over 19.9s, x-stainless-retry-count 0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2
Q1: 18 requests (HTTP 429) over 20.6s, x-stainless-retry-count 0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2
U1: 6 requests (HTTP 401) over 20.3s, x-stainless-retry-count 0,0,0,0,0,0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every cookbook call that got a 429, in both runs, looked like A1: 8 calls, 18 requests each, 12 of them SDK retries. Inside each group the third request went out 1.2 to 1.5 s after the first. The cookbook itself warns that "unsuccessful requests contribute to your per-minute limit, so continuously resending a request won’t work". The inner loop resends twice within 1.5 s before tenacity's backoff even starts.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Quota Error Got 18 Requests Too
&lt;/h2&gt;

&lt;p&gt;OpenAI uses 429 for two different problems. &lt;code&gt;rate_limit_exceeded&lt;/code&gt; clears up if you wait. &lt;code&gt;insufficient_quota&lt;/code&gt;, "You exceeded your current quota, please check your plan and billing details", does not: no amount of backoff buys credits. Without an &lt;code&gt;x-should-retry&lt;/code&gt; header, the SDK decides by status code, and tenacity's default is &lt;code&gt;retry_if_exception_type()&lt;/code&gt;, which retries on any exception. So Q1 sent 18 requests and got the same answer each time.&lt;/p&gt;

&lt;p&gt;U1 shows the other half. The SDK does not retry a 401, but tenacity does, so the wrapper still made 6 requests. Across both runs the four quota calls took 20.7 to 31.4 s to fail and the four bad-key calls 9.1 to 28.5 s. Both errors were final on the first response.&lt;/p&gt;

&lt;h2&gt;
  
  
  except openai.RateLimitError Never Ran
&lt;/h2&gt;

&lt;p&gt;After the sixth attempt, tenacity does not raise the error it caught. With the default &lt;code&gt;reraise=False&lt;/code&gt; it raises &lt;code&gt;tenacity.RetryError&lt;/code&gt;, which wraps the last attempt. My client had &lt;code&gt;except openai.RateLimitError&lt;/code&gt; and &lt;code&gt;except openai.AuthenticationError&lt;/code&gt; handlers. All 12 cookbook calls across both runs skipped both and landed in the generic &lt;code&gt;except Exception&lt;/code&gt;. Any code that maps a quota error to "check billing" or a rate limit to "try again later" never runs; &lt;code&gt;RetryError.last_attempt.exception()&lt;/code&gt; holds the original error if you need it.&lt;/p&gt;

&lt;h2&gt;
  
  
  One Retry Layer That Knows Which 429 Is Which
&lt;/h2&gt;

&lt;p&gt;This is the version I would ship. The client does not retry, tenacity retries only errors that waiting can fix, and &lt;code&gt;reraise=True&lt;/code&gt; hands the original exception to the caller:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;openai&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;tenacity&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;retry&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;retry_if_exception&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stop_after_attempt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wait_random_exponential&lt;/span&gt;

&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;openai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;OpenAI&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_retries&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# this layer does all the retrying&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;is_transient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exc&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;BaseException&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;isinstance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exc&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;openai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;RateLimitError&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;exc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;code&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"insufficient_quota"&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;isinstance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exc&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;openai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;APIConnectionError&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;openai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;InternalServerError&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nd"&gt;@retry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;retry&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nf"&gt;retry_if_exception&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;is_transient&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;wait&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nf"&gt;wait_random_exponential&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;stop&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nf"&gt;stop_after_attempt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;reraise&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;completion_with_backoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;completions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Against the same stub, the rate-limited call made 6 requests (8.4 to 21.5 s over two runs) and then &lt;code&gt;openai.RateLimitError&lt;/code&gt; reached its own handler. The quota error and the bad key each made 1 request and failed in 0.1 s or less. In this SDK &lt;code&gt;APITimeoutError&lt;/code&gt; is a subclass of &lt;code&gt;APIConnectionError&lt;/code&gt;, so timeouts are covered too.&lt;/p&gt;

&lt;h2&gt;
  
  
  Or Let the SDK Be the Only Loop
&lt;/h2&gt;

&lt;p&gt;If you do not need the quota distinction, the smaller fix is to delete tenacity and raise the SDK's own budget with &lt;code&gt;OpenAI(max_retries=5)&lt;/code&gt;. That made 6 requests per rate-limited call, retry counts 0 to 5, in 13.2 to 14.3 s, and the error came out as a plain &lt;code&gt;openai.RateLimitError&lt;/code&gt;. According to the 3.51.0 source, it also honors a server's &lt;code&gt;Retry-After&lt;/code&gt; of up to 120 s, which &lt;code&gt;wait_random_exponential&lt;/code&gt; never reads; I did not measure that part. The cost: the SDK retries every 429, so the quota error also took 6 requests and 13.5 to 13.9 s to fail.&lt;/p&gt;

&lt;h2&gt;
  
  
  What This Test Does Not Show
&lt;/h2&gt;

&lt;p&gt;The stub is not OpenAI. It answers instantly and sends no &lt;code&gt;Retry-After&lt;/code&gt; or &lt;code&gt;x-should-retry&lt;/code&gt; header, so the timings show backoff alone. The SDK obeys &lt;code&gt;x-should-retry&lt;/code&gt; before it looks at the status code, and I have not checked whether OpenAI's real quota error sends one. I also cannot say how a real 429 burst moves your quota window, only how many requests your code sends into it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Count retry layers before you tune one. With the SDK default, &lt;code&gt;stop_after_attempt(n)&lt;/code&gt; means up to 3n requests.&lt;/li&gt;
&lt;li&gt;Give retries one owner: &lt;code&gt;max_retries=0&lt;/code&gt; under tenacity, or the SDK alone with a larger &lt;code&gt;max_retries&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Retry by cause, not by status code. &lt;code&gt;insufficient_quota&lt;/code&gt; and a 401 should fail on the first response.&lt;/li&gt;
&lt;li&gt;With tenacity, set &lt;code&gt;reraise=True&lt;/code&gt;, or your &lt;code&gt;except openai.RateLimitError&lt;/code&gt; handlers never run.&lt;/li&gt;
&lt;li&gt;Log &lt;code&gt;x-stainless-retry-count&lt;/code&gt; on your proxy, or set &lt;code&gt;OPENAI_LOG=info&lt;/code&gt; to see the SDK's own "Retrying request" lines.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>openai</category>
    </item>
    <item>
      <title>Ollama /api/embed Silently Dropped 45% of My Document</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Sun, 15 Nov 2026 05:33:53 +0000</pubDate>
      <link>https://dev.to/acemeridian/ollama-apiembed-silently-dropped-45-of-my-document-4en</link>
      <guid>https://dev.to/acemeridian/ollama-apiembed-silently-dropped-45-of-my-document-4en</guid>
      <description>&lt;p&gt;On a machine without a GPU, Ollama 0.40.14 loaded qwen3-embedding:0.6b with a 4,096-token context, and &lt;code&gt;/api/embed&lt;/code&gt; cut my 7,510-token document down to 4,095 tokens with no error, no warning and no flag in the response. Send &lt;code&gt;"truncate": false&lt;/code&gt; so an overlong input fails with HTTP 400, and split documents into chunks of about 2,000 characters before you embed them.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. Every number below comes from one run on an 8-core Linux box with no GPU: Ollama 0.40.14, qwen3-embedding:0.6b (Q8_0, 1,024 dimensions) and Python 3.14.4 calling the HTTP API with &lt;code&gt;urllib&lt;/code&gt;. The test document is the GPL-3 license text (35,149 characters).&lt;/p&gt;

&lt;h2&gt;
  
  
  The Model Says 32,768, the Server Uses 4,096
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;/api/show&lt;/code&gt; reports &lt;code&gt;qwen3.context_length = 32768&lt;/code&gt; for this model. That is what the model was trained for, not what the server used. After the first request, &lt;code&gt;/api/ps&lt;/code&gt; listed the loaded model with &lt;code&gt;context_length=4096&lt;/code&gt;, and the server log said why: &lt;code&gt;msg="vram-based default context" total_vram="0 B" default_num_ctx=4096&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;With no VRAM to measure, the server picked 4,096 tokens. Embedding requests run in that same context, so one embedding sees at most 4,095 tokens of input.&lt;/p&gt;

&lt;h2&gt;
  
  
  A Sentence at the End Changed Nothing
&lt;/h2&gt;

&lt;p&gt;I wrote one fact that appears nowhere in the license: "The staging cluster's nightly backup runs at 02:30 UTC and keeps 14 snapshots." Then I embedded three documents: the license alone, the license with the fact appended at the end, and the license with the fact at the start. The query was "When does the staging cluster's nightly backup run?"&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;D_none (GPL only): HTTP 200 44.6s chars=35149 prompt_eval_count=4095 keys=['embeddings', 'load_duration', 'model', 'prompt_eval_count', 'total_duration']
D_end (needle last): HTTP 200 50.6s chars=35230 prompt_eval_count=4095 keys=['embeddings', 'load_duration', 'model', 'prompt_eval_count', 'total_duration']
e_end == e_none (exact list equality): True  max|diff| = 0.0
cos(q, D_none) = 0.2773  cos(q, D_end) = 0.2773  cos(q, D_start) = 0.7830
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The vector for "license plus fact at the end" is identical to the vector for the license alone: all 1,024 floats equal. Both score 0.2773 against the query. Put the same sentence first and the score jumps to 0.7830. In a RAG index this is the quiet kind of failure: the chunk is stored, the vector looks normal, and nothing in the second half of the text can ever be retrieved.&lt;/p&gt;

&lt;h2&gt;
  
  
  Nothing in the Response Says It Was Cut
&lt;/h2&gt;

&lt;p&gt;The response has five keys, and none of them is a truncation flag. The only hint is &lt;code&gt;prompt_eval_count&lt;/code&gt; = 4095, the context minus one, and you only notice it if you compare it with what you sent. The runner's log line for the same request reads &lt;code&gt;n_tokens = 4095, truncated = 0&lt;/code&gt;, so grepping the server log for truncation finds nothing either.&lt;/p&gt;

&lt;p&gt;The behaviour is documented. The API reference says &lt;code&gt;truncate&lt;/code&gt; "truncates the end of each input to fit within context length. Returns error if &lt;code&gt;false&lt;/code&gt; and context length is exceeded. Defaults to &lt;code&gt;true&lt;/code&gt;". The default is the trap. At this text's 4.7 characters per token, everything after roughly the first 19,000 characters was dropped.&lt;/p&gt;

&lt;h2&gt;
  
  
  truncate=false Turns It Into a 400
&lt;/h2&gt;

&lt;p&gt;This is the guard I now put in front of every embedding call:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;urllib&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;embed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;texts&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"http://127.0.0.1:11434"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;body&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"model"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"qwen3-embedding:0.6b"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"input"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;texts&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"truncate"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;req&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;urllib&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Request&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;url&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;"/api/embed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                                 &lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"Content-Type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"application/json"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;urllib&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;urlopen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# raises HTTPError 400 instead of truncating&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;loads&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"embeddings"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A short input still returns a 1,024-dimension vector. The full license raised &lt;code&gt;HTTPError&lt;/code&gt; 400 after 0.03 seconds with &lt;code&gt;{"error":"the input length exceeds the context length"}&lt;/code&gt;. That is the failure you want: fast, loud, and before a useless vector lands in the index. The silent version took 44.6 seconds to produce that useless vector.&lt;/p&gt;

&lt;h2&gt;
  
  
  Chunks Found the Fact; the Long Context Barely Did
&lt;/h2&gt;

&lt;p&gt;The fix that worked was splitting the text on paragraph boundaries into chunks of at most 2,000 characters. That gave 20 chunks, the longest 1,992 characters, sent as one batch with &lt;code&gt;truncate: false&lt;/code&gt;. The batch returned HTTP 200 in 54.1 seconds for 7,529 tokens. The chunk holding the fact ranked first of 20 with a cosine of 0.8372; the next best scored 0.3272.&lt;/p&gt;

&lt;p&gt;The other obvious fix is a bigger context. I started a second server with &lt;code&gt;OLLAMA_CONTEXT_LENGTH=16384&lt;/code&gt; and embedded the whole document in one call. All 7,510 tokens were read this time, and the fact did move the vector: the query scored 0.6103 against the license with the fact and 0.3650 without it. That is retrievable, but far weaker than 0.8372, because one vector now has to summarise 7,500 tokens of license text plus one sentence about backups.&lt;/p&gt;

&lt;h2&gt;
  
  
  What a Bigger Context Costs on CPU
&lt;/h2&gt;

&lt;p&gt;The single 7,510-token embedding took 124.0 seconds. The 20 chunks covering the same text took 54.1 seconds, 2.3 times faster. The loaded model grew too: &lt;code&gt;/api/ps&lt;/code&gt; reported 1.24 GB at a 4,096-token context, 1.72 GB at 8,192 and 2.70 GB at 16,384. A per-request &lt;code&gt;"options": {"num_ctx": 8192}&lt;/code&gt; also raised the context, but the server reloaded the model to apply it, so mixing context sizes across requests means reloads.&lt;/p&gt;

&lt;p&gt;I did not test a GPU machine; its default context may be larger, but the trap is the same whenever a document is longer than the loaded context.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Do not trust the model card's context length. Check &lt;code&gt;/api/ps&lt;/code&gt; or the server log for the context that was actually loaded.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;"truncate": false&lt;/code&gt; on every &lt;code&gt;/api/embed&lt;/code&gt; call. A 400 in hundredths of a second beats a vector that ignores half the document.&lt;/li&gt;
&lt;li&gt;Log &lt;code&gt;prompt_eval_count&lt;/code&gt; next to each input's length. A value equal to the context minus one means the input was cut.&lt;/li&gt;
&lt;li&gt;Chunk before you embed. Here, 2,000-character chunks found the fact at 0.84 cosine and ran 2.3 times faster than one embedding of the whole text at a 16,384-token context.&lt;/li&gt;
&lt;li&gt;If you do raise the context, budget for it: 124 seconds for one document, and the model grew from 1.24 GB to 2.70 GB.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>ollama</category>
    </item>
    <item>
      <title>OpenAI timeout=60 Never Fired on a Stream With Keep-Alives</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Sat, 14 Nov 2026 05:29:18 +0000</pubDate>
      <link>https://dev.to/acemeridian/openai-timeout60-never-fired-on-a-stream-with-keep-alives-10o7</link>
      <guid>https://dev.to/acemeridian/openai-timeout60-never-fired-on-a-stream-with-keep-alives-10o7</guid>
      <description>&lt;p&gt;The openai Python SDK's &lt;code&gt;timeout=60&lt;/code&gt; limits each socket read, not the request, so a streamed completion that receives an SSE keep-alive comment every 15 seconds never times out, even though your loop never sees an event. Put a wall clock around the whole attempt instead: with &lt;code&gt;AsyncOpenAI&lt;/code&gt;, &lt;code&gt;asyncio.timeout(30)&lt;/code&gt; ended the same stalled stream at 30.0 to 30.1 seconds in every run.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. The numbers come from openai 2.43.0 and httpx 0.28.1 on Python 3.14.4, run against a local fake OpenAI-compatible endpoint over plain HTTP and TLS. I did not test OpenAI's own API, and I do not know whether it sends comment lines.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Server Sends One Token, Then Only Heartbeats
&lt;/h2&gt;

&lt;p&gt;The fake endpoint answers &lt;code&gt;POST /v1/chat/completions&lt;/code&gt; with &lt;code&gt;text/event-stream&lt;/code&gt;, sends one normal &lt;code&gt;data:&lt;/code&gt; chunk containing "Hello", and then stops producing tokens. In the silent variant it sends nothing more and holds the connection open. In the heartbeat variant it writes &lt;code&gt;: keep-alive&lt;/code&gt; every 15 seconds and never sends &lt;code&gt;[DONE]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The client copies the settings of a real pipeline I reviewed this week: &lt;code&gt;OpenAI(timeout=60.0, max_retries=0)&lt;/code&gt;, &lt;code&gt;stream=True&lt;/code&gt;, and a &lt;code&gt;for chunk in stream&lt;/code&gt; loop. Each scenario ran as its own process under a 150-second &lt;code&gt;timeout&lt;/code&gt; command, so exit code 124 means it was still blocked when the cap hit.&lt;/p&gt;

&lt;h2&gt;
  
  
  Silence Times Out at 60 Seconds; Heartbeats Never Do
&lt;/h2&gt;

&lt;p&gt;Result lines from one plain-HTTP run, all scenarios in parallel:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{"result": "exception", "type": "httpx.ReadTimeout", "msg": "timed out", "is_openai_APITimeoutError": false, "t": 60.6, "scenario": "silent", "tls": false}
{"scenario": "comments", "exit": 124}
{"result": "exception", "type": "builtins.TimeoutError", "msg": "", "t": 30.1, "scenario": "comments-async", "tls": false}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The silent stream failed at 60.4 to 60.6 seconds across three runs, as expected. The heartbeat stream was still waiting at 150 seconds in all three, including the TLS run. Nothing in the loop body ran after the first chunk.&lt;/p&gt;

&lt;p&gt;Look at the type in the silent case: &lt;code&gt;httpx.ReadTimeout&lt;/code&gt;, not &lt;code&gt;openai.APITimeoutError&lt;/code&gt;. The SDK converts timeouts into its own exception while it sends the request; once you are iterating, the raw httpx exception comes through. An &lt;code&gt;except openai.APITimeoutError&lt;/code&gt; around a stream misses it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why the Loop Sees Nothing but the Timer Resets
&lt;/h2&gt;

&lt;p&gt;Two pieces combine. First, the SDK's SSE decoder discards comment lines: &lt;code&gt;openai/_streaming.py&lt;/code&gt; has &lt;code&gt;if line.startswith(":"): return None&lt;/code&gt;, which is correct for the format, so your code never learns that bytes arrived. Second, &lt;code&gt;timeout=60&lt;/code&gt; becomes &lt;code&gt;httpx.Timeout(60)&lt;/code&gt;, which sets the same 60 seconds for connect, read, write and pool acquisition. None of the four is a total. The read limit restarts on every successful read, and each comment is one.&lt;/p&gt;

&lt;p&gt;So the 60 seconds measure silence on the socket, not progress on your completion. A heartbeat every 15 seconds means the socket is never silent for 60.&lt;/p&gt;

&lt;p&gt;I hit the same shape with &lt;code&gt;requests&lt;/code&gt; last week, when a server dripping one byte every three seconds &lt;a href="https://medium.com/@acemeridian/my-python-request-had-timeout-5-it-ran-for-57-seconds-d6352e36c786" rel="noopener noreferrer"&gt;kept &lt;code&gt;timeout=5&lt;/code&gt; busy for 57 seconds&lt;/a&gt;. The difference here is that the bytes are invisible: no partial content, no log line, nothing that tells you the call is still alive.&lt;/p&gt;

&lt;h2&gt;
  
  
  Who Actually Sends Comment Lines
&lt;/h2&gt;

&lt;p&gt;This is not exotic. The HTML Standard's section on server-sent events suggests sending a comment line every 15 seconds or so, because some legacy proxies drop connections that go quiet. OpenRouter's streaming docs say it occasionally sends comments such as &lt;code&gt;: OPENROUTER PROCESSING&lt;/code&gt; to prevent connection timeouts. Any gateway, proxy or self-hosted server that follows that advice turns a per-read timeout into no timeout while the model is stuck.&lt;/p&gt;

&lt;h2&gt;
  
  
  A Wall-Clock Budget Ended It at 30 Seconds
&lt;/h2&gt;

&lt;p&gt;With &lt;code&gt;AsyncOpenAI&lt;/code&gt;, I put &lt;code&gt;asyncio.timeout&lt;/code&gt; around the request and the iteration together. This is the exact function I ran this morning, pointed at the fake endpoint through &lt;code&gt;OPENAI_BASE_URL&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;openai&lt;/span&gt;
&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;openai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;AsyncOpenAI&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;60.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_retries&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;ask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;budget_s&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;30.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;parts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;budget_s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# wall clock for the whole attempt&lt;/span&gt;
        &lt;span class="n"&gt;stream&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;completions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"gpt-4o-mini"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"role"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"user"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;stream&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;choices&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;choices&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delta&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;content&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;parts&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;choices&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delta&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;content&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It raised &lt;code&gt;TimeoutError&lt;/code&gt; at 30.0 seconds in both runs this morning; an earlier version of the test ended at 30.0 to 30.1 seconds in three runs. I also checked the socket. Right after the timeout, &lt;code&gt;ss&lt;/code&gt; showed no established connection from the client, and the server's next keep-alive write, at 45 seconds, failed with &lt;code&gt;BrokenPipeError&lt;/code&gt;. Wrapping the loop in &lt;code&gt;async with stream:&lt;/code&gt; made no difference in the same two runs; the cancellation had already closed the connection.&lt;/p&gt;

&lt;h2&gt;
  
  
  In Sync Code, close() Was 15 Seconds Late
&lt;/h2&gt;

&lt;p&gt;Sync code has no cancellation, so I tried a &lt;code&gt;threading.Timer&lt;/code&gt; that fires at 30 seconds. Calling &lt;code&gt;stream.close()&lt;/code&gt; from the timer did not interrupt the blocked read. The loop only failed when the next keep-alive arrived, with &lt;code&gt;httpx.ReadError: [Errno 9] Bad file descriptor&lt;/code&gt; at 45.4 to 45.5 seconds. So a 30-second deadline ended at 45 seconds. I did not test &lt;code&gt;close()&lt;/code&gt; against a silent stream.&lt;/p&gt;

&lt;p&gt;Shutting down the socket worked. The timer took the raw socket from &lt;code&gt;stream.response.extensions["network_stream"].get_extra_info("socket")&lt;/code&gt; and called &lt;code&gt;shutdown(socket.SHUT_RDWR)&lt;/code&gt;, and the loop ended at 30.4 to 30.5 seconds over plain HTTP and TLS. That reaches into a low-level httpx response extension, so I would rather move the call into async code or a worker process that can be killed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Treat &lt;code&gt;timeout=&lt;/code&gt; on a streamed call as an idle limit. It does not bound how long the attempt runs.&lt;/li&gt;
&lt;li&gt;Put one wall-clock budget around the request and the iteration together: &lt;code&gt;asyncio.timeout()&lt;/code&gt; with &lt;code&gt;AsyncOpenAI&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In sync code, &lt;code&gt;stream.close()&lt;/code&gt; from another thread waits for the next read. Shut the socket down instead.&lt;/li&gt;
&lt;li&gt;Around iteration, catch &lt;code&gt;httpx.TimeoutException&lt;/code&gt; as well as &lt;code&gt;openai.APITimeoutError&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Test against a server that sends one chunk and then only &lt;code&gt;: keep-alive&lt;/code&gt;. Mine is 77 lines of standard-library Python, and one run shows whether your deadline holds.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you run a gateway in front of a model API, does it send comment lines while the model thinks?&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>ai</category>
      <category>openai</category>
    </item>
    <item>
      <title>Count Rows, Not Errors: 7 Data Bugs I Reproduced</title>
      <dc:creator>Ace Meridian</dc:creator>
      <pubDate>Fri, 13 Nov 2026 05:28:12 +0000</pubDate>
      <link>https://dev.to/acemeridian/count-rows-not-errors-7-data-bugs-i-reproduced-72j</link>
      <guid>https://dev.to/acemeridian/count-rows-not-errors-7-data-bugs-i-reproduced-72j</guid>
      <description>&lt;p&gt;To find out whether a write path loses data, count rows in the source of truth after a forced failure or a concurrent run; the error rate will not tell you. In seven bugs I reproduced over the past week, every call that lost or duplicated data returned success, and one independent count caught each bug.&lt;/p&gt;

&lt;p&gt;This story was written with the assistance of an AI writing program. Each case ran on the real software (PostgreSQL 16.4, Kafka 4.4.0, Elasticsearch 7.17.29, Redis 8.10.2, SQLite 3.46.1); only the external payment and webhook providers were simulated. Each section ends with the check that caught the bug.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. A Caught Exception Rolled Back the Row It Protected
&lt;/h2&gt;

&lt;p&gt;A migration dual-writes in one Spring &lt;code&gt;@Transactional&lt;/code&gt; method: insert into the legacy table, then into the new one inside a try/catch that counts failures and queues the id for repair. I left out the new table's December partition and recorded 20 events, 10 in December.&lt;/p&gt;

&lt;p&gt;All 20 calls returned normally, and nothing was logged at WARN or ERROR. The legacy table, the source of truth, held 10 rows: PostgreSQL aborts the whole transaction when one statement fails, so COMMIT silently rolled back (pgjdbc 42.7.8 and 42.2.5). None of the 10 queued ids existed in legacy, so repair had nothing to copy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// as written: 20 calls OK, the legacy table keeps 10 of 20 rows&lt;/span&gt;
&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="k"&gt;record&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;OrderEvent&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;legacyInsert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nf"&gt;v2Insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;DataAccessException&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nf"&gt;caught&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;// fix: nested is a TransactionTemplate with PROPAGATION_NESTED (a savepoint)&lt;/span&gt;
&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;recordNested&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;OrderEvent&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;legacyInsert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;nested&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;executeWithoutResult&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;v2Insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;DataAccessException&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nf"&gt;caught&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The savepoint kept all 20 legacy rows, as did &lt;code&gt;autosave=always&lt;/code&gt; on the JDBC URL. 2,000 clean writes took 3,150/3,005 ms instead of 2,646/2,850.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check:&lt;/strong&gt; after a forced failure, count the legacy table, not the failure counter.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Exactly-Once Kafka Paid 20 of 40 Payouts Twice
&lt;/h2&gt;

&lt;p&gt;One partition, 40 payouts, &lt;code&gt;read_committed&lt;/code&gt;, one transaction per poll of 20. Nothing crashed. One provider call took 12 s, past &lt;code&gt;max.poll.interval.ms&lt;/code&gt; (10 s), so a second consumer took the partition and restarted at offset 0. The first, still alive, paid the other 14 payouts of its batch after the handover; its &lt;code&gt;CommitFailedException&lt;/code&gt; came about 8 s later.&lt;/p&gt;

&lt;p&gt;With a fresh UUID as the idempotency key per attempt, 20 of 40 payouts were paid twice, in both runs and under KIP-848. Kafka looked perfect: committed offset 40, 40 output records. A key derived from the payout, &lt;code&gt;"payout:" + payoutId&lt;/code&gt;, turned 60 provider calls into 40 transfers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check:&lt;/strong&gt; count transfers per payout id at the provider.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. A Conditional UPDATE Protected the Row, Not the Charge
&lt;/h2&gt;

&lt;p&gt;Two checkouts of one order, 0 to 20 ms apart, each read &lt;code&gt;pending&lt;/code&gt;, called the provider, then ran &lt;code&gt;UPDATE ... WHERE status = 'pending'&lt;/code&gt;. The loser's UPDATE matched 0 rows after its charge went out: 100 of 100 orders were charged twice. Claiming before the call brought it to 0:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;claim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;conn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;oid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;uuid4&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;hex&lt;/span&gt;
    &lt;span class="n"&gt;cur&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;conn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"UPDATE orders SET status = 'charging', attempt_id = %s WHERE id = %s AND status = 'pending'"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attempt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;oid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;cur&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rowcount&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s1"&gt;'skip'&lt;/span&gt;
    &lt;span class="nf"&gt;provider&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;oid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;cur&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;conn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"UPDATE orders SET status = 'paid', updated_at = now() WHERE id = %s AND status = 'charging' AND attempt_id = %s"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;oid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s1"&gt;'paid'&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;cur&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rowcount&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="s1"&gt;'lost'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In production, also pass &lt;code&gt;attempt_id&lt;/code&gt; to the provider as its idempotency key; my fake took none.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check:&lt;/strong&gt; fire two checkouts 0 to 20 ms apart and count provider calls.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. The Checkpoint Reached the Max and Still Skipped Events
&lt;/h2&gt;

&lt;p&gt;A projector read &lt;code&gt;WHERE global_seq &amp;gt; checkpoint&lt;/code&gt; on a &lt;code&gt;BIGSERIAL&lt;/code&gt; column. The number is assigned at INSERT; the row becomes visible at COMMIT. If 101 commits before 100, the projector checkpoints 101 and never reads 100. With 8 concurrent writers the checkpoint reached &lt;code&gt;max(global_seq)&lt;/code&gt; every run, yet 201 to 214 of 3,228 events were never projected. One writer missed 0.&lt;/p&gt;

&lt;p&gt;Storing &lt;code&gt;pg_current_xact_id()&lt;/code&gt; per event, reading only &lt;code&gt;tx_id &amp;lt; pg_snapshot_xmin(pg_current_snapshot())&lt;/code&gt; and checkpointing on &lt;code&gt;(tx_id, global_seq)&lt;/code&gt; missed 0 in 8 runs. The price: any open write transaction stalls the projection.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check:&lt;/strong&gt; after the drain, events must equal projected rows.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. bulk.close() Returned Before the Last Bulks Landed
&lt;/h2&gt;

&lt;p&gt;An Elasticsearch reindex fed a &lt;code&gt;BulkProcessor&lt;/code&gt; (5,000 actions, 2 concurrent requests), called &lt;code&gt;close()&lt;/code&gt;, then swapped the alias. &lt;code&gt;close()&lt;/code&gt; is &lt;code&gt;awaitClose(0, NANOSECONDS)&lt;/code&gt;, so two bulks, 10,000 documents, were still in flight. Counts through the alias right after the swap: 45,676, 68,830 and 70,116 of 100,000 (the 1 s refresh hid the rest). &lt;code&gt;failedItems&lt;/code&gt; stayed 0. &lt;code&gt;awaitClose(60, SECONDS)&lt;/code&gt; plus a refresh gave 100,000 in 3 of 3 runs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check:&lt;/strong&gt; swap only after &lt;code&gt;awaitClose&lt;/code&gt; returns true and the new count equals the source count.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. A Webhook Got a 200 and Was Processed Zero Times
&lt;/h2&gt;

&lt;p&gt;The handler claimed the delivery key in Redis with &lt;code&gt;SET NX PX 30000&lt;/code&gt;, then processed. Processing threw, the handler returned 500, and the claim stayed. The retry at t=5 s hit the claim and got a 200 for "in progress"; most providers stop on any 2xx. At t=31 s the claim had expired with no done marker: processed 0 times. Releasing the claim in the catch (random token, Lua compare-and-delete) let the 5 s retry process it once. Answer 409 for in-progress claims.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check:&lt;/strong&gt; make the handler throw once, replay 5 s later, count successful runs.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Eight SQLite Workers Committed 2,000 Times and Kept 250
&lt;/h2&gt;

&lt;p&gt;Eight Python processes each added 1 to one row 250 times: read, update, commit. All 2,000 commits succeeded; the counter ended at 250 in six of six runs. Default &lt;code&gt;sqlite3&lt;/code&gt; opens the transaction at the UPDATE, after the read, and the 5 s busy timeout turned contention into waiting, not errors. &lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt; before the read gave 2,000. &lt;a href="https://medium.com/@acemeridian/8-python-workers-lost-1-750-sqlite-updates-without-an-error-d31bc6a24073" rel="noopener noreferrer"&gt;Full write-up here.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check:&lt;/strong&gt; N workers add 1 M times each; assert the result is N × M.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I Test Now
&lt;/h2&gt;

&lt;p&gt;Error rates count calls that failed; all seven bugs lived in calls that succeeded. Before I trust a write path:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Force one failure, then count the source of truth.&lt;/li&gt;
&lt;li&gt;Count external side effects per business id.&lt;/li&gt;
&lt;li&gt;Test with concurrent writers: the checkpoint gap was 0 with one writer, about 200 with eight.&lt;/li&gt;
&lt;li&gt;Count before switching reads: alias, checkpoint, new table.&lt;/li&gt;
&lt;li&gt;Replay a delivery after a failure; claims and dedupe keys break on the second attempt.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>database</category>
      <category>programming</category>
      <category>backend</category>
      <category>testing</category>
    </item>
  </channel>
</rss>
