Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 6 additions & 0 deletions src/instrumentserver/client/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,12 @@ def _getProxyParameters(self) -> None:
bluePrint=pbp,
setpoints_instrument=self,
)
else:
# the Server can change a unit in place (a Type's unit edit
# propagates to its Instances), so keep it current
param = self.parameters[pn]
if isinstance(param, Parameter):
param.unit = p.unit

delKeys = []
for pn in self.parameters.keys():
Expand Down
19 changes: 7 additions & 12 deletions src/instrumentserver/gui/parameter_manager/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,30 +408,25 @@ def rank_lock_targets(
follower: str,
candidates: Iterable[str],
claims: Mapping[str, Claim],
arm_rel: Optional[str] = None,
) -> List[str]:
"""The arm strip's Target candidates in the mock's completer order.

``arm_rel`` is the Follower's path relative to its Instance (the part
behind the Claiming Type's Instance path), or ``None`` when the
Follower is claimed by no Type; an explicit ``arm_rel`` argument
overrides it, which the Types tab's Type Lock re-target (plan task
5.5) uses to rank for a Type's entry path — there is no claimed
Follower and so nothing to exclude. Rank 0: the candidate's own
Follower is claimed by no Type. Rank 0: the candidate's own
relative path equals ``arm_rel`` (the same leaf on a sibling Instance,
the mock's first pick). Rank 1: ``.<arm_rel>`` occurs in the candidate
(a submodule on the way). Rank 2: everything else. Equal ranks order
alphabetically; the Follower itself is never a candidate. Cycles are
not filtered here: the Server refuses them and the arm strip shows its
error text.
"""
if arm_rel is None:
follower_claim = claims.get(follower)
arm_rel = (
follower[len(follower_claim.instance) + 1 :]
if follower_claim is not None
else None
)
follower_claim = claims.get(follower)
arm_rel = (
follower[len(follower_claim.instance) + 1 :]
if follower_claim is not None
else None
)

def own_rel(candidate: str) -> Optional[str]:
claim = claims.get(candidate)
Expand Down
237 changes: 194 additions & 43 deletions src/instrumentserver/gui/parameter_manager/panels.py

Large diffs are not rendered by default.

223 changes: 163 additions & 60 deletions src/instrumentserver/gui/parameter_manager/widget.py

Large diffs are not rendered by default.

83 changes: 68 additions & 15 deletions src/instrumentserver/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,45 @@ class LogLevels(Enum):
class _LogBridge(QtCore.QObject):
"""The Qt side of :class:`QLogHandler`: the text widget, and the signal
that carries each html line into the GUI thread, where the slot
appends it to the widget."""
appends it to the widget.

The bridge has no Qt parent, so Qt never deletes it together with the
widget. Records are emitted on it from any thread (the server logs
from its own), and a parent deleting it in the GUI thread while
another thread emits on it crashes or deadlocks. The handler deletes
the bridge itself (:meth:`QLogHandler.detach`), only after no thread
can emit on it any more."""

#: Signal(str) : Emitted with the html-formatted log record to append to the widget
new_html = QtCore.Signal(str)

def __init__(self, parent: Optional[QtWidgets.QWidget]) -> None:
super().__init__(parent)
def __init__(
self,
parent: Optional[QtWidgets.QWidget],
on_widget_destroyed: Callable[[], None],
) -> None:
super().__init__()
self.widget = QtWidgets.QTextEdit(parent)
self.widget.setReadOnly(True)
self._widget_alive = True
self._on_widget_destroyed_cb = on_widget_destroyed
# connect signal to slot that actually touches the widget (GUI thread)
self.new_html.connect(self._append_html)
# the widget dies with its parent (the LogWidget); both run in the
# GUI thread, so this slot runs right inside the deletion
self.widget.destroyed.connect(self._on_widget_destroyed)

@QtCore.Slot()
def _on_widget_destroyed(self) -> None:
self._widget_alive = False
self._on_widget_destroyed_cb()

@QtCore.Slot(str)
def _append_html(self, html: str) -> None:
"""Append HTML to the text widget in the GUI thread."""
# a line posted before the widget was deleted can arrive after it
if not self._widget_alive:
return
self.widget.append(html)
# reset char format so bold/italics don’t bleed into the next line
self.widget.setCurrentCharFormat(QtGui.QTextCharFormat())
Expand All @@ -54,7 +78,11 @@ class QLogHandler(logging.Handler):
``QObject``: :func:`logging.shutdown` visits every handler at
interpreter exit, after Qt has deleted the widgets, and touching a
deleted ``QObject`` there raises. The Qt objects live in a
:class:`_LogBridge` parented to ``parent``."""
:class:`_LogBridge`; the text widget is parented to ``parent``.

When the text widget is deleted the handler detaches itself from every
logger, so windows that come and go (each server window has a
LogWidget) leave no handlers behind on the shared logger."""

COLORS = {
logging.ERROR: QtGui.QColor("red"),
Expand All @@ -65,7 +93,8 @@ class QLogHandler(logging.Handler):

def __init__(self, parent: Optional[QtWidgets.QWidget]) -> None:
super().__init__()
self._bridge = _LogBridge(parent)
self._closed = False
self._bridge = _LogBridge(parent, self.detach)
self.widget = self._bridge.widget
self._transform: Optional[Callable[[logging.LogRecord, str], Optional[str]]] = (
None
Expand All @@ -78,6 +107,11 @@ def set_transform(
self._transform = fn

def emit(self, record: logging.LogRecord) -> None:
# logging.Handler.handle holds self.lock around emit, and detach
# sets _closed under the same lock: once detach has returned, no
# thread is inside emit or can enter the bridge again
if self._closed:
return
try:
formatted = self.format(record) # prefix + message
raw_msg = record.getMessage() # message only
Expand Down Expand Up @@ -113,16 +147,35 @@ def emit(self, record: logging.LogRecord) -> None:

self._bridge.new_html.emit(html)
except RuntimeError:
# Widget has been destroyed; detach self from the logger so we
# stop receiving further records and Python can collect us.
# Assign a new list rather than removeHandler: the logger is
# iterating over its handlers list right now, and removing from
# it in place would skip the handler after this one.
for lg in list(logging.Logger.manager.loggerDict.values()) + [
logging.getLogger()
]:
if isinstance(lg, logging.Logger) and self in lg.handlers:
lg.handlers = [h for h in lg.handlers if h is not self]
# the bridge is gone (e.g. at interpreter exit): stop receiving
# records so Python can collect us
self._remove_from_loggers()

def detach(self) -> None:
"""Stop handling records and delete the bridge.

Called in the GUI thread when the text widget is deleted. Waits for
a record another thread is emitting right now, then removes the
handler from every logger and schedules the bridge for deletion."""
with self.lock: # type: ignore[union-attr]
if self._closed:
return
self._closed = True
self._remove_from_loggers()
try:
self._bridge.deleteLater()
except RuntimeError:
pass

def _remove_from_loggers(self) -> None:
# Assign a new list rather than removeHandler: another thread (or
# this one) may be iterating over the logger's handlers right now,
# and removing from the list in place would skip the next handler.
for lg in list(logging.Logger.manager.loggerDict.values()) + [
logging.getLogger()
]:
if isinstance(lg, logging.Logger) and self in lg.handlers:
lg.handlers = [h for h in lg.handlers if h is not self]


class LogWidget(QtWidgets.QWidget):
Expand Down
18 changes: 18 additions & 0 deletions src/instrumentserver/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -1654,6 +1654,9 @@ def set_type_parameter_unit(self, type_name: str, path: str, unit: str) -> None:
propagated.add(full)
if self.has_param(full):
cast(Parameter, self.parameter(full)).unit = unit
global_path = f"_globals.{type_name}.{path}"
if self.has_param(global_path):
cast(Parameter, self.parameter(global_path)).unit = unit
for name in affected:
self._broadcast_type_update(name)

Expand Down Expand Up @@ -2042,6 +2045,21 @@ def _ensure_global_target(self, type_name: str, path: str) -> str:
self._broadcast_parameter_creation(global_path, entry.default, entry.unit)
return global_path

def ensure_global_targets(self) -> List[str]:
"""Create the Globals parameter ``_globals.<type>.<path>`` of every
Type entry that has none yet, with the entry's default value and
unit, and return the created paths; the GUI calls it so every
entry has a global value to edit. Raises like
:meth:`_ensure_global_target`."""
created: List[str] = []
for type_name, definition in self._types.items():
for path in definition.parameters:
global_path = f"_globals.{type_name}.{path}"
if not self.has_param(global_path):
self._ensure_global_target(type_name, path)
created.append(global_path)
return created

# ------------------------------------------------------------------
# Type Locks (plan decision D17, task 3.2)
#
Expand Down
4 changes: 3 additions & 1 deletion src/instrumentserver/server/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,9 @@ def startServer(self) -> bool:
pool.submit(self._handleRouterMessage, identity, message)

# handle wakeup events (one or more workers finished)
if self._wakeup_r in socks and (socks[self._wakeup_r] & zmq.POLLIN):
# the poller reports a plain socket by its file descriptor,
# not by the socket object
if socks.get(self._wakeup_r.fileno(), 0) & zmq.POLLIN:
# Drain the wakeup pipe so it doesn't stay "always readable"
try:
# Read whatever is there; content doesn't matter
Expand Down
22 changes: 22 additions & 0 deletions test/pytest/test_basic_functionality.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import time

from qcodes.math_utils.field_vector import FieldVector


Expand Down Expand Up @@ -71,3 +73,23 @@ def test_sending_and_receiving_arbitrary_objects(cli, start_server):
new_field_vector = FieldVector(101, 102, 103)
magnet.set_field(new_field_vector)
assert magnet.get_field().is_equal(new_field_vector)


def test_the_server_goes_idle_after_answering_requests(cli, start_server):
"""Regression: the Server's request loop is woken when a worker has
finished a request, and must drain that wakeup. Left undrained, every
poll returns at once and an idle Server spins a whole core. After a
few requests the process may use only a fraction of an idle second's
CPU time; the Server runs in this process, on its own thread."""
for _ in range(3):
cli.list_instruments()
time.sleep(0.5) # the last response goes out and the loop settles

start = time.process_time()
time.sleep(1.0)
used = time.process_time() - start

assert used < 0.5, (
f"the process used {used:.2f} s of CPU time in an idle second: "
"the Server's request loop does not go idle"
)
40 changes: 40 additions & 0 deletions test/pytest/test_log_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,43 @@ def test_closing_the_app_leaves_no_traceback_from_the_log_handler():
assert result.returncode == 0, result.stderr
assert "Traceback" not in result.stderr, result.stderr
assert "has been deleted" not in result.stderr, result.stderr


def test_deleting_the_widget_detaches_the_handler(qtbot):
"""Each server window has a LogWidget; deleting the widget must take its
handler off the shared logger right away, not leave it behind for the
next window's server thread to log into."""
logger = logging.getLogger(LOGGER)
widget = LogWidget()
handler = widget.handler
assert handler in logger.handlers
sip.delete(widget)
assert handler not in logger.handlers


def test_deleting_widgets_while_another_thread_logs(qtbot):
"""Regression for a crash/hang in CI: a server thread logs while the GUI
thread deletes log widgets. Records must never reach a deleted bridge."""
logger = logging.getLogger(LOGGER)
stop = threading.Event()

def spam():
while not stop.is_set():
logger.info("from the server thread")

thread = threading.Thread(target=spam)
thread.start()
try:
with qtbot.captureExceptions() as exceptions:
for _ in range(50):
widget = LogWidget()
qtbot.wait(1) # let some lines reach the widget
handler = widget.handler
sip.delete(widget)
assert handler not in logger.handlers
qtbot.wait(1) # deliver lines posted before the deletion
assert exceptions == []
finally:
stop.set()
thread.join()
assert not any(isinstance(h, QLogHandler) for h in logger.handlers)
Loading
Loading