From 39c81133dce3e8de5cd565825e8434e041303f63 Mon Sep 17 00:00:00 2001 From: lemke_h Date: Tue, 22 Sep 2026 12:24:00 +0200 Subject: [PATCH] more server upgrades --- eco/status_server/client.py | 19 +- eco/status_server/namespace_store.py | 139 +++++++++----- eco/status_server/simulate_scan_monitoring.py | 177 ++++++++++++++++++ 3 files changed, 285 insertions(+), 50 deletions(-) create mode 100644 eco/status_server/simulate_scan_monitoring.py diff --git a/eco/status_server/client.py b/eco/status_server/client.py index c7cebb8..7291e2b 100644 --- a/eco/status_server/client.py +++ b/eco/status_server/client.py @@ -430,7 +430,7 @@ class StatusServerClient: max_points_per_channel=100_000, max_value_elements=None, subscription_mask=None, - pgroup=None, run_number=None) -> dict: + pgroup=None, run_number=None, timeout=None) -> dict: """Start monitoring every monitorable status channel on the server. mode: @@ -456,6 +456,18 @@ class StatusServerClient: capture for the same run can opportunistically backfill a channel that has not updated on its own yet - see NamespaceMonitorStore.backfill_running_recordings. + + This call still blocks until the server has attached (or failed + to attach) every requested channel - RecordingSession.start() + fans that attach loop out over a thread pool server-side now, but + it is not async from this client's point of view. It therefore + defaults its own timeout to `snapshot_timeout` (180 s), not the + much shorter general-purpose `timeout` (10 s) - the same + distinction `stop_recording`/`capture_recording` already make, and + the actual root cause of "start monitoring failed ... falling + back" against bernina's ~13 000+ channels before this: the call + was reliably slower than 10 s even before it started timing out, + just not given the timeout that would have covered it. """ body = { "recording_id": recording_id, @@ -469,7 +481,10 @@ class StatusServerClient: "pgroup": pgroup, "run_number": run_number, } - return self._post("/recording/start", body, ok_codes=(200, 202)) + return self._post( + "/recording/start", body, + timeout=timeout or self.snapshot_timeout, ok_codes=(200, 202), + ) def recording(self, recording_id, channels=False, size=False, size_top_n=None) -> dict: diff --git a/eco/status_server/namespace_store.py b/eco/status_server/namespace_store.py index f04bbf4..e7182ea 100644 --- a/eco/status_server/namespace_store.py +++ b/eco/status_server/namespace_store.py @@ -745,6 +745,7 @@ class NamespaceMonitorStore: pgroup=pgroup, run_number=run_number, required_component_names=required_component_names, + attach_workers=self.monitor_workers, ) session.start(seed_from=running_siblings) self._recordings[recording_id] = session @@ -1047,6 +1048,7 @@ class RecordingSession: pgroup=None, run_number=None, required_component_names=None, + attach_workers=16, ): if mode not in ("all", "throttle", "sample"): raise ValueError(f"unknown recording mode {mode!r}") @@ -1079,6 +1081,11 @@ class RecordingSession: int(max_value_elements) if max_value_elements else None ) self.subscription_mask = subscription_mask + # How many channels start() attaches concurrently - see start()'s + # docstring note on why the attach loop is fanned out the same way + # _build_monitors()/snapshot() already fan out their own per-channel + # CA work. + self.attach_workers = int(attach_workers) self.started_at = None self.stopped_at = None @@ -1142,70 +1149,106 @@ class RecordingSession: return [], [] def start(self, seed_from=None): + """Attach a CA monitor to every requested channel. + + Split into two passes on purpose. Pass 1 (below, sequential): + set_current_value_callback() just builds the CallbackEpics wrapper + object - no CA traffic - so it stays cheap and in-order. Pass 2 + (``_attach_one``, fanned out over a ThreadPoolExecutor): ``mon. + start()`` is where the actual blocking CA work happens (a get() + when seeding, and/or waiting on the PV's own connection) - the part + that made a single unthreaded loop over bernina's ~13 000+ + monitorable channels reliably exceed a caller's request timeout. + Fanning out only this half mirrors _build_monitors()/snapshot()'s + own pattern for the same reason, without changing when + set_current_value_callback() itself runs relative to other + channels. + """ self.started_at = time.time() siblings = [s for s in (seed_from or []) if s is not self] + prepared = [] for name, obj, _ in self.detectors: values, timestamps = self._seed_buffer_from_siblings(name, siblings) self._buffers[name] = {"values": values, "timestamps": timestamps} try: mon = obj.set_current_value_callback(func=self._make_callback(name)) - if mon is None: - self.n_attach_failed += 1 - self._attach_failed_names.append(name) - continue + except Exception: + mon = None + logger.debug("could not attach a recording monitor to %s", name, + exc_info=True) + if mon is None: + self.n_attach_failed += 1 + self._attach_failed_names.append(name) + continue + # add_current_value, though, only costs a blocking round trip + # for a channel that would need one anyway: pyepics' + # PV.get_with_metadata() returns the cached last value with + # zero network traffic when auto_monitor is already True and + # the channel is connected (see ca_tuning's "Resolved + # 2026-09-06" note - measured at ~0.017 ms there). That is + # true for the large majority of channels under + # ca_tuning.make_pv()'s default policy, so seed those for + # free rather than leaving every channel's first point to + # chance; a demoted "fast" channel or one not yet connected + # would make this a real blocking get, so those still get no + # seed here - see backfill_from_status for how they can get + # one anyway, opportunistically, without new CA traffic. + pv = getattr(mon, "pv", None) + seed = bool( + pv is not None + and getattr(pv, "auto_monitor", False) + and getattr(pv, "connected", False) + ) + if not seed and isinstance(mon, CallbackComposedValue): + # AdjustableVirtual/DetectorVirtual: its seed is a + # get_current_value() recompute from its own already- + # monitored parents (mon.start() below only reaches + # here because set_current_value_callback() already + # required every parent to be a MonitorableValueUpdate), + # not a CA get of its own - free in the common case. Not + # strictly free if a parent happens to be individually + # demoted/disconnected right now, but that costs at + # most that one parent's own get, bounded by how many + # direct parents one computed value has (a handful), + # nowhere near the per-channel storm this policy exists + # to avoid - simpler to always seed these than to + # recurse the same connected/auto_monitor check through + # an arbitrary composition tree. + seed = True + prepared.append((name, mon, seed)) + + def _attach_one(item): + name, mon, seed = item + try: # with_ctrlvars=False always: get_ctrlvars() (units, limits, # precision) is a blocking CA round trip per channel # regardless of monitor state - a get-storm at namespace # scale either way. - # - # add_current_value, though, only costs that same round trip - # for a channel that would need one anyway: pyepics' - # PV.get_with_metadata() returns the cached last value with - # zero network traffic when auto_monitor is already True and - # the channel is connected (see ca_tuning's "Resolved - # 2026-09-06" note - measured at ~0.017 ms there). That is - # true for the large majority of channels under - # ca_tuning.make_pv()'s default policy, so seed those for - # free rather than leaving every channel's first point to - # chance; a demoted "fast" channel or one not yet connected - # would make this a real blocking get, so those still get no - # seed here - see backfill_from_status for how they can get - # one anyway, opportunistically, without new CA traffic. - pv = getattr(mon, "pv", None) - seed = bool( - pv is not None - and getattr(pv, "auto_monitor", False) - and getattr(pv, "connected", False) - ) - if not seed and isinstance(mon, CallbackComposedValue): - # AdjustableVirtual/DetectorVirtual: its seed is a - # get_current_value() recompute from its own already- - # monitored parents (mon.start() below only reaches - # here because set_current_value_callback() already - # required every parent to be a MonitorableValueUpdate), - # not a CA get of its own - free in the common case. Not - # strictly free if a parent happens to be individually - # demoted/disconnected right now, but that costs at - # most that one parent's own get, bounded by how many - # direct parents one computed value has (a handful), - # nowhere near the per-channel storm this policy exists - # to avoid - simpler to always seed these than to - # recurse the same connected/auto_monitor check through - # an arbitrary composition tree. - seed = True mon.start( add_current_value=seed, with_ctrlvars=False, auto_monitor=self.subscription_mask, ) - self._monitors[name] = mon - if seed: - self.n_seeded += 1 - except Exception: - self.n_attach_failed += 1 - self._attach_failed_names.append(name) - logger.debug("could not attach a recording monitor to %s", name, - exc_info=True) + return name, mon, seed, None + except Exception as exc: + return name, mon, seed, exc + + if prepared: + with ThreadPoolExecutor( + max_workers=self.attach_workers, initializer=_ca_initializer + ) as pool: + for name, mon, seed, exc in pool.map(_attach_one, prepared): + if exc is not None: + self.n_attach_failed += 1 + self._attach_failed_names.append(name) + logger.debug( + "could not attach a recording monitor to %s", name, + exc_info=exc, + ) + continue + self._monitors[name] = mon + if seed: + self.n_seeded += 1 if self.mode == "sample": self._sampler_stop.clear() self._sampler = threading.Thread( diff --git a/eco/status_server/simulate_scan_monitoring.py b/eco/status_server/simulate_scan_monitoring.py new file mode 100644 index 0000000..6f2d2b7 --- /dev/null +++ b/eco/status_server/simulate_scan_monitoring.py @@ -0,0 +1,177 @@ +"""Client-side simulation of one scan's monitoring traffic against a running +eco.status_server (namespace mode): start_monitoring, an idle wait standing +in for the scan itself, then stop_monitoring - the same request pair +Daq.start_scan_monitoring()/.end_scan_monitoring() send (see +eco.status_server.namespace_component.StatusServer), without ever writing +under a real pgroup's data directory. + +recording_id still follows the usual "{pgroup}_run{run_number:04d}" +convention (informational only - the server's own bookkeeping/backfill +matching keys off it), but the recording is stopped with save=False: the +server never writes anything to a pgroup's own directory tree, regardless of +which pgroup is named. include_data=True brings the raw per-channel buffers +back to this process instead, and this script writes them into a local tmp +directory (or --out-dir, if given) as one escape ArrayTimestamps per +channel - the same file eco.status_server.storage.write_monitor_recording +would have produced server-side, just written here instead. + +Usage: + python -m eco.status_server.simulate_scan_monitoring \\ + --url http://saresb-cons-04:8091 --duration 600 + + # lighter-weight, against production, a handful of channels only: + python -m eco.status_server.simulate_scan_monitoring \\ + --url http://saresb-cons-04:8091 --duration 60 \\ + --names bernina.mono.energy bernina.izero +""" + +from __future__ import annotations + +import argparse +import tempfile +import time +from pathlib import Path + +from .client import ( + StatusServerClient, + warn_failed_required, + warn_recording_failed_required, +) +from .storage import write_monitor_recording + + +def simulate( + url, + pgroup="p19641", + run_number=None, + duration=600.0, + mode="throttle", + min_interval=0.1, + names=None, + poll_interval=30.0, + out_dir=None, + filename="namespace_monitor.ixp.h5", +): + client = StatusServerClient(url) + health = client.health() + print( + f"{url}: {health.get('state')} ({health.get('n_initialized')}/" + f"{health.get('n_target_names')} initialized, {health.get('n_failed')} failed)" + ) + warn_failed_required(health) + if not health.get("ready"): + raise SystemExit( + f"server not ready ({health.get('state')}) - not starting a recording" + ) + + run_number = int(run_number if run_number is not None else time.time() % 10_000) + recording_id = f"{pgroup}_run{run_number:04d}" + + print(f"starting recording '{recording_id}' (mode={mode}, min_interval={min_interval}) ...") + t0 = time.time() + result = client.start_recording( + recording_id=recording_id, names=names, mode=mode, min_interval=min_interval, + pgroup=pgroup, run_number=run_number, + ) + print( + f" attached {result.get('n_channels_attached')}/" + f"{result.get('n_channels_requested')} channels in {time.time() - t0:.1f} s" + ) + warn_recording_failed_required(result) + + deadline = time.time() + duration + tick = poll_interval if poll_interval and poll_interval > 0 else duration + print(f"recording for {duration:.0f} s (standing in for the body of a scan) ...") + while True: + remaining = deadline - time.time() + if remaining <= 0: + break + time.sleep(min(tick, remaining)) + if poll_interval and poll_interval > 0 and time.time() < deadline: + live = client.recording(recording_id) + print( + f" t+{time.time() - t0:.0f}s: {live.get('n_updates')} updates, " + f"{live.get('n_stored')} stored, {live.get('n_channels_with_data')} " + f"channels with data" + ) + + print("stopping recording (save=False - nothing written under any pgroup) ...") + stopped = client.stop_recording(recording_id, save=False, include_data=True) + + out_dir = Path(out_dir) if out_dir else Path(tempfile.mkdtemp(prefix="namespace_monitor_sim_")) + out_dir.mkdir(parents=True, exist_ok=True) + path = write_monitor_recording(out_dir, stopped, filename=filename) + report = stopped.get("write_report", {}) + print( + f"wrote {report.get('n_written')} channel(s) ({report.get('n_skipped', 0)} " + f"skipped) to {path} ({path.stat().st_size} bytes)" + ) + return path + + +def main(argv=None): + parser = argparse.ArgumentParser( + description="Simulate one scan's status-server monitoring traffic " + "(start_monitoring/.../stop_monitoring), writing only to a " + "local tmp directory - no pgroup data is ever touched." + ) + parser.add_argument( + "--url", required=True, + help="status server base URL, e.g. http://saresb-cons-04:8091 (production) " + "or a disposable test-server URL", + ) + parser.add_argument( + "--pgroup", default="p19641", + help="informational only (recording_id convention/backfill matching) - " + "default is bernina's safe, dormant commissioning pgroup; nothing " + "is ever written there since the recording is stopped with " + "save=False (default: %(default)s)", + ) + parser.add_argument( + "--run-number", type=int, default=None, + help="default: derived from the current time, to avoid colliding with " + "a real run's recording_id", + ) + duration_group = parser.add_mutually_exclusive_group() + duration_group.add_argument( + "--duration", type=float, default=600.0, + help="how long to hold the recording open, in seconds " + "(default: %(default)s, i.e. a 10 minute scan)", + ) + duration_group.add_argument( + "--hours", type=float, default=None, + help="how long to hold the recording open, in hours - alternative " + "to --duration, for a long soak test", + ) + parser.add_argument("--mode", default="throttle", choices=("all", "throttle", "sample")) + parser.add_argument("--min-interval", type=float, default=0.1) + parser.add_argument( + "--names", nargs="*", default=None, + help="restrict to these channels instead of every monitorable one - " + "useful for a lighter-weight run against production instead of " + "recording the whole namespace", + ) + parser.add_argument( + "--poll-interval", type=float, default=30.0, + help="print a progress line this often while waiting; 0 disables " + "(default: %(default)s)", + ) + parser.add_argument( + "--out-dir", default=None, + help="where to write the resulting file (default: a fresh directory " + "under the system tmp dir)", + ) + parser.add_argument("--filename", default="namespace_monitor.ixp.h5") + args = parser.parse_args(argv) + duration = args.hours * 3600.0 if args.hours is not None else args.duration + + simulate( + args.url, pgroup=args.pgroup, run_number=args.run_number, + duration=duration, mode=args.mode, min_interval=args.min_interval, + names=args.names, poll_interval=args.poll_interval, + out_dir=args.out_dir, filename=args.filename, + ) + + +if __name__ == "__main__": + main()