aind-codeocean-dispatch 0.6.0__py3-none-any.whl → 0.7.0__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.
@@ -0,0 +1,118 @@
1
+ """Bounded retrieval of worker-produced failure artifacts.
2
+
3
+ Install the ``diagnostics`` extra to use this module. Callers supply the stage
4
+ and unit rather than teaching the dispatcher their capsule parameter names.
5
+ Fetching diagnostics never changes whether a computation succeeded.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from dataclasses import dataclass, replace
12
+ from typing import Any
13
+
14
+ import requests
15
+ from codeocean.error import Error as CodeOceanError
16
+
17
+ from .runner import Outcome
18
+
19
+ REPORT_LIMIT = 2 * 1024 * 1024
20
+ FAILURE_LIMIT = 64 * 1024
21
+ _UNAVAILABLE = (CodeOceanError, requests.RequestException, OSError, ValueError, KeyError, TypeError, RecursionError)
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class WorkerFailure:
26
+ """An explanation and optional evidence from one failed computation."""
27
+
28
+ computation_id: str
29
+ filename: str
30
+ error: str
31
+ report: dict[str, Any] | None = None
32
+
33
+ def render(self) -> str:
34
+ """Include the worker and exact results artifact for follow-up."""
35
+ return f"{self.error}; worker {self.computation_id}; details: {self.filename} in worker results"
36
+
37
+
38
+ def result_json(client: Any, computation_id: str, filename: str, limit: int = REPORT_LIMIT) -> dict[str, Any]:
39
+ """Read a JSON object with bounded download size and request timeout.
40
+
41
+ This lower-level function propagates errors for callers that require the
42
+ artifact. Signed download URLs are used for the request and never logged.
43
+ """
44
+ if limit <= 0:
45
+ raise ValueError("An artifact byte limit must be positive")
46
+ urls = client.computations.get_result_file_urls(computation_id, filename)
47
+ with requests.get(urls.download_url, stream=True, timeout=30) as response:
48
+ response.raise_for_status()
49
+ content = bytearray()
50
+ for chunk in response.iter_content(chunk_size=4096):
51
+ content.extend(chunk)
52
+ if len(content) > limit:
53
+ raise ValueError("Worker artifact exceeds limit")
54
+ value = json.loads(content)
55
+ if not isinstance(value, dict):
56
+ raise TypeError("Worker artifact is not an object")
57
+ return value
58
+
59
+
60
+ def worker_diagnostic_report(
61
+ client: Any, computation_id: str, stage: str, unit: str | None, failure: dict[str, Any]
62
+ ) -> dict[str, Any] | None:
63
+ """Prefer full evidence, retaining a valid summary when detail is unavailable."""
64
+ from aind_code_ocean_pipeline_utils.failure_reporting import diagnostic_path
65
+ from aind_diagnostics import validate_report
66
+
67
+ packet = failure.get("diagnostic_summary")
68
+ if not isinstance(packet, dict):
69
+ return None
70
+ try:
71
+ fallback = validate_report({**packet, "diagnostics": []})
72
+ except _UNAVAILABLE:
73
+ return None
74
+ path = (diagnostic_path(stage, unit) / "report.json").as_posix()
75
+ if failure.get("diagnostic_report_file") == path:
76
+ try:
77
+ return validate_report(result_json(client, computation_id, path))
78
+ except _UNAVAILABLE:
79
+ pass
80
+ fallback["facts"]["diagnostic_details_available"] = False
81
+ return fallback
82
+
83
+
84
+ def worker_failure(client: Any, computation_id: str, stage: str, unit: str | None = None) -> WorkerFailure | None:
85
+ """Read new or legacy failure artifacts, returning None when unavailable.
86
+
87
+ Only the expected stage/unit report path is fetched. A producer cannot
88
+ redirect the orchestrator to an unrelated result file. Callers retain their
89
+ existing fallback for older workers with no structured artifacts.
90
+ """
91
+ from aind_code_ocean_pipeline_utils.failure_reporting import diagnostic_path, safe_text
92
+
93
+ try:
94
+ filename = (diagnostic_path(stage, unit) / "failure.json").as_posix()
95
+ failure = result_json(client, computation_id, filename, FAILURE_LIMIT)
96
+ if type(failure.get("schema_version")) is not int or failure["schema_version"] != 1:
97
+ raise ValueError("Unknown failure report version")
98
+ if not isinstance(failure.get("error"), str):
99
+ raise TypeError("Invalid failure explanation")
100
+ report = worker_diagnostic_report(client, computation_id, stage, unit, failure)
101
+ error = report["summary"] if report is not None else safe_text(failure["error"])
102
+ causes = failure.get("causes") or []
103
+ if report is None and len(causes) > 1:
104
+ cause = causes[-1]
105
+ error += safe_text(f"; caused by {cause['type']}: {cause['message']}")
106
+ return WorkerFailure(computation_id, filename, error, report)
107
+ except _UNAVAILABLE:
108
+ return None
109
+
110
+
111
+ def diagnose_outcome(client: Any, outcome: Outcome, stage: str, unit: str | None = None) -> Outcome:
112
+ """Attach worker evidence without changing status, retry class, or capture state."""
113
+ if outcome.status != "failed" or not outcome.computation_ids:
114
+ return outcome
115
+ failure = worker_failure(client, outcome.computation_ids[-1], stage, unit)
116
+ if failure is None:
117
+ return outcome
118
+ return replace(outcome, error=failure.render(), diagnostic_report=failure.report)
@@ -140,6 +140,7 @@ class Outcome:
140
140
  error: str | None = None
141
141
  failure: Failure | None = None
142
142
  resumed: bool = False
143
+ diagnostic_report: dict[str, Any] | None = None
143
144
 
144
145
  @property
145
146
  def ok(self) -> bool:
@@ -160,6 +161,14 @@ class DispatchFailed(RuntimeError):
160
161
  lines = [f"{len(self.failures)} job(s) failed:"]
161
162
  lines += [f" {o.job.label}: {o.error}" for o in self.failures]
162
163
  super().__init__("\n".join(lines))
164
+ reports = [outcome.diagnostic_report for outcome in self.failures if outcome.diagnostic_report is not None]
165
+ if reports:
166
+ try:
167
+ from aind_diagnostics import combined_report
168
+
169
+ self.diagnostic_report = combined_report(reports)
170
+ except (ImportError, ValueError, TypeError, KeyError, RecursionError):
171
+ logger.warning("Could not combine worker diagnostics; original dispatch failure is retained")
163
172
 
164
173
 
165
174
  class DispatchInterrupted(GracefulExit):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: aind-codeocean-dispatch
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: Launch, monitor, and capture batches of Code Ocean capsule runs
5
5
  Project-URL: Repository, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/
6
6
  Project-URL: Issues, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/issues
@@ -13,6 +13,9 @@ Classifier: Programming Language :: Python :: 3
13
13
  Requires-Python: >=3.11
14
14
  Requires-Dist: aind-code-ocean-pipeline-utils>=0.7.1
15
15
  Requires-Dist: codeocean>=0.13
16
+ Provides-Extra: diagnostics
17
+ Requires-Dist: aind-code-ocean-pipeline-utils[diagnostics]<1,>=0.10.0; extra == 'diagnostics'
18
+ Requires-Dist: aind-diagnostics<1,>=0.2.0; extra == 'diagnostics'
16
19
  Description-Content-Type: text/markdown
17
20
 
18
21
  # AIND Code Ocean dispatch
@@ -140,3 +143,40 @@ Setup, checks, tests and conventions are in [CONTRIBUTING.md](CONTRIBUTING.md).
140
143
  ## License
141
144
 
142
145
  This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
146
+
147
+ ## Worker diagnostics
148
+
149
+ Install `aind-codeocean-dispatch[diagnostics]` when workers emit structured
150
+ failure artifacts. The extra uses `aind-diagnostics` for the report contract and
151
+ `aind-code-ocean-pipeline-utils` for the shared artifact namespace.
152
+
153
+ Optional reporting dependencies load when the reporting helpers are used, so
154
+ importing the module also works with the base installation.
155
+
156
+ ```python
157
+ from aind_codeocean_dispatch import raise_for_failures, run_jobs
158
+ from aind_codeocean_dispatch.diagnostics import diagnose_outcome
159
+
160
+ outcomes = run_jobs(client, jobs)
161
+ outcomes = [diagnose_outcome(client, item, stage="ephys", unit=item.job.label) for item in outcomes]
162
+ raise_for_failures(outcomes)
163
+ ```
164
+
165
+ Supply the stage and unit that the worker used when saving its report; the
166
+ dispatcher does not infer capsule-specific parameter names. `diagnose_outcome`
167
+ adds `diagnostic_report` and a readable explanation to failed outcomes while
168
+ preserving their status, failure classification, and capture state. Successful
169
+ outcomes are unchanged. `DispatchFailed` combines attached reports and retains
170
+ the individual failures for per-worker facts and provenance.
171
+
172
+ `worker_failure` reads the small failure header and then its namespaced report.
173
+ It bounds downloads, validates the common schema and causal graph, accepts new
174
+ domain codes, and keeps the producer's summary when full evidence is missing,
175
+ malformed, or larger than 2 MiB. It returns `None` when no usable header exists,
176
+ so callers can retain their fallback for older workers. Result-file errors
177
+ cannot replace the original computation failure, and signed download URLs are
178
+ never included in the returned explanation.
179
+
180
+ For other required JSON artifacts, `result_json` provides the same bounded
181
+ reader but propagates retrieval errors. Domain facts such as manifest coverage
182
+ remain the caller's responsibility.
@@ -2,9 +2,10 @@ aind_codeocean_dispatch/__init__.py,sha256=v8QJf40j_JhvvabsZlLLfXtscdDkfTAw6KTIG
2
2
  aind_codeocean_dispatch/automation.py,sha256=_7yPA8dJee2zLOY1vcPhdfFLoqDtiNY60hdz6INj11Q,6120
3
3
  aind_codeocean_dispatch/capsule_git.py,sha256=BnUiGY1blXAFqnNAztBbYX0h5U5Mlsm5M2sFsOa4ICk,2762
4
4
  aind_codeocean_dispatch/capture.py,sha256=aj3dgLNtGRmKhUbVZeIcPjfbPP42YYiz6gwMGwZSlAg,3506
5
+ aind_codeocean_dispatch/diagnostics.py,sha256=6KsS6JR7mLBz-D9H3Boohs7AJ7skxd80U49RnKoWT-Q,4994
5
6
  aind_codeocean_dispatch/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
6
- aind_codeocean_dispatch/runner.py,sha256=09WI4BYr9KBV7qH5VcNMCmFDUgKbuV9TKadLWGmxQNU,37096
7
- aind_codeocean_dispatch-0.6.0.dist-info/METADATA,sha256=Bj1bUoPCTkFGqxv50F8qJAu81FTQNkBHj6UwDdDInUA,6722
8
- aind_codeocean_dispatch-0.6.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
- aind_codeocean_dispatch-0.6.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
10
- aind_codeocean_dispatch-0.6.0.dist-info/RECORD,,
7
+ aind_codeocean_dispatch/runner.py,sha256=kPJvNVHRoD-nYzvFPNScHxMN3DNoDzqNeAmG0GnVF3Q,37622
8
+ aind_codeocean_dispatch-0.7.0.dist-info/METADATA,sha256=Iw20-frOEGI3jiS5o09YN-K2_mlxszkvFAq9_wAymhk,8765
9
+ aind_codeocean_dispatch-0.7.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ aind_codeocean_dispatch-0.7.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
11
+ aind_codeocean_dispatch-0.7.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.4
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any