|
| 1 | +import { createSseByteGuard } from "./sse-byte-guard.js"; |
1 | 2 | // Ollama tests cover stream runtime plugin behavior. |
2 | 3 | import { afterEach, describe, expect, it, vi } from "vitest"; |
3 | 4 |
|
@@ -1603,6 +1604,182 @@ describe("parseNdjsonStream", () => { |
1603 | 1604 | }); |
1604 | 1605 | }); |
1605 | 1606 |
|
| 1607 | +describe("parseNdjsonStream bounded read (16 MiB cap)", () => { |
| 1608 | + // Layer 1: inline deterministic overflow. 32 × 1 MiB chunks advertised by a |
| 1609 | + // fake pull stream. The wrapped reader must cancel and throw the canonical |
| 1610 | + // overflow error after ~16 MiB, long before the full 32 MiB is drained. |
| 1611 | + it("cancels and throws when bytes exceed 16 MiB", async () => { |
| 1612 | + const CHUNK = 1024 * 1024; // 1 MiB |
| 1613 | + const TOTAL_CHUNKS = 32; // 32 MiB server-side |
| 1614 | + let pullCount = 0; |
| 1615 | + let cancelReason: unknown; |
| 1616 | + const overflowing = new ReadableStream<Uint8Array>({ |
| 1617 | + pull(controller) { |
| 1618 | + pullCount += 1; |
| 1619 | + if (pullCount > TOTAL_CHUNKS) { |
| 1620 | + controller.close(); |
| 1621 | + return; |
| 1622 | + } |
| 1623 | + controller.enqueue(new Uint8Array(CHUNK)); |
| 1624 | + }, |
| 1625 | + cancel(reason) { |
| 1626 | + cancelReason = reason; |
| 1627 | + }, |
| 1628 | + }); |
| 1629 | + const guarded = createSseByteGuard(overflowing.getReader(), { |
| 1630 | + maxBytes: 16 * 1024 * 1024, |
| 1631 | + onOverflow: ({ size, maxBytes }) => |
| 1632 | + new Error(`Ollama streaming body exceeded ${maxBytes} bytes (received ${size})`), |
| 1633 | + }); |
| 1634 | + |
| 1635 | + let thrown: Error | undefined; |
| 1636 | + try { |
| 1637 | + for await (const _ of parseNdjsonStream(guarded)) { |
| 1638 | + // exhaust — overflow must fire on the read that crosses 16 MiB |
| 1639 | + } |
| 1640 | + } catch (err) { |
| 1641 | + thrown = err as Error; |
| 1642 | + } |
| 1643 | + |
| 1644 | + expect(thrown).toBeInstanceOf(Error); |
| 1645 | + expect(thrown?.message).toMatch( |
| 1646 | + /^Ollama streaming body exceeded 16777216 bytes \(received \d+\)$/, |
| 1647 | + ); |
| 1648 | + // pullCount must be capped somewhere in [17, 20]: 16 MiB exact cap leaves |
| 1649 | + // room for one in-flight chunk read plus one TCP-coalesced tail. |
| 1650 | + expect(pullCount).toBeGreaterThanOrEqual(17); |
| 1651 | + expect(pullCount).toBeLessThanOrEqual(20); |
| 1652 | + expect(cancelReason).toBeInstanceOf(Error); |
| 1653 | + expect(guarded.overflowed()).toBe(true); |
| 1654 | + expect(guarded.cancelled()).toBe(true); |
| 1655 | + }); |
| 1656 | + |
| 1657 | + // Layer 2: negative control. A small valid NDJSON response must drain |
| 1658 | + // end-to-end without overflow. Proves the cap is the cause of rejection, |
| 1659 | + // not body structure. |
| 1660 | + it("drains small valid NDJSON without overflow", async () => { |
| 1661 | + const lines = [ |
| 1662 | + '{"model":"m","created_at":"t","message":{"role":"assistant","content":"hello"},"done":false}', |
| 1663 | + '{"model":"m","created_at":"t","message":{"role":"assistant","content":""},"done":true,"prompt_eval_count":5,"eval_count":2}', |
| 1664 | + ]; |
| 1665 | + const reader = mockNdjsonReader(lines); |
| 1666 | + const guarded = createSseByteGuard(reader, { |
| 1667 | + maxBytes: 16 * 1024 * 1024, |
| 1668 | + onOverflow: ({ size, maxBytes }) => |
| 1669 | + new Error(`Ollama streaming body exceeded ${maxBytes} bytes (received ${size})`), |
| 1670 | + }); |
| 1671 | + |
| 1672 | + const chunks = []; |
| 1673 | + for await (const chunk of parseNdjsonStream(guarded)) { |
| 1674 | + chunks.push(chunk); |
| 1675 | + } |
| 1676 | + expect(chunks).toHaveLength(2); |
| 1677 | + expect(chunks[1].done).toBe(true); |
| 1678 | + expect(guarded.totalBytes()).toBeLessThan(16 * 1024 * 1024); |
| 1679 | + expect(guarded.overflowed()).toBe(false); |
| 1680 | + }); |
| 1681 | + |
| 1682 | + // Layer 3: loopback http.createServer real-wire proof. Drives the |
| 1683 | + // production `createSseByteGuard` over a real TCP socket. Server streams |
| 1684 | + // unbounded 1 MiB chunks with no newline terminator; client overflows at |
| 1685 | + // 16 MiB and observes the same canonical error message. |
| 1686 | + it("bounds real TCP-streamed NDJSON body without content-length", async () => { |
| 1687 | + const { createServer } = await import("node:http"); |
| 1688 | + type AddressInfo = { address: string; family: string; port: number }; |
| 1689 | + const CHUNK = 1024 * 1024; |
| 1690 | + const TOTAL_CHUNKS = 64; |
| 1691 | + let bytesSent = 0; |
| 1692 | + let aborted = false; |
| 1693 | + |
| 1694 | + const server = createServer((req, res) => { |
| 1695 | + res.writeHead(200, { |
| 1696 | + "Content-Type": "application/x-ndjson", |
| 1697 | + "Transfer-Encoding": "chunked", |
| 1698 | + }); |
| 1699 | + let i = 0; |
| 1700 | + const interval = setInterval(() => { |
| 1701 | + if (aborted || i >= TOTAL_CHUNKS) { |
| 1702 | + clearInterval(interval); |
| 1703 | + res.end(); |
| 1704 | + return; |
| 1705 | + } |
| 1706 | + i += 1; |
| 1707 | + bytesSent += CHUNK; |
| 1708 | + res.write(new Uint8Array(CHUNK)); |
| 1709 | + }, 1); |
| 1710 | + req.on("close", () => { |
| 1711 | + aborted = true; |
| 1712 | + clearInterval(interval); |
| 1713 | + }); |
| 1714 | + }); |
| 1715 | + |
| 1716 | + await new Promise<void>((resolve) => { |
| 1717 | + server.listen(0, "127.0.0.1", () => resolve()); |
| 1718 | + }); |
| 1719 | + const address = server.address() as AddressInfo; |
| 1720 | + const port = address.port; |
| 1721 | + |
| 1722 | + try { |
| 1723 | + const response = await fetch(`http://127.0.0.1:${port}/api/chat`, { |
| 1724 | + method: "POST", |
| 1725 | + body: "{}", |
| 1726 | + }); |
| 1727 | + if (!response.body) { |
| 1728 | + throw new Error("loopback test setup: empty response body"); |
| 1729 | + } |
| 1730 | + const guarded = createSseByteGuard(response.body.getReader(), { |
| 1731 | + maxBytes: 16 * 1024 * 1024, |
| 1732 | + onOverflow: ({ size, maxBytes }) => |
| 1733 | + new Error(`Ollama streaming body exceeded ${maxBytes} bytes (received ${size})`), |
| 1734 | + }); |
| 1735 | + |
| 1736 | + let thrown: Error | undefined; |
| 1737 | + let totalRead = 0; |
| 1738 | + try { |
| 1739 | + // Keep reading until overflow throws or stream closes. Don't cap the |
| 1740 | + // read count; trust the server will cancel once the cap fires. |
| 1741 | + while (true) { |
| 1742 | + const result = await guarded.read(); |
| 1743 | + if (result.done) { |
| 1744 | + break; |
| 1745 | + } |
| 1746 | + totalRead += result.value.byteLength; |
| 1747 | + } |
| 1748 | + } catch (err) { |
| 1749 | + thrown = err as Error; |
| 1750 | + } |
| 1751 | + |
| 1752 | + // Print quantitative read-out for PR body evidence. |
| 1753 | + console.log( |
| 1754 | + `[layer3 loopback proof] cap=16777216, totalRead=${totalRead}, bytesSent=${bytesSent}, overflowed=${guarded.overflowed()}, cancelled=${guarded.cancelled()}, receivedBytes=${thrown?.message.match(/received (\d+)/)?.[1] ?? "?"}`, |
| 1755 | + ); |
| 1756 | + |
| 1757 | + expect(thrown).toBeInstanceOf(Error); |
| 1758 | + expect(thrown?.message).toMatch( |
| 1759 | + /^Ollama streaming body exceeded 16777216 bytes \(received \d+\)$/, |
| 1760 | + ); |
| 1761 | + // The cap fires when `total + chunkLen > cap`. The thrown error's |
| 1762 | + // `size` is that crossed value, so receivedBytes is strictly > cap. |
| 1763 | + // totalRead is the sum of chunks actually returned (none cross cap), |
| 1764 | + // so totalRead <= cap. bytesSent is what the server kept writing |
| 1765 | + // before our cancel propagated, so bytesSent > totalRead. |
| 1766 | + const receivedMatch = thrown?.message.match(/received (\d+)/); |
| 1767 | + const receivedBytes = receivedMatch ? Number(receivedMatch[1]) : 0; |
| 1768 | + expect(receivedBytes).toBeGreaterThan(16 * 1024 * 1024); |
| 1769 | + expect(totalRead).toBeLessThanOrEqual(16 * 1024 * 1024); |
| 1770 | + expect(totalRead).toBeLessThan(bytesSent); |
| 1771 | + expect(bytesSent).toBeLessThanOrEqual(TOTAL_CHUNKS * CHUNK); |
| 1772 | + expect(guarded.overflowed()).toBe(true); |
| 1773 | + expect(guarded.cancelled()).toBe(true); |
| 1774 | + } finally { |
| 1775 | + aborted = true; |
| 1776 | + await new Promise<void>((resolve) => { |
| 1777 | + server.close(() => resolve()); |
| 1778 | + }); |
| 1779 | + } |
| 1780 | + }); |
| 1781 | +}); |
| 1782 | + |
1606 | 1783 | async function withMockNdjsonFetch( |
1607 | 1784 | lines: string[], |
1608 | 1785 | run: (fetchMock: typeof fetchWithSsrFGuardMock) => Promise<void>, |
|
0 commit comments