holoviz/panel · #9105

fix: Order unlocked writes after the changes of the document lock holder

philippjfr · merged Nov 18, 20263 files · 699 + / 14 −
panel/io/document.py243 + / 9 −
@@ -45,6 +45,7 @@      from bokeh.core.enums import HoldPolicyType     from bokeh.core.has_props import HasProps+    from bokeh.core.types import ID     from bokeh.protocol.message import Message     from bokeh.server.connection import ServerConnection     from bokeh.server.session import ServerSession@@ -70,12 +71,27 @@ _UNCONNECTED_EVENTS: WeakKeyDictionary[Document, list[DocumentChangedEvent]] = WeakKeyDictionary() _SCHEDULED_UPDATES: WeakKeyDictionary[Document, deque[Callable[[], t.Any]]] = WeakKeyDictionary() _SCHEDULED_UPDATES_LOCK = threading.Lock()+# Events held back until another context releases the document lock+_DEFERRED_EVENTS: WeakKeyDictionary[Document, list[DocumentChangedEvent]] = WeakKeyDictionary()+# Messages serialized but not yet written to the client+_UNWRITTEN: WeakKeyDictionary[Document, list[_Unwritten]] = WeakKeyDictionary()  _panel_last_cleanup = None _write_tasks: WeakKeyDictionary[Document, list[asyncio.Task]] = WeakKeyDictionary()  extra_socket_handlers: dict[type, Callable[..., Sequence[Future]]] = {} +@dataclasses.dataclass(eq=False)+class _Unwritten:+    """+    The models a message serialized but not yet written defines (or may+    define) and the properties it changes.+    """++    models: set[ID]+    changes: set[tuple[str, str]]++ @dataclasses.dataclass class Request:     headers : dict@@ -354,9 +370,185 @@ def _track_task(doc: Document, task: asyncio.Task) -> None:     _write_tasks.setdefault(doc, []).append(task)     task.add_done_callback(partial(_cleanup_task, doc)) +@contextmanager+def _owning_document_lock(session: ServerSession) -> Iterator[None]:+    """+    Marks the calling context as holding the session's document lock and+    first writes the events other contexts held back while it was taken+    by someone else, so they precede the changes made under this lock.+    """+    with state._own_document_lock(session):+        if session.document in _DEFERRED_EVENTS:+            try:+                _dispatch_deferred_events(session.document)+            except Exception:+                logger.exception('Failed to dispatch deferred events')+        yield++def _run_owning_document_lock(session: ServerSession, func: Callable[..., t.Any], *args, **kwargs) -> t.Any:+    with _owning_document_lock(session):+        result = func(*args, **kwargs)+    if inspect.isawaitable(result):+        awaiting = _await_owning_document_lock(session, result)+        if inspect.iscoroutine(result):+            # Bokeh closes the callback's coroutine if it is cancelled+            # before awaiting it, which only reaches ours.+            weakref.finalize(awaiting, result.close)+        return awaiting+    return result++async def _await_owning_document_lock(session: ServerSession, awaitable: t.Awaitable) -> t.Any:+    with state._own_document_lock(session):+        return await awaitable+ @_needs_document_lock_on_loop def _run_with_document_lock(session: ServerSession, func: Callable[..., t.Any], *args, **kwargs) -> t.Any:-    return func(*args, **kwargs)+    return _run_owning_document_lock(session, func, *args, **kwargs)+++def _unsent_models(doc: Document) -> set[Model]:+    # Copied in one step, since the lock holder may add to it meanwhile+    return set(getattr(doc.models, '_new_models', ()))++def _event_target(event: DocumentChangedEvent) -> Model | None:+    model = getattr(event, 'model', None)+    if model is None and isinstance(event, MessageSentEvent):+        model = getattr(event.msg_data, 'model', None)+    return model if isinstance(model, Model) else None++def _change_key(event: DocumentChangedEvent) -> tuple[str, str] | None:+    model, attr = getattr(event, 'model', None), getattr(event, 'attr', None)+    if model is None or attr is None:+        return None+    return (model.id, attr)++def _track_unwritten(+    doc: Document, models: Iterable[ID], events: Iterable[DocumentChangedEvent]+) -> _Unwritten:+    changes = {key for event in events if (key := _change_key(event))}+    record = _Unwritten(set(models), changes)+    with _WRITE_LOCK:+        _UNWRITTEN.setdefault(doc, []).append(record)+    return record++def _untrack_unwritten(doc: Document, record: _Unwritten) -> None:+    with _WRITE_LOCK:+        records = _UNWRITTEN.get(doc, [])+        if record in records:+            records.remove(record)+        if not records:+            _UNWRITTEN.pop(doc, None)++async def _send_pending_patches_tracked(send_pending_patches, session: ServerSession, pending) -> None:+    """+    Tracks the changes a lock holder writes once its callback returned.+    Bokeh serializes them in a worker thread, so any model not yet sent+    when it starts may be defined by them.+    """+    doc = session.document+    unsent = [model.id for model in _unsent_models(doc)]+    record = _track_unwritten(doc, unsent, (patch.event for patch in pending))+    try:+        await send_pending_patches(session, pending)+    finally:+        _untrack_unwritten(doc, record)++def _refers_to(doc: Document, value: t.Any, ids: set[ID]) -> bool:+    """+    Whether serializing value refers to one of the models. Models the+    client has not been sent are serialized in full, so their references+    are followed, while any other model is only referenced.+    """+    unsent = _unsent_models(doc)+    seen: set[ID] = set()+    stack = _immediate_references(value)+    while stack:+        model = stack.pop()+        if model.id in ids:+            return True+        if model.id in seen or model not in unsent:+            continue+        seen.add(model.id)+        for attr in model.properties_with_refs():+            stack.extend(_immediate_references(getattr(model, attr, None)))+    return False++def _split_unknown_to_client(+    doc: Document, session: ServerSession, events: list[DocumentChangedEvent]+) -> tuple[list[DocumentChangedEvent], list[DocumentChangedEvent]]:+    """+    Splits off the events that must wait for changes another context+    has not written yet: changes to a model the client does not have,+    changes whose value refers to a model only an unwritten message+    defines, and changes to a property the unwritten changes also set,+    whose older value would otherwise overwrite the newer one.+    """+    with _WRITE_LOCK:+        records = list(_UNWRITTEN.get(doc, []))+        deferred = list(_DEFERRED_EVENTS.get(doc, []))+    pending = session._pending_writes or []+    if not (records or deferred or pending or _is_locked_elsewhere(session)):+        return events, []+    unsent = {model.id for model in _unsent_models(doc)}+    unwritten = set().union(*(record.models for record in records))+    changes = set().union(*(record.changes for record in records))+    changes |= {key for event in deferred if (key := _change_key(event))}+    changes |= {key for patch in list(pending) if (key := _change_key(patch.event))}+    immediate, held = [], []+    for event in events:+        model = _event_target(event)+        if isinstance(event, ModelChangedEvent):+            value = event.new+        elif isinstance(event, MessageSentEvent):+            value = event.msg_data+        else:+            value = None+        if (+            (model is not None and (model.id in unsent or model.id in unwritten)) or+            _change_key(event) in changes or+            (unwritten and value is not None and _refers_to(doc, value, unwritten))+        ):+            held.append(event)+        else:+            immediate.append(event)+    return immediate, held++def _is_locked_elsewhere(session: ServerSession) -> bool:+    """+    Whether a context other than the calling one holds the session's+    document lock.+    """+    lock = getattr(session, '_lock', None)+    return bool(lock is not None and lock.locked() and not state._document_lock_held)++def _defer_until_unlocked(doc: Document, events: list[DocumentChangedEvent]) -> None:+    """+    Holds back events until the context holding the document lock has+    released it, and with it written everything it changed.+    """+    events = _suppress_property_callbacks(events)+    with _WRITE_LOCK:+        if (deferred := _DEFERRED_EVENTS.get(doc)) is not None:+            deferred.extend(events)+            return+        _DEFERRED_EVENTS[doc] = list(events)+    # The next context taking the lock writes them first, this callback+    # only does so if no other context is waiting for the lock.+    _schedule_locked(doc, _dispatch_deferred_events, doc)++def _dispatch_deferred_events(doc: Document) -> None:+    with _WRITE_LOCK:+        events = _DEFERRED_EVENTS.pop(doc, [])+    session = getattr(doc.session_context, 'session', None)+    if not events or _is_destroyed(doc) or session is None:+        return+    with set_curdoc(doc):+        if doc.callbacks.hold_value:+            doc.callbacks._held_events += events+            return+        _hold_doc(doc, 'collect')+        doc.callbacks._held_events += events+        _flush_events(doc, session)  def _schedule_locked(doc: Document, func: Callable[..., t.Any], *args, **kwargs) -> None:     """@@ -565,6 +757,8 @@ def _destroy_document(self, session):     with _WRITE_LOCK:         _WRITE_EVENTS.pop(self, None)         _WRITE_BLOCK.pop(self, None)+        _DEFERRED_EVENTS.pop(self, None)+        _UNWRITTEN.pop(self, None)     _UNCONNECTED_EVENTS.pop(self, None)     _HOLD_POLICY.pop(self, None)     with _SCHEDULED_UPDATES_LOCK:@@ -853,12 +1047,17 @@ def _suppress_property_callbacks(     return events  async def _write_message(-    doc: Document, connections: list[ServerConnection], message: Message+    doc: Document, connections: list[ServerConnection], message: Message,+    record: _Unwritten | None = None ) -> None:-    for conn in connections:-        lock = getattr(conn._socket, 'write_lock', None)-        with (await lock.acquire()) if lock is not None else nullcontext():-            await _await_writes(_socket_dispatcher(conn._socket)(conn, msg=message))+    try:+        for conn in connections:+            lock = getattr(conn._socket, 'write_lock', None)+            with (await lock.acquire()) if lock is not None else nullcontext():+                await _await_writes(_socket_dispatcher(conn._socket)(conn, msg=message))+    finally:+        if record is not None:+            _untrack_unwritten(doc, record)  def _write_from_worker_thread(     doc: Document,@@ -890,10 +1089,20 @@ def _write_from_worker_thread(     connections = list(connections)     if asyncio_loop is None or asyncio_loop.is_closed() or not connections:         return False+    unsent = _unsent_models(doc)+    # Tracked before serializing, which marks the models it defines as sent+    record = _track_unwritten(doc, (model.id for model in unsent), patches)     message = connections[0].protocol.create('PATCH-DOC', patches)-    asyncio_loop.call_soon_threadsafe(-        _dispatch_write_task, doc, _write_message, doc, connections, message-    )+    defined = {model.id for model in unsent - _unsent_models(doc)}+    with _WRITE_LOCK:+        record.models = defined+    try:+        asyncio_loop.call_soon_threadsafe(+            _dispatch_write_task, doc, _write_message, doc, connections, message, record+        )+    except RuntimeError:+        _untrack_unwritten(doc, record)+        raise     return True  def _flush_events(curdoc: Document, session: ServerSession) -> None:@@ -919,6 +1128,31 @@ def _flush_events(curdoc: Document, session: ServerSession) -> None:     events = _take_held_events(curdoc)     monkeypatch_events(events) +    # A context that does not hold the document lock, e.g. an unlocked+    # async callback on the event loop, writes right away, except for+    # changes that would reach the client ahead of unwritten changes of+    # the lock holder they depend on. Those join the holder's pending+    # writes while its callback runs, or are held back until it has+    # written them, so they follow the holder's changes in order.+    if not state._document_lock_held:+        events, held = _split_unknown_to_client(curdoc, session, events)+        if held:+            if session._pending_writes is not None:+                curdoc.callbacks._held_events += _suppress_property_callbacks(held)+                try:+                    curdoc.unhold()+                except RuntimeError:+                    # The holder finished writing in the meantime+                    curdoc.callbacks._hold = None+                    _defer_until_unlocked(curdoc, held)+                if events:+                    _hold_doc(curdoc, 'collect')+            else:+                _defer_until_unlocked(curdoc, held)+        if not events:+            curdoc.unhold()+            return+     if (         not queued and session._pending_writes == [] and         _write_from_worker_thread(curdoc, connections, events)
panel/io/server.py16 + / 4 −
@@ -83,7 +83,8 @@ from .application import build_applications from .auth import configure_auth from .document import (  # noqa-    _cleanup_doc, init_doc, unlocked, with_lock,+    _cleanup_doc, _owning_document_lock, _run_owning_document_lock,+    _send_pending_patches_tracked, init_doc, unlocked, with_lock, ) from .liveness import LivenessHandler from .loading import _loading_css_classes@@ -789,13 +790,14 @@ def _track_document_lock(func):     if inspect.iscoroutinefunction(func):         @wraps(func)         async def wrapper(self, *args, **kwargs):-            with state._own_document_lock(self):+            with _owning_document_lock(self):                 return await func(self, *args, **kwargs)     else:+        # An async callback is awaited after this returns, so its+        # coroutine has to own the lock while it runs too.         @wraps(func)         def wrapper(self, *args, **kwargs):-            with state._own_document_lock(self):-                return func(self, *args, **kwargs)+            return _run_owning_document_lock(self, func, self, *args, **kwargs)     wrapper._panel_tracks_lock = True  # type: ignore[attr-defined]     return wrapper @@ -872,6 +874,16 @@ def _serialize_patches(pending): if hasattr(bk_session, '_PendingPatch') and hasattr(bk_session, '_serialize_patches'):     bk_session._serialize_patches = _serialize_patches +if not getattr(ServerSession._send_pending_patches, '_panel_tracks_unwritten', False):+    _bk_send_pending_patches = ServerSession._send_pending_patches++    @wraps(_bk_send_pending_patches)+    async def _send_pending_patches(self, pending):+        await _send_pending_patches_tracked(_bk_send_pending_patches, self, pending)++    _send_pending_patches._panel_tracks_unwritten = True  # type: ignore[attr-defined]+    ServerSession._send_pending_patches = _send_pending_patches  # type: ignore[method-assign]+ if not getattr(ServerSession._document_patched, '_panel_skips_patch_connection', False):     ServerSession._document_patched = _skip_patch_connection(  # type: ignore[method-assign]         ServerSession._document_patched
panel/tests/io/test_document.py440 + / 1 −
@@ -1,4 +1,5 @@ import asyncio+import contextvars import gc import threading import time@@ -504,7 +505,7 @@ async def trigger():         release.set()     future.result(timeout=5) -    assert written == [True, False]+    assert written[0] and not any(written[1:])     assert pending == {'holder': 0, 'other': 1}     wait_until(lambda: len(socket_writes) == 1 and len(bokeh_writes) == 1) @@ -1534,3 +1535,441 @@ async def trigger():      assert len(messages) == 1     assert [event['attr'] for event in messages[0].content['events']] == ['text'] * 5+++def _undefined_references(messages, known):+    """+    Returns the ids of models a sequence of PATCH-DOC messages refers to+    before any message, or the initial Document, defined them.+    """+    def walk(obj, defined, referenced):+        if isinstance(obj, dict):+            if obj.get('type') == 'object' and 'id' in obj:+                defined.append(obj['id'])+            elif set(obj) == {'id'}:+                referenced.append(obj['id'])+            for value in obj.values():+                walk(value, defined, referenced)+        elif isinstance(obj, (list, tuple)):+            for value in obj:+                walk(value, defined, referenced)++    known, undefined = set(known), []+    for msg in messages:+        defined, referenced = [], []+        walk(msg.content, defined, referenced)+        known |= set(defined)+        undefined += [ref for ref in referenced if ref not in known]+    return undefined+++def _text_changes(messages):+    return [+        event for msg in messages for event in msg.content['events']+        if event['kind'] == 'ModelChanged' and event['attr'] == 'text'+    ]+++def _serve_with_message_log(obj, monkeypatch):+    """+    Serves obj and records every message written to a fake connection,+    whether Panel writes it to the socket directly or Bokeh sends it+    after a locked callback, in the order they are written.+    """+    serve_and_request(obj)+    wait_until(lambda: bool(obj._documents))++    doc = list(obj._documents)[0]+    session = doc.session_context.session+    monkeypatch.setitem(state._loaded, doc, True)+    monkeypatch.setitem(state._connected, doc, True)++    messages = []++    async def send_message(message):+        messages.append(message)++    conn = _FakeConn(lock_held=False)+    conn.protocol = Protocol()+    conn.send_message = send_message+    monkeypatch.setattr(session, '_subscribed_connections', {conn})+    monkeypatch.setitem(+        extra_socket_handlers, _FakeSocket,+        lambda conn, msg=None: messages.append(msg) or []+    )+    # The client has been sent the Document+    doc.models.flush_synced()+    known = {model.id for model in doc.models}+    return doc, messages, known+++@pytest.mark.xdist_group(name="server")+@pytest.mark.parametrize('pending', [False, True])+def test_unlocked_change_on_loop_is_ordered_after_locked_callback(pending, monkeypatch):+    """+    An unlocked change made on the event loop, e.g. by an async+    callback, while a locked callback on a worker thread attaches the+    model it changes must not reach the client ahead of the model.+    """+    col = pn.Column(pn.pane.Markdown('a'))+    doc, messages, known = _serve_with_message_log(col, monkeypatch)+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop++    md = pn.pane.Markdown('b')+    entered, release = threading.Event(), threading.Event()+    paused, resume = threading.Event(), threading.Event()++    def pause():+        paused.set()+        resume.wait(timeout=5)++    def change():+        with set_curdoc(doc):+            md.object = 'c'++    def holder():+        with set_curdoc(doc):+            if pending:+                # A change Bokeh writes once the callback has returned+                doc.roots[0].css_classes = ['pending']+            # Block the event loop so that the unlocked change is queued+            # to run before the loop writes the attached model.+            asyncio_loop.call_soon_threadsafe(pause)+            assert paused.wait(timeout=5)+            # A fresh context, so the change does not inherit the lock+            asyncio_loop.call_soon_threadsafe(change, context=contextvars.Context())+            col.append(md)+            resume.set()+        entered.set()+        release.wait(timeout=5)++    async def trigger():+        await session.with_document_locked(holder)++    future = asyncio.run_coroutine_threadsafe(trigger(), asyncio_loop)+    try:+        assert entered.wait(timeout=5)+    finally:+        resume.set()+        release.set()+    future.result(timeout=5)++    wait_until(lambda: len(_text_changes(messages)) == 1)+    assert _undefined_references(messages, known) == []+++@pytest.mark.xdist_group(name="server")+def test_unlocked_change_while_locked_callback_writes_is_deferred(monkeypatch):+    """+    An unlocked change made while the context holding the document lock+    is writing the changes of its callback must be written after them.+    """+    col = pn.Column(pn.pane.Markdown('a'))+    doc, messages, known = _serve_with_message_log(col, monkeypatch)+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop++    md = pn.pane.Markdown('b')+    send_pending_patches = session._send_pending_patches++    def change():+        with set_curdoc(doc):+            md.object = 'c'++    async def send_while_changing(pending):+        contextvars.Context().run(change)+        await send_pending_patches(pending)++    monkeypatch.setattr(session, '_send_pending_patches', send_while_changing)++    def holder():+        with set_curdoc(doc):+            doc.roots[0].css_classes = ['pending']+            col.append(md)++    async def trigger():+        await session.with_document_locked(holder)++    asyncio.run_coroutine_threadsafe(trigger(), asyncio_loop).result(timeout=5)++    wait_until(lambda: len(_text_changes(messages)) == 1)+    assert _undefined_references(messages, known) == []+++@pytest.mark.xdist_group(name="server")+def test_async_locked_callback_writes_while_it_awaits(monkeypatch):+    """+    An async callback holding the document lock owns it across awaits,+    so its changes are written before it returns.+    """+    md = pn.pane.Markdown('a')+    doc, messages, _ = _serve_with_message_log(md, monkeypatch)+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop++    seen = []++    async def holder():+        with set_curdoc(doc):+            md.object = 'progress'+        await asyncio.sleep(0.2)+        seen.append(len(_text_changes(messages)))++    async def trigger():+        await session.with_document_locked(holder)++    asyncio.run_coroutine_threadsafe(trigger(), asyncio_loop).result(timeout=5)+    assert seen == [1]+++@pytest.mark.xdist_group(name="server")+def test_deferred_unlocked_change_precedes_later_locked_callback(monkeypatch):+    """+    Events held back while the lock holder writes its changes are written+    before the changes of the next context to take the lock.+    """+    md = pn.pane.Markdown('a')+    doc, messages, _ = _serve_with_message_log(md, monkeypatch)+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop++    send_pending_patches = session._send_pending_patches+    later = {}++    def change():+        with set_curdoc(doc):+            md.object = 'unlocked'++    def locked_later():+        with set_curdoc(doc):+            md.object = 'locked'++    async def send_while_changing(pending):+        later['future'] = asyncio.ensure_future(session.with_document_locked(locked_later))+        await asyncio.sleep(0)+        contextvars.Context().run(change)+        await send_pending_patches(pending)++    monkeypatch.setattr(session, '_send_pending_patches', send_while_changing)++    def holder():+        with set_curdoc(doc):+            doc.roots[0].css_classes = ['pending']++    async def trigger():+        await session.with_document_locked(holder)+        await later['future']++    asyncio.run_coroutine_threadsafe(trigger(), asyncio_loop).result(timeout=5)++    wait_until(lambda: len(_text_changes(messages)) == 2)+    assert md.object == 'locked'+    texts = [event['new'] for event in _text_changes(messages)]+    assert ['unlocked' in text for text in texts] == [True, False]+++def test_owning_document_lock_closes_callback_coroutine_closed_before_awaiting():+    from panel.io.document import _run_owning_document_lock++    class Session:+        document = Document()++    async def callback():+        pass++    coroutine = callback()+    awaiting = _run_owning_document_lock(Session(), lambda: coroutine)+    awaiting.close()+    del awaiting+    gc.collect()+    assert coroutine.cr_frame is None+++def _run_on_loop_unlocked(asyncio_loop, func):+    # A fresh context, so the change does not inherit the lock holder's+    done = threading.Event()++    def run():+        try:+            func()+        finally:+            done.set()++    asyncio_loop.call_soon_threadsafe(run, context=contextvars.Context())+    assert done.wait(timeout=5)+++@pytest.mark.xdist_group(name="server")+def test_unrelated_unlocked_change_is_written_while_locked_callback_runs(monkeypatch):+    """+    An unlocked change to a model the client has is written right away+    even while another callback holds the lock and has unwritten changes.+    """+    md = pn.pane.Markdown('a')+    col = pn.Column(md)+    doc, messages, _ = _serve_with_message_log(col, monkeypatch)+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop++    entered, release = threading.Event(), threading.Event()+    seen = []++    def change():+        with set_curdoc(doc):+            md.object = 'progress'++    def holder():+        with set_curdoc(doc):+            doc.roots[0].css_classes = ['pending']+            col.append(pn.pane.Markdown('new'))+        entered.set()+        release.wait(timeout=5)++    async def trigger():+        await session.with_document_locked(holder)++    future = asyncio.run_coroutine_threadsafe(trigger(), asyncio_loop)+    try:+        assert entered.wait(timeout=5)+        _run_on_loop_unlocked(asyncio_loop, change)+        wait_until(lambda: len(_text_changes(messages)) == 1)+        seen.append(session._lock.locked())+    finally:+        release.set()+    future.result(timeout=5)++    assert seen == [True]+    assert 'progress' in _text_changes(messages)[0]['new']+++@pytest.mark.xdist_group(name="server")+def test_unlocked_change_to_property_the_lock_holder_changed_is_written_after(monkeypatch):+    """+    An unlocked change to a property the lock holder has changed but not+    written yet must follow the holder's change, otherwise the client+    ends up with the holder's older value.+    """+    md = pn.pane.Markdown('a')+    doc, messages, _ = _serve_with_message_log(md, monkeypatch)+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop++    entered, release = threading.Event(), threading.Event()++    def change():+        with set_curdoc(doc):+            md.object = 'unlocked'++    def holder():+        with set_curdoc(doc):+            doc.roots[0].css_classes = ['pending']+            md.object = 'holder'+        entered.set()+        release.wait(timeout=5)++    async def trigger():+        await session.with_document_locked(holder)++    future = asyncio.run_coroutine_threadsafe(trigger(), asyncio_loop)+    try:+        assert entered.wait(timeout=5)+        _run_on_loop_unlocked(asyncio_loop, change)+    finally:+        release.set()+    future.result(timeout=5)++    wait_until(lambda: len(_text_changes(messages)) == 2)+    texts = [event['new'] for event in _text_changes(messages)]+    assert ['unlocked' in text for text in texts] == [False, True]+    assert md.object == 'unlocked'+++@pytest.mark.xdist_group(name="server")+def test_unlocked_change_referring_to_model_in_unwritten_message_is_written_after(monkeypatch):+    """+    An unlocked change whose new value refers to a model that only a+    serialized but unwritten message of the lock holder defines must not+    be written ahead of that message.+    """+    col = pn.Column(pn.pane.Markdown('a'))+    doc, messages, known = _serve_with_message_log(col, monkeypatch)+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop+    conn = next(iter(session._subscribed_connections))+    send_message = conn.send_message+    changed = []++    def change():+        with set_curdoc(doc), unlocked():+            doc.roots[0].children[0].tags = [doc.roots[0].children[-1]]++    async def send_after_changing(message):+        if not changed:+            changed.append(True)+            contextvars.Context().run(change)+        await send_message(message)++    conn.send_message = send_after_changing++    def holder():+        with set_curdoc(doc):+            doc.roots[0].css_classes = ['pending']+            col.append(pn.pane.Markdown('b'))++    async def trigger():+        await session.with_document_locked(holder)++    asyncio.run_coroutine_threadsafe(trigger(), asyncio_loop).result(timeout=5)++    wait_until(lambda: any(+        event.get('attr') == 'tags' for msg in messages for event in msg.content['events']+    ))+    assert _undefined_references(messages, known) == []+++@pytest.mark.xdist_group(name="server")+def test_unlocked_message_to_model_attached_by_lock_holder_is_written_after(monkeypatch):+    """+    A message sent from an unlocked context to a model the lock holder+    has attached but not written yet must follow the holder's changes.+    """+    from panel.models.layout import ScrollToEvent++    col = pn.Column(pn.pane.Markdown('a'))+    doc, messages, known = _serve_with_message_log(col, monkeypatch)+    session = doc.session_context.session+    asyncio_loop = doc.session_context.server_context.application_context.io_loop.asyncio_loop+    new = pn.Column('b')+    paused, resume = threading.Event(), threading.Event()++    def pause():+        paused.set()+        resume.wait(timeout=5)++    def change():+        with set_curdoc(doc), unlocked():+            doc.callbacks.send_event(ScrollToEvent(model=doc.roots[0].children[-1], index=0))++    def holder():+        with set_curdoc(doc):+            # Block the event loop so the message is sent before the loop+            # writes the attached model.+            asyncio_loop.call_soon_threadsafe(pause)+            assert paused.wait(timeout=5)+            col.append(new)+            asyncio_loop.call_soon_threadsafe(change, context=contextvars.Context())+            resume.set()++    async def trigger():+        await session.with_document_locked(holder)++    try:+        asyncio.run_coroutine_threadsafe(trigger(), asyncio_loop).result(timeout=5)+    finally:+        resume.set()++    wait_until(lambda: any(+        event['kind'] == 'MessageSent' for msg in messages for event in msg.content['events']+    ))+    assert _undefined_references(messages, known) == []