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
@@ -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 },
});
});