labtasker-client 2.5.0__tar.gz → 2.7.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 (26) hide show
  1. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/PKG-INFO +1 -1
  2. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/pyproject.toml +1 -1
  3. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/__init__.py +1 -1
  4. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/api.py +2 -0
  5. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/cli.py +56 -50
  6. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/client.py +94 -49
  7. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/command_worker.py +28 -26
  8. labtasker_client-2.7.0/src/labtasker/config.py +294 -0
  9. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/execution.py +16 -21
  10. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/journal.py +33 -18
  11. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/local.py +40 -48
  12. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/models.py +7 -0
  13. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/observations.py +4 -2
  14. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/types.py +1 -0
  15. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/validation.py +18 -1
  16. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/worker.py +150 -15
  17. labtasker_client-2.5.0/src/labtasker/config.py +0 -213
  18. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/.gitignore +0 -0
  19. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/LICENSE +0 -0
  20. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/__main__.py +0 -0
  21. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/binding.py +0 -0
  22. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/command_template.py +0 -0
  23. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/errors.py +0 -0
  24. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/paths.py +0 -0
  25. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/py.typed +0 -0
  26. {labtasker_client-2.5.0 → labtasker_client-2.7.0}/src/labtasker/tee.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: labtasker-client
3
- Version: 2.5.0
3
+ Version: 2.7.0
4
4
  Summary: A small task queue for parallel model inference and evaluation
5
5
  Project-URL: Homepage, https://github.com/luocfprime/labtasker
6
6
  Project-URL: Repository, https://github.com/luocfprime/labtasker.git
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "labtasker-client"
7
- version = "2.5.0"
7
+ version = "2.7.0"
8
8
  description = "A small task queue for parallel model inference and evaluation"
9
9
  requires-python = ">=3.10"
10
10
  license = "Apache-2.0"
@@ -50,7 +50,7 @@ from labtasker.models import (
50
50
  from labtasker.types import JSONValue, TaskOrderField, TaskStatus, TaskUpdate
51
51
  from labtasker.worker import loop
52
52
 
53
- __version__ = "2.5.0"
53
+ __version__ = "2.7.0"
54
54
 
55
55
  __all__ = [
56
56
  "APIError",
@@ -20,6 +20,7 @@ def submit_task(
20
20
  priority: int = 0,
21
21
  max_attempts: int = 3,
22
22
  routes: list[str] | None = None,
23
+ dependencies: list[str] | None = None,
23
24
  task_id: str | None = None,
24
25
  queue: str | None = None,
25
26
  ) -> Task:
@@ -30,6 +31,7 @@ def submit_task(
30
31
  priority=priority,
31
32
  max_attempts=max_attempts,
32
33
  routes=routes,
34
+ dependencies=dependencies,
33
35
  task_id=task_id,
34
36
  queue=queue,
35
37
  )
@@ -3,6 +3,9 @@ from __future__ import annotations
3
3
  import json
4
4
  import logging
5
5
  from collections.abc import Callable
6
+ from contextvars import ContextVar
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
6
9
  from typing import Annotated, Any, TypeVar, cast
7
10
 
8
11
  import typer
@@ -15,8 +18,6 @@ from labtasker.command_template import TemplateSyntaxError
15
18
  from labtasker.command_worker import run_command_worker
16
19
  from labtasker.config import resolve_config
17
20
  from labtasker.errors import LabtaskerError
18
- from labtasker.execution import report_progress as report_current_progress
19
- from labtasker.execution import report_worker_telemetry as report_current_worker_telemetry
20
21
  from labtasker.types import TaskOrderField, TaskStatus, TaskUpdate
21
22
  from labtasker.validation import RequestValidationError, validate_grouping, validate_json_object
22
23
 
@@ -59,6 +60,15 @@ app.add_typer(config_app, name="config")
59
60
  logger = logging.getLogger("labtasker.cli")
60
61
 
61
62
 
63
+ @dataclass(frozen=True, slots=True)
64
+ class CLIState:
65
+ labtasker_root: Path | None
66
+ auto_start_local_server: bool
67
+
68
+
69
+ _CLI_STATE: ContextVar[CLIState | None] = ContextVar("labtasker_cli_state", default=None)
70
+
71
+
62
72
  def _version_callback(value: bool) -> None:
63
73
  if value:
64
74
  typer.echo(f"labtasker-client {__version__}")
@@ -76,8 +86,20 @@ def main(
76
86
  help="Show the Client package version and exit.",
77
87
  ),
78
88
  ] = False,
89
+ labtasker_root: Annotated[
90
+ Path | None,
91
+ typer.Option(help="Exact configuration, journal, and managed-local root."),
92
+ ] = None,
93
+ auto_start_local_server: Annotated[
94
+ bool,
95
+ typer.Option(
96
+ "--auto-start-local-server",
97
+ help="Allow this invocation to start a managed-local daemon.",
98
+ ),
99
+ ] = False,
79
100
  ) -> None:
80
101
  """Submit, inspect, and execute Labtasker v2 Tasks."""
102
+ _CLI_STATE.set(CLIState(labtasker_root, auto_start_local_server))
81
103
 
82
104
 
83
105
  class _SeparatedCommand(TyperCommand):
@@ -161,6 +183,8 @@ def worker_loop(
161
183
  max_consecutive_failures=max_consecutive_failures,
162
184
  force_stop_timeout=force_stop_timeout,
163
185
  metadata=worker_metadata,
186
+ labtasker_root=_cli_state().labtasker_root,
187
+ auto_start_local_server=_cli_state().auto_start_local_server,
164
188
  )
165
189
  except (TemplateSyntaxError, RequestValidationError) as error:
166
190
  raise typer.BadParameter(str(error)) from error
@@ -177,29 +201,6 @@ def worker_loop(
177
201
  raise typer.Exit(1) from error
178
202
 
179
203
 
180
- @app.command("progress")
181
- def progress_report(
182
- data: Annotated[
183
- str,
184
- typer.Option(help="Latest progress as one strict JSON object."),
185
- ],
186
- ) -> None:
187
- """Replace the current Task run's progress snapshot.
188
-
189
- This command is available inside a command launched by ``labtasker loop``.
190
- It prints whether the best-effort report was accepted; transport failures
191
- and confirmed revocation return ``reported: false`` without failing the
192
- command workload.
193
- """
194
- try:
195
- progress = _json_object(data, option="--data")
196
- reported = _invoke(lambda: report_current_progress(progress))
197
- except RuntimeError as error:
198
- typer.echo(str(error), err=True)
199
- raise typer.Exit(1) from error
200
- _write_json({"reported": reported})
201
-
202
-
203
204
  @task_app.command("submit")
204
205
  def task_submit(
205
206
  args: Annotated[
@@ -230,6 +231,13 @@ def task_submit(
230
231
  str | None,
231
232
  typer.Option("--id", help="Caller-chosen idempotent Task ID."),
232
233
  ] = None,
234
+ dependencies: Annotated[
235
+ list[str] | None,
236
+ typer.Option(
237
+ "--dependency",
238
+ help="Experimental: same-Queue Task ID required to succeed; repeat as needed.",
239
+ ),
240
+ ] = None,
233
241
  queue: Annotated[
234
242
  str | None,
235
243
  typer.Option(help="Target Queue; otherwise use Client configuration."),
@@ -256,6 +264,7 @@ def task_submit(
256
264
  priority=priority,
257
265
  max_attempts=max_attempts,
258
266
  routes=routes,
267
+ dependencies=dependencies,
259
268
  task_id=task_id,
260
269
  queue=queue,
261
270
  )
@@ -472,28 +481,6 @@ def worker_count(
472
481
  _write_json({"count": result} if isinstance(result, int) else result)
473
482
 
474
483
 
475
- @worker_app.command("telemetry")
476
- def worker_telemetry_report(
477
- data: Annotated[
478
- str,
479
- typer.Option(help="Latest Worker telemetry as one strict JSON object."),
480
- ],
481
- ) -> None:
482
- """Replace telemetry for the current Worker invocation.
483
-
484
- This command is available inside a command launched by ``labtasker loop``.
485
- It performs one best-effort synchronous report and prints whether the Server
486
- accepted it.
487
- """
488
- try:
489
- telemetry = _json_object(data, option="--data")
490
- reported = _invoke(lambda: report_current_worker_telemetry(telemetry))
491
- except RuntimeError as error:
492
- typer.echo(str(error), err=True)
493
- raise typer.Exit(1) from error
494
- _write_json({"reported": reported})
495
-
496
-
497
484
  def _count_options(
498
485
  group_by: list[str] | None, allowed: set[str], limit: int | None, cursor: str | None
499
486
  ) -> dict[str, Any]:
@@ -628,7 +615,10 @@ def queue_delete(
628
615
  name: Annotated[str, typer.Argument(help="Queue name to delete.")],
629
616
  cascade: Annotated[
630
617
  bool,
631
- typer.Option(help="Also permanently delete every non-running Task in the Queue."),
618
+ typer.Option(
619
+ "--cascade",
620
+ help="Also permanently delete every non-running Task in the Queue.",
621
+ ),
632
622
  ] = False,
633
623
  ) -> None:
634
624
  """Permanently delete one Queue.
@@ -647,14 +637,30 @@ def config_show() -> None:
647
637
  .labtasker/config.toml, then built-in defaults. The token value is never
648
638
  printed.
649
639
  """
650
- _write_json(_invoke(lambda: resolve_config().public_dict()))
640
+ state = _cli_state()
641
+ _write_json(
642
+ _invoke(
643
+ lambda: resolve_config(
644
+ labtasker_root=state.labtasker_root,
645
+ auto_start_local_server=state.auto_start_local_server,
646
+ ).public_dict()
647
+ )
648
+ )
651
649
 
652
650
 
653
651
  def _with_client(operation: Callable[[Client], T]) -> T:
654
- with Client() as client:
652
+ state = _cli_state()
653
+ with Client(
654
+ labtasker_root=state.labtasker_root,
655
+ auto_start_local_server=state.auto_start_local_server,
656
+ ) as client:
655
657
  return operation(client)
656
658
 
657
659
 
660
+ def _cli_state() -> CLIState:
661
+ return _CLI_STATE.get() or CLIState(None, False)
662
+
663
+
658
664
  def _invoke(operation: Callable[[], T]) -> T:
659
665
  try:
660
666
  return operation()
@@ -13,12 +13,7 @@ from pydantic import TypeAdapter, ValidationError
13
13
 
14
14
  from labtasker.config import ResolvedConfig, resolve_config
15
15
  from labtasker.errors import APIError, TransportError
16
- from labtasker.local import (
17
- ensure_local_server,
18
- local_paths,
19
- require_local_capabilities,
20
- socket_transport,
21
- )
16
+ from labtasker.local import ensure_local_server, socket_transport
22
17
  from labtasker.models import (
23
18
  BulkUpdateResult,
24
19
  ClaimResponse,
@@ -35,6 +30,7 @@ from labtasker.models import (
35
30
  from labtasker.types import JSONValue, TaskOrderField, TaskStatus, TaskUpdate
36
31
  from labtasker.validation import (
37
32
  RequestValidationError,
33
+ validate_dependencies,
38
34
  validate_filter,
39
35
  validate_grouping,
40
36
  validate_identifier,
@@ -53,7 +49,7 @@ from labtasker.validation import (
53
49
 
54
50
  T = TypeVar("T")
55
51
  ModelT = TypeVar("ModelT", bound=ResponseModel)
56
- REQUEST_TIMEOUT_SECONDS = 10.0
52
+ REQUEST_TIMEOUT_SECONDS = 15.0
57
53
  MAX_RETRY_ATTEMPTS = 3
58
54
  RETRY_BACKOFF_SECONDS = (0.05, 0.1)
59
55
  QUEUE_LIST_ADAPTER = TypeAdapter(list[Queue])
@@ -63,21 +59,36 @@ class Client:
63
59
  def __init__(
64
60
  self,
65
61
  url: str | None = None,
62
+ socket: str | Path | None = None,
63
+ labtasker_root: str | Path | None = None,
64
+ auto_start_local_server: bool = False,
66
65
  token: str | None = None,
67
66
  queue: str | None = None,
68
67
  ) -> None:
69
- self._initialize(resolve_config(url=url, token=token, queue=queue))
68
+ self._initialize(
69
+ resolve_config(
70
+ url=url,
71
+ socket=socket,
72
+ labtasker_root=labtasker_root,
73
+ auto_start_local_server=auto_start_local_server,
74
+ token=token,
75
+ queue=queue,
76
+ )
77
+ )
70
78
 
71
79
  @classmethod
72
- def _from_local_directory(cls, directory: Path, *, queue: str) -> Client:
73
- require_local_capabilities()
80
+ def _from_socket(cls, socket: Path, *, queue: str) -> Client:
74
81
  client = cls.__new__(cls)
75
82
  client._initialize(
76
83
  ResolvedConfig(
77
84
  url=None,
85
+ socket=socket,
86
+ managed_local=False,
87
+ labtasker_root=Path("/"),
78
88
  queue=validate_identifier(queue, field="queue"),
79
89
  token=None,
80
- local=local_paths(directory),
90
+ auto_start_local_server=False,
91
+ local=None,
81
92
  )
82
93
  )
83
94
  return client
@@ -87,22 +98,22 @@ class Client:
87
98
  headers = {}
88
99
  if self._config.token is not None:
89
100
  headers["Authorization"] = f"Bearer {self._config.token}"
90
- if self._config.local is None:
91
- assert self._config.url is not None
101
+ if self._config.url is not None:
92
102
  self._http = httpx.Client(
93
103
  base_url=f"{self._config.url}/api/v2/",
94
104
  headers=headers,
95
105
  timeout=REQUEST_TIMEOUT_SECONDS,
96
106
  )
97
107
  else:
108
+ assert self._config.socket is not None
98
109
  self._http = httpx.Client(
99
110
  base_url="http://labtasker/api/v2/",
100
- transport=socket_transport(self._config.local),
111
+ transport=socket_transport(self._config.socket),
101
112
  timeout=REQUEST_TIMEOUT_SECONDS,
102
113
  )
103
114
  self._closed = False
104
115
  self._endpoint_announced = False
105
- self._local_ready = False
116
+ self._local_ensure_result: tuple[int | None, str | None] | None = None
106
117
  self._server_version: str | None = None
107
118
  self._warned_server_versions: set[Version] = set()
108
119
 
@@ -148,7 +159,7 @@ class Client:
148
159
  )
149
160
 
150
161
  @property
151
- def configuration(self) -> ResolvedConfig:
162
+ def _configuration(self) -> ResolvedConfig:
152
163
  return self._config
153
164
 
154
165
  def submit_task(
@@ -160,6 +171,7 @@ class Client:
160
171
  priority: int = 0,
161
172
  max_attempts: int = 3,
162
173
  routes: list[str] | None = None,
174
+ dependencies: list[str] | None = None,
163
175
  task_id: str | None = None,
164
176
  queue: str | None = None,
165
177
  ) -> Task:
@@ -170,6 +182,9 @@ class Client:
170
182
  field="metadata",
171
183
  )
172
184
  normalized_routes = validate_routes(["default"] if routes is None else routes)
185
+ normalized_dependencies = validate_dependencies(
186
+ [] if dependencies is None else dependencies
187
+ )
173
188
  body: dict[str, object] = {
174
189
  "name": validate_task_name(name),
175
190
  "args": normalized_args,
@@ -182,6 +197,8 @@ class Client:
182
197
  ),
183
198
  "routes": normalized_routes,
184
199
  }
200
+ if normalized_dependencies:
201
+ body["dependencies"] = normalized_dependencies
185
202
  queue_name = self._queue(queue)
186
203
  if task_id is not None:
187
204
  selected_id = validate_task_id(task_id)
@@ -538,7 +555,7 @@ class Client:
538
555
  path=f"queues/{queue_name}/tasks/claim",
539
556
  json={"route": normalized_route, "run_id": normalized_run_id},
540
557
  parser=_parse_claim,
541
- retry=True,
558
+ recover_local_connect=False,
542
559
  )
543
560
 
544
561
  def _health(self) -> HealthResponse:
@@ -561,6 +578,7 @@ class Client:
561
578
  task_id: str,
562
579
  run_id: str,
563
580
  queue: str | None = None,
581
+ recover_local_connect: bool = True,
564
582
  ) -> HeartbeatResponse:
565
583
  return self._run_action(
566
584
  "heartbeat",
@@ -569,6 +587,7 @@ class Client:
569
587
  queue=queue,
570
588
  body={},
571
589
  parser=lambda response: _parse_model(response, HeartbeatResponse, {200}),
590
+ recover_local_connect=recover_local_connect,
572
591
  )
573
592
 
574
593
  def _complete(
@@ -707,6 +726,7 @@ class Client:
707
726
  queue: str | None,
708
727
  body: dict[str, object],
709
728
  parser: Callable[[httpx.Response], T],
729
+ recover_local_connect: bool = True,
710
730
  ) -> T:
711
731
  self._ensure_open()
712
732
  queue_name = self._queue(queue)
@@ -718,6 +738,7 @@ class Client:
718
738
  path=f"queues/{queue_name}/tasks/{normalized_task_id}/{action}",
719
739
  json={"run_id": normalized_run_id, **body},
720
740
  parser=parser,
741
+ recover_local_connect=recover_local_connect,
721
742
  )
722
743
 
723
744
  def _queue(self, queue: str | None) -> str:
@@ -733,9 +754,9 @@ class Client:
733
754
  json: object | None = None,
734
755
  params: dict[str, str | int] | None = None,
735
756
  retry: bool = False,
757
+ recover_local_connect: bool = True,
736
758
  ) -> T:
737
759
  self._ensure_open()
738
- self._prepare_endpoint()
739
760
  attempts = MAX_RETRY_ATTEMPTS if retry else 1
740
761
  last_transport_error: TransportError | None = None
741
762
  local_connect_recovery_used = False
@@ -746,13 +767,14 @@ class Client:
746
767
  except httpx.RequestError as error:
747
768
  last_transport_error = self._connection_error(operation)
748
769
  can_recover_local_connect = (
749
- self._config.local is not None
770
+ recover_local_connect
771
+ and self._config.managed_local
772
+ and self._config.auto_start_local_server
750
773
  and isinstance(error, (httpx.ConnectError, httpx.ConnectTimeout))
751
774
  and not local_connect_recovery_used
752
775
  )
753
776
  if can_recover_local_connect:
754
777
  local_connect_recovery_used = True
755
- self._local_ready = False
756
778
  self._ensure_local_available()
757
779
  if attempt + 1 == attempts:
758
780
  attempts += 1
@@ -760,7 +782,7 @@ class Client:
760
782
  raise last_transport_error from error
761
783
  else:
762
784
  self._observe_server_version(response)
763
- self._announce_http_endpoint()
785
+ self._announce_endpoint()
764
786
  if response.is_error:
765
787
  try:
766
788
  api_error = _parse_api_error(response)
@@ -794,32 +816,55 @@ class Client:
794
816
  raise AssertionError("Request loop ended without a result or error.")
795
817
  raise last_transport_error
796
818
 
819
+ def _repair_local_connection(self, error: TransportError) -> None:
820
+ """Repair an opted-in managed-local connection without replaying a request."""
821
+ cause = error.__cause__
822
+ if (
823
+ self._config.managed_local
824
+ and self._config.auto_start_local_server
825
+ and isinstance(cause, (httpx.ConnectError, httpx.ConnectTimeout))
826
+ ):
827
+ self._ensure_local_available()
828
+
797
829
  def _ensure_open(self) -> None:
798
830
  if self._closed:
799
831
  raise RuntimeError("Client is closed.")
800
832
 
801
833
  @property
802
834
  def _operation_endpoint_details(self) -> dict[str, object]:
803
- if self._config.local is None:
835
+ if self._config.url is not None:
804
836
  return {"url": self._config.url}
805
837
  return {
806
- "directory": str(self._config.local.directory),
807
- "socket": str(self._config.local.socket),
838
+ "labtasker_root": str(self._config.labtasker_root),
839
+ "socket": str(self._config.socket),
808
840
  }
809
841
 
810
- def _prepare_endpoint(self) -> None:
811
- if self._config.local is not None and not self._local_ready:
812
- self._ensure_local_available()
813
-
814
- def _announce_http_endpoint(self) -> None:
815
- if self._endpoint_announced or self._config.local is not None:
842
+ def _announce_endpoint(self) -> None:
843
+ if self._endpoint_announced:
816
844
  return
817
- assert self._config.url is not None
818
- transport = self._config.url.partition(":")[0]
819
- print(
820
- f"[labtasker] connected server=remote transport={transport} url={self._config.url}",
821
- file=sys.stderr,
822
- )
845
+ if self._config.url is not None:
846
+ transport = self._config.url.partition(":")[0]
847
+ message = (
848
+ f"[labtasker] connected server=remote transport={transport} url={self._config.url}"
849
+ )
850
+ elif self._config.managed_local:
851
+ assert self._config.local is not None and self._config.socket is not None
852
+ pid, version = self._local_ensure_result or (None, None)
853
+ message = (
854
+ "[labtasker] connected server=local transport=unix "
855
+ f"labtasker_root={self._config.labtasker_root} "
856
+ f"database={self._config.local.database} socket={self._config.socket}"
857
+ )
858
+ if pid is not None:
859
+ message += f" pid={pid}"
860
+ if version is not None:
861
+ message += f" version={version}"
862
+ else:
863
+ assert self._config.socket is not None
864
+ message = (
865
+ f"[labtasker] connected server=external transport=unix socket={self._config.socket}"
866
+ )
867
+ print(message, file=sys.stderr)
823
868
  self._endpoint_announced = True
824
869
 
825
870
  def _ensure_local_available(self) -> None:
@@ -827,16 +872,7 @@ class Client:
827
872
  if paths is None:
828
873
  return
829
874
  result = ensure_local_server(paths, emit=self._emit_local_transition)
830
- pid = result.pid if result.pid is not None else "unknown"
831
- version = result.server_version if result.server_version is not None else "unknown"
832
- print(
833
- "[labtasker] connected server=local transport=unix "
834
- f"directory={paths.directory} database={paths.database} socket={paths.socket} "
835
- f"pid={pid} version={version}",
836
- file=sys.stderr,
837
- )
838
- self._endpoint_announced = True
839
- self._local_ready = True
875
+ self._local_ensure_result = (result.pid, result.server_version)
840
876
 
841
877
  @staticmethod
842
878
  def _emit_local_transition(message: str) -> None:
@@ -844,16 +880,25 @@ class Client:
844
880
 
845
881
  def _connection_error(self, operation: str) -> TransportError:
846
882
  details: dict[str, object] = {"operation": operation}
847
- if self._config.local is None:
883
+ if self._config.url is not None:
848
884
  details["url"] = self._config.url
885
+ elif not self._config.managed_local:
886
+ details["socket"] = str(self._config.socket)
849
887
  else:
888
+ assert self._config.local is not None
850
889
  details.update(
851
890
  {
852
891
  "state": "unhealthy",
853
- "directory": str(self._config.local.directory),
892
+ "labtasker_root": str(self._config.labtasker_root),
854
893
  "database": str(self._config.local.database),
855
- "socket": str(self._config.local.socket),
894
+ "socket": str(self._config.socket),
856
895
  "log": str(self._config.local.log),
896
+ "remedies": [
897
+ "rerun with --auto-start-local-server",
898
+ "launch labtasker-server serve --connection socket --daemon "
899
+ f"--labtasker-root {self._config.labtasker_root}",
900
+ "configure LABTASKER_URL or LABTASKER_SOCKET",
901
+ ],
857
902
  }
858
903
  )
859
904
  return TransportError("The Labtasker Server could not be reached.", details)
@@ -29,15 +29,14 @@ from labtasker.tee import configure_worker_logger
29
29
  from labtasker.types import JSONValue
30
30
  from labtasker.validation import validate_identifier, validate_json_object
31
31
  from labtasker.worker import (
32
- POLL_INTERVAL_SECONDS,
33
32
  Heartbeat,
34
33
  _best_effort_unclaim,
35
34
  _ExecutionResult,
36
35
  _FailureGuard,
37
36
  _finish_journal,
38
- _generate_run_id,
39
37
  _guard_worker_topology,
40
38
  _journal_best_effort,
39
+ _next_claim,
41
40
  _preflight,
42
41
  _report_until_resolved,
43
42
  _safe_diagnostic_text,
@@ -58,6 +57,8 @@ def run_command_worker(
58
57
  force_stop_timeout: float | None = None,
59
58
  max_consecutive_failures: int = 5,
60
59
  metadata: dict[str, JSONValue] | None = None,
60
+ labtasker_root: Path | None = None,
61
+ auto_start_local_server: bool = False,
61
62
  ) -> None:
62
63
  guard = _FailureGuard(max_consecutive_failures)
63
64
  templates = compile_argv(argv)
@@ -70,29 +71,26 @@ def run_command_worker(
70
71
  _guard_command_worker_platform()
71
72
  _guard_worker_topology()
72
73
  configure_worker_logger()
73
- with Client(queue=queue) as client:
74
- queue_name = client.configuration.queue
74
+ with Client(
75
+ queue=queue,
76
+ labtasker_root=labtasker_root,
77
+ auto_start_local_server=auto_start_local_server,
78
+ ) as client:
79
+ queue_name = client._configuration.queue
75
80
  _preflight(client, queue_name)
76
81
  with ObservationReporter(
77
- client.configuration, normalized_route, normalized_metadata
82
+ client._configuration, normalized_route, normalized_metadata
78
83
  ) as observer:
79
- idle_deadline: float | None = None
80
84
  while True:
81
- claim = client._claim(
85
+ claim = _next_claim(
86
+ client,
82
87
  route=normalized_route,
83
- run_id=_generate_run_id(),
84
88
  queue=queue_name,
89
+ idle_timeout=normalized_idle_timeout,
85
90
  )
86
91
  if claim is None:
87
- now = time.monotonic()
88
- if idle_deadline is None:
89
- idle_deadline = now + normalized_idle_timeout
90
- if now >= idle_deadline:
91
- logger.info("Worker idle timeout reached; stopping normally.")
92
- return
93
- time.sleep(min(POLL_INTERVAL_SECONDS, idle_deadline - now))
94
- continue
95
- idle_deadline = None
92
+ logger.info("Worker idle timeout reached; stopping normally.")
93
+ return
96
94
  observer.activity(claim.task.id)
97
95
  logger.info(
98
96
  "Claimed Task %s as run %s (attempt %d, route %s).",
@@ -136,9 +134,10 @@ def _run_command_claim(
136
134
  try:
137
135
  journal = LocalRunJournal.create(
138
136
  claim=claim,
139
- endpoint=client.configuration.endpoint_dict(),
137
+ endpoint=client._configuration.endpoint_dict(),
140
138
  queue=queue,
141
139
  route=route,
140
+ labtasker_root=client._configuration.labtasker_root,
142
141
  )
143
142
  except Exception:
144
143
  _best_effort_unclaim(client, claim, queue)
@@ -423,8 +422,10 @@ def _terminate_process_group(
423
422
  # cooperative signal handler writes cleanup output before exiting.
424
423
  if drain_output is not None:
425
424
  drain_output()
426
- process.poll()
427
- if not _process_group_alive(process.pid):
425
+ # The launcher itself proves that its process group is still alive.
426
+ # Avoid the more expensive group scan until it exits; on Darwin that
427
+ # scan starts /bin/ps and can otherwise starve PTY drainage.
428
+ if process.poll() is not None and not _process_group_alive(process.pid):
428
429
  break
429
430
  if deadline is not None and time.monotonic() >= deadline:
430
431
  _signal_process_group(process.pid, signal.SIGKILL)
@@ -510,18 +511,19 @@ def _command_environment(
510
511
  "LABTASKER_WORKER_ID": worker_id,
511
512
  }
512
513
  )
513
- configuration = client.configuration
514
- if configuration.local is None:
514
+ configuration = client._configuration
515
+ if configuration.url is not None:
515
516
  assert configuration.url is not None
516
517
  environment["LABTASKER_URL"] = configuration.url
517
518
  environment.pop("LABTASKER_SOCKET", None)
518
- environment.pop("LABTASKER_LOCAL_DIRECTORY", None)
519
519
  else:
520
- environment["LABTASKER_SOCKET"] = str(configuration.local.socket)
521
- environment["LABTASKER_LOCAL_DIRECTORY"] = str(configuration.local.directory)
520
+ assert configuration.socket is not None
521
+ environment["LABTASKER_SOCKET"] = str(configuration.socket)
522
522
  environment.pop("LABTASKER_URL", None)
523
+ environment.pop("LABTASKER_ROOT", None)
524
+ environment.pop("LABTASKER_LOCAL_DIRECTORY", None)
523
525
  token = configuration.token
524
- if token is None or configuration.local is not None:
526
+ if token is None or configuration.url is None:
525
527
  environment.pop("LABTASKER_TOKEN", None)
526
528
  else:
527
529
  environment["LABTASKER_TOKEN"] = token