Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

fix(ai): normalize usage quota scope IDs [skip version]

Juan Denis0fc47c3d3e1a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 00faed8c..e10a51bb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,7 +31,8 @@ release history; historical `agent-v*` tags are not panel releases.
### Fixed
- Refresh the bundled extension registry and generated API inventories.
-- Raise the clean-checkout backend test floor from 5,110 to 5,197 tests.
+- Normalize usage-report user and workspace filters before quota calculations.
+- Raise the clean-checkout backend test floor from 5,110 to 5,205 tests.
[Source changes since 1.10.0](https://github.com/jhd3197/ServerKit/compare/v1.10.0...v1.11.0).
diff --git a/backend/app/services/ai_usage.py b/backend/app/services/ai_usage.py
index 5d4697e2..e4723451 100644
--- a/backend/app/services/ai_usage.py
+++ b/backend/app/services/ai_usage.py
@@ -171,11 +171,13 @@ def report(args):
days = ai_management.number(args.get('days', 30), 'Days', 1, 366, integer=True)
from datetime import timedelta
query = AiRun.query.filter(AiRun.created_at >= datetime.utcnow() - timedelta(days=days))
+ scope_ids = {'user_id': None, 'workspace_id': None}
for key in ('profile', 'connection_id', 'user_id', 'workspace_id'):
value = args.get(key)
if value:
if key.endswith('_id') and key != 'connection_id':
value = ai_management.number(value, key, 1, 2147483647, integer=True)
+ scope_ids[key] = value
query = query.filter(getattr(AiRun, key) == value)
rows = query.order_by(AiRun.created_at.desc()).all()
groups = {key: {} for key in ('daily', 'profile', 'model', 'connection_id', 'user_id', 'workspace_id')}
@@ -196,6 +198,6 @@ def report(args):
totals['average_duration_ms'] = totals['duration_ms'] / len(rows) if rows else 0
offset = ai_management.number(args.get('offset', 0), 'Offset', 0, 10000000, integer=True)
return {'totals': totals, 'groups': {key: list(value.values()) for key, value in groups.items()},
- 'allowances': quota_status(ai_management.settings(), args.get('user_id'), args.get('workspace_id')),
+ 'allowances': quota_status(ai_management.settings(), scope_ids['user_id'], scope_ids['workspace_id']),
'runs': [row.to_dict() for row in rows[offset:offset + 50]],
'has_more': offset + 50 < len(rows), 'next_offset': offset + 50}
diff --git a/backend/tests/BASELINE_COUNT b/backend/tests/BASELINE_COUNT
index 12d87d95..42753493 100644
--- a/backend/tests/BASELINE_COUNT
+++ b/backend/tests/BASELINE_COUNT
@@ -1 +1 @@
-5197
+5205
diff --git a/backend/tests/test_ai_management.py b/backend/tests/test_ai_management.py
index d2253494..ab684909 100644
--- a/backend/tests/test_ai_management.py
+++ b/backend/tests/test_ai_management.py
@@ -239,7 +239,7 @@ def test_degradation_switches_only_to_known_cheaper_connection(app, client, auth
assert second['usage']['budget']['exceeded'] is True
-def test_scoped_allowances_and_unknown_cost_are_conservative(app, client, auth_headers, setup_ai):
+def test_scoped_allowances_and_unknown_cost_are_conservative(app, client, auth_headers, setup_ai, monkeypatch):
from factories import make_workspace
configure(client, auth_headers, user_monthly_limit_usd=1, workspace_monthly_limit_usd=1)
with app.app_context():
@@ -260,6 +260,29 @@ def test_scoped_allowances_and_unknown_cost_are_conservative(app, client, auth_h
assert AiRun.query.one().budget_charge == 0.5
assert ai_usage.report({'user_id': other.id})['totals']['runs'] == 0
assert ai_usage.report({'workspace_id': workspace.id})['totals']['tokens'] == 10
+ original_quota_status = ai_usage.quota_status
+
+ def typed_quota_status(config, user_id, workspace_id):
+ assert type(user_id) is int
+ assert type(workspace_id) is int
+ return original_quota_status(config, user_id, workspace_id)
+
+ monkeypatch.setattr(ai_usage, 'quota_status', typed_quota_status)
+ response = client.get('/api/v1/ai/usage', query_string={
+ 'user_id': str(user.id), 'workspace_id': str(workspace.id),
+ }, headers=auth_headers)
+ assert response.status_code == 200
+ assert response.get_json()['allowances'] == mine
+ assert response.get_json()['totals']['tokens'] == 10
+
+
[email protected]('scope', ['user_id', 'workspace_id'])
[email protected]('value', ['', 'invalid', '0', '1.5'])
+def test_usage_scope_query_validation(client, auth_headers, scope, value):
+ response = client.get('/api/v1/ai/usage', query_string={scope: value}, headers=auth_headers)
+ assert response.status_code == (200 if value == '' else 400)
+ if value == '':
+ assert all(item['scope'] == 'Panel' for item in response.get_json()['allowances'])
def test_resume_rechecks_workspace_membership(app, client, auth_headers, setup_ai):