Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lazy recomputeDependents #2827

Merged
merged 5 commits into from
Dec 18, 2024
Merged

lazy recomputeDependents #2827

merged 5 commits into from
Dec 18, 2024

Conversation

dmaskasky
Copy link
Collaborator

@dmaskasky dmaskasky commented Nov 17, 2024

Related Bug Reports or Discussions

#2782

Summary

Currently, recomputeDependents runs for each call to set. This causes overlapping dependents to recompute multiple times.

We still need to recompute some dependents if they are accessed with get. But the remaining dependents can be recomputed at the end of the transaction in flushPending.

const a = atom(0)
const b = atom((get) => get(a))
const fetch = vi.fn()
const c = atom((get) => fetch(get(a)))
const w = atom(null, (get, set) => {
  set(a, 1)
  expect(get(b)).toBe(1)
  expect(fetch).toHaveBeenCalledTimes(0)
})
const store = createStore()
store.sub(b, () => {})
store.sub(c, () => {})
fetch.mockClear()
store.set(w)
expect(fetch).toHaveBeenCalledOnce()
expect(fetch).toBeCalledWith(1)
expect(store.get(a)).toBe(1)
image

Proposed Fix

  1. on set
    • keep a list of all atoms that have been changed
    • mark the atom's state and its dependents' state as dirty
  2. on get, if the atom's state is dirty
    • recompute the atom and all it's dependencies that are dirty
  3. on flushPending, recompute all remaining dirty dependents

More complex example

Suppose you write to node 17. Itself and it's dependents are {17, 15, 16, 12, 13, 14, 9, 10, 11, 6, 3, 1}.
We save these nodes as pending recompute.
Then suppose you read from node 1. Itself and it's dependencies are {1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 17}.
The intersection of these two sets is {1, 3, 6, 9, 12, 15, 17}.
On get, only these nodes will be eagerly recomputed.
On flushPending, the remaining nodes {16, 13, 14, 10, 11} will be recomputed.

image

Description of Core Functions

getMountedDependents

Was previously getDependents. Is called by getAllDependents. Returns a set of all mounted dependents.

getAllDependents

Is called by markRecomputePending and getSortedDependents. Returns a map of atoms to a set of their dependents (Map<AnyAtom, Set<AnyAtom>>).

markRecomputePending

Is called by recomputeDependents and setter. Sets atomState.x to true.

getSortedDependents

Is called by recomputeDependents. Returns a topological sorted list of atoms and its dependent atoms (deep).

recomputeDependents

Is called by recomputeDependencies and flushPending. Receives a set of atoms for which to recompute dependents on. Iteratively calls readAtomState and mountDependencies on all atoms and their dependents (deep) whose atomState.x is true.

recomputeDependencies

Is called by the getter in writeAtomState. Recomputes the dependents (deep) of all dependencies (deep) whose atomState.x is true.

flushPending

Is called in the following places

  1. In the readAtomState getter finally block if getter is called async.
  2. In complete which is called when a valueOrPromise is a promise and has settled.
  3. In setter finally block if setter is called async.
  4. In writeAtom finally block.
  5. In setAtom finally block if setAtom is called async.
  6. At the end of subscribeAtom
  7. At the end of unsubscribeAtom

Check List

  • pnpm run prettier for formatting code and docs

Copy link

vercel bot commented Nov 17, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
jotai ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 18, 2024 0:49am

Copy link

codesandbox-ci bot commented Nov 17, 2024

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@dmaskasky dmaskasky changed the title add failing test: batches sync writes fix: add failing test: batches sync writes Nov 17, 2024
Copy link

github-actions bot commented Nov 17, 2024

LiveCodes Preview in LiveCodes

Latest commit: c758a69
Last updated: Dec 18, 2024 12:49am (UTC)

Playground Link
React demo https://livecodes.io?x=id/4ACRS53X4

See documentations for usage instructions.

@dai-shi
Copy link
Member

dai-shi commented Nov 17, 2024

  • Unrelated: aState.m.l subscribers are not deduped in flushPending Fixed

The commit link is not found. (because of force pushing?)

@dmaskasky dmaskasky changed the title fix: add failing test: batches sync writes fix: only recompute dependents accessed with get in-place, defer rest to flushPending Nov 17, 2024
@dmaskasky dmaskasky changed the title fix: only recompute dependents accessed with get in-place, defer rest to flushPending only recompute dependents accessed with get in-place, defer rest to flushPending Nov 17, 2024
@dmaskasky dmaskasky changed the title only recompute dependents accessed with get in-place, defer rest to flushPending [WIP] only recompute dependents accessed with get in-place, defer remaining to flushPending Dec 3, 2024
@dmaskasky dmaskasky requested a review from dai-shi December 3, 2024 09:22
Comment on lines 274 to 275
while (pending[0].size || pending[1].size || pending[2].size) {
recomputeDependents(pending, new Set(pending[0].keys()))
Copy link
Collaborator Author

@dmaskasky dmaskasky Dec 15, 2024

Choose a reason for hiding this comment

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

Actual change

- while (pending[1].size || pending[2].size) {
-   pending[0].clear()
+ while (pending[0].size || pending[1].size || pending[2].size) {
+   recomputeDependents(pending, new Set(pending[0].keys()))

Copy link
Member

@dai-shi dai-shi left a comment

Choose a reason for hiding this comment

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

Thanks so much for working on it. The commit history tells how challenging this has been.

I only check the diff, and assuming that this keeps the basic logic and only defers the execution, it's pretty close to what I would do. What's blocking is the reasonable understanding of the store.test.tsx change and failed CI tests.

You can stop it here and I can take it over, if you like.

src/vanilla/store.ts Show resolved Hide resolved
@@ -198,33 +207,6 @@ const addPendingFunction = (pending: Pending, fn: () => void) => {
pending[2].add(fn)
}

const flushPending = (pending: Pending) => {
Copy link
Member

Choose a reason for hiding this comment

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

While I'm not sure which is better, I would try keeping it outside. I'm not sure about the future, and we may put "pending" in buildStore. In general, I prefer isolating it.

src/vanilla/store.ts Show resolved Hide resolved
const getter: Getter = <V>(a: Atom<V>) =>
returnAtomValue(readAtomState(pending, a))
const getter: Getter = <V>(a: Atom<V>) => {
recomputeDependencies(pending, atom)
Copy link
Member

Choose a reason for hiding this comment

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

I'm not sure why this is necessary.

Copy link
Collaborator Author

@dmaskasky dmaskasky Dec 16, 2024

Choose a reason for hiding this comment

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

Perhaps I should leave a comment here.

Before we get any atom, we need to recompute the dependents of any of its dependencies that have been marked as dirty, to ensure we are returning the latest value. This is the exception to the lazy recomputeDependents rule.

Example:

const a = atom(0)
const b = atom(0)
const c = atom((get) => [get(a), get(b)])
const d = atom((get) => get(c))
const e = atom((get) => get(a))
const w = atom(null, (get, set) => {
  get(d) // [0, 0]

  // does not immediately recompute,
  // marks `a` and all its dependents as dirty
  set(a, 1)

  // setA: dependencies of `d` are {c,a,b}
  // setB: dirty atoms of setA are {a}
  // setC: dependents setB are {a,c,e}
  // setD: intersection of setC and setB are {a,c}
  // recompute setD
  get(d) // [1, 0]

  // recompute remaining dependents of dirty atoms in flushPending {e}
})
store.set(w)

Copy link
Member

Choose a reason for hiding this comment

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

I'm not convinced but maybe I need to play with it to get better understanding. It's my problem.

Copy link
Collaborator Author

@dmaskasky dmaskasky Dec 16, 2024

Choose a reason for hiding this comment

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

I made this graphic to help me reason about this better. Red is setD in this example.
image

@dmaskasky
Copy link
Collaborator Author

dmaskasky commented Dec 16, 2024

I think I figured out why this passes the peek test. Here's a better test.
This test also fails on main, but passes on fix/deep-peek. This is good to know, but I don't think this is something we want to fix.

it('can read in write function without changing dependencies', () => {
  const a = atom(0)
  let bReadCount = 0
  const b = atom(
    (get) => {
      ++bReadCount
      return get(a)
    },
    () => {},
  )
  let bMountCalled = false
  b.onMount = () => {
    bMountCalled = true
  }
  const c = atom((get) => get(a))
  const w = atom(null, (get, set) => {
    expect(bReadCount).toBe(0)
    get(b)
    expect(bReadCount).toBe(1)
    set(a, 1)
    expect(bReadCount).toBe(1)
  })
  const store = createStore()
  store.sub(c, () => {}) // mounts c,a
  store.set(w)
  
  expect(bMountCalled).toBe(false) // ✅ PASSES (should fail if b atomState.m is defined
  expect(bReadCount).toBe(1) // ❌ FAILS - received 2
  expect(getAtomState(b)!.m).toBeUndefined() // ✅ PASSES (could fail)
  expect(getAtomState(b)!.d.size).toBe(0) // ❌ FAILS - 1 (a atomState)
  expect(getAtomState(a)!.m!.d.has(b)).toBe(false) // ❌ FAILS - true
})

Copy link

pkg-pr-new bot commented Dec 17, 2024

Open in Stackblitz

More templates

npm i https://pkg.pr.new/jotai@2827

commit: c758a69

Copy link
Member

@dai-shi dai-shi left a comment

Choose a reason for hiding this comment

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

Thanks so much for your effort! This is a big improvement.

@dai-shi dai-shi added this to the v2.11.0 milestone Dec 18, 2024
@dai-shi dai-shi merged commit ee43134 into pmndrs:main Dec 18, 2024
42 checks passed
alexandresoro pushed a commit to alexandresoro/ouca that referenced this pull request Dec 23, 2024
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [jotai](https://github.com/pmndrs/jotai) | dependencies | minor | [`2.9.3` -> `2.11.0`](https://renovatebot.com/diffs/npm/jotai/2.9.3/2.11.0) |

---

### Release Notes

<details>
<summary>pmndrs/jotai (jotai)</summary>

### [`v2.11.0`](https://github.com/pmndrs/jotai/releases/tag/v2.11.0)

[Compare Source](pmndrs/jotai@v2.10.4...v2.11.0)

There are no public API changes, but some internal behaviors have been improved. Now, atom updates are batched in a single write, which might provide a performance benefit in certain edge cases. This feature has been requested actually for a long time, and it's finally implemented. See also [#&#8203;2782](pmndrs/jotai#2782).

#### What's Changed

-   refactor(store): rename pending to batch by [@&#8203;dai-shi](https://github.com/dai-shi) in pmndrs/jotai#2868
-   lazy recomputeDependents by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2827
-   fix(store): robust flush batch by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2871
-   fix(store): refactor batch priority by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2875
-   feat: dev store with unstable_derive by [@&#8203;dai-shi](https://github.com/dai-shi) in pmndrs/jotai#2852

#### New Contributors

-   [@&#8203;rainagalbiati-turngate](https://github.com/rainagalbiati-turngate) made their first contribution in pmndrs/jotai#2882
-   [@&#8203;leweyse](https://github.com/leweyse) made their first contribution in pmndrs/jotai#2883

**Full Changelog**: pmndrs/jotai@v2.10.4...v2.11.0

### [`v2.10.4`](https://github.com/pmndrs/jotai/releases/tag/v2.10.4)

[Compare Source](pmndrs/jotai@v2.10.3...v2.10.4)

A minor improvement for some edge cases. (For more information, see [#&#8203;2789](pmndrs/jotai#2789).)

#### What's Changed

-   fix(store): do not recompute unmounted atoms eagerly by [@&#8203;dai-shi](https://github.com/dai-shi) in pmndrs/jotai#2849

#### New Contributors

-   [@&#8203;rmillio](https://github.com/rmillio) made their first contribution in pmndrs/jotai#2832
-   [@&#8203;sukvvon](https://github.com/sukvvon) made their first contribution in pmndrs/jotai#2851

**Full Changelog**: pmndrs/jotai@v2.10.3...v2.10.4

### [`v2.10.3`](https://github.com/pmndrs/jotai/releases/tag/v2.10.3)

[Compare Source](pmndrs/jotai@v2.10.2...v2.10.3)

This fixes various edge cases. Huge thanks to [@&#8203;dmaskasky](https://github.com/dmaskasky) ! 🎉

#### What's Changed

-   fix: flushPending in async write by [@&#8203;dai-shi](https://github.com/dai-shi) in pmndrs/jotai#2804
-   fix: flush pending finally everywhere by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2818
-   fix: rethrow falsy errors thrown in flushPending by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2820
-   fix: setAtom uses stale pending on atom unmount by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2811
-   fix: onMount setSelf does not notify listeners by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2815
-   refactor(core): Use iterative approach in recompute dependents by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2821
-   refactor(store): prefer epoch number comparisons to indicate value change by [@&#8203;dmaskasky](https://github.com/dmaskasky) in pmndrs/jotai#2828

**Full Changelog**: pmndrs/jotai@v2.10.2...v2.10.3

### [`v2.10.2`](https://github.com/pmndrs/jotai/releases/tag/v2.10.2)

[Compare Source](pmndrs/jotai@v2.10.1...v2.10.2)

Fixed some jotai/utils for a regression in v2.10.0.

#### What's Changed

-   fix(unstable_derive): trap atom methods by [@&#8203;dai-shi](https://github.com/dai-shi) in pmndrs/jotai#2741
-   Throw error on `useAtom(undefined)` or `useAtom(null)` by [@&#8203;kevinschaich](https://github.com/kevinschaich) in pmndrs/jotai#2778
-   fix(utils): make 'loadable' update immediate after resolve by [@&#8203;e7h4n](https://github.com/e7h4n) in pmndrs/jotai#2790
-   fix(utils): make 'unwrap' update immediate after resolve by [@&#8203;organize](https://github.com/organize) in pmndrs/jotai#2794

#### New Contributors

-   [@&#8203;niklasbec](https://github.com/niklasbec) made their first contribution in pmndrs/jotai#2773
-   [@&#8203;romain-trotard](https://github.com/romain-trotard) made their first contribution in pmndrs/jotai#2781
-   [@&#8203;kretajak](https://github.com/kretajak) made their first contribution in pmndrs/jotai#2786
-   [@&#8203;Brokyeom](https://github.com/Brokyeom) made their first contribution in pmndrs/jotai#2798
-   [@&#8203;ryoku4](https://github.com/ryoku4) made their first contribution in pmndrs/jotai#2802
-   [@&#8203;yairEO](https://github.com/yairEO) made their first contribution in pmndrs/jotai#2805
-   [@&#8203;kevinschaich](https://github.com/kevinschaich) made their first contribution in pmndrs/jotai#2778
-   [@&#8203;e7h4n](https://github.com/e7h4n) made their first contribution in pmndrs/jotai#2790
-   [@&#8203;organize](https://github.com/organize) made their first contribution in pmndrs/jotai#2794

**Full Changelog**: pmndrs/jotai@v2.10.1...v2.10.2

### [`v2.10.1`](https://github.com/pmndrs/jotai/releases/tag/v2.10.1)

[Compare Source](pmndrs/jotai@v2.10.0...v2.10.1)

This fixes a bug in an extreme edge case. If you find this change breaks something, please report to us.

#### What's Changed

-   fix(core): recompute dependents in edge cases by [@&#8203;dai-shi](https://github.com/dai-shi) in pmndrs/jotai#2742

#### New Contributors

-   [@&#8203;vangie](https://github.com/vangie) made their first contribution in pmndrs/jotai#2753
-   [@&#8203;ts1994tw](https://github.com/ts1994tw) made their first contribution in pmndrs/jotai#2759
-   [@&#8203;KagamiChan](https://github.com/KagamiChan) made their first contribution in pmndrs/jotai#2761
-   [@&#8203;nguyenbry](https://github.com/nguyenbry) made their first contribution in pmndrs/jotai#2762
-   [@&#8203;jaycho46](https://github.com/jaycho46) made their first contribution in pmndrs/jotai#2766
-   [@&#8203;midzdotdev](https://github.com/midzdotdev) made their first contribution in pmndrs/jotai#2767

**Full Changelog**: pmndrs/jotai@v2.10.0...v2.10.1

### [`v2.10.0`](https://github.com/pmndrs/jotai/releases/tag/v2.10.0)

[Compare Source](pmndrs/jotai@v2.9.3...v2.10.0)

It comes with another significant internal change to address some edge cases.

Since v2.9.0, we've been working on some internal refactors to support more edge cases and clean up the code.

Users are encouraged to update to the new versions eventually, but if you're satisfied with the current situation and prefer to avoid temporary instability, you can stick with v2.8.4 for now.

#### What's Changed

-   breaking(core): avoid continuable promise in store api by [@&#8203;dai-shi](https://github.com/dai-shi) in pmndrs/jotai#2695

#### New Contributors

-   [@&#8203;sphinxrave](https://github.com/sphinxrave) made their first contribution in pmndrs/jotai#2653
-   [@&#8203;mxthxngx](https://github.com/mxthxngx) made their first contribution in pmndrs/jotai#2712
-   [@&#8203;hoangvu12](https://github.com/hoangvu12) made their first contribution in pmndrs/jotai#2716
-   [@&#8203;YuHyeonWook](https://github.com/YuHyeonWook) made their first contribution in pmndrs/jotai#2734

**Full Changelog**: pmndrs/jotai@v2.9.3...v2.10.0

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOS41Ny40IiwidXBkYXRlZEluVmVyIjoiMzkuODIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.tristess.app/alexandresoro/ouca/pulls/380
Reviewed-by: Alexandre Soro <[email protected]>
Co-authored-by: renovate <[email protected]>
Co-committed-by: renovate <[email protected]>
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