holoviz/panel · #9070

perf: Batch scheduled model updates and combine held events linearly

philippjfr · merged Nov 14, 20267 files · 442 + / 68 −
panel/io/document.py225 + / 65 −
@@ -13,6 +13,7 @@ import typing as t import weakref +from collections import deque from contextlib import ExitStack, contextmanager, nullcontext from functools import partial, wraps from weakref import WeakKeyDictionary@@ -21,18 +22,20 @@ from bokeh.document.document import Document from bokeh.document.events import (     DocumentChangedEvent, DocumentPatchedEvent, MessageSentEvent,-    SessionCallbackAdded, SessionCallbackRemoved,+    ModelChangedEvent, SessionCallbackAdded, SessionCallbackRemoved,+    TitleChangedEvent, ) from bokeh.model import Model from bokeh.model.util import (     collect_models, visit_value_and_its_immediate_references, ) from bokeh.models import CustomJS+from bokeh.server.session import _needs_document_lock_on_loop  from ..config import config from .loading import _loading_css_classes from .model import monkeypatch_events  # noqa: F401 API import-from .state import state+from .state import set_curdoc, state  if t.TYPE_CHECKING:     from asyncio.futures import Future@@ -57,10 +60,16 @@  GC_DEBOUNCE = 5 _HOLD_LOCK: WeakKeyDictionary[Document, threading.Lock] = WeakKeyDictionary()+# The policy requested for a hold Panel established; the Document itself+# always collects, see _hold_doc.+_HOLD_POLICY: WeakKeyDictionary[Document, HoldPolicyType] = WeakKeyDictionary() _WRITE_FUTURES: WeakKeyDictionary[Document, list[Future]] = WeakKeyDictionary()-_WRITE_EVENTS: WeakKeyDictionary[Document, list[EventBatch]] = WeakKeyDictionary()+_WRITE_EVENTS: WeakKeyDictionary[Document, deque[EventBatch]] = WeakKeyDictionary() _WRITE_BLOCK: WeakKeyDictionary[Document, bool] = WeakKeyDictionary()+_WRITE_LOCK = threading.Lock() _UNCONNECTED_EVENTS: WeakKeyDictionary[Document, list[DocumentChangedEvent]] = WeakKeyDictionary()+_SCHEDULED_UPDATES: WeakKeyDictionary[Document, deque[Callable[[], t.Any]]] = WeakKeyDictionary()+_SCHEDULED_UPDATES_LOCK = threading.Lock()  _panel_last_cleanup = None _write_tasks: WeakKeyDictionary[Document, list[asyncio.Task]] = WeakKeyDictionary()@@ -104,6 +113,59 @@ def _cleanup_task(doc: Document, task: asyncio.Task) -> None:     if tasks and task in tasks:         tasks.remove(task) +def _hold_doc(doc: Document, policy: HoldPolicyType = 'combine') -> None:+    """+    Puts the Document on hold. Bokeh's 'combine' policy scans all held+    events for every new one, which is quadratic in the number of+    distinct changes, so the Document always collects and the events are+    combined when they are released, see ``_combine_events``.+    """+    _HOLD_POLICY[doc] = policy+    doc.hold('collect')++def _combine_events(events: Iterable[DocumentChangedEvent]) -> list[DocumentChangedEvent]:+    """+    Merges events that set the same model property, or the title, into+    the first such event, which ends up carrying the last value and+    callback invoker, exactly as bokeh's 'combine' hold policy does, but+    in linear time.+    """+    combined: list[DocumentChangedEvent] = []+    index: dict[tuple[t.Any, ...], int] = {}+    for event in events:+        if isinstance(event, ModelChangedEvent) and getattr(event, 'hint', None) is None:+            key: tuple[t.Any, ...] = (+                ModelChangedEvent, event.model.id, event.attr, id(event.setter), id(event.document)+            )+        elif isinstance(event, TitleChangedEvent):+            key = (TitleChangedEvent, id(event.setter), id(event.document))+        else:+            combined.append(event)+            continue+        position = index.get(key)+        if position is None:+            index[key] = len(combined)+            combined.append(event)+            continue+        first = combined[position]+        if isinstance(event, ModelChangedEvent):+            first.new = event.new  # type: ignore[attr-defined]+        else:+            first.title = event.title  # type: ignore[attr-defined]+        first.callback_invoker = event.callback_invoker+    return combined++def _take_held_events(doc: Document) -> list[DocumentChangedEvent]:+    """+    Removes the events held on the Document and returns them, combined+    unless the hold was requested with the 'collect' policy.+    """+    events = list(doc.callbacks._held_events or [])+    doc.callbacks._held_events = []+    if _HOLD_POLICY.pop(doc, 'combine') == 'combine':+        events = _combine_events(events)+    return events+ def _client_has_document(doc: Document) -> bool:     """     Whether the client was sent the Document, after which held events@@ -278,6 +340,45 @@ async def _await_writes(futures: Iterable[Future]) -> None:         except Exception as e:             logger.warning(f"Failed sending message due to following error: {e}") +def _log_task_exception(task: asyncio.Task) -> None:+    if task.cancelled():+        return+    if (exception := task.exception()) is not None:+        logger.error("Error thrown from callback:", exc_info=exception)++def _track_task(doc: Document, task: asyncio.Task) -> None:+    _write_tasks.setdefault(doc, []).append(task)+    task.add_done_callback(partial(_cleanup_task, doc))++@_needs_document_lock_on_loop+def _run_with_document_lock(session: ServerSession, func: Callable[..., t.Any], *args, **kwargs) -> t.Any:+    return func(*args, **kwargs)++def _schedule_locked(doc: Document, func: Callable[..., t.Any], *args, **kwargs) -> None:+    """+    Runs ``func`` on the server event loop while holding the Document+    lock, awaiting its result if it is a coroutine. Unlike a next tick+    callback the function is not offloaded to a worker thread first+    and scheduling it emits no session callback events.+    """+    session = getattr(doc.session_context, 'session', None)+    loop = state._document_loop(doc)+    asyncio_loop = t.cast(+        'asyncio.AbstractEventLoop | None', getattr(loop, 'asyncio_loop', loop)+    )+    if session is None or asyncio_loop is None:+        doc.add_next_tick_callback(partial(func, *args, **kwargs))+        return++    def start() -> None:+        task = asyncio.ensure_future(+            _run_with_document_lock(session, func, *args, **kwargs), loop=asyncio_loop+        )+        _track_task(doc, task)+        task.add_done_callback(_log_task_exception)++    asyncio_loop.call_soon_threadsafe(start)+ def _dispatch_write_task(doc, func, *args, **kwargs):     """     Schedules tasks that write messages to the socket.@@ -288,11 +389,9 @@ def _dispatch_write_task(doc, func, *args, **kwargs):         # No running loop on this thread (e.g. a callback offloaded to a         # worker thread by Bokeh); avoid creating the coroutine here         # since there is nothing to await it, and reschedule instead.-        doc.add_next_tick_callback(partial(func, *args, **kwargs))+        _schedule_locked(doc, func, *args, **kwargs)         return-    task = loop.create_task(func(*args, **kwargs))-    _write_tasks.setdefault(doc, []).append(task)-    task.add_done_callback(partial(_cleanup_task, doc))+    _track_task(doc, loop.create_task(func(*args, **kwargs)))  def _is_write_locked(conn: ServerConnection) -> bool:     return _is_write_blocked(conn._socket)@@ -365,42 +464,51 @@ def _apply_json_patch(*args, **kwargs):  async def _dispatch_msgs(doc):     """-    Serializes and writes batches of events to the sockets, ensuring-    that the write_lock is not set, otherwise re-schedules the write-    task on the event loop.--    The events are serialized here, i.e. at write time, and not when-    they were scheduled. Bokeh tracks which models a client has already-    been sent as part of the Document, so serializing a patch declares-    the models it defines as synced. Serializing eagerly and writing-    later would therefore allow a message that was serialized after-    ours (e.g. one Bokeh itself dispatches at the end of a locked-    callback) to be written first, referencing models the client has-    not been sent yet.+    Serializes and writes the queued batches of events to the sockets+    in order, waiting for each socket's write lock rather than writing+    while something else is writing to it. Only one dispatcher runs per+    Document, draining batches queued while it was writing, so the+    order the batches were scheduled in is preserved.++    The events are serialized here, i.e. at write time while holding+    the write lock, and not when they were scheduled. Bokeh tracks which+    models a client has already been sent as part of the Document, so+    serializing a patch declares the models it defines as synced.+    Serializing eagerly and writing later would therefore allow a+    message that was serialized after ours (e.g. one Bokeh itself+    dispatches at the end of a locked callback) to be written first,+    referencing models the client has not been sent yet.     """-    if doc not in _WRITE_BLOCK:-        return-    futures: list[Future] = []-    batches = _WRITE_EVENTS.pop(doc, [])-    while batches:-        connections, events = batches[0]-        if any(_is_write_locked(conn) for conn in connections):-            break-        batches.pop(0)-        futures += write_events(doc, connections, events, run=False)-    if futures:-        if doc in _WRITE_FUTURES:-            _WRITE_FUTURES[doc] += futures-        else:-            _WRITE_FUTURES[doc] = futures-        await _run_write_futures(doc)-    if not batches:-        if doc in _WRITE_BLOCK:-            del _WRITE_BLOCK[doc]-        return-    _WRITE_EVENTS[doc] = batches + _WRITE_EVENTS.get(doc, [])-    await asyncio.sleep(0.01)-    _dispatch_write_task(doc, _dispatch_msgs, doc)+    while True:+        with _WRITE_LOCK:+            batches = _WRITE_EVENTS.get(doc)+            if not batches or doc not in _WRITE_BLOCK:+                if not batches:+                    _WRITE_EVENTS.pop(doc, None)+                _WRITE_BLOCK.pop(doc, None)+                return+            connections, events = batches[0]+            # Consecutive batches for the same connections share a message+            merged = 1+            while merged < len(batches) and batches[merged][0] == connections:+                events = events + batches[merged][1]+                merged += 1+        try:+            message = None+            for conn in connections:+                lock = getattr(conn._socket, 'write_lock', None)+                with (await lock.acquire()) if lock is not None else nullcontext():+                    if message is None:+                        message = conn.protocol.create('PATCH-DOC', events)+                    await _await_writes(_socket_dispatcher(conn._socket)(conn, msg=message))+        except Exception as e:+            logger.warning(f"Failed sending message due to following error: {e}")+        finally:+            with _WRITE_LOCK:+                # The destroyed document already dropped its queue+                if _WRITE_EVENTS.get(doc) is batches:+                    for _ in range(merged):+                        batches.popleft()  def _garbage_collect():     if (new_time:= time.monotonic()-_panel_last_cleanup) < GC_DEBOUNCE:@@ -449,9 +557,13 @@ def _destroy_document(self, session):         cb.stop()      # Cancel any pending write tasks for this document-    _WRITE_EVENTS.pop(self, None)-    _WRITE_BLOCK.pop(self, None)+    with _WRITE_LOCK:+        _WRITE_EVENTS.pop(self, None)+        _WRITE_BLOCK.pop(self, None)     _UNCONNECTED_EVENTS.pop(self, None)+    _HOLD_POLICY.pop(self, None)+    with _SCHEDULED_UPDATES_LOCK:+        _SCHEDULED_UPDATES.pop(self, None)     for future in _WRITE_FUTURES.pop(self, []):         future.cancel()     for task in _write_tasks.pop(self, []):@@ -521,6 +633,46 @@ def write_events(         doc.add_next_tick_callback(partial(_run_write_futures, doc))  # type: ignore[arg-type]     return futures +def schedule_model_update(doc: Document, callback: Callable[[], t.Any]) -> None:+    """+    Queues a model update that may only be applied while the Document+    lock is held, e.g. one made from a thread that does not own it, and+    schedules one locked callback per Document that applies all queued+    updates and writes them in a single message.+    """+    with _SCHEDULED_UPDATES_LOCK:+        pending = _SCHEDULED_UPDATES.get(doc)+        if pending is None:+            _SCHEDULED_UPDATES[doc] = pending = deque()+        pending.append(callback)+        schedule = len(pending) == 1+    if not schedule:+        return+    try:+        _schedule_locked(doc, _apply_scheduled_updates, doc)+    except Exception:+        with _SCHEDULED_UPDATES_LOCK:+            _SCHEDULED_UPDATES.pop(doc, None)+        raise++def _apply_scheduled_updates(doc: Document) -> None:+    with _SCHEDULED_UPDATES_LOCK:+        pending = _SCHEDULED_UPDATES.pop(doc, None)+    if not pending:+        return+    errors: list[Exception] = []+    with set_curdoc(doc):+        # Every queued update is written, so updates to the same property+        # must not be combined into the last one.+        with unlocked(policy='collect'):+            for callback in pending:+                try:+                    callback()+                except Exception as e:+                    errors.append(e)+        for error in errors:+            state._handle_exception(error)+ def schedule_write_events(     doc: Document,     connections: Iterable[ServerConnection],@@ -532,10 +684,15 @@ def schedule_write_events(     thread. The events are serialized by ``_dispatch_msgs`` when they     are actually written.     """-    # Set up write locks-    _WRITE_BLOCK[doc] = True-    _WRITE_EVENTS[doc] = batches = _WRITE_EVENTS.get(doc, [])-    batches.append((list(connections), events))+    with _WRITE_LOCK:+        batches = _WRITE_EVENTS.get(doc)+        if batches is None:+            _WRITE_EVENTS[doc] = batches = deque()+        batches.append((list(connections), events))+        if doc in _WRITE_BLOCK:+            # The running dispatcher drains the queue+            return+        _WRITE_BLOCK[doc] = True     _dispatch_write_task(doc, _dispatch_msgs, doc)  def create_doc_if_none_exists(doc: Document | None) -> Document:@@ -658,6 +815,14 @@ def dispatch_django(         ])     return futures +def _release_held_events(doc: Document) -> None:+    """+    Releases a hold established by ``hold`` on a worker thread, letting+    bokeh dispatch the (combined) events it collected.+    """+    doc.callbacks._held_events = _suppress_property_callbacks(_take_held_events(doc))+    doc.unhold()+ def _suppress_property_callbacks(     events: list[DocumentChangedEvent] ) -> list[DocumentChangedEvent]:@@ -746,8 +911,7 @@ def _flush_events(curdoc: Document, session: ServerSession) -> None:             locked = True             break -    events = list(curdoc.callbacks._held_events or [])-    curdoc.callbacks._held_events = []+    events = _take_held_events(curdoc)     monkeypatch_events(events)      if (@@ -839,7 +1003,7 @@ def unlocked(policy: HoldPolicyType = 'combine') -> Iterator:         monkeypatch_events(curdoc.callbacks._held_events)         return -    curdoc.hold(policy=policy)+    _hold_doc(curdoc, policy)     try:         yield     finally:@@ -912,13 +1076,13 @@ def hold(                 with hold_lock:                     held = doc.callbacks.hold_value                     if not held:-                        doc.hold(policy)+                        _hold_doc(doc, policy)                         we_held = True                 yield             else:                 with unlocked(policy=policy):                     if not doc.callbacks.hold_value:-                        doc.hold(policy)+                        _hold_doc(doc, policy)                     yield         finally:             if policy is None:@@ -931,32 +1095,25 @@ def hold(                         # Without a server loop a next tick callback never                         # runs, so the hold has to be released right away.                         with hold_lock:-                            _suppress_property_callbacks(doc.callbacks._held_events)-                            doc.unhold()+                            _release_held_events(doc)                     else:                         def _unhold(lock=hold_lock, doc=doc):                             with lock:-                                _suppress_property_callbacks(doc.callbacks._held_events)-                                doc.unhold()-                        with hold_lock:-                            # Clear the hold around scheduling the callback-                            # so the SessionCallbackAdded event it emits is-                            # dispatched rather than collected by the hold-                            # it is releasing.-                            doc.callbacks._hold = None-                            doc.add_next_tick_callback(_unhold)-                            doc.callbacks._hold = policy+                                _release_held_events(doc)+                        _schedule_locked(doc, _unhold)             elif held:                 doc.callbacks._hold = held             elif comm is not None:                 from .notebook import push                  # Release the hold so events bokeh is still dispatching are not collected                 doc.callbacks._hold = None+                doc.callbacks._held_events = _take_held_events(doc)                 push(doc, comm)             elif not _client_has_document(doc):                 _dispatch_events(doc, _drain_unconnected_events(doc, hold_lock))             else:+                doc.callbacks._held_events = _take_held_events(doc)                 doc.unhold()  @contextmanager@@ -980,12 +1137,15 @@ def immediate_dispatch(doc: Document | None = None):      old_events = doc.callbacks._held_events     held = doc.callbacks._hold+    policy = _HOLD_POLICY.pop(doc, None)     doc.callbacks._held_events = []     doc.callbacks.unhold()     with unlocked():         yield     doc.callbacks._hold = held     doc.callbacks._held_events = old_events+    if policy is not None:+        _HOLD_POLICY[doc] = policy  def _immediate_references(value: t.Any) -> list[Model]:     # Layout children are flat lists of models, which bokeh's generic
panel/io/state.py6 + / 1 −
@@ -992,7 +992,12 @@ def execute(             future.add_done_callback(self._handle_future_exception)         elif param.parameterized.iscoroutinefunction(callback):             param.parameterized.async_executor(callback)-        elif doc and doc.session_context and (schedule == True or (schedule == 'auto' and not self._unblocked(doc))):+        elif doc and doc.session_context and schedule == True:+            # Explicitly scheduled callbacks update models, so they are+            # batched into one locked callback writing a single message.+            from .document import schedule_model_update+            schedule_model_update(doc, callback)+        elif doc and doc.session_context and schedule == 'auto' and not self._unblocked(doc):             doc.add_next_tick_callback(self._handle_exception_wrapper(callback, doc))         else:             try:
panel/models/icon.ts2 + / 0 −
@@ -144,6 +144,8 @@ export class ClickableIconView extends ControlView {       this.icon_view.remove()       this.icon_view = icon_view       this.was_svg_icon = is_svg_icon+      // The size may have changed while the new icon view was built+      this.update_size()       this.update_cursor()       // We need to re-append the new icon view to the DOM       this.row_div.insertBefore(this.icon_view.el, this.label_el)
panel/tests/io/test_document.py161 + / 2 −
@@ -684,7 +684,7 @@ async def test_schedule_write_events_defers_serialization():         assert written == []          # Release the socket and let the write task drain the queue-        conn._socket.write_lock._block._value = 1+        conn._socket.write_lock.release()         await asyncio.sleep(0.05)          assert len(conn.protocol.created) == 1@@ -715,7 +715,7 @@ async def test_schedule_write_events_defers_on_asgi_socket():         assert conn.protocol.created == []         assert written == [] -        conn._socket.write_lock._lock._locked = False+        conn._socket.write_lock._lock.release()         await asyncio.sleep(0.05)          assert len(conn.protocol.created) == 1@@ -1169,3 +1169,162 @@ def test_freeze_doc_unchanged_properties_do_not_freeze(recompute_count):         root.width = 100      assert not recompute_count+++def test_combine_events_matches_bokeh_combine_policy():+    """+    Holding with 'collect' and combining on release must produce the+    same events as bokeh's quadratic 'combine' policy.+    """+    import copy+    import random++    from bokeh.document.callbacks import _combine_document_events+    from bokeh.document.events import RootAddedEvent, TitleChangedEvent+    from bokeh.models import Div++    from panel.io.document import _combine_events++    rng = random.Random(1)+    doc = Document()+    models = [Div() for _ in range(5)]+    setters = [None, object()]+    events = []+    for _ in range(500):+        r = rng.random()+        if r < 0.85:+            events.append(ModelChangedEvent(+                doc, rng.choice(models), rng.choice(['text', 'visible']),+                rng.random(), setter=rng.choice(setters), callback_invoker=object()+            ))+        elif r < 0.95:+            events.append(TitleChangedEvent(doc, str(rng.random()), setter=rng.choice(setters)))+        else:+            events.append(RootAddedEvent(doc, rng.choice(models)))++    expected = []+    for event in events:+        _combine_document_events(copy.copy(event), expected)+    combined = _combine_events(events)++    def signature(event):+        return (+            type(event), getattr(event, 'model', None), getattr(event, 'attr', None),+            getattr(event, 'new', None), getattr(event, 'title', None),+            event.setter, event.callback_invoker,+        )++    assert len(combined) < len(events)+    assert [signature(e) for e in combined] == [signature(e) for e in expected]+++def test_hold_collects_and_combines_on_release():+    """+    Panel holds the Document with the 'collect' policy and combines the+    events when it releases the hold, so only the last value of a+    property set repeatedly inside the hold is dispatched.+    """+    doc = Document()+    doc.callbacks._change_callbacks[None] = lambda e: e+    model = IntSlider().get_root(doc)+    doc.add_root(model)+    state._connected[doc] = True++    dispatched = []+    doc.on_change(dispatched.append)++    with set_curdoc(doc):+        with hold(doc):+            assert doc.callbacks.hold_value == 'collect'+            for i in range(1, 11):+                model.value = i+            assert len(doc.callbacks._held_events) == 10++    assert doc.callbacks.hold_value is None+    assert [(e.attr, e.new) for e in dispatched] == [('value', 10)]+++@pytest.mark.asyncio+async def test_dispatch_msgs_merges_queued_batches_into_one_message():+    """+    Batches queued while the socket was busy are written in one message+    once it is released, in the order they were queued.+    """+    written = []+    extra_socket_handlers[_FakeSocket] = lambda conn, msg=None: written.append(msg) or []++    class RecordingProtocol(_FakeProtocol):+        def create(self, msgtype, events):+            self.created.append(list(events))+            return self.created[-1]++    try:+        doc = Document()+        conn = _FakeConn(lock_held=True)+        conn.protocol = RecordingProtocol()+        first, second = object(), object()++        schedule_write_events(doc, [conn], [first])+        schedule_write_events(doc, [conn], [second])+        await asyncio.sleep(0.05)++        assert len(_write_tasks[doc]) == 1+        assert conn.protocol.created == []++        conn._socket.write_lock.release()+        await asyncio.sleep(0.05)++        assert conn.protocol.created == [[first, second]]+        assert written == conn.protocol.created+        assert doc not in _WRITE_BLOCK+    finally:+        extra_socket_handlers.pop(_FakeSocket, None)+        _WRITE_BLOCK.pop(doc, None)+++@pytest.mark.xdist_group(name="server")+def test_scheduled_updates_from_thread_are_batched_without_loss(threads, monkeypatch):+    """+    Updates made from a thread that does not hold the document lock are+    applied by a single locked callback and written in one message,+    with every intermediate value, in order.+    """+    slider = IntSlider()++    serve_and_request(slider)+    wait_until(lambda: bool(slider._documents))++    doc, model = list(slider._documents.items())[0]+    session = doc.session_context.session+    monkeypatch.setitem(state._loaded, doc, True)+    monkeypatch.setitem(state._connected, doc, True)++    messages = []+    conn = _FakeConn(lock_held=False)+    conn.protocol = Protocol()+    monkeypatch.setattr(session, '_subscribed_connections', {conn})+    monkeypatch.setitem(+        extra_socket_handlers, _FakeSocket,+        lambda conn, msg=None: messages.append(msg) or []+    )++    n = 50+    expected = list(range(1, n + 1))++    def update():+        with set_curdoc(doc):+            for value in expected:+                slider.value = value++    state._thread_pool.submit(update).result(timeout=5)++    def values():+        return [+            event['new'] for msg in messages for event in msg.content['events']+            if event['kind'] == 'ModelChanged' and event['attr'] == 'value'+        ]++    wait_until(lambda: len(values()) >= n)+    assert values() == expected+    assert len(messages) < n+    assert model.value == n
panel/tests/ui/io/test_document.py27 + / 0 −
@@ -170,3 +170,30 @@ def cb(event):      expect(page.locator('.markdown')).to_have_text('Running', timeout=1500)     expect(page.locator('.markdown')).to_have_text('Done')+++def test_threaded_periodic_updates_reach_client_without_loss(page, threads):+    """+    A periodic callback running on the thread pool updates a different+    widget on every tick. The updates are applied by locked callbacks+    the pool thread does not own, which must neither drop nor merge+    them, so every widget ends up showing its own value.+    """+    n = 20+    panes = [Markdown('pending', css_classes=[f'target-{i}']) for i in range(n)]+    ticks = {'i': 0}++    def cb():+        i = ticks['i']+        ticks['i'] += 1+        panes[i].object = f'value {i}'++    def app():+        state.onload(lambda: state.add_periodic_callback(cb, period=1, count=n))+        return Column(*panes)++    serve_component(page, app)++    for i in range(n):+        expect(page.locator(f'.target-{i}')).to_have_text(f'value {i}')+    wait_until(lambda: ticks['i'] == n, page)
panel/tests/widgets/test_input.py14 + / 0 −
@@ -341,6 +341,20 @@ def test_text_input_set_value_none(widget_type, document, comm):     assert widget.value == ''     assert widget.value_input == '' +def test_text_input_value_syncs_value_input_in_one_update(document, comm):+    text = TextInput(value='ABC')+    text.get_root(document, comm=comm)++    # A Python-side value change carries value_input in the same update,+    # a frontend change leaves value_input to the frontend+    assert text._process_param_change({'value': 'X'}) == {'value': 'X', 'value_input': 'X'}+    text._param__private.syncing.add('value')+    try:+        assert text._process_param_change({'value': 'X'}) == {'value': 'X'}+    finally:+        text._param__private.syncing.discard('value')++ def test_text_input_value_input_synced_with_value(document, comm):     text = TextInput(value='ABC') 
panel/widgets/input.py7 + / 0 −
@@ -76,6 +76,13 @@ def __init__(self, **params):         )      def _process_param_change(self, params: dict[str, t.Any]) -> dict[str, t.Any]:+        if (+            'value' in params and 'value_input' not in params and+            'value' not in self._param__private.syncing+        ):+            # _sync_value_input updates the parameter afterwards, syncing+            # the model here sends both in one message.+            params = dict(params, value_input=params['value'])         params = super()._process_param_change(params)         # The bokeh model only accepts str, None renders as an empty input         for key in ('value', 'value_input'):