[GH-ISSUE #4690] [GUI] Completed /v1 streams are logged as failed ("Request cancelled.") when the client closes at [DONE] #2142

Closed
opened 2026-11-04 01:57:00 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @gunesdogan382 on GitHub (Oct 30, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/4690

Area

[GUI] (the desktop app)

Desktop app, Terminal or source?

Desktop app (Windows, Linux or Mac)

What happened

A client using the OpenAI Python SDK (Hermes Agent, OpenAI/Python 2.24.0) talks to the app's /v1/chat/completions. On the API server page most of its requests show as failed, with input tokens "—" and "usage not available". The client received these answers completely and carried on working.

GET /api/serving, two non-overlapping snapshots for that client (the list keeps 60 requests), 103 finished requests:

  • 22 are done, all with tokensIn.
  • 81 are error, all with the text Request cancelled., none with tokensIn.
  • 73 of the 81 have output tokens. All 73 have a matching completed call in the client's own log (same output token count, latency within 1 s).
  • The other 8 have no output tokens. I checked 3 of them and those are real client aborts (a 30 s timeout on a background title request, twice, and a job the client interrupted). I did not check the other 5.

In the first snapshot's run (IQ3_S, 38 of the 73), the engine log has no (cancelled) line at all.

The share of false errors grows with the prompt size. Finished requests with output tokens, both snapshots, input tokens from the client's log:

prompt tokens | done | error
under 20,000  |   13 |     1
20,000-40,000 |    3 |    19
40,000-80,000 |    5 |    28
over 80,000   |    1 |    25

Expected: a stream that reached its end is logged as done, with its usage. The answers themselves are not affected. What is wrong is the request log and the completed / failed counters.

The path, read from the source and confirmed by the reproduction below:

  1. apps/host/server/native-gateway.mjs only calls res.end() after the upstream body has ended, and res.on('close') aborts when !res.writableEnded.
  2. serve/server.py answers with HTTP/1.0 and ends an SSE stream by closing the connection, after it has written data: [DONE].
  3. The OpenAI SDK stops reading at [DONE] and calls response.close() (openai/_streaming.py). That closes the socket, because the gateway's chunked body has not ended yet.
  4. If that close arrives before the gateway has seen the upstream end, the request is aborted and the catch records Request cancelled. That branch only passes tokensOut, which is where the "—" and unavailable come from.

Smallest steps or command that reproduce it

Without a GPU. The script below drives the real nativeGateway with a fake engine and a raw socket client, 20 runs per line. The client received the whole stream in every run (the script throws otherwise). Run from apps/host: node repro.mjs

close delay | client                 | done | error | last record
       0 ms | reads to end of stream |   20 |     0 | state=done error=- tokensIn=12 tokensOut=3
       0 ms | hangs up at [DONE]     |    8 |    12 | state=done error=- tokensIn=12 tokensOut=3
       1 ms | reads to end of stream |   20 |     0 | state=done error=- tokensIn=12 tokensOut=3
       1 ms | hangs up at [DONE]     |    9 |    11 | state=error error=Request cancelled. tokensIn=null tokensOut=3
       5 ms | reads to end of stream |   20 |     0 | state=done error=- tokensIn=12 tokensOut=3
       5 ms | hangs up at [DONE]     |    0 |    20 | state=error error=Request cancelled. tokensIn=null tokensOut=3
      20 ms | reads to end of stream |   20 |     0 | state=done error=- tokensIn=12 tokensOut=3
      20 ms | hangs up at [DONE]     |    0 |    20 | state=error error=Request cancelled. tokensIn=null tokensOut=3
      50 ms | reads to end of stream |   20 |     0 | state=done error=- tokensIn=12 tokensOut=3
      50 ms | hangs up at [DONE]     |    0 |    20 | state=error error=Request cancelled. tokensIn=null tokensOut=3
repro.mjs
// A completed stream is logged as failed when the client hangs up right after `data: [DONE]`.
// No GPU needed: a fake engine, the real nativeGateway and a raw-socket client.
// Usage: node repro.mjs [path/to/native-gateway.mjs]   (default: server/native-gateway.mjs, run from apps/host)
import http from 'node:http';
import net from 'node:net';
import path from 'node:path';
import {pathToFileURL} from 'node:url';

const file = path.resolve(process.argv[2] ?? 'server/native-gateway.mjs');
const {nativeGateway} = await import(pathToFileURL(file).href);
const listen = server => new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve(server.address().port)));
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

let closeDelay = 0;   // time between `data: [DONE]` and the engine closing its connection
const engine = http.createServer(async (req, res) => {
  for await (const _ of req);
  res.writeHead(200, {'content-type': 'text/event-stream', connection: 'close'});
  res.write('data: {"choices":[{"delta":{"content":"Hi"}}]}\n\n');
  res.write('data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":3}}\n\n');
  res.write('data: [DONE]\n\n');
  await sleep(closeDelay);
  res.end();
});
const enginePort = await listen(engine);

const records = [];
const serving = {
  open: value => { const record = {id: records.length, state: 'queued', tokensIn: null, tokensOut: null, ...value}; records.push(record); return record; },
  mark: (id, value) => Object.assign(records[id], value),
  finish: (id, {tokensOut, error}) => Object.assign(records[id], {state: error ? 'error' : 'done', tokensOut, error}),
};
const control = {resolveInstance: () => ({id: 'x', apiModelId: 'x', port: enginePort, key: 'k', gpus: [0]})};
const gateway = http.createServer(async (req, res) => {
  let text = '';
  for await (const chunk of req) text += chunk;
  await nativeGateway({req, res, path: req.url, body: JSON.parse(text), control, serving});
});
const gatewayPort = await listen(gateway);

function call(hangUpAtDone) {
  return new Promise(resolve => {
    const body = JSON.stringify({model: 'x', stream: true, messages: []});
    const socket = net.connect(gatewayPort, '127.0.0.1', () => socket.write(
      `POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`));
    let text = '';
    socket.on('data', data => { text += data; if (hangUpAtDone && text.includes('data: [DONE]')) socket.destroy(); });
    socket.on('close', () => resolve(text));
  });
}

const RUNS = 20;
console.log('close delay | client                 | done | error | last record');
for (const delay of [0, 1, 5, 20, 50]) {
  closeDelay = delay;
  for (const hangUp of [false, true]) {
    let done = 0, failed = 0, last;
    for (let run = 0; run < RUNS; run++) {
      const received = await call(hangUp);
      if (!received.includes('data: [DONE]')) throw new Error('client did not receive the whole stream');
      const record = records.at(-1);
      for (let wait = 0; wait < 100 && !['done', 'error'].includes(record.state); wait++) await sleep(5);
      if (record.state === 'done') done++; else failed++;
      last = record;
    }
    const client = hangUp ? 'hangs up at [DONE]' : 'reads to end of stream';
    console.log(`${String(delay).padStart(8)} ms | ${client.padEnd(22)} | ${String(done).padStart(4)} | ${String(failed).padStart(5)} | ` +
      `state=${last.state} error=${last.error ?? '-'} tokensIn=${last.tokensIn} tokensOut=${last.tokensOut}`);
  }
}
gateway.closeAllConnections(); gateway.close(); engine.closeAllConnections(); engine.close();

Against the running app. A streaming request through /v1/chat/completions with max_tokens: 8 and include_usage, on Unsloth Q8_0, while an agent was also using the model. "Reads to end" is a plain http.client client:

59 prompt tokens (1 message), 3 runs each
  reads to end       : 3 done            [DONE] to end of stream: 0.5-0.6 ms
  OpenAI SDK 2.24.0  : 3 done

47,196 prompt tokens (601 short messages, 20 tools), 3 runs each
  reads to end       : 3 done            [DONE] to end of stream: 0.6-0.9 ms
  OpenAI SDK 2.24.0  : 1 done, 2 error   error="Request cancelled." tokensIn=null tokensOut=8 usageSource=unavailable
                       the SDK received finish_reason=length and usage 47196/8 on all 3 runs

So a small request does not show it, and it is a race. I did not establish why the share grows with the prompt size: the window measured by the reading client barely differs between these two sizes, and this is only 3 runs each.

Reproduction status

Reproduced locally

Strata version

Strata 0.2.3 · engine 0.1.52. Not run on 0.2.8, but native-gateway.mjs is identical on v0.2.8 and main (file compared), and serve/server.py on main still uses HTTP/1.0 for this.

Graphics card, memory and system

RTX 4070 Ti SUPER 16 GB · 64 GB RAM · Windows 11

Model, size and settings

Seen with Qwen3.8-Flash-Next IQ3_S (256K context) and Unsloth Q8_0 (128K context), pictures on.

Logs

One request as seen by all three parts, from the IQ3_S run (IDs removed):

/api/serving  state=error error="Request cancelled." tokensIn=null tokensOut=103 duration=42.2s usageSource=unavailable
engine log    strata serve: prompt 48090 tokens = 13942 reused + 34148 read in 11765 ms (2902.6 tok/s), 103 generated in 1622 ms (63.5 tok/s), drafts accepted 65 of 83, 3 checkpoints
client log    API call #9: model=iq3_s provider=custom in=48090 out=103 total=48193 latency=42.2s cache=13942/48090 (29%)

Possible fix

A change I tried on a copy of the file only: once the protocol's last event has been forwarded, a client that leaves is no longer a cancellation.

+const TERMINAL=/^(data: ?\[DONE\]|event: ?(message_stop|response\.(completed|failed|incomplete)))\s*$/;
-started=Date.now();res.on('close',()=>{if(!res.writableEnded)abort.abort();});
+started=Date.now();let complete=false;res.on('close',()=>{if(!res.writableEnded&&!complete)abort.abort();});
-buffer=buffer.slice(end+1);if(line.startsWith('data:'))
+buffer=buffer.slice(end+1);if(TERMINAL.test(line))complete=true;if(line.startsWith('data:'))
-if(!res.write(chunk))await once(res,'drain',{signal:abort.signal});
+if(!res.destroyed&&!res.write(chunk)&&!complete)await once(res,'drain',{signal:abort.signal});
  • Passed: repro.mjs against the changed copy gives 20 of 20 done with tokensIn=12 on every line. tests/native-gateway.test.mjs passes with and without the change.
  • Not run: the app with this change, /v1/messages and /v1/responses against a real engine, the rest of the test suite.

#4678 shows the same tokensIn: null and usageSource: "unavailable" on done entries of the app's own chat. That looks like a different code path (client: 'Strata chat' in index.mjs, not this gateway), so I kept this report separate.

This report was investigated and written by an AI agent (Claude Code) for the account owner. All numbers come from the commands and logs shown here.

Originally created by @gunesdogan382 on GitHub (Oct 30, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/4690 ### Area [GUI] (the desktop app) ### Desktop app, Terminal or source? Desktop app (Windows, Linux or Mac) ### What happened A client using the OpenAI Python SDK (Hermes Agent, `OpenAI/Python 2.24.0`) talks to the app's `/v1/chat/completions`. On the API server page most of its requests show as failed, with input tokens "—" and "usage not available". The client received these answers completely and carried on working. `GET /api/serving`, two non-overlapping snapshots for that client (the list keeps 60 requests), 103 finished requests: - 22 are `done`, all with `tokensIn`. - 81 are `error`, all with the text `Request cancelled.`, none with `tokensIn`. - 73 of the 81 have output tokens. All 73 have a matching completed call in the client's own log (same output token count, latency within 1 s). - The other 8 have no output tokens. I checked 3 of them and those are real client aborts (a 30 s timeout on a background title request, twice, and a job the client interrupted). I did not check the other 5. In the first snapshot's run (IQ3_S, 38 of the 73), the engine log has no `(cancelled)` line at all. The share of false errors grows with the prompt size. Finished requests with output tokens, both snapshots, input tokens from the client's log: ```text prompt tokens | done | error under 20,000 | 13 | 1 20,000-40,000 | 3 | 19 40,000-80,000 | 5 | 28 over 80,000 | 1 | 25 ``` Expected: a stream that reached its end is logged as `done`, with its usage. The answers themselves are not affected. What is wrong is the request log and the `completed` / `failed` counters. The path, read from the source and confirmed by the reproduction below: 1. `apps/host/server/native-gateway.mjs` only calls `res.end()` after the upstream body has ended, and `res.on('close')` aborts when `!res.writableEnded`. 2. `serve/server.py` answers with HTTP/1.0 and ends an SSE stream by closing the connection, after it has written `data: [DONE]`. 3. The OpenAI SDK stops reading at `[DONE]` and calls `response.close()` (`openai/_streaming.py`). That closes the socket, because the gateway's chunked body has not ended yet. 4. If that close arrives before the gateway has seen the upstream end, the request is aborted and the `catch` records `Request cancelled.` That branch only passes `tokensOut`, which is where the "—" and `unavailable` come from. ### Smallest steps or command that reproduce it **Without a GPU.** The script below drives the real `nativeGateway` with a fake engine and a raw socket client, 20 runs per line. The client received the whole stream in every run (the script throws otherwise). Run from `apps/host`: `node repro.mjs` ```text close delay | client | done | error | last record 0 ms | reads to end of stream | 20 | 0 | state=done error=- tokensIn=12 tokensOut=3 0 ms | hangs up at [DONE] | 8 | 12 | state=done error=- tokensIn=12 tokensOut=3 1 ms | reads to end of stream | 20 | 0 | state=done error=- tokensIn=12 tokensOut=3 1 ms | hangs up at [DONE] | 9 | 11 | state=error error=Request cancelled. tokensIn=null tokensOut=3 5 ms | reads to end of stream | 20 | 0 | state=done error=- tokensIn=12 tokensOut=3 5 ms | hangs up at [DONE] | 0 | 20 | state=error error=Request cancelled. tokensIn=null tokensOut=3 20 ms | reads to end of stream | 20 | 0 | state=done error=- tokensIn=12 tokensOut=3 20 ms | hangs up at [DONE] | 0 | 20 | state=error error=Request cancelled. tokensIn=null tokensOut=3 50 ms | reads to end of stream | 20 | 0 | state=done error=- tokensIn=12 tokensOut=3 50 ms | hangs up at [DONE] | 0 | 20 | state=error error=Request cancelled. tokensIn=null tokensOut=3 ``` <details><summary>repro.mjs</summary> ```js // A completed stream is logged as failed when the client hangs up right after `data: [DONE]`. // No GPU needed: a fake engine, the real nativeGateway and a raw-socket client. // Usage: node repro.mjs [path/to/native-gateway.mjs] (default: server/native-gateway.mjs, run from apps/host) import http from 'node:http'; import net from 'node:net'; import path from 'node:path'; import {pathToFileURL} from 'node:url'; const file = path.resolve(process.argv[2] ?? 'server/native-gateway.mjs'); const {nativeGateway} = await import(pathToFileURL(file).href); const listen = server => new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve(server.address().port))); const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); let closeDelay = 0; // time between `data: [DONE]` and the engine closing its connection const engine = http.createServer(async (req, res) => { for await (const _ of req); res.writeHead(200, {'content-type': 'text/event-stream', connection: 'close'}); res.write('data: {"choices":[{"delta":{"content":"Hi"}}]}\n\n'); res.write('data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":3}}\n\n'); res.write('data: [DONE]\n\n'); await sleep(closeDelay); res.end(); }); const enginePort = await listen(engine); const records = []; const serving = { open: value => { const record = {id: records.length, state: 'queued', tokensIn: null, tokensOut: null, ...value}; records.push(record); return record; }, mark: (id, value) => Object.assign(records[id], value), finish: (id, {tokensOut, error}) => Object.assign(records[id], {state: error ? 'error' : 'done', tokensOut, error}), }; const control = {resolveInstance: () => ({id: 'x', apiModelId: 'x', port: enginePort, key: 'k', gpus: [0]})}; const gateway = http.createServer(async (req, res) => { let text = ''; for await (const chunk of req) text += chunk; await nativeGateway({req, res, path: req.url, body: JSON.parse(text), control, serving}); }); const gatewayPort = await listen(gateway); function call(hangUpAtDone) { return new Promise(resolve => { const body = JSON.stringify({model: 'x', stream: true, messages: []}); const socket = net.connect(gatewayPort, '127.0.0.1', () => socket.write( `POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`)); let text = ''; socket.on('data', data => { text += data; if (hangUpAtDone && text.includes('data: [DONE]')) socket.destroy(); }); socket.on('close', () => resolve(text)); }); } const RUNS = 20; console.log('close delay | client | done | error | last record'); for (const delay of [0, 1, 5, 20, 50]) { closeDelay = delay; for (const hangUp of [false, true]) { let done = 0, failed = 0, last; for (let run = 0; run < RUNS; run++) { const received = await call(hangUp); if (!received.includes('data: [DONE]')) throw new Error('client did not receive the whole stream'); const record = records.at(-1); for (let wait = 0; wait < 100 && !['done', 'error'].includes(record.state); wait++) await sleep(5); if (record.state === 'done') done++; else failed++; last = record; } const client = hangUp ? 'hangs up at [DONE]' : 'reads to end of stream'; console.log(`${String(delay).padStart(8)} ms | ${client.padEnd(22)} | ${String(done).padStart(4)} | ${String(failed).padStart(5)} | ` + `state=${last.state} error=${last.error ?? '-'} tokensIn=${last.tokensIn} tokensOut=${last.tokensOut}`); } } gateway.closeAllConnections(); gateway.close(); engine.closeAllConnections(); engine.close(); ``` </details> **Against the running app.** A streaming request through `/v1/chat/completions` with `max_tokens: 8` and `include_usage`, on Unsloth Q8_0, while an agent was also using the model. "Reads to end" is a plain `http.client` client: ```text 59 prompt tokens (1 message), 3 runs each reads to end : 3 done [DONE] to end of stream: 0.5-0.6 ms OpenAI SDK 2.24.0 : 3 done 47,196 prompt tokens (601 short messages, 20 tools), 3 runs each reads to end : 3 done [DONE] to end of stream: 0.6-0.9 ms OpenAI SDK 2.24.0 : 1 done, 2 error error="Request cancelled." tokensIn=null tokensOut=8 usageSource=unavailable the SDK received finish_reason=length and usage 47196/8 on all 3 runs ``` So a small request does not show it, and it is a race. I did not establish why the share grows with the prompt size: the window measured by the reading client barely differs between these two sizes, and this is only 3 runs each. ### Reproduction status Reproduced locally ### Strata version Strata 0.2.3 · engine 0.1.52. Not run on 0.2.8, but `native-gateway.mjs` is identical on `v0.2.8` and `main` (file compared), and `serve/server.py` on `main` still uses HTTP/1.0 for this. ### Graphics card, memory and system RTX 4070 Ti SUPER 16 GB · 64 GB RAM · Windows 11 ### Model, size and settings Seen with Qwen3.8-Flash-Next IQ3_S (256K context) and Unsloth Q8_0 (128K context), pictures on. ### Logs One request as seen by all three parts, from the IQ3_S run (IDs removed): ```text /api/serving state=error error="Request cancelled." tokensIn=null tokensOut=103 duration=42.2s usageSource=unavailable engine log strata serve: prompt 48090 tokens = 13942 reused + 34148 read in 11765 ms (2902.6 tok/s), 103 generated in 1622 ms (63.5 tok/s), drafts accepted 65 of 83, 3 checkpoints client log API call #9: model=iq3_s provider=custom in=48090 out=103 total=48193 latency=42.2s cache=13942/48090 (29%) ``` ### Possible fix A change I tried on a copy of the file only: once the protocol's last event has been forwarded, a client that leaves is no longer a cancellation. ```diff +const TERMINAL=/^(data: ?\[DONE\]|event: ?(message_stop|response\.(completed|failed|incomplete)))\s*$/; -started=Date.now();res.on('close',()=>{if(!res.writableEnded)abort.abort();}); +started=Date.now();let complete=false;res.on('close',()=>{if(!res.writableEnded&&!complete)abort.abort();}); -buffer=buffer.slice(end+1);if(line.startsWith('data:')) +buffer=buffer.slice(end+1);if(TERMINAL.test(line))complete=true;if(line.startsWith('data:')) -if(!res.write(chunk))await once(res,'drain',{signal:abort.signal}); +if(!res.destroyed&&!res.write(chunk)&&!complete)await once(res,'drain',{signal:abort.signal}); ``` - Passed: `repro.mjs` against the changed copy gives 20 of 20 `done` with `tokensIn=12` on every line. `tests/native-gateway.test.mjs` passes with and without the change. - Not run: the app with this change, `/v1/messages` and `/v1/responses` against a real engine, the rest of the test suite. ### Related #4678 shows the same `tokensIn: null` and `usageSource: "unavailable"` on `done` entries of the app's own chat. That looks like a different code path (`client: 'Strata chat'` in `index.mjs`, not this gateway), so I kept this report separate. This report was investigated and written by an AI agent (Claude Code) for the account owner. All numbers come from the commands and logs shown here.
Author
Owner

@Niko1221 commented on GitHub (Oct 31, 2026):

Fixed in 0.2.9: when a client closes the connection right after data: [DONE], the request is logged as done, with its token counts. Your script is now one of our tests. If you still see it on 0.2.9, comment here and we'll reopen.

<!-- gh-comment-id:6541128191 --> @Niko1221 commented on GitHub (Oct 31, 2026): Fixed in [0.2.9](https://github.com/Niko1221/Strata/releases/tag/v0.2.9): when a client closes the connection right after `data: [DONE]`, the request is logged as done, with its token counts. Your script is now one of our tests. If you still see it on 0.2.9, comment here and we'll reopen.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#2142
No description provided.