envloop-envhub 2.4.0__tar.gz → 2.5.0__tar.gz

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.
Files changed (44) hide show
  1. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/PKG-INFO +1 -1
  2. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/proxyhub/guest.py +18 -3
  3. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/contract.py +77 -10
  4. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/controller.py +33 -10
  5. envloop_envhub-2.5.0/envhub/supervisor/paths.py +122 -0
  6. envloop_envhub-2.5.0/envhub/supervisor/proxyhub.py +204 -0
  7. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/pyproject.toml +5 -1
  8. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/NOTICE +0 -0
  9. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/README.pypi.md +0 -0
  10. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/__init__.py +0 -0
  11. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/__init__.py +0 -0
  12. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/client/__init__.py +0 -0
  13. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/client/download.py +0 -0
  14. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/client/materialize.py +0 -0
  15. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/client/recipe_package.py +0 -0
  16. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/__init__.py +0 -0
  17. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/ans.proto +0 -0
  18. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/errors.py +0 -0
  19. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/manifests.py +0 -0
  20. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/params.py +0 -0
  21. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/recipe.py +0 -0
  22. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/schemas.py +0 -0
  23. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/tags.py +0 -0
  24. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/ans/proto/uri.py +0 -0
  25. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/checkpoints/__init__.py +0 -0
  26. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/checkpoints/source.py +0 -0
  27. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/jobs/__init__.py +0 -0
  28. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/jobs/types.py +0 -0
  29. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/proxyhub/__init__.py +0 -0
  30. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/proxyhub/bundle.py +0 -0
  31. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/proxyhub/policy.py +0 -0
  32. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/proxyhub/services.py +0 -0
  33. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/__init__.py +0 -0
  34. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/__main__.py +0 -0
  35. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/asset_io.py +0 -0
  36. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/bootstrap.py +0 -0
  37. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/declarations.py +0 -0
  38. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/guest.py +0 -0
  39. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/outputs.py +0 -0
  40. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/process.py +0 -0
  41. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/redaction.py +0 -0
  42. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/sdk.py +0 -0
  43. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/envhub/supervisor/tools.py +0 -0
  44. {envloop_envhub-2.4.0 → envloop_envhub-2.5.0}/hatch_build.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: envloop-envhub
3
- Version: 2.4.0
3
+ Version: 2.5.0
4
4
  Summary: Dependency-free ANS protocol and verified downloads
5
5
  License-File: NOTICE
6
6
  Requires-Python: >=3.12
@@ -391,7 +391,7 @@ def create_app(config: dict[str, Any], spool: Spool, call: Any, *, provider_chat
391
391
  if extra and protocol == 'anthropic':
392
392
  arguments['extra_headers'] = extra
393
393
  if provider_paths and not config.get('native_litellm'):
394
- if streaming and config['provider_stream_options']:
394
+ if streaming and config.get('provider_stream_options', True):
395
395
  body = body | {'stream_options': {'include_usage': True}}
396
396
  response = await provider_chat(config['api_base'], config['api_key'], config['timeout'], body)
397
397
  else:
@@ -521,11 +521,25 @@ def create_app(config: dict[str, Any], spool: Spool, call: Any, *, provider_chat
521
521
  return app
522
522
 
523
523
 
524
+ def listen_host(config: dict[str, Any]) -> str:
525
+ """Loopback by default; a DinD bridge gateway is the only other accepted listener."""
526
+ import ipaddress
527
+
528
+ host = config.get('host', '127.0.0.1')
529
+ try:
530
+ address = ipaddress.IPv4Address(host) if isinstance(host, str) else None
531
+ except ValueError:
532
+ address = None
533
+ if address is None or not (address.is_loopback or address.is_private) or address.is_unspecified:
534
+ raise ValueError('PROXYHUB_HOST_INVALID')
535
+ return str(address)
536
+
537
+
524
538
  def control(root: Path, operation: str, *args: str) -> dict[str, Any]:
525
539
  from urllib.request import Request, urlopen
526
540
  config = json.loads((root / 'config.json').read_text())
527
541
  if operation in ('health', 'drain', 'activate'):
528
- request = Request(f"http://127.0.0.1:{config['port']}/" + operation,
542
+ request = Request(f"http://{listen_host(config)}:{config['port']}/" + operation,
529
543
  headers={'Authorization': 'Bearer ' + config.get('control_token', config['token']), 'Content-Type': 'application/json'},
530
544
  data=(root / 'phase.json').read_bytes() if operation == 'activate' else None,
531
545
  method='GET' if operation == 'health' else 'POST')
@@ -578,6 +592,7 @@ def main() -> None:
578
592
  or not isinstance(config.get('control_token'), str) or not config['control_token']
579
593
  or hmac.compare_digest(config['token'], config['control_token'])):
580
594
  raise ValueError('PROXYHUB_CONTROL_TOKEN_REQUIRED')
595
+ listen_host(config)
581
596
  import importlib.metadata
582
597
 
583
598
  import litellm
@@ -591,7 +606,7 @@ def main() -> None:
591
606
  calls = {'anthropic': litellm.anthropic.acreate, 'openai': litellm.acompletion,
592
607
  'openai-responses': litellm.aresponses}
593
608
  uvicorn.run(create_app(config, Spool(root / 'spool.sqlite'), calls),
594
- host='127.0.0.1', port=config['port'], access_log=False, log_level='critical')
609
+ host=listen_host(config), port=config['port'], access_log=False, log_level='critical')
595
610
  return
596
611
  if operation == 'start':
597
612
  os.umask(0o077)
@@ -15,11 +15,13 @@ from collections.abc import Mapping
15
15
  from pathlib import PurePosixPath
16
16
  from typing import Any
17
17
 
18
+ from envhub.supervisor.paths import LEGACY, Layout
19
+
18
20
  CONTRACT = "envloop.supervisor/1"
19
21
  PLAN_SCHEMA = "envloop.supervisor-plan/v1"
20
22
  RECEIPT_SCHEMA = "envloop.supervisor-receipt/v1"
21
- ROOT = "/work/data"
22
- WORK = "/work"
23
+ ROOT = LEGACY.delivery
24
+ WORK = LEGACY.work
23
25
  INPUT_CATEGORIES = ("model", "dataset", "checkpoint", "artifact")
24
26
  CODE_ROLES = ("runner", "recipe", "dep")
25
27
  OUTPUT_KINDS = ("dataset", "artifact", "checkpoint")
@@ -167,12 +169,68 @@ def _plan_output(value: object) -> dict[str, Any]:
167
169
  return item
168
170
 
169
171
 
170
- def validate_plan(value: object) -> dict[str, Any]:
171
- """Validate a frozen worker preparation plan; returns a canonical copy."""
172
+ PROXYHUB_PROTOCOLS = ("anthropic", "openai", "openai-responses")
173
+ # loopback: the workload shares ProxyHub's network namespace. worker-address: nested Task containers (DinD)
174
+ # reach ProxyHub on the worker's own private address; the per-boot token still guards every request.
175
+ PROXYHUB_LISTEN = ("loopback", "worker-address")
176
+ _VERSION = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)")
177
+ _ABSOLUTE = re.compile(r"/[A-Za-z0-9_./-]{1,255}")
178
+
179
+
180
+ def _upstream(value: object) -> str:
181
+ from urllib.parse import urlsplit
182
+
183
+ _require(isinstance(value, str) and len(value) <= 2048)
184
+ assert isinstance(value, str)
185
+ url = urlsplit(value)
186
+ _require(url.scheme == "https" and bool(url.hostname) and url.username is None and url.password is None
187
+ and not url.query and not url.fragment)
188
+ return value
189
+
190
+
191
+ def _proxyhub(value: object) -> dict[str, Any]:
192
+ """The frozen ProxyHub service. The upstream credential is delivered separately and never enters the plan."""
193
+ item = _closed(value, {"protocol", "model", "upstream", "listen", "port", "capture", "python", "version"},
194
+ {"retry"})
195
+ _require(item["protocol"] in PROXYHUB_PROTOCOLS and item["listen"] in PROXYHUB_LISTEN)
196
+ _require(isinstance(item["model"], str) and _LABEL.fullmatch(item["model"].replace("/", "-").replace(":", "-")))
197
+ item["upstream"] = _upstream(item["upstream"])
198
+ _require(type(item["port"]) is int and 1024 <= item["port"] <= 65535)
199
+ _require(isinstance(item["python"], str) and _ABSOLUTE.fullmatch(item["python"])
200
+ and ".." not in PurePosixPath(item["python"]).parts)
201
+ _require(isinstance(item["version"], str) and _VERSION.fullmatch(item["version"]))
202
+ capture = _closed(item["capture"], {"require_complete"})
203
+ _require(type(capture["require_complete"]) is bool)
204
+ item["capture"] = capture
205
+ from envhub.proxyhub.policy import RetryPolicy
206
+
207
+ try:
208
+ RetryPolicy.from_config(item.get("retry"))
209
+ except (TypeError, ValueError):
210
+ _require(False)
211
+ item["retry"] = dict(item.get("retry") or {"max_attempts": 1})
212
+ return item
213
+
214
+
215
+ def _services(value: object) -> dict[str, Any]:
216
+ services = _closed(value, set(), {"proxyhub"})
217
+ _require(bool(services))
218
+ if "proxyhub" in services:
219
+ services["proxyhub"] = _proxyhub(services["proxyhub"])
220
+ return services
221
+
222
+
223
+ def validate_plan(value: object, layout: Layout = LEGACY) -> dict[str, Any]:
224
+ """Validate a frozen worker preparation plan; returns a canonical copy.
225
+
226
+ ``layout`` is the path layout the plan was frozen under; a plan for another layout is rejected.
227
+ """
172
228
  try:
173
- plan = _closed(value, {"schema", "contract", "root", "work", "inputs", "outputs", "quota"})
229
+ plan = _closed(value, {"schema", "contract", "root", "work", "inputs", "outputs", "quota"}, {"services"})
230
+ if "services" in plan:
231
+ plan["services"] = _services(plan["services"])
174
232
  _require(plan["schema"] == PLAN_SCHEMA and plan["contract"] == CONTRACT)
175
- _require(plan["root"] == ROOT and plan["work"] == WORK)
233
+ _require(plan["root"] == layout.delivery and plan["work"] == layout.work)
176
234
  inputs, outputs = plan["inputs"], plan["outputs"]
177
235
  _require(isinstance(inputs, list) and len(inputs) <= MAX_INPUTS)
178
236
  _require(isinstance(outputs, list) and len(outputs) <= MAX_OUTPUTS)
@@ -231,8 +289,17 @@ def canonical(value: object) -> bytes:
231
289
  return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
232
290
 
233
291
 
234
- def input_path(item: Mapping[str, Any], root: str = ROOT) -> str:
235
- """Absolute read-only path of one validated plan input."""
292
+ def input_path(item: Mapping[str, Any], root: str = ROOT, layout: Layout = LEGACY) -> str:
293
+ """Absolute read-only path of one validated plan input.
294
+
295
+ Under ``LEGACY`` (the default) ``root`` is the delivery root, as before. Under any other layout
296
+ the layout owns every path and ``root`` is ignored.
297
+ """
298
+ if layout is not LEGACY:
299
+ if item["category"] == "code":
300
+ slot = "main" if item["role"] == "recipe" else item["alias"]
301
+ return layout.runner if item["role"] == "runner" else layout.asset("recipe", slot)
302
+ return layout.asset(item["category"], item["alias"])
236
303
  if item["category"] == "code":
237
304
  if item["role"] == "dep":
238
305
  return f"{root}/code/deps/{item['alias']}"
@@ -244,7 +311,7 @@ def output_path(alias: str, root: str = ROOT) -> str:
244
311
  return f"{root}/{OUTPUT_DIR}/{_alias(alias)}"
245
312
 
246
313
 
247
- def handoff_inputs(plan: Mapping[str, Any], root: str = ROOT) -> dict[str, dict[str, Any]]:
314
+ def handoff_inputs(plan: Mapping[str, Any], root: str = ROOT, layout: Layout = LEGACY) -> dict[str, dict[str, Any]]:
248
315
  """The ``ENVLOOP_INPUTS_FILE`` document of one plan: slot -> ``{path, uri, manifest_sha256}``.
249
316
 
250
317
  The same frozen plan drives delivery and the handoff, so the paths a Recipe reads are exactly the
@@ -254,7 +321,7 @@ def handoff_inputs(plan: Mapping[str, Any], root: str = ROOT) -> dict[str, dict[
254
321
  for item in plan["inputs"]:
255
322
  if item["category"] == "code":
256
323
  continue
257
- entry = {"path": input_path(item, root), "uri": item["ref"], "manifest_sha256": item["digest"][len("sha256:"):]}
324
+ entry = {"path": input_path(item, root, layout), "uri": item["ref"], "manifest_sha256": item["digest"][len("sha256:"):]}
258
325
  for key in ("config", "split"):
259
326
  if key in item.get("selector", {}):
260
327
  entry[key] = item["selector"][key]
@@ -15,6 +15,8 @@ from uuid import uuid4
15
15
  from .asset_io import postflight_diagnostic
16
16
  from .bootstrap import CLEANUP
17
17
  from .guest import INVENTORY, PROBE
18
+ from .paths import LEGACY, Layout
19
+ from .proxyhub import PROXYHUB_OUTPUTS, ProxyHub, ProxyHubError, ProxyHubSession
18
20
 
19
21
  logger = logging.getLogger(__name__)
20
22
  PROBE_FAILURE_LIMIT = 3
@@ -38,8 +40,9 @@ class RunSpec:
38
40
  output_quota: int
39
41
  outputs: tuple[str, ...]
40
42
  redactions: tuple[str, ...] = ()
41
- cwd: str = '/work/runner'
43
+ cwd: str = LEGACY.runner
42
44
  log_limit: int = 16384
45
+ proxyhub: ProxyHub | None = None
43
46
 
44
47
 
45
48
  @dataclass
@@ -55,10 +58,10 @@ Bridge = Callable[[dict[str, str], str, str], AbstractContextManager[dict[str, s
55
58
  def execute(provider: Any, handle: Any, spec: RunSpec, deadline: float, *,
56
59
  observe: Callable[[dict[str, Any]], None],
57
60
  publish: Callable[[Callable[..., dict[str, Any]]], dict[str, Any]],
58
- bridge: Bridge | None = None, on_output: Any = None) -> Outcome:
61
+ bridge: Bridge | None = None, on_output: Any = None, layout: Layout = LEGACY) -> Outcome:
59
62
  outcome = Outcome()
60
63
  nonce = uuid4().hex
61
- directory = '/work/.data-process-' + nonce
64
+ directory = layout.work + '/.data-process-' + nonce
62
65
  root = spec.tool_root
63
66
  python = spec.python
64
67
  def run(argv: list[str], **options: Any) -> Any:
@@ -67,14 +70,22 @@ def execute(provider: Any, handle: Any, spec: RunSpec, deadline: float, *,
67
70
  raise SupervisorError('WORKER_DATA_FAILED', 'Worker Data control failed.')
68
71
  return result
69
72
  run(['mkdir','-m','0700',directory])
73
+ proxyhub = ProxyHubSession(spec.proxyhub, provider, handle, directory, deadline) if spec.proxyhub else None
74
+ environment = spec.environment
70
75
  state: dict[str, Any] = {}
71
76
  def workload() -> None:
72
77
  try:
73
78
  state['result'] = provider.run(handle,[python,'-I','-S',root+'/supervisor.py',directory,nonce,
74
- str(max(1,deadline-time.monotonic())),spec.script],deadline,cwd=spec.cwd,envs=spec.environment,
79
+ str(max(1,deadline-time.monotonic())),spec.script],deadline,cwd=spec.cwd,envs=environment,
75
80
  on_output=on_output,log_limit=spec.log_limit)
76
81
  except BaseException as error:
77
82
  state['error'] = error
83
+ if proxyhub is not None:
84
+ try:
85
+ environment = proxyhub.start(spec.environment)
86
+ except ProxyHubError as error:
87
+ run([python, '-I', '-S', '-c', CLEANUP, directory])
88
+ raise SupervisorError(error.code, str(error)) from None
78
89
  thread = threading.Thread(target=workload,name='envloop-supervisor',daemon=True)
79
90
  thread.start()
80
91
  observed_exit: int | None = None
@@ -123,10 +134,20 @@ def execute(provider: Any, handle: Any, spec: RunSpec, deadline: float, *,
123
134
  if outcome.exit_code:
124
135
  outcome.error = 'RUNNER_COMMAND_FAILED'
125
136
  output = spec.output_root
137
+ outputs = spec.outputs
138
+ redactions = [*spec.redactions, spec.environment.get('ENVLOOP_API_KEY','')]
139
+ if proxyhub is not None:
140
+ try:
141
+ proxyhub.finish()
142
+ proxyhub.seal(python, output)
143
+ except ProxyHubError as error:
144
+ raise SupervisorError(error.code, str(error)) from None
145
+ outputs = (*outputs, *PROXYHUB_OUTPUTS)
146
+ redactions = [*redactions, *proxyhub.secrets]
126
147
  inventory_path=directory+'/inventory.json'
127
148
  run([python,'-I','-S','-c',INVENTORY,output,
128
- str(spec.output_quota),inventory_path,json.dumps(spec.outputs)],
129
- envs={'ENVLOOP_OUTPUT_REDACT':json.dumps([*spec.redactions, spec.environment.get('ENVLOOP_API_KEY','')])})
149
+ str(spec.output_quota),inventory_path,json.dumps(list(outputs))],
150
+ envs={'ENVLOOP_OUTPUT_REDACT':json.dumps(redactions)})
130
151
  inventory=json.loads(provider.read(handle,inventory_path,1024*1024,deadline))
131
152
  if inventory:
132
153
  # Workloads may run as image root. Never give postflight a CLI tree they could have modified.
@@ -161,6 +182,8 @@ def execute(provider: Any, handle: Any, spec: RunSpec, deadline: float, *,
161
182
  failed = True
162
183
  raise
163
184
  finally:
185
+ if proxyhub is not None:
186
+ proxyhub.stop()
164
187
  try:
165
188
  run(['touch', directory + '/release'])
166
189
  thread.join(timeout=10)
@@ -196,14 +219,14 @@ class Prepared:
196
219
 
197
220
  def prepare(provider: Any, handle: Any, items: list[dict[str, Any]], deadline: float, *,
198
221
  lease: Callable[[str, str], AbstractContextManager[dict[str, str]]],
199
- input_bytes: int = 64 * 1024**3, input_files: int = 100_000) -> Prepared:
222
+ input_bytes: int = 64 * 1024**3, input_files: int = 100_000, layout: Layout = LEGACY) -> Prepared:
200
223
  """Install the fixed tool and run prefetch; the caller owns grant/revoke policy."""
201
224
  from .bootstrap import INSTALL, payload
202
225
  from .tools import runtime_files
203
226
 
204
227
  digest, encoded = payload(runtime_files())
205
- root = '/opt/envloop/data-runtime/' + digest
206
- temporary = '/work/.data-prefetch-' + digest[:16]
228
+ root = layout.supervisor + '/' + digest
229
+ temporary = layout.work + '/.data-prefetch-' + digest[:16]
207
230
 
208
231
  def run(argv: list[str], *, environment: dict[str, str] | None = None,
209
232
  local_api: bool = False) -> Any:
@@ -213,7 +236,7 @@ def prepare(provider: Any, handle: Any, items: list[dict[str, Any]], deadline: f
213
236
  raise SupervisorError('SUPERVISOR_DELIVERY_FAILED', 'Worker input preparation failed.')
214
237
  return result
215
238
 
216
- run(['mkdir', '-p', '/work', '/work/output', '/logs', temporary])
239
+ run(['mkdir', '-p', layout.work, layout.work + '/output', layout.logs, temporary])
217
240
  run(['chmod', '0700', temporary])
218
241
  probe = provider.run(handle, ['python3', '-I', '-S', '-c',
219
242
  'import sys;assert sys.version_info >= (3,12);print(sys.executable)'], deadline, cwd='/')
@@ -0,0 +1,122 @@
1
+ """Single definition of the in-environment paths a Job sees.
2
+
3
+ Standard library only, so the Train GPU guest can ship this file beside itself.
4
+ ``TARGET`` is the ``/envloop/`` layout; ``LEGACY`` keeps the paths frozen Runners and
5
+ Recipes already use. Callers take paths from a ``Layout`` instead of building strings,
6
+ so switching layouts changes values, not code.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Layout:
16
+ root: str
17
+ delivery: str
18
+ runner: str
19
+ assets: str
20
+ handoff: str
21
+ output: str
22
+ work: str
23
+ private: str
24
+ logs: str
25
+ runtime: str
26
+ supervisor: str
27
+ profile: str
28
+ task: str
29
+ runner_output: str
30
+
31
+ @classmethod
32
+ def target(cls, root: str = "/envloop") -> Layout:
33
+ return cls(
34
+ root=root,
35
+ delivery=root,
36
+ runner=f"{root}/runner",
37
+ assets=f"{root}/assets",
38
+ handoff=f"{root}/handoff",
39
+ output=f"{root}/output",
40
+ work=f"{root}/work",
41
+ private=f"{root}/.private",
42
+ logs=f"{root}/logs",
43
+ runtime=f"{root}/runtime",
44
+ supervisor=f"{root}/runtime/supervisor",
45
+ profile=f"{root}/assets/profile",
46
+ task=f"{root}/assets/dataset/task",
47
+ runner_output=f"{root}/output",
48
+ )
49
+
50
+ def asset(self, category: str, slot: str) -> str:
51
+ return f"{self.assets}/{category}/{slot}"
52
+
53
+
54
+ TARGET = Layout.target()
55
+
56
+ LEGACY = Layout(
57
+ root="/work",
58
+ delivery="/work/data",
59
+ runner="/work/runner",
60
+ assets="/work/data",
61
+ handoff="/work/data/.handoff",
62
+ output="/work/data/output",
63
+ work="/work",
64
+ private="/work/data/.meta",
65
+ logs="/logs",
66
+ runtime="/opt/envloop",
67
+ supervisor="/opt/envloop/data-runtime",
68
+ profile="/work/profile",
69
+ task="/work/input",
70
+ runner_output="/work/output",
71
+ )
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class TrainLayout:
76
+ """Paths a Train workload container sees.
77
+
78
+ Train mounts each piece separately instead of one delivery tree, so it has its own
79
+ shape: ``inputs`` holds one directory per slot (``recipe_code`` included), and
80
+ ``params`` is the bootstrap environment, not the Recipe parameters in ``handoff``.
81
+ There is no ``/envloop/`` Train layout yet.
82
+ """
83
+
84
+ runner: str
85
+ inputs: str
86
+ output: str
87
+ work: str
88
+ handoff: str
89
+ params: str
90
+ projections: str
91
+ data_runtime: str
92
+ metrics: str
93
+
94
+ def projection(self, name: str) -> str:
95
+ """A historical single-file projection such as ``inputs.json``."""
96
+ return self.projections + name
97
+
98
+
99
+ TRAIN_LOCAL_LEGACY = TrainLayout(
100
+ runner="/work/runner",
101
+ inputs="/work/inputs",
102
+ output="/work/output",
103
+ work="/work/work",
104
+ handoff="/work/handoff",
105
+ params="/work/params.json",
106
+ projections="/work/",
107
+ data_runtime="/run/envloop-data",
108
+ metrics="/run/envloop-metrics",
109
+ )
110
+
111
+ # The GPU guest mounts no scratch directory; ``work`` is the container's own /tmp.
112
+ TRAIN_GUEST_LEGACY = TrainLayout(
113
+ runner="/work/runner",
114
+ inputs="/work/inputs",
115
+ output="/work/output",
116
+ work="/tmp",
117
+ handoff="/run/envloop",
118
+ params="/run/envloop-params.json",
119
+ projections="/run/envloop-",
120
+ data_runtime="/run/envloop-data",
121
+ metrics="/run/envloop-metrics",
122
+ )
@@ -0,0 +1,204 @@
1
+ """Supervisor-owned ProxyHub: one frozen ProxyHub per Trial, sealed with the worker outputs.
2
+
3
+ Standard library only. ProxyHub depends on LiteLLM. The controller starts ProxyHub before the workload exists and stops it only after
4
+ the worker is quiet; the workload sees the local ProxyHub endpoint and a per-boot token, never the upstream key.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import secrets
10
+ import threading
11
+ import time
12
+ from collections.abc import Callable
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ PROXYHUB_OUTPUTS = ('proxyhub/trajectory.jsonl', 'proxyhub/metrics.json')
17
+ START_TIMEOUT = 30.0
18
+ FLUSH_TIMEOUT = 10.0
19
+ MAX_COLLECT_ROUNDS = 11
20
+ POLL_INTERVAL = 2.0
21
+ # Upstream connection names the workload would otherwise inherit from the frozen Profile.
22
+ CONNECTION_NAMES = ('MODEL_API_KEY', 'MODEL_BASE_URL', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN',
23
+ 'ANTHROPIC_BASE_URL', 'ANTHROPIC_API_BASE', 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_API_BASE')
24
+ # The source address the worker uses for outbound traffic; no packet is sent by a UDP connect.
25
+ ADDRESS = ("import socket;s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM);s.connect(('192.0.2.1',9));"
26
+ "print(s.getsockname()[0])")
27
+
28
+ SEAL = r'''import json,os,pathlib,sys
29
+ # PROXYHUB_SEAL: controller-collected evidence becomes two reserved output files.
30
+ evidence=json.loads(pathlib.Path(sys.argv[1]).read_bytes());output=pathlib.Path(sys.argv[2])
31
+ assert output.is_dir() and not any(p.is_symlink() for p in (output,*output.parents))
32
+ target=output/'proxyhub'
33
+ if os.path.lexists(target):raise SystemExit(3)
34
+ target.mkdir(mode=0o755)
35
+ header={'schema':evidence['schema'],'complete':evidence['complete']}
36
+ rows=''.join(json.dumps(row,ensure_ascii=False,allow_nan=False)+'\n' for row in [header,*evidence['events']])
37
+ for name,body in (('trajectory.jsonl',rows),('metrics.json',json.dumps(evidence['metrics'],sort_keys=True))):
38
+ with open(target/name,'x',encoding='utf-8') as stream:stream.write(body)
39
+ '''
40
+
41
+
42
+ class ProxyHubError(RuntimeError):
43
+ def __init__(self, code: str, message: str) -> None:
44
+ super().__init__(message)
45
+ self.code = code
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class ProxyHub:
50
+ """A validated ``services.proxyhub`` entry plus its separately delivered upstream credential."""
51
+
52
+ service: dict[str, Any]
53
+ api_key: str = field(repr=False)
54
+ ingest: Callable[[list[dict[str, Any]]], None] = field(repr=False)
55
+
56
+
57
+ class ProxyHubSession:
58
+ def __init__(self, proxyhub: ProxyHub, provider: Any, handle: Any, directory: str, deadline: float) -> None:
59
+ self.proxyhub, self.provider, self.handle, self.deadline = proxyhub, provider, handle, deadline
60
+ self.service = proxyhub.service
61
+ self.root = directory + '/proxyhub'
62
+ self.script = self.root + '/guest.py'
63
+ self.token = secrets.token_urlsafe(32)
64
+ self.control_token = secrets.token_urlsafe(32)
65
+ self.evidence: dict[str, Any] | None = None
66
+ self._lock = threading.Lock()
67
+ self._stop = threading.Event()
68
+ self._poller: threading.Thread | None = None
69
+ self._started = self._stopped = False
70
+
71
+ @property
72
+ def secrets(self) -> tuple[str, ...]:
73
+ return (self.proxyhub.api_key, self.token, self.control_token)
74
+
75
+ def _deadline(self, budget: float) -> float:
76
+ return min(self.deadline, time.monotonic() + budget)
77
+
78
+ def _proxyhub(self, operation: str, *args: str, budget: float = FLUSH_TIMEOUT + 2) -> dict[str, Any]:
79
+ result = self.provider.run(self.handle, [self.service['python'], self.script, operation, self.root, *args],
80
+ self._deadline(budget), cwd='/')
81
+ if result.exit_code:
82
+ raise ProxyHubError('PROXYHUB_UNAVAILABLE', 'ProxyHub operation failed.')
83
+ try:
84
+ value = json.loads(result.stdout)
85
+ except ValueError:
86
+ value = None
87
+ if not isinstance(value, dict):
88
+ raise ProxyHubError('PROXYHUB_UNAVAILABLE', 'ProxyHub response is invalid.')
89
+ return value
90
+
91
+ def _host(self) -> str:
92
+ if self.service['listen'] == 'loopback':
93
+ return '127.0.0.1'
94
+ result = self.provider.run(self.handle, [self.service['python'], '-I', '-S', '-c', ADDRESS],
95
+ self._deadline(FLUSH_TIMEOUT), cwd='/')
96
+ host = result.stdout.strip() if not result.exit_code else ''
97
+ if not host:
98
+ raise ProxyHubError('PROXYHUB_NOT_READY', 'The worker address is unavailable.')
99
+ return host
100
+
101
+ def start(self, environment: dict[str, str]) -> dict[str, str]:
102
+ """Return the workload environment with the upstream connection replaced by the local ProxyHub."""
103
+ from envhub.proxyhub.bundle import payload
104
+
105
+ self._started = True
106
+ try:
107
+ host = self._host()
108
+ if self.provider.run(self.handle, ['mkdir', '-m', '0700', self.root], self._deadline(FLUSH_TIMEOUT),
109
+ cwd='/').exit_code:
110
+ raise ProxyHubError('PROXYHUB_NOT_READY', 'ProxyHub directory is unavailable.')
111
+ self.provider.write(self.handle, self.script, payload(), self.deadline)
112
+ config = dict(model=self.service['model'], api_base=self.service['upstream'], api_key=self.proxyhub.api_key,
113
+ protocol=self.service['protocol'], token=self.token, control_token=self.control_token,
114
+ version=self.service['version'], port=self.service['port'], host=host,
115
+ timeout=max(1, self.deadline - time.monotonic()), start_timeout=START_TIMEOUT,
116
+ flush_timeout=FLUSH_TIMEOUT, retry=self.service['retry'], capture=True,
117
+ native_litellm=True)
118
+ self.provider.write(self.handle, self.root + '/config.json', json.dumps(config).encode(), self.deadline)
119
+ ready = self._proxyhub('start', budget=START_TIMEOUT + 2)
120
+ if ready.get('version') != self.service['version'] or ready.get('accepting') is not True:
121
+ raise ProxyHubError('PROXYHUB_NOT_READY', 'ProxyHub is not ready.')
122
+ except Exception:
123
+ self.stop()
124
+ raise ProxyHubError('PROXYHUB_NOT_READY', 'ProxyHub runtime is missing, incompatible or not ready.') from None
125
+ self._poller = threading.Thread(target=self._poll, name='envloop-proxyhub-usage', daemon=True)
126
+ self._poller.start()
127
+ origin = f'http://{host}:{self.service["port"]}'
128
+ local = {name: value for name, value in environment.items() if name not in CONNECTION_NAMES}
129
+ if self.service['protocol'] == 'anthropic':
130
+ local.update(MODEL_BASE_URL=origin, ANTHROPIC_BASE_URL=origin, ANTHROPIC_API_BASE=origin,
131
+ MODEL_API_KEY=self.token, ANTHROPIC_API_KEY=self.token)
132
+ else:
133
+ # OpenAI SDKs append /chat/completions or /responses to a base URL that includes /v1.
134
+ local.update(MODEL_BASE_URL=origin + '/v1', OPENAI_BASE_URL=origin + '/v1', OPENAI_API_BASE=origin + '/v1',
135
+ MODEL_API_KEY=self.token, OPENAI_API_KEY=self.token)
136
+ return local
137
+
138
+ def _poll(self) -> None:
139
+ while not self._stop.wait(POLL_INTERVAL):
140
+ try:
141
+ self.collect()
142
+ except Exception:
143
+ # The durable outbox keeps unacknowledged events; the final collection decides completeness.
144
+ pass
145
+
146
+ def collect(self) -> None:
147
+ with self._lock:
148
+ for _ in range(MAX_COLLECT_ROUNDS):
149
+ batch = self._proxyhub('snapshot')
150
+ events, sequence = batch.get('events'), batch.get('sequence')
151
+ if not isinstance(events, list) or type(sequence) is not int:
152
+ raise ProxyHubError('PROXYHUB_USAGE_INCOMPLETE', 'ProxyHub usage snapshot is invalid.')
153
+ if not events:
154
+ return
155
+ try:
156
+ self.proxyhub.ingest(events)
157
+ except Exception:
158
+ raise ProxyHubError('PROXYHUB_USAGE_INCOMPLETE', 'ProxyHub usage was not persisted.') from None
159
+ self._proxyhub('ack', str(sequence))
160
+ raise ProxyHubError('PROXYHUB_USAGE_INCOMPLETE', 'ProxyHub usage exceeds bounded collection.')
161
+
162
+ def finish(self) -> None:
163
+ """After worker quiet: drain, persist usage, capture evidence, then stop."""
164
+ self._stop.set()
165
+ if self._poller is not None:
166
+ self._poller.join(timeout=FLUSH_TIMEOUT)
167
+ try:
168
+ self._proxyhub('drain')
169
+ try:
170
+ self.collect()
171
+ except ProxyHubError as error:
172
+ raise ProxyHubError('PROXYHUB_USAGE_INCOMPLETE', str(error)) from None
173
+ evidence = self._proxyhub('evidence')
174
+ if (evidence.get('schema') != 'envloop.proxyhub-trajectory/v1' or type(evidence.get('complete')) is not bool
175
+ or not isinstance(evidence.get('events'), list) or not isinstance(evidence.get('metrics'), dict)):
176
+ raise ProxyHubError('PROXYHUB_TRAJECTORY_INVALID', 'ProxyHub evidence is invalid.')
177
+ self.evidence = evidence
178
+ finally:
179
+ self.stop()
180
+ if self.evidence is not None and not self.evidence['complete'] and self.service['capture']['require_complete']:
181
+ raise ProxyHubError('PROXYHUB_TRAJECTORY_INCOMPLETE', 'ProxyHub trajectory capture is incomplete.')
182
+
183
+ def stop(self) -> None:
184
+ self._stop.set()
185
+ if not self._started or self._stopped:
186
+ return
187
+ self._stopped = True
188
+ try:
189
+ self._proxyhub('stop')
190
+ except ProxyHubError:
191
+ # The control directory is removed with the supervisor; a running ProxyHub loses its configuration.
192
+ pass
193
+
194
+ def seal(self, python: str, output_root: str) -> None:
195
+ if self.evidence is None:
196
+ raise ProxyHubError('PROXYHUB_TRAJECTORY_INVALID', 'ProxyHub evidence is unavailable.')
197
+ path = self.root + '/evidence.json'
198
+ self.provider.write(self.handle, path, json.dumps(self.evidence, allow_nan=False).encode(), self.deadline)
199
+ result = self.provider.run(self.handle, [python, '-I', '-S', '-c', SEAL, path, output_root],
200
+ self._deadline(FLUSH_TIMEOUT), cwd='/')
201
+ if result.exit_code == 3:
202
+ raise ProxyHubError('PROXYHUB_OUTPUT_CONFLICT', 'The workload wrote the reserved proxyhub output.')
203
+ if result.exit_code:
204
+ raise ProxyHubError('PROXYHUB_TRAJECTORY_INVALID', 'ProxyHub evidence could not be sealed.')
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "envloop-envhub"
7
- version = "2.4.0"
7
+ version = "2.5.0"
8
8
  description = "Dependency-free ANS protocol and verified downloads"
9
9
  readme = "README.pypi.md"
10
10
  license-files = ["NOTICE"]
@@ -37,6 +37,7 @@ only-include = [
37
37
  "envhub/supervisor/__main__.py",
38
38
  "envhub/supervisor/bootstrap.py",
39
39
  "envhub/supervisor/controller.py",
40
+ "envhub/supervisor/proxyhub.py",
40
41
  "envhub/supervisor/redaction.py",
41
42
  "envhub/supervisor/declarations.py",
42
43
  "envhub/supervisor/asset_io.py",
@@ -61,6 +62,7 @@ only-include = [
61
62
  "envhub/ans/proto/tags.py",
62
63
  "envhub/ans/proto/ans.proto",
63
64
  "envhub/supervisor/contract.py",
65
+ "envhub/supervisor/paths.py",
64
66
  "envhub/supervisor/sdk.py"
65
67
  ]
66
68
 
@@ -78,6 +80,7 @@ only-include = [
78
80
  "envhub/supervisor/__main__.py",
79
81
  "envhub/supervisor/bootstrap.py",
80
82
  "envhub/supervisor/controller.py",
83
+ "envhub/supervisor/proxyhub.py",
81
84
  "envhub/supervisor/redaction.py",
82
85
  "envhub/supervisor/declarations.py",
83
86
  "envhub/supervisor/asset_io.py",
@@ -102,6 +105,7 @@ only-include = [
102
105
  "envhub/ans/proto/tags.py",
103
106
  "envhub/ans/proto/ans.proto",
104
107
  "envhub/supervisor/contract.py",
108
+ "envhub/supervisor/paths.py",
105
109
  "envhub/supervisor/sdk.py",
106
110
  "pyproject.toml",
107
111
  "README.pypi.md",
File without changes