Dependency graph and timing?

I’m probably doing something wrong, but I don’t understand what it is…

I have a cell with a top-level Generator a that is presumably getting updated each frame by Observable. I have a second cell with a top-level value b that depends on a.

If it takes less than one frame (~15 ms) for a to update, then everything seems fine. If it takes longer than one frame for a to update, then a gets updated, but b never does.

I’ve constructed a minimal example to demonstrate this:

https://observablehq.com/d/9d2740b41c8211ff

(Note that I’ve used Mutables to try to make it clear what is and isn’t getting updated, but I don’t think the underlying effect on updating depends on the presence of Mutables.)

Your add method isn’t assigning to history.value, which looks wrong; that will mutate the value but not trigger cells with reference history to run. You typically want to use copy-on-write semantics instead, like history.value = history.value.concat(foo) instead of direct mutation. (Confusing, perhaps, but even with mutables you want values to be immutable!)

I think the real problem here is that you are mutating the counter (via increment) and reacting to it in the same cell, which means that your a generator is constantly interrupting itself. It would be better to read the counter value non-reactively, say by having the increment function return the new value.

Like so:

const a = async function*(duration) {
  while (true) {
    await Promises.delay(duration);
    yield increment() * 100;
  }
}(duration);

Thank you!

Indeed, the second problem does seem to be the real culprit here. I was both modifying the value of the Mutable and then explicitly using the value of the Mutable in the same cell.

If I understand it correctly:
If we call the cell defining the Mutable “Cell M” and the cell modifying and using the value of the Mutable “Cell U”, I was creating a situation where “Cell U” precedes “Cell M” in the dependency graph because it is causing the value of the Mutable to change, but then “Cell U” follows “Cell M” in the dependency graph because it depends on the value of the Mutable. While this wasn’t generating an error, it was causing strange temporally sensitive dependencies.

The take aways are:

  1. Use “copy-on-write” semantics when setting the value of a Mutable in a “hook”. Or, to put it another way, in the “hook” for a Mutable, make sure you are assigning a new value to <Mutable>.value and not just changing the internal contents.
  2. Don’t call a hook for a Mutable and directly access the value of the Mutable in the same cell. (If you need the value of the Mutable after calling the hook, then return it from the hook!)

Does this sound about right?

(Here is a new fork of the notebook with those changes made and everything behaving properly:

https://observablehq.com/d/115bfac93accaee3

)