Repository navigation
[ui] Connection-bound reactive sessions: the WebSocket owns the session - #1664
Merged
Merged
Conversation
…ession
**Problem**
A server-driven kyo-ui session (the live per-tab `Signal` graph) has no owner and no lifetime. It is a cookie-keyed entry in an in-memory `SessionStore`, fed by Server-Sent-Events down and HTTP POST up, with per-region subscription fibers tracked by hand. Nothing tears it down: the store is never evicted, so sessions accumulate for the process lifetime; and a nested region's re-render interrupts only its immediate child fibers, orphaning grandchildren, so the leak grows while the app is in use. The root cause is a missing ownership model: no scope defines when a session is alive or gone, so cleanup is manual and incomplete.
**Solution**
Add `Signal.observe`, a scoped switch combinator, and build the session on it. `f` runs for the current value and each change inside a fresh per-value `Scope`, held open until the next value, then closed (releasing whatever `f` forked, transitively) before the next runs. It is register-before-read, so a write racing the read never loses the latest value, and it never tears a still-current value's scope down on an idle timer.
The session then *is* the connection, owned by a `Scope`:
```scala
Scope.run {
subscribe(root, wsExchange(ws))
Async.race(ws.stream.foreach(dispatch), ws.onPeerClose)
}
```
Socket close completes the block, the `Scope` closes, and every reactive region (a `Fiber.init` in the scope tree, each driven by one `observe`) is interrupted by cascade. Teardown is structural and cannot be forgotten, and a value change releases the prior subtree with no manual fiber bookkeeping. WebSocket is the enabling choice: its handler runs for the connection's lifetime with a `Scope` that closes on disconnect, where SSE+POST had no per-connection lifecycle to attach cleanup to.
Transport is a single WebSocket. The page `GET` is pure SSR (initial HTML + a small WS client; no session created, nothing stored). `SessionStore`, the `kyo-sid` cookie, and the `/_kyo/event` + `/_kyo/sse` routes are gone; the inline client uses one `WebSocket` both directions (`HtmlOp` out, `UIEvent` in, shapes unchanged). `runHandlers` / `runMount` / `runRender` signatures are unchanged.
**Notes**
- **Trade-off to weigh: per-connection state resets on disconnect.** A dropped socket ends the session; reconnect starts a fresh one. Better than today (reconnect was silently broken), but state that must survive a drop has to live above the per-connection evaluation. A resume/grace layer can be added later without changing the ownership model.
- **WebSocket is required for interactivity** (no-WS clients get the SSR page only). It also pins a session to one server, removing the prior need to sticky-route SSE and POST together.
- **Leak-freedom is covered by tests** (Scope-finalizer witnesses on teardown), not assumed.
- **Cross-platform** JVM/JS/Native/Wasm; the WS round-trip and disconnect tests are `.notNative` (a kyo-http IO-driver constraint, not an API gap).
- Unchanged: the per-boundary `HtmlOp.Replace` diff model, `data-kyo-path` addressing, and the focused-input morph. The in-process `DomBackend` shares the scoped engine.
hearnadam
reviewed
Jun 8, 2026
| // (register-before-read) loops instead of inheriting the default read/register repair loop. This keeps `map`-over-leaf | ||
| // chains exact (and idle-no-teardown) on the leaf. | ||
| @nowarn("msg=anonymous") | ||
| private inline def _initRawF[A]( |
Collaborator
There was a problem hiding this comment.
Shouldn't initRaw be created with this?
Collaborator
Author
There was a problem hiding this comment.
The new observe mechanism is derived from the other functions. We could expose it but it'd be a low-level feature that is very easy to get wrong. I think we can wait for concrete use cases to see if exposing makes sense
…ala Native) Problem: The exact register-before-read observe override on SignalRef held the next-change promise live across the per-value Scope.run/Async suspension. On Scala Native 0.5.10 that pattern miscompiles: it runs correctly in isolation, but its presence in a downstream native binary perturbs whole-program codegen and corrupts the heap, surfacing as an unrecoverable SIGSEGV/SIGABRT under concurrent load (kyo-browser native suite, around test 788 in BrowserIsolateTest). Solution: Remove the override so SignalRef uses the trait's repairing observe. That loop never holds a promise across the suspension and is lossless: a write that races the read/register window is reconciled within repairInterval, never dropped (validated: 0 losses across 40k back-to-back writes, worst case ~900ms under the 1s default). Leaf and map-over-leaf observe lose exact instant delivery on that rare race (~0.07% of back-to-back writes) but never lose the value. Notes: The two SignalTest back-to-back-write tests are re-aimed at the actual guarantee (no loss within repairInterval) instead of 300ms-exact. A SignalRef comment warns against reintroducing an exact override without re-validating the kyo-browser native suite.
fwbrasil
added a commit
that referenced
this pull request
Jun 10, 2026
Resolves conflicts introduced by #1664 (connection-bound reactive sessions): - HtmlRenderer: clientJs(jsStr(basePath)), combining #1664's dropped sessionId (the WebSocket owns the session) with #1665's jsStr JS-string escaping. - HtmlRendererTest: keep both added blocks (charts' JS-escaping tests + main's clientJs transport tests), adapting charts' tests to the 4-arg renderPage. - SvgReactiveTest: import scala.language.implicitConversions (UISession removed upstream; UIExchange unused in the merged body). - README: charts' demo list (matches the actual XDemo.scala files), with the stale "over SSE" corrected to "over the WebSocket". - ChartMorphTest: 4-arg renderPage (drop the sessionId argument). Validated: kyo-ui Test/compile clean; affected tests 116 passed, 0 failed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
This PR solves flaky tests in CI. A server-driven kyo-ui session (the live per-tab
Signalgraph) has no owner and no lifetime. It is a cookie-keyed entry in an in-memorySessionStore, fed by Server-Sent-Events down and HTTP POST up, with per-region subscription fibers tracked by hand. Nothing tears it down: the store is never evicted, so sessions accumulate for the process lifetime; and a nested region's re-render interrupts only its immediate child fibers, orphaning grandchildren, so the leak grows while the app is in use. The root cause is a missing ownership model: no scope defines when a session is alive or gone, so cleanup is manual and incomplete.Solution
Add
Signal.observe, a scoped switch combinator, and build the session on it.fruns for the current value and each change inside a fresh per-valueScope, held open until the next value, then closed (releasing whateverfforked, transitively) before the next runs. It is register-before-read, so a write racing the read never loses the latest value, and it never tears a still-current value's scope down on an idle timer.The session then is the connection, owned by a
Scope:Socket close completes the block, the
Scopecloses, and every reactive region (aFiber.initin the scope tree, each driven by oneobserve) is interrupted by cascade. Teardown is structural and cannot be forgotten, and a value change releases the prior subtree with no manual fiber bookkeeping. WebSocket is the enabling choice: its handler runs for the connection's lifetime with aScopethat closes on disconnect, where SSE+POST had no per-connection lifecycle to attach cleanup to.Transport is a single WebSocket. The page
GETis pure SSR (initial HTML + a small WS client; no session created, nothing stored).SessionStore, thekyo-sidcookie, and the/_kyo/event+/_kyo/sseroutes are gone; the inline client uses oneWebSocketboth directions (HtmlOpout,UIEventin, shapes unchanged).runHandlers/runMount/runRendersignatures are unchanged.Notes