Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
3f662e2
fix: deliver shared signal changes hidden by the session snapshot
totally-not-ai[bot] Nov 23, 2026
d3e6516
fix: keep hidden change delivery when the UI closes first
totally-not-ai[bot] Nov 23, 2026
e6bca54
test: cover hidden change delivery without UI and in explicit transac…
totally-not-ai[bot] Nov 23, 2026
780185f
test: cover closed UI and removed listener for hidden change delivery
totally-not-ai[bot] Nov 23, 2026
d4297d0
fix: check fresh read executor argument explicitly
totally-not-ai[bot] Nov 23, 2026
1421d9d
refactor: let the effect run hidden change delivery in a new access
totally-not-ai[bot] Nov 26, 2026
98c8eb7
fix: forward fresh read context through cached signal usages
totally-not-ai[bot] Nov 26, 2026
73df7d3
Merge remote-tracking branch 'origin/main' into fix/shared-signal-cha…
totally-not-ai[bot] Nov 26, 2026
8b6bb07
test: cover more paths of hidden change delivery
totally-not-ai[bot] Nov 26, 2026
197e6f9
fix: report hidden change re-runs as background changes
totally-not-ai[bot] Nov 26, 2026
11658ce
test: check that only the delivered re-run is a background change
totally-not-ai[bot] Nov 26, 2026
7b611d2
refactor: let ElementEffect decide how hidden changes reach an access
totally-not-ai[bot] Nov 26, 2026
fe401f4
test: cover a hidden change at a detached element's first run
totally-not-ai[bot] Nov 26, 2026
3f2e931
fix: check new effect dispatcher arguments and log skipped delivery
totally-not-ai[bot] Nov 26, 2026
cb8891d
test: check that a null fresh read dispatcher is rejected
totally-not-ai[bot] Nov 26, 2026
883b017
refactor: defer hidden signal changes until the transaction ends
totally-not-ai[bot] Nov 26, 2026
aec9f4f
fix: keep releasing deferred signal listeners when one fails
totally-not-ai[bot] Nov 26, 2026
bb6ec88
refactor: detect hidden signal changes when observing the tree
totally-not-ai[bot] Nov 27, 2026
cfb07b3
fix: notify a deferred tree observer under the tree lock
totally-not-ai[bot] Nov 27, 2026
f7d75ff
refactor: simplify deferred tree observers and rethrow finalize errors
totally-not-ai[bot] Nov 27, 2026
8b71c56
test: cover a failing finalize task after a successful transaction
totally-not-ai[bot] Nov 27, 2026
9f9a3ee
Merge remote-tracking branch 'origin/main' into fix/shared-signal-cha…
totally-not-ai[bot] Nov 30, 2026
32de531
Merge main into fix/shared-signal-change-hidden-by-session-snapshot
totally-not-ai[bot] Dec 1, 2026
1a92eaf
refactor: address review of deferred tree observers
totally-not-ai[bot] Dec 1, 2026
cf73d0a
docs: clarify the deferred observer registration comment
totally-not-ai[bot] Dec 1, 2026
28f951f
Merge main into fix/shared-signal-change-hidden-by-session-snapshot
totally-not-ai[bot] Dec 1, 2026
26e1765
refactor: use plain null checks for deferred observer registration
totally-not-ai[bot] Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.vaadin.flow.function.SerializableExecutor;
import com.vaadin.flow.function.SerializableFunction;
import com.vaadin.flow.server.ErrorEvent;
import com.vaadin.flow.server.VaadinSession;
import com.vaadin.flow.shared.Registration;
import com.vaadin.flow.signals.DeniedSignalUsageException;
import com.vaadin.flow.signals.EffectContext;
Expand Down Expand Up @@ -273,9 +274,15 @@ private void enableEffect(UI ui) {
.error(new ErrorEvent(e, elem.getNode()));

SerializableExecutor uiDispatcher = command -> {
VaadinSession session = ui.getSession();
if (ui.getInternals().isCurrentAndLocked()) {
// Run immediately if on the same UI with its session locked
command.run();
} else if (session != null && session.hasLock()) {
// This thread already holds the lock, so access only queues
// the task to run before the lock is released, without
// locking another session or blocking
ui.access(command::run);
} else {
SignalEnvironment.getDefaultEffectDispatcher().execute(() -> {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2769,6 +2769,10 @@ public void ensureAccessQueuePurged(VaadinSession session) {
public void runPendingAccessTasks(VaadinSession session) {
session.checkHasLock();

// Signal listeners deferred by the session-scoped transaction may queue
// access tasks to run below when it is finalized
session.clearSessionScopedTransaction();

if (session.getPendingAccessQueue().isEmpty()) {
return;
}
Expand All @@ -2779,8 +2783,7 @@ public void runPendingAccessTasks(VaadinSession session) {
Map<Class<?>, CurrentInstance> oldInstances = CurrentInstance
.getInstances();
try {
while ((pendingAccess = session.getPendingAccessQueue()
.poll()) != null) {
while ((pendingAccess = pollPendingAccess(session)) != null) {
if (!pendingAccess.isCancelled()) {
CurrentInstance.clearAll();
CurrentInstance.setCurrent(session);
Expand All @@ -2807,6 +2810,20 @@ public void runPendingAccessTasks(VaadinSession session) {
}
}

/*
* Polls the next pending access task. When the queue is empty, the
* session-scoped transaction of the last task is first cleared, since
* signal listeners that it has deferred may queue more tasks.
*/
private static FutureAccess pollPendingAccess(VaadinSession session) {
FutureAccess next = session.getPendingAccessQueue().poll();
if (next == null) {
session.clearSessionScopedTransaction();
next = session.getPendingAccessQueue().poll();
}
return next;
}

/**
* Adds a service destroy listener that gets notified when this service is
* destroyed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -757,11 +757,38 @@ Transaction getOrCreateSessionScopedTransaction() {
* Clears the session-scoped transaction so that the next signal operation
* will create a fresh transaction with up-to-date values.
* <p>
* The cleared transaction is finalized outside any transaction and without
* a current UI. Signal listeners that it has deferred because it kept
* returning an old value after another thread changed a shared signal are
* thus notified as if that change had been made by another thread at this
* moment. An effect of a UI in this session then queues an access task that
* is run before the lock is released. An exception from a deferred listener
* is passed to the error handler of this session.
* <p>
* The session lock must be held when calling this method.
*/
void clearSessionScopedTransaction() {
assert hasLock();
Transaction transaction = sessionScopedTransaction;
sessionScopedTransaction = null;
if (transaction == null) {
return;
}
Map<Class<?>, CurrentInstance> oldInstances = CurrentInstance
.getInstances();
CurrentInstance.clearAll();
CurrentInstance.setCurrent(this);
try {
Transaction.runWithoutTransaction(transaction::finalizeTransaction);
} catch (Exception e) {
getErrorHandler().error(new ErrorEvent(e));
} finally {
CurrentInstance.clearAll();
CurrentInstance.restoreInstances(oldInstances);
}
// Signals don't use the transaction fallback while running without a
// transaction, so finalizing doesn't create a new session transaction
assert sessionScopedTransaction == null;
}

/**
Expand Down Expand Up @@ -844,7 +871,7 @@ public void unlock() {
}
}
}
sessionScopedTransaction = null;
clearSessionScopedTransaction();
this.lastUnlocked = System.currentTimeMillis();
}
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@
package com.vaadin.flow.signals.impl;

import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

import org.jspecify.annotations.Nullable;

import com.vaadin.flow.function.SerializableSupplier;
import com.vaadin.flow.shared.Registration;
import com.vaadin.flow.signals.SignalCommand;
import com.vaadin.flow.signals.function.TransactionTask;
import com.vaadin.flow.signals.function.ValueSupplier;
Expand All @@ -45,6 +48,8 @@
* @since 25.1
*/
public abstract class Transaction implements Serializable {
private transient @Nullable ArrayDeque<Runnable> finalizeTasks;

/**
* Creates a new transaction.
*/
Expand Down Expand Up @@ -203,6 +208,11 @@ abstract Transaction create(Transaction outer)
* <p>
* The supplier should return <code>null</code> if no fallback is available
* for the current context (e.g. no session lock is held).
* <p>
* The code that provides a fallback transaction owns it and must finalize
* it with {@link #finalizeTransaction()} when it stops providing it, since
* signal listeners that are added while the transaction hides a change are
* only notified at that point.
*
* @param fallback
* the fallback supplier, or <code>null</code> to remove the
Expand Down Expand Up @@ -323,6 +333,7 @@ public static boolean inExplicitTransaction() {

Transaction inner = transactionType.create(outer);
currentTransaction.set(inner);
RuntimeException failure = null;
try {
T value = transactionTask.supply();
TransactionOperation<T> op = new TransactionOperation<>(value);
Expand All @@ -333,13 +344,28 @@ public static boolean inExplicitTransaction() {
} catch (RuntimeException e) {
inner.rollback();

failure = e;
throw e;
} finally {
if (previousThreadLocal == null) {
currentTransaction.remove();
} else {
currentTransaction.set(previousThreadLocal);
}
finalizeAfterRun(inner, failure);
}
}

private static void finalizeAfterRun(Transaction transaction,
@Nullable RuntimeException failure) {
try {
transaction.finalizeTransaction();
} catch (RuntimeException e) {
if (failure == null) {
throw e;
}
// Don't hide the exception from the transaction task
failure.addSuppressed(e);
}
}

Expand Down Expand Up @@ -490,6 +516,79 @@ public void include(SignalTree tree, SignalCommand command,
*/
public abstract TreeRevision read(SignalTree tree);

/**
* Registers a task to run once this transaction has been finalized, i.e.
* when it no longer applies to the code that runs on the thread. The task
* runs outside this transaction, in the context of the code that finalized
* it. This can be used to react to changes that this transaction hides
* because it keeps returning the values it first read.
* <p>
* A transaction run with {@link #runInTransaction} is finalized when that
* method returns. Other transactions are finalized by the code that owns
* them, with {@link #finalizeTransaction()}.
*
* @param task
* the task to run, not <code>null</code>
* @return a registration that can be used to remove the task before it has
* been run, not <code>null</code>
*/
public Registration runAfterFinalize(Runnable task) {
Objects.requireNonNull(task, "Task cannot be null");
synchronized (this) {
if (finalizeTasks == null) {
finalizeTasks = new ArrayDeque<>();
}
finalizeTasks.add(task);
}
return () -> {
synchronized (this) {
if (finalizeTasks != null) {
finalizeTasks.remove(task);
}
}
};
}

/**
* Finalizes this transaction, running the tasks registered with
* {@link #runAfterFinalize(Runnable)}. This is intended for the code that
* owns a transaction that isn't run with {@link #runInTransaction}, to be
* called once the transaction no longer applies to the code that runs on
* the thread. The caller must make sure that this transaction isn't the
Comment thread
Legioth marked this conversation as resolved.
Resolved
* current transaction while the tasks run.
* <p>
* All tasks are run even if some of them throw. The first exception is then
* rethrown, with any later ones added as suppressed exceptions, so that the
* caller can handle it after doing any necessary cleanup in a
* <code>finally</code> block.
*/
public void finalizeTransaction() {
assert currentTransaction.get() != this
: "Cannot finalize the current transaction";
RuntimeException failure = null;
Runnable task;
while ((task = pollFinalizeTask()) != null) {
try {
task.run();
} catch (Exception e) {
if (failure == null) {
failure = e instanceof RuntimeException runtimeException
? runtimeException
: new IllegalStateException(e);
} else {
failure.addSuppressed(e);
}
}
}
if (failure != null) {
throw failure;
}
}

private synchronized @Nullable Runnable pollFinalizeTask() {
return finalizeTasks != null ? finalizeTasks.poll() : null;
}

/**
* Commits any staged commands in this transaction.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,10 @@ public interface Usage extends Serializable {
/**
* Registers a listener that will be invoked the next time there's a
* change to the used value. If this usage already has changes, then the
* listener is invoked immediately.
* listener is invoked immediately. If the value has been changed in a
* way that the current transaction doesn't show, then the listener is
* instead notified once that transaction has been finalized, see
* {@link Transaction#runAfterFinalize(Runnable)}.
*
* @param listener
* the listener to use, not <code>null</code>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;

import org.jspecify.annotations.Nullable;
Expand All @@ -36,6 +37,7 @@
import com.vaadin.flow.signals.SignalCommand;
import com.vaadin.flow.signals.function.ValueSupplier;
import com.vaadin.flow.signals.impl.LeafLock;
import com.vaadin.flow.signals.impl.Transaction;
import com.vaadin.flow.signals.impl.TransientListener;
import com.vaadin.flow.signals.shared.impl.CommandsAndHandlers.CommandResultHandler;

Expand Down Expand Up @@ -256,6 +258,15 @@ protected SerializableRunnable wrapWithLock(SerializableRunnable action) {
* snapshot. The observer is removed when invoked and needs to be registered
* again if it's still relevant unless it returns <code>true</code>. It is
* safe to register the observer again from within the callback.
* <p>
* If the current transaction shows an older version of the node than the
* submitted snapshot, e.g. because it provides repeatable reads and the
* node has been changed outside it, then the observer is instead added once
* that transaction has been finalized, see
* {@link Transaction#runAfterFinalize(Runnable)}. At that point, it is
* invoked right away with <code>immediate</code> set to <code>true</code>,
* in the context of the code that finalized the transaction, as if the node
* had changed at that moment.
*
* @param nodeId
* the id of the node to observe, not <code>null</code>
Expand All @@ -270,9 +281,31 @@ public Registration observeNextChange(Id nodeId,
assert nodeId != null;
assert observer != null;

return observe(nodeId, observer, false);
}

/*
* Adds the observer, or defers it if the current transaction hides a change
* to the node. A deferred observer is notified right away once it is added,
* since the change happened before that. The tree lock is held so that a
* change between notifying and adding the observer isn't missed.
*/
private Registration observe(Id nodeId, TransientListener observer,
boolean notifyNow) {
Transaction transaction = Transaction.getCurrent();

return Objects.requireNonNull(getWithLock(() -> {
assert submitted().nodes().containsKey(nodeId);

if (hasHiddenChange(transaction, nodeId)) {
return observeAfterFinalize(transaction, nodeId, observer);
}

if (notifyNow && !observer.invoke(true)) {
return () -> {
};
}

List<TransientListener> list = observers.computeIfAbsent(nodeId,
ignore -> new ArrayList<>());

Expand All @@ -282,6 +315,53 @@ public Registration observeNextChange(Id nodeId,
}));
}

/*
* A transaction with repeatable reads, such as the one used while a session
* is locked, keeps returning the node it first read even after someone else
* has changed it. An observer added now would only learn about later
* changes and thus never about that one.
*/
private boolean hasHiddenChange(Transaction transaction, Id nodeId) {
return !transaction.read(this).data(nodeId)
.equals(submitted().data(nodeId));
}

/*
* Adds the observer once the transaction has been finalized, in the context
* that finalized it, and notifies it as if the change had happened at that
* moment. If an outer transaction still hides the change, the observer is
* deferred again until that one is finalized.
*/
private Registration observeAfterFinalize(Transaction transaction,
Id nodeId, TransientListener observer) {
assert lock.isHeldByCurrentThread();

/*
* Holds the registration of the finalize task until the transaction has
* been finalized, then the registration of the observer in the tree,
* and null once removed. Only accessed while holding the tree lock.
*/
AtomicReference<@Nullable Registration> current = new AtomicReference<>();
current.set(transaction.runAfterFinalize(() -> runWithLock(() -> {
if (current.get() != null) {
Registration registration = observe(nodeId, observer, true);
// The observer may have been removed while it was notified
if (current.get() == null) {
registration.remove();
} else {
current.set(registration);
}
}
})));
return wrapWithLock(() -> {
Registration registration = current.get();
if (registration != null) {
current.set(null);
registration.remove();
}
})::run;
}

/**
* Notify all observers that are affected by changes between two snapshots.
* All notified observers are removed. It is safe for an observer to
Expand Down
Loading