mechlens 0.1.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.
mechlens-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: mechlens
3
+ Version: 0.1.0
4
+ Summary: Record and share mechanistic interpretability experiments
5
+ Author: MechLens
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://mechlens-cloud-fgstc.ondigitalocean.app
8
+ Keywords: interpretability,mechanistic-interpretability,sae,steering,experiments
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: httpx<1,>=0.27
22
+ Requires-Dist: python-dotenv<2,>=1
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest<9,>=8; extra == "test"
25
+ Provides-Extra: docs
26
+ Requires-Dist: mkdocs<2,>=1.6; extra == "docs"
27
+ Requires-Dist: mkdocs-material<10,>=9.7; extra == "docs"
28
+ Requires-Dist: mkdocstrings-python<3,>=2; extra == "docs"
29
+ Requires-Dist: ruff; extra == "docs"
30
+ Dynamic: license-file
31
+
32
+ # MechLens Python SDK
33
+
34
+ The lightweight client for recording an experiment in existing Python code and
35
+ sending it to MechLens Cloud. Model execution and metric calculation stay in the
36
+ researcher's code.
37
+
38
+ This package is intentionally separate from the GPU application and has no
39
+ Torch, TransformerLens, or SAE dependencies.
40
+
41
+ ## Try the complete upload flow
42
+
43
+ The included demo sends a synthetic baseline and steered run with the same four
44
+ prompt IDs. It exercises local saving, API-key authentication, validation, and
45
+ Cloud ingestion without downloading a model.
46
+
47
+ Create an API key from **MechLens → Account → API keys**. Put it in
48
+ `examples/.env` (the demo loads this file automatically):
49
+
50
+ ```dotenv
51
+ MECHLENS_API_KEY="ml_your_key_here"
52
+ # Omit this line to upload to MechLens Cloud. For a local Cloud:
53
+ MECHLENS_API_URL="http://localhost:5175"
54
+ ```
55
+
56
+ Then run:
57
+
58
+ ```bash
59
+ cd /path/to/mechlens-sdk
60
+ python3 -m venv .venv
61
+ source .venv/bin/activate
62
+ pip install -e .
63
+ python examples/steering_demo.py
64
+ ```
65
+
66
+ Variables exported in your shell take priority over values in `examples/.env`.
67
+
68
+ The script prints both saved-run URLs and keeps local JSON copies under
69
+ `.mechlens/runs/`. Its outputs are clearly marked synthetic and are only for
70
+ testing the integration.
71
+
72
+ ## Use it in an experiment
73
+
74
+ ```python
75
+ import mechlens
76
+
77
+ run = mechlens.start_run(
78
+ project="refusal-steering",
79
+ name="strength-2",
80
+ model={"id": "google/gemma-2-2b", "revision": "exact-revision"},
81
+ config={"feature_id": 1234, "steering_strength": 2.0, "seed": 42},
82
+ question="Does steering this feature reduce refusals?",
83
+ dataset={"id": "refusal-prompts", "revision": "v1"},
84
+ )
85
+
86
+ for example in dataset:
87
+ answer = generate_with_steering(example["prompt"], strength=2.0)
88
+ run.log_example(id=example["id"], input=example["prompt"], output=answer)
89
+
90
+ run.log_metrics({"refusal_rate": measured_refusal_rate})
91
+ receipt = run.finish()
92
+ print(receipt.url)
93
+ ```
94
+
95
+ Set `MECHLENS_API_KEY` to the account key. Runs upload to MechLens Cloud
96
+ (`https://mechlens-cloud-fgstc.ondigitalocean.app`); set `MECHLENS_API_URL` for another deployment, such as
97
+ `http://localhost:5175` during local development.
98
+ Finished runs are written atomically to `.mechlens/runs/<run-id>.json` before
99
+ upload. Set `MECHLENS_DIR` to choose another local directory.
100
+
101
+ ## Local development
102
+
103
+ ```bash
104
+ python3 -m venv .venv
105
+ source .venv/bin/activate
106
+ pip install -e '.[test]'
107
+ pytest
108
+ ```
109
+
110
+ ## Documentation
111
+
112
+ The user docs live in `docs/` and build with Material for MkDocs. The API
113
+ reference is generated from the docstrings in `src/mechlens`, so update those
114
+ when the public API changes.
115
+
116
+ ```bash
117
+ pip install -e '.[docs]'
118
+ mkdocs serve # preview at http://127.0.0.1:8000
119
+ mkdocs build # static site in site/ (strict: broken links fail)
120
+ ```
121
+
122
+ ## Cloud contract
123
+
124
+ The SDK sends `POST /api/sdk/runs` with an `Authorization: Bearer ...`
125
+ header and an `Idempotency-Key` equal to the run ID. Cloud returns:
126
+
127
+ ```json
128
+ {"run_id": "...", "url": "https://.../app/projects/.../runs/..."}
129
+ ```
130
+
131
+ If an upload fails, `finish()` preserves the completed local run and raises
132
+ `MechLensUploadError`. Call `run.retry_upload()` to retry during the same
133
+ process.
@@ -0,0 +1,102 @@
1
+ # MechLens Python SDK
2
+
3
+ The lightweight client for recording an experiment in existing Python code and
4
+ sending it to MechLens Cloud. Model execution and metric calculation stay in the
5
+ researcher's code.
6
+
7
+ This package is intentionally separate from the GPU application and has no
8
+ Torch, TransformerLens, or SAE dependencies.
9
+
10
+ ## Try the complete upload flow
11
+
12
+ The included demo sends a synthetic baseline and steered run with the same four
13
+ prompt IDs. It exercises local saving, API-key authentication, validation, and
14
+ Cloud ingestion without downloading a model.
15
+
16
+ Create an API key from **MechLens → Account → API keys**. Put it in
17
+ `examples/.env` (the demo loads this file automatically):
18
+
19
+ ```dotenv
20
+ MECHLENS_API_KEY="ml_your_key_here"
21
+ # Omit this line to upload to MechLens Cloud. For a local Cloud:
22
+ MECHLENS_API_URL="http://localhost:5175"
23
+ ```
24
+
25
+ Then run:
26
+
27
+ ```bash
28
+ cd /path/to/mechlens-sdk
29
+ python3 -m venv .venv
30
+ source .venv/bin/activate
31
+ pip install -e .
32
+ python examples/steering_demo.py
33
+ ```
34
+
35
+ Variables exported in your shell take priority over values in `examples/.env`.
36
+
37
+ The script prints both saved-run URLs and keeps local JSON copies under
38
+ `.mechlens/runs/`. Its outputs are clearly marked synthetic and are only for
39
+ testing the integration.
40
+
41
+ ## Use it in an experiment
42
+
43
+ ```python
44
+ import mechlens
45
+
46
+ run = mechlens.start_run(
47
+ project="refusal-steering",
48
+ name="strength-2",
49
+ model={"id": "google/gemma-2-2b", "revision": "exact-revision"},
50
+ config={"feature_id": 1234, "steering_strength": 2.0, "seed": 42},
51
+ question="Does steering this feature reduce refusals?",
52
+ dataset={"id": "refusal-prompts", "revision": "v1"},
53
+ )
54
+
55
+ for example in dataset:
56
+ answer = generate_with_steering(example["prompt"], strength=2.0)
57
+ run.log_example(id=example["id"], input=example["prompt"], output=answer)
58
+
59
+ run.log_metrics({"refusal_rate": measured_refusal_rate})
60
+ receipt = run.finish()
61
+ print(receipt.url)
62
+ ```
63
+
64
+ Set `MECHLENS_API_KEY` to the account key. Runs upload to MechLens Cloud
65
+ (`https://mechlens-cloud-fgstc.ondigitalocean.app`); set `MECHLENS_API_URL` for another deployment, such as
66
+ `http://localhost:5175` during local development.
67
+ Finished runs are written atomically to `.mechlens/runs/<run-id>.json` before
68
+ upload. Set `MECHLENS_DIR` to choose another local directory.
69
+
70
+ ## Local development
71
+
72
+ ```bash
73
+ python3 -m venv .venv
74
+ source .venv/bin/activate
75
+ pip install -e '.[test]'
76
+ pytest
77
+ ```
78
+
79
+ ## Documentation
80
+
81
+ The user docs live in `docs/` and build with Material for MkDocs. The API
82
+ reference is generated from the docstrings in `src/mechlens`, so update those
83
+ when the public API changes.
84
+
85
+ ```bash
86
+ pip install -e '.[docs]'
87
+ mkdocs serve # preview at http://127.0.0.1:8000
88
+ mkdocs build # static site in site/ (strict: broken links fail)
89
+ ```
90
+
91
+ ## Cloud contract
92
+
93
+ The SDK sends `POST /api/sdk/runs` with an `Authorization: Bearer ...`
94
+ header and an `Idempotency-Key` equal to the run ID. Cloud returns:
95
+
96
+ ```json
97
+ {"run_id": "...", "url": "https://.../app/projects/.../runs/..."}
98
+ ```
99
+
100
+ If an upload fails, `finish()` preserves the completed local run and raises
101
+ `MechLensUploadError`. Call `run.retry_upload()` to retry during the same
102
+ process.
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mechlens"
7
+ version = "0.1.0"
8
+ description = "Record and share mechanistic interpretability experiments"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "MechLens" }]
13
+ requires-python = ">=3.10"
14
+ keywords = ["interpretability", "mechanistic-interpretability", "sae", "steering", "experiments"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Science/Research",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = ["httpx>=0.27,<1", "python-dotenv>=1,<2"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://mechlens-cloud-fgstc.ondigitalocean.app"
30
+
31
+ [project.optional-dependencies]
32
+ test = ["pytest>=8,<9"]
33
+ docs = ["mkdocs>=1.6,<2", "mkdocs-material>=9.7,<10", "mkdocstrings-python>=2,<3", "ruff"]
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.setuptools.package-data]
39
+ mechlens = ["py.typed"]
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,18 @@
1
+ """Public interface for the MechLens experiment SDK."""
2
+
3
+ from .client import CloudClient, UploadReceipt
4
+ from .errors import MechLensConfigurationError, MechLensError, MechLensUploadError
5
+ from .run import Run, start_run
6
+
7
+ __all__ = [
8
+ "CloudClient",
9
+ "MechLensConfigurationError",
10
+ "MechLensError",
11
+ "MechLensUploadError",
12
+ "Run",
13
+ "UploadReceipt",
14
+ "start_run",
15
+ ]
16
+
17
+ __version__ = "0.1.0"
18
+
@@ -0,0 +1,118 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from .errors import MechLensUploadError
10
+
11
+ # Statuses where sending the same run again cannot succeed.
12
+ _NOT_RETRYABLE = {
13
+ 400: "Cloud could not read the run.",
14
+ 401: "Check MECHLENS_API_KEY: the key is missing, invalid, or revoked.",
15
+ 403: "This key cannot upload to the workspace.",
16
+ 409: "A different run with this ID already exists. Record the run again to get a new ID.",
17
+ 413: "The run is larger than Cloud accepts. Log fewer or shorter examples.",
18
+ 422: "Cloud rejected the run's contents. Fix the run and record it again.",
19
+ }
20
+
21
+
22
+ def _server_detail(response: httpx.Response) -> str:
23
+ """Cloud's explanation of a failed request, from FastAPI JSON or a plain-text body."""
24
+ try:
25
+ detail = response.json().get("detail")
26
+ except (ValueError, AttributeError):
27
+ return response.text.strip()[:500]
28
+ if isinstance(detail, list):
29
+ # Request validation errors: [{"loc": [...], "msg": "..."}, ...]
30
+ return "; ".join(
31
+ f"{'.'.join(str(part) for part in item.get('loc', []))}: {item.get('msg', '')}"
32
+ if isinstance(item, dict)
33
+ else str(item)
34
+ for item in detail
35
+ )
36
+ return str(detail) if detail else response.text.strip()[:500]
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class UploadReceipt:
41
+ """Confirmation that Cloud stored a run.
42
+
43
+ Attributes:
44
+ run_id: The run's ID, the same as the local record's.
45
+ url: Where to open the run in MechLens Cloud.
46
+ """
47
+
48
+ run_id: str
49
+ url: str
50
+
51
+
52
+ class CloudClient:
53
+ """Small synchronous client for the MechLens ingestion API."""
54
+
55
+ def __init__(
56
+ self,
57
+ *,
58
+ api_key: str,
59
+ base_url: str,
60
+ timeout: float = 30.0,
61
+ transport: httpx.BaseTransport | None = None,
62
+ ) -> None:
63
+ self.api_key = api_key
64
+ self.base_url = base_url.rstrip("/")
65
+ self.timeout = timeout
66
+ self.transport = transport
67
+
68
+ def upload_run(self, data: Mapping[str, Any], *, local_path) -> UploadReceipt:
69
+ """Send one finished run to Cloud.
70
+
71
+ Raises:
72
+ MechLensUploadError: Cloud could not be reached or rejected the run. Its
73
+ `status_code` and `retryable` attributes say whether to retry.
74
+ """
75
+ run_id = str(data["id"])
76
+ try:
77
+ with httpx.Client(
78
+ base_url=self.base_url,
79
+ timeout=self.timeout,
80
+ transport=self.transport,
81
+ follow_redirects=False,
82
+ trust_env=False,
83
+ ) as client:
84
+ response = client.post(
85
+ "/api/sdk/runs",
86
+ json=data,
87
+ headers={
88
+ "Authorization": f"Bearer {self.api_key}",
89
+ "Idempotency-Key": run_id,
90
+ "User-Agent": "mechlens-python/0.1.0",
91
+ },
92
+ )
93
+ response.raise_for_status()
94
+ payload = response.json()
95
+ returned_id = payload.get("run_id")
96
+ url = payload.get("url")
97
+ if returned_id != run_id or not isinstance(url, str) or not url:
98
+ raise ValueError("response is missing the expected run_id or url")
99
+ return UploadReceipt(run_id=returned_id, url=url)
100
+ except httpx.HTTPStatusError as exc:
101
+ status = exc.response.status_code
102
+ detail = _server_detail(exc.response)
103
+ hint = _NOT_RETRYABLE.get(status, "Call run.retry_upload() to try again.")
104
+ raise MechLensUploadError(
105
+ f"Cloud rejected the upload ({status}): {detail or exc.response.reason_phrase}. {hint}",
106
+ local_path=local_path,
107
+ status_code=status,
108
+ retryable=status not in _NOT_RETRYABLE,
109
+ ) from exc
110
+ except httpx.TransportError as exc:
111
+ raise MechLensUploadError(
112
+ f"Could not reach MechLens at {self.base_url}: {exc}. Check MECHLENS_API_URL and your "
113
+ "connection, then call run.retry_upload().",
114
+ local_path=local_path,
115
+ ) from exc
116
+ except (httpx.HTTPError, ValueError, TypeError) as exc:
117
+ raise MechLensUploadError(f"Could not upload run: {exc}.", local_path=local_path) from exc
118
+
@@ -0,0 +1,34 @@
1
+ from pathlib import Path
2
+
3
+
4
+ class MechLensError(Exception):
5
+ """Base exception raised by the SDK."""
6
+
7
+
8
+ class MechLensConfigurationError(MechLensError):
9
+ """The SDK is missing configuration required to contact MechLens."""
10
+
11
+
12
+ class MechLensUploadError(MechLensError):
13
+ """An upload failed after the run was safely stored on disk.
14
+
15
+ Attributes:
16
+ local_path: The saved copy of the run.
17
+ status_code: Cloud's HTTP status, or `None` if Cloud was never reached.
18
+ retryable: Whether retrying the same run could succeed. `False` for an
19
+ invalid key or a rejected run, which need fixing first.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ message: str,
25
+ *,
26
+ local_path: Path,
27
+ status_code: int | None = None,
28
+ retryable: bool = True,
29
+ ):
30
+ super().__init__(f"{message} Local copy: {local_path}")
31
+ self.local_path = local_path
32
+ self.status_code = status_code
33
+ self.retryable = retryable
34
+
File without changes
@@ -0,0 +1,298 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import os
6
+ import subprocess
7
+ import tempfile
8
+ import uuid
9
+ from collections.abc import Mapping
10
+ from copy import deepcopy
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ from .client import CloudClient, UploadReceipt
16
+ from .errors import MechLensConfigurationError
17
+
18
+ if TYPE_CHECKING:
19
+ from typing_extensions import Self
20
+
21
+ DEFAULT_API_URL = "https://mechlens-cloud-fgstc.ondigitalocean.app"
22
+
23
+
24
+ def _now() -> str:
25
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
26
+
27
+
28
+ def _git_commit() -> str | None:
29
+ try:
30
+ result = subprocess.run(
31
+ ["git", "rev-parse", "HEAD"],
32
+ capture_output=True,
33
+ text=True,
34
+ timeout=2,
35
+ check=True,
36
+ )
37
+ return result.stdout.strip() or None
38
+ except (OSError, subprocess.SubprocessError):
39
+ return None
40
+
41
+
42
+ def _json_copy(value: Any, *, label: str) -> Any:
43
+ try:
44
+ encoded = json.dumps(value, allow_nan=False)
45
+ return json.loads(encoded)
46
+ except (TypeError, ValueError) as exc:
47
+ raise ValueError(f"{label} must contain only finite JSON values") from exc
48
+
49
+
50
+ class Run:
51
+ """One experiment run, recorded locally and uploaded when finished.
52
+
53
+ Create runs with [`start_run`][mechlens.start_run] rather than directly. A run can
54
+ also be used as a context manager: leaving the `with` block without an exception
55
+ calls [`finish`][mechlens.Run.finish].
56
+
57
+ Attributes:
58
+ data: The run record that will be saved and uploaded.
59
+ local_path: Where the finished run is written as JSON.
60
+ """
61
+
62
+ def __init__(self, data: dict[str, Any], *, client: CloudClient, local_dir: Path) -> None:
63
+ self.data = data
64
+ self.client = client
65
+ self.local_path = local_dir / f"{data['id']}.json"
66
+ self._example_ids: set[str] = set()
67
+ self._sealed = False
68
+ self._receipt: UploadReceipt | None = None
69
+
70
+ def log_example(self, *, id: str, input: str, output: str, **fields: Any) -> None:
71
+ """Record one input and the model's output for it.
72
+
73
+ Use the same `id` for the same prompt in every run you want to compare;
74
+ MechLens matches examples across runs by ID.
75
+
76
+ Args:
77
+ id: Stable identifier for this example, unique within the run.
78
+ input: The prompt or input given to the model.
79
+ output: What the model produced.
80
+ **fields: Per-example measurements such as `refused=True` or
81
+ `helpfulness=4`. Values must be JSON-serializable. Cloud reports an
82
+ example as "behavior changed" when these fields differ between runs.
83
+
84
+ Raises:
85
+ ValueError: The ID is empty or already logged, or `fields` is not
86
+ JSON-serializable.
87
+ TypeError: `input` or `output` is not a string.
88
+ RuntimeError: The run is already finished.
89
+ """
90
+ self._ensure_open()
91
+ if not isinstance(id, str) or not id:
92
+ raise ValueError("example id must be a non-empty string")
93
+ if id in self._example_ids:
94
+ raise ValueError(f"example id {id!r} was already logged")
95
+ if not isinstance(input, str) or not isinstance(output, str):
96
+ raise TypeError("example input and output must be strings")
97
+ extra = _json_copy(fields, label="example fields")
98
+ forbidden = {"id", "input", "output"}.intersection(extra)
99
+ if forbidden:
100
+ raise ValueError(f"example fields cannot replace {sorted(forbidden)}")
101
+ self.data["examples"].append({"id": id, "input": input, "output": output, **extra})
102
+ self._example_ids.add(id)
103
+
104
+ def log_metrics(self, metrics: Mapping[str, Any]) -> None:
105
+ """Record run-level metrics, merging with any logged earlier.
106
+
107
+ Args:
108
+ metrics: Metric names mapped to JSON-serializable values. Numbers must be
109
+ finite. Names containing `rate` are shown as percentages in Cloud.
110
+
111
+ Raises:
112
+ ValueError: A key is empty, a value is not JSON-serializable, or a number
113
+ is NaN or infinite.
114
+ RuntimeError: The run is already finished.
115
+ """
116
+ self._ensure_open()
117
+ if not isinstance(metrics, Mapping) or not all(isinstance(key, str) and key for key in metrics):
118
+ raise ValueError("metrics must be a mapping with non-empty string keys")
119
+ clean = _json_copy(dict(metrics), label="metrics")
120
+ for key, value in clean.items():
121
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and not math.isfinite(value):
122
+ raise ValueError(f"metric {key!r} must be finite")
123
+ self.data["metrics"].update(clean)
124
+
125
+ def finish(self) -> UploadReceipt:
126
+ """Seal the run, save it to disk, then upload it.
127
+
128
+ The run is written to [`local_path`][mechlens.Run] before any network call,
129
+ so a failed upload never loses data. Calling `finish` again returns the same
130
+ receipt without uploading twice.
131
+
132
+ Returns:
133
+ The uploaded run's ID and its Cloud URL.
134
+
135
+ Raises:
136
+ MechLensUploadError: The upload failed. The local copy is kept. If the
137
+ error's `retryable` is true, call
138
+ [`retry_upload`][mechlens.Run.retry_upload]; otherwise its message
139
+ says what to fix.
140
+ """
141
+ if self._receipt is not None:
142
+ return self._receipt
143
+ if not self._sealed:
144
+ self.data["finished_at"] = _now()
145
+ self._sealed = True
146
+ self._save_local()
147
+ return self.retry_upload()
148
+
149
+ def retry_upload(self) -> UploadReceipt:
150
+ """Upload a finished run whose earlier upload failed.
151
+
152
+ Uploads use the run ID as an idempotency key, so retrying never creates a
153
+ duplicate run in Cloud.
154
+
155
+ Returns:
156
+ The uploaded run's ID and its Cloud URL.
157
+
158
+ Raises:
159
+ RuntimeError: The run has not been finished.
160
+ MechLensUploadError: The upload failed again.
161
+ """
162
+ if not self._sealed:
163
+ raise RuntimeError("finish the run before retrying its upload")
164
+ if self._receipt is None:
165
+ self._receipt = self.client.upload_run(self.data, local_path=self.local_path)
166
+ return self._receipt
167
+
168
+ def _save_local(self) -> None:
169
+ self.local_path.parent.mkdir(parents=True, exist_ok=True)
170
+ with tempfile.NamedTemporaryFile(
171
+ "w", encoding="utf-8", dir=self.local_path.parent, prefix=f".{self.local_path.name}.", delete=False
172
+ ) as handle:
173
+ temporary = Path(handle.name)
174
+ try:
175
+ json.dump(self.data, handle, indent=2, sort_keys=True, allow_nan=False)
176
+ handle.write("\n")
177
+ handle.flush()
178
+ os.fsync(handle.fileno())
179
+ except Exception:
180
+ temporary.unlink(missing_ok=True)
181
+ raise
182
+ os.replace(temporary, self.local_path)
183
+
184
+ def _ensure_open(self) -> None:
185
+ if self._sealed:
186
+ raise RuntimeError("this run is finished and cannot be changed")
187
+
188
+ def __enter__(self) -> Self:
189
+ return self
190
+
191
+ def __exit__(self, exc_type, exc, traceback) -> bool:
192
+ if exc_type is None:
193
+ self.finish()
194
+ return False
195
+
196
+
197
+ def start_run(
198
+ *,
199
+ project: str,
200
+ name: str,
201
+ model: Mapping[str, Any],
202
+ config: Mapping[str, Any],
203
+ question: str,
204
+ dataset: Mapping[str, Any] | None = None,
205
+ sae: Mapping[str, Any] | None = None,
206
+ intervention: Mapping[str, Any] | None = None,
207
+ generation: Mapping[str, Any] | None = None,
208
+ metric_definitions: Mapping[str, Any] | None = None,
209
+ code_commit: str | None = None,
210
+ api_key: str | None = None,
211
+ base_url: str | None = None,
212
+ local_dir: str | Path | None = None,
213
+ client: CloudClient | None = None,
214
+ ) -> Run:
215
+ """Create a local-first experiment run ready to receive examples and metrics.
216
+
217
+ Everything except `project`, `name`, `model`, `config` and `question` is optional,
218
+ but Cloud can only check what you record: a field missing from either run is
219
+ reported as unknown rather than assumed to match.
220
+
221
+ Args:
222
+ project: Groups runs that can be compared, such as a baseline and its
223
+ intervention.
224
+ name: This run's label within the project. A name containing `baseline` or
225
+ `control` is chosen as the default baseline in Cloud.
226
+ model: Must include `id`. Include `revision` so the comparison can confirm
227
+ both runs used the same weights.
228
+ config: Any other settings for this run, such as `seed` or
229
+ `steering_strength`.
230
+ question: The research question the run helps answer.
231
+ dataset: Where the examples came from, ideally with `id`, `revision` and
232
+ `split`.
233
+ sae: The sparse autoencoder used, if any.
234
+ intervention: What this run changes relative to the baseline. Leave it out of
235
+ the baseline run.
236
+ generation: Decoding settings such as `temperature` and `max_new_tokens`.
237
+ metric_definitions: Metric names mapped to how each is calculated, e.g.
238
+ `{"refusal_rate": {"description": "..."}}`.
239
+ code_commit: Commit of the code that produced the run. Detected with
240
+ `git rev-parse HEAD` when omitted.
241
+ api_key: Overrides the `MECHLENS_API_KEY` environment variable.
242
+ base_url: Overrides `MECHLENS_API_URL`. Defaults to MechLens Cloud,
243
+ `https://mechlens-cloud-fgstc.ondigitalocean.app`.
244
+ local_dir: Overrides `MECHLENS_DIR`, where finished runs are saved.
245
+ Defaults to `.mechlens/runs`.
246
+ client: A preconfigured [`CloudClient`][mechlens.CloudClient], mainly for
247
+ tests. When given, `api_key` and `base_url` are ignored.
248
+
249
+ Returns:
250
+ An open run. Log examples and metrics, then call
251
+ [`finish`][mechlens.Run.finish].
252
+
253
+ Raises:
254
+ ValueError: A required argument is empty or not JSON-serializable.
255
+ TypeError: `config` is not a mapping.
256
+ MechLensConfigurationError: No API key was passed or set in the environment.
257
+ """
258
+ for label, value in (("project", project), ("name", name), ("question", question)):
259
+ if not isinstance(value, str) or not value.strip():
260
+ raise ValueError(f"{label} must be a non-empty string")
261
+ if not isinstance(model, Mapping) or not isinstance(model.get("id"), str) or not model["id"]:
262
+ raise ValueError("model must include a non-empty string id")
263
+ if not isinstance(config, Mapping):
264
+ raise TypeError("config must be a mapping")
265
+
266
+ if client is None:
267
+ resolved_key = api_key or os.environ.get("MECHLENS_API_KEY")
268
+ if not resolved_key:
269
+ raise MechLensConfigurationError("Set MECHLENS_API_KEY or pass api_key to start_run")
270
+ resolved_url = base_url or os.environ.get("MECHLENS_API_URL", DEFAULT_API_URL)
271
+ client = CloudClient(api_key=resolved_key, base_url=resolved_url)
272
+
273
+ root = Path(local_dir or os.environ.get("MECHLENS_DIR", ".mechlens/runs")).expanduser()
274
+ data = {
275
+ "schema_version": 1,
276
+ "id": str(uuid.uuid4()),
277
+ "project": project.strip(),
278
+ "name": name.strip(),
279
+ "question": question.strip(),
280
+ "created_at": _now(),
281
+ "finished_at": None,
282
+ "model": _json_copy(dict(model), label="model"),
283
+ "code_commit": code_commit if code_commit is not None else _git_commit(),
284
+ "dataset": _json_copy(dict(dataset), label="dataset") if dataset is not None else None,
285
+ "sae": _json_copy(dict(sae), label="sae") if sae is not None else None,
286
+ "intervention": _json_copy(dict(intervention), label="intervention") if intervention is not None else None,
287
+ "generation": _json_copy(dict(generation), label="generation") if generation is not None else None,
288
+ "config": _json_copy(dict(config), label="config"),
289
+ "metric_definitions": (
290
+ _json_copy(dict(metric_definitions), label="metric_definitions")
291
+ if metric_definitions is not None
292
+ else None
293
+ ),
294
+ "metrics": {},
295
+ "examples": [],
296
+ }
297
+ return Run(deepcopy(data), client=client, local_dir=root)
298
+
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: mechlens
3
+ Version: 0.1.0
4
+ Summary: Record and share mechanistic interpretability experiments
5
+ Author: MechLens
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://mechlens-cloud-fgstc.ondigitalocean.app
8
+ Keywords: interpretability,mechanistic-interpretability,sae,steering,experiments
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: httpx<1,>=0.27
22
+ Requires-Dist: python-dotenv<2,>=1
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest<9,>=8; extra == "test"
25
+ Provides-Extra: docs
26
+ Requires-Dist: mkdocs<2,>=1.6; extra == "docs"
27
+ Requires-Dist: mkdocs-material<10,>=9.7; extra == "docs"
28
+ Requires-Dist: mkdocstrings-python<3,>=2; extra == "docs"
29
+ Requires-Dist: ruff; extra == "docs"
30
+ Dynamic: license-file
31
+
32
+ # MechLens Python SDK
33
+
34
+ The lightweight client for recording an experiment in existing Python code and
35
+ sending it to MechLens Cloud. Model execution and metric calculation stay in the
36
+ researcher's code.
37
+
38
+ This package is intentionally separate from the GPU application and has no
39
+ Torch, TransformerLens, or SAE dependencies.
40
+
41
+ ## Try the complete upload flow
42
+
43
+ The included demo sends a synthetic baseline and steered run with the same four
44
+ prompt IDs. It exercises local saving, API-key authentication, validation, and
45
+ Cloud ingestion without downloading a model.
46
+
47
+ Create an API key from **MechLens → Account → API keys**. Put it in
48
+ `examples/.env` (the demo loads this file automatically):
49
+
50
+ ```dotenv
51
+ MECHLENS_API_KEY="ml_your_key_here"
52
+ # Omit this line to upload to MechLens Cloud. For a local Cloud:
53
+ MECHLENS_API_URL="http://localhost:5175"
54
+ ```
55
+
56
+ Then run:
57
+
58
+ ```bash
59
+ cd /path/to/mechlens-sdk
60
+ python3 -m venv .venv
61
+ source .venv/bin/activate
62
+ pip install -e .
63
+ python examples/steering_demo.py
64
+ ```
65
+
66
+ Variables exported in your shell take priority over values in `examples/.env`.
67
+
68
+ The script prints both saved-run URLs and keeps local JSON copies under
69
+ `.mechlens/runs/`. Its outputs are clearly marked synthetic and are only for
70
+ testing the integration.
71
+
72
+ ## Use it in an experiment
73
+
74
+ ```python
75
+ import mechlens
76
+
77
+ run = mechlens.start_run(
78
+ project="refusal-steering",
79
+ name="strength-2",
80
+ model={"id": "google/gemma-2-2b", "revision": "exact-revision"},
81
+ config={"feature_id": 1234, "steering_strength": 2.0, "seed": 42},
82
+ question="Does steering this feature reduce refusals?",
83
+ dataset={"id": "refusal-prompts", "revision": "v1"},
84
+ )
85
+
86
+ for example in dataset:
87
+ answer = generate_with_steering(example["prompt"], strength=2.0)
88
+ run.log_example(id=example["id"], input=example["prompt"], output=answer)
89
+
90
+ run.log_metrics({"refusal_rate": measured_refusal_rate})
91
+ receipt = run.finish()
92
+ print(receipt.url)
93
+ ```
94
+
95
+ Set `MECHLENS_API_KEY` to the account key. Runs upload to MechLens Cloud
96
+ (`https://mechlens-cloud-fgstc.ondigitalocean.app`); set `MECHLENS_API_URL` for another deployment, such as
97
+ `http://localhost:5175` during local development.
98
+ Finished runs are written atomically to `.mechlens/runs/<run-id>.json` before
99
+ upload. Set `MECHLENS_DIR` to choose another local directory.
100
+
101
+ ## Local development
102
+
103
+ ```bash
104
+ python3 -m venv .venv
105
+ source .venv/bin/activate
106
+ pip install -e '.[test]'
107
+ pytest
108
+ ```
109
+
110
+ ## Documentation
111
+
112
+ The user docs live in `docs/` and build with Material for MkDocs. The API
113
+ reference is generated from the docstrings in `src/mechlens`, so update those
114
+ when the public API changes.
115
+
116
+ ```bash
117
+ pip install -e '.[docs]'
118
+ mkdocs serve # preview at http://127.0.0.1:8000
119
+ mkdocs build # static site in site/ (strict: broken links fail)
120
+ ```
121
+
122
+ ## Cloud contract
123
+
124
+ The SDK sends `POST /api/sdk/runs` with an `Authorization: Bearer ...`
125
+ header and an `Idempotency-Key` equal to the run ID. Cloud returns:
126
+
127
+ ```json
128
+ {"run_id": "...", "url": "https://.../app/projects/.../runs/..."}
129
+ ```
130
+
131
+ If an upload fails, `finish()` preserves the completed local run and raises
132
+ `MechLensUploadError`. Call `run.retry_upload()` to retry during the same
133
+ process.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/mechlens/__init__.py
5
+ src/mechlens/client.py
6
+ src/mechlens/errors.py
7
+ src/mechlens/py.typed
8
+ src/mechlens/run.py
9
+ src/mechlens.egg-info/PKG-INFO
10
+ src/mechlens.egg-info/SOURCES.txt
11
+ src/mechlens.egg-info/dependency_links.txt
12
+ src/mechlens.egg-info/requires.txt
13
+ src/mechlens.egg-info/top_level.txt
14
+ tests/test_run.py
@@ -0,0 +1,11 @@
1
+ httpx<1,>=0.27
2
+ python-dotenv<2,>=1
3
+
4
+ [docs]
5
+ mkdocs<2,>=1.6
6
+ mkdocs-material<10,>=9.7
7
+ mkdocstrings-python<3,>=2
8
+ ruff
9
+
10
+ [test]
11
+ pytest<9,>=8
@@ -0,0 +1 @@
1
+ mechlens
@@ -0,0 +1,179 @@
1
+ import json
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ import mechlens
7
+
8
+
9
+ def client(handler):
10
+ return mechlens.CloudClient(
11
+ api_key="test-key",
12
+ base_url="https://cloud.example",
13
+ transport=httpx.MockTransport(handler),
14
+ )
15
+
16
+
17
+ def test_finish_saves_before_upload_and_returns_receipt(tmp_path):
18
+ observed = {}
19
+
20
+ def accept(request):
21
+ observed["authorization"] = request.headers["authorization"]
22
+ observed["idempotency_key"] = request.headers["idempotency-key"]
23
+ observed["body"] = json.loads(request.content)
24
+ assert run.local_path.exists()
25
+ return httpx.Response(201, json={"run_id": observed["body"]["id"], "url": "https://cloud.example/run/1"})
26
+
27
+ run = mechlens.start_run(
28
+ project="refusal-steering",
29
+ name="strength-2",
30
+ model={"id": "google/gemma-2-2b", "revision": "abc"},
31
+ config={"steering_strength": 2.0},
32
+ question="Does steering reduce refusals?",
33
+ dataset={"id": "prompts", "revision": "v1"},
34
+ code_commit="deadbeef",
35
+ client=client(accept),
36
+ local_dir=tmp_path,
37
+ )
38
+ run.log_example(id="001", input="Hello", output="Hi")
39
+ run.log_metrics({"refusal_rate": 0.25})
40
+
41
+ receipt = run.finish()
42
+
43
+ assert receipt.url == "https://cloud.example/run/1"
44
+ assert observed["authorization"] == "Bearer test-key"
45
+ assert observed["idempotency_key"] == observed["body"]["id"]
46
+ saved = json.loads(run.local_path.read_text())
47
+ assert saved["examples"][0]["id"] == "001"
48
+ assert saved["metrics"] == {"refusal_rate": 0.25}
49
+ assert saved["sae"] is None
50
+ assert saved["intervention"] is None
51
+ assert saved["finished_at"].endswith("Z")
52
+
53
+
54
+ def test_failed_upload_keeps_local_copy_and_can_be_retried(tmp_path):
55
+ attempts = 0
56
+
57
+ def flaky(request):
58
+ nonlocal attempts
59
+ attempts += 1
60
+ if attempts == 1:
61
+ return httpx.Response(503, text="unavailable")
62
+ body = json.loads(request.content)
63
+ return httpx.Response(200, json={"run_id": body["id"], "url": "https://cloud.example/run/recovered"})
64
+
65
+ run = mechlens.start_run(
66
+ project="p",
67
+ name="baseline",
68
+ model={"id": "model"},
69
+ config={},
70
+ question="q",
71
+ code_commit="abc",
72
+ client=client(flaky),
73
+ local_dir=tmp_path,
74
+ )
75
+
76
+ with pytest.raises(mechlens.MechLensUploadError) as caught:
77
+ run.finish()
78
+ assert caught.value.local_path == run.local_path
79
+ assert run.local_path.exists()
80
+
81
+ assert run.retry_upload().url.endswith("/recovered")
82
+ assert attempts == 2
83
+
84
+
85
+ def test_duplicate_example_ids_and_changes_after_finish_are_rejected(tmp_path):
86
+ def accept(request):
87
+ body = json.loads(request.content)
88
+ return httpx.Response(200, json={"run_id": body["id"], "url": "https://cloud.example/run/1"})
89
+
90
+ run = mechlens.start_run(
91
+ project="p",
92
+ name="n",
93
+ model={"id": "m"},
94
+ config={},
95
+ question="q",
96
+ code_commit="abc",
97
+ client=client(accept),
98
+ local_dir=tmp_path,
99
+ )
100
+ run.log_example(id="same", input="one", output="one")
101
+ with pytest.raises(ValueError, match="already logged"):
102
+ run.log_example(id="same", input="two", output="two")
103
+
104
+ run.finish()
105
+ with pytest.raises(RuntimeError, match="finished"):
106
+ run.log_metrics({"late": 1})
107
+
108
+
109
+ def test_missing_api_key_fails_at_start(tmp_path, monkeypatch):
110
+ monkeypatch.delenv("MECHLENS_API_KEY", raising=False)
111
+ with pytest.raises(mechlens.MechLensConfigurationError):
112
+ mechlens.start_run(
113
+ project="p",
114
+ name="n",
115
+ model={"id": "m"},
116
+ config={},
117
+ question="q",
118
+ code_commit="abc",
119
+ local_dir=tmp_path,
120
+ )
121
+
122
+
123
+ def finished_upload_error(tmp_path, handler):
124
+ run = mechlens.start_run(
125
+ project="p",
126
+ name="n",
127
+ model={"id": "m"},
128
+ config={},
129
+ question="q",
130
+ code_commit="abc",
131
+ client=client(handler),
132
+ local_dir=tmp_path,
133
+ )
134
+ with pytest.raises(mechlens.MechLensUploadError) as caught:
135
+ run.finish()
136
+ return caught.value
137
+
138
+
139
+ @pytest.mark.parametrize(
140
+ ("response", "status", "retryable", "expected"),
141
+ [
142
+ (
143
+ httpx.Response(401, json={"detail": "Invalid or revoked MechLens API key"}),
144
+ 401,
145
+ False,
146
+ ["Invalid or revoked MechLens API key", "Check MECHLENS_API_KEY"],
147
+ ),
148
+ (
149
+ httpx.Response(422, json={"detail": [{"loc": ["body", "model", "id"], "msg": "Field required"}]}),
150
+ 422,
151
+ False,
152
+ ["body.model.id: Field required", "record it again"],
153
+ ),
154
+ (
155
+ httpx.Response(413, text="Run exceeds the 32 MiB upload limit"),
156
+ 413,
157
+ False,
158
+ ["32 MiB"],
159
+ ),
160
+ (httpx.Response(503, text="unavailable"), 503, True, ["unavailable", "retry_upload()"]),
161
+ ],
162
+ )
163
+ def test_rejected_upload_explains_cause_and_whether_to_retry(tmp_path, response, status, retryable, expected):
164
+ error = finished_upload_error(tmp_path, lambda request: response)
165
+ assert error.status_code == status
166
+ assert error.retryable is retryable
167
+ for text in expected:
168
+ assert text in str(error)
169
+
170
+
171
+ def test_unreachable_cloud_names_the_url(tmp_path):
172
+ def refuse(request):
173
+ raise httpx.ConnectError("connection refused", request=request)
174
+
175
+ error = finished_upload_error(tmp_path, refuse)
176
+ assert error.status_code is None
177
+ assert error.retryable
178
+ assert "https://cloud.example" in str(error)
179
+ assert "MECHLENS_API_URL" in str(error)