meterline-anthropic 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. meterline_anthropic-0.2.0/LICENSE +202 -0
  2. meterline_anthropic-0.2.0/PKG-INFO +233 -0
  3. meterline_anthropic-0.2.0/README.md +200 -0
  4. meterline_anthropic-0.2.0/pyproject.toml +41 -0
  5. meterline_anthropic-0.2.0/setup.cfg +4 -0
  6. meterline_anthropic-0.2.0/src/meterline_anthropic/__init__.py +19 -0
  7. meterline_anthropic-0.2.0/src/meterline_anthropic/cli.py +874 -0
  8. meterline_anthropic-0.2.0/src/meterline_anthropic/client.py +240 -0
  9. meterline_anthropic-0.2.0/src/meterline_anthropic/fetch.py +436 -0
  10. meterline_anthropic-0.2.0/src/meterline_anthropic/normalise.py +844 -0
  11. meterline_anthropic-0.2.0/src/meterline_anthropic/testing.py +477 -0
  12. meterline_anthropic-0.2.0/src/meterline_anthropic.egg-info/PKG-INFO +233 -0
  13. meterline_anthropic-0.2.0/src/meterline_anthropic.egg-info/SOURCES.txt +42 -0
  14. meterline_anthropic-0.2.0/src/meterline_anthropic.egg-info/dependency_links.txt +1 -0
  15. meterline_anthropic-0.2.0/src/meterline_anthropic.egg-info/entry_points.txt +2 -0
  16. meterline_anthropic-0.2.0/src/meterline_anthropic.egg-info/requires.txt +10 -0
  17. meterline_anthropic-0.2.0/src/meterline_anthropic.egg-info/top_level.txt +1 -0
  18. meterline_anthropic-0.2.0/tests/test_cli_units.py +168 -0
  19. meterline_anthropic-0.2.0/tests/test_client_units.py +172 -0
  20. meterline_anthropic-0.2.0/tests/test_conformance_anthropic.py +43 -0
  21. meterline_anthropic-0.2.0/tests/test_done_check.py +626 -0
  22. meterline_anthropic-0.2.0/tests/test_done_check_B6_python_entry_anthropic.py +96 -0
  23. meterline_anthropic-0.2.0/tests/test_done_check_shapes.py +48 -0
  24. meterline_anthropic-0.2.0/tests/test_done_check_v2.py +82 -0
  25. meterline_anthropic-0.2.0/tests/test_empty_answer_anthropic.py +147 -0
  26. meterline_anthropic-0.2.0/tests/test_exit_codes_anthropic.py +81 -0
  27. meterline_anthropic-0.2.0/tests/test_fake_api.py +206 -0
  28. meterline_anthropic-0.2.0/tests/test_fetch_normalise_units.py +375 -0
  29. meterline_anthropic-0.2.0/tests/test_key_in_every_sink_anthropic.py +92 -0
  30. meterline_anthropic-0.2.0/tests/test_missing_required_fields_anthropic.py +199 -0
  31. meterline_anthropic-0.2.0/tests/test_output_permissions_anthropic.py +49 -0
  32. meterline_anthropic-0.2.0/tests/test_pagination_anthropic.py +119 -0
  33. meterline_anthropic-0.2.0/tests/test_probe_ending_at_anthropic.py +39 -0
  34. meterline_anthropic-0.2.0/tests/test_prompt_content_never_written_anthropic.py +77 -0
  35. meterline_anthropic-0.2.0/tests/test_public_api_anthropic.py +48 -0
  36. meterline_anthropic-0.2.0/tests/test_raw_not_overwritten_anthropic.py +68 -0
  37. meterline_anthropic-0.2.0/tests/test_retry_after_cap_anthropic.py +118 -0
  38. meterline_anthropic-0.2.0/tests/test_review_f25_live_status_anthropic.py +18 -0
  39. meterline_anthropic-0.2.0/tests/test_shapes_negative_control_anthropic.py +32 -0
  40. meterline_anthropic-0.2.0/tests/test_spec_windows_anthropic.py +120 -0
  41. meterline_anthropic-0.2.0/tests/test_state_file_anthropic.py +137 -0
  42. meterline_anthropic-0.2.0/tests/test_summaries_unavailable_anthropic.py +38 -0
  43. meterline_anthropic-0.2.0/tests/test_unknown_fields_anthropic.py +128 -0
  44. meterline_anthropic-0.2.0/tests/test_write_phase_anthropic.py +63 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Xavier Meyer
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,233 @@
1
+ Metadata-Version: 2.4
2
+ Name: meterline-anthropic
3
+ Version: 0.2.0
4
+ Summary: Reads the Anthropic Enterprise Analytics API and emits meterline records.
5
+ Author: Xavier Meyer
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/meyerx/meterline
8
+ Project-URL: Source, https://github.com/meyerx/meterline/tree/main/packages/meterline-anthropic
9
+ Project-URL: Issues, https://github.com/meyerx/meterline/issues
10
+ Project-URL: Changelog, https://github.com/meyerx/meterline/blob/main/CHANGELOG.md
11
+ Keywords: ai,llm,usage,cost,tokens,finops,anthropic,claude
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: System :: Monitoring
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: meterline>=0.2
25
+ Requires-Dist: httpx>=0.27
26
+ Provides-Extra: parquet
27
+ Requires-Dist: pyarrow>=17; extra == "parquet"
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8; extra == "dev"
30
+ Requires-Dist: pytest-xdist==3.8.0; extra == "dev"
31
+ Requires-Dist: ruff==0.17.3; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # meterline-anthropic
35
+
36
+ > Part of [meterline](https://github.com/meyerx/meterline/blob/main/README.md). meterline helps people who run or pay for AI tools in an organisation see and compare usage and cost across providers: it reads each provider's usage API and writes the data in one common record format.
37
+
38
+ Reads the Anthropic Claude Enterprise Analytics API and emits [`meterline`](https://github.com/meyerx/meterline/blob/main/packages/meterline/README.md) records. Python 3.10 or later; runtime dependencies `meterline` and `httpx`.
39
+
40
+ **Status:** built against documented shapes ([evidence level](https://github.com/meyerx/meterline/blob/main/docs/glossary.md#evidence-levels)): spec v1.1 ([`docs/dev/meterline-anthropic-SPEC-v1.1-2026-10-10.md`](https://github.com/meyerx/meterline/blob/main/docs/dev/meterline-anthropic-SPEC-v1.1-2026-10-10.md)), with its acceptance tests run against a fake API. Since v2 phase 1 it writes the v2 record format and keeps v1's zeros (spec v2 section 4). Not yet run against a live account. See [Known limits](#known-limits).
41
+
42
+ ```sh
43
+ pip install meterline-anthropic
44
+ pip install "meterline-anthropic[parquet]" # optional: Parquet output
45
+ ```
46
+
47
+ **From a clone** of the repository (for the tests and development):
48
+
49
+ ```sh
50
+ pip install -e packages/meterline -e "packages/meterline-anthropic[dev]"
51
+ pip install -e "packages/meterline-anthropic[parquet]" # optional: Parquet output
52
+ ```
53
+
54
+ Then, with an Analytics key in the environment (the full list of things to check is under "Before you run it"):
55
+
56
+ ```sh
57
+ export ANTHROPIC_ANALYTICS_KEY=... # never commit this
58
+ meterline-anthropic backfill --since 2026-01-01
59
+ ```
60
+
61
+ ## Provider status
62
+
63
+ As of 2026-10-30, from Anthropic's documentation read on 2026-10-29.
64
+
65
+ - **Four of the six endpoints are legacy.** Anthropic declared `user_usage_report`, `user_cost_report`, `usage_report` and `cost_report` legacy on 2026-10-29. They are still supported, and no sunset date is known. `users` and `summaries` are not legacy.
66
+ - **The successors.** `GET /v1/organizations/analytics/usage` and `GET /v1/organizations/analytics/cost` (beta; they need the header `anthropic-beta: analytics-usage-cost-2026-08-24`). This connector does not call them: it stays on the legacy endpoints in the current releases. Follow-up: the move to the new endpoints is tracked separately.
67
+ - **The plan.** Every endpoint of this API needs a Claude Enterprise plan. `users` and `summaries` work on all Enterprise plans. The report endpoints apply to usage-based Enterprise plans; on a seat-based Enterprise plan they show usage credits only. An organisation without an Enterprise plan cannot use this connector; the other Anthropic connector, [`meterline-anthropic-admin`](https://github.com/meyerx/meterline/blob/main/packages/meterline-anthropic-admin/README.md), reads a Console organisation.
68
+ - **The pinned version and two renames.** The connector sends `anthropic-version: 2023-06-01` (`API_VERSION` in `client.py`). From version `2026-10-21` Anthropic removed two old names: `actor.email` in the per-user reports (now `actor.email_address`) and the `summaries` list of the `summaries` answer (now `data`). The connector reads only the new names. It needs `email_address` on every row of the per-user reports and of `users`: a row without it stops the run with exit 2 and names the field. It reads the seat list from `data`. **Unverified:** whether an answer under `2023-06-01` carries the new names. Anthropic's migration text says the new version drops the old names; it does not say that the old version already has the new ones. If it does not, the first live run stops with exit 2 on the missing field, and the fix is to move the pinned version together with the shape files (see Response shapes).
69
+ - **The header of the key.** The connector sends the key as `x-api-key`, as Anthropic's guide says. Anthropic's reference examples send `Authorization: Bearer` instead. **Unverified:** which of the two this API accepts for an Analytics key.
70
+
71
+ ## Before you run it
72
+
73
+ Check these four things first:
74
+
75
+ - You need an **Analytics key** with scope `read:analytics`, created by the organization's Primary Owner in claude.ai. An Admin API key is rejected by this API.
76
+ - Export it as `ANTHROPIC_ANALYTICS_KEY`. That variable is the only place the key is read.
77
+ - The limit is 60 requests per minute per organization, shared by everything using the key. The connector throttles to 50 by default (`--rate-per-minute`).
78
+ - Data starts at 2026-01-01, and `starting_at` can be at most 365 days back.
79
+
80
+ ## Commands
81
+
82
+ All commands take `--data-dir` (default `exports/meterline-anthropic`, which is gitignored) and `--parquet` (also write a `.parquet` next to each published `.jsonl`). `--rate-per-minute` applies to `backfill` and `daily`; `rebuild` accepts it for symmetry and ignores it, because it makes no API calls.
83
+
84
+ | Command | What it does |
85
+ |---|---|
86
+ | `backfill --since YYYY-MM-DD` | Walks 31-day windows from the start date to today: per-user tokens and cost, organization totals, then daily activity and seat summaries from the start date. Resumes after a failure by re-running the same command. |
87
+ | `daily [--since YYYY-MM-DD]` | Tokens, cost and organization totals for the current month, plus the previous month through the 8th; activity for every day since the last one loaded; yesterday's summary. Safe to run twice a day: unchanged data publishes nothing. With no `state.json` it stops (exit 2) and asks for `--since`, the first day of activity to load, rather than quietly fetching the month again; `--since` is ignored once a state file exists. |
88
+ | `rebuild` | Re-creates every record from the raw store and the published run manifests. No API calls and no key needed. |
89
+
90
+ Exit codes, which a run also reports as `failure_kind` (`RunResult.failure_kind` from Python; a manifest written by a run that failed a check carries it too):
91
+
92
+ | Code | `failure_kind` | Meaning | What to do |
93
+ |---|---|---|---|
94
+ | `0` | `none` | The run finished. | Nothing. |
95
+ | `1` | `transient` | A 5xx, a 429 after the retries, a timeout or a connection error. | Run the same command again later; progress is kept. |
96
+ | `2` | `input` | A failed check, a response that lacks a field the connector needs or holds one of the wrong type, bad arguments or a configuration error such as a missing key. | Fix the input; running the same command again fails the same way. |
97
+ | `3` | `permanent` | The provider refused the request: 400, 401, 403, 404 or 422. The message starts "permanent:" and `RunResult.http_status` holds the status. | Fix the key, its scope or the identifier the message names; do not retry unchanged. |
98
+
99
+ An activity day that is not yet available returns HTTP 400 naming the latest available day. The connector ends the activity part of the run cleanly there and picks the day up on the next run.
100
+
101
+ To run this connector every day, with a retry rule and a gold build after it, see [the daily job example](https://github.com/meyerx/meterline/blob/main/examples/03-daily-job/README.md).
102
+
103
+ ## From Python
104
+
105
+ ```python
106
+ from meterline_anthropic import run
107
+
108
+ key = "..." # from your secret store
109
+ result = run("backfill", since="2026-09-01", data_dir="exports/meterline-anthropic",
110
+ credentials={"ANTHROPIC_ANALYTICS_KEY": key})
111
+ print(result.exit_code, result.records)
112
+ ```
113
+
114
+ `run(command, *, data_dir, credentials=None, transport=None, **options)` does what the command line does. `command` is `"backfill"`, `"daily"` or `"rebuild"`; the options are the command-line ones under Python names (`since`, `rate_per_minute`, `max_retry_after`, `parquet`) with the same defaults, and an unknown name raises `TypeError`. `credentials` is a mapping from `ANTHROPIC_ANALYTICS_KEY` to the key, or a function that returns such a mapping; when it is given the environment is not read, and the key goes only to the HTTP client. It returns a `RunResult` (from `meterline`): `exit_code`, `ok`, `batch_id`, `manifest_path`, `records` (published count per kind), `windows`, `skipped` and `unknown_fields` (the same list as the manifest's). A failed run does not raise: it returns the exit code the command line would have exited with (`1` an API or transport failure, `2` a failed check or a configuration error) after printing the same messages to stderr.
115
+
116
+ ## Testing your integration without a key
117
+
118
+ ```python
119
+ from meterline_anthropic import run
120
+ from meterline_anthropic.testing import FakeAPI
121
+
122
+ fake = FakeAPI(api_key="demo") # serves a small synthetic dataset
123
+ result = run("backfill", since="2026-09-01", data_dir="out",
124
+ credentials={"ANTHROPIC_ANALYTICS_KEY": "demo"}, transport=fake.transport)
125
+ assert result.ok and result.records
126
+ ```
127
+
128
+ `FakeAPI` is a fake of the Analytics API on an `httpx.MockTransport`. With no argument it serves `sample_dataset()`: four invented people, 2026-09-01 to 2026-09-14, in the documented response shapes. Everything in it is synthetic. It can script faults (`fail_page`, `expire_cursor_on_page`, `set_latest_activity_date`). It does not prove that a live key is accepted, that the live API still has these shapes, or how the live rate limits behave.
129
+
130
+ ## How it works
131
+
132
+ Two layers:
133
+
134
+ 1. **Fetcher** (`client.py`, `fetch.py`). Calls the API and writes every response page as received to `raw/<endpoint>/<window>/<pulled_at>.json.gz`, with the request URL, `data_refreshed_at` and the organization id. The key and request headers are never written.
135
+ 2. **Normaliser** (`normalise.py`). Reads raw files only, never the network, and emits records. `cli.py` ties them together and holds the run state.
136
+
137
+ Behaviour worth knowing:
138
+
139
+ - **Endpoints:** per-user tokens (`user_usage_report`) and per-user cost (`user_cost_report`) are asked 1000 rows per page and grouped by model and product. Organization tokens (`usage_report`) and cost (`cost_report`) are asked 31 day buckets per page, per-user activity (`users`) one day at a time with 1000 users per page, and seats (`summaries`) once per range. Array parameters are sent as repeated `name[]=value` pairs.
140
+ - **Pagination:** the report endpoints continue while `has_more` is true and `next_page` is set. `users` has no `has_more`, so it continues while `next_page` is set. Every other parameter stays unchanged. A cursor that expires (HTTP 410) restarts the query from page 1, at most 3 times.
141
+ - **Organization id:** taken from the top level of the report responses (`organization_id`). `users` and `summaries` have none, so their records use the id of the run's report responses; when a run has no report window, the fetcher first makes one single-day `usage_report` request to learn it. No record carries an empty or `"None"` organization id.
142
+ - **Stable reads (the probe):** before each report window the connector sends one `limit=1` request without `ending_at` and reads its `data_refreshed_at`. The window is then fetched with `ending_at` set to the earlier of the window end and UTC midnight of that day, so only whole days are read. This costs one extra request per report endpoint and window (four per window); the probe is not stored as a raw file.
143
+ - **No refresh stamp:** `data_refreshed_at` may be null. A window whose probe has none, or whose cap leaves no whole day (a one-day window whose stamp falls on that same day), is skipped and listed in the run manifest under `skipped_windows` as `<endpoint> <window>: no data yet`. The run still completes. Records from `users` and `summaries` always carry a null `data_refreshed_at`.
144
+ - **Rate and retry:** a sliding one-minute window. On 429 and 5xx it backs off exponentially with jitter (1 s to 60 s, 6 tries) and honours `retry-after`. Any other 4xx stops the run.
145
+ - **Join:** usage and cost join on (actor, day, product, model). A usage row with no cost row gets `cost = null`, never 0. A cost row with no usage row is kept as a `UsageRecord` with zero tokens, `requests` null and `cost_only = true`, and listed in the manifest under `cost_only` as `<actor_id>|<day>|<product>|<model>`; it never fails the run.
146
+ - **Activity:** each `users` row yields one `ActivityRecord` per product block that has at least one non-zero count, plus one record with product `all` for `web_search_count`. The product names and field mapping are in the [record reference](https://github.com/meyerx/meterline/blob/main/docs/records.md#activityrecord).
147
+ - **Money:** the API's `amount` and `list_amount` are decimal strings in cents. They are parsed as `Decimal` and divided by 100; no float is used on the cost path.
148
+ - **Revisions:** a re-pull writes only records that changed, under a new `batch_id`. Readers take the latest batch per key.
149
+ - **Final periods:** `daily` re-pulls the previous month on days 1 to 8 inclusive. A period is `is_final` when its month ended more than 7 days before the pull.
150
+ - **v2 mapping:** `tokens_input` is now `tokens_input_uncached`, with `tokens_cache_write` and `tokens_input_total` derived; `web_search_requests` is `extras["web_search_requests"]`; the five activity counters with no core field (`conversations`, `artifacts`, `skills_used`, `connectors_used`, `web_searches`) are `counters` entries; `cost_basis` is `consumption` when a cost is set. The full table is in section 4 of the v2 spec and in the [record reference](https://github.com/meyerx/meterline/blob/main/docs/records.md). Records written before v2 convert with `meterline.convert_v1_batch`.
151
+ - **Checks before publishing:** the v2 record rules (grain, token sums, cost basis, no future dates, no negative numbers), no duplicate keys in a batch, record totals equal raw totals (cost-only records included), and per-user cost per day not above the organization total. A failed check publishes nothing, writes a manifest with `status: "failed"` and the failures, and exits `2`.
152
+ - **New products and models:** there is no fixed list of known products or models. Every value is kept as received, and each run's manifest lists, under `unknown_products` and `unknown_models`, the values that no earlier published batch contained. On a first run that is every value.
153
+ - **Never grouped by `rbac_group_id`:** a user in two groups would be counted twice.
154
+ - **Core imports:** records are built and checked with `meterline.records` (`UsageRecord`, `ActivityRecord`, `SeatSnapshot`, `OrgTotal`, `batch_failures`, `latest_per_key`) and written and read with `meterline.writers` (`write_jsonl`, `write_parquet`, `read_jsonl`), the two submodule routes the core package keeps stable. A script that reads this connector's output can import the same names from those routes or from the package root, `meterline`.
155
+
156
+ ## Files under the data directory
157
+
158
+ A run reads and writes these four things under `--data-dir`:
159
+
160
+ | Path | Contents |
161
+ |---|---|
162
+ | `raw/<endpoint>/<window>/<pulled_at>.json.gz` | One file per window pull: endpoint, window, request URL, `pulled_at`, `data_refreshed_at` (null when no page had one), `organization_id`, and every page's status and body text. |
163
+ | `runs/<batch_id>.json` | The run manifest: `command`, `batch_id`, `pulled_at`, `status`, `windows`, `pages`, `row_counts`, `totals`, `unknown_products`, `unknown_models`, `skipped_windows`, `cost_only`, `raw_files`, `published_counts`, `failures` and `unknown_fields` (the fields of the provider that the connector does not know, as endpoint, key path and count, never a value). `batch_id` is the run's `pulled_at` as `YYYYMMDDTHHMMSSZ`. |
164
+ | `records/<kind>/<batch_id>.jsonl` | Published records (v2); kinds are `usage`, `activity`, `seats`, `org_totals` (this connector writes no `seat_assignments`). A batch with no changed records writes no file. |
165
+ | `state.json` | `activity_loaded` and `summaries_loaded` (days already loaded), `refreshed_at` (last `data_refreshed_at` per endpoint), `latest_activity_date`, and a `pending` block that lets an interrupted run resume. |
166
+
167
+ The state file is checked on every `backfill` and `daily`. If it is cut short, empty, not the shape above or points outside the data directory, the run stops with exit 2 before any request and names the file. Restore it from a backup, or move it aside and run `backfill --since`: published records are kept, and unchanged rows are not written twice. `rebuild` does not read it.
168
+
169
+ Raw files and published records contain email addresses (records trimmed and lower-cased). Treat the data directory as sensitive and keep it out of git.
170
+
171
+ ## Record mapping
172
+
173
+ Each endpoint feeds one record kind. The [record reference](https://github.com/meyerx/meterline/blob/main/docs/records.md) gives the Anthropic source of every field, column by column; in short:
174
+
175
+ | Record | From |
176
+ |---|---|
177
+ | `UsageRecord`, `actor_kind` `user`, `grain` `day`, per user, product and model | `user_usage_report`, joined to `user_cost_report` on (user, day, product, model) |
178
+ | `OrgTotal`, `grain` `day`, one all-models row per day | `usage_report` and `cost_report` day buckets, summed |
179
+ | `ActivityRecord`, per user, day and product | `users`, one record per product block with a non-zero count, plus product `all` for web searches |
180
+ | `SeatSnapshot`, per day | `summaries` |
181
+
182
+ This connector writes no `SeatAssignment`. The changes from the v1 format are listed under How it works.
183
+
184
+ ## Response shapes
185
+
186
+ The six files at the top of [`docs/api-shapes/`](https://github.com/meyerx/meterline/blob/main/docs/api-shapes) are the documented response shapes, one per endpoint, with synthetic values: `user_usage_report.json`, `user_cost_report.json`, `usage_report.json`, `cost_report.json`, `users.json` and `summaries.json`. They were transcribed from Anthropic's API reference (section 2.1 of the spec); [`docs/api-shapes/README.md`](https://github.com/meyerx/meterline/blob/main/docs/api-shapes/README.md) gives the source and the date read. Done-check 12 compares what the fake API returns with these files, structurally and ignoring values, so the fake cannot drift from the transcribed shapes. It cannot show that the shapes match what the live API sends.
187
+
188
+ **When a live response differs.** A live run is the first real test of these shapes. If a response does not match its shape file:
189
+
190
+ 1. Save the live response's structure as the new shape file, with every value replaced by an invented one: synthetic values only, and never commit a real response.
191
+ 2. Run the shape check, `python -m pytest -q packages/meterline-anthropic -k "check_12"`. Done-check 12 fails and names each key that differs between the fake API and the file.
192
+ 3. Change the fake API to match, then `fetch.py` and `normalise.py`, until the shape check and the other acceptance tests pass.
193
+ 4. Update the source and the date read in the shape folder's README, and add an entry to the change list of the spec.
194
+
195
+ **When Anthropic releases a new API version.** Every request sends `anthropic-version: 2023-06-01` (`API_VERSION` in `client.py`), and a unit test pins it. To move to a new API version, read its changes, update the shape files as above, then change the constant and the test together.
196
+
197
+ ## Known limits
198
+
199
+ The limits of this connector, grouped by kind.
200
+
201
+ **How the connector reads the API.** These follow from the API's own limits and the connector's rules:
202
+
203
+ - **Raw files are kept and never replaced.** Every pull writes its own `raw/.../<pulled_at>.json.gz`; nothing in the connector deletes or rewrites one, so the evidence a record was built from stays. A second pull in the same UTC second would need the same file name. Such a run is refused (exit 2) before it asks the API anything, or, if it had started, stops without replacing the file; a run in the second of a finished run is refused too. Wait a second and run again. Raw files grow with every run; archive or delete old ones by hand once the records they produced are no longer needed for a `rebuild`.
204
+ - **Page loops end.** One query follows at most 10,000 pages (`MAX_PAGES` in `client.py`). A cursor that comes back, or more pages than that, stops the run with exit 2 and a failed manifest instead of requesting for ever. A page the API skips cannot be seen from the client (the cursor is opaque and the answer has no total); the only trace is a rise in the manifest's `cost_only` list.
205
+ - **Waits are capped.** A `Retry-After` header is honoured up to 300 seconds (`--max-retry-after`); both the delay-seconds and the HTTP-date forms are read, and a value that is not a finite number is ignored in favour of the back-off.
206
+ - **Seat summaries are cut into ranges.** The API accepts at most 366 days per call (spec section 2.1), so a longer range is asked in several calls.
207
+ - **A resumed run reuses the pages it already has.** After a failure, the same command picks up the pages the failed run stored (the `pending` block of `state.json`), however old they are, and publishes them under the new run's `pulled_at`. Running a different command in between drops them, and a run whose checks fail clears them, so a failed long `backfill` asks for everything again.
208
+
209
+ **Not verified.** The connector has not met a live organization; [Response shapes](#response-shapes) says what to do when a live response differs.
210
+
211
+ **Not in the API.** Claude Code used through Amazon Bedrock, seat fees and the effort level are not reported by this API, so no record holds them.
212
+
213
+ **Out of scope.** Identity resolution, pricing from tokens, contract discounts, seat-fee allocation, currency conversion, alerting and consumer-specific table layouts are left to other tools; see the root [Known limits](https://github.com/meyerx/meterline/blob/main/README.md#known-limits).
214
+
215
+ ## Public interface
216
+
217
+ What later releases keep working, under the rules of the compatibility policy in [`docs/records.md`](https://github.com/meyerx/meterline/blob/main/docs/records.md#compatibility):
218
+
219
+ - the `meterline-anthropic` command line: its commands, options and exit codes, as listed under Commands;
220
+ - the records it publishes under `records/`, in the v2 format of [`docs/records.md`](https://github.com/meyerx/meterline/blob/main/docs/records.md);
221
+ - from Python, the names in `meterline_anthropic.__all__`: `run` and the `RunResult` it returns, the error classes `ApiError`, `StateError` and `RawFileExists`, and `__version__`;
222
+ - the `meterline_anthropic.testing` module: `FakeAPI` and `sample_dataset()`, as described under Testing your integration without a key.
223
+
224
+ Everything else is internal and may change in any release: every other module of the `meterline_anthropic` package, and the layout of the raw files, the run manifests and `state.json` (they are documented so you can read them, not so you can build on them).
225
+
226
+ ## Tests
227
+
228
+ ```sh
229
+ python -m pytest -q packages/meterline-anthropic # everything
230
+ python -m pytest -q packages/meterline-anthropic -k done_check # the 17 v1.1 acceptance tests and A01-A03
231
+ ```
232
+
233
+ Tests run against `meterline_anthropic.testing.FakeAPI`, an `httpx.MockTransport` that replays the large synthetic fixtures (`tests/fixtures/data`) in the documented shapes and can script faults (429 with `retry-after`, 410 cursor expiry, a 400 for an unavailable date, 5xx). The clock and sleep are injected, so nothing really waits. Fixture notes are in [`tests/fixtures/README.md`](https://github.com/meyerx/meterline/blob/main/packages/meterline-anthropic/tests/fixtures/README.md).