From dae44f5cf4bd259315b66209422d31c632dd72ba Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 21:58:39 +0900 Subject: [PATCH 01/74] =?UTF-8?q?test(http):=20interaction=20signal=20list?= =?UTF-8?q?ener=20=EC=A0=95=EB=A6=AC=EB=8F=84=20=EA=B3=A0=EC=A0=95?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 실행기는 호출자·interaction·scope 세 signal에 abort listener를 달고 끝날 때 셋을 모두 지운다(src/adapters/http/http-execution-v3.ts:662-664). listener 정리 테스트는 호출자와 scope signal만 감시해서, interaction signal 쪽 제거 줄(:663)을 지운 변이 R2b가 107파일 995개를 모두 통과했다. 한 interaction 안에서 요청을 여러 번 보내면 요청마다 listener 하나(lifetime controller를 잡은 closure)가 interaction 마감까지 남는다. 고른 방법과 버린 대안 - 같은 테스트(tests/unit/http-execution-v3.test.ts)에 createExecutionContext로 만든 interaction을 넘기고, 그 cancellation.signal도 감시 목록에 넣는다. - 끝나는 경우에 "interaction cancel"을 더한다. interaction 취소는 호출자 abort와 같은 forwarder를 타지만 listener를 단 signal이 달라서 따로 본다. - 별도 테스트를 새로 만드는 안은 버렸다. 세 signal은 같은 정리 함수가 지우므로 한 테스트에서 함께 보는 편이 규칙과 맞다. 위험·한계 - 테스트만 바꿨다. 실행기 코드는 그대로다. 실제 누수량은 재지 않는다. 검증 - desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/http-execution-v3.test.ts - 변이 R2b(:663 제거)를 넣으면 세 경우 모두 "removes the listeners it added to the caller, interaction and scope signals after …"가 실패해야 한다. Refs: 1105/10-02 --- tests/unit/http-execution-v3.test.ts | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/tests/unit/http-execution-v3.test.ts b/tests/unit/http-execution-v3.test.ts index 06757200..e9b1ec8b 100644 --- a/tests/unit/http-execution-v3.test.ts +++ b/tests/unit/http-execution-v3.test.ts @@ -761,15 +761,29 @@ describe("descriptor-driven HTTP execution lifetime", () => { await expect(result).resolves.toMatchObject({ kind: "CANCELLED" }); }); - // 1103/10-04 ②. A signal is shared by many requests (a screen, a session - // scope). Every abort listener an execution adds to the caller's and the + // 1103/10-04 ②, 1105/10-02. A signal is shared by many requests (a screen, + // a session scope, one interaction that sends several requests). Every abort + // listener an execution adds to the caller's, the interaction's and the // scope's signal is removed when it ends, however it ends. - it.each(["an answer", "a caller abort"] as const)( - "removes the listeners it added to the caller and scope signals after %s", + it.each(["an answer", "a caller abort", "an interaction cancel"] as const)( + "removes the listeners it added to the caller, interaction and scope signals after %s", async (ending) => { const caller = new AbortController(); const scopeLifetime = new AbortController(); - const watched = [caller.signal, scopeLifetime.signal].map((signal) => ({ + const interaction = createExecutionContext({ + interactionId: "listener-cleanup", + deadlineMs: 10_000, + traffic: { + maxPhysicalRequests: 4, + maxRetries: 2, + maxConcurrentRequests: 1, + }, + }); + const watched = [ + caller.signal, + interaction.cancellation.signal, + scopeLifetime.signal, + ].map((signal) => ({ add: vi.spyOn(signal, "addEventListener"), remove: vi.spyOn(signal, "removeEventListener"), })); @@ -784,8 +798,10 @@ describe("descriptor-driven HTTP execution lifetime", () => { routeId: ROUTE_ID, scope: { ...scope, signal: scopeLifetime.signal }, signal: caller.signal, + execution: interaction, }); if (ending === "a caller abort") caller.abort(); + if (ending === "an interaction cancel") interaction.cancellation.cancel(); await expect(result).resolves.toMatchObject({ kind: ending === "an answer" ? "SUCCESS" : "CANCELLED", -- 2.54.0 From bde7fa4609960d87fb07be7712b4c5b1fa08ff6e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:01:01 +0900 Subject: [PATCH 02/74] =?UTF-8?q?test(realtime):=20=EC=A1=B0=ED=95=A9=20tr?= =?UTF-8?q?ansport=EC=9D=98=20OFFLINE=20=EC=9E=AC=EC=8B=9C=EB=8F=84=20?= =?UTF-8?q?=EA=B7=9C=EC=B9=99=EC=9D=84=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= =?UTF-8?q?=EB=A1=9C=20=EB=8B=A4=EC=8B=9C=20=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 0929/04-01 규칙은 "환경이 online이면 transport가 낸 OFFLINE도 online 이벤트를 기다리지 않고 backoff로 재시도한다"이다 (reconnect-coordinator.ts의 RealtimeReconnectEnvironment 주석, 설계 5.3). 이 규칙을 막던 두 테스트는 SSE fetch·reader 거절이 OFFLINE이던 것을 이용했다. af00067(1103/04-04)이 SSE 거절을 PROVIDER_UNAVAILABLE로 바꾼 뒤 두 테스트는 그 kind의 재시도만 본다. 4d27b20이 지운 requireOnline() 두 줄을 되살리는 변이(MR1)에서 realtime 테스트가 모두 통과했다(리뷰 04-R4). 고른 방법: 조합 코드가 만든 transport로 그 경로를 직접 지나는 테스트 둘을 더한다. 환경은 계속 online이다. - attempt가 OFFLINE/CONNECT/retryable로 실패한다 → 3회 시도, backoff [50, 100], OFFLINE retryable로 끝난다. 관측 순서도 고정한다. - 세션이 열린 뒤 OFFLINE/RECEIVE/retryable로 닫힌다 → 3회 시도, OFFLINE retryable로 끝난다. 리뷰 대조 C1·C2와 같은 입력이고, `as never` 없이 파일의 도우미를 쓴다. 버린 대안: SSE 테스트 기대값을 OFFLINE으로 되돌리기. 템플릿 SSE는 이제 OFFLINE을 내지 않으므로 실제 동작과 다른 테스트가 된다. 위험·한계: 테스트만 더했다. 동작은 바뀌지 않는다. 그래서 RED(부모 코드)에서도 이 테스트는 통과한다. 결함을 보이는 방법은 변이 MR1이다. 검증: desktop batch에서 확인. - GREEN: node scripts/run-vitest.ts run tests/unit/realtime/ - 변이 MR1(reconnect-coordinator.ts의 두 retry 분기 뒤 OFFLINE이면 requireOnline()): 새 두 테스트가 attempts 1, result null로 실패해야 한다 Refs: 1105/04-01 --- .../realtime-reconnect-coordinator.test.ts | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts index abf6b80e..5ef1faf7 100644 --- a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts +++ b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts @@ -2198,6 +2198,93 @@ describe("transport failures through the reconnect coordinator", () => { ]); }); + // 1105/04-01. No template transport reports OFFLINE any more (1103/04-04), + // so the two SSE tests above no longer reach the 0929/04-01 rule. A + // composer's transport (a STOMP one, say) still may. While the environment + // stays online, its OFFLINE is retried with backoff; waiting for an online + // event that never comes would park the run with no retry and no result. + it("retries a composer transport's OFFLINE attempt failure while the browser stays online", async () => { + const clock = new ManualClock(); + const offline = realtimeFailure("OFFLINE", "CONNECT", true); + const observed: string[] = []; + let attempts = 0; + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy(), + environment: new MutableOnlineEnvironment(true), + clock, + random: () => 0.5, + confirmTransportBarrier: confirmationSucceeded, + attempt: () => { + attempts += 1; + return failed(offline); + }, + observe: (observation) => observed.push(observationLabel(observation)), + }); + + let result: RealtimeResult | null = null; + void coordinator.run().then((value) => { + result = value; + }); + await advanceUntil(clock, () => result !== null); + + expect(attempts).toBe(3); + expect(clock.sleepCalls).toEqual([50, 100]); + expect(result).toEqual({ + ok: false, + error: { kind: "OFFLINE", operation: "CONNECT", retryable: true }, + }); + expect(observed).toEqual([ + "ATTEMPT_STARTED", + "RETRY_SCHEDULED:OFFLINE", + "ATTEMPT_STARTED", + "RETRY_SCHEDULED:OFFLINE", + "ATTEMPT_STARTED", + "RUN_ENDED:OFFLINE:EXHAUSTED", + ]); + }); + + it("reconnects after a composer session closes with OFFLINE while the browser stays online", async () => { + const clock = new ManualClock(); + const offline = realtimeFailure("OFFLINE", "RECEIVE", true); + const observed: string[] = []; + let attempts = 0; + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy(), + environment: new MutableOnlineEnvironment(true), + clock, + random: () => 0.5, + confirmTransportBarrier: confirmationSucceeded, + attempt: () => { + attempts += 1; + return opened( + Object.freeze({ + classifyClosed: ( + receipt: RealtimeReconnectOutcome, + ) => receipt, + close: vi.fn(), + waitClosed: () => failed(offline), + }), + ); + }, + observe: (observation) => observed.push(observationLabel(observation)), + }); + + let result: RealtimeResult | null = null; + void coordinator.run().then((value) => { + result = value; + }); + await advanceUntil(clock, () => result !== null); + + expect(attempts).toBe(3); + expect(result).toEqual({ + ok: false, + error: { kind: "OFFLINE", operation: "RECEIVE", retryable: true }, + }); + expect( + observed.filter((label) => label === "RETRY_SCHEDULED:OFFLINE"), + ).toHaveLength(2); + }); + it.each(["before", "after"] as const)( "waits for the online event when the browser goes offline %s the SSE fetch rejects", async (order) => { -- 2.54.0 From 05330e30a844d0dfd2cda8885df6667a4ae0f1ad Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:03:56 +0900 Subject: [PATCH 03/74] =?UTF-8?q?fix(realtime)!:=20=EB=8D=98=EC=A7=80?= =?UTF-8?q?=EB=8A=94=20poll=20execute=EB=A5=BC=20=EC=84=9C=EB=B2=84=20?= =?UTF-8?q?=EC=9E=A5=EC=95=A0=EA=B0=80=20=EC=95=84=EB=8B=88=EB=9D=BC=20PRO?= =?UTF-8?q?TOCOL=5FMISMATCH=EB=A1=9C=20=EB=81=9D=EB=82=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: bounded poll은 `execute`의 throw를 PROVIDER_UNAVAILABLE/retryable로 바꿔 lease 안에서 다시 부른다(af00067). 설계 9.2가 권하는 조합은 `execute` 안에서 V3 실행기를 부르는 것이고, 실행기는 fetch 거절을 던지지 않고 NETWORK_FAILURE 결과로 돌려준다. 그래서 그 조합에서 throw는 결과 매핑·디코딩 같은 조합 코드 결함이다. 지금은 그 결함이 maxAttempts번의 요청과 ATTEMPT_FINISHED: PROVIDER_UNAVAILABLE, 끝으로 POLL_BUDGET_EXHAUSTED가 되어 서버 장애로 보인다. 원인 예외는 남지 않는다. 고른 방법: 리뷰 04-02의 선택지 (b). throw를 모양이 틀린 결과와 같은 계약 위반으로 본다. coordinator는 이미 `parseAttemptResult`가 거절한 결과를 재시도 없이 PROTOCOL_MISMATCH로 끝낸다. throw도 그 길로 보낸다. lease 자신의 abort로 생긴 throw는 지금처럼 abort의 이유(ABORTED, OFFLINE, 예산 소진 등)로 끝난다. `execute` 타입 주석, 설계 9.2와 13.1의 PROVIDER_UNAVAILABLE·PROTOCOL_MISMATCH 행을 같이 고쳤다. 버린 대안: - (c) 주석과 13.1에만 "throw는 서버 장애로 재시도된다"를 적기. 완료 기준은 "결과를 보고 조합 결함과 서버 장애를 구분한다"인데, (c)는 읽는 사람만 알고 결과는 그대로라 구분할 수 없다. - 관측에 throw 표시 칸을 더하기. 닫힌 관측 어휘를 넓히고, 결과 kind는 여전히 서버 장애다. 위험·한계: - 배럴로 공개된 bounded poll의 결과가 바뀐다. repo 안 소비자는 테스트뿐이다. - `fetch`를 직접 부르는 조합은 네트워크 실패를 결과로 바꾸지 않으면 첫 거절에서 lease가 끝난다. 설계가 권하지 않는 조합이고, 타입 주석과 9.2가 "실패도 결과로 돌려준다"를 적는다. - reconnect coordinator는 던지는 `attempt`를 계속 PROVIDER_UNAVAILABLE로 재시도한다. 그쪽 attempt는 브라우저 연결 API를 감싸는 자리라 이번 범위 밖이다. - CHANGELOG.md 미출시 [계약] 행의 "poll은 던지는 execute도 lease 안에서 다시 시도한다"는 이 커밋과 맞지 않는다. CHANGELOG는 오케스트레이터가 고친다. 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/realtime/ - RED: "ends the lease with PROTOCOL_MISMATCH for an async execute that rejects"·"... throws before returning"가 옛 코드에서 execute 3회, POLL_BUDGET_EXHAUSTED로 실패한다. "keeps ABORTED ..."는 양쪽에서 통과한다 (보존 조건). BREAKING CHANGE: createBoundedPollCoordinator의 `execute`가 던지면(abort로 생긴 것 제외) 재시도 없이 PROTOCOL_MISMATCH(retryable: false)로 lease가 끝난다. 전에는 PROVIDER_UNAVAILABLE로 maxAttempts까지 재시도했다. 네트워크 실패를 throw로 내던 `execute`는 그것을 retryable PROVIDER_UNAVAILABLE 결과로 바꿔 돌려준다. Refs: 1105/04-02 --- ...ime-events-web-push-and-bounded-polling.md | 7 +- .../polling/bounded-poll-coordinator.ts | 25 +++-- .../realtime/bounded-poll-coordinator.test.ts | 103 ++++++++++++------ 3 files changed, 92 insertions(+), 43 deletions(-) diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index a0d3a2e7..428776d0 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1667,7 +1667,8 @@ poll coordinator는 실행할 V3 descriptor(`InstalledHttpContract`, 조립된 (`http-execution-v3.ts` `retryCeiling`). 이 값을 descriptor에서 읽으므로, poll에 묶은 descriptor가 0이면 실행기의 `maxRetryAttempts`(`MAX_RETRY_ATTEMPTS`)와 상관없이 poll 한 attempt가 요청 한 번이다. 같은 descriptor를 `execute` 안에서 실행기에 -넘긴다. 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 +넘긴다. `execute`는 서버·네트워크 실패도 결과로 돌려준다. 던지면 조합 코드 +결함으로 보고 재시도 없이 `PROTOCOL_MISMATCH`로 lease를 끝낸다(1105/04-02). 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 거절된다. poll 전용 operation을 따로 등록한다. V3에는 401 재전송이 없다. command/mutation, GraphQL subscription, Connect/gRPC-Web server stream과 arbitrary status URL은 poll하지 않는다. TanStack Query retry도 `false`여야 한다. @@ -1958,8 +1959,8 @@ credential을 보호할 수 있다고 주장하지 않는다. | `AUTH_REQUIRED` | session expired/recovery 실패 | sign-in UX | | `FORBIDDEN` | stream/resource 거절 | retry 없음 | | `RATE_LIMITED` | connection/request/provider limit | bounded server hint | -| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. 환경은 online인데 서버·프록시에 닿지 않은 것(SSE fetch·reader 거절, WebSocket `error`, poll `execute` 거절)도 세 transport 모두 이 kind다(1103/04-04, `retryable: true`). stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 | -| `PROTOCOL_MISMATCH` | version/subprotocol/content type | terminal/rollout rollback | +| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. 환경은 online인데 서버·프록시에 닿지 않은 것(SSE fetch·reader 거절, WebSocket `error`)도 이 kind다(1103/04-04, `retryable: true`). poll은 `execute`가 돌려준 결과의 kind를 쓴다. V3 실행기는 fetch 거절을 던지지 않고 `NETWORK_FAILURE` 결과로 돌려주므로, `execute`가 그 결과를 이 kind로 바꾼다. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 | +| `PROTOCOL_MISMATCH` | version/subprotocol/content type. poll `execute`가 던지거나 모양이 틀린 결과를 돌려준 것도 이 kind다. 조합 코드 결함이라 서버 장애로 재시도하지 않는다(1105/04-02, `retryable: false`) | terminal/rollout rollback | | `MALFORMED_EVENT` | state-bearing syntax/schema/exact-key 실패 | cursor 미진행, freshness `UNKNOWN`, close + registered recovery | | `MAPPING_CONTRACT_VIOLATION` | validated DTO의 registered mapper 실패 | effect/cache/cursor write 0, close + registered recovery | | `EVENT_CONFLICT` | 같은 ID/sequence가 다른 event를 가리킴 | terminal protocol conflict + resync/rollback | diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index c92908d3..f2f73202 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -101,6 +101,12 @@ export type BoundedPollCoordinatorDependencies = Readonly<{ * refuses one whose `frontend.retryBudget` is not 0. */ operation: BoundedPollOperation; + /** + * Returns every outcome as a result, server and network failures included + * (the V3 executor returns a rejected fetch as NETWORK_FAILURE). A throw, + * like a result of the wrong shape, ends the lease with PROTOCOL_MISMATCH + * and is not retried: it is a composition defect, not a server outage. + */ execute(input: Readonly<{ operationId: string; attempt: number; @@ -300,7 +306,7 @@ export function createBoundedPollCoordinator( } attempts += 1; - let result: BoundedPollAttemptResult; + let result: BoundedPollAttemptResult | null; const attemptOutcome = await awaitWithinLease( () => trackWork( @@ -320,12 +326,14 @@ export function createBoundedPollCoordinator( if (attemptOutcome.kind === "VALUE") { result = attemptOutcome.value; } else if (attemptOutcome.kind === "REJECTED") { - // 1103/04-04. No server answered; OFFLINE is the environment's. - result = realtimeFailure( - controller.signal.aborted ? "ABORTED" : "PROVIDER_UNAVAILABLE", - "POLL", - !controller.signal.aborted, - ); + // 1105/04-02. `execute` returns every failure as a result; the V3 + // executor already returns a rejected fetch as NETWORK_FAILURE. A + // throw is a composition defect, read below like a malformed + // result, not retried as a server outage. One caused by this + // lease's abort ends with the abort's reason. + result = controller.signal.aborted + ? realtimeFailure("ABORTED", "POLL", false) + : null; } else { if (attemptOutcome.kind === "CLOCK_FAILED") { controller.abort(); @@ -374,7 +382,8 @@ export function createBoundedPollCoordinator( return pollFailure("POLL_BUDGET_EXHAUSTED"); } - const parsedResult = parseAttemptResult(result); + const parsedResult = + result === null ? null : parseAttemptResult(result); if (!parsedResult) { return pollFailure("PROTOCOL_MISMATCH"); } diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index c2c9cfd3..cbd8e735 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -903,47 +903,86 @@ describe("bounded poll coordinator", () => { }); }); - // 1103/04-04. A rejected executor means the request did not reach a server - // that answered. It is PROVIDER_UNAVAILABLE, retried within the lease like - // one the executor reports; OFFLINE comes only from the environment. - it("retries a throwing executor as PROVIDER_UNAVAILABLE within the lease", async () => { + // 1105/04-02. `execute` returns server and network failures as results (the + // V3 executor returns a rejected fetch as NETWORK_FAILURE). A throw is a + // composition defect, like a malformed result: the lease ends at once with + // PROTOCOL_MISMATCH instead of retrying it as a server outage until the + // budget runs out. + it.each([ + ["an async execute that rejects", async () => { + throw new TypeError("Cannot read properties of undefined"); + }], + ["an execute that throws before returning", () => { + throw new TypeError("Cannot read properties of undefined"); + }], + ] as const)( + "ends the lease with PROTOCOL_MISMATCH for %s", + async (_label, body) => { + const clock = new ManualClock(); + const observations: BoundedPollObservation[] = []; + const execute = vi.fn( + body as () => Promise>, + ); + const coordinator = createBoundedPollCoordinator({ + policy, + operation, + environment: new MutableEnvironment(), + clock, + random: () => 0.5, + execute, + observe: (observation) => observations.push(observation), + }); + + let result: unknown = null; + void coordinator.run().then((value) => { + result = value; + }); + for (let turn = 0; turn < 120 && result === null; turn += 1) { + clock.advance(1_000); + await flush(); + } + + expect(execute).toHaveBeenCalledTimes(1); + expect(result).toEqual({ + ok: false, + error: { + kind: "PROTOCOL_MISMATCH", + operation: "POLL", + retryable: false, + }, + }); + expect(observations).toEqual([ + { kind: "LEASE_STARTED" }, + { kind: "LEASE_STOPPED", outcome: "PROTOCOL_MISMATCH" }, + ]); + expect(coordinator.getState()).toBe("IDLE"); + }, + ); + + it("keeps ABORTED when execute rejects because the caller aborted", async () => { const clock = new ManualClock(); - const observations: BoundedPollObservation[] = []; - const execute = vi.fn(async (): Promise> => { - throw new TypeError("Failed to fetch"); - }); + const caller = new AbortController(); const coordinator = createBoundedPollCoordinator({ policy, operation, environment: new MutableEnvironment(), clock, - random: () => 0.5, - execute, - observe: (observation) => observations.push(observation), + execute: ({ signal }) => + new Promise>((_resolve, reject) => { + signal.addEventListener( + "abort", + () => reject(new DOMException("Aborted", "AbortError")), + { once: true }, + ); + caller.abort(); + }), }); - let result: unknown = null; - void coordinator.run().then((value) => { - result = value; - }); - for (let turn = 0; turn < 120 && result === null; turn += 1) { - clock.advance(1_000); - await flush(); - } - - expect(execute).toHaveBeenCalledTimes(policy.maxAttempts); - expect( - observations - .filter((observation) => observation.kind === "ATTEMPT_FINISHED") - .map((observation) => observation.outcome), - ).toEqual([ - "PROVIDER_UNAVAILABLE", - "PROVIDER_UNAVAILABLE", - "PROVIDER_UNAVAILABLE", - ]); - expect(result).toMatchObject({ + const running = coordinator.run({ signal: caller.signal }); + clock.advance(5_000); + await expect(running).resolves.toEqual({ ok: false, - error: { kind: "POLL_BUDGET_EXHAUSTED", operation: "POLL" }, + error: { kind: "ABORTED", operation: "POLL", retryable: false }, }); }); -- 2.54.0 From 27e3dec5dd5848d8e4777a75577d67812b1f7e92 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:05:31 +0900 Subject: [PATCH 04/74] =?UTF-8?q?fix(realtime):=20poll=20execute=EC=97=90?= =?UTF-8?q?=20=EC=83=9D=EC=84=B1=20=EB=95=8C=20=EA=B2=80=EC=82=AC=ED=95=9C?= =?UTF-8?q?=20descriptor=EB=A5=BC=20=EB=84=98=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: bounded poll은 생성 때 descriptor의 `retryBudget`이 0인지 본다 (1103/04-01). 그런데 `execute` 입력에는 descriptor가 없다. 조합 코드는 실행기에 넘길 descriptor를 스스로 골라야 하고, 같은 경로의 기본 GET (`retryBudget: 2`)을 넘겨도 막는 것이 없다. 리뷰 04-R1 P5에서 poll 3회가 요청 9회, 실행기 대기 6번이었다. 타입 주석과 설계 9.2가 "같은 객체를 넘긴다"고 적을 뿐이다. 고른 방법: coordinator가 생성 때 검사한 그 객체를 모든 `execute` 호출에 `input.operation`으로 넘긴다. 생성 때 한 번 잡아 두므로 나중에 dependencies 객체가 바뀌어도 검사한 객체가 간다. 조합 코드는 클로저의 descriptor 대신 이것을 실행기에 넘기면 된다. 테스트의 V3 조합도 그렇게 바꿨다. 타입 주석(`bounded-polling.ts`, `bounded-poll-coordinator.ts`)과 설계 9.2를 고쳤다. 버린 대안: coordinator가 실행기를 직접 받아 부르기. 실행기 타입은 `adapters/http`에 있어 realtime 어댑터가 import할 수 없다(adapter 사이 import 금지, kernel 예외 아님). 구조 타입을 새로 두면 결과 매핑까지 coordinator가 정해야 해서 공개 모양이 크게 바뀐다. 위험·한계: 일부만 닫는다. 조합 코드가 `input.operation`을 무시하고 다른 descriptor를 실행기에 넘기면 여전히 attempt마다 요청이 최대 3번이다. 설계 9.2가 이 남은 틈을 적는다. 입력 칸을 더한 것이라 기존 `execute`는 그대로 돈다. 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/realtime/ - RED: "hands every execute call the descriptor it checked at creation" (받은 값이 undefined), "sends one request per poll attempt with a poll descriptor"(실행기에 undefined가 가서 요청 0개, PROTOCOL_MISMATCH)가 옛 코드에서 실패한다. Refs: 1103/04-01 --- ...ime-events-web-push-and-bounded-polling.md | 6 ++- .../polling/bounded-poll-coordinator.ts | 16 ++++-- src/application/policies/bounded-polling.ts | 5 +- .../realtime/bounded-poll-coordinator.test.ts | 51 ++++++++++++++++++- 4 files changed, 69 insertions(+), 9 deletions(-) diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index 428776d0..c2dd5e3f 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1666,8 +1666,10 @@ poll coordinator는 실행할 V3 descriptor(`InstalledHttpContract`, 조립된 `min(retryBudget, maxRetryAttempts, 2)`번 다시 보낸다 (`http-execution-v3.ts` `retryCeiling`). 이 값을 descriptor에서 읽으므로, poll에 묶은 descriptor가 0이면 실행기의 `maxRetryAttempts`(`MAX_RETRY_ATTEMPTS`)와 상관없이 -poll 한 attempt가 요청 한 번이다. 같은 descriptor를 `execute` 안에서 실행기에 -넘긴다. `execute`는 서버·네트워크 실패도 결과로 돌려준다. 던지면 조합 코드 +poll 한 attempt가 요청 한 번이다. coordinator는 생성 때 검사한 그 descriptor를 +`execute` 입력의 `operation`으로 넘긴다. `execute`는 그것을 실행기에 넘긴다. +같은 경로의 다른 행(예: 기본 GET, `retryBudget: 2`)을 넘기면 막는 것이 없고 +attempt마다 요청이 최대 3번이다. `execute`는 서버·네트워크 실패도 결과로 돌려준다. 던지면 조합 코드 결함으로 보고 재시도 없이 `PROTOCOL_MISMATCH`로 lease를 끝낸다(1105/04-02). 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 거절된다. poll 전용 operation을 따로 등록한다. V3에는 401 재전송이 없다. command/mutation, GraphQL subscription, Connect/gRPC-Web server stream과 arbitrary diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index f2f73202..0e03c1fb 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -98,7 +98,8 @@ export type BoundedPollCoordinatorDependencies = Readonly<{ policy: PollLeasePolicy; /** * The V3 descriptor `execute` runs (`BoundedPollOperation`). Creation - * refuses one whose `frontend.retryBudget` is not 0. + * refuses one whose `frontend.retryBudget` is not 0, and every `execute` + * call receives this same object as `input.operation`. */ operation: BoundedPollOperation; /** @@ -109,6 +110,13 @@ export type BoundedPollCoordinatorDependencies = Readonly<{ */ execute(input: Readonly<{ operationId: string; + /** + * 1103/04-01. The `operation` this coordinator was created with, the + * object creation checked. Run this one on the executor, not another row + * for the same path: a descriptor with `retryBudget: 2` sends up to three + * requests per attempt. + */ + operation: BoundedPollOperation; attempt: number; /** * Hard response-body ceiling that must be enforced before decoding. @@ -138,10 +146,11 @@ export function createBoundedPollCoordinator( dependencies: BoundedPollCoordinatorDependencies, ): BoundedPollCoordinator { const policy = definePollLeasePolicy(dependencies.policy); - assertBoundedPollOperation(policy, dependencies.operation); + const operation = dependencies.operation; + assertBoundedPollOperation(policy, operation); const maxResponseBytes = Math.min( policy.maxResponseBytes, - dependencies.operation.frontend.responseByteLimit, + operation.frontend.responseByteLimit, ); const clock = dependencies.clock ?? systemClock; const random = dependencies.random ?? Math.random; @@ -312,6 +321,7 @@ export function createBoundedPollCoordinator( trackWork( dependencies.execute({ operationId: policy.operationId, + operation, attempt: attempts, maxResponseBytes, signal: controller.signal, diff --git a/src/application/policies/bounded-polling.ts b/src/application/policies/bounded-polling.ts index 8d343df0..25c31b7f 100644 --- a/src/application/policies/bounded-polling.ts +++ b/src/application/policies/bounded-polling.ts @@ -31,8 +31,9 @@ export type PollLeasePolicy = Readonly<{ /** * 1103/04-01. A poll lease runs one installed V3 descriptor: the composed row - * (`composeContractContributions(...).httpByOperationId.get(id)`). Hand the - * same object to the executor (`createContractHttpExecutor().execute`). The + * (`composeContractContributions(...).httpByOperationId.get(id)`). The poll + * coordinator hands that same object back to `execute` as `input.operation`; + * pass it to the executor (`createContractHttpExecutor().execute`). The * executor reads its retry ceiling from `frontend.retryBudget`, so a budget of * 0 is what makes one poll attempt one physical request; the poll coordinator * owns every retry between attempts. diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index cbd8e735..db27657f 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -1142,9 +1142,11 @@ describe("a poll attempt on the V3 executor", () => { environment: new MutableEnvironment(), clock, random: () => 0.5, - execute: async ({ signal }) => { + // 1103/04-01. Runs the descriptor the coordinator hands back, never a + // closed-over one. + execute: async ({ operation: polled, signal }) => { const outcome = await executor.execute( - descriptor, + polled, { limit: 20 }, { routeId: "TEST_ROUTE", scope, signal }, ); @@ -1199,4 +1201,49 @@ describe("a poll attempt on the V3 executor", () => { }); expect(requests).toHaveLength(pollPolicy.maxAttempts); }); + + // 1103/04-01's remaining gap: `execute` had no descriptor, so composition + // code chose one itself and could run the default row (three requests per + // attempt, review 04-R1 P5). + it("hands every execute call the descriptor it checked at creation", async () => { + const clock = new ManualClock(); + const pollOnly = Object.freeze({ + ...TEST_LIST_HTTP_CONTRACT, + frontend: Object.freeze({ + ...TEST_LIST_HTTP_CONTRACT.frontend, + retryBudget: 0 as const, + }), + }) as BoundedPollOperation; + const received: unknown[] = []; + const coordinator = createBoundedPollCoordinator({ + policy: pollPolicy, + operation: pollOnly, + environment: new MutableEnvironment(), + clock, + random: () => 0.5, + execute: async ({ operation: polled }) => { + received.push(polled); + return { + ok: false, + error: { + kind: "PROVIDER_UNAVAILABLE", + operation: "POLL", + retryable: true, + }, + }; + }, + }); + + let result: unknown = null; + void coordinator.run().then((value) => { + result = value; + }); + for (let turn = 0; turn < 400 && result === null; turn += 1) { + clock.advance(1_000); + await flush(); + } + + expect(received).toHaveLength(pollPolicy.maxAttempts); + for (const polled of received) expect(polled).toBe(pollOnly); + }); }); -- 2.54.0 From bfd9d50d2bdd205520865f093bcabfe5a9a651ec Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:06:33 +0900 Subject: [PATCH 05/74] =?UTF-8?q?fix(registries):=20=EA=B3=84=EC=95=BD=20?= =?UTF-8?q?=EC=A1=B0=EB=A6=BD=20=EC=8B=A4=ED=8C=A8=EC=9D=98=20=EC=9B=90?= =?UTF-8?q?=EC=9D=B8=EC=9D=84=20check:registries=EC=97=90=20=ED=95=9C=20?= =?UTF-8?q?=EB=B2=88=EB=A7=8C=20=EC=B0=8D=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 계약 조립이 실패하면 check:registries 출력에 같은 원인이 두 번 나온다. 1103/09-07 수정이 ContractContributionError의 message 끝에 reason을 붙였고, 1103/14-06 수정이 loadErrorText에서 message 뒤에 "(reason: ...)"를 또 붙였다. 두 수정이 다른 브랜치에서 들어왔다. 기존 테스트는 reason이 message에 없는 가짜 오류로만 시험해 중복을 보지 못했다. 고른 방법: loadErrorText가 message에 reason이 이미 들어 있으면 붙이지 않는다. reason을 message에 싣지 않는 오류(기존 테스트의 가짜 오류)는 지금처럼 "(reason: ...)"가 붙는다. 버린 대안: ContractContributionError message에서 reason을 다시 빼는 것. message만 찍는 다른 출구(부팅 오류, 테스트 출력)가 원인을 잃는다(1103/09-07이 고친 문제). 위험·한계: message 첫 줄만 보므로 여러 줄 reason은 다시 붙는다. 지금 reason은 한 줄이다. docs/manual/reference/errors.md의 출력 형식 줄을 실제 출력에 맞췄다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/unit/registry-governance.test.ts 새 테스트는 실제 ContractContributionError를 던지는 source로 check:registries를 돌려 원인이 한 번만 나오는지 본다. Refs: 1105/09-03 --- docs/manual/reference/errors.md | 2 +- scripts/check-registries.ts | 10 +++-- tests/unit/registry-governance.test.ts | 62 ++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 4 deletions(-) diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 5ba0d59e..c0461617 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -151,7 +151,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `FE-REG-ROUTE.. has unknown value ` | `access`·`errorSurface`가 정해진 값이 아니다 | 계약 `routes` | | `FE-REG-ROUTE..paramsSchema references unknown FE-REG-SCHEMA.schemaId=` | 라우트 스키마 ID를 기능이 등록하지 않았다 (`searchSchema`도 같은 꼴) | 계약 스키마 메타 | | `FE-REG-API. has no executable consumer for operationId=` | 계약의 operation을 기능 `adapters/`·`application/`에서 쓰지 않는다 | 쓰지 않으면 descriptor를 지운다 | -| `missing registry source : (reason: )` | 레지스트리 source를 읽다가 오류가 났다. 계약 조립 실패면 ``이 위 `reason` 표의 값이다. 읽지 못한 레지스트리는 `removed` 증거를 요구하지 않는다 | ``이 가리키는 곳 | +| `missing registry source : ` | 레지스트리 source를 읽다가 오류가 났다. 계약 조립 실패면 ``가 `Installed contract contribution is not composable: `이고 ``이 위 `reason` 표의 값이다. 다른 오류가 `reason` 속성을 message와 따로 가지면 끝에 ` (reason: )`이 붙는다. 읽지 못한 레지스트리는 `removed` 증거를 요구하지 않는다 | ``이 가리키는 곳 | | `breaking change missing evidence: ` | 행을 빼거나 바꿨는데 승인이 없다 | `update:registry-baseline` 또는 `config/contracts/registry-change-evidence.json` | | `stale breaking evidence : no breaking change in the current diff has this changeId. ...` | 지금 diff와 맞지 않는 증거 행 | 그 행을 지운다 | | `registry baseline approval digest mismatch: approved= actual=` | 기준선 파일을 손으로 고쳤다 | `update:registry-baseline`으로 다시 찍는다 | diff --git a/scripts/check-registries.ts b/scripts/check-registries.ts index 73c3c11d..313ababb 100644 --- a/scripts/check-registries.ts +++ b/scripts/check-registries.ts @@ -152,13 +152,17 @@ async function resolveRegistrySource( } /** - * 1103/14-06. A contract composition failure (`ContractContributionError`) - * says only "not composable"; its cause is the `reason` property. + * 1103/14-06. A load error's cause may be only in its `reason` property, so + * it is printed after the message. 1105/09-03. `ContractContributionError` + * already ends its message with the reason (1103/09-07); that cause is + * printed once. */ function loadErrorText(error: Error): string { const message = error.message.split("\n")[0] ?? ""; const reason: unknown = (error as Error & { reason?: unknown }).reason; - return typeof reason === "string" && reason.length > 0 + return typeof reason === "string" && + reason.length > 0 && + !message.includes(reason) ? `${message} (reason: ${reason})` : message; } diff --git a/tests/unit/registry-governance.test.ts b/tests/unit/registry-governance.test.ts index e038d441..e9541785 100644 --- a/tests/unit/registry-governance.test.ts +++ b/tests/unit/registry-governance.test.ts @@ -2,6 +2,7 @@ import { spawnSync } from "node:child_process"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; +import { pathToFileURL } from "node:url"; import { describe, expect, it } from "vitest"; import { @@ -648,4 +649,65 @@ describe("registry governance manifest", () => { await rm(directory, { recursive: true, force: true }); } }); + + // 1105/09-03. The real composition error already ends its message with the + // reason (1103/09-07). The gate prints that cause once, not again in + // `(reason: ...)`. + it("names a ContractContributionError's reason once", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "registry-source-real-error-")); + const errorModule = pathToFileURL( + path.resolve("src/contracts/external-contract-runtime.ts"), + ).href; + try { + await mkdir(path.join(directory, "src"), { recursive: true }); + await writeFile( + path.join(directory, "src/composed.ts"), + [ + `import { ContractContributionError } from ${JSON.stringify(errorModule)};`, + 'throw new ContractContributionError("notice-feature/NOTICE_LIST_ITEMS: unknown authProfileId NOTICE_NOPE");', + "", + ].join("\n"), + ); + await writeFile( + path.join(directory, "governance.json"), + JSON.stringify({ + schemaVersion: 1, + sourceDirectories: [], + registries: [ + { + registryId: "FIXTURE-COMPOSED", + path: "src/composed.ts", + exportName: "ROWS", + owner: "fixture", + keyField: "id", + requiredFields: ["id"], + fieldTypes: { id: "string" }, + }, + ], + }), + ); + const result = spawnSync( + process.execPath, + [ + path.resolve("scripts/check-registries.ts"), + "--governance", + "governance.json", + "--artifact", + "out.json", + "--no-baseline", + ], + { cwd: directory, encoding: "utf8" }, + ); + const output = `${result.stdout}${result.stderr}`; + + expect(result.status).toBe(1); + expect(output).toContain( + "missing registry source src/composed.ts: Installed contract contribution is not composable: notice-feature/NOTICE_LIST_ITEMS: unknown authProfileId NOTICE_NOPE\n", + ); + expect(output.split("unknown authProfileId NOTICE_NOPE")).toHaveLength(2); + expect(output).not.toContain("(reason:"); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); }); -- 2.54.0 From 05880d12faa726fdab5e582961d9acb4dffbc319 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:06:38 +0900 Subject: [PATCH 06/74] =?UTF-8?q?docs(realtime):=20VD-28=EA=B3=BC=20?= =?UTF-8?q?=EC=84=A4=EA=B3=84=203=EC=A0=88=EC=9D=98=20poll=20=EA=B7=9C?= =?UTF-8?q?=EC=B9=99=EC=9D=84=20V3=20descriptor=EB=A1=9C=20=EA=B3=A0?= =?UTF-8?q?=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: VD-28은 poll 규칙을 지운 V2 실행 예산으로 적는다. "operation은 registered terminal·replay-safe REST `QUERY`", "Poll-bound VD-23 budget은 `maxAttempts=1`, `authRecoveryCount=0`, `maxCumulativeSleepMs=0`"이다. 설계 3절도 "REST `QUERY` operation"과 "REST operation registry"라고 적는다. V2 실행 경로는 2026-11-03에 지웠고(VD-23 상태 줄), 지금 규칙은 V3 descriptor의 `frontend.retryBudget: 0`이다(설계 9.2, 1103/04-01). a65df74가 9.2만 고쳤다. 고른 방법: VD-28 1절 끝 문장과 11절 목록, 설계 3절 두 항목을 지금 규칙으로 바꾼다. GET·HEAD, SAFE·IDEMPOTENT인 V3 descriptor, `retryBudget` 0이 아니면 생성 때 거절, 실행기가 그 칸에서 재시도 상한을 읽어 한 attempt가 요청 하나라는 것이다. 상세는 9.2를 가리킨다. 설계 3절의 "REST operation registry의 credential, conditional request, ... 재사용"은 주어를 V3 실행기로 바꾸면서 conditional request를 뺐다. V3 실행기에는 ETag 처리가 없고(`http-execution-v3.ts`에 If-None-Match 없음), VD-23 상태 줄이 conditional execution을 `DESIGNED_NOT_IMPLEMENTED`로 적는다. 위험·한계: 문서만 바꿨다. VD-28 11절의 "ETag/`If-None-Match` 또는 server cursor 사용" 목표 줄은 결정 내용이라 그대로 두었다. 검증: 문서 전용이라 RED 없음. desktop batch에서 확인. - pnpm verify:documentation - `git grep -n "authRecoveryCount\|maxCumulativeSleepMs" -- docs/architecture/decisions/VD-28*` 0건(로컬 확인) Refs: 1105/04-03 --- ...altime-events-web-push-and-bounded-polling.md | 16 +++++++++------- ...altime-events-web-push-and-bounded-polling.md | 14 ++++++++------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/docs/architecture/decisions/VD-28-realtime-events-web-push-and-bounded-polling.md b/docs/architecture/decisions/VD-28-realtime-events-web-push-and-bounded-polling.md index 402365a4..45414d1b 100644 --- a/docs/architecture/decisions/VD-28-realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/decisions/VD-28-realtime-events-web-push-and-bounded-polling.md @@ -114,9 +114,10 @@ protocol-specific terminal proof와 protobuf decode/schema/mapper를 끝낸 runtime-wide notification branch에서만 공통 scope/gap/resync coordinator를 재사용한다. frame/media/trailer, reconnect와 operation deadline owner를 SSE/WebSocket adapter로 합치거나 protobuf message를 -`REALTIME_EVENT_V1` JSON으로 다시 감싸지 않는다. Polling의 개별 attempt는 VD-23의 -terminal·replay-safe REST `QUERY` execution contract를 재사용하되 transport/Query -retry는 끄고, 이 결정은 attempt 사이 bounded lease만 소유한다. +`REALTIME_EVENT_V1` JSON으로 다시 감싸지 않는다. Polling의 개별 attempt는 V3 +contract executor가 실행하는 V3 REST descriptor 하나다(GET·HEAD, SAFE·IDEMPOTENT, +`frontend.retryBudget: 0`, 상세 설계 9.2). transport/Query retry는 끄고, 이 결정은 +attempt 사이 bounded lease만 소유한다. ### 2. source of truth는 서버다 @@ -438,10 +439,11 @@ Service Worker를 선택해도 offline fetch, PWA shell cache나 background sync 각 lease는 operation owner, minimum/success/max interval, max attempts, max elapsed, response byte cap, visible-only policy와 terminal states를 가진다. -- operation은 registered terminal·replay-safe REST `QUERY`여야 함 -- Poll `maxAttempts`는 physical request 하나인 logical completion을 셈 -- Poll-bound VD-23 budget은 `maxAttempts=1`, `authRecoveryCount=0`, - `maxCumulativeSleepMs=0`; TanStack Query retry도 끔 +- operation은 설치된 V3 REST descriptor(`InstalledHttpContract`)로, method가 + GET·HEAD이고 `retrySemantics`가 SAFE·IDEMPOTENT여야 함 +- descriptor의 `frontend.retryBudget`은 0이어야 함. 아니면 poll coordinator 생성이 + 거절한다(상세 설계 9.2, 1103/04-01). V3 실행기는 재시도 상한을 이 칸에서 읽으므로 + Poll `maxAttempts`의 한 attempt가 physical request 하나다. TanStack Query retry도 끔 - completion-chained timeout으로 single-flight - hidden/offline/pagehide/unmount/scope change/user cancel에서 stop - ETag/`If-None-Match` 또는 server cursor 사용 diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index c2dd5e3f..dd8d6398 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -362,12 +362,14 @@ Connect/gRPC-Web server stream과 향후 GraphQL subscription은 이 문서의 S VD-29/VD-27 규칙을 우선한다. - API operation registry의 현재 `SERVER_STREAM`은 `CONNECT_HTTP | GRPC_WEB + rpcKind=SERVER_STREAM`만 허용한다. SSE, WebSocket과 Web Push는 - realtime registry가 소유하고, bounded polling은 terminal·replay-safe REST - `QUERY` operation에 적용하는 scheduling policy다. -- bounded polling의 한 logical attempt는 REST operation registry의 credential, - conditional request, schema/mapper와 deadline을 재사용한다. Poll 전용 - operation은 transport retry를 끄며 이 문서는 완료된 attempt 사이 cadence와 - failure backoff만 소유한다. + realtime registry가 소유하고, bounded polling은 V3 REST descriptor 중 + GET·HEAD이고 SAFE·IDEMPOTENT인 읽기 operation에 적용하는 scheduling policy다. +- bounded polling의 한 logical attempt는 V3 contract executor가 실행하고, 그 + 실행기의 credential, schema/mapper와 deadline을 재사용한다. conditional + request(ETag)는 V3 실행기에 아직 없다(VD-23 conditional execution + `DESIGNED_NOT_IMPLEMENTED`). Poll 전용 + operation은 `frontend.retryBudget: 0`으로 transport retry를 끈다(9.2). 이 문서는 + 완료된 attempt 사이 cadence와 failure backoff만 소유한다. 같은 stream을 Connect/gRPC-Web과 SSE로 자동 failover하지 않는다. wire와 resume 의미가 같다는 backend contract와 별도 rollout evidence가 있을 때만 명시된 fallback으로 -- 2.54.0 From 00b12b35b97c1881bea2591c46c615f915aecbb5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:06:55 +0900 Subject: [PATCH 07/74] =?UTF-8?q?test(bootstrap):=20=ED=94=8C=EB=9E=AB?= =?UTF-8?q?=ED=8F=BC=20=EA=B7=9C=EC=B9=99=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EB=91=98=EC=9D=84=20=EC=83=98=ED=94=8C=20=EB=B0=96=EC=9C=BC?= =?UTF-8?q?=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 문제 1103 수정이 더한 플랫폼 규칙 테스트 둘이 참조 샘플에 기댄다. 샘플을 지우면 두 테스트가 사라지거나 비어도 test:all과 제거 드릴이 통과한다. - MAX_RETRY_ATTEMPTS가 실행기에 닿는다: 유일한 테스트가 tests/features/reference-feature/reference-runtime-composition.test.ts 에 있다. createRuntimeAdapters는 설치된 기능의 HTTP로만 실행기에 닿아, 기능이 없으면 시험할 길이 없다. REQUEST_TIMEOUT_MS도 같은 모양이다. - 복구 중인 세션은 보호 라우트에서 기다린다: tests/unit/navigation-policy.test.ts는 설치된 보호 라우트를 돌며 단언하는데, 보호 라우트는 모두 샘플 것이라 샘플을 지우면 반복이 0번이다. 고른 방법과 버린 대안 - src/bootstrap/runtime-adapters.ts: 설정 두 값과 auth profile 표로 실행기를 만드는 부분을 createRuntimeContractHttpExecutor로 뺀다. 조립 루트는 이 함수로만 실행기를 만든다. tests/unit/runtime-adapters .test.ts가 테스트 계약(TEST_LIST, 재시도 예산 2)으로 MAX_RETRY_ATTEMPTS 0·1·2에 1·2·3번 나가는지, REQUEST_TIMEOUT_MS 5가 10초 계약을 5ms에 끊는지 본다. 이 파일은 이미 제거 드릴의 공통 테스트 목록에 있다. - tests/unit/session-route-access.test.ts(새 파일): component 테스트와 같은 방법으로 생성 index를 mock해 tests/helpers/fixture-feature.tsx를 설치하고, 보호 라우트 FIXTURE_ITEMS에서 네 세션 상태의 결정을 본다. decideRouteAccess에 라우트 정의를 받는 순수 함수를 따로 두는 안(리뷰 ⓐ)은 버렸다. fixture 기능을 설치하는 방법이 이미 있어서 운영 코드를 바꾸지 않고 실제 getRoute 경로까지 시험할 수 있다. - scripts/test-sample-removal.ts: 새 파일을 공통 테스트 목록에 넣어, 제거 드릴이 그 파일이 남았는지 본다. - 매뉴얼에 "샘플을 지우면 다시 고정한다"고만 적는 안(ⓒ)은 사람이 기억해야 해서 버렸다. 위험·한계 - 조립 루트가 이 함수 대신 실행기를 직접 만들도록 바뀌면 새 unit 테스트는 그걸 모른다. 템플릿 상태에서는 참조 기능 테스트가 계속 조립 루트 전체를 지킨다. - 샘플을 지운 복사본에 변이를 넣어 돌리지는 않았다. 검증 - desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/runtime-adapters.test.ts tests/unit/session-route-access.test.ts tests/unit/navigation-policy.test.ts tests/features/reference-feature/reference-runtime-composition.test.ts - RED: 부모 커밋의 운영 코드에는 createRuntimeContractHttpExecutor가 없어 runtime-adapters.test.ts의 새 4건이 실패한다. - 변이: 새 함수의 maxRetryAttempts를 상수 2로 바꾸면 "honours MAX_RETRY_ATTEMPTS 0/1"이, navigation-policy.ts의 recovery-pending 분기를 show-sign-in으로 바꾸면 session-route-access.test.ts의 "answers a recovery-pending session …"이 실패해야 한다. Refs: 1105/10-01 --- scripts/test-sample-removal.ts | 4 + src/bootstrap/runtime-adapters.ts | 52 +++++++--- .../reference-runtime-composition.test.ts | 2 + tests/unit/navigation-policy.test.ts | 3 + tests/unit/runtime-adapters.test.ts | 99 ++++++++++++++++++- tests/unit/session-route-access.test.ts | 57 +++++++++++ 6 files changed, 205 insertions(+), 12 deletions(-) create mode 100644 tests/unit/session-route-access.test.ts diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index 2fe4c041..88173ba0 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -137,7 +137,11 @@ const isSample = featureId in SAMPLE_EXTRAS; const commonTestPaths = [ "tests/unit/external-contract-runtime.test.ts", "tests/unit/http-execution-v3.test.ts", + // 1105/10-01. MAX_RETRY_ATTEMPTS and REQUEST_TIMEOUT_MS reach the executor + // (`createRuntimeContractHttpExecutor`), and a session being recovered waits + // on a session-required route. Before, only sample tests held these rules. "tests/unit/runtime-adapters.test.ts", + "tests/unit/session-route-access.test.ts", "tests/integration/http-execution-v3-observability.test.ts", // 0929/10-02. HTTP scenario evidence (FE-GATE-007) and the feature API // negative type fixtures (FE-GATE-003) run on the test contracts. diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 995c2e30..340c68a6 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -7,6 +7,8 @@ import { import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts"; import { createContractHttpExecutor, + type ContractHttpExecutor, + type ContractHttpExecutorDependencies, type HttpExecutionObservation, type InstalledHttpOperationExecutor, } from "../adapters/http/index.ts"; @@ -57,6 +59,7 @@ import { type ReleaseManifest, } from "./load-release-manifest.ts"; import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts"; +import type { RuntimeConfig } from "./runtime-config-schema.ts"; import { createServerStateGenerationStore } from "./server-state-generation-store.ts"; import { composeProduct, @@ -278,6 +281,43 @@ function isTerminalNonAbortFailure( ); } +/** + * 1105/10-01. Where Runtime Config's two HTTP dials reach the V3 executor: + * `MAX_RETRY_ATTEMPTS` caps every contract's retry budget and + * `REQUEST_TIMEOUT_MS` caps every contract's deadline. The composition root + * below builds its executor only through this function. It is a function of + * its own so a platform test can drive the dials without an installed + * feature: `createRuntimeAdapters` reaches the executor only through a + * feature's HTTP, and a product that removed the sample has none + * (tests/unit/runtime-adapters.test.ts). + */ +export function createRuntimeContractHttpExecutor( + config: Pick< + RuntimeConfig, + "API_BASE_URL" | "MAX_RETRY_ATTEMPTS" | "REQUEST_TIMEOUT_MS" + >, + collaborators: Pick< + ContractHttpExecutorDependencies, + "fetcher" | "attachCredentials" | "observe" + >, +): ContractHttpExecutor { + return createContractHttpExecutor({ + baseUrl: config.API_BASE_URL, + maxRetryAttempts: config.MAX_RETRY_ATTEMPTS, + // §6.1. `REQUEST_TIMEOUT_MS` was declared, validated and then dropped on the + // floor here: every V3 operation ran on its contract's own 10s deadline and + // the deployment dial did nothing. It is a ceiling, so it can tighten an + // operation but never loosen one. + requestDeadlineCeilingMs: config.REQUEST_TIMEOUT_MS, + fetcher: collaborators.fetcher, + // §7.7. The installed registry owns Fetch credentials and the exact + // credential-header sets; `attachCredentials` only supplies proof headers. + authProfiles: INSTALLED_REST_AUTH_PROFILES, + attachCredentials: collaborators.attachCredentials, + observe: collaborators.observe, + }); +} + export async function createRuntimeAdapters( context: RuntimeAdaptersContext, ) { @@ -497,18 +537,8 @@ export async function createRuntimeAdapters( diagnostics, telemetry, }); - const contractHttp = createContractHttpExecutor({ - baseUrl: config.API_BASE_URL, - maxRetryAttempts: config.MAX_RETRY_ATTEMPTS, - // §6.1. `REQUEST_TIMEOUT_MS` was declared, validated and then dropped on the - // floor here: every V3 operation ran on its contract's own 10s deadline and - // the deployment dial did nothing. It is a ceiling, so it can tighten an - // operation but never loosen one. - requestDeadlineCeilingMs: config.REQUEST_TIMEOUT_MS, + const contractHttp = createRuntimeContractHttpExecutor(config, { fetcher: context.fetcher, - // §7.7. The installed registry owns Fetch credentials and the exact - // credential-header sets; this collaborator only supplies proof headers. - authProfiles: INSTALLED_REST_AUTH_PROFILES, async attachCredentials(operation, authContext) { if (serverStateScope.getPhase() !== "READY") { return Object.freeze({ kind: "SCOPE_FENCED" as const }); diff --git a/tests/features/reference-feature/reference-runtime-composition.test.ts b/tests/features/reference-feature/reference-runtime-composition.test.ts index 5661d2bd..bc76418f 100644 --- a/tests/features/reference-feature/reference-runtime-composition.test.ts +++ b/tests/features/reference-feature/reference-runtime-composition.test.ts @@ -163,6 +163,8 @@ describe("reference feature runtime composition", () => { // 1103/10-04 ①. MAX_RETRY_ATTEMPTS is the operator's dial over every // contract's retry budget (the list declares 2). Zero must stop retries. + // This drives it through the whole composition; the same rule without the + // sample is in tests/unit/runtime-adapters.test.ts (1105/10-01). it.each([ [0, 1], [1, 2], diff --git a/tests/unit/navigation-policy.test.ts b/tests/unit/navigation-policy.test.ts index c4903c86..cda4480b 100644 --- a/tests/unit/navigation-policy.test.ts +++ b/tests/unit/navigation-policy.test.ts @@ -29,6 +29,9 @@ describe("installed route registry", () => { }); }); + // Every protected route the template installs is the sample's, so this loop + // is empty once a product removes it. session-route-access.test.ts holds the + // same decisions on the platform's fixture feature (1105/10-01). it("treats every non-public route as explicitly session-required", () => { const protectedRoutes = Object.values( ROUTE_REGISTRY as Readonly>, diff --git a/tests/unit/runtime-adapters.test.ts b/tests/unit/runtime-adapters.test.ts index 62f0a561..892e4323 100644 --- a/tests/unit/runtime-adapters.test.ts +++ b/tests/unit/runtime-adapters.test.ts @@ -1,12 +1,17 @@ import { describe, expect, it, vi } from "vitest"; -import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { + createRuntimeAdapters, + createRuntimeContractHttpExecutor, +} from "../../src/bootstrap/runtime-adapters.ts"; import { createBrowserMutationIntentFactory } from "../../src/adapters/platform/browser-mutation-intent-factory.ts"; import { createApplication } from "../../src/application/create-application.ts"; import type { ApplicationFeatureId } from "../../src/application/ports/in/application-api.ts"; import { loadFeatureRuntime } from "../../src/features/feature-module.ts"; import { INSTALLED_PRODUCT_FEATURE_MODULES } from "../../src/features/installed-product-manifest.ts"; +import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; import { testRuntimeConfig } from "../helpers/runtime-config.ts"; +import { scopeSnapshot } from "../helpers/traffic-test-kit.ts"; type Runtime = Parameters[0]["runtime"]; type Release = Parameters[0]["release"]; @@ -496,3 +501,95 @@ describe("runtime adapter composition", () => { ); }); }); + +/** + * 1105/10-01. Runtime Config's two HTTP dials, on the test contracts. The + * reference feature's composition test drives MAX_RETRY_ATTEMPTS through + * `createRuntimeAdapters`, which needs an installed feature's HTTP. These need + * none, so they stay when a product removes the sample + * (`scripts/test-sample-removal.ts` keeps this file). + */ +describe("runtime contract HTTP executor", () => { + const answerReady = () => ({ kind: "READY" as const, headers: {} }); + + // The test list read is SAFE and declares a retry budget of 2. + it.each([ + [0, 1], + [1, 2], + [2, 3], + ])( + "honours MAX_RETRY_ATTEMPTS %i: a retryable read goes out %i time(s)", + async (maxRetryAttempts, sends) => { + const fetcher = vi.fn(async (_input: RequestInfo | URL) => + Response.json( + { type: "about:blank", title: "temporary", status: 503 }, + { status: 503 }, + ), + ); + // No backoff wait: the jitter is the random draw times a ceiling. + const random = vi.spyOn(Math, "random").mockReturnValue(0); + try { + const executor = createRuntimeContractHttpExecutor( + { ...runtime.config, MAX_RETRY_ATTEMPTS: maxRetryAttempts }, + { fetcher, attachCredentials: answerReady }, + ); + + const outcome = await executor.execute( + TEST_LIST_HTTP_CONTRACT, + { limit: 20 }, + { routeId: "TEST_ROUTE", scope: scopeSnapshot() }, + ); + + expect(outcome.kind).not.toBe("SUCCESS"); + expect(fetcher).toHaveBeenCalledTimes(sends); + } finally { + random.mockRestore(); + } + }, + ); + + // The test list read declares a 10s deadline; REQUEST_TIMEOUT_MS may only + // shorten it. + it("holds a contract's deadline to REQUEST_TIMEOUT_MS", async () => { + vi.useFakeTimers(); + try { + const fetcher = vi.fn( + (_input: RequestInfo | URL, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener( + "abort", + () => reject(new DOMException("Aborted", "AbortError")), + { once: true }, + ); + }), + ); + const executor = createRuntimeContractHttpExecutor( + { ...runtime.config, MAX_RETRY_ATTEMPTS: 0, REQUEST_TIMEOUT_MS: 5 }, + { fetcher, attachCredentials: answerReady }, + ); + let settled = false; + + const result = executor + .execute( + TEST_LIST_HTTP_CONTRACT, + { limit: 20 }, + { routeId: "TEST_ROUTE", scope: scopeSnapshot() }, + ) + .then((outcome) => { + settled = true; + return outcome; + }); + await vi.advanceTimersByTimeAsync(5); + await Promise.resolve(); + await Promise.resolve(); + + expect(settled).toBe(true); + await expect(result).resolves.toMatchObject({ + kind: "TRANSPORT_FAILURE", + failure: { kind: "TIMEOUT" }, + }); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/tests/unit/session-route-access.test.ts b/tests/unit/session-route-access.test.ts new file mode 100644 index 00000000..fcf14e86 --- /dev/null +++ b/tests/unit/session-route-access.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from "vitest"; + +import { getRoute } from "../../src/features/installed-feature-contracts.ts"; +import { decideRouteAccess } from "../../src/presentation/routes/navigation-policy.ts"; + +/** + * 1105/10-01. The route access rule on the platform's own test feature + * (`tests/helpers/fixture-feature.tsx`), not on the removable sample. The + * sample owns every session-required route the template installs, so with it + * removed navigation-policy.test.ts loops over no protected route at all. + * `scripts/test-sample-removal.ts` keeps this file. + */ +vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], + PRODUCT_FEATURE_MODULES: [ + (await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE, + ], +})); +vi.mock("../../src/.generated/product-context-index.ts", async () => ({ + PRODUCT_CONTEXT_MODULES: [ + (await import("../helpers/fixture-feature.tsx")).FIXTURE_CONTEXT_MODULE, + ], +})); + +const SESSION_ROUTE = "FIXTURE_ITEMS"; + +describe("route access on an installed session-required route", () => { + it("installs the fixture route as session-required", () => { + expect(getRoute(SESSION_ROUTE).access).toBe("session-required"); + }); + + it.each([ + ["authenticated", { allowed: true, action: "none" }], + ["unauthenticated", { allowed: false, action: "show-sign-in" }], + // 1101/10-03. A session still being recovered waits; showing sign-in + // there would bounce a returning user out of a page they may enter. + ["recovery-pending", { allowed: false, action: "wait-for-session" }], + ["integration-failed", { allowed: false, action: "show-sign-in" }], + ] as const)("answers a %s session with %o", (sessionState, decision) => { + expect(decideRouteAccess(SESSION_ROUTE, sessionState)).toEqual(decision); + }); + + it("lets every session state through a public route", () => { + expect(getRoute("FIXTURE_FIRST_PAGE").access).toBe("public"); + for (const sessionState of [ + "authenticated", + "unauthenticated", + "recovery-pending", + "integration-failed", + ] as const) { + expect(decideRouteAccess("FIXTURE_FIRST_PAGE", sessionState)).toEqual({ + allowed: true, + action: "none", + }); + } + }); +}); -- 2.54.0 From 6608fef4ba78c8acdcb8de2215af70798be910f7 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:07:43 +0900 Subject: [PATCH 08/74] =?UTF-8?q?fix(http):=20Fileserver=20202=20REJECTED?= =?UTF-8?q?=EB=A5=BC=20=ED=8C=8C=EC=9D=BC=20=EA=B1=B0=EC=A0=88=EB=A1=9C=20?= =?UTF-8?q?=EC=9D=BD=EA=B3=A0=20=EB=B9=88=20=ED=8C=8C=EC=9D=BC=EC=9D=80=20?= =?UTF-8?q?=EB=B3=B4=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 문제: 짝 백엔드(45d2a478)는 POST /v1/files를 요청 안에서 동기로 검증하고 READY가 아닌 state를 모두 202로 답한다(FileUploadController#created). 악성 코드가 아닌 이유로 검증기가 거절하면 예외 없이 202 REJECTED다 (FinalizeUploadApplicationUseCase#applyNonAcceptVerdict). 기본 검증기 사슬의 첫 검증기(LengthVerifier)가 빈 파일을 그렇게 거절하므로, 0바이트 파일 하나로 닿는다. client schema에는 REJECTED가 없어 이 답이 SCHEMA_MISMATCH, APPLIED_CONFIRMED, "응답 형식 오류" 문구로 끝난다. 사용자는 파일을 바꾸라는 안내 대신 지원 문의를 보게 된다. 테스트의 MSW는 202 VERIFYING만 적은 백엔드 문서에서 왔고, 매뉴얼도 202를 "아직 검사 중"으로 적어 QUARANTINED(동기 검증 202의 대부분)를 끝나지 않는 대기로 보이게 한다. 고른 방법(리뷰 01-01 최소 개선 방향 (가)): - schema가 REJECTED를 받는다. 202 REJECTED는 성공이 아니라 실패 VALIDATION_REJECTED, code FILE_REJECTED, NOT_APPLIED, httpStatus 202다. 413·415·422 파일 거절과 같은 규칙이다. 백엔드는 그 레코드를 공개하지 않고 바이트 정리를 예약하므로 쓸 수 있는 파일이 남지 않는다. 공개 타입 FileserverFileState와 FileserverUploadedFile은 바꾸지 않았다(REJECTED는 성공 값으로 나오지 않는다). - 빈 파일은 읽기 전(선언 크기 0) 또는 읽은 뒤(선언 없음, 0바이트) 보내지 않고 FILE_EMPTY, NOT_STARTED로 끝낸다. 서버의 202 REJECTED에는 이유가 없어 기능이 "빈 파일"이라고 말할 수 없기 때문이다. - 201⇔READY 검사, size 일치 검사, 모르는 필드 무시는 그대로다. 201 REJECTED는 여전히 SCHEMA_MISMATCH다. - MSW 설명을 백엔드 코드(45d2a478) 기준으로 고치고 202 QUARANTINED· REJECTED 행을 더했다(1103/01-01의 "MSW가 문서에서 왔다" 부분). - 매뉴얼 7절이 202 state 셋의 뜻(VERIFYING 재검사 대기, QUARANTINED 관리자 결정 전 내려받기 불가, REJECTED는 실패)과 FILE_EMPTY를 적는다. 버린 대안: - REJECTED를 성공 state로 넘긴다: 타입 변경은 작지만 기능마다 성공 값에서 거절을 다시 찾아야 하고, 공개 타입 FileserverFileState가 넓어진다. - 빈 파일 거절만 한다: 기본 사슬은 막지만 제품이 더한 검증기의 REJECT는 그대로 SCHEMA_MISMATCH다. 위험·한계: - upload() 결과가 바뀐다. 202 REJECTED가 SCHEMA_MISMATCH에서 VALIDATION_REJECTED/FILE_REJECTED로, 빈 파일이 서버 요청에서 FILE_EMPTY로 바뀐다. CHANGELOG [계약] 한 줄이 필요하다. - 빈 파일 거절은 짝 백엔드 기본 검증기 사슬을 가정한다. 제품이 사슬에서 LengthVerifier를 빼 빈 파일을 받게 하면 client 규칙도 바꿔야 한다. - 실제 짝 백엔드를 띄워 빈 파일을 올려 보지 않았다(미검증). 응답 모양은 백엔드 코드(UploadedFileResponse, FileRecord#toDescriptor)를 읽은 것이다. - 1103/01-01의 남은 부분은 이 커밋 밖이다: 백엔드 매뉴얼의 짝 경로 안내와 docs/fileserver/http-contract.md의 202 state 목록(백엔드로 넘김), 실제 업로드 검증(미검증). 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/integration/fileserver-upload.test.ts RED(이 커밋의 테스트 + 부모 src): "reads 202 REJECTED as a refused file, not as a broken answer"(SCHEMA_MISMATCH로 끝남), "an empty file", "an undeclared size that turns out empty"(fetch를 부름)가 실패한다. Refs: 1105/01-01, 1103/01-01 --- docs/manual/02-decision-tables.md | 16 ++++-- src/adapters/http/fileserver-upload.ts | 45 ++++++++++++++-- tests/integration/fileserver-upload.test.ts | 59 +++++++++++++++++++-- 3 files changed, 105 insertions(+), 15 deletions(-) diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index e36381f1..95869c07 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -286,7 +286,8 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 → FileContentPort.openSource(ref) → FileByteSource → 기능 어댑터: upload({ source, filename, mediaType, idempotencyKey, signal }) → POST /v1/files (multipart, 파트 이름 file) - → 201 READY 또는 202 VERIFYING + 저장된 파일 정보(fileId, sha256 …) + → 201 READY 또는 202 VERIFYING·QUARANTINED + 저장된 파일 정보(fileId, sha256 …) + 202 REJECTED는 저장된 파일이 아니다 → 실패 FILE_REJECTED ``` - `FileByteSource`: 고른 파일의 바이트를 조각으로 읽는 값이다. `File`·`Blob`은 파일 어댑터 밖으로 나오지 않는다. @@ -308,13 +309,17 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 **결과 읽기**: `upload()`는 `Result`를 돌려준다. -- 성공 `state`가 `READY`(201)면 바로 내려받을 수 있다. 그 밖(202 `VERIFYING` 등)은 서버가 아직 검사 중이다. +- 성공 `state`가 `READY`(201)면 바로 내려받을 수 있다. 202는 아직 내려받을 수 없다. 짝 백엔드는 업로드 요청 안에서 검증을 끝내고, `READY`가 아닌 state는 모두 202로 답한다. + - `VERIFYING`: 검증기가 나중에 다시 보자고 했다. 서버가 다시 검사하면 `READY`가 될 수 있다. + - `QUARANTINED`: 격리됐다. 이름·타입 불일치, 스크립트 같은 이유다. 관리자가 정하기 전까지 내려받을 수 없다. "검사 중"으로 보이면 화면이 끝나지 않는 대기가 된다. + - `REJECTED`: 검증기가 거절했다(악성 코드 말고 다른 이유). 저장된 파일이 아니므로 성공으로 돌려주지 않는다. 실패 `VALIDATION_REJECTED`, code `FILE_REJECTED`, `NOT_APPLIED`다. 사용자가 다른 파일을 골라야 한다. +- 빈 파일은 보내지 않는다. 짝 백엔드 기본 검증기가 빈 파일을 거절하기 때문이다. `VALIDATION_REJECTED`, code `FILE_EMPTY`, `NOT_STARTED`다. - 실패 `effect`: - `NOT_STARTED`: 보내지 않았다. 입력, 크기, 자격 증명에서 거절했다. - `NOT_APPLIED`: 서버가 거절했고 파일은 없다. Fileserver는 모호하지 않은 실패에서 업로드를 취소한다. 아래 `MAYBE_APPLIED` 경우를 뺀 4xx와, 5xx 중 정한 code(`STORAGE_UNAVAILABLE` 등)다. - `MAYBE_APPLIED`: 올라갔을 수도 있다. 응답을 잃음, 시간 초과, `details.ambiguous: true`, 409 `IDEMPOTENT_IN_FLIGHT`, 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`, 그 밖의 5xx다. 다시 보낼 때는 같은 `idempotencyKey`를 쓴다. - `APPLIED_CONFIRMED`: 서버는 만들었다고 답했지만 응답을 읽지 못했다. 다시 올리지 않는다. -- `code`는 백엔드 code 그대로다(`FILE_TOO_LARGE`, `UNSUPPORTED_MEDIA_TYPE`, `MALWARE_DETECTED` …). 화면 문구는 기능이 code로 고른다. +- `code`는 백엔드 code 그대로다(`FILE_TOO_LARGE`, `UNSUPPORTED_MEDIA_TYPE`, `MALWARE_DETECTED` …). 백엔드가 code를 주지 않는 거절은 client가 이름을 붙인다(`FILE_REJECTED`, `FILE_EMPTY`, `FILE_NOT_READABLE`). 화면 문구는 기능이 code로 고른다. - client는 스스로 다시 보내지 않는다. `retryable: true`이고 `retryAfterMs`가 있으면 그만큼 기다린 뒤 기능이 다시 부른다. 서버가 상한(`maxRetryAfterMs`, 기본 30초)보다 길게 기다리라고 하면 `retryable: false`다. **주의 — 멱등 키**: 짝 백엔드(`bbe944bd`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`). @@ -390,6 +395,7 @@ export const createAttachmentFeatureInput = defineFeatureAdapterContribution({ **틀리면** - 프로필의 필수 헤더가 없으면 `fetch`를 부르지 않고 `MISSING_REQUIRED_CREDENTIAL_HEADER`로 끝난다. -- 파일이 `maxFileBytes`보다 크면 읽기 전에 `FILE_TOO_LARGE`(`NOT_STARTED`)다. +- 파일이 `maxFileBytes`보다 크면 읽기 전에 `FILE_TOO_LARGE`(`NOT_STARTED`)다. 비어 있으면 `FILE_EMPTY`(`NOT_STARTED`)다. +- 202 응답을 모두 "검사 중"으로 보이면 `QUARANTINED` 파일의 화면이 끝나지 않는다. state마다 따로 보인다. - 백엔드가 Fileserver 응답 모양이나 code를 바꾸면 검사가 잡지 못한다. 실패 판정 표(`fileserver-upload.ts`의 `NOT_APPLIED_5XX_CODES`, `MAYBE_APPLIED_CODES`)는 백엔드 `bbe944bd` 기준이다. 백엔드 SHA가 바뀌면 같이 다시 본다. -- 테스트 예: `tests/integration/fileserver-upload.test.ts`(백엔드 계약대로 답하는 MSW). +- 테스트 예: `tests/integration/fileserver-upload.test.ts`(백엔드 코드가 답하는 대로 답하는 MSW. 백엔드 문서는 202 `VERIFYING`만 적는다). diff --git a/src/adapters/http/fileserver-upload.ts b/src/adapters/http/fileserver-upload.ts index f3832d7e..4e833b0a 100644 --- a/src/adapters/http/fileserver-upload.ts +++ b/src/adapters/http/fileserver-upload.ts @@ -48,7 +48,8 @@ import type { AuthOperationContext } from "./http-execution-v3.ts"; * gives (`FileserverByteSource` is its shape), so no `File` or `Blob` crosses * into this adapter. Its bytes are read * once into the multipart body, at most `maxFileBytes` of them; a file that - * declares a larger size is refused before reading. + * declares a larger size is refused before reading, and an empty file is + * never sent. * * One request per call. The client never resends: the body is the whole * file, and only the caller knows whether to spend that again. It keeps the @@ -59,6 +60,19 @@ import type { AuthOperationContext } from "./http-execution-v3.ts"; export type FileserverFileState = "READY" | "UPLOADED" | "VERIFYING" | "QUARANTINED"; +/** + * 1105/01-01. The states the backend answers `POST /v1/files` with. It + * verifies synchronously and answers 202 for every state but `READY` + * (`FileUploadController#created`), so a file its verifiers refused, for a + * reason other than malware, comes back as 202 `REJECTED`. That one is not a + * stored file: the client returns it as a `FILE_REJECTED` failure. + */ +type FileserverAnswerState = FileserverFileState | "REJECTED"; + +type FileserverAnswer = Readonly< + Omit & { state: FileserverAnswerState } +>; + /** * The bytes to send: structurally the browser-file-storage port's * `FileByteSource`, which a product passes as it is. Written here instead of @@ -75,7 +89,12 @@ export type FileserverByteSource = Readonly<{ /** The stored file, as the backend's `UploadedFileResponse` describes it. */ export type FileserverUploadedFile = Readonly<{ fileId: string; - /** `READY` with 201. Anything else came with 202: not readable yet. */ + /** + * `READY` with 201: readable now. With 202 the file is not readable: + * `VERIFYING` means a verifier asked to check again later, and `QUARANTINED` + * means it is held until an operator decides, so a screen must not wait for + * it as for a check in progress. + */ state: FileserverFileState; filename: string; mediaType: string; @@ -191,7 +210,7 @@ export function createFileserverUploadClient( const uploadedFileSchema = z .object({ fileId: z.string().regex(UUID), - state: z.enum(["READY", "UPLOADED", "VERIFYING", "QUARANTINED"]), + state: z.enum(["READY", "UPLOADED", "VERIFYING", "QUARANTINED", "REJECTED"]), filename: z.string().min(1).max(1_024), mediaType: z.string().min(1).max(255), size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), @@ -426,6 +445,11 @@ async function readMultipartBody( // The server's code for the same refusal, so a feature handles one code. return failure("VALIDATION_REJECTED", "FILE_TOO_LARGE", notSent); } + // 1105/01-01. The backend's default verifier chain rejects empty content + // first (`LengthVerifier`), and that answer is a 202 `REJECTED` with no + // reason. Refused here instead, under a code that says why. + const empty = () => failure("VALIDATION_REJECTED", "FILE_EMPTY", notSent); + if (declared === 0) return empty(); const random = new Uint8Array(16); crypto.getRandomValues(random); const boundary = `----FileserverUpload${[...random] @@ -485,6 +509,7 @@ async function readMultipartBody( return failure("REQUEST_ABORTED", "REQUEST_ABORTED", notSent); } if (declared !== null && fileBytes !== declared) return changed(); + if (fileBytes === 0) return empty(); let bytes: Uint8Array; if (sized) { bytes = sized; @@ -564,7 +589,7 @@ async function readAnswer( response: Response, attempt: AbortableOperation, settings: Settings, - uploadedFileSchema: z.ZodType, + uploadedFileSchema: z.ZodType, sentBytes: number, ): Promise> { const status = response.status; @@ -629,9 +654,19 @@ async function readAnswer( ) { return unreadable("SCHEMA_MISMATCH", "UPLOADED_FILE_INVALID"); } + const { state, ...file } = parsed.data; + if (state === "REJECTED") { + // 1105/01-01. The file is the user's to replace, as with a 413, 415 or + // 422 refusal. The backend keeps the record unpublished and schedules + // its bytes for removal, so nothing usable was stored. + return failure("VALIDATION_REJECTED", "FILE_REJECTED", { + httpStatus: status, + effect: "NOT_APPLIED", + }); + } return Object.freeze({ ok: true as const, - value: Object.freeze({ ...parsed.data }), + value: Object.freeze({ ...file, state }), }); } if (status < 400) return unreadable("ENVELOPE_MISMATCH", "STATUS_UNEXPECTED"); diff --git a/tests/integration/fileserver-upload.test.ts b/tests/integration/fileserver-upload.test.ts index ec5bd27b..79b6bd4c 100644 --- a/tests/integration/fileserver-upload.test.ts +++ b/tests/integration/fileserver-upload.test.ts @@ -12,11 +12,22 @@ import type { RestAuthProfile } from "../../src/contracts/rest-profiles.ts"; /** * 2026-11-03 01-01. The paired backend Fileserver's `POST /v1/files`, answered - * exactly as clean-architecture-backend-template `bbe944bd` documents it: - * docs/fileserver/http-contract.md (201 READY / 202 VERIFYING, Envelope - * failure body, `details.ambiguous`, `Retry-After`) and docs/web/http-contract.md - * §1–§2 (Envelope keys, 409 IDEMPOTENT_IN_FLIGHT with `Retry-After: 2`). - * The success body is `UploadedFileResponse` wrapped by `EnvelopeBodyAdvice`. + * as clean-architecture-backend-template `45d2a478` (the pin) answers it in + * code, not only as its docs/fileserver/http-contract.md lists it. + * + * 1105/01-01. The document lists 202 VERIFYING alone. The code verifies the + * upload synchronously and answers 201 for `READY` and 202 for every other + * state (`FileUploadController#created`): `VERIFYING` (a verifier asked to + * retry), `QUARANTINED` and `REJECTED` (a refusal other than malware, + * `FinalizeUploadApplicationUseCase#applyNonAcceptVerdict`). The default + * verifier chain rejects an empty file that way (`LengthVerifier`). A record + * not yet published reports `application/octet-stream` (`FileRecord#toDescriptor`). + * + * Failure bodies, `details.ambiguous` and `Retry-After` follow the Fileserver + * handler; Envelope keys and the idempotency answers follow + * docs/web/http-contract.md §1–§2 (409 IDEMPOTENT_IN_FLIGHT with + * `Retry-After: 2`). The success body is `UploadedFileResponse` wrapped by + * `EnvelopeBodyAdvice`. */ const BASE_URL = "https://api.test/api/"; const UPLOAD_URL = "https://api.test/api/v1/files"; @@ -188,6 +199,40 @@ describe("Fileserver multipart upload — success", () => { expect(result).toEqual({ ok: true, value: uploaded("VERIFYING") }); }); + it("reads 202 QUARANTINED as a stored file held until an operator decides", async () => { + const held = uploaded("QUARANTINED", { mediaType: "application/octet-stream" }); + answer({ status: 202, body: successEnvelope(held) }); + + const result = await client().client.upload(upload()); + + expect(result).toEqual({ ok: true, value: held }); + }); + + it("reads 202 REJECTED as a refused file, not as a broken answer", async () => { + // 1105/01-01. A verifier refused the file for a reason other than malware. + answer({ + status: 202, + body: successEnvelope( + uploaded("REJECTED", { mediaType: "application/octet-stream" }), + ), + }); + + const result = await client().client.upload(upload()); + + expect(result).toEqual({ + ok: false, + error: expect.objectContaining({ + kind: "VALIDATION_REJECTED", + code: "FILE_REJECTED", + httpStatus: 202, + effect: "NOT_APPLIED", + retryable: false, + action: "none", + operationId: "FILESERVER_UPLOAD", + }), + }); + }); + it("sends a source whose size is not declared up front", async () => { const captured = answer({ status: 201, body: successEnvelope(uploaded("READY")) }); @@ -261,6 +306,7 @@ describe("Fileserver multipart upload — answers that do not match the contract it.each([ ["201 with a state that is not READY", 201, successEnvelope(uploaded("VERIFYING")), "SCHEMA_MISMATCH"], ["202 with READY", 202, successEnvelope(uploaded("READY")), "SCHEMA_MISMATCH"], + ["201 with REJECTED", 201, successEnvelope(uploaded("REJECTED")), "SCHEMA_MISMATCH"], ["a size other than the bytes sent", 201, successEnvelope(uploaded("READY", { size: 1 })), "SCHEMA_MISMATCH"], ["the DTO without its Envelope", 201, uploaded("READY"), "ENVELOPE_MISMATCH"], ] as const)("%s is a created file the client cannot read", async (_label, status, body, kind) => { @@ -497,6 +543,9 @@ describe("Fileserver multipart upload — refused before sending", () => { it.each([ ["a declared size above maxFileBytes", { source: byteSource(new Uint8Array(2_000)) }, "VALIDATION_REJECTED", "FILE_TOO_LARGE"], + // 1105/01-01. The backend's default verifier chain rejects these. + ["an empty file", { source: byteSource(new Uint8Array(0)) }, "VALIDATION_REJECTED", "FILE_EMPTY"], + ["an undeclared size that turns out empty", { source: byteSource(new Uint8Array(0), { byteLength: null }) }, "VALIDATION_REJECTED", "FILE_EMPTY"], ["an undeclared size that grows past maxFileBytes", { source: byteSource(new Uint8Array(2_000), { byteLength: null, chunkBytes: 512 }) }, "VALIDATION_REJECTED", "FILE_TOO_LARGE"], ["a file that shrank after selection", { source: byteSource(FILE_BYTES, { byteLength: FILE_BYTES.byteLength + 1 }) }, "VALIDATION_REJECTED", "FILE_NOT_READABLE"], ["a file that grew after selection", { source: byteSource(FILE_BYTES, { byteLength: FILE_BYTES.byteLength - 1 }) }, "VALIDATION_REJECTED", "FILE_NOT_READABLE"], -- 2.54.0 From 23662fb23a91b230a1ae6d06dbec51cb69d419ee Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:08:19 +0900 Subject: [PATCH 09/74] =?UTF-8?q?fix(storage):=20=EA=B0=9D=EC=B2=B4?= =?UTF-8?q?=EB=A5=BC=20=EB=81=9D=EA=B9=8C=EC=A7=80=20=EB=8F=88=20=EA=B3=84?= =?UTF-8?q?=EC=A0=95=20=EC=82=AD=EC=A0=9C=20purge=EB=8A=94=20=EB=8A=98=20p?= =?UTF-8?q?artition=EC=9D=84=20=EC=A7=80=EC=9A=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 승인된 LOGOUT·ACCOUNT_DELETION purge는 객체 목록을 읽고, 하나씩 지우고, 마지막에 journal 행을 한 번 센 뒤 0이면 chunk sweep으로 끝나 `chunkSweep: "COMPLETED"`를 돌려준다. 목록과 세기는 각각 한 순간만 본다. - 다른 탭이 새 객체를 put하는 중이면 purge의 remove가 그 put이 쥔 origin lease를 기다린다. partition에 객체가 3개 이상이면 그 put은 목록 뒤에 commit하고 세기 전에 complete까지 끝난다. 목록에도 행 수에도 없어 sweep이 그 chunk를 건너뛰고, 계정 삭제 뒤에도 파일이 읽힌다 (리뷰 실험 Y1b 메모리 20/20, Chromium 6/6). 저장소 테스트는 객체 0~1개로만 돌아서 이 틈을 놓쳤다. - FILES_READY에서 멈춘 put의 행이 `logicalKey`를 잃으면 세지 못한다. staging receipt가 chunk를 sweep에서 지켜 purge마다 COMPLETED인데 receipt·chunk·manifest가 남는다(Y2). 고른 방법: 마지막 객체까지 돈 purge는 sweep 대신 늘 partition 삭제로 끝낸다(리뷰 2.1절 (d')). exclusive partition lock이 그때 진행 중인 put·delete를 모두 기다린 뒤 디렉터리 전체(staging 포함)와 그 partition 행을 지우므로 두 경우를 함께 막는다. 객체 순회는 `removedObjects`· `releasedBytes` 보고와 예산 단위 진행을 위해 남긴다. 예산이나 다른 탭의 변경(CONFLICT) 때문에 끝까지 돌지 못한 호출은 지금처럼 `moreObjectsAvailable: true`를 돌려주고, 그때만 journal 행을 세서 끝나지 않은 행이 있으면 바로 partition을 지운다(2026-11-03 05-01 그대로). purge 성공 report는 이제 `partitionDeleted`와 `moreObjectsAvailable` 중 정확히 하나를 가진다(walk 뒤 abort도 more로 보고). 버린 대안: - (a) sweep 뒤에 다시 세고 committed 객체를 한 번 더 본다: ①만 막고 ②가 남는다. 다시 볼 때 정책상 남겨야 할 객체를 가려내려면 목록을 끝까지 다시 읽어야 한다. - (b)+(a): 둘 다 막지만 판단 조건이 일곱 개가 된다. - 세기를 아예 없애기: 예산에 걸린 호출의 crash 행 처리가 다음 호출로 밀린다. 지금 동작을 바꿀 이유가 없어 남겼다. 위험·한계: - 모든 승인 purge가 다른 탭의 진행 중 put을 기다린다(지금까지는 끝나지 않은 행이 있을 때만). 기다림 상한은 `mutationLockWaitTimeoutMs` (1103/05-02)이고 abort로 멈출 수 있다. - 같은 partition에 LOGOUT 때 남겨야 하는 객체가 섞이면 이 방법은 맞지 않는다. 지금 정책 검사는 OPAQUE_PARTITION이면 LOGOUT·ACCOUNT_DELETION 모두 purge만 허용해 그런 객체가 생기지 않는다. - port의 `chunkSweep`은 아무도 채우지 않는다. 읽는 코드가 깨지지 않게 타입은 남기고 `@deprecated`로 적었다. - recipe fake의 purge도 늘 `partitionDeleted`다. - `logicalKey`를 잃은 행 자체는 여전히 남는다(05-03 설계). 그 bytes는 이제 남지 않는다. - Firefox·WebKit에서 Y1은 돌리지 않았다. browser spec은 객체 0·3개 두 경우로 늘렸다. 검증: desktop batch에서 확인 - node scripts/run-vitest.ts run tests/unit/opfs-worker-runtime.test.ts tests/unit/opfs-byte-store.test.ts tests/unit/indexeddb-opfs-journal.test.ts - node scripts/run-vitest.ts run tests/recipes/browser-file-storage-contracts.test.ts - corepack pnpm test:browser-capabilities tests/browser-capabilities/opfs-runtime.spec.ts --project=chromium Refs: 1103/05-01 --- .../browser-file-storage-recovery.md | 71 ++--- .../browser-file-storage-fakes.ts | 14 +- .../storage/opfs/opfs-byte-store-adapter.ts | 73 ++---- .../ports/browser-file-storage/opfs-ports.ts | 31 ++- .../browser-capabilities/opfs-runtime.spec.ts | 204 +++++++++------ .../browser-file-storage-contracts.test.ts | 10 +- tests/unit/opfs-worker-runtime.test.ts | 245 ++++++++++++++++-- 7 files changed, 442 insertions(+), 206 deletions(-) diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index dc245541..dd758100 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -40,23 +40,24 @@ cleanup 결과를 확인하지 못하면 성공 값이 아니라 실패로 답 계속 돌고, 관측은 `OBJECT_RECONCILE` `DEGRADED` / `CORRUPT_DATA`로 남는다 ([0929] 05-01). reconcile은 그 row를 지우지 않는다. 그 partition이 승인된 purge로 통째로 지워질 때 함께 지워지는 것은 partition 키(`logicalKey`)를 - 읽을 수 있는 row뿐이다(§7). 승인된 LOGOUT/ACCOUNT_DELETION purge는 그런 - row를 보면 그 partition을 지운다(2026-11-03 05-01). + 읽을 수 있는 row뿐이다(§7). 승인된 LOGOUT/ACCOUNT_DELETION purge는 객체를 + 끝까지 돌면 늘 그 partition을 지운다(1103/05-01 잔여). - `unattributedCorruptTransactions`: 위 수 가운데 `logicalKey`까지 읽을 수 없는 row 수다. 어느 partition에도 속하지 않아 partition 삭제도 지우지 못한다. 그래서 따로 세고 `DEGRADED` 관측에서 뺀다(2026-11-03 05-03). 예전에는 이런 row 하나가 reconcile마다 `DEGRADED`를 남겨 경보가 늘 켜졌다. 같은 수로 남아 있으면 할 일이 없다. 수가 늘면 키 없는 row를 쓴 writer(다른 release, 외부 도구)를 찾는다. 이 row도 수동으로 지우지 않는다(3번). 그 row의 - staging은 partition 디렉터리 안에 있어 그 partition이 지워지면 함께 - 지워지지만, 이 row는 purge의 partition 삭제 조건에 들지 않는다. + staging은 partition 디렉터리 안에 있어 승인된 purge가 그 partition을 + 지울 때 함께 지워진다. 예전에는 purge가 이 row를 세지 못해 chunk sweep으로 + 끝났고, staging receipt가 지킨 chunk·manifest가 `COMPLETED` 뒤에도 + 남았다(1103/05-01 잔여). 3. journal row를 수동으로 삭제하지 않는다. row가 사라지면 stale staging을 추적할 근거가 사라지고 quota만 누수된다. 4. OPFS root나 journal database를 통째로 삭제하거나 schema를 downgrade하지 않는다. rollback은 새 v2 write admission을 닫고 v1+v2 reader를 유지하는 것으로 - 수행한다. runtime이 스스로 지우는 것은 승인된 purge가 손상이나 끝나지 않은 - transaction 때문에 끝나지 못할 때의 그 partition 디렉터리 하나와 그 partition의 - journal row뿐이다(§7). + 수행한다. runtime이 스스로 통째로 지우는 것은 승인된 LOGOUT/ACCOUNT_DELETION + purge의 그 partition 디렉터리 하나와 그 partition의 journal row뿐이다(§7). ## 1. 공통 원칙 @@ -450,27 +451,33 @@ VD-15 목표 runtime을 먼저 구현한다. - `COMMITTED` + file missing/corrupt: reconstructable만 server rehydrate; user-created private는 read-only/export/recovery - stale staging/orphan chunk는 grace period와 bounded mark/sweep 후 제거 -- `LOGOUT`/`ACCOUNT_DELETION` purge는 객체를 모두 지운 뒤 그 partition의 journal - row를 센다. 하나라도 있으면(다른 tab에서 진행 중인 put·delete, crash가 남긴 - `PREPARING`·`FILES_READY`, 키는 읽히는 손상 row) sweep 대신 아래 partition - 삭제로 간다(2026-11-03 05-01). 예전에는 이 row를 보지 않고 `COMPLETED`를 - 돌려줬다. 그래서 진행 중 put의 객체가 purge 뒤에도 읽혔고, `FILES_READY` row는 - 다음 reconcile이 commit해 객체로 되살렸다. row가 없으면 그 partition의 chunk를 - grace 없이 sweep한다(05-04, `opfs-byte-store-adapter.ts` `enforcePolicies`). - staging receipt가 참조하는 chunk는 이때도 지우지 않는다. 이 두 reason에서는 - report의 `chunkSweep`이 `COMPLETED`이거나 `partitionDeleted`가 있을 때 그 - partition의 bytes가 지워진 것이다. `DEADLINE_REACHED`면 같은 - purge를 다시 호출하고, `STAGING_STATE_UNREADABLE`이면 읽을 수 없는 staging부터 - 처리한다. 다른 탭이 바꾸고 있던 객체를 지우지 못하면 report는 - `moreObjectsAvailable: true`이고 `chunkSweep`이 없다. 이때도 같은 purge를 다시 - 호출한다([0929] 05-02) -- 손상이나 끝나지 않은 transaction 때문에 끝나지 못하는 `LOGOUT`/ - `ACCOUNT_DELETION` purge는 partition을 통째로 지운다([0929] 05-01, - 2026-11-03 05-01, `opfs-byte-store-adapter.ts` `enforcePolicies`). +- `LOGOUT`/`ACCOUNT_DELETION` purge는 객체를 하나씩 지운 뒤, 마지막 객체까지 + 돌았으면 늘 아래 partition 삭제로 끝낸다(1103/05-01 잔여, + `opfs-byte-store-adapter.ts` `enforcePolicies`). chunk sweep으로 끝내지 않는다. + - 예전 동작: 객체를 다 돈 뒤 journal row를 한 번 세고, 0이면 chunk를 grace 없이 + sweep해 `chunkSweep: "COMPLETED"`를 돌려줬다(05-04, 2026-11-03 05-01). 목록과 + 세기는 각각 한 순간만 본다. 그래서 두 경우에 bytes가 남은 채 `COMPLETED`였다. + ① 다른 tab이 새 객체를 put하는 중이고 partition에 객체가 3개 이상이면, 그 put이 + 목록 뒤에 commit하고 세기 전에 끝났다. 목록에도 row 수에도 없어 sweep이 그 + chunk를 건너뛰었고, 그 파일이 계정 삭제 뒤에도 읽혔다(메모리 20/20, Chromium + 6/6). ② 멈춘 put의 journal row가 `logicalKey`를 잃으면 세지 못했고, 그 + staging receipt·chunk·manifest가 purge마다 남았다. + - 이제 결과: 그 partition의 bytes가 지워진 것은 report에 `partitionDeleted`가 + 있을 때다. `chunkSweep`은 더 이상 채우지 않는다(port 타입에는 호환을 위해 + 남겼다). + - 예산(`budgetMs`·`maxObjects`)이나 다른 tab의 변경 때문에 객체를 끝까지 돌지 + 못하면 report는 `moreObjectsAvailable: true`이고 `partitionDeleted`가 없다. + 같은 purge를 다시 호출한다([0929] 05-02). 다만 이때 그 partition의 journal + row(다른 tab에서 진행 중인 put·delete, crash가 남긴 `PREPARING`·`FILES_READY`, + 키는 읽히는 손상 row)가 하나라도 있으면 그 호출이 바로 partition을 지운다 + (2026-11-03 05-01). +- 승인된 `LOGOUT`/`ACCOUNT_DELETION` purge의 partition 삭제([0929] 05-01, + 2026-11-03 05-01, 1103/05-01 잔여, `opfs-byte-store-adapter.ts` + `enforcePolicies`). - 조건: 정책이 그 reason을 허용하고, authority가 이번 purge의 proof를 내주고 consumer가 소비했을 때(IndexedDB의 database 전체 삭제와 같은 승인). 그리고 - 다음 중 하나를 만났을 때: 목록에서 건너뛴 손상 object row, 손상 row 때문에 - `CORRUPT_DATA`로 끝난 remove나 chunk sweep, `STAGING_STATE_UNREADABLE`, 그 + 다음 중 하나일 때: 마지막 객체까지 돌았다, 목록에서 건너뛴 손상 object row, + 손상 row 때문에 `CORRUPT_DATA`로 끝난 remove, 끝까지 돌지 못한 호출에서 그 partition 키를 가진 journal row(`countPartitionTransactions`가 1 이상). TTL·SESSION_END·UNTIL_SYNCED·PRESSURE는 손상 row를 건너뛰고 세기만 한다. - 범위: worker가 origin mutation lease를 쥔 채 @@ -482,8 +489,9 @@ VD-15 목표 runtime을 먼저 구현한다. row는 남긴다. 다른 partition은 건드리지 않는다. - 결과: `partitionDeleted: true`, `moreObjectsAvailable: false`, 건너뛴 row 수 `corruptObjects`. 이 report면 그 partition의 bytes는 모두 지워진 것이다. - `chunkSweep`은 없다. 디렉터리는 지웠는데 journal 정리가 실패하면 실패를 - 반환한다. 같은 purge를 다시 호출하면 이어서 끝난다. + `removedObjects`·`releasedBytes`는 삭제 전에 하나씩 지운 객체만 센다. + 디렉터리는 지웠는데 journal 정리가 실패하면 실패를 반환한다. 같은 purge를 + 다시 호출하면 이어서 끝난다. - 다른 tab의 put·delete와의 순서: 모든 put·delete는 journal `begin`부터 끝날 때까지 partition lock(Web Lock `:partition:::`)을 @@ -504,9 +512,10 @@ VD-15 목표 runtime을 먼저 구현한다. 멈추고 `ABORTED`를 반환한다. 삭제 뒤에 줄 선 put·delete도 자기 `signal`로 기다림을 멈춘다. 어느 쪽이든 partition lock 기다림은 `mutationLockWaitTimeoutMs`(기본 10분)에서 `BLOCKED`(retryable)로 끝난다 - (2026-11-03 05-02). purge가 journal row를 센 뒤에 시작한 put, 삭제가 - lock을 요청한 뒤 온 put의 데이터는 남는다(point-in-time). purge 전에 그 - partition의 쓰기를 멈추는 것이 composition의 몫이다. + (2026-11-03 05-02). 삭제가 lock을 요청한 뒤 온 put의 데이터는 남는다 + (point-in-time). 그 전에 시작한 put은 삭제가 기다렸다가 함께 지운다. + 모든 승인 purge가 이제 이 lock을 기다리므로, 다른 tab에서 오래 걸리는 put이 + 있으면 purge도 그만큼 늦게 끝난다. - lock/worker 문제면 OPFS write off → approved capped fallback 또는 online-only - scope binding mismatch면 affected scope를 read-only로 격리하고 registry/ composition을 forward fix; 다른 token path로 bytes를 이동하거나 추측 복구 금지 diff --git a/recipes/frontend-capabilities/browser-file-storage-fakes.ts b/recipes/frontend-capabilities/browser-file-storage-fakes.ts index d23f572b..cc2ca491 100644 --- a/recipes/frontend-capabilities/browser-file-storage-fakes.ts +++ b/recipes/frontend-capabilities/browser-file-storage-fakes.ts @@ -1652,8 +1652,9 @@ type MemoryDurableObjectStoreOptions = Readonly<{ * a journal row, and a LOGOUT or ACCOUNT_DELETION the policy allows leaves the * partition empty. `reconcile` rolls a row that stopped while PREPARING back * and commits one that stopped after FILES_READY, like the runtime's - * roll-forward; such a purge also drops every stopped row and reports - * `partitionDeleted` (2026-11-03 05-01, 05-04). + * roll-forward; such a purge also drops every stopped row. Every purge + * reports `partitionDeleted`, never a chunk sweep (2026-11-03 05-01, 05-04, + * 1103/05-01 rest). * * It does not model the worker, Web Locks, the composition authority, chunk * dedup, orphan GC or the other maintenance reasons (`UNSUPPORTED`). Its @@ -1926,8 +1927,9 @@ export class MemoryDurableObjectStore const removedObjects = this.#objects.size; this.#objects.clear(); // 2026-11-03 05-01. A stopped put goes with the partition, as the - // runtime's partition delete takes its row and its files. - const partitionDeleted = this.#pending.size > 0; + // runtime's partition delete takes its row and its files. 1103/05-01 + // rest: the runtime ends every purge that walked all objects in that + // delete, so this one always reports it. this.#pending.clear(); return dataSuccess( Object.freeze({ @@ -1936,9 +1938,7 @@ export class MemoryDurableObjectStore releasedBytes, moreObjectsAvailable: false, deadlineReached: false, - ...(partitionDeleted - ? { partitionDeleted: true as const } - : { chunkSweep: "COMPLETED" as const }), + partitionDeleted: true as const, }), ); } diff --git a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts index 9c918f51..e150a461 100644 --- a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts +++ b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts @@ -805,8 +805,7 @@ export function createOpfsByteStoreAdapter( const sweeping = request.reason === "LOGOUT" || request.reason === "ACCOUNT_DELETION"; // [0929] 05-01. Rows the journal could not read and skipped, and damage - // met past the listing: a remove or the sweep failing on an unreadable - // row, or staging the sweep cannot read. + // met past the listing: a remove failing on an unreadable row. let corruptObjects = 0; let damaged = false; @@ -888,14 +887,25 @@ export function createOpfsByteStoreAdapter( } afterObjectId = page.value.nextObjectId; } - // 2026-11-03 05-01. A put or delete of this partition that has not - // finished holds bytes the object walk never sees and the sweep skips: - // one running in another tab, or a row a crash left (PREPARING, or - // FILES_READY, which the next reconcile would commit) or nothing can - // read. Any such row sends the purge to the partition delete below, - // which first waits for every live one. + // 1103/05-01 (rest). A walk that reached the last object no longer ends + // in a chunk sweep. The walk and a journal count each see one moment: + // another tab's put of a new object that committed after the listing + // and settled before the count was in neither, and a stopped put whose + // row lost its partition key is never counted. The sweep then skipped + // their chunks and staging and still reported COMPLETED, so the file + // stayed readable after the account deletion. Such a walk now always + // ends in the partition delete below, which waits for every put and + // delete of the partition and takes the whole directory, staging + // included, so nothing that began before it is left. + const walkFinished = !moreObjectsAvailable && !deadlineReached; + // 2026-11-03 05-01. A walk the budget or another tab's change stopped + // leaves the rest for the next call, unless a put or delete of this + // partition has not finished: one running in another tab, or a row a + // crash left (PREPARING, or FILES_READY, which the next reconcile would + // commit) or nothing can read. Any such row sends this call to the + // partition delete too. let unfinished = 0; - if (sweeping && !request.signal?.aborted) { + if (sweeping && !walkFinished && !request.signal?.aborted) { const counted = await dependencies.journal.countPartitionTransactions( dependencies.scope, ); @@ -904,40 +914,6 @@ export function createOpfsByteStoreAdapter( } unfinished = counted.value; } - // 05-04. Removing an object leaves its chunks, and GC only takes a - // chunk 24 h after it was written, so a purged user's bytes stayed on - // the device. Once every object is gone the partition's chunks are swept - // without that grace. The sweep still skips any chunk the journal or a - // staged put references. - let chunkSweep: OpfsPolicyMaintenanceReport["chunkSweep"]; - if ( - sweeping && - !unfinished && - !corruptObjects && - !damaged && - !moreObjectsAvailable && - !deadlineReached && - !request.signal?.aborted - ) { - const swept = await reconcileOrphanChunks( - deadline, - request.signal, - now(), - ); - if (!swept.ok) { - if (swept.error.code !== "CORRUPT_DATA") { - return rebaseFailure(swept.error, "OBJECT_RECONCILE"); - } - damaged = true; - } else { - chunkSweep = swept.value.status; - damaged = chunkSweep === "STAGING_STATE_UNREADABLE"; - if (chunkSweep === "DEADLINE_REACHED") { - deadlineReached = true; - moreObjectsAvailable = true; - } - } - } // [0929] 05-01. A row nothing can read never lets this purge finish, so // the user's bytes would stay on the device for good. The authority // approved this exact LOGOUT or ACCOUNT_DELETION (the same approval the @@ -949,7 +925,7 @@ export function createOpfsByteStoreAdapter( // wait for every put and delete of the partition in any tab. const partitionDeleted = sweeping && - (corruptObjects > 0 || damaged || unfinished > 0) && + (walkFinished || corruptObjects > 0 || damaged || unfinished > 0) && !request.signal?.aborted; if (partitionDeleted) { const removed = await withPartitionLock( @@ -970,8 +946,12 @@ export function createOpfsByteStoreAdapter( if (!removed.ok) { return rebaseFailure(removed.error, "OBJECT_RECONCILE"); } - chunkSweep = undefined; moreObjectsAvailable = false; + } else if (sweeping) { + // Only an abort between the walk and the delete gets here with the + // walk finished. Either way the partition still holds bytes, so a + // purge reports exactly one of `partitionDeleted` and more work. + moreObjectsAvailable = true; } const report: OpfsPolicyMaintenanceReport = Object.freeze({ inspectedObjects, @@ -979,7 +959,6 @@ export function createOpfsByteStoreAdapter( releasedBytes, moreObjectsAvailable, deadlineReached, - ...(chunkSweep ? { chunkSweep } : {}), ...(corruptObjects ? { corruptObjects } : {}), ...(partitionDeleted ? { partitionDeleted } : {}), }); @@ -1365,7 +1344,6 @@ export function createOpfsByteStoreAdapter( async function reconcileOrphanChunks( deadline: number, signal: AbortSignal | undefined, - olderThanEpochMs = Math.max(0, now() - policy.orphanGracePeriodMs), ): Promise< BrowserDataResult< Readonly<{ @@ -1378,6 +1356,7 @@ export function createOpfsByteStoreAdapter( }> > > { + const olderThanEpochMs = Math.max(0, now() - policy.orphanGracePeriodMs); let inspected = 0; let deleted = 0; // R-5.1. Candidates include committed chunks, so a page can be all diff --git a/src/application/ports/browser-file-storage/opfs-ports.ts b/src/application/ports/browser-file-storage/opfs-ports.ts index 7c638698..48dac066 100644 --- a/src/application/ports/browser-file-storage/opfs-ports.ts +++ b/src/application/ports/browser-file-storage/opfs-ports.ts @@ -152,12 +152,15 @@ export type OpfsPolicyMaintenanceReport = Readonly<{ moreObjectsAvailable: boolean; deadlineReached: boolean; /** - * 05-04. LOGOUT and ACCOUNT_DELETION only, once every object is removed and - * no put or delete of the partition is unfinished: how the sweep of the - * partition's now unreferenced chunks ended. For those two reasons the - * partition's bytes are gone exactly when this is `COMPLETED` or - * `partitionDeleted` is set; a put that begins after the purge reached its - * journal check is kept (2026-11-03 05-01). + * 05-04. How a LOGOUT or ACCOUNT_DELETION chunk sweep ended. + * + * @deprecated The reference runtime and the recipe fake no longer set it + * (1103/05-01 rest): a sweep after the object walk missed a new object + * another tab's put settled during the walk, and the staging of a stopped + * put whose journal row lost its partition key, and still said + * `COMPLETED`. Such a purge now ends in the partition delete, so + * `partitionDeleted` is the one completion signal. Kept so code that reads + * it still compiles; it is always absent. */ chunkSweep?: "COMPLETED" | "DEADLINE_REACHED" | "STAGING_STATE_UNREADABLE"; /** @@ -166,12 +169,16 @@ export type OpfsPolicyMaintenanceReport = Readonly<{ */ corruptObjects?: number; /** - * [0929] 05-01. An approved LOGOUT or ACCOUNT_DELETION that damage kept - * from finishing, or that found an unfinished put or delete of the - * partition (2026-11-03 05-01), removed the whole partition directory and - * the partition's journal rows instead, after every put and delete of the - * partition then running in any tab had returned. Every byte of the - * partition is gone. + * [0929] 05-01. An approved LOGOUT or ACCOUNT_DELETION removed the whole + * partition directory and the partition's journal rows, after every put + * and delete of the partition then running in any tab had returned. Every + * byte of the partition is gone; a put that begins after that delete is + * kept. A purge that walked every object always ends this way (1103/05-01 + * rest). One the budget or another tab's change stopped part-way ends this + * way only when damage or an unfinished put or delete of the partition + * (2026-11-03 05-01) was met; otherwise it reports `moreObjectsAvailable` + * and the caller runs it again. For these two reasons the partition's bytes + * are gone exactly when this is set. */ partitionDeleted?: true; }>; diff --git a/tests/browser-capabilities/opfs-runtime.spec.ts b/tests/browser-capabilities/opfs-runtime.spec.ts index 7157a7fc..59d42d64 100644 --- a/tests/browser-capabilities/opfs-runtime.spec.ts +++ b/tests/browser-capabilities/opfs-runtime.spec.ts @@ -329,97 +329,129 @@ async function removeOpfsAuthority( // 2026-11-03 05-01 X1. The purge used to report a completed sweep while the // other tab's put landed, and the object stayed readable after the account // deletion. It now waits for that put and takes it with the partition. -test("05-01 an approved purge in another tab waits for a live put and takes it with the partition", async ({ - page, -}) => { - const secondPage = await page.context().newPage(); - const suffix = crypto.randomUUID().replaceAll("-", ""); - const scope: OpfsTabScope = { - namespace: "durable-objects", - authorityToken: `authority_${suffix}`, - namespaceToken: `namespace_${suffix}`, - partitionToken: `partition_${suffix}`, - }; - type Tab = import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts").BrowserOpfsRuntime; - try { - await Promise.all([page.goto("/"), secondPage.goto("/")]); - if (!(await installOpfsTab(page, scope))) return; - expect(await installOpfsTab(secondPage, scope, true)).toBe(true); +// 1103/05-01 rest. That fix still reported a completed sweep, with the new +// object readable, once the purged partition held three or more objects: +// each remove waits for the origin lease the put holds, so the put settled +// before the purge counted the journal. A purge that walked every object now +// always ends in the partition delete. +for (const committedObjects of [0, 3]) { + test(`05-01 an approved purge in another tab waits for a live put and takes it with the partition (${committedObjects} committed objects)`, async ({ + page, + }) => { + const secondPage = await page.context().newPage(); + const suffix = crypto.randomUUID().replaceAll("-", ""); + const scope: OpfsTabScope = { + namespace: "durable-objects", + authorityToken: `authority_${suffix}`, + namespaceToken: `namespace_${suffix}`, + partitionToken: `partition_${suffix}`, + }; + type Tab = import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts").BrowserOpfsRuntime; + try { + await Promise.all([page.goto("/"), secondPage.goto("/")]); + if (!(await installOpfsTab(page, scope))) return; + expect(await installOpfsTab(secondPage, scope, true)).toBe(true); - await page.evaluate(async () => { - const state = globalThis as unknown as { - __opfsTab: Tab; - __release?: () => void; - __put?: Promise; - }; - let streaming!: () => void; - const started = new Promise((resolve) => { - streaming = resolve; - }); - const gate = new Promise((resolve) => { - state.__release = resolve; - }); - state.__put = state.__opfsTab.objects.put({ - objectId: "object_tab_12345678", - expectedGeneration: null, - mediaType: "application/octet-stream", - source: { - byteLength: 4, - async *stream() { - streaming(); - await gate; - yield { ok: true as const, value: new Uint8Array([2, 7, 1, 8]) }; + const seeded = await secondPage.evaluate(async (count) => { + const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab; + const codes: string[] = []; + for (let index = 0; index < count; index += 1) { + const put = await runtime.objects.put({ + objectId: `object_secret_${String(index).padStart(4, "0")}`, + expectedGeneration: null, + mediaType: "application/octet-stream", + source: { + byteLength: 1, + async *stream() { + yield { ok: true as const, value: new Uint8Array([index + 1]) }; + }, + }, + }); + codes.push(put.ok ? "OK" : put.error.code); + } + return codes; + }, committedObjects); + expect(seeded).toEqual(Array.from({ length: committedObjects }, () => "OK")); + + await page.evaluate(async () => { + const state = globalThis as unknown as { + __opfsTab: Tab; + __release?: () => void; + __put?: Promise; + }; + let streaming!: () => void; + const started = new Promise((resolve) => { + streaming = resolve; + }); + const gate = new Promise((resolve) => { + state.__release = resolve; + }); + state.__put = state.__opfsTab.objects.put({ + objectId: "object_tab_12345678", + expectedGeneration: null, + mediaType: "application/octet-stream", + source: { + byteLength: 4, + async *stream() { + streaming(); + await gate; + yield { ok: true as const, value: new Uint8Array([2, 7, 1, 8]) }; + }, }, + }); + await started; + }); + await secondPage.evaluate(() => { + const state = globalThis as unknown as { + __opfsTab: Tab; + __purge?: Promise; + }; + state.__purge = state.__opfsTab.maintenance.enforcePolicies({ + reason: "ACCOUNT_DELETION", + }); + }); + await page.waitForTimeout(250); + const put = await page.evaluate(async () => { + const state = globalThis as unknown as { + __release: () => void; + __put: Promise; + }; + state.__release(); + return await state.__put; + }); + const report = await secondPage.evaluate( + async () => + await (globalThis as unknown as { __purge: Promise }).__purge, + ); + const opened = await secondPage.evaluate(async () => { + const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab; + const result = await runtime.objects.open({ + objectId: "object_tab_12345678", + }); + return result.ok ? "OPENED" : result.error.code; + }); + + expect(put).toMatchObject({ ok: true, value: { generation: 1 } }); + expect(report).toMatchObject({ + ok: true, + value: { + removedObjects: committedObjects, + moreObjectsAvailable: false, + partitionDeleted: true, }, }); - await started; - }); - await secondPage.evaluate(() => { - const state = globalThis as unknown as { - __opfsTab: Tab; - __purge?: Promise; - }; - state.__purge = state.__opfsTab.maintenance.enforcePolicies({ - reason: "ACCOUNT_DELETION", - }); - }); - await page.waitForTimeout(250); - const put = await page.evaluate(async () => { - const state = globalThis as unknown as { - __release: () => void; - __put: Promise; - }; - state.__release(); - return await state.__put; - }); - const report = await secondPage.evaluate( - async () => - await (globalThis as unknown as { __purge: Promise }).__purge, - ); - const opened = await secondPage.evaluate(async () => { - const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab; - const result = await runtime.objects.open({ - objectId: "object_tab_12345678", - }); - return result.ok ? "OPENED" : result.error.code; - }); - - expect(put).toMatchObject({ ok: true, value: { generation: 1 } }); - expect(report).toMatchObject({ - ok: true, - value: { moreObjectsAvailable: false, partitionDeleted: true }, - }); - expect(opened).toBe("NOT_FOUND"); - } finally { - for (const tab of [page, secondPage]) { - await tab.evaluate(() => - (globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(), - ); + expect(opened).toBe("NOT_FOUND"); + } finally { + for (const tab of [page, secondPage]) { + await tab.evaluate(() => + (globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(), + ); + } + expect(await removeOpfsAuthority(page, scope)).toBe("DELETED"); + await secondPage.close(); } - expect(await removeOpfsAuthority(page, scope)).toBe("DELETED"); - await secondPage.close(); - } -}); + }); +} test("05-01 a reconcile in another tab skips a live put and the put stays readable", async ({ page, diff --git a/tests/recipes/browser-file-storage-contracts.test.ts b/tests/recipes/browser-file-storage-contracts.test.ts index f4e0202b..0ff59eff 100644 --- a/tests/recipes/browser-file-storage-contracts.test.ts +++ b/tests/recipes/browser-file-storage-contracts.test.ts @@ -672,12 +672,14 @@ describe("production browser file and storage recipe contracts", () => { expectedGeneration: asObjectGeneration(2), }), ).toMatchObject({ ok: false, error: { code: "CONFLICT" } }); - expect( - await store.enforcePolicies({ reason: "ACCOUNT_DELETION" }), - ).toMatchObject({ + // 1103/05-01 rest. Like the runtime, a purge that walked every object + // ends in the partition delete, never in a chunk sweep. + const purged = await store.enforcePolicies({ reason: "ACCOUNT_DELETION" }); + expect(purged).toMatchObject({ ok: true, - value: { removedObjects: 1, chunkSweep: "COMPLETED" }, + value: { removedObjects: 1, partitionDeleted: true }, }); + expect(purged.ok && purged.value.chunkSweep).toBeUndefined(); expect(await store.open({ objectId })).toMatchObject({ ok: false, error: { code: "NOT_FOUND" }, diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index e319754c..063f7c19 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -2254,15 +2254,17 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh expect(await putBytes(purged, "object_secret_2", [4, 5])).toMatchObject({ ok: true }); expect(await putBytes(kept, "object_kept_0001", [7, 7])).toMatchObject({ ok: true }); - expect(await purged.maintenance.enforcePolicies({ reason })).toMatchObject({ + const report = await purged.maintenance.enforcePolicies({ reason }); + expect(report).toMatchObject({ ok: true, value: { removedObjects: 2, moreObjectsAvailable: false, deadlineReached: false, - chunkSweep: "COMPLETED", + partitionDeleted: true, }, }); + expect(report.ok && report.value.chunkSweep).toBeUndefined(); expect(filesUnder(root, scopeA)).toEqual([]); expect(await openedBytes(kept, "object_kept_0001")).toEqual({ generation: 1, @@ -2273,7 +2275,7 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh // 1101/13.6. A journal may hand back a page shorter than the limit (the port // does not promise full pages). A purge that walked two such pages and - // removed everything is finished: it must say so and sweep the chunks. + // removed everything is finished: it must say so and take the partition. it("finishes a purge that walked more than one journal page", async () => { const { root, idb, tab } = sharedRootTabs(); const journal = createIndexedDbOpfsJournal({ @@ -2300,7 +2302,7 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh inspectedObjects: 2, removedObjects: 2, moreObjectsAvailable: false, - chunkSweep: "COMPLETED", + partitionDeleted: true, }, }); expect(filesUnder(root, scopeA)).toEqual([]); @@ -2310,25 +2312,89 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh // it, report a completed sweep and leave that object readable. A put or // delete of the partition that has not finished now sends the purge to the // partition delete, which waits for it and then takes it. - it("waits for a put that began before the purge and takes it with the partition", async () => { - const { root, tab } = sharedRootTabs(); - const purger = tab("p", authority); + // 1103/05-01 rest (Y1b). That fix counted the journal once, after the walk. + // Each remove waits for the origin lease the other tab's put holds, so with + // three or more objects the put committed and settled before the count: + // neither the listing nor the count saw it, the sweep skipped its chunks + // and said COMPLETED, and the file stayed readable. One object hid this. + it.each([1, 3, 8])( + "waits for a put that began before the purge and takes it with the partition (%i committed objects)", + async (count) => { + const { root, tab } = sharedRootTabs(); + const purger = tab("p", authority); + const writer = tab("w", authority); + for (let index = 1; index <= count; index += 1) { + expect( + await putBytes(purger, `object_secret_${index}`, [index]), + ).toMatchObject({ ok: true }); + } + const stalled = stalledSource(); + const put = writer.objects.put({ + objectId: "object_late_0001", + expectedGeneration: null, + mediaType: "application/octet-stream", + source: stalled.source, + }); + await stalled.streaming; + const purge = purger.maintenance.enforcePolicies({ reason: "LOGOUT" }); + await new Promise((resolve) => setTimeout(resolve, 20)); + stalled.release(); + + expect(await put).toMatchObject({ ok: true }); + const report = await purge; + expect(report).toMatchObject({ + ok: true, + value: { + removedObjects: count, + moreObjectsAvailable: false, + partitionDeleted: true, + }, + }); + expect(report.ok && report.value.chunkSweep).toBeUndefined(); + expect(filesUnder(root, scopeA)).toEqual([]); + expect(await openedBytes(writer, "object_late_0001")).toBe("NOT_FOUND"); + }, + ); + + // 1103/05-01 rest (Y1a). The same gap without timing: another tab's put of + // a new object commits and settles right after the purge lists the + // partition, so the listing misses it and no journal row is left to count. + it("takes a new object another tab's put settles between the purge's listing and its end", async () => { + const { root, idb, tab } = sharedRootTabs(); + const journal = createIndexedDbOpfsJournal({ + authorityToken: scopeA.authorityToken, + factory: idb.factory, + keyRange: idb.keyRange, + }); + const stalled = stalledSource(); + let late: ReturnType | undefined; + const purger = tab("p", { + ...authority, + journal: { + ...journal, + async listCommittedObjects(request) { + const page = await journal.listCommittedObjects(request); + stalled.release(); + await late; + return page; + }, + }, + }); const writer = tab("w", authority); expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); - const stalled = stalledSource(); - const put = writer.objects.put({ + late = writer.objects.put({ objectId: "object_late_0001", expectedGeneration: null, mediaType: "application/octet-stream", source: stalled.source, }); await stalled.streaming; - const purge = purger.maintenance.enforcePolicies({ reason: "LOGOUT" }); - await new Promise((resolve) => setTimeout(resolve, 20)); - stalled.release(); - expect(await put).toMatchObject({ ok: true }); - const report = await purge; + const report = await purger.maintenance.enforcePolicies({ + reason: "ACCOUNT_DELETION", + }); + + expect(await late).toMatchObject({ ok: true, value: { generation: 1 } }); expect(report).toMatchObject({ ok: true, value: { @@ -2339,7 +2405,72 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh }); expect(report.ok && report.value.chunkSweep).toBeUndefined(); expect(filesUnder(root, scopeA)).toEqual([]); - expect(await openedBytes(writer, "object_late_0001")).toBe("NOT_FOUND"); + expect(await openedBytes(purger, "object_late_0001")).toBe("NOT_FOUND"); + }); + + // 2026-11-03 05-01. A walk the budget stops part-way is no finished purge. + // It leaves the rest for the next call, unless a put or delete of the + // partition is unfinished: then that call takes the partition at once. + it("continues a purge the object budget stopped, and takes the partition when a put is unfinished", async () => { + const { root, idb, tab } = sharedRootTabs(); + const purger = tab("p", authority); + for (const objectId of ["object_secret_1", "object_secret_2", "object_secret_3"]) { + expect(await putBytes(purger, objectId, [1])).toMatchObject({ ok: true }); + } + + const first = await purger.maintenance.enforcePolicies({ + reason: "ACCOUNT_DELETION", + maxObjects: 1, + }); + expect(first).toEqual({ + ok: true, + value: { + inspectedObjects: 1, + removedObjects: 1, + releasedBytes: 1, + moreObjectsAvailable: true, + deadlineReached: false, + }, + }); + expect(filesUnder(root, scopeA)).not.toEqual([]); + + // A put that died before it wrote anything leaves a PREPARING row. + const journal = createIndexedDbOpfsJournal({ + authorityToken: scopeA.authorityToken, + factory: idb.factory, + keyRange: idb.keyRange, + }); + expect( + await journal.begin({ + transactionId: "transaction_left_0001", + mutation: "PUT", + scope: scopeA, + objectId: "object_left_0001", + expectedGeneration: null, + targetGeneration: 1, + targetByteLength: 1, + targetStoragePolicy: storagePolicy, + startedAtEpochMs: 2, + }), + ).toMatchObject({ ok: true }); + + expect( + await purger.maintenance.enforcePolicies({ + reason: "ACCOUNT_DELETION", + maxObjects: 1, + }), + ).toMatchObject({ + ok: true, + value: { + inspectedObjects: 1, + removedObjects: 1, + moreObjectsAvailable: false, + partitionDeleted: true, + }, + }); + expect(filesUnder(root, scopeA)).toEqual([]); + expect(idb.readRaw("opfs-journal", "transaction_left_0001")).toBeUndefined(); + expect(await openedBytes(purger, "object_secret_3")).toBe("NOT_FOUND"); }); // 2026-11-03 05-01 X2, X2b, X3. A put that stopped before it finished leaves @@ -2420,11 +2551,87 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh }, ); + // 1103/05-01 rest (Y2). The journal counts rows by their partition key, so a + // stopped put whose row lost that key was never counted. Its staging + // receipt kept its chunk out of the sweep, and every purge said COMPLETED + // with the receipt, the chunk and the manifest still on disk. The partition + // delete takes them; the keyless row itself stays, counted apart (05-03). + it("leaves no bytes of a stopped put whose journal row lost its partition key", async () => { + const { root, idb, tab } = sharedRootTabs(); + const journal = createIndexedDbOpfsJournal({ + authorityToken: scopeA.authorityToken, + factory: idb.factory, + keyRange: idb.keyRange, + }); + const writerWorker = loopbackGateway( + createOpfsWorkerRuntime({ + root: root as unknown as FileSystemDirectoryHandle, + crypto: globalThis.crypto, + policy: runtimePolicy, + leaseManager: exclusiveLeases(), + dedicatedWorker: true, + supportsSynchronousAccessHandles: false, + }), + ); + const unavailable = async () => + browserDataFailure("UNAVAILABLE", "INDEXEDDB_WRITE", { + retryable: true, + recovery: "RETRY", + }); + // The tab crashes before commit: neither the commit nor its compensation + // lands, so the row stays FILES_READY with its staging on disk. + const writer = tab("w", { + journal: { ...journal, commitPut: unavailable } as OpfsJournalPort, + worker: { + ...writerWorker, + abortPreparedPut: async () => + browserDataFailure("UNAVAILABLE", "OBJECT_WRITE", { + retryable: true, + recovery: "RETRY", + }), + }, + }); + const purger = tab("p", authority); + expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); + expect(await putBytes(writer, "object_dead_0001", [9, 9, 9])).toMatchObject({ + ok: false, + }); + const { logicalKey: _dropped, ...keyless } = idb.readRaw( + "opfs-journal", + "transaction_w_1", + ) as Record; + idb.seed("opfs-journal", keyless); + expect(filesUnder(root, scopeA)).not.toEqual([]); + + for (let run = 0; run < 2; run += 1) { + const report = await purger.maintenance.enforcePolicies({ + reason: "ACCOUNT_DELETION", + }); + expect(report).toMatchObject({ + ok: true, + value: { moreObjectsAvailable: false, partitionDeleted: true }, + }); + expect(report.ok && report.value.chunkSweep).toBeUndefined(); + expect(filesUnder(root, scopeA)).toEqual([]); + expect(await purger.maintenance.reconcile()).toMatchObject({ + ok: true, + value: { + committedTransactions: 0, + corruptTransactions: 1, + unattributedCorruptTransactions: 1, + }, + }); + } + expect(await openedBytes(purger, "object_dead_0001")).toBe("NOT_FOUND"); + expect(idb.readRaw("opfs-journal", "transaction_w_1")).toBeDefined(); + }); + // [0929] 05-02. Another tab overwrites the object the purge is removing, so // the purge's remove ends in CONFLICT. That purge is not finished and must - // not claim a completed chunk sweep. The overwrite finishes between the - // purge's listing and its remove: one still running when the purge checks - // the journal sends it to the partition delete instead (2026-11-03 05-01). + // not claim to be. The overwrite finishes between the purge's listing and + // its remove: one still running when the purge checks the journal sends it + // to the partition delete instead (2026-11-03 05-01). The next call walks + // every object and takes the partition (1103/05-01 rest). it("reports a purge that skipped a changing object as unfinished", async () => { const { root, idb, tab } = sharedRootTabs(); const journal = createIndexedDbOpfsJournal({ @@ -2472,7 +2679,7 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh value: { removedObjects: 1, moreObjectsAvailable: false, - chunkSweep: "COMPLETED", + partitionDeleted: true, }, }); expect(filesUnder(root, scopeA)).toEqual([]); -- 2.54.0 From 2e1acb1f2185248941cba9779b338732eaf8634a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:08:22 +0900 Subject: [PATCH 10/74] =?UTF-8?q?fix(bootstrap):=20=EA=B8=88=EC=A7=80?= =?UTF-8?q?=EB=90=9C=20=EC=84=A4=EC=A0=95=20=ED=82=A4=EB=A1=9C=20=EB=A9=88?= =?UTF-8?q?=EC=B6=98=20=EB=B6=80=ED=8C=85=20=EC=98=A4=EB=A5=98=EC=97=90=20?= =?UTF-8?q?=EA=B7=B8=20=ED=82=A4=20=EC=9D=B4=EB=A6=84=EC=9D=84=20=EC=8B=A3?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 런타임 설정에 비밀처럼 보이는 키(`CLIENT_SECRET` 등)가 있으면 부팅이 CONFIG_SECRET_NAME_REJECTED로 멈추지만, 안전한 부팅 오류에는 buildId만 있고 어느 키인지가 없다. assertSafeConfigNames가 던진 오류의 message에는 키 이름이 있었지만 loadRuntimeConfig가 그 오류를 버렸다. 같은 파일의 스키마 실패는 키 이름을 invalidKeys로 싣는다. 고른 방법: assertSafeConfigNames가 UnsafeConfigNameError를 던지고 그 `key`에 거절한 키의 점 경로(`CAPABILITY_OVERRIDES.AUTH_TOKEN`, `FEATURE_OVERRIDES..CLIENT_SECRET`)를 싣는다. 로더는 그 경로를 스키마 실패와 같은 SAFE_KEY_PATTERN으로 거른 뒤 invalidKeys에 넣는다. 오류 화면은 이미 invalidKeys를 "잘못된 설정 키"로 보인다. 값은 어디에도 싣지 않는다. 버린 대안: message에서 키를 정규식으로 다시 읽는 것. message 문구가 바뀌면 조용히 빠진다. 위험·한계: 키 이름은 거절된 문서에서 온다. 그래서 길이·문자를 제한하고, 그 밖의 이름은 빼고 코드만 남긴다. 첫 번째로 걸린 키 하나만 싣는다 (검사가 첫 키에서 멈추는 동작은 그대로). assertSafeConfigNames의 시그니처와 message는 바꾸지 않았다. UnsafeConfigNameError는 src/contracts/env.ts에 새로 더한 export다(추가만). 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/runtime-schema/runtime-config.test.ts Refs: 1103/07-04 --- docs/manual/03-outside-feature-folder.md | 2 +- src/bootstrap/load-runtime-config.ts | 20 ++++++++-- src/contracts/env.ts | 41 ++++++++++++++++++--- tests/runtime-schema/runtime-config.test.ts | 38 +++++++++++++++++++ 4 files changed, 92 insertions(+), 9 deletions(-) diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index ca3ce7c8..d4b56fcf 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -110,7 +110,7 @@ release admission refused for staging: - 실시간 갱신: 짝 백엔드의 실시간 출구(STOMP·NDJSON)와 프론트 realtime 어댑터(SSE·`realtime.v1` WebSocket)는 그대로 연결되지 않는다. 지금 되는 경로는 bounded polling이다. 대응표: [realtime 설계 0.1절](../architecture/realtime-events-web-push-and-bounded-polling.md#01-짝-백엔드-템플릿과의-대응-110304-02). - `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때. - 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다. - - 설정 키 이름에 `TOKEN`·`COOKIE`·`SECRET`·`PASSWORD` 같은 조각(`src/contracts/env.ts`의 `FORBIDDEN_CONFIG_NAME_FRAGMENTS`, 대소문자 무관)을 넣지 않는다. 부팅이 `CONFIG_SECRET_NAME_REJECTED`로 멈춘다. `test:unit`의 `env-registry-coverage`가 먼저 `Forbidden client configuration key: <키>`로 실패한다. + - 설정 키 이름에 `TOKEN`·`COOKIE`·`SECRET`·`PASSWORD` 같은 조각(`src/contracts/env.ts`의 `FORBIDDEN_CONFIG_NAME_FRAGMENTS`, 대소문자 무관)을 넣지 않는다. 부팅이 `CONFIG_SECRET_NAME_REJECTED`로 멈추고, 오류 화면의 "잘못된 설정 키"에 그 키 이름(값은 아님. 중첩 키는 `CAPABILITY_OVERRIDES.AUTH_TOKEN`처럼 경로)이 나온다. `test:unit`의 `env-registry-coverage`가 먼저 `Forbidden client configuration key: <키>`로 실패한다. - FE-REG-ENV 행의 `required`·`defaultValue`는 zod 필드가 키가 없을 때 하는 것과 같게 적는다. 기본값이 없으면 `defaultValue: null`이다. 같은 테스트가 대조한다. - `config/runtime/.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`). - `src/features/product-capabilities.ts`의 선택 런타임(`PRODUCT_RUNTIME_CAPABILITY_SELECTION`): Service Worker를 켤 때. 아래 "SW 켜기"를 본다. diff --git a/src/bootstrap/load-runtime-config.ts b/src/bootstrap/load-runtime-config.ts index 566002fa..b31898ba 100644 --- a/src/bootstrap/load-runtime-config.ts +++ b/src/bootstrap/load-runtime-config.ts @@ -1,4 +1,8 @@ -import { assertSafeConfigNames, getBuildConfig } from "../contracts/env.ts"; +import { + assertSafeConfigNames, + getBuildConfig, + UnsafeConfigNameError, +} from "../contracts/env.ts"; import { checkReleaseCoherence } from "../platform/release/release-coherence.ts"; import { BOOT_JSON_POLICIES, @@ -21,7 +25,10 @@ export type BootConfigSafe = Readonly<{ buildId: string; configSchemaVersion?: string; releaseId?: string; - /** 09-04. Names of rejected keys (never their values), bounded. */ + /** + * 09-04. Names of rejected keys (never their values), bounded: the keys the + * schema rejected, or (1103/07-04) the secret-looking key's dotted path. + */ invalidKeys?: readonly string[]; supportReference: string; }>; @@ -117,9 +124,16 @@ export async function loadRuntimeConfig( try { assertSafeConfigNames(rawConfig); - } catch { + } catch (error) { + // 1103/07-04. The rejected key's name, never its value, tells an operator + // what to remove. It comes from the rejected document, so it is bounded + // like the schema failure's keys below. + const key = error instanceof UnsafeConfigNameError ? error.key : undefined; throw new BootConfigError("CONFIG_SECRET_NAME_REJECTED", { buildId: buildConfig.buildId, + ...(key !== undefined && SAFE_KEY_PATTERN.test(key) + ? { invalidKeys: Object.freeze([key]) } + : {}), }); } diff --git a/src/contracts/env.ts b/src/contracts/env.ts index 0fcf1a9e..363bf00f 100644 --- a/src/contracts/env.ts +++ b/src/contracts/env.ts @@ -116,25 +116,56 @@ function runtime( return Object.freeze({ phase: "runtime", classification, required, defaultValue }); } +/** + * 1103/07-04. What `assertSafeConfigNames` throws. `key` is the rejected + * key's dotted path from where the check started + * (`CAPABILITY_OVERRIDES.AUTH_TOKEN`), so the boot error can name it without + * its value. It is absent when the document nests too deep. + */ +export class UnsafeConfigNameError extends Error { + readonly key: string | undefined; + + constructor(message: string, key?: string) { + super(message); + this.name = "UnsafeConfigNameError"; + this.key = key; + } +} + export function assertSafeConfigNames( config: Readonly>, depth = 0, +): void { + assertSafeConfigNamesAt(config, depth, []); +} + +function assertSafeConfigNamesAt( + config: Readonly>, + depth: number, + path: readonly string[], ): void { if (depth > 4) { - throw new Error("Client configuration nesting exceeds its bound"); + throw new UnsafeConfigNameError( + "Client configuration nesting exceeds its bound", + ); } for (const [name, value] of Object.entries(config)) { const allowlisted = depth === 0 && SEMANTIC_KEY_ALLOWLIST.has(name); if (!allowlisted && isForbiddenConfigName(name)) { - throw new Error(`Forbidden client configuration key: ${name}`); + throw new UnsafeConfigNameError( + `Forbidden client configuration key: ${name}`, + [...path, name].join("."), + ); } if (!isPlainNested(value)) continue; if (depth === 0 && FEATURE_ID_KEYED_MAPS.has(name)) { - for (const entry of Object.values(value)) { - if (isPlainNested(entry)) assertSafeConfigNames(entry, depth + 2); + for (const [featureId, entry] of Object.entries(value)) { + if (isPlainNested(entry)) { + assertSafeConfigNamesAt(entry, depth + 2, [...path, name, featureId]); + } } } else { - assertSafeConfigNames(value, depth + 1); + assertSafeConfigNamesAt(value, depth + 1, [...path, name]); } } } diff --git a/tests/runtime-schema/runtime-config.test.ts b/tests/runtime-schema/runtime-config.test.ts index 39ac1f86..451bcc30 100644 --- a/tests/runtime-schema/runtime-config.test.ts +++ b/tests/runtime-schema/runtime-config.test.ts @@ -294,6 +294,44 @@ describe("runtime configuration boundary", () => { expect(JSON.stringify(safe)).not.toContain("value-probe"); }); + // 1103/07-04. A secret-looking key stops boot before the schema runs. The + // boot error names that key, with its path below a nested map, and never + // its value. A key name that is not safe to show is left out. + it.each<[Record, readonly string[] | undefined]>([ + [{ CLIENT_SECRET: "value-probe" }, ["CLIENT_SECRET"]], + [ + { CAPABILITY_OVERRIDES: { AUTH_TOKEN: "value-probe" } }, + ["CAPABILITY_OVERRIDES.AUTH_TOKEN"], + ], + [ + { FEATURE_OVERRIDES: { alpha: { CLIENT_SECRET: "value-probe" } } }, + ["FEATURE_OVERRIDES.alpha.CLIENT_SECRET"], + ], + [{ "CLIENT_SECRET": "value-probe" }, undefined], + ])( + "names the forbidden key of %o as %o, never its value (1103/07-04)", + async (extra, invalidKeys) => { + const failure = await loadRuntimeConfig({ + buildConfig: { + buildId: "build-a", + commitSha: "local", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + fetcher: async () => + new Response(JSON.stringify({ ...validConfig, ...extra }), { + headers: { "content-type": "application/json" }, + }), + }).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(BootConfigError); + const safe = (failure as BootConfigError).safe; + expect(safe.code).toBe("CONFIG_SECRET_NAME_REJECTED"); + expect(safe.invalidKeys).toEqual(invalidKeys); + expect(JSON.stringify(safe)).not.toContain("value-probe"); + }, + ); + it("returns only safe boot fields on failure", async () => { await expect( loadRuntimeConfig({ -- 2.54.0 From 1c7c614b47914f82284aaf0f99ef1ab6ba087cac Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:08:50 +0900 Subject: [PATCH 11/74] =?UTF-8?q?fix(service-worker):=20=EC=82=AC=EC=A0=84?= =?UTF-8?q?=20=EC=BA=90=EC=8B=9C=EB=A5=BC=20Vite=20assets=20=ED=8F=B4?= =?UTF-8?q?=EB=8D=94=EC=9D=98=20=ED=95=B4=EC=8B=9C=20=ED=8C=8C=EC=9D=BC?= =?UTF-8?q?=EB=A1=9C=20=EC=A0=9C=ED=95=9C=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 사전 캐시 수집기(`collectStaticAssets`)는 dist 전체를 돌고 파일 이름만 해시 정규식으로 본다. `public/` 파일은 이름 그대로 dist 루트에 복사되는데, `apple-touch-icon.png`, `android-chrome-192x192.png`, `safari-pinned-tab.svg`는 정규식에 걸려 immutable 자산으로 들어간다(리뷰 06-R1). 제품이 같은 이름으로 아이콘을 바꾸고 CDN이 옛 바이트를 주면 새 릴리스 install이 INTEGRITY_MISMATCH로 통째로 거절된다. 이전 릴리스 fallback, 호스팅 정책 `/assets/*`, MIME probe, 레시피 문서는 모두 `assets/`만 가정한다. 고른 방법: 리뷰 06-01의 (a). 계약 모듈에 `BUILD_ASSET_DIRECTORY = "assets/"` 하나를 두고, 수집기는 그 아래 파일만 받는다. 워커 fallback (`service-worker-static-assets.ts`)과 probe(`hosting-probe.ts`)도 같은 상수를 읽는다. `build.assetsDir`를 바꿀 때(0925/06-08) 이 상수 한 곳만 고치면 된다. 수집기의 `.vite/` 제외는 새 조건이 덮으므로 지웠다. 레시피 문서에 루트 파일이 빠진다는 문장을 더했다. 버린 대안: - 정규식을 Vite 해시 형식(8자 고정)으로 좁히기. 우연히 맞는 이름이 남는다. - 문서만 고치기. 아이콘 문제가 그대로다. 위험·한계: 루트에 해시 이름 파일을 일부러 두는 제품은 그 파일이 사전 캐시에서 빠진다. Vite는 그런 파일을 만들지 않는다. 상수는 vite 설정에서 읽지 않는다. `build.assetsDir`를 바꾸는 제품은 상수도 같이 바꿔야 한다 (0925/06-08은 그대로 남는다). 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/service-worker-web-push-remediation.test.ts tests/unit/service-worker-runtime.test.ts tests/unit/hosting-probe.test.ts tests/unit/service-worker-build-output.test.ts - RED: "precaches only the assets directory, not public files at the dist root"가 옛 수집기에서 루트 아이콘 세 개를 받아 실패한다. Refs: 1105/06-01 --- docs/architecture/optional-adapter-recipes.md | 4 ++- scripts/generate-service-worker-assets.ts | 16 ++++++++-- scripts/lib/hosting-probe.ts | 7 +++-- .../service-worker-static-assets.ts | 9 +++--- src/contracts/service-worker.ts | 10 ++++++ ...ervice-worker-web-push-remediation.test.ts | 31 +++++++++++++++++++ 6 files changed, 66 insertions(+), 11 deletions(-) diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 3027cdf7..16638e60 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -158,7 +158,9 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시 오프라인 셸(0929/06-03): reference 워커는 navigation을 가로채지 않는다 (`service-worker-static-assets.ts` navigation `NETWORK_ONLY`, `service-worker-lifecycle.ts` `intercepts`). 사전 캐시는 해시 이름의 -`assets/`뿐이고 `index.html`은 넣지 않는다(`scripts/generate-service-worker-assets.ts`). +`assets/`(`src/contracts/service-worker.ts` `BUILD_ASSET_DIRECTORY`)뿐이고 `index.html`은 +넣지 않는다(`scripts/generate-service-worker-assets.ts`). `public/`에서 dist 루트로 복사된 +PWA 아이콘 같은 파일은 이름이 해시처럼 보여도 넣지 않는다(1105/06-01). 설계가 cached `index.html` fallback을 금지한다(closed deep design 18.8). 오프라인 셸이 필요한 제품은 템플릿 워커를 켜는 것으로 얻지 못한다. 별도 제품 capability로 설계하고, 그때 넘겨받는 파일은 위 세 파일과 `vite.service-worker.config.ts`다. diff --git a/scripts/generate-service-worker-assets.ts b/scripts/generate-service-worker-assets.ts index 282a3ec0..733fd405 100644 --- a/scripts/generate-service-worker-assets.ts +++ b/scripts/generate-service-worker-assets.ts @@ -11,6 +11,7 @@ import path from "node:path"; import { getBuildConfig } from "../src/contracts/env.ts"; import { + BUILD_ASSET_DIRECTORY, HASHED_STATIC_ASSET_NAME, SERVICE_WORKER_BOUNDS, SERVICE_WORKER_SCRIPT_PATH, @@ -19,7 +20,8 @@ import { /** * §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed - * asset list the Service Worker will verify at install time. + * asset list under `BUILD_ASSET_DIRECTORY` the Service Worker will verify at + * install time. * * `service-worker.js` itself and `index.html` are excluded (§17.2.2), as are * the runtime config and release manifest, which are network-only (§18.4). @@ -41,7 +43,12 @@ const EXCLUDED_FILES: ReadonlySet = new Set([ "runtime-config.schema.json", ]); -/** Vite emits content-hashed names; only those may be treated as immutable. */ +/** + * Vite emits content-hashed names under its assets directory; only those may + * be treated as immutable. A `public/` file copied to the dist root keeps its + * own name even when it looks hashed (`android-chrome-192x192.png`), and a + * product may change its bytes under that name (1105/06-01). + */ const HASHED_NAME = HASHED_STATIC_ASSET_NAME; /** @@ -59,7 +66,10 @@ export async function collectStaticAssets( for (const relative of files.sort()) { const base = path.basename(relative); - if (EXCLUDED_FILES.has(base) || relative.startsWith(".vite/")) continue; + if (!relative.split(path.sep).join("/").startsWith(BUILD_ASSET_DIRECTORY)) { + continue; + } + if (EXCLUDED_FILES.has(base)) continue; const contentType = CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()]; if (!contentType || !HASHED_NAME.test(base)) continue; diff --git a/scripts/lib/hosting-probe.ts b/scripts/lib/hosting-probe.ts index dc7bca24..310d2d3e 100644 --- a/scripts/lib/hosting-probe.ts +++ b/scripts/lib/hosting-probe.ts @@ -2,7 +2,10 @@ import { isIP } from "node:net"; import path from "node:path"; import { connect } from "node:tls"; -import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts"; +import { + BUILD_ASSET_DIRECTORY, + type InstalledServiceWorkerSelection, +} from "../../src/contracts/service-worker.ts"; import { CACHEABLE_ASSET_CONTENT_TYPES } from "../../src/contracts/service-worker-static-manifest.ts"; import { changedRuntimeConfigBuildFields } from "./runtime-config-switches.ts"; @@ -282,7 +285,7 @@ export async function probeAssetContentTypes( for (const file of distFiles.map((entry) => entry.split(path.sep).join("/")).sort()) { const extension = path.posix.extname(file).toLowerCase(); if ( - file.startsWith("assets/") && + file.startsWith(BUILD_ASSET_DIRECTORY) && acceptedAssetContentTypes(extension).length > 0 && !samples.has(extension) ) { diff --git a/src/adapters/service-worker/service-worker-static-assets.ts b/src/adapters/service-worker/service-worker-static-assets.ts index d96eb4e0..4affcdb0 100644 --- a/src/adapters/service-worker/service-worker-static-assets.ts +++ b/src/adapters/service-worker/service-worker-static-assets.ts @@ -1,4 +1,5 @@ import { + BUILD_ASSET_DIRECTORY, HASHED_STATIC_ASSET_NAME, isOwnedStaticCacheName, SERVICE_WORKER_BOUNDS, @@ -59,12 +60,10 @@ export function classifyFetch(input: ClassificationInput): FetchClassification { } /** - * 06-08. Vite's default `build.assetsDir`, under the app base that is also the - * registration scope. A hashed-looking API or download name elsewhere is not an - * old build chunk and is left to the browser. + * 06-08. `BUILD_ASSET_DIRECTORY` is resolved under the app base that is also + * the registration scope. A hashed-looking API or download name elsewhere is + * not an old build chunk and is left to the browser. */ -const BUILD_ASSET_DIRECTORY = "assets/"; - function isSameOriginHashedAsset(requestUrl: string, scopeUrl: string): boolean { try { const request = new URL(requestUrl); diff --git a/src/contracts/service-worker.ts b/src/contracts/service-worker.ts index b0f1f62a..85d4deeb 100644 --- a/src/contracts/service-worker.ts +++ b/src/contracts/service-worker.ts @@ -115,6 +115,16 @@ export interface StaticAssetManifestV1 { */ export const HASHED_STATIC_ASSET_NAME = /-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/; +/** + * 1105/06-01. Vite's default `build.assetsDir` (`vite.config.ts` leaves it + * unset), relative to the app base. Vite writes content-hashed files only + * here; `public/` files land at the dist root under their own names, so a + * name there that matches `HASHED_STATIC_ASSET_NAME` is not immutable. The + * precache generator, the worker's previous-release fallback and the hosting + * probe read this one value (0925/06-08: change it with `build.assetsDir`). + */ +export const BUILD_ASSET_DIRECTORY = "assets/" as const; + /** §18.2. `ca-static-v1-`. */ export const STATIC_CACHE_PREFIX = "ca-static-v1-" as const; diff --git a/tests/unit/service-worker-web-push-remediation.test.ts b/tests/unit/service-worker-web-push-remediation.test.ts index dfb9efc9..50b1e949 100644 --- a/tests/unit/service-worker-web-push-remediation.test.ts +++ b/tests/unit/service-worker-web-push-remediation.test.ts @@ -125,6 +125,37 @@ describe("SW-02 the generator and the decoder share one path grammar", () => { } }); + // 1105/06-01. `public/` files are copied to the dist root under their own + // names. A PWA icon such as `android-chrome-192x192.png` matches the hashed + // name pattern, but a product may change its bytes under the same name; a + // CDN that still serves the old bytes then fails every install with + // INTEGRITY_MISMATCH. Only Vite's assets directory holds hashed files. + it("precaches only the assets directory, not public files at the dist root", async () => { + const { collectStaticAssets } = await import( + "../../scripts/generate-service-worker-assets.ts" + ); + const root = await distWith({ + "index.html": "page", + "config.json": "{}", + "release-manifest.json": "{}", + "apple-touch-icon.png": "icon", + "android-chrome-192x192.png": "icon", + "safari-pinned-tab.svg": "icon", + "favicon.svg": "icon", + "robots.txt": "robots", + "icons/maskable-512x512.png": "icon", + "assets/index-AbCdEf12.js": "entry", + "assets/index-AbCdEf12.css": "style", + }); + + const manifest = await collectStaticAssets(root, "build-1", "release-1"); + + expect(manifest.assets.map((asset) => asset.url)).toEqual([ + "/assets/index-AbCdEf12.css", + "/assets/index-AbCdEf12.js", + ]); + }); + // 0929/06-02. dist is served under the router base path; a root URL made // the worker's install request /assets/... and fail under /app/. it("puts every asset URL under the router base path", async () => { -- 2.54.0 From 3b62ccd5dbe501d3eabb0ecd9f7f2963df685496 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:10:05 +0900 Subject: [PATCH 12/74] =?UTF-8?q?fix(registry):=20=EC=9D=91=EB=8B=B5=20?= =?UTF-8?q?=EC=8A=A4=ED=82=A4=EB=A7=88=20=ED=96=89=EC=9D=84=20REJECT=5FUNK?= =?UTF-8?q?NOWN=EC=9C=BC=EB=A1=9C=20=EC=A2=81=ED=9E=88=EB=A9=B4=20breaking?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EB=B3=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 응답 DTO를 `.strict()`로 바꾸고 FE-REG-SCHEMA 행의 `unknownFieldPolicy`를 STRIP_UNKNOWN에서 REJECT_UNKNOWN으로 같이 고치면 check:registries가 behavior-change로 통과한다(리뷰 배치 07-R1). 1103/07-03 수정은 행과 검증기를 묶었지만 등급은 그대로였다. 그 뒤 백엔드가 응답에 필드 하나를 더하면 그 API는 SCHEMA_MISMATCH로 실패한다. 같은 경계에서 FE-REG-API는 acceptedStatuses 축소를 breaking으로 본다. 고른 방법: 분류기에 규칙 하나를 더한다. `direction: "RESPONSE"` 행의 `unknownFieldPolicy`가 REJECT_UNKNOWN이 아니던 값에서 REJECT_UNKNOWN으로 바뀌면 kind `response-reader-narrowed`, breaking이다. 반대 방향 (REJECT→STRIP, 읽는 쪽을 넓힘)과 REQUEST 행(프론트가 스스로 채우는 값)은 그대로 behavior-change다. 버린 대안: governance의 FE-REG-SCHEMA breakingFields에 `unknownFieldPolicy`를 넣는 것(리뷰 안 B). 넓히는 변경까지 증거를 요구하게 되고, governance 계약이 바뀌어 템플릿과 다운스트림 모두 기준선을 다시 승인해야 한다. 이 규칙은 기준선과 governance를 바꾸지 않는다. 리뷰 안 (1)의 fieldTypes 선언도 같은 이유로 하지 않았다. 위험·한계: 규칙은 칸 이름(`unknownFieldPolicy`)과 값 어휘 (src/contracts/schema-registry.ts)에 묶여 있다. 어휘를 바꾸면 이 함수도 고친다. route-params·route-search(REQUEST 방향, URL을 읽는 쪽)를 REJECT_UNKNOWN으로 좁히는 변경은 여전히 behavior-change다. 지금 템플릿 스냅샷은 기준선과 같아 결과는 none 그대로다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/unit/registry-compatibility.test.ts 리뷰 07-R1 패치(응답 DTO `.strict()` + 응답 행 두 개 REJECT_UNKNOWN)를 다시 적용하면 check:registries가 `breaking change missing evidence: FE-REG-SCHEMA:ReferenceResource(List)Payload:unknownFieldPolicy: response-reader-narrowed`로 실패해야 한다. Refs: 1105/07-02 --- docs/contracts/compatibility.md | 5 ++ docs/manual/01-add-a-feature.md | 1 + scripts/lib/registry-compatibility.ts | 25 ++++++++++ tests/unit/registry-compatibility.test.ts | 60 +++++++++++++++++++++++ 4 files changed, 91 insertions(+) diff --git a/docs/contracts/compatibility.md b/docs/contracts/compatibility.md index 5d1337b2..ce4d99c5 100644 --- a/docs/contracts/compatibility.md +++ b/docs/contracts/compatibility.md @@ -30,6 +30,11 @@ reader that accepts it must ship before any writer sends it. | Browser RPC transport error code | closed vocabulary; unknown code is a protocol violation | breaking | `decodeTransportFailure` in `src/adapters/browser-rpc/browser-rpc-runtime.ts` | | Persisted client storage | versioned key; incompatible value discarded | use a new key version | `defineStorageKey` in `src/contracts/storage-keys.ts` | +Turning a response DTO strict changes its row in this table. `check:registries` +grades it as breaking (`response-reader-narrowed`) when the FE-REG-SCHEMA row +of a `RESPONSE` schema goes from `STRIP_UNKNOWN` to `REJECT_UNKNOWN`, so the +change needs registry evidence (1105/07-02). + `CAPABILITY_OVERRIDES` and `FEATURE_OVERRIDES` differ on purpose. Feature ids vary per build because each downstream project installs its own features, and one shared config document may cover several builds. The capability set is diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 6128b020..442978a1 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -539,6 +539,7 @@ projectRequest: (input) => Object.freeze({ - 행을 **빼거나** breaking 칸을 **바꾸면** breaking 변경이다. breaking 칸은 `config/contracts/registry-governance.json`의 `breakingFields`다. 배열 칸에서 값을 빼는 것도 breaking이다. - FE-REG-API 예: 생성 API의 `acceptedStatuses`를 `[200, 201]`에서 `[201]`로 줄이거나, `problemSchema`를 바꾸거나, 검증기를 `unvalidatedPayload`로 바꾸면(`unvalidated` 칸) breaking이다. - status를 더하는 것, 바이트 상한·마감·`retryBudget`·`traffic`·`commandEffect`·`commandRecovery`를 바꾸는 것은 behavior-change다. 통과하지만 스냅샷 diff(`artifacts/quality/registries.json`의 `compatibility.changes`)에 남는다. PR에서 본다. + - FE-REG-SCHEMA 예: 응답 DTO를 `.strict()`로 바꾸고 스키마 메타 행을 `REJECT_UNKNOWN`으로 고치면(`direction: "RESPONSE"`) `response-reader-narrowed` breaking이다. 백엔드가 응답에 필드를 하나 더하면 그 API가 `SCHEMA_MISMATCH`로 실패하기 때문이다. 반대(`REJECT_UNKNOWN`→`STRIP_UNKNOWN`)와 요청 행은 behavior-change다. - breaking 변경이면 둘 중 하나를 한다. - `REGISTRY_BASELINE_OWNER`, `REGISTRY_BASELINE_REASON`을 주고 `corepack pnpm update:registry-baseline`을 돌린다. - 또는 `config/contracts/registry-change-evidence.json`에 항목을 더한다. 칸 설명은 `docs/operations/ci-quality-gates.md`에 있다. diff --git a/scripts/lib/registry-compatibility.ts b/scripts/lib/registry-compatibility.ts index c69fb510..5d20de5a 100644 --- a/scripts/lib/registry-compatibility.ts +++ b/scripts/lib/registry-compatibility.ts @@ -138,6 +138,28 @@ function onlyExtendsAllowedValues(before: unknown, after: unknown): boolean { }); } +/** + * 1105/07-02. A response schema row that starts rejecting unknown keys + * narrows what the frontend accepts, as removing an accepted status does in + * FE-REG-API: every response the backend extends with a field then fails with + * SCHEMA_MISMATCH. That one direction is breaking. REJECT -> STRIP widens the + * reader, and a REQUEST row's policy is checked against what the frontend + * itself sends; both stay behavior-change, as does any other policy change. + */ +function narrowsResponseReader( + field: string, + before: unknown, + after: unknown, + row: Readonly>, +): boolean { + return ( + field === "unknownFieldPolicy" && + before !== "REJECT_UNKNOWN" && + after === "REJECT_UNKNOWN" && + row.direction === "RESPONSE" + ); +} + function changeId( registryId: string, rowName: string, @@ -343,6 +365,9 @@ export function diffRegistrySnapshots( } else if (keyedSetFields.has(field) && Array.isArray(afterValue)) { kind = "set-items-added"; changeImpact = "additive"; + } else if (narrowsResponseReader(field, beforeValue, afterValue, afterRow)) { + kind = "response-reader-narrowed"; + changeImpact = "breaking"; } else { kind = "field-changed"; changeImpact = breakingFields.has(field) diff --git a/tests/unit/registry-compatibility.test.ts b/tests/unit/registry-compatibility.test.ts index 04236396..b18768c8 100644 --- a/tests/unit/registry-compatibility.test.ts +++ b/tests/unit/registry-compatibility.test.ts @@ -123,6 +123,66 @@ describe("registry compatibility evidence", () => { }); }); + // 1105/07-02. A response schema that starts rejecting unknown keys fails + // every response the backend extends with a field, so it is graded like + // removing an accepted status. Widening, and a request row the frontend + // fills itself, stay behavior-change. The rows are FE-REG-SCHEMA's shape + // (src/contracts/schema-registry.ts), not the committed baseline, which + // loses the reference rows when the sample is removed. + describe("a schema row's unknown-key policy", () => { + const contract = { breakingFields: ["schemaId", "boundary", "runtime"] }; + function schemas(direction: "REQUEST" | "RESPONSE", unknownFieldPolicy: string) { + return { + schemaVersion: 2, + registries: [ + { + registryId: "FE-REG-SCHEMA", + contract, + rows: { + Payload: { + schemaId: "Payload", + boundary: direction === "RESPONSE" ? "api-response" : "api-request", + direction, + owner: "fixture", + runtime: "zod", + schemaVersion: 1, + unknownFieldPolicy, + }, + }, + }, + ], + }; + } + + it.each([ + ["a response narrowed to REJECT_UNKNOWN", "RESPONSE", "STRIP_UNKNOWN", "REJECT_UNKNOWN", "response-reader-narrowed", "breaking"], + ["a response widened to STRIP_UNKNOWN", "RESPONSE", "REJECT_UNKNOWN", "STRIP_UNKNOWN", "field-changed", "behavior-change"], + ["a request narrowed to REJECT_UNKNOWN", "REQUEST", "STRIP_UNKNOWN", "REJECT_UNKNOWN", "field-changed", "behavior-change"], + ["a request widened to STRIP_UNKNOWN", "REQUEST", "REJECT_UNKNOWN", "STRIP_UNKNOWN", "field-changed", "behavior-change"], + ] as const)("grades %s", (_label, direction, before, after, kind, impact) => { + const diff = diffRegistrySnapshots( + schemas(direction, before), + schemas(direction, after), + ); + expect(diff.changes.map((change) => [change.changeId, change.impact])).toEqual([ + [`FE-REG-SCHEMA:Payload:unknownFieldPolicy:${kind}`, impact], + ]); + expect(diff.impact).toBe(impact); + }); + + it("asks for evidence when a response row is narrowed", () => { + const diff = diffRegistrySnapshots( + schemas("RESPONSE", "STRIP_UNKNOWN"), + schemas("RESPONSE", "REJECT_UNKNOWN"), + ); + expect( + validateBreakingEvidence(diff, { schemaVersion: 1, changes: [] }).failures, + ).toEqual([ + "breaking change missing evidence: FE-REG-SCHEMA:Payload:unknownFieldPolicy:response-reader-narrowed", + ]); + }); + }); + // 1101/16-01 (decision 1). Every feature with server state adds a topic, so // adding one must not need a new baseline. The committed baseline is used // as it stands: after the sample's removal its graph may be empty. -- 2.54.0 From 471b001c409793ef79466dd0a1a87683b8179f7a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:11:17 +0900 Subject: [PATCH 13/74] =?UTF-8?q?fix(http):=20Fileserver=20504=20TRANSFER?= =?UTF-8?q?=5FTIMEOUT=EB=A5=BC=20=EA=B2=B0=EA=B3=BC=20=EB=B6=88=EB=AA=85?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=9D=BD=EA=B3=A0=20=EB=A9=B1=EB=93=B1=20?= =?UTF-8?q?=EC=9D=91=EB=8B=B5=EC=9D=80=20V3=20=ED=91=9C=EB=A5=BC=20?= =?UTF-8?q?=EC=93=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: client는 504 TRANSFER_TIMEOUT을 NOT_APPLIED, retryable:true, retryAfterMs 5000으로 준다. 매뉴얼대로면 기능이 5초 뒤 자동으로 다시 올린다. 근거로 든 "백엔드가 게시 전에 낸다"는 이 code에 맞지 않는다. 백엔드(45d2a478)는 업로드 작업을 전송 풀에 넘기고, 대기 스레드가 await-seconds가 지나면 작업 단계와 상관없이 future.cancel(true) 뒤 TRANSFER_TIMEOUT을 던진다(BlockingTransferExecutor). interrupt는 파일 복사는 멈추지만 게시 rename과 READY 커밋은 멈추지 않는다. 그래서 504 뒤에 파일이 READY가 될 수 있고, 백엔드가 멱등 키를 읽지 않으므로 다시 보내면 같은 파일이 둘 생긴다. 같은 client의 효과 표는 V3 표와도 갈라졌다. 503 IDEMPOTENCY_UNAVAILABLE을 client는 NOT_APPLIED, V3 표(backend-envelope.ts)와 매뉴얼 4절은 MAYBE_APPLIED로 본다. 계약 문서 6.1의 fileserver 행은 4xx를 MAYBE_APPLIED로 적는데 client는 NOT_APPLIED로 보고, 어느 쪽도 다른 쪽을 말하지 않는다. pin 대조도 이 표를 보지 않는다. 고른 방법: - TRANSFER_TIMEOUT을 NOT_APPLIED_5XX_CODES에서 뺀다. 5xx 기본값대로 MAYBE_APPLIED이고, createFailure가 retryable:false, action contact-support로 만든다. 자동 재전송은 없다. 남은 NOT_APPLIED 5xx는 작업 스레드가 게시 전에 내는 넷(PARTIAL_WRITE, ATOMIC_PUBLISH_UNSUPPORTED, STORAGE_UNAVAILABLE, STORAGE_FULL)이다. - 멱등성 code(IDEMPOTENT_*, IDEMPOTENCY_* 접두)와 V3 표의 행(REFUSED_BEFORE_WRITE, MAYBE_APPLIED_ANSWERS의 status+code)은 client도 envelopeFailureEffect로 판정한다(sharedAnswerEffect). 같은 백엔드 code의 판정이 이 repo에 하나다. 503 IDEMPOTENCY_UNAVAILABLE은 MAYBE_APPLIED가 되고, 400 IDEMPOTENCY_KEY_INVALID·422 IDEMPOTENT_REQUEST_MISMATCH는 그대로 NOT_APPLIED, 409 IDEMPOTENT_IN_FLIGHT 등은 그대로 MAYBE_APPLIED다. 손으로 둔 MAYBE_APPLIED_CODES 목록은 AMBIGUOUS_COMPLETION 비교 하나로 줄었다. - pin 옆에 복사한 백엔드 답 표(config/contracts/backend-idempotency-answers.json)의 행마다 client 결과의 effect가 V3 표와 같은지 통합 테스트가 본다. 그 표는 tests/unit/backend-contract-pin.test.ts가 V3 표를 묶는 표와 같다. pin을 옮기면 두 reader가 함께 다시 대조된다. - Fileserver 4xx를 NOT_APPLIED로 보는 이유(업로드 use case가 취소)를 계약 문서 6.1에 한 곳으로 적고, client 주석과 매뉴얼은 그곳을 가리킨다. - client 주석·매뉴얼의 백엔드 SHA 표기를 bbe944bd에서 pin(45d2a478)으로 맞췄다. 두 SHA 사이 Fileserver main 코드는 바뀌지 않았다(리뷰 2.1절). 버린 대안: - client 효과 판정을 V3 표로 통째로 바꾼다: Fileserver 4xx가 모두 결과 불명이 되어 413·415·422 파일 거절과 202 REJECTED 화면이 나빠진다. 단일 업로드에서는 use case가 취소하므로 근거도 없다. - TRANSFER_TIMEOUT 한 줄만 고친다: 위험한 줄은 없어지지만 세 표의 갈라짐과 pin 밖 상태가 남는다. 위험·한계: - 504 TRANSFER_TIMEOUT 뒤 화면이 "재시도"에서 "결과 불명"으로 바뀐다. 503 IDEMPOTENCY_UNAVAILABLE도 같다. CHANGELOG [계약] 한 줄이 필요하다. - 백엔드로 넘김: 백엔드는 TRANSFER_TIMEOUT을 retryable=true, ambiguous 없이 보낸다(FileserverErrorCode, BlockingTransferExecutor). 요청 — (a) 작업이 시작된 뒤의 대기 초과는 details.ambiguous=true, reconciliationRequired=true, retryable=false로 보내거나, (b) 작업 스레드가 게시 rename과 READY 커밋 전에 interrupt를 확인해 504가 "READY 없음"을 보장하게 하고, 어느 쪽인지 docs/fileserver/http-contract.md에 적는다. 백엔드가 (b)를 고르면 이 줄을 되돌린다(재검토 조건). - 백엔드로 넘김: POST /v1/files가 Idempotency-Key를 읽지 않는다 (UploadFileApplicationUseCase NOT_IDEMPOTENT). 요청 — 업로드를 멱등성 executor 뒤에 두거나, 키를 무시한다고 Fileserver 계약 문서에 적는다. - 리뷰 최소 개선 방향 ④의 "drift 검사 대상에 docs/fileserver/http-contract.md 추가"는 하지 않았다. scripts/check-backend-contract-drift.ts와 pin 모양은 같은 라운드의 1105/07-01 수정이 다시 짠다. 같은 파일을 두 브랜치가 고치면 충돌한다. 07-01과 함께 넣는 편이 낫다. - Fileserver 자신의 code 표(NOT_APPLIED_5XX_CODES)는 여전히 손으로 읽은 것이고 pin 대조 밖이다. 늦게 READY가 되는 경쟁은 재현하지 않았다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/integration/fileserver-upload.test.ts RED(이 커밋의 테스트 + 부모 src): Envelope failures 표의 "503 IDEMPOTENCY_UNAVAILABLE → SERVER_FAILURE, MAYBE_APPLIED, retryable false", "504 TRANSFER_TIMEOUT → SERVER_FAILURE, MAYBE_APPLIED, retryable false", "504 TRANSFER_TIMEOUT is an unknown result the client does not offer to retry", pinned backend answer table의 "reads 503 IDEMPOTENCY_UNAVAILABLE as the V3 Envelope table does"가 실패한다. Refs: 1105/01-02 --- .../backend-api-and-server-state-contract.md | 16 +++++ docs/manual/02-decision-tables.md | 11 +-- src/adapters/http/fileserver-upload.ts | 68 ++++++++++++------ tests/integration/fileserver-upload.test.ts | 70 ++++++++++++++++++- 4 files changed, 140 insertions(+), 25 deletions(-) diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 2e2fe977..e3a317fc 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -330,6 +330,22 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 `RepoStatsAclMapper.java`, `DomainExceptionHandler.java`: `clean-architecture-backend-template/src/sample-portfolio/` - `FileserverErrorCode.java`, `FinalizeUploadApplicationUseCase.java`: `clean-architecture-backend-template/src/application-fileserver/` +- Fileserver 한 번 업로드(`POST /v1/files`)는 V3 실행기가 아니라 + `src/adapters/http/fileserver-upload.ts`의 client가 부른다(1105/01-02). 이 client는 + 위 표의 fileserver 행과 달리 4xx를 `NOT_APPLIED`로 본다. 업로드 use case + (`UploadFileApplicationUseCase.java`)가 모호하지 않은 실패에서 업로드를 취소하므로 + `READY` 파일이 남지 않는다. `MALWARE_DETECTED`처럼 레코드를 `REJECTED`로 쓴 뒤 + 던지는 code도 그 레코드는 공개되지 않는다. 위 행은 fileserver 응답을 V3 실행기로 + 읽을 때의 판정이다. + - 멱등성 code와 V3 표(`REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`)에 있는 답은 + client도 V3 표로 판정한다. 그래서 503 `IDEMPOTENCY_UNAVAILABLE`은 `MAYBE_APPLIED`다. + `tests/integration/fileserver-upload.test.ts`가 복사한 답 표의 행마다 둘이 같은지 본다. + - 5xx는 작업 스레드가 게시 전에 내는 code 넷(`PARTIAL_WRITE`, + `ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `STORAGE_FULL`)만 + `NOT_APPLIED`다. 504 `TRANSFER_TIMEOUT`은 `MAYBE_APPLIED`다. 대기 스레드가 + 작업 단계와 상관없이 내고, 게시 rename과 `READY` 커밋은 interrupt로 멈추지 않는다 + (`BlockingTransferExecutor.java`, `FinalizeUploadApplicationUseCase.java`). 백엔드는 + 이 code를 `retryable: true`, `ambiguous` 없이 보낸다. 이 차이는 백엔드 결정으로 남는다. **operation이 선언하는 쓰기 전 거절**(1103/03-01): 업무 code는 엔드포인트마다 단계가 달라 위 표에 "쓰기 뒤 가능"으로 둔다. 쓰기 전에만 그 code를 내는 엔드포인트를 diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 95869c07..77f5d1ad 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -316,13 +316,15 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - 빈 파일은 보내지 않는다. 짝 백엔드 기본 검증기가 빈 파일을 거절하기 때문이다. `VALIDATION_REJECTED`, code `FILE_EMPTY`, `NOT_STARTED`다. - 실패 `effect`: - `NOT_STARTED`: 보내지 않았다. 입력, 크기, 자격 증명에서 거절했다. - - `NOT_APPLIED`: 서버가 거절했고 파일은 없다. Fileserver는 모호하지 않은 실패에서 업로드를 취소한다. 아래 `MAYBE_APPLIED` 경우를 뺀 4xx와, 5xx 중 정한 code(`STORAGE_UNAVAILABLE` 등)다. - - `MAYBE_APPLIED`: 올라갔을 수도 있다. 응답을 잃음, 시간 초과, `details.ambiguous: true`, 409 `IDEMPOTENT_IN_FLIGHT`, 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`, 그 밖의 5xx다. 다시 보낼 때는 같은 `idempotencyKey`를 쓴다. + - `NOT_APPLIED`: 서버가 거절했고 파일은 없다. Fileserver는 모호하지 않은 실패에서 업로드를 취소한다. 아래 `MAYBE_APPLIED` 경우를 뺀 4xx와, 5xx 중 작업 스레드가 게시 전에 내는 code 넷(`PARTIAL_WRITE`, `ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `STORAGE_FULL`)이다. + - `MAYBE_APPLIED`: 올라갔을 수도 있다. 응답을 잃음, 시간 초과, `details.ambiguous: true`, 그 밖의 5xx다. 504 `TRANSFER_TIMEOUT`도 여기 든다. 백엔드는 대기 시간이 지나면 작업이 어느 단계에 있든 이 code를 내고, 작업은 그 뒤에 끝나 `READY`가 될 수 있다. 다시 보낼 때는 같은 `idempotencyKey`를 쓴다. + - 멱등성 응답(`IDEMPOTENT_*`, `IDEMPOTENCY_*`)과 V3 표에 있는 web 공통 응답은 V3 실행기와 같은 표(`backend-envelope.ts`, 4절)로 판정한다. 400 `IDEMPOTENCY_KEY_INVALID`·422 `IDEMPOTENT_REQUEST_MISMATCH`는 `NOT_APPLIED`, 409 `IDEMPOTENT_IN_FLIGHT`·503 `IDEMPOTENCY_UNAVAILABLE`·503 `IDEMPOTENCY_COMPLETION_UNKNOWN`·500 `IDEMPOTENCY_RECOVERY_REQUIRED`는 `MAYBE_APPLIED`다. - `APPLIED_CONFIRMED`: 서버는 만들었다고 답했지만 응답을 읽지 못했다. 다시 올리지 않는다. - `code`는 백엔드 code 그대로다(`FILE_TOO_LARGE`, `UNSUPPORTED_MEDIA_TYPE`, `MALWARE_DETECTED` …). 백엔드가 code를 주지 않는 거절은 client가 이름을 붙인다(`FILE_REJECTED`, `FILE_EMPTY`, `FILE_NOT_READABLE`). 화면 문구는 기능이 code로 고른다. - client는 스스로 다시 보내지 않는다. `retryable: true`이고 `retryAfterMs`가 있으면 그만큼 기다린 뒤 기능이 다시 부른다. 서버가 상한(`maxRetryAfterMs`, 기본 30초)보다 길게 기다리라고 하면 `retryable: false`다. +- `MAYBE_APPLIED`는 언제나 `retryable: false`다. 백엔드가 Envelope에 `retryable: true`와 `Retry-After`를 붙여도(504 `TRANSFER_TIMEOUT`) 기능이 자동으로 다시 부르지 않는다. 아래 주의대로 먼저 확인한다. -**주의 — 멱등 키**: 짝 백엔드(`bbe944bd`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`). +**주의 — 멱등 키**: 짝 백엔드(`45d2a478`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`). - 그래서 `MAYBE_APPLIED` 뒤 다시 보내면 같은 파일이 두 개 생길 수 있다. - 같은 키 재전송이 중복을 막는 것은 배포가 업로드를 백엔드 멱등성 executor 뒤에 둘 때뿐이다. @@ -397,5 +399,6 @@ export const createAttachmentFeatureInput = defineFeatureAdapterContribution({ - 프로필의 필수 헤더가 없으면 `fetch`를 부르지 않고 `MISSING_REQUIRED_CREDENTIAL_HEADER`로 끝난다. - 파일이 `maxFileBytes`보다 크면 읽기 전에 `FILE_TOO_LARGE`(`NOT_STARTED`)다. 비어 있으면 `FILE_EMPTY`(`NOT_STARTED`)다. - 202 응답을 모두 "검사 중"으로 보이면 `QUARANTINED` 파일의 화면이 끝나지 않는다. state마다 따로 보인다. -- 백엔드가 Fileserver 응답 모양이나 code를 바꾸면 검사가 잡지 못한다. 실패 판정 표(`fileserver-upload.ts`의 `NOT_APPLIED_5XX_CODES`, `MAYBE_APPLIED_CODES`)는 백엔드 `bbe944bd` 기준이다. 백엔드 SHA가 바뀌면 같이 다시 본다. +- 멱등성·web 공통 응답의 판정은 V3 표를 그대로 쓴다. `tests/integration/fileserver-upload.test.ts`가 pin 옆에 복사한 백엔드 답 표(`config/contracts/backend-idempotency-answers.json`)의 행마다 client와 V3 표가 같은지 본다. pin을 옮기면 같이 다시 돈다. +- 백엔드가 Fileserver 응답 모양이나 Fileserver 자신의 code를 바꾸면 검사가 잡지 못한다. 그 표(`fileserver-upload.ts`의 `NOT_APPLIED_5XX_CODES`)는 백엔드 `45d2a478`(pin) 코드를 읽은 것이다. 백엔드 SHA가 바뀌면 `FileserverErrorCode`, `BlockingTransferExecutor`, 게시 경로를 같이 다시 본다. 4xx를 `NOT_APPLIED`로 보는 이유는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절에 있다. - 테스트 예: `tests/integration/fileserver-upload.test.ts`(백엔드 코드가 답하는 대로 답하는 MSW. 백엔드 문서는 202 `VERIFYING`만 적는다). diff --git a/src/adapters/http/fileserver-upload.ts b/src/adapters/http/fileserver-upload.ts index 4e833b0a..2ef5465c 100644 --- a/src/adapters/http/fileserver-upload.ts +++ b/src/adapters/http/fileserver-upload.ts @@ -15,10 +15,13 @@ import { } from "../platform/abortable-operation.ts"; import { parseRetryAfterDelay } from "../platform/retry-after.ts"; import { + envelopeFailureEffect, envelopeFailureReading, gatewayFailureOr, + maybeAppliedAnswerRows, readFailureEnvelope, readSuccessEnvelope, + refusedBeforeWriteRows, type EnvelopeError, } from "./backend-envelope.ts"; import { @@ -35,7 +38,8 @@ import type { AuthOperationContext } from "./http-execution-v3.ts"; /** * 2026-11-03 01-01. A client for the paired backend Fileserver's multipart * single upload, `POST /v1/files` (clean-architecture-backend-template - * `bbe944bd`, docs/fileserver/http-contract.md; Envelope and idempotency in + * `45d2a478`, the commit config/contracts/backend-contract-pin.json pins; + * docs/fileserver/http-contract.md and its code; Envelope and idempotency in * docs/web/http-contract.md §1–§2). * * The paired backend removed presigned and direct multipart transfer on @@ -111,7 +115,7 @@ export type FileserverUploadRequest = Readonly<{ mediaType?: string; /** * Sent as `Idempotency-Key`. After a `MAYBE_APPLIED` failure, resend with - * the same key and never a new one. At `bbe944bd` the backend runs + * the same key and never a new one. At `45d2a478` the backend runs * `POST /v1/files` without its idempotency executor, so the key protects * only a deployment that routes the upload through it. */ @@ -172,30 +176,49 @@ const MAX_FILENAME_LENGTH = 255; /** * Backend `UploadFileApplicationUseCase` cancels the upload on every failure - * except an ambiguous completion, and the Fileserver contract marks a failure - * that may already have taken effect with `details.ambiguous`. So a 4xx - * Envelope is NOT_APPLIED unless it says otherwise. A 5xx stays MAYBE_APPLIED - * except these codes, which the backend raises before the file is published - * (`FileserverErrorCode`; 503 IDEMPOTENCY_UNAVAILABLE is web contract §2). - * Recheck both lists when the backend SHA above moves. + * its worker raises except an ambiguous completion, and the Fileserver + * contract marks a failure that may already have taken effect with + * `details.ambiguous`. So a 4xx Envelope is NOT_APPLIED unless it says + * otherwise. A 5xx stays MAYBE_APPLIED except these codes, which the worker + * raises before the file is published (`FileserverErrorCode`, + * `AtomicMoveContentPublisher`). Recheck the list when the pinned backend + * commit moves; contract §6.1 says why the 4xx reading differs from its + * fileserver row. + * + * 1105/01-02. 504 TRANSFER_TIMEOUT is not here. The waiting servlet thread + * raises it when `await-seconds` runs out, whatever stage the worker is in + * (`BlockingTransferExecutor`), and the interrupt that follows does not stop a + * publish rename or the READY commit. The file may still become READY, so a + * resend can store it twice. */ const NOT_APPLIED_5XX_CODES: ReadonlySet = new Set([ "PARTIAL_WRITE", "ATOMIC_PUBLISH_UNSUPPORTED", "STORAGE_UNAVAILABLE", - "TRANSFER_TIMEOUT", "STORAGE_FULL", - "IDEMPOTENCY_UNAVAILABLE", ]); -/** Answers that may have taken effect whatever their status. */ -const MAYBE_APPLIED_CODES: ReadonlySet = new Set([ - "AMBIGUOUS_COMPLETION", - // Web contract §2: resend with the same key, never a new one. - "IDEMPOTENT_IN_FLIGHT", - "IDEMPOTENCY_COMPLETION_UNKNOWN", - "IDEMPOTENCY_RECOVERY_REQUIRED", -]); +/** + * 1105/01-02. The web contract's own answers (idempotency §2, and the other + * codes the V3 table lists) read as the V3 executor reads them, so the same + * backend code has one verdict in this repository. The idempotency codes are + * taken by prefix: one the table does not list yet stays MAYBE_APPLIED. + */ +function sharedAnswerEffect( + status: number, + error: EnvelopeError, +): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined { + const listed = (rows: readonly Readonly<{ code: string; status: number }>[]) => + rows.some((row) => row.code === error.code && row.status === status); + if ( + !/^IDEMPOTEN(?:T|CY)_/u.test(error.code) && + !listed(refusedBeforeWriteRows()) && + !listed(maybeAppliedAnswerRows()) + ) { + return undefined; + } + return envelopeFailureEffect(status, error) ?? "MAYBE_APPLIED"; +} export function createFileserverUploadClient( dependencies: FileserverUploadClientDependencies, @@ -722,7 +745,10 @@ function envelopeFailure( }); } -/** See `NOT_APPLIED_5XX_CODES`. */ +/** + * In this order: an ambiguous answer, then the web contract's own answers + * (`sharedAnswerEffect`), then the Fileserver reading (`NOT_APPLIED_5XX_CODES`). + */ export function fileserverFailureEffect( status: number, error: EnvelopeError, @@ -733,7 +759,9 @@ export function fileserverFailureEffect( typeof details === "object" && !Array.isArray(details) && (details as Readonly>)["ambiguous"] === true; - if (ambiguous || MAYBE_APPLIED_CODES.has(error.code)) return "MAYBE_APPLIED"; + if (ambiguous || error.code === "AMBIGUOUS_COMPLETION") return "MAYBE_APPLIED"; + const shared = sharedAnswerEffect(status, error); + if (shared !== undefined) return shared; if (status >= 400 && status < 500) return "NOT_APPLIED"; return NOT_APPLIED_5XX_CODES.has(error.code) ? "NOT_APPLIED" : "MAYBE_APPLIED"; } diff --git a/tests/integration/fileserver-upload.test.ts b/tests/integration/fileserver-upload.test.ts index 79b6bd4c..c8f9aa86 100644 --- a/tests/integration/fileserver-upload.test.ts +++ b/tests/integration/fileserver-upload.test.ts @@ -1,8 +1,12 @@ +import { readFileSync } from "node:fs"; + import { delay, HttpResponse, http, type JsonBodyType } from "msw"; import { setupServer } from "msw/node"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { z } from "zod"; import type { FileByteSource } from "../../src/application/ports/browser-file-storage/file.ts"; +import { envelopeFailureEffect } from "../../src/adapters/http/backend-envelope.ts"; import { createFileserverUploadClient, type CredentialPatchOutcome, @@ -369,9 +373,14 @@ describe("Fileserver multipart upload — Envelope failures", () => { { status: 500, code: "INTERNAL_ERROR", category: "INTERNAL", retryable: false, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, { status: 503, code: "STORAGE_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: true }, { status: 503, code: "STORAGE_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, details: { ambiguous: true }, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, - { status: 503, code: "IDEMPOTENCY_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: true }, + // 1105/01-02. As the V3 table reads it: only an unknown result keeps the key. + { status: 503, code: "IDEMPOTENCY_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, { status: 503, code: "IDEMPOTENCY_COMPLETION_UNKNOWN", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, { status: 507, code: "STORAGE_FULL", category: "TRANSIENT_DEPENDENCY", retryable: false, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: false }, + // 1105/01-02. Raised by the waiting thread at any stage of the work, which + // may still publish the file: the backend's own retryable:true does not + // make a resend safe. + { status: 504, code: "TRANSFER_TIMEOUT", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, ])( "$status $code → $kind, $effect, retryable $clientRetryable", async ({ status, code, category, retryable, details, kind, effect, clientRetryable }) => { @@ -427,6 +436,28 @@ describe("Fileserver multipart upload — Envelope failures", () => { ]); }); + it("504 TRANSFER_TIMEOUT is an unknown result the client does not offer to retry", async () => { + // 1105/01-02. The backend sends Retry-After: 5 with it. + answer({ + status: 504, + body: failureEnvelope("TRANSFER_TIMEOUT", "TRANSIENT_DEPENDENCY", true), + headers: { "Retry-After": "5" }, + }); + + const result = await client().client.upload(upload()); + + expect(result).toMatchObject({ + ok: false, + error: { + kind: "SERVER_FAILURE", + code: "TRANSFER_TIMEOUT", + effect: "MAYBE_APPLIED", + retryable: false, + action: "contact-support", + }, + }); + }); + it.each([ { retryAfter: "3", retryable: true, retryAfterMs: 3_000 }, // 2026-11-03 01-02: past the ceiling, neither the wait nor an immediate retry. @@ -451,6 +482,43 @@ describe("Fileserver multipart upload — Envelope failures", () => { ); }); +/** + * 1105/01-02. The backend answer table copied next to the pin + * (config/contracts/backend-contract-pin.json) holds the V3 Envelope table in + * tests/unit/backend-contract-pin.test.ts. The same rows hold this client, so + * one backend code has one verdict and a pin move rechecks both readers. + */ +const PINNED_ANSWERS = (() => { + const pin = z + .object({ tables: z.object({ idempotencyAnswers: z.string().min(1) }) }) + .parse(JSON.parse(readFileSync("config/contracts/backend-contract-pin.json", "utf8"))); + return z + .object({ + answers: z + .array(z.object({ code: z.string().min(1), status: z.number().int() })) + .min(1), + }) + .parse(JSON.parse(readFileSync(pin.tables.idempotencyAnswers, "utf8"))).answers; +})(); + +describe("Fileserver multipart upload — the pinned backend answer table", () => { + it.each(PINNED_ANSWERS.map((row) => [`${row.status} ${row.code}`, row] as const))( + "reads %s as the V3 Envelope table does", + async (_label, row) => { + answer({ + status: row.status, + body: failureEnvelope(row.code, "TRANSIENT_DEPENDENCY", false), + }); + + const result = await client().client.upload(upload()); + + expect(result.ok ? undefined : result.error.effect).toBe( + envelopeFailureEffect(row.status, { code: row.code }), + ); + }, + ); +}); + describe("Fileserver multipart upload — unknown results", () => { it("a network failure after sending is MAYBE_APPLIED, and the resend keeps the key", async () => { const captured = answer("NETWORK_ERROR", { -- 2.54.0 From 4d6f25443873764080691327cc6fdda923f3ce20 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:11:49 +0900 Subject: [PATCH 14/74] =?UTF-8?q?fix(hosting):=20=EC=9E=90=EC=82=B0=20MIME?= =?UTF-8?q?=20probe=EA=B0=80=20redirect=EB=A5=BC=20=EA=B1=B0=EC=A0=88?= =?UTF-8?q?=ED=95=98=EA=B3=A0=20live=20=EB=B6=84=EA=B8=B0=EB=A5=BC=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 확장자별 MIME probe(1103/06-03)는 install 조건 일부만 옮겼다. 1. install fetch는 `redirect: "error"`라 redirect가 하나라도 있으면 실패한다. probe는 `redirect: "follow"`로 받고 최종 status와 MIME만 본다. 같은 origin 안 redirect 뒤 200을 주는 호스트가 PASS다(리뷰 06-R1). FE-GATE-019가 PASS인데 워커 install은 매번 실패한다. 2. 워커 없는 빌드에서도 돈다. 주석과 문서는 이유를 워커로만 적는다. 3. live 분기의 호출 줄(`verify-hosting-headers.ts`)을 지키는 테스트가 없다. live 모드는 루프백·http를 거절해 저장소 테스트가 들어갈 수 없다. 호출을 지우는 변이가 44건 통과로 살아남았다(06-R2). 고른 방법: 1. 자산 probe 기본 fetcher를 `redirect: "manual"`로 바꾸고, `response.redirected`이거나 `opaqueredirect`이면 관측 "redirected", 이유 "install fetch가 redirect를 거절"로 FAIL이다. 3xx는 지금처럼 `HTTP 3xx`로 FAIL이다. fetcher가 redirect를 따라가도 `redirected`로 잡으므로 fetcher 방식과 무관하다. 2. 동작은 그대로 두고 의도를 주석과 운영 문서에 적었다. 워커가 없어도 `nosniff` 아래 script·style은 MIME이 틀리면 페이지가 깨지고, 나중에 워커를 켜는 릴리스가 호스팅을 다시 확인하지 않아도 된다. 글꼴·이미지는 페이지에 피해가 없는데 FAIL한다는 것도 적었다. 워커 없는 빌드에서 script·style만 보도록 좁히는 것은 검사를 약하게 하는 정책 결정이라 하지 않았다(결정 대기, 템플릿 소유자). 3. live 분기 전체를 `probeLiveHosting`(release surface + 자산 MIME)으로 빼고 스크립트는 그것만 부른다. 테스트가 fetcher 대역으로 이 함수를 돌려 CSS `text/plain`이 FAIL인지 본다. 자산 probe 호출을 빼면 이 테스트가 실패한다. 스크립트에서 `probeLiveHosting` 호출을 빼면 live 결과가 비어 cache-control 행이 모두 FAIL이라 스스로 드러난다. 버린 대안: 문서에 한계만 적기(리뷰 (b)). 1·3이 그대로다. 위험·한계: 정규 경로 규칙으로 자산을 redirect하는 호스트는 이제 FE-GATE-019에서 FAIL이다. 워커가 없는 제품도 마찬가지다(2의 판단). 실제 호스트로 live 모드를 돌리지는 않았다. 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/hosting-probe.test.ts - RED: "fails an asset the host answers only after a redirect"(옛 probe는 redirect 뒤 200을 PASS), "checks every built asset type besides the release surfaces"(옛 코드에 `probeLiveHosting`이 없음)가 실패한다. - 변이(06-R2 대응): `probeLiveHosting`에서 `probeAssetContentTypes` 결과를 빼면 "checks every built asset type ..."가 실패해야 한다. Refs: 1105/06-02 --- docs/operations/release-cache-rollback.md | 6 ++ scripts/lib/hosting-probe.ts | 47 ++++++++++++++-- scripts/verify-hosting-headers.ts | 8 +-- tests/unit/hosting-probe.test.ts | 67 +++++++++++++++++++++++ 4 files changed, 119 insertions(+), 9 deletions(-) diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index 9515ccb0..b6211a37 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -78,6 +78,12 @@ release has under `assets/` (`.css`, `.js`, `.woff2` and the rest of exactly that type (`hashedAsset.css` and so on). The worker's install refuses the whole release when one precached asset has another type, while a page still uses a font served as `application/octet-stream` (review 1103/06-03). +The install fetch also refuses any redirect, so an asset the host answers only +after a redirect fails even when the final answer is a correct 200 (review +1105/06-02). This asset check runs for a build without a worker too: under +`nosniff` a script or style of another type breaks the page anyway, and a later +release that turns the worker on then needs no new hosting check. A font or +image of another type fails it although a worker-free page still loads it. The served `release-manifest.json` must name the `buildId` and `releaseId` of the release being checked: correct headers on an earlier release are not diff --git a/scripts/lib/hosting-probe.ts b/scripts/lib/hosting-probe.ts index 310d2d3e..82e90fd5 100644 --- a/scripts/lib/hosting-probe.ts +++ b/scripts/lib/hosting-probe.ts @@ -275,11 +275,20 @@ export function acceptedAssetContentTypes(extension: string): readonly string[] * mismatch, while a page still uses, say, a font served as octet-stream. The * entry script alone does not show that, so the live probe requests the first * built `assets/` file of each cacheable extension. + * + * 1105/06-02. The install fetch also refuses any redirect (`redirect: + * "error"`), so an asset answered only after one fails here too, whichever + * redirect mode the fetcher uses. + * + * It runs for a build without a worker as well, on purpose: under `nosniff` + * a script or style of another type breaks the page anyway, and a later + * release that turns the worker on needs no new hosting check. A font or + * image of another type fails this probe although such a page still loads it. */ export async function probeAssetContentTypes( base: URL, distFiles: readonly string[], - fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }), + fetcher: HostingFetcher = (url) => fetch(url, { redirect: "manual" }), ): Promise { const samples = new Map(); for (const file of distFiles.map((entry) => entry.split(path.sep).join("/")).sort()) { @@ -296,11 +305,14 @@ export async function probeAssetContentTypes( for (const [extension, file] of [...samples].sort(([left], [right]) => left.localeCompare(right))) { const expected = acceptedAssetContentTypes(extension); let observed: string; + let redirected = false; try { const response = await fetcher(new URL(file, base)); await response.body?.cancel().catch(() => undefined); - observed = - response.status === 200 + redirected = response.redirected || response.type === "opaqueredirect"; + observed = redirected + ? "redirected" + : response.status === 200 ? (response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "") : `HTTP ${response.status}`; } catch (error: unknown) { @@ -311,12 +323,39 @@ export async function probeAssetContentTypes( header: "content-type", expected, observed, - passed: expected.includes(observed), + ...(redirected + ? { reason: "the worker's install fetch refuses a redirected asset" } + : {}), + passed: !redirected && expected.includes(observed), }); } return results; } +/** + * 1105/06-02. Everything live mode of `verify:hosting-headers` asks the + * deployed host: the release surfaces (`probeLiveRelease`) and one built asset + * per cacheable type (`probeAssetContentTypes`). Live mode refuses loopback + * and plain http, so tests reach it only through this function and a fetcher + * double; a check dropped from here fails a test. + */ +export async function probeLiveHosting( + base: URL, + paths: Readonly>, + candidate: CandidateRelease, + distFiles: readonly string[], + transport: ProbeTransport = {}, +): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> { + const probed = await probeLiveRelease(base, paths, candidate, transport); + return { + responses: probed.responses, + results: [ + ...probed.results, + ...(await probeAssetContentTypes(base, distFiles, transport.fetcher)), + ], + }; +} + /** A build ships a worker script for these selections (06-03: REMOVE_REGISTRATION ships the self-unregistering one). */ export function shipsServiceWorker(selection: InstalledServiceWorkerSelection | null): boolean { return selection?.mode === "ACTIVE" || selection?.mode === "REMOVE_REGISTRATION"; diff --git a/scripts/verify-hosting-headers.ts b/scripts/verify-hosting-headers.ts index 8829b375..f77db9f2 100644 --- a/scripts/verify-hosting-headers.ts +++ b/scripts/verify-hosting-headers.ts @@ -7,8 +7,7 @@ import { checkPublicServiceWorkers, classifyLiveHostingBaseUrl, hostingVerdict, - probeAssetContentTypes, - probeLiveRelease, + probeLiveHosting, releaseIdentity, shipsServiceWorker, type HostingMode, @@ -111,13 +110,12 @@ if (liveTarget?.passed && !slotEmpty) { runtimeConfig: await readFile(path.join(distRoot, "config.json"), "utf8"), indexHtml: await readFile(path.join(distRoot, "index.html"), "utf8"), }; - const probed = await probeLiveRelease(liveTarget.url, paths, candidate, { + // 1103/06-03, 1105/06-02. Release surfaces and every precached asset type. + const probed = await probeLiveHosting(liveTarget.url, paths, candidate, distFiles, { alpnProtocols: strings(recordValue(cachePolicy.transport).alpnProtocols), }); responses = probed.responses; probeResults.push(...probed.results); - // 1103/06-03. The worker needs every precached asset kind typed exactly. - probeResults.push(...(await probeAssetContentTypes(liveTarget.url, distFiles))); } else if (liveTarget && !liveTarget.passed) { mode = "invalid-live"; probeResults.push({ diff --git a/tests/unit/hosting-probe.test.ts b/tests/unit/hosting-probe.test.ts index 9f109b45..0bae3ed7 100644 --- a/tests/unit/hosting-probe.test.ts +++ b/tests/unit/hosting-probe.test.ts @@ -11,6 +11,7 @@ import { classifyLiveHostingBaseUrl, hostingVerdict, probeAssetContentTypes, + probeLiveHosting, probeLiveRelease, servedEntryScript, } from "../../scripts/lib/hosting-probe.ts"; @@ -371,6 +372,30 @@ describe("hashed asset content types (1103/06-03)", () => { ]); }); + // 1105/06-02. The worker's install fetch uses `redirect: "error"`: a host + // that redirects a hashed asset, even to the same origin, fails every + // install although the final answer is a 200 with the right type. + it("fails an asset the host answers only after a redirect", async () => { + const results = await probeAssetContentTypes( + base, + ["assets/index-A1.js", "assets/index-C3.css"], + async (url) => { + const response = new Response("", { + status: url.pathname.endsWith(".js") ? 200 : 301, + headers: { "content-type": url.pathname.endsWith(".js") ? "text/javascript" : "text/html" }, + }); + Object.defineProperty(response, "url", { value: `${url.href}?moved=1` }); + Object.defineProperty(response, "redirected", { value: url.pathname.endsWith(".js") }); + return response; + }, + ); + expect(results.map((result) => [result.surface, result.observed, result.passed])).toEqual([ + ["hashedAsset.css", "HTTP 301", false], + ["hashedAsset.js", "redirected", false], + ]); + expect(results[1]).toMatchObject({ reason: expect.stringContaining("redirect") }); + }); + it("accepts for JavaScript what the hashedAsset surface declares", async () => { const policy = JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as { surfaces: { hashedAsset: { contentTypes: string[] } }; @@ -380,6 +405,48 @@ describe("hashed asset content types (1103/06-03)", () => { }); }); +// 1105/06-02. Live mode of verify-hosting-headers refuses loopback and plain +// http, so no test can run the script against a host. Its whole live branch is +// probeLiveHosting; dropping the asset type probe from it fails here. +describe("live hosting probe (1105/06-02)", () => { + const base = new URL("https://frontend.example.test/"); + const INDEX = ''; + const IDENTITY = { buildId: "gitea-42-1", releaseId: "r-42" }; + const PATHS = { index: "/", releaseManifest: "/release-manifest.json" }; + const CANDIDATE = { ...IDENTITY, runtimeConfig: "{}", indexHtml: INDEX }; + const DIST_FILES = ["index.html", "release-manifest.json", "assets/index-A1.js", "assets/index-C3.css"]; + + it("checks every built asset type besides the release surfaces", async () => { + const served: Record = { + "/": [INDEX, "text/html"], + "/release-manifest.json": [JSON.stringify(IDENTITY), "application/json"], + "/assets/index-A1.js": ["", "text/javascript"], + "/assets/index-C3.css": ["", "text/plain"], + }; + const { results } = await probeLiveHosting(base, PATHS, CANDIDATE, DIST_FILES, { + fetcher: async (url) => { + const entry = served[url.pathname]; + const response = new Response(entry?.[0] ?? "Not Found", { + status: entry ? 200 : 404, + headers: entry ? { "content-type": entry[1] } : {}, + }); + Object.defineProperty(response, "url", { value: url.href }); + return response; + }, + }); + + expect( + results.filter((result) => !result.passed).map((result) => `${result.surface} ${result.header}`), + ).toEqual(["hashedAsset.css content-type"]); + expect(results).toContainEqual( + expect.objectContaining({ surface: "hashedAsset.js", header: "content-type", passed: true }), + ); + expect(results).toContainEqual( + expect.objectContaining({ surface: "releaseManifest", header: "build-id", passed: true }), + ); + }); +}); + // 1101/13-01. FE-GATE-019 checks the promoted candidate it downloaded, not a // local rebuild, and an empty deployment slot proves nothing about the host. describe("verify-hosting-headers on a promoted release root (1101/13-01)", () => { -- 2.54.0 From 8b92f45f5eefe85c92a58a3cd65fc7b2bd6b30b1 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:12:19 +0900 Subject: [PATCH 15/74] =?UTF-8?q?fix(http):=20Fileserver=20=EC=97=85?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=20=EC=8B=A4=ED=8C=A8=EC=97=90=20Envelope?= =?UTF-8?q?=EC=9D=98=20traceId=EB=A5=BC=20=EC=8B=A3=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: readFailureEnvelope는 실패 Envelope의 meta.traceId를 함께 돌려주고, V3 실행기는 그 값을 AppFailure.traceId로 싣는다(1103/03-06). Fileserver client는 envelope.value만 넘겨 traceId를 버린다. 지원 담당이 업로드 실패를 서버 로그의 요청과 잇지 못한다. 같은 백엔드의 다른 쓰기 실패는 이을 수 있다. 고른 방법: envelopeFailure가 읽은 Envelope 전체를 받아 traceId가 있으면 createFailure의 traceId로 싣는다. V3와 같은 규칙이다. 없으면 키를 두지 않는다. 매뉴얼 7절 결과 읽기에 한 줄 적었다. 위험·한계: Envelope 실패에만 싣는다. 성공 Envelope을 읽지 못한 실패 (SCHEMA_MISMATCH 등, 202 REJECTED 포함)는 readSuccessEnvelope가 meta를 돌려주지 않아 traceId가 없다. V3도 같다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/integration/fileserver-upload.test.ts RED(이 커밋의 테스트 + 부모 src): Envelope failures 표 17행이 traceId "trace-1"이 없어 모두 실패한다. Refs: 1105/01-03 --- docs/manual/02-decision-tables.md | 1 + src/adapters/http/fileserver-upload.ts | 8 ++++++-- tests/integration/fileserver-upload.test.ts | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 77f5d1ad..3571f427 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -321,6 +321,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - 멱등성 응답(`IDEMPOTENT_*`, `IDEMPOTENCY_*`)과 V3 표에 있는 web 공통 응답은 V3 실행기와 같은 표(`backend-envelope.ts`, 4절)로 판정한다. 400 `IDEMPOTENCY_KEY_INVALID`·422 `IDEMPOTENT_REQUEST_MISMATCH`는 `NOT_APPLIED`, 409 `IDEMPOTENT_IN_FLIGHT`·503 `IDEMPOTENCY_UNAVAILABLE`·503 `IDEMPOTENCY_COMPLETION_UNKNOWN`·500 `IDEMPOTENCY_RECOVERY_REQUIRED`는 `MAYBE_APPLIED`다. - `APPLIED_CONFIRMED`: 서버는 만들었다고 답했지만 응답을 읽지 못했다. 다시 올리지 않는다. - `code`는 백엔드 code 그대로다(`FILE_TOO_LARGE`, `UNSUPPORTED_MEDIA_TYPE`, `MALWARE_DETECTED` …). 백엔드가 code를 주지 않는 거절은 client가 이름을 붙인다(`FILE_REJECTED`, `FILE_EMPTY`, `FILE_NOT_READABLE`). 화면 문구는 기능이 code로 고른다. +- 실패 Envelope의 `meta.traceId`는 실패의 `traceId`로 온다. V3 실행기와 같다. 지원 담당이 서버 로그에서 그 요청을 찾을 때 쓴다. - client는 스스로 다시 보내지 않는다. `retryable: true`이고 `retryAfterMs`가 있으면 그만큼 기다린 뒤 기능이 다시 부른다. 서버가 상한(`maxRetryAfterMs`, 기본 30초)보다 길게 기다리라고 하면 `retryable: false`다. - `MAYBE_APPLIED`는 언제나 `retryable: false`다. 백엔드가 Envelope에 `retryable: true`와 `Retry-After`를 붙여도(504 `TRANSFER_TIMEOUT`) 기능이 자동으로 다시 부르지 않는다. 아래 주의대로 먼저 확인한다. diff --git a/src/adapters/http/fileserver-upload.ts b/src/adapters/http/fileserver-upload.ts index 2ef5465c..736392ed 100644 --- a/src/adapters/http/fileserver-upload.ts +++ b/src/adapters/http/fileserver-upload.ts @@ -695,15 +695,16 @@ async function readAnswer( if (status < 400) return unreadable("ENVELOPE_MISMATCH", "STATUS_UNEXPECTED"); const envelope = readFailureEnvelope(json); if (!envelope.ok) return unreadable("ENVELOPE_MISMATCH", "ENVELOPE_INVALID"); - return envelopeFailure(status, envelope.value, response, settings); + return envelopeFailure(status, envelope, response, settings); } function envelopeFailure( status: number, - error: EnvelopeError, + envelope: Readonly<{ value: EnvelopeError; traceId?: string }>, response: Response, settings: Settings, ): Result { + const error = envelope.value; const effect = fileserverFailureEffect(status, error); const retryAfterMs = parseRetryAfterDelay( response.headers.get("retry-after"), @@ -731,6 +732,9 @@ function envelopeFailure( ...(reading.validationIssues === undefined ? {} : { validationIssues: reading.validationIssues }), + // 1105/01-03. The backend's `meta.traceId`, as the V3 executor carries it + // (1103/03-06), so support can find this upload in the server logs. + ...(envelope.traceId === undefined ? {} : { traceId: envelope.traceId }), }); // `retryable` in the Envelope is the server's decision for this answer and // can only narrow the client's. diff --git a/tests/integration/fileserver-upload.test.ts b/tests/integration/fileserver-upload.test.ts index c8f9aa86..41595697 100644 --- a/tests/integration/fileserver-upload.test.ts +++ b/tests/integration/fileserver-upload.test.ts @@ -397,11 +397,26 @@ describe("Fileserver multipart upload — Envelope failures", () => { effect, retryable: clientRetryable, operationId: "FILESERVER_UPLOAD", + // 1105/01-03. The Envelope's meta.traceId, as V3 carries it. + traceId: META.traceId, }, }); }, ); + it("carries no traceId when the failure Envelope has none", async () => { + const envelope = failureEnvelope("STORAGE_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true); + answer({ + status: 503, + body: { success: envelope.success, error: envelope.error, meta: { requestId: "req-1" } }, + }); + + const result = await client().client.upload(upload()); + + expect(result.ok).toBe(false); + expect(result.ok ? undefined : Object.hasOwn(result.error, "traceId")).toBe(false); + }); + it("409 IDEMPOTENT_IN_FLIGHT keeps the server's wait and asks for the same key", async () => { const captured = answer( { -- 2.54.0 From ddbda4d21eda971255c92c4b086d83f881a307ee Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:12:33 +0900 Subject: [PATCH 16/74] =?UTF-8?q?fix(feature-index):=20=EB=B0=94=EB=80=8C?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EC=9D=80=20=EA=B8=B0=EB=8A=A5=20=EC=9D=B8?= =?UTF-8?q?=EB=8D=B1=EC=8A=A4=EB=8A=94=20=EB=8B=A4=EC=8B=9C=20=EC=93=B0?= =?UTF-8?q?=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 문제: 빌드, dev 서버, 타입 검사, vitest가 모두 시작할 때 `scripts/generate-product-feature-index.ts`로 `src/.generated/*.ts`를 다시 쓴다. 생성기는 `writeFile`로 파일을 제자리에서 비우고 다시 썼다. 한 checkout에서 두 실행이 겹치면, 한쪽이 파일을 비운 순간 다른 쪽의 Vite나 tsc가 빈 파일이나 반쯤 쓴 파일을 읽을 수 있다(1105/12-04의 "한 checkout 두 실행" 중 공유 소스 파일 부분). 고른 방법: 내용이 같으면 쓰지 않는다. 다르면 같은 폴더의 임시 파일에 쓰고 rename으로 바꾼다. 읽는 쪽은 옛 파일이나 새 파일 하나만 본다. 같은 선택(같은 PRODUCT_APP_ID·VITE_PRODUCT_FEATURES)으로 도는 두 실행은 아예 쓰지 않는다. 버린 대안: 실행마다 `src/.generated`를 따로 두기. 앱 소스가 이 경로를 import하므로 경로를 바꾸면 Vite·tsc·ESLint 설정이 모두 따라 바뀐다. 잠금 파일: 겹친 실행을 직렬로 만들 뿐이고, 죽은 프로세스가 잠금을 남긴다. 위험·한계: 선택이 서로 다른 두 실행(예: 한쪽만 VITE_PRODUCT_FEATURES=none)은 여전히 서로의 인덱스를 바꾼다. 그건 실행이 아니라 checkout 상태가 다른 것이라 이 커밋 범위 밖이다. 임시 파일은 `.tmp`로 끝나 tsc·Vite·ESLint 대상이 아니다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/unit/product-feature-index-write.test.ts Refs: 1105/12-04 --- scripts/generate-product-feature-index.ts | 27 +++++- .../unit/product-feature-index-write.test.ts | 85 +++++++++++++++++++ 2 files changed, 109 insertions(+), 3 deletions(-) create mode 100644 tests/unit/product-feature-index-write.test.ts diff --git a/scripts/generate-product-feature-index.ts b/scripts/generate-product-feature-index.ts index 5740e956..26100243 100644 --- a/scripts/generate-product-feature-index.ts +++ b/scripts/generate-product-feature-index.ts @@ -1,5 +1,6 @@ -import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"; -import { dirname, relative, resolve } from "node:path"; +import { randomUUID } from "node:crypto"; +import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { basename, dirname, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { selectCompiledProductFeatures } from "../src/contracts/product-features.ts"; @@ -404,6 +405,26 @@ export async function generateAppIndexes( ); } +/** + * 1105/12-04. Every build, dev server, type check and test run renders these + * files first, so two runs in one checkout render them at the same time while + * the other run's Vite or tsc reads them. `writeFile` truncated the file in + * place, and a reader could see it empty or half written. An index that has + * not changed is left alone; a changed one replaces the old file with one + * rename, so a reader sees the old file or the new one, never a part. + */ +export async function writeIndexIfChanged(file: string, content: string): Promise { + if ((await readFile(file, "utf8").catch(() => null)) === content) return; + const temporary = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`); + try { + await writeFile(temporary, content, { encoding: "utf8", flag: "wx" }); + await rename(temporary, file); + } catch (error) { + await rm(temporary, { force: true }); + throw error; + } +} + async function main(): Promise { const scriptDir = dirname(fileURLToPath(import.meta.url)); // `--root=` points the same production command at another checkout (used by @@ -448,7 +469,7 @@ async function main(): Promise { await Promise.all( (["feature", "context", "app"] as const).map((key) => - writeFile(outputs[key], rendered[key], "utf8"), + writeIndexIfChanged(outputs[key], rendered[key]), ), ); } diff --git a/tests/unit/product-feature-index-write.test.ts b/tests/unit/product-feature-index-write.test.ts new file mode 100644 index 00000000..5439e35c --- /dev/null +++ b/tests/unit/product-feature-index-write.test.ts @@ -0,0 +1,85 @@ +import { spawnSync } from "node:child_process"; +import { cp, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +/** + * 1105/12-04. Every build, dev server, type check and test run renders + * src/.generated first, so two runs in one checkout render it while the other + * run's Vite or tsc reads it. The generator truncated each file in place on + * every run, and a reader could see it empty or half written. It now leaves an + * unchanged file alone and replaces a changed one with a rename. + * + * The generator runs against a copy (`--root=`), so the checkout's own index + * is never touched while other test files read it. + */ +const DECLARATIONS = ["src/apps", "src/contexts", "src/features"] as const; +const OUTPUTS = [ + "product-feature-index.ts", + "product-context-index.ts", + "product-app.ts", +] as const; +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function declarationCopy(): Promise { + const root = await mkdtemp(path.join(tmpdir(), "feature-index-write-")); + roots.push(root); + for (const input of DECLARATIONS) { + await cp(input, path.join(root, input), { recursive: true }); + } + return root; +} + +function generate(root: string): void { + const environment: NodeJS.ProcessEnv = { ...process.env }; + delete environment["PRODUCT_APP_ID"]; + delete environment["VITE_PRODUCT_FEATURES"]; + const run = spawnSync( + process.execPath, + ["scripts/generate-product-feature-index.ts", `--root=${root}`], + { encoding: "utf8", env: environment }, + ); + expect(run.status, run.stderr).toBe(0); +} + +async function identity(file: string): Promise { + const metadata = await stat(file, { bigint: true }); + return `${metadata.ino}:${metadata.mtimeNs}`; +} + +describe("product feature index writes (1105/12-04)", () => { + it("leaves an index that has not changed untouched", async () => { + const root = await declarationCopy(); + const files = OUTPUTS.map((name) => path.join(root, "src/.generated", name)); + generate(root); + const before = await Promise.all(files.map(identity)); + + generate(root); + + expect(await Promise.all(files.map(identity))).toEqual(before); + }); + + it("replaces a stale index with a new file instead of rewriting it in place", async () => { + const root = await declarationCopy(); + const file = path.join(root, "src/.generated/product-feature-index.ts"); + generate(root); + const rendered = await readFile(file, "utf8"); + await writeFile(file, "// stale\n", "utf8"); + const { ino: staleInode } = await stat(file, { bigint: true }); + + generate(root); + + expect(await readFile(file, "utf8")).toBe(rendered); + // A reader that opened the stale file keeps reading the stale file. + expect((await stat(file, { bigint: true })).ino).not.toBe(staleInode); + expect( + (await readdir(path.dirname(file))).filter((name) => name.endsWith(".tmp")), + ).toEqual([]); + }); +}); -- 2.54.0 From aaa782bab4591cba820b4a277689ba550a23ea35 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:13:53 +0900 Subject: [PATCH 17/74] =?UTF-8?q?test(service-worker):=20=EC=98=9B=20?= =?UTF-8?q?=ED=83=AD=EC=9D=B4=20=EC=A7=80=EC=9B=8C=EC=A7=84=20route?= =?UTF-8?q?=EB=A5=BC=20reload=20=EC=97=86=EC=9D=B4=20=EC=97=AC=EB=8A=94?= =?UTF-8?q?=EC=A7=80=20=EB=B3=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: update spec은 옛 탭 회복을 페이지의 `fetch(removedChunk)`로만 본다. 바이트가 오는지는 알지만, B가 제어하는 A 탭에서 지워진 route를 여는 실제 경로는 아무 spec도 지나지 않는다. 워커 제어 아래 preload는 11-09 허용(`preloadunverifiable:service-worker:`) 때문에 fixture가 하나도 판정하지 못한다(리뷰 06-R9: 158줄 모두 ALLOWED). 워커가 직전 캐시로 답하지 않게 바꾼 변이(06-R10)에서 화면 단언은 통과했다. chunk 복구가 페이지를 B로 reload해 같은 not-found 화면을 그렸기 때문이다. 고른 방법: 리뷰 06-03의 (a). update spec에 test 하나를 더한다. B가 제어하는 A 탭에서 client navigation(pushState + popstate)으로 일치하지 않는 경로를 연다. `CHANGED_ROUTE_SOURCE`가 not-found 페이지라 그 경로가 지워진 chunk를 import한다. 단언: - not-found heading이 보인다. - 같은 문서다. navigation 전에 심은 전역 표시가 남아 있고 entry script가 그대로다(reload 없음). - 그 문서가 chunk를 요청했다(Resource Timing 항목, 단언이 빈 경로를 보지 않게). - navigation 뒤 서버 요청에 그 chunk가 없다(워커가 답했다). - strict fixture가 허용 밖 실패 줄을 보지 않는다(기존 teardown 검사). 지워진 chunk를 찾는 코드는 기존 test와 같이 쓰도록 `removedRouteChunk`로 뺐다. Firefox는 같은 파일의 기존 격리(quarantine, 2027-03-31)를 그대로 따른다. Playwright Firefox는 워커가 페이지를 제어하지 못한다(06-R11 확인). 버린 대안: fixture가 워커 쪽 응답을 추적. Playwright 워커 network 이벤트는 Chromium 전용이다. 위험·한계: 테스트만 더했다. 지금 코드는 맞으므로 RED(부모 코드)에서도 통과한다. 결함은 변이로 보인다. 엔진마다 약 7초가 늘어난다(06-R9 기준). WebKit에서는 chunk가 modulepreload link로 요청되어 워커 경로가 Chromium과 같은지 확인하지 않았다. 허용 패턴 자체는 그대로다. 검증: desktop batch에서 확인. - corepack pnpm exec playwright test tests/e2e/service-worker-update.spec.ts --project=chromium --project=webkit - 변이(06-R10과 같음, `service-worker-lifecycle.ts`의 PREVIOUS_RELEASE_FALLBACK 분기가 `return null`): 새 test가 chromium에서 sameDocument false(또는 fixture 실패 줄)로 실패해야 한다. Refs: 1105/06-03 --- tests/e2e/service-worker-update.spec.ts | 82 +++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 6 deletions(-) diff --git a/tests/e2e/service-worker-update.spec.ts b/tests/e2e/service-worker-update.spec.ts index 585df28c..3562825f 100644 --- a/tests/e2e/service-worker-update.spec.ts +++ b/tests/e2e/service-worker-update.spec.ts @@ -237,12 +237,10 @@ test("announces update-waiting and reload-required through the host when build B } }); -test("serves A's removed chunk from the previous cache once B controls the page", async ({ - page, - browserName, -}) => { - test.skip(browserName === "firefox", NO_CONTROLLED_PAGES); - const { dist } = requireBuilds(); +/** The route chunk of A that B no longer has: `CHANGED_ROUTE_SOURCE`'s. */ +async function removedRouteChunk( + dist: ServiceWorkerBuilds["dist"], +): Promise { const routeChunks = Object.values( ( JSON.parse( @@ -255,6 +253,16 @@ test("serves A's removed chunk from the previous cache once B controls the page" .map((chunk) => `/${chunk}`) .find((chunk) => !inB.has(chunk)); if (!removedChunk) throw new Error("Build B kept every route chunk of A."); + return removedChunk; +} + +test("serves A's removed chunk from the previous cache once B controls the page", async ({ + page, + browserName, +}) => { + test.skip(browserName === "firefox", NO_CONTROLLED_PAGES); + const { dist } = requireBuilds(); + const removedChunk = await removedRouteChunk(dist); const server = await startBuildServer(dist); try { @@ -279,6 +287,68 @@ test("serves A's removed chunk from the previous cache once B controls the page" } }); +type SameDocumentProbe = typeof globalThis & { __swE2eSameDocument?: boolean }; + +// 1105/06-03. The old tab's real path, not only `fetch()`: A's page, now +// controlled by B's worker, opens the route whose chunk B removed +// (`CHANGED_ROUTE_SOURCE` is the not-found page, so any unmatched path +// imports it). Under the worker the preload fixture cannot judge preloads +// (the 11-09 allowance above), so this test asserts the outcome: the route +// renders in the same document, the chunk never reaches the server, and the +// strict fixture sees no failure outside the allowance. A worker that cannot +// answer the chunk makes the app's chunk recovery reload into B, which also +// renders the not-found page; only the same-document check tells them apart +// (review 06-R10). +test("opens A's removed route in the old tab without a reload once B controls it", async ({ + page, + browserName, +}) => { + test.skip(browserName === "firefox", NO_CONTROLLED_PAGES); + const { dist } = requireBuilds(); + const removedChunk = await removedRouteChunk(dist); + + const server = await startBuildServer(dist); + try { + const { controlled } = await updateFromAToB(page, server); + expect(controlled).toBe(true); + const entryScript = () => + page.evaluate( + () => + document.querySelector('script[type="module"][src]') + ?.src ?? null, + ); + const entryBefore = await entryScript(); + await page.evaluate(() => { + (globalThis as SameDocumentProbe).__swE2eSameDocument = true; + }); + const servedBefore = server.served.length; + + // A client-side navigation, as a link inside the app makes. + await page.evaluate(() => { + history.pushState({}, "", "/sw-e2e-removed-route"); + dispatchEvent(new PopStateEvent("popstate")); + }); + + await expect( + page.getByRole("heading", { name: /페이지를 찾을 수 없습니다|Page not found/u }), + ).toBeVisible({ timeout: 30_000 }); + const after = await page.evaluate((chunk) => ({ + sameDocument: + (globalThis as SameDocumentProbe).__swE2eSameDocument === true, + chunkRequested: + performance.getEntriesByName(new URL(chunk, location.origin).href) + .length > 0, + }), removedChunk); + expect(after).toEqual({ sameDocument: true, chunkRequested: true }); + expect(await entryScript()).toBe(entryBefore); + expect( + server.served.slice(servedBefore).map((response) => response.path), + ).not.toContain(removedChunk); + } finally { + await server.close(); + } +}); + // `beforeAll` already ran `scripts/build-frontend.ts` unmodified (default // `bundle` config loader); this pins that both builds emitted the worker. test("builds the ACTIVE worker with the repo's unmodified build script", async () => { -- 2.54.0 From f2f7dc4cdb4690dfbf3b16363ac68b83f313771f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:13:54 +0900 Subject: [PATCH 18/74] =?UTF-8?q?test(http):=20Fileserver=20client?= =?UTF-8?q?=EC=9D=98=205xx=C2=B7deadline=C2=B7=EC=9D=BD=EA=B8=B0=20?= =?UTF-8?q?=EC=A0=84=20=ED=81=AC=EA=B8=B0=20=EA=B1=B0=EC=A0=88=20=EA=B7=9C?= =?UTF-8?q?=EC=B9=99=EC=9D=84=20=EA=B3=A0=EC=A0=95=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: Fileserver client 규칙 셋을 바꿔도 통합 테스트 48건이 모두 통과했다(리뷰 변이 FS4·FS5·FS8 생존). - FS4: 5xx ATOMIC_PUBLISH_UNSUPPORTED를 NOT_APPLIED에서 빼도 표에 그 행이 없다. - FS5: deadline에서 바이트 비례 몫을 없애도 시간 초과 테스트는 작은 고정값만 본다. 큰 파일이 느린 망에서 기본 30초에 끊기는 회귀를 못 잡는다. - FS8: 선언 크기가 maxFileBytes보다 큰 파일을 읽기 전에 거절하지 않아도, 읽는 중 상한 검사가 같은 code를 내서 통과한다. 그 사이 선언 크기만큼 버퍼를 먼저 잡는다. 고른 방법(리뷰 01-04 최소 개선 방향): - Envelope 실패 표에 503 ATOMIC_PUBLISH_UNSUPPORTED → NOT_APPLIED 행을 더한다. 504 TRANSFER_TIMEOUT 행은 01-02 커밋이 MAYBE_APPLIED로 더했다. 두 방향(빼기·되넣기)이 모두 실패를 만든다. - 가짜 setTimeout과 주입한 fetcher·monotonicNow로, 기본 1초에 바이트당 1초를 더한 deadline 안에서 1.5초 뒤 온 답이 성공하는지, 자격 증명 owner가 받은 deadline이 1,000 + 바이트 수 × 1,000 ms인지 본다. 실제 시간에 기대지 않아 부하에 흔들리지 않는다. - 선언 크기 초과에서 stream()이 한 번도 불리지 않음을 본다. 버린 대안: MSW에 지연을 넣고 실제 시간으로 deadline을 재는 방법. 부하가 큰 desktop에서 흔들릴 수 있고, 시간 여유를 키우면 테스트가 느려진다. 위험·한계: 테스트만 더했다. 지금 코드는 의도대로라서 부모 src에서도 통과한다. 검출력은 변이로만 확인할 수 있다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/integration/fileserver-upload.test.ts RED 없음(테스트 추가). 변이 셋이 각각 실패를 만들어야 한다: FS4' NOT_APPLIED_5XX_CODES에서 "ATOMIC_PUBLISH_UNSUPPORTED" 줄 삭제, FS5 timeoutMs 식의 Math.ceil(...) 몫을 0으로, FS8 readMultipartBody의 declared > maxFileBytes 거절 블록 삭제. Refs: 1105/01-04 --- tests/integration/fileserver-upload.test.ts | 63 +++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/tests/integration/fileserver-upload.test.ts b/tests/integration/fileserver-upload.test.ts index 41595697..c4981fa0 100644 --- a/tests/integration/fileserver-upload.test.ts +++ b/tests/integration/fileserver-upload.test.ts @@ -372,6 +372,8 @@ describe("Fileserver multipart upload — Envelope failures", () => { { status: 500, code: "AMBIGUOUS_COMPLETION", category: "DATA_INTEGRITY", retryable: false, details: { ambiguous: true, reconciliationRequired: true }, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, { status: 500, code: "INTERNAL_ERROR", category: "INTERNAL", retryable: false, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, { status: 503, code: "STORAGE_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: true }, + // 1105/01-04. The atomic move itself was refused: nothing was published. + { status: 503, code: "ATOMIC_PUBLISH_UNSUPPORTED", category: "PERMANENT_DEPENDENCY", retryable: false, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: false }, { status: 503, code: "STORAGE_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, details: { ambiguous: true }, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, // 1105/01-02. As the V3 table reads it: only an unknown result keeps the key. { status: 503, code: "IDEMPOTENCY_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false }, @@ -575,6 +577,53 @@ describe("Fileserver multipart upload — unknown results", () => { }); }); + it("adds the file's transfer allowance to the base deadline", async () => { + // 1105/01-04. At one byte per second the file earns one second per byte + // on top of the one-second base, so an answer after 1.5 s still counts. + // Without the allowance a large file on a slow uplink ends at the base. + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + let respond: (response: Response) => void = () => {}; + let sent: () => void = () => {}; + const requestSent = new Promise((resolve) => { + sent = resolve; + }); + const fetcher = vi.fn( + () => + new Promise((resolve) => { + respond = resolve; + sent(); + }), + ); + const { client: uploader, attachCredentials } = client({ + fetcher: fetcher as unknown as typeof fetch, + timeoutMs: 1_000, + minTransferBytesPerSecond: 1, + monotonicNow: () => 0, + }); + + const pending = uploader.upload(upload()); + await requestSent; + await vi.advanceTimersByTimeAsync(1_500); + respond( + new Response(JSON.stringify(successEnvelope(uploaded("READY"))), { + status: 201, + headers: { "content-type": "application/json" }, + }), + ); + + expect(await pending).toEqual({ ok: true, value: uploaded("READY") }); + expect(attachCredentials).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + deadlineAtMonotonicMs: 1_000 + FILE_BYTES.byteLength * 1_000, + }), + ); + } finally { + vi.useRealTimers(); + } + }); + it("a caller abort after sending may have applied; before sending it did not", async () => { const controller = new AbortController(); let arrived: () => void = () => {}; @@ -641,6 +690,20 @@ describe("Fileserver multipart upload — refused before sending", () => { }); }); + it("refuses a declared size above maxFileBytes without reading a byte", async () => { + // 1105/01-04. Before the body buffer is sized from the declared length. + const stream = vi.fn(async function* () { + yield { ok: true as const, value: new Uint8Array(3) }; + }); + const source: FileByteSource = { byteLength: 2_000, stream }; + + expect(await unsent({}, { source })).toMatchObject({ + ok: false, + error: { kind: "VALIDATION_REJECTED", code: "FILE_TOO_LARGE", effect: "NOT_STARTED" }, + }); + expect(stream).not.toHaveBeenCalled(); + }); + it("a source that fails mid-stream is not readable", async () => { const source: FileByteSource = { byteLength: 6, -- 2.54.0 From f738348d9dece1e8194a00b4b3bfbcaf85c0afe8 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:14:54 +0900 Subject: [PATCH 19/74] =?UTF-8?q?fix(bootstrap):=20=EC=8B=A4=ED=8C=A8?= =?UTF-8?q?=ED=95=9C=20scope=20closer=EB=A5=BC=20label=EA=B3=BC=20?= =?UTF-8?q?=ED=95=A8=EA=BB=98=20=EC=A7=84=EB=8B=A8=EC=97=90=20=EB=82=A8?= =?UTF-8?q?=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 1103/02-01이 제품 closer를 scope reset에 넣었다. template participant 하나가 제품 closer를 차례로 부르고, 하나라도 던지면 이유 없는 Error를 던진다. scope runtime은 그 실패를 `failed = true`로만 받아 scope를 `FAILED`에 둔다. 그동안 모든 서버 요청이 `SCOPE_FENCED`로 막히는데 진단 기록은 0건이다(리뷰 실험 E-3). 계약의 `ProductScopeParticipant.label`을 읽는 코드도 없다. 개발자는 "로그아웃 뒤 앱이 요청을 안 보낸다"만 보고 원인 closer를 찾으려면 closer를 하나씩 지워 봐야 한다. 고른 방법(리뷰 대안 (다)): - scope runtime이 reset의 실패 단계마다 `cache.operation.failed`를 하나 남긴다. `operation: "SCOPE_RESET"`, `reason`은 `PARTICIPANT_FAILED`· `CACHE_RESET_FAILED`·`GENERATION_ACTIVATION_FAILED`(+ 목록 함수가 던질 때 `PARTICIPANTS_UNREADABLE`), `error_kind`, participant 실패면 `scope_participant: