You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by gs...@apache.org on 2026/10/13 03:44:52 UTC

(tooling-llmao) branch main updated (cd76f08 -> e3b27cc)

This is an automated email from the ASF dual-hosted git repository.

gstein pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git


    from cd76f08  proxy: KeyManager, the last class cut from LiteLLMBackend
     new 1f5a8eb  proxy: delete the Backend protocol and the pass-throughs only it needed
     new 196bad8  proxy: remove the last pass-throughs; the seam talks to the managers
     new 8a8ede1  proxy: LiteLLMBackend keeps only what it uses
     new 33724d8  tiers: mint keys on the right tier, with the tier's current limits
     new 8a5af10  tests: test_phase1 and test_projects become test_seam
     new 895c82a  tests: name two test files for what they test. No functional change
     new 21bc158  tests: TeamManager's tests get a file of their own
     new 18fe212  tests: the tier tests get a file of their own
     new e3b27cc  tests: split what was left of test_entitlements by what it tests

The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 llmao/proxy/client.py                              | 177 +++-------
 llmao/seam.py                                      |  77 +++--
 tests/fake_transport.py                            |  26 ++
 tests/mock_backend.py                              |  14 +-
 tests/test_access_requests.py                      |  75 +---
 tests/test_contention.py                           |  47 +++
 tests/{test_mix.py => test_deployments.py}         |   0
 tests/test_keys.py                                 |  75 ++++
 tests/test_phase1.py                               | 179 ----------
 tests/test_projects.py                             | 193 -----------
 tests/test_seam.py                                 | 377 +++++++++++++++++++++
 tests/test_teams.py                                | 124 +++++++
 tests/test_tiers.py                                | 171 ++++++++++
 .../{test_entitlements.py => test_token_window.py} | 133 +-------
 tests/{test_spend_rows.py => test_usage.py}        |  95 +-----
 15 files changed, 931 insertions(+), 832 deletions(-)
 create mode 100644 tests/test_contention.py
 rename tests/{test_mix.py => test_deployments.py} (100%)
 create mode 100644 tests/test_keys.py
 delete mode 100644 tests/test_phase1.py
 delete mode 100644 tests/test_projects.py
 create mode 100644 tests/test_seam.py
 create mode 100644 tests/test_teams.py
 create mode 100644 tests/test_tiers.py
 rename tests/{test_entitlements.py => test_token_window.py} (51%)
 rename tests/{test_spend_rows.py => test_usage.py} (78%)


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 07/09: tests: TeamManager's tests get a file of their own

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 21bc1585fb7eccb25481ea561fd1cacf5fb37fd6
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 22:37:17 2026 -0500

    tests: TeamManager's tests get a file of their own
    
    tests/test_usage.py still held the tests for the team cap backfill and for
    looking up a team not yet listed. Both are TeamManager's, left there from
    when all of it was one class. They move to tests/test_teams.py unchanged,
    which leaves test_usage.py holding only UsageManager's.
    
    No test is added, dropped or changed.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 tests/test_teams.py | 124 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 tests/test_usage.py |  95 +---------------------------------------
 2 files changed, 125 insertions(+), 94 deletions(-)

diff --git a/tests/test_teams.py b/tests/test_teams.py
new file mode 100644
index 0000000..0fbf9fe
--- /dev/null
+++ b/tests/test_teams.py
@@ -0,0 +1,124 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""TeamManager: LiteLLM's teams, one per project."""
+
+import asyncio
+
+from easydict import EasyDict as edict  # noqa: N813
+
+from llmao.proxy.client import TeamManager
+from tests.fake_transport import FakeTransport
+
+
+def _run(coro):
+    return asyncio.run(coro)
+
+
+# ---------------------------------------------------------------------------
+# Which team is whose
+# ---------------------------------------------------------------------------
+
+
+def test_a_team_not_yet_listed_is_looked_up():
+    """A project created since the last listing must not show as no project."""
+    listing = {"teams": [{"team_alias": "tooling", "team_id": "team-tooling"}]}
+    teams = TeamManager(edict(), FakeTransport(lambda call: listing))
+    assert _run(teams.projects({"team-tooling"})) == {"team-tooling": "tooling"}
+    # ...and once it is known, it is not asked about again
+    _run(teams.projects({"team-tooling"}))
+    assert [c.path for c in teams._transport.calls] == ["team/list"]
+
+
+# ---------------------------------------------------------------------------
+# Token-cap backfill
+#
+# Projects come from LDAP, so nobody sets one up and nobody can be asked for
+# its allocation. Teams predating the allocation have none, and more appear
+# whenever a PMC is created while an older build runs.
+# ---------------------------------------------------------------------------
+
+
+def _backfill_backend(default_cap=20_000_000):
+    cfg = edict(budgets=edict(default_team_token_cap=default_cap))
+    return TeamManager(cfg, FakeTransport())
+
+
+def _sent(b):
+    """What LiteLLM was sent, as (path, json)."""
+    return [(c.path, c.json) for c in b._transport.calls]
+
+
+def test_backfill_sets_a_cap_on_teams_without_one():
+    b = _backfill_backend()
+    _run(b.backfill_token_caps([{"team_alias": "tooling", "team_id": "t1", "metadata": {"grantor": "Free Tier"}}]))
+    assert len(_sent(b)) == 1
+    path, body = _sent(b)[0]
+    assert path == "team/update"
+    assert body["metadata"]["token_cap"] == 20_000_000
+    # merged, not replaced -- grantor has to survive
+    assert body["metadata"]["grantor"] == "Free Tier"
+
+
+def test_backfill_leaves_an_existing_cap_alone():
+    """Including one deliberately set to something unusual.
+
+    The test is on the key being absent, not on its value, so a project
+    capped at zero on purpose is not quietly reset to the default.
+    """
+    b = _backfill_backend()
+    _run(
+        b.backfill_token_caps(
+            [
+                {"team_alias": "tooling", "team_id": "t1", "metadata": {"token_cap": 5}},
+                {"team_alias": "comdev", "team_id": "t2", "metadata": {"token_cap": 0}},
+            ]
+        )
+    )
+    assert _sent(b) == []
+
+
+def test_backfill_is_idempotent_across_restarts():
+    """It runs at every startup; the second boot must be a no-op."""
+    b = _backfill_backend()
+    rows = [{"team_alias": "tooling", "team_id": "t1", "metadata": {}}]
+    _run(b.backfill_token_caps(rows))
+    assert len(_sent(b)) == 1
+    rows[0]["metadata"] = _sent(b)[0][1]["metadata"]
+    _run(b.backfill_token_caps(rows))
+    assert len(_sent(b)) == 1
+
+
+def test_backfill_does_nothing_without_a_configured_default():
+    b = _backfill_backend(default_cap=0)
+    _run(b.backfill_token_caps([{"team_alias": "t", "team_id": "t1", "metadata": {}}]))
+    assert _sent(b) == []
+
+
+def test_backfill_skips_malformed_rows_without_stopping():
+    """One bad row must not cost every other project its allocation."""
+    b = _backfill_backend()
+    _run(
+        b.backfill_token_caps(
+            [
+                "not a dict",
+                {"team_alias": None, "team_id": "t0", "metadata": {}},
+                {"team_alias": "ok", "team_id": "t1", "metadata": {}},
+            ]
+        )
+    )
+    assert len(_sent(b)) == 1
+    assert _sent(b)[0][1]["team_id"] == "t1"
diff --git a/tests/test_usage.py b/tests/test_usage.py
index 820704f..0f595cf 100644
--- a/tests/test_usage.py
+++ b/tests/test_usage.py
@@ -24,10 +24,8 @@ numbers look plausible, and nobody can tell a dropped row from a quiet week.
 import asyncio
 import datetime as dt
 
-from easydict import EasyDict as edict  # noqa: N813
-
 from llmao.fleet import Fleet, FleetDeployment
-from llmao.proxy.client import TeamManager, UsageManager
+from llmao.proxy.client import UsageManager
 from tests.fake_transport import FakeTransport
 
 NOON = dt.datetime(2026, 10, 12, 12, 0, tzinfo=dt.UTC)
@@ -237,16 +235,6 @@ def test_a_key_llmao_did_not_issue_is_kept():
     assert rows[0]["user"] is None
 
 
-def test_a_team_not_yet_listed_is_looked_up():
-    """A project created since the last listing must not show as no project."""
-    listing = {"teams": [{"team_alias": "tooling", "team_id": "team-tooling"}]}
-    teams = TeamManager(edict(), FakeTransport(lambda call: listing))
-    assert _run(teams.projects({"team-tooling"})) == {"team-tooling": "tooling"}
-    # ...and once it is known, it is not asked about again
-    _run(teams.projects({"team-tooling"}))
-    assert [c.path for c in teams._transport.calls] == ["team/list"]
-
-
 def test_second_read_is_cached():
     """A page refresh must not cost another read."""
     b = _usage(WEEK)
@@ -365,84 +353,3 @@ def test_a_longer_allowance_window_reads_the_extra_days():
     _run(b.allowance("akm"))
     assert _asked(b)[-1][1].start_date == "2026-10-03"
     assert len(_asked(b)) == 2
-
-
-# ---------------------------------------------------------------------------
-# Token-cap backfill
-#
-# Projects come from LDAP, so nobody sets one up and nobody can be asked for
-# its allocation. Teams predating the allocation have none, and more appear
-# whenever a PMC is created while an older build runs.
-# ---------------------------------------------------------------------------
-
-
-def _backfill_backend(default_cap=20_000_000):
-    cfg = edict(budgets=edict(default_team_token_cap=default_cap))
-    return TeamManager(cfg, FakeTransport())
-
-
-def _sent(b):
-    """What LiteLLM was sent, as (path, json)."""
-    return [(c.path, c.json) for c in b._transport.calls]
-
-
-def test_backfill_sets_a_cap_on_teams_without_one():
-    b = _backfill_backend()
-    _run(b.backfill_token_caps([{"team_alias": "tooling", "team_id": "t1", "metadata": {"grantor": "Free Tier"}}]))
-    assert len(_sent(b)) == 1
-    path, body = _sent(b)[0]
-    assert path == "team/update"
-    assert body["metadata"]["token_cap"] == 20_000_000
-    # merged, not replaced -- grantor has to survive
-    assert body["metadata"]["grantor"] == "Free Tier"
-
-
-def test_backfill_leaves_an_existing_cap_alone():
-    """Including one deliberately set to something unusual.
-
-    The test is on the key being absent, not on its value, so a project
-    capped at zero on purpose is not quietly reset to the default.
-    """
-    b = _backfill_backend()
-    _run(
-        b.backfill_token_caps(
-            [
-                {"team_alias": "tooling", "team_id": "t1", "metadata": {"token_cap": 5}},
-                {"team_alias": "comdev", "team_id": "t2", "metadata": {"token_cap": 0}},
-            ]
-        )
-    )
-    assert _sent(b) == []
-
-
-def test_backfill_is_idempotent_across_restarts():
-    """It runs at every startup; the second boot must be a no-op."""
-    b = _backfill_backend()
-    rows = [{"team_alias": "tooling", "team_id": "t1", "metadata": {}}]
-    _run(b.backfill_token_caps(rows))
-    assert len(_sent(b)) == 1
-    rows[0]["metadata"] = _sent(b)[0][1]["metadata"]
-    _run(b.backfill_token_caps(rows))
-    assert len(_sent(b)) == 1
-
-
-def test_backfill_does_nothing_without_a_configured_default():
-    b = _backfill_backend(default_cap=0)
-    _run(b.backfill_token_caps([{"team_alias": "t", "team_id": "t1", "metadata": {}}]))
-    assert _sent(b) == []
-
-
-def test_backfill_skips_malformed_rows_without_stopping():
-    """One bad row must not cost every other project its allocation."""
-    b = _backfill_backend()
-    _run(
-        b.backfill_token_caps(
-            [
-                "not a dict",
-                {"team_alias": None, "team_id": "t0", "metadata": {}},
-                {"team_alias": "ok", "team_id": "t1", "metadata": {}},
-            ]
-        )
-    )
-    assert len(_sent(b)) == 1
-    assert _sent(b)[0][1]["team_id"] == "t1"


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 08/09: tests: the tier tests get a file of their own

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 18fe2123294034ba2673ef10bcc0e2853bd53892
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 22:40:15 2026 -0500

    tests: the tier tests get a file of their own
    
    Tier tests were in two places and named for neither. What config says a
    tier may do was in tests/test_entitlements.py, with the rolling allowance
    and the contention sampler; what an admin has changed -- TierManager -- was
    at the end of tests/test_access_requests.py. Both move, unchanged, to
    tests/test_tiers.py.
    
    The stand-in for LiteLLM's memory store was private to
    test_access_requests.py and both files need it now, so it becomes
    fake_memory() in tests/fake_transport.py.
    
    No test is added, dropped or changed.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 tests/fake_transport.py       |  26 +++++++
 tests/test_access_requests.py |  85 ++-------------------
 tests/test_entitlements.py    |  84 ---------------------
 tests/test_tiers.py           | 171 ++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 204 insertions(+), 162 deletions(-)

diff --git a/tests/fake_transport.py b/tests/fake_transport.py
index 028525e..225412d 100644
--- a/tests/fake_transport.py
+++ b/tests/fake_transport.py
@@ -58,3 +58,29 @@ class FakeTransport:
 
     async def aclose(self) -> None:
         return None
+
+
+def fake_memory(*, down: bool = False):
+    """A FakeTransport that behaves like LiteLLM's /v1/memory, and what it holds.
+
+    Returns (transport, store). `store` is the rows, key to value, for a
+    test to seed or to look at. Any call that is not to /v1/memory fails.
+    """
+    store = {}
+
+    def answer(call):
+        assert call.path == "v1/memory" or call.path.startswith("v1/memory/"), f"unexpected call: {call}"
+        key = call.path.removeprefix("v1/memory").lstrip("/")
+        if call.method == "GET" and not key:
+            hits = [{"key": k, "value": v} for k, v in store.items() if k.startswith(call.params.key_prefix)]
+            return {"memories": hits, "total": len(hits)}
+        if call.method == "GET":
+            return {"key": key, "value": store[key]} if key in store else (404, {})
+        if call.method == "PUT":
+            store[key] = call.json.value
+            return {"key": key, "value": store[key]}
+        if call.method == "DELETE":
+            return {"deleted": True} if store.pop(key, None) is not None else (404, {})
+        raise AssertionError(f"unexpected call: {call}")
+
+    return FakeTransport(answer, down=down), store
diff --git a/tests/test_access_requests.py b/tests/test_access_requests.py
index c3fbaa0..0b67778 100644
--- a/tests/test_access_requests.py
+++ b/tests/test_access_requests.py
@@ -26,7 +26,6 @@ import datetime as dt
 import json
 
 import pytest
-from easydict import EasyDict as edict  # noqa: N813
 
 from llmao import access_requests
 from llmao.access_requests import (
@@ -43,8 +42,8 @@ from llmao.access_requests import (
     loads,
     prune,
 )
-from llmao.proxy.client import AccessRequestManager, MemoryStore, TierManager
-from tests.fake_transport import FakeTransport
+from llmao.proxy.client import AccessRequestManager, MemoryStore
+from tests.fake_transport import fake_memory
 
 UTC = dt.UTC
 
@@ -309,54 +308,20 @@ def test_an_adjusted_request_differs_from_what_was_asked():
 
 
 # ---------------------------------------------------------------------------
-# The backend, against a memory store that behaves like LiteLLM's
+# AccessRequestManager, against a memory store that behaves like LiteLLM's
 #
-# Requests and tier overrides used to live in team metadata. The point of
-# moving them is that reading them no longer touches a team at all, so the
-# stand-in fails on any call that is not to /v1/memory.
+# Requests used to live in team metadata. The point of moving them is that
+# reading them no longer touches a team at all, and the stand-in fails on
+# any call that is not to /v1/memory.
 # ---------------------------------------------------------------------------
 
 
-def _litellm(*, down=False):
-    """A memory store that behaves like LiteLLM's: (transport, what it holds)."""
-    store = {}
-
-    def answer(call):
-        assert call.path == "v1/memory" or call.path.startswith("v1/memory/"), f"unexpected call: {call}"
-        key = call.path.removeprefix("v1/memory").lstrip("/")
-        if call.method == "GET" and not key:
-            hits = [{"key": k, "value": v} for k, v in store.items() if k.startswith(call.params.key_prefix)]
-            return {"memories": hits, "total": len(hits)}
-        if call.method == "GET":
-            return {"key": key, "value": store[key]} if key in store else (404, {})
-        if call.method == "PUT":
-            store[key] = call.json.value
-            return {"key": key, "value": store[key]}
-        if call.method == "DELETE":
-            return {"deleted": True} if store.pop(key, None) is not None else (404, {})
-        raise AssertionError(f"unexpected call: {call}")
-
-    return FakeTransport(answer, down=down), store
-
-
 def _requests():
     """An AccessRequestManager, and what its store holds."""
-    transport, store = _litellm()
+    transport, store = fake_memory()
     return AccessRequestManager(MemoryStore(transport)), store
 
 
-def _tiers(*, down=False):
-    """A TierManager over that store, and what the store holds."""
-    transport, store = _litellm(down=down)
-    cfg = edict(
-        entitlements=edict(
-            default=edict(rpm_limit=60, tpm_limit=60000, max_parallel_requests=4),
-            free_tier=edict(token_cap=1_000_000, token_window_days=7),
-        )
-    )
-    return TierManager(cfg, MemoryStore(transport)), store
-
-
 def _run(coro):
     return asyncio.run(coro)
 
@@ -408,39 +373,3 @@ def test_a_lapsed_approval_is_deleted_on_the_next_write():
     fresh = _capacity()
     _run(m.add(fresh))
     assert list(store) == [key_for(fresh.id)]
-
-
-def test_tier_limits_are_config_until_an_admin_changes_them():
-    t, store = _tiers()
-    assert _run(t.limits("free_tier"))["token_cap"] == 1_000_000
-    got = _run(t.set_limits("free_tier", token_cap=250_000))
-    assert got["token_cap"] == 250_000
-    assert got["token_window_days"] == 7, "what was not changed still comes from config"
-    assert list(store) == ["llmao:tiers"]
-
-
-def test_changing_one_tier_leaves_another_alone():
-    """Every tier shares the one row."""
-    t, store = _tiers()
-    _run(t.set_limits("free_tier", token_cap=250_000))
-    _run(t.set_limits("service", rpm_limit=10))
-    _run(t.set_limits("free_tier", token_window_days=3))
-    assert json.loads(store["llmao:tiers"]) == {
-        "free_tier": {"token_cap": 250_000, "token_window_days": 3},
-        "service": {"rpm_limit": 10},
-    }
-
-
-def test_tier_limits_fall_back_to_config_when_litellm_is_down():
-    """A page must still have limits to show during a proxy restart."""
-    assert _run(_tiers(down=True)[0].limits("free_tier"))["token_cap"] == 1_000_000
-
-
-def test_a_new_keys_limits_include_what_an_admin_has_changed():
-    """The Tiers page says a change applies to keys issued from then on."""
-    t, _ = _tiers()
-    assert _run(t.key_limits("service")) == {"rpm_limit": 60, "tpm_limit": 60000, "max_parallel_requests": 4}
-    _run(t.set_limits("service", rpm_limit=10, token_cap=5_000_000))
-    limits = _run(t.key_limits("service"))
-    assert limits == {"rpm_limit": 10, "tpm_limit": 60000, "max_parallel_requests": 4}
-    assert "token_cap" not in limits, "LiteLLM holds rate limits on a key, not our token cap"
diff --git a/tests/test_entitlements.py b/tests/test_entitlements.py
index c4f0fcc..407a918 100644
--- a/tests/test_entitlements.py
+++ b/tests/test_entitlements.py
@@ -25,95 +25,11 @@ identical to a working one until somebody's week does not reset.
 
 import datetime as dt
 
-import pytest
-from easydict import EasyDict as edict  # noqa: N813
-
-from llmao.proxy.client import TIER_FREE, TIER_PROJECT, TIER_SERVICE, resolve_entitlement
 from llmao.token_window import RollingAllowance
 
 UTC = dt.UTC
 
 
-def _cfg(**over):
-    base = {
-        "entitlements": {
-            "default": {"rpm_limit": 60, "tpm_limit": 60000, "max_parallel_requests": 4},
-            "free_tier": {
-                "rpm_limit": 30,
-                "tpm_limit": 30000,
-                "max_parallel_requests": 2,
-                "token_cap": 1000000,
-                "token_window_days": 7,
-            },
-            "project": {"rpm_limit": 120, "tpm_limit": 120000, "max_parallel_requests": 8},
-            "service": {"rpm_limit": 240, "tpm_limit": 300000, "max_parallel_requests": 8},
-        }
-    }
-    base.update(over)
-    return edict(base)
-
-
-# ---------------------------------------------------------------------------
-# Resolution
-# ---------------------------------------------------------------------------
-
-
-@pytest.mark.parametrize(
-    "tier,expected",
-    [
-        (TIER_FREE, {"rpm_limit": 30, "tpm_limit": 30000, "max_parallel_requests": 2}),
-        (TIER_PROJECT, {"rpm_limit": 120, "tpm_limit": 120000, "max_parallel_requests": 8}),
-        (TIER_SERVICE, {"rpm_limit": 240, "tpm_limit": 300000, "max_parallel_requests": 8}),
-    ],
-)
-def test_tier_overrides_default(tier, expected):
-    assert resolve_entitlement(_cfg(), tier) == expected
-
-
-def test_tier_inherits_what_it_does_not_name():
-    """A tier raising one ceiling must not have to restate the others.
-
-    Otherwise every tier carries a full copy of default, and the next person
-    to change default silently fails to change three of the four tiers.
-    """
-    cfg = _cfg()
-    cfg.entitlements.sparse = edict({"rpm_limit": 999})
-    assert resolve_entitlement(cfg, "sparse") == {
-        "rpm_limit": 999,  # named
-        "tpm_limit": 60000,  # inherited
-        "max_parallel_requests": 4,
-    }
-
-
-def test_unknown_tier_falls_back_to_default():
-    assert resolve_entitlement(_cfg(), "no-such-tier") == {
-        "rpm_limit": 60,
-        "tpm_limit": 60000,
-        "max_parallel_requests": 4,
-    }
-
-
-def test_absent_config_yields_no_limits():
-    """Documents the dangerous case rather than pretending it cannot happen.
-
-    LiteLLM's default for every limit is unlimited, so a config without an
-    entitlements block mints keys that can saturate the fleet. The function
-    returns {} honestly; config.yaml shipping with values is what prevents
-    it, and this test is here so nobody "fixes" the empty return into a
-    guess.
-    """
-    assert resolve_entitlement(edict({}), TIER_FREE) == {}
-
-
-def test_every_shipped_tier_sets_all_three_limits():
-    """A tier missing a limit is a tier that is unlimited in that dimension."""
-    cfg = _cfg()
-    for tier in (TIER_FREE, TIER_PROJECT, TIER_SERVICE):
-        got = resolve_entitlement(cfg, tier)
-        for field in ("rpm_limit", "tpm_limit", "max_parallel_requests"):
-            assert got.get(field), f"{tier} leaves {field} unlimited"
-
-
 # ---------------------------------------------------------------------------
 # The rolling allowance
 # ---------------------------------------------------------------------------
diff --git a/tests/test_tiers.py b/tests/test_tiers.py
new file mode 100644
index 0000000..7318b1b
--- /dev/null
+++ b/tests/test_tiers.py
@@ -0,0 +1,171 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tiers: what a key of each kind is allowed.
+
+Two layers. Config gives every tier its limits, and an admin can change them
+at runtime; a change is kept in LiteLLM's memory store and laid over config.
+
+This matters more than most because the failure is silent. A key minted
+without limits looks identical to a limited one until something saturates
+the fleet.
+"""
+
+import asyncio
+import json
+
+import pytest
+from easydict import EasyDict as edict  # noqa: N813
+
+from llmao.proxy.client import TIER_FREE, TIER_PROJECT, TIER_SERVICE, MemoryStore, TierManager, resolve_entitlement
+from tests.fake_transport import fake_memory
+
+
+def _cfg(**over):
+    base = {
+        "entitlements": {
+            "default": {"rpm_limit": 60, "tpm_limit": 60000, "max_parallel_requests": 4},
+            "free_tier": {
+                "rpm_limit": 30,
+                "tpm_limit": 30000,
+                "max_parallel_requests": 2,
+                "token_cap": 1000000,
+                "token_window_days": 7,
+            },
+            "project": {"rpm_limit": 120, "tpm_limit": 120000, "max_parallel_requests": 8},
+            "service": {"rpm_limit": 240, "tpm_limit": 300000, "max_parallel_requests": 8},
+        }
+    }
+    base.update(over)
+    return edict(base)
+
+
+# ---------------------------------------------------------------------------
+# What config says
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+    "tier,expected",
+    [
+        (TIER_FREE, {"rpm_limit": 30, "tpm_limit": 30000, "max_parallel_requests": 2}),
+        (TIER_PROJECT, {"rpm_limit": 120, "tpm_limit": 120000, "max_parallel_requests": 8}),
+        (TIER_SERVICE, {"rpm_limit": 240, "tpm_limit": 300000, "max_parallel_requests": 8}),
+    ],
+)
+def test_tier_overrides_default(tier, expected):
+    assert resolve_entitlement(_cfg(), tier) == expected
+
+
+def test_tier_inherits_what_it_does_not_name():
+    """A tier raising one ceiling must not have to restate the others.
+
+    Otherwise every tier carries a full copy of default, and the next person
+    to change default silently fails to change three of the four tiers.
+    """
+    cfg = _cfg()
+    cfg.entitlements.sparse = edict({"rpm_limit": 999})
+    assert resolve_entitlement(cfg, "sparse") == {
+        "rpm_limit": 999,  # named
+        "tpm_limit": 60000,  # inherited
+        "max_parallel_requests": 4,
+    }
+
+
+def test_unknown_tier_falls_back_to_default():
+    assert resolve_entitlement(_cfg(), "no-such-tier") == {
+        "rpm_limit": 60,
+        "tpm_limit": 60000,
+        "max_parallel_requests": 4,
+    }
+
+
+def test_absent_config_yields_no_limits():
+    """Documents the dangerous case rather than pretending it cannot happen.
+
+    LiteLLM's default for every limit is unlimited, so a config without an
+    entitlements block mints keys that can saturate the fleet. The function
+    returns {} honestly; config.yaml shipping with values is what prevents
+    it, and this test is here so nobody "fixes" the empty return into a
+    guess.
+    """
+    assert resolve_entitlement(edict({}), TIER_FREE) == {}
+
+
+def test_every_shipped_tier_sets_all_three_limits():
+    """A tier missing a limit is a tier that is unlimited in that dimension."""
+    cfg = _cfg()
+    for tier in (TIER_FREE, TIER_PROJECT, TIER_SERVICE):
+        got = resolve_entitlement(cfg, tier)
+        for field in ("rpm_limit", "tpm_limit", "max_parallel_requests"):
+            assert got.get(field), f"{tier} leaves {field} unlimited"
+
+
+# ---------------------------------------------------------------------------
+# What an admin has changed: TierManager
+# ---------------------------------------------------------------------------
+
+
+def _tiers(*, down=False):
+    """A TierManager over a stand-in memory store, and what the store holds."""
+    transport, store = fake_memory(down=down)
+    cfg = edict(
+        entitlements=edict(
+            default=edict(rpm_limit=60, tpm_limit=60000, max_parallel_requests=4),
+            free_tier=edict(token_cap=1_000_000, token_window_days=7),
+        )
+    )
+    return TierManager(cfg, MemoryStore(transport)), store
+
+
+def _run(coro):
+    return asyncio.run(coro)
+
+
+def test_tier_limits_are_config_until_an_admin_changes_them():
+    t, store = _tiers()
+    assert _run(t.limits("free_tier"))["token_cap"] == 1_000_000
+    got = _run(t.set_limits("free_tier", token_cap=250_000))
+    assert got["token_cap"] == 250_000
+    assert got["token_window_days"] == 7, "what was not changed still comes from config"
+    assert list(store) == ["llmao:tiers"]
+
+
+def test_changing_one_tier_leaves_another_alone():
+    """Every tier shares the one row."""
+    t, store = _tiers()
+    _run(t.set_limits("free_tier", token_cap=250_000))
+    _run(t.set_limits("service", rpm_limit=10))
+    _run(t.set_limits("free_tier", token_window_days=3))
+    assert json.loads(store["llmao:tiers"]) == {
+        "free_tier": {"token_cap": 250_000, "token_window_days": 3},
+        "service": {"rpm_limit": 10},
+    }
+
+
+def test_tier_limits_fall_back_to_config_when_litellm_is_down():
+    """A page must still have limits to show during a proxy restart."""
+    assert _run(_tiers(down=True)[0].limits("free_tier"))["token_cap"] == 1_000_000
+
+
+def test_a_new_keys_limits_include_what_an_admin_has_changed():
+    """The Tiers page says a change applies to keys issued from then on."""
+    t, _ = _tiers()
+    assert _run(t.key_limits("service")) == {"rpm_limit": 60, "tpm_limit": 60000, "max_parallel_requests": 4}
+    _run(t.set_limits("service", rpm_limit=10, token_cap=5_000_000))
+    limits = _run(t.key_limits("service"))
+    assert limits == {"rpm_limit": 10, "tpm_limit": 60000, "max_parallel_requests": 4}
+    assert "token_cap" not in limits, "LiteLLM holds rate limits on a key, not our token cap"


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 02/09: proxy: remove the last pass-throughs; the seam talks to the managers

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 196bad8da8cfd7b2920962cc2d0f5b60f33abef2
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 22:03:34 2026 -0500

    proxy: remove the last pass-throughs; the seam talks to the managers
    
    LiteLLMBackend still forwarded six calls -- team_info, ensure_team, usage,
    list_keys, create_key, delete_key -- because the tests' MockBackend had
    those names. They are gone, and the seam's nineteen calls name the manager
    they want: backend.teams.info(), backend.keys.find(),
    backend.metering.rows() and so on. A manager is a named group of methods;
    there is nothing for a layer in between to do.
    
    LiteLLMBackend is now what builds the managers and holds them: the
    constructor, the startup warm, the version check and close.
    
    MockBackend gets the same three names. Its methods and data are untouched;
    the constructor groups them, as teams, keys and metering.
    
    The team a projectless key is minted into is KeyManager.PROJECTLESS_TEAM.
    The seam was reading it from the backend as the private _TIER_STORE_TEAM, a
    name from when tier overrides lived on that team.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 llmao/proxy/client.py | 42 +++++++++++-------------------------------
 llmao/seam.py         | 40 ++++++++++++++++++++--------------------
 tests/mock_backend.py | 11 +++++++++--
 3 files changed, 40 insertions(+), 53 deletions(-)

diff --git a/llmao/proxy/client.py b/llmao/proxy/client.py
index b66aa15..b0b288a 100644
--- a/llmao/proxy/client.py
+++ b/llmao/proxy/client.py
@@ -299,10 +299,13 @@ class LiteLLMTransport:
 
 
 class LiteLLMBackend:
-    """Talks to a running litellm proxy, through a LiteLLMTransport.
+    """Everything llmao asks of a running litellm proxy, as one object.
 
-    In-process cache is only project (team_alias) → team_id. Spend/budget are
-    never taken from the cache. Call ``warm()`` at process start (fail-fast).
+    It builds the managers, each over the one transport, and holds them;
+    callers go to the manager for what they want -- `backend.keys.find()`,
+    `backend.teams.info()`. What each manager keeps in memory is its own
+    business and is described there. Call ``warm()`` at process start
+    (fail-fast).
     """
 
     def __init__(self, cfg: Any, fleet: Any, *, transport: Any = None):
@@ -348,34 +351,6 @@ class LiteLLMBackend:
         except BackendUnavailableError as e:
             _LOGGER.warning("could not warm usage: %s", e)
 
-    # The team a key with no project is minted into. LiteLLM wants every
-    # key in a team, and a projectless one has to go somewhere.
-    _TIER_STORE_TEAM = "llmao-entitlement-defaults"
-
-    # ---- teams: TeamManager, below --------------------------------------
-
-    async def team_info(self, project: str) -> TeamInfo | None:
-        return await self.teams.info(project)
-
-    async def ensure_team(self, project: str) -> TeamInfo:
-        return await self.teams.ensure(project)
-
-    # ---- usage: UsageManager, below -------------------------------------
-
-    async def usage(self, project: str | None) -> list[dict]:
-        return await self.metering.rows(project)
-
-    # ---- keys: KeyManager, below ----------------------------------------
-
-    async def list_keys(self, *, user: str | None = None, project: str | None = None, size: int = 100) -> list[KeyInfo]:
-        return await self.keys.find(user=user, project=project, size=size)
-
-    async def create_key(self, **wanted: Any) -> CreatedKey:
-        return await self.keys.create(**wanted)
-
-    async def delete_key(self, token_id: str) -> None:
-        await self.keys.delete(token_id)
-
 
 class KeyManager:
     """LiteLLM's virtual keys: listing, minting, revoking, and what each may do.
@@ -384,6 +359,11 @@ class KeyManager:
     into its project's team.
     """
 
+    # The team a key with no project is minted into. LiteLLM wants every
+    # key in a team, and a projectless one has to go somewhere. (The name
+    # is from when tier overrides were kept on this team's metadata.)
+    PROJECTLESS_TEAM = "llmao-entitlement-defaults"
+
     def __init__(self, cfg: Any, transport: Any, teams: Any):
         self._cfg = cfg
         self._transport = transport
diff --git a/llmao/seam.py b/llmao/seam.py
index d9b19af..08bf2f2 100644
--- a/llmao/seam.py
+++ b/llmao/seam.py
@@ -242,7 +242,7 @@ class Seam:
         names = sorted(identity.all_projects())
         rows: list[ProjectListRow] = []
         for project in names:
-            info = await self._backend.ensure_team(project)
+            info = await self._backend.teams.ensure(project)
             rows.append(self._row_from_team(project, identity, info))
         return rows
 
@@ -250,8 +250,8 @@ class Seam:
     async def project_overview(self, identity: Identity, project: str) -> ProjectOverview:
         """Read-only project budget + key-based people/automation breakdown."""
         project = (project or "").strip()
-        info = await self._backend.ensure_team(project)
-        keys = await self._backend.list_keys(project=project, size=100)
+        info = await self._backend.teams.ensure(project)
+        keys = await self._backend.keys.find(project=project, size=100)
         people, automation, by_person, auto_keys = _aggregate_keys(keys)
         return ProjectOverview(
             project=project,
@@ -271,7 +271,7 @@ class Seam:
 
     @require_member
     async def team_status(self, identity: Identity, project: str) -> TeamInfo | None:
-        return await self._backend.team_info(project)
+        return await self._backend.teams.info(project)
 
     # ---- requests -------------------------------------------------------
 
@@ -421,8 +421,8 @@ class Seam:
         the largest single consumer -- which is the thing a PMC most needs to
         see and the thing hiding it inside a person's row would obscure.
         """
-        rows = await self._backend.usage(project)
-        keys = await self._backend.list_keys(project=project, size=200)
+        rows = await self._backend.metering.rows(project)
+        keys = await self._backend.keys.find(project=project, size=200)
         # token_id -> (display name, is_service). A key with no user is
         # automation; one with a user belongs to that person.
         owner: dict[str, tuple[str, bool]] = {}
@@ -457,7 +457,7 @@ class Seam:
         return sorted(acc.values(), key=lambda e: -e["tokens"])
 
     async def list_my_keys(self, identity: Identity) -> list[KeyInfo]:
-        return await self._backend.list_keys(user=identity.uid, size=100)
+        return await self._backend.keys.find(user=identity.uid, size=100)
 
     async def my_key_usage(self, identity: Identity) -> dict[str, int]:
         """Tokens drawn per key, this week.
@@ -542,8 +542,8 @@ class Seam:
             raise AuthzError("That request has not been approved.")
 
         granted = {**req.wanted, **req.granted}
-        created = await self._backend.create_key(
-            project=req.project or self._backend._TIER_STORE_TEAM,
+        created = await self._backend.keys.create(
+            project=req.project or self._backend.keys.PROJECTLESS_TEAM,
             purpose=granted.get("purpose") or "",
             user=identity.uid,
             tier=granted.get("tier") or TIER_SERVICE,
@@ -577,7 +577,7 @@ class Seam:
         out = []
         for project in sorted(identity.committees):
             try:
-                rows = await self._backend.usage(project)
+                rows = await self._backend.metering.rows(project)
             except BackendUnavailableError:
                 continue
             tokens = 0
@@ -598,7 +598,7 @@ class Seam:
             # 20M" does.
             cap = budget = None
             try:
-                info = await self._backend.team_info(project)
+                info = await self._backend.teams.info(project)
                 if info is not None:
                     cap = getattr(info, "token_cap", None)
                     budget = info.max_budget
@@ -619,7 +619,7 @@ class Seam:
     @require_admin
     async def list_automation_keys(self, identity: Identity, project: str) -> list[KeyInfo]:
         """Automation keys for a project (admin / PMC only)."""
-        keys = await self._backend.list_keys(project=project, size=100)
+        keys = await self._backend.keys.find(project=project, size=100)
         return [k for k in keys if k.is_automation]
 
     @require_member
@@ -630,7 +630,7 @@ class Seam:
         purpose: str,
     ) -> CreatedKey:
         purpose = (purpose or "").strip()
-        return await self._backend.create_key(
+        return await self._backend.keys.create(
             project=project,
             purpose=purpose,
             user=identity.uid,
@@ -645,7 +645,7 @@ class Seam:
     ) -> CreatedKey:
         """Admin-only team-scoped key (no user) for scripts after formal request."""
         purpose = (purpose or "").strip()
-        return await self._backend.create_key(
+        return await self._backend.keys.create(
             project=project,
             purpose=purpose,
             user=None,
@@ -658,21 +658,21 @@ class Seam:
             raise AuthzError("key id required")
         # Confirm ownership: personal key belongs to uid, or automation key on
         # a project they admin.
-        keys = await self._backend.list_keys(size=100)
+        keys = await self._backend.keys.find(size=100)
         match = next((k for k in keys if k.token_id == token_id), None)
         if match is None:
-            mine = await self._backend.list_keys(user=identity.uid, size=100)
+            mine = await self._backend.keys.find(user=identity.uid, size=100)
             match = next((k for k in mine if k.token_id == token_id), None)
         if match is None:
             raise AuthzError("key not found or not visible")
         if match.user == identity.uid:
-            await self._backend.delete_key(token_id)
+            await self._backend.keys.delete(token_id)
             _log_revocation(identity, match, "own key")
             return
         if match.is_automation:
             project = match.project
             if identity.is_site_admin:
-                await self._backend.delete_key(token_id)
+                await self._backend.keys.delete(token_id)
                 _log_revocation(identity, match, "site admin")
                 return
             # Any PMC member, not only whoever created it. A service key
@@ -680,11 +680,11 @@ class Seam:
             # cannot stop -- because the creator is away at 2am -- is the
             # failure mode worth avoiding.
             if project and identity.admin_of(project):
-                await self._backend.delete_key(token_id)
+                await self._backend.keys.delete(token_id)
                 _log_revocation(identity, match, f"PMC member of {project}")
                 return
         raise AuthzError("not allowed to revoke this key")
 
     @require_admin
     async def project_activity(self, identity: Identity, project: str) -> list[dict]:
-        return await self._backend.usage(project)
+        return await self._backend.metering.rows(project)
diff --git a/tests/mock_backend.py b/tests/mock_backend.py
index 56120b9..a4f889e 100644
--- a/tests/mock_backend.py
+++ b/tests/mock_backend.py
@@ -17,8 +17,8 @@
 
 """In-process LiteLLM stand-in for the test suite only.
 
-Speaks **project** (LDAP name) like the product Backend. Uses the project
-string as the opaque team identity — no separate team_id map.
+Speaks **project** (LDAP name) like LiteLLMBackend. Uses the project string
+as the opaque team identity — no separate team_id map.
 """
 
 from __future__ import annotations
@@ -27,6 +27,8 @@ import time
 import uuid
 from typing import Any
 
+from easydict import EasyDict as edict  # noqa: N813
+
 from llmao.proxy.client import (
     GRANTOR_FREE_TIER,
     CreatedKey,
@@ -47,6 +49,11 @@ class MockBackend:
             "keys": [],
             "usage": [],
         }
+        # The seam talks to the backend's managers. Here a manager is only a
+        # name for some of the methods below.
+        self.teams = edict(info=self.team_info, ensure=self.ensure_team)
+        self.keys = edict(find=self.list_keys, create=self.create_key, delete=self.delete_key)
+        self.metering = edict(rows=self.usage)
 
     async def team_info(self, project: str) -> TeamInfo | None:
         t = self._data.get("teams", {}).get(project)


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 03/09: proxy: LiteLLMBackend keeps only what it uses

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 8a8ede166d1d5e1ffc4547502648ff71794070bd
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 22:06:34 2026 -0500

    proxy: LiteLLMBackend keeps only what it uses
    
    It stored the fleet, the config and the memory store, and read none of them
    after its constructor. The fleet and the config were kept for code that has
    since moved into managers, each of which is handed what it needs. The
    memory store is used on the two lines after it is built, so it is a local.
    
    What the backend holds now is the transport, to close it and to ask the
    proxy its version, and the six managers.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 llmao/proxy/client.py | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/llmao/proxy/client.py b/llmao/proxy/client.py
index b0b288a..12263ed 100644
--- a/llmao/proxy/client.py
+++ b/llmao/proxy/client.py
@@ -309,13 +309,11 @@ class LiteLLMBackend:
     """
 
     def __init__(self, cfg: Any, fleet: Any, *, transport: Any = None):
-        self._cfg = cfg
-        self.fleet = fleet
         self._transport = transport or LiteLLMTransport(cfg)
         self.deployments = DeploymentManager(cfg, fleet, self._transport)
-        self._memory = MemoryStore(self._transport)
-        self.requests = AccessRequestManager(self._memory)
-        self.tiers = TierManager(cfg, self._memory)
+        memory = MemoryStore(self._transport)
+        self.requests = AccessRequestManager(memory)
+        self.tiers = TierManager(cfg, memory)
         self.teams = TeamManager(cfg, self._transport)
         self.metering = UsageManager(self._transport, fleet, self.teams, self.tiers)
         self.keys = KeyManager(cfg, self._transport, self.teams)


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 05/09: tests: test_phase1 and test_projects become test_seam

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 8a5af10ab418d4586379f58c5ac5f369ccd4ba49
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 22:32:05 2026 -0500

    tests: test_phase1 and test_projects become test_seam
    
    Both tested the seam against MockBackend, with the same two helpers copied
    into each. "phase1" said when the file was written, not what it covers.
    
    tests/test_phase1.py is renamed tests/test_seam.py, and the tests from
    tests/test_projects.py are moved into it under their own heading, ahead of
    the tier tests. The duplicate helpers go; no test is added, dropped or
    changed. 286 before and after.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 tests/test_projects.py                 | 193 ---------------------------------
 tests/{test_phase1.py => test_seam.py} | 153 +++++++++++++++++++++++++-
 2 files changed, 148 insertions(+), 198 deletions(-)

diff --git a/tests/test_projects.py b/tests/test_projects.py
deleted file mode 100644
index c46d37b..0000000
--- a/tests/test_projects.py
+++ /dev/null
@@ -1,193 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-"""P0.1: project list + overview seam (mock backend)."""
-
-import asyncio
-
-import pytest
-from easydict import EasyDict as edict  # noqa: N813
-
-from llmao.proxy.client import GRANTOR_FREE_TIER, BackendUnavailableError, resolve_budget_duration
-from llmao.seam import (
-    AuthzError,
-    Identity,
-    Seam,
-)
-from tests.mock_backend import MockBackend
-
-
-def _cfg():
-    return edict(
-        {
-            "litellm": {
-                "base_url": "http://127.0.0.1:4000",
-                "master_key": "sk-test",
-                "request_timeout_s": 30,
-            },
-            "budgets": {
-                "default_team_budget_usd": 100.0,
-                "duration": "30d",
-            },
-            "site_admins": ["root"],
-            "models_path": "models.yaml",
-        }
-    )
-
-
-def _seam():
-    cfg = _cfg()
-    backend = MockBackend(cfg)
-    return Seam(cfg, backend), cfg, backend
-
-
-def test_resolve_budget_duration_prefers_raw_then_cfg():
-    cfg = _cfg()
-    assert resolve_budget_duration("7d", cfg) == "7d"
-    assert resolve_budget_duration(None, cfg) == "30d"
-    assert resolve_budget_duration("  ", cfg) == "30d"
-    bad = edict({"budgets": {}})
-    with pytest.raises(BackendUnavailableError):
-        resolve_budget_duration(None, bad)
-
-
-def test_list_projects_empty_membership():
-    async def run():
-        seam, _, _ = _seam()
-        ident = Identity(uid="jdoe", projects=[], committees=[])
-        assert await seam.list_projects_for(ident) == []
-
-    asyncio.run(run())
-
-
-def test_list_projects_ensures_team_and_budget():
-    async def run():
-        seam, cfg, backend = _seam()
-        ident = Identity(uid="jdoe", projects=["airflow"], committees=[])
-        assert await backend.team_info("airflow") is None
-        rows = await seam.list_projects_for(ident)
-        assert len(rows) == 1
-        r = rows[0]
-        assert r.project == "airflow"
-        assert r.is_steward is False
-        assert r.max_budget == float(cfg.budgets.default_team_budget_usd)
-        assert r.spend == 0.0
-        assert r.remaining == r.max_budget
-        assert r.pct_used == 0.0
-        assert r.budget_duration == "30d"
-        assert r.grantor == GRANTOR_FREE_TIER
-        info = await backend.team_info("airflow")
-        assert info is not None
-        assert info.budget_duration == "30d"
-
-    asyncio.run(run())
-
-
-def test_list_projects_steward_flag():
-    async def run():
-        seam, _, _ = _seam()
-        ident = Identity(
-            uid="chair",
-            projects=["kafka"],
-            committees=["airflow"],
-        )
-        rows = await seam.list_projects_for(ident)
-        by_name = {r.project: r for r in rows}
-        assert by_name["airflow"].is_steward is True
-        assert by_name["kafka"].is_steward is False
-        assert sorted(by_name) == ["airflow", "kafka"]
-
-    asyncio.run(run())
-
-
-def test_overview_authz_outsider():
-    async def run():
-        seam, _, _ = _seam()
-        ident = Identity(uid="jdoe", projects=["airflow"], committees=[])
-        with pytest.raises(AuthzError):
-            await seam.project_overview(ident, "kafka")
-
-    asyncio.run(run())
-
-
-def test_overview_ensures_team():
-    async def run():
-        seam, cfg, backend = _seam()
-        ident = Identity(uid="jdoe", projects=["airflow"], committees=[])
-        ov = await seam.project_overview(ident, "airflow")
-        assert ov.project == "airflow"
-        assert ov.max_budget == float(cfg.budgets.default_team_budget_usd)
-        assert ov.budget_duration == "30d"
-        assert ov.grantor == GRANTOR_FREE_TIER
-        assert ov.people_spend == 0.0
-        assert ov.automation_spend == 0.0
-        assert ov.by_person == []
-        assert ov.automation_key_count == 0
-        assert await backend.team_info("airflow") is not None
-
-    asyncio.run(run())
-
-
-def test_overview_people_automation_and_by_person():
-    async def run():
-        seam, _, backend = _seam()
-        admin = Identity(uid="chair", projects=[], committees=["airflow"])
-        alice = Identity(uid="alice", projects=["airflow"], committees=[])
-        bob = Identity(uid="bob", projects=["airflow"], committees=[])
-
-        k_alice = await seam.create_personal_key(alice, "airflow", "cli")
-        k_bob1 = await seam.create_personal_key(bob, "airflow", "a")
-        k_bob2 = await seam.create_personal_key(bob, "airflow", "b")
-        k_auto = await seam.create_automation_key(admin, "airflow", "ci")
-
-        backend.set_key_spend(k_alice.info.token_id, 10.0)
-        backend.set_key_spend(k_bob1.info.token_id, 3.0)
-        backend.set_key_spend(k_bob2.info.token_id, 4.0)
-        backend.set_key_spend(k_auto.info.token_id, 2.5)
-        backend.set_team_spend("airflow", 50.0)
-
-        # Member (non-steward) sees transparency.
-        ov = await seam.project_overview(alice, "airflow")
-        assert ov.is_steward is False
-        assert ov.spend == 50.0
-        assert ov.people_spend == 17.0
-        assert ov.automation_spend == 2.5
-        assert [p.uid for p in ov.by_person] == ["alice", "bob"]
-        assert ov.by_person[0].spend == 10.0
-        assert ov.by_person[0].key_count == 1
-        assert ov.by_person[1].spend == 7.0
-        assert ov.by_person[1].key_count == 2
-        assert ov.automation_key_count == 1
-        assert ov.automation_keys[0].created_by == "chair"
-        assert ov.automation_keys[0].spend == 2.5
-        assert ov.grantor == GRANTOR_FREE_TIER
-
-    asyncio.run(run())
-
-
-def test_site_admin_overview_without_membership():
-    async def run():
-        seam, _, _ = _seam()
-        root = Identity(uid="root", projects=[], committees=[], is_site_admin=True)
-        # Not on list (all_projects empty)
-        assert await seam.list_projects_for(root) == []
-        ov = await seam.project_overview(root, "airflow")
-        assert ov.project == "airflow"
-        assert ov.is_steward is True  # site admin
-        assert ov.grantor == GRANTOR_FREE_TIER
-
-    asyncio.run(run())
diff --git a/tests/test_phase1.py b/tests/test_seam.py
similarity index 58%
rename from tests/test_phase1.py
rename to tests/test_seam.py
index 70b88d5..b6feb37 100644
--- a/tests/test_phase1.py
+++ b/tests/test_seam.py
@@ -15,12 +15,11 @@
 # specific language governing permissions and limitations
 # under the License.
 
-"""Offline tests: mock backend + seam authz.
+"""The seam, against the in-memory stand-in for LiteLLM (tests/mock_backend.py).
 
-Authenticated HTTP endpoints require a real asfquart session (OAuth). Those
-paths are not automated while the stack is in flux; expand later if needed.
-Model inventory tests live in test_models.py.
-Run with: pytest -q
+Who may do what, and how the seam puts together what the managers give it:
+keys, the project list and a project's overview. Nothing here reaches
+LiteLLM or needs a signed-in session.
 """
 
 import asyncio
@@ -29,6 +28,7 @@ import time
 import pytest
 from easydict import EasyDict as edict  # noqa: N813
 
+from llmao.proxy.client import GRANTOR_FREE_TIER, BackendUnavailableError, resolve_budget_duration
 from llmao.seam import AuthzError, Identity, Seam
 from tests.mock_backend import MockBackend
 
@@ -179,6 +179,149 @@ def test_site_admin_sees_any_project():
     asyncio.run(run())
 
 
+# ---------------------------------------------------------------------------
+# The project list, and one project's overview
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_budget_duration_prefers_raw_then_cfg():
+    cfg = _cfg()
+    assert resolve_budget_duration("7d", cfg) == "7d"
+    assert resolve_budget_duration(None, cfg) == "30d"
+    assert resolve_budget_duration("  ", cfg) == "30d"
+    bad = edict({"budgets": {}})
+    with pytest.raises(BackendUnavailableError):
+        resolve_budget_duration(None, bad)
+
+
+def test_list_projects_empty_membership():
+    async def run():
+        seam, _, _ = _seam()
+        ident = Identity(uid="jdoe", projects=[], committees=[])
+        assert await seam.list_projects_for(ident) == []
+
+    asyncio.run(run())
+
+
+def test_list_projects_ensures_team_and_budget():
+    async def run():
+        seam, cfg, backend = _seam()
+        ident = Identity(uid="jdoe", projects=["airflow"], committees=[])
+        assert await backend.team_info("airflow") is None
+        rows = await seam.list_projects_for(ident)
+        assert len(rows) == 1
+        r = rows[0]
+        assert r.project == "airflow"
+        assert r.is_steward is False
+        assert r.max_budget == float(cfg.budgets.default_team_budget_usd)
+        assert r.spend == 0.0
+        assert r.remaining == r.max_budget
+        assert r.pct_used == 0.0
+        assert r.budget_duration == "30d"
+        assert r.grantor == GRANTOR_FREE_TIER
+        info = await backend.team_info("airflow")
+        assert info is not None
+        assert info.budget_duration == "30d"
+
+    asyncio.run(run())
+
+
+def test_list_projects_steward_flag():
+    async def run():
+        seam, _, _ = _seam()
+        ident = Identity(
+            uid="chair",
+            projects=["kafka"],
+            committees=["airflow"],
+        )
+        rows = await seam.list_projects_for(ident)
+        by_name = {r.project: r for r in rows}
+        assert by_name["airflow"].is_steward is True
+        assert by_name["kafka"].is_steward is False
+        assert sorted(by_name) == ["airflow", "kafka"]
+
+    asyncio.run(run())
+
+
+def test_overview_authz_outsider():
+    async def run():
+        seam, _, _ = _seam()
+        ident = Identity(uid="jdoe", projects=["airflow"], committees=[])
+        with pytest.raises(AuthzError):
+            await seam.project_overview(ident, "kafka")
+
+    asyncio.run(run())
+
+
+def test_overview_ensures_team():
+    async def run():
+        seam, cfg, backend = _seam()
+        ident = Identity(uid="jdoe", projects=["airflow"], committees=[])
+        ov = await seam.project_overview(ident, "airflow")
+        assert ov.project == "airflow"
+        assert ov.max_budget == float(cfg.budgets.default_team_budget_usd)
+        assert ov.budget_duration == "30d"
+        assert ov.grantor == GRANTOR_FREE_TIER
+        assert ov.people_spend == 0.0
+        assert ov.automation_spend == 0.0
+        assert ov.by_person == []
+        assert ov.automation_key_count == 0
+        assert await backend.team_info("airflow") is not None
+
+    asyncio.run(run())
+
+
+def test_overview_people_automation_and_by_person():
+    async def run():
+        seam, _, backend = _seam()
+        admin = Identity(uid="chair", projects=[], committees=["airflow"])
+        alice = Identity(uid="alice", projects=["airflow"], committees=[])
+        bob = Identity(uid="bob", projects=["airflow"], committees=[])
+
+        k_alice = await seam.create_personal_key(alice, "airflow", "cli")
+        k_bob1 = await seam.create_personal_key(bob, "airflow", "a")
+        k_bob2 = await seam.create_personal_key(bob, "airflow", "b")
+        k_auto = await seam.create_automation_key(admin, "airflow", "ci")
+
+        backend.set_key_spend(k_alice.info.token_id, 10.0)
+        backend.set_key_spend(k_bob1.info.token_id, 3.0)
+        backend.set_key_spend(k_bob2.info.token_id, 4.0)
+        backend.set_key_spend(k_auto.info.token_id, 2.5)
+        backend.set_team_spend("airflow", 50.0)
+
+        # Member (non-steward) sees transparency.
+        ov = await seam.project_overview(alice, "airflow")
+        assert ov.is_steward is False
+        assert ov.spend == 50.0
+        assert ov.people_spend == 17.0
+        assert ov.automation_spend == 2.5
+        assert [p.uid for p in ov.by_person] == ["alice", "bob"]
+        assert ov.by_person[0].spend == 10.0
+        assert ov.by_person[0].key_count == 1
+        assert ov.by_person[1].spend == 7.0
+        assert ov.by_person[1].key_count == 2
+        assert ov.automation_key_count == 1
+        assert ov.automation_keys[0].created_by == "chair"
+        assert ov.automation_keys[0].spend == 2.5
+        assert ov.grantor == GRANTOR_FREE_TIER
+
+    asyncio.run(run())
+
+
+def test_site_admin_overview_without_membership():
+    async def run():
+        seam, _, _ = _seam()
+        root = Identity(uid="root", projects=[], committees=[], is_site_admin=True)
+        # Not on list (all_projects empty)
+        assert await seam.list_projects_for(root) == []
+        ov = await seam.project_overview(root, "airflow")
+        assert ov.project == "airflow"
+        assert ov.is_steward is True  # site admin
+        assert ov.grantor == GRANTOR_FREE_TIER
+
+    asyncio.run(run())
+
+
 # ---------------------------------------------------------------------------
 # Which tier a key is minted on
 #


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 04/09: tiers: mint keys on the right tier, with the tier's current limits

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 33724d8bb23e8e91a6df0e4547667c16edbb4c51
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 22:27:06 2026 -0500

    tiers: mint keys on the right tier, with the tier's current limits
    
    Four bugs in how a tier reaches a key.
    
    A tier change never reached new keys. The Tiers page tells an admin that
    rate limits "apply to keys issued from now on", but minting read the limits
    from config alone and ignored what the admin had set. KeyManager.create now
    asks TierManager, through the new key_limits(), for the tier as it stands.
    
    Automation keys were minted on the project tier. Minting defaulted to it,
    and create_automation_key did not say otherwise. It names the service tier
    now, which is what that tier is for. The tier argument has no default any
    more, so a caller that forgets fails rather than quietly getting project
    limits. This raises the limits on automation keys created from here on.
    
    A key request could name any tier. It arrives in a form post and was stored
    unchecked, so an invented name would later mint a key on the default limits
    under a tier no page lists. request_key and set_tier refuse a tier that is
    not one of the three.
    
    A key's recorded tier could disagree with its limits. Metadata that already
    named a tier kept its name while the limits came from the argument. The
    argument decides both.
    
    tests/test_keys.py is the first test of the real KeyManager: what
    key/generate is sent. The seam tests check which tier each path uses and
    that unknown tiers are refused.
    
    Not addressed: keys already minted keep the limits they were given.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 llmao/proxy/client.py         | 34 +++++++++++++++-----
 llmao/seam.py                 | 18 +++++++++--
 tests/mock_backend.py         |  3 ++
 tests/test_access_requests.py | 10 ++++++
 tests/test_keys.py            | 75 +++++++++++++++++++++++++++++++++++++++++++
 tests/test_phase1.py          | 55 +++++++++++++++++++++++++++++++
 6 files changed, 184 insertions(+), 11 deletions(-)

diff --git a/llmao/proxy/client.py b/llmao/proxy/client.py
index 12263ed..9e33b07 100644
--- a/llmao/proxy/client.py
+++ b/llmao/proxy/client.py
@@ -54,6 +54,7 @@ GRANTOR_FREE_TIER = "Free Tier"
 TIER_FREE = "free_tier"
 TIER_PROJECT = "project"
 TIER_SERVICE = "service"
+TIERS = (TIER_FREE, TIER_PROJECT, TIER_SERVICE)
 
 # LiteLLM fields these map to. Named here so the mapping is in one place
 # rather than spread across call sites.
@@ -316,7 +317,7 @@ class LiteLLMBackend:
         self.tiers = TierManager(cfg, memory)
         self.teams = TeamManager(cfg, self._transport)
         self.metering = UsageManager(self._transport, fleet, self.teams, self.tiers)
-        self.keys = KeyManager(cfg, self._transport, self.teams)
+        self.keys = KeyManager(self._transport, self.teams, self.tiers)
 
     async def aclose(self) -> None:
         await self._transport.aclose()
@@ -353,8 +354,8 @@ class LiteLLMBackend:
 class KeyManager:
     """LiteLLM's virtual keys: listing, minting, revoking, and what each may do.
 
-    Handed the config, the transport and the teams -- every key is minted
-    into its project's team.
+    Handed the transport, the teams -- every key is minted into its
+    project's team -- and the tiers, which say what a new key may do.
     """
 
     # The team a key with no project is minted into. LiteLLM wants every
@@ -362,10 +363,10 @@ class KeyManager:
     # is from when tier overrides were kept on this team's metadata.)
     PROJECTLESS_TEAM = "llmao-entitlement-defaults"
 
-    def __init__(self, cfg: Any, transport: Any, teams: Any):
-        self._cfg = cfg
+    def __init__(self, transport: Any, teams: Any, tiers: Any):
         self._transport = transport
         self.teams = teams
+        self.tiers = tiers
 
     async def update_entitlement(
         self,
@@ -444,10 +445,15 @@ class KeyManager:
         project: str,
         purpose: str,
         user: str | None = None,
+        tier: str,
         metadata: dict | None = None,
-        tier: str = TIER_PROJECT,
         token_cap: int | None = None,
     ) -> CreatedKey:
+        """Mint a key on `tier`, which decides its rate limits.
+
+        The tier has no default. It used to be the project tier, and a
+        caller that forgot to say got project limits for a pipeline key.
+        """
         project = (project or "").strip()
         if not project:
             raise BackendUnavailableError("create_key requires project")
@@ -463,7 +469,7 @@ class KeyManager:
         # price and no budget can ever be exhausted by them. A key minted
         # without limits can saturate the fleet, and LiteLLM's default is
         # unlimited.
-        meta.setdefault("tier", tier)
+        meta["tier"] = tier
         if token_cap is not None:
             # A per-key allowance, set by an admin when approving. Only a
             # projectless service key really needs one: a project key draws
@@ -471,7 +477,10 @@ class KeyManager:
             # a key belonging to neither has nothing to draw on, and
             # unattended automation would consume a week in an afternoon.
             meta["token_cap"] = int(token_cap)
-        limits = resolve_entitlement(self._cfg, tier)
+        # From the tiers rather than from config alone: an admin who has
+        # changed a tier's limits is told they apply to keys issued from
+        # then on, and this is where that is made true.
+        limits = await self.tiers.key_limits(tier)
 
         payload: dict[str, Any] = {
             "team_id": team_id,
@@ -1140,6 +1149,15 @@ class TierManager:
             effective.update({k: v for k, v in stored.items() if v is not None})
         return effective
 
+    async def key_limits(self, tier: str) -> dict[str, Any]:
+        """The rate limits a key minted on this tier is given.
+
+        Config with the admin's changes on top, like limits(), but only what
+        LiteLLM holds on a key. The token cap is not one of those: it is
+        metered here, against usage, and LiteLLM would not know the field.
+        """
+        return {k: v for k, v in (await self.limits(tier)).items() if k in _LIMIT_FIELDS}
+
     async def set_limits(
         self,
         tier: str,
diff --git a/llmao/seam.py b/llmao/seam.py
index 08bf2f2..71dffe8 100644
--- a/llmao/seam.py
+++ b/llmao/seam.py
@@ -33,9 +33,9 @@ from typing import Any
 from . import access_requests as _access
 from .proxy.client import (
     GRANTOR_FREE_TIER,
-    TIER_FREE,
     TIER_PROJECT,
     TIER_SERVICE,
+    TIERS,
     BackendUnavailableError,
     CreatedKey,
     KeyInfo,
@@ -319,12 +319,18 @@ class Seam:
             raise AuthzError("Say what the key is for.")
         if project and project not in (identity.committees or []):
             raise AuthzError(f"You are not on the {project} PMC.")
+        tier = (tier or "").strip() or TIER_SERVICE
+        if tier not in TIERS:
+            # The tier arrives in a form post and ends up deciding a key's
+            # limits. An unknown one would mint a key on the defaults, under
+            # a name no page lists.
+            raise AuthzError(f"There is no {tier} tier.")
         req = _access.AccessRequest.new(
             kind=_access.KIND_KEY,
             requester=identity.uid,
             project=project,
             reason=reason,
-            wanted={"purpose": purpose, "tier": tier or TIER_SERVICE},
+            wanted={"purpose": purpose, "tier": tier},
         )
         return await self._backend.requests.add(req)
 
@@ -339,7 +345,7 @@ class Seam:
         if not identity.is_site_admin:
             raise AuthzError("Tiers are limited to site admins.")
         out = []
-        for tier in (TIER_FREE, TIER_PROJECT, TIER_SERVICE):
+        for tier in TIERS:
             out.append({"tier": tier, **(await self._backend.tiers.limits(tier))})
         return out
 
@@ -351,6 +357,8 @@ class Seam:
         """
         if not identity.is_site_admin:
             raise AuthzError("Changing tiers is limited to site admins.")
+        if tier not in TIERS:
+            raise AuthzError(f"There is no {tier} tier.")
         named = {k: v for k, v in limits.items() if v is not None}
         if not named:
             raise AuthzError("Nothing to change.")
@@ -634,6 +642,8 @@ class Seam:
             project=project,
             purpose=purpose,
             user=identity.uid,
+            # A person's key in a project draws on the project's share.
+            tier=TIER_PROJECT,
         )
 
     @require_admin
@@ -650,6 +660,8 @@ class Seam:
             purpose=purpose,
             user=None,
             metadata={"created_by": identity.uid},
+            # No person at the keyboard: this is what the service tier is for.
+            tier=TIER_SERVICE,
         )
 
     async def revoke_key(self, identity: Identity, token_id: str) -> None:
diff --git a/tests/mock_backend.py b/tests/mock_backend.py
index a4f889e..f756bf9 100644
--- a/tests/mock_backend.py
+++ b/tests/mock_backend.py
@@ -116,8 +116,10 @@ class MockBackend:
         *,
         project: str,
         purpose: str,
+        tier: str,
         user: str | None = None,
         metadata: dict | None = None,
+        token_cap: int | None = None,
     ) -> CreatedKey:
         project = (project or "").strip()
         purpose = (purpose or "").strip()
@@ -126,6 +128,7 @@ class MockBackend:
         token_id = f"tok-{uuid.uuid4().hex[:16]}"
         meta = dict(metadata or {})
         meta["project"] = project
+        meta["tier"] = tier
         if purpose:
             meta["purpose"] = purpose
         row = {
diff --git a/tests/test_access_requests.py b/tests/test_access_requests.py
index 940f0d5..c3fbaa0 100644
--- a/tests/test_access_requests.py
+++ b/tests/test_access_requests.py
@@ -434,3 +434,13 @@ def test_changing_one_tier_leaves_another_alone():
 def test_tier_limits_fall_back_to_config_when_litellm_is_down():
     """A page must still have limits to show during a proxy restart."""
     assert _run(_tiers(down=True)[0].limits("free_tier"))["token_cap"] == 1_000_000
+
+
+def test_a_new_keys_limits_include_what_an_admin_has_changed():
+    """The Tiers page says a change applies to keys issued from then on."""
+    t, _ = _tiers()
+    assert _run(t.key_limits("service")) == {"rpm_limit": 60, "tpm_limit": 60000, "max_parallel_requests": 4}
+    _run(t.set_limits("service", rpm_limit=10, token_cap=5_000_000))
+    limits = _run(t.key_limits("service"))
+    assert limits == {"rpm_limit": 10, "tpm_limit": 60000, "max_parallel_requests": 4}
+    assert "token_cap" not in limits, "LiteLLM holds rate limits on a key, not our token cap"
diff --git a/tests/test_keys.py b/tests/test_keys.py
new file mode 100644
index 0000000..3ca1844
--- /dev/null
+++ b/tests/test_keys.py
@@ -0,0 +1,75 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Minting a key: what LiteLLM is actually sent.
+
+The seam tests run against MockBackend and never reach this code.
+"""
+
+import asyncio
+
+from easydict import EasyDict as edict  # noqa: N813
+
+from llmao.proxy.client import KeyManager
+from tests.fake_transport import FakeTransport
+
+
+class _Teams:
+    """Stands in for TeamManager: every project has a team."""
+
+    async def ensure(self, project):
+        return edict(team_id=f"team-{project}")
+
+
+class _Tiers:
+    """Stands in for TierManager: the service tier has been cut to 10 a minute."""
+
+    async def key_limits(self, tier):
+        return {"rpm_limit": 10 if tier == "service" else 120, "tpm_limit": 60000}
+
+
+def _keys():
+    def litellm(call):
+        # key/generate answers with the key it made
+        return {"key": "sk-secret", "token": "tok1", **call.json}
+
+    return KeyManager(FakeTransport(litellm), _Teams(), _Tiers())
+
+
+def _sent(keys):
+    return keys._transport.calls[-1]
+
+
+def test_a_key_is_minted_with_its_tiers_limits():
+    keys = _keys()
+    created = asyncio.run(keys.create(project="airflow", purpose="ci", user="jdoe", tier="service"))
+    sent = _sent(keys)
+    assert (sent.method, sent.path) == ("POST", "key/generate")
+    assert sent.json.rpm_limit == 10, "the tier's limit as it stands now, not as config had it"
+    assert sent.json.tpm_limit == 60000
+    assert sent.json.team_id == "team-airflow"
+    assert sent.json.user_id == "jdoe"
+    assert created.secret == "sk-secret"
+    assert created.info.project == "airflow"
+
+
+def test_the_tier_asked_for_is_the_tier_recorded():
+    """Metadata naming one tier while the limits came from another is how an audit goes wrong."""
+    keys = _keys()
+    asyncio.run(keys.create(project="airflow", purpose="ci", user="jdoe", tier="project", metadata={"tier": "service"}))
+    sent = _sent(keys)
+    assert sent.json.metadata.tier == "project"
+    assert sent.json.rpm_limit == 120
diff --git a/tests/test_phase1.py b/tests/test_phase1.py
index 8a2ddb7..70b88d5 100644
--- a/tests/test_phase1.py
+++ b/tests/test_phase1.py
@@ -177,3 +177,58 @@ def test_site_admin_sees_any_project():
         assert len(rows) == 1
 
     asyncio.run(run())
+
+
+# ---------------------------------------------------------------------------
+# Which tier a key is minted on
+#
+# The tier decides a key's rate limits, and those are the only control there
+# is on self-hosted capacity. Minting used to default to the project tier,
+# so a path that did not say got project limits whatever it was for.
+# ---------------------------------------------------------------------------
+
+
+def _minted_tier(backend):
+    return backend._data["keys"][-1]["metadata"]["tier"]
+
+
+def test_a_persons_project_key_is_on_the_project_tier():
+    async def run():
+        seam, _, backend = _seam()
+        await seam.create_personal_key(Identity(uid="jdoe", projects=["airflow"], committees=[]), "airflow", "cli")
+        assert _minted_tier(backend) == "project"
+
+    asyncio.run(run())
+
+
+def test_an_automation_key_is_on_the_service_tier():
+    """No person at the keyboard is what the service tier is for."""
+
+    async def run():
+        seam, _, backend = _seam()
+        await seam.create_automation_key(Identity(uid="chair", projects=[], committees=["airflow"]), "airflow", "ci")
+        assert _minted_tier(backend) == "service"
+
+    asyncio.run(run())
+
+
+def test_a_key_request_cannot_name_a_tier_that_does_not_exist():
+    """The tier comes from a form post and ends up deciding a key's limits."""
+
+    async def run():
+        seam, _, _ = _seam()
+        ident = Identity(uid="jdoe", projects=[], committees=[])
+        with pytest.raises(AuthzError, match="no platinum tier"):
+            await seam.request_key(ident, purpose="ci", tier="platinum", reason="because")
+
+    asyncio.run(run())
+
+
+def test_an_admin_cannot_change_a_tier_that_does_not_exist():
+    async def run():
+        seam, _, _ = _seam()
+        root = Identity(uid="root", projects=[], committees=[], is_site_admin=True)
+        with pytest.raises(AuthzError, match="no platinum tier"):
+            await seam.set_tier(root, "platinum", rpm_limit=1)
+
+    asyncio.run(run())


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 09/09: tests: split what was left of test_entitlements by what it tests

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit e3b27cc0c957fc4a61484081a21d3da3299cb077
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 22:42:06 2026 -0500

    tests: split what was left of test_entitlements by what it tests
    
    With the tier tests gone, tests/test_entitlements.py held two unrelated
    things under a name that fitted neither: the rolling token allowance, and
    parsing a box's metrics for the contention sampler.
    
    It is renamed tests/test_token_window.py, after the module it tests, and
    the two contention tests move to tests/test_contention.py.
    
    No test is added, dropped or changed. The contention tests import
    parse_metrics once at the top of their file rather than inside each test.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 tests/test_contention.py                           | 47 +++++++++++++++++++++
 .../{test_entitlements.py => test_token_window.py} | 49 ++--------------------
 2 files changed, 50 insertions(+), 46 deletions(-)

diff --git a/tests/test_contention.py b/tests/test_contention.py
new file mode 100644
index 0000000..1764edd
--- /dev/null
+++ b/tests/test_contention.py
@@ -0,0 +1,47 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Contention sampling (llmao/contention.py).
+
+The pilot's one unanswerable-after-the-fact question: did anyone wait?
+"""
+
+from llmao.contention import parse_metrics
+
+
+def test_parse_metrics_reads_the_four_figures():
+    text = "\n".join(
+        [
+            "# HELP vllm:num_requests_running whatever",
+            'vllm:num_requests_running{engine="0",model_name="x"} 4.0',
+            'vllm:num_requests_waiting{engine="0",model_name="x"} 2.0',
+            'vllm:gpu_cache_usage_perc{engine="0",model_name="x"} 0.31',
+            'vllm:num_preemptions_total{engine="0",model_name="x"} 3.0',
+        ]
+    )
+    got = parse_metrics("gemma4-26b", text, now=1.0).as_dict()
+    assert got["running"] == 4.0
+    assert got["waiting"] == 2.0
+    assert got["preempted"] == 3.0
+    # exposed as a fraction, reported as a percentage
+    assert got["kv_pct"] == 31.0
+
+
+def test_parse_metrics_survives_an_unexpected_body():
+    """A box returning HTML, or nothing, must not stop the sampler."""
+    for body in ("", "<html>503</html>", "vllm:num_requests_running{} notanumber"):
+        got = parse_metrics("x", body, now=1.0)
+        assert got.running == 0.0
diff --git a/tests/test_entitlements.py b/tests/test_token_window.py
similarity index 73%
rename from tests/test_entitlements.py
rename to tests/test_token_window.py
index 407a918..a8b4219 100644
--- a/tests/test_entitlements.py
+++ b/tests/test_token_window.py
@@ -15,12 +15,10 @@
 # specific language governing permissions and limitations
 # under the License.
 
-"""Entitlement resolution and the rolling token allowance.
+"""The rolling token allowance (llmao/token_window.py).
 
-These matter more than most because the failure is silent in both
-directions. A key minted without limits looks identical to a limited one
-until something saturates the fleet; an allowance that never ages out looks
-identical to a working one until somebody's week does not reset.
+The failure here is silent: an allowance that never ages out looks identical
+to a working one until somebody's week does not reset.
 """
 
 import datetime as dt
@@ -29,11 +27,6 @@ from llmao.token_window import RollingAllowance
 
 UTC = dt.UTC
 
-
-# ---------------------------------------------------------------------------
-# The rolling allowance
-# ---------------------------------------------------------------------------
-
 DAY0 = dt.datetime(2026, 9, 1, 12, tzinfo=UTC)
 
 
@@ -161,39 +154,3 @@ def test_window_length_is_honoured():
     a.spend(1_000_000, DAY0)
     assert a.exhausted(DAY0)
     assert not a.exhausted(_at(1))
-
-
-# ---------------------------------------------------------------------------
-# Contention sampling
-#
-# The pilot's one unanswerable-after-the-fact question: did anyone wait?
-# ---------------------------------------------------------------------------
-
-
-def test_parse_metrics_reads_the_four_figures():
-    from llmao.contention import parse_metrics
-
-    text = "\n".join(
-        [
-            "# HELP vllm:num_requests_running whatever",
-            'vllm:num_requests_running{engine="0",model_name="x"} 4.0',
-            'vllm:num_requests_waiting{engine="0",model_name="x"} 2.0',
-            'vllm:gpu_cache_usage_perc{engine="0",model_name="x"} 0.31',
-            'vllm:num_preemptions_total{engine="0",model_name="x"} 3.0',
-        ]
-    )
-    got = parse_metrics("gemma4-26b", text, now=1.0).as_dict()
-    assert got["running"] == 4.0
-    assert got["waiting"] == 2.0
-    assert got["preempted"] == 3.0
-    # exposed as a fraction, reported as a percentage
-    assert got["kv_pct"] == 31.0
-
-
-def test_parse_metrics_survives_an_unexpected_body():
-    """A box returning HTML, or nothing, must not stop the sampler."""
-    from llmao.contention import parse_metrics
-
-    for body in ("", "<html>503</html>", "vllm:num_requests_running{} notanumber"):
-        got = parse_metrics("x", body, now=1.0)
-        assert got.running == 0.0


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 01/09: proxy: delete the Backend protocol and the pass-throughs only it needed

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 1f5a8ebf73ee5addce0599915f68f8c67fe35bb5
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 21:49:47 2026 -0500

    proxy: delete the Backend protocol and the pass-throughs only it needed
    
    The Backend protocol listed sixteen methods. The one other implementation,
    the tests' MockBackend, has seven of them; the seam already called things
    it did not list; and its only use was a type hint. It was a list that had
    been accurate once. It is deleted, and the seam's hint names
    LiteLLMBackend.
    
    Eight of the backend's fourteen pass-throughs existed only to satisfy it,
    and go with it: tier_entitlement, set_tier_entitlement,
    update_team_entitlement, key_usage, allowance, invalidate_spend,
    invalidate_allowance and update_key_entitlement. Three had no callers. The
    seam's five calls go to the managers: tiers.limits, tiers.set_limits,
    teams.update_entitlement, metering.by_key, metering.allowance.
    
    The six that remain are the ones MockBackend also has.
    
    KNOWN WRONG, TO BE FIXED: dropping the cached usage after a tier change was
    in the set_tier_entitlement pass-through, and is now in the seam's
    set_tier. The seam should not be invalidating a cache; that belongs behind
    the managers.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 llmao/proxy/client.py | 93 +--------------------------------------------------
 llmao/seam.py         | 19 +++++++----
 2 files changed, 13 insertions(+), 99 deletions(-)

diff --git a/llmao/proxy/client.py b/llmao/proxy/client.py
index 1547554..b66aa15 100644
--- a/llmao/proxy/client.py
+++ b/llmao/proxy/client.py
@@ -33,7 +33,7 @@ import pathlib
 import re
 import time
 from dataclasses import dataclass, field
-from typing import Any, Protocol
+from typing import Any
 
 import httpx
 from asfpy.stopwatch import Stopwatch
@@ -195,66 +195,6 @@ class CreatedKey:
     info: KeyInfo
 
 
-class Backend(Protocol):
-    async def team_info(self, project: str) -> TeamInfo | None: ...
-    async def set_tier_entitlement(
-        self,
-        tier: str,
-        *,
-        rpm_limit: int | None = None,
-        tpm_limit: int | None = None,
-        max_parallel_requests: int | None = None,
-        token_cap: int | None = None,
-        token_window_days: int | None = None,
-    ) -> dict[str, Any]: ...
-    async def tier_entitlement(self, tier: str) -> dict[str, Any]: ...
-    async def update_team_entitlement(
-        self,
-        project: str,
-        *,
-        max_budget_usd: float | None = None,
-        token_cap: int | None = None,
-        rpm_limit: int | None = None,
-        tpm_limit: int | None = None,
-        max_parallel_requests: int | None = None,
-    ) -> TeamInfo: ...
-    async def update_key_entitlement(
-        self,
-        token_id: str,
-        *,
-        rpm_limit: int | None = None,
-        tpm_limit: int | None = None,
-        max_parallel_requests: int | None = None,
-        max_budget_usd: float | None = None,
-    ) -> None: ...
-    async def ensure_team(self, project: str) -> TeamInfo: ...
-    async def list_keys(
-        self,
-        *,
-        user: str | None = None,
-        project: str | None = None,
-        size: int = 100,
-    ) -> list[KeyInfo]: ...
-    async def create_key(
-        self,
-        *,
-        project: str,
-        purpose: str,
-        user: str | None = None,
-        metadata: dict | None = None,
-        tier: str = TIER_PROJECT,
-        token_cap: int | None = None,
-    ) -> CreatedKey: ...
-    async def delete_key(self, token_id: str) -> None: ...
-    async def usage(self, project: str | None) -> list[dict]: ...
-    async def key_usage(self, user: str) -> dict[str, int]: ...
-    def invalidate_spend(self) -> None: ...
-    async def allowance(self, user: str, *, tier: str = TIER_FREE) -> RollingAllowance: ...
-    def invalidate_allowance(self, user: str | None = None) -> None: ...
-    async def proxy_version(self) -> str | None: ...
-    async def aclose(self) -> None: ...
-
-
 def _normalize_key_obj(raw: Any) -> KeyInfo:
     """Build KeyInfo from a LiteLLM key object (wire → design names)."""
     if isinstance(raw, str):
@@ -412,19 +352,6 @@ class LiteLLMBackend:
     # key in a team, and a projectless one has to go somewhere.
     _TIER_STORE_TEAM = "llmao-entitlement-defaults"
 
-    # ---- tiers: TierManager, below --------------------------------------
-
-    async def tier_entitlement(self, tier: str) -> dict[str, Any]:
-        return await self.tiers.limits(tier)
-
-    async def set_tier_entitlement(self, tier: str, **limits: int | None) -> dict[str, Any]:
-        result = await self.tiers.set_limits(tier, **limits)
-        # The cap is re-read on every check, but today's usage is cached --
-        # without this an admin lowering a cap sees a stale remaining figure
-        # for up to a minute and concludes the control did not work.
-        self.invalidate_allowance()
-        return result
-
     # ---- teams: TeamManager, below --------------------------------------
 
     async def team_info(self, project: str) -> TeamInfo | None:
@@ -433,26 +360,11 @@ class LiteLLMBackend:
     async def ensure_team(self, project: str) -> TeamInfo:
         return await self.teams.ensure(project)
 
-    async def update_team_entitlement(self, project: str, **limits: float | int | None) -> TeamInfo:
-        return await self.teams.update_entitlement(project, **limits)
-
     # ---- usage: UsageManager, below -------------------------------------
 
     async def usage(self, project: str | None) -> list[dict]:
         return await self.metering.rows(project)
 
-    async def key_usage(self, user: str) -> dict[str, int]:
-        return await self.metering.by_key(user)
-
-    async def allowance(self, user: str, *, tier: str = TIER_FREE) -> RollingAllowance:
-        return await self.metering.allowance(user, tier=tier)
-
-    def invalidate_spend(self) -> None:
-        self.metering.invalidate()
-
-    def invalidate_allowance(self, user: str | None = None) -> None:
-        self.metering.invalidate()
-
     # ---- keys: KeyManager, below ----------------------------------------
 
     async def list_keys(self, *, user: str | None = None, project: str | None = None, size: int = 100) -> list[KeyInfo]:
@@ -464,9 +376,6 @@ class LiteLLMBackend:
     async def delete_key(self, token_id: str) -> None:
         await self.keys.delete(token_id)
 
-    async def update_key_entitlement(self, token_id: str, **limits: int | None) -> None:
-        await self.keys.update_entitlement(token_id, **limits)
-
 
 class KeyManager:
     """LiteLLM's virtual keys: listing, minting, revoking, and what each may do.
diff --git a/llmao/seam.py b/llmao/seam.py
index ceed07c..d9b19af 100644
--- a/llmao/seam.py
+++ b/llmao/seam.py
@@ -36,10 +36,10 @@ from .proxy.client import (
     TIER_FREE,
     TIER_PROJECT,
     TIER_SERVICE,
-    Backend,
     BackendUnavailableError,
     CreatedKey,
     KeyInfo,
+    LiteLLMBackend,
     TeamInfo,
 )
 
@@ -217,7 +217,7 @@ def _tokens_short(n) -> str:
 
 
 class Seam:
-    def __init__(self, cfg: Any, backend: Backend):
+    def __init__(self, cfg: Any, backend: LiteLLMBackend):
         self._cfg = cfg
         self._backend = backend
 
@@ -340,7 +340,7 @@ class Seam:
             raise AuthzError("Tiers are limited to site admins.")
         out = []
         for tier in (TIER_FREE, TIER_PROJECT, TIER_SERVICE):
-            out.append({"tier": tier, **(await self._backend.tier_entitlement(tier))})
+            out.append({"tier": tier, **(await self._backend.tiers.limits(tier))})
         return out
 
     async def set_tier(self, identity: Identity, tier: str, **limits) -> dict:
@@ -354,7 +354,12 @@ class Seam:
         named = {k: v for k, v in limits.items() if v is not None}
         if not named:
             raise AuthzError("Nothing to change.")
-        return await self._backend.set_tier_entitlement(tier, **named)
+        limits = await self._backend.tiers.set_limits(tier, **named)
+        # The cap is re-read on every check, but today's usage is cached --
+        # without this an admin lowering a cap sees a stale remaining figure
+        # for up to a minute and concludes the control did not work.
+        self._backend.metering.invalidate()
+        return limits
 
     async def my_requests(self, identity: Identity) -> list:
         """This person's own requests, newest first.
@@ -400,7 +405,7 @@ class Seam:
             granted=granted,
         )
         if approve and req.kind == _access.KIND_CAPACITY:
-            await self._backend.update_team_entitlement(req.project, token_cap=int(req.granted.get("token_cap") or 0))
+            await self._backend.teams.update_entitlement(req.project, token_cap=int(req.granted.get("token_cap") or 0))
         return await self._backend.requests.save(req)
 
     @require_member
@@ -462,7 +467,7 @@ class Seam:
         spend log groups differently for each.
         """
         try:
-            return await self._backend.key_usage(identity.uid)
+            return await self._backend.metering.by_key(identity.uid)
         except BackendUnavailableError:
             # An empty map renders dashes rather than zeros. "0" claims the
             # key is idle; we only know we could not ask.
@@ -558,7 +563,7 @@ class Seam:
         No authz decision: a principal always sees their own draw. Project
         figures go through the normal membership checks below.
         """
-        return await self._backend.allowance(identity.uid)
+        return await self._backend.metering.allowance(identity.uid)
 
     async def my_project_usage(self, identity: Identity) -> list[dict]:
         """Per-project draw for the projects this committer belongs to.


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-llmao) 06/09: tests: name two test files for what they test. No functional change

Posted by gs...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

gstein pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 895c82a5a52e0178846adf753c15b7c0ee35c8a1
Author: Greg Stein <gs...@gmail.com>
AuthorDate: Mon Oct 12 22:32:52 2026 -0500

    tests: name two test files for what they test. No functional change
    
    Renames only; no line in either file changes.
    
      tests/test_spend_rows.py -> tests/test_usage.py
      tests/test_mix.py        -> tests/test_deployments.py
    
    test_spend_rows was named for a method that folded the spend log, which is
    gone; the file tests UsageManager. test_mix tests DeploymentManager, in
    llmao/proxy/deployments.py.
    
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 tests/{test_mix.py => test_deployments.py}  | 0
 tests/{test_spend_rows.py => test_usage.py} | 0
 2 files changed, 0 insertions(+), 0 deletions(-)

diff --git a/tests/test_mix.py b/tests/test_deployments.py
similarity index 100%
rename from tests/test_mix.py
rename to tests/test_deployments.py
diff --git a/tests/test_spend_rows.py b/tests/test_usage.py
similarity index 100%
rename from tests/test_spend_rows.py
rename to tests/test_usage.py


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org