okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221apps/host: the owner's UI and the Node App Host0b3299a01

main
7.1 KiB172 linesraw
1/**
2 * Stream framing: partial UTF-8 and split SSE lines must not corrupt output (checklist A02).
3 *
4 * This is the failure mode that looks like a model problem and is actually a decoder problem. A
5 * multi-byte character split across two TCP reads becomes U+FFFD if the decoder is reset per chunk,
6 * and an SSE line split across two reads is dropped or merged if the buffer is not carried. Both
7 * produce answers with mojibake or missing text in them, which is very hard to attribute later.
8 *
9 * The fixture therefore splits at the **byte** level, not at convenient character boundaries, so the
10 * test cannot accidentally pass because the writer happened to split somewhere safe.
11 */
12import test from 'node:test';
13import assert from 'node:assert/strict';
14import http from 'node:http';
15import { mkdtemp, rm } from 'node:fs/promises';
16import { tmpdir } from 'node:os';
17import { join } from 'node:path';
18
19const wait = (ms) => new Promise((r) => setTimeout(r, ms));
20
21async function listen(server) {
22  await new Promise((r) => server.listen(0, '127.0.0.1', r));
23  return server.address().port;
24}
25
26/** An SSE data line carrying one delta. */
27function line(text) {
28  return `data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\n`;
29}
30
31/** Split a UTF-8 string into byte chunks of `n` bytes, so multi-byte characters straddle them. */
32function byteChunks(text, n) {
33  const bytes = Buffer.from(text, 'utf8');
34  const out = [];
35  for (let i = 0; i < bytes.length; i += n) out.push(bytes.subarray(i, i + n));
36  return out;
37}
38
39async function loadCompletion() {
40  const home = await mkdtemp(join(tmpdir(), 'strata-framing-'));
41  process.env.STRATA_HOME = home;
42  process.env.STRATA_MODELS_DIR = join(home, 'models');
43  const { proxyCompletion } = await import('../server/inference.mjs');
44  return { proxyCompletion, home };
45}
46
47test('a multi-byte character split across reads survives intact', async () => {
48  const { proxyCompletion, home } = await loadCompletion();
49  // Every one of these is multi-byte in UTF-8, and several are outside the BMP (4 bytes), so a
50  // chunk boundary can land inside any of them.
51  const wanted = 'héllo — 世界 🌍 日本語 ✅';
52  const payload = line(wanted) + 'data: [DONE]\n\n';
53  const fixture = http.createServer((req, res) => {
54    req.resume();
55    res.writeHead(200, { 'content-type': 'text/event-stream' });
56    // Three bytes at a time: every emoji and every CJK character is straddled.
57    for (const chunk of byteChunks(payload, 3)) res.write(chunk);
58    res.end();
59  });
60  const port = await listen(fixture);
61  try {
62    const frames = [];
63    await proxyCompletion({
64      baseUrl: `http://127.0.0.1:${port}`, message: 'x', onFrame: (f) => frames.push(f),
65      signal: new AbortController().signal,
66    });
67    const text = frames.filter((f) => f.type === 'delta').map((f) => f.text).join('');
68    assert.equal(text, wanted, 'the streamed text must be byte-identical to what was sent');
69    assert.ok(!text.includes('\uFFFD'), 'no replacement character may appear');
70  } finally {
71    await new Promise((r) => fixture.close(r));
72    await rm(home, { recursive: true, force: true });
73  }
74});
75
76test('an SSE line split across reads is reassembled, not dropped', async () => {
77  const { proxyCompletion, home } = await loadCompletion();
78  const fixture = http.createServer((req, res) => {
79    req.resume();
80    res.writeHead(200, { 'content-type': 'text/event-stream' });
81    // Split the JSON mid-object, mid-escape and mid-line, with pauses so the reads really separate.
82    const body = line('alpha') + line('beta') + 'data: [DONE]\n\n';
83    const chunks = byteChunks(body, 7);
84    (async () => {
85      for (const c of chunks) { res.write(c); await wait(2); }
86      res.end();
87    })();
88  });
89  const port = await listen(fixture);
90  try {
91    const frames = [];
92    await proxyCompletion({
93      baseUrl: `http://127.0.0.1:${port}`, message: 'x', onFrame: (f) => frames.push(f),
94      signal: new AbortController().signal,
95    });
96    const text = frames.filter((f) => f.type === 'delta').map((f) => f.text).join('');
97    assert.equal(text, 'alphabeta', 'both deltas must survive the split');
98  } finally {
99    await new Promise((r) => fixture.close(r));
100    await rm(home, { recursive: true, force: true });
101  }
102});
103
104test('a stream that ends without a trailing newline still yields its last delta', async () => {
105  const { proxyCompletion, home } = await loadCompletion();
106  const fixture = http.createServer((req, res) => {
107    req.resume();
108    res.writeHead(200, { 'content-type': 'text/event-stream' });
109    // No trailing blank line: the reader must flush the remaining buffer when the stream ends.
110    res.end(`data: ${JSON.stringify({ choices: [{ delta: { content: 'tail' } }] })}`);
111  });
112  const port = await listen(fixture);
113  try {
114    const frames = [];
115    await proxyCompletion({
116      baseUrl: `http://127.0.0.1:${port}`, message: 'x', onFrame: (f) => frames.push(f),
117      signal: new AbortController().signal,
118    });
119    const text = frames.filter((f) => f.type === 'delta').map((f) => f.text).join('');
120    assert.equal(text, 'tail');
121  } finally {
122    await new Promise((r) => fixture.close(r));
123    await rm(home, { recursive: true, force: true });
124  }
125});
126
127test('a malformed frame is skipped without losing the frames around it', async () => {
128  const { proxyCompletion, home } = await loadCompletion();
129  const fixture = http.createServer((req, res) => {
130    req.resume();
131    res.writeHead(200, { 'content-type': 'text/event-stream' });
132    // A truncated JSON object in the middle. The contract is that it is skipped, not that it
133    // aborts the turn: a provider may emit a partial line and the answer is still usable.
134    res.end(line('before') + 'data: {"choices":[{"delta":{"content":"trunc\n\n' + line('after') + 'data: [DONE]\n\n');
135  });
136  const port = await listen(fixture);
137  try {
138    const frames = [];
139    await proxyCompletion({
140      baseUrl: `http://127.0.0.1:${port}`, message: 'x', onFrame: (f) => frames.push(f),
141      signal: new AbortController().signal,
142    });
143    const text = frames.filter((f) => f.type === 'delta').map((f) => f.text).join('');
144    assert.equal(text, 'beforeafter', 'the good frames on both sides must survive');
145  } finally {
146    await new Promise((r) => fixture.close(r));
147    await rm(home, { recursive: true, force: true });
148  }
149});
150
151test('an error frame is surfaced rather than silently ending the turn', async () => {
152  const { proxyCompletion, home } = await loadCompletion();
153  const fixture = http.createServer((req, res) => {
154    req.resume();
155    res.writeHead(200, { 'content-type': 'text/event-stream' });
156    res.end(`data: ${JSON.stringify({ error: { message: 'the engine refused this request' } })}\n\n`);
157  });
158  const port = await listen(fixture);
159  try {
160    await assert.rejects(
161      () => proxyCompletion({
162        baseUrl: `http://127.0.0.1:${port}`, message: 'x', onFrame: () => {},
163        signal: new AbortController().signal,
164      }),
165      /refused this request/,
166      'an error frame must reach the caller with the provider\'s own words',
167    );
168  } finally {
169    await new Promise((r) => fixture.close(r));
170    await rm(home, { recursive: true, force: true });
171  }
172});