ReviewOS

stacks/stx

signals: bindIfChain effect over-subscribes — re-runs on every signal mutation in scope even when picked branch doesn't change

#1738
Closed glennmichael123 opened this 22 days ago · 0 comments
22 days ago

Observation (follow-up to #1737)

While verifying the #1737 fix in bench-review (which the disposeSubtreeScopes patch + my workaround landed), the diagnostic trace surfaced a separate perf characteristic worth flagging.

After any signal mutation that doesn't change a branch's picked index, the chain effect still runs end-to-end:

[stx-debug] bindIfChain pick: 0 of 2 ( :if ) prev: 0   ← picked same, no DOM op
[stx-debug] bindIfChain pick: 1 of 3 ( :else-if ) prev: 1   ← picked same, no DOM op
[stx-debug] bindIfChain pick: 0 of 2 ( :if ) prev: 0
[stx-debug] bindIfChain pick: 1 of 3 ( :else-if ) prev: 1
... (dozens of times during a single page load) ...

The early-return at if (pickedIdx === currentIdx) return correctly short-circuits the DOM mutation, but the effect body itself runs every time. On a page with two chains (composer/sign-in + loading/empty/list) and ~5 fetches resolving across mount, I counted 50+ no-op effect invocations.

Root cause

bindIfChain (signals.ts:2495-2510):

effect(function() {
  // Subscribe to every signal in scope for reactivity.
  for (var sk in trackScope) {
    var sv = trackScope[sk]
    if (sv && typeof sv === 'function' && (sv._isSignal || sv._isDerived)) sv()
  }

  // Pick the first matching branch; terminal x-else (expr=null) matches.
  var pickedIdx = -1
  for (var i = 0; i < chain.length; i++) {
    var b = chain[i]
    if (b.terminal) { pickedIdx = i; break }
    if (evalBranch(b)) { pickedIdx = i; break }
  }
  if (pickedIdx === currentIdx) return
  // ...DOM ops...
})

The eager read of every signal in trackScope is correctness-defensive. The picker's for...break only evaluates branches up to the first true one, so later branches' signal reads never register as dependencies. Without the eager pass, a transition from "branch 2 picked" → "branch 0 should pick" wouldn't re-fire the effect, because the proxy never read branch 0's signal during the previous run.

The cost is: every mutation to any signal in scope re-runs every chain's effect, even when neither the trigger nor the picker outcome involved that chain. On bench-review's article page with ~30 scoped signals, every signal.set from any store re-runs both Comments chain effects.

Proposed fix

Two-pass setup, so the dependency-tracking happens once and stays correct:

function bindIfChain(chain, passedScope) {
  // ...existing setup, placeholders, detach...

  // Setup pass: eagerly evaluate every branch expression once so the
  // tracker registers dependencies on ALL branches' signals. Discard
  // the values; this pass is just for dependency registration.
  effect(function setupTracking() {
    for (var i = 0; i < chain.length; i++) {
      var b = chain[i]
      if (b.terminal) continue
      try { evalBranch(b) } catch { /* swallow — runtime pass handles real eval */ }
    }
  })

  // Picker pass: only fires when one of the tracked signals actually
  // changes. Short-circuits at the first truthy branch.
  effect(function picker() {
    var pickedIdx = -1
    for (var i = 0; i < chain.length; i++) {
      var b = chain[i]
      if (b.terminal) { pickedIdx = i; break }
      if (evalBranch(b)) { pickedIdx = i; break }
    }
    if (pickedIdx === currentIdx) return
    // ...DOM ops...
  })
}

The setup pass establishes the dependency graph once. The picker pass naturally only re-fires when any of those tracked signals change — which IS the trigger set we want.

Alternative: single effect, but unconditionally evalBranch all branches every run (drop the for-break), then pick the first truthy. Same eager-evaluation cost but no separate setup pass.

Either approach removes the "all-of-scope subscription" sledgehammer in favor of dependency-narrow subscriptions.

Impact

Not user-facing visible at small scale — the DOM-op short-circuit makes the effect runs invisible. At larger scale (many chains, many signals, fast-changing data sources like SSE feeds) the wasted work compounds and shows up as scroll jank or input latency.

The console-noise side effect is what makes it noticeable during diagnosis ([stx-debug] pick: X prev: X firing dozens of times for unrelated signal mutations).

Happy to PR. Test surface:

test('picker effect does not re-run on unrelated scope signal mutation', () => {
  const a = state(true)
  const b = state(1)
  // chain reads only `a`
  const html = '<div :if="a">A</div><div :else>B</div>'
  // ...mount...
  let pickerRuns = 0
  // Instrument picker effect — count invocations
  b.set(2) // unrelated mutation — picker should NOT re-fire
  expect(pickerRuns).toBe(0)
  a.set(false) // related mutation — picker SHOULD re-fire
  expect(pickerRuns).toBe(1)
})
  • #1737 — disposeSubtreeScopes nested-scope deletion (different bug, just landed the workaround)
  • #1733 — bindIf retry-without-unwrap (separate code path)

Sign in to comment on this issue.