Repository navigation
fix: deliver shared signal changes hidden by the session snapshot - #27177
totally-not-ai[bot] wants to merge 27 commits into
Conversation
While the session is locked, shared signal reads come from a snapshot taken at the first read. An effect that started listening against that snapshot, either when its component was attached or when it was created later in the same request, missed a change made by another thread in the meantime and kept showing the old value. Such a change is now delivered in a new access task, which runs with a fresh snapshot before the response is written. Fixes #27160
Queue the deferred listener on the session so it still runs when the UI is closed in the meantime, and run it right away for transactions that don't defer, which keeps their old behaviour.
Type of change
Why this approach
API changes// com.vaadin.flow.signals.impl.Transaction
// Added
public static Transaction createWriteThrough(SerializableExecutor freshReadExecutor)
public void runWithFreshReads(Runnable task) // default runs the task right away |
|
Added tests for the paths that were not covered: delivery when there is no current UI or the UI closes before delivery, a listener removed before delivery, and an explicit write-through transaction, which keeps listening for later changes. Each test fails if its path breaks. |
|
|
|
I'm not sure about the abstraction level used for this fix. If each access tasks has its own transaction, then I imagine it would be enough to make sure the effect's change processing logic kicks in also in this case since that logic should be run as a new access task that thus sees the updated values. |
|
@Legioth I tried that: drop the new
So some piece has to know that the change is hidden and move the re-run to a new access. Today that is the usage, which asks the transaction for a context with fresh reads. The other place is the effect:
I'd keep 1, but 2 is a reasonable fit if you'd rather keep this in the effect. Tell me which one and I'll update the PR. |
|
The main architectural mismatch is maybe that a transaction has to know anything about how to run a tasks outside that transaction. That seems like something that would be more related to the effect instead. Would it be feasible to move only that part of the logic while keeping the rest? |
A transaction should not need to know how to run a task outside itself. The usage still detects a change that the current transaction hides, but it now asks the listener for a context with fresh reads instead of the transaction. Effect provides that context by queuing a new session access, so the session-scoped transaction and VaadinSession no longer take part in delivering the change. Listeners that don't provide such a context keep the previous behaviour and are only notified of later changes. The tests that used a plain usage listener under a session lock now use an effect, since a plain listener no longer gets the deferred delivery.
A listener wrapper that doesn't delegate runWithFreshReads hides the wrapped listener's context, so the cached signal usage wrapper now forwards it like the combined usage does, and the TransientListener Javadoc says wrappers should delegate. The removed-listener case is now tested at the usage level, since a disposed effect never re-runs regardless of whether the deferred registration is added. Also covers an effect whose hidden change has no locked session to defer to.
|
@Legioth Yes, I moved that part to the effect and kept the rest.
Now that the effect starts the deferred delivery, it could also mark that re-run so that |
…nge-hidden-by-session-snapshot
Covers a computed signal whose cache the other thread never refreshes, the effect re-running with its UI as the current UI, a fresh-read task that runs while the change is still hidden, and removing a listener after its deferred registration was added.
|
Make |
The re-run that delivers a change hidden by the session snapshot runs in a new access with the owner UI as the current UI, so it looked like a change made by that UI. The change was made by another thread, so the effect now marks the re-run explicitly and isBackgroundChange() returns true for it.
Also words the comments as a change made outside the session transaction, since that is what the flag tracks; usually that is another thread.
|
@Legioth Done. The re-run that delivers a hidden change now reports
|
Memory footprintNo change compared with the base commit f61c209. |
|
|
|
Is it so that the initial read when the effect is created leaves no listeners behind which means that the "concurrent" write doesn't deliver any updates. This in turn means that detection of the situation would have to happen when reading for the attach? Would it be a valid approach to always put all attach reads in a separate Alternatively, could |
|
@Legioth Yes, that's what happens. The probe run of a detached element passivates the effect right away, so no listener is left on the tree, and the other thread's Always running the attach in a separate
Having So I see three options:
I'd go with 1 or 2. Let me know which one you prefer. |
|
Yet another brainstorming idea: could the logic that starts listening for changes detect that the listener was added from a context that sees a stale value and in that case schedule a listener invocation to be scheduled in a way that uses |
|
@Legioth That's close to what the PR does now. The listener-adding logic in Two differences from your sketch:
I lean towards 1, because it keeps |
|
Semantically, the thread where the view is created should perceive things as though the signal write happened exactly at the moment when the shadowing transaction ended. The automatic read transaction is closed between access tasks which means that the effect listener would be notified at a time when there's no current UI which in turn means that the change would be applied as a new access task. Would it work to collect a quite of pending notifications on the transaction instance and then release them at a stage where no custom dispatching logic is needed? |
|
@Legioth Yes, I think that works, and it fits the semantics better: the transaction keeps a queue of listeners that were added while it hid a newer value, and releases them when it ends. Releasing one means adding the listener again outside the transaction, the same re-listen the usage does now, so a listener that wants to keep listening still ends up registered. The Three things to settle:
If you're fine with 2, I'll rework the PR to this approach. |
|
Is there any way of making the ui dispatcher do |
|
Would a locked session but no current UI work as av indication that access should skip the executor dispatcher? |
|
@Legioth Yes to both, with a slightly narrower condition: "the current thread holds the lock of this UI's session" rather than "a session is locked and there's no current UI".
Combined with your transaction-queue idea, that gives same-round-trip delivery without any custom dispatching:
That removes the |
|
Du it |
A listener added while the current transaction hides a newer value is now queued on that transaction and added again when the transaction ends, as if the change had happened at that moment. Explicit transactions release the queue when runInTransaction returns. The session releases the queue of its session-scoped transaction without a current UI before pending access tasks run, after each of them and when it is unlocked. Since there is no current UI when a released listener fires, the effect re-run reports a background change by itself. The UI effect dispatcher queues the re-run with ui.access directly when the current thread already holds that UI's session lock, instead of going through the effect dispatcher thread, so it is run before the response is written. This replaces the fresh read hook on TransientListener and the fresh read dispatcher of Effect, so those and their tests are removed.
A failing deferred listener no longer stops the remaining ones from being added again or leaves the stale session transaction in place: the session clears its transaction before releasing the listeners, and each end task's exception goes to the thread's uncaught exception handler. Also documents that the owner of a fallback transaction must release its end tasks, and covers the release when the next access task starts and a UI that is detached before the release.
|
@Legioth Done. The PR now uses the transaction queue plus the
|
SignalTree.observeNextChange now checks whether the current transaction shows an older version of the observed node than the tree, and in that case notifies the observer once the transaction has been finalized instead of only waiting for later changes. This replaces the same check in the shared signal usage, so every observer of a tree gets it. Renames the transaction hooks to runAfterFinalize and finalizeTransaction after what they mean, catches any exception from a finalize task, and lets the session clear its transaction instead of only running its finalize tasks, so that finalizing always means the transaction no longer applies.
The observer released when a transaction is finalized is now checked again against the finalizing context, notified with immediate set to true since the change happened before it was added, and added back to the tree under the same lock so that a concurrent change isn't missed. Documents the deferred path on observeNextChange and covers a hidden list insert, a hidden change that was reverted, a fresh read after the access tasks have run and a failing finalize task.
runAfterFinalize now returns a registration that removes the task, so a deferred observer only needs a small holder guarded by the tree lock instead of a separately synchronized registration. Adding an observer and adding a released one share the same code path, and the check is renamed to hasHiddenChange. finalizeTransaction runs all tasks and then rethrows the first exception with the others suppressed. runInTransaction keeps the exception of its own task and adds a finalize failure to it as suppressed, and the session passes a failure to its error handler after clearing its transaction.
…nge-hidden-by-session-snapshot # Conflicts: # flow-server/src/main/java/com/vaadin/flow/dom/ElementEffect.java
Hold a deferred observer's registration in an AtomicReference where null means removed, and keep it removed when the observer removes itself while it is notified after the transaction ends; it used to stay in the tree and get notified again. Keep finalize tasks in an ArrayDeque so that running them doesn't shift the list each time, assert that a transaction isn't finalized while it is current, and let the session handle any exception from finalizing its transaction.
| if (finalizeTask != null) { | ||
| Registration registration = observe(nodeId, observer, true); | ||
| // The observer may have been removed while it was notified | ||
| if (!current.compareAndSet(finalizeTask, registration)) { |
There was a problem hiding this comment.
The atomic operation makes this more difficult to understand than necessary. Checking for current.get() == null would be easier to understand and should be just as correct since current is also protected by the lock.
There was a problem hiding this comment.
@Legioth Agreed. The finalize task now checks current.get() == null after notifying the observer: if it is null, the observer was removed meanwhile and the new registration is removed; otherwise it is stored. The returned registration likewise uses get() and set(null) instead of getAndSet. The AtomicReference is now only a mutable holder guarded by the tree lock, as the comment above it says.
The holder is only accessed while holding the tree lock, so the atomic compare-and-set adds nothing over a null check.
|



Fixes #27160
Behavior deviation · flow-server · apps that change shared signals from threads other than the request thread
Background — session snapshot. While a session is locked, shared signal reads come from a write-through transaction that keeps returning the values it first read. A change made by another thread becomes visible once that transaction is cleared, which happens before each pending access task and when the lock is released.
When another thread changed a shared signal during a request, a binding attached later in that request, or an effect created later in it, kept showing the old value until the next change. Such a listener is now held back until the transaction that hides the change ends, and is then added again as if the change had happened at that moment. For a UI, that means a new access task that runs before the response is written, so the browser gets one update in the same round trip. The workaround was to make the change through
access.Risks:
EffectContext.isBackgroundChange()as true for that re-run. Before, they never saw the change.ui.accessdirectly instead of going through the effect dispatcher thread. This also means a change made in one UI's request reaches another UI of the same session in the same round trip.com.vaadin.flow.signals.impl:Transaction.runAfterFinalize(Runnable), which returns aRegistrationfor removing the task, andTransaction.finalizeTransaction(), which runs all tasks and then rethrows the first exception with the others suppressed.Transaction.runInTransactioncan thus throw from a failing deferred observer after the transaction has applied its changes; if the transaction task itself threw, that exception is thrown with the finalize failure added as suppressed. Code that installs its own transaction fallback withTransaction.setTransactionFallbackmust finalize that transaction when it stops providing it; otherwise observers deferred on it are never notified.SignalTree.observeNextChangecan now notify an observer when the current transaction is finalized, if that transaction hid a newer version of the node.VaadinService.runPendingAccessTasksnow always clears the session-scoped transaction, also when no access task is queued. Shared signal reads after it, e.g. afterUI.push()in an access block or while the response is written, see the latest values.Context. #24400 cleared the snapshot before access tasks. That fixed effects that were already listening, because the tree notifies them on the writer's thread. A listener added after the change compared against the same stale snapshot and then only waited for future changes, so it never saw the change that had already happened.
SignalTree.observeNextChangechecks, under the tree lock, whether the current transaction shows an older version of the node than the tree. If so, it registers a task withTransaction.runAfterFinalize. When the transaction is finalized, the observer is notified as if the node had changed at that moment, and added back to the tree if it asks to keep listening, all under the tree lock. If an outer transaction still hides the change, the observer is deferred again until that one is finalized.Transaction.runInTransactionfinalizes its transaction when it returns.VaadinSessionfinalizes its session-scoped transaction whenever it clears it, outside any transaction and without a current UI: at the start ofrunPendingAccessTasks, before each access task, when the access queue runs empty, and on unlock. If a deferred observer fails, the session passes the exception to its error handler after clearing the transaction.ElementEffect's dispatcher then queues the re-run withui.access, because the current thread already holds the session lock, and the running drain loop picks it up before the response is written.Working on behalf of @Legioth