oprunner 0.1.0.dev0__py3-none-any.whl → 0.1.0.dev2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
oprunner/_pixi.py ADDED
@@ -0,0 +1,104 @@
1
+ """Keep appose's own pixi new enough to build environments.
2
+
3
+ Appose downloads a pixi of its own and builds every environment with it.
4
+ Released appose (0.12.0) pins pixi v0.58.0, and that pixi now fails fresh
5
+ builds with ``io error: unexpected end of file`` while solving: every recipe
6
+ under ``envs/`` that has PyPI packages, which is all of them. Environments
7
+ built earlier keep working, because an up-to-date environment is never
8
+ installed again; a new user cannot build any.
9
+
10
+ Appose's main fixed this upstream (apposed/appose-python#10, pin v0.81.0, and
11
+ then a self-update), but no release carries it yet. Until one does, this
12
+ does the same from here:
13
+
14
+ * Before appose has downloaded pixi, point its download at ``MINIMUM``, so a
15
+ new user gets that version and no other.
16
+ * If appose already has an older pixi, ``pixi self-update`` it once, before
17
+ the first build that needs to install anything.
18
+
19
+ Remove this module once scikit-ops requires an appose release whose pinned
20
+ pixi is at least ``MINIMUM``.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import re
26
+ import subprocess
27
+ from collections.abc import Callable
28
+ from pathlib import Path
29
+
30
+ #: The pixi appose's main pins; the version apposed/appose-python#10 tested.
31
+ MINIMUM = "0.81.0"
32
+
33
+ _checked = False
34
+
35
+
36
+ def _parse(text: str) -> tuple[int, ...] | None:
37
+ found = re.search(r"(\d+)\.(\d+)\.(\d+)", text or "")
38
+ return tuple(int(part) for part in found.groups()) if found else None
39
+
40
+
41
+ def _installed_version(command: Path) -> tuple[int, ...] | None:
42
+ out = subprocess.run(
43
+ [str(command), "--version"],
44
+ capture_output=True,
45
+ text=True,
46
+ timeout=60,
47
+ check=False,
48
+ )
49
+ return _parse(out.stdout)
50
+
51
+
52
+ def ensure_recent_pixi(report: Callable[[str], None] = print) -> None:
53
+ """Make appose build with a pixi at least ``MINIMUM``. Once per process.
54
+
55
+ Never raises: a failure is reported, and the build goes ahead with
56
+ whatever pixi there is, so this can only ever help.
57
+ """
58
+ global _checked
59
+ if _checked:
60
+ return
61
+ _checked = True
62
+ try:
63
+ from appose.tool.pixi import Pixi
64
+ except ImportError:
65
+ return
66
+
67
+ minimum = _parse(MINIMUM)
68
+ pinned = _parse(Pixi.PIXI_VERSION)
69
+ if pinned is not None and pinned >= minimum:
70
+ return # an appose that is new enough already
71
+
72
+ # Before appose's first download: fetch MINIMUM instead of its pin.
73
+ Pixi.PIXI_VERSION = f"v{MINIMUM}"
74
+ if Pixi.PIXI_BINARY:
75
+ Pixi.DOWNLOAD_URL = (
76
+ "https://github.com/prefix-dev/pixi/releases/download/"
77
+ f"{Pixi.PIXI_VERSION}/{Pixi.PIXI_BINARY}"
78
+ )
79
+
80
+ # After it: an older pixi already installed is updated in place.
81
+ try:
82
+ command = Path(Pixi().command)
83
+ if not command.exists():
84
+ return
85
+ installed = _installed_version(command)
86
+ if installed is None or installed >= minimum:
87
+ return
88
+ old = ".".join(map(str, installed))
89
+ report(
90
+ f"Updating appose's pixi from {old} to {MINIMUM} ({command}): "
91
+ f"pixi {old} can no longer build environments"
92
+ )
93
+ subprocess.run(
94
+ [str(command), "self-update", "--version", MINIMUM],
95
+ capture_output=True,
96
+ text=True,
97
+ timeout=600,
98
+ check=True,
99
+ )
100
+ now = _installed_version(command)
101
+ if now is None or now < minimum:
102
+ report(f"pixi still reports {now}; building with it anyway")
103
+ except Exception as e: # noqa: BLE001 - never block a build over this
104
+ report(f"Could not update appose's pixi ({e}); building with it anyway")
oprunner/runner.py CHANGED
@@ -8,6 +8,7 @@ living in the op's declared environment.
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
+ import atexit
11
12
  import contextlib
12
13
  import contextvars
13
14
  import functools
@@ -16,6 +17,8 @@ import itertools
16
17
  import json
17
18
  import re
18
19
  import sys
20
+ import threading
21
+ import weakref
19
22
  from collections.abc import Callable, Iterator
20
23
  from dataclasses import dataclass
21
24
  from pathlib import Path
@@ -150,6 +153,32 @@ def _default_envs_dir(root: Path) -> Path | None:
150
153
  return checkout if checkout.is_dir() else None
151
154
 
152
155
 
156
+ #: Every Runner not yet garbage-collected, so their workers can be closed at
157
+ #: interpreter exit.
158
+ _live_runners: weakref.WeakSet = weakref.WeakSet()
159
+
160
+
161
+ def _close_live_runners() -> None:
162
+ for runner in list(_live_runners):
163
+ with contextlib.suppress(Exception):
164
+ runner.close()
165
+
166
+
167
+ # A worker lives until its stdin closes, and Appose watches each one with
168
+ # three non-daemon threads (stdout, stderr, process monitor) that end only
169
+ # when it does. A runner left open -- a script that never calls close(), or
170
+ # a GUI's one shared runner -- therefore kept Python from exiting: shutdown
171
+ # waits on non-daemon threads, forever. atexit runs too late for this, after
172
+ # that wait; threading's own hook runs before it, and is what
173
+ # concurrent.futures uses for the same reason. It is private, so atexit is
174
+ # the fallback, which at least closes workers for anyone whose threads are
175
+ # already gone.
176
+ if hasattr(threading, "_register_atexit"):
177
+ threading._register_atexit(_close_live_runners)
178
+ else: # pragma: no cover
179
+ atexit.register(_close_live_runners)
180
+
181
+
153
182
  class Runner:
154
183
  """Builds environments, keeps workers warm, and dispatches op calls."""
155
184
 
@@ -169,6 +198,7 @@ class Runner:
169
198
  self._build_progress: list[Callable[[str, int, int], None]] = []
170
199
  self._build_output: list[Callable[[str], None]] = []
171
200
  self._build_error: list[Callable[[str], None]] = []
201
+ _live_runners.add(self)
172
202
 
173
203
  # -- build reporting -------------------------------------------------
174
204
 
@@ -195,6 +225,16 @@ class Runner:
195
225
  """Hear the build tool's standard output, in raw chunks."""
196
226
  self._build_output.append(subscriber)
197
227
 
228
+ def _say(self, message: str) -> None:
229
+ """One line of the runner's own build news, where build output goes."""
230
+ if not self._build_output:
231
+ print(message, flush=True)
232
+ for subscriber in self._build_output:
233
+ try:
234
+ subscriber(message + "\n")
235
+ except Exception: # noqa: BLE001 - a listener must not stop a build
236
+ pass
237
+
198
238
  def subscribe_build_error(self, subscriber: Callable[[str], None]) -> None:
199
239
  """Hear the build tool's standard error, in raw chunks.
200
240
 
@@ -354,6 +394,12 @@ class Runner:
354
394
  if key in self._envs:
355
395
  return self._envs[key]
356
396
 
397
+ if not _is_built(env):
398
+ # About to install: make sure appose's pixi can. See _pixi.
399
+ from ._pixi import ensure_recent_pixi
400
+
401
+ ensure_recent_pixi(self._say)
402
+
357
403
  builder = appose.pixi(env.config).name(env.name)
358
404
  for progress_subscriber in self._build_progress:
359
405
  builder = builder.subscribe_progress(progress_subscriber)
@@ -820,6 +866,21 @@ class Env:
820
866
  return Path(appose_envs_dir()) / self.name
821
867
 
822
868
 
869
+ def _is_built(env: Env) -> bool:
870
+ """Whether *env* is built from its current file, so appose installs nothing.
871
+
872
+ The comparison ``Runner.environment_status`` makes, for any ``Env``.
873
+ """
874
+ import json
875
+
876
+ record = env.folder / "appose.json"
877
+ try:
878
+ built = json.loads(record.read_text()).get("content", "")
879
+ return built.strip() == env.config.read_text().strip()
880
+ except (OSError, ValueError):
881
+ return False
882
+
883
+
823
884
  def _package_name(module: str, root: Path) -> str:
824
885
  """Whose environments these are, for naming them: a package's name.
825
886
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: oprunner
3
- Version: 0.1.0.dev0
3
+ Version: 0.1.0.dev2
4
4
  Summary: Run image-processing ops in their own environments, with Appose.
5
5
  Author: scikit-ops developers
6
6
  License-Expression: BSD-2-Clause
@@ -1,12 +1,13 @@
1
1
  oprunner/__init__.py,sha256=vkU84LHsBdIMhEoI2mo4y9xhVlURbOM6sup9sCqpdsE,1920
2
2
  oprunner/_adapt.py,sha256=3k8tufgIlCdXNjP0MQZi2DPcPjxF2VUk_U7EGX7rkmI,6978
3
3
  oprunner/_codec.py,sha256=0j7F5FDKfNlvZmMOwO4kV6wVKPHFMUfPPALWabhbLZI,4456
4
+ oprunner/_pixi.py,sha256=-nPHNW7L2gfWirvnXlbyglqY7Q3konzfzTQWGdpUQiI,3623
4
5
  oprunner/_tiling.py,sha256=ofh_wxVT2MeDD1XpzwbvkefWJ6rX3XahnWt1RiaWUv0,16512
5
6
  oprunner/discovery.py,sha256=odv78i7Lf_WRw6v7JEnKLy0tCGXoQJwvPhTtSDRFdBo,4575
6
7
  oprunner/host.py,sha256=Vzlbwzv20M3J634m4BdneiwQpiMS4OQlaTh62CVN0Ys,10981
7
- oprunner/runner.py,sha256=oVsvd4Rieb5FVNTYm1pJYbdNQvRBGtXdrn4sb5XCH3g,35480
8
+ oprunner/runner.py,sha256=oCOMY8B3yZ8d8Hy_SGWAWms1OOEYuN9MxDz-ToA6RSc,37677
8
9
  oprunner/worker.py,sha256=VOFXzxmfMuppwfV9YeKPBx1qJHouA5wSDLa5x5WZZJg,5808
9
- oprunner-0.1.0.dev0.dist-info/METADATA,sha256=ues12QCwl3Jvksm2jFIBCDo5RX2hlgjNmRSmeKAg5Mo,1089
10
- oprunner-0.1.0.dev0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
- oprunner-0.1.0.dev0.dist-info/licenses/LICENSE,sha256=OVmXAsSBJBi_elQtTc9S-H02MbKDRyFy7_ZPE95OJkA,1299
12
- oprunner-0.1.0.dev0.dist-info/RECORD,,
10
+ oprunner-0.1.0.dev2.dist-info/METADATA,sha256=AOtH1HgO4gAvlxBPdkAGR2QSIL2h-12UqGGyBDWOmnU,1089
11
+ oprunner-0.1.0.dev2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ oprunner-0.1.0.dev2.dist-info/licenses/LICENSE,sha256=OVmXAsSBJBi_elQtTc9S-H02MbKDRyFy7_ZPE95OJkA,1299
13
+ oprunner-0.1.0.dev2.dist-info/RECORD,,