문제: 1196b86은 stream coordinator의 마감 실패만 13.1 어휘로 바꿨다.
live↔Poll handoff coordinator는 아직 네 마감을 모두 `IDLE_TIMEOUT`으로
보고한다. 설계 13.1에서 `IDLE_TIMEOUT`은 전송 idle(heartbeat/byte
deadline → close + bounded reconnect)이다. 그래서 관측에서 "서버가
조용함"과 "우리 effect·checkpoint가 멈춤"을 kind로 나눌 수 없다.
- switchToPoll quiescence 마감: IDLE_TIMEOUT/RECOVER
- activateProbe quiescence 마감: IDLE_TIMEOUT/RECOVER
- checkpoint 마감: IDLE_TIMEOUT/RECOVER
- close drain 마감: IDLE_TIMEOUT/CLOSE
고른 방법: 결정 (a)를 1196b86과 같은 방식으로 적용한다. kind만 바꾸고
operation, retryable(전과 같이 true), fail-close 동작은 그대로 둔다.
- quiescence 마감 → APPLY_FAILED/RECOVER. 기다리는 것은 이전 writer의
apply effect tail이다. stream coordinator의 effect 마감과 같은 kind다.
APPLY_FAILED의 기본 retryable은 false라 true를 명시했다. 두 곳의 같은
분기를 `quiescenceFailure` 하나로 합쳤다.
- checkpoint 마감 → PROVIDER_UNAVAILABLE/RECOVER. checkpoint authority가
throw할 때와 같은 kind다.
- close drain 마감 → PROVIDER_UNAVAILABLE/CLOSE. stream·reconnect
coordinator의 drain 상한과 같다. 이전부터 timer 실패도 같은 값이라 두
분기를 하나로 합쳤다.
- 13.1 표: IDLE_TIMEOUT 행에서 handoff를 빼고 "내부 task 마감에는 쓰지
않는다"로 적었다. APPLY_FAILED·PROVIDER_UNAVAILABLE 행에 handoff 마감과
retryable 값, 뒤 동작을 적었다. 남은 IDLE_TIMEOUT 생성 지점은 SSE·WS의
RECEIVE·SUBSCRIBE(전송 idle)뿐이다.
버린 대안:
- retryable도 kind 기본값으로(quiescence가 false가 됨): 결정 범위는
어휘다. 재시도 판단 변경은 따로 정한다.
- close 마감에 CLOSED: 1196b86과 같은 이유로 버렸다. 아직 writer가
settle하지 않았는데 "닫힘"으로 읽힌다.
위험·한계:
- 배럴로 공개된 handoff coordinator 결과의 kind가 바뀐다. IDLE_TIMEOUT을
보던 조합 코드는 APPLY_FAILED·PROVIDER_UNAVAILABLE을 봐야 한다. repo
안에 소비자는 없다(AVAILABLE_NOT_COMPOSED).
- handoff에는 observer가 없어 관측 reason은 바뀌는 것이 없다.
- 같은 APPLY_FAILED라도 stream coordinator는 retryable:false, handoff는
true다. 13.1 표에 둘 다 적었다.
- realtime 레시피 gzip 40,902 → 40,878 B(한도 42,200).
검증:
- RED: 기대값을 먼저 바꾸고 activateProbe quiescence 마감 테스트를 새로
넣은 뒤 live-poll-handoff-coordinator.test.ts 실행 → 7 failed | 9
passed. 7건 모두 received kind IDLE_TIMEOUT(close 4건, switchToPoll
quiescence, activateProbe quiescence, checkpoint).
- GREEN: `node scripts/run-vitest.ts run tests/unit/realtime` 14 files,
231 passed.
- tsc app·test·recipes 통과, 바꾼 두 파일 eslint 통과,
`check-optional-recipes`(source) PASS, `verify-documentation-readiness`
PASS_SCOPED, `check-adapter-inventory` PASS.
- 미실행: `check:architecture`(pnpm 필요).
Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.1 04-02, 14.4
문제: stream coordinator는 effect 마감 초과를 IDLE_TIMEOUT/APPLY로,
recovery 마감 초과를 IDLE_TIMEOUT/RECOVER로, close drain 초과를
IDLE_TIMEOUT/CLOSE로 보고한다. 설계 13.1에서 IDLE_TIMEOUT은 전송
idle(heartbeat/byte deadline -> close + bounded reconnect)이다. reconnect
관측(RUN_ENDED failureKind)에는 operation이 없어서 운영에서 "서버가
조용해짐"과 "우리 effect가 멈춤"을 failureKind로 나눌 수 없다.
5b3f5b0은 13.1에 두 뜻을 적기만 했다(리뷰의 (b)).
고른 방법: 리뷰의 (a). kind만 바꾸고 retryable:false, DRAINING 유지,
resume token 폐기는 그대로 둔다.
- effect 마감: APPLY_FAILED/APPLY. 13.1의 "feature effect 실패"이고,
WebSocket 연결도 자기 apply 마감을 APPLY_FAILED로 보고한다.
- recovery 마감: PROVIDER_UNAVAILABLE/RECOVER. recovery source가 제때
답하지 않은 것이다. recovery가 throw한 경우와 같은 kind다.
- close drain 마감: PROVIDER_UNAVAILABLE/CLOSE. reconnect coordinator가
drain 상한 초과를 PROVIDER_UNAVAILABLE로 보고하는 것과 맞춘다.
- 관측 reason도 같은 kind로 바꾼다.
- 13.1 표는 IDLE_TIMEOUT 행에서 stream coordinator 설명을 빼고,
APPLY_FAILED·PROVIDER_UNAVAILABLE 행에 마감 경우를 적는다.
VD-28의 같은 설명도 고친다.
이 템플릿으로 운영 중인 제품이 아직 없어서 관측 값을 바꾸는 비용이
지금 가장 작다.
버린 대안: (b) 문서만 고친다. 5b3f5b0이 한 것이고, 관측에서는 여전히
구분되지 않는다. close 마감에 CLOSED를 쓰는 것도 버렸다. 아직
DRAINING인데 "닫힘"으로 읽힌다.
위험·한계:
- 공개로 관측되는 값이 바뀐다. stream coordinator 결과의 kind와
RealtimeObservation.reason에서 IDLE_TIMEOUT을 보던 조합 코드는
APPLY_FAILED/PROVIDER_UNAVAILABLE을 봐야 한다. repo 안에 그런
소비자는 없다.
- live-poll handoff coordinator의 quiescence·checkpoint·close 마감은
여전히 IDLE_TIMEOUT이다. 결정 범위(stream coordinator)를 지켰다.
13.1 IDLE_TIMEOUT 행에 handoff 마감만 남겨 적었다.
- realtime 레시피 번들 gzip이 40,897 B에서 40,902 B로 늘어 예산
40,900 B를 2 B 넘는다. "PROVIDER_UNAVAILABLE"이 "IDLE_TIMEOUT"보다
8자 길어 3곳에서 원본이 24 B 늘었다. 예산은 올리지 않았다.
check-optional-recipes가 REFERENCE_RUNTIME_BUNDLE_BUDGET_EXCEEDED로
실패한다.
검증:
- RED: 기대값을 먼저 바꾸고 stream-coordinator.test.ts 실행 ->
7 failed | 31 passed. 예: expected kind APPLY_FAILED, received
IDLE_TIMEOUT.
- GREEN: tests/unit/realtime 14 files, 230 passed.
- tsc (tsconfig.app.json, tsconfig.test.json) 통과. 바꾼 두 파일 eslint
통과. verify-documentation-readiness PASS_SCOPED.
- check-optional-recipes: realtime 40902 > 40900 실패(위험 참고).
Refs: docs/reviews/2026-11-01-maturity-review/04-adapters-realtime.md 04-02
문제: reconnect coordinator, live/poll handoff, SSE onOpen·onEvent,
WS onSubscribed·onEvent는 받은 RealtimeResult를 2단계로 동결된
객체만 받는다. 타입은 Readonly일 뿐이라 같은 모양의 평범한 객체도
컴파일된다. 그런데 동결된 결과를 만드는 realtimeSuccess /
realtimeFailure는 result.ts에만 있고 배럴에 없다. 조합 코드는 배럴만
import할 수 있으므로 결과를 손으로 만들게 되고, 그러면 첫 실패나 첫
종료에서 PROTOCOL_MISMATCH·MAPPING_CONTRACT_VIOLATION으로 재시도
없이 끝난다. 이 규칙은 주석에도 없었고, reconnect 경계의 동결 검사
3곳을 지워도(MU4) 테스트가 모두 통과했다.
고른 방법: 리뷰 6.2절의 (b). 배럴 src/adapters/realtime/index.ts에서
두 함수를 export하고(추가만, 기존 시그니처 변화 없음), 엄격한 경계의
타입 주석(RealtimeReconnectOutcome, RealtimeReconnectSession,
confirmTransportBarrier, handoff apply·establishAuthoritativeCheckpoint,
SSE onOpen·onEvent, WS onEvent·onSubscribed)과 생성 함수 주석에 규칙을
적었다. 동결 규칙 자체와 DEFAULT_RETRYABLE 기본값은 그대로다.
버린 대안:
- (c) 엄격한 경계도 stream coordinator처럼 한 번 복사하기. 규칙이
하나가 되지만 "검증한 실패 객체를 그대로 돌려준다"(toBe) 계약을
깬다.
- (d) 생성 함수를 application port(shared.ts)에 두기. feature 코드도
쓸 수 있게 되지만 application 계층에 런타임 헬퍼가 는다. handoff
apply를 feature가 구현한다고 정해지면 그때 옮긴다.
- 런타임 오류 이름을 따로 두기(예: RESULT_NOT_FROZEN). failure kind
어휘가 바뀌는 계약 변경이라 이번 범위 밖이다.
위험·한계:
- 동결하지 않은 결과는 여전히 컴파일된다. 타입으로 막으려면 brand가
필요하고, 그건 공개 타입을 깨는 변경이다. 주석과 테스트로만 알린다.
- realtime 레시피 번들 40,863 -> 40,879 / 40,900 gzip B(+16 B, 여유
21 B). 예산은 그대로다.
검증:
- RED: 새 테스트 "retries a failure built with the barrel's
realtimeFailure"가 수정 전 `TypeError: realtimeFailure is not a
function`으로 실패(1 failed | 43 passed).
- 새 테스트 4건(시도의 평범한 실패, 동결된 실패 안의 평범한 error,
classifyClosed의 평범한 성공 -> PROTOCOL_MISMATCH, 재시도 없음)과
handoff apply의 평범한 성공 -> MAPPING_CONTRACT_VIOLATION 1건.
- MU4(reconnect 동결 검사 3곳 제거)를 다시 넣으면 새 테스트 3건이
실패한다(수정 전에는 생존).
- GREEN: `node scripts/run-vitest.ts run tests/unit/realtime/` ->
14파일 230건 통과.
- `npx tsc --project tsconfig.app.json --noEmit`,
`npx tsc --project tsconfig.test.json --noEmit` -> 오류 0.
- `npx eslint <바꾼 파일 8개> --max-warnings=0` -> 통과.
- `node scripts/check-realtime-boundaries.ts` -> PASS,
`node scripts/check-adapter-inventory.ts` -> PASS,
`node scripts/check-optional-recipes.ts` -> PASS(realtime 40879/40900).
Refs: docs/reviews/2026-11-01-maturity-review/04-adapters-realtime.md 04-01, 6.2절
문제: SSE 어댑터는 fetch 거절과 열린 스트림의 reader 거절을 모두
OFFLINE(retryable)으로 보고한다. reconnect coordinator는 transport가
OFFLINE을 보고하면 requireOnline()으로 "새 online 이벤트"를 요구했다.
서버만 내려가거나 프록시가 연결을 끊으면 브라우저 navigator.onLine은
true 그대로라 online 이벤트가 오지 않는다. run이 재시도도 종료도 없이
RUNNING으로 멈췄다(리뷰 재현: 20분 동안 fetch 1회, 결과 없음).
고른 방법: 수정안 b. coordinator의 attempt 실패 경로와 classifyClosed
경로에서 transport OFFLINE 뒤의 requireOnline() 두 줄을 지운다. 이제
transport OFFLINE은 다른 retryable 실패처럼 backoff로 재시도하고, 시도
상한이나 elapsed 상한에 닿으면 마지막 실패로 끝난다. online 대기는
환경 신호(observeOnline(false))가 offline을 알렸을 때만 한다.
- 리뷰의 MU1은 "&& !online" 조건을 붙이는 방식이었다. 두 지점에
닿을 때 online은 항상 true다. 그 사이에 offline이 오면 wentOffline
분기가 먼저 받고, observeOnline(false)가 이미 requireOnline()을
부른다. 그래서 조건을 붙이는 것과 줄을 지우는 것은 동작이 같고,
지우는 쪽이 짧다.
- 규칙은 RealtimeReconnectEnvironment 주석과 설계 5.3절에 적었다.
버린 대안: 수정안 c(SSE가 네트워크 거절을 PROVIDER_UNAVAILABLE로
보고). SSE 한 곳의 어휘만 바뀌고 coordinator의 함정은 남는다. 조합
코드가 classifyClosed에서 OFFLINE을 돌려주거나 다른 transport가
OFFLINE을 보고하면 같은 방식으로 멈춘다. OFFLINE을 보고 화면에
"오프라인"을 띄우는 소비자의 분류도 바뀐다. b는 모든 transport가
지나는 한 곳에서 고친다. (d) online 대기에 상한 시간을 두는 방식은
상수와 상태가 늘어서 버렸다.
위험·한계:
- 환경 offline 이벤트보다 transport 실패를 먼저 보면, 첫 backoff
타이머가 잡힌다. offline 이벤트가 오면 그 sleep을 끊고 online을
기다린다(새 테스트 "after"가 고정). offline 이벤트가 타이머보다
늦게 오면 헛시도가 한두 번 생길 수 있다. 시도 상한 안이다.
- lie-fi(브라우저는 online, 실제 네트워크 없음)에서는 이제 상한까지
재시도한 뒤 OFFLINE으로 끝난다. 설계 5.3의 "budget 소진 뒤
fallback"과 같다.
- 0929/04-02(열린 SSE 세션 bridge 부재)는 그대로다. 테스트 안의
sseAttempt는 설계 6.3이 조합 코드에 맡긴 최소 bridge다.
- 설계 문서의 reconnect-coordinator.ts 줄 번호를 새 위치로 고쳤다.
- 레시피 번들(realtime): 40,886 -> 40,863 / 40,900 gzip B. 예산은
바꾸지 않았다.
검증:
- RED(수정 전): `node scripts/run-vitest.ts run
tests/unit/realtime/realtime-reconnect-coordinator.test.ts`
-> X1·X2 2건 실패 "expected "vi.fn()" to be called 3 times, but
got 1 times". 실제 offline 대기 테스트 2건(before/after)은 통과.
- GREEN: `node scripts/run-vitest.ts run tests/unit/realtime/`
-> 14파일 225건 통과(기존 221 + 새 4).
- 변이: 수정 위에 MU2(SSE 거절 -> PROVIDER_UNAVAILABLE)를 넣으면 X1·X2
2건 실패.
- `node scripts/run-vitest.ts run tests/unit` -> 165파일 2357건 통과.
- `npx tsc --project tsconfig.app.json --noEmit`,
`npx tsc --project tsconfig.test.json --noEmit` -> 오류 0.
- `npx eslint <바꾼 ts 2개> --max-warnings=0` -> 통과.
- `node scripts/check-realtime-boundaries.ts` -> PASS.
- `node scripts/verify-documentation-readiness.ts` -> PASS_SCOPED.
- `node scripts/check-optional-recipes.ts` -> PASS, realtime 40863/40900.
- 미실행: check:architecture(pnpm을 띄운다). depcruise 직접 실행은
0 modules로 끝나 의미가 없다. import는 바꾸지 않았다.
Refs: docs/reviews/2026-11-01-maturity-review/04-adapters-realtime.md 2절, 6.1절
VD-01 decision 3 hands unused diagnostics to tsc and turns off ESLint's
no-unused-vars for TS files, but tsconfig.base.json never enabled the
tsc check (D-19). The flag found 46 unused imports, types and helpers
across 22 files; none of them were read, so removing them changes no
behaviour.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Design 14.1 connect and bounded_poll events had no place to come from, and
an exhausted budget looked the same as a terminal failure. Both coordinators
now emit a closed observation vocabulary through a best-effort sink.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The IDLE_TIMEOUT path had no test, so flipping it to retryable:false (M7)
passed. Two ManualClock tests now fail on that mutation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The browser picks the read size, so a chunk over 256KB ended the stream as
EVENT_TOO_LARGE even when every event was normal size.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A type added by a newer backend ended the connection as MALFORMED_EVENT and
left the stream CURRENT. It is now PROTOCOL_MISMATCH/REGISTRY, and any decode
failure after the stream lookup marks that stream UNKNOWN (design 13.1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A 429/503 Retry-After reached only onRetryHint, so passing the read result
to the reconnect coordinator retried before the server allowed.
readSseForReconnect returns the hint as serverNotBeforeMs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A long healthy connection that ended offline or with a throwing waitClosed
kept a spent elapsed budget and stopped with zero retries. Offline waits no
longer spend the budget, and WebSocket HEARTBEAT_ACK is now observable so a
quiet stream can earn a fresh budget.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The parser now finds CR/LF with Uint8Array.indexOf before decoding, so a
line's UTF-8 byte count comes from byte offsets instead of re-encoding the
text. Each complete line is decoded once by a streaming fatal TextDecoder;
a line that continues into the next read is stream-decoded, and the bytes
of a character split across reads count once it completes, as before.
Behavior kept (the push() input was already Uint8Array; no seam change in
fetch-sse-connection.ts, public API unchanged):
- CR / LF / CRLF, CR and LF split across reads, multi-line data
- one leading BOM stripped (now done by the parser, decoder uses
ignoreBOM: true, so a BOM at a later line start stays text)
- line / event / incomplete-buffer byte limits, same failure point
- drain() and the per-call item cap; kept bytes are copied
- a pending CR or the item cap waits while only part of a character is
left, as the text-based parser did
- error codes (MALFORMED_EVENT / EVENT_TOO_LARGE / QUEUE_OVERFLOW / CLOSED)
Differences only on invalid UTF-8: the old parser decoded a whole chunk
first, so malformed bytes won over another error later in that chunk and
malformed bytes past the item cap failed in push(). Now the first
problem in stream order wins and those bytes fail in drain(). Both
still fail closed.
Fixed: Node's streaming TextDecoder (ignoreBOM: false) drops a U+FEFF
right after the stream's first character when that character is split
across reads, e.g. [EF] [BB BF EF BB BF] decoded to "" instead of
"". The old parser inherited that; the new one keeps the text.
Tests: existing parser and connection tests unchanged and passing. Added
a split-BOM case and a differential test against the round-2 parser
(tests/unit/realtime/sse-parser-reference.ts) over 2x1,500 seeded random
ASCII / multibyte streams with random read splits, random small limits,
truncated streams and skipped drains. 300,000 seeds also matched in a
manual run.
Benchmark (manual, not committed; Node v24.14.0, one push of one chunk,
best of 150 runs, host load average ~11-14 so absolute ms are noisy):
| input (one chunk) | original e59994a | round 2 | new | new vs original | new vs round 2 |
|--------------------------------|------------------|---------|---------|-----------------|----------------|
| ASCII, 249 KB, 209 events | 103.72 ms | 0.48 ms | 0.30 ms | 348x | 1.6x |
| Korean/emoji, 249 KB, 209 ev. | 23.30 ms | 0.85 ms | 0.44 ms | 53x | 1.9x |
| ASCII, 234 KB, 4 x 60 KB lines | 176.45 ms | 0.61 ms | 0.34 ms | 513x | 1.8x |
| Korean/emoji, 234 KB, 4 x 60KB | 25.28 ms | 1.10 ms | 0.65 ms | 39x | 1.7x |
Across five runs, multibyte new vs original stayed between 19x and 70x
(target: 10x or more).
Realtime bundle: 39903 / 40000 gzip bytes (baseline 39685, +218).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- bounded-poll: an executor that throws becomes OFFLINE retryable:true,
but OFFLINE is not a poll-retryable kind, so the run ended through
pollFailure(kind) with retryable:false. OFFLINE now keeps its
retryable flag on that exit, like the lifecycle OFFLINE exits.
- sse-parser: TextDecoder(ignoreBOM: false) already strips the one
leading BOM the stream grammar allows; the parser stripped a second one.
The manual strip is removed.
- event-codec: the raw event was UTF-8 encoded twice; now once.
- fetch-sse-connection: one module TextEncoder instead of a new one per
event and per cursor check.
- websocket-protocol: the R-05 admission JSDoc sat on utf8ByteLength; it
now documents exceedsUtf8ByteLimit, and utf8ByteLength reuses one
encoder.
RED: a throwing executor returned retryable:false; a stream starting with
two BOMs before "data: x" produced an event. Both pass now; the
encode/JSDoc items are covered by the existing codec, SSE and WS suites.
Gates: architecture, types app/test, lint, adapter-inventory, test:unit,
test:component pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bufferProbeValue compared the ceilings against acceptedEvents /
acceptedBytes, counters that only grew. Activation drains the buffer
while the probe keeps receiving, so once a probe had accepted
maxProbeBufferedEvents values in total, the next write during activation
failed closed and left the coordinator CLOSED even with an almost empty
buffer. The check now uses buffer.length and bufferedBytes, which the
drain already decrements; the two cumulative counters are removed.
RED: new test (limit 2, write two, activate, write a third while the
first drains) got QUEUE_OVERFLOW before the fix; it now buffers, and a
fourth write that really exceeds the current buffer still fails closed.
Gates: architecture, types app/test, lint, adapter-inventory, test:unit,
test:component pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Realtime kept three DataSnapshot readers and about ten hand-written
abort/timeout races, and two parsers had drifted copies in other adapters.
Snapshot: reconnect-coordinator and bounded-poll now use result.ts
captureRealtimeDataSnapshot (+ `source`, variadic hasExactSnapshotKeys).
Kept the result.ts rules, the stricter ones: Object.hasOwn instead of
`"value" in` (prototype pollution), enumerable fields only, keys read from
one descriptor snapshot, frozen computed at snapshot time instead of a
later Object.isFrozen. Poll therefore now rejects non-enumerable fields;
it also accepts null-prototype records, which the other two copies
already did (pure data, no inherited accessors). Characterization test
added for both in bounded-poll-coordinator.test.ts.
Race: one raceRealtimeTask(task, signal, deadline) in result.ts, built on
kernel createAbortableOperation, replaces fetch-sse timed/cancelReader,
reconnect race/drain (the drain keeps a host timer via timerDeadline,
since the clock itself may hang), poll awaitTaskOrAbort/awaitWithinLease,
live-poll checkpoint + two quiescence races (now one), stream-coordinator
deadline/recovery-wait/close-drain, and the two WS inline races. Kept
semantics: deadline armed first and wins a tie (poll lease), task still
starts when the clock throws (reader cancel), collaborator rejections
still reach stream-coordinator callers, scheduler install failure still
fails closed as a timeout. Small change: nothing starts once the signal is
already aborted (WS apply / SSE onEvent / reader.read could run just
before being reported ABORTED). The mapping adds one microtask per race,
so the reconnect test flush() helper gets 16 turns instead of 8.
Kernel: parseRetryAfterDelay moves to platform/retry-after.ts (realtime
re-exports it; http retry-policy parseRetryAfter now delegates, so it
rejects "", " ", "1e3", "1.5", "0x10" and non-IMF dates it used to
accept). json-member-scanner moves to platform/; web-push push-codec uses
it instead of its top-level-only duplicate-key check, so nested
duplicates are rejected too. INVENTORY 136 -> 137, detail tables updated.
Tests: RED for http strict Retry-After, web-push nested duplicate, poll
snapshot rules; new direct raceRealtimeTask tests. Gates: architecture,
types app/test (+ service-worker/web-worker), lint, adapter-inventory
(abort ratchet 21/21), test:unit, test:component, realtime-boundaries,
integration/platform all pass. Realtime bundle 40346 -> 39433 gzip.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
isReconnectAttemptResetEligible returned true on either a valid
heartbeat/event or stableOpenMs elapsed. A server or proxy that sends one
`:` comment and drops kept attemptIndex at 0, so the delay stayed in
[0, baseDelay) and maxAttempts/maxElapsed were never reached (many
clients reconnecting in lockstep). Both conditions are now required. The
reconnect coordinator uses this helper at both close paths, so no
coordinator change is needed. The two design docs that stated "or" now
say "and".
Existing tests encoded the old "either" rule (policy unit test and the
coordinator "resets a spent retry" test) and are rewritten. RED: the
policy test (heartbeat-only returned true) and the coordinator test
(heartbeat on an instant close still reset: 3 attempts, expected 2)
failed before the fix. Gates: architecture, types app/test, lint,
adapter-inventory, test:unit, test:component pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A full dedupe window (2,048 IDs / 4 MiB) used to trigger a full
DEDUPE_OVERFLOW recovery on every event past capacity, so a steady
3.4 events/s stream re-fetched snapshots and reconnected every window.
The coordinator now drops the oldest entry (Map insertion order equals
apply order) and keeps applying; a replay pushed out of the window still
drops as STALE_EVENT through the sequence check. The design doc row and
the maxDedupeBytes contract comment now say eviction instead of recovery.
The semantic fingerprint is now a 16-char 64-bit FNV-1a hash of the
canonical envelope instead of the canonical text itself (up to 64 KiB
each). The canonical-size EVENT_TOO_LARGE check only bounded that stored
text, so it goes too; the wire-size check stays. pruneDedupe stops at the
first unexpired entry instead of scanning every entry.
The old "recovers instead of evicting" coordinator test encoded the bug
and is replaced by an eviction test. RED: the eviction test (got
RECOVERED/DEDUPE_OVERFLOW) and a fixed-size fingerprint codec test (got
3326 vs 333 bytes) failed before the change. Added a TTL prune
characterization test (passes before and after). Gates: architecture,
types app/test, lint, adapter-inventory, test:unit, test:component pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A single reader chunk with more than maxItemsPerChunk (256) items used to
fail the stream with non-retryable QUEUE_OVERFLOW, killing normal replay
bursts even though maxChunkBytes already bounds memory. The parser now
stops at the cap, keeps the remaining decoded text, and returns it through
a new additive drain() call; fetch-sse-connection drains after every push
before reading again. Pushing or finishing with undrained text still fails
closed (QUEUE_OVERFLOW), so buffered text stays bounded by one chunk. A
lone CR followed by another line now re-checks the cap before continuing.
COMMENT and empty item lists reuse frozen constants.
The old parser test that expected QUEUE_OVERFLOW for 3 comments with a
cap of 2 encoded the bug and is replaced.
RED: new parser drain test and a 300-event single-chunk connection test
failed with QUEUE_OVERFLOW before the change. Gates: check:architecture,
check:types:app/test, lint, check:adapter-inventory, test:unit,
test:component all pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
consumeText() walked every code point, appended it to the line string and
called TextEncoder.encode() on it to count UTF-8 bytes, so a 250KB chunk
allocated ~250k arrays on the main thread.
It now finds the next CR/LF with one regex scan, appends the text before it
as one slice and encodes that slice once for its byte count. Byte counts only
grow within a line, so checking the line/incomplete-buffer limits per segment
fails on exactly the same inputs as the per-character check. BOM, pending CR
across reads, CRLF terminator bytes and QUEUE_OVERFLOW ordering are unchanged.
Correctness: existing parser tests pass unchanged. New tests (all green on
the old parser first, as characterization): whole vs byte-by-byte input with
CRLF, CR-only, multi-line data, BOM and a mid-stream U+FEFF, 2/3/4-byte
UTF-8 split across reads; trailing CR blank line dispatched at finish; UTF-8
bytes (not UTF-16 units) counted against line and event limits, also when a
multibyte character is split across reads; a max-size line over 1,000-byte
reads accepted and one byte more rejected; a 248,780-byte chunk of 200
events.
Benchmark (throwaway script, not committed; Node 24.14; 200 events in one
~250KB chunk; machine under load avg 39-54 on 22 cores, so numbers are noisy):
- old/new interleaved in one process, forced GC before each run, median:
ASCII 248,780 B: 294-345 ms -> 4.3-8.2 ms (36-80x)
multibyte 248,180 B (Korean/emoji/accented): 95-130 ms -> 19-26 ms (~5x)
- each parser standalone, sequential runs, average:
ASCII: 664-764 ms -> 0.9-3.7 ms
multibyte: 155-196 ms -> 1.5-6.3 ms
Remaining cost of the new parser is mostly native TextDecoder/TextEncoder
work (profiled); a JS charCode loop for the byte count was not faster.
Gates: check:architecture, check:types:app, check:types:test, lint,
test:component pass. test:unit passes except removal-fixture.test.ts, which
needs generated artifacts/release evidence absent from this fresh worktree
(unrelated).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The event consumer projected every RECOVERED disposition to a
RECOVERY_COMMITTED transport outcome. For a SNAPSHOT_ONLY + barrier NONE
stream the coordinator never sets awaitingTransportBarrier, so the transport
closed, the reconnect path called confirmTransportBarrier, and the
coordinator answered PROTOCOL_MISMATCH: one sequence gap ended the stream.
The RECOVERED disposition now carries transportBarrierRequired (optional,
additive field on the RealtimeAcceptDisposition port type; absent keeps the
old "barrier required" behavior). The coordinator fills it from the same
recoveryRequiresTransportBarrier() rule that decides awaitingTransportBarrier,
and the consumer returns CONTINUE when it is false.
Test: "keeps reading after a SNAPSHOT_ONLY recovery that needs no transport
barrier" in event-consumer.test.ts wires the real fetch SSE connection,
consumer, codec and stream coordinator (only the app authority is faked).
RED before the fix: read() ended with RECOVERY_COMMITTED at the gap instead
of EOF. After: the gap recovers to snapshot 3, event 4 still applies, the
stream reads to EOF and no barrier is pending.
Gates: check:architecture, check:types:app, check:types:test, lint,
test:component pass. test:unit passes except removal-fixture.test.ts, which
needs generated artifacts/release evidence absent from this fresh worktree
(unrelated).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
runRecovery() checked lifecycle === "DRAINING" only on entry. After
`await quiescence` it re-checked closed/abort/scope but not DRAINING, so an
effect that timed out while the recovery waited left the stream DRAINING and
the recovery still called the authority, committed a new resume state and
cleared recoveryRequired while the abandoned effect kept running (the
RT-RR-01/02 case).
The post-quiescence check now also fails with CLOSED/RECOVER when the stream
is DRAINING, without calling the authority.
Test: "fails a recovery whose effect quiescence ends in DRAINING" in
stream-coordinator.test.ts. RED before the fix: the recovery resolved
{ ok: true } (authority called and committed). After: CLOSED, authority not
called, no resume state; once the late effect settles the stream is OPEN and
STALE.
Gates: check:architecture, check:types:app, check:types:test, lint,
test:component pass. test:unit passes except removal-fixture.test.ts, which
needs generated artifacts/release evidence absent from this fresh worktree
(unrelated).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
reconnectable() in the reconnect coordinator returned false for
PROVIDER_UNAVAILABLE/RATE_LIMITED whenever serverNotBeforeMs was null, even
with retryable:true. The transports send exactly that for WS NETWORK_LOST /
RESTART (1006/1001/1012, error event) and SSE 502/504, and WS can never carry
a hint, so those streams ended instead of reconnecting. The bounded poll
coordinator had the same rule for retryAfterMs.
Both now decide on retryable + kind only; a missing hint falls back to policy
backoff. Transports that require a hint and lack one already report
retryable:false (SSE 429/503 without Retry-After, WS OVERLOADED), which stays
terminal.
Tests: the reconnect and poll tests that pinned the old behavior ("does not
reconnect/retry ... without a server hint") encoded the bug and are rewritten
to expect a policy-backoff retry. New seam tests wire the real
createWebSocketConnection / createFetchSseConnection into the reconnect
coordinator. RED before the fix: "reconnects a WebSocket NETWORK_LOST|RESTART
close that carries no server hint" (1 socket, expected 2), "reconnects SSE
HTTP 502|504 that carries no server hint" (got PROVIDER_UNAVAILABLE
retryable:true instead of the second attempt's FORBIDDEN), "retries retryable
RATE_LIMITED|PROVIDER_UNAVAILABLE without a server hint on policy backoff"
(execute called once). The WS test also closes with OVERLOADED to show
retryable:false stays terminal.
Gates: check:architecture, check:types:app, check:types:test, lint,
test:component pass. test:unit passes except removal-fixture.test.ts, which
needs generated artifacts/release evidence absent from this fresh worktree
(unrelated).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A server stream's registration was pruned on any settled close receipt.
`waitClosed()` rejecting, throwing synchronously, or not returning a
promise at all was absorbed into a fulfilled `undefined`, so the runtime
opened a second physical stream for the same operation while the first was
still running against the server. Only a fulfilled, contract-shaped
receipt confirms closure now; every negative receipt keeps the operation
DRAINING.
Cleanup also read foreign state outside the result boundary. A throwing
iterator `return` accessor replaced the already selected timeout with a
native `TypeError` and skipped the rest of the teardown, and the exported
lease decoder threw on a hostile `Symbol.asyncIterator`. Both reads move
inside their own boundaries, and the positive-close subscription is
installed before any fallible cleanup.
Composition validated the caller's registries before snapshotting them, so
a hostile accessor ran twice during validation, and rows hiding fields
behind a prototype or a non-enumerable key installed. Transport results
were checked for allowed own keys only, so own `{ok,message,encodedBytes}`
plus a prototype `injected` was a success and a missing `message` reached
a permissive schema as `undefined`.
In Realtime the tracked task was registered after the collaborator
returned. An authority that re-entered `close()` from inside its own
invocation saw an empty registry and got `{ok:true}` while its effect was
pending. The task is now registered first and the collaborator is invoked
a microtask later. A `scheduleTimeout` that threw was worse: the caller's
own catch treated it as an apply failure and started a recovery beside the
still-running effect, and `close()` rejected with a native `TypeError`. An
uninstallable deadline now fails closed as an expired one.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
RT-RR-01. An effect or recovery task was registered as retained only after its
public wait expired, so a close() that arrived first saw an empty set and
reported quiescence while the raw task was still running against the authority.
Tasks are now registered when they are created and removed when they settle;
DRAINING keeps its narrower meaning through a separate timed-out set.
RT-RR-02. Admission happened when an event was queued; execution is a second
decision. A queue entry admitted before the stream entered DRAINING no longer
starts running inside it. And an abandoned task may have applied part of its
effect, so the resume token it was based on is discarded and recovery is
required explicitly — the next ordinary event can no longer skip authoritative
recovery on the strength of state a timed-out effect may have invalidated.
RT-RR-03. close() cached the first timeout forever, so a writer that later
settled could never be proved quiescent and the retained registry could never be
pruned. Only an in-flight close is shared now, every writer a close fences is
retained until its tail actually settles, and the tail prunes itself. A second
close therefore converges to success once the writer finishes.
RT-RR-04. Checkpoint work joins writer tails in the physical-task registry from
invocation to settlement and is drained on the same terms.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
R-04: install the RPC contract bindings as exact immutable snapshots. Registry
and row data are copied from own data descriptors into frozen null-prototype
maps before validation, so a getter is never invoked, extra and symbol keys and
malformed descriptors are composition-time TypeErrors, and the runtime reads
only the snapshot. A post-validation mutation can no longer change replay
policy, deadlines, byte ceilings or transport selection.
R-01: bound transport stream cleanup. The generation is fenced and listeners
released immediately, and iterator.return() is awaited only within a cleanup
bound, so a non-cooperative iterator cannot keep the application generator, its
listeners or the total deadline alive. Unresolved cleanup stays observed.
R-05: reject oversized WebSocket text frames before allocating an encoded copy
and count UTF-8 bytes incrementally with an early exit, matching TextEncoder for
surrogate pairs and lone surrogates.
R-06: canonicalise clock and generation-fence failures into the closed Result
taxonomy instead of letting them escape as native rejections, with listener and
timer cleanup on every exit path.
Browser RPC remains AVAILABLE_NOT_COMPOSED; R-07 transport evidence is still
required before composition.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
R-02: add an OPEN/DRAINING/CLOSED lifecycle orthogonal to freshness. Effect and
recovery authorities are now awaited under a deadline: on expiry the commit
capability is revoked and the work aborted, the caller gets a bounded
non-retryable IDLE_TIMEOUT, and the underlying task is retained rather than
dropped. A draining stream refuses new events and recovery, and close() returns
a Promise that succeeds only once every retained task actually settled,
reporting IDLE_TIMEOUT otherwise.
R-03: a handoff fail-close moves active, probe, quiescing and transition leases
into a retired-writer set before clearing their references, and close() waits on
current and retired writers together, so an abandoned non-cooperative writer can
no longer make teardown report a false success.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>