aind-diagnostics 0.2.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,33 @@
1
+ """Structured diagnostics for scientific data processing."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from .models import (
6
+ DIAGNOSTIC_VERSION,
7
+ Diagnostic,
8
+ DiagnosticError,
9
+ DiagnosticReport,
10
+ Outcome,
11
+ ReportedFailure,
12
+ combined_report,
13
+ safe_value,
14
+ validate_report,
15
+ )
16
+
17
+ __all__ = [
18
+ "DIAGNOSTIC_VERSION",
19
+ "Diagnostic",
20
+ "DiagnosticError",
21
+ "DiagnosticReport",
22
+ "Outcome",
23
+ "ReportedFailure",
24
+ "combined_report",
25
+ "safe_value",
26
+ "validate_report",
27
+ ]
28
+
29
+ try:
30
+ __version__ = version("aind-diagnostics")
31
+ except PackageNotFoundError:
32
+ # imported without being installed: valid PEP 440, below every release, and plainly not one
33
+ __version__ = "0+unknown"
@@ -0,0 +1,235 @@
1
+ """Portable failed expectations and validated causal reports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import re
9
+ from collections import defaultdict, deque
10
+ from typing import Annotated, Any, Final, Literal
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field, JsonValue, StrictStr, ValidationInfo, model_validator
13
+ from typing_extensions import Self
14
+
15
+ DIAGNOSTIC_VERSION: Final = "1.0.0"
16
+ Outcome = Literal["failed", "unknown", "unsupported", "blocked"]
17
+ NonEmpty = Annotated[StrictStr, Field(min_length=1)]
18
+
19
+
20
+ def safe_value(value: Any) -> Any:
21
+ """Copy JSON evidence, redact URL queries, and normalize nonfinite floats.
22
+
23
+ Callers must omit secrets in other forms before constructing a diagnostic.
24
+ Unsupported objects remain subject to Pydantic's JSON-value validation.
25
+ """
26
+ if isinstance(value, str):
27
+ return re.sub(r"(https?://[^\s?]+)\?[^\s]+", r"\1?[redacted]", value)
28
+ if isinstance(value, dict):
29
+ return {str(key): safe_value(item) for key, item in value.items()}
30
+ if isinstance(value, (list, tuple)):
31
+ return [safe_value(item) for item in value]
32
+ if isinstance(value, float) and not math.isfinite(value):
33
+ return str(value)
34
+ return value
35
+
36
+
37
+ class _Model(BaseModel):
38
+ """Validate producer and receiver data through the same JSON contract."""
39
+
40
+ model_config = ConfigDict(frozen=True, extra="forbid")
41
+
42
+ @model_validator(mode="before")
43
+ @classmethod
44
+ def _sanitize(cls, value: Any) -> Any:
45
+ """Sanitize before computing identities or explaining evidence."""
46
+ return safe_value(value)
47
+
48
+
49
+ class Diagnostic(_Model):
50
+ """Describe one expectation, its evidence, and an actionable next step."""
51
+
52
+ code: NonEmpty
53
+ message: NonEmpty
54
+ expected: NonEmpty
55
+ observed: dict[str, JsonValue]
56
+ next_step: NonEmpty
57
+ subject: dict[str, JsonValue] = Field(default_factory=dict)
58
+ evidence: tuple[dict[str, JsonValue], ...] = ()
59
+ outcome: Outcome = "failed"
60
+ severity: Literal["error", "warning", "info"] = "error"
61
+ caused_by: tuple[NonEmpty, ...] = ()
62
+ # Wire v1 also permits opaque IDs supplied by older producers.
63
+ id: NonEmpty = Field(default="", validate_default=False)
64
+
65
+ @model_validator(mode="before")
66
+ @classmethod
67
+ def _wire_fields(cls, value: Any, info: ValidationInfo) -> Any:
68
+ """Require complete serialized entries while allowing producer defaults."""
69
+ if info.context and info.context.get("wire"):
70
+ required = set(cls.model_fields)
71
+ if not isinstance(value, dict) or not required.issubset(value):
72
+ raise ValueError("Incomplete diagnostic definition")
73
+ return value
74
+
75
+ @model_validator(mode="after")
76
+ def _identity(self) -> Self:
77
+ """Keep generated IDs stable across presentation and cause linking."""
78
+ if not self.id:
79
+ content = json.dumps([self.code, self.subject, self.observed, self.evidence], sort_keys=True)
80
+ object.__setattr__(self, "id", hashlib.sha256(content.encode()).hexdigest()[:24])
81
+ return self
82
+
83
+ def updated(self, **changes: Any) -> Diagnostic:
84
+ """Validate replacements and recompute identity from the new evidence."""
85
+ return Diagnostic.model_validate({**self.model_dump(exclude={"id"}), **changes})
86
+
87
+ def to_dict(self) -> dict[str, Any]:
88
+ """Return the JSON wire representation, including the stable ID."""
89
+ return self.model_dump(mode="json")
90
+
91
+
92
+ class DiagnosticReport(_Model):
93
+ """Carry a causal graph and domain-owned facts across process boundaries.
94
+
95
+ A supplied summary belongs to the producer and is preserved on receipt.
96
+ Otherwise the report groups root causes into a bounded text explanation.
97
+ Facts have JSON types; their meaning and validation belong to the producer.
98
+ """
99
+
100
+ schema_version: Literal["1.0.0"] = DIAGNOSTIC_VERSION
101
+ diagnostics: tuple[Diagnostic, ...] = Field(max_length=2000)
102
+ facts: dict[str, JsonValue] = Field(default_factory=dict)
103
+ summary: Annotated[StrictStr, Field(max_length=16000)] | None = None
104
+
105
+ @model_validator(mode="after")
106
+ def _check_graph(self) -> Self:
107
+ """Reject duplicate IDs, missing causes, and cycles without recursion."""
108
+ by_id = {entry.id: entry for entry in self.diagnostics}
109
+ if len(by_id) != len(self.diagnostics):
110
+ raise ValueError("Duplicate diagnostic IDs")
111
+ remaining = {key: set(entry.caused_by) for key, entry in by_id.items()}
112
+ if any(not causes.issubset(by_id) for causes in remaining.values()):
113
+ raise ValueError("Missing diagnostic cause")
114
+ children: dict[str, list[str]] = {key: [] for key in by_id}
115
+ for key, causes in remaining.items():
116
+ for cause in causes:
117
+ children[cause].append(key)
118
+ ready = deque(key for key, causes in remaining.items() if not causes)
119
+ visited = 0
120
+ while ready:
121
+ key = ready.popleft()
122
+ visited += 1
123
+ for child in children[key]:
124
+ remaining[child].remove(key)
125
+ if not remaining[child]:
126
+ ready.append(child)
127
+ if visited != len(by_id):
128
+ raise ValueError("Diagnostic cause cycle")
129
+ if self.summary is None:
130
+ object.__setattr__(self, "summary", _render(self.diagnostics))
131
+ return self
132
+
133
+ def render(self) -> str:
134
+ """Return the producer's bounded human-readable explanation."""
135
+ return self.summary or ""
136
+
137
+ def to_dict(self) -> dict[str, Any]:
138
+ """Serialize the versioned contract without dropping evidence."""
139
+ return self.model_dump(mode="json")
140
+
141
+
142
+ def _render(diagnostics: tuple[Diagnostic, ...]) -> str:
143
+ """Group root causes while retaining every affected subject in JSON."""
144
+ groups: dict[str, list[Diagnostic]] = defaultdict(list)
145
+ for diagnostic in diagnostics:
146
+ if diagnostic.caused_by:
147
+ continue
148
+ key = json.dumps(
149
+ [
150
+ diagnostic.code,
151
+ diagnostic.message,
152
+ diagnostic.expected,
153
+ diagnostic.observed,
154
+ diagnostic.next_step,
155
+ diagnostic.outcome,
156
+ diagnostic.severity,
157
+ ],
158
+ sort_keys=True,
159
+ )
160
+ groups[key].append(diagnostic)
161
+ lines = []
162
+ priority = {"error": 0, "warning": 1, "info": 2}
163
+ for entries in sorted(groups.values(), key=lambda items: priority[items[0].severity]):
164
+ first = entries[0]
165
+ lines.append(f"{first.message} [{first.code}]")
166
+ subjects = sorted({_subject(entry.subject) for entry in entries})
167
+ lines.append(f"Affected ({len(subjects)}): " + "; ".join(subjects[:5]))
168
+ if len(subjects) > 5:
169
+ lines.append(f" and {len(subjects) - 5} more; see full diagnostics.")
170
+ lines.append(f"Expected: {first.expected}")
171
+ for key, value in first.observed.items():
172
+ text = json.dumps(value, ensure_ascii=False)
173
+ lines.append(f"{key.replace('_', ' ').capitalize()}: {text[:800]}")
174
+ lines.extend([f"Next step: {first.next_step}", ""])
175
+ text = "\n".join(lines).strip()
176
+ if len(text) > 12000:
177
+ text = text[:11800].rsplit("\n", 1)[0] + "\nAdditional diagnoses are retained in the full report."
178
+ return text
179
+
180
+
181
+ def _subject(subject: dict[str, JsonValue]) -> str:
182
+ """Prefer authorable locations over internal inventory hashes."""
183
+ location = "/".join(str(subject[key]) for key in ("recording", "collection") if subject.get(key))
184
+ location = location or "/".join(str(subject[key]) for key in ("asset", "path") if subject.get(key)) or "run"
185
+ if subject.get("row") is not None:
186
+ location += f" row {subject['row']}"
187
+ if subject.get("column"):
188
+ location += f" ({subject['column']})"
189
+ if subject.get("layer"):
190
+ location += f" layer {subject['layer']}"
191
+ return location
192
+
193
+
194
+ def validate_report(report: Any) -> dict[str, Any]:
195
+ """Validate a complete wire report while accepting unknown domain codes."""
196
+ if not isinstance(report, dict) or not {"schema_version", "diagnostics", "facts", "summary"}.issubset(report):
197
+ raise ValueError("Incomplete diagnostic report")
198
+ if report["summary"] is None:
199
+ raise ValueError("Invalid diagnostic summary")
200
+ return DiagnosticReport.model_validate(report, context={"wire": True}).to_dict()
201
+
202
+
203
+ def combined_report(reports: list[dict[str, Any]]) -> dict[str, Any]:
204
+ """Combine report graphs and explanations; later facts replace earlier keys.
205
+
206
+ Orchestrators should keep per-worker reports alongside this aggregate when
207
+ the same fact key describes different jobs. The aggregate is for display.
208
+ """
209
+ diagnostics, facts, summaries = {}, {}, []
210
+ for report in reports:
211
+ checked = validate_report(report)
212
+ diagnostics.update({entry["id"]: entry for entry in checked["diagnostics"]})
213
+ facts.update(checked["facts"])
214
+ summaries.append(checked["summary"])
215
+ return DiagnosticReport(
216
+ diagnostics=tuple(Diagnostic.model_validate(entry) for entry in diagnostics.values()),
217
+ facts=facts,
218
+ summary="\n\n".join(dict.fromkeys(summaries))[:16000],
219
+ ).to_dict()
220
+
221
+
222
+ class DiagnosticError(ValueError):
223
+ """Stop a domain operation while retaining a machine-readable report."""
224
+
225
+ def __init__(self, report: DiagnosticReport) -> None:
226
+ self.diagnostic_report = report.to_dict()
227
+ super().__init__(report.render())
228
+
229
+
230
+ class ReportedFailure(RuntimeError):
231
+ """Propagate a validated remote report without interpreting its codes."""
232
+
233
+ def __init__(self, report: dict[str, Any]) -> None:
234
+ self.diagnostic_report = validate_report(report)
235
+ super().__init__(self.diagnostic_report["summary"])
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.5
2
+ Name: aind-diagnostics
3
+ Version: 0.2.0
4
+ Summary: Structured diagnostics for scientific data processing
5
+ Project-URL: Repository, https://github.com/AllenNeuralDynamics/aind-diagnostics/
6
+ Project-URL: Issues, https://github.com/AllenNeuralDynamics/aind-diagnostics/issues
7
+ Project-URL: Changelog, https://github.com/AllenNeuralDynamics/aind-diagnostics/blob/main/CHANGELOG.md
8
+ Author: Allen Institute for Neural Dynamics
9
+ Author-email: Galen Lynch <galen@galenlynch.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: pydantic<3,>=2.10
15
+ Requires-Dist: typing-extensions>=4.12
16
+ Description-Content-Type: text/markdown
17
+
18
+ # AIND diagnostics
19
+
20
+ `aind-diagnostics` gives Python libraries a common way to explain failed checks.
21
+ A diagnostic records what was expected, what was observed, which input is affected,
22
+ and what the user can do next. Reports retain that evidence as JSON and provide a
23
+ short explanation for people reading pipeline output.
24
+
25
+ The package targets PyPI and Python 3.10 or newer. Once released, install it with
26
+ `uv add aind-diagnostics`. For development, use `uv sync` in this checkout.
27
+
28
+ ```python
29
+ from aind_diagnostics import Diagnostic, DiagnosticError, DiagnosticReport
30
+
31
+ missing = Diagnostic(
32
+ code="input.collection_absent",
33
+ message="The requested collection was not found.",
34
+ expected="A recorded collection named ProbeA.",
35
+ observed={"available_collections": ["ProbeB", "ProbeC"]},
36
+ subject={"asset": "recording-123", "collection": "ProbeA"},
37
+ next_step="Check the collection name against the recording metadata.",
38
+ )
39
+ report = DiagnosticReport(diagnostics=(missing,), facts={"inputs_inspected": 1})
40
+ print(report.render())
41
+ payload = report.to_dict()
42
+ # Stop an operation while retaining evidence for the execution host:
43
+ raise DiagnosticError(report)
44
+ ```
45
+
46
+ ## Reports and causes
47
+
48
+ Each diagnostic has a stable `id`, a `code`, a severity (`error`, `warning`, or
49
+ `info`), and an outcome. Use `failed` for an observed unmet expectation, `unknown`
50
+ when inspection could not establish the answer, `unsupported` for a known case
51
+ that the software cannot handle, and `blocked` when another failed check prevented
52
+ evaluation. A blocked diagnostic links to its prerequisites through `caused_by`.
53
+
54
+ Construct a report containing both causes and consequences. Reports reject
55
+ repeated IDs, missing references, and cycles. Their text groups root causes and
56
+ lists affected inputs; their JSON retains every diagnostic. `diagnostic.updated(...)`
57
+ validates changes and recomputes the ID when evidence changes. Pydantic's
58
+ `model_copy(update=...)` skips validation and should not be used for this purpose.
59
+
60
+ One report holds up to 2,000 diagnostics. A generated explanation is at most
61
+ 12,000 characters; an explanation supplied by a producer can be up to 16,000.
62
+ Larger sets of checks should be split into reports for separate work units.
63
+
64
+ The wire format has its own `schema_version`, currently `1.0.0`, independent of
65
+ the package release. `validate_report(payload)` validates incoming JSON, preserves
66
+ the producer's summary, and accepts diagnostic codes it has never seen. Generate
67
+ the schema with `DiagnosticReport.model_json_schema()`.
68
+
69
+ `subject`, `observed`, `evidence`, and `facts` contain JSON values. Their domain
70
+ meaning belongs to the library producing them. For example, an ephys library
71
+ defines what constitutes a valid recording; this package validates the report
72
+ structure and its causal graph. Display summaries are bounded; full evidence
73
+ remains in the report. URL queries are redacted before identity calculation and
74
+ serialization. Producers must omit credentials in other forms themselves.
75
+
76
+ ## Integration
77
+
78
+ Scientific libraries depend only on this package and Pydantic. Execution hosts
79
+ can catch `DiagnosticError` or inspect an exception's `diagnostic_report`
80
+ attribute. `ReportedFailure` carries a validated report received from another
81
+ process. `combined_report` provides a display aggregate; keep individual worker
82
+ reports when facts with the same key refer to different jobs.
83
+
84
+ Code Ocean report files and exception rendering belong in
85
+ `aind-code-ocean-pipeline-utils[diagnostics]`. Fetching reports from remote
86
+ computations belongs in `aind-codeocean-dispatch[diagnostics]`. Neither is a
87
+ dependency of this package.
88
+
89
+ Development and validation commands are in [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -0,0 +1,7 @@
1
+ aind_diagnostics/__init__.py,sha256=mUK0q8VhyXt541dkw6NZvkI2Xjf165viHQyR7GJiM-w,738
2
+ aind_diagnostics/models.py,sha256=5t_qplooYwvXlWqPUQBDM0-44qnkyo1WgYZjnZG3_m8,9784
3
+ aind_diagnostics/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
4
+ aind_diagnostics-0.2.0.dist-info/METADATA,sha256=IKK4E9FFBcxkBIz0h3LiOgTHPszd4ylWHaUO5uGMjPQ,4425
5
+ aind_diagnostics-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ aind_diagnostics-0.2.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
7
+ aind_diagnostics-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Allen Institute for Neural Dynamics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+