chore: sync the frontend template from ebea300 to af3d8e6

Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
This commit is contained in:
DongHyeonka
2026-11-12 08:28:54 +09:00
parent 585c62431a
commit c80320dfc7
738 changed files with 55027 additions and 13567 deletions
@@ -0,0 +1,94 @@
import { describe, expect, it } from "vitest";
import {
ConcurrencyQueueFullError,
createConcurrencyBudget,
} from "../../../src/platform/traffic/concurrency-budget.ts";
const live = () => new AbortController().signal;
describe("createConcurrencyBudget", () => {
it("never grants more than maximum simultaneous leases", async () => {
const budget = createConcurrencyBudget({ maximum: 2, maxQueued: 1 });
const first = await budget.acquire(live());
const second = await budget.acquire(live());
expect(budget.active).toBe(2);
const queued = budget.acquire(live());
expect(budget.queued).toBe(1);
await expect(budget.acquire(live())).rejects.toThrow(/queue/i);
await expect(budget.acquire(live())).rejects.toBeInstanceOf(
ConcurrencyQueueFullError,
);
first.release();
const third = await queued;
expect(budget.active).toBe(2);
second.release();
third.release();
expect(budget.active).toBe(0);
});
it("removes an aborted waiter", async () => {
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 1 });
const lease = await budget.acquire(live());
const controller = new AbortController();
const waiting = budget.acquire(controller.signal);
controller.abort();
await expect(waiting).rejects.toMatchObject({ name: "AbortError" });
expect(budget.queued).toBe(0);
lease.release();
expect(budget.active).toBe(0);
});
it("rejects immediately when the signal is already aborted", async () => {
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 1 });
const controller = new AbortController();
controller.abort();
await expect(budget.acquire(controller.signal)).rejects.toMatchObject({
name: "AbortError",
});
expect(budget.active).toBe(0);
});
it("grants waiters in FIFO order", async () => {
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 3 });
const holder = await budget.acquire(live());
const order: string[] = [];
const a = budget.acquire(live()).then((lease) => {
order.push("a");
return lease;
});
const b = budget.acquire(live()).then((lease) => {
order.push("b");
return lease;
});
holder.release();
(await a).release();
(await b).release();
expect(order).toEqual(["a", "b"]);
});
it("treats release as idempotent", async () => {
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 0 });
const lease = await budget.acquire(live());
lease.release();
lease.release();
expect(budget.active).toBe(0);
const again = await budget.acquire(live());
await expect(budget.acquire(live())).rejects.toBeInstanceOf(
ConcurrencyQueueFullError,
);
again.release();
});
it("rejects an unbounded configuration", () => {
expect(() =>
createConcurrencyBudget({ maximum: 1, maxQueued: Number.POSITIVE_INFINITY }),
).toThrow(TypeError);
expect(() => createConcurrencyBudget({ maximum: 0, maxQueued: 1 })).toThrow(
TypeError,
);
});
});
@@ -0,0 +1,244 @@
import { describe, expect, it, vi } from "vitest";
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
import {
TEST_CREATE_HTTP_CONTRACT,
TEST_LIST_HTTP_CONTRACT,
} from "../../helpers/external-contract-fixture.ts";
import {
jsonRows,
manualClock,
networkFailure,
scopeSnapshot,
testExecutionContext,
testExecutor,
type Transport,
} from "../../helpers/traffic-test-kit.ts";
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
unknown,
unknown,
unknown
>;
const TEST_COMMAND = TEST_CREATE_HTTP_CONTRACT as InstalledHttpContract<
unknown,
unknown,
unknown
>;
const ROUTE_ID = "TEST_ROUTE";
/** A transport that only ever ends when its request is aborted. */
function hangingTransport(): Transport & { calls: number } {
const transport = ((_input: RequestInfo | URL, init?: RequestInit) => {
transport.calls += 1;
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
"abort",
() => reject(new DOMException("aborted", "AbortError")),
{ once: true },
);
});
}) as Transport & { calls: number };
transport.calls = 0;
return transport;
}
describe("HTTP dispatch under interaction traffic budgets", () => {
it("does not dispatch after the interaction physical-request budget is exhausted", async () => {
const transport = vi.fn<Transport>(networkFailure);
const execution = testExecutionContext({
maxPhysicalRequests: 1,
maxRetries: 3,
});
const outcome = await testExecutor(transport).execute(TEST_QUERY, { limit: 5 }, {
routeId: ROUTE_ID,
scope: scopeSnapshot(),
execution,
});
expect(outcome.kind).toBe("TRANSPORT_FAILURE");
expect(transport).toHaveBeenCalledTimes(1);
expect(execution.traffic.requests.consumed).toBe(1);
});
it("rejects a second operation once the shared request budget is gone", async () => {
const transport = vi.fn<Transport>(networkFailure);
const execution = testExecutionContext({
maxPhysicalRequests: 1,
maxRetries: 0,
});
const executor = testExecutor(transport);
const context = { routeId: ROUTE_ID, scope: scopeSnapshot(), execution };
await executor.execute(TEST_QUERY, { limit: 5 }, context);
const second = await executor.execute(TEST_QUERY, { limit: 5 }, context);
expect(second).toMatchObject({
kind: "TRANSPORT_FAILURE",
failure: { kind: "OVERLOADED_BEFORE_SEND" },
});
expect(transport).toHaveBeenCalledTimes(1);
});
it("shares one retry budget across independent failing operations", async () => {
const transport = vi.fn<Transport>(networkFailure);
const execution = testExecutionContext({
maxPhysicalRequests: 10,
maxRetries: 1,
});
const executor = testExecutor(transport);
const context = { routeId: ROUTE_ID, scope: scopeSnapshot(), execution };
await executor.execute(TEST_QUERY, { limit: 5 }, context);
await executor.execute(TEST_QUERY, { limit: 5 }, context);
// First operation: attempt + its one shared retry. Second: attempt only.
expect(transport).toHaveBeenCalledTimes(3);
expect(execution.traffic.retries.consumed).toBe(1);
});
it("does not reset the interaction deadline before retry", async () => {
const clock = manualClock(0);
const execution = testExecutionContext({
deadlineMs: 5_000,
maxPhysicalRequests: 4,
maxRetries: 3,
clock: clock.now,
});
const transport = vi.fn<Transport>(() => {
clock.advance(5_001);
return networkFailure();
});
const outcome = await testExecutor(transport).execute(TEST_QUERY, { limit: 5 }, {
routeId: ROUTE_ID,
scope: scopeSnapshot(),
execution,
});
expect(outcome.kind).toBe("TRANSPORT_FAILURE");
expect(transport).toHaveBeenCalledTimes(1);
expect(execution.traffic.retries.consumed).toBe(0);
});
it("gives a late operation only the interaction's remaining deadline", async () => {
const clock = manualClock(0);
const execution = testExecutionContext({
deadlineMs: 1_000,
clock: clock.now,
});
clock.advance(1_000);
const transport = vi.fn<Transport>(async () => jsonRows(1));
const outcome = await testExecutor(transport).execute(TEST_QUERY, { limit: 5 }, {
routeId: ROUTE_ID,
scope: scopeSnapshot(),
execution,
});
expect(outcome).toMatchObject({
kind: "TRANSPORT_FAILURE",
failure: { kind: "TIMEOUT" },
});
expect(transport).not.toHaveBeenCalled();
});
it("rejects instead of queueing beyond the interaction queue bound", async () => {
const transport = hangingTransport();
const execution = testExecutionContext({
maxPhysicalRequests: 10,
maxConcurrentRequests: 1,
maxQueuedRequests: 0,
});
const executor = testExecutor(transport);
const context = { routeId: ROUTE_ID, scope: scopeSnapshot(), execution };
const first = executor.execute(TEST_QUERY, { limit: 5 }, context);
await vi.waitFor(() => expect(transport.calls).toBe(1));
const second = await executor.execute(TEST_QUERY, { limit: 5 }, context);
expect(second).toMatchObject({
kind: "TRANSPORT_FAILURE",
failure: { kind: "OVERLOADED_BEFORE_SEND" },
});
execution.cancellation.cancel();
await expect(first).resolves.toMatchObject({ kind: "CANCELLED" });
expect(transport.calls).toBe(1);
});
it("releases every lease and waiting entry when the interaction is aborted", async () => {
const transport = hangingTransport();
const execution = testExecutionContext({
maxPhysicalRequests: 10,
maxConcurrentRequests: 1,
maxQueuedRequests: 2,
});
const executor = testExecutor(transport);
const context = { routeId: ROUTE_ID, scope: scopeSnapshot(), execution };
const running = [1, 2, 3].map(() =>
executor.execute(TEST_QUERY, { limit: 5 }, context),
);
await vi.waitFor(() => {
expect(execution.traffic.concurrency.active).toBe(1);
expect(execution.traffic.concurrency.queued).toBe(2);
});
execution.cancellation.cancel();
const outcomes = await Promise.all(running);
expect(outcomes.map((outcome) => outcome.kind)).toEqual([
"CANCELLED",
"CANCELLED",
"CANCELLED",
]);
expect(execution.traffic.concurrency.active).toBe(0);
expect(execution.traffic.concurrency.queued).toBe(0);
expect(transport.calls).toBe(1);
});
it("keeps KEYED command replay safety even when the budget allows retries", async () => {
const transport = vi.fn<Transport>(networkFailure);
const execution = testExecutionContext({
maxPhysicalRequests: 10,
maxRetries: 5,
});
const outcome = await testExecutor(transport).execute(
TEST_COMMAND,
{ name: "entity" },
{
routeId: ROUTE_ID,
scope: scopeSnapshot(),
execution,
intent: Object.freeze({
intentId: "intent-1",
operationId: "TEST_CREATE_ENTITY",
canonicalInputIdentity: "opaque",
idempotencyKey: "key-1",
createdAtMonotonicMs: 1,
}),
},
);
expect(outcome).toMatchObject({
kind: "TRANSPORT_FAILURE",
effect: "MAYBE_APPLIED",
});
expect(transport).toHaveBeenCalledTimes(1);
expect(execution.traffic.retries.consumed).toBe(0);
});
it("bounds an execution without an explicit interaction by the default policy", async () => {
const transport = vi.fn<Transport>(networkFailure);
await testExecutor(transport, { maxRetryAttempts: 2 }).execute(
TEST_QUERY,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(transport).toHaveBeenCalledTimes(3);
});
});
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import {
composeContractContributions,
ContractContributionError,
type InstalledContractContribution,
type InstalledHttpContract,
} from "../../../src/contracts/external-contract-runtime.ts";
import type { TrafficBudget } from "../../../src/platform/traffic/traffic-budget.ts";
import {
TEST_CONTRACT_CONTRIBUTION,
TEST_LIST_HTTP_CONTRACT,
} from "../../helpers/external-contract-fixture.ts";
function compositionReason(run: () => unknown): string {
try {
run();
} catch (error) {
return error instanceof ContractContributionError ? error.reason : String(error);
}
throw new Error("composition unexpectedly succeeded");
}
const FINITE: TrafficBudget = Object.freeze({
maxPhysicalRequests: 3,
maxRetries: 2,
maxConcurrentRequests: 2,
maxQueuedRequests: 2,
});
function withTraffic(traffic: unknown): InstalledContractContribution {
const list = {
...TEST_LIST_HTTP_CONTRACT,
frontend: { ...TEST_LIST_HTTP_CONTRACT.frontend, traffic },
} as unknown as InstalledHttpContract<unknown, unknown, unknown>;
return {
...TEST_CONTRACT_CONTRIBUTION,
http: [list],
};
}
describe("operation traffic policy", () => {
it("requires finite positive traffic limits for an operation", () => {
expect(
compositionReason(() =>
composeContractContributions([
withTraffic({ ...FINITE, maxPhysicalRequests: Number.POSITIVE_INFINITY }),
]),
),
).toMatch(/traffic.*maxPhysicalRequests/i);
});
it.each([
{ ...FINITE, maxRetries: -1 },
{ ...FINITE, maxConcurrentRequests: 0 },
{ maxPhysicalRequests: 3, maxRetries: 1, maxConcurrentRequests: 1 },
{ ...FINITE, extra: 1 },
])("rejects a malformed traffic policy %#", (traffic) => {
expect(
compositionReason(() => composeContractContributions([withTraffic(traffic)])),
).toMatch(/traffic|field/i);
});
it("installs an immutable snapshot of a finite traffic policy", () => {
const source = { ...FINITE };
const composed = composeContractContributions([withTraffic(source)]);
source.maxPhysicalRequests = 60;
const installed = composed.httpByOperationId.get("TEST_LIST_ENTITIES");
expect(installed?.frontend.traffic).toEqual(FINITE);
expect(Object.isFrozen(installed?.frontend.traffic)).toBe(true);
});
it("keeps operations without a traffic policy valid", () => {
const composed = composeContractContributions([TEST_CONTRACT_CONTRIBUTION]);
expect(
composed.httpByOperationId.get("TEST_LIST_ENTITIES")?.frontend.traffic,
).toBeUndefined();
});
});
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { createRequestBudget } from "../../../src/platform/traffic/request-budget.ts";
describe("createRequestBudget", () => {
it("allows exactly the configured number of physical requests", () => {
const budget = createRequestBudget(2);
expect(budget.tryConsume()).toBe(true);
expect(budget.tryConsume()).toBe(true);
expect(budget.tryConsume()).toBe(false);
expect(budget.consumed).toBe(2);
expect(budget.remaining).toBe(0);
});
it("never refills and never over-counts after exhaustion", () => {
const budget = createRequestBudget(1);
budget.tryConsume();
for (let i = 0; i < 100; i += 1) budget.tryConsume();
expect(budget.consumed).toBe(1);
});
it.each([0, -1, Number.POSITIVE_INFINITY, Number.NaN, 2.5])(
"rejects non-positive or unbounded maximum %s",
(maximum) => {
expect(() => createRequestBudget(maximum)).toThrow(TypeError);
},
);
});
@@ -0,0 +1,89 @@
import { describe, expect, it, vi } from "vitest";
import {
createQueryClient,
QUERY_CACHE_DEFAULTS,
} from "../../../src/adapters/query-cache/tanstack-query-cache.ts";
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
import {
jsonRows,
networkFailure,
scopeSnapshot,
testExecutor,
type Transport,
} from "../../helpers/traffic-test-kit.ts";
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
unknown,
unknown,
unknown
>;
/**
* Spec §16. Multiple consumers of one query identity must not imply multiple
* physical requests. TanStack Query owns in-flight coalescing; this suite pins
* that the installed query client plus the real V3 executor keep it that way.
*/
describe("request deduplication and coalescing", () => {
function loadSameQuery(
client: ReturnType<typeof createQueryClient>,
executor: ReturnType<typeof testExecutor>,
key: readonly unknown[] = ["entities", "list", { limit: 20 }],
) {
return client.fetchQuery({
queryKey: key,
queryFn: ({ signal }) =>
executor.execute(TEST_QUERY, { limit: 20 }, {
routeId: "TEST_ROUTE",
scope: scopeSnapshot(),
signal,
}),
});
}
it("coalesces concurrent consumers of the same query identity", async () => {
const transport = vi.fn<Transport>(async () => jsonRows(3));
const executor = testExecutor(transport);
const client = createQueryClient();
const results = await Promise.all([
loadSameQuery(client, executor),
loadSameQuery(client, executor),
loadSameQuery(client, executor),
]);
expect(transport).toHaveBeenCalledTimes(1);
expect(results.every((result) => result.kind === "SUCCESS")).toBe(true);
client.clear();
});
it("keeps distinct query identities as distinct physical requests", async () => {
const transport = vi.fn<Transport>(async () => jsonRows(1));
const executor = testExecutor(transport);
const client = createQueryClient();
await Promise.all([
loadSameQuery(client, executor, ["entities", "list", 1]),
loadSameQuery(client, executor, ["entities", "list", 2]),
]);
expect(transport).toHaveBeenCalledTimes(2);
client.clear();
});
it("does not stack a query-layer retry on top of the executor retry budget", async () => {
expect(QUERY_CACHE_DEFAULTS.retry).toBe(false);
expect(QUERY_CACHE_DEFAULTS.mutationRetry).toBe(false);
const transport = vi.fn<Transport>(networkFailure);
const executor = testExecutor(transport, { maxRetryAttempts: 2 });
const client = createQueryClient();
await Promise.all([loadSameQuery(client, executor), loadSameQuery(client, executor)]);
// One coalesced logical execution: 1 attempt + at most 2 executor retries.
expect(transport.mock.calls.length).toBeLessThanOrEqual(3);
client.clear();
});
});
@@ -0,0 +1,74 @@
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;
/**
* Spec §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<Transport>(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);
});
});
@@ -0,0 +1,101 @@
import { describe, expect, it, vi } from "vitest";
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
import {
networkFailure,
scopeSnapshot,
testExecutionContext,
testExecutor,
type Transport,
} from "../../helpers/traffic-test-kit.ts";
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
unknown,
unknown,
unknown
>;
/**
* Spec §32 / §34. Backend failure coinciding with a user spike must not let
* the client multiply the incident: physical requests per interaction stay at
* or below the interaction budget no matter how many operations it starts.
*/
async function runInteraction(
options: Readonly<{
transport: Transport;
maxPhysicalRequests: number;
maxRetries: number;
operationsPerInteraction?: number;
}>,
) {
const executor = testExecutor(options.transport, { maxRetryAttempts: 2 });
const execution = testExecutionContext({
maxPhysicalRequests: options.maxPhysicalRequests,
maxRetries: options.maxRetries,
maxConcurrentRequests: 2,
maxQueuedRequests: 8,
});
const context = { routeId: "TEST_ROUTE", scope: scopeSnapshot(), execution };
await Promise.all(
Array.from({ length: options.operationsPerInteraction ?? 1 }, () =>
executor.execute(TEST_QUERY, { limit: 5 }, context),
),
);
return execution;
}
describe("traffic amplification invariants", () => {
it("keeps physical requests bounded when every dispatch fails", async () => {
const transport = vi.fn<Transport>(networkFailure);
const interactions = Array.from({ length: 1_000 }, () =>
runInteraction({ transport, maxPhysicalRequests: 2, maxRetries: 1 }),
);
await Promise.allSettled(interactions);
expect(transport.mock.calls.length).toBeLessThanOrEqual(2_000);
});
it("does not let parallel operations inside one interaction multiply retries", async () => {
const transport = vi.fn<Transport>(networkFailure);
const results = await Promise.all(
Array.from({ length: 200 }, () =>
runInteraction({
transport,
maxPhysicalRequests: 4,
maxRetries: 1,
operationsPerInteraction: 5,
}),
),
);
// Without the shared budget: 5 ops x 3 attempts = 15 requests each.
expect(transport.mock.calls.length).toBeLessThanOrEqual(200 * 4);
for (const execution of results) {
expect(execution.traffic.retries.consumed).toBeLessThanOrEqual(1);
expect(execution.traffic.requests.consumed).toBeLessThanOrEqual(4);
expect(execution.traffic.concurrency.active).toBe(0);
expect(execution.traffic.concurrency.queued).toBe(0);
}
});
it("amplifies at most maxPhysicalRequests per interaction across budget sizes", async () => {
for (const maxPhysicalRequests of [1, 2, 3]) {
const transport = vi.fn<Transport>(networkFailure);
await Promise.all(
Array.from({ length: 100 }, () =>
runInteraction({
transport,
maxPhysicalRequests,
maxRetries: 5,
operationsPerInteraction: 3,
}),
),
);
expect(transport.mock.calls.length / 100).toBeLessThanOrEqual(
maxPhysicalRequests,
);
}
});
});
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import {
createTrafficRuntime,
defineTrafficBudget,
} from "../../../src/platform/traffic/traffic-budget.ts";
import { createExecutionContext } from "../../../src/platform/execution/execution-context.ts";
const POLICY = {
maxPhysicalRequests: 4,
maxRetries: 1,
maxConcurrentRequests: 2,
maxQueuedRequests: 2,
} as const;
describe("createTrafficRuntime", () => {
it("creates one request, retry, and concurrency budget per interaction", () => {
const runtime = createTrafficRuntime(POLICY);
expect(runtime.requests.maximum).toBe(4);
expect(runtime.retries.maximum).toBe(1);
expect(runtime.concurrency.maximum).toBe(2);
expect(runtime.concurrency.maxQueued).toBe(2);
expect(Object.isFrozen(runtime.policy)).toBe(true);
});
it("keeps immutable policy separate from mutable per-interaction counters", () => {
const a = createTrafficRuntime(POLICY);
const b = createTrafficRuntime(POLICY);
a.requests.tryConsume();
expect(a.requests.consumed).toBe(1);
expect(b.requests.consumed).toBe(0);
});
it("shares one runtime with every child of an execution context", () => {
const context = createExecutionContext({
interactionId: "shared",
deadlineMs: 1_000,
traffic: POLICY,
});
const childA = context.traffic;
const childB = context.traffic;
childA.retries.tryConsume("a");
expect(childB.retries.tryConsume("b")).toBe(false);
});
it.each([
["maxPhysicalRequests", Number.POSITIVE_INFINITY],
["maxRetries", -1],
["maxConcurrentRequests", 0],
["maxQueuedRequests", Number.NaN],
["maxPhysicalRequests", 65],
["maxQueuedRequests", 257],
] as const)("rejects %s=%s", (key, value) => {
expect(() => defineTrafficBudget({ ...POLICY, [key]: value })).toThrow(
new RegExp(key),
);
});
});