Closed WHenderson closed 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.
Closing this in favour of the earlier issue @mnrx raised (#10376)
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:
This creates a dependency graph something like:
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:Following the diagram, it's clear at point (5) that store
c
is evaluating prematurely. At point (5) storec
believes both its dependencies to be valid, but in fact onlya
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 toa
.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:
note that the above test case fails with the current implementation
Logs
System Info
Severity
annoyance