[p5.js 2.0+ Bug Report]: p5.strands loop-carried variables can read values overwritten earlier in the same iteration
Most appropriate sub-area of p5.js?
- [ ] Accessibility
- [ ] Color
- [ ] Core/Environment/Rendering
- [ ] Data
- [ ] DOM
- [ ] Events
- [ ] Image
- [ ] IO
- [ ] Math
- [ ] Typography
- [ ] Utilities
- [ ] WebGL
- [ ] WebGPU
- [x] p5.strands
- [ ] Build process
- [ ] Unit testing
- [ ] Internationalization
- [ ] Friendly errors
- [ ] Other (specify if possible)
p5.js version
2.4.0-rc.5
Web browser and version
Google Chrome 152
Operating system
Fedora Linux
Steps to reproduce this
Steps
- Use two loop-carried values inside a p5.strands hook.
- Swap them inside a
forloop. - Use the result for the output color.
filterColor.begin();
let a = 0.25;
let b = 0.75;
for (let i = 0; i < 1; i++) {
const t = a;
a = b;
b = t;
}
filterColor.set([a, b, 0, 1]);
filterColor.end();
Expected
a = 0.75
b = 0.25
roughly [191, 64, 0].
Actual
a = 0.75
b = 0.75
roughly [191, 191, 0], with no error.
I can reproduce the same ordering issue with rotations and Fibonacci-style updates. It happens on WebGL and WebGPU on 2.4.0-rc.5, current main (8831d5baf), and 2.3.4.
The ordering is already present before backend-specific code generation, so this seems to be in the loop-carried state handling.
I'd be happy to work on a fix if this is confirmed.
hey @davepagurek, looks like @Pcmhacker-hero has opened #9383 before assignment again, similar to what happened on #9327. could you clarify who should take this one?
Hi @bhabishnu thanks for flagging. The account has now been permanently suspended, for repeated violations of expectations despite plenty of warnings.
Thanks @bhabishnu! Do you want to take a look and see what part of the flow is not working? Normally assignment order is preserved, is this because in the transpiled js, loops involve returning an object with changed properties? I would still expect in that case the assignments and their order to be preserved beforehand.
ok actually I think I see the problem. This is what the code transpiles into:
filterColor.begin();
let a = 0.25;
let b = 0.75;
{
const __block_2 = __p5.strandsFor(() => {
return 0;
}, loopVar0 =>
(__p5.strandsNode(loopVar0).lessThan(1)), loopVar0 => {
return loopVar0 = __p5.strandsNode(loopVar0).add(1);
}, (loopVar0, vars) => {
let __copy_a_0 = vars.a.copy();
let __copy_b_1 = vars.b.copy();
const t = __copy_a_0;
__copy_a_0 = __copy_b_1;
__copy_b_1 = t;
return {
'a': __copy_a_0,
'b': __copy_b_1
};
}, {
'a': __p5.strandsNode(a),
'b': __p5.strandsNode(b)
});
a = __block_2.a;
b = __block_2.b;
}
debugger;
filterColor.set(__p5.strandsNode([
a,
b,
0,
1
]));
filterColor.end();
This looks correct given what we wrote before, but is subtly incorrect, because we are actually working with numbers. The original js code in your example is semantically correct for numbers, where assignment essentially creates a new copy, but it would be incorrect with objects. In our transpiled strands code, numbers ARE actually objects, but we aren't changing anything about how the assignment switching works.
So it looks like we want to transpile it into essentially const t = __copy_a_0.copy().
The question, I think, is how often do we want to do that? The more often we do it, the safer it is, but possibly some of our existing assignments, like +=, don't need it. Maybe we do it for any straight-assignment we see? What do you think @bhabishnu?
@davepagurek I’m not sure the current .copy() fixes this one. It keeps the same node underneath, so const t = a.copy() still seems to generate the same broken swap.
From what I can tell, the issue is when StrandsFor writes the carried values back one by one, so a later one can end up reading something that’s already been updated. I can get the same thing with += too, so I don’t think it’s just straight assignment.
Maybe the safer approach is to evaluate all the next values first, then write them back together? That feels simpler than trying to detect which ones depend on each other, but happy to go with whatever fits the design better.
I think this is more general than just StrandsFor, assignment to varyings seem to have the same problem.
Generally, the problem seems to be that we're sharing references to some mutable states, when elsewhere in the code, we treat nodes as references to VALUES in the original js (see all the state diagrams in https://github.com/processing/p5.js/blob/main/contributor_docs/p5.strands.md#the-program-graph). So that's why my mind went to making sure that these different values are treated differently. I think you're right that it's not limited to assignment, but I think generally we need a way to differentiate these states. I see that a .copy() already exists and returns a new object but doesn't necessarily have a new id, but I was thinking more about the p5.Vector .copy(), which works a little differently. Maybe something like a .copyToNewNode() that forces it to be its own variable in the output. Possibly longer term .copy() should just do that, and the version that doesn't reassign the id would be the special case? But it's kinda a broad change and I suspect there are things that that might break if we do, especially around varyings.
One compromise idea from that:
- make a method to copy to a new node and output variable (have to connect this to the code generator backends somehow)
- before assigning any phi node in a for loop, and every helper state update, copy the values to a new variable
- also return a new copy when we read a varying
...which I think would work but also still leaves us in a state where "an id in the graph refers to a specific snapshot of the value" because varyings are the exception, but at least what you read out of a varying would have that property.
ok, taking a step back. I think your idea could also work. If I'm understanding it correctly, this would be in the code generation? Where we have to tread for loop phi node assignments special and assign them to temporary variables in the GLSL/WGSL and then assign them back? And presumably do something similar for varyings, do you have thoughts on what that would have to look like?
Anyway sorry for the long reply -- this is an interesting case and I want to make sure we navigate it carefully. I think since this is a complex part of the codebase we want to make sure we can have these "theorems" we can say about what the code models, and one of them, that ids represent distinct values, seems to not actually be true right now, which is why things don't work. So I'm trying to balance the work of keeping that theorem and making the codebase match, or finding a new theorem that's still simple enough to let people reason about it. I think either of the two approaches could work here, e.g. "every id represents a different value snapshot, and varying objects are just GENERATORS of nodes with those ids, not really in the same system" in what I was describing. If we push all the handling to the code generator phase, it feels like we could come up with some similarly simple theorems maybe, so lmk if you have thoughts on what those could be, it's definitely worth considering!
@davepagurek thanks for the detailed reply, this helped a lot. The varying example especially made me rethink the shape of the problem.
I tried a few similar cases, and I think the cleanest rule is that an id should always represent a value that won’t change, while anything writable is more like a location. Reading one gives you a value at that point, and later writes shouldn’t change what that earlier read meant.
I tried a small internal snapshot node around that idea. For loops, the body snapshots the carried values at the start of each iteration, and GLSL/WGSL just emit those as locals. That fixed the swap, compound assignment, break, helper state, and your varying example in the cases I tried, and the existing p5.Shader tests still passed on both backends.
I’d lean toward keeping that in the shared graph rather than making each backend track whether a read crossed a later write. I also tried making .copy() create a new shader value, but it seems to be doing a different job and broke a few existing cases, so I’d probably leave that as-is.
The two things I’m still unsure about are whether you’d prefer loop snapshots at the start of the body or just before writeback, and for vector varyings, whether const old = v; v.x = 1 should leave old unchanged or keep the current object-like behaviour.
I don't have a super strong opinion on where in the loop it should be, let me know if you have any thoughts either way, if one feels more natural.
From the p5 programmer's point of view, do want to keep the behaviour of glsl where updating a swizzle updates the original object. Internally, it can be a new object/id/etc once we update a swizzle.
I think snapshotting at the start of the body feels more natural after trying both.
They behaved the same in the cases I tested on WebGL and WebGPU, but with the body-entry version each iteration just works from the values it started with, then the end of the body or a break writes the results back. The order of those writes stops mattering.
The writeback version works too, but every exit path has to remember to buffer the user variables and helper state together first, which feels easier to trip over later if we add something like continue. It also seems closer to how if already works internally.
ok that sounds good to me then!