From 4f6e7729060589fea51574e335c4685022b5336e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 10:42:17 +0900 Subject: [PATCH 1/6] =?UTF-8?q?fix(browser-rpc):=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=ED=95=84=20=EC=83=81=ED=95=9C=EC=9D=84=20=EB=84=98=EB=8A=94=20?= =?UTF-8?q?Retry-After=EC=97=90=EB=8A=94=20=EB=8B=A4=EC=8B=9C=20=EB=B3=B4?= =?UTF-8?q?=EB=82=B4=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: retryDelay가 서버 힌트를 profile.maxRetryAfterMs로 잘라 쓴다. 서버가 5초 뒤라고 했는데 상한이 100 ms면 0.1초 뒤에 같은 호출을 다시 보낸다. 서버가 정한 재시도 하한보다 먼저 보내는 것이다. 고른 방법: shouldRetry가 힌트를 프로필 상한과 비교해 넘으면 막는다. 그 힌트를 실은 실패의 kind·code와 retryAfterMs를 돌려준다. 잘라 쓰기는 지운다. 계약 문서 16.1 표의 그 칸을 같이 고친다. 버린 대안: 상한을 올린다. 상한은 제품이 정하는 값이고, 올려도 더 큰 힌트에서 같은 일이 난다. 위험·한계: maxRetryAfterMs를 0이나 작은 값으로 둔 채 잘린 재시도에 기대던 파생 프로젝트는 그 힌트에서 더는 재시도하지 않는다. 남은 deadline도 모자라 RPC_RETRY_BUDGET_EXHAUSTED로 끝나던 호출도 그 실패의 code로 끝난다. jitter는 뒤 커밋이 더한다. 검증: 새 시험이 고치기 전 desktop에서 실패했다(전송 2회, 기대 1회). 고친 뒤 tests/unit/browser-rpc 58 tests 통과. Refs: REV-FE-0024 --- .../backend-api-and-server-state-contract.md | 2 +- .../browser-rpc/browser-rpc-runtime.ts | 10 +-- .../browser-rpc/browser-rpc-runtime.test.ts | 88 +++++++++++++++++++ 3 files changed, 94 insertions(+), 6 deletions(-) diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index b8920d0d..4f3e11a1 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -732,7 +732,7 @@ query invalidate hint로만 쓸지 operation별 reducer contract가 필요하다 |---|---|---| | KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답으로는 재시도하지 않는다. 예외: Envelope operation이 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절, 백엔드 §2가 같은 키 재전송을 요구)을 받으면 `retryBudget` 안에서 같은 키로 다시 보낸다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`, `backend-envelope.ts` `invitesKeyedResend`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) | | 재시도 횟수 상한 | min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2) (`http-execution-v3.ts` `retryCeiling`) | profile `maxAttempts`(시도 횟수), 하드 상한 4 (`src/contracts/browser-rpc.ts` `BROWSER_RPC_HARD_LIMITS`) | -| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`로 잘라 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `retryDelay`) | +| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`를 넘으면 재시도하지 않는다. 이하면 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `shouldRetry`, `retryDelay`) | | `REQUEST_TIMEOUT_MS` | 상한이다. 계약 `totalDeadlineMs`를 줄이기만 한다 (`runtime-adapters.ts` `requestDeadlineCeilingMs`) | 쓰지 않는다. operation `totalDeadlineMs`만 쓴다. 하드 상한 30분 | 결과 불명 뒤 사용자 재전송은 전송과 무관하게 같은 intent·같은 키를 쓴다 diff --git a/src/adapters/browser-rpc/browser-rpc-runtime.ts b/src/adapters/browser-rpc/browser-rpc-runtime.ts index 5842a154..4157c781 100644 --- a/src/adapters/browser-rpc/browser-rpc-runtime.ts +++ b/src/adapters/browser-rpc/browser-rpc-runtime.ts @@ -1521,6 +1521,10 @@ function shouldRetry( profile.retryOwner === "FRONTEND_ADAPTER" && attempt + 1 < profile.maxAttempts && profile.retryableFailures.includes(failure.code) && + // A hint is a lower bound. Past the profile ceiling there is no retry, + // never an earlier one. + (failure.retryAfterMs === undefined || + failure.retryAfterMs <= profile.maxRetryAfterMs) && (["SAFE", "IDEMPOTENT"].includes(operation.replayPolicy) || (operation.replayPolicy === "KEYED_COMMAND" && validIdempotencyKey(idempotencyKey))) @@ -1533,11 +1537,7 @@ function retryDelay( attempt: number, ): number { const backoff = profile.backoffMs[attempt] ?? 0; - const retryAfter = Math.min( - failure.retryAfterMs ?? 0, - profile.maxRetryAfterMs, - ); - return Math.max(backoff, retryAfter); + return Math.max(backoff, failure.retryAfterMs ?? 0); } function mapTransportFailure( diff --git a/tests/unit/browser-rpc/browser-rpc-runtime.test.ts b/tests/unit/browser-rpc/browser-rpc-runtime.test.ts index 629bcb55..b445db5b 100644 --- a/tests/unit/browser-rpc/browser-rpc-runtime.test.ts +++ b/tests/unit/browser-rpc/browser-rpc-runtime.test.ts @@ -161,6 +161,28 @@ describe("Browser RPC provider-neutral runtime", () => { expect(calls).toBe(2); }); + it("does not retry ahead of a server hint past the profile ceiling", async () => { + const run = await retryAfterRun({ hintMs: 5_000, maxRetryAfterMs: 100 }); + + expect(run.calls).toBe(1); + expect(run.delays).toEqual([]); + expect(run.result).toMatchObject({ + ok: false, + error: { + kind: "SERVER_FAILURE", + code: "RPC_UNAVAILABLE", + retryAfterMs: 5_000, + }, + }); + }); + + it("retries on a hint equal to the profile ceiling", async () => { + const run = await retryAfterRun({ hintMs: 100, maxRetryAfterMs: 100 }); + + expect(run.calls).toBe(2); + expect(run.delays).toEqual([100]); + }); + it("drops a late unary result after its scope generation changes", async () => { const transport = defineBrowserRpcTransport({ runtimeProfileId: "CONNECT_REFERENCE_UNARY", @@ -398,6 +420,72 @@ function baseDependencies(transport: BrowserRpcTransport) { } as const; } +/** One failed attempt that carries a hint, then a success, on a fake clock. */ +async function retryAfterRun(input: Readonly<{ + hintMs: number; + maxRetryAfterMs?: number; +}>) { + let calls = 0; + let now = 0; + const delays: number[] = []; + const profile = unaryProfile({ + retryProfileId: "RPC_RETRY_TWO", + retryOwner: "FRONTEND_ADAPTER", + maxAttempts: 2, + backoffMs: [0], + retryableFailures: ["UNAVAILABLE"], + maxRetryAfterMs: input.maxRetryAfterMs ?? 60_000, + }); + const transport = defineBrowserRpcTransport({ + runtimeProfileId: profile.runtimeProfileId, + providerId: profile.providerId, + protocol: profile.protocol, + rpcKind: profile.rpcKind, + async invokeUnary() { + calls += 1; + return calls === 1 + ? { + ok: false, + failure: { code: "UNAVAILABLE", retryAfterMs: input.hintMs }, + } + : { + ok: true, + message: { id: "resource-2", name: "Retried resource" }, + encodedBytes: 32, + }; + }, + }); + const runtime = createBrowserRpcRuntime({ + ...baseDependencies(transport), + operations: { + GET_RPC_RESOURCE: unaryOperation({ retryProfileId: "RPC_RETRY_TWO" }), + }, + profiles: { CONNECT_REFERENCE_UNARY: profile }, + clock: { + now: () => now, + sleep(milliseconds, signal) { + // raceWithin arms a deadline timer with its own signal; only the retry + // wait resolves, and only it moves the clock. + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + delays.push(milliseconds); + now += milliseconds; + resolve(); + }, 0); + signal?.addEventListener("abort", () => { + clearTimeout(timer); + reject(new DOMException("Aborted", "AbortError")); + }, { once: true }); + }); + }, + }, + }); + const result = await runtime + .bindUnary("GET_RPC_RESOURCE", isResourceView) + .execute({ resourceId: "resource-2" }); + return { calls, delays, result }; +} + function streamRuntime( transport: BrowserRpcTransport, observations?: Readonly<{ -- 2.54.0 From 8d1c45c3079bdc97a001c0aafb945847f9c188d5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 10:42:52 +0900 Subject: [PATCH 2/6] =?UTF-8?q?refactor(http):=20Retry-After=20=EC=9E=AC?= =?UTF-8?q?=EC=8B=9C=EB=8F=84=20=EC=A7=80=EC=97=B0=20=EA=B7=9C=EC=B9=99?= =?UTF-8?q?=EC=9D=84=20kernel=EB=A1=9C=20=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 힌트를 하한으로 두고 jitter를 더하는 규칙이 HTTP V3 안에만 있다. 다른 adapter 넷은 같은 계산을 따로 하고 jitter가 빠져 있다. 고른 방법: kernel retry-after.ts에 delayAfterRetryHint를 두고 retryDelayFor가 부른다. 상한·로컬 backoff·난수 검사는 부르는 쪽이 갖는다. 남은 예산을 건네면 jitter 창을 힌트 뒤 여유의 절반까지로 줄이는 칸을 둔다(HTTP는 쓰지 않는다). 버린 대안: adapter마다 jitter만 고친다. 여섯 번째 복사본이 생기고 상한 초과 때 포기와 자르기가 다시 갈릴 수 있다. 위험·한계: 동작은 같다. 상한을 넘는 힌트에서도 random을 한 번 부르는 것만 다르다. 검증: desktop에서 옛 구현과 retryIndex 0~5, 힌트 null·0~5100, 표본 101개, 모두 3,091,812 조합을 대조해 차이 0. kernel 새 시험과 HTTP 재시도 시험 87 tests 통과. Refs: REV-FE-0024 --- docs/architecture/layers.md | 2 +- src/adapters/http/http-retry-lifecycle.ts | 23 +++++------ src/adapters/platform/retry-after.ts | 39 ++++++++++++++++++ tests/unit/retry-after-delay.test.ts | 50 +++++++++++++++++++++++ 4 files changed, 100 insertions(+), 14 deletions(-) create mode 100644 tests/unit/retry-after-delay.test.ts diff --git a/docs/architecture/layers.md b/docs/architecture/layers.md index b013f25f..a2c62e34 100644 --- a/docs/architecture/layers.md +++ b/docs/architecture/layers.md @@ -84,7 +84,7 @@ adapter가 presentation까지 들어온다. - `src/adapters/platform/**` — 여러 adapter 그룹이 함께 쓰는 동작 장치: 시스템 시계, 공용 abort 기본 요소, 용량 상한 가드, IndexedDB 연결·트랜잭션 - 헬퍼, `Retry-After` 파싱, JSON 멤버 스캐너. bootstrap만 쓰는 platform + 헬퍼, `Retry-After` 파싱과 재시도 지연, JSON 멤버 스캐너. bootstrap만 쓰는 platform 서비스 두 개도 여기 있다: 브라우저 lifecycle runtime과 mutation intent factory다(adapter는 이 둘을 import하지 않는다). kernel 파일은 동작 방식만 소유한다. 이름, schema, 실패 코드, 관측 모양은 절대 소유하지 않는다. diff --git a/src/adapters/http/http-retry-lifecycle.ts b/src/adapters/http/http-retry-lifecycle.ts index ae9e30da..66588a23 100644 --- a/src/adapters/http/http-retry-lifecycle.ts +++ b/src/adapters/http/http-retry-lifecycle.ts @@ -1,4 +1,5 @@ import type { RetrySemantics } from "../../contracts/external-contract-runtime.ts"; +import { delayAfterRetryHint } from "../platform/retry-after.ts"; import type { PhysicalAttemptState } from "./http-effect-certainty.ts"; const RETRYABLE_STATUSES: ReadonlySet = new Set([ @@ -45,22 +46,18 @@ export function jitteredDelay( return Math.floor(random() * localJitterCeiling(retryIndex)); } -/** - * scale-architecture.md §13.3. `Retry-After` is a floor, never an exact instant: every client - * that received the same hint would otherwise retry in one synchronized second - * spike. The cohort is spread over a bounded window that grows with the hint - * (a quarter of it) but never beyond the local 2s jitter ceiling. - */ +/** scale-architecture.md §13.3, through the kernel `delayAfterRetryHint`. */ export function retryDelayFor( retryAfterMs: number | null, retryIndex: number, random: () => number, ): number | null { - if (retryAfterMs === null) return jitteredDelay(retryIndex, random); - if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null; - const window = Math.min( - RETRY_MAX_LOCAL_DELAY_MS, - Math.max(localJitterCeiling(retryIndex), Math.ceil(retryAfterMs / 4)), - ); - return retryAfterMs + Math.floor(random() * window); + const sample = random(); + return delayAfterRetryHint({ + hintMs: retryAfterMs, + ceilingMs: RETRY_AFTER_CEILING_MS, + localDelayMs: jitteredDelay(retryIndex, () => sample), + localWindowMs: localJitterCeiling(retryIndex), + sample, + }); } diff --git a/src/adapters/platform/retry-after.ts b/src/adapters/platform/retry-after.ts index 88946745..053bc586 100644 --- a/src/adapters/platform/retry-after.ts +++ b/src/adapters/platform/retry-after.ts @@ -36,3 +36,42 @@ export function parseRetryAfterDelay( ? Math.max(0, timestamp - nowEpochMs) : null; } + +const RETRY_HINT_MAX_JITTER_MS = 2_000; + +/** + * scale-architecture.md §13.3. The one rule for waiting on a server retry hint. + * + * The hint is a floor, never an exact instant: every client that received the + * same hint would otherwise retry in one synchronized spike. The jitter above + * it spans the wider of the local window and a quarter of the hint, up to 2 s. + * When the caller has a budget the jitter takes at most half of what the hint + * leaves of it: the retried attempt needs the rest to answer. A hint past the + * caller's ceiling is `null` (do not retry), never a shorter wait. The result + * is the later of that instant and the local delay. + * + * Callers own the ceiling, the local backoff and the checked random sample. + */ +export function delayAfterRetryHint(input: Readonly<{ + hintMs: number | null; + /** Bounds the hint, not the jitter added on top of it. */ + ceilingMs: number; + localDelayMs: number; + localWindowMs: number; + /** A value in [0, 1). */ + sample: number; + remainingMs?: number; +}>): number | null { + const { hintMs, localDelayMs } = input; + if (hintMs === null) return localDelayMs; + if (hintMs > input.ceilingMs) return null; + const jitterWindowMs = Math.min( + RETRY_HINT_MAX_JITTER_MS, + Math.max(input.localWindowMs, Math.ceil(hintMs / 4)), + ((input.remainingMs ?? Number.POSITIVE_INFINITY) - hintMs) / 2, + ); + return Math.max( + localDelayMs, + hintMs + Math.floor(input.sample * Math.max(0, jitterWindowMs)), + ); +} diff --git a/tests/unit/retry-after-delay.test.ts b/tests/unit/retry-after-delay.test.ts new file mode 100644 index 00000000..b2798318 --- /dev/null +++ b/tests/unit/retry-after-delay.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; + +import { delayAfterRetryHint } from "../../src/adapters/platform/retry-after.ts"; + +const delay = ( + overrides: Partial[0]>, +) => + delayAfterRetryHint({ + hintMs: 3_000, + ceilingMs: 60_000, + localDelayMs: 100, + localWindowMs: 250, + sample: 0, + ...overrides, + }); + +describe("delay after a server retry hint", () => { + it("spreads the same hint without retrying before it", () => { + expect(delay({ sample: 0 })).toBe(3_000); + // The window is max(250, 3000 / 4). + expect(delay({ sample: 0.999 })).toBe(3_749); + }); + + it("uses the local window when it is wider than a quarter of the hint", () => { + expect(delay({ localWindowMs: 1_000, sample: 0.5 })).toBe(3_500); + }); + + it("bounds the window whatever the hint and the local backoff are", () => { + expect( + delay({ hintMs: 60_000, localWindowMs: 60_000, sample: 0.999 }), + ).toBe(61_998); + }); + + it("refuses a hint past the ceiling instead of cutting it", () => { + expect(delay({ hintMs: 60_000 })).toBe(60_000); + expect(delay({ hintMs: 60_001 })).toBeNull(); + }); + + it("keeps the local delay when there is no hint or it is later", () => { + expect(delay({ hintMs: null, sample: 0.999 })).toBe(100); + expect(delay({ hintMs: 0, localWindowMs: 100, sample: 0.5 })).toBe(100); + expect(delay({ localDelayMs: 9_000, sample: 0.999 })).toBe(9_000); + }); + + it("leaves at least half of the budget after the hint to the retry", () => { + expect(delay({ remainingMs: 3_100, sample: 0.999 })).toBe(3_049); + // A spent budget adds no negative jitter: the caller sees the hint and stops. + expect(delay({ remainingMs: 2_000, sample: 0.999 })).toBe(3_000); + }); +}); -- 2.54.0 From 6e47167abbf022c7e4375b49db6c97b00d000a0d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 10:49:34 +0900 Subject: [PATCH 3/6] =?UTF-8?q?fix(retry):=20Retry-After=20=ED=95=98?= =?UTF-8?q?=ED=95=9C=20=EC=9C=84=EC=97=90=20jitter=EB=A5=BC=20=EB=8D=94?= =?UTF-8?q?=ED=95=B4=20=EC=9E=AC=EC=8B=9C=EB=8F=84=EB=A5=BC=20=ED=9D=A9?= =?UTF-8?q?=EB=9C=A8=EB=A6=B0=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: resumable upload·realtime 재연결·bounded poll·browser-rpc가 max(로컬 지연, 힌트)만큼 기다린다. 힌트가 로컬 지연보다 크면 같은 힌트를 받은 클라이언트가 모두 힌트 시각에 다시 보낸다. scale-architecture 13.3절은 jitter를 더하라고 적고 VD-28은 max를 적어 문서도 갈려 있다. 고른 방법: 넷이 kernel delayAfterRetryHint를 부른다. 상한 값과 실패 code는 그대로다. 시간 예산이 있는 셋은 jitter를 힌트 뒤 여유의 절반까지만 써서, 다시 보낸 시도가 답을 받을 시간을 남긴다. browser-rpc는 주입할 수 있는 random(선택 칸)을 받는다. 13.3절·계약 16.1 표를 고치고 VD-28은 기록 규칙대로 보완 절로 고친다. 버린 대안: 재연결·poll은 max를 유지한다(카드 안 B). 문서 불일치와 몰림이 남는다. jitter까지 상한 안에 자르기는 힌트가 상한과 같을 때 모두 같은 순간에 다시 보내게 되어 버렸다. 위험·한계: 네 곳의 재시도가 최대 2초 미만 늦어진다. 실제 대기가 maxDelayMs·maxIntervalMs·maxRetryAfterMs보다 그만큼 길 수 있다. 다시 보낸 시도의 시간은 최악에 여유의 절반으로 준다. 로컬 지연에 난수가 없는 browser-rpc backoff 표와 poll 첫 실패의 최소 간격은 힌트보다 충분히 늦으면 여전히 같은 시각에 모인다. 안 A는 소유자가 아니라 review가 자율 운영 규칙으로 정했다. 검증: 새 시험이 고치기 전 desktop에서 실패했다(resumable 80≠99, 재연결·poll 10000≠11998, rpc 1000≠1249). 고친 뒤 check:types·lint· architecture·unit·verify:documentation rc=0. Refs: REV-FE-0024 --- ...ime-events-web-push-and-bounded-polling.md | 7 ++ .../backend-api-and-server-state-contract.md | 2 +- docs/architecture/scale-architecture.md | 7 ++ .../browser-rpc/browser-rpc-runtime.ts | 53 +++++++++++- .../resumable-upload-runtime.ts | 22 +++-- .../polling/bounded-poll-coordinator.ts | 23 +++-- src/adapters/realtime/reconnect-policy.ts | 26 ++++-- .../browser-rpc/browser-rpc-runtime.test.ts | 86 ++++++++++++++++++- .../realtime/bounded-poll-coordinator.test.ts | 74 ++++++++++++++++ .../realtime-reconnect-coordinator.test.ts | 9 +- .../realtime-reconnect-policy.test.ts | 20 ++++- tests/unit/resumable-upload-runtime.test.ts | 61 +++++++++++++ 12 files changed, 354 insertions(+), 36 deletions(-) diff --git a/docs/adr/VD-28-realtime-events-web-push-and-bounded-polling.md b/docs/adr/VD-28-realtime-events-web-push-and-bounded-polling.md index eb47a850..22b9f258 100644 --- a/docs/adr/VD-28-realtime-events-web-push-and-bounded-polling.md +++ b/docs/adr/VD-28-realtime-events-web-push-and-bounded-polling.md @@ -676,3 +676,10 @@ common runtime status는 `AVAILABLE_NOT_COMPOSED`다. 위의 미완료 promotion - [RFC 8030](https://www.rfc-editor.org/rfc/rfc8030) - [RFC 8291](https://www.rfc-editor.org/rfc/rfc8291) - [RFC 8292](https://www.rfc-editor.org/rfc/rfc8292) + +## 보완 + +> 위 본문은 고치지 않았다(`docs/README.md` 2절). 7절의 not-before 규칙은 아래처럼 바뀌었다. + +- 2026-11-22: 7절의 「valid server hint는 local delay보다 이른 retry를 금지하는 not-before bound」를 `docs/architecture/scale-architecture.md` 13.3절 규칙으로 넓힌다. reconnect와 poll은 hint를 하한으로 두고 그 위에 한도 있는 jitter를 더한다. 전에는 local delay와 hint 중 큰 값을 그대로 써서, 같은 hint를 받은 client가 같은 순간에 다시 붙었다. 실제 대기는 「hint + jitter」와 local delay 중 늦은 쪽이다. +- 2026-11-22: 같은 절의 「implementation max/remaining elapsed budget을 넘으면 낮춰 clamp하지 않고 종료」는 hint에 그대로 걸린다. max는 hint의 상한이라 실제 대기는 max보다 jitter만큼 길 수 있고, jitter는 hint 뒤에 남는 elapsed budget의 절반까지만 쓴다. 소유자가 직접 고른 것이 아니라 리뷰 담당이 자율 운영 규칙으로 정한 결정이다(카드 REV-FE-0024의 2026-11-22 정정, 안 A). diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 4f3e11a1..e77ec46e 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -732,7 +732,7 @@ query invalidate hint로만 쓸지 operation별 reducer contract가 필요하다 |---|---|---| | KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답으로는 재시도하지 않는다. 예외: Envelope operation이 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절, 백엔드 §2가 같은 키 재전송을 요구)을 받으면 `retryBudget` 안에서 같은 키로 다시 보낸다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`, `backend-envelope.ts` `invitesKeyedResend`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) | | 재시도 횟수 상한 | min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2) (`http-execution-v3.ts` `retryCeiling`) | profile `maxAttempts`(시도 횟수), 하드 상한 4 (`src/contracts/browser-rpc.ts` `BROWSER_RPC_HARD_LIMITS`) | -| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`를 넘으면 재시도하지 않는다. 이하면 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `shouldRetry`, `retryDelay`) | +| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다(`docs/architecture/scale-architecture.md` 13.3절) (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`를 넘으면 재시도하지 않는다. 이하면 「hint + jitter」와 backoff 중 늦은 쪽까지 기다린다(`docs/architecture/scale-architecture.md` 13.3절). 하드 상한 60초 (`browser-rpc-runtime.ts` `shouldRetry`, `retryDelay`) | | `REQUEST_TIMEOUT_MS` | 상한이다. 계약 `totalDeadlineMs`를 줄이기만 한다 (`runtime-adapters.ts` `requestDeadlineCeilingMs`) | 쓰지 않는다. operation `totalDeadlineMs`만 쓴다. 하드 상한 30분 | 결과 불명 뒤 사용자 재전송은 전송과 무관하게 같은 intent·같은 키를 쓴다 diff --git a/docs/architecture/scale-architecture.md b/docs/architecture/scale-architecture.md index 67ec89d0..7fcb4a8c 100644 --- a/docs/architecture/scale-architecture.md +++ b/docs/architecture/scale-architecture.md @@ -566,6 +566,13 @@ C cannot retry after budget exhaustion 실제 재시도 시각은 서버가 알려 준 값에 한도가 있는 jitter(무작위 지연)를 합쳐 정한다. +HTTP V3, Browser RPC, 재개형 업로드, realtime 재연결, bounded poll이 같은 규칙(`src/adapters/platform/retry-after.ts`의 `delayAfterRetryHint`)을 쓴다. + +- 서버 값이 하한이다. 「서버 값 + jitter」와 로컬 지연 중 늦은 쪽까지 기다린다. +- jitter는 하한 위에 더한다. 창은 로컬 backoff 창과 서버 값의 4분의 1 중 큰 쪽이고, `RETRY_HINT_MAX_JITTER_MS`를 넘지 않는다. 남은 시간 예산을 건네는 호출처(Browser RPC, 재연결, poll)에서는 서버 값 뒤에 남는 예산의 절반까지만 쓴다. 나머지는 다시 보낸 시도가 답을 받을 시간이다. +- 서버 값이 부르는 쪽 상한을 넘으면 다시 보내지 않는다. 잘라서 더 일찍 보내지 않는다. 상한은 서버 값에 걸리므로 실제 대기는 상한보다 jitter만큼 길 수 있다. +- 상한 값과 실패 code는 각 adapter가 정한다. + ## 14. 동시 실행 예산 interaction마다 동시에 보내는 물리 요청 수에 한도가 있다. diff --git a/src/adapters/browser-rpc/browser-rpc-runtime.ts b/src/adapters/browser-rpc/browser-rpc-runtime.ts index 4157c781..b90fc871 100644 --- a/src/adapters/browser-rpc/browser-rpc-runtime.ts +++ b/src/adapters/browser-rpc/browser-rpc-runtime.ts @@ -27,6 +27,7 @@ import { type FailureKind, } from "../../contracts/errors.ts"; import type { RuntimeSchemaCodec } from "../../contracts/schema-registry.ts"; +import { delayAfterRetryHint } from "../platform/retry-after.ts"; import { systemClock } from "../platform/system-clock.ts"; import { decodeServerStreamLease } from "./transport.ts"; import type { @@ -67,6 +68,8 @@ export type BrowserRpcRuntimeDependencies = Readonly<{ transports: Readonly>; generationFence?: BrowserRpcGenerationFence; clock?: ClockPort; + /** Spreads the retry after a server hint. Defaults to `Math.random`. */ + random?: () => number; observations?: BrowserRpcObservationSink; }>; @@ -112,6 +115,7 @@ export function createBrowserRpcRuntime( dependencies: BrowserRpcRuntimeDependencies, ): BrowserRpcRuntime { const clock = dependencies.clock ?? systemClock; + const random = dependencies.random ?? Math.random; const generationFence = dependencies.generationFence ?? stableGenerationFence; // RPC-RR-03 / RPC-03. Snapshot before validating — every registry, not just @@ -179,6 +183,7 @@ export function createBrowserRpcRuntime( isOutput, generationFence, clock, + random, ), }); }, @@ -289,6 +294,7 @@ async function executeUnary( isOutput: (value: unknown) => value is Output, generationFence: BrowserRpcGenerationFence, clock: ClockPort, + random: () => number, ): Promise> { const { operation, profile, encoder, transport } = bound; const linked = linkedAbortController(context.signal); @@ -474,8 +480,29 @@ async function executeUnary( context.idempotencyKey, ) ) { - const delay = retryDelay(profile, transportResult.failure, attempt); - if (delay >= deadlineAt - safeNowOrDeadline(clock, deadlineAt)) { + const sample = safeSample(random); + if (sample === null) { + return finish( + failureResult( + callFailure( + operation, + attempt, + "SERVER_FAILURE", + "RPC_RUNTIME_DEPENDENCY_FAILED", + ), + ), + "FAILED", + ); + } + const retryBudgetMs = deadlineAt - safeNowOrDeadline(clock, deadlineAt); + const delay = retryDelay( + profile, + transportResult.failure, + attempt, + sample, + retryBudgetMs, + ); + if (delay === null || delay >= retryBudgetMs) { linked.controller.abort("deadline"); return finish( failureResult( @@ -1535,9 +1562,27 @@ function retryDelay( profile: BrowserRpcProviderProfile, failure: BrowserRpcTransportFailure, attempt: number, -): number { + sample: number, + remainingMs: number, +): number | null { const backoff = profile.backoffMs[attempt] ?? 0; - return Math.max(backoff, failure.retryAfterMs ?? 0); + return delayAfterRetryHint({ + hintMs: failure.retryAfterMs ?? null, + ceilingMs: profile.maxRetryAfterMs, + localDelayMs: backoff, + localWindowMs: backoff, + sample, + remainingMs, + }); +} + +function safeSample(random: () => number): number | null { + try { + const sample = random(); + return Number.isFinite(sample) && sample >= 0 && sample < 1 ? sample : null; + } catch { + return null; + } } function mapTransportFailure( diff --git a/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts b/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts index da280ebe..e9d5c57a 100644 --- a/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts +++ b/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts @@ -29,6 +29,7 @@ import { combineAbortSignals, createAbortableOperation, } from "../../platform/abortable-operation.ts"; +import { delayAfterRetryHint } from "../../platform/retry-after.ts"; import { observeTransferResult, transferAllowanceMs, @@ -1474,12 +1475,6 @@ async function waitForRetry( signal: AbortSignal, operation: BrowserDataOperation, ): Promise> { - const retryAfter = - Number.isSafeInteger(failure.retryAfterMs) && - (failure.retryAfterMs ?? -1) >= 0 && - (failure.retryAfterMs ?? 0) <= dependencies.policy.maxRetryAfterMs - ? (failure.retryAfterMs ?? 0) - : null; const randomValue = safeRandom(dependencies); if (!randomValue.ok) return randomValue; const exponential = Math.min( @@ -1487,7 +1482,20 @@ async function waitForRetry( dependencies.policy.retryBaseDelayMs * 2 ** retryIndex, ); const jittered = Math.floor(exponential * (0.5 + randomValue.value / 2)); - const delayMs = Math.max(jittered, retryAfter ?? 0); + const delayMs = delayAfterRetryHint({ + hintMs: failure.retryAfterMs ?? null, + ceilingMs: dependencies.policy.maxRetryAfterMs, + localDelayMs: jittered, + localWindowMs: exponential, + sample: randomValue.value, + }); + // `canRetry` admits no hint past the ceiling, so this does not wait less. + if (delayMs === null) { + return browserDataFailure("UNAVAILABLE", operation, { + retryable: false, + recovery: "RESUME", + }); + } try { await dependencies.sleep(delayMs, signal); return signal.aborted diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index 910ec420..5679d98d 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -11,6 +11,7 @@ import { type RealtimeFailureKind, type RealtimeResult, } from "../../../application/ports/realtime/shared.ts"; +import { delayAfterRetryHint } from "../../platform/retry-after.ts"; import { systemClock } from "../../platform/system-clock.ts"; import { captureRealtimeDataSnapshot, @@ -439,6 +440,7 @@ export function createBoundedPollCoordinator< ? result.error.retryAfterMs : undefined, random, + policy.maxElapsedMs - (attemptFinishedAt - startedAtMs), ); if (failureDelay === null) { return pollFailure("POLL_BUDGET_EXHAUSTED"); @@ -751,14 +753,13 @@ function retryDelay( consecutiveFailures: number, retryAfterMs: number | undefined, random: () => number, + remainingMs: number, ): number | null { const sample = safeRandom(random); if (sample === null) return null; if ( retryAfterMs !== undefined && - (!Number.isSafeInteger(retryAfterMs) || - retryAfterMs < 0 || - retryAfterMs > policy.maxIntervalMs) + (!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0) ) { return null; } @@ -766,11 +767,17 @@ function retryDelay( policy.maxIntervalMs, policy.minimumIntervalMs * 2 ** Math.max(0, consecutiveFailures - 1), ); - return Math.max( - policy.minimumIntervalMs, - Math.floor(ceiling * sample), - retryAfterMs ?? 0, - ); + return delayAfterRetryHint({ + hintMs: retryAfterMs ?? null, + ceilingMs: policy.maxIntervalMs, + localDelayMs: Math.max( + policy.minimumIntervalMs, + Math.floor(ceiling * sample), + ), + localWindowMs: ceiling, + sample, + remainingMs, + }); } function isPollRetryableFailureKind( diff --git a/src/adapters/realtime/reconnect-policy.ts b/src/adapters/realtime/reconnect-policy.ts index d5f64582..e65bf78e 100644 --- a/src/adapters/realtime/reconnect-policy.ts +++ b/src/adapters/realtime/reconnect-policy.ts @@ -1,3 +1,5 @@ +import { delayAfterRetryHint } from "../platform/retry-after.ts"; + export { parseRetryAfterDelay } from "../platform/retry-after.ts"; export const REALTIME_RECONNECT_CEILINGS = Object.freeze({ @@ -35,7 +37,8 @@ export type ReconnectDelayInput = Readonly<{ random: () => number; /** * Relative delay required by Retry-After, SSE retry or another validated - * protocol hint. It is a lower bound, never a value to clamp downward. + * protocol hint. It is a lower bound with bounded jitter above it, never a + * value to clamp downward. `maxDelayMs` bounds the hint, not that jitter. */ serverNotBeforeMs?: number | null; }>; @@ -67,7 +70,8 @@ export function defineReconnectPolicy( } /** - * Full-jitter exponential backoff with a server-provided not-before floor. + * Full-jitter exponential backoff. A server hint is a not-before floor with + * bounded jitter above it (`delayAfterRetryHint`). * `null` means the attempt budget cannot safely admit another delay. */ export function calculateReconnectDelay( @@ -99,16 +103,22 @@ export function calculateReconnectDelay( policy.baseDelayMs * 2 ** input.attemptIndex, ); const localDelay = Math.floor(exponentialCeiling * sample); - const serverNotBeforeMs = input.serverNotBeforeMs ?? 0; + const serverNotBeforeMs = input.serverNotBeforeMs ?? null; if ( - !Number.isSafeInteger(serverNotBeforeMs) || - serverNotBeforeMs < 0 || - serverNotBeforeMs > policy.maxDelayMs + serverNotBeforeMs !== null && + (!Number.isSafeInteger(serverNotBeforeMs) || serverNotBeforeMs < 0) ) { return null; } - const effectiveDelay = Math.max(localDelay, serverNotBeforeMs); - return effectiveDelay >= input.remainingElapsedMs + const effectiveDelay = delayAfterRetryHint({ + hintMs: serverNotBeforeMs, + ceilingMs: policy.maxDelayMs, + localDelayMs: localDelay, + localWindowMs: exponentialCeiling, + sample, + remainingMs: input.remainingElapsedMs, + }); + return effectiveDelay === null || effectiveDelay >= input.remainingElapsedMs ? null : effectiveDelay; } diff --git a/tests/unit/browser-rpc/browser-rpc-runtime.test.ts b/tests/unit/browser-rpc/browser-rpc-runtime.test.ts index b445db5b..d4f1e911 100644 --- a/tests/unit/browser-rpc/browser-rpc-runtime.test.ts +++ b/tests/unit/browser-rpc/browser-rpc-runtime.test.ts @@ -183,6 +183,75 @@ describe("Browser RPC provider-neutral runtime", () => { expect(run.delays).toEqual([100]); }); + it("spreads a server hint above its floor", async () => { + const early = await retryAfterRun({ hintMs: 1_000, random: () => 0 }); + const late = await retryAfterRun({ hintMs: 1_000, random: () => 0.999 }); + + expect(early.delays).toEqual([1_000]); + expect(late.delays).toEqual([1_249]); + }); + + it("keeps the jitter inside half of the deadline left after the hint", async () => { + const run = await retryAfterRun({ hintMs: 4_900, random: () => 0.999 }); + + expect(run.delays).toEqual([4_949]); + expect(run.calls).toBe(2); + }); + + it("leaves the retried attempt time to answer", async () => { + const run = await retryAfterRun({ + hintMs: 4_000, + responseMs: [100, 200], + random: () => 0.999, + }); + + expect(run.delays).toEqual([4_449]); + expect(run.result).toMatchObject({ ok: true }); + }); + + it.each([ + ["no hint", undefined, 300, 300], + ["a hint before the backoff", 1_000, 3_000, 3_000], + ["a backoff wider than a quarter of the hint", 1_000, 400, 1_399], + ] as const)( + "keeps the profile backoff with %s", + async (_label, hintMs, backoffMs, expected) => { + const run = await retryAfterRun({ + hintMs, + backoffMs, + random: () => 0.999, + }); + + expect(run.delays).toEqual([expected]); + }, + ); + + it("stops when the hint alone spends the total deadline", async () => { + const run = await retryAfterRun({ hintMs: 5_000, random: () => 0.999 }); + + expect(run.calls).toBe(1); + expect(run.result).toMatchObject({ + ok: false, + error: { code: "RPC_RETRY_BUDGET_EXHAUSTED" }, + }); + }); + + it.each([ + ["throws", (): number => { throw new Error("no entropy"); }], + ["returns one", (): number => 1], + ["returns a negative number", (): number => -0.1], + ["returns NaN", (): number => Number.NaN], + ] as const)("fails closed when random %s", async (_label, random) => { + const run = await retryAfterRun({ hintMs: 1_000, random }); + + expect(run.calls).toBe(1); + expect(run.delays).toEqual([]); + expect(run.result).toMatchObject({ + ok: false, + error: { code: "RPC_RUNTIME_DEPENDENCY_FAILED" }, + }); + }); + it("drops a late unary result after its scope generation changes", async () => { const transport = defineBrowserRpcTransport({ runtimeProfileId: "CONNECT_REFERENCE_UNARY", @@ -422,8 +491,12 @@ function baseDependencies(transport: BrowserRpcTransport) { /** One failed attempt that carries a hint, then a success, on a fake clock. */ async function retryAfterRun(input: Readonly<{ - hintMs: number; + hintMs: number | undefined; maxRetryAfterMs?: number; + backoffMs?: number; + /** How long the first and the retried attempt take to answer. */ + responseMs?: readonly [number, number]; + random?: () => number; }>) { let calls = 0; let now = 0; @@ -432,7 +505,7 @@ async function retryAfterRun(input: Readonly<{ retryProfileId: "RPC_RETRY_TWO", retryOwner: "FRONTEND_ADAPTER", maxAttempts: 2, - backoffMs: [0], + backoffMs: [input.backoffMs ?? 0], retryableFailures: ["UNAVAILABLE"], maxRetryAfterMs: input.maxRetryAfterMs ?? 60_000, }); @@ -443,10 +516,16 @@ async function retryAfterRun(input: Readonly<{ rpcKind: profile.rpcKind, async invokeUnary() { calls += 1; + now += input.responseMs?.[calls === 1 ? 0 : 1] ?? 0; return calls === 1 ? { ok: false, - failure: { code: "UNAVAILABLE", retryAfterMs: input.hintMs }, + failure: { + code: "UNAVAILABLE", + ...(input.hintMs === undefined + ? {} + : { retryAfterMs: input.hintMs }), + }, } : { ok: true, @@ -461,6 +540,7 @@ async function retryAfterRun(input: Readonly<{ GET_RPC_RESOURCE: unaryOperation({ retryProfileId: "RPC_RETRY_TWO" }), }, profiles: { CONNECT_REFERENCE_UNARY: profile }, + random: input.random ?? (() => 0), clock: { now: () => now, sleep(milliseconds, signal) { diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index eae35c09..15c51825 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -633,6 +633,80 @@ describe("bounded poll coordinator", () => { expect(execute).toHaveBeenCalledTimes(2); }); + it.each([ + [0, 10_000, 60_000, 10_000], + [0.999, 10_000, 60_000, 11_998], + // The ceiling bounds the hint. The jitter goes above it, inside the lease. + [0.999, 60_000, 120_000, 61_998], + [0.999, 10_000, 15_100, 10_049], + // The local window is wider than a quarter of the hint. + [0.999, 5_000, 60_000, 6_998], + ] as const)( + "spreads Retry-After (random %d, hint %d, lease %d)", + async (sample, retryAfterMs, maxElapsedMs, expected) => { + const clock = new ManualClock(); + const coordinator = createBoundedPollCoordinator({ + policy: definePollLeasePolicy({ ...policy, maxElapsedMs }), + operation, + execute: async () => ({ + ok: false, + error: { + kind: "RATE_LIMITED", + operation: "POLL", + retryable: true, + retryAfterMs, + }, + }), + environment: new MutableEnvironment(), + clock, + random: () => sample, + }); + + const pending = coordinator.run(); + clock.advance(5_000); + await flush(); + + expect( + clock.sleepers.map((sleeper) => sleeper.dueAt - clock.current), + ).toEqual([expected]); + coordinator.close(); + await expect(pending).resolves.toMatchObject({ ok: false }); + }, + ); + + it("does not poll again on a hint past the interval ceiling", async () => { + const clock = new ManualClock(); + const execute = vi.fn().mockResolvedValue({ + ok: false, + error: { + kind: "RATE_LIMITED", + operation: "POLL", + retryable: true, + retryAfterMs: 60_001, + }, + }); + const coordinator = createBoundedPollCoordinator({ + policy: definePollLeasePolicy({ ...policy, maxElapsedMs: 120_000 }), + operation, + execute, + environment: new MutableEnvironment(), + clock, + random: () => 0, + }); + + const pending = coordinator.run(); + clock.advance(5_000); + await flush(); + + // Nothing waits for another attempt. + expect(clock.sleepers).toEqual([]); + await expect(pending).resolves.toMatchObject({ + ok: false, + error: { kind: "POLL_BUDGET_EXHAUSTED" }, + }); + expect(execute).toHaveBeenCalledOnce(); + }); + it.each(["RATE_LIMITED", "PROVIDER_UNAVAILABLE"] as const)( "retries retryable %s without a server hint on policy backoff", async (kind) => { diff --git a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts index 191a7f6e..5e01156d 100644 --- a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts +++ b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts @@ -2085,11 +2085,12 @@ describe("transport failures through the reconnect coordinator", () => { }, }); - // 10_000 is each read's connect timeout; 3_000 is the reconnect wait. + // 10_000 is each read's connect timeout. The reconnect wait is the + // 3_000 hint plus half of its jitter window (3_000 / 4). const running = coordinator.run(); await flushUntil(() => clock.sleepCalls.length === 2); - expect(clock.sleepCalls).toEqual([10_000, 3_000]); - clock.advance(3_000); + expect(clock.sleepCalls).toEqual([10_000, 3_375]); + clock.advance(3_375); // A hint above the policy's maxDelayMs still ends the run. await expect(running).resolves.toMatchObject({ @@ -2097,7 +2098,7 @@ describe("transport failures through the reconnect coordinator", () => { error: { operation: "CONNECT", retryable: true }, }); expect(fetcher).toHaveBeenCalledTimes(2); - expect(clock.sleepCalls).toEqual([10_000, 3_000, 10_000]); + expect(clock.sleepCalls).toEqual([10_000, 3_375, 10_000]); }, ); diff --git a/tests/unit/realtime/realtime-reconnect-policy.test.ts b/tests/unit/realtime/realtime-reconnect-policy.test.ts index b95a6562..ce190754 100644 --- a/tests/unit/realtime/realtime-reconnect-policy.test.ts +++ b/tests/unit/realtime/realtime-reconnect-policy.test.ts @@ -36,7 +36,8 @@ describe("realtime reconnect policy", () => { random: () => 0.5, serverNotBeforeMs: 3_000, }), - ).toBe(3_000); + // 3000 + floor(0.5 * min(2000, max(4000, 750))) + ).toBe(4_000); }); it("stops instead of clamping a hint past a hard or remaining budget", () => { @@ -68,6 +69,23 @@ describe("realtime reconnect policy", () => { ).toBeNull(); }); + it("spreads a server hint that is later than the local delay", () => { + const delay = (sample: number, hintMs: number, remainingElapsedMs: number) => + calculateReconnectDelay({ + policy, + attemptIndex: 0, + remainingElapsedMs, + random: () => sample, + serverNotBeforeMs: hintMs, + }); + + expect(delay(0, 10_000, 100_000)).toBe(10_000); + expect(delay(0.999, 10_000, 100_000)).toBe(11_998); + // The ceiling bounds the hint. The jitter goes above it, inside the budget. + expect(delay(0.999, 60_000, 100_000)).toBe(61_998); + expect(delay(0.999, 10_000, 10_100)).toBe(10_049); + }); + it("parses only bounded-shape Retry-After syntax for caller validation", () => { expect(parseRetryAfterDelay("12", 0)).toBe(12_000); expect( diff --git a/tests/unit/resumable-upload-runtime.test.ts b/tests/unit/resumable-upload-runtime.test.ts index e0fcba58..817c186b 100644 --- a/tests/unit/resumable-upload-runtime.test.ts +++ b/tests/unit/resumable-upload-runtime.test.ts @@ -581,6 +581,67 @@ describe("production resumable upload runtime", () => { expect(delays).toEqual([7]); }); + it.each([ + [0, 80, 1, 80], + [0.999, 80, 1, 99], + // The ceiling bounds the hint; the jitter goes above it. + [0.999, 100, 1, 124], + // The local window is wider than a quarter of the hint. + [0.999, 80, 40, 119], + // The local backoff (half of it with random 0) is later than the hint. + [0, 7, 40, 20], + ] as const)( + "spreads Retry-After (random %d, hint %d, backoff %d)", + async (sample, retryAfterMs, backoffMs, expected) => { + const harness = createControlHarness(); + const original = executorFor(harness); + const delays: number[] = []; + let uploadAttempts = 0; + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: { + async uploadPart(input) { + uploadAttempts += 1; + if (uploadAttempts > 1) return original.uploadPart(input); + return Object.freeze({ + ok: false as const, + error: Object.freeze({ + code: "UNAVAILABLE" as const, + operation: "UPLOAD_PART" as const, + retryable: true, + recovery: "REISSUE_CAPABILITY" as const, + retryAfterMs, + }), + }); + }, + }, + checkpoints: new MemoryCheckpointStore(), + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy({ + maxRetries: 1, + retryBaseDelayMs: backoffMs, + retryMaxDelayMs: Math.max(10, backoffMs), + }), + now: () => 1_000, + random: () => sample, + sleep: async (delay) => { + delays.push(delay); + }, + }); + const result = await runtime.upload({ + uploadKey: "upload_key_retry_jitter", + purpose: "attachment", + mediaType: "application/octet-stream", + source: rangeSource(new Uint8Array([1, 2, 3, 4])), + signal: activeSignal, + }); + + expect(result.ok).toBe(true); + expect(delays).toEqual([expected]); + }, + ); + it("detects source mutation between the fingerprint and transfer passes", async () => { let reads = 0; const source: ResumableUploadSource = { -- 2.54.0 From d7f3ebea9b5eaadc71ff3de362894b2d6b5bb41b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 10:49:52 +0900 Subject: [PATCH 4/6] =?UTF-8?q?docs(changelog):=20Retry-After=20=EC=9E=AC?= =?UTF-8?q?=EC=8B=9C=EB=8F=84=20=EA=B7=9C=EC=B9=99=20=EB=B3=80=EA=B2=BD?= =?UTF-8?q?=EC=9D=84=20=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: browser-rpc의 상한 초과 재시도와 네 adapter의 대기 시각이 바뀌어 파생 프로젝트가 옮길 일이 있다. 고른 방법: 미출시 절 「먼저 할 일」 둘과 계약 변경 한 줄을 적는다. 위험·한계: 문서만 바꾼다. Refs: REV-FE-0024 --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ff909d5..edbe86dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,14 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 - 옮기기 전: `src/platform/routing/`의 다른 파일이 features·contexts·apps·adapters·bootstrap·presentation·application을 import하거나, `context-route-module.ts`가 그 두 파일 밖의 제품 모듈을 import하면 FE-GATE-010(`check:architecture`)이 실패한다. - 옮기는 법: 그 파일을 제품 쪽(`src/apps`나 그 owner 곁)으로 옮긴다. routing에 descriptor가 정말 하나 더 필요하면 그 파일 이름을 새 규칙의 `to.pathNot`에 더한다. 폴더로 넓히지 않는다. - 옮긴 뒤 확인: `scripts/verify.sh script check:architecture`. +- Browser RPC가 profile `maxRetryAfterMs`를 넘는 `Retry-After`에서 재시도하지 않는다. 전에는 그 값으로 잘라 더 일찍 다시 보냈다(REV-FE-0024). + - 옮기기 전: `retryOwner: "FRONTEND_ADAPTER"`인 profile의 `maxRetryAfterMs`가 서버가 주는 힌트보다 작으면(0 포함) 재시도되던 호출이 그 힌트를 실은 실패에서 끝난다. 결과는 그 실패의 kind·code와 `retryAfterMs`다. 남은 deadline도 모자라 `RPC_RETRY_BUDGET_EXHAUSTED`로 끝나던 호출도 이제 그 실패의 code로 끝난다. + - 옮기는 법: 자기 서버가 주는 힌트의 최댓값까지 `maxRetryAfterMs`를 올리고(하드 상한은 `BROWSER_RPC_HARD_LIMITS`), operation `totalDeadlineMs`를 「첫 시도 + max(backoff, 힌트 + jitter 상한 2초) + 다시 보낸 시도」보다 길게 둔다. 기다리지 않을 것이면 그대로 둔다. + - 옮긴 뒤 확인: 자기 profile과 deadline으로 상한과 같은 힌트는 재시도되고 넘는 힌트는 재시도되지 않는지 시험한다. +- 재개형 업로드·realtime 재연결·bounded poll·Browser RPC가 서버 힌트 위에 jitter(2초 미만)를 더해 다시 보낸다(REV-FE-0024). + - 옮기기 전: 대기가 힌트와 같거나, 힌트보다 늦은 로컬 지연과 같다고 단언한 시험이 실패할 수 있다. 실제 대기가 `maxDelayMs`·`maxIntervalMs`·`maxRetryAfterMs`보다 jitter만큼 길 수 있다. + - 옮기는 법: 시험에 `random: () => 0`을 넣으면 jitter가 0이다. 그 밖에는 하한과 범위로 단언한다. + - 옮긴 뒤 확인: `scripts/verify.sh script test:unit`. ### 보안·계약 변경 @@ -124,6 +132,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 | [계약] | FE-GATE-009의 `test:a11y`가 `playwright.a11y.config.ts`로 돌아 결과 폴더·HTML report·`results.xml`을 `artifacts/tests/a11y/`에 쓴다. 전에는 e2e 설정을 그대로 써서, merge browser job이 008 다음 009를 돌고 올린 e2e 증거가 009 실행의 것이었다. FE-GATE-009 증거에 a11y `results.xml`·`report/index.html`(producer `test-a11y`)이 들어간다. 게이트 밖 `test:e2e:dev`는 `artifacts/tests/e2e-dev/`에 쓴다. 새 시험이 package script가 부르는 Playwright 설정끼리·게이트 명령끼리 결과 경로가 겹치거나, 게이트 명령이 쓰는 JUnit·report가 그 게이트의 증거가 아니면 실패한다. 제거 fixture 사본은 두 새 결과 폴더를 복사하지 않고, 같은 시험이 각 Playwright 설정의 결과 폴더가 그 제외 목록에 드는지 본다. a11y 설정은 FE-GATE-029가 읽도록 `testDir`을 글자로 둔다. 위 "먼저 할 일" (1106 영역 11의 3.2 (3) 증거 읽기 주의) | `package.json`, `playwright.a11y.config.ts`, `playwright.dev.config.ts`, `config/ci/gates.json`, `config/repository-layout.json`, `scripts/lib/removal-fixture.ts`, `tests/unit/playwright-result-paths.test.ts`, `tests/unit/removal-fixture.test.ts`, `tests/unit/ungated-tests.test.ts`, `tests/helpers/playwright-run-isolation.ts`, `tests/unit/ci-workflow-generation.test.ts`, `docs/testing/taxonomy.md`, `docs/work/reference/decisions.md` | `ede99cb9` | | [계약] | `dependency-cache` 단계를 main job(`main_gate`)에도 둔다. 키·경로·main run만 저장·frozen install은 merge job과 같다. release·promotion·provider job은 그대로 거절한다. 위 `7ed0af3d` 행의 「merge job 셋에만」을 바꾼다(decisions.md FE-7) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `.gitea/workflows/quality-gates.yml`, `tests/unit/ci-workflow-generation.test.ts`, `docs/operations/ci-quality-gates.md` | `d254d70a` | | [계약] | FE-GATE-005의 명령이 `test:coverage`·`check:scale:pr` 둘이 된다. `tests/unit`·`tests/contract`의 JUnit 증거(`unit.xml`·`contract.xml`, 이름·형식 그대로)는 coverage 실행 안의 reporter가 쓰고, 두 증거의 producer는 `test-coverage`다. 한 폴더에서 시험 파일이 하나도 돌지 않거나 보고서가 그 폴더에서 돈 파일과 다른 파일을 담으면 그 실행이 실패한다. unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. FE-GATE-004·006·007은 자기 실행을 그대로 둔다(decisions.md FE-4) | `config/ci/gates.json`, `package.json`, `scripts/lib/coverage-bundle-junit-reporter.ts`, `scripts/lib/feature-scaffold-drill.ts`, `tests/unit/coverage-bundle-junit-reporter.test.ts`, `docs/operations/ci-quality-gates.md` | `6cba1f50` | +| [계약] | 서버 힌트(`Retry-After`, SSE `retry`)를 반영하는 재시도 지연을 kernel `delayAfterRetryHint` 하나로 합친다. 힌트가 하한이고 그 위에 한도 있는 jitter를 더하며, 부르는 쪽 상한을 넘으면 다시 보내지 않는다. Browser RPC는 힌트를 잘라 먼저 보내던 동작이 없어지고 선택 칸 `random`(`BrowserRpcRuntimeDependencies`)을 받는다. 재개형 업로드·realtime 재연결·bounded poll은 힌트 시각에 몰리지 않는다. HTTP V3 동작은 같다. scale-architecture 13.3절·계약 16.1 표·VD-28 보완 절을 맞춘다. 위 "먼저 할 일" (REV-FE-0024) | `src/adapters/platform/retry-after.ts`, `src/adapters/browser-rpc/browser-rpc-runtime.ts`, `src/adapters/http/http-retry-lifecycle.ts`, `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts`, `src/adapters/realtime/`, `docs/architecture/scale-architecture.md`, `docs/architecture/backend-api-and-server-state-contract.md` | `4f6e7729`, `8d1c45c3`, `6e47167a` | | [계약] | `check:ci:gating`(FE-GATE-029)이 Playwright 실행의 `--grep`·`--grep-invert`·파일 필터를 읽는다. testDir은 필터 없는 gated 실행이 있거나, `--grep-invert P` 실행마다 같은 testDir을 `--grep P`(같은 글자)로 도는 gated 실행이 있을 때만 게이트 안으로 센다. 파일 필터가 있는 실행, `--grep`·`--grep-invert`를 합쳐 둘 이상 쓴 실행, 설정(또는 그 설정이 import한 설정)에 `grep`·`grepInvert`가 있는 실행은 부분 실행으로 센다. 그 testDir의 게이트 밖 파일은 testDir·실행·빠진 짝을 대는 한 줄로 실패한다. 전에는 009의 Playwright 실행을 빼도 통과해, 시험이 모두 `@a11y`인 `tests/e2e/accessibility.spec.ts`가 어느 게이트에서도 돌지 않았다. `-c X`·`-cX`·`--config=X`로 고른 설정도 이제 읽는다(전에는 e2e 설정의 testDir로 셌다). 위 "먼저 할 일" | `scripts/lib/playwright-test-args.ts`, `scripts/lib/ungated-tests.ts`, `scripts/check-ci-gating.ts`, `playwright.a11y.config.ts`, `tests/unit/playwright-test-args.test.ts`, `tests/unit/ungated-tests.test.ts`, `tests/unit/playwright-result-paths.test.ts`, `docs/operations/ci-quality-gates.md` | `32982e55` | | [보안] | telemetry payload 정제가 복사하는 값의 총수를 `maxNodes`(기본 512)로 막는다. 같은 객체를 여러 key가 가리키는 payload(정규화된 엔티티 graph 등)를 경로마다 따로 복사해, `emit` 한 번이 호출 스택을 수 초 막거나 heap OOM으로 탭을 죽였다. 여러 경로가 가리키는 객체의 key는 한 번만 읽는다. 순회가 너비 우선이 되어 상한이 차면 얕은 필드가 남고 깊은 값이 `[truncated]`가 된다. 복사본 객체의 key 순서가 원본 순서가 된다(전에는 거꾸로, fingerprint는 그대로). 깊이 제한 시험이 잘린 모양과 순환 payload를 단언한다 | `src/platform/telemetry/redact-telemetry.ts`, `src/platform/telemetry/telemetry-pipeline.ts`, `tests/platform/telemetry/redact-telemetry.test.ts`, `config/scale/feature-shape-ceilings.json` | `d406c10b`, `0190b631` | | [계약] | `mapTransportFailure`가 `JsonBudgetExceededError`의 own data `violation`이 `"invalid-json"`이면 `response.invalid`로 분류한다. 전에는 `parseBoundedJson`이 JSON이 아닌 응답에 던진 오류가 `response.too-large`가 되어 날 `SyntaxError`(`response.invalid`)와 갈렸다. 두 kind의 category(`contract`)·retryability(`never`)는 같다. `violation`이 accessor면 부르지 않고 `response.too-large`로 둔다. 시험 표에 fan-out 초과·`TimeoutError`·invalid-json 줄을 더한다 | `src/platform/errors/platform-errors.ts`, `tests/platform/errors/platform-errors.test.ts` | `a934554d` | -- 2.54.0 From 533b1779682f5ae3bbc91c843e9c7ba3d7ca024a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 12:22:21 +0900 Subject: [PATCH 5/6] =?UTF-8?q?fix(retry):=20=EB=82=9C=EC=88=98=20?= =?UTF-8?q?=EB=81=9D=EA=B0=92=EA=B3=BC=20=EB=84=98=EC=B9=9C=20=ED=9E=8C?= =?UTF-8?q?=ED=8A=B8=EC=97=90=EC=84=9C=20=EC=9E=AC=EC=8B=9C=EB=8F=84=20?= =?UTF-8?q?=EA=B7=9C=EC=B9=99=EC=9D=84=20=EC=A7=80=ED=82=A8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 확인 리뷰 Low(F3). kernel은 [0, 1) 표본을 받는데 재개형 업로드의 safeRandom은 1을 받아 jitter가 창과 같아진다(2초 미만이 깨진다). HTTP는 상한을 넘은 힌트에서도 random을 먼저 부른다. random이 예외를 던지면 응답 자체의 실패가 NETWORK_FAILURE로 바뀐다. 고른 방법: 업로드는 이 PR이 더한 호출 줄에서 표본을 1 미만으로 줄인다. HTTP는 상한을 넘으면 난수를 뽑기 전에 null을 돌려준다. 버린 대안: safeRandom이 1을 거절하게 한다. 1을 주던 주입 난수가 실패로 바뀌고 이 PR 밖 파일이다(review 몫). 위험·한계: 다시 리뷰하지 않는다(소유자 2026-11-21 DES-DEC-0005). 시험으로 닫는다. 검증: desktop에서 새 시험 둘이 고치기 전 실패했다(100≠99, random 예외). 고친 뒤 43 tests 통과, types·lint·architecture rc=0. Refs: REV-FE-0024 --- .../resumable-upload/resumable-upload-runtime.ts | 3 ++- src/adapters/http/http-retry-lifecycle.ts | 4 ++++ tests/unit/http-retry-lifecycle.test.ts | 7 +++++++ tests/unit/resumable-upload-runtime.test.ts | 2 ++ 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts b/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts index e9d5c57a..b1e36bc0 100644 --- a/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts +++ b/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts @@ -1487,7 +1487,8 @@ async function waitForRetry( ceilingMs: dependencies.policy.maxRetryAfterMs, localDelayMs: jittered, localWindowMs: exponential, - sample: randomValue.value, + // `safeRandom` admits 1; the kernel's sample is below 1. + sample: Math.min(randomValue.value, 1 - Number.EPSILON), }); // `canRetry` admits no hint past the ceiling, so this does not wait less. if (delayMs === null) { diff --git a/src/adapters/http/http-retry-lifecycle.ts b/src/adapters/http/http-retry-lifecycle.ts index 66588a23..7f8ecd5f 100644 --- a/src/adapters/http/http-retry-lifecycle.ts +++ b/src/adapters/http/http-retry-lifecycle.ts @@ -52,6 +52,10 @@ export function retryDelayFor( retryIndex: number, random: () => number, ): number | null { + // A refused hint needs no sample. + if (retryAfterMs !== null && retryAfterMs > RETRY_AFTER_CEILING_MS) { + return null; + } const sample = random(); return delayAfterRetryHint({ hintMs: retryAfterMs, diff --git a/tests/unit/http-retry-lifecycle.test.ts b/tests/unit/http-retry-lifecycle.test.ts index 9841e443..07cd1603 100644 --- a/tests/unit/http-retry-lifecycle.test.ts +++ b/tests/unit/http-retry-lifecycle.test.ts @@ -47,5 +47,12 @@ describe("HTTP retry lifecycle policy", () => { expect(retryDelayFor(400, 0, () => 0.5)).toBe(525); expect(retryDelayFor(400, 0, () => 0)).toBe(400); expect(retryDelayFor(5_001, 0, () => 0.5)).toBeNull(); + // A refused hint needs no sample, so a failing random cannot replace the + // response's own failure. + expect( + retryDelayFor(5_001, 0, () => { + throw new Error("random is unavailable"); + }), + ).toBeNull(); }); }); diff --git a/tests/unit/resumable-upload-runtime.test.ts b/tests/unit/resumable-upload-runtime.test.ts index 817c186b..4426e0a7 100644 --- a/tests/unit/resumable-upload-runtime.test.ts +++ b/tests/unit/resumable-upload-runtime.test.ts @@ -584,6 +584,8 @@ describe("production resumable upload runtime", () => { it.each([ [0, 80, 1, 80], [0.999, 80, 1, 99], + // This runtime's random may return 1; the jitter stays below its window. + [1, 80, 1, 99], // The ceiling bounds the hint; the jitter goes above it. [0.999, 100, 1, 124], // The local window is wider than a quarter of the hint. -- 2.54.0 From 47cd11900c49886a9a6abd4f60a1a1397452c516 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 12:22:21 +0900 Subject: [PATCH 6/6] =?UTF-8?q?docs(changelog):=20=EC=9E=AC=EC=8B=9C?= =?UTF-8?q?=EB=8F=84=EA=B0=80=20=EC=97=AC=EB=9F=BF=EC=9D=BC=20=EB=95=8C?= =?UTF-8?q?=EC=9D=98=20deadline=EA=B3=BC=20timeout=20=EC=9C=84=ED=97=98?= =?UTF-8?q?=EC=9D=84=20=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 확인 리뷰 Low(F1·F2). 옮기는 법이 재시도 한 번만 세어 maxAttempts 3~4에서 모자란 deadline을 권한다. 상한 안 힌트만 받던 설정에서도 timeout이 새로 날 수 있다는 것이 없다. 고른 방법: deadline을 모든 시도와 재시도마다의 대기 합으로 적고, jitter 몫 여유를 옮기는 법에 더한다. 커밋 목록에 앞 커밋을 더한다. 위험·한계: 문서만 바꾼다. Refs: REV-FE-0024 --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index edbe86dd..decce241 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,11 +90,11 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 - 옮긴 뒤 확인: `scripts/verify.sh script check:architecture`. - Browser RPC가 profile `maxRetryAfterMs`를 넘는 `Retry-After`에서 재시도하지 않는다. 전에는 그 값으로 잘라 더 일찍 다시 보냈다(REV-FE-0024). - 옮기기 전: `retryOwner: "FRONTEND_ADAPTER"`인 profile의 `maxRetryAfterMs`가 서버가 주는 힌트보다 작으면(0 포함) 재시도되던 호출이 그 힌트를 실은 실패에서 끝난다. 결과는 그 실패의 kind·code와 `retryAfterMs`다. 남은 deadline도 모자라 `RPC_RETRY_BUDGET_EXHAUSTED`로 끝나던 호출도 이제 그 실패의 code로 끝난다. - - 옮기는 법: 자기 서버가 주는 힌트의 최댓값까지 `maxRetryAfterMs`를 올리고(하드 상한은 `BROWSER_RPC_HARD_LIMITS`), operation `totalDeadlineMs`를 「첫 시도 + max(backoff, 힌트 + jitter 상한 2초) + 다시 보낸 시도」보다 길게 둔다. 기다리지 않을 것이면 그대로 둔다. + - 옮기는 법: 자기 서버가 주는 힌트의 최댓값까지 `maxRetryAfterMs`를 올리고(하드 상한은 `BROWSER_RPC_HARD_LIMITS`), operation `totalDeadlineMs`를 「보낼 수 있는 시도(`maxAttempts`번) 시간의 합 + 재시도마다 max(그 차례 backoff, 힌트 + jitter 상한 2초)의 합」보다 길게 둔다. 기다리지 않을 것이면 그대로 둔다. - 옮긴 뒤 확인: 자기 profile과 deadline으로 상한과 같은 힌트는 재시도되고 넘는 힌트는 재시도되지 않는지 시험한다. - 재개형 업로드·realtime 재연결·bounded poll·Browser RPC가 서버 힌트 위에 jitter(2초 미만)를 더해 다시 보낸다(REV-FE-0024). - - 옮기기 전: 대기가 힌트와 같거나, 힌트보다 늦은 로컬 지연과 같다고 단언한 시험이 실패할 수 있다. 실제 대기가 `maxDelayMs`·`maxIntervalMs`·`maxRetryAfterMs`보다 jitter만큼 길 수 있다. - - 옮기는 법: 시험에 `random: () => 0`을 넣으면 jitter가 0이다. 그 밖에는 하한과 범위로 단언한다. + - 옮기기 전: 대기가 힌트와 같거나, 힌트보다 늦은 로컬 지연과 같다고 단언한 시험이 실패할 수 있다. 실제 대기가 `maxDelayMs`·`maxIntervalMs`·`maxRetryAfterMs`보다 jitter만큼 길 수 있다. 상한 안의 힌트만 받던 설정도 다시 보낸 시도에 남는 시간이 줄어 timeout이 새로 날 수 있다. + - 옮기는 법: 시간 예산(`totalDeadlineMs`, `maxElapsedMs`)을 재시도마다 더해지는 jitter 상한 2초만큼 여유 있게 둔다. 시험에 `random: () => 0`을 넣으면 jitter가 0이다. 그 밖에는 하한과 범위로 단언한다. - 옮긴 뒤 확인: `scripts/verify.sh script test:unit`. ### 보안·계약 변경 @@ -132,7 +132,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 | [계약] | FE-GATE-009의 `test:a11y`가 `playwright.a11y.config.ts`로 돌아 결과 폴더·HTML report·`results.xml`을 `artifacts/tests/a11y/`에 쓴다. 전에는 e2e 설정을 그대로 써서, merge browser job이 008 다음 009를 돌고 올린 e2e 증거가 009 실행의 것이었다. FE-GATE-009 증거에 a11y `results.xml`·`report/index.html`(producer `test-a11y`)이 들어간다. 게이트 밖 `test:e2e:dev`는 `artifacts/tests/e2e-dev/`에 쓴다. 새 시험이 package script가 부르는 Playwright 설정끼리·게이트 명령끼리 결과 경로가 겹치거나, 게이트 명령이 쓰는 JUnit·report가 그 게이트의 증거가 아니면 실패한다. 제거 fixture 사본은 두 새 결과 폴더를 복사하지 않고, 같은 시험이 각 Playwright 설정의 결과 폴더가 그 제외 목록에 드는지 본다. a11y 설정은 FE-GATE-029가 읽도록 `testDir`을 글자로 둔다. 위 "먼저 할 일" (1106 영역 11의 3.2 (3) 증거 읽기 주의) | `package.json`, `playwright.a11y.config.ts`, `playwright.dev.config.ts`, `config/ci/gates.json`, `config/repository-layout.json`, `scripts/lib/removal-fixture.ts`, `tests/unit/playwright-result-paths.test.ts`, `tests/unit/removal-fixture.test.ts`, `tests/unit/ungated-tests.test.ts`, `tests/helpers/playwright-run-isolation.ts`, `tests/unit/ci-workflow-generation.test.ts`, `docs/testing/taxonomy.md`, `docs/work/reference/decisions.md` | `ede99cb9` | | [계약] | `dependency-cache` 단계를 main job(`main_gate`)에도 둔다. 키·경로·main run만 저장·frozen install은 merge job과 같다. release·promotion·provider job은 그대로 거절한다. 위 `7ed0af3d` 행의 「merge job 셋에만」을 바꾼다(decisions.md FE-7) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `.gitea/workflows/quality-gates.yml`, `tests/unit/ci-workflow-generation.test.ts`, `docs/operations/ci-quality-gates.md` | `d254d70a` | | [계약] | FE-GATE-005의 명령이 `test:coverage`·`check:scale:pr` 둘이 된다. `tests/unit`·`tests/contract`의 JUnit 증거(`unit.xml`·`contract.xml`, 이름·형식 그대로)는 coverage 실행 안의 reporter가 쓰고, 두 증거의 producer는 `test-coverage`다. 한 폴더에서 시험 파일이 하나도 돌지 않거나 보고서가 그 폴더에서 돈 파일과 다른 파일을 담으면 그 실행이 실패한다. unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. FE-GATE-004·006·007은 자기 실행을 그대로 둔다(decisions.md FE-4) | `config/ci/gates.json`, `package.json`, `scripts/lib/coverage-bundle-junit-reporter.ts`, `scripts/lib/feature-scaffold-drill.ts`, `tests/unit/coverage-bundle-junit-reporter.test.ts`, `docs/operations/ci-quality-gates.md` | `6cba1f50` | -| [계약] | 서버 힌트(`Retry-After`, SSE `retry`)를 반영하는 재시도 지연을 kernel `delayAfterRetryHint` 하나로 합친다. 힌트가 하한이고 그 위에 한도 있는 jitter를 더하며, 부르는 쪽 상한을 넘으면 다시 보내지 않는다. Browser RPC는 힌트를 잘라 먼저 보내던 동작이 없어지고 선택 칸 `random`(`BrowserRpcRuntimeDependencies`)을 받는다. 재개형 업로드·realtime 재연결·bounded poll은 힌트 시각에 몰리지 않는다. HTTP V3 동작은 같다. scale-architecture 13.3절·계약 16.1 표·VD-28 보완 절을 맞춘다. 위 "먼저 할 일" (REV-FE-0024) | `src/adapters/platform/retry-after.ts`, `src/adapters/browser-rpc/browser-rpc-runtime.ts`, `src/adapters/http/http-retry-lifecycle.ts`, `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts`, `src/adapters/realtime/`, `docs/architecture/scale-architecture.md`, `docs/architecture/backend-api-and-server-state-contract.md` | `4f6e7729`, `8d1c45c3`, `6e47167a` | +| [계약] | 서버 힌트(`Retry-After`, SSE `retry`)를 반영하는 재시도 지연을 kernel `delayAfterRetryHint` 하나로 합친다. 힌트가 하한이고 그 위에 한도 있는 jitter를 더하며, 부르는 쪽 상한을 넘으면 다시 보내지 않는다. Browser RPC는 힌트를 잘라 먼저 보내던 동작이 없어지고 선택 칸 `random`(`BrowserRpcRuntimeDependencies`)을 받는다. 재개형 업로드·realtime 재연결·bounded poll은 힌트 시각에 몰리지 않는다. HTTP V3 동작은 같다. scale-architecture 13.3절·계약 16.1 표·VD-28 보완 절을 맞춘다. 위 "먼저 할 일" (REV-FE-0024) | `src/adapters/platform/retry-after.ts`, `src/adapters/browser-rpc/browser-rpc-runtime.ts`, `src/adapters/http/http-retry-lifecycle.ts`, `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts`, `src/adapters/realtime/`, `docs/architecture/scale-architecture.md`, `docs/architecture/backend-api-and-server-state-contract.md` | `4f6e7729`, `8d1c45c3`, `6e47167a`, `533b1779` | | [계약] | `check:ci:gating`(FE-GATE-029)이 Playwright 실행의 `--grep`·`--grep-invert`·파일 필터를 읽는다. testDir은 필터 없는 gated 실행이 있거나, `--grep-invert P` 실행마다 같은 testDir을 `--grep P`(같은 글자)로 도는 gated 실행이 있을 때만 게이트 안으로 센다. 파일 필터가 있는 실행, `--grep`·`--grep-invert`를 합쳐 둘 이상 쓴 실행, 설정(또는 그 설정이 import한 설정)에 `grep`·`grepInvert`가 있는 실행은 부분 실행으로 센다. 그 testDir의 게이트 밖 파일은 testDir·실행·빠진 짝을 대는 한 줄로 실패한다. 전에는 009의 Playwright 실행을 빼도 통과해, 시험이 모두 `@a11y`인 `tests/e2e/accessibility.spec.ts`가 어느 게이트에서도 돌지 않았다. `-c X`·`-cX`·`--config=X`로 고른 설정도 이제 읽는다(전에는 e2e 설정의 testDir로 셌다). 위 "먼저 할 일" | `scripts/lib/playwright-test-args.ts`, `scripts/lib/ungated-tests.ts`, `scripts/check-ci-gating.ts`, `playwright.a11y.config.ts`, `tests/unit/playwright-test-args.test.ts`, `tests/unit/ungated-tests.test.ts`, `tests/unit/playwright-result-paths.test.ts`, `docs/operations/ci-quality-gates.md` | `32982e55` | | [보안] | telemetry payload 정제가 복사하는 값의 총수를 `maxNodes`(기본 512)로 막는다. 같은 객체를 여러 key가 가리키는 payload(정규화된 엔티티 graph 등)를 경로마다 따로 복사해, `emit` 한 번이 호출 스택을 수 초 막거나 heap OOM으로 탭을 죽였다. 여러 경로가 가리키는 객체의 key는 한 번만 읽는다. 순회가 너비 우선이 되어 상한이 차면 얕은 필드가 남고 깊은 값이 `[truncated]`가 된다. 복사본 객체의 key 순서가 원본 순서가 된다(전에는 거꾸로, fingerprint는 그대로). 깊이 제한 시험이 잘린 모양과 순환 payload를 단언한다 | `src/platform/telemetry/redact-telemetry.ts`, `src/platform/telemetry/telemetry-pipeline.ts`, `tests/platform/telemetry/redact-telemetry.test.ts`, `config/scale/feature-shape-ceilings.json` | `d406c10b`, `0190b631` | | [계약] | `mapTransportFailure`가 `JsonBudgetExceededError`의 own data `violation`이 `"invalid-json"`이면 `response.invalid`로 분류한다. 전에는 `parseBoundedJson`이 JSON이 아닌 응답에 던진 오류가 `response.too-large`가 되어 날 `SyntaxError`(`response.invalid`)와 갈렸다. 두 kind의 category(`contract`)·retryability(`never`)는 같다. `violation`이 accessor면 부르지 않고 `response.too-large`로 둔다. 시험 표에 fan-out 초과·`TimeoutError`·invalid-json 줄을 더한다 | `src/platform/errors/platform-errors.ts`, `tests/platform/errors/platform-errors.test.ts` | `a934554d` | -- 2.54.0