unalloc 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,75 @@
1
+ """LiteLLM adapter.
2
+
3
+ LiteLLM's proxy already attributes spend per virtual key, team and tag, which
4
+ makes it the single highest-signal LLM source. It is also the only one that can
5
+ give you request-level granularity, so where a team runs LiteLLM this adapter
6
+ should be preferred over the direct provider adapters to avoid double counting.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import datetime
12
+ from typing import Any
13
+
14
+ from unalloc.core.models import CostRow
15
+ from unalloc.core.normalize import normalize_labels
16
+ from unalloc.sources.base import Source, money, parse_ts
17
+
18
+
19
+ class LiteLLMSource(Source):
20
+ name = "litellm"
21
+
22
+ def fetch(self, start: datetime, end: datetime) -> list[CostRow]:
23
+ payload = self._get(
24
+ "/spend/logs",
25
+ params={
26
+ "start_date": start.date().isoformat(),
27
+ "end_date": end.date().isoformat(),
28
+ },
29
+ )
30
+ return self.parse(payload)
31
+
32
+ def parse(self, payload: Any) -> list[CostRow]:
33
+ records = payload.get("data", payload) if isinstance(payload, dict) else payload
34
+ if not isinstance(records, list):
35
+ return []
36
+ return [self._row(rec) for rec in records if isinstance(rec, dict)]
37
+
38
+ def _row(self, rec: dict[str, Any]) -> CostRow:
39
+ metadata = rec.get("metadata") or {}
40
+ raw_labels: dict[str, Any] = dict(metadata) if isinstance(metadata, dict) else {}
41
+
42
+ # Tags arrive as a list; index them so a `team:platform` style tag
43
+ # becomes a real dimension instead of an opaque string.
44
+ for tag in rec.get("request_tags") or []:
45
+ text = str(tag)
46
+ if ":" in text:
47
+ key, _, value = text.partition(":")
48
+ raw_labels.setdefault(key, value)
49
+ else:
50
+ raw_labels.setdefault(text, "true")
51
+
52
+ for field in ("team_id", "user", "end_user", "api_key_alias", "model"):
53
+ if rec.get(field):
54
+ raw_labels.setdefault(field, rec[field])
55
+
56
+ tokens = rec.get("total_tokens")
57
+ if tokens is None:
58
+ tokens = (rec.get("prompt_tokens") or 0) + (rec.get("completion_tokens") or 0)
59
+
60
+ return CostRow(
61
+ source=self.name,
62
+ name=str(rec.get("model") or rec.get("api_key_alias") or "litellm-request"),
63
+ amount_usd=money(rec.get("spend") if rec.get("spend") is not None else rec.get("cost")),
64
+ start=parse_ts(rec.get("startTime") or rec.get("start_time")),
65
+ end=parse_ts(rec.get("endTime") or rec.get("end_time")),
66
+ labels=normalize_labels(raw_labels, self.aliases),
67
+ quantity=money(tokens) or None,
68
+ unit="tokens" if tokens else None,
69
+ meta={
70
+ "request_id": rec.get("request_id"),
71
+ "prompt_tokens": rec.get("prompt_tokens"),
72
+ "completion_tokens": rec.get("completion_tokens"),
73
+ "cache_hit": rec.get("cache_hit"),
74
+ },
75
+ )
@@ -0,0 +1,68 @@
1
+ """OpenAI organization costs adapter.
2
+
3
+ Uses the org-level costs endpoint, which buckets spend by time and (optionally)
4
+ project. Project is the only attribution dimension the billing API exposes, so
5
+ if an org runs everything under one project this adapter will correctly report
6
+ near-100% unallocated. That is not a bug in unalloc; it is the finding.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import datetime
12
+ from typing import Any
13
+
14
+ from unalloc.core.models import CostRow
15
+ from unalloc.core.normalize import normalize_labels
16
+ from unalloc.sources.base import Source, money, parse_ts
17
+
18
+
19
+ class OpenAISource(Source):
20
+ name = "openai"
21
+ default_base_url = "https://api.openai.com/v1"
22
+
23
+ def fetch(self, start: datetime, end: datetime) -> list[CostRow]:
24
+ payload = self._get_pages(
25
+ "/organization/costs",
26
+ params={
27
+ "start_time": int(start.timestamp()),
28
+ "end_time": int(end.timestamp()),
29
+ "bucket_width": "1d",
30
+ "group_by": "project_id",
31
+ "limit": 180,
32
+ },
33
+ )
34
+ return self.parse(payload)
35
+
36
+ def parse(self, payload: Any) -> list[CostRow]:
37
+ buckets = payload.get("data", []) if isinstance(payload, dict) else payload
38
+ if not isinstance(buckets, list):
39
+ return []
40
+ rows: list[CostRow] = []
41
+ for bucket in buckets:
42
+ if not isinstance(bucket, dict):
43
+ continue
44
+ start = parse_ts(bucket.get("start_time"))
45
+ end = parse_ts(bucket.get("end_time"), default=start)
46
+ for result in bucket.get("results") or []:
47
+ if not isinstance(result, dict):
48
+ continue
49
+ rows.append(self._row(result, start, end))
50
+ return rows
51
+
52
+ def _row(self, result: dict[str, Any], start: datetime, end: datetime) -> CostRow:
53
+ amount = result.get("amount") or {}
54
+ raw_labels = {
55
+ "project_id": result.get("project_id"),
56
+ "project": result.get("project_name"),
57
+ "line_item": result.get("line_item"),
58
+ "provider": "openai",
59
+ }
60
+ return CostRow(
61
+ source=self.name,
62
+ name=str(result.get("line_item") or result.get("project_id") or "openai-usage"),
63
+ amount_usd=money(amount.get("value") if isinstance(amount, dict) else amount),
64
+ start=start,
65
+ end=end,
66
+ labels=normalize_labels(raw_labels, self.aliases),
67
+ meta={"currency": (amount or {}).get("currency") if isinstance(amount, dict) else None},
68
+ )
@@ -0,0 +1,127 @@
1
+ """OpenCost adapter.
2
+
3
+ Reads the /allocation endpoint, which returns one or more time windows, each a
4
+ map of allocation name -> allocation object. Since 1.121.0 OpenCost also
5
+ exposes per-model inference costs for vLLM/llm-d deployments; those arrive
6
+ through the same allocation shape, so they land in the ledger for free and get
7
+ tagged with `unalloc_layer=inference` where detectable.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import datetime
13
+ from decimal import Decimal
14
+ from typing import Any
15
+
16
+ from unalloc.core.models import CostRow
17
+ from unalloc.core.normalize import normalize_labels
18
+ from unalloc.sources.base import Source, money, parse_ts
19
+
20
+
21
+ class OpenCostSource(Source):
22
+ name = "opencost"
23
+
24
+ def fetch(self, start: datetime, end: datetime) -> list[CostRow]:
25
+ payload = self._get(
26
+ "/allocation",
27
+ params={
28
+ "window": f"{start.date().isoformat()},{end.date().isoformat()}",
29
+ "aggregate": "namespace,controller,label:team",
30
+ "accumulate": "true",
31
+ "includeIdle": "true",
32
+ },
33
+ )
34
+ return self.parse(payload)
35
+
36
+ def parse(self, payload: Any) -> list[CostRow]:
37
+ rows: list[CostRow] = []
38
+ for window in _windows(payload):
39
+ for name, alloc in window.items():
40
+ if not isinstance(alloc, dict):
41
+ continue
42
+ rows.append(self._row(name, alloc))
43
+ return rows
44
+
45
+ def _row(self, name: str, alloc: dict[str, Any]) -> CostRow:
46
+ props = alloc.get("properties") or {}
47
+ raw_labels: dict[str, Any] = {}
48
+ raw_labels.update(props.get("labels") or {})
49
+ # Labels are the owner contract; an annotation with the same key must
50
+ # not silently override one.
51
+ for key, value in (props.get("annotations") or {}).items():
52
+ raw_labels.setdefault(key, value)
53
+ # Structural identity is a legitimate fallback dimension, so promote it
54
+ # into labels rather than hiding it in meta.
55
+ for key in ("namespace", "controller", "controllerKind", "cluster", "node"):
56
+ if props.get(key):
57
+ raw_labels.setdefault(key, props[key])
58
+
59
+ model = _inference_model(alloc, props)
60
+ if model:
61
+ raw_labels.setdefault("model", model)
62
+ raw_labels.setdefault("unalloc_layer", "inference")
63
+
64
+ total: Any = alloc.get("totalCost")
65
+ if total is None:
66
+ # Sum as Decimal: going via float here reintroduced exactly the
67
+ # 0.30000000000000004 noise that money() exists to keep out.
68
+ total = sum(
69
+ (
70
+ money(alloc.get(field))
71
+ for field in (
72
+ "cpuCost",
73
+ "ramCost",
74
+ "gpuCost",
75
+ "pvCost",
76
+ "networkCost",
77
+ "loadBalancerCost",
78
+ "sharedCost",
79
+ "externalCost",
80
+ )
81
+ ),
82
+ Decimal("0"),
83
+ )
84
+
85
+ return CostRow(
86
+ source=self.name,
87
+ name=alloc.get("name") or name,
88
+ amount_usd=money(total),
89
+ start=parse_ts(alloc.get("start") or alloc.get("window", {}).get("start")),
90
+ end=parse_ts(alloc.get("end") or alloc.get("window", {}).get("end")),
91
+ labels=normalize_labels(raw_labels, self.aliases),
92
+ quantity=money(alloc.get("gpuHours")) or None,
93
+ unit="gpu-hours" if alloc.get("gpuHours") else None,
94
+ meta={
95
+ "cpuCost": alloc.get("cpuCost"),
96
+ "ramCost": alloc.get("ramCost"),
97
+ "gpuCost": alloc.get("gpuCost"),
98
+ "sharedCost": alloc.get("sharedCost"),
99
+ "efficiency": alloc.get("totalEfficiency"),
100
+ },
101
+ )
102
+
103
+
104
+ def _windows(payload: Any) -> list[dict[str, Any]]:
105
+ """OpenCost has shipped several response envelopes. Accept all of them."""
106
+ data = payload.get("data") if isinstance(payload, dict) else payload
107
+ if data is None:
108
+ return []
109
+ if isinstance(data, dict):
110
+ return [data]
111
+ if isinstance(data, list):
112
+ return [window for window in data if isinstance(window, dict)]
113
+ return []
114
+
115
+
116
+ def _inference_model(alloc: dict[str, Any], props: dict[str, Any]) -> str | None:
117
+ """Best-effort detection of the 1.121.0+ inference metadata.
118
+
119
+ The field naming here is the least stable part of this adapter. If it moves
120
+ upstream, only this function changes.
121
+ """
122
+ for container in (alloc, props):
123
+ for key in ("model", "modelName", "llmModel", "inferenceModel"):
124
+ value = container.get(key)
125
+ if value:
126
+ return str(value)
127
+ return None
@@ -0,0 +1,254 @@
1
+ Metadata-Version: 2.5
2
+ Name: unalloc
3
+ Version: 0.2.0
4
+ Summary: Find the AI spend nobody owns. Joins OpenCost allocation data with LLM provider bills and reports what's unattributed.
5
+ Project-URL: Homepage, https://github.com/timurista/unalloc
6
+ Project-URL: Issues, https://github.com/timurista/unalloc/issues
7
+ Project-URL: Changelog, https://github.com/timurista/unalloc/blob/main/CHANGELOG.md
8
+ Project-URL: Paper, https://github.com/timurista/unalloc/blob/main/paper/unalloc-case-studies.pdf
9
+ Project-URL: Explorer, https://timurista.github.io/unalloc/
10
+ Author: Timothy Urista
11
+ License: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: cost-attribution,finops,kubernetes,llm,llmops,opencost,showback
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: System Administrators
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: System :: Monitoring
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: httpx>=0.27
24
+ Requires-Dist: rich>=13.7
25
+ Requires-Dist: typer>=0.12
26
+ Provides-Extra: dev
27
+ Requires-Dist: mypy>=1.11; extra == 'dev'
28
+ Requires-Dist: pytest>=8.0; extra == 'dev'
29
+ Requires-Dist: ruff>=0.6; extra == 'dev'
30
+ Provides-Extra: research
31
+ Requires-Dist: ipykernel>=6.29; extra == 'research'
32
+ Requires-Dist: jupyterlab>=4.2; extra == 'research'
33
+ Requires-Dist: matplotlib>=3.8; extra == 'research'
34
+ Requires-Dist: nbclient>=0.10; extra == 'research'
35
+ Requires-Dist: nbformat>=5.10; extra == 'research'
36
+ Requires-Dist: numpy>=1.26; extra == 'research'
37
+ Requires-Dist: psycopg[binary]>=3.2; extra == 'research'
38
+ Requires-Dist: torch>=2.3; extra == 'research'
39
+ Requires-Dist: typst>=0.13; extra == 'research'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # unalloc
43
+
44
+ **Find the AI spend nobody owns.** Joins OpenCost allocation data with LLM provider bills and reports what's unattributed.
45
+
46
+ [![ci](https://github.com/timurista/unalloc/actions/workflows/ci.yml/badge.svg)](https://github.com/timurista/unalloc/actions/workflows/ci.yml)
47
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/timurista/unalloc/blob/main/LICENSE)
48
+ [![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://github.com/timurista/unalloc/blob/main/pyproject.toml)
49
+ [![Paper](https://img.shields.io/badge/paper-PDF-1f5b45.svg)](https://github.com/timurista/unalloc/blob/main/paper/unalloc-case-studies.pdf)
50
+ [![Explorer](https://img.shields.io/badge/explorer-live-1f5b45.svg)](https://timurista.github.io/unalloc/)
51
+
52
+ OpenCost tells you what your Kubernetes workloads cost. Your provider dashboard tells you what your OpenAI and Anthropic calls cost. Neither tells you what a single AI feature costs, because the two live in different systems with different keys. `unalloc` pulls both into one normalized ledger, joins them on a label dimension you choose, and reports the number your finance team keeps asking for: how much of this month's AI spend can't be attributed to any team.
53
+
54
+ ## The output
55
+
56
+ ```
57
+ $ unalloc report --fixtures --dimension team
58
+
59
+ ╭──────────────────────────── unalloc ─────────────────────────────╮
60
+ │ 73.5% of $66,630.38 AI spend is unattributed │
61
+ │ $48,983.14 has no 'team' label │
62
+ ╰──────────────────────────────────────────────────────────────────╯
63
+
64
+ Spend by team
65
+ ┏━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┓
66
+ ┃ team ┃ Cost ┃ Share ┃ Sources ┃ Rows ┃
67
+ ┡━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━┩
68
+ │ platform │ $13,166.02 │ 19.8% │ litellm, opencost │ 2 │
69
+ │ search │ $4,481.22 │ 6.7% │ litellm, opencost │ 2 │
70
+ │ <unallocated> │ $48,983.14 │ 73.5% │ anthropic, litellm, opencost, openai │ 11 │
71
+ └─────────────────┴─────────────┴───────┴───────────────────────────────────────┴──────┘
72
+ ```
73
+
74
+ Then the actionable half: a labeling backlog sorted by dollars.
75
+
76
+ ```
77
+ $ unalloc labels --fixtures --dimension team
78
+
79
+ Labeling backlog — rows missing 'team', by cost
80
+ ┏━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
81
+ ┃ # ┃ Source ┃ Cost object ┃ Cost ┃ Labels it does have ┃
82
+ ┡━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
83
+ │ 1 │ opencost │ inference/vllm-llama-70b │ $19,147.10 │ cluster, controller, ... │
84
+ │ 2 │ opencost │ __idle__ │ $6,070.00 │ cluster │
85
+ │ 3 │ litellm │ claude-opus-5 │ $5,412.75 │ environment, model │
86
+ └────┴──────────┴───────────────────────────┴────────────┴────────────────────────────┘
87
+ ```
88
+
89
+ `inference/vllm-llama-70b` is the whole pitch: $19K of GPU spend carrying a `costCenter` label but no `team`, sitting next to $5K of Claude API spend on an unlabeled legacy key. Two systems, one gap, no existing tool that shows them in the same table.
90
+
91
+ Add a fallback and unalloc says how much of the "allocated" spend only got there through it, so a fallback onto something that is not an owner can't hide inside the headline:
92
+
93
+ ```
94
+ $ unalloc report --fixtures -D team --fallback namespace
95
+ │ 37.9% of $66,630.38 AI spend is unattributed │
96
+ │ $25,237.54 has no 'team' label │
97
+ │ $23,745.60 attributed only via fallback (namespace) │
98
+ ```
99
+
100
+ ## Install
101
+
102
+ ```bash
103
+ pip install unalloc # or: uv tool install unalloc
104
+ unalloc report --fixtures # works immediately, no infrastructure needed
105
+ ```
106
+
107
+ From a clone:
108
+
109
+ ```bash
110
+ make dev # editable install with test + lint tooling
111
+ make demo # all three commands against bundled fixtures
112
+ make check # ruff + pytest, same as CI
113
+ ```
114
+
115
+ Or as a container, which needs no Python on the host:
116
+
117
+ ```bash
118
+ docker build -t unalloc:0.2.0 .
119
+ docker run --rm unalloc:0.2.0 report --fixtures -D team
120
+
121
+ # against real systems, reachable from the container
122
+ docker run --rm --network host --env-file .env unalloc:0.2.0 report -D team
123
+ ```
124
+
125
+ Copy `.env.example` to `.env` for the source configuration. unalloc stores
126
+ nothing: no database, no state directory, no cached credentials.
127
+
128
+ ## Usage
129
+
130
+ ```bash
131
+ # What percentage of spend has no owner?
132
+ unalloc report --dimension team --days 30
133
+
134
+ # Accept a second-best key before declaring a row unallocated
135
+ unalloc report -D team --fallback namespace --fallback cost_center
136
+
137
+ # Fail a CI job when more than 10% of spend is unowned
138
+ unalloc report -D team --budget 10
139
+
140
+ # Which label keys does my data actually have?
141
+ unalloc labels --available
142
+
143
+ # The backlog honours the same fallbacks as the report
144
+ unalloc labels -D team --fallback namespace
145
+
146
+ # Does the ledger tie out to the invoice?
147
+ unalloc reconcile --invoice openai=4031.36 --invoice anthropic=8737.03
148
+
149
+ # Pipe it into something else
150
+ unalloc report --json | jq '.unallocated_pct, .fallback_usd'
151
+ ```
152
+
153
+ Configure sources by environment variable:
154
+
155
+ | Variable | Purpose |
156
+ | --- | --- |
157
+ | `UNALLOC_OPENCOST_URL` | OpenCost API root, e.g. `http://opencost.opencost:9003` |
158
+ | `UNALLOC_LITELLM_URL` | LiteLLM proxy root |
159
+ | `UNALLOC_LITELLM_KEY` | LiteLLM master or admin key |
160
+ | `OPENAI_ADMIN_KEY` | OpenAI org admin key (costs endpoint) |
161
+ | `ANTHROPIC_ADMIN_KEY` | Anthropic org admin key (cost report endpoint, sent as `x-api-key`) |
162
+ | `UNALLOC_OPENAI_URL`, `UNALLOC_ANTHROPIC_URL` | Optional overrides for the public API roots, e.g. a proxy |
163
+
164
+ Restrict the run with `--source` to avoid double counting: if your traffic goes through LiteLLM, prefer `--source opencost --source litellm` and skip the direct provider adapters, since the same tokens appear in both. The [end-to-end case study](#case-studies-and-paper) measures exactly how much that costs you if you forget.
165
+
166
+ ## How it works
167
+
168
+ ```
169
+ OpenCost /allocation ─┐
170
+ LiteLLM /spend/logs ─┤
171
+ OpenAI org costs ─┼──▶ normalize (label canonicalization + aliases)
172
+ Anthropic cost report ┘ │
173
+ ▼
174
+ CostRow[]
175
+ │
176
+ ┌────────────────┼────────────────┐
177
+ ▼ ▼ ▼
178
+ attribute reconcile labels
179
+ (unallocated %) (vs invoice) (backlog by $)
180
+ ```
181
+
182
+ Everything rests on one dataclass. An adapter's only job is turning a provider payload into `CostRow`s; it never aggregates, filters or decides anything about attribution. Adding a provider is one file and one fixture.
183
+
184
+ Two design choices worth calling out:
185
+
186
+ **Money is `Decimal`, never `float`.** Attribution that disagrees with the invoice by a cent per row is how you lose an argument with finance.
187
+
188
+ **Label canonicalization is the actual hard part.** OpenCost gives you `label_costCenter`. LiteLLM gives you `team_id` or a `team:platform` request tag. OpenAI gives you a project ID. None of those join on a naive dict lookup, so every adapter runs its labels through `normalize.py` first, which strips provider prefixes (repeatedly, so `label_app_kubernetes_io_name` and `app.kubernetes.io/name` agree), converts camelCase, and applies an alias table you can extend per-org. When two raw keys land on the same canonical key, a fixed precedence decides - explicit key, then alias, then rewritten key, then path-derived key - so the result never depends on the order a provider serialized its labels in.
189
+
190
+ ## Case studies and paper
191
+
192
+ Five studies push real (or realistically simulated) inference workloads through unalloc's own adapters. They exposed nine defects in the tool along the way, all fixed with regression tests, and they're written up as a paper: **[paper/unalloc-case-studies.pdf](https://github.com/timurista/unalloc/blob/main/paper/unalloc-case-studies.pdf)**.
193
+
194
+ | Study | What runs | Headline |
195
+ | --- | --- | --- |
196
+ | [`kv_cache`](https://github.com/timurista/unalloc/blob/main/case_studies/kv_cache) | Discrete-event vLLM-style engine: paged KV blocks, prefix caching, continuous batching, preemption | Step-time metering shows ~0% idle once any request is in flight; KV-memory metering leaves a large share of the bill unowned |
197
+ | [`torch_kv`](https://github.com/timurista/unalloc/blob/main/case_studies/torch_kv) | A from-scratch PyTorch decoder with a real KV cache serving a 4-tenant trace | Per-token showback over-charges a RAG tenant by 33 points of the pool ($5.7K/month) vs measured compute |
198
+ | [`distributed`](https://github.com/timurista/unalloc/blob/main/case_studies/distributed) | Tensor and pipeline parallel on `torch.distributed` (gloo), verified against a single-process reference | Owner label on LeaderWorkerSet leaders only: 66% unallocated; falling back to `name` "fixes" it by sending 61% to a Helm chart name |
199
+ | [`hybrid_e2e`](https://github.com/timurista/unalloc/blob/main/case_studies/hybrid_e2e) | The real CLI as a subprocess against live mock OpenCost / LiteLLM / OpenAI / Anthropic APIs (Postgres-backed LiteLLM in the dev container) | Enabling every source double counts $11.8K; reading only page one of the billing APIs reports 25% of spend |
200
+ | [`use_cases`](https://github.com/timurista/unalloc/blob/main/case_studies/use_cases) | Labeling Pareto, per-feature unit economics, self-host break-even, CI budget gate | Three label fixes take a 67%-unallocated org under 10% |
201
+
202
+ ```bash
203
+ make research # CPU torch, notebook tooling, typst
204
+ make case-studies # all five, full size (a few minutes)
205
+ make paper # figures + PDF
206
+ make notebook # execute case_studies/unalloc_case_studies.ipynb
207
+ make ui # ledger explorer on http://127.0.0.1:8765
208
+ ```
209
+
210
+ ![Share of a shared vLLM pod's bill under five metering rules](https://raw.githubusercontent.com/timurista/unalloc/main/paper/figures/kv_shares.png)
211
+
212
+ The **[ledger explorer](https://timurista.github.io/unalloc/)** (or `python -m case_studies.ui` locally) shows every dataset row by row: pick the label that means "owner", add fallbacks, and watch each row resolve to a team, a fallback value, or the backlog. `python -m case_studies.ui --export explorer.html` writes a self-contained copy you can share.
213
+
214
+ ## Development environment
215
+
216
+ An isolated dev stack lives in [`.devcontainer/`](https://github.com/timurista/unalloc/blob/main/.devcontainer): a Python 3.11 workspace with the case-study dependencies (CPU-only PyTorch) and a small Postgres that backs the mock LiteLLM spend-log store. Open the folder in VS Code's Dev Containers, or from a terminal:
217
+
218
+ ```bash
219
+ make devcontainer # docker compose up
220
+ make devcontainer-check # lint, tests and every case study at smoke size, inside the container
221
+ ```
222
+
223
+ ## Scope, and what this is not
224
+
225
+ OpenCost 1.121.0 added inference cost tracking for vLLM and llm-d deployments: cost per million tokens, KV-cache-corrected pricing, shared infrastructure attribution. That is excellent and `unalloc` does not reimplement it. Those rows arrive through the same `/allocation` shape and land in this ledger tagged `unalloc_layer=inference`.
226
+
227
+ What OpenCost structurally cannot do is see your OpenAI and Anthropic bills, because they aren't Kubernetes objects. What LiteLLM cannot do is see your GPU nodes. `unalloc` lives in exactly that seam and nowhere else. It is:
228
+
229
+ - **not** a dashboard — it prints a number and exits (the explorer is a case-study companion, not part of the CLI)
230
+ - **not** an optimizer — it makes no recommendations about rightsizing or commitments
231
+ - **not** a collector — it queries systems you already run, and stores nothing
232
+
233
+ ## Roadmap
234
+
235
+ - [ ] Prometheus exporter so `unalloc_unallocated_ratio` can be alerted on
236
+ - [ ] OpenCost external-cost plugin, so LLM API spend appears natively in OpenCost
237
+ - [ ] Per-feature unit economics using the `quantity`/`unit` fields already carried on `CostRow`
238
+ - [ ] Azure OpenAI and Bedrock adapters
239
+ - [x] `--budget` mode: exit non-zero when unallocated share crosses a threshold, for CI
240
+ - [ ] `--exclude label=value` on a source, so gateway traffic can be dropped from provider billing instead of whole sources
241
+ - [ ] Warn when distinct raw label keys collide on one canonical key
242
+
243
+ ## Contributing
244
+
245
+ Adding a source is deliberately small: implement `parse()` on a `Source` subclass, add a fixture to `src/unalloc/fixtures/`, add a case to `tests/test_sources.py`. The fixtures are the contract, so a PR with a real (scrubbed) payload from a provider is valuable even without the adapter.
246
+
247
+ ```bash
248
+ pip install -e ".[dev]"
249
+ ruff check . && pytest
250
+ ```
251
+
252
+ ## License
253
+
254
+ Apache 2.0, matching OpenCost.
@@ -0,0 +1,24 @@
1
+ unalloc/__init__.py,sha256=6L0WsNms3YMi2pc2yAPYOs8TOw0wEmiBU8oF4Adl1Io,134
2
+ unalloc/cli.py,sha256=i16vWKPt5w6lKz_hmVl8nbH8VEBbomeH4QjVgWM9--U,8046
3
+ unalloc/core/__init__.py,sha256=U4S_2y3zgLZVfMenHRaJFBW8yqh2mUBuI291LGQVOJ8,35
4
+ unalloc/core/attribute.py,sha256=cmKIMT3clJ1HBkxEYD941r_lSi981XkpR5LCiXyfWLg,4634
5
+ unalloc/core/models.py,sha256=E4Yzhru9jfuSgJ5QwewUzwCIcRfD_jm7XWGdGUyDe38,2335
6
+ unalloc/core/normalize.py,sha256=PfKyp6a-mbMbuWefEh4NvTm4r_uA3WTqkwA29OIuET4,4707
7
+ unalloc/core/reconcile.py,sha256=F_e54M30UA9gfOeE9AGzxG7O2rFb-Nv7Tn2sEVZ7xGM,3030
8
+ unalloc/fixtures/anthropic_cost_report.json,sha256=xZLD3SjzdE9WAuWLXOYUkITLK54TowqgfoWjd_nOHf0,657
9
+ unalloc/fixtures/litellm_spend.json,sha256=v3-kARdDBZHPiWfgdDOPQQrwnHMwBxmgppBYcrLfLOY,1634
10
+ unalloc/fixtures/openai_costs.json,sha256=1o8ayWPLRDZE3JMaTxdG0SY-3as59IuxfgcY4DWJVMw,685
11
+ unalloc/fixtures/opencost_allocation.json,sha256=GXrAglAqTi9qd9eV-JEUkkkM7T32ujD5Xiobh7q-m24,2657
12
+ unalloc/render/__init__.py,sha256=U4S_2y3zgLZVfMenHRaJFBW8yqh2mUBuI291LGQVOJ8,35
13
+ unalloc/render/table.py,sha256=_OBzS9Xel3SA5lHaXYD6SkBXSjujrk0tFrwxQ3aYkoY,5388
14
+ unalloc/sources/__init__.py,sha256=R9ZTZdfzbne4QnrixQU-G4OtbJJWE5vKWQmjlnjq05A,641
15
+ unalloc/sources/anthropic.py,sha256=gKbcQ3kEujP4c0S7Yjxnp1IHZmRFXNCZy9BQvTt_CIo,2711
16
+ unalloc/sources/base.py,sha256=HI1tWAwQS1l6qxe3mZe69-w24KD91X4QYNLILav2YCU,5003
17
+ unalloc/sources/litellm.py,sha256=bPhwCcND8nF6DfTBhPkUetwnMK5Luepa6Hkb1qcKc1U,2983
18
+ unalloc/sources/openai.py,sha256=nScpuV3XwBfk3INoBrLLVHsHpDSk27i5mTBUibIaIiY,2608
19
+ unalloc/sources/opencost.py,sha256=CILHj5PGd7RvVTP3AbiVp5cVXsusmrOsgXPXbJIHmyk,4799
20
+ unalloc-0.2.0.dist-info/METADATA,sha256=UXZMgtir_Qs8R5wrI3Ew3H_Nx152Q6uRKsLhNWkltII,16269
21
+ unalloc-0.2.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
22
+ unalloc-0.2.0.dist-info/entry_points.txt,sha256=NBLNMNWavNcp6Bya_aRUnSowUxx6Uk3uPQ5gGUFsjMY,45
23
+ unalloc-0.2.0.dist-info/licenses/LICENSE,sha256=vkzgu9eNXnW1xeak-rrh2sdGg9Ypa0PjLBDEFPq-oLs,11345
24
+ unalloc-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ unalloc = unalloc.cli:main