sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
77.81k stars 4.06k forks source link

derived stores evaluate prematurely / semi-diamond dependency problem #10451

Closed WHenderson closed 5 months ago

WHenderson commented 5 months ago

Describe the bug

The current implementation of svelte stores have a limitation whereby derived stores may evaluate and trigger their subscribers prematurely.

(@mnrx described it thus in his PR #9458, @mnrx I am taking the liberty of splitting this into its own issue. If you already have an issue tracking this then my apologies - I'll move to yours once I know about it)

Currently, a change to a store's value only causes stores which are immediately dependent on it to be invalidated. Svelte does not propagate invalidation downstream to subsequent derived stores, and this can cause issues when two criteria are met:

Svelte's current implementation correctly handles dependency diamonds, but such cases do not meet the second criterion; unequal path length.

Example

Consider the following example:

const a = writable(1);
const b = derived(a, a => a*2);
const c = derived([a,b], ([a,b]) => a+b);
c.subscribe(c => console.log(c));
...
<input type=number bind:value={$a} />

This creates a dependency graph something like:

stateDiagram-v2
    direction RL

    input
    a
    b
    c
    log

    log --> c
    c --> b
    b --> a
    c --> a
    a --> input

Svelte's Current Implementation

With sveltes current implementation, the derived store c will prematurely evaluate every time store a changes. In the example above, if we change the input to 2, the current implementation will go through the following sequence:

sequenceDiagram
    autonumber

    participant input
    participant a
    participant b
    participant c
    participant log

    note right of a: a == 1
    note right of b: b == a * 2 == 1 * 2 == 2
    note right of c: c == a + b == 1 + 2 == 3

    input ->> a: 2
    note right of a: a == 2
    a -->> c: invalidate
    activate c
    a -->> b: invalidate
    activate b
    a ->> c: 2
    deactivate c
    rect rgb(255, 128, 128)
    note right of c: c == a + b == 2 + 2 == 4
    c ->> log: 4
    end
    a ->> b: 2
    deactivate b
    note right of b: b == a * 2 == 2 * 2 == 4
    b -->> c: invalidate
    activate c
    b ->> c: 4
    deactivate c
    note right of c: c == a + b == 2 + 4 == 6
    c ->> log: 6

Following the diagram, it's clear at point (5) that store c is evaluating prematurely. At point (5) store c believes both its dependencies to be valid, but in fact only a has been resolved at this point.

The correct behaviour would be for invalidations to be "deep" and for resolution to only occur once all dependencies are fully resolved. Thus in the given example, c should only emit once for each change to a.

Why fix it?

Prematurely evaluating a derived store in many situations would result in just a brief glitch - an incorrect calculation immediately followed by the correct one. But in many contexts, the derived store subscriptions result in side effects. Depending on the nature of these side effects, the results of a premature evaluation with incorrect data may be quite pronounced - sending data to a service, permanently modifying data, crashing an application.

Reproduction

See: semi-diamond dependency problem REPL

As a head start for any patch request, here is a test case:

    it('only updates once dependents are resolved', () => {
        const a = writable(1);
        const b = derived(a, a => a*2);
        const c = derived([a,b], ([a,b]) => a+b);

        const values: number[] = [];

        const unsubscribe = c.subscribe(c => {
            values.push(c);
        });

        a.set(2);
        a.set(3);
        assert.deepEqual(values, [3, 6, 9]);
    });

note that the above test case fails with the current implementation

Logs

N/A

System Info

Svelte v4.2.10

Severity

annoyance

mnrx commented 5 months ago

I created #10376 a couple of weeks ago—I think this is the same issue. That said, the sequence diagram and test case you created would be good additions to it.

WHenderson commented 5 months ago

Closing this in favour of the earlier issue @mnrx raised (#10376)