@@ -1209,6 +1209,166 @@ describe("OpenAiNativeHandler", () => {
12091209 expect ( mockCaptureException ) . not . toHaveBeenCalled ( )
12101210 } )
12111211
1212+ it ( "rejects with the contract AbortError when the fallback body closes in the turn the caller aborts" , async ( ) => {
1213+ // The loop-boundary check runs before reader.read(), so a done that lands while the
1214+ // cancellation is pending used to end the generator normally: the caller received a
1215+ // completed partial stream for a request it had already stopped. The pull after the
1216+ // first chunk stays parked until this test releases it, which is the turn the abort
1217+ // lands in; releasing it closes the body so read() resolves { done: true }.
1218+ mockResponsesCreate . mockRejectedValue ( new Error ( "SDK not available" ) )
1219+ let parkedOnSecondPull = false
1220+ let releaseParkedPull : ( ( ) => void ) | undefined
1221+ const mockFetch = vitest . fn ( ) . mockImplementation ( ( ) => {
1222+ const encoder = new TextEncoder ( )
1223+ let pulls = 0
1224+ const body = new ReadableStream < Uint8Array > ( {
1225+ pull : ( streamController ) => {
1226+ pulls ++
1227+ if ( pulls === 1 ) {
1228+ streamController . enqueue (
1229+ encoder . encode ( 'data: {"type":"response.output_text.delta","delta":"partial"}\n\n' ) ,
1230+ )
1231+ return
1232+ }
1233+ parkedOnSecondPull = true
1234+ return new Promise < void > ( ( resolve ) => {
1235+ releaseParkedPull = ( ) => {
1236+ streamController . close ( )
1237+ resolve ( )
1238+ }
1239+ } )
1240+ } ,
1241+ } )
1242+ return Promise . resolve ( { ok : true , body } )
1243+ } )
1244+ global . fetch = mockFetch as typeof fetch
1245+
1246+ const signalController = new AbortController ( )
1247+ const stream = handler . createMessage (
1248+ systemPrompt ,
1249+ messages ,
1250+ makeCreateMessageMetadata ( { abortSignal : signalController . signal } ) ,
1251+ )
1252+ const iterator = stream [ Symbol . asyncIterator ] ( )
1253+ const first = await iterator . next ( )
1254+ expect ( first . done ) . toBe ( false )
1255+ expect ( first . value ) . toMatchObject ( { type : "text" , text : "partial" } )
1256+
1257+ // Start the next pull before cancelling, so the abort lands after the loop-boundary
1258+ // check has passed and while read() is pending.
1259+ const pending = iterator . next ( )
1260+ await tick ( )
1261+ expect ( parkedOnSecondPull ) . toBe ( true )
1262+ signalController . abort ( )
1263+ releaseParkedPull ! ( )
1264+
1265+ await expect ( pending ) . rejects . toMatchObject ( {
1266+ name : "AbortError" ,
1267+ message : "The OpenAI Native request was aborted" ,
1268+ } )
1269+ // A stop is not a provider failure to report.
1270+ expect ( mockCaptureException ) . not . toHaveBeenCalled ( )
1271+ } )
1272+
1273+ it ( "cancels the open fallback body and releases the reader lock when the consumer abandons the stream" , async ( ) => {
1274+ // Regression evidence for the failed pre-merge check: a consumer that stops early (the
1275+ // stop-button path) must tear the socket down instead of leaving the body open. Nothing
1276+ // here aborts, so the early exit alone has to do the cancelling.
1277+ mockResponsesCreate . mockRejectedValue ( new Error ( "SDK not available" ) )
1278+ let cancelCalls = 0
1279+ // One SSE chunk, then the body stays open: no close, no abort, no error.
1280+ const body = new ReadableStream < Uint8Array > ( {
1281+ start : ( streamController ) => {
1282+ streamController . enqueue (
1283+ new TextEncoder ( ) . encode (
1284+ 'data: {"type":"response.output_text.delta","delta":"partial"}\n\n' ,
1285+ ) ,
1286+ )
1287+ } ,
1288+ cancel : ( ) => {
1289+ cancelCalls ++
1290+ } ,
1291+ } )
1292+ const mockFetch = vitest . fn ( ) . mockResolvedValue ( { ok : true , body } )
1293+ global . fetch = mockFetch as typeof fetch
1294+
1295+ const stream = handler . createMessage ( systemPrompt , messages , makeCreateMessageMetadata ( ) )
1296+ const iterator = stream [ Symbol . asyncIterator ] ( )
1297+ const first = await iterator . next ( )
1298+ expect ( first . done ) . toBe ( false )
1299+ expect ( first . value ) . toMatchObject ( { type : "text" , text : "partial" } )
1300+ // The provider holds the only reader while the stream is live.
1301+ expect ( body . locked ) . toBe ( true )
1302+
1303+ // return() on the generator is the abandonment path a stop takes.
1304+ const completed = await iterator . return ( undefined )
1305+ expect ( completed . done ) . toBe ( true )
1306+ // The body was still open when the consumer stopped, so the finally had to cancel it.
1307+ expect ( cancelCalls ) . toBe ( 1 )
1308+ // A second reader is acquirable only once the lock was released: that is the observable
1309+ // form of "its reader lock is released".
1310+ expect ( body . locked ) . toBe ( false )
1311+ expect ( ( ) => body . getReader ( ) ) . not . toThrow ( )
1312+ // Abandoning a stream is a stop, not a provider failure to report.
1313+ expect ( mockCaptureException ) . not . toHaveBeenCalled ( )
1314+ } )
1315+
1316+ it ( "hands out every event delivered by one pull and only then observes the cancellation" , async ( ) => {
1317+ // This row tests the bound the file states in its own comments: cancellation is observed
1318+ // between pulls, never between chunks. One read carries three SSE events, so an abort
1319+ // landing between the yields of that batch must not truncate it, and the next pull is
1320+ // where the cancellation surfaces. Tightening the bound to per-chunk is a maintainer
1321+ // decision, and changing it has to change this row.
1322+ mockResponsesCreate . mockRejectedValue ( new Error ( "SDK not available" ) )
1323+ const mockFetch = vitest . fn ( ) . mockImplementation ( ( ) => {
1324+ const encoder = new TextEncoder ( )
1325+ let pulls = 0
1326+ const body = new ReadableStream < Uint8Array > ( {
1327+ pull : ( streamController ) => {
1328+ pulls ++
1329+ if ( pulls === 1 ) {
1330+ streamController . enqueue (
1331+ encoder . encode (
1332+ 'data: {"type":"response.output_text.delta","delta":"one"}\n\n' +
1333+ 'data: {"type":"response.output_text.delta","delta":"two"}\n\n' +
1334+ 'data: {"type":"response.output_text.delta","delta":"three"}\n\n' ,
1335+ ) ,
1336+ )
1337+ return
1338+ }
1339+ // Never settles: the next pull is where the between-pulls check must fire.
1340+ return new Promise < void > ( ( ) => { } )
1341+ } ,
1342+ } )
1343+ return Promise . resolve ( { ok : true , body } )
1344+ } )
1345+ global . fetch = mockFetch as typeof fetch
1346+
1347+ const signalController = new AbortController ( )
1348+ const stream = handler . createMessage (
1349+ systemPrompt ,
1350+ messages ,
1351+ makeCreateMessageMetadata ( { abortSignal : signalController . signal } ) ,
1352+ )
1353+ const iterator = stream [ Symbol . asyncIterator ] ( )
1354+ const one = await iterator . next ( )
1355+ expect ( one . value ) . toMatchObject ( { type : "text" , text : "one" } )
1356+ signalController . abort ( )
1357+ // The rest of the batch was already pulled, so the declared bound hands it out.
1358+ const two = await iterator . next ( )
1359+ expect ( two . done ) . toBe ( false )
1360+ expect ( two . value ) . toMatchObject ( { type : "text" , text : "two" } )
1361+ const three = await iterator . next ( )
1362+ expect ( three . done ) . toBe ( false )
1363+ expect ( three . value ) . toMatchObject ( { type : "text" , text : "three" } )
1364+ // Only the next pull is a cancellation point.
1365+ await expect ( iterator . next ( ) ) . rejects . toMatchObject ( {
1366+ name : "AbortError" ,
1367+ message : "The OpenAI Native request was aborted" ,
1368+ } )
1369+ expect ( mockCaptureException ) . not . toHaveBeenCalled ( )
1370+ } )
1371+
12121372 it ( "should not convert a non-abort stream error into an AbortError and keeps the full wrapper" , async ( ) => {
12131373 mockResponsesCreate . mockRejectedValue ( new Error ( "SDK not available" ) )
12141374 const mockFetch = vitest . fn ( ) . mockImplementation ( ( ) => {
@@ -1542,6 +1702,45 @@ describe("OpenAiNativeHandler", () => {
15421702 expect ( mockCaptureException . mock . calls [ 0 ] ?. [ 0 ] ) . toMatchObject ( { operation : "createMessage" } )
15431703 } )
15441704
1705+ it ( "propagates the original SDK error when the abort-race telemetry capture itself throws" , async ( ) => {
1706+ // The capture sits between the status branch and the rethrow, so a throwing telemetry
1707+ // client (or an uninitialized singleton getter) must not become the error the caller
1708+ // sees: the guard contains it and the exact SDK object still propagates.
1709+ const mockFetch = vitest . fn ( )
1710+ global . fetch = mockFetch as typeof fetch
1711+ const controller = new AbortController ( )
1712+ const rateLimited = Object . assign ( new Error ( "Rate limit exceeded" ) , { status : 429 } )
1713+ mockResponsesCreate . mockImplementation ( ( _body : unknown , options : { signal ?: AbortSignal } ) => {
1714+ return new Promise ( ( _resolve , reject ) => {
1715+ options ?. signal ?. addEventListener ( "abort" , ( ) => reject ( rateLimited ) , { once : true } )
1716+ } )
1717+ } )
1718+ // Force the guarded path: the capture throws once, on the way to the rethrow.
1719+ mockCaptureException . mockImplementationOnce ( ( ) => {
1720+ throw new Error ( "Telemetry client unavailable" )
1721+ } )
1722+
1723+ const collected = collectStream (
1724+ handler . createMessage (
1725+ systemPrompt ,
1726+ messages ,
1727+ makeCreateMessageMetadata ( { abortSignal : controller . signal } ) ,
1728+ ) ,
1729+ )
1730+ await tick ( )
1731+ controller . abort ( )
1732+
1733+ const error = await collected . then (
1734+ ( ) => undefined ,
1735+ ( e : unknown ) => e ,
1736+ )
1737+ // Not the telemetry failure and not a wrapper: the SDK object retry needs to read.
1738+ expect ( error ) . toBe ( rateLimited )
1739+ // Containment is not suppression: the failure still has to be reported.
1740+ expect ( mockCaptureException ) . toHaveBeenCalledTimes ( 1 )
1741+ expect ( mockFetch ) . not . toHaveBeenCalled ( )
1742+ } )
1743+
15451744 it ( "keeps the provider's own error text out of the abort-race telemetry capture" , async ( ) => {
15461745 // A 400 body can echo request content — an address, a prompt fragment — and the
15471746 // telemetry client forwards error.message to PostHog, so an abort-raced failure
0 commit comments