Skip to content

[ui] Connection-bound reactive sessions: the WebSocket owns the session - #1664

Merged
fwbrasil merged 2 commits into
mainfrom
kyo-ui-session-connection-bound
Jun 10, 2026
Merged

fwbrasil merged 2 commits into
mainfrom
kyo-ui-session-connection-bound

Conversation

@fwbrasil

@fwbrasil fwbrasil commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Problem

This PR solves flaky tests in CI. 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:

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.

…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.
// (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](

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't initRaw be created with this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
fwbrasil merged commit ff2ad7c into main Jun 10, 2026
9 of 10 checks passed
@fwbrasil
fwbrasil deleted the kyo-ui-session-connection-bound branch June 10, 2026 01:07
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants