ls-algorithm-plugin-sdk 0.3.3__py3-none-any.whl → 0.3.4__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.
@@ -62,6 +62,16 @@ def configure_parser(parser: argparse.ArgumentParser) -> None:
62
62
  help="maximum concurrent executions (default: GPU count, or 1)",
63
63
  )
64
64
  parser.add_argument("--scratch-dir")
65
+ parser.add_argument(
66
+ "--local-scratch",
67
+ action="store_true",
68
+ help="override request scratchRoot with <repository>/.scratch",
69
+ )
70
+ parser.add_argument(
71
+ "--local-output",
72
+ action="store_true",
73
+ help="override request output paths with <repository>/.output/<job-id>",
74
+ )
65
75
  parser.add_argument(
66
76
  "--gpu-ids",
67
77
  type=gpu_ids,
@@ -409,6 +419,8 @@ def generate_config(
409
419
  webui=args.webui,
410
420
  max_concurrency=max_concurrency,
411
421
  scratch_dir=args.scratch_dir,
422
+ local_scratch=args.local_scratch,
423
+ local_output=args.local_output,
412
424
  token=args.service_token,
413
425
  registration=registration_from_args(args, repository),
414
426
  gpu_ids=args.gpu_ids,
@@ -81,6 +81,8 @@ def configure_parser(parser: argparse.ArgumentParser) -> None:
81
81
  def execute(args: argparse.Namespace) -> int:
82
82
  config: DeploymentConfig | None = None
83
83
  service: dict[str, object] | None = None
84
+ local_scratch = False
85
+ local_output = False
84
86
  if args.config:
85
87
  # Apply the process mask before refreshing/loading the algorithm. A
86
88
  # repository module may import CUDA during module import.
@@ -91,6 +93,8 @@ def execute(args: argparse.Namespace) -> int:
91
93
  args.port = int(service["port"])
92
94
  args.max_concurrent_executions = int(service["maxConcurrency"])
93
95
  args.scratch_dir = service.get("scratchDir")
96
+ local_scratch = bool(service.get("localScratch", False))
97
+ local_output = bool(service.get("localOutput", False))
94
98
  args.gpu_ids = list(service.get("gpuIds", []))
95
99
  args.webui = bool(service.get("webui"))
96
100
  values = config.process_environment()
@@ -120,6 +124,8 @@ def execute(args: argparse.Namespace) -> int:
120
124
  ),
121
125
  max_concurrent_executions=args.max_concurrent_executions,
122
126
  scratch_dir=args.scratch_dir,
127
+ local_scratch=local_scratch,
128
+ local_output=local_output,
123
129
  gpu_ids=args.gpu_ids,
124
130
  runner_factory=create_runner,
125
131
  max_attempts=args.max_attempts,
@@ -146,6 +146,8 @@ class DeploymentConfig:
146
146
  gpu_ids: list[int] | None = None,
147
147
  environment: dict[str, str] | None = None,
148
148
  default_parameters: dict[str, Any] | None = None,
149
+ local_scratch: bool = False,
150
+ local_output: bool = False,
149
151
  ) -> "DeploymentConfig":
150
152
  repository = repository_root(root)
151
153
  _make_repository_importable(repository)
@@ -189,6 +191,8 @@ class DeploymentConfig:
189
191
  "webui": webui,
190
192
  "maxConcurrency": max_concurrency,
191
193
  "scratchDir": _absolute(scratch_dir, repository),
194
+ "localScratch": local_scratch,
195
+ "localOutput": local_output,
192
196
  "gpuIds": configured_gpu_ids,
193
197
  "token": token or None,
194
198
  "defaultParameters": dict(default_parameters or {}),
@@ -268,6 +272,9 @@ class DeploymentConfig:
268
272
  raise RuntimeError("service port must be in [1, 65535]")
269
273
  if concurrency < 1:
270
274
  raise RuntimeError("service maxConcurrency must be positive")
275
+ for name in ("localScratch", "localOutput"):
276
+ if not isinstance(service.get(name, False), bool):
277
+ raise RuntimeError(f"service {name} must be a boolean")
271
278
  gpu_ids = service.get("gpuIds")
272
279
  if not isinstance(gpu_ids, list) or any(
273
280
  isinstance(gpu_id, bool) or not isinstance(gpu_id, int) or gpu_id < 0
@@ -10,6 +10,9 @@ from typing import Any
10
10
  from .context import utc_now
11
11
 
12
12
  _SAFE_NAME = re.compile(r"[^A-Za-z0-9._-]+")
13
+ _TIMESTAMP_GLOB = "[0-9]" * 14
14
+ _FILE_LOCKS_GUARD = threading.Lock()
15
+ _FILE_LOCKS: dict[Path, threading.RLock] = {}
13
16
 
14
17
 
15
18
  def _safe_name(value: str) -> str:
@@ -17,20 +20,61 @@ def _safe_name(value: str) -> str:
17
20
  return cleaned or "job"
18
21
 
19
22
 
23
+ def _file_lock(path: Path) -> threading.RLock:
24
+ with _FILE_LOCKS_GUARD:
25
+ return _FILE_LOCKS.setdefault(path, threading.RLock())
26
+
27
+
28
+ def _timestamp_prefix() -> str:
29
+ return utc_now().replace("-", "").replace(":", "").replace("T", "")[:14]
30
+
31
+
32
+ def _job_log_path(directory: Path, job_id: str) -> Path:
33
+ safe_job_id = _safe_name(job_id)
34
+ pattern = f"{_TIMESTAMP_GLOB}-{safe_job_id}.log"
35
+ with _FILE_LOCKS_GUARD:
36
+ existing = sorted(directory.glob(pattern))
37
+ if existing:
38
+ return existing[0]
39
+ timestamp = _timestamp_prefix()
40
+ path = directory / f"{timestamp}-{safe_job_id}.log"
41
+ path.touch(exist_ok=True)
42
+ return path
43
+
44
+
20
45
  class ExecutionLog:
21
- """Per-execution, line-buffered log sink attached to context.logger."""
46
+ """Per-job, line-buffered log sink attached to context.logger."""
22
47
 
23
- def __init__(self, *, log_dir: str | Path, job_id: str, execution_id: str, logger: logging.Logger) -> None:
48
+ def __init__(
49
+ self,
50
+ *,
51
+ log_dir: str | Path,
52
+ job_id: str,
53
+ execution_id: str,
54
+ logger: logging.Logger,
55
+ task_id: str | None = None,
56
+ ) -> None:
57
+ resolved_task_id = task_id or execution_id
58
+ self._event_context = {
59
+ "jobId": job_id,
60
+ "taskId": resolved_task_id,
61
+ "executionId": execution_id,
62
+ "job_id": job_id,
63
+ "task_id": resolved_task_id,
64
+ "execution_id": execution_id,
65
+ }
24
66
  directory = Path(log_dir).expanduser()
25
67
  directory.mkdir(parents=True, exist_ok=True)
26
- path = directory / f"{_safe_name(job_id)}.log"
27
- if path.exists():
28
- path = directory / f"{_safe_name(job_id)}-{_safe_name(execution_id)}.log"
68
+ path = _job_log_path(directory, job_id)
29
69
  self.path = path
30
70
  self._stream = path.open("a", encoding="utf-8", buffering=1)
31
- self._lock = threading.RLock()
32
- self._handler = _FlushFileHandler(self._stream)
33
- self._handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
71
+ self._lock = _file_lock(path)
72
+ self._handler = _FlushFileHandler(self._stream, self._lock)
73
+ self._handler.setFormatter(
74
+ logging.Formatter(
75
+ f"%(asctime)s %(levelname)s [executionId={execution_id}] %(message)s"
76
+ )
77
+ )
34
78
  self._handler.setLevel(logging.DEBUG)
35
79
  self.logger = logger
36
80
  self.logger.setLevel(logging.DEBUG)
@@ -38,7 +82,12 @@ class ExecutionLog:
38
82
  self._closed = False
39
83
 
40
84
  def write_event(self, event: str, **values: Any) -> None:
41
- payload = {"event": event, "timestamp": utc_now(), **values}
85
+ payload = {
86
+ "event": event,
87
+ "timestamp": utc_now(),
88
+ **self._event_context,
89
+ **values,
90
+ }
42
91
  with self._lock:
43
92
  if self._closed:
44
93
  return
@@ -56,10 +105,10 @@ class ExecutionLog:
56
105
 
57
106
 
58
107
  class _FlushFileHandler(logging.Handler):
59
- def __init__(self, stream: Any) -> None:
108
+ def __init__(self, stream: Any, lock: threading.RLock) -> None:
60
109
  super().__init__()
61
110
  self.stream = stream
62
- self._lock = threading.RLock()
111
+ self._lock = lock
63
112
 
64
113
  def emit(self, record: logging.LogRecord) -> None:
65
114
  try:
@@ -6,6 +6,7 @@ import logging
6
6
  import random
7
7
  import threading
8
8
  import time
9
+ import traceback
9
10
  import uuid
10
11
  from concurrent.futures import Future, ThreadPoolExecutor
11
12
  from contextlib import asynccontextmanager
@@ -123,6 +124,8 @@ class ExecutionManager:
123
124
  scratch_dir: str | None = None,
124
125
  repository: str | Path | None = None,
125
126
  log_dir: str | Path | None = None,
127
+ local_scratch: bool = False,
128
+ local_output: bool = False,
126
129
  gpu_ids: list[int] | None = None,
127
130
  runner_factory: RunnerFactory | None = None,
128
131
  max_attempts: int = MAX_ATTEMPTS,
@@ -138,6 +141,17 @@ class ExecutionManager:
138
141
  raise ValueError("retry_seconds must be positive")
139
142
  if not 0 <= retry_jitter_ratio <= 1:
140
143
  raise ValueError("retry_jitter_ratio must be in [0, 1]")
144
+ if not isinstance(local_scratch, bool) or not isinstance(
145
+ local_output, bool
146
+ ):
147
+ raise ValueError("local_scratch and local_output must be booleans")
148
+ repository_path = (
149
+ Path(repository).expanduser().resolve()
150
+ if repository is not None
151
+ else None
152
+ )
153
+ if (local_scratch or local_output) and repository_path is None:
154
+ raise ValueError("repository is required for local scratch or output")
141
155
  configured_gpu_ids = None if gpu_ids is None else list(gpu_ids)
142
156
  if configured_gpu_ids is not None and (
143
157
  any(
@@ -156,10 +170,19 @@ class ExecutionManager:
156
170
  raise ValueError("default_parameters must be a JSON object")
157
171
  self.default_parameters = dict(default_parameters or {})
158
172
  self.scratch_dir = scratch_dir
173
+ self._local_scratch_root = (
174
+ repository_path / ".scratch" if local_scratch else None
175
+ )
176
+ self._local_output_root = (
177
+ repository_path / ".output" if local_output else None
178
+ )
179
+ for local_root in (self._local_scratch_root, self._local_output_root):
180
+ if local_root is not None:
181
+ local_root.mkdir(parents=True, exist_ok=True)
159
182
  self.log_dir = (
160
183
  Path(log_dir).expanduser()
161
184
  if log_dir is not None
162
- else (Path(repository).expanduser() / "logs" if repository is not None else None)
185
+ else (repository_path / "logs" if repository_path is not None else None)
163
186
  )
164
187
  self.gpu_ids = configured_gpu_ids
165
188
  self.max_concurrent_executions = max_concurrent_executions
@@ -191,6 +214,46 @@ class ExecutionManager:
191
214
  self.runner.start()
192
215
  self._started = True
193
216
 
217
+ def _apply_local_paths(
218
+ self,
219
+ request: AlgorithmRequest,
220
+ job_id: str,
221
+ ) -> AlgorithmRequest:
222
+ workspace = dict(request.workspace or {})
223
+ inputs = request.inputs
224
+ if self._local_scratch_root is not None:
225
+ workspace["scratchRoot"] = str(self._local_scratch_root)
226
+ if self._local_output_root is not None:
227
+ workspace["outputRoot"] = str(self._local_output_root)
228
+ job_output = self._job_output_dir(job_id)
229
+ if len(inputs) == 1:
230
+ output_paths = [job_output]
231
+ else:
232
+ output_paths = [
233
+ job_output / f"{index}-{Path(item.output).name or 'output'}"
234
+ for index, item in enumerate(inputs)
235
+ ]
236
+ for output_path in output_paths:
237
+ output_path.mkdir(parents=True, exist_ok=True)
238
+ inputs = [
239
+ replace(item, output=str(output_path))
240
+ for item, output_path in zip(inputs, output_paths)
241
+ ]
242
+ return replace(request, inputs=inputs, workspace=workspace or None)
243
+
244
+ def _job_output_dir(self, job_id: str) -> Path:
245
+ assert self._local_output_root is not None
246
+ if Path(job_id).name != job_id or job_id in {"", ".", ".."}:
247
+ raise ValueError(f"job ID is unsafe for local output: {job_id!r}")
248
+ output = (self._local_output_root / job_id).resolve()
249
+ if (
250
+ output == self._local_output_root
251
+ or self._local_output_root not in output.parents
252
+ ):
253
+ raise ValueError(f"job output escapes local root: {job_id!r}")
254
+ output.mkdir(parents=True, exist_ok=True)
255
+ return output
256
+
194
257
  def submit(
195
258
  self,
196
259
  request: AlgorithmRequest,
@@ -226,6 +289,7 @@ class ExecutionManager:
226
289
  execution_id = f"exec-{uuid.uuid4().hex}"
227
290
  resolved_job_id = str(job_id or execution_id)
228
291
  resolved_task_id = str(task_id or execution_id)
292
+ request = self._apply_local_paths(request, resolved_job_id)
229
293
  record = ExecutionRecord(
230
294
  execution_id=execution_id,
231
295
  request=request,
@@ -237,10 +301,9 @@ class ExecutionManager:
237
301
  record.context = ExecutionContext(
238
302
  execution_id,
239
303
  [item.input_dataset for item in request.inputs],
240
- scratch_dir=(
241
- record.request.workspace["scratchRoot"]
242
- if record.request.workspace is not None
243
- else self.scratch_dir
304
+ scratch_dir=(record.request.workspace or {}).get(
305
+ "scratchRoot",
306
+ self.scratch_dir,
244
307
  ),
245
308
  progress_callback=record.add_progress,
246
309
  )
@@ -248,6 +311,7 @@ class ExecutionManager:
248
311
  record.log = ExecutionLog(
249
312
  log_dir=self.log_dir,
250
313
  job_id=record.job_id,
314
+ task_id=record.task_id,
251
315
  execution_id=record.execution_id,
252
316
  logger=record.context.logger,
253
317
  )
@@ -430,10 +494,16 @@ class ExecutionManager:
430
494
  record.log.write_event("result", state="cancelled", error=str(exc))
431
495
  except Exception as exc:
432
496
  error = f"{type(exc).__name__}: {exc}"
497
+ stack_trace = traceback.format_exc()
433
498
  record.context.mark_unfinished("failed", error)
434
499
  record.set_state("failed", error=error)
435
500
  if record.log is not None:
436
- record.log.write_event("result", state="failed", error=error)
501
+ record.log.write_event(
502
+ "result",
503
+ state="failed",
504
+ error=error,
505
+ traceback=stack_trace,
506
+ )
437
507
  else:
438
508
  record.set_state(result.status, result=result)
439
509
  if record.log is not None:
@@ -466,7 +536,7 @@ class ExecutionManager:
466
536
  self.retry_seconds * (1 - self.retry_jitter_ratio),
467
537
  self.retry_seconds * (1 + self.retry_jitter_ratio),
468
538
  )
469
- logger.warning(
539
+ record.context.logger.warning(
470
540
  "algorithm execution %s failed on attempt %d/%d; "
471
541
  "releasing and restarting algorithm in %.3f seconds: %s: %s",
472
542
  record.execution_id,
@@ -475,16 +545,18 @@ class ExecutionManager:
475
545
  delay,
476
546
  type(exc).__name__,
477
547
  exc,
548
+ exc_info=True,
478
549
  )
479
550
  else:
480
551
  delay = 0.0
481
- logger.error(
552
+ record.context.logger.error(
482
553
  "algorithm execution %s exhausted %d attempts; "
483
554
  "releasing and restarting algorithm for future requests: %s: %s",
484
555
  record.execution_id,
485
556
  self.max_attempts,
486
557
  type(exc).__name__,
487
558
  exc,
559
+ exc_info=True,
488
560
  )
489
561
  finally:
490
562
  self._release_runner()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ls-algorithm-plugin-sdk
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary: Protocol-independent runtime SDK for dataset algorithms
5
5
  Author: Ling Robotics
6
6
  License: Proprietary
@@ -2,22 +2,22 @@ algorithm_plugin_sdk/__init__.py,sha256=OKj2VcNXTwZmRgPlECI6QUBlxW1YLtflr4RAgs6w
2
2
  algorithm_plugin_sdk/algorithm.py,sha256=INjX-ygMQfHk8D1AZbEEdCw1P4VNQLGF989lP1J1H1k,1025
3
3
  algorithm_plugin_sdk/cli.py,sha256=V9HFJ98iyhM1q6PZqd-366g1AoKuieC_Fn4u9RJcMNI,1252
4
4
  algorithm_plugin_sdk/context.py,sha256=Kj-eDZg7PgX6xNzrWrQs37UfepTP8fXv4_8hCgsAIDA,11016
5
- algorithm_plugin_sdk/deployment.py,sha256=nx4-26vs5OqO6miBf6GegZIhdvOgFaw9MdjpTHZNDPo,14583
5
+ algorithm_plugin_sdk/deployment.py,sha256=5WlZfML9ymWrAFsmdX-bBHTP2kuVY4WO5wKHs35Dkd4,14936
6
6
  algorithm_plugin_sdk/errors.py,sha256=DNmI2c36Pd7K6tTaonqfEgpBzwX0o6pXzYrc8r2Z--k,730
7
7
  algorithm_plugin_sdk/gpu_isolation.py,sha256=toXUQ1vfzfLPiideJ8dWkfa9NW2Lc8V0sbNx-75YTjg,794
8
8
  algorithm_plugin_sdk/loader.py,sha256=XKmyqbJMoUMdKoo2eRQFGdbsmlz6NBgtUeIdqzumJFs,2561
9
- algorithm_plugin_sdk/log_manager.py,sha256=ktVVvf4khqXiYENr1QRpSf7yTG4HBzxW2AOHIZElDuE,2457
9
+ algorithm_plugin_sdk/log_manager.py,sha256=fmqSivxi-BCOWs4Qomms9nHZC7MRl5NUVuRiTL0J12Q,3723
10
10
  algorithm_plugin_sdk/models.py,sha256=FIwUm8QDK8L37pV7AcCMnmYlDP-2l93zp8yc0KSu4yo,12196
11
11
  algorithm_plugin_sdk/registration.py,sha256=s5oQkf12_uRjdA4CYMYM8SDQjhsk1rzDDF-3w36U_lA,10474
12
12
  algorithm_plugin_sdk/release.py,sha256=KM-kRM1oFYMgjDFnXdu6BLR1b4dsvWWDCEgTNq8cb3w,9439
13
13
  algorithm_plugin_sdk/runner.py,sha256=583Y9_7efvW5rrmM2nt316NEpCRO6kd8dKYjFRjgtCk,3183
14
- algorithm_plugin_sdk/service.py,sha256=HcO8PmtPczogi0an7irajsRCD-11GAH8pnE7rOHOLSM,28004
14
+ algorithm_plugin_sdk/service.py,sha256=HQLDW5nlGGXJNZ0KMFU4I1rPzWHMf_LlE-tsY42PHnc,31045
15
15
  algorithm_plugin_sdk/webui_app.py,sha256=Gvt2FPt0xZBjYi39sqTQqcosllifYeJam49_mGfkEVw,1530
16
16
  algorithm_plugin_sdk/cli_impl/__init__.py,sha256=uLknQVGipNd7eSJegDHZS0NVowMa0qAaOf63wFI3zHM,78
17
- algorithm_plugin_sdk/cli_impl/configure.py,sha256=OlYuNnPZXHbaoWKfBpFivyP8lZk2QQpvMN572hAjriA,13353
17
+ algorithm_plugin_sdk/cli_impl/configure.py,sha256=hO9vwFfZ4yqeQUyYc3heE1MDLK1lppN69OoF2zeVVaM,13761
18
18
  algorithm_plugin_sdk/cli_impl/parsing.py,sha256=TDX45Spu4WMrczuzTMN9ZC2SYyHE11OPBCvN45yPsxs,1399
19
19
  algorithm_plugin_sdk/cli_impl/run.py,sha256=C4raNwhj4KZJc7_aTJeoiwNMQtgeXyMWyLTZEVUL0mM,6041
20
- algorithm_plugin_sdk/cli_impl/serve.py,sha256=BBxjFjOI8bORzNij9DbKccAdt4zNzX_vqZyyKtliGSg,4936
20
+ algorithm_plugin_sdk/cli_impl/serve.py,sha256=1Ma08MHMjKk9wKO8tGdymVvedcGC-jaKdaUCVBTPMro,5187
21
21
  algorithm_plugin_sdk/examples/__init__.py,sha256=WxZZzUzxKhqZg3KibVY-7CB960DNjt6IfjciZ8JXbq0,57
22
22
  algorithm_plugin_sdk/examples/example_algorithm.py,sha256=j2RsVaRPxpJn3kK6_H_JqAceKTpJE8txNm-oTrH2v6E,3787
23
23
  algorithm_plugin_sdk/examples/simulated_algorithm.py,sha256=bIaneSMM09CJfV5-oGuZ5QwBDWV1u-7Fn0WDN1TuwGw,2944
@@ -25,8 +25,8 @@ algorithm_plugin_sdk/webui/__init__.py,sha256=cvtaktJXz_DYG4QbV5ppoqY2bFaMLuiUcT
25
25
  algorithm_plugin_sdk/webui/app.css,sha256=5HGDKlbUFLZMgCknlRuwCjiNcCr8poIF5YGHchyaamE,2965
26
26
  algorithm_plugin_sdk/webui/app.js,sha256=0YsXsocEY3yDseG3jh0RhzI8xo_bYmsbSxdN3FdCswQ,7657
27
27
  algorithm_plugin_sdk/webui/index.html,sha256=Z222OuaacWdbr0s-sjJq6wmg45u96tIneM5-LP55Z8I,2261
28
- ls_algorithm_plugin_sdk-0.3.3.dist-info/METADATA,sha256=iLerkePM3Ff_GG0oA4TAdTsidnxYJxP1pmsSaIARMJw,2317
29
- ls_algorithm_plugin_sdk-0.3.3.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
30
- ls_algorithm_plugin_sdk-0.3.3.dist-info/entry_points.txt,sha256=TU0R_TxuB5OuOiZ5BHOEmUPtHvN3v8ARUW8d3PztHcE,67
31
- ls_algorithm_plugin_sdk-0.3.3.dist-info/top_level.txt,sha256=8lsgxZ8HJGLlzJ5Rt8CiVzw9Ccme286i3akbmeMjBos,21
32
- ls_algorithm_plugin_sdk-0.3.3.dist-info/RECORD,,
28
+ ls_algorithm_plugin_sdk-0.3.4.dist-info/METADATA,sha256=S21Rk6HWDt6q5H94F_pj8DpUtY-bKCicc7Vlmq1zWxA,2317
29
+ ls_algorithm_plugin_sdk-0.3.4.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
30
+ ls_algorithm_plugin_sdk-0.3.4.dist-info/entry_points.txt,sha256=TU0R_TxuB5OuOiZ5BHOEmUPtHvN3v8ARUW8d3PztHcE,67
31
+ ls_algorithm_plugin_sdk-0.3.4.dist-info/top_level.txt,sha256=8lsgxZ8HJGLlzJ5Rt8CiVzw9Ccme286i3akbmeMjBos,21
32
+ ls_algorithm_plugin_sdk-0.3.4.dist-info/RECORD,,