tokenaudit 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.
Files changed (107) hide show
  1. tokenaudit-0.1.0/.github/workflows/ci.yml +33 -0
  2. tokenaudit-0.1.0/.gitignore +24 -0
  3. tokenaudit-0.1.0/.pre-commit-config.yaml +15 -0
  4. tokenaudit-0.1.0/CHANGELOG.md +27 -0
  5. tokenaudit-0.1.0/DECISIONS.md +41 -0
  6. tokenaudit-0.1.0/LICENSE +202 -0
  7. tokenaudit-0.1.0/Makefile +10 -0
  8. tokenaudit-0.1.0/PKG-INFO +111 -0
  9. tokenaudit-0.1.0/README.md +84 -0
  10. tokenaudit-0.1.0/corpus/README.md +83 -0
  11. tokenaudit-0.1.0/corpus/captured/README.md +56 -0
  12. tokenaudit-0.1.0/corpus/captured/capture_tradingagents.sh +88 -0
  13. tokenaudit-0.1.0/corpus/captured/redact.py +100 -0
  14. tokenaudit-0.1.0/corpus/captured/runner.py +183 -0
  15. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-01-NVDA-2026-08-14/decision.txt +1 -0
  16. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-01-NVDA-2026-08-14/manifest.json +29 -0
  17. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-01-NVDA-2026-08-14/trace.jsonl +114 -0
  18. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-02-AAPL-2026-08-14/decision.txt +1 -0
  19. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-02-AAPL-2026-08-14/manifest.json +29 -0
  20. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-02-AAPL-2026-08-14/trace.jsonl +112 -0
  21. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-03-NVDA-2026-08-21/decision.txt +1 -0
  22. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-03-NVDA-2026-08-21/manifest.json +29 -0
  23. tokenaudit-0.1.0/corpus/captured/runs/tradingagents/run-03-NVDA-2026-08-21/trace.jsonl +125 -0
  24. tokenaudit-0.1.0/corpus/synthetic/fixtures/breakpoint_limit.label.json +34 -0
  25. tokenaudit-0.1.0/corpus/synthetic/fixtures/breakpoint_limit.trace.json +354 -0
  26. tokenaudit-0.1.0/corpus/synthetic/fixtures/context_bloat.label.json +35 -0
  27. tokenaudit-0.1.0/corpus/synthetic/fixtures/context_bloat.trace.json +574 -0
  28. tokenaudit-0.1.0/corpus/synthetic/fixtures/healthy_cached.label.json +32 -0
  29. tokenaudit-0.1.0/corpus/synthetic/fixtures/healthy_cached.trace.json +512 -0
  30. tokenaudit-0.1.0/corpus/synthetic/fixtures/healthy_incremental.label.json +33 -0
  31. tokenaudit-0.1.0/corpus/synthetic/fixtures/healthy_incremental.trace.json +512 -0
  32. tokenaudit-0.1.0/corpus/synthetic/fixtures/healthy_small.label.json +32 -0
  33. tokenaudit-0.1.0/corpus/synthetic/fixtures/healthy_small.trace.json +239 -0
  34. tokenaudit-0.1.0/corpus/synthetic/fixtures/lookback_overflow.label.json +34 -0
  35. tokenaudit-0.1.0/corpus/synthetic/fixtures/lookback_overflow.trace.json +275 -0
  36. tokenaudit-0.1.0/corpus/synthetic/fixtures/manifest.json +144 -0
  37. tokenaudit-0.1.0/corpus/synthetic/fixtures/model_switch.label.json +36 -0
  38. tokenaudit-0.1.0/corpus/synthetic/fixtures/model_switch.trace.json +512 -0
  39. tokenaudit-0.1.0/corpus/synthetic/fixtures/openai_healthy_cached.label.json +32 -0
  40. tokenaudit-0.1.0/corpus/synthetic/fixtures/openai_healthy_cached.trace.json +433 -0
  41. tokenaudit-0.1.0/corpus/synthetic/fixtures/prefix_drift.label.json +35 -0
  42. tokenaudit-0.1.0/corpus/synthetic/fixtures/prefix_drift.trace.json +512 -0
  43. tokenaudit-0.1.0/corpus/synthetic/fixtures/prefix_drift_legacy_flat.label.json +35 -0
  44. tokenaudit-0.1.0/corpus/synthetic/fixtures/prefix_drift_legacy_flat.trace.json +404 -0
  45. tokenaudit-0.1.0/corpus/synthetic/fixtures/prefix_drift_no_content.label.json +35 -0
  46. tokenaudit-0.1.0/corpus/synthetic/fixtures/prefix_drift_no_content.trace.json +440 -0
  47. tokenaudit-0.1.0/corpus/synthetic/fixtures/prefix_drift_openinference.label.json +35 -0
  48. tokenaudit-0.1.0/corpus/synthetic/fixtures/prefix_drift_openinference.trace.json +692 -0
  49. tokenaudit-0.1.0/corpus/synthetic/fixtures/retry_storm.label.json +34 -0
  50. tokenaudit-0.1.0/corpus/synthetic/fixtures/retry_storm.trace.json +373 -0
  51. tokenaudit-0.1.0/corpus/synthetic/fixtures/sub_minimum.label.json +34 -0
  52. tokenaudit-0.1.0/corpus/synthetic/fixtures/sub_minimum.trace.json +433 -0
  53. tokenaudit-0.1.0/corpus/synthetic/fixtures/tool_schema_churn.label.json +34 -0
  54. tokenaudit-0.1.0/corpus/synthetic/fixtures/tool_schema_churn.trace.json +512 -0
  55. tokenaudit-0.1.0/corpus/synthetic/fixtures/ttl_expiry.label.json +35 -0
  56. tokenaudit-0.1.0/corpus/synthetic/fixtures/ttl_expiry.trace.json +433 -0
  57. tokenaudit-0.1.0/corpus/synthetic/generate.py +884 -0
  58. tokenaudit-0.1.0/docs/rulebook.md +57 -0
  59. tokenaudit-0.1.0/eval/results.json +668 -0
  60. tokenaudit-0.1.0/eval/results.md +19 -0
  61. tokenaudit-0.1.0/eval/run_eval.py +154 -0
  62. tokenaudit-0.1.0/pyproject.toml +93 -0
  63. tokenaudit-0.1.0/src/tokenaudit/__init__.py +3 -0
  64. tokenaudit-0.1.0/src/tokenaudit/__main__.py +152 -0
  65. tokenaudit-0.1.0/src/tokenaudit/ci/__init__.py +1 -0
  66. tokenaudit-0.1.0/src/tokenaudit/counterfactual/__init__.py +1 -0
  67. tokenaudit-0.1.0/src/tokenaudit/detect/__init__.py +15 -0
  68. tokenaudit-0.1.0/src/tokenaudit/detect/base.py +96 -0
  69. tokenaudit-0.1.0/src/tokenaudit/detect/corpus_record.json +56 -0
  70. tokenaudit-0.1.0/src/tokenaudit/detect/engine.py +87 -0
  71. tokenaudit-0.1.0/src/tokenaudit/detect/findings.py +86 -0
  72. tokenaudit-0.1.0/src/tokenaudit/detect/rules/__init__.py +1 -0
  73. tokenaudit-0.1.0/src/tokenaudit/detect/rules/breakpoint_limit.py +102 -0
  74. tokenaudit-0.1.0/src/tokenaudit/detect/rules/context_bloat.py +105 -0
  75. tokenaudit-0.1.0/src/tokenaudit/detect/rules/lookback_overflow.py +120 -0
  76. tokenaudit-0.1.0/src/tokenaudit/detect/rules/model_switch.py +107 -0
  77. tokenaudit-0.1.0/src/tokenaudit/detect/rules/prefix_drift.py +157 -0
  78. tokenaudit-0.1.0/src/tokenaudit/detect/rules/retry_storm.py +102 -0
  79. tokenaudit-0.1.0/src/tokenaudit/detect/rules/sub_minimum.py +112 -0
  80. tokenaudit-0.1.0/src/tokenaudit/detect/rules/tool_schema_churn.py +120 -0
  81. tokenaudit-0.1.0/src/tokenaudit/detect/rules/ttl_expiry.py +121 -0
  82. tokenaudit-0.1.0/src/tokenaudit/examples/sample.trace.json +512 -0
  83. tokenaudit-0.1.0/src/tokenaudit/ingest/__init__.py +39 -0
  84. tokenaudit-0.1.0/src/tokenaudit/ingest/containers.py +172 -0
  85. tokenaudit-0.1.0/src/tokenaudit/ingest/dedup.py +64 -0
  86. tokenaudit-0.1.0/src/tokenaudit/ingest/dialects.py +258 -0
  87. tokenaudit-0.1.0/src/tokenaudit/ingest/quality.py +65 -0
  88. tokenaudit-0.1.0/src/tokenaudit/ingest/sessionize.py +47 -0
  89. tokenaudit-0.1.0/src/tokenaudit/model/__init__.py +5 -0
  90. tokenaudit-0.1.0/src/tokenaudit/model/records.py +99 -0
  91. tokenaudit-0.1.0/src/tokenaudit/py.typed +0 -0
  92. tokenaudit-0.1.0/src/tokenaudit/report/__init__.py +14 -0
  93. tokenaudit-0.1.0/src/tokenaudit/report/corpus_record.py +35 -0
  94. tokenaudit-0.1.0/src/tokenaudit/report/health.py +86 -0
  95. tokenaudit-0.1.0/src/tokenaudit/report/html.py +152 -0
  96. tokenaudit-0.1.0/src/tokenaudit/rulebook/__init__.py +238 -0
  97. tokenaudit-0.1.0/src/tokenaudit/rulebook/anthropic.json +36 -0
  98. tokenaudit-0.1.0/src/tokenaudit/rulebook/google.json +23 -0
  99. tokenaudit-0.1.0/src/tokenaudit/rulebook/openai.json +45 -0
  100. tokenaudit-0.1.0/tests/test_corpus.py +154 -0
  101. tokenaudit-0.1.0/tests/test_detect.py +201 -0
  102. tokenaudit-0.1.0/tests/test_eval.py +41 -0
  103. tokenaudit-0.1.0/tests/test_ingest.py +200 -0
  104. tokenaudit-0.1.0/tests/test_package.py +13 -0
  105. tokenaudit-0.1.0/tests/test_redact.py +43 -0
  106. tokenaudit-0.1.0/tests/test_report.py +68 -0
  107. tokenaudit-0.1.0/tests/test_rulebook.py +69 -0
@@ -0,0 +1,33 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ checks:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ python-version: ["3.11", "3.12", "3.13"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ cache: pip
21
+ cache-dependency-path: pyproject.toml
22
+ - name: Install package and dev tools
23
+ run: |
24
+ python -m pip install --upgrade pip
25
+ pip install -e ".[dev]"
26
+ - name: Lint
27
+ run: ruff check .
28
+ - name: Format check
29
+ run: ruff format --check .
30
+ - name: Type check
31
+ run: mypy
32
+ - name: Tests
33
+ run: pytest
@@ -0,0 +1,24 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .venv/
8
+ venv/
9
+
10
+ # Tool caches
11
+ .pytest_cache/
12
+ .mypy_cache/
13
+ .ruff_cache/
14
+ .coverage
15
+ htmlcov/
16
+
17
+ # Environment / editors / OS
18
+ .env
19
+ .vscode/
20
+ .idea/
21
+ .DS_Store
22
+
23
+ # Capture workdir (throwaway venv + clone, never committed)
24
+ corpus/captured/.work/
@@ -0,0 +1,15 @@
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v5.0.0
4
+ hooks:
5
+ - id: trailing-whitespace
6
+ - id: end-of-file-fixer
7
+ - id: check-yaml
8
+ - id: check-toml
9
+ - id: check-added-large-files
10
+ - repo: https://github.com/astral-sh/ruff-pre-commit
11
+ rev: v0.6.9
12
+ hooks:
13
+ - id: ruff
14
+ args: [--fix]
15
+ - id: ruff-format
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — 2026-08-30
4
+
5
+ First usable release.
6
+
7
+ - **Ingest** four real trace dialects into one normalized accounting model:
8
+ OTel GenAI current semconv, legacy flat names (older openllmetry),
9
+ OpenInference, and the OTel Python SDK's `to_json()` JSONL — with
10
+ layered-span deduplication (framework + SDK instrumentors double-report
11
+ the same call), a data-quality gate that refuses to price malformed
12
+ telemetry, and prompt privacy by construction (block hashes and lengths,
13
+ never text).
14
+ - **Nine deterministic detectors** — prefix drift, sub-minimum cache
15
+ blocks, model switch, TTL expiry, breakpoint limit, lookback overflow,
16
+ tool-schema churn, context bloat, retry storm — each with evidence
17
+ pointers, bounded impact ranges with stated assumptions, and abstention
18
+ (with a reason) as a first-class outcome distinct from "checked, clean".
19
+ - **Provider caching rulebook** packaged as sourced, dated JSON (Anthropic,
20
+ OpenAI, Google), with a CI staleness alarm and a rendered comparison
21
+ table (`tokenaudit rulebook`).
22
+ - **Evaluation** against a byte-reproducible labeled corpus, published in
23
+ `eval/results.md`; per-detector corpus records ship inside the package
24
+ and appear on findings.
25
+ - **CLI**: `tokenaudit diagnose` (text, `--json`, self-contained `--html`
26
+ report, `--sample`), `tokenaudit ingest`, `tokenaudit rulebook`.
27
+ - Zero runtime dependencies. Python 3.11+.
@@ -0,0 +1,41 @@
1
+ # Decision log
2
+
3
+ Short, dated notes on the non-obvious calls, so the "why" survives longer than my memory of it.
4
+
5
+ ## 001 — Verdicts come from deterministic rules, not an LLM (2026-08-29)
6
+
7
+ **Decision:** the diagnosis engine is a library of explicit, testable rules. No model call anywhere in the verdict path. If an LLM is ever used, it drafts prose or patch text from an already-decided finding, in a module the detectors cannot import.
8
+
9
+ **Why:** same trace in, same findings out; every detector can be unit-tested against labeled fixtures and given a measured precision; running the tool is free, which matters for a tool whose whole point is reducing cost; and every finding carries an evidence pointer instead of a vibe.
10
+
11
+ **Cost accepted:** rules only catch what I have enumerated. An enumerated catalog with measured precision beats open-ended guesses I can't test.
12
+
13
+ ## 002 — Name: tokenaudit, not cachelens (2026-08-29)
14
+
15
+ The working name for this project was "cachelens". The day-one collision check found [cachelens on PyPI](https://pypi.org/project/cachelens/) — released June 2026, an SDK-wrapper cache meter, i.e. a neighbor in this space, not just a name squatter. Shipping a lookalike name would be unfair to them and confusing for everyone.
16
+
17
+ Picked **tokenaudit** over the other candidates (wastelens, cachedoctor) for two reasons: it leaves the cache-/-lens naming family entirely, and several planned detectors (retry storms, context bloat, tool-schema bloat) are token-waste problems that aren't cache problems at all, so "cache" in the name undersold the scope. Verified free on PyPI and GitHub 2026-08-29.
18
+
19
+ ## 003 — Apache-2.0, not MIT (2026-08-29)
20
+
21
+ Explicit patent grant, and it matches the ecosystem this project sits in (OpenTelemetry is Apache-2.0).
22
+
23
+ ## 004 — src layout and strict mypy from the first commit (2026-08-29)
24
+
25
+ src/ layout so tests import the installed package rather than the working directory. `mypy --strict` costs nothing to adopt on an empty package and a lot to adopt later; the detector engine will be pure functions, which is exactly the code strict typing is cheap for.
26
+
27
+ ## 005 — The rulebook is JSON inside the package, not YAML beside it (2026-08-30)
28
+
29
+ **Decision:** provider caching constants live in `src/tokenaudit/rulebook/*.json`, loaded with the standard library via `importlib.resources`, and ship inside the wheel.
30
+
31
+ **Why:** the package has zero runtime dependencies, and adding a YAML parser just to read our own constants would end that for no gain — sources and notes are data fields, so YAML's comments aren't needed. Packaging the data means the installed CLI works without a repo checkout. Two boundaries drawn at the same time: trace field-name *mappings* stay in `ingest/dialects.py` (one owner, no code/data drift), and prices appear only where verified — unknown numbers are `null` with a note, never a guess. The corpus generator now reads these same files, so the simulator and the detectors share one set of constants, with the byte-exact corpus regeneration test guarding every edit.
32
+
33
+ ## 006 — argparse over Typer; a ratio over a weighted score; records over probabilities (2026-08-30)
34
+
35
+ Three calls made together for the 0.1.0 release, all in service of the same principle.
36
+
37
+ **CLI stays argparse.** Typer gives nicer help text at the cost of the package's zero-runtime-dependency property — a bad trade for a tool whose pitch includes "installs nothing else and never phones home".
38
+
39
+ **The cache health score is `realized / achievable` savings** — realized cache savings over realized-plus-what-the-findings-quantify. Both halves are computed the same way, so there are no weights to defend; overlapping findings make the denominator conservative, so the score is presented as a floor and says so.
40
+
41
+ **Findings carry a corpus record, not a confidence number.** A precision float computed from a 16-fixture corpus would be theater. The package ships the raw record instead — "3/4 planted cases found, 0 false alarms in N negatives" — generated by the eval harness and drift-tested, so what appears next to a finding is exactly what was measured.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ https://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 [yyyy] [name of copyright owner]
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
+ https://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,10 @@
1
+ .PHONY: corpus check
2
+
3
+ corpus:
4
+ python corpus/synthetic/generate.py
5
+
6
+ check:
7
+ ruff check .
8
+ ruff format --check .
9
+ mypy
10
+ pytest
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.5
2
+ Name: tokenaudit
3
+ Version: 0.1.0
4
+ Summary: Root-cause diagnosis of wasted LLM tokens, from the traces your agents already emit
5
+ Project-URL: Repository, https://github.com/yashmyeole/tokenaudit
6
+ Project-URL: Issues, https://github.com/yashmyeole/tokenaudit/issues
7
+ Author-email: Yash Manohar Yeole <yashmyeole@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: cost,diagnosis,llm,observability,opentelemetry,prompt-caching,tokens,waste
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: System :: Monitoring
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Provides-Extra: dev
22
+ Requires-Dist: mypy>=1.11; extra == 'dev'
23
+ Requires-Dist: pre-commit>=3.8; extra == 'dev'
24
+ Requires-Dist: pytest>=8.3; extra == 'dev'
25
+ Requires-Dist: ruff>=0.6.9; extra == 'dev'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # tokenaudit
29
+
30
+ **Root-cause diagnosis of wasted LLM tokens — from the traces your agents already emit.**
31
+
32
+ > Status: early development, pre-0.1. Interfaces will change.
33
+
34
+ Every LLM cost tool can tell you *how much* you spent and *who* spent it. Almost none can tell you *why a specific request wasted money*. The biggest lever on an LLM bill — prompt caching, up to a 10× discount on repeated input — fails silently: change one byte of a cached prefix, drop below a model's minimum cacheable size, let a timer expire, and the provider just bills you full price. No error, no warning. There are [documented](https://barndoor.ai/what-happens-to-your-llm-bill-when-prompt-caching-fails/) [cases](https://github.com/TauricResearch/TradingAgents/issues/750) of agents running at ~0% cache hit rate for months, at 30–40% unnecessary cost, because of a single line of prompt construction.
35
+
36
+ tokenaudit reads the traces agents already produce and, for each expensive request, answers four questions: **what was wasted, why, what it cost, and what to change.**
37
+
38
+ ## Quickstart
39
+
40
+ pip install tokenaudit
41
+ tokenaudit diagnose --sample # diagnose the bundled demo trace
42
+ tokenaudit diagnose mytraces/ --html report.html
43
+
44
+ Zero runtime dependencies; reads OTLP/JSON files and OTel SDK JSONL. Try it
45
+ on this repo's real captured runs: `tokenaudit diagnose corpus/captured/runs`.
46
+
47
+ The plan, in one line each:
48
+
49
+ - Ingest standard traces — OpenTelemetry GenAI in all three of its cache-field naming generations, OpenInference, raw provider SDK logs — into one normalized accounting model.
50
+ - Run a library of deterministic detectors for the silent failure modes: prefix drift, sub-minimum cache blocks, model switches, TTL expiry, breakpoint and lookback limits, tool-schema churn and bloat, context bloat, retry storms.
51
+ - Price each finding against a counterfactual — what the bill would have been under the fix — as a bounded range, never a point guess.
52
+ - Publish per-detector precision and recall against a labeled corpus, so you know how much to trust each finding.
53
+
54
+ ## Prior art
55
+
56
+ This space is crowded, and being precise about what already exists is the point of this section.
57
+
58
+ | Tool | What it does |
59
+ |---|---|
60
+ | [CacheLens](https://github.com/ChingEnLin/CacheLens) | Closest prior art. Dev-time SDK wrapper that meters cache hit rate and prefix stability per prompt layer in apps you instrument. Doesn't read existing traces, and prefix stability is its one diagnosis. |
61
+ | [Helicone](https://helicone.ai) | Observability proxy: cost and token accounting per user/session/feature, including cache token counts |
62
+ | [Langfuse](https://langfuse.com) | Open-source LLM engineering platform: tracing, evals, per-trace cost accounting |
63
+ | [Datadog LLM Observability](https://docs.datadoghq.com/llm_observability/) | Enterprise monitoring: per-request token and cost tracking, quality-issue clustering |
64
+ | [Braintrust](https://braintrust.dev) | Evals and observability; its Loop assistant root-causes *quality* failures |
65
+ | [LiteLLM](https://github.com/BerriAI/litellm) | Gateway with budgets, rate limits and spend tracking across providers |
66
+ | [ccusage](https://github.com/ryoppippi/ccusage) | CLI usage and cost reporting from Claude Code's local logs |
67
+ | [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/) | Platform-level caching, spend caps and alerts |
68
+
69
+ All of these answer "how much", and several now count cache tokens. The ones that do automatic root-cause analysis target response *quality*, not cost. The closest tool diagnoses one failure mode, for one integration style, going forward only. What none of them do is take the telemetry any agent already emitted — no code changes, any vendor — and say: *these 44 requests missed cache because the system prompt embeds a timestamp; here is the evidence, and here is what it cost.* That attribution step is this project.
70
+
71
+ If you know a tool that already does this, please open an issue — I would genuinely rather find out now.
72
+
73
+ ## What tokenaudit is not
74
+
75
+ - **Not a dashboard.** The tools above already report spend well.
76
+ - **Not a proxy, gateway, or wrapper.** It reads traces after the fact and never sits in the request path, so it can't change what it measures and doesn't need your code.
77
+ - **Not an LLM reading your logs.** Verdicts come from explicit rules with unit tests and a published false-positive rate ([decision 001](DECISIONS.md)).
78
+ - **Not a savings guarantee.** Estimates are ranges with stated assumptions, and requests whose telemetry fails a plausibility check are flagged as unpriceable, not silently priced.
79
+
80
+ ## Planned layout
81
+
82
+ src/tokenaudit/
83
+ ingest/ trace readers + schema normalization
84
+ model/ normalized requests/sessions + token accounting
85
+ detect/ the diagnosis engine (deterministic detectors)
86
+ counterfactual/ what the bill would have been under a fix
87
+ report/ CLI, JSON and HTML output
88
+ ci/ cost-regression gate for pipelines
89
+
90
+ ## Roadmap
91
+
92
+ - [x] Prior-art survey, positioning, project scaffold
93
+ - [x] Labeled trace corpus: synthetic known-answer fixtures + captured runs from real public agents
94
+ - [x] Trace reader and normalizer with a data-quality gate (bad telemetry is refused, not zero-filled)
95
+ - [x] Provider caching rulebook: minimums, TTL semantics, invalidation rules — versioned, with sources
96
+ - [x] Detectors, starting with prefix drift, sub-minimum blocks, and model/version switch
97
+ - [x] Evaluation harness: per-detector results published in [eval/results.md](eval/results.md)
98
+ - [x] `tokenaudit diagnose` CLI, HTML report, cache health score
99
+ - [ ] CI cost-regression mode: fail a build that tanks the cache hit rate
100
+ - [ ] Case studies on public agents, with reproduction commands
101
+
102
+ ## Development
103
+
104
+ python -m venv .venv && source .venv/bin/activate
105
+ pip install -e ".[dev]"
106
+ pre-commit install
107
+ pytest
108
+
109
+ ## License
110
+
111
+ Apache-2.0
@@ -0,0 +1,84 @@
1
+ # tokenaudit
2
+
3
+ **Root-cause diagnosis of wasted LLM tokens — from the traces your agents already emit.**
4
+
5
+ > Status: early development, pre-0.1. Interfaces will change.
6
+
7
+ Every LLM cost tool can tell you *how much* you spent and *who* spent it. Almost none can tell you *why a specific request wasted money*. The biggest lever on an LLM bill — prompt caching, up to a 10× discount on repeated input — fails silently: change one byte of a cached prefix, drop below a model's minimum cacheable size, let a timer expire, and the provider just bills you full price. No error, no warning. There are [documented](https://barndoor.ai/what-happens-to-your-llm-bill-when-prompt-caching-fails/) [cases](https://github.com/TauricResearch/TradingAgents/issues/750) of agents running at ~0% cache hit rate for months, at 30–40% unnecessary cost, because of a single line of prompt construction.
8
+
9
+ tokenaudit reads the traces agents already produce and, for each expensive request, answers four questions: **what was wasted, why, what it cost, and what to change.**
10
+
11
+ ## Quickstart
12
+
13
+ pip install tokenaudit
14
+ tokenaudit diagnose --sample # diagnose the bundled demo trace
15
+ tokenaudit diagnose mytraces/ --html report.html
16
+
17
+ Zero runtime dependencies; reads OTLP/JSON files and OTel SDK JSONL. Try it
18
+ on this repo's real captured runs: `tokenaudit diagnose corpus/captured/runs`.
19
+
20
+ The plan, in one line each:
21
+
22
+ - Ingest standard traces — OpenTelemetry GenAI in all three of its cache-field naming generations, OpenInference, raw provider SDK logs — into one normalized accounting model.
23
+ - Run a library of deterministic detectors for the silent failure modes: prefix drift, sub-minimum cache blocks, model switches, TTL expiry, breakpoint and lookback limits, tool-schema churn and bloat, context bloat, retry storms.
24
+ - Price each finding against a counterfactual — what the bill would have been under the fix — as a bounded range, never a point guess.
25
+ - Publish per-detector precision and recall against a labeled corpus, so you know how much to trust each finding.
26
+
27
+ ## Prior art
28
+
29
+ This space is crowded, and being precise about what already exists is the point of this section.
30
+
31
+ | Tool | What it does |
32
+ |---|---|
33
+ | [CacheLens](https://github.com/ChingEnLin/CacheLens) | Closest prior art. Dev-time SDK wrapper that meters cache hit rate and prefix stability per prompt layer in apps you instrument. Doesn't read existing traces, and prefix stability is its one diagnosis. |
34
+ | [Helicone](https://helicone.ai) | Observability proxy: cost and token accounting per user/session/feature, including cache token counts |
35
+ | [Langfuse](https://langfuse.com) | Open-source LLM engineering platform: tracing, evals, per-trace cost accounting |
36
+ | [Datadog LLM Observability](https://docs.datadoghq.com/llm_observability/) | Enterprise monitoring: per-request token and cost tracking, quality-issue clustering |
37
+ | [Braintrust](https://braintrust.dev) | Evals and observability; its Loop assistant root-causes *quality* failures |
38
+ | [LiteLLM](https://github.com/BerriAI/litellm) | Gateway with budgets, rate limits and spend tracking across providers |
39
+ | [ccusage](https://github.com/ryoppippi/ccusage) | CLI usage and cost reporting from Claude Code's local logs |
40
+ | [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/) | Platform-level caching, spend caps and alerts |
41
+
42
+ All of these answer "how much", and several now count cache tokens. The ones that do automatic root-cause analysis target response *quality*, not cost. The closest tool diagnoses one failure mode, for one integration style, going forward only. What none of them do is take the telemetry any agent already emitted — no code changes, any vendor — and say: *these 44 requests missed cache because the system prompt embeds a timestamp; here is the evidence, and here is what it cost.* That attribution step is this project.
43
+
44
+ If you know a tool that already does this, please open an issue — I would genuinely rather find out now.
45
+
46
+ ## What tokenaudit is not
47
+
48
+ - **Not a dashboard.** The tools above already report spend well.
49
+ - **Not a proxy, gateway, or wrapper.** It reads traces after the fact and never sits in the request path, so it can't change what it measures and doesn't need your code.
50
+ - **Not an LLM reading your logs.** Verdicts come from explicit rules with unit tests and a published false-positive rate ([decision 001](DECISIONS.md)).
51
+ - **Not a savings guarantee.** Estimates are ranges with stated assumptions, and requests whose telemetry fails a plausibility check are flagged as unpriceable, not silently priced.
52
+
53
+ ## Planned layout
54
+
55
+ src/tokenaudit/
56
+ ingest/ trace readers + schema normalization
57
+ model/ normalized requests/sessions + token accounting
58
+ detect/ the diagnosis engine (deterministic detectors)
59
+ counterfactual/ what the bill would have been under a fix
60
+ report/ CLI, JSON and HTML output
61
+ ci/ cost-regression gate for pipelines
62
+
63
+ ## Roadmap
64
+
65
+ - [x] Prior-art survey, positioning, project scaffold
66
+ - [x] Labeled trace corpus: synthetic known-answer fixtures + captured runs from real public agents
67
+ - [x] Trace reader and normalizer with a data-quality gate (bad telemetry is refused, not zero-filled)
68
+ - [x] Provider caching rulebook: minimums, TTL semantics, invalidation rules — versioned, with sources
69
+ - [x] Detectors, starting with prefix drift, sub-minimum blocks, and model/version switch
70
+ - [x] Evaluation harness: per-detector results published in [eval/results.md](eval/results.md)
71
+ - [x] `tokenaudit diagnose` CLI, HTML report, cache health score
72
+ - [ ] CI cost-regression mode: fail a build that tanks the cache hit rate
73
+ - [ ] Case studies on public agents, with reproduction commands
74
+
75
+ ## Development
76
+
77
+ python -m venv .venv && source .venv/bin/activate
78
+ pip install -e ".[dev]"
79
+ pre-commit install
80
+ pytest
81
+
82
+ ## License
83
+
84
+ Apache-2.0
@@ -0,0 +1,83 @@
1
+ # The corpus
2
+
3
+ Ground truth for the diagnosis engine, in two tracks:
4
+
5
+ - `synthetic/` — generated fixtures with **known answers**. A deterministic
6
+ simulator (`synthetic/generate.py`) replays agent sessions under specific
7
+ broken configurations and emits the traces a correctly instrumented app
8
+ would have produced, in three real schema dialects.
9
+ - `captured/` — recorded runs of **real public projects** (arrives with the
10
+ capture track). These contain genuine waste nobody scripted.
11
+
12
+ ## The boundary between the tracks
13
+
14
+ Synthetic fixtures are **unit tests, never evidence**. "The tool catches
15
+ nine bugs I planted myself" is a strawman, and this project doesn't ship
16
+ strawmen. Any number that appears in the top-level README — savings, hit
17
+ rates, case-study results — must come from `captured/` runs of code I did
18
+ not write. The synthetic track exists so that every detector has a measured
19
+ precision and recall against cases with published answers, including
20
+ negative cases where a correct tool must stay silent.
21
+
22
+ One caveat worth stating plainly: the simulator encodes the same provider
23
+ rules the detectors will check, so agreement between them is partly
24
+ circular. That is what makes the captured track non-optional — real traces
25
+ are the check against reality, and the simulator's rules cite the provider
26
+ docs they came from so they can be audited independently.
27
+
28
+ ## Label format
29
+
30
+ Every `<fixture>.trace.json` ships with `<fixture>.label.json`:
31
+
32
+ | Field | Meaning |
33
+ |---|---|
34
+ | `contains` | failure modes genuinely present — the tool should report these |
35
+ | `must_not_contain` | every other mode — reporting one of these is a false positive |
36
+ | `content_captured` | whether message content is in the trace; without it, a tool can prove waste but must not guess the cause |
37
+ | `evidence` | machine-readable pointers (which call, which block, which gap) |
38
+ | `totals` | session-level token accounting, used to cross-check dialects |
39
+ | `notes` | the human explanation |
40
+
41
+ `contains` and `must_not_contain` always partition the full failure-mode
42
+ set, so an evaluation can score both misses and false alarms.
43
+
44
+ **Attribution precedence:** when tool definitions change or reorder, ground
45
+ truth is `tool_schema_churn`, not `prefix_drift`, even though the prefix
46
+ did technically change — the fix is different, so the finding must be too.
47
+ Fixtures encode this: the tool-churn fixture lists `prefix_drift` under
48
+ `must_not_contain`.
49
+
50
+ ## Determinism
51
+
52
+ The generator uses a fixed simulated clock (2026-01-15T09:00:00Z), no
53
+ randomness, integer-only payloads, and stable JSON rendering. The same
54
+ command produces byte-identical output on any machine and Python ≥ 3.10:
55
+
56
+ python corpus/synthetic/generate.py
57
+
58
+ `tests/test_corpus.py` regenerates the corpus on every test run and fails
59
+ if the committed files differ from what the generator produces, so the
60
+ generator and fixtures cannot drift apart. Every trace carries
61
+ `tokenaudit.synthetic = true` in its resource attributes so a synthetic
62
+ file can never be mistaken for a captured one.
63
+
64
+ ## Schema dialects covered
65
+
66
+ 1. **Current OTel GenAI semconv** — `gen_ai.usage.cache_read.input_tokens`,
67
+ `gen_ai.usage.cache_creation.input_tokens`; `gen_ai.usage.input_tokens`
68
+ includes cached tokens. Message content (opt-in in real
69
+ instrumentations) rides `gen_ai.input.messages` / `gen_ai.output.messages`.
70
+ 2. **Legacy flat names** (older openllmetry) —
71
+ `gen_ai.usage.cache_read_input_tokens` etc., alongside deprecated
72
+ `gen_ai.usage.prompt_tokens`, which passes the provider's field through —
73
+ for Anthropic that count EXCLUDES cache tokens. Same session, different
74
+ arithmetic: the normalizer has to make them agree.
75
+ 3. **OpenInference** — `llm.token_count.prompt_details.cache_read` /
76
+ `.cache_write`, flattened `llm.input_messages.<i>.message.*` attributes.
77
+
78
+ Sources (verified 2026-08-29):
79
+ [OTel GenAI spans](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-spans.md) ·
80
+ [openllmetry #3647](https://github.com/traceloop/openllmetry/issues/3647) ·
81
+ [OpenInference spec](https://github.com/Arize-ai/openinference/blob/main/spec/semantic_conventions.md) ·
82
+ [Anthropic prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) ·
83
+ [OpenAI prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching)