Skip to content

fix: batch views of reactions - #19030

Open
dummdidumm wants to merge 93 commits into
mainfrom
batch-views
Open

dummdidumm wants to merge 93 commits into
mainfrom
batch-views

Conversation

@dummdidumm

@dummdidumm dummdidumm commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

This changes the async reactivity system when multiple batches are active such that they check if they need to be re-executed in a batch by comparing the write versions of the dependencies they last saw with the ones they have now - if there's any difference, they re-execute. These write version arrays, the value, the dependencies that batch sees - all is stored in a record local to the batch. Logic exists to promote them to the real world if we know the derived was computed from real-world/latest dependencies only, and async/block effects promote once the batch commits.

This introduces some complexity, on the other hand various things are simplified or removed (#commit for example got easier).

This is WIP, but I've commited a readme that gives a good overview of how the system works in more detail and the gaps vs async-reactivity-another-try-pt-1

@pkg-svelte-dev

pkg-svelte-dev Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Install the latest version of svelte from ef13a2b:

pnpm add https://pkg.svelte.dev/svelte/c/ef13a2b25e52d560c01c24800f50ed46d4aca121

Open in pkg.svelte.dev: https://pkg.svelte.dev/repos/svelte/pr/19030

@changeset-bot

changeset-bot Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: ef13a2b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
svelte Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@svelte-docs-bot

Copy link
Copy Markdown

Rich-Harris and others added 12 commits November 2, 2026 17:09
…_batch` (#19122)

This PR does three things:

- it moves `current_batch = this` to inside `#process`, such that it is
assigned in precisely three places: `#process`, `activate`, and `ensure`
- uses `view_batch` in place of `previous_batch` and `async_mode_flag ?
previous_batch : current_batch`, since it's equivalent
- gets rid of the no-longer-needed `previous_batch` (which was
originally only needed for legacy mode, but had started to creep
elsewhere) and the ungodly `prev_previous_batch`

Essentially we have two separate but related concepts — the batch that
is being set up/written to (`current_batch`), and the batch that is
being read from (`view_batch`). It's likely that there are other places
where we're using `current_batch` where it would be slightly more
correct (if of no practical importance) to use `view_batch`, but this
doesn't attempt to identify or change any of those sites

---------

Co-authored-by: Simon Holthausen <simon.holthausen@vercel.com>
…try (#19148)

corrects and clarifies comments around the connection between
`batch.current` and `batch.previous`, which are _not_ mirrors of each
other — previously uninitialized values are not added to
`batch.previous`
…sync mode (#19146)

Turns out we can make this a bit simpler — no need to gate it on
`$effect` in non-async mode
…19151)

follow-up to #19150 — making them required properties simplifies a
couple of sites, at the cost of requiring the property in 'synthetic'
teardown entries (i.e. `held ??= {...}` in `teardown_view`, and
`teardown_run`). But it feels better for an entry to have a consistent
shape

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
…uated after the assignment (#19124)

Draft because the recursion seems expensive and I don't like it; would
like to find an alternative.

Turns out the `version_of(deps[i]) > wv` check is insufficient in some
cases, because a derived's version records when it was evaluated rather
than the change that _caused_ the evaluation happened.

---------

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
resolves
https://github.com/sveltejs/svelte/pull/19030/files#r4319379716. ~~This
is definitely a trade-off — we now need to create the `seen` set and do
the iteration at two callsites — but I think it's _probably_ the right
one because we're not creating an array to wrap every reaction, and
`#revalidate` isn't being called with an array in one case and an
`Iterable` in another. (On the flip side, we now have more function
calls? And the function is still polymorphic because it can receive a
`Source` or a `Value`)~~

Edit: realised we can do this without recursion. Feels a bit nicer. We
need a second set (one for values, one for effects) but that seems fine

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
We have three `return length` statements in `update_dependencies`, and
one `return update_record(...)`, which in turn has its own `return
length` (which to be fair is unnecessary because `length` is passed in
as an argument). None of this plumbing is really explained, and it's
unnecessary because the state that `length` is computed from (`new_deps`
and `skipped_deps`) is available inside `update_reaction` anyway.

Getting rid of it makes the code a bit less confusing, and gets rid of a
pair of command-query separation violations, without sacrificing the
fast path bail-out for effects that write state but don't read it
We write effect results to a batch record rather than the signal itself
if it's a) an async effect or b) an initialized block effect. Normally
we don't need to care about `view_batch?.committing` because these
effects run during traversal. The exception is block effects that are
dirtied during `flush_queued_effects` and need to run immediately.

~~We can get rid of the `view_batch?.committing` check if we move
`#release_records` to _after_ `flush_queued_effects`, so that records
are still created but then immediately released. With that change, we
can get rid of `batch.committing` altogether.~~ _Edit: this can cause
things to get slightly out of whack if an effect contains a `flushSync`
— not in such a way that a user would ever notice, but still worth
avoiding_

We can replace the `view_batch?.committing` check with `view_batch ===
current_batch`, since that's true during traversal and false afterwards,
which is equivalent. Since nothing else uses it, we can save ourselves
the unnecessary property
Trying to make the `update_record` logic a bit more self-explanatory,
one small change at a time. First up, instead of `batch` being non-null
implicitly meaning 'we should use a batch record', replacing it with an
explicit `should_record` variable

---------

Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
This fixes a bug where a block effect, created by an effect during
effect-flush-phase, is committed into the DOM eagerly and can therefore
cause tearing, e.g. because it contains an async expression.

It does so by also defering the append during the effect flush phase,
along with having a check if effects in the queue are already skipped in
`current_batch` (the next batch, which will be set as soon as one effect
writes to a value).

When a block is scheduled for creation/removal, the effect writes up
until that point are stored along with it, so that the teardown context
can be reconstructed more correctly (though the teardown context of the
prior effect flush phase is otherwise ignored, as strictly speaking this
is now the next flush phase where the "old" teardown values should no
longer apply).

Essentially, this is #19211 but with the teardown logic tweaked and
moved from `branches.js` to `batch.js` (which makes it also apply to
each blocks), and without the "skip intermediate work" logic which has
caused extra work + regressions in that PR (and it's an edge case and
only a harmless create+destroy anyway).

---------

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Rich-Harris and others added 5 commits November 9, 2026 17:26
Just yoinking this out of #19168 since these changes have nothing to do
with abort signals. If a batch is committed but stays linked (because it
still has work inside a pending boundary), its later results should be
grouped with the committed state; the easiest way to achieve this is by
moving committed batches to the front
If a fork runs an async expression, then a later real batch also runs
the async expression but with different values, then finishes, the real
batch will commit and potentially rebase the fork. While doing so the
fork most not take the async result values, as they can be computed from
different inputs, and the fork is not guaranteed to rerun the async
expression - in such a case, overtaking the result would mean stale
values once the fork commits.

This fixes it by adding a new `async` property to `BatchValue` which is
only set for async results, and then subsequently used in `#commit()`.

Extracted from #19159

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
This extracts the `getAbortSignal` stuff from #19087 so it can be
reviewed independently.

I'm not sure we've quite nailed the behaviour yet. If I have a situation
like
[this](https://svelte.dev/playground/hello-world?version=pr-19168#H4sIAAAAAAAAE42RQY_bIBCF_8qIVoqttZKendjRXqq991h6IHiIUPBgwXi3K8p_r4idVbpq1T0Bj_e-QY8kSI0oWvGEznl48cENUOFgGYdaNMJYh1G035Pg16n4iiCaW-pxmrbxGR0X7aQi_k3XnhiJo2jFIepgJwan6NxJwVGKXpJkO04-MCQwPlwaOCM_nnzgb_ZMyjVQZsNXHy6QwQQ_wmaBb_aSStwhA0EHnyMrxupLvb-ppl1yv4Bm56C7LmvKzKTZegLtabBlV1ELNI8nDDWkYpGsPUXvcOv8udpEVoFx2DRA9QqR_Odjq3rrSZUzdFDV0PU30jvW1XPHYsn5jRmQ50DAYcbrXZZ02C3dlb7ocJqZPYEn7ay-dGmZRA8PubekA45IfNgtrv6ffgPHY3ftvHoD1Lkvwv_DCcxxq_04Wq7qPZi1XMi5X9QPIgYbtQrDe8Yq30EkpU_W3P9WnRPltLMmSwLRCMafLNrSWv7RCFbWvVgaRGuUi9gIFV9Jr_e_AZg0G-b5AgAA),
I would expect `increment`, `fork`, `commit` to result in the following:

```
started 0

<click increment>
aborted 0
started 1

<click fork>
started 2

<click commit>
aborted 1
```

Or `increment`, `fork`, `discard` to result in this:

```
started 0

<click increment>
aborted 0
started 1

<click fork>
started 2

<click discard>
aborted 2
```

At present, that's not what happens — the aborts don't happen the effect
in question next runs outside a fork. That's too late — if SvelteKit
creates a fork when I hover over `<a href="/foo">`, starts fetching
stuff, and discards the fork when I hover over `<a href="/bar">`, the
fetches need to be aborted immediately, not at some arbitrary time in
the future long after the obsolete fetches were allowed to complete.
_edit: this is now fixed_

---------

Co-authored-by: Simon Holthausen <simon.holthausen@vercel.com>
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Make them async-aware, which means
- making sure only the latest run commits its result in case they
overlap (avoid rewinds causing stuck UI)
- making them work with forks - previously they would "break out" of
forks because the promise resolve is a separate batch (but no longer in
forks now).

The `merge_target` is introduced here to follow a merge, which may/will
be useful outside await blocks, later, too

Extract from #19159

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
dummdidumm and others added 4 commits November 13, 2026 17:57
Apply the same "is there a later batch with a newer value" logic on fork
commit
Alternative to #19240. Not quite ready yet — two tests are still
failing, and I think there are further opportunities for simplification
— but I think the overall idea makes sense. Essentially, any time a
branch has `await` expressions, we wrap the contents in a synthetic
`{#if ready}` block, where `ready` means 'all the async dependencies
have a value'.

The problem this solves is most easily illustrated with this example:

```svelte
{#if a || b}
  <p>{await load(x)}</p>
{/if}
```

If `a=1` and `x=1` are written, and then `b=1` is written while we're
waiting for the initial `load(x=1)`, and the second batch resolves
before the first, at present we will render `<p> </p>` before the
`await` expression is ready. With this change, we render `<p>{await
load(x=0)}</p>` initially, then update it to `<p>{await load(x=1)}</p>`
when the first batch resolves.

---------

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: Simon Holthausen <simon.holthausen@vercel.com>
@joeldrapper

Copy link
Copy Markdown

We've been trying this branch (at 4a669eb) in a large async-mode SvelteKit app. It fixes most of the batching bugs we patch Svelte for today, which is great.

There's one regression: an update made while the first render is still waiting on two awaits is lost. The component stays on one 0 instead of one 1. With a single await it's fine. The test passes on main and at e7ea0c4^, and fails from e7ea0c4 (#19242, "create effects in flatten whenever values are ready").

Failing test, as a runtime-runes sample on top of this branch: https://github.com/joeldrapper/svelte/tree/claude/batch-views-lost-update/packages/svelte/tests/runtime-runes/samples/async-update-during-first-render (commit)

@Rich-Harris

Copy link
Copy Markdown
Member

Thank you trying it and for the repro! It's fixed on both #19277 and #19262

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment