datatorch 0.8.4__tar.gz → 0.8.5__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 (112) hide show
  1. {datatorch-0.8.4 → datatorch-0.8.5}/PKG-INFO +1 -1
  2. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/pull.py +121 -0
  3. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/main/pull.py +26 -2
  4. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/client.py +2 -1
  5. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/daemon.py +9 -4
  6. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/monitoring.py +24 -3
  7. datatorch-0.8.5/datatorch/utils/aio.py +60 -0
  8. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch.egg-info/PKG-INFO +1 -1
  9. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch.egg-info/SOURCES.txt +1 -0
  10. {datatorch-0.8.4 → datatorch-0.8.5}/setup.py +1 -1
  11. {datatorch-0.8.4 → datatorch-0.8.5}/README.md +0 -0
  12. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/__init__.py +0 -0
  13. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/agent/__init__.py +0 -0
  14. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/__init__.py +0 -0
  15. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/api.py +0 -0
  16. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/client.py +0 -0
  17. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/__init__.py +0 -0
  18. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/annotation.py +0 -0
  19. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/base.py +0 -0
  20. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/dataset.py +0 -0
  21. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/file.py +0 -0
  22. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/label.py +0 -0
  23. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/project.py +0 -0
  24. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/settings.py +0 -0
  25. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/sources/__init__.py +0 -0
  26. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/sources/image/__init__.py +0 -0
  27. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/sources/image/bounding_box.py +0 -0
  28. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/sources/image/segmentations.py +0 -0
  29. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/sources/image/typings.py +0 -0
  30. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/sources/source.py +0 -0
  31. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/storage_link.py +0 -0
  32. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/entity/user.py +0 -0
  33. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/scripts/__init__.py +0 -0
  34. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/scripts/import_coco.py +0 -0
  35. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/scripts/import_coco_server.py +0 -0
  36. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/scripts/import_pixmask.py +0 -0
  37. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/scripts/utils/__init__.py +0 -0
  38. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/scripts/utils/simplify.py +0 -0
  39. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/utils.py +0 -0
  40. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/api/where.py +0 -0
  41. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/__init__.py +0 -0
  42. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/action/__init__.py +0 -0
  43. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/action/create.py +0 -0
  44. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/action/pull.py +0 -0
  45. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/action/run.py +0 -0
  46. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/groups.py +0 -0
  47. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/import_cmds/__init__.py +0 -0
  48. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/import_cmds/coco.py +0 -0
  49. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/import_cmds/pixmask.py +0 -0
  50. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/main/__init__.py +0 -0
  51. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/main/login.py +0 -0
  52. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/main/logout.py +0 -0
  53. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/main/upgrade.py +0 -0
  54. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/main/version.py +0 -0
  55. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/pipeline/__init__.py +0 -0
  56. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/pipeline/generate.py +0 -0
  57. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/pipeline/run.py +0 -0
  58. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/pipeline/upload.py +0 -0
  59. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/runner/__init__.py +0 -0
  60. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/runner/create.py +0 -0
  61. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/runner/dir.py +0 -0
  62. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/runner/start.py +0 -0
  63. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/spinner.py +0 -0
  64. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/upload/__init__.py +0 -0
  65. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/upload/folder.py +0 -0
  66. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/cli/utils.py +0 -0
  67. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/core/__init__.py +0 -0
  68. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/core/env.py +0 -0
  69. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/core/folder.py +0 -0
  70. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/core/settings.py +0 -0
  71. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/__init__.py +0 -0
  72. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/directory.py +0 -0
  73. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/log_handler.py +0 -0
  74. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/logging.py +0 -0
  75. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/__init__.py +0 -0
  76. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/action/__init__.py +0 -0
  77. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/action/action.py +0 -0
  78. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/action/cache.py +0 -0
  79. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/action/config.py +0 -0
  80. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/job/__init__.py +0 -0
  81. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/job/job.py +0 -0
  82. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/pipeline.py +0 -0
  83. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/resolver.py +0 -0
  84. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/runner/__init__.py +0 -0
  85. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/runner/command.py +0 -0
  86. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/runner/docker.py +0 -0
  87. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/runner/factory.py +0 -0
  88. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/runner/node.py +0 -0
  89. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/runner/python.py +0 -0
  90. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/runner/runner.py +0 -0
  91. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/runner/shell.py +0 -0
  92. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/step/__init__.py +0 -0
  93. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/step/step.py +0 -0
  94. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/pipelines/template.py +0 -0
  95. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/services/__init__.py +0 -0
  96. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/utils/__init__.py +0 -0
  97. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/utils/docker.py +0 -0
  98. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/runner/utils/process.py +0 -0
  99. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/utils/__init__.py +0 -0
  100. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/utils/converters.py +0 -0
  101. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/utils/files.py +0 -0
  102. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/utils/hash_table.py +0 -0
  103. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/utils/objects.py +0 -0
  104. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/utils/package.py +0 -0
  105. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/utils/string_style.py +0 -0
  106. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch/utils/url.py +0 -0
  107. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch.egg-info/dependency_links.txt +0 -0
  108. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch.egg-info/entry_points.txt +0 -0
  109. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch.egg-info/not-zip-safe +0 -0
  110. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch.egg-info/requires.txt +0 -0
  111. {datatorch-0.8.4 → datatorch-0.8.5}/datatorch.egg-info/top_level.txt +0 -0
  112. {datatorch-0.8.4 → datatorch-0.8.5}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datatorch
3
- Version: 0.8.4
3
+ Version: 0.8.5
4
4
  Summary: A CLI and library for interacting with DataTorch.
5
5
  Home-page: https://github.com/datatorch/python
6
6
  Author: DataTorch
@@ -111,11 +111,48 @@ ANNOTATION_FILENAMES = {
111
111
 
112
112
  ANNOTATIONS_BUILD_TIMEOUT = 600 # seconds
113
113
 
114
+ # The verified-email gate on dataset downloads (server, November 2026): a
115
+ # person who is not part of a project verifies their email before taking
116
+ # its data. The server refuses each file with this code; asking up front
117
+ # says so before anything is listed, and has the link sent.
118
+ VERIFY_REQUIRED_QUERY = """
119
+ query PullVerificationRequired($projectId: ID!) {
120
+ downloadVerificationRequired(projectId: $projectId)
121
+ }
122
+ """
123
+
124
+ SEND_VERIFICATION_MUTATION = """
125
+ mutation PullSendVerification($projectId: ID!) {
126
+ sendDownloadVerificationEmail(projectId: $projectId)
127
+ }
128
+ """
129
+
130
+ EMAIL_NOT_VERIFIED = "EMAIL_NOT_VERIFIED"
131
+ VERIFY_POLL_SECONDS = 5
132
+
133
+ VERIFY_HEADLINE = "Verify your email to download this dataset."
134
+ VERIFY_SENT = "We sent a link to the address on your account."
135
+ VERIFY_NOT_SENT = (
136
+ "We could not send the link just now. Open the one from when you signed "
137
+ "up, or ask for a new one from the dataset's Download button on the web."
138
+ )
139
+ VERIFY_RETRY = "Open it, then run this command again."
140
+
114
141
 
115
142
  class PullError(Exception):
116
143
  """User-facing pull failure (bad input, auth, server error)."""
117
144
 
118
145
 
146
+ class PullVerificationRequired(PullError):
147
+ """The account's email is not verified, and this download asks for it."""
148
+
149
+
150
+ def verification_message(sent: bool) -> str:
151
+ if sent:
152
+ return f"{VERIFY_HEADLINE} {VERIFY_SENT} {VERIFY_RETRY}"
153
+ return f"{VERIFY_HEADLINE} {VERIFY_NOT_SENT} Then run this command again."
154
+
155
+
119
156
  @dataclass
120
157
  class PullFile:
121
158
  file_id: str # live File id — what /api/file/v1/<id> resolves
@@ -183,12 +220,39 @@ class _PullSession:
183
220
  body = r.json()
184
221
  errors = body.get("errors")
185
222
  if errors:
223
+ if any(
224
+ (e.get("extensions") or {}).get("code") == EMAIL_NOT_VERIFIED
225
+ for e in errors
226
+ ):
227
+ raise PullVerificationRequired(verification_message(True))
186
228
  message = "; ".join(e.get("message", "unknown error") for e in errors)
187
229
  if _AUTH_ERROR_RE.search(message):
188
230
  raise PullError(self._auth_hint(message))
189
231
  raise PullError(message)
190
232
  return body.get("data") or {}
191
233
 
234
+ def ask(self, query: str, variables: dict) -> Optional[dict]:
235
+ """
236
+ A question the pull can go on without: None on any failure. A server
237
+ older than the question answers HTTP 400 (unknown field), and the
238
+ pull then runs as it always did.
239
+ """
240
+ try:
241
+ r = self.session.post(
242
+ self.graphql_url,
243
+ json={"query": query, "variables": variables},
244
+ headers=self.headers,
245
+ timeout=30,
246
+ )
247
+ if r.status_code >= 400:
248
+ return None
249
+ body = r.json()
250
+ except (requests.RequestException, ValueError):
251
+ return None
252
+ if not isinstance(body, dict) or body.get("errors"):
253
+ return None
254
+ return body.get("data") or None
255
+
192
256
  def _auth_hint(self, message: str) -> str:
193
257
  hint = (
194
258
  "This project requires authentication (or does not exist)."
@@ -217,6 +281,50 @@ def _none_safe(value: Optional[dict]) -> dict:
217
281
  return value or {}
218
282
 
219
283
 
284
+ def _verification_required(api: _PullSession, project_id: str) -> bool:
285
+ data = api.ask(VERIFY_REQUIRED_QUERY, {"projectId": project_id})
286
+ return bool((data or {}).get("downloadVerificationRequired"))
287
+
288
+
289
+ def _ensure_verified(
290
+ api: _PullSession,
291
+ project_id: str,
292
+ wait_seconds: int = 0,
293
+ on_waiting: Optional[Callable[[bool], None]] = None,
294
+ on_verified: Optional[Callable[[], None]] = None,
295
+ ) -> None:
296
+ """
297
+ Stop here when the server asks for a verified email before this
298
+ download. Has the link sent (the server does not send a second one
299
+ within ten minutes of the last), then either waits for the person to
300
+ open it (`wait_seconds`, for someone at a terminal) or raises.
301
+ """
302
+ if not _verification_required(api, project_id):
303
+ return
304
+ data = api.ask(SEND_VERIFICATION_MUTATION, {"projectId": project_id})
305
+ sent = bool((data or {}).get("sendDownloadVerificationEmail"))
306
+
307
+ if wait_seconds > 0:
308
+ if on_waiting:
309
+ on_waiting(sent)
310
+ deadline = time.time() + wait_seconds
311
+ while time.time() < deadline:
312
+ time.sleep(VERIFY_POLL_SECONDS)
313
+ if not _verification_required(api, project_id):
314
+ if on_verified:
315
+ on_verified()
316
+ return
317
+ raise PullVerificationRequired(verification_message(sent))
318
+
319
+
320
+ def _refused_for_verification(response) -> bool:
321
+ """True when the file route refused with the verified-email code."""
322
+ try:
323
+ return (response.json() or {}).get("code") == EMAIL_NOT_VERIFIED
324
+ except ValueError:
325
+ return False
326
+
327
+
220
328
  def _select_datasets(project: dict, dataset_name: Optional[str]) -> list:
221
329
  nodes = [d for d in (project.get("datasets") or {}).get("nodes") or [] if d]
222
330
  if dataset_name is None:
@@ -401,6 +509,8 @@ def _download_one(
401
509
  return "missing"
402
510
  if r.status_code in (401, 403):
403
511
  abort.set()
512
+ if r.status_code == 403 and _refused_for_verification(r):
513
+ raise PullVerificationRequired(verification_message(True))
404
514
  if api.anonymous:
405
515
  raise PullError(
406
516
  "Downloading files requires a DataTorch account. "
@@ -507,6 +617,9 @@ def pull_project(
507
617
  annotations: Optional[str] = None,
508
618
  on_start: Optional[Callable[[str, int], None]] = None,
509
619
  on_file_done: Optional[Callable[[str], None]] = None,
620
+ verify_wait_seconds: int = 0,
621
+ on_verify_waiting: Optional[Callable[[bool], None]] = None,
622
+ on_verified: Optional[Callable[[], None]] = None,
510
623
  ) -> dict:
511
624
  """
512
625
  Download a project's dataset files. Returns a tally dict:
@@ -514,9 +627,17 @@ def pull_project(
514
627
 
515
628
  on_start(dataset_name, file_count) fires per dataset before downloads;
516
629
  on_file_done(outcome) fires per completed file (any outcome).
630
+
631
+ When the server asks for a verified email first, the link is sent and
632
+ PullVerificationRequired is raised, unless verify_wait_seconds says to
633
+ wait for the person to open it: on_verify_waiting(sent) fires once
634
+ before the wait, on_verified() when it ends well.
517
635
  """
518
636
  api = _PullSession(api_url, api_key, workers)
519
637
  project = _resolve_project(api, owner, slug)
638
+ _ensure_verified(
639
+ api, project["id"], verify_wait_seconds, on_verify_waiting, on_verified
640
+ )
520
641
  out_dir = out or f"./{project.get('slug') or slug}"
521
642
 
522
643
  datasets = _select_datasets(project, dataset)
@@ -1,9 +1,21 @@
1
+ import sys
2
+
1
3
  import click
2
4
  from tqdm import tqdm
3
5
 
4
6
  from datatorch.core import BASE_URL_API, user_settings
5
7
  from datatorch.utils.url import normalize_api_url
6
- from datatorch.api.pull import PullError, pull_project
8
+ from datatorch.api.pull import (
9
+ VERIFY_HEADLINE,
10
+ VERIFY_NOT_SENT,
11
+ VERIFY_SENT,
12
+ PullError,
13
+ pull_project,
14
+ )
15
+
16
+ # How long a pull at a terminal waits for the person to open the
17
+ # verification link before it gives up (a script never waits).
18
+ VERIFY_WAIT_SECONDS = 600
7
19
 
8
20
 
9
21
  @click.command(help="Download a project's dataset files (requires login).")
@@ -49,7 +61,9 @@ def pull(path, dataset, version_name, out, workers, force, annotations_format, h
49
61
 
50
62
  Requires a DataTorch account: run `datatorch login` (or set
51
63
  DATATORCH_API_KEY). Public projects stay browsable on the web without an
52
- account, but file downloads are account-gated.
64
+ account, but file downloads are account-gated. A project you are not
65
+ part of also asks for a verified email: the link is sent when you pull,
66
+ and at a terminal the pull waits for you to open it.
53
67
  """
54
68
  parts = [p for p in path.split("/") if p]
55
69
  if len(parts) != 2:
@@ -92,6 +106,13 @@ def pull(path, dataset, version_name, out, workers, force, annotations_format, h
92
106
  counts[outcome] = counts.get(outcome, 0) + 1
93
107
  bar.set_postfix(counts, refresh=False)
94
108
 
109
+ def on_verify_waiting(sent: bool):
110
+ click.echo(f"{VERIFY_HEADLINE} {VERIFY_SENT if sent else VERIFY_NOT_SENT}")
111
+ click.echo("Waiting for you to open the link. Press Ctrl-C to stop.")
112
+
113
+ def on_verified():
114
+ click.echo(click.style("Email verified.", fg="green"))
115
+
95
116
  try:
96
117
  tally = pull_project(
97
118
  api_url,
@@ -106,6 +127,9 @@ def pull(path, dataset, version_name, out, workers, force, annotations_format, h
106
127
  annotations=annotations_format,
107
128
  on_start=on_start,
108
129
  on_file_done=on_file_done,
130
+ verify_wait_seconds=VERIFY_WAIT_SECONDS if sys.stdin.isatty() else 0,
131
+ on_verify_waiting=on_verify_waiting,
132
+ on_verified=on_verified,
109
133
  )
110
134
  except PullError as ex:
111
135
  if progress["bar"] is not None:
@@ -1,6 +1,7 @@
1
1
  from typing import AsyncGenerator, List, Optional, cast
2
2
  from gql import gql
3
3
  from .directory import runner_directory
4
+ from datatorch.utils.aio import wait_within
4
5
  from gql.client import AsyncClientSession
5
6
  from gql.transport.exceptions import TransportError, TransportQueryError
6
7
  from websockets.exceptions import ConnectionClosed
@@ -137,7 +138,7 @@ class AgentApiClient(object):
137
138
  async def wait_connected(self, timeout: Optional[float] = None) -> bool:
138
139
  """Waits until a session is attached. False when `timeout` ran out."""
139
140
  try:
140
- await asyncio.wait_for(self._connected.wait(), timeout)
141
+ await wait_within(self._connected.wait(), timeout)
141
142
  return True
142
143
  except asyncio.TimeoutError:
143
144
  return False
@@ -11,6 +11,7 @@ from .directory import runner_directory
11
11
 
12
12
  from gql.client import AsyncClientSession
13
13
  from datatorch.runner.pipelines.step import Step
14
+ from datatorch.utils.aio import wait_within
14
15
 
15
16
  logger = logging.getLogger(__name__)
16
17
 
@@ -116,6 +117,10 @@ class RunnerDaemon(object):
116
117
  cancelled: a websocket blip is not a reason to kill a four-hour
117
118
  step. Idempotent."""
118
119
  self.api.detach()
120
+ if self.system_stats is not None:
121
+ # Belt and braces with the cancel below: the monitor's loop
122
+ # also ends on its own flag (see `AgentSystemStats.stop`).
123
+ self.system_stats.stop()
119
124
  for task in self._service_tasks:
120
125
  if not task.done():
121
126
  task.cancel()
@@ -344,12 +349,12 @@ class RunnerDaemon(object):
344
349
  await self.api.wait_connected(timeout=remaining)
345
350
  continue
346
351
  try:
352
+ # `wait_within`, not `asyncio.wait_for`: a stop that lands as
353
+ # the call returns must still stop this step's task.
347
354
  if not logs_sent:
348
- await asyncio.wait_for(
349
- step.upload_logs(), REPORT_CALL_TIMEOUT_SECONDS
350
- )
355
+ await wait_within(step.upload_logs(), REPORT_CALL_TIMEOUT_SECONDS)
351
356
  logs_sent = True
352
- accepted = await asyncio.wait_for(send(), REPORT_CALL_TIMEOUT_SECONDS)
357
+ accepted = await wait_within(send(), REPORT_CALL_TIMEOUT_SECONDS)
353
358
  except asyncio.CancelledError:
354
359
  raise
355
360
  except Exception as e:
@@ -8,6 +8,7 @@ import json
8
8
  from psutil._common import scpufreq
9
9
  from datetime import datetime, timezone
10
10
  from datatorch.utils.package import get_version
11
+ from datatorch.utils.aio import wait_within
11
12
  from datatorch.runner.directory import runner_directory
12
13
  from collections import namedtuple
13
14
 
@@ -82,6 +83,19 @@ class AgentSystemStats(object):
82
83
  self.sample = 0
83
84
  self.report_failures = 0
84
85
  self.local_actions_digest = None
86
+ self.stopped = False
87
+
88
+ def stop(self) -> None:
89
+ """This monitor's connection is over: its loop ends at the next
90
+ check and sends nothing more.
91
+
92
+ The daemon also cancels the task; the flag is what ends the loop
93
+ when that cancel does not come through. One monitor serves one
94
+ connection, so a monitor that outlives its connection reports
95
+ beside the next one's: before 0.8.5 a websocket that dropped under
96
+ a metric report in flight left the old loop running (see
97
+ `datatorch.utils.aio.wait_within`), and each such drop added one."""
98
+ self.stopped = True
85
99
 
86
100
  async def start(self):
87
101
  try:
@@ -92,6 +106,7 @@ class AgentSystemStats(object):
92
106
 
93
107
  logger.info("Starting system monitoring task.")
94
108
  await self._task_monitoring()
109
+ logger.info("Exiting system monitoring task.")
95
110
  except asyncio.CancelledError:
96
111
  logger.info("Exiting system monitoring task.")
97
112
 
@@ -99,11 +114,13 @@ class AgentSystemStats(object):
99
114
  logger.debug(f"Sampling system stats every {self.sample_rate} seconds.")
100
115
  psutil.cpu_percent()
101
116
 
102
- while True:
117
+ while not self.stopped:
103
118
  self.sample += 1
104
119
  stats = self.stats()
105
120
  if self.sample != 1:
106
121
  await self._report(stats)
122
+ if self.stopped:
123
+ break
107
124
  # A folder dropped into actions/local shows up in the
108
125
  # editor within a minute, no restart needed.
109
126
  await self._report_local_actions()
@@ -124,7 +141,7 @@ class AgentSystemStats(object):
124
141
  if digest == self.local_actions_digest:
125
142
  return
126
143
  try:
127
- await asyncio.wait_for(
144
+ await wait_within(
128
145
  self.agent.api.report_local_actions(actions),
129
146
  timeout=self.REPORT_TIMEOUT,
130
147
  )
@@ -138,13 +155,17 @@ class AgentSystemStats(object):
138
155
  async def _report(self, stats):
139
156
  """Sends one metric report; repeated failures force a reconnect."""
140
157
  try:
141
- await asyncio.wait_for(
158
+ await wait_within(
142
159
  self.agent.api.metrics(stats), timeout=self.REPORT_TIMEOUT
143
160
  )
144
161
  self.report_failures = 0
145
162
  except asyncio.CancelledError:
146
163
  raise
147
164
  except Exception as e:
165
+ if self.stopped:
166
+ # The connection this monitor served is already gone; its
167
+ # last report failing says nothing about the next one.
168
+ return
148
169
  self.report_failures += 1
149
170
  logger.warning(
150
171
  f"Metric report failed ({self.report_failures}/{self.MAX_REPORT_FAILURES}): {e}"
@@ -0,0 +1,60 @@
1
+ import asyncio
2
+ from typing import Awaitable, Optional, TypeVar
3
+
4
+ T = TypeVar("T")
5
+
6
+
7
+ def _consume(task: "asyncio.Future") -> None:
8
+ """Marks a discarded call's error as seen, so asyncio does not log
9
+ "Task exception was never retrieved" for it."""
10
+ if not task.cancelled():
11
+ task.exception()
12
+
13
+
14
+ async def _stop(task: "asyncio.Future") -> None:
15
+ """Cancels `task` and waits until it has really finished. A cancel of
16
+ the caller that lands during the wait passes through."""
17
+ task.add_done_callback(_consume)
18
+ if task.done():
19
+ return
20
+ waiter = asyncio.get_running_loop().create_future()
21
+
22
+ def release(_):
23
+ if not waiter.done():
24
+ waiter.set_result(None)
25
+
26
+ task.add_done_callback(release)
27
+ task.cancel()
28
+ try:
29
+ await waiter
30
+ finally:
31
+ task.remove_done_callback(release)
32
+
33
+
34
+ async def wait_within(awaitable: Awaitable[T], timeout: Optional[float]) -> T:
35
+ """Awaits `awaitable` for at most `timeout` seconds (None: no limit).
36
+
37
+ Raises `asyncio.TimeoutError` when the time runs out, after cancelling
38
+ the call and waiting for it to finish.
39
+
40
+ Use it instead of `asyncio.wait_for` wherever the caller may be
41
+ cancelled. Before Python 3.12, `wait_for` drops a cancel that arrives in
42
+ the same event-loop tick as the call's own result or error: the caller
43
+ gets that result or error and never learns it was cancelled. A websocket
44
+ dying under a call in flight produces exactly that tick (the call fails,
45
+ and the daemon cancels its per-connection tasks), which left one extra
46
+ monitoring loop behind per such drop: the prod runner was sending 19
47
+ metric reports a minute on 2026-11-27. Here a cancel of the caller is
48
+ always re-raised, whatever the call did.
49
+ """
50
+ task = asyncio.ensure_future(awaitable)
51
+ try:
52
+ await asyncio.wait({task}, timeout=timeout)
53
+ except asyncio.CancelledError:
54
+ await _stop(task)
55
+ raise
56
+ if not task.done():
57
+ await _stop(task)
58
+ if task.cancelled():
59
+ raise asyncio.TimeoutError()
60
+ return task.result()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datatorch
3
- Version: 0.8.4
3
+ Version: 0.8.5
4
4
  Summary: A CLI and library for interacting with DataTorch.
5
5
  Home-page: https://github.com/datatorch/python
6
6
  Author: DataTorch
@@ -100,6 +100,7 @@ datatorch/runner/utils/__init__.py
100
100
  datatorch/runner/utils/docker.py
101
101
  datatorch/runner/utils/process.py
102
102
  datatorch/utils/__init__.py
103
+ datatorch/utils/aio.py
103
104
  datatorch/utils/converters.py
104
105
  datatorch/utils/files.py
105
106
  datatorch/utils/hash_table.py
@@ -33,7 +33,7 @@ requirements = [
33
33
 
34
34
  setup(
35
35
  name="datatorch",
36
- version="0.8.4",
36
+ version="0.8.5",
37
37
  description="A CLI and library for interacting with DataTorch.",
38
38
  author="DataTorch",
39
39
  author_email="support@datatorch.io",
File without changes
File without changes