import { describe, expect, it, vi } from "vitest"; import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts"; import { assertRequestFanoutWithinBudget, RequestFanoutExceededError, } from "../../../src/platform/traffic/request-fanout.ts"; import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts"; import { jsonRows, paginatedCollection, scopeSnapshot, testExecutionContext, testExecutor, type Transport, } from "../../helpers/traffic-test-kit.ts"; const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract< unknown, unknown, unknown >; /** Physical requests one collection load may cost. */ const COLLECTION_LOAD_FANOUT_BUDGET = 1; /** * scale-architecture.md §12 / §41. Feature-neutral fan-out gate over the installed-contract * path; the reference feature's own collection proof lives with the feature. */ async function loadCollection(transport: Transport) { const execution = testExecutionContext({ maxPhysicalRequests: 3 }); const outcome = await testExecutor(transport).execute(TEST_QUERY, { limit: 100 }, { routeId: "TEST_ROUTE", scope: scopeSnapshot(), execution, }); return { outcome, execution }; } describe("request fan-out budget", () => { it.each([10, 50, 100, 1_000])( "loads a page of a %i-row collection with one physical request", async (totalRows) => { const transport = paginatedCollection(totalRows); const { outcome, execution } = await loadCollection(transport); expect(outcome.kind).toBe("SUCCESS"); expect(outcome.kind === "SUCCESS" && outcome.value).toHaveLength(Math.min(totalRows, 100)); expect(execution.traffic.requests.consumed).toBe(transport.calls); expect(() => assertRequestFanoutWithinBudget(transport.calls, COLLECTION_LOAD_FANOUT_BUDGET), ).not.toThrow(); }, ); it("rejects a single oversized response in one request without row-proportional fan-out", async () => { const transport = vi.fn(async () => jsonRows(1_000)); const { outcome } = await loadCollection(transport); expect(outcome.kind).toBe("CONTRACT_VIOLATION"); expect(transport).toHaveBeenCalledTimes(1); }); it("fails loudly when a flow exceeds its fan-out budget", () => { expect(() => assertRequestFanoutWithinBudget(4, 3)).toThrow( RequestFanoutExceededError, ); expect(() => assertRequestFanoutWithinBudget(4, 3)).toThrow( /fan-out 4 exceeds 3/, ); expect(() => assertRequestFanoutWithinBudget(1, 0)).toThrow(TypeError); }); });