fix(realtime)!: 던지는 poll execute를 서버 장애가 아니라 PROTOCOL_MISMATCH로 끝낸다

문제: 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
This commit is contained in:
DongHyeonka
2026-11-05 22:03:56 +09:00
parent bde7fa4609
commit 05330e30a8
3 changed files with 92 additions and 43 deletions
@@ -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 |
@@ -101,6 +101,12 @@ export type BoundedPollCoordinatorDependencies<Value> = 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<Value>(
}
attempts += 1;
let result: BoundedPollAttemptResult<Value>;
let result: BoundedPollAttemptResult<Value> | null;
const attemptOutcome = await awaitWithinLease(
() =>
trackWork(
@@ -320,12 +326,14 @@ export function createBoundedPollCoordinator<Value>(
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<Value>(
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
const parsedResult = parseAttemptResult<Value>(result);
const parsedResult =
result === null ? null : parseAttemptResult<Value>(result);
if (!parsedResult) {
return pollFailure("PROTOCOL_MISMATCH");
}
@@ -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<BoundedPollAttemptResult<string>>,
);
const coordinator = createBoundedPollCoordinator<string>({
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<BoundedPollAttemptResult<string>> => {
throw new TypeError("Failed to fetch");
});
const caller = new AbortController();
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: new MutableEnvironment(),
clock,
random: () => 0.5,
execute,
observe: (observation) => observations.push(observation),
execute: ({ signal }) =>
new Promise<BoundedPollAttemptResult<string>>((_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 },
});
});