holoviz/panel · #9101

fix: Do not echo frontend changes released by a hold back to their client

philippjfr · merged Nov 16, 20263 files · 113 + / 6 −
panel/io/jupyter_executor.py2 + / 1 −
@@ -27,7 +27,7 @@ from ..util import edit_readonly from .application import build_single_handler_application from .resources import Resources-from .server import server_html_page_for_session+from .server import _skip_patch_connection, server_html_page_for_session from .state import set_curdoc, state  if t.TYPE_CHECKING:@@ -54,6 +54,7 @@ class JupyterServerSession(ServerSession):      _tasks: set[asyncio.Task] = set() +    @_skip_patch_connection     def _document_patched(self, event: DocumentPatchedEvent) -> None:         may_suppress = event.setter is self         connections = [
panel/io/server.py46 + / 5 −
@@ -796,17 +796,58 @@ def wrapper(self, *args, **kwargs):     wrapper._panel_tracks_lock = True  # type: ignore[attr-defined]     return wrapper ++def _tag_held_patch_events(func):+    """+    Records the connection a patch was received on on the frontend+    changes it leaves held on the Document. Bokeh only skips the+    originating connection while the patch is being applied, so when a+    hold dispatches the change later it would otherwise be echoed back+    to the client and revert anything changed there since.+    """+    @wraps(func)+    async def wrapper(self, message, connection):+        try:+            return await func(self, message, connection)+        finally:+            for event in list(self.document.callbacks._held_events):+                if getattr(event, 'setter', None) is self and getattr(event, '_panel_patch_connection', None) is None:+                    event._panel_patch_connection = connection+    return wrapper+++def _skip_patch_connection(document_patched):+    @wraps(document_patched)+    def wrapper(self, event):+        connection = getattr(event, '_panel_patch_connection', None)+        if connection is None:+            return document_patched(self, event)+        current = self._current_patch_connection+        self._current_patch_connection = connection+        try:+            return document_patched(self, event)+        finally:+            self._current_patch_connection = current+    wrapper._panel_skips_patch_connection = True  # type: ignore[attr-defined]+    return wrapper+ # Record which context holds the document lock so state._unblocked can # tell the holder apart from other threads while the lock is taken. if not getattr(ServerSession.with_document_locked.__wrapped__, '_panel_tracks_lock', False):  # type: ignore[attr-defined]     ServerSession.with_document_locked = _needs_document_lock(  # type: ignore[method-assign]         _track_document_lock(ServerSession.with_document_locked.__wrapped__)  # type: ignore[attr-defined]     )-    for _method in ('_handle_push', '_handle_patch'):-        setattr(ServerSession, _method, _needs_document_lock_on_loop(-            _track_document_lock(getattr(ServerSession, _method).__wrapped__)-        ))-    del _method+    ServerSession._handle_push = _needs_document_lock_on_loop(  # type: ignore[method-assign]+        _track_document_lock(ServerSession._handle_push.__wrapped__)  # type: ignore[attr-defined]+    )+    ServerSession._handle_patch = _needs_document_lock_on_loop(  # type: ignore[method-assign]+        _track_document_lock(_tag_held_patch_events(ServerSession._handle_patch.__wrapped__))  # type: ignore[attr-defined]+    )++if not getattr(ServerSession._document_patched, '_panel_skips_patch_connection', False):+    ServerSession._document_patched = _skip_patch_connection(  # type: ignore[method-assign]+        ServerSession._document_patched+    )   # Patch Server to attach task factory to asyncio loop and handle Admin server context
panel/tests/io/test_document.py65 + / 0 −
@@ -613,6 +613,71 @@ def callback():     assert received == []  +@pytest.mark.xdist_group(name="server")+def test_frontend_patch_applied_while_held_is_not_echoed():+    """+    A client patch applied while a worker thread holds the Document is+    collected by the hold and dispatched when it is released, after the+    patch has finished. It must still reach Python, but must not be sent+    back to the connection it came from, where it would overwrite+    anything the user typed since, e.g. dropping characters from a text+    input on a high latency connection.+    """+    slider = IntSlider()++    serve_and_request(slider)+    wait_until(lambda: bool(slider._documents))++    doc, model = list(slider._documents.items())[0]+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop+    state._connected[doc] = True++    class Connection:+        protocol = Protocol()++        def __init__(self):+            self.values = []++        async def send_message(self, message):+            if message.msgtype == 'PATCH-DOC':+                self.values += [+                    event['new'] for event in message.content['events']+                    if event.get('attr') == 'value'+                ]++        def ok(self, message):+            return None++    origin, other = Connection(), Connection()+    session.subscribe(origin)+    session.subscribe(other)++    patch = Protocol().create('PATCH-DOC', [ModelChangedEvent(doc, model, 'value', 5)])++    def worker():+        with set_curdoc(doc), hold(doc):+            asyncio.run_coroutine_threadsafe(+                session._handle_patch(patch, origin), asyncio_loop+            ).result(timeout=5)+            assert doc.callbacks.hold_value++    try:+        thread = threading.Thread(target=worker)+        thread.start()+        thread.join()++        wait_until(lambda: slider.value == 5 and not doc.callbacks.hold_value)+        # Leave time for an echo to be written+        time.sleep(0.2)+    finally:+        session.unsubscribe(origin)+        session.unsubscribe(other)++    assert origin.values == []+    assert other.values == [5]++ def test_suppress_property_callbacks_keeps_frontend_changes():     doc = Document()     model = IntSlider().get_root(doc)