Commit Graph
16 Commits
Author SHA1 Message Date
DongHyeonkaandClaude Opus 5.5 b35304dd48 fix(realtime): retryable OFFLINE for a throwing poll, one BOM, single encodes (Q-6.4-11)
- 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>
2026-09-24 13:54:42 +09:00
DongHyeonkaandClaude Opus 5.5 13274f7f3a fix(realtime): bound the live probe buffer by what it still holds (Q-6.4-10)
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>
2026-09-24 13:54:42 +09:00
DongHyeonkaandClaude Opus 5.5 ae2f006b6d refactor(realtime): merge snapshot and race helpers, move shared parsers to kernel (Q-6.4-8)
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>
2026-09-24 13:54:42 +09:00
DongHyeonkaandClaude Opus 5.5 54e6bce9d2 fix(realtime): reset the retry budget only after a signal on a stable open (Q-6.4-7)
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>
2026-09-24 13:54:29 +09:00
DongHyeonkaandClaude Opus 5.5 bc17ed4bd7 fix(realtime): evict dedupe entries FIFO and store hashed fingerprints (Q-6.4-6)
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>
2026-09-24 13:54:29 +09:00
DongHyeonkaandClaude Opus 5.5 cc906f08b4 fix(realtime): hand SSE items past the per-chunk cap to drain() (Q-6.4-5)
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>
2026-09-24 13:54:29 +09:00
DongHyeonkaandClaude Opus 5.5 df9b15c039 fix(realtime): parse SSE text a line at a time (R-4.4)
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>
2026-09-24 12:19:48 +09:00
DongHyeonkaandClaude Opus 5.5 a0e84eb897 fix(realtime): keep the transport open after a barrier-free recovery (R-4.3)
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>
2026-09-24 12:19:48 +09:00
DongHyeonkaandClaude Opus 5.5 a6553e67bd fix(realtime): refuse recovery once its quiescence ends in DRAINING (R-4.1)
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>
2026-09-24 12:19:48 +09:00
DongHyeonkaandClaude Opus 5.5 87a45893d6 fix(realtime): reconnect retryable failures without a server hint (R-4.2)
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>
2026-09-24 12:19:48 +09:00
DongHyeonkaandClaude Opus 5 aa8ac35600 fix: make Browser RPC and Realtime own the physical work they report on
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>
2026-08-15 01:25:48 +09:00
DongHyeonkaandClaude Opus 5 c0f53d1855 fix: track realtime physical work from invocation to settlement
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>
2026-08-14 16:59:15 +09:00
DongHyeonkaandClaude Opus 5 8f67974f68 fix: install bounded Browser RPC stream leases
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>
2026-08-14 00:00:15 +09:00
DongHyeonkaandClaude Opus 5 2f29ccbf1a fix: retain realtime work through draining
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>
2026-08-13 23:52:46 +09:00
DongHyeonka c6da03369c refactor: 리펙토링 2026-08-01 19:39:59 +09:00
donghyeon-ka 6c52cdb916 feat: 기능 추가 과정중 2026-07-30 15:58:20 +09:00